text stringlengths 14 6.51M |
|---|
unit MainLib;
interface
uses
Windows, Messages, SysUtils,
Variants, Classes, Graphics, Controls,
Forms,Dialogs,ComObj,OPCtypes,OPCDA,
OPCutils,ActiveX, StdCtrls,BaseTypes,
ExtCtrls,LogsUnit,ScktComp,Ini,superobject,
Common,StrUtils,Clipbrd, CoolTrayIcon, Menus;
type
TMainForm = class(TForm)
Logs: TMemo;
LogClear: TCheckBox;
ClearLogBtn: TButton;
DeBugCk: TCheckBox;
Timer: TTimer;
TimeStart: TTimer;
TimeRun: TTimer;
CoolTrayIcon: TCoolTrayIcon;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
procedure ClearLogBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TimeStartTimer(Sender: TObject);
procedure TimeRunTimer(Sender: TObject);
procedure CoolTrayIconDblClick(Sender: TObject);
procedure N2Click(Sender: TObject);
procedure N3Click(Sender: TObject);
procedure N4Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormHide(Sender: TObject);
private
{ Private declarations }
public
ServerPath : string; //OPC服务路径
Port : Integer; //本地监听端口
Time : Integer; //时间
Filters : TStrings; //过滤文本
ScoketServer : TServerSocket; //本地监听scoket
Servers : TServers; //服务端集合
LogicDevices : TLogicDevices; //逻辑设备集合
Scokets : TScokets; //客户端连接集合
RegeditStrings : TStringMap; //引擎注册字符串集合
IsClear : Boolean;
PointCount : Integer; //点数
procedure AddLogs(Content:string);
procedure Start;
procedure OnClientConnect(Sender: TObject;Socket: TCustomWinSocket);
procedure OnClientDisConnect(Sender: TObject;Socket: TCustomWinSocket);
procedure OnClientRead(Sender: TObject;Socket: TCustomWinSocket);
procedure OnErrorEvent(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure OnClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure OnDataChange(PreSends:TPreSends);
procedure ClearData;
end;
var
MainForm: TMainForm;
Cl,shows:Boolean;
implementation
{$R *.dfm}
procedure TMainForm.AddLogs(Content:string);
begin
if DeBugCk.Checked then
begin
Logs.Lines.Add(FormatDateTime('hh:mm:ss', now) + ' ' + Content);
end
else
begin
if (LogClear.Checked) and (Logs.Lines.Count >= 100) then
begin
Logs.Lines.Clear;
end;
LogsUnit.addErrors(Content);
end;
end;
procedure TMainForm.ClearLogBtnClick(Sender: TObject);
begin
Clipboard.AsText := Logs.Text;
Logs.Lines.Clear;
end;
procedure TMainForm.CoolTrayIconDblClick(Sender: TObject);
begin
if shows then Hide
else Show;
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if not Cl and CoolTrayIcon.Enabled then
begin
Hide;
Abort;
end;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
var
I :Integer;
begin
for I := 0 to Servers.Count - 1 do
begin
Servers.Values[I].Free ;
end;
end;
procedure TMainForm.FormHide(Sender: TObject);
begin
shows := False;
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
DeBugCk.Checked := True;
Shows := True;
end;
procedure TMainForm.N2Click(Sender: TObject);
begin
Show;
end;
procedure TMainForm.N3Click(Sender: TObject);
begin
Hide;
end;
procedure TMainForm.N4Click(Sender: TObject);
begin
Cl := True;
Close;
end;
procedure TMainForm.Start;
var
temp : TStrings;
begin
if not DirectoryExists(ExtractFileDir(PARAMSTR(0)) + '\logs') then CreateDirectory(PChar(ExtractFilePath(ParamStr(0)) + '\logs'), nil);
if not FileExists(ExtractFileDir(PARAMSTR(0)) + '\config.ini') then
begin
temp := TStringList.Create;
temp.Add('[server]');
temp.Add('port=5000');
temp.Add('time=5000');
temp.Add('serverpath=');
temp.Add('filter=');
AddLogs('没有找到配置文件,默认端口5000,连接本地..');
temp.SaveToFile(ExtractFileDir(PARAMSTR(0)) + '\config.ini');
Port := 5000;
ServerPath := '';
Time := 5000;
Filters := TStringList.Create;
Filters.Add('Bad');
end
else
begin
Port := StrToInt(Ini.ReadIni('server','port'));
Time := StrToInt(Ini.ReadIni('server','time'));
ServerPath := Ini.ReadIni('server','serverpath');
Filters := Common.SplitToStrings(Ini.ReadIni('server','filter'),',');
end;
ScoketServer := TServerSocket.Create(Application);
ScoketServer.Port := Port;
ScoketServer.OnClientConnect := OnClientConnect;
ScoketServer.OnClientRead := OnClientRead;
ScoketServer.OnClientDisconnect := OnClientDisConnect;
ScoketServer.Socket.OnErrorEvent := OnErrorEvent;
ScoketServer.Socket.OnClientError := OnClientError;
try
ScoketServer.Open;
AddLogs('成功监听在端口:' + IntToStr(Port));
except
AddLogs('打开失败,可能是端口被占用了,当前端口:' + IntToStr(Port));
Exit;
end;
Servers := TServers.Create;
LogicDevices := TLogicDevices.Create;
Scokets := TScokets.Create;
RegeditStrings := TStringMap.Create;
IsClear := False;
TimeRun.Interval := Time;
PointCount := 0;
end;
procedure TMainForm.TimerTimer(Sender: TObject);
begin
Timer.Enabled := False;
Start;
end;
procedure TMainForm.TimeRunTimer(Sender: TObject);
var
I,K :Integer;
ItemValue :string;
ItemQuality :Word;
Item :TItem;
Counts :Integer;
PreSend :TPreSend;
PreSends :TPreSends;
begin
Counts := 0;
SetLength(PreSends,0);
for I := 0 to Servers.Count - 1 do
begin
for K := 0 to Servers.Values[I].Items.Count - 1 do
begin
Item := Servers.Values[I].Items.Values[K];
ReadOPCGroupItemValue(Servers.Values[I].GroupIf, Item.ItemHandel,ItemValue, ItemQuality);
//if (ItemQuality = OPC_QUALITY_GOOD) and (Item.ItemValue <> ItemValue) and (Filters.IndexOf(ItemValue) = -1)then
if (ItemQuality = OPC_QUALITY_GOOD) and (Filters.IndexOf(ItemValue) = -1) then
begin
Item.ItemValue := ItemValue;
PreSend := TPreSend.Create;
PreSend.LogicDeviceId := Item.LogicDeviceId;
PreSend.ItemHandel := Item.ItemHandel;
PreSend.ItemValue := ItemValue;
SetLength(PreSends,Length(PreSends) + 1);
PreSends[Length(PreSends) - 1] := PreSend;
Servers.Values[I].Items.Add(Servers.Values[I].Items.Keys[K],Item);
end;
Inc(Counts);
end;
end;
OnDataChange(PreSends);
if Counts <> PointCount then
AddLogs('扫描的OPC点与原先添加的点个数不符,添加了' + IntToStr(PointCount)+'个,扫描了'+InttoStr(Counts)+'个')
end;
procedure TMainForm.TimeStartTimer(Sender: TObject);
begin
TimeStart.Enabled := False;
AddLogs('开始扫描OPC...');
TimeRun.Enabled := True;
end;
procedure TMainForm.OnClientConnect(Sender: TObject;Socket: TCustomWinSocket);
var
address : string;
begin
address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
AddLogs(address + '已经连接');
end;
procedure TMainForm.OnClientDisConnect(Sender: TObject;Socket: TCustomWinSocket);
var
address : string;
begin
address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
AddLogs(address + '断开连接');
ClearData;
end;
procedure TMainForm.ClearData;
var
I:Integer;
begin
if IsClear then Exit;
if LogicDevices.Count = 0 then Exit;
IsClear := True;
TimeRun.Enabled := False;
for I := 0 to Servers.Count - 1 do
begin
Servers.Values[I].Clear;
end;
Scokets.clear;
LogicDevices.clear;
RegeditStrings.clear;
IsClear := False;
PointCount := 0;
end;
procedure TMainForm.OnClientRead(Sender: TObject;Socket: TCustomWinSocket);
var
RevText : string;
Temp : string;
Index : Integer;
RevObj : ISuperObject;
Address : string;
Devs : TSuperArray;
Dev : ISuperObject;
I : Integer;
K : Integer;
ALogicDevice: TLogicDevice;
Points : TSuperArray;
phDev : ISuperObject;
Active : Boolean;
Server : TServer;
ItemHandle : Opchandle;
FailLogicDevice : TStrings;
HasAdd :Boolean;
IsNewItem :Boolean;
begin
HasAdd := False;
Address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
RevText := Trim(Socket.ReceiveText);
Index := Pos('^_^',RevText);
if (Index = 0) and (RevText <> '') then
begin
Temp := RegeditStrings.Items[Address];
Temp := Temp + RevText;
RegeditStrings.Add(Address,Temp);
Exit;
end;
Temp := RegeditStrings.Items[Address];
Temp := Temp + RevText;
RevText := '';
Temp := LeftStr(Temp,Length(Temp)-3);
try
RevText := Common.decode(Temp);
except
AddLogs('解码发生异常!('+Address+')'+RevText);
Exit;
end;
RevObj := SO(RevText);
if not Assigned(RevObj) then
begin
AddLogs('解析格式错误('+Address+')'+RevText);
Exit;
end;
Devs := RevObj.A['device'];
if not Assigned(Devs) then
begin
AddLogs('解析格式错误('+Address+')'+RevText);
Exit;
end;
Scokets.Add(Address,Socket);
FailLogicDevice := TStringList.Create;
for I := 0 to Devs.Length - 1 do
begin
Dev := Devs.O[I];
ALogicDevice := TLogicDevice.Create;
ALogicDevice.ID := Dev.S['id'];
ALogicDevice.Address := Address;
Points := Dev.A['device'];
Active := True;
for K := 0 to Points.Length - 1 do
begin
HasAdd := True;
phDev := Points.O[K];
Server := Servers.Items[phDev.S['serverName']];
if not Assigned(Server) then
begin
Server := TServer.Create;
Server.ServerName := phDev.S['serverName'];
if not Server.Init then
begin
AddLogs('错误的服务名:' + phDev.S['serverName']);
Server.Free;
Server := nil;
end;
if Assigned(Server) then
begin
Servers.Add(phDev.S['serverName'],Server);
end;
end;
if Assigned(Server) then
begin
ItemHandle := Server.Add(ALogicDevice.ID,phDev.S['itemName'],IsNewItem);
if ItemHandle = 0 then
begin
Active := False;
AddLogs(phDev.S['serverName'] + '>'+ phDev.S['itemName']+'激活失败!,逻辑设备ID是' + ALogicDevice.ID);
end;
if ItemHandle <> 0 then
begin
ALogicDevice.ItemsValues.Add(IntToStr(ItemHandle),'-');
if IsNewItem then
Inc(PointCount)
else
AddLogs(phDev.S['itemName'] + '添加失败,可能是已经添加过或者点不存在!');
end
else
Active := False;
end
else
begin
Active := False;
AddLogs(phDev.S['serverName'] + '>'+ phDev.S['itemName']+'激活失败!');
end;
end;
LogicDevices.Add(ALogicDevice.ID,ALogicDevice);
if not Active then
FailLogicDevice.Add(ALogicDevice.ID);
end;
for K := 0 to FailLogicDevice.Count - 1 do
begin
Servers.RemoveErrors(LogicDevices.Items[FailLogicDevice[K]].ItemsValues.Keys);
LogicDevices.Remove(FailLogicDevice[K]);
end;
if HasAdd and not TimeStart.Enabled then
TimeStart.Enabled := True;
AddLogs('本连接有' + IntToStr(Devs.Length) + '个设备需要添加,实际添加了' + IntToStr(Devs.Length - FailLogicDevice.Count)+'个,' + IntToStr(FailLogicDevice.Count) + '个失败,目前一共有' + IntToStr(LogicDevices.Count) + '个,有' + IntToStr(PointCount)+'个点已添');
end;
procedure TMainForm.OnErrorEvent(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
var
address:string;
begin
address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
AddLogs(address + '发生异常');
ClearData;
ErrorCode := 0;
end;
procedure TMainForm.OnClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
var
address : string;
begin
address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
AddLogs(address + '发生异常');
ClearData;
ErrorCode := 0;
end;
procedure TMainForm.OnDataChange(PreSends:TPreSends);
var
LogicDevice :TLogicDevice;
Value:string;
Socket :TCustomWinSocket ;
I,LengthA,K :Integer;
LogicDeviceId,PreAddess:TStrings;
begin
LengthA := Length(PreSends) - 1;
PreAddess := TStringList.Create;
for K := 0 to LengthA do
begin
LogicDeviceId := PreSends[K].LogicDeviceId;
for I := 0 to LogicDeviceId.Count - 1 do
begin
LogicDevice := LogicDevices.Items[LogicDeviceId[I]];
if Assigned(LogicDevice) then
begin
try
LogicDevice.ItemsValues.Add(InttoStr(PreSends[K].ItemHandel),PreSends[K].ItemValue);
Value := LogicDevice.getValueString;
except
Addlogs(LogicDeviceId[I] + '计算值时发生异常');
end;
if Value <> '' then
begin
Socket := Scokets.Items[LogicDevice.Address];
if Assigned(Socket) then
begin
if not Assigned(Socket.SendMsgOfOneScoket) then
begin
Socket.SendMsgOfOneScoket := SO('[]');
Socket.MsgCounts := 0;
end;
Socket.SendMsgOfOneScoket.S[IntToStr(Socket.MsgCounts)] := Value;
Inc(Socket.MsgCounts);
if PreAddess.IndexOf(LogicDevice.Address) = -1 then
PreAddess.Add(LogicDevice.Address)
end
else
Addlogs('找不到会话,id是' + LogicDevice.ID);
end
end
else
Addlogs('找不到逻辑设备,id是' + LogicDeviceId[I]);
end;
end;
for I := 0 to PreAddess.Count - 1 do
begin
Socket := Scokets.Items[PreAddess[I]];
Socket.SendText(Common.encode(Socket.SendMsgOfOneScoket.AsString) + #$D#$A);
Socket.MsgCounts := 0;
end;
//
// for I := 0 to LogicDeviceId.Count - 1 do
// begin
// LogicDevice := LogicDevices.Items[LogicDeviceId[I]];
// if Assigned(LogicDevice) then
// begin
// try
// LogicDevice.ItemsValues.Add(InttoStr(ItemHandel),ItemValue);
// Value := LogicDevice.getValueString;
// except
// Addlogs(LogicDeviceId[I] + '计算值时发生异常');
// end;
// if Value <> '' then
// begin
// Socket := Scokets.Items[LogicDevice.Address];
// if Assigned(Socket) then
// Socket.SendText(Common.encode(Value) + #$D#$A)
// else
// Addlogs('找不到会话!' + LogicDevice.ID);
// end
//// else
//// Addlogs('其他设备没有值!' + LogicDevice.ID);
// end
// else
// begin
// Addlogs('找不到逻辑设备!' + ItemValue);
// end;
// end;
end;
end.
|
//******************************************************************************
// Пакет для добавленя, изменения, удаления данных о свойствах людей
// параметры: ID - идентификатор, если добавление, то идентификатор человека, иначе
// идентификатор свойства человека.
//******************************************************************************
unit PeopleProp_ByPeriod_MainForm2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxDropDownEdit, cxLookupEdit,
type, ActnList, StdCtrls, cxButtons, cxCalendar, cxTextEdit, cxMaskEdit,
cxDBLookupEdit, cxDBLookupComboBox, cxContainer, cxEdit, cxLabel,
ExtCtrls, cxControls, cxGroupBox
TFPeople_Prop_ByPeriod1 = class(TForm)
PeriodBox: TcxGroupBox;
YesBtn: TcxButton;
CancelBtn: TcxButton;
Bevel1: TBevel;
PropLabel: TcxLabel;
PropEdit: TcxLookupComboBox;
DateBegLabel: TcxLabel;
DateBeg: TcxDateEdit;
DateEndLabel: TcxLabel;
DateEnd: TcxDateEdit;
Actions: TActionList;
ActionYes: TAction;
procedure CancelBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ActionYesExecute(Sender: TObject);
private
PParameter:TZPeoplePropParameters;
PLanguageIndex:Byte;
public
constructor Create(AOwner: TComponent;DB_Handle:TISC_DB_HANDLE);reintroduce;
end;
implementation
uses StrUtils;
{$R *.dfm}
constructor TFPeople_Prop_ByPeriod1.Create(AOwner: TComponent;DB_Handle:TISC_DB_HANDLE);
begin
inherited Create(AOwner);
{PParameter := AParameters;
DM := TDM_Ctrl.Create(AOwner,DB_Handle,AParameters,Is_Grant);
PLanguageIndex:=LanguageIndex;
pNumPredpr := StrToInt(VarToStrDef(ValueFieldZSetup(DB_Handle,'NUM_PREDPR'),'1'));
//******************************************************************************
PeopleLabel.Caption := LabelMan_Caption[PLanguageIndex];
PropLabel.Caption := GridClPropertyName_Caption[PLanguageIndex];
DateBegLabel.Caption := LabelDateBeg_Caption[PLanguageIndex]+' - ';
DateEndLabel.Caption := ' - '+AnsiLowerCase(LabelDateEnd_Caption[PLanguageIndex]);
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
//******************************************************************************
PropEdit.Properties.ListFieldNames := 'NAME_PEOPLE_PROP';
PropEdit.Properties.KeyFieldNames :='ID_PEOPLE_PROP';
PropEdit.Properties.DataController.DataSource := DM.DSourceProp;
DateBeg.Properties.MaxDate := VarToDateTime(DM.DSetData['PERIOD_BEG']);
DateBeg.Properties.MinDate := VarToDateTime(DM.DSetData['PERIOD_END']);
DateEnd.Properties.MaxDate := VarToDateTime(DM.DSetData['PERIOD_BEG']);
DateEnd.Properties.MinDate := VarToDateTime(DM.DSetData['PERIOD_END']);
//******************************************************************************
Caption := ZPeoplePropCtrl_Caption_Insert[PLanguageIndex];
PeopleEdit.Text := VarToStr(DM.DSetData.FieldValues['TN'])+' - '+VarToStr(DM.DSetData.FieldValues['FIO']);
//strtodate(KodSetupToPeriod(grKodSetup(DB_Handle), 6))
DateBeg.Date := strtodate(KodSetupToPeriod(CurrentKodSetup(DB_Handle), 6));
DateEnd.Date := VarToDateTime(DM.DSetData['PERIOD_END']);
}
end;
procedure TFPeople_Prop_ByPeriod1.CancelBtnClick(Sender: TObject);
begin
//ModalResult:=mrCancel;
end;
procedure TFPeople_Prop_ByPeriod1.FormCreate(Sender: TObject);
begin
{if PParameter.ControlFormStyle = zcfsDelete then
begin
if ZShowMessage(ZPeoplePropCtrl_Caption_Delete[PLanguageIndex],DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then
with DM do
try
StoredProc.Database := DB;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_PEOPLE_PROP_DELETE';
StoredProc.Prepare;
StoredProc.ParamByName('ID').AsInteger := PParameter.ID;
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on E:Exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end
else
ModalResult:=mrCancel;
end; }
end;
procedure TFPeople_Prop_ByPeriod1.ActionYesExecute(Sender: TObject);
var ID:integer;
begin
//
end;
end.
|
unit MainServiceLib;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs,MainRunLib;
type
TshService = class(TService)
procedure ServiceStart(Sender: TService; var Started: Boolean);
private
{ Private declarations }
public
function GetServiceController: TServiceController; override;
{ Public declarations }
end;
var
shService: TshService;
implementation
{$R *.DFM}
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
shService.Controller(CtrlCode);
end;
function TshService.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TshService.ServiceStart(Sender: TService; var Started: Boolean);
begin
MainView := TMainView.Create(Application);
end;
end.
|
unit Plugins;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, PluginX;
type
TFrmPlugins = class(TForm)
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
ListView1: TListView;
Label1: TLabel;
MemDesc: TMemo;
Label2: TLabel;
LabAuthor: TLabel;
Label4: TLabel;
LabCopy: TLabel;
Label6: TLabel;
LabHome: TLabel;
procedure FormCreate(Sender: TObject);
procedure ListView1Change(Sender: TObject; Item: TListItem;
Change: TItemChange);
private
{ Private declarations }
public
{ Public declarations }
AppInfo : TAppInfo;
procedure InitPlugins;
procedure DeInitPlugins;
procedure NewPPlugin(var APlugin: PPlugin);
end;
var
FrmPlugins: TFrmPlugins;
PluginList: TList;//Lista de Plugins carregados
Plugin : PPlugin;
implementation
uses Center;
{$R *.dfm}
//Retorna lista arquivos numa pasta
procedure EnumFiles(Pasta, Arquivo: String; Files: TStringList);
var
SR: TSearchRec;
ret : integer;
begin
if Pasta[Length(Pasta)] <> '\' then
Pasta := Pasta + '\';
ret := FindFirst(Pasta + Arquivo, faAnyFile, SR);
if ret = 0 then
try
repeat
if not (SR.Attr and faDirectory > 0) then
Files.Add(Pasta + SR.Name);
ret := FindNext(SR);
until ret <> 0;
finally
SysUtils.FindClose(SR)
end;
end;
//Carrega DLLs/Plugins/Funções das DLLs na memória
procedure TFrmPlugins.InitPlugins;
var
DllList : TStringList;
X : Integer;
LibHandle: THandle;
Item: TListItem;
begin
PluginList := TList.Create;
DllList := TStringList.Create;
//Procura DLLs na subpasta plugins da aplicação
EnumFiles(ExtractFilePath(Application.ExeName)+'plugins\', '*.dll', DllList);
try
if DllList.Count > 0 then
for X := 0 to DllList.Count -1 do
begin
NewPPlugin(Plugin);
//New(PLugin);
with Plugin^ do
begin
StrPCopy(DLLName, DllList[X]);
//Carrega DLL
LibHandle := LoadLibrary(PChar(DllList[X]));
if LibHandle <> 0 then
begin
DLLHandle := LibHandle;
//Carrega funções
@FLoadPlugin := GetProcAddress(LibHandle, 'LoadPlugin');
@FUnloadPlugin := GetProcAddress(LibHandle, 'UnLoadPlugin');
@FOnExecute := GetProcAddress(LibHandle, 'OnExecute');
@FSendClientToPlug := GetProcAddress(LibHandle, 'SendClientToPlug');
end;
if @FLoadPlugin <> nil then
begin
//ShowMEssage(StrPas(DLLName));
//Executa função LoadPlugin
FLoadPlugin(AppInfo, PluginInfo);
//ShowMEssage(StrPas(DLLName));
//Coloca informações no ListView
with PluginInfo do
begin
Item := ListView1.Items.Add;
Item.Caption := StrPas(pFunction);
LabAuthor.Caption := StrPas(pAuthor);
LabCopy.Caption := StrPas(pCopyright);
LabHome.Caption := StrPas(pHome);
MemDesc.Lines.Text := StrPas(pDescription);
Item.SubItems.Add(StrPas(pVersion));
Item.SubItems.Add(ExtractFileName(StrPas(DLLName)));
//Item.SubItems.Add(FileSize(StrPas(DLLName)));
Item.Data := Plugin;
end;
end;
end;
PluginList.Add(Plugin);
end;
finally
DllList.Free;
end;
end;
//Libera DLLs/plugins da memória
procedure TFrmPlugins.DeInitPlugins;
var
X : Integer;
begin
if PluginList.Count > 0 then
for X := PluginList.Count -1 downto 0 do
begin
Plugin := PPlugin(PluginList.Items[X]);
with Plugin^ do
begin
{ Executa função UnloadPlugin da DLL }
if @FUnloadPlugin <> nil then
FUnloadPlugin;
{ Libera DLL }
FreeLibrary(DLLHandle);
@FLoadPlugin := nil;
@FUnloadPlugin := nil;
@FOnExecute := nil;
end;
{ Liebra plugin }
Dispose(Plugin);
//PluginList.Delete(X);
end;
PluginList.Clear;
PluginList.Free;
end;
procedure TFrmPlugins.FormCreate(Sender: TObject);
begin
{ Define valores a serem enviados para o plugin quando
executar a função LoadPlugin }
AppInfo.Version := '1.0.0.1';
AppInfo.Hwnd := FrmCenter.Handle;
//AppInfo.Keep := True;
{ Carrega/Inicializa plugins }
InitPlugins;
end;
//Aloca espaço na memória para novo Plugin carregado
procedure TFrmPlugins.NewPPlugin(var APlugin: PPlugin);
begin
New(APlugin);
with APlugin^ do
begin
DLLName := AllocMem(SizeOf(TPlugin));
with PluginInfo do
begin
pVersion := AllocMem(SizeOf(TPlugin));
pAuthor := AllocMem(SizeOf(TPlugin));
pCopyright := AllocMem(SizeOf(TPlugin));
pHome := AllocMem(SizeOf(TPlugin));
pFunction := AllocMem(SizeOf(TPlugin));
pDescription := AllocMem(SizeOf(TPlugin));
end;
end;
end;
procedure TFrmPlugins.ListView1Change(Sender: TObject; Item: TListItem;
Change: TItemChange);
var
X : Integer;
begin
X := PluginList.IndexOf(Item.Data);
if X <> -1 then
with PPlugin(PluginList[X])^.PluginInfo do
begin
Item.Caption := StrPas(pFunction);
LabAuthor.Caption := StrPas(pAuthor);
LabCopy.Caption := StrPas(pCopyright);
LabHome.Caption := StrPas(pHome);
MemDesc.Lines.Text := StrPas(pDescription);
Item.SubItems[0] := StrPas(pVersion);
Item.SubItems[1] := ExtractFileName(StrPas(PPlugin(PluginList[X])^.DLLName));
//Item.SubItems[2] := FileSize(StrPas(DLLName));
end;
end;
end.
|
unit glAviPlane;
interface
uses
Winapi.Windows,
System.Classes,
GLScene,
GLVectorGeometry,
GLBaseClasses,
OpenGL1x,
GLTexture,
GLRenderContextInfo,
GLSVfw;
type
TQual = 1 .. 4;
TRenderMode = (rmTriStripArray, rmTriStrip);
TAVIUpdateEvent = procedure(sender: TObject; FrameIndex: integer) of object;
TGLAviPlane = class(TGLSceneObject)
private
fFilename: string;
fQuality: TQual;
fRenderMode: TRenderMode;
IntQuality: integer;
currdelta: single;
fFrameindex, fFirstFrame, fLastFrame: integer;
fUpdateRate: integer;
pAvi: IAVIFile;
pAvis: IAVIStream;
AviInfo: TAVIStreamInfoA;
// pavisound:IAVIStream;
pFrame: IGetFrame;
pBmi: PBitmapInfoHeader;
pColors: pRGBTriple;
fAviOpened: boolean;
CurrTime: Double;
CurrFrameCount: integer;
FileOrPosChanged: boolean;
StripArray: array of TAffineVector;
ColorArray: array of TAffineVector;
fwidth, fheight: single;
fCurrentFrameRate, fUserFrameRate: integer;
fTargetFrameRate: single;
fAutoFrameRate: boolean;
fOnUpdate: TAVIUpdateEvent;
function OpenAvi: boolean;
procedure FillColorArray;
procedure BuildStripArray;
protected
procedure SetFilename(val: string);
procedure SetQuality(val: TQual);
procedure SetRendermode(val: TRenderMode);
procedure SetFrameIndex(val: integer);
procedure SetAutoFrameRate(val: boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure buildlist(var rci: TGLRenderContextInfo); override;
procedure StructureChanged; override;
procedure DoProgress(const progressTime: TProgressTimes); override;
procedure CloseAvi;
function GetFrame(Framenum: integer): boolean;
property UserFrameRate: integer read fUserFrameRate write fUserFrameRate;
property FrameIndex: longint read fFrameindex write SetFrameIndex;
property FirstFrame: longint read fFirstFrame write fFirstFrame;
property LastFrame: longint read fLastFrame write fLastFrame;
property Filename: string read fFilename write SetFilename;
property AviOpened: boolean read fAviOpened;
property Quality: TQual read fQuality write SetQuality;
property Rendermode: TRenderMode read fRenderMode write SetRendermode;
property width: single read fwidth;
property height: single read fheight;
property CurrentFrameRate: integer read fCurrentFrameRate;
// current number of frames shown per second
property TargetFrameRate: single read fTargetFrameRate;
// Actual avi file frame rate
property AutoFrameRate: boolean read fAutoFrameRate write SetAutoFrameRate;
// Ignores UserFrameRate and uses TargetFrameRate instead
property OnUpdate: TAVIUpdateEvent read fOnUpdate write fOnUpdate;
end;
// ====================================================================
implementation
// ====================================================================
procedure TGLAviPlane.SetAutoFrameRate(val: boolean);
begin
fAutoFrameRate := val;
FileOrPosChanged := true;
end;
procedure TGLAviPlane.SetFrameIndex(val: integer);
begin
fFrameindex := val;
FileOrPosChanged := true;
end;
procedure TGLAviPlane.SetRendermode(val: TRenderMode);
begin
fRenderMode := val;
StructureChanged;
end;
procedure TGLAviPlane.SetQuality(val: TQual);
begin
fQuality := val;
case fQuality of
1:
IntQuality := 8;
2:
IntQuality := 4;
3:
IntQuality := 2;
4:
IntQuality := 1;
end;
StructureChanged;
end;
procedure TGLAviPlane.SetFilename(val: string);
begin
fFilename := val;
OpenAvi;
end;
constructor TGLAviPlane.Create(AOwner: TComponent);
begin
inherited;
ObjectStyle := ObjectStyle + [osDirectDraw];
fQuality := 4;
IntQuality := 1;
fFrameindex := 0;
fFirstFrame := 0;
fLastFrame := 0;
fUpdateRate := 10;
pBmi := nil;
pColors := nil;
fCurrentFrameRate := 0;
CurrTime := 0;
CurrFrameCount := 0;
fTargetFrameRate := 0;
fAutoFrameRate := true;
end;
destructor TGLAviPlane.Destroy;
begin
// if faviopened then
// closeavi;
SetLength(StripArray, 0);
SetLength(ColorArray, 0);
inherited;
end;
procedure TGLAviPlane.buildlist(var rci: TGLRenderContextInfo);
var
w, h: integer;
x, y: integer;
r: integer;
rgb: pRGBTriple;
begin
if not assigned(pBmi) then
exit;
r := IntQuality;
w := pBmi^.biWidth div r;
h := pBmi^.biHeight div r;
glpushmatrix;
gltranslatef(-w / (120 / r), -h / (120 / r), 0);
fwidth := w / (60 / r);
fheight := h / (60 / r);
case Rendermode of
rmTriStrip:
begin
// glFrontFace(GL_CW);
r := IntQuality;
w := pBmi^.biWidth;
h := pBmi^.biHeight;
rgb := pColors;
inc(rgb, w);
for y := 1 to (h div r) - 1 do
begin
glbegin(GL_TRIANGLE_STRIP);
for x := (w div r) - 1 downto 0 do
begin
glcolor3f(rgb^.rgbtred / 255, rgb^.rgbtgreen / 255,
rgb^.rgbtblue / 255);
glvertex3f(x / (60 / r), y / (60 / r), 0);
glvertex3f(x / (60 / r), (y - 1) / (60 / r), 0);
inc(rgb, r);
end;
if r > 1 then
inc(rgb, w * (r - 1));
glend;
end;
// glFrontFace(GL_CCW);
end;
rmTriStripArray:
begin
if length(ColorArray) <> length(StripArray) then
exit;
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, @StripArray[0]);
glColorPointer(3, GL_FLOAT, 0, @ColorArray[0]);
glLockArraysEXT(0, w * h);
for y := 0 to h - 1 do
glDrawArrays(GL_TRIANGLE_STRIP, (y * (w)), w);
glUnlockArraysEXT;
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
end;
end;
glpopmatrix;
end;
procedure TGLAviPlane.StructureChanged;
begin
inherited;
SetLength(StripArray, 0);
SetLength(ColorArray, 0);
case Rendermode of
rmTriStripArray:
begin
BuildStripArray;
FillColorArray;
end;
end;
end;
procedure TGLAviPlane.DoProgress(const progressTime: TProgressTimes);
var
temp: single;
begin
inherited;
if fAutoFrameRate then
temp := fTargetFrameRate
else
temp := fUserFrameRate;
if (temp = 0) or (not fAviOpened) then
exit;
currdelta := currdelta + progressTime.DeltaTime;
if (currdelta >= 1 / temp) or FileOrPosChanged then
begin
currdelta := currdelta - (1 / temp);
GetFrame(fFrameindex);
FillColorArray;
inc(fFrameindex);
if fFrameindex > fLastFrame then
// do event ?
fFrameindex := fFirstFrame;
CurrFrameCount := CurrFrameCount + 1;
if (progressTime.newTime >= CurrTime + 1) or FileOrPosChanged then
begin
if FileOrPosChanged then
begin
CurrTime := progressTime.newTime;
currdelta := 0;
FileOrPosChanged := false;
end
else
CurrTime := CurrTime + 1;
fCurrentFrameRate := CurrFrameCount;
CurrFrameCount := 0;
if assigned(fOnUpdate) then
fOnUpdate(self, fFrameindex);
end;
end;
end;
function TGLAviPlane.GetFrame(Framenum: integer): boolean;
var
tempbmi: PBitmapInfoHeader;
begin
if not fAviOpened then
begin
result := false;
exit;
end;
try
tempbmi := AVIStreamGetFrame(pFrame, Framenum);
result := assigned(tempbmi);
if result then
begin
pBmi := tempbmi;
pColors := pRGBTriple(DWORD(pBmi) + pBmi^.bisize);
end;
except
result := false;
end;
end;
function TGLAviPlane.OpenAvi: boolean;
var
m: integer;
begin
// if fAviOpened then
// CloseAvi;
fFirstFrame := 0;
fFrameindex := 0;
fLastFrame := 0;
result := AVIFileOpen(pAvi, PChar(fFilename), OF_READ, nil) = AVIERR_OK;
if not result then
exit;
result := AVIFILEGetStream(pAvi, pAvis, streamtypeVIDEO, 0) = AVIERR_OK;
if not result then
exit;
result := AVIStreamInfoA(pAvis, AviInfo, sizeof(TAVIStreamInfoA)) = AVIERR_OK;
if not result then
exit;
if AviInfo.dwRate > 1000 then
begin
if AviInfo.dwRate > 100000 then
m := 10000
else if AviInfo.dwRate > 10000 then
m := 1000
else
m := 100;
end
else
m := 1;
fTargetFrameRate := AviInfo.dwRate / m;
fFirstFrame := AVIStreamStart(pAvis);
fLastFrame := AVIStreamENd(pAvis);
pFrame := AVIStreamGetFrameOpen(pAvis, nil);
result := assigned(pFrame);
AVIStreamBeginStreaming(pAvis, fFirstFrame, fLastFrame, 1000);
if not result then
CloseAvi
else
begin
fAviOpened := true;
GetFrame(fFirstFrame);
StructureChanged;
currdelta := 0;
CurrFrameCount := 0;
FileOrPosChanged := true;
end;
end;
procedure TGLAviPlane.CloseAvi;
begin
AVIStreamEndStreaming(pAvis);
AVIStreamGetFrameClose(pFrame);
AVIStreamrelease(pAvis);
// avifilerelease(pavi);
if assigned(pBmi) then
begin
pBmi := nil;
pColors := nil;
end;
fFirstFrame := 0;
fFrameindex := 0;
fLastFrame := 0;
fAviOpened := false;
end;
procedure TGLAviPlane.BuildStripArray;
var
r: integer;
temp, w, h: integer;
x, y: integer;
i: integer;
begin
if not assigned(pBmi) then
exit;
r := IntQuality;
w := (pBmi^.biWidth div r) - 2;
h := pBmi^.biHeight div r;
if (w + 2) * h <> length(StripArray) then
SetLength(StripArray, (w + 2) * h);
x := 0;
for y := 0 to h - 1 do
begin
StripArray[(y * (w + 2))] := affinevectormake(0, (y) / (60 / r), 0);
i := 0;
for temp := 1 to w do
begin
x := temp;
i := 1 - i;
if i = 0 then
StripArray[(y * (w + 2)) + x] := affinevectormake((x - 1) / (60 / r),
y / (60 / r), 0)
else
StripArray[(y * (w + 2)) + x] := affinevectormake((x - 1) / (60 / r),
(y + 1) / (60 / r), 0);
end;
StripArray[(y * (w + 2)) + x] := affinevectormake((x - 2) / (60 / r),
(y + 1) / (60 / r), 0);
end;
end;
procedure TGLAviPlane.FillColorArray;
var
x, y, i: integer;
rgb: pRGBTriple;
r, rw, w, h: integer;
begin
if not assigned(pBmi) then
exit;
r := IntQuality;
rw := pBmi^.biWidth;
w := (rw div r) - 2;
h := pBmi^.biHeight div r;
rgb := pColors;
inc(rgb, rw);
if (w + 2) * h <> length(ColorArray) then
SetLength(ColorArray, (w + 2) * h);
for y := 0 to h - 2 do
begin
i := 1;
for x := w + 1 downto 0 do
begin
if Rendermode = rmTriStripArray then
begin
i := 1 - i;
if i = 1 then
inc(rgb, (rw * (r - 1)));
end;
ColorArray[(y * (w + 2)) + x].x := rgb^.rgbtred / 256;
ColorArray[(y * (w + 2)) + x].y := rgb^.rgbtgreen / 256;
ColorArray[(y * (w + 2)) + x].Z := rgb^.rgbtblue / 256;
if Rendermode = rmTriStripArray then
begin
if i = 1 then
dec(rgb, (rw * (r - 1)));
end;
inc(rgb, r);
end;
if r > 1 then
inc(rgb, rw * (r - 1));
end;
end;
initialization
avifileinit;
finalization
avifileExit;
end.
|
unit MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons;
type
TfrmMain = class(TForm)
btnParse: TBitBtn;
mmoResult: TMemo;
procedure btnParseClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TEntChar = record
HTMLChar: string;
Unicode: string;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
API_HTTP,
API_Strings;
procedure TfrmMain.btnParseClick(Sender: TObject);
var
CharRow: string;
CharRowArr: TArray<string>;
EntChar: TEntChar;
EntCharArr: TArray<TEntChar>;
HTTP: THTTP;
i: Integer;
Page: string;
begin
HTTP := THTTP.Create;
try
Page := HTTP.Get('http://www.oasis-open.org/docbook/specs/wd-docbook-xmlcharent-0.3.html');
CharRowArr := TStrTool.CutArrayByKey(Page, '<tr><td><a name="', '</tr>');
EntCharArr := [];
for CharRow in CharRowArr do
begin
EntChar.HTMLChar := TStrTool.CutByKey(CharRow, '', '"');
EntChar.Unicode := TStrTool.CutByKey(CharRow, 'align="center">', '<');
EntCharArr := EntCharArr + [EntChar];
end;
mmoResult.Lines.Add('HTMLChars := [');
i := 0;
for EntChar in EntCharArr do
begin
Inc(i);
CharRow := Format(' [''%s'', #$%s]', [EntChar.HTMLChar, EntChar.Unicode]);
if i < Length(EntCharArr) then
CharRow := CharRow + ',';
mmoResult.Lines.Add(CharRow);
end;
mmoResult.Lines.Add('];');
finally
HTTP.Free;
end;
end;
end.
|
unit mckAccEditor;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TKOLAccEdit = class(TForm)
public
btOK: TButton;
edAcc: TEdit;
btCancel: TButton;
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btOKClick(Sender: TObject);
procedure btCancelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
constructor Create( AOwner: TComponent ); override;
end;
var
KOLAccEdit: TKOLAccEdit;
implementation
procedure TKOLAccEdit.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var S, K: String;
begin
if (Key = VK_CONTROL) or (Key = VK_SHIFT) or (Key = VK_MENU) then Exit;
if Shift * [ ssShift, ssAlt, ssCtrl ] = [ ] then Exit;
S := '';
if ssCtrl in Shift then S := S + 'Ctrl+';
if ssAlt in Shift then S := S + 'Alt+';
if ssShift in Shift then S := S + 'Shift+';
case Key of
VK_CANCEL : K := 'Cancel' ;
VK_BACK : K := 'Back' ;
VK_TAB : K := 'Tab' ;
VK_CLEAR : K := 'Clear' ;
VK_RETURN : K := 'Enter' ;
VK_PAUSE : K := 'Pause' ;
VK_CAPITAL : K := 'CapsLock' ;
VK_ESCAPE : K := 'Escape' ;
VK_SPACE : K := 'Space' ;
VK_PRIOR : K := 'PgUp' ;
VK_NEXT : K := 'PgDn' ;
VK_END : K := 'End' ;
VK_HOME : K := 'Home' ;
VK_LEFT : K := 'Left' ;
VK_UP : K := 'Up' ;
VK_RIGHT : K := 'Right' ;
VK_DOWN : K := 'Down' ;
VK_SELECT : K := 'Select' ;
VK_EXECUTE : K := 'Execute' ;
VK_SNAPSHOT : K := 'PrintScreen' ;
VK_INSERT : K := 'Insert' ;
VK_DELETE : K := 'Delete' ;
VK_HELP : K := 'Help' ;
$30..$39, $41..$5A : K := Char( Key );
VK_LWIN : K := 'LWin' ;
VK_RWIN : K := 'RWin' ;
VK_APPS : K := 'Apps' ;
VK_NUMPAD0 : K := 'Num0' ;
VK_NUMPAD1 : K := 'Num1' ;
VK_NUMPAD2 : K := 'Num2' ;
VK_NUMPAD3 : K := 'Num3' ;
VK_NUMPAD4 : K := 'Num4' ;
VK_NUMPAD5 : K := 'Num5' ;
VK_NUMPAD6 : K := 'Num6' ;
VK_NUMPAD7 : K := 'Num7' ;
VK_NUMPAD8 : K := 'Num8' ;
VK_NUMPAD9 : K := 'Num9' ;
VK_MULTIPLY : K := '*' ;
VK_ADD : K := '+' ;
VK_SEPARATOR : K := ';' ;
VK_SUBTRACT : K := '-' ;
VK_DECIMAL : K := ',' ;
VK_DIVIDE : K := '/' ;
VK_F1 : K := 'F1' ;
VK_F2 : K := 'F2' ;
VK_F3 : K := 'F3' ;
VK_F4 : K := 'F4' ;
VK_F5 : K := 'F5' ;
VK_F6 : K := 'F6' ;
VK_F7 : K := 'F7' ;
VK_F8 : K := 'F8' ;
VK_F9 : K := 'F9' ;
VK_F10 : K := 'F10' ;
VK_F11 : K := 'F11' ;
VK_F12 : K := 'F12' ;
VK_F13 : K := 'F13' ;
VK_F14 : K := 'F14' ;
VK_F15 : K := 'F15' ;
VK_F16 : K := 'F16' ;
VK_F17 : K := 'F17' ;
VK_F18 : K := 'F18' ;
VK_F19 : K := 'F19' ;
VK_F20 : K := 'F20' ;
VK_F21 : K := 'F21' ;
VK_F22 : K := 'F22' ;
VK_F23 : K := 'F23' ;
VK_F24 : K := 'F24' ;
VK_NUMLOCK : K := 'NumLock' ;
VK_SCROLL : K := 'ScrollLock' ;
VK_ATTN : K := 'ATTN' ;
VK_CRSEL : K := 'CRSel' ;
VK_EXSEL : K := 'EXSel' ;
VK_EREOF : K := 'EREOF' ;
VK_PLAY : K := 'Play' ;
VK_ZOOM : K := 'Zoom' ;
VK_NONAME : K := 'Noname' ;
VK_PA1 : K := 'PA1' ;
VK_OEM_CLEAR : K := 'OEMClear' ;
else K := '';
end;
if K <> '' then
edAcc.Text := S+K;
end;
procedure TKOLAccEdit.btOKClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
procedure TKOLAccEdit.btCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
constructor TKOLAccEdit.Create(AOwner: TComponent);
begin
CreateNew(AOwner);
Left := 208 ;
Top := 213 ;
BorderIcons := [biSystemMenu] ;
BorderStyle := bsToolWindow ;
Caption := 'Enter accelerator key for ' ;
ClientHeight := 38 ;
ClientWidth := 317 ;
Color := clBtnFace ;
//Font.Charset := DEFAULT_CHARSET ;
//Font.Color := clWindowText ;
//Font.Height := -11 ;
//Font.Name := 'MS Sans Serif' ;
//Font.Style := [] ;
KeyPreview := True ;
//OldCreateOrder := False ;
Scaled := False ;
OnKeyDown := FormKeyDown ;
//PixelsPerInch := 96 ;
//TextHeight := 13 ;
btOK := TButton.Create( Self ) ;
btOK.Parent := Self ;
btOK.Left := 154 ;
btOK.Top := 6 ;
btOK.Width := 75 ;
btOK.Height := 25 ;
btOK.Caption := 'OK' ;
btOK.Default := True ;
//btOK.TabOrder := 0 ;
btOK.OnClick := btOKClick ;
btCancel := TButton.Create( Self ) ;
btCancel.Parent := Self ;
btCancel.Left := 236 ;
btCancel.Top := 6 ;
btCancel.Width := 75 ;
btCancel.Height := 25 ;
btCancel.Cancel := True ;
btCancel.Caption := 'Cancel' ;
//btCancel.TabOrder := 1 ;
btCancel.OnClick := btCancelClick ;
edAcc := TEdit.Create( Self ); ;
edAcc.Parent := Self; ;
edAcc.Left := 10 ;
edAcc.Top := 6 ;
edAcc.Width := 135 ;
edAcc.Height := 21 ;
edAcc.Color := clBtnFace ;
edAcc.ReadOnly := True ;
edAcc.TabOrder := 2 ;
end;
end.
|
unit SyntaxHighlightThread;
interface
uses
SysUtils,Windows,Classes,Controls,Graphics,SyntaxHighlighter,SyncObjs;
type
IHighlightControl=interface
['{B1E3B5B2-CB8B-4D89-8AA6-81FDA48E5A89}']
procedure InvalidateLine(Index:Integer);
procedure TokenizeLineClass(const LastLineClass:TLineClass;var NewLineClass:TLineClass;const TextBuffer:PChar;const TextLength:Integer);
procedure TokenizeLine(const LineClass:TLineClass;const TextBuffer:PChar;const TextLength:Integer;CharClass:PCharClassArray);
procedure ContentModified;
end;
TLineData=record
ClassValid:Boolean;
LineClass,PreviousLineClass:TLineClass;
LineData:PCharClassArray;
LineLength:Integer;
end;
TLineDataArray=array[0..$FFFF] of TLineData;
PLineDataArray=^TLineDataArray;
TLinesData=record
Count:Integer;
Lines:PLineDataArray;
end;
TSyntaxHighlightThread=class(TThread)
private
FStrings:TStringList;
FControl:IHighlightControl;
FLinesData:TLinesData;
FSection:TCriticalSection;
FEvent:TEvent;
FLastStrings:TStrings;
procedure StringsChanging(Sender:TObject);
procedure StringsChanged(Sender:TObject);
function GetCharClass(Line, Column: Integer): TCharClass;
protected
procedure Execute;override;
procedure UpdateState;
public
constructor Create(AStrings:TStringList;AControl:IHighlightControl);
procedure Update;
procedure Lock;
procedure UnLock;
property CharClass[Line,Column:Integer]:TCharClass read GetCharClass;
procedure Terminate;
destructor Destroy;override;
end;
implementation
{ TSyntaxHighlightThread }
constructor TSyntaxHighlightThread.Create(AStrings: TStringList;
AControl: IHighlightControl);
begin
inherited Create(True);
IsMultiThread:=True;
FControl:=AControl;
FStrings:=AStrings;
FStrings.OnChange:=StringsChanged;
FStrings.OnChanging:=StringsChanging;
FLastStrings:=TStringList.Create;
FEvent:=TEvent.Create(nil,False,True,'');
FSection:=TCriticalSection.Create;
Priority:=tpIdle;
end;
destructor TSyntaxHighlightThread.Destroy;
begin
FLastStrings.Destroy;
FSection.Destroy;
FEvent.Destroy;
FStrings.OnChange:=nil;
FStrings.OnChanging:=nil;
inherited;
end;
procedure TSyntaxHighlightThread.Execute;
begin
while not Terminated do begin
UpdateState;
FEvent.WaitFor(INFINITE);
end;
end;
function TSyntaxHighlightThread.GetCharClass(Line,
Column: Integer): TCharClass;
begin
Lock;
try
if (Line<0) or (Line>=FLastStrings.Count) then
Result:=0
else begin
if (Column<0) or (Column>=FLinesData.Lines[Line].LineLength) then
Result:=0
else
Result:=FLinesData.Lines[Line].LineData[Column];
end;
finally
UnLock;
end;
end;
procedure TSyntaxHighlightThread.Lock;
begin
FSection.Enter;
end;
procedure TSyntaxHighlightThread.StringsChanged(Sender: TObject);
begin
FEvent.SetEvent;
FControl.ContentModified;
FSection.Leave;
end;
procedure TSyntaxHighlightThread.StringsChanging(Sender: TObject);
begin
FSection.Enter;
end;
procedure TSyntaxHighlightThread.Terminate;
begin
inherited;
Update;
end;
procedure TSyntaxHighlightThread.UnLock;
begin
FSection.Leave;
end;
procedure TSyntaxHighlightThread.Update;
begin
FEvent.SetEvent;
end;
procedure TSyntaxHighlightThread.UpdateState;
var
a,b,c:Integer;
l,m:TLineClass;
begin
FSection.Enter;
try
b:=0;
while (b<FLastStrings.Count) and
(b<FStrings.Count) and
(FLastStrings[b]=FStrings[b]) do
Inc(b);
Dec(b);
c:=1;
while (FLastStrings.Count-c>b) and
(FStrings.Count-c>=0) and
(FLastStrings[FLastStrings.Count-c]=FStrings[FStrings.Count-c]) do
Inc(c);
Dec(c);
if FStrings.Count>=FLastStrings.Count then begin
ReallocMem(FLinesData.Lines,FStrings.Count*SizeOf(TLineData));
CopyMemory(@FLinesData.Lines[FStrings.Count-c],@FLinesData.Lines[FLastStrings.Count-c],c*SizeOf(TLineData));
for a:=FLastStrings.Count-c to FStrings.Count-c-1 do
with FLinesData.Lines[a] do begin
ClassValid:=False;
LineClass:=0;
PreviousLineClass:=0;
LineLength:=Length(FStrings[a]);
GetMem(LineData,LineLength*SizeOf(TCharClass));
ZeroMemory(LineData,LineLength*SizeOf(TCharClass));
end;
end else begin
for a:=FStrings.Count-c to FLastStrings.Count-c-1 do
with FLinesData.Lines[a] do
FreeMem(LineData);
CopyMemory(@FLinesData.Lines[FStrings.Count-c],@FLinesData.Lines[FLastStrings.Count-c],c*SizeOf(TLineData));
ReallocMem(FLinesData.Lines,FStrings.Count*SizeOf(TLineData));
end;
FLastStrings.Assign(FStrings);
FLinesData.Count:=FStrings.Count;
for a:=b+1 to FStrings.Count-c-1 do
with FLinesData.Lines[a] do begin
ClassValid:=False;
LineClass:=0;
if LineLength<>Length(FStrings[a]) then begin
LineLength:=Length(FStrings[a]);
ReallocMem(LineData,LineLength*SizeOf(TCharClass));
end;
end;
a:=b+1;
if a=0 then
l:=0
else
l:=FLinesData.Lines[a-1].LineClass;
while (a<FStrings.Count) and (not FLinesData.Lines[a].ClassValid) do
with FLinesData.Lines[a] do begin
m:=0;
FControl.TokenizeLineClass(l,m,PChar(FStrings[a]),LineLength);
ZeroMemory(LineData,LineLength*SizeOf(TCharClass));
FControl.TokenizeLine(l,PChar(FStrings[a]),LineLength,LineData);
FControl.InvalidateLine(a);
if a<FStrings.Count-1 then
FLinesData.Lines[a+1].ClassValid:=FLinesData.Lines[a+1].ClassValid and (m=FLinesData.Lines[a+1].PreviousLineClass);
ClassValid:=True;
PreviousLineClass:=l;
LineClass:=m;
l:=m;
Inc(a);
end;
finally
FSection.Leave;
end;
end;
end.
|
{
Autor: Vinícius Lopes de Melo
Data: 17/06/2014
Link: https://github.com/viniciuslopesmelo/Aplicacao-Delphi
Script da tabela da base de dados:
CREATE TABLE VENDA (
ID_VENDA INTEGER NOT NULL,
NOME_CLIENTE VARCHAR(100),
VALOR NUMERIC(15,2));
ALTER TABLE VENDA ADD CONSTRAINT PK_VENDA PRIMARY KEY (ID_VENDA);
}
unit untDMPrincipal;
interface
uses
untDMConexao,
Forms, Variants, SysUtils, Classes, DBXFirebird, DB, SqlExpr,
FMTBcd, ppDB, ppDBPipe, ppComm, ppRelatv, ppProd, ppClass,
ppReport, DBClient, Provider, ppCtrls, ppPrnabl, ppBands,
ppCache, ppDesignLayer, ppParameter, ppVar, Windows,
Dialogs, Controls;
type
TDMPrincipal = class(TDataModule)
dsDados: TDataSource;
dspDados: TDataSetProvider;
qryDados: TSQLQuery;
qryDadosID_VENDA: TIntegerField;
qryDadosNOME_CLIENTE: TStringField;
qryDadosVALOR: TFMTBCDField;
qryPesquisa: TSQLQuery;
cdsDados: TClientDataSet;
cdsDadosID_VENDA: TIntegerField;
cdsDadosNOME_CLIENTE: TStringField;
cdsDadosVALOR: TFMTBCDField;
ppReport: TppReport;
ppDBPipeline: TppDBPipeline;
ppParameterList1: TppParameterList;
ppDesignLayers1: TppDesignLayers;
ppDesignLayer1: TppDesignLayer;
ppHeaderBand1: TppHeaderBand;
ppDetailBand1: TppDetailBand;
ppFooterBand1: TppFooterBand;
ppDBText1: TppDBText;
ppDBText2: TppDBText;
ppDBText3: TppDBText;
ppLabel1: TppLabel;
ppLabel2: TppLabel;
ppLabel3: TppLabel;
ppLabel4: TppLabel;
ppSystemVariable1: TppSystemVariable;
ppLine1: TppLine;
public
function gravarRegistros(iQtdeRegistros: Integer): Boolean;
function excluirTodosRegistros: Integer;
function pesquisarPrimeiraVenda: Boolean;
function pesquisarVendas: Boolean;
function pesquisarUltimoId: Boolean;
function emitirRelatorio: Boolean;
function atualizarConexaoAplicativo: Boolean;
function imprimirMensagem(sMensagem : string;
sTipoMensagem : string): Boolean;
end;
var
DMPrincipal: TDMPrincipal;
implementation
{$R *.dfm}
{ TDMAplicativo }
function TDMPrincipal.atualizarConexaoAplicativo: Boolean;
begin
DMConexao.atualizarConexaoAplicativo;
end;
function TDMPrincipal.emitirRelatorio: Boolean;
begin
ppReport.Print;
end;
function TDMPrincipal.excluirTodosRegistros: Integer;
var
iQtdeRegistrosExcluidos: Integer;
begin
try
DMConexao.iniciarTransacao;
qryDados.Close;
qryDados.SQL.Clear;
qryDados.SQL.Add('DELETE FROM VENDA');
iQtdeRegistrosExcluidos := qryDados.ExecSQL(True);
if (iQtdeRegistrosExcluidos > 0) then
begin
DMConexao.confirmarTransacao;
Result := iQtdeRegistrosExcluidos;
end
else
begin
DMConexao.reverterTransacao;
Result := 0;
end;
except
on E:Exception do
begin
DMConexao.reverterTransacao;
imprimirMensagem('Não foi possível excluir todos os registros.' + sLineBreak + sLineBreak +
'Erro: ' + E.Message,
'Erro');
end;
end;
end;
function TDMPrincipal.gravarRegistros(iQtdeRegistros: Integer): Boolean;
var
i, iUltimoId: Integer;
begin
try
DMConexao.iniciarTransacao;
if (pesquisarUltimoId) then
begin
if (qryPesquisa.FieldByName('ULTIMO_ID').Value = Null) then
iUltimoId := 0
else
iUltimoId := qryPesquisa.FieldByName('ULTIMO_ID').Value;
if (iUltimoId = 0) then
begin
if (not cdsDados.Active) then
cdsDados.Open;
for i := 1 to iQtdeRegistros do
begin
cdsDados.Append;
cdsDadosID_VENDA.Value := i;
cdsDadosNOME_CLIENTE.Value := 'Cliente Consumidor ' + IntToStr(i);
cdsDadosVALOR.AsCurrency := i;
cdsDados.Post;
end;
end
else
begin
Inc(iUltimoId);
if (not cdsDados.Active) then
cdsDados.Open;
for i := 1 to iQtdeRegistros do
begin
cdsDados.Append;
cdsDadosID_VENDA.Value := iUltimoId;
cdsDadosNOME_CLIENTE.Value := 'Cliente Consumidor ' + IntToStr(iUltimoId);
cdsDadosVALOR.AsCurrency := i;
cdsDados.Post;
Inc(iUltimoId);
end;
end;
end
else
begin
if (not cdsDados.Active) then
cdsDados.Open;
for i := 1 to iQtdeRegistros do
begin
cdsDados.Append;
cdsDadosID_VENDA.Value := i;
cdsDadosNOME_CLIENTE.Value := 'Cliente Consumidor ' + IntToStr(i);
cdsDadosVALOR.AsCurrency := i;
cdsDados.Post;
end;
end;
if (cdsDados.ApplyUpdates(0) = 0) then
begin
DMConexao.confirmarTransacao;
Result := True;
end
else
begin
DMConexao.reverterTransacao;
Result := False;
end;
except
on E:Exception do
begin
DMConexao.reverterTransacao;
imprimirMensagem('Não foi possível gravar o registro: ' + sLineBreak +
'ID Venda: ' + IntToStr(cdsDadosID_VENDA.Value) +
' Cliente: ' + cdsDadosNOME_CLIENTE.Value +
' Valor: ' + FloatToStr(cdsDadosVALOR.AsCurrency) + sLineBreak + sLineBreak +
'Erro: ' + E.Message,
'Erro');
end;
end;
end;
function TDMPrincipal.imprimirMensagem(sMensagem : string;
sTipoMensagem : string): Boolean;
begin
Result := False;
if (sTipoMensagem = 'Informação') then
MessageBox(Application.Handle, PWideChar(sMensagem), 'Informação', MB_OK + MB_ICONINFORMATION)
else if (sTipoMensagem = 'Aviso') then
MessageBox(Application.Handle, PWideChar(sMensagem), 'Aviso', MB_OK + MB_ICONWARNING)
else if (sTipoMensagem = 'Erro') then
MessageBox(Application.Handle,
PWideChar(sMensagem + sLineBreak + sLineBreak + 'Dúvidas? Entre em contato com o desenvolvedor.'),
'Erro',
MB_OK + MB_ICONERROR)
else if (sTipoMensagem = 'Pergunta') then
begin
if (MessageBox(Application.Handle, PWideChar(sMensagem), 'Pergunta', MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON2) = IDYES) then
Result := True
else
Result := False;
end;
end;
function TDMPrincipal.pesquisarPrimeiraVenda: Boolean;
begin
qryPesquisa.Close;
qryPesquisa.SQL.Clear;
qryPesquisa.SQL.Add('SELECT FIRST 1 * ');
qryPesquisa.SQL.Add(' FROM VENDA');
qryPesquisa.Open;
if (not qryPesquisa.IsEmpty) then
Result := True
else
Result := False;
end;
function TDMPrincipal.pesquisarUltimoId: Boolean;
begin
qryPesquisa.Close;
qryPesquisa.SQL.Clear;
qryPesquisa.SQL.Add('SELECT MAX(ID_VENDA) AS ULTIMO_ID FROM VENDA');
qryPesquisa.Open;
if (not qryPesquisa.IsEmpty) then
Result := True
else
Result := False;
end;
function TDMPrincipal.pesquisarVendas: Boolean;
begin
cdsDados.Close;
qryDados.SQL.Clear;
qryDados.SQL.Add('SELECT * FROM VENDA');
cdsDados.Open;
if (not cdsDados.IsEmpty) then
Result := True
else
Result := False;
end;
end.
|
unit untAutenticacao;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, RxGIF, HkHints, untDeclaracoes;
type
TfrmAutenticacao = class(TForm)
Label1: TLabel;
Panel1: TPanel;
btnAutenticar: TButton;
btnCancelar: TButton;
imgVermelha: TImage;
imgVerde: TImage;
edtSenha: TEdit;
Label4: TLabel;
Label3: TLabel;
edtUsuario: TEdit;
Label2: TLabel;
edtEmpresa: TEdit;
lblempresa: TLabel;
lblusuario: TLabel;
procedure edtEmpresaExit(Sender: TObject);
procedure edtUsuarioExit(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure verificaAcesso();
procedure btnAutenticarClick(Sender: TObject);
procedure edtEmpresaKeyPress(Sender: TObject; var Key: Char);
procedure edtSenhaChange(Sender: TObject);
procedure edtSenhaEnter(Sender: TObject);
procedure edtEmpresaEnter(Sender: TObject);
procedure edtUsuarioEnter(Sender: TObject);
private
f : TFuncoes;
{ Private declarations }
public
{ Public declarations }
end;
var
frmAutenticacao: TfrmAutenticacao;
implementation
uses untDM, untPrincipal;
{$R *.dfm}
procedure TfrmAutenticacao.edtEmpresaExit(Sender: TObject);
{
verificica se a empresa existe no banco de dados, caso ela nao existir
o edt fica vermelho
}
begin
if edtEmpresa.Text<>'' then
begin
dm.executaSql(dm.cdsAux,'select nmfant as nome from empre where cdempr='+
QuotedStr(edtEmpresa.Text));
if dm.cdsAux.IsEmpty then
begin
lblempresa.Visible:= true;
lblEmpresa.Caption := 'Empresa Não Existe!';
lblEmpresa.Font.Color := clred;
edtEmpresa.Color := clred;
end else
begin
lblEmpresa.Visible:= true;
lblEmpresa.Font.Color := clOlive;
lblEmpresa.Caption := dm.cdsAux.FieldByName('nome').AsString;
edtEmpresa.Color := clWindow;
end;
end;
end;
procedure TfrmAutenticacao.edtUsuarioExit(Sender: TObject);
{
verificica se o usuario existe no banco de dados, caso ele nao existir
o edt fica vermelho
}
begin
if edtUsuario.Text <> '' then
begin
dm.executaSql(dm.cdsAux,'select uclogin as nome from uctabusers where uciduser='+
QuotedStr(edtUsuario.Text));
if dm.cdsAux.IsEmpty then
begin
lblusuario.Visible:= true;
lblusuario.Caption := 'Usuário Não Existe!';
lblusuario.Font.Color := clred;
edtUsuario.Color := clred;
end else
begin
lblusuario.Visible:= true;
lblusuario.Font.Color := clOlive;
lblusuario.Caption := dm.cdsAux.FieldByName('nome').AsString;
edtUsuario.Color:= clWindow;
end;
end;
end;
procedure TfrmAutenticacao.btnCancelarClick(Sender: TObject);
{
se clicar no botão cancelar termina a aplicação
}
begin
Application.Terminate;
end;
procedure TfrmAutenticacao.verificaAcesso;
{
verifica o acesso do usuario na function no dm,
caso seja true ele da acesso, dando enabled true
para o botão autentica
}
begin
if dm.Autenticacao(StrToInt(edtEmpresa.Text),lblusuario.Caption,edtSenha.Text) then
begin
imgVermelha.Visible:= false;
imgVerde.Visible:= true;
btnAutenticar.Enabled := true;
end else
begin
imgVermelha.Visible:= true;
imgVerde.Visible:= false;
btnAutenticar.Enabled := false;
end;
end;
procedure TfrmAutenticacao.btnAutenticarClick(Sender: TObject);
{
atribui as variaveis do form principal, de acordo
com a autenticação
}
begin
frmPrincipal.lbEdtNick.Text := 'Emp.: ' + edtEmpresa.Text + ' ' +
'" ' + lblusuario.Caption + ' "';
frmPrincipal.btnConecta.OnClick(Sender);
close;
end;
procedure TfrmAutenticacao.edtEmpresaKeyPress(Sender: TObject;
var Key: Char);
begin
If not( key in['0'..'9',#8] ) then key := #0;
end;
procedure TfrmAutenticacao.edtSenhaChange(Sender: TObject);
{
verifica o acesso a cada letra que o usuario digita
para asism mostrar o sinal verde ou vermelho
}
begin
verificaAcesso;
end;
procedure TfrmAutenticacao.edtSenhaEnter(Sender: TObject);
{
caso o usuario ou empresa estiverem em branco,
ele não deixa que seja digitada a senha
}
begin
if edtEmpresa.Text = '' then
begin
f.Mensagem(false,'Preencha o código da Empresa!');
edtEmpresa.SetFocus;
end
else if edtUsuario.Text = '' then
begin
f.Mensagem(false,'Preencha o código do Usuário!');
edtUsuario.SetFocus;
end;
end;
procedure TfrmAutenticacao.edtEmpresaEnter(Sender: TObject);
{
no onenter de emrpesa ele deixa senha em barnco, para
que o usuario depois de ter o acesso, não possa mudar a emrpesa
}
begin
edtSenha.Text := '';
end;
procedure TfrmAutenticacao.edtUsuarioEnter(Sender: TObject);
{
no onenter de usuario ele deixa senha em barnco, para
que o usuario depois de ter o acesso, não possa mudar o usuario
}
begin
edtSenha.Text := '';
end;
end.
|
UNIT tempUnit;
INTERFACE
FUNCTION isPlausible_Unit(h, min : INTEGER; temp : REAL) : BOOLEAN;
IMPLEMENTATION
(*Globale Vraiblen in der UNIT*)
VAR lastTime : INTEGER;
VAR lastTemp : REAL;
FUNCTION isPlausible_Unit(h, min : INTEGER; temp : REAL) : BOOLEAN;
VAR diff_time : INTEGER;
VAR diff_temp : REAL;
BEGIN
diff_time := ((h * 60) + min) - lastTime;
diff_temp := temp - lastTemp;
lastTime := (h * 60) + min;
lastTemp := temp;
isPlausible_Var := True;
IF (temp <936.8) OR (temp > 1345.3) OR (((11.45 / 60) * diff_time) >= diff_temp) THEN
isPlausible_Var := False;
END;
BEGIN
lasTime := 0;
lastTemp := 1000;
END. |
unit Cotacao.Model.Interf;
interface
uses ormbr.container.objectset.interfaces,
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, TESTCOTACAO.Entidade.Model;
type
ICotacaoModel = interface
['{2363B7B6-5799-453F-82BD-73A93BA096C3}']
function Entidade(AValue: TTESTCOTACAO): ICotacaoModel; overload;
function Entidade: TTESTCOTACAO; overload;
function DAO: IContainerObjectSet<TTESTCOTACAO>;
function query: TFDQuery;
function queryItensCotacao(ACodOrcamento: string): TFDQuery;
end;
implementation
end.
|
unit UList;
interface
Uses
UListItem, SyncObjs, System.Classes, Windows, dialogs, SysUtils;
Type
TListState = (lsNormal, lsAddbefore, lsAddAfter, lsDelete);
TListMode = (lmControl, lmNormal, lmDemo);
TList = class
Private
Count: Integer;
First: TListItem;
// ThreadId: Integer;
// FState: TListState;
FTempItem: TListItem;
FNewItem: TListItem;
// Поле ссылающееся на обработчик события MyEvent.
// Тип TNotifyEvent описан в модуле Clases так: TNotifyEvent = procedure(Sender: TObject) of object;
// Фраза "of object" означает, что в качестве обработчика можно назначить только метод какого-либо
// класса, а не произвольную процедуру.
FOnThreadSuspended: TNotifyEvent;
FDeleteItem: TListItem;
procedure _AddAfter();
procedure _AddBefore();
Function _Delete(): boolean;
procedure Pause();
Public
ThreadId: Integer;
State: TListState;
Mode: TListMode;
Constructor Create;
Function Getcount: Integer;
Function GetFirst: TListItem;
Function AddAfter(SearchItem: string; NewItem: TListItem): boolean;
Function AddBefore(SearchItem: string; NewItem: TListItem): boolean;
Function Delete(SearchItem: string): boolean;
Function Search(SearchItem: string): TListItem;
procedure NextStep();
// Эта процедура проверяет задан ли обработчик события. И, если задан, запускает его.
procedure DoMyEvent; dynamic;
// Это свойство позволяет назначить обработчик для обработки события MyEvent.
property OnThreadSyspended: TNotifyEvent read FOnThreadSuspended
write FOnThreadSuspended;
// Процедура, которая принимает решение - произошло событие MyEvent или нет.
// Таких процедур может быть несколько - везде где может возникнуть событие MyEvent.
// Если событие MyEvent произошло, то вызвается процедура DoMyEvent().
procedure GenericMyEvent;
property NewItem: TListItem read FNewItem;
property TempItem: TListItem read FTempItem;
property DeleteItem: TListItem read FDeleteItem;
End;
implementation
uses Logger;
var
CritSec: TCriticalSection; // объект критической секции
// переменные для хранения входных парамтеров в функцию добавления
_NewItem: TListItem;
_SearchItem: string;
Constructor TList.Create;
begin
Count := 0;
First := nil;
Mode := lmControl;
State := lsNormal;
CritSec := TCriticalSection.Create;
end;
{$REGION 'Public functions'}
Function TList.Getcount: Integer;
begin
result := Count;
end;
Function TList.GetFirst: TListItem;
begin
result := First;
end;
function TList.AddAfter(SearchItem: string; NewItem: TListItem): boolean;
var
id: longword;
begin
_NewItem := NewItem;
_SearchItem := SearchItem;
State := lsAddAfter;
ThreadId := BeginThread(nil, 0, @TList._AddAfter, Self, 0, id);
end;
function TList.AddBefore(SearchItem: string; NewItem: TListItem): boolean;
var
id: longword;
begin
_NewItem := NewItem;
_SearchItem := SearchItem;
State := lsAddAfter;
ThreadId := BeginThread(nil, 0, @TList._AddBefore, Self, 0, id);
end;
Function TList.Delete(SearchItem: string): boolean;
var
id: longword;
begin
State := lsDelete;
_SearchItem := SearchItem;
ThreadId := BeginThread(nil, 0, @TList._Delete, Self, 0, id);
// _Delete(SearchItem);
end;
{$ENDREGION}
{$REGION 'Thread functions'}
procedure TList._AddAfter();
var
NewItem: TListItem;
SearchItem: string;
{$REGION 'вложенные функции для добавления'}
procedure CLeanListItemsStates;
var
temp, last: TListItem;
begin
temp := First;
while temp <> nil do
begin
temp.IsAddBefore := false;
temp.IsAddAfter := false;
temp.IsFirst := false;
temp.IsLast := false;
last := temp;
temp := temp.GetNext;
end;
First.IsFirst := true;
last.IsLast := true;
FTempItem := nil;
FNewItem := nil;
end;
procedure FuncEnd();
begin
State := lsNormal;
CLeanListItemsStates;
TLogger.Log('=====Закончили добавление нового элемента в список=====');
if Mode <> lmNormal then
GenericMyEvent;
CritSec.Leave;
EndThread(0);
exit;
end;
{$ENDREGION}
Begin
CritSec.Enter;
NewItem := _NewItem;
SearchItem := _SearchItem;
TLogger.Log('=====Добавление нового элемента в список=====');
If First = nil then
begin
TLogger.Log('Список пуст. Добавляем первый элемент');
TLogger.Log('Указатель First адресуем с новый элемент');
First := NewItem;
NewItem.IsFirst := true;
NewItem.IsLast := true;
Pause();
TLogger.Log('Увеличиваем счетчик числа элементов');
inc(Count);
// result := true;
FuncEnd();
End;
TLogger.Log('=====Поиск заданного элемента=====');
FNewItem := NewItem;
FTempItem := Search(SearchItem);
If TempItem = nil then
begin
TLogger.Log('Искомый элемент не найден');
// result := false;
FuncEnd();
end;
If TempItem.GetNext = nil then
begin
TempItem.IsAddAfter := true;
TLogger.Log('Адресное поле next у найденного = null. Добавляем в конец.');
NewItem.SetNext(nil);
Pause();
TLogger.Log
('В адресной поле "Prev" для нового элемента записываем ссылку на найденного');
NewItem.SetPrev(TempItem);
Pause();
TLogger.Log
('В адресной поле "Next" для найденного элемента записываем ссылку на новый элемент "New" ');
TempItem.SetNext(NewItem);
TempItem.IsAddAfter := false;
TempItem.IsLast := false;
NewItem.IsLast := true;
Pause();
TLogger.Log('Увеличиваем счетчик числа элементов');
inc(Count);
// result := true
End
Else
Begin
TempItem.IsAddAfter := true;
TLogger.Log('Формируем поля нового элемента');
Pause();
TLogger.Log
('в поле next заносится адрес следующего элемента (берется из поля next найденного элемента)');
NewItem.SetNext(TempItem.GetNext);
Pause();
TLogger.Log
('в поле prev заносится адрес предшествующего элемента, которым является найденный элемент');
NewItem.SetPrev(TempItem);
Pause();
TLogger.Log
('Изменяем адресное поле prev у элемента, который должен следовать за новым, на адрес нового элемента');
NewItem.GetNext.SetPrev(NewItem);
Pause();
TLogger.Log
('Изменяем адресное поле next у найденного элемента на адрес нового элемента');
TempItem.SetNext(NewItem);
inc(Count)
End;
FuncEnd();
end;
procedure TList._AddBefore();
var
NewItem: TListItem;
SearchItem: string;
{$REGION 'вложенные функции для добавления'}
procedure CLeanListItemsStates;
var
temp, last: TListItem;
begin
temp := First;
while temp <> nil do
begin
temp.IsAddBefore := false;
temp.IsAddAfter := false;
temp.IsFirst := false;
temp.IsLast := false;
last := temp;
temp := temp.GetNext;
end;
First.IsFirst := true;
last.IsLast := true;
FTempItem := nil;
FNewItem := nil;
end;
procedure FuncEnd();
begin
State := lsNormal;
CLeanListItemsStates;
TLogger.Log('=====Закончили добавление нового элемента в список=====');
if Mode <> lmNormal then
GenericMyEvent;
CritSec.Leave;
EndThread(0);
exit;
end;
{$ENDREGION}
Begin
CritSec.Enter;
NewItem := _NewItem;
SearchItem := _SearchItem;
TLogger.Log('=====Добавление нового элемента в список=====');
TLogger.Log('1. Поиск заданного элемента ');
FNewItem := NewItem;
FTempItem := Search(SearchItem);
If TempItem = nil then
begin
TLogger.Log('• Искомый элемент не найден');
// result := false;
FuncEnd();
end;
If TempItem.GetPrev = nil then
begin
TempItem.IsAddBefore := true;
TLogger.Log
('Адресное поле prev у найденного = null. Добавляем перед первым.');
NewItem.SetPrev(nil);
Pause();
TLogger.Log
('В адресное поле "Prev" для найденного элемента записываем ссылку нового');
TempItem.SetPrev(NewItem);
Pause();
TLogger.Log
('В адресное поле "Next" для нового элемента записываем ссылку найденнлшл элемента "Temp" ');
NewItem.SetNext(TempItem);
TLogger.Log('Изменяем указатель "First"');
First := NewItem;
// TempItem.IsAddBefore := false;
// TempItem.IsLast := false;
Pause();
TLogger.Log('Увеличиваем счетчик числа элементов');
inc(Count);
// result := true
End
Else
Begin
TempItem.IsAddBefore := true;
TLogger.Log('3. Формируем поля нового элемента, в частности: ');
Pause();
TLogger.Log('• в поле next заносится адрес заданного элемента');
NewItem.SetNext(TempItem);
Pause();
TLogger.Log
('• в поле prev заносится адрес предшествующего элемента (берется из поля prev найденного элемента)');
NewItem.SetPrev(TempItem.GetPrev);
Pause();
TLogger.Log
('4. Изменяем адресное поле prev у заданного элемента на адрес нового элемента');
TempItem.SetPrev(NewItem);
Pause();
TLogger.Log
('5. Изменяем адресное поле next у предшествующего элемента на адрес нового элемента');
NewItem.GetPrev.SetNext(NewItem);
TLogger.Log('6. Увеличиваем количество элементов');
inc(Count)
End;
FuncEnd();
end;
Function TList._Delete(): boolean;
// var
// temp: TListItem;
{$REGION 'вложенные функции для удаления'}
procedure CLeanListItemsStates;
var
temp, last: TListItem;
begin
temp := First;
while temp <> nil do
begin
temp.IsAddBefore := false;
temp.IsAddAfter := false;
temp.IsFirst := false;
temp.IsLast := false;
temp.IsDelete := false;
last := temp;
temp := temp.GetNext;
end;
First.IsFirst := true;
last.IsLast := true;
FDeleteItem := nil;
FTempItem := nil;
FNewItem := nil;
end;
procedure FuncEnd();
begin
State := lsNormal;
CLeanListItemsStates;
GenericMyEvent;
TLogger.Log('=====Элемент удален из списка=====');
CritSec.Leave;
EndThread(0);
exit;
end;
{$ENDREGION}
begin
CritSec.Enter;
TLogger.Log('=====Удаление элемента из списка=====');
TLogger.Log('1. Проверка наличия элементов в списке');
TLogger.Log(' count= ' + IntToStr(Count));
result := false;
if Count = 0 then
FuncEnd;
TLogger.Log('2. Поиск заданного элемента');
FTempItem := Search(_SearchItem);
If TempItem = nil then
begin
TLogger.Log('Искомый элемент не найден');
// result := false;
FuncEnd();
end;
TLogger.Log('Искомый элемент найден, адресуем его указателем pTemp');
FTempItem.IsDelete := true;
FDeleteItem := FTempItem;
If FTempItem = First then
begin
// удаление единственного эл.
If First.GetNext = nil then
begin
TLogger.Log('=====Удаление единственного элемента из списка=====');
result := true;
TLogger.Log('Указатель First адресуем в nil');
First := nil;
Pause();
TLogger.Log('Уменьшаем количество элементов');
Count := 0;
FuncEnd;
End
else
begin
// удаление первого эл.
TLogger.Log('=====Удаление первого элемента из списка=====');
TLogger.Log
('3. Изменяем адресное поле Prev у элемента следующего после удаляемого');
First.GetNext.SetPrev(nil);
Pause();
TLogger.Log
('4. Указатель First адресуем в следующий за удаляемым элементом');
First := FTempItem.GetNext;
CLeanListItemsStates;
Pause();
TLogger.Log('5. Уменьшаем количество элементов');
Count := Count - 1;
result := true;
TLogger.Log('6. Обрабатываем удаляемый элемент');
FTempItem := nil;
FuncEnd;
end;
End;
// удаление из середины списка
if FTempItem.GetNext <> nil then
TLogger.Log('=====Удаление элемента из середины списка=====')
else
TLogger.Log('=====Удаление элемента из конца списка=====');
TLogger.Log
('3. Изменяем адресное поле next у элемента, предшествующего удаляемому на адрес элемента, следующего за удаляемым');
TempItem.GetPrev.SetNext(FTempItem.GetNext);
Pause();
if FTempItem.GetNext <> nil then
begin
TLogger.Log
('4. Изменяем адресное поле prev у следующего за удаляемым элемента на адрес элемента, предшествующего удаляемому');
FTempItem.GetNext.SetPrev(FTempItem.GetPrev);
end;
Pause();
TLogger.Log('5. Обрабатываем удаляемый элемент');
FTempItem := nil;
Pause();
Count := Count - 1;
result := true;
FuncEnd;
end;
Function TList.Search(SearchItem: string): TListItem;
begin
result := nil;
TLogger.Log('Устанавливаем указатель temp в адрес первого элемента в списке');
FTempItem := First;
Pause();
TLogger.Log('Сравниваем искомый элемент с текущим:');
while (FTempItem <> nil) do
if (FTempItem.GetInfo = SearchItem) then
begin
TLogger.Log(FTempItem.GetInfo + ' = ' + SearchItem);
result := FTempItem;
break;
end
else
begin
TLogger.Log(FTempItem.GetInfo + ' <> ' + SearchItem);
FTempItem := FTempItem.GetNext;
TLogger.Log('Переходим к следующему');
Pause();
end;
end;
procedure TList.Pause();
begin
case Mode of
lmControl:
begin
GenericMyEvent;
SuspendThread(ThreadId);
end;
lmNormal:
;
lmDemo:
;
end;
end;
Procedure TList.NextStep();
begin
ResumeThread(ThreadId);
end;
{$ENDREGION}
{$REGION 'Event'}
procedure TList.DoMyEvent;
begin
// Если обработчик назначен, то запускаем его.
if Assigned(FOnThreadSuspended) then
FOnThreadSuspended(Self);
end;
procedure TList.GenericMyEvent;
var
MyEventIsOccurred: boolean;
begin
MyEventIsOccurred := true;
// Если верно некоторое условие, которое подтверждает, что событие MyEvent
// произошло, то делаем попытку запустить связанный обработчик.
if MyEventIsOccurred then
begin
DoMyEvent;
end;
end;
{$ENDREGION}
end.
|
{Una empresa transportista clasifica el tamaño de las cargas (son cubos) según el peso y la
medida de un lado, de la siguiente forma:
- Grande si el peso es mayor a 10 kg y el lado mide mas de 90 cm.
- Medianos si pesa mas de 5kg y hasta 10 inclusive y el lado mide menor o igual de 90 cm.
- Chico si es menor o igual e 5 kg. Y el lado mide menos de 50 cm.
Se pide leer las especificaciones de una carga e informar la clasificación correspondiente, o “no
clasifica”. Además en el caso de que clasifique informar cuanto debe abonar teniendo en cuenta
que se cobra $5, $3 y $2.5 por kilo respectivamente a las categorías mencionadas.
Determine los datos que se requieren para calcular la clasificación y costo de una carga}
Program transportista;
Var
peso,lado:longint;
precio:real;
Begin
write('Ingrese el peso de la carga : ');readln(peso);
write('Ingrese la medida en cm de un lado del cubo : ');readln(lado);
writeln(' ');
If (peso <= 5) and (lado < 50) then
begin
writeln('El tamanio de la carga es: chico');
precio:= peso * 2.5;
end
Else
if (peso <= 10) and (lado <= 90) then
begin
writeln('El tamanio de la carga es: mediano');
precio:= peso * 3;
end
Else
begin
writeln('El tamanio de la carga es: grande');
precio:= peso * 5;
end;
writeln(' ');
writeln('El costo de la carga es : ',precio:2:0);
end.
|
unit uPRK_SP_TYPE_DOP_DOK;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uPrK_SpravOneLevel, cxGraphics, cxStyles, cxCustomData,
cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, dxBar,
dxBarExtItems, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase,
pFIBDatabase, FIBDataSet, pFIBDataSet, ImgList, ActnList, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses,
cxControls, cxGridCustomView, cxGrid, dxStatusBar,uPrK_Resources,
cxCheckBox;
type
TFormPRK_SP_TYPE_DOP_DOK = class(TFormPrK_SpravOneLevel)
colNAME_VEDOM_TYPE: TcxGridDBColumn;
colIS_OCENKA: TcxGridDBColumn;
colNAME_PREDM: TcxGridDBColumn;
colIS_NO_ROZPISKA: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
procedure ActionADDExecute(Sender: TObject);
procedure ActionChangeExecute(Sender: TObject);
procedure ActionViewExecute(Sender: TObject);
procedure ActionVibratExecute(Sender: TObject);
private
procedure InicCaption;override;
public
{ Public declarations }
end;
type
TDataPrKSpravDOP_DOK=class(TDataPrKSprav)
private
FIdSpIspitVedomType: int64;
FIsOcenka: Smallint;
FShortNameVedomType: string;
FIdSpPredm: int64;
FShortNamePredm: string;
FIsNoRozpiska: Integer;
constructor Create(aKodMax: Integer;aNppMax: Integer);overload;override;
constructor Create(aId:int64; aName:String; aShortName:String;
aKod:Integer;aNpp: Integer;
aIdSpIspitVedomType :int64;
aShortNameVedomType :string;
aIdSpPredm :int64;
aShortNamePredm :string;
aIsOcenka :Smallint;
aIsNoRozpiska :Integer);overload;
procedure SetIdSpIspitVedomType(const Value: int64);
procedure SetIsOcenka(const Value: Smallint);
procedure SetShortNameVedomType(const Value: string);
procedure SetIdSpPredm(const Value: int64);
procedure SetShortNamePredm(const Value: string);
procedure SetIsNoRozpiska(const Value: Integer);
public
property IdSpIspitVedomType :int64 read FIdSpIspitVedomType write SetIdSpIspitVedomType;
property ShortNameVedomType :string read FShortNameVedomType write SetShortNameVedomType;
property IdSpPredm :int64 read FIdSpPredm write SetIdSpPredm;
property ShortNamePredm :string read FShortNamePredm write SetShortNamePredm;
property IsOcenka :Smallint read FIsOcenka write SetIsOcenka;
property IsNoRozpiska :Integer read FIsNoRozpiska write SetIsNoRozpiska;
end;
var
FormPRK_SP_TYPE_DOP_DOK: TFormPRK_SP_TYPE_DOP_DOK;
implementation
uses uConstants,uPrKSpravEditTYPE_DOP_DOK, uPrKKlassSprav,
AArray ;
{$R *.dfm}
procedure TFormPRK_SP_TYPE_DOP_DOK.FormCreate(Sender: TObject);
begin
inherited;
{ID_NAME должен стоять первым так как в SelectSQLText может делаться CloseOpen}
ID_NAME :='ID_SP_TYPE_DOP_DOK';
SelectSQLText :='Select * from PRK_SP_TYPE_DOP_DOK_SELECT('+IntTostr(ParamSprav['Input']['ID_CN_SP_FORM_STUD'].AsInt64)+','
+IntTostr(ParamSprav['Input']['ID_CN_SP_KAT_STUD'].AsInt64)+','+IntTostr(ParamSprav['Input']['ID_CN_JN_FACUL_SPEC'].AsInt64)+')';
ShowNpp := false;
StoredProcAddName :='PRK_SP_TYPE_DOP_DOK_ADD';
StoredProcChangeName :='PRK_SP_TYPE_DOP_DOK_CHANGE';
StoredProcDelName :='PRK_SP_TYPE_DOP_DOK_DEL';
InicFormCaption :=nFormPRK_SP_TYPE_DOP_DOK_Caption[IndexLanguage];
//CheckAccessAdd :='';
//CheckAccessChange :='';
//CheckAccessDel :='';
end;
procedure TFormPRK_SP_TYPE_DOP_DOK.InicCaption;
begin
inherited;
colNAME_VEDOM_TYPE.Caption :=ncolNAME_VEDOM_TYPE[IndexLanguage];
colIS_OCENKA.Caption :=ncolIS_OCENKA_Vedom[IndexLanguage];
colNAME_PREDM.Caption :=ncolPREDM[IndexLanguage];
colIS_NO_ROZPISKA.Caption :=ncolIS_NO_ROZPISKA[IndexLanguage];
end;
{ TDataPrKSpravDOP_DOK }
constructor TDataPrKSpravDOP_DOK.Create(aId: int64; aName,
aShortName: String; aKod, aNpp: Integer; aIdSpIspitVedomType: int64;
aShortNameVedomType: string; aIdSpPredm :int64; aShortNamePredm :string;
aIsOcenka: Smallint;aIsNoRozpiska :Integer);
begin
Create(aId, aName, aShortName,aKod,aNpp);
IdSpIspitVedomType :=aIdSpIspitVedomType;
ShortNameVedomType :=aShortNameVedomType;
IdSpPredm :=aIdSpPredm;
ShortNamePredm :=aShortNamePredm;
IsOcenka :=aIsOcenka;
IsNoRozpiska :=aIsNoRozpiska;
end;
constructor TDataPrKSpravDOP_DOK.Create(aKodMax, aNppMax: Integer);
begin
inherited;
IdSpIspitVedomType :=-1;
ShortNameVedomType :='';
IdSpPredm :=-1;
ShortNamePredm :='';
IsOcenka :=0;
IsNoRozpiska :=0;
end;
procedure TDataPrKSpravDOP_DOK.SetIdSpIspitVedomType(const Value: int64);
begin
FIdSpIspitVedomType := Value;
end;
procedure TDataPrKSpravDOP_DOK.SetIdSpPredm(const Value: int64);
begin
FIdSpPredm := Value;
end;
procedure TDataPrKSpravDOP_DOK.SetIsNoRozpiska(const Value: Integer);
begin
FIsNoRozpiska := Value;
end;
procedure TDataPrKSpravDOP_DOK.SetIsOcenka(const Value: Smallint);
begin
FIsOcenka := Value;
end;
procedure TDataPrKSpravDOP_DOK.SetShortNamePredm(const Value: string);
begin
FShortNamePredm := Value;
end;
procedure TDataPrKSpravDOP_DOK.SetShortNameVedomType(const Value: string);
begin
FShortNameVedomType := Value;
end;
procedure TFormPRK_SP_TYPE_DOP_DOK.ActionADDExecute(Sender: TObject);
var
DataPrKSpravAdd :TDataPrKSpravDOP_DOK;
T:TFormPrKSpravEditTYPE_DOP_DOK;
TryAgain :boolean;
begin
TryAgain:=false;
DataPrKSpravAdd:=TDataPrKSpravDOP_DOK.Create(StrToInt(DataSetPrKSprav.FieldValues['KOD_MAX']),
StrToInt(DataSetPrKSprav.FieldValues['NPP_MAX']));
if DataSetPrKSprav.FieldValues[ID_NAME]<>Null
then DataPrKSpravAdd.Id:=StrToInt64(DataSetPrKSprav.FieldValues[ID_NAME]);
T := TFormPrKSpravEditTYPE_DOP_DOK.Create(self,DataPrKSpravAdd,AllDataKods,AllDataNpps);
T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_Add[IndexLanguage];
if ShowNpp=true then
begin
T.cxLabelNPP.Visible :=true;
T.cxTextEditNPP.Visible :=true;
end;
if T.ShowModal=MrOk then
begin
StoredProcPrKSprav.Transaction.StartTransaction;
StoredProcPrKSprav.StoredProcName:=StoredProcAddName;
StoredProcPrKSprav.Prepare;
StoredProcPrKSprav.ParamByName('NAME').AsString :=DataPrKSpravAdd.Name;
StoredProcPrKSprav.ParamByName('SHORT_NAME').AsString :=DataPrKSpravAdd.ShortName;
StoredProcPrKSprav.ParamByName('KOD').AsInteger :=DataPrKSpravAdd.Kod;
StoredProcPrKSprav.ParamByName('NPP').AsInteger :=DataPrKSpravAdd.Npp;
if DataPrKSpravAdd.IsOcenka=1
then begin
StoredProcPrKSprav.ParamByName('ID_SP_ISPIT_VEDOM_TYPE').AsInt64 :=DataPrKSpravAdd.IdSpIspitVedomType;
StoredProcPrKSprav.ParamByName('ID_SP_PREDM').AsInt64 :=DataPrKSpravAdd.IdSpPredm;
end
else begin
StoredProcPrKSprav.ParamByName('ID_SP_ISPIT_VEDOM_TYPE').AsInt64 :=-1;
StoredProcPrKSprav.ParamByName('ID_SP_PREDM').AsInt64 :=-1;
end;
StoredProcPrKSprav.ParamByName('ID_SP_PREDM').AsInt64 :=DataPrKSpravAdd.IdSpPredm;
StoredProcPrKSprav.ParamByName('IS_OCENKA').AsShort :=DataPrKSpravAdd.IsOcenka;
StoredProcPrKSprav.ParamByName('IS_NO_ROZPISKA').AsInteger :=DataPrKSpravAdd.IsNoRozpiska;
try
StoredProcPrKSprav.ExecProc;
StoredProcPrKSprav.Transaction.commit;
DataPrKSpravAdd.Id:=StoredProcPrKSprav.FieldByName('ID_OUT').AsInt64;
except on e: Exception do
begin
MessageBox(Handle,Pchar(nMsgErrorTransaction[IndexLanguage]+chr(13)+
nMsgTryAgain[IndexLanguage]+nMsgOr[IndexLanguage]+nMsgToAdmin[IndexLanguage]+chr(13)+
e.Message),Pchar(nMsgBoxTitle[IndexLanguage]),MB_OK or MB_ICONWARNING);
StoredProcPrKSprav.Transaction.Rollback;
TryAgain:=true;
end;
end;
end;
T.Free;
T:=nil;
Obnovit(DataPrKSpravAdd.Id);
DataPrKSpravAdd.Free;
DataPrKSpravAdd:=nil;
if TryAgain=true
then ActionADDExecute(Sender);
end;
procedure TFormPRK_SP_TYPE_DOP_DOK.ActionChangeExecute(Sender: TObject);
var
DataPrKSpravChange :TDataPrKSpravDOP_DOK;
T:TFormPrKSpravEditTYPE_DOP_DOK;
TryAgain :boolean;
begin
TryAgain:=false;
if DataSetPrKSprav.FieldValues[ID_NAME]<>Null then
begin
DataPrKSpravChange:=TDataPrKSpravDOP_DOK.Create(StrToInt64(DataSetPrKSprav.FieldValues[ID_NAME]),
DataSetPrKSprav.FieldValues['NAME'],
DataSetPrKSprav.FieldValues['SHORT_NAME'],
StrToInt(DataSetPrKSprav.FieldValues['KOD']),
StrToInt(DataSetPrKSprav.FieldValues['NPP']),
StrToInt64(DataSetPrKSprav.FieldValues['ID_SP_ISPIT_VEDOM_TYPE']),
DataSetPrKSprav.FieldValues['SHORT_NAME_VEDOM_TYPE'],
StrToInt64(DataSetPrKSprav.FieldValues['ID_SP_PREDM']),
DataSetPrKSprav.FieldValues['SHORT_NAME_PREDM'],
StrToInt(DataSetPrKSprav.FieldValues['IS_OCENKA']),
StrToInt(DataSetPrKSprav.FieldValues['IS_NO_ROZPISKA']));
T:=TFormPrKSpravEditTYPE_DOP_DOK.Create(self,DataPrKSpravChange,AllDataKods,AllDataNpps);
T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_Change[IndexLanguage];
if ShowNpp=true then
begin
T.cxLabelNPP.Visible :=true;
T.cxTextEditNPP.Visible :=true;
end;
if T.ShowModal=MrOk then
begin
StoredProcPrKSprav.Transaction.StartTransaction;
StoredProcPrKSprav.StoredProcName:=StoredProcChangeName;
StoredProcPrKSprav.Prepare;
StoredProcPrKSprav.ParamByName(ID_NAME).AsInt64 :=DataPrKSpravChange.Id;
StoredProcPrKSprav.ParamByName('NAME').AsString :=DataPrKSpravChange.Name;
StoredProcPrKSprav.ParamByName('SHORT_NAME').AsString :=DataPrKSpravChange.ShortName;
StoredProcPrKSprav.ParamByName('KOD').AsInteger :=DataPrKSpravChange.Kod;
StoredProcPrKSprav.ParamByName('NPP').AsInteger :=DataPrKSpravChange.Npp;
if DataPrKSpravChange.IsOcenka=1
then begin
StoredProcPrKSprav.ParamByName('ID_SP_ISPIT_VEDOM_TYPE').AsInt64 :=DataPrKSpravChange.IdSpIspitVedomType;
StoredProcPrKSprav.ParamByName('ID_SP_PREDM').AsInt64 :=DataPrKSpravChange.IdSpPredm;
end
else begin
StoredProcPrKSprav.ParamByName('ID_SP_ISPIT_VEDOM_TYPE').AsInt64 :=-1;
StoredProcPrKSprav.ParamByName('ID_SP_PREDM').AsInt64 :=-1;
end;
StoredProcPrKSprav.ParamByName('ID_SP_PREDM').AsInt64 :=DataPrKSpravChange.IdSpPredm;
StoredProcPrKSprav.ParamByName('IS_OCENKA').AsShort :=DataPrKSpravChange.IsOcenka;
StoredProcPrKSprav.ParamByName('IS_NO_ROZPISKA').AsInteger :=DataPrKSpravChange.IsNoRozpiska;
try
StoredProcPrKSprav.ExecProc;
StoredProcPrKSprav.Transaction.Commit;
except on e: Exception do
begin
MessageBox(Handle,Pchar(nMsgErrorTransaction[IndexLanguage]+chr(13)+
nMsgTryAgain[IndexLanguage]+nMsgOr[IndexLanguage]+nMsgToAdmin[IndexLanguage]+chr(13)+
e.Message),Pchar(nMsgBoxTitle[IndexLanguage]),MB_OK or MB_ICONWARNING);
StoredProcPrKSprav.Transaction.Rollback;
TryAgain:=true;
end;
end;
end;
T.Free;
T:=nil;
Obnovit(DataPrKSpravChange.Id);
DataPrKSpravChange.Free;
DataPrKSpravChange:=nil;
end;
if TryAgain=true
then ActionChangeExecute(sender);
end;
procedure TFormPRK_SP_TYPE_DOP_DOK.ActionViewExecute(Sender: TObject);
var
DataPrKSpravView :TDataPrKSpravDOP_DOK;
T:TFormPrKSpravEditTYPE_DOP_DOK;
begin
if DataSetPrKSprav.FieldValues[ID_NAME]<>Null then
begin
DataPrKSpravView:=TDataPrKSpravDOP_DOK.Create(StrToInt64(DataSetPrKSprav.FieldValues[ID_NAME]),
DataSetPrKSprav.FieldValues['NAME'],
DataSetPrKSprav.FieldValues['SHORT_NAME'],
StrToInt(DataSetPrKSprav.FieldValues['KOD']),
StrToInt(DataSetPrKSprav.FieldValues['NPP']),
StrToInt64(DataSetPrKSprav.FieldValues['ID_SP_ISPIT_VEDOM_TYPE']),
DataSetPrKSprav.FieldValues['SHORT_NAME_VEDOM_TYPE'],
StrToInt64(DataSetPrKSprav.FieldValues['ID_SP_PREDM']),
DataSetPrKSprav.FieldValues['SHORT_NAME_PREDM'],
StrToInt(DataSetPrKSprav.FieldValues['IS_OCENKA']),
StrToInt(DataSetPrKSprav.FieldValues['IS_NO_ROZPISKA']));
T:=TFormPrKSpravEditTYPE_DOP_DOK.Create(self,DataPrKSpravView,AllDataKods,AllDataNpps);
if ShowNpp=true then
begin
T.cxLabelNPP.Visible :=true;
T.cxTextEditNPP.Visible :=true;
end;
T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_View[IndexLanguage];
T.cxButtonEditISPIT_VEDOM_TYPE.Properties.ReadOnly :=true;
T.cxButtonEditISPIT_VEDOM_TYPE.Properties.Buttons[0].Visible:=false;
T.cxButtonEditPredm.Properties.ReadOnly :=true;
T.cxButtonEditPredm.Properties.Buttons[0].Visible :=false;
T.cxTextEditName.Properties.ReadOnly :=true;
T.cxTextEditShortName.Properties.ReadOnly :=true;
T.cxTextEditKod.Properties.ReadOnly :=true;
T.cxTextEditNpp.Properties.ReadOnly :=true;
T.cxCheckBoxIsOCENKA.Properties.ReadOnly :=true;
T.cxCheckBoxIsNoRozpiska.Properties.ReadOnly :=true;
T.cxButtonEditISPIT_VEDOM_TYPE.Style.Color :=TextViewColor;
T.cxButtonEditPredm.Style.Color :=TextViewColor;
T.cxTextEditName.Style.Color :=TextViewColor;
T.cxTextEditShortName.Style.Color :=TextViewColor;
T.cxTextEditKod.Style.Color :=TextViewColor;
T.cxTextEditNpp.Style.Color :=TextViewColor;
T.cxCheckBoxIsOCENKA.Style.Color :=TextViewColor;
T.cxCheckBoxIsNoRozpiska.Style.Color :=TextViewColor;
T.ShowModal;
T.Free;
T:=nil;
DataPrKSpravView.Free;
DataPrKSpravView:=nil;
end;
end;
procedure TFormPRK_SP_TYPE_DOP_DOK.ActionVibratExecute(Sender: TObject);
begin
if DataSetPrKSprav.FieldValues[ID_NAME]<>NULL then
begin
if DataSetPrKSprav.FieldValues[ID_NAME]=-1 then exit;
FillArrayFromDataSet(ParamSprav['Output'],DataSetPrKSprav);
end;
inherited;
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit fFileCompare;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ActnList, Registry, uCommon, fFileCompareSettings,
frFileCompareFileChoice, uMultiLanguage;
type
TfmFileCompare = class(TForm)
alFileCompare: TActionList;
acCompare: TAction;
acSettings: TAction;
acCancel: TAction;
Button1: TButton;
Button2: TButton;
Button3: TButton;
frameFile1: TframeFileCompareFileChoice;
frameFile2: TframeFileCompareFileChoice;
procedure acCompareExecute(Sender: TObject);
procedure acSettingsExecute(Sender: TObject);
procedure acCancelExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
fSettings: TFileCompareSettings;
procedure SettingsToForm;
procedure FormToSettings;
public
property Settings: TFileCompareSettings read fSettings;
end;
implementation
{$R *.dfm}
uses
fMain, fEditor, fFileCompareResults;
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmFileCompare.SettingsToForm;
begin
with fSettings do begin
frameFile1.FileSelection:=File1Selection;
frameFile1.EditingFileName:=File1EditingFileName;
frameFile1.FileFromDiskName:=File1FromDiskFileName;
frameFile2.FileSelection:=File2Selection;
frameFile2.EditingFileName:=File2EditingFileName;
frameFile2.FileFromDiskName:=File2FromDiskFileName;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmFileCompare.FormToSettings;
begin
with fSettings do begin
File1Selection:=frameFile1.FileSelection;
File1EditingFileName:=frameFile1.EditingFileName;
File1FromDiskFileName:=frameFile1.FileFromDiskName;
File2Selection:=frameFile2.FileSelection;
File2EditingFileName:=frameFile2.EditingFileName;
File2FromDiskFileName:=frameFile2.FileFromDiskName;
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Actions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmFileCompare.acCompareExecute(Sender: TObject);
begin
FormToSettings;
if not Assigned(fmFileCompareResults) then begin
fmFileCompareResults:=TfmFileCompareResults.Create(fmMain);
end;
fmFileCompareResults.Show;
fmFileCompareResults.File1Info:=frameFile1.CreateFileInfo;
fmFileCompareResults.File2Info:=frameFile2.CreateFileInfo;
fmFileCompareResults.Execute(fSettings);
end;
//------------------------------------------------------------------------------------------
procedure TfmFileCompare.acSettingsExecute(Sender: TObject);
begin
with TfmFileCompareSettings.Create(SELF, fSettings) do
try
ShowModal;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmFileCompare.acCancelExecute(Sender: TObject);
begin
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Form events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmFileCompare.FormCreate(Sender: TObject);
begin
mlApplyLanguageToForm(SELF, Name);
fSettings:=TFileCompareSettings.Create;
SettingsToForm;
end;
//------------------------------------------------------------------------------------------
procedure TfmFileCompare.FormDestroy(Sender: TObject);
begin
fSettings.Free;
end;
//------------------------------------------------------------------------------------------
end.
|
unit fruDateTimeFilter;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.ComCtrls,
dxCore, cxDateUtils, dxSkinsCore, dxSkinOffice2013White, cxSpinEdit,
cxTimeEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar,
System.Actions, Vcl.ActnList, cxCheckBox, Vcl.Menus, Vcl.StdCtrls, cxButtons,
Vcl.ImgList, dxBevel, Vcl.ExtCtrls, App.Params, Registry;
type
TfrDateTimeFilter = class(TFrame)
edFromDate: TcxDateEdit;
edTillDate: TcxDateEdit;
edFromTime: TcxTimeEdit;
edTillTime: TcxTimeEdit;
ActionList: TActionList;
acShowTime: TAction;
ImageList: TcxImageList;
buFilterOptions: TcxButton;
poDateMenu: TPopupMenu;
miShowTime: TMenuItem;
buClearFromDate: TcxButton;
buClearTillDate: TcxButton;
acClearFromDate: TAction;
acClearTillDate: TAction;
paTop: TPanel;
paMain: TPanel;
miLogicDate: TMenuItem;
miClearFilter: TMenuItem;
N3: TMenuItem;
acClearFilter: TAction;
acRefresh: TAction;
mRefresh: TMenuItem;
acLogicDate: TAction;
laLogicDate: TLabel;
procedure acShowTimeExecute(Sender: TObject);
procedure acClearFromDateExecute(Sender: TObject);
procedure acClearTillDateExecute(Sender: TObject);
procedure acClearFilterExecute(Sender: TObject);
procedure acRefreshExecute(Sender: TObject);
procedure acLogicDateExecute(Sender: TObject);
procedure edFromDatePropertiesEditValueChanged(Sender: TObject);
procedure edTillDatePropertiesEditValueChanged(Sender: TObject);
procedure edFromTimePropertiesEditValueChanged(Sender: TObject);
procedure edTillTimePropertiesEditValueChanged(Sender: TObject);
private
FOnRefresh: TNotifyEvent;
FShowTime: TRegBooleanParam;
FLogicDate: TRegBooleanParam;
FOnlyDate: Boolean;
FForMSSql: Boolean;
procedure DoRefresh(); dynamic;
procedure Loaded; override;
procedure SetOnlyDate(const Value: Boolean);
function GetWithTime: Boolean;
function GetFromDate: Variant;
function GetTillDate: Variant;
function GetFromTime: Variant;
function GetTillTime: Variant;
procedure Load();
procedure Save();
protected
function GetFieldName(const FieldName, LogicField: String): String;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy(); override;
function GetSqlFilter(const FieldName, LogicField: String): String; virtual;
procedure Refresh();
property OnlyDate: Boolean read FOnlyDate write SetOnlyDate;
property WithTime: Boolean read GetWithTime;
property FromDate: Variant read GetFromDate;
property FromTime: Variant read GetFromTime;
property TillDate: Variant read GetTillDate;
property TillTime: Variant read GetTillTime;
property OnRefresh: TNotifyEvent read FOnRefresh write FOnRefresh;
end;
implementation
{$R *.dfm}
uses
uServiceUtils;
constructor TfrDateTimeFilter.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
FOnlyDate := False;
FForMSSql := False;
FShowTime := TRegBooleanParam.Create('ShowTime', aOwner.ClassName + '\' + Self.Name, True);
FLogicDate := TRegBooleanParam.Create('LogicDate', aOwner.ClassName + '\' + Self.Name, False);
Load;
end;
destructor TfrDateTimeFilter.Destroy();
begin
Save;
FShowTime.Value := miShowTime.Checked;
FLogicDate.Value := miLogicDate.Checked;
FreeWithCheckExist(FShowTime);
FreeWithCheckExist(FLogicDate);
inherited;
end;
procedure TfrDateTimeFilter.DoRefresh;
begin
if Assigned(FOnRefresh) then
FOnRefresh(Self);
end;
procedure TfrDateTimeFilter.Load;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey:= HKEY_CURRENT_USER;
FShowTime.Load(Reg);
FLogicDate.Load(Reg);
finally
Reg.Free;
end;
end;
procedure TfrDateTimeFilter.Save;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey:= HKEY_CURRENT_USER;
FShowTime.Save(Reg);
FLogicDate.Save(Reg);
finally
Reg.Free;
end;
end;
procedure TfrDateTimeFilter.Loaded;
begin
inherited;
edFromDate.EditValue := Null;
edTillDate.EditValue := Null;
Refresh;
end;
procedure TfrDateTimeFilter.acClearFilterExecute(Sender: TObject);
begin
acClearFromDate.Execute;
acClearTillDate.Execute;
end;
procedure TfrDateTimeFilter.acClearFromDateExecute(Sender: TObject);
begin
edFromDate.Clear;
edFromTime.Clear;
end;
procedure TfrDateTimeFilter.acClearTillDateExecute(Sender: TObject);
begin
edTillDate.Clear;
edTillTime.Clear;
end;
procedure TfrDateTimeFilter.acLogicDateExecute(Sender: TObject);
begin
FLogicDate.Value := not FLogicDate.Value;
{фильтрация по логической дате}
if FLogicDate.Value then
FShowTime.Value := False; //время не учитывается
Refresh;
end;
procedure TfrDateTimeFilter.acRefreshExecute(Sender: TObject);
begin
DoRefresh;
end;
procedure TfrDateTimeFilter.acShowTimeExecute(Sender: TObject);
begin
FShowTime.Value := not FShowTime.Value;
Refresh;
end;
procedure TfrDateTimeFilter.edFromDatePropertiesEditValueChanged(Sender: TObject);
begin
DoRefresh;
end;
procedure TfrDateTimeFilter.edFromTimePropertiesEditValueChanged(Sender: TObject);
begin
DoRefresh;
end;
procedure TfrDateTimeFilter.edTillDatePropertiesEditValueChanged(Sender: TObject);
begin
DoRefresh;
end;
procedure TfrDateTimeFilter.edTillTimePropertiesEditValueChanged(Sender: TObject);
begin
DoRefresh;
end;
function TfrDateTimeFilter.GetFieldName(const FieldName, LogicField: String): String;
begin
if miLogicDate.Checked then
Result := LogicField
else
Result := FieldName;
end;
function TfrDateTimeFilter.GetSqlFilter(const FieldName, LogicField: String): String;
function GetFieldFilterPart(): String;
begin
Result := GetFieldName(FieldName, LogicField);
if not WithTime then
Result:= ' CAST(' + Result + ' as DATE) '; //отбрасываем время
end;
function GetValueFilterPart(const Value: TDateTime): String;
begin
if WithTime then
Result := ' CAST(''' + FormatDateTime('yyyy-mm-dd hh:nn:ss', Value) + ''' as TIMESTAMP) '
else
Result := ' CAST(''' + FormatDateTime('yyyy-mm-dd', Value) + ''' as DATE) ';
end;
begin
Result := '';
if not (edFromDate.EditingValue = Null) then
Result := Result + '(' + GetFieldFilterPart() + ' >= ' +
GetValueFilterPart(edFromDate.EditingValue + edFromTime.EditingValue) + ')';
if not (edTillDate.EditingValue = Null) then
begin
if Result <> '' then
Result := Result + ' AND ';
Result := Result + '(' + GetFieldFilterPart() + ' <= ' +
GetValueFilterPart(edTillDate.EditingValue + edTillTime.EditingValue) + ')';
end;
if Result <> '' then
Result := ' AND (' + Result + ') ';
end;
function TfrDateTimeFilter.GetWithTime: Boolean;
begin
Result := FShowTime.Value and not FOnlyDate;
end;
function TfrDateTimeFilter.GetFromDate: Variant;
begin
Result := edFromDate.EditingValue;
end;
function TfrDateTimeFilter.GetFromTime: Variant;
begin
Result := edFromTime.EditingValue;
end;
function TfrDateTimeFilter.GetTillDate: Variant;
begin
Result := edTillDate.EditingValue;
end;
function TfrDateTimeFilter.GetTillTime: Variant;
begin
Result := edTillTime.EditingValue;
end;
procedure TfrDateTimeFilter.SetOnlyDate(const Value: Boolean);
begin
FOnlyDate := Value;
Refresh;
end;
procedure TfrDateTimeFilter.Refresh;
begin
miShowTime.Checked := WithTime;
miShowTime.Enabled := not FLogicDate.Value;
miShowTime.Visible := not FOnlyDate;
miLogicDate.Checked := FLogicDate.Value;
laLogicDate.Visible := FLogicDate.Value;
if FShowTime.Value then
begin
edFromTime.Visible := True;
edTillTime.Visible := True;
Self.Width := 332;
end
else
begin
edTillTime.Clear;
edFromTime.Clear;
edFromTime.Visible := False;
edTillTime.Visible := False;
Self.Width := 252;
end;
end;
end.
|
unit RazProbem;
interface
uses Math, StdRut, SysUtils, RazProbemBase ;
type
TDMIList = array[1..MxDMIList] of TDMI ; // seznam DMIjev osebe, ki so prosti/zasedeni dolocenega Dne
TDMIListIdx = 0..MxDMIList ; // index v TDMIList
TOsebNaDMIIdx0 = 0..MxOsebNaDMI ;
TDMIValsEl = record // mozne vrednosti DMIja
nVrsteVz: array [TVrstaVzorca] of smallint ; // stevila moznih DMIjev po grupah izmen(dopV, popV, nocV)
nVals: TDMIListIdx ; // stevilo moznih razlicnih vrednosti DMIja
vals: TDMIList ; // seznam moznih vrednosti DMIja (DMIji osebe ki so prosti dolocenega Dne)
end ;
TDMIVals = array[TDanIdx, TOsebaIdx] of TDMIValsEl ;
TDMIDanVals = array[TOsebaIdx] of TDMIValsEl ;
TDanVzorecInt = array[1..MxDnevi, 0..MxVrstVzorcev] of smallint ;
TDMIValsOut = array[TDanIdx, TOsebaIdx] of TDMI ;
TRazProblem = class(TRazKriteriji)
private
function DMIValIdx( dmi: TDMI ; var DMIValsEl: TDMIValsEl ) : TDMIListIdx ;
// vrne index DMI v DMIVals[Dan,Oseba]
protected
DMIValsInitial: TDMIVals ; // DMIValsDOInitial[d,o] so mozni DMIji osebe o dne d
public
stSk: array [TDanIdx] of smallint ; // st. neodvisnih skupin oseb
skOseb: array[TDanIdx, 1..MxOseb] of smallint ; // indexi neodvisnih skupin oseb
dmiSk: array [TDanIdx, 1..MxSkupin] of TDMISet ;
constructor Create ;
procedure getOsebeSkupine( d: TDanIdx; sk: smallint; var oList: TOsebeList; var lIdx: TOsebaIdx ) ;
function dmiSkupine( var DMIVals: TDMIVals; d: TDanIdx; sk: smallint ): TDMISet ;
procedure initProblem ;
procedure initDMIVals( var DMIVals: TDMIVals ) ;
procedure povezaneOsebeDne( var DMIVals: TDMIVals; d: TDanIdx ) ;
function stDMIvDP( dmi: TDMI ; dan: TDanIdx ) : TOsebNaDMIIdx0 ;
// st. oseb ki so v DP[dan] razporejene na dmi
function VrstaVzDMI( dmi: TDMI ) : TVrstaVzorca ;
procedure addDMIVal( dmi: TDMI; var DMIValsEl: TDMIValsEl ) ;
// v DMIVals[Dan,Oseba] doda novo vrednost dmi, ter poveca ustrezno st. vzorca
// to naredimo pri inicializaciji, in ko osebo prerazporedimo na drug DMI
procedure delDMIVal( dmi: TDMI ; var DMIValsEl: TDMIValsEl ) ;
// iz DMIVals[Dan,Oseba] zbrise vrednost dmi, ter zmanjsa ustrezno st. vzorca
// to na zacetku pri fiksiranju oseb, in ko vrednost DMIja ni vec mogoca za to osebo
function prostoMedDMI(var posDMIVals: TDMIValsEl): boolean ;
// true ce je 0 med moznimi vrednostmi dmija
function vplivDniKritOsebe(o: TOsebaIdx): TDanIdx ;
// vrne st. zadnjih dni, ki vplivajo na kriterije osebe o (mozni krseni dnevi pred d)
procedure recompKrit(kritIdx: TTipKriterija; d: TDanIdx; o: TOsebaIdx; var DMIVals: TDMIVals) ;
// od dne=1 do d ponovno izracuna kriterij kritIdx osebe o
// rezultat je vrednost kriterija od dnevu d (krsenja v prejsnjih dnevih so ignorirana)
procedure recompAllKrit(d: TDanIdx; o: TOsebaIdx; var DMIVals: TDMIVals) ;
function prihKritOk(d: TDanIdx; o: TOsebaIdx; var DMIVals: TDMIVals): boolean ;
// true ce ima oseba o krsene gotove kriterija v prihodnosti (od d+1) dalje
procedure updateKritSure(curD, d: TDanIdx; o: TOsebaIdx; var posDMIVals: TDMIValsEl) ;
//procedure updateKritSure(d: TDanIdx; o: TOsebaIdx; var posDMIVals: TDMIValsEl) ;
// za vse kriterije i: naredi update kriterija i le ce je gotova spremeba kriterija
function minKritChange(kritIdx: TTipKriterija; d: TDanIdx; o: TOsebaIdx; var posDMIVals: TDMIValsEl): TKritVal ;
procedure kritOkDMIVals(d: TDanIdx; o: TOsebaIdx; var posDMIVals, okDMIVals: TDMIValsEl) ;
// izracuna okDMIVals tako da iz posDMIVals odstrani vse dmi, ki krsijo kriterije osebe o, dne d
function preveriresitev( var DMIVals: TDMIVals) : boolean ;
procedure zapisi( var DMIVals: TDMIVals );
procedure preberi( var DMIVals: TDMIVals );
end ; {TRazProblem}
implementation
// *******
// ******* class TRazProblem
// *******
constructor TRazProblem.Create ;
begin
inherited Create ;
end ;
procedure TRazProblem.initProblem ;
var
d, i: smallint ;
begin
initKriteriji ;
if DMIOseb = nil then
MsgHalt( 'DMIOseb ni dolocen', 0, -1, -1 ) ;
initDMIVals( DMIValsInitial ) ;
Dispose( DMIOseb ) ;
for d := 1 to nDni do begin
stSk[d] := 0 ;
for i := 1 to MxSkupin do
dmiSk[d,i] := [] ;
end ;
end ; {TRazProblem.initProblem}
procedure TRazProblem.initDMIVals( var DMIVals: TDMIVals ) ;
var
d: TDanIdx ;
o: TOsebaIdx ;
dmi1: TDMI ;
vv: TVrstaVzorca ;
ki: TTipKriterija ;
dmiListIdx: TDMIListIdx ;
prevKrit: TKritValList ;
stPribitihDMI: array[1..MxDnevi, 1..MxDMI] of byte ; // dodano 13.03.2007
j, dmiIdx: smallint ;
pribitDMI: boolean ; // dodano 28.03.2007
begin
for o := 1 to nOseb do begin
osebe[o].nePribiti := nDni ;
osebe[o].delovni := 0 ;
for d := 1 to nDni do begin
for vv := 0 to MxVrstVzorcev do
DMIVals[d,o].nVrsteVz[vv] := 0 ;
DMIVals[d,o].nVals := 0 ;
end ;
end ;
for d := 1 to nDni do
for dmi1 := 1 to nDMI do
stPribitihDMI[d,dmi1] := 0 ;
for o := 1 to nOseb do with Osebe[o] do begin
for d := 1 to nDni do begin
for dmi1 := 0 to nDMI do begin
if dmi1 in DMIOseb^[d,o] then begin
pribitDMI := (DMIOseb^[d,o] - [dmi1] = []) ;
if pribitDMI or (dmi1 = 0) or (stDMIvDP( dmi1, d) > 0) then // !!! po 28.03.2007:tudi pribite osebe, ki niso v DP, dodamo v DP
addDMIVal( dmi1, DMIVals[d,o] ) ;
if (dmi1 <> 0) and (stDMIvDP( dmi1, d) = 0) then
if not NOMSG then msg( 'initDMIVals: Oseba o'+IntToStr(o)+': DMI '+IntTostr(dmi1)+' ni v del.planu za d'+IntToStr(d)) ;
// Pazi: problem napr. ce imata o1 in o2 samo dmi1 in dmi2, nimata pa dmi0 in sta to edini osebi na dmi1 in dmi2
// potem nobena ni pribita in dmi1 in dmi2 ne damo v DP, torej resitev ne bo obstajala
if not pribitDMI and (DMIVals[d,o].Vals[1] <> 0) then // dodano 28.03.2007
MsgHalt( 'Nepribita oseba mora imeti vedno tudi dmi0(prosto)', 3, d, o ) ;
// if (DMIVals[d,o].nVals = 1) and (DMIVals[d,o].Vals[1] <> 0) then begin // do 28.3.2007
if pribitDMI and (DMIVals[d,o].Vals[1] <> 0) then begin // !!! po 28.3.2007
stPribitihDMI[d,dmi1] := stPribitihDMI[d,dmi1]+1 ;
if stPribitihDMI[d,dmi1] > stDMIvDP( dmi1, d) then begin // dodaj dmi v DP
msg( 'Oseba '+IntToStr(o)+': prevec pribitih oseb; v DP dodajam dodaten DMI='+IntToStr(dmi1)+' dne '+IntToStr(d) ) ;
// poiscem dmi
dmiIdx := -1 ;
for j := 1 to DP[d].nDMI do
if DP[d].DPDMIList[j] = dmi1 then begin
dmiIdx := j ; break ;
end ;
if dmiIdx > 0 then
DP[d].nOsebList[dmiIdx] := DP[d].nOsebList[dmiIdx] + 1
else begin// vstavi dmi
DP[d].nDMI := DP[d].nDMI + 1 ;
DP[d].DPDMIList[DP[d].nDMI] := dmi1 ;
DP[d].nOsebList[DP[d].nDMI] := 1 ;
end ;
end ;
end ;
end ;
end ; {for dmi}
if BRISIDMIkiKrsKRIT then begin // preverimo ce mozni dmiji ne krsijo kriterijev
for dmiListIdx := 1 to DMIVals[d,o].nVals do begin
if not newKritOK( d, o, DMIVals[d,o].Vals[dmiListIdx] ) then begin
if DMIVals[d,o].nVals > 1 then begin
delDMIVal( DMIVals[d,o].Vals[dmiListIdx], DMIVals[d,o] ) ; // brisemo dmi ki krsi kriterije iz DMIVals
end ;
end ;
end ;
end ;
prevKrit := osebe[o].vKrit ;
for ki := Low(TTipKriterija) to High(TTipKriterija) do
if krit[ki].enabled then
osebe[o].vKrit[ki] := minKritChange( ki, d, o, DMIVals[d,o] ) ;
if not kritOK( o ) then begin
if DOVOLIGotovoKrsKRIT then
msg(' ***** initDMIVals(DOVOLIGotovoKrsKRIT=1): o'+IntToStr(o)+' vsekakor(katerikoli dmi) krsi kriterije dne d'+IntToStr(d))
else
MsgHalt('initDMIVals: o'+IntToStr(o)+' vsekakor(katerikoli dmi) krsi kriterije dne d'+IntToStr(d), 5, d, o) ;
osebe[o].vKrit := prevKrit ;
osebe[o].vKrit[PDanPocitek] := 0 ;
end ; // if preveriDMIpoKriterijih
end ; {for d}
end ;
for o := 1 to nOseb do
for ki := Low(TTipKriterija) to High(TTipKriterija) do
initKritOsebeDan1( ki, o ) ;
// !!! dodano 29.03.2007 preverim ce je za vsak dmi iz DP vsaj ena razpolozljiva oseba
for d := 1 to nDni do begin
for dmi1 := 1 to nDMI do begin
j := stDMIvDP( dmi1, d ) ;
if j > 0 then begin // preverim ce je dovolj razpolozljivih oseb
for o := 1 to nOseb do
if DMIValIdx(dmi1, DMIVals[d,o])<>0 then // razpolozljiva oseba
j := j - 1 ;
if j > 0 then
MsgHalt('Premalo oseb za izvajanje dela dne '+IntToStr(d), 3, d, dmi1) ;
end ;
end ;
end ;
end ; {initDMIVals}
function TRazProblem.stDMIvDP( dmi: TDMI ; dan: TDanIdx ) : TOsebNaDMIIdx0 ;
// st. oseb ki so v DP[dan] razporejene na dmi
var
DPdmiListIdx: 1..MxDelPlanDMI ;
begin
stDMIvDP := 0 ;
if dmi=0 then begin
msg('stDMIvDP: dmi=0' ) ;
stDMIvDP := 1 ;
end ;
for DPdmiListIdx := 1 to DP[dan].nDMI do
if (dmi = DP[dan].DPDMIList[DPdmiListIdx]) then begin
stDMIvDP := DP[dan].nOsebList[DPdmiListIdx] ;
exit ;
end ;
end ; {stDMIvDP}
function TRazProblem.VrstaVzDMI( dmi: TDMI ) : TVrstaVzorca ;
begin
Result := DMIList[dmi].vz ;
end ; {VrstVzorcaDMI}
function TRazProblem.DMIValIdx(dmi: TDMI; var DMIValsEl: TDMIValsEl) : TDMIListIdx ;
// vrne index DMI v DMIValsEl (=DMIVals[Dan,Oseba])
var
i: integer ;
begin
DMIValIdx := 0 ;
for i := 1 to DMIValsEl.nVals do
if DMIValsEl.Vals[i] = dmi then begin
DMIValIdx := i ;
break ;
end ;
end ; {DMIValIdx}
procedure TRazProblem.addDMIVal( dmi: TDMI; var DMIValsEl: TDMIValsEl ) ;
// v DMIValsEl doda novo vrednost dmi, ter poveca ustrezno st. vzorca
// to naredimo pri inicializaciji, in ko osebo prerazporedimo na drug DMI
var
vv: TVrstaVzorca ;
idx: TDMIListIdx ;
begin
idx := DMIValIdx(dmi, DMIValsEl ) ;
with DMIValsEl do begin
if idx > 0 then begin // dmi ze obstaja v DMIValsEl
MsgHalt( 'TRazProblem.addDMIVal: ta dmi ze v DMIVals',0, -1, -1 );
end else begin
if nVals >= MxDMIList then begin
MsgHalt( 'Prevec DMI Vrednosti osebe',4, -1, -1 ) ;
exit ;
end ;
nVals := nVals + 1 ;
Vals[nVals] := dmi ;
vv := VrstaVzDMI(dmi) ;
nVrsteVz[vv] := nVrsteVz[vv] + 1 ;
end ;
end ;
end ; {addDMIVal}
procedure TRazProblem.delDMIVal( dmi: TDMI ; var DMIValsEl: TDMIValsEl ) ;
// iz DMIVals[Dan,Oseba] zbrise vrednost dmi, ter zmanjsa ustrezno st. vzorca
// to na zacetku pri fiksiranju oseb, in ko vrednost DMIja ni vec mogoca za to osebo
var
idx: TDMIListIdx ;
vv: TVrstaVzorca ;
begin
idx := DMIValIdx( dmi, DMIValsEl) ;
if idx = 0 then
MsgHalt( 'Brisanje neobstojecega DMI',0, -1, -1 ) ;
with DMIValsEl do begin
if nVals=1 then
MsgHalt('DelDMIVal: dmi '+IntToStr(dmi)+' ze pribit!',0, -1, -1 ) ;
Vals[idx] := Vals[nVals] ;
nVals := nVals - 1 ;
vv := VrstaVzDMI(dmi) ;
nVrsteVz[vv] := nVrsteVz[vv] - 1 ;
end ;
end ; {delDMIVal}
function TRazProblem.prostoMedDMI(var posDMIVals: TDMIValsEl): boolean ;
// true ce je 0 med moznimi vrednostmi dmija
var
dmiListIdx: TDMIListIdx ;
begin
Result := true ;
for dmiListIdx := 1 to posDMIVals.nVals do
if posDMIVals.Vals[dmiListIdx]=0 then
exit ;
Result := false ;
end ; {prestoMedDMI}
function TRazProblem.dmiSkupine( var DMIVals: TDMIVals; d: TDanIdx; sk: smallint ): TDMISet ;
var
dmi: TDMI ;
o: TOsebaIdx ;
begin
Result := [] ;
for o := 1 to nOseb do begin
if skOseb[d,o] <> sk then
continue ;
for dmi := 0 to nDMI do begin
if (DMIValIdx(dmi, DMIVals[d,o])<>0) then
Result := Result + [dmi] ;
end ;
end ;
end ; {dmiSkupine}
procedure TRazProblem.getOsebeSkupine( d: TDanIdx; sk: smallint; var oList: TOsebeList; var lIdx: TOsebaIdx ) ;
var
j: TOsebaIdx0 ;
o: TOsebaIdx ;
// v oList vrne vse osebe o za katere skOseb[d,o]=sk
begin
j := 0 ;
for o := 1 to nOseb do
if skOseb[d,o] = sk then begin
j := j + 1 ;
oList[j] := o ;
end ;
if j <= 0 then MsgHalt( 'Skupina ne obstaja',0, d, -1 ) ;
lIdx := j ;
end ; {getOsebeSkupine}
procedure TRazProblem.povezaneOsebeDne( var DMIVals: TDMIVals; d: TDanIdx ) ;
// poisce skupine oseb, ki delajo na istih DDMIjih, dne d
var
i, j: smallint ;
dmi: TDMI ;
spr: boolean ;
s: string ;
procedure preimenuj(sk, novaSk: smallint ) ;
var
k: smallint ;
begin
// primenuj sk v novaSk
for k := 1 to nOseb do begin
if skOseb[d,k] = sk then
skOseb[d,k] := novaSk ;
end ;
// preimenuj zadnjo skupino v sk
for k := 1 to nOseb do begin
if skOseb[d,k] = stSk[d] then
skOseb[d,k] := sk ;
end ;
stSk[d] := stSk[d] - 1 ;
end ;
begin
for i := 1 to nOseb do
skOseb[d,i] := i ;
stSk[d] := nOseb ;
// na zacetku je vsaka oseba v svoji skupini, potem zdruzujemo skupine,
// ce sta osebi iz razlicnih skupin na istem ddmi
// dmi=0 ni v nobeni skupini; v skupino ga damo kasneje, ce ga ima lahko vsaj ena oseba
spr := true ;
while spr do begin
spr := false ;
for dmi := 1 to nDMI do begin
i := 1 ;
while i <= nOseb do begin
j := i ;
while j < nOseb do begin
j := j + 1 ;
if skOseb[d,i] = skOseb[d,j] then
continue ;
if (DMIValIdx(dmi, DMIVals[d,i])<>0) and (DMIValIdx(dmi, DMIVals[d,j])<>0) then begin
// obe osebi delata na dmi - zdruzi skupine
spr := true ;
if skOseb[d,i] < skOseb[d,j] then
preimenuj( skOseb[d,j], skOseb[d,i] )
else
preimenuj( skOseb[d,i], skOseb[d,j] ) ;
end ;
end ; // while j
i := i + 1 ;
end ; // while i
end ; // for dmi
end ;
// postavi dmiSk za dan d
for i := 1 to stSk[d] do
dmiSk[d,i] := dmiSkupine( DMIVals, d, i ) ;
end ; {povezaneOsebeDne}
function TRazProblem.vplivDniKritOsebe(o: TOsebaIdx): TDanIdx ;
// vrne st. zadnjih dni, ki vplivajo na kriterije osebe o (mozni krseni dnevi pred d)
begin
Result := MxDnevi ;
if kritOKIgnorePocitek( o ) then
Result := 1
else begin
if kritOKIgnoreTeden( o ) then
Result := 6 ;
end ;
end ; {vplivDniKritOsebe}
procedure TRazProblem.recompAllKrit(d: TDanIdx; o: TOsebaIdx; var DMIVals: TDMIVals) ;
// od dne=1 do d ponovno izracuna kriterije osebe o
var
i: TTipKriterija ;
begin
for i := Low(TTipKriterija) to High(TTipKriterija) do
if krit[i].enabled then
recompKrit( i, d, o, DMIVals ) ;
end ; {recompAllKrit}
procedure TRazProblem.recompKrit(kritIdx: TTipKriterija; d: TDanIdx; o: TOsebaIdx; var DMIVals: TDMIVals) ;
// od dne=1 do d ponovno izracuna kriterij kritIdx osebe o
// rezultat je vrednost kriterija od dnevu d (krsenja v prejsnjih dnevih so ignorirana)
var
pd, ds: smallint ;
begin
initKritOsebeDan1(kritIdx, o ) ;
case kritIdx of
PDanPocitek: ds := d-1 ;
PZapUrTedenMx, PZapDniTedenMx: ds := d-6 ;
else
ds := 1 ;
end ;
for pd:=MaxInt( 1, ds ) to d do begin
// popravljeno 29.2.2007, napaka pri P12, zdaj dovoljujem da ima iseba o dne d vec moznih dmi
if DMIVals[pd,o].nVals = 1 then
osebe[o].vKrit[kritIdx] := newVal( kritIdx, pd, o, DMIVals[pd,o].Vals[1] )
else begin
if pd < d then
MsgHalt( 'recomKrit: dmiji za prejsnje dni morajo biti pribiti',0, pd, -1 ) ;
end ;
end ;
end ; {recompKrit}
function TRazProblem.prihKritOk(d: TDanIdx; o: TOsebaIdx; var DMIVals: TDMIVals): boolean ;
// true ce ima oseba o krsene gotove kriterija v prihodnosti (od d+1) dalje
var
tmpvKrit: TKritValList ; // vrednosti kriterijev za osebo
d1: TDanIdx ;
begin
Result := true ;
tmpvKrit := osebe[o].vKrit ;
d1 := d ;
while d1 < nDni do begin
d1 := d1+1 ;
updateKritSure(d, d1, o, DMIVals[d1, o]) ;
if not kritOK(o) then begin // nek kriterij prihodnjega dne krsen
Result := false ; break ;
end ;
end ;
osebe[o].vKrit := tmpvKrit ; // vrnem stare kriterije
end ; {prihKritOK}
procedure TRazProblem.updateKritSure(curD, d: TDanIdx; o: TOsebaIdx; var posDMIVals: TDMIValsEl) ;
// za vse kriterije i: naredi update kriterija i le ce je gotova spremeba kriterija, zacne z dnem d=curD+1
var
i: TTipKriterija ;
begin
for i := Low(TTipKriterija) to High(TTipKriterija) do begin
if (i in [PZapUrTedenMx,PZapDniTedenMx]) and (d - curD > 6) then // ta pogoj je logicno pravilen
continue ; // samo za prihodnjih 6 dni
if (i = PDanPocitek) and (d - curD > 1) then continue ; // samo za prihodnji dan
if krit[i].enabled then
osebe[o].vKrit[i] := minKritChange( i, d, o, posDMIVals ) ;
end ;
end ; {updateKritSure}
function TRazProblem.minKritChange(kritIdx: TTipKriterija; d: TDanIdx; o: TOsebaIdx; var posDMIVals: TDMIValsEl): TKritVal ;
// vrne minimalno vrednost kriterija, ce dmi pribijemo na neko vrednost iz posDMIVals
var
dmiListIdx: TDMIListIdx ;
dmi: TDMI ;
v, v1, minV, minV1: TKritVal ;
begin
if prostoMedDMI(posDMIVals) then begin // dmi=0 (prosto) da vedno min.vrednost kriterija
Result := newVal( kritIdx, d, o, 0 ) ;
exit ;
end ;
if krit[kritIdx].dmiIgnore then begin
Result := newVal( kritIdx, d, o, posDMIVals.Vals[1] ) ;
exit ;
end ;
minV1 := High(TKritVal) ; minV := High(TKritVal) ;
for dmiListIdx := 1 to posDMIVals.nVals do begin
dmi := posDMIVals.Vals[dmiListIdx] ;
v := newVal( kritIdx, d, o, dmi ) ;
if kritIdx = PVkdMesecMx then
v1 := VkdMesecValToVkdCount(v)
else v1 := v ;
if v1 < minV1 then begin
minV1 := v1 ; minV := v ;
end ;
end ;
Result := minV ;
end ; {minKritChange}
procedure TRazProblem.kritOkDMIVals(d: TDanIdx; o: TOsebaIdx; var posDMIVals, okDMIVals: TDMIValsEl) ;
// izracuna okDMIVals tako da iz posDMIVals odstrani vse dmi, ki krsijo kriterije osebe o, dne d
var
dmiListIdx: TDMIListIdx ;
dmi: TDMI ;
vv: TVrstaVzorca ;
begin
for vv := 0 to MxVrstVzorcev do
okDMIVals.nVrsteVz[vv] := 0 ;
okDMIVals.nVals := 0 ;
for dmiListIdx := 1 to posDMIVals.nVals do begin
dmi := posDMIVals.Vals[dmiListIdx] ;
if newKritOK( d, o, dmi ) then
addDMIVal( dmi, okDMIVals ) ;
// else msg('dmi val not ok' ) ;
end ;
end ; {kritOkDMIVals}
function TRazProblem.preveriresitev( var DMIVals: TDMIVals ): boolean ;
var
o: TOsebaIdx;
d: TDanIdx ;
dmi: TDMI ;
i, kkFirst, k: integer ;
ik: TTipKriterija ;
vv: TVrstaVzorca ;
st: array[TVrstaVzorca] of smallint ;
sv: array[TVrstaVzorca] of smallint ;
s: string ;
oList: TOsebeList ;
mxKrit: TKritValList ;
prevKrit, osMxKrit: array[1..MxOseb] of TKritValList ;
kk: boolean ;
nKrsenih, nKrsInc: integer ;
v: TkritVal ;
vrstadne: TTipDneva ;
begin
// Prenosi se pri izracunu vrednosti kriterijev ne upostevajo
Result := true ;
for i := 1 to nOseb do
oList[i] := i ;
for d := 1 to nDni do begin
for dmi := 1 to nDMI do begin
i := stDMIvDP(dmi, d) ;
for o := 1 to nOseb do begin
if DMIVals[d,o].Vals[1] = dmi then
i := i - 1 ;
end ;
if i <> 0 then begin
MsgHalt( 'Preveri resitev: NAPAKA: d'+IntToStr(d)+' dmi= '+IntToStr(dmi),0, d, -1 ) ;
Result := false ;
end ;
end ;
end ;
// izpisi statistike
initKriteriji ;
nKrsenih := 0 ; // steje dni, ko so kriteriji krseni
nKrsInc := 0 ; // steje dni, ko so kriteriji krseni in hkrati povecani; steje vse krsene kriterije za vse osebe
for ik := Low(TTipKriterija) to High(TTipKriterija) do begin
mxKrit[ik] := 0 ;
for o := 1 to nOseb do begin
prevKrit[o,ik] := 0 ;
osMxKrit[o, ik] := 0 ;
end ;
end ;
for vv := 0 to MxVrstVzorcev do
sv[vv] := 0 ;
for o := 1 to nOseb do begin
for vv := 0 to MxVrstVzorcev do
st[vv] := 0 ;
kk := false ; kkFirst := 0 ;
for d := 1 to nDni do begin
if DMIVals[d,o].nVals <> 1 then begin
MsgHalt( 'DMIVals ni Pribit: d='+IntToStr(d)+' o='+IntToStr(o),0, d, o ) ;
Result := false ;
exit ;
end ;
prevKrit[o] := osebe[o].vKrit ;
updateKrit(d, o, DMIVals[d,o].Vals[1]) ;
for ik := Low(TTipKriterija) to High(TTipKriterija) do begin
if ik = PVkdMesecMx then
v := VkdMesecValToVkdCount(osebe[o].vKrit[ik])
else v := osebe[o].vKrit[ik] ;
mxKrit[ik] := MaxInt(mxKrit[ik], v) ;
osMxKrit[o,ik] := MaxInt(osMxKrit[o,ik], v) ;
end ;
if not kritOK(o) then begin // kriteriji krseni
nKrsenih := nKrsenih + 1 ;
kk := true ;
if kkFirst = 0 then kkFirst := d ;
for ik := Low(TTipKriterija) to High(TTipKriterija) do begin
if not valOK( osebe[o].vKrit[ik], ik ) then begin
if (ik <> PVkdMesecMx) and (prevKrit[o,ik] < osebe[o].vKrit[ik]) then
nKrsInc := nKrsInc + 1 ; // dodatna krsitev kriterija
if (ik = PVkdMesecMx) and (VkdMesecValToVkdCount(prevKrit[o,ik]) < VkdMesecValToVkdCount(osebe[o].vKrit[ik])) then
nKrsInc := nKrsInc + 1 ; // dodatna krsitev kriterija
end ;
end ;
end ;
vv := VrstaVzDMI(DMIVals[d,o].Vals[1]) ;
st[vv] := st[vv] + 1 ;
sv[vv] := sv[vv] + 1 ;
end ;
s := 'o'+IntToStr(o)+':' ;
if o < 10 then
s := s + ' ' ;
// izpisi se vzorce za vse osebe
vrstadne := prviDanMeseca ;
for d := 1 to nDni do begin
vv := VrstaVzDMI(DMIVals[d,o].Vals[1]) ;
s := s + IntToStr(vv) ;
if vrstadne = ned then begin
vrstadne := pon ;
s := s + ' ' ;
end else
vrstadne := Succ(vrstadne) ;
end ;
s := s + ' N='+IntToStr(st[3]) + ' P='+IntToStr(st[0])+' ' ;
if st[0] < 10 then
s := s +' ' ;
// izpise se kriterije
//s := s + ' k:' ;
for ik := Low(TTipKriterija) to High(TTipKriterija) do begin
k := osMxKrit[o,ik] ;
if ik in [PDanPocitek, PZapUrTedenMx, PUrMesecMx] then // spremeni minute v ure
s := s + ' k'+IntToStr(Ord(ik))+'='+IntToStr(round(k/UraMinut))
else
s := s + ' k'+IntToStr(Ord(ik))+'='+IntToStr(k) ;
if (k >= 0) and (k < 10) then
s := s + ' ' ;
if (k >= 0) and (k < 100) then
s := s + ' ' ;
end ;
s := s + ' *o'+intToStr(o) ;
if kk then // kriteriji krseni
s := s + ' -d'+IntToStr(kkFirst) ;
msg( s ) ;
end ; // for o := 1 to nOseb do
// izpisi vzorce zadnjega dne oseb
s := '=== ' ;
for vv := 0 to MxVrstVzorcev do begin
s := s + ' v'+IntToStr(vv)+'='+IntToStr(sv[vv]) ;
if sv[vv] < 10 then
s := s + ' ' ;
end ;
//s := s+ ' =skup.vz.; mx.krit=' ;
s := s+ ' === KrD='+IntToStr(nKrsenih)+' ' ;
for ik := Low(TTipKriterija) to High(TTipKriterija) do begin
if ik in [PDanPocitek, PZapUrTedenMx, PUrMesecMx] then // spremeni minute v ure
s := s + ' k'+IntToStr(Ord(ik))+'='+IntToStr(round(mxKrit[ik]/UraMinut))
else
s := s + ' k'+IntToStr(Ord(ik))+'='+IntToStr(mxKrit[ik]) ;
end ;
//msg( s+ ' KrD='+IntToStr(nKrsenih)+' E='+IntToStr(nKrsInc) ) ;
msg( s+ ' kK='+IntToStr(nKrsInc) ) ;
if Result then
msg( 'Resitev OK' ) ;
end ; {preveriResitev}
procedure TRazProblem.zapisi( var DMIVals: TDMIVals );
// TDMIValsOut = array[TDanIdx, TOsebaIdx] of TDMI ;
var
f: file of TDMIValsOut ;
d: TDanIdx ;
o: TOsebaIdx ;
DMIValsOut: TDMIValsOut ;
begin
msg( 'Zapisujem zadnjo resitev na '+DMIValsFile ) ;
for d := 1 to MxDnevi do
for o := 1 to MxOseb do
DMIValsOut[d,o] := DMIVals[d,o].Vals[1] ;
assign(f, DMIValsFile ) ;
rewrite(f) ;
write(f, DMIValsOut ) ;
close( f ) ;
end ;
procedure TRazProblem.preberi( var DMIVals: TDMIVals );
// TDMIValsOut = array[TDanIdx, TOsebaIdx] of TDMI ;
var
s: string ;
f: file of TDMIValsOut ;
d: TDanIdx ;
o: TOsebaIdx ;
DMIValsOut: TDMIValsOut ;
begin
initProblem ;
s := DMIValsFile ;
msg( 'Berem DMIValsOut z '+s ) ;
assign(f, s ) ;
reset(f) ;
read(f, DMIValsOut ) ;
close( f ) ;
for d := 1 to MxDnevi do
for o := 1 to MxOseb do begin
DMIVals[d,o].nVals := 1 ;
DMIVals[d,o].Vals[1] := DMIValsOut[d,o] ;
end ;
end ;
end.
|
unit Config;
interface
uses BattleField, Geometry, StaticConfig, Types, Lists;
const
NEWLINE = chr(10);
type
ErrorCode = record
code: (OK, FILE_ERROR, BFIELD_OVERFLOW, PARSE_ERROR, INCOMPL_BFIELD, INCOMPL_PAIR, INVALID_KEY, MISSING_KEY);
msg: ansistring;
end;
ConfigStruct = record
bfield_file: ansistring;
{ How many times stronger than normal terrain the forts are }
fort_modifier: double;
{ Maximum shot force }
initial_hp: double;
max_force: double;
max_wind: double;
fort_file: array [1..2] of ansistring;
{ Positions of forts' origins relative to battlefield }
fort_pos: array [1..2] of IntVector;
{ Players colors and names }
name: array[1..2] of ansistring;
color: array[1..2] of shortint;
equipment: Equip;
end;
function parse_bfield_dimensions(var field_str: ansistring; var w, h: integer; var nextpos: integer) : ErrorCode;
function parse_bfield_dimensions(var field_str: ansistring; var w, h: integer) : ErrorCode;
function parse_bfield_string(var field: BField; origin: IntVector; var field_str: ansistring; var cannon, king: IntVector; modifier: double; owner: integer; initial_king_hp: double) : ErrorCode;
function parse_bfield_string(var field: BField; origin: IntVector; var field_str: ansistring; modifier: double; owner: integer; initial_king_hp: double) : ErrorCode;
function read_file_to_string(filename: ansistring; var ostr: ansistring) : ErrorCode;
function parse_game_string(var options: ansistring; var config: ConfigStruct) : ErrorCode;
implementation
uses SysUtils, strutils;
{ Auxiliary function used by parse_num }
function numeric(c: char) : boolean;
begin
numeric := ((ord(c) >= ord('0')) and (ord(c) <= ord('9'))) or (c = '-');
end;
function is_whitespace(c: char) : boolean;
begin
is_whitespace := c in [' ', chr(9), NEWLINE, chr(13)];
end;
{ parses a number in string from position l[s], leaves the number in num,
returns the position of the first non-digit }
function parse_num(var l: ansistring; s: integer; var num: integer) : integer;
var
sign, len: integer;
begin
sign := 1;
num := 0;
len := length(l);
while (s <= len) and is_whitespace(l[s]) do
inc(s);
while (s <= len) and numeric(l[s]) do
begin
if l[s] = '-' then
sign := -1
else
num := num * 10 + ord(l[s]) - ord('0');
inc(s);
end;
num := num * sign;
parse_num := s;
end;
function parse_bfield_dimensions(var field_str: ansistring; var w, h: integer) : ErrorCode;
var
nextpos: integer;
begin
parse_bfield_dimensions := parse_bfield_dimensions(field_str, w, h, nextpos);
end;
{ Leaves position after dimensions in nextpos }
function parse_bfield_dimensions(var field_str: ansistring; var w, h: integer; var nextpos: integer) : ErrorCode;
var
i: integer;
begin
parse_bfield_dimensions.code := OK;
if (length(field_str) < 5) or not numeric(field_str[1]) then
begin
parse_bfield_dimensions.code := PARSE_ERROR;
parse_bfield_dimensions.msg := 'Parse error: expected battlefield dimensions';
exit;
end;
i := parse_num(field_str, 1, w);
if (length(field_str) < i + 1) or not numeric(field_str[i + 1]) then
begin
parse_bfield_dimensions.code := PARSE_ERROR;
parse_bfield_dimensions.msg := 'Parse error: expected battlefield dimensions';
exit;
end;
nextpos := parse_num(field_str, i, h);
if (w = 0) or (h = 0) or (w > MAX_W) or (h > MAX_H) then
begin
parse_bfield_dimensions.code := BFIELD_OVERFLOW;
parse_bfield_dimensions.msg := 'Unsupported field dimensions: ' + IntToStr(w) + ' x ' + IntToStr(h);
end
end;
function parse_bfield_string(var field: BField; origin: IntVector; var field_str: ansistring; modifier: double; owner: integer; initial_king_hp: double) : ErrorCode;
var
cannon, king: IntVector;
begin
parse_bfield_string := parse_bfield_string(field, origin, field_str, cannon, king, modifier, owner, initial_king_hp);
end;
{ Parses battlefield or fort description and pastes it into the BField record }
function parse_bfield_string(var field: BField; origin: IntVector; var field_str: ansistring; var cannon, king: IntVector; modifier: double; owner: integer; initial_king_hp: double) : ErrorCode;
var
i: integer;
len: integer;
el_type: integer;
w, h, x, y: integer;
wx, wy: integer;
err: ErrorCode;
begin
parse_bfield_string.code := OK;
err := parse_bfield_dimensions(field_str, w, h, i);
if err.code <> OK then
begin
parse_bfield_string := err;
exit;
end;
if (field.width < w + origin.x) or (field.height < h + origin.y) then
begin
parse_bfield_string.code := BFIELD_OVERFLOW;
parse_bfield_string.msg := 'The fort does not fit in the battlefield';
exit;
end;
len := length(field_str);
x := 0; y := 0;
for i := i to len do
begin
if numeric(field_str[i]) or (field_str[i] in ['.', 'C', 'K']) then
begin
wx := x + origin.x;
wy := y + origin.y;
if field_str[i] <> '.' then
field.arr[wx, wy].owner := owner
else
field.arr[wx, wy].owner := 0;
el_type := ord(field_str[i]) - ord('0');
{ Omit the dot which means `transparent' }
if numeric(field_str[i]) then
field.arr[wx, wy].hp := INITIAL_HP[el_type] * modifier
else if field_str[i] in ['C', 'K'] then
field.arr[wx, wy].hp := initial_king_hp;
if field_str[i] = 'C' then
cannon := iv(x, y);
if field_str[i] = 'K' then
king := iv(x, y);
field.arr[wx, wy].current_hp := field.arr[wx, wy].hp;
field.arr[wx, wy].previous_hp := field.arr[wx, wy].hp;
field.arr[wx, wy].hp_speed := 0;
inc(x);
if not (x < w) then
begin
x := 0;
inc(y);
end;
end
else if is_whitespace(field_str[i]) then
continue
else
begin
parse_bfield_string.code := PARSE_ERROR;
parse_bfield_string.msg := 'Malformed field file at byte ' + IntToStr(i) +
': got: `' + field_str[i] + ''', expected digit, `K'', `C'' or `.''';
exit;
end;
end;
if (y * w + x) < (w * h) then
begin
parse_bfield_string.code := INCOMPL_BFIELD;
parse_bfield_string.msg := 'The field is incomplete. Got ' + IntToStr(y * w + x) +
' characters, expected ' + IntToStr(w * h);
end
end;
function read_file_to_string(filename: ansistring; var ostr: ansistring) : ErrorCode;
var
fp: text;
t: ansistring;
begin
read_file_to_string.code := OK;
{$I-}
assign(fp, filename);
reset(fp);
readln(fp, ostr);
ostr := ostr + NEWLINE;
while not eof(fp) do begin
readln(fp, t);
ostr := ostr + t + NEWLINE;
end;
if IOResult <> 0 then
begin
read_file_to_string.code := FILE_ERROR;
read_file_to_string.msg := 'There was a problem reading file: ' + filename + '!';
end
{$I+}
end;
function is_separator(a: char) : boolean;
begin
is_separator := (a = '=');
end;
function is_sensible(a: char) : boolean;
begin
is_sensible := a in [' '..'~'];
end;
{ Produces a list of configuration key-value pairs }
function parse_keys(var pairs: ConfigPairList; var confstr: ansistring) : ErrorCode;
var
pair: ConfigPair;
len: integer;
i, l: integer;
begin
parse_keys.code := OK;
len := length(confstr);
i := 0;
l := 1;
while i <= len do
begin
pair.key := '';
while (i <= len) and (is_whitespace(confstr[i]) and not (confstr[i] = NEWLINE)) do
inc(i);
if (i > len) or (confstr[i] = NEWLINE) then
begin
inc(i);
inc(l);
continue;
end;
while (i <= len) and not (is_separator(confstr[i]) or (confstr[i] = NEWLINE)) do
begin
if is_sensible(confstr[i]) then
pair.key := pair.key + confstr[i];
inc(i);
end;
if (i > len) or (confstr[i] = NEWLINE) then
begin
parse_keys.code := INCOMPL_PAIR;
parse_keys.msg := 'Incomplete key-value pair in line: ' + IntToStr(l);
exit;
end;
inc(i); pair.value := '';
while (i <= len) and (confstr[i] <> NEWLINE) do
begin
if is_sensible(confstr[i]) then
pair.value := pair.value + confstr[i];
inc(i);
end;
pair.value := trim(pair.value);
pair.key := trim(pair.key);
if pair.value = '' then
begin
parse_keys.code := INCOMPL_PAIR;
parse_keys.msg := 'Empty value in line: ' + IntToStr(l);
exit;
end;
pair.line := l;
push_front(pairs, pair);
end;
end;
{ Parses game configuration }
function parse_game_string(var options: ansistring; var config: ConfigStruct) : ErrorCode;
var
list: ConfigPairList;
cur: pConfigPairNode;
err: ErrorCode;
what: ansistring;
num: integer;
i: integer;
begin
for i := 1 to 9 do
begin
config.equipment[i].amount := 1;
config.equipment[i].exp_force := 0;
config.equipment[i].exp_radius := 0;
config.equipment[i].drill_len := 0;
config.equipment[i].num := 0;
end;
config.fort_modifier := 2;
config.max_force := 30;
config.max_wind := 4;
config.initial_hp := 300;
config.name[1] := 'Player 1';
config.name[2] := 'Player 2';
config.color[1] := 2; {Green}
config.color[2] := 14; {Yellow}
config.fort_pos[1] := iv(0, 0);
config.fort_pos[2] := iv(0, 0);
parse_game_string.code := OK;
new_list(list);
err := parse_keys(list, options);
if err.code <> OK then
begin
parse_game_string := err;
exit;
end;
cur := list.head;
while cur <> nil do
begin
if cur^.v.key = 'map_file' then
config.bfield_file := cur^.v.value
else if cur^.v.key = 'fort_modifier' then
config.fort_modifier := StrToFloat(cur^.v.value)
else if cur^.v.key = 'max_force' then
config.max_force := StrToFloat(cur^.v.value)
else if cur^.v.key = 'max_wind' then
config.max_wind := StrToFloat(cur^.v.value)
else if cur^.v.key = 'initial_hp' then
config.initial_hp := StrToFloat(cur^.v.value)
else if (length(cur^.v.key) >= 8) and
AnsiStartsStr('player', cur^.v.key) and (cur^.v.key[7] in ['1', '2']) then
begin
num := ord(cur^.v.key[7]) - ord('0');
what := AnsiMidStr(cur^.v.key, 9, 100000);
if what = 'fort_file' then
config.fort_file[num] := cur^.v.value
else if what = 'name' then
config.name[num] := cur^.v.value
else if what = 'fort_pos' then
begin
i := parse_num(cur^.v.value, 1, config.fort_pos[num].x);
parse_num(cur^.v.value, i, config.fort_pos[num].y);
end
else if what = 'color' then
config.color[num] := StrToInt(cur^.v.value)
else
begin
parse_game_string.code := INVALID_KEY;
parse_game_string.msg := 'Invalid player description key `' + cur^.v.key + ''' in line ' + IntToStr(cur^.v.line);
break;
end;
end
else if (length(cur^.v.key) >= 8) and
AnsiStartsStr('weapon', cur^.v.key) and (cur^.v.key[7] in ['1'..'9']) then
begin
num := ord(cur^.v.key[7]) - ord('0');
what := AnsiMidStr(cur^.v.key, 9, 100000);
if what = 'name' then
config.equipment[num].name := cur^.v.value
else if what = 'force' then
config.equipment[num].exp_force := StrToFloat(cur^.v.value)
else if what = 'radius' then
config.equipment[num].exp_radius := StrToFloat(cur^.v.value)
else if what = 'amount' then
config.equipment[num].amount := StrToInt(cur^.v.value)
else if what = 'limit' then
config.equipment[num].num := StrToInt(cur^.v.value)
else if what = 'drill' then
config.equipment[num].drill_len := StrToFloat(cur^.v.value)
else
begin
parse_game_string.code := INVALID_KEY;
parse_game_string.msg := 'Invalid rocket description key `' + cur^.v.key + ''' in line ' + IntToStr(cur^.v.line);
end;
end
else
begin
parse_game_string.code := INVALID_KEY;
parse_game_string.msg := 'Invalid key `' + cur^.v.key + ''' in line ' + IntToStr(cur^.v.line);
break;
end;
cur := cur^.next;
end;
if config.bfield_file = '' then
begin
parse_game_string.code := MISSING_KEY;
parse_game_string.msg := 'Missing key bfield_file';
end;
if config.fort_file[1] = '' then
begin
parse_game_string.code := MISSING_KEY;
parse_game_string.msg := 'Missing key player1_fort_file';
end;
if config.fort_file[2] = '' then
begin
parse_game_string.code := MISSING_KEY;
parse_game_string.msg := 'Missing key player2_fort_file';
end;
end;
begin
end.
|
unit QRemote;
interface
uses classes,sysutils,quickRTTI,IdTCPConnection, IdTCPClient, IdHTTP, IdBaseComponent,
IdComponent, IdTCPServer, IdHTTPServer,
IdThreadMgr, IdThreadMgrPool;
{Relies on Indy Components}
type
TRemoteRequest = class(TXMLAware)
private
fcommand,fguid,fservice:String; fparams:TStringlist;
fObj:TPersistent;
published
property Service:String read fservice write fservice;
property Command:String read fcommand write fcommand;
property Parameters:tstringlist read fparams write fparams;
property RTTIObject:TPersistent read fObj write fObj;
property GUID:String read fGUID write fGUID; {sort of a transaction id sort of thing, optional}
end;
TRemoteResponse = class(TXMLAware)
private
fObj:TPersistent;
ferr:integer; fmsg,fGUID,fservice:String;
published
property Service:String read fservice write fservice;
property ErrorNumber:integer read ferr write ferr;
property ErrorMessage:String read fmsg write fmsg;
property RTTIObject:TPersistent read fObj write fObj;
property GUID:String read fGUID write fGUID; {echos the GUID back to you.}
end;
TQRemoteObject = class(TXMLAware)
private
fservice:String;
public
function ProcessCall (Command:String;Parameters:TStrings):TRemoteResponse;virtual;
constructor create (Service:String);virtual;
procedure RemoteCall(URL,Command:String);
property Service:String read fservice write fservice;
end;
TQRemoteObjectProcessor = class(TPersistent)
private
fobjs:TList;
public
Constructor create;
destructor destroy;override;
published
function AddObject (Obj:TQRemoteObject):integer;
procedure DeleteObject (index:integer);
function ObjectCount:integer;
function GetObject(index:integer):TQRemoteObject;
function ServiceIndex(Service:String):integer;
procedure ProcessCall (RTTIENabler:TCustomXMLRTTI;RequestXML:String; var ResponseXML:String);
end;
{This call assumes the server is going to send and receive the same object for processing..
hand it a user, call login, and get the user back all filled in...}
function ReceiveRemoteCall (Q:TCustomXMLRTTI;RequestXML:String):TRemoteRequest;
function BuildResponse (Obj:TQRemoteObject;Q:TCustomXMLRTTI;ErrorNumber:integer;ErrorMessage:String) : TRemoteResponse;
implementation
procedure TQRemoteObjectProcessor.ProcessCall (RTTIENabler:TCustomXMLRTTI;RequestXML:String; var ResponseXML:String);
var Obj,Hold:TQRemoteObject;O:TObject; RRq:TRemoteRequest; RR:TRemoteResponse; Q:TCustomXMLRTTI; idx:integer;
begin
Q:=RTTIENABLER;
RRq:= ReceiveRemoteCall(Q,RequestXML);
idx:= self.ServiceIndex(RRq.service);
if idx>-1 then
begin
Obj:= TQRemoteObject(fobjs[idx]);
{Make a copy of the base object... for thread safety}
try
Hold:=TQRemoteObject(Obj.newinstance);
Hold.create(Obj.service);
hold.RTTIEnabler := Q;
RRq.RTTIObject := hold;
RRq.RTTIEnabler:=q;
RRQ.LoadFromXML ('RemoteRequest',RequestXML);
RR:= Hold.ProcessCall (RRq.command,RRq.Parameters);
RR.RTTIObject := Hold;
RR.RTTIEnabler:= Q;
ResponseXML := RR.savetoXML ('RemoteResponse');
RR.Free;
finally
HOld.free;{clean up!}
end;
end else
begin
RR:=TRemoteResponse.create;
RR.RTTIEnabler:= Q;
RR.ErrorNumber:=1;
RR.ErrorMessage := 'Service ['+RRq.Service+'] Not Available.';
ResponseXML := RR.savetoXML ('RemoteResponse');
RR.Free;
end;
RRq.free;
end;
Constructor TQRemoteObjectProcessor.create;
begin
fobjs:=tlist.create;
end;
destructor TQRemoteObjectProcessor.destroy;
begin
try
while fobjs.count>0 do
begin
if assigned(TQRemoteObject(fobjs[0])) then TQRemoteObject(fobjs[0]).free;
fobjs.delete(0);
end;
finally
inherited destroy;
end;
end;
function TQRemoteObjectProcessor.AddObject (Obj:TQRemoteObject):integer;
begin
fobjs.add(Obj);
end;
procedure TQRemoteObjectProcessor.DeleteObject (index:integer);
begin
if assigned(TQRemoteObject(fobjs[index])) then TQRemoteObject(fobjs[index]).free;
fobjs.delete(index);
end;
function TQRemoteObjectProcessor.ObjectCount:integer;
begin
result:=fobjs.count;
end;
function TQRemoteObjectProcessor.GetObject(index:integer):TQRemoteObject;
begin
result:= TQRemoteObject(fobjs[index]);
end;
function TQRemoteObjectProcessor.ServiceIndex(Service:String):integer;
var found,i,max:integer; Obj:TQRemoteObject;
begin
max:=fobjs.count-1;
result:=-1;
for i:= 0 to max do
begin
Obj:= GetObject(i);
if Obj.Service=Service then result:= i;
end;
end;
function BuildResponse (Obj:TQRemoteObject;Q:TCustomXMLRTTI;ErrorNumber:integer;ErrorMessage:String) : TRemoteResponse;
var xmlout:String; RR:TRemoteResponse;
begin
{Server will hand back the current time in an object}
RR:=TRemoteResponse.create;
RR.Service:= Obj.service;
RR.RTTIEnabler := Q;
RR.RTTIObject := Obj;
RR.ErrorNumber := ErrorNumber;
RR.ErrorMessage := ErrorMessage;
result:=RR;
end;
function ReceiveRemoteCall (Q:TCustomXMLRTTI;RequestXML:String):TRemoteRequest;
var RRq:TRemoteRequest;
begin
RRq:=TRemoteRequest.create;
RRq.RTTIEnabler:=Q;
RRq.LoadFromXML ('RemoteRequest',RequestXML);
result:=RRq;
end;
constructor TQRemoteObject.create (Service:String);
begin
fservice:=Service;
end;
function TQRemoteObject.ProcessCall (Command:String;Parameters:TStrings):TRemoteResponse;
begin
{do your processing and then call inherited(Command,Parameters}
end;
function MakeRemoteCall (Obj:TXMLAware;URL,Service,Command:String):TRemoteResponse;
var Q:TCustomXMLRTTI; RR:TRemoteResponse; RRq:TRemoterequest;
postlines,readlines:tstringlist;ms:Tmemorystream; Client:TIdHTTP;
raiseerr:integer;Msg:String; Err:Exception;
begin
{Server will hand back the current time in an object}
raiseerr:=0;
try
Client:=TIdHTTP.create(nil);
Q:=Obj.RTTIEnabler;
RRq:=TRemoteRequest.create;
RRQ.rttiobject:=Obj;
RRq.rttienabler:= Q;
RRQ.service:=Service;
RRQ.command:=Command;
postlines:=tstringlist.create;
postlines.text:= RRQ.SavetoXML('RemoteRequest');
ms:=Tmemorystream.create;
Client.Post(URL,postlines,ms);
readlines:=tstringlist.create;
ms.seek(0,0);
readlines.loadfromstream(ms);
RR:=TRemoteResponse.create;
RR.RTTIEnabler := Q;
RR.RTTIObject:= Obj;
RR.LoadFromXML ('RemoteResponse',readlines.text);
raiseerr:=RR.ErrorNumber ;
msg:=rr.ErrorMessage ;
rr.free;
except on E:Exception do
begin
raiseerr:=2;
msg:=E.Message;
end
end;
if assigned(RRQ) then RRQ.free;
if assigned(Client) then Client.free;
if raiseerr>0 then
begin
Err:=Exception.create(Msg);
raise(err);
end;
end;
procedure TQRemoteObject.RemoteCall (URL,Command:String);
begin
MakeRemoteCall (self,URL,fservice,Command);
end;
end.
|
(*
Category: SWAG Title: STRING HANDLING ROUTINES
Original name: 0020.PAS
Description: String Centering
Author: GUY MCLOUGHLIN
Date: 07-16-93 06:04
*)
(*
===========================================================================
BBS: Canada Remote Systems
Date: 06-25-93 (13:52) Number: 25767
From: GUY MCLOUGHLIN Refer#: NONE
To: CHRIS PRIEDE Recvd: NO
Subj: STRING CENTERING ROUTINES Conf: (552) R-TP
---------------------------------------------------------------------------
Hi, Chris:
CP>Ideally such function should be written in assembly, but since this
CP>is Pascal conference and I've flooded it with my assembly code enough
CP>lately, we will use plain Turbo Pascal.
Try running this program using your routine and the one I posted,
you might notice something "funny" about the ouput displayed. <g>
*)
program DemoStringRoutines;
USES Crt;
function FCenter(S: string; W: byte): string;
var
SpaceCnt: byte;
begin
if Length(S) < W then
begin
SpaceCnt := (W - Length(S)) div 2;
Move(S[1], S[1+SpaceCnt], Length(S));
FillChar(S[1], SpaceCnt, '-');
S[0] := Chr(Length(S) + SpaceCnt);
end;
FCenter := S;
end;
(* Set these constants according to your needs. *)
const
BlankChar = '-';
ScreenWidth = 80;
(***** Create video-display string with input string centered. *)
(* *)
function CenterVidStr({input} InText : string) : {output} string;
var
InsertPos : byte;
TempStr : string;
begin
(* Initialize TempStr. *)
TempStr[0] := chr(ScreenWidth);
fillchar(TempStr[1], ScreenWidth, BlankChar);
(* Calculate string insertion position. *)
InsertPos := succ((ScreenWidth - length(InText)) div 2);
(* Insert text in the center of TempStr. *)
move(InText[1], TempStr[InsertPos], length(InText));
(* Return function result. *)
CenterVidStr := TempStr
end; (* CenterVidStr. *)
var
TempStr : string;
BEGIN
Clrscr;
fillchar(TempStr[1], 30, 'X');
TempStr[0] := #30;
writeln(FCenter(TempStr, 80));
writeln(CenterVidStr(TempStr))
END.
{
...I tried timing these two routines on my PC (Recently upgraded
to a 386dx-40 AMD motherboard), and here are the results:
Compiler │ Length │ Your routine │ My routine │ Ratio
──────────┼────────┼──────────────┼────────────┼────────
TP 7 │ 30 │ 0.03167 │ 0.04043 │ 1.28
──────────┼────────┼──────────────┼────────────┼────────
PASCAL+ │ 30 │ 0.02037 │ 0.01959 │ 0.96
*** Both functions were called in a loop 1000 times on each run,
result was discarded ($X+ directive).
For curiosity sake I'll post the StonyBrook PASCAL+ machine-code
listing in the next message.
- Guy
---
■ DeLuxe²/386 1.25 #5060 ■
}
|
unit SHDefaultClipboardFormat;
interface
uses
Windows, SysUtils,Classes, Clipbrd,DB,
DBGridEh, DBGridEhImpExp,
SHDesignIntf;
type
TBTClipboardFormat = class(TSHComponent, ISHClipboardFormat, ISHDemon)
private
protected
procedure CutToClipboard(AComponent, ADataset, AGrid: TComponent);
procedure CopyToClipboard(AComponent, ADataset, AGrid: TComponent);
function PasteFromClipboard(AComponent, ADataset, AGrid: TComponent): Boolean;
end;
TDBGridEhExportAsTextWithNulls = class(TDBGridEhExportAsText)
private
FirstCell:boolean;
FirstRec :boolean;
protected
procedure CheckFirstCell; override;
procedure CheckFirstRec; override;
procedure WriteRecord(ColumnsList: TColumnsEhList); override;
procedure WriteTitle(ColumnsList: TColumnsEhList); override;
procedure WriteDataCell(Column: TColumnEh; FColCellParamsEh: TColCellParamsEh); override;
end;
procedure Register();
implementation
var
IsWinNT:boolean;
procedure Register();
begin
SHRegisterComponents([TBTClipboardFormat]);
end;
{ TBTClipboardFormat }
procedure TBTClipboardFormat.CutToClipboard(AComponent, ADataset,
AGrid: TComponent);
begin
CopyToClipboard(AComponent, ADataset, AGrid);
end;
procedure SaveClipboard ;
var
Data: THandle;
s:WideString;
ms: TMemoryStream;
begin
with ClipBoard do
begin
Open;
Data := GetClipboardData(CF_UNICODETEXT);
try
if Data <> 0 then
s:= PWideChar(GlobalLock(Data))
else
s:= '';
finally
if Data <> 0 then GlobalUnlock(Data);
Close;
end;
end;
ms := TMemoryStream.Create;
ms.WriteBuffer(PWideChar(S)^, (Length(s) + 1) * SizeOf(WideChar));
ms.SaveToFile('d:\ccc.txt');
ms.Free
end;
procedure TBTClipboardFormat.CopyToClipboard(AComponent, ADataset,
AGrid: TComponent);
var
ms: TMemoryStream;
procedure Clipboard_PutFromStream(Format: Word; ms: TMemoryStream);
var
Data: THandle;
DataPtr: Pointer;
Buffer: Pointer;
begin
// ms.SaveToFile('d:\Clip.txt');
Buffer := ms.Memory;
ClipBoard.Open;
try
Data := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, ms.Size);
try
DataPtr := GlobalLock(Data);
try
Move(Buffer^, DataPtr^, ms.Size);
ClipBoard.SetAsHandle(Format, Data);
finally
GlobalUnlock(Data);
end;
except
GlobalFree(Data);
raise;
end;
finally
ClipBoard.Close;
end;
end;
begin
// SaveClipboard;
if AGrid.InheritsFrom(TDBGridEh) then
begin
Clipboard.Open;
TDBGridEh(AGrid).DataSource.DataSet.DisableControls;
ms := TMemoryStream.Create;
try
WriteDBGridEhToExportStream(TDBGridEhExportAsTextWithNulls, TDBGridEh(AGrid), ms, False);
ms.WriteBuffer(PChar('')^, 1);
if IsWinNT then
Clipboard_PutFromStream(CF_UNICODETEXT , ms)
else
Clipboard_PutFromStream(CF_TEXT , ms);
ms.Clear;
finally
ms.Free;
Clipboard.Close;
TDBGridEh(AGrid).DataSource.DataSet.EnableControls;
end;
// DBGridEh_DoCopyAction(TDBGridEh(AGrid), False);
end;
end;
function TBTClipboardFormat.PasteFromClipboard(AComponent, ADataset,
AGrid: TComponent): Boolean;
begin
Result := False;
if AGrid.InheritsFrom(TDBGridEh) then
begin
DBGridEh_DoPasteAction(TDBGridEh(AGrid), False);
end;
end;
{ TDBGridEhExportAsTextWithNulls }
procedure TDBGridEhExportAsTextWithNulls.CheckFirstCell;
var s: WideString;
begin
if IsWinNT then
begin
if FirstCell = False then
begin
s := #09;
Stream.Write(PWideChar(s)^, (Length(s)) * SizeOf(WideChar));
end else
FirstCell := False;
end
else
inherited
end;
procedure TDBGridEhExportAsTextWithNulls.CheckFirstRec;
var
s: WideString;
begin
if IsWinNT then
begin
if FirstRec = False then
begin
s := #13#10;
Stream.Write(PWideChar(s)^, (Length(s)) * SizeOf(WideChar));
end
else
FirstRec := False;
end
else
inherited;
end;
procedure TDBGridEhExportAsTextWithNulls.WriteDataCell(Column: TColumnEh;
FColCellParamsEh: TColCellParamsEh);
var
ws:WideString;
begin
if IsWinNT then
begin
CheckFirstCell;
if Assigned(Column) and Assigned(Column.Field) and Column.Field.IsNull then
begin
ws:='NULL';
Stream.Write(PWideChar(ws)^, (Length(ws)) * SizeOf(WideChar));
end
else
begin
if Assigned(Column) and Assigned(Column.Field) and (Column.Field is TWideStringField) then
ws:=TWideStringField(Column.Field).Value
else
ws := FColCellParamsEh.Text;
Stream.Write(PWideChar(ws)^, (Length(ws)) * SizeOf(WideChar));
end
end
else
if Assigned(Column) and Assigned(Column.Field) and Column.Field.IsNull then
begin
CheckFirstCell;
Stream.Write('NULL' , 4);
end
else
inherited WriteDataCell(Column, FColCellParamsEh);
end;
procedure TDBGridEhExportAsTextWithNulls.WriteRecord(
ColumnsList: TColumnsEhList);
begin
FirstCell := True;
inherited;
end;
procedure TDBGridEhExportAsTextWithNulls.WriteTitle(
ColumnsList: TColumnsEhList);
var i: Integer;
ws:WideString;
begin
CheckFirstRec;
for i := 0 to ColumnsList.Count - 1 do
begin
if IsWinNT then
begin
ws := ColumnsList[i].Title.Caption;
if i <> ColumnsList.Count - 1 then
begin
Stream.Write(PWideChar(ws)^, (Length(ws)) * SizeOf(WideChar));
ws := #09;
Stream.Write(PWideChar(ws)^, (Length(ws)) * SizeOf(WideChar));
end;
end
else
inherited WriteTitle(ColumnsList)
end;
end;
initialization
Register();
IsWinNT := (Win32Platform and VER_PLATFORM_WIN32_NT) <> 0;
end.
|
// FLibMaterialPicker
{: Egg<p>
Allows choosing a material in a material library<p>
<b>Historique : </b><font size=-1><ul>
</ul></font>
}
unit FLibMaterialPickerLCL;
interface
{$i GLScene.inc}
uses
lresources, LCLIntf,
Controls, Classes, Forms, StdCtrls, Buttons, dialogs, Graphics,
GLViewer, GLMaterial, GLScene, GLObjects, GLTexture,
GLHUDObjects, GLTeapot, GLGeomObjects, GLColor,
GLCoordinates;
type
{ TLibMaterialPicker }
TLibMaterialPicker = class(TForm)
LBMaterials: TListBox;
Label1: TLabel;
Label2: TLabel;
BBOk: TBitBtn;
BBCancel: TBitBtn;
GLScene1: TGLScene;
SceneViewer: TGLSceneViewer;
CBObject: TComboBox;
Camera: TGLCamera;
Cube: TGLCube;
Sphere: TGLSphere;
LightSource: TGLLightSource;
CBBackground: TComboBox;
BackGroundSprite: TGLHUDSprite;
Cone: TGLCone;
Teapot: TGLTeapot;
World: TGLDummyCube;
Light: TGLDummyCube;
FireSphere: TGLSphere;
GLMaterialLibrary: TGLMaterialLibrary;
procedure LBMaterialsClick(Sender: TObject);
procedure LBMaterialsKeyPress(Sender: TObject; var Key: Char);
procedure LBMaterialsDblClick(Sender: TObject);
procedure CBObjectChange(Sender: TObject);
procedure CBBackgroundChange(Sender: TObject);
procedure SceneViewerMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure SceneViewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure SceneViewerMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
private
function GetMaterial: TGLMaterial;
procedure SetMaterial(const Value: TGLMaterial);
property Material : TGLMaterial read GetMaterial write SetMaterial;
{ Diclarations privies }
public
{ Diclarations publiques }
constructor Create(AOwner : TComponent); override;
function Execute(var materialName : TGLLibMaterialName;
materialLibrary : TGLMaterialLibrary) : Boolean;
end;
function LibMaterialPicker : TLibMaterialPicker;
procedure ReleaseLibMaterialPicker;
implementation
var
vLibMaterialPicker : TLibMaterialPicker;
function LibMaterialPicker : TLibMaterialPicker;
begin
if not Assigned(vLibMaterialPicker) then
vLibMaterialPicker:=TLibMaterialPicker.Create(nil);
Result:=vLibMaterialPicker;
end;
procedure ReleaseLibMaterialPicker;
begin
if Assigned(vLibMaterialPicker) then begin
vLibMaterialPicker.Free; vLibMaterialPicker:=nil;
end;
end;
// Execute
//
function TLibMaterialPicker.Execute(var materialName : TGLLibMaterialName;
materialLibrary : TGLMaterialLibrary) : Boolean;
begin
with LBMaterials do begin
materialLibrary.Materials.SetNamesToTStrings(LBMaterials.Items);
ItemIndex:=Items.IndexOf(materialName);
if (ItemIndex<0) and (Items.Count>0) then ItemIndex:=0;
BBOk.Enabled:=(Items.Count>0);
end;
LBMaterialsClick(Self);
Result:=(ShowModal=mrOk);
if Result then begin
with LBMaterials do
if ItemIndex>=0 then
materialName:=Items[ItemIndex]
else materialName:='';
end;
end;
var
MX, MY: Integer;
constructor TLibMaterialPicker.Create(AOwner : TComponent);
begin
inherited;
{$IFDEF UNIX}
SceneViewer.Height:= 160;
SceneViewer.Top:= 64;
{$ENDIF}
BackGroundSprite.Position.X := SceneViewer.Width div 2;
BackGroundSprite.Position.Y := SceneViewer.Height div 2;
BackGroundSprite.Width := SceneViewer.Width;
BackGroundSprite.Height := SceneViewer.Height;
CBObject.ItemIndex:=0; CBObjectChange(Self);
CBBackground.ItemIndex:=0; CBBackgroundChange(Self);
end;
procedure TLibMaterialPicker.LBMaterialsClick(Sender: TObject);
begin
with LBMaterials do if ItemIndex>=0 then
Material:=TGLLibMaterial(Items.Objects[ItemIndex]).Material;
end;
procedure TLibMaterialPicker.LBMaterialsKeyPress(Sender: TObject;
var Key: Char);
begin
LBMaterialsClick(Sender);
end;
procedure TLibMaterialPicker.LBMaterialsDblClick(Sender: TObject);
begin
BBOk.Click;
end;
procedure TLibMaterialPicker.CBObjectChange(Sender: TObject);
var
i : Integer;
begin
i:=CBObject.ItemIndex;
Cube.Visible := I = 0;
Sphere.Visible := I = 1;
Cone.Visible := I = 2;
Teapot.Visible := I = 3;
end;
procedure TLibMaterialPicker.CBBackgroundChange(Sender: TObject);
var
bgColor : TColor;
begin
case CBBackground.ItemIndex of
1 : bgColor:=clWhite;
2 : bgColor:=clBlack;
3 : bgColor:=clBlue;
4 : bgColor:=clRed;
5 : bgColor:=clGreen;
else
bgColor:=clNone;
end;
with BackGroundSprite.Material do begin
Texture.Disabled:=(bgColor<>clNone);
FrontProperties.Diffuse.Color:=ConvertWinColor(bgColor);
end;
end;
procedure TLibMaterialPicker.SceneViewerMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if (ssRight in Shift) and (ssLeft in Shift) then
Camera.AdjustDistanceToTarget(1 - 0.01 * (MY - Y))
else
if (ssRight in Shift) or (ssLeft in Shift) then
Camera.MoveAroundTarget(Y - MY, X - MX);
MX := X;
MY := Y;
end;
procedure TLibMaterialPicker.SceneViewerMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
MX := X;
MY := Y;
end;
procedure TLibMaterialPicker.SceneViewerMouseWheel(Sender: TObject;
Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint;
var Handled: Boolean);
begin
Camera.AdjustDistanceToTarget(1 - 0.1 * (Abs(WheelDelta) / WheelDelta));
end;
function TLibMaterialPicker.GetMaterial: TGLMaterial;
begin
Result := GLMaterialLibrary.Materials[0].Material;
end;
procedure TLibMaterialPicker.SetMaterial(const Value: TGLMaterial);
begin
GLMaterialLibrary.Materials[0].Material.Assign(Value);
end;
initialization
{$I FLibMaterialPickerLCL.lrs}
finalization
ReleaseLibMaterialPicker;
end.
|
unit Backend.MARSServer;
interface
uses
System.SysUtils,
MARS.HTTP.Server.Indy,
MARS.Core.Engine,
MARS.Core.Application;
type
TBackendMARSServer = class
private
FEngine: TMARSEngine;
FServer: TMARSHTTPServerIndy;
public
constructor Create;
procedure Run;
destructor Destroy; override;
end;
implementation
{ TBackendMARSServer }
constructor TBackendMARSServer.Create;
begin
FEngine := TMARSEngine.Create;
FEngine.Port := 81;
FEngine.ThreadPoolSize := 4;
FEngine.AddApplication('SAID','/said',['Backend.Resource.*']);
FServer := TMARSHTTPServerIndy.Create(FEngine);
FServer.DefaultPort := FEngine.Port;
end;
destructor TBackendMARSServer.Destroy;
begin
FreeAndNil(FEngine);
FreeAndNil(FServer);
inherited;
end;
procedure TBackendMARSServer.Run;
begin
FServer.Active := True;
end;
end.
|
unit Nathan.ObjectMapping.Types;
interface
uses
System.SysUtils,
System.Rtti;
{$M+}
type
TMappingType = (mtUnknown, mtField, mtProperty, mtMethod);
TCoreMapDetails = record
RttiTypeName: string;
Name: string;
TypeOfWhat: TTypeKind;
MappingType: TMappingType;
MemberClass: TRttiMember;
end;
MappedSrcDest = (msdSource, msdDestination);
TMappedSrcDest = array [MappedSrcDest] of TCoreMapDetails;
{$M+}
implementation
end.
|
unit uFrmHistory;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls;
type
TFrmHistory = class(TForm)
Panel1: TPanel;
Bevel1: TBevel;
BitBtn2: TBitBtn;
BtnSave: TBitBtn;
memHistory: TMemo;
BitBtn3: TBitBtn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BitBtn3Click(Sender: TObject);
private
{ Private declarations }
procedure GetHistory;
procedure SetHistory;
public
{ Public declarations }
function Start:Boolean;
end;
implementation
uses uMainConf, uDMServer, uDMRepl;
{$R *.dfm}
procedure TFrmHistory.GetHistory;
begin
if FileExists(DMServer.LocalPath+HISTORY_FILE) then
memHistory.Lines.LoadFromFile(DMServer.LocalPath+HISTORY_FILE);
memHistory.SelStart := 0;
end;
procedure TFrmHistory.SetHistory;
begin
memHistory.Lines.SaveToFile(DMServer.LocalPath+HISTORY_FILE);
end;
function TFrmHistory.Start:boolean;
begin
GetHistory;
ShowModal;
Result := (ModalResult=mrOK);
if Result then
SetHistory;
end;
procedure TFrmHistory.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmHistory.BitBtn3Click(Sender: TObject);
begin
memHistory.Lines.Clear;
BtnSave.Enabled := True;
end;
end.
|
unit uAngularJSSDK;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
System.Actions, FMX.ActnList, FMX.Controls.Presentation, FMX.ScrollBox,
FMX.Memo, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, System.IOUtils, StrUtils;
type
TAngularJSSDKFrame = class(TFrame)
HeaderFunctionMemo: TMemo;
GetFunctionMemo: TMemo;
SDKMemo: TMemo;
PostFunctionMemo: TMemo;
DeleteFunctionMemo: TMemo;
ActionList1: TActionList;
GenerateSDKAction: TAction;
private
{ Private declarations }
Host,Port: String;
EndPointTable: TFDDataSet;
FDMemTableInfo: TFDDataSet;
function GetQueryStringList(ADataSet: TFDDataSet): String;
public
{ Public declarations }
procedure Initialize(AHost,APort: String; ADataSet: TFDDataSet; AInfoDataSet: TFDDataSet);
function GenerateSDK(AFileName: String): String;
end;
implementation
{$R *.fmx}
uses
uMainForm;
function TAngularJSSDKFrame.GetQueryStringList(ADataSet: TFDDataSet): String;
begin
Result := MainForm.GetQueryStringList(ADataSet);
end;
procedure TAngularJSSDKFrame.Initialize(AHost,APort: String; ADataSet: TFDDataSet; AInfoDataSet: TFDDataSet);
begin
Host := AHost;
Port := APort;
EndPointTable := ADataSet;
FDMemTableInfo := AInfoDataSet;
end;
function TAngularJSSDKFrame.GenerateSDK(AFileName: String): String;
var
I: Integer;
SL: TStringList;
QueryString, ParamString: String;
CompCount: Integer;
FunctionList, HeaderList: TStringList;
ATemplatePath: String;
AOutputPath: String;
begin
CompCount := 1;
EndPointTable.DisableControls;
EndPointTable.First;
FunctionList := TStringList.Create;
HeaderList := TStringList.Create;
SL := TStringList.Create;
SL.StrictDelimiter := True;
while not EndPointTable.EOF do
begin
QueryString := '';
ParamString := '';
SL.Clear;
SL.CommaText := GetQueryStringList(EndPointTable) + IfThen((EndPointTable.FieldByName('Params').AsString<>'') OR (EndPointTable.FieldByName('Macros').AsString<>''),',format','format');
for I := 0 to SL.Count-1 do
begin
if SL[I]='format' then
begin
QueryString := QueryString + '''+(aformat!='''' ? '''+ IfThen(I=0,'?','&') + SL[I] + '=''+a' + SL[I] + IfThen(I=SL.Count-1,'','+''') + ' : '''')';
end
else
QueryString := QueryString + IfThen(I=0,'?','&') + SL[I] + '=''+a' + SL[I] + IfThen(I=SL.Count-1,'','+''');
ParamString := ParamString + IfThen(I=0,'',', ') + 'a' + SL[I] + IfThen(SL[I]='format',' = ''''','');
end;
if EndPointTable.FieldByName('RequestType').AsString='POST' then
begin
ParamString := '('+ParamString+IfThen(ParamString<>'',',','')+'abody'+')';
end
else
begin
ParamString := '('+ParamString+')';
end;
SL.Clear;
if EndPointTable.FieldByName('RequestType').AsString='GET' then
begin
SL.Append(GetFunctionMemo.Lines.Text
.Replace('{#EndPoint#}',EndPointTable.FieldByName('EndPoint').AsString,[rfReplaceAll])
.Replace('{#RootSegment#}',FDMemTableInfo.FieldByName('RootSegment').AsString,[rfReplaceAll])
.Replace('{#ParamString#}',ParamString,[rfReplaceAll])
.Replace('{#QueryString#}',QueryString + IfThen(QueryString='','''',''),[rfReplaceAll]));
end
else
if EndPointTable.FieldByName('RequestType').AsString='POST' then
begin
SL.Append(PostFunctionMemo.Lines.Text
.Replace('{#EndPoint#}',EndPointTable.FieldByName('EndPoint').AsString,[rfReplaceAll])
.Replace('{#RootSegment#}',FDMemTableInfo.FieldByName('RootSegment').AsString,[rfReplaceAll])
.Replace('{#ParamString#}',ParamString,[rfReplaceAll])
.Replace('{#QueryString#}',QueryString + IfThen(QueryString='','''',''),[rfReplaceAll]));
end
else
if EndPointTable.FieldByName('RequestType').AsString='DELETE' then
begin
SL.Append(DeleteFunctionMemo.Lines.Text
.Replace('{#EndPoint#}',EndPointTable.FieldByName('EndPoint').AsString,[rfReplaceAll])
.Replace('{#RootSegment#}',FDMemTableInfo.FieldByName('RootSegment').AsString,[rfReplaceAll])
.Replace('{#ParamString#}',ParamString,[rfReplaceAll])
.Replace('{#QueryString#}',QueryString + IfThen(QueryString='','''',''),[rfReplaceAll]));
end;
FunctionList.Append(SL.Text);
SL.Clear;
SL.Append(HeaderFunctionMemo.Lines.Text.Replace('{#EndPoint#}',EndPointTable.FieldByName('EndPoint').AsString,[rfReplaceAll]).Replace('{#ParamString#}',ParamString,[]));
HeaderList.Append(SL.Text);
EndPointTable.Next;
Inc(CompCount);
end;
SL.Free;
EndPointTable.EnableControls;
ATemplatePath := TPath.Combine(TPath.Combine(TPath.Combine(ExtractFilePath(ParamStr(0)),TemplatePath),SDKPath),OPLangPath);
AOutputPath := TPath.Combine(ExtractFilePath(ParamStr(0)),OutputPath);
if TDirectory.Exists(AOutputPath)=False then
begin
TDirectory.CreateDirectory(AOutputPath);
end;
SL := TStringList.Create;
if TFile.Exists(TPath.Combine(ATemplatePath,AngularJSSDKTemplateFile)) then
SL.LoadFromFile(TPath.Combine(ATemplatePath,AngularJSSDKTemplateFile))
else
SL.Text := SDKMemo.Lines.Text;
SL.Text := SL.Text.Replace('sdktemplatefile',AFileName.Replace(ExtractFileExt(AFileName),'',[rfIgnoreCase]));
SL.Text := SL.Text.Replace('{#Filename#}',AFileName.Replace(ExtractFileExt(AFileName),'',[rfIgnoreCase]));
SL.Text := SL.Text.Replace('{#URLHost#}',Host);
SL.Text := SL.Text.Replace('{#URLPort#}',Port);
SL.Text := SL.Text.Replace('{#Username#}','');
SL.Text := SL.Text.Replace('{#Password#}','');
SL.Text := SL.Text.Replace('{#SDKFunctionList#}',FunctionList.Text);
SL.Text := SL.Text.Replace('{#SDKHeaderList#}',HeaderList.Text);
SL.SaveToFile(TPath.Combine(AOutputPath,AFileName));
Result := SL.Text;
SL.Free;
FunctionList.Free;
HeaderList.Free;
end;
end.
|
unit kpZcnst;
interface
{ Constant definitions for VCLZip StringTable }
const
IDS_OPENZIP = 176;
IDS_ZIPNAMEFILTER = 177;
IDS_CANCELDESTDIR = 178;
IDS_INDEXOUTOFRANGE = 179;
IDS_CANCELLOADDISK = 180;
IDS_CANCELOPERATION = 181;
IDS_INCOMPLETEZIP = 182;
IDS_INVALIDZIP = 183;
IDS_INSERTDISK = 184;
IDS_OFMULTISET = 185;
IDS_CANCELZIPNAME = 186;
IDS_CANCELZIPOPERATION =187;
IDS_NEWFIXEDNAME = 188;
IDS_ZIPFILESFILTER = 189;
IDS_SEEKERROR = 190;
IDS_SEEKORIGINERROR = 191;
IDS_PUTBACKOVERFLOW = 192;
IDS_LOWMEM = 193;
IDS_PREMEND = 194;
IDS_REPLACEFILE = 195;
IDS_FILEXISTALERT = 196;
IDS_UNKNOWNMETH = 197;
IDS_ZIPERROR = 198;
IDS_OUTPUTTOLARGE = 199;
IDS_NOTREGISTERED = 200;
IDS_WARNING = 201;
IDS_NOCOPY = 202;
IDS_ERROR = 203;
IDS_NOTENOUGHROOM = 204;
IDS_CANTCREATEZCF = 205;
IDS_CANTWRITEZCF = 206;
IDS_CANTWRITEUCF = 207;
implementation
{$R kpZCnst.res}
end.
|
{-----------------------------------------------------------------------------
Unit Name: dlgPickList
Author: Kiriakos Vlahos
Date: 10-Mar-2006
Purpose: Generic Pick List dialog
History:
-----------------------------------------------------------------------------}
unit dlgPickList;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, CheckLst, Menus;
type
TPickListDialog = class(TForm)
CheckListBox: TCheckListBox;
Panel2: TPanel;
OKButton: TBitBtn;
BitBtn2: TBitBtn;
lbMessage: TLabel;
PickListPopUp: TPopupMenu;
mnSelectAll: TMenuItem;
mnDeselectAll: TMenuItem;
procedure mnDeselectAllClick(Sender: TObject);
procedure mnSelectAllClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
PickListDialog: TPickListDialog;
implementation
{$R *.dfm}
procedure TPickListDialog.mnSelectAllClick(Sender: TObject);
var
i : integer;
begin
for i := 0 to CheckListBox.Items.Count - 1 do
CheckListBox.Checked[i] := True;
end;
procedure TPickListDialog.mnDeselectAllClick(Sender: TObject);
var
i : integer;
begin
for i := 0 to CheckListBox.Items.Count - 1 do
CheckListBox.Checked[i] := False;
end;
end.
|
unit Form.Mail;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Objekt.Maildat,
System.UITypes;
type
Tfrm_Mail = class(TForm)
Panel1: TPanel;
cbo_Provider: TComboBox;
Label1: TLabel;
Panel2: TPanel;
btn_Ok: TButton;
btn_Cancel: TButton;
btn_Mail: TButton;
GroupBox1: TGroupBox;
Label2: TLabel;
edt_Host: TEdit;
Label3: TLabel;
edt_EMail: TEdit;
Label4: TLabel;
edt_User: TEdit;
lbl_Passwort: TLabel;
edt_Passwort: TEdit;
GroupBox2: TGroupBox;
Label5: TLabel;
edt_Betreff: TEdit;
Label6: TLabel;
edt_EMailAn: TEdit;
procedure btn_CancelClick(Sender: TObject);
procedure btn_OkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btn_MailClick(Sender: TObject);
private
fMaildat: TMaildat;
procedure LoadMailDat;
procedure MailSenden;
procedure MailError(Sender: TObject; aError: string);
public
end;
var
frm_Mail: Tfrm_Mail;
implementation
{$R *.dfm}
uses
Objekt.Allgemein, Objekt.SendMail;
procedure Tfrm_Mail.FormCreate(Sender: TObject);
begin
edt_Host.Text := '';
edt_EMail.Text := '';
edt_User.Text := '';
edt_Betreff.Text := '';
cbo_Provider.ItemIndex := 0;
fMaildat := TMaildat.Create;
cbo_Provider.Clear;
cbo_Provider.AddItem('Exchange', TObject(pvExchange));
cbo_Provider.AddItem('GMail', TObject(pvGMail));
cbo_Provider.AddItem('Web', TObject(pvWeb));
LoadMailDat;
end;
procedure Tfrm_Mail.FormDestroy(Sender: TObject);
begin
FreeAndNil(fMaildat);
end;
procedure Tfrm_Mail.LoadMailDat;
var
i1: Integer;
begin
fMaildat.Load;
cbo_Provider.ItemIndex := 0;
for i1 := 0 to cbo_Provider.Items.Count -1 do
begin
if Integer(cbo_Provider.Items.Objects[i1]) = Ord(fMaildat.Provider) then
begin
cbo_Provider.ItemIndex := i1;
break;
end;
end;
edt_Host.Text := fMailDat.Host;
edt_User.Text := fMaildat.User;
edt_EMail.Text := fMaildat.Mail;
edt_Passwort.Text := fMaildat.Passwort;
edt_Betreff.Text := fMaildat.Betreff;
edt_EMailAn.Text := fMaildat.MailAn;
end;
procedure Tfrm_Mail.btn_CancelClick(Sender: TObject);
begin
close;
end;
procedure Tfrm_Mail.btn_OkClick(Sender: TObject);
begin
fMaildat.Host := edt_Host.Text;
fMaildat.User := edt_User.Text;
fMaildat.Mail := edt_EMail.Text;
fMaildat.Passwort := edt_Passwort.Text;
fMaildat.Betreff := edt_Betreff.Text;
fMaildat.MailAn := edt_EMailAn.Text;
fMaildat.Provider := TProvider(Integer(cbo_Provider.Items.Objects[cbo_Provider.ItemIndex]));
fMaildat.Save;
close;
end;
procedure Tfrm_Mail.btn_MailClick(Sender: TObject);
begin
MailSenden;
end;
procedure Tfrm_Mail.MailSenden;
var
Mail: TSendMail;
Provider: TProvider;
Cur: TCursor;
begin
Cur := Screen.Cursor;
Mail := TSendMail.Create;
try
Screen.Cursor := crHourGlass;
Mail.MeineEMail := edt_EMail.Text;
Mail.MeinPasswort := edt_Passwort.Text;
Mail.MeinUsername := edt_User.Text;
Mail.Betreff := edt_Betreff.Text;
Mail.Nachricht := 'Das ist eine Nachricht (nfsBackup)';
Mail.EMailAdresse := edt_EMailAn.Text;
Mail.Host := edt_Host.Text;
Mail.OnMailError := MailError;
Provider := TProvider(Integer(cbo_Provider.Items.Objects[cbo_Provider.ItemIndex]));
if Provider = pvExchange then
Mail.SendenUeberExchange;
if Provider = pvGmail then
Mail.SendenUeberGMail;
if Provider = pvWeb then
Mail.SendenUeberWebDe;
finally
FreeAndNil(Mail);
Screen.Cursor := Cur;
end;
end;
procedure Tfrm_Mail.MailError(Sender: TObject; aError: string);
begin
AllgemeinObj.Log.DebugInfo('Fehler beim Senden einer Mail: ' + aError);
MessageDlg('Fehler beim Senden einer Mail:' + sLineBreak + aError, mtError, [mbOk], 0);
end;
end.
|
unit Chapter08._06_Solution1;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DeepStar.UString,
DeepStar.Utils;
/// 79. Word Search
/// Source : https://leetcode.com/problems/word-search/description/
/// 回溯法
/// 时间复杂度: O(m*n*m*n)
/// 空间复杂度: O(m*n)
type
TSolution = class
public
function exist(board: TArr2D_chr; word: UString): boolean;
end;
procedure Main;
implementation
procedure Main;
var
board: TArr2D_chr;
begin
board := [
['A', 'B', 'C', 'E'],
['S', 'F', 'C', 'S'],
['A', 'D', 'E', 'E']];
with TSolution.Create do
begin
WriteLn(exist(board, 'ABCCED'));
WriteLn(exist(board, 'SEE'));
WriteLn(exist(board, 'ABCB'));
Free;
end;
end;
{ TSolution }
function TSolution.exist(board: TArr2D_chr; word: UString): boolean;
const
D: TArr2D_int = ((-1, 0), (0, 1), (1, 0), (0, -1));
var
visited: array of array of boolean;
n, m: integer;
function __inArea__(x, y: integer): boolean;
begin
Result := (x >= 0) and (y >= 0) and (x < n) and (y < m);
end;
function __search__(x, y, index: integer): boolean;
var
newX, i, newY: integer;
begin
if index = word.Length - 1 then
begin
Result := word.Chars[index] = board[x, y];
Exit;
end;
if board[x, y] = word.Chars[index] then
begin
visited[x, y] := true;
for i := 0 to High(D) do
begin
newX := x + D[i, 0];
newY := y + D[i, 1];
if __inArea__(newX, newY)
and (visited[newX, newY] = false)
and __search__(newX, newY, index + 1) then
begin
Result := true;
Exit;
end;
end;
visited[x, y] := false;
end;
Result := false;
end;
var
i, j: integer;
begin
n := Length(board);
m := Length(board[0]);
SetLength(visited, n, m);
for i := 0 to n - 1 do
for j := 0 to m - 1 do
visited[i, j] := false;
for i := 0 to n - 1 do
begin
for j := 0 to m - 1 do
begin
if __search__(i, j, 0) then
Exit(true);
end;
end;
Result := false;
end;
end.
|
//******************************************************************************
// Проект "Контракты"
// Файл типовых ресурсов
// Чернявский А.Э. 2005г.
// последние изменения Перчак А.Л. 28/10/2008
//******************************************************************************
unit cn_Common_Types;
interface
uses Classes, IBase, Forms, Types,RxMemDS;
type TSelectMode = (SingleSelect, MultiSelect);
type TActionMode = (View, Edit);
type TSelectSynchEDBO = record
SynchEDBO_facul : boolean;
SynchEDBO_spec : boolean;
SynchEDBO_okr : boolean;
SynchEDBO_kurs : boolean;
SynchEDBO_group : boolean;
end;
{type
TReturnMode = record
Mode: (Single, Multy);
end;}
Type TcnSimpleParams = class
public
Owner: TComponent;
Db_Handle: TISC_DB_HANDLE;
Formstyle: TFormStyle;
WaitPakageOwner : TForm;
SMode : TSelectMode;
AMode : TActionMode;
ID_SESSION: Int64;
Type_Report:Integer;
Sql_Master,Sql_Detail,Report_Name:String;
FieldView,NotFieldView,FieldNameReport:Variant;
LastIgnor:Integer;
Date_beg,Date_end:TDateTime;
ID_User : Int64;
User_Name: string;
ID_Locate : int64;
ID_Locate_1 : int64;
ID_Locate_2 : int64;
DontShowGroups : boolean;
DontShowFacs : boolean;
ID_PRICE: Int64;
is_admin: boolean; //признак админа
is_debug : boolean; //признак редактирования отчета
CN_USE_EDBO_FIZ_LIC : Integer; //использовать ли справочник физических лиц ЕДБО - 1 или наш - 0
end;
type TcnParamsToPakage = record
ID_DOG_ROOT : int64;
ID_DOG : int64;
ID_STUD : int64;
ID_RATE_ACCOUNT : int64;
ID_DOC : int64;
FIO : String;
Num_Doc : String;
Note : String;
DATE_DOG : TDateTime;
Summa : Currency;
IsWithSumma : Boolean;
DissDownAllContract : boolean;
Is_collect : byte;
IsUpload : Boolean; // признак переоформления договора
Is_Admin : Boolean; //Признак админестратора
BarCode : String;
end;
type TcnSimpleParamsEx = class(TcnSimpleParams)
public
cnParamsToPakage : TcnParamsToPakage;
ReturnMode : string; // Single, Multy
// для рапортов
TypeDoc : byte; // 1-отчисление, 2-восстановление
TR_Handle : TISC_TR_HANDLE;
end;
type TcnAccessResult = record
ID_User:integer;
Name_user:string;
User_Id_Card:integer;
User_Fio:string;
DB_Handle : TISC_DB_HANDLE;
Password: string;
end;
type TcnAcademicYear = record
Date_Beg: TDateTime;
Date_End: TDateTime;
end;
type TCurrentConnect = record
Db_Handle: TISC_DB_HANDLE;
PLanguageIndex: byte;
end;
type TDissInfo = record
flag : Integer;
TR_Handle: TISC_TR_HANDLE;
Date_Diss: TDateTime;
end;
type TcnExAcademicYear = array of TcnAcademicYear;
type TFinanceSource = record
isEmpty : boolean;
ID_SMETA : int64;
ID_RAZDEL : int64;
ID_STAT : int64;
ID_KEKV : int64;
PERCENT : Currency;
TEXT_SMETA :string;
TEXT_RAZDEL :string;
TEXT_STAT :string;
TEXT_KEKV :string;
CODE_SMETA :string;
CODE_RAZDEL :string;
CODE_STAT :string;
CODE_KEKV :string;
end;
type TcnSourceStudInf = record
ID_FAC : int64;
ID_SPEC : int64;
end;
type TcnSourceStudInfParams = class(TcnSimpleParams)
public
cnSourceStudInf : TcnSourceStudInf;
end;
type
TcnCalcIn = record
Owner : TComponent;
DB_Handle : TISC_DB_HANDLE;
ID_STUD : int64;
BEG_CHECK : TDateTime;
END_CHECK : TDateTime;
CNUPLSUM : Currency;
end;
type
TcnCalcOut = record
CNDATEOPL : TDateTime;
CN_SNEED : Currency;
CN_SNEEDL : Currency;
ID_SESSION : int64;
end;
type
TcnPayIn = record
Owner : TComponent;
DB_Handle : TISC_DB_HANDLE;
ID_STUD : int64;
BEG_CHECK : TDateTime;
END_CHECK : TDateTime;
DATE_PROV_CHECK : byte;
IS_DOC_GEN : byte;
IS_PROV_GEN : byte;
IS_SMET_GEN : byte;
NOFPROV : byte;
DIGNORDOCID : int64;
end;
type
TcnPayOut = record
SUMMA_ALL : Currency;
CNUPLSUM : Currency;
CNSUMDOC : Currency;
CNINSOST :Currency;
ID_SESSION : int64;
end;
type
TcnAnnulContractIn = record
Owner : TComponent;
DB_Handle : TISC_DB_HANDLE;
ID_DOG_ROOT : int64;
ID_DOG : int64;
ID_STUD : int64;
DATE_DISS : TDateTime;
ID_TYPE_DISS : int64;
ORDER_DATE : TDateTime;
ORDER_NUM : String;
COMMENT : String;
IS_COLLECT : integer;
// ID_DOG_DISS_IN : int64;
end;
type TcnParamsToAddContract = record
// идентификаторы
ID_DOG_STATUS : int64; // статус
ID_DEPARTMENT : int64; // факультет (подразделение)
ID_SPEC : int64; // специальность
ID_GROUP : int64; // группа
ID_FORM_STUD : int64; // форма обучения
ID_KAT_STUD : int64; // категория обучения
ID_NATIONAL : int64; // гражданство
KURS : Integer; // курс
DATE_BEG : TDateTime; // Дата начала обучения
DATE_END : TDateTime; // Дата конца обучения
ID_MAN : int64; // ?
end;
type TcnSimpleParamsAbiturient = class(TcnSimpleParams)
public
WorkMode : string; // 'simple', 'extra'
ActionMode : string; // 'add', 'edit'
cnParamsToAddContract : TcnParamsToAddContract;
cnParamsToPakage :TcnParamsToPakage;
end;
Type TcnView = class
public
ViewRX : TRxMemoryData;
end;
implementation
end.
|
unit uZeeBeTestGRPC;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Mask, JvExMask,
JvToolEdit, Vcl.StdCtrls, Vcl.Grids, Vcl.ComCtrls,
gateway_protocol.Proto,
uZeeBeClient;
type
TfrmZeeBeTestgRPC = class(TForm)
pnlZeeBeConnection: TPanel;
lbledtServer: TLabeledEdit;
lbledtPort: TLabeledEdit;
btnGetTopology: TButton;
pnlNsvBrowser: TPanel;
edtZeeBeURL: TEdit;
btnShowInDefaultBrowser: TButton;
pnlWorkFlow: TPanel;
edFileNameBPMN: TJvFilenameEdit;
btnDeployWorkFlow: TButton;
lbledtBPMNID: TLabeledEdit;
pnlWFInstance: TPanel;
spl1: TSplitter;
mmoLOG: TMemo;
pnlZeeBeGUI: TPanel;
spl2: TSplitter;
pnlWFITree: TPanel;
grpCase: TGroupBox;
lblCaseVar: TLabel;
btnStartNewCase: TButton;
lbledtCaseID: TLabeledEdit;
stgrdCaseVars: TStringGrid;
grpActivity: TGroupBox;
lbl1: TLabel;
btnActivateJob: TButton;
btnCompleteJob: TButton;
btnPublishMessage: TButton;
cbbJobName: TComboBox;
lbledtJobID: TLabeledEdit;
lbledtMessageKey: TLabeledEdit;
lbledtMessage: TLabeledEdit;
stgrdJobVars: TStringGrid;
chkAutoComplete: TCheckBox;
btnSetVariables: TButton;
lbledtWorkFlowId: TLabeledEdit;
tvWorkFlow: TTreeView;
procedure btnGetTopologyClick(Sender: TObject);
procedure btnShowInDefaultBrowserClick(Sender: TObject);
procedure btnDeployWorkFlowClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lbledtPortChange(Sender: TObject);
procedure lbledtServerChange(Sender: TObject);
procedure btnStartNewCaseClick(Sender: TObject);
procedure btnActivateJobClick(Sender: TObject);
procedure btnCompleteJobClick(Sender: TObject);
procedure btnPublishMessageClick(Sender: TObject);
procedure btnSetVariablesClick(Sender: TObject);
private
procedure WriteToMemo(const aText: string);
function GetVarsFromStrGrid(const aStrGrid: TStringGrid): String;
function GetWFTreeNodeByID(aKey: UInt64): TTreeNode;
function CurrWFInstance: UInt64;
procedure DeployWorkflow;
procedure StartNewCase;
procedure SetWFVariables(const aVars: String);
procedure GUIUpdateJob(aJobResponse: TActivatedJob);
procedure DoJob(JobInfo: TActivatedJob);
public
{ Public-Deklarationen }
end;
var
frmZeeBeTestgRPC: TfrmZeeBeTestgRPC;
implementation
uses
Winapi.ShellAPI,
Superobject;
{$R *.dfm}
procedure TfrmZeeBeTestgRPC.btnActivateJobClick(Sender: TObject);
var aJobName: string;
begin
WriteToMemo('Create Job...');
aJobName := cbbJobName.Text;
WriteToMemo(Format('JOB: %s',[aJobName]));
ZeeBeClient.ActivateJob(aJobName,DoJob,chkAutoComplete.Checked);
WriteToMemo('Create Job done.');
end;
procedure TfrmZeeBeTestgRPC.btnCompleteJobClick(Sender: TObject);
begin
WriteToMemo('Completing JOB...');
try
ZeeBeClient.CompleteJobRequest(StrToUInt64(lbledtJobID.Text));
except
on e: Exception do WriteToMemo('Error in CompleteJob: '+E.Message)
end;
WriteToMemo('Complete JOB done.');
end;
procedure TfrmZeeBeTestgRPC.btnDeployWorkFlowClick(Sender: TObject);
begin
WriteToMemo('Deploy Workflow...');
DeployWorkflow;
WriteToMemo('Deploy WF done');
end;
procedure TfrmZeeBeTestgRPC.btnGetTopologyClick(Sender: TObject);
var aStr: String;
begin
WriteToMemo('Get Topology...');
aSTR := ZeeBeClient.Topology;
WriteToMemo(aStr);
WriteToMemo('Topology DONE');
end;
procedure TfrmZeeBeTestgRPC.btnPublishMessageClick(Sender: TObject);
var aPMRequest: TPublishMessageRequest;
CaseNode, MsgNode: TTreeNode;
begin
WriteToMemo('Publishing message...');
try
ZeeBeClient.PublishMessage(
lbledtMessage.Text,
lbledtMessageKey.Text,
CurrWFInstance);
WriteToMemo(Format('MESSAGE: %s, Key: %s',[lbledtMessage.Text, lbledtMessageKey.Text]));
//Update WF-Tree
tvWorkFlow.Items.BeginUpdate;
CaseNode := GetWFTreeNodeByID(CurrWFInstance);
MsgNode := tvWorkFlow.Items.AddChild(CaseNode,'');
MsgNode.Text := Format('MESSAGE: %s, CorrelitionKey: %s)',
[lbledtMessageKey.Text, lbledtMessageKey.Text]);
MsgNode.Data := NIL;
tvWorkFlow.Items.EndUpdate;
tvWorkFlow.Items[0].Expand(true);
except
on E: Exception do
WriteToMemo('Error in PublishMessage: '+E.Message)
end;
WriteToMemo('Publishing message done.');
end;
procedure TfrmZeeBeTestgRPC.btnSetVariablesClick(Sender: TObject);
var aVars: string;
begin
WriteToMemo('Set variables...');
aVars := '{'+GetVarsFromStrGrid(stgrdJobVars)+'}';
SetWFVariables(aVars);
WriteToMemo('Set variables done.');
end;
procedure TfrmZeeBeTestgRPC.btnShowInDefaultBrowserClick(Sender: TObject);
var URL: string;
begin
URL := edtZeeBeURL.Text;
ShellExecute(0,'open',PChar(URL),nil,nil, SW_SHOWNORMAL);
end;
procedure TfrmZeeBeTestgRPC.btnStartNewCaseClick(Sender: TObject);
begin
WriteToMemo('Start new WF-Instance running...');
StartNewCase;
WriteToMemo('Start new WF-Instance done.');
end;
function TfrmZeeBeTestgRPC.CurrWFInstance: UInt64;
begin
Result := StrToUInt64(lbledtCaseID.Text);
end;
procedure TfrmZeeBeTestgRPC.DeployWorkflow;
var aStr, bpmnProcessId: string;
workflowKey: UInt64;
aNode: TTreeNode;
begin
aStr := ZeeBeClient.DeployWorkflow(edFileNameBPMN.FileName);
WriteToMemo(aStr);
if not Assigned(SO(aStr).A['workflows'].O[0])
then Begin
WriteToMemo('Response is empty in DeployWorkflow');
Exit;
end;
workflowKey := SO(aStr).A['workflows'].O[0].I['workflowKey'];
bpmnProcessId := SO(aStr).A['workflows'].O[0].S['bpmnProcessId'];
lbledtWorkFlowId.Text := workflowKey.ToString;
lbledtBPMNID.Text := bpmnProcessId;
tvWorkFlow.Items.BeginUpdate;
tvWorkFlow.Items.Clear;
aNode := tvWorkFlow.Items.AddChildFirst(nil,'');
aNode.Text := Format('BPMN ID: "%s" - #%d',
[bpmnProcessId,
workflowKey]);
aNode.Data := Pointer(workflowKey);
tvWorkFlow.Items.EndUpdate;
tvWorkFlow.Items[0].Expand(true);
btnStartNewCase.Enabled := true;
end;
procedure TfrmZeeBeTestgRPC.DoJob(JobInfo: TActivatedJob);
begin
GUIUpdateJob(JobInfo);
end;
procedure TfrmZeeBeTestgRPC.FormActivate(Sender: TObject);
begin
//Values for ZeeBe testcase "BPM Order-Process "
stgrdCaseVars.Cells[0,0] := 'Name';
stgrdCaseVars.Cells[1,0] := 'Value';
stgrdCaseVars.Cells[0,1] := 'orderId';
stgrdCaseVars.Cells[1,1] := '123456';
stgrdCaseVars.Cells[0,2] := 'orderValue';
stgrdCaseVars.Cells[1,2] := '199';
stgrdJobVars.Cells[0,0] := 'Name';
stgrdJobVars.Cells[1,0] := 'Value';
stgrdJobVars.Cells[0,1] := 'orderId';
stgrdJobVars.Cells[1,1] := '234567';
stgrdJobVars.Cells[0,2] := 'orderValue';
stgrdJobVars.Cells[1,2] := '50';
end;
procedure TfrmZeeBeTestgRPC.FormCreate(Sender: TObject);
begin
ZeeBeClient.Port := StrToIntDef(lbledtPort.Text,26500); {use port 58772 for testing with grpc-dump}
ZeeBeClient.Server := lbledtServer.Text;
end;
procedure TfrmZeeBeTestgRPC.lbledtPortChange(Sender: TObject);
begin
ZeeBeClient.Port := StrToIntDef(lbledtPort.Text,ZeeBeClient.Port);
end;
procedure TfrmZeeBeTestgRPC.lbledtServerChange(Sender: TObject);
begin
ZeeBeClient.Server := lbledtServer.Text;
end;
procedure TfrmZeeBeTestgRPC.SetWFVariables(const aVars: String);
var
aSVR: TSetVariablesRequest;
CaseNode, aNode: TTreeNode;
begin
try
ZeeBeClient.SetVariables(CurrWFInstance,aVars);
WriteToMemo(Format('SETVARIABLES: %s',[aVars]));
tvWorkFlow.Items.BeginUpdate;
CaseNode := GetWFTreeNodeByID(CurrWFInstance);
aNode := tvWorkFlow.Items.AddChild(CaseNode,'');
aNode.Text := Format('VARIABLES: %s)',[aVars]);
aNode.Data := NIL;
tvWorkFlow.Items.EndUpdate;
tvWorkFlow.Items[0].Expand(true);
except
on e: Exception do
WriteToMemo(Format('Exception in SetWFVariables: %s ', [e.Message]));
end;
end;
procedure TfrmZeeBeTestgRPC.StartNewCase;
var
aVars: string;
aWFInstanceID: UInt64;
aCaseNode: TTreeNode;
begin
try
aVars := '{' + GetVarsFromStrGrid(stgrdCaseVars) + '}';
aWFInstanceID := ZeeBeClient.StartCase(lbledtBPMNID.Text,aVars);
lbledtCaseID.Text := aWFInstanceID.ToString;
WriteToMemo(Format('New workflow instance (alias case): #%d ruinnig, CaseVars: %s', [aWFInstanceID, aVars]));
tvWorkFlow.Items.BeginUpdate;
aCaseNode := tvWorkFlow.Items.AddChildFirst(tvWorkFlow.TopItem, Format('WORK FLOW Instance: #%d', [aWFInstanceID]));
aCaseNode.Data := Pointer(aWFInstanceID);
tvWorkFlow.Items.EndUpdate;
except
on e: Exception do
WriteToMemo(Format('Exception in StartCase: %s ', [e.Message]));
end;
end;
procedure TfrmZeeBeTestgRPC.WriteToMemo(const aText: string);
begin
TThread.Queue(nil,
procedure
begin
mmoLog.Lines.Add(aText);
Application.ProcessMessages;
end);
end;
function TfrmZeeBeTestgRPC.GetVarsFromStrGrid (const aStrGrid: TStringGrid): String;
var
aVariables: string;
I: Integer;
begin
aVariables := '';
for I := 1 to aStrGrid.RowCount - 1
do begin
if aStrGrid.Cells[0, I] <> ''
then begin
if aVariables <> ''
then aVariables := aVariables + ',';
aVariables := aVariables + format('"%s": %s', //values enclosed in " "?
[aStrGrid.Cells[0, I], aStrGrid.Cells[1, I]]);
end;
end;
Result := aVariables;
end;
function TfrmZeeBeTestgRPC.GetWFTreeNodeByID(aKey: UInt64): TTreeNode;
var I: Integer;
begin
if Assigned(tvWorkFlow.Selected)
and( tvWorkFlow.Selected.Data = Pointer(aKey))
then Result := tvWorkFlow.Selected
else begin
Result := NIL;
for I := 0 to tvWorkFlow.Items.Count - 1 do
begin
if tvWorkFlow.Items[I].Data = Pointer(aKey) then
begin
Result := tvWorkFlow.Items[I];
tvWorkFlow.Selected := Result;
break;
end;
end;
if not Assigned(Result)
then begin
Result :=
tvWorkFlow.Items.Add(tvWorkFlow.Items[0],Format('UNKNOWN Instance: %d',[aKey]));
Result.Data := Pointer(aKey);
end;
end
end;
procedure TfrmZeeBeTestgRPC.GUIUpdateJob(aJobResponse: TActivatedJob);
var CaseNode, ActivityNode: TTreeNode;
begin
TThread.Queue(nil,
procedure
begin
try
lbledtJobID.Text := aJobResponse.Key.ToString;
WriteToMemo('JOB-RESPONSE:');
WriteToMemo(TSuperRttiContext.Create.AsJson<TActivatedJob>(aJobResponse).AsJSon());
//Update WF-Tree
tvWorkFlow.Items.BeginUpdate;
CaseNode := GetWFTreeNodeByID(aJobResponse.workflowInstanceKey);
ActivityNode := tvWorkFlow.Items.AddChild(CaseNode,'');
ActivityNode.Text := Format('JOB: %s Headers: %s, Variables: %s)',
[aJobResponse._type , aJobResponse.customHeaders, aJobResponse.variables]);
ActivityNode.Data := Pointer(aJobResponse.key);
tvWorkFlow.Items.EndUpdate;
tvWorkFlow.Items[0].Expand(true);
except
on e: Exception do
WriteToMemo(Format('Exception in DoJob: %s ', [e.Message]))
end;
end
);
end;
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils,
VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes,
Vcl.StdCtrls, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps;
type
TFrmMain = class(TForm)
Map: TTMSFNCMaps;
Log: TMemo;
procedure FormCreate(Sender: TObject);
procedure MapMapInitialized(Sender: TObject);
private
{ Private declarations }
procedure OnMapEvent( Sender: TObject; AEventData: TTMSFNCMapsEventData );
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
procedure TFrmMain.FormCreate(Sender: TObject);
begin
Log.Lines.Clear;
Map.OnMapClick := OnMapEvent;
Map.OnMapDblClick := OnMapEvent;
Map.OnMapMouseUp := OnMapEvent;
Map.OnMapMouseDown := OnMapEvent;
Map.OnMarkerMouseEnter := OnMapEvent;
Map.OnMarkerMouseLeave := OnMapEvent;
// not supported for OpenLayers
//Map.OnMapMouseEnter := OnMapEvent;
//Map.OnMapMouseLeave := OnMapEvent;
end;
procedure TFrmMain.MapMapInitialized(Sender: TObject);
begin
var lCoord := CreateCoordinate(51.43691667, 7.378277778);
Map.AddMarker(lCoord);
Map.SetCenterCoordinate(lCoord);
Map.SetZoomLevel(13);
end;
procedure TFrmMain.OnMapEvent(Sender: TObject;
AEventData: TTMSFNCMapsEventData);
begin
Log.Lines.Add(AEventData.EventName );
end;
end.
|
unit Configuracoes;
interface
type
TConfiguracoesServer = Class
private
FPortBD: String;
FPasswordBD: String;
FSenhaServ: String;
FHostBD: String;
FUsuarioBD: STring;
FUsuarioServ: String;
FPortaServ: String;
FCaminhoBD: String;
procedure SetCaminhoBD(const Value: String);
procedure SetHostBD(const Value: String);
procedure SetPasswordBD(const Value: String);
procedure SetPortaServ(const Value: String);
procedure SetPortBD(const Value: String);
procedure SetSenhaServ(const Value: String);
procedure SetUsuarioBD(const Value: STring);
procedure SetUsuarioServ(const Value: String);
public
property PortaServ : String read FPortaServ write SetPortaServ;
property UsuarioServ : String read FUsuarioServ write SetUsuarioServ;
property SenhaServ : String read FSenhaServ write SetSenhaServ;
property PortBD : String read FPortBD write SetPortBD;
property UsuarioBD : STring read FUsuarioBD write SetUsuarioBD;
property PasswordBD : String read FPasswordBD write SetPasswordBD;
property CaminhoBD : String read FCaminhoBD write SetCaminhoBD;
property HostBD : String read FHostBD write SetHostBD;
constructor Create;
End;
implementation
{ TConfiguracoesServer }
constructor TConfiguracoesServer.Create;
begin
end;
procedure TConfiguracoesServer.SetCaminhoBD(const Value: String);
begin
FCaminhoBD := Value;
end;
procedure TConfiguracoesServer.SetHostBD(const Value: String);
begin
FHostBD := Value;
end;
procedure TConfiguracoesServer.SetPasswordBD(const Value: String);
begin
FPasswordBD := Value;
end;
procedure TConfiguracoesServer.SetPortaServ(const Value: String);
begin
FPortaServ := Value;
end;
procedure TConfiguracoesServer.SetPortBD(const Value: String);
begin
FPortBD := Value;
end;
procedure TConfiguracoesServer.SetSenhaServ(const Value: String);
begin
FSenhaServ := Value;
end;
procedure TConfiguracoesServer.SetUsuarioBD(const Value: STring);
begin
FUsuarioBD := Value;
end;
procedure TConfiguracoesServer.SetUsuarioServ(const Value: String);
begin
FUsuarioServ := Value;
end;
end.
|
unit ibSHDependenciesFrm;
interface
uses
SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHComponentFrm,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ImgList, ComCtrls, ToolWin, VirtualTrees, Menus, Contnrs,
SynEdit, pSHSynEdit, ActnList, AppEvnts;
type
TibBTDependenciesForm = class(TibBTComponentForm)
ImageList1: TImageList;
Panel1: TPanel;
Panel2: TPanel;
pSHSynEdit1: TpSHSynEdit;
Splitter1: TSplitter;
Splitter2: TSplitter;
Panel5: TPanel;
ActionList1: TActionList;
actClear: TAction;
actExtractDependencies: TAction;
Tree: TVirtualStringTree;
actShowSource: TAction;
ApplicationEvents1: TApplicationEvents;
actRefreshDependencies: TAction;
actCheckDependencies: TAction;
procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
procedure Panel1Resize(Sender: TObject);
private
{ Private declarations }
FDependencies: TComponent;
FDDLGenerator: TComponent;
FUsesList: TObjectList;
function GetDependencies: IibSHDependencies;
function GetDDLGenerator: IibSHDDLGenerator;
{ Tree }
procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
procedure TreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
procedure TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
procedure TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
procedure TreePaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType);
procedure TreeIncrementalSearch(Sender: TBaseVirtualTree;
Node: PVirtualNode; const SearchText: WideString; var Result: Integer);
procedure TreeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure TreeDblClick(Sender: TObject);
procedure TreeGetPopupMenu(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; const P: TPoint;
var AskParent: Boolean; var PopupMenu: TPopupMenu);
procedure TreeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode;
Column: TColumnIndex; var Result: Integer);
procedure TreeFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
procedure SetTreeEvents(ATree: TVirtualStringTree);
procedure GutterDrawNotify(Sender: TObject; ALine: Integer; var ImageIndex: Integer);
function CreateUsesArea: TVirtualStringTree;
procedure InitUsesArea(const AClassIID: TGUID; const ACaption, AOwnerCaption: string; ATree: TVirtualStringTree);
// procedure ShowMessageWindow;
procedure HideMessageWindow;
procedure ShowSource;
procedure JumpToSource;
procedure ShowDependencies;
procedure ClearDependencies;
procedure ExtractDependencies;
procedure RefreshDependencies;
// procedure CheckDependencies;
protected
protected
{ ISHRunCommands }
function GetCanRun: Boolean; override;
function GetCanRefresh: Boolean; override;
procedure Run; override;
procedure Refresh; override;
function DoOnOptionsChanged: Boolean; override;
procedure DoOnIdle; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string); override;
destructor Destroy; override;
function InsertNew(const AClassIID: TGUID; const ACaption: string; AParent: PVirtualNode): PVirtualNode;
property Dependencies: IibSHDependencies read GetDependencies;
property DDLGenerator: IibSHDDLGenerator read GetDDLGenerator;
end;
TibBTDependenciesFormAction_ = 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;
TibBTDependenciesFormAction_Run = class(TibBTDependenciesFormAction_)
end;
TibBTDependenciesFormAction_Refresh = class(TibBTDependenciesFormAction_)
end;
var
ibBTDependenciesForm: TibBTDependenciesForm;
procedure Register;
implementation
uses
ibSHConsts, ibSHValues;
{$R *.dfm}
type
PTreeRec = ^TTreeRec;
TTreeRec = record
NormalText: string;
StaticText: string;
ClassIID: TGUID;
ImageIndex: Integer;
IsEmpty: Integer;
U: Integer; {0 None | 1 Used By| 2 Uses}
end;
var
NodeIDGenerator: Integer;
procedure Register;
begin
SHRegisterImage(TibBTDependenciesFormAction_Run.ClassName, 'Button_Run.bmp');
SHRegisterImage(TibBTDependenciesFormAction_Refresh.ClassName, 'Button_Refresh.bmp');
SHRegisterActions([
TibBTDependenciesFormAction_Run,
TibBTDependenciesFormAction_Refresh]);
end;
{ TibBTDependencesForm }
constructor TibBTDependenciesForm.Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string);
var
vComponentClass: TSHComponentClass;
begin
FUsesList := TObjectList.Create;
inherited Create(AOwner, AParent, AComponent, ACallString);
FocusedControl := Tree;
SetTreeEvents(Tree);
vComponentClass := Designer.GetComponent(IibSHDependencies);
if Assigned(vComponentClass) then FDependencies := vComponentClass.Create(nil);
vComponentClass := Designer.GetComponent(IibSHDDLGenerator);
if Assigned(vComponentClass) then FDDLGenerator := vComponentClass.Create(nil);
ClearDependencies;
Panel2.Height := Trunc(Self.Height * 5/9);
Editor := pSHSynEdit1;
Editor.OnGutterDraw := GutterDrawNotify;
Editor.GutterDrawer.ImageList := ImageList1;
Editor.GutterDrawer.Enabled := True;
RegisterEditors;
DoOnOptionsChanged;
HideMessageWindow;
// ShowMessageWindow;
end;
destructor TibBTDependenciesForm.Destroy;
begin
FUsesList.Free;
FDependencies.Free;
FDDLGenerator.Free;
inherited Destroy;
end;
function TibBTDependenciesForm.GetDependencies: IibSHDependencies;
begin
Supports(FDependencies, IibSHDependencies, Result);
end;
function TibBTDependenciesForm.GetDDLGenerator: IibSHDDLGenerator;
begin
Supports(FDDLGenerator, IibSHDDLGenerator, Result);
end;
function TibBTDependenciesForm.GetCanRun: Boolean;
begin
Result := Assigned(Tree.FocusedNode) and
Assigned(TVirtualStringTree(FUsesList[Tree.FocusedNode.Dummy]).FocusedNode) and
(TVirtualStringTree(FUsesList[Tree.FocusedNode.Dummy]).GetNodeLevel(TVirtualStringTree(FUsesList[Tree.FocusedNode.Dummy]).FocusedNode) > 1);
end;
function TibBTDependenciesForm.GetCanRefresh: Boolean;
begin
Result := True;
end;
procedure TibBTDependenciesForm.Run;
begin
ExtractDependencies;
end;
procedure TibBTDependenciesForm.Refresh;
begin
RefreshDependencies;
end;
function TibBTDependenciesForm.DoOnOptionsChanged: Boolean;
begin
Result := inherited DoOnOptionsChanged;
if Result then Editor.ReadOnly := True;
end;
procedure TibBTDependenciesForm.DoOnIdle;
begin
// actClear.Enabled := True;
// actExtractDependencies.Enabled := Assigned(Tree.FocusedNode) and
// Assigned(TVirtualStringTree(FUsesList[Tree.FocusedNode.Dummy]).FocusedNode) and
// (TVirtualStringTree(FUsesList[Tree.FocusedNode.Dummy]).GetNodeLevel(TVirtualStringTree(FUsesList[Tree.FocusedNode.Dummy]).FocusedNode) > 1);
end;
procedure TibBTDependenciesForm.SetTreeEvents(ATree: TVirtualStringTree);
begin
ATree.Images := Designer.ImageList;
ATree.OnGetNodeDataSize := TreeGetNodeDataSize;
ATree.OnFreeNode := TreeFreeNode;
ATree.OnGetImageIndex := TreeGetImageIndex;
ATree.OnGetText := TreeGetText;
ATree.OnPaintText := TreePaintText;
ATree.OnIncrementalSearch := TreeIncrementalSearch;
ATree.OnDblClick := TreeDblClick;
ATree.OnKeyDown := TreeKeyDown;
ATree.OnGetPopupMenu := TreeGetPopupMenu;
ATree.OnCompareNodes := TreeCompareNodes;
ATree.OnFocusChanged := TreeFocusChanged;
end;
procedure TibBTDependenciesForm.GutterDrawNotify(Sender: TObject; ALine: Integer;
var ImageIndex: Integer);
begin
if ALine = 0 then ImageIndex := 0;
end;
function TibBTDependenciesForm.CreateUsesArea: TVirtualStringTree;
begin
Result := TVirtualStringTree.Create(nil);
Result.BorderStyle := bsNone;
Result.Align := alClient;
Result.Tag := 1;
Result.Parent := Panel5;
Result.ButtonFillMode := fmShaded;
Result.HintAnimation := hatNone;
Result.HintMode := hmTooltip;
Result.IncrementalSearch := isAll;
Result.Indent := 12;
Result.ShowHint := True;
Result.TreeOptions.MiscOptions := [toAcceptOLEDrop, toFullRepaintOnResize, toGridExtensions, toInitOnSave, toWheelPanning];
Result.TreeOptions.PaintOptions := [toHideFocusRect, toHotTrack, toShowButtons, toShowDropmark, toShowRoot, toThemeAware, toUseBlendedImages, toUseBlendedSelection];
Result.TreeOptions.SelectionOptions := [toFullRowSelect, toRightClickSelect];
Result.TreeOptions.StringOptions := [toSaveCaptions, toShowStaticText, toAutoAcceptEditChange];
Result.Header.Options := [hoAutoResize, hoColumnResize, hoDrag, hoVisible];
Result.Header.Style := hsFlatButtons;
Result.Header.Columns.Add.Text := Format('%s', [STypeAndObjects]);
Result.Header.Font.Name := 'Tahoma';
Result.BringToFront;
SetTreeEvents(Result);
FUsesList.Add(Result);
end;
procedure TibBTDependenciesForm.InitUsesArea(const AClassIID: TGUID; const ACaption, AOwnerCaption: string; ATree: TVirtualStringTree);
var
ObjectList, FieldList: TStrings;
Node: PVirtualNode;
Node0, Node1: PVirtualNode;
NodeData: PTreeRec;
vU: Integer;
function DoInitNode(const AIID: TGUID; const AText: string; AParent: PVirtualNode): PVirtualNode;
begin
Result := ATree.AddChild(AParent);
NodeData := ATree.GetNodeData(Result);
NodeData.NormalText := AText;
NodeData.ClassIID := AIID;
NodeData.ImageIndex := Designer.GetImageIndex(AIID);
NodeData.IsEmpty := -1;
NodeData.U := vU;
end;
procedure DoInitObjects(const AIID: TGUID; AParent: PVirtualNode);
var
I, J: Integer;
begin
ObjectList.Assign(Dependencies.GetObjectNames(AIID));
if ObjectList.Count > 0 then
begin
Node0 := DoInitNode(AIID, Format('%s', [GUIDToName(AIID, 1)]), AParent);
for I := 0 to Pred(ObjectList.Count) do
begin
Node1 := DoInitNode(AIID, ObjectList[I], Node0);
FieldList.Assign(Dependencies.GetObjectNames(AIID, ObjectList[I]));
if FieldList.Count > 0 then
for J := 0 to Pred(FieldList.Count) do
DoInitNode(IibSHField, FieldList[J], Node1);
end;
end;
end;
begin
if not Assigned(Dependencies) then Exit;
if ATree.RootNodeCount <> 0 then
Exit;
ObjectList := TStringList.Create;
FieldList := TStringList.Create;
try
ATree.BeginUpdate;
vU := 1;
Dependencies.Execute(dtUsedBy, (Component as IibSHDBObject).BTCLDatabase, AClassIID, ACaption, AOwnerCaption);
if not Dependencies.IsEmpty then
begin
Node := DoInitNode(IUnknown, 'Used By', nil);
DoInitObjects(IibSHTable, Node);
DoInitObjects(IibSHConstraint, Node);
DoInitObjects(IibSHIndex, Node);
DoInitObjects(IibSHView, Node);
DoInitObjects(IibSHProcedure, Node);
DoInitObjects(IibSHTrigger, Node);
DoInitObjects(IibSHGenerator, Node);
DoInitObjects(IibSHException, Node);
DoInitObjects(IibSHFunction, Node);
DoInitObjects(IibSHFilter, Node);
if Node.ChildCount <> 0 then ATree.Expanded[Node] := True;
end;
vU := 2;
Dependencies.Execute(dtUses, (Component as IibSHDBObject).BTCLDatabase, AClassIID, ACaption,AOwnerCaption);
if not Dependencies.IsEmpty then
begin
Node := DoInitNode(IUnknown, 'Uses', nil);
DoInitObjects(IibSHDomain, Node);
DoInitObjects(IibSHTable, Node);
DoInitObjects(IibSHConstraint, Node);
DoInitObjects(IibSHIndex, Node);
DoInitObjects(IibSHView, Node);
DoInitObjects(IibSHProcedure, Node);
DoInitObjects(IibSHTrigger, Node);
DoInitObjects(IibSHGenerator, Node);
DoInitObjects(IibSHException, Node);
DoInitObjects(IibSHFunction, Node);
DoInitObjects(IibSHFilter, Node);
if Node.ChildCount <> 0 then ATree.Expanded[Node] := True;
end;
finally
ATree.EndUpdate;
ObjectList.Free;
FieldList.Free;
end;
Node := ATree.GetFirst;
if not Assigned(Node) then
begin
Node := ATree.AddChild(nil);
NodeData := ATree.GetNodeData(Node);
NodeData.NormalText := '< none >';
NodeData.ImageIndex := -1;
NodeData.IsEmpty := -1;
end;
if Assigned(Node) then
begin
ATree.FocusedNode := Node;
ATree.Selected[ATree.FocusedNode] := True;
ATree.Repaint;
ATree.Invalidate;
end;
end;
function TibBTDependenciesForm.InsertNew(const AClassIID: TGUID; const ACaption: string; AParent: PVirtualNode): PVirtualNode;
var
Node: PVirtualNode;
NodeData: PTreeRec;
begin
CreateUsesArea;
Node := Tree.AddChild(AParent);
Node.Dummy := NodeIDGenerator;
Inc(NodeIDGenerator);
NodeData := Tree.GetNodeData(Node);
NodeData.NormalText := ACaption;
NodeData.StaticText := EmptyStr;
NodeData.ClassIID := AClassIID;
NodeData.ImageIndex := Designer.GetImageIndex(AClassIID);
Result := Node;
if Assigned(AParent) then Node := Tree.GetFirst;
if Assigned(Node) then
begin
// if Assigned(AParent) and (AParent.ChildCount <> 0) then Tree.Expanded[AParent] := True;
Tree.FocusedNode := Node;
Tree.Selected[Tree.FocusedNode] := True;
end;
end;
//procedure TibBTDependenciesForm.ShowMessageWindow;
//begin
// Panel2.Visible := True;
// Splitter1.Visible := True;
//end;
procedure TibBTDependenciesForm.HideMessageWindow;
begin
Panel2.Visible := False;
Splitter1.Visible := False;
end;
procedure TibBTDependenciesForm.ShowSource;
var
Node: PVirtualNode;
NodeData: PTreeRec;
vTree: TVirtualStringTree;
vComponentClass: TSHComponentClass;
vComponent: TSHComponent;
vSource: string;
vDBObject: IibSHDBObject;
begin
Node := nil;
if Panel2.Visible then Node := Tree.FocusedNode;
if Assigned(Node) and not Tree.Focused and (FUsesList.Count > 0) then
vTree := TVirtualStringTree(FUsesList[Node.Dummy])
else
vTree := Tree;
if Assigned(Editor) then Editor.Lines.Clear;
if Assigned(vTree) then
begin
Node := vTree.FocusedNode;
NodeData := nil;
case vTree.Tag of
0:;
1: case vTree.GetNodeLevel(Node) of
2: NodeData := vTree.GetNodeData(Node);
3: NodeData := vTree.GetNodeData(Node.Parent);
end;
end;
if Assigned(NodeData) then
begin
vComponentClass := Designer.GetComponent(NodeData.ClassIID);
if Assigned(vComponentClass) then vComponent := vComponentClass.Create(nil);
if Assigned(vComponent) and Supports(vComponent, IibSHDBObject, vDBObject) then
begin
try
vDBObject.Caption := NodeData.NormalText;
vDBObject.OwnerIID := Component.OwnerIID;
vDBObject.State := csSource;
if Assigned(DDLGenerator) then vSource := DDLGenerator.GetDDLText(vDBObject);
finally
if Assigned(vDBObject) then vDBObject := nil;
FreeAndNil(vComponent);
end;
end;
if Assigned(Editor) then
begin
Editor.BeginUpdate;
Editor.Lines.Clear;
Editor.Lines.Text := vSource;
Editor.EndUpdate;
end;
end;
end;
end;
procedure TibBTDependenciesForm.JumpToSource;
var
Node: PVirtualNode;
NodeData: PTreeRec;
vTree: TVirtualStringTree;
begin
vTree := nil;
Node := Tree.FocusedNode;
if Assigned(Node) then vTree := TVirtualStringTree(FUsesList[Node.Dummy]);
if Assigned(vTree) then
begin
Node := vTree.FocusedNode;
NodeData := nil;
case vTree.GetNodeLevel(Node) of
2: NodeData := vTree.GetNodeData(Node);
3: NodeData := vTree.GetNodeData(Node.Parent);
end;
if Assigned(NodeData) then
Designer.JumpTo(Component.InstanceIID, NodeData.ClassIID, NodeData.NormalText);
end;
end;
procedure TibBTDependenciesForm.ShowDependencies;
var
Node: PVirtualNode;
NodeData, NodeDataOwner: PTreeRec;
vTree: TVirtualStringTree;
S: string;
begin
Node := Tree.FocusedNode;
NodeData := Tree.GetNodeData(Node);
vTree := nil;
if Assigned(Node) then vTree := TVirtualStringTree(FUsesList[Node.Dummy]);
if Assigned(NodeData) then
begin
if IsEqualGUID(NodeData.ClassIID, IibSHField) then
begin
NodeDataOwner := Tree.GetNodeData(Node.Parent);
S := NodeDataOwner.NormalText;
end;
try
Screen.Cursor := crHourGlass;
InitUsesArea(NodeData.ClassIID, NodeData.NormalText, S, vTree);
vTree.BringToFront;
finally
Screen.Cursor := crDefault;
end;
end;
end;
procedure TibBTDependenciesForm.ClearDependencies;
var
I: Integer;
begin
NodeIDGenerator := 0;
try
Panel5.Visible := False;
Tree.Clear;
FUsesList.Clear;
InsertNew(Component.ClassIID, Component.Caption, nil);
if Supports(Component, IibSHTable) then
for I := 0 to Pred((Component as IibSHTable).Fields.Count) do
InsertNew(IibSHField, (Component as IibSHTable).Fields[I], Tree.GetFirst);
finally
Panel5.Visible := True;
end;
ShowDependencies;
end;
procedure TibBTDependenciesForm.ExtractDependencies;
var
Node: PVirtualNode;
NodeData, NodeData2: PTreeRec;
vTree: TVirtualStringTree;
begin
vTree := nil;
Node := Tree.FocusedNode;
if Assigned(Node) then vTree := TVirtualStringTree(FUsesList[Node.Dummy]);
if Assigned(vTree) then
begin
Node := vTree.FocusedNode;
NodeData := nil;
case vTree.GetNodeLevel(Node) of
2: NodeData := vTree.GetNodeData(Node);
3: NodeData := vTree.GetNodeData(Node.Parent);
end;
if Assigned(NodeData) then
begin
Node := Tree.FocusedNode.FirstChild;
while Assigned(Node) do
begin
NodeData2 := Tree.GetNodeData(Node);
if IsEqualGUID(NodeData2.ClassIID, NodeData.ClassIID) and
(CompareStr(NodeData2.NormalText, NodeData.NormalText) = 0) then Break;
Node := Tree.GetNextSibling(Node);
end;
if not Assigned(Node) then
begin
Tree.Expanded[Tree.FocusedNode] := True;
Node := InsertNew(NodeData.ClassIID, NodeData.NormalText, Tree.FocusedNode);
NodeData2 := Tree.GetNodeData(Node);
NodeData2.U := NodeData.U;
end;
if Assigned(Node) then
begin
Tree.FocusedNode := Node;
Tree.Selected[Tree.FocusedNode] := True;
ShowDependencies;
end;
end;
end;
end;
procedure TibBTDependenciesForm.RefreshDependencies;
begin
TVirtualStringTree(FUsesList[Tree.FocusedNode.Dummy]).Clear;
ShowDependencies;
end;
(*
procedure TibBTDependenciesForm.CheckDependencies;
var
Node: PVirtualNode;
NodeData: PTreeRec;
vTree: TVirtualStringTree;
begin
vTree := nil;
try
Screen.Cursor := crHourGlass;
vTree := TVirtualStringTree(FUsesList[Tree.FocusedNode.Dummy]);
Node := vTree.GetFirst;
while Assigned(Node) do
begin
if vTree.GetNodeLevel(Node) = 2 then
begin
NodeData := vTree.GetNodeData(Node);
Dependencies.Execute(dtUsedBy, (Component as IibSHDBObject).BTCLDatabase, NodeData.ClassIID, NodeData.NormalText);
if Dependencies.IsEmpty then NodeData.IsEmpty := 1;
Dependencies.Execute(dtUses, (Component as IibSHDBObject).BTCLDatabase, NodeData.ClassIID, NodeData.NormalText);
if Dependencies.IsEmpty then NodeData.IsEmpty := 1;
end;
Node := vTree.GetNext(Node);
end;
finally
Screen.Cursor := crDefault;
if Assigned(vTree) then vTree.Invalidate;
end;
end;
*)
procedure TibBTDependenciesForm.ApplicationEvents1Idle(Sender: TObject;
var Done: Boolean);
begin
DoOnIdle;
end;
{ Tree }
procedure TibBTDependenciesForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
begin
NodeDataSize := SizeOf(TTreeRec);
end;
procedure TibBTDependenciesForm.TreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if Assigned(Data) then Finalize(Data^);
end;
procedure TibBTDependenciesForm.TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if (Kind = ikNormal) or (Kind = ikSelected) then ImageIndex := Data.ImageIndex;
end;
procedure TibBTDependenciesForm.TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
case TextType of
ttNormal: CellText := Data.NormalText;
ttStatic:
begin
if (Sender.Tag = 0) then
case Data.U of
0: CellText := '';
1: CellText := 'Used By';
2: CellText := 'Uses';
end;
if (Sender.Tag = 1) and (Node.ChildCount > 0) then CellText := Format('%d', [Node.ChildCount]);
end;
end;
end;
procedure TibBTDependenciesForm.TreePaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
case TextType of
ttNormal: if Sender.Focused and (vsSelected in Node.States) then
TargetCanvas.Font.Color := clWindow
else
if Data.IsEmpty = 1 then TargetCanvas.Font.Color := clGreen;
ttStatic: if Sender.Focused and (vsSelected in Node.States) then
TargetCanvas.Font.Color := clWindow
else
TargetCanvas.Font.Color := clGray;
end;
end;
procedure TibBTDependenciesForm.TreeIncrementalSearch(Sender: TBaseVirtualTree;
Node: PVirtualNode; const SearchText: WideString; var Result: Integer);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if Pos(AnsiUpperCase(SearchText), AnsiUpperCase(Data.NormalText)) <> 1 then
Result := 1;
end;
procedure TibBTDependenciesForm.TreeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
if TComponent(Sender).Tag = 1 then JumpToSource;
end;
procedure TibBTDependenciesForm.TreeDblClick(Sender: TObject);
var
HT: THitInfo;
P: TPoint;
begin
GetCursorPos(P);
P := Tree.ScreenToClient(P);
Tree.GetHitTestInfoAt(P.X, P.Y, True, HT);
if not (hiOnItemButton in HT.HitPositions) then
if TComponent(Sender).Tag = 1 then JumpToSource;
end;
procedure TibBTDependenciesForm.TreeGetPopupMenu(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; const P: TPoint;
var AskParent: Boolean; var PopupMenu: TPopupMenu);
var
HT: THitInfo;
Data: PTreeRec;
begin
if not Enabled then Exit;
PopupMenu := nil;
Data := Sender.GetNodeData(Sender.FocusedNode);
Sender.GetHitTestInfoAt(P.X, P.Y, True, HT);
if Assigned(Data) and (Sender.GetNodeLevel(Sender.FocusedNode) = 0) and (HT.HitNode = Sender.FocusedNode) and (hiOnItemLabel in HT.HitPositions) then
;
end;
procedure TibBTDependenciesForm.TreeCompareNodes(
Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode;
Column: TColumnIndex; var Result: Integer);
var
Data1, Data2: PTreeRec;
begin
Data1 := Sender.GetNodeData(Node1);
Data2 := Sender.GetNodeData(Node2);
Result := CompareStr(Data1.NormalText, Data2.NormalText);
end;
procedure TibBTDependenciesForm.TreeFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
begin
ShowDependencies;
ShowSource;
end;
procedure TibBTDependenciesForm.Panel1Resize(Sender: TObject);
begin
Tree.Width := Tree.Parent.ClientWidth div 2;
end;
{ TibBTDependenciesFormAction_ }
constructor TibBTDependenciesFormAction_.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallToolbar;
if Self is TibBTDependenciesFormAction_Run then Tag := 1;
if Self is TibBTDependenciesFormAction_Refresh then Tag := 2;
case Tag of
0: Caption := '-'; // separator
1:
begin
Caption := Format('%s', ['Run (Extract Dependencies)']);
ShortCut := TextToShortCut('Ctrl+Enter');
SecondaryShortCuts.Add('F9');
end;
2:
begin
Caption := Format('%s', ['Refresh']);
ShortCut := TextToShortCut('F5');
end;
end;
if Tag <> 0 then Hint := Caption;
end;
function TibBTDependenciesFormAction_.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHDomain) or
IsEqualGUID(AClassIID, IibSHTable) or
//IsEqualGUID(AClassIID, IibSHConstraint) or
//IsEqualGUID(AClassIID, IibSHIndex) or
IsEqualGUID(AClassIID, IibSHView) or
IsEqualGUID(AClassIID, IibSHProcedure) or
IsEqualGUID(AClassIID, IibSHTrigger) or
IsEqualGUID(AClassIID, IibSHGenerator) or
IsEqualGUID(AClassIID, IibSHException) or
IsEqualGUID(AClassIID, IibSHFunction) or
IsEqualGUID(AClassIID, IibSHFilter) or
//IsEqualGUID(AClassIID, IibSHRole) or
IsEqualGUID(AClassIID, IibSHSystemDomain) or
IsEqualGUID(AClassIID, IibSHSystemTable) or
IsEqualGUID(AClassIID, IibSHSystemTableTmp);
end;
procedure TibBTDependenciesFormAction_.EventExecute(Sender: TObject);
begin
case Tag of
// Run
1: (Designer.CurrentComponentForm as ISHRunCommands).Run;
// Refresh
2: (Designer.CurrentComponentForm as ISHRunCommands).Refresh;
end;
end;
procedure TibBTDependenciesFormAction_.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibBTDependenciesFormAction_.EventUpdate(Sender: TObject);
begin
if Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDependencies) then
begin
case Tag of
// Separator
0:
begin
Visible := True;
end;
// Run
1:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun;
end;
// Refresh
2:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRefresh;
end;
end;
end else
Visible := False;
end;
initialization
Register;
(*
if actShowSource.Checked then
begin
ShowMessageWindow;
ShowSource;
end else
HideMessageWindow;
*)
end.
|
//
// Generated by JavaToPas v1.5 20150830 - 104023
////////////////////////////////////////////////////////////////////////////////
unit android.print.PrinterCapabilitiesInfo_Builder;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.print.PrinterId,
android.print.PrintAttributes_MediaSize,
android.print.PrintAttributes_Resolution,
android.print.PrintAttributes_Margins,
android.print.PrinterCapabilitiesInfo;
type
JPrinterCapabilitiesInfo_Builder = interface;
JPrinterCapabilitiesInfo_BuilderClass = interface(JObjectClass)
['{79E8CA89-E7BA-4352-BE83-7BE0F32F0336}']
function addMediaSize(mediaSize : JPrintAttributes_MediaSize; isDefault : boolean) : JPrinterCapabilitiesInfo_Builder; cdecl;// (Landroid/print/PrintAttributes$MediaSize;Z)Landroid/print/PrinterCapabilitiesInfo$Builder; A: $1
function addResolution(resolution : JPrintAttributes_Resolution; isDefault : boolean) : JPrinterCapabilitiesInfo_Builder; cdecl;// (Landroid/print/PrintAttributes$Resolution;Z)Landroid/print/PrinterCapabilitiesInfo$Builder; A: $1
function build : JPrinterCapabilitiesInfo; cdecl; // ()Landroid/print/PrinterCapabilitiesInfo; A: $1
function init(printerId : JPrinterId) : JPrinterCapabilitiesInfo_Builder; cdecl;// (Landroid/print/PrinterId;)V A: $1
function setColorModes(colorModes : Integer; defaultColorMode : Integer) : JPrinterCapabilitiesInfo_Builder; cdecl;// (II)Landroid/print/PrinterCapabilitiesInfo$Builder; A: $1
function setMinMargins(margins : JPrintAttributes_Margins) : JPrinterCapabilitiesInfo_Builder; cdecl;// (Landroid/print/PrintAttributes$Margins;)Landroid/print/PrinterCapabilitiesInfo$Builder; A: $1
end;
[JavaSignature('android/print/PrinterCapabilitiesInfo_Builder')]
JPrinterCapabilitiesInfo_Builder = interface(JObject)
['{BF631100-CB12-4B6B-8A27-EB190D087DF2}']
function addMediaSize(mediaSize : JPrintAttributes_MediaSize; isDefault : boolean) : JPrinterCapabilitiesInfo_Builder; cdecl;// (Landroid/print/PrintAttributes$MediaSize;Z)Landroid/print/PrinterCapabilitiesInfo$Builder; A: $1
function addResolution(resolution : JPrintAttributes_Resolution; isDefault : boolean) : JPrinterCapabilitiesInfo_Builder; cdecl;// (Landroid/print/PrintAttributes$Resolution;Z)Landroid/print/PrinterCapabilitiesInfo$Builder; A: $1
function build : JPrinterCapabilitiesInfo; cdecl; // ()Landroid/print/PrinterCapabilitiesInfo; A: $1
function setColorModes(colorModes : Integer; defaultColorMode : Integer) : JPrinterCapabilitiesInfo_Builder; cdecl;// (II)Landroid/print/PrinterCapabilitiesInfo$Builder; A: $1
function setMinMargins(margins : JPrintAttributes_Margins) : JPrinterCapabilitiesInfo_Builder; cdecl;// (Landroid/print/PrintAttributes$Margins;)Landroid/print/PrinterCapabilitiesInfo$Builder; A: $1
end;
TJPrinterCapabilitiesInfo_Builder = class(TJavaGenericImport<JPrinterCapabilitiesInfo_BuilderClass, JPrinterCapabilitiesInfo_Builder>)
end;
implementation
end.
|
// -------------------------------------------------------------
// Este programa calcula as raizes de uma equação de segundo
// grau, segundo a conhecida formula de Baskara :~
// Autor : Luiz Reginaldo - Desenvolvedor do Pzim
// -------------------------------------------------------------
Program EquacaoSegundoGrau ;
var a, b, c : integer ;
delta, x1, x2 : real ;
Begin
writeln('Raizes da equacao ax^2 + bx + c = 0');
// Solicita os valores de a, b e c
write('Entre com o valor de a : ');
read( a );
write('Entre com o valor de b : ');
read( b );
write('Entre com o valor de c : ');
read( c );
// Calcula o valor de delta
delta := sqr(b) - 4*a*c ;
writeln('Delta = b^2 - 4ac') ;
writeln('O valor de delta = ', delta );
// Verifica se existem raizes reais
if( delta < 0 ) then
Begin
writeln('Porque delta e menor do que zero, nao existem raizes reais.');
End;
// Verifica se só tem uma raiz
if( delta = 0 ) then
Begin
writeln('Para delta = 0 so existe uma raiz real, x1') ;
writeln('Nesse caso x1 = -b/2a ');
x1 := -b / (2*a) ;
writeln('O valor de x1 = ', x1 );
End ;
// Verifica se existem duas raizes
if( delta > 0 ) then
Begin
writeln('Para delta > 0 existem duas raizes reais, x1 e x2') ;
writeln('Nesse caso x1 = (-b + raiz(delta)) / 2a ');
writeln('Nesse caso x1 = (-b - raiz(delta)) / 2a ');
x1 := (-b + sqrt(delta)) / (2*a) ;
x2 := (-b - sqrt(delta)) / (2*a) ;
writeln('O valor de x1 = ', x1 );
writeln('O valor de x2 = ', x2 );
End ;
End.
|
unit PerformanceTest;
interface
uses
DUnitX.TestFramework,
SysUtils,
// Classes,
Diagnostics,
uEnums,
TestHelper,
uIntXLibTypes,
uIntX;
type
[TestFixture]
TPerformanceTest = class(TObject)
var
Fint1, Fint2: TIntX;
public
[Test]
procedure Multiply128BitNumbers();
end;
implementation
[Test]
procedure TPerformanceTest.Multiply128BitNumbers();
var
temp1, temp2: TIntXLibUInt32Array;
StopWatch: TStopwatch;
// Writer: TStreamWriter;
begin
SetLength(temp1, 4);
temp1[0] := 47668;
temp1[1] := 58687;
temp1[2] := 223234234;
temp1[3] := 42424242;
SetLength(temp2, 4);
temp2[0] := 5674356;
temp2[1] := 34656476;
temp2[2] := 45667;
temp2[3] := 678645646;
Fint1 := TIntX.Create(temp1, False);
Fint2 := TIntX.Create(temp2, False);
StopWatch := TStopwatch.Create;
StopWatch.Start;
TTestHelper.Repeater(100000,
procedure
begin
TIntX.Multiply(Fint1, Fint2, TMultiplyMode.mmClassic);
end);
StopWatch.Stop();
System.WriteLn(Format('classic multiply operation took %d ms',
[StopWatch.ElapsedMilliseconds]));
{
// uncomment to save to file.
Writer := TStreamWriter.Create('timetaken.txt');
try
Writer.WriteLine(Format('classic multiply operation took %d ms',
[StopWatch.ElapsedMilliseconds]));
finally
Writer.Free;
end;
}
end;
initialization
TDUnitX.RegisterTestFixture(TPerformanceTest);
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Simple TGA formats supports for Delphi.
Currently supports only 24 and 32 bits RGB formats (uncompressed
and RLE compressed).
}
unit VXS.FileTGA;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
FMX.Graphics,
FMX.Types,
VXS.Graphics,
VXS.CrossPlatform;
type
{ TGA image load/save capable class for Delphi.
TGA formats supported : 24 and 32 bits uncompressed or RLE compressed,
saves only to uncompressed TGA. }
TTGAImage = class(TBitmap)
public
constructor Create; override;
destructor Destroy; override;
procedure LoadFromStream(stream: TStream); // in VCL override;
procedure SaveToStream(stream: TStream); // in VCL override;
end;
ETGAException = class(Exception)
end;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
type
TTGAHeader = packed record
IDLength: Byte;
ColorMapType: Byte;
ImageType: Byte;
ColorMapOrigin: Word;
ColorMapLength: Word;
ColorMapEntrySize: Byte;
XOrigin: Word;
YOrigin: Word;
Width: Word;
Height: Word;
PixelSize: Byte;
ImageDescriptor: Byte;
end;
procedure ReadAndUnPackRLETGA24(stream: TStream; destBuf: PAnsiChar;
totalSize: Integer);
type
TRGB24 = packed record
r, g, b: Byte;
end;
PRGB24 = ^TRGB24;
var
n: Integer;
color: TRGB24;
bufEnd: PAnsiChar;
b: Byte;
begin
bufEnd := @destBuf[totalSize];
while destBuf < bufEnd do
begin
stream.Read(b, 1);
if b >= 128 then
begin
// repetition packet
stream.Read(color, 3);
b := (b and 127) + 1;
while b > 0 do
begin
PRGB24(destBuf)^ := color;
Inc(destBuf, 3);
Dec(b);
end;
end
else
begin
n := ((b and 127) + 1) * 3;
stream.Read(destBuf^, n);
Inc(destBuf, n);
end;
end;
end;
procedure ReadAndUnPackRLETGA32(stream: TStream; destBuf: PAnsiChar;
totalSize: Integer);
type
TRGB32 = packed record
r, g, b, a: Byte;
end;
PRGB32 = ^TRGB32;
var
n: Integer;
color: TRGB32;
bufEnd: PAnsiChar;
b: Byte;
begin
bufEnd := @destBuf[totalSize];
while destBuf < bufEnd do
begin
stream.Read(b, 1);
if b >= 128 then
begin
// repetition packet
stream.Read(color, 4);
b := (b and 127) + 1;
while b > 0 do
begin
PRGB32(destBuf)^ := color;
Inc(destBuf, 4);
Dec(b);
end;
end
else
begin
n := ((b and 127) + 1) * 4;
stream.Read(destBuf^, n);
Inc(destBuf, n);
end;
end;
end;
// ------------------
// ------------------ TTGAImage ------------------
// ------------------
constructor TTGAImage.Create;
begin
inherited Create;
end;
destructor TTGAImage.Destroy;
begin
inherited Destroy;
end;
procedure TTGAImage.LoadFromStream(stream: TStream);
var
header: TTGAHeader;
y, rowSize, bufSize: Integer;
verticalFlip: Boolean;
unpackBuf: PAnsiChar;
function GetLineAddress(ALine: Integer): PByte;
begin
{ TODO : E2003 Undeclared identifier: 'ScanLine' }
(* Result := PByte(ScanLine[ALine]); *)
end;
begin
stream.Read(header, Sizeof(TTGAHeader));
if header.ColorMapType <> 0 then
raise ETGAException.Create('ColorMapped TGA unsupported');
{ TODO : E2129 Cannot assign to a read-only property }
(*
case header.PixelSize of
24 : PixelFormat:=TPixelFormat.RGBA; //in VCL glpf24bit;
32 : PixelFormat:=TPixelFormat.RGBA32F; //in VCL glpf32bit;
else
raise ETGAException.Create('Unsupported TGA ImageType');
end;
*)
Width := header.Width;
Height := header.Height;
rowSize := (Width * header.PixelSize) div 8;
verticalFlip := ((header.ImageDescriptor and $20) = 0);
if header.IDLength > 0 then
stream.Seek(header.IDLength, soFromCurrent);
try
case header.ImageType of
0:
begin // empty image, support is useless but easy ;)
Width := 0;
Height := 0;
Abort;
end;
2:
begin // uncompressed RGB/RGBA
if verticalFlip then
begin
for y := 0 to Height - 1 do
stream.Read(GetLineAddress(Height - y - 1)^, rowSize);
end
else
begin
for y := 0 to Height - 1 do
stream.Read(GetLineAddress(y)^, rowSize);
end;
end;
10:
begin // RLE encoded RGB/RGBA
bufSize := Height * rowSize;
unpackBuf := GetMemory(bufSize);
try
// read & unpack everything
if header.PixelSize = 24 then
ReadAndUnPackRLETGA24(stream, unpackBuf, bufSize)
else
ReadAndUnPackRLETGA32(stream, unpackBuf, bufSize);
// fillup bitmap
if verticalFlip then
begin
for y := 0 to Height - 1 do
begin
Move(unpackBuf[y * rowSize], GetLineAddress(Height - y - 1)
^, rowSize);
end;
end
else
begin
for y := 0 to Height - 1 do
Move(unpackBuf[y * rowSize], GetLineAddress(y)^, rowSize);
end;
finally
FreeMemory(unpackBuf);
end;
end;
else
raise ETGAException.Create('Unsupported TGA ImageType ' +
IntToStr(header.ImageType));
end;
finally
//
end;
end;
procedure TTGAImage.SaveToStream(stream: TStream);
var
y, rowSize: Integer;
header: TTGAHeader;
begin
// prepare the header, essentially made up from zeroes
FillChar(header, Sizeof(TTGAHeader), 0);
header.ImageType := 2;
header.Width := Width;
header.Height := Height;
case PixelFormat of
TPixelFormat.RGBA32F:
header.PixelSize := 32;
else
raise ETGAException.Create('Unsupported Bitmap format');
end;
stream.Write(header, Sizeof(TTGAHeader));
rowSize := (Width * header.PixelSize) div 8;
for y := 0 to Height - 1 do
{ TODO : E2003 Undeclared identifier: 'ScanLine' }
(* stream.Write(ScanLine[Height-y-1]^, rowSize); *)
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
{ TODO : E2003 Undeclared identifier: 'RegisterFileFormat' }
(* TPicture.RegisterFileFormat('tga', 'Targa', TTGAImage); *)
// ? RegisterRasterFormat('tga', 'Targa', TTGAImage);
finalization
{ TODO : E2003 Undeclared identifier: 'UNregisterFileFormat' }
(* TPicture.UnregisterGraphicClass(TTGAImage); *)
end.
|
Var
DocumentScope : Integer;
ParameterColor : TColor;
ParameterOffset : Integer;
ParameterName : String;
ParameterNameShow : Boolean;
AssignParamToPin : Boolean;
FormParamMaker : TFormParamMaker;
{..............................................................................}
{..............................................................................}
Procedure TFormParamMaker.FormParamMakerCreate(Sender: TObject);
Var
J : Integer;
Project : IProject;
Doc : IDocument;
FocussedDoc : IDocument;
CurrentSch : ISch_Document;
Begin
// Check if schematic server exists or not.
If SchServer = Nil Then Exit;
// Obtain the current schematic document interface.
CurrentSch := SchServer.GetCurrentSchDocument;
If CurrentSch = Nil Then Exit;
// do a compile so the logical documents get expanded into physical documents.
Project := GetWorkspace.DM_FocusedProject;
If Project = Nil Then Exit;
Project.DM_Compile;
// Populate the CheckListBoxDocuments control with physical document filenames
For J := 0 to Project.DM_PhysicalDocumentCount - 1 Do
Begin
Doc := Project.DM_PhysicalDocuments(J);
CheckListBoxDocuments.Items.Add(Doc.DM_FileName);
End;
ButtonClearAll.Enabled := False;
ButtonSelectAll.Enabled := False;
CheckListBoxDocuments.Enabled := False;
End;
{..............................................................................}
{..............................................................................}
Procedure TFormParamMaker.RadioGroupScopeClick(Sender: TObject);
Begin
If RadioGroupScope.ItemIndex <> 0 Then
Begin
// focussed document only
ButtonClearAll.Enabled := True;
ButtonSelectAll.Enabled := True;
CheckListBoxDocuments.Enabled := True
End
Else
Begin
// selected or all documents
ButtonClearAll.Enabled := False;
ButtonSelectAll.Enabled := False;
CheckListBoxDocuments.Enabled := False;
End;
End;
{..............................................................................}
{..............................................................................}
Procedure TFormParamMaker.XPBitBtnColorClick(Sender: TObject);
Begin
If ColorDialog1.Execute Then
ParameterColor := ColorDialog1.Color
Else
ParameterColor := clBlue;
ColorShape.Brush.Color := ParameterColor;
End;
{..............................................................................}
{..............................................................................}
Procedure TFormParamMaker.XPGenerateClick(Sender: TObject);
Var
I : Integer;
DocumentList : TStringList;
Begin
Try
DocumentList := TStringList.Create;
DocumentScope := RadioGroupScope.ItemIndex;
ParameterOffset := StrToInt(EditBoxOffset.Text);
ParameterName := EditParameterName.Text;
ParameterNameShow := False;
AssignParamToPin := False;
If CheckBoxParameterNameVisibility.State = cbChecked Then
ParameterNameShow := True;
If CheckBoxAssignParamToPin.State = cbChecked Then
AssignParamToPin := True;
If DocumentScope = 1 Then
Begin
For I := 0 to CheckListBoxDocuments.Items.Count -1 Do
Begin
If CheckListBoxDocuments.State[i] = cbChecked Then
DocumentList.Add(CheckListBoxDocuments.Items[i]);
End;
End;
FetchComponentNetInfo(DocumentScope, DocumentList, ParameterColor, ParameterOffset, ParameterName, ParameterNameShow, AssignParamToPin);
DocumentList.Free;
Finally
Close;
End;
End;
{..............................................................................}
{..............................................................................}
Procedure TFormParamMaker.ButtonClearAllClick(Sender: TObject);
Var
I : Integer;
Begin
// clear all toggled items
For i := 0 To CheckListBoxDocuments.Items.Count - 1 Do
CheckListBoxDocuments.State[i] := cbUnChecked;
End;
{..............................................................................}
{..............................................................................}
Procedure TFormParamMaker.ButtonSelectAllClick(Sender: TObject);
Var
I : Integer;
Begin
// select all items
For i := 0 To CheckListBoxDocuments.Items.Count - 1 Do
CheckListBoxDocuments.State[i] := cbChecked;
End;
{..............................................................................}
{..............................................................................}
Procedure TFormParamMaker.UpDownParameterOffsetClick(Sender: TObject; Button: TUDBtnType);
Begin
ParameterOffset := StrToInt(EditBoxOffset.Text);
End;
{..............................................................................}
{..............................................................................}
Procedure TFormParamMaker.CheckBoxAssignParamToPinClick(Sender: TObject);
Begin
//
End;
{..............................................................................}
{..............................................................................}
Procedure TFormParamMaker.XPCancelClick(Sender: TObject);
Begin
Close;
End;
{..............................................................................}
{..............................................................................}
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,Box,Ini,Common, StdCtrls, ExtCtrls,ModBusLoad,Clipbrd;
const
Colors : array [0.. 8] of Integer = (
clBtnFace,clRed,clFuchsia,clLime,clYellow,clTeal,clSilver,clWhite,clOlive
);
type
TMainForm = class(TForm)
Logs: TMemo;
Panel1: TPanel;
ClearLogBtn: TButton;
LogClear: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ClearLogBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Events : TStrings;
PointStart:Integer;
PointEnd:Integer;
Comm :string;
procedure InitC;
procedure AddLog(logContent:string);
procedure ShowData(Comm:string;MacAddress,Address,Value:Integer);
end;
var
MainForm: TMainForm;
PControl : TPControl;
implementation
{$R *.dfm}
procedure TMainForm.ClearLogBtnClick(Sender: TObject);
begin
Clipboard.AsText := Logs.Text;
Logs.Lines.Clear;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
WindowState := wsMaximized;
PControl := TPControl.Create(Application);
PControl.Parent := Self;
PControl.Width := Screen.Width;
PControl.Height := Screen.Monitors[0].Height - 300;
PControl.Left := 0;
PControl.Top := 0;
InitC;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
ModLoad.Free;
end;
procedure TMainForm.InitC;
var
HCount,SCount:Integer;
I,K,N :Integer;
GroupBox :TGroupBox;
Edit :TEdit;
IsSuccess :Boolean;
PCount : Integer;
begin
PointStart := StrToInt(Ini.ReadIni('server','pointStart'));
if PointStart < 1 then
begin
AddLog('最少从1开始..');
PointStart := 1;
end;
PointEnd := StrToInt(Ini.ReadIni('server','pointEnd'));
if PointEnd > 255 then
begin
AddLog('最多到255..');
PointEnd := 255;
end;
PCount := PointEnd - PointStart + 1;
Comm := Ini.ReadIni('server','com');
Events := TStringList.Create;
Events.LoadFromFile(ExtractFileDir(PARAMSTR(0)) + '\event.txt');
HCount := (PControl.Width - 20) div 138; //一行多少
SCount := (PCount + HCount - 1) div HCount; //多少行
for I := 0 to SCount - 1 do
begin
for K := 1 to HCount do
begin
N := (I * HCount) + K + PointStart - 1;
if N <= PointEnd then
begin
GroupBox := TGroupBox.Create(Self);
GroupBox.Parent := PControl;
GroupBox.Caption := InttoStr(N);
GroupBox.Width := 130;
GroupBox.Height := 50;
GroupBox.Left := 8 * K + 130 * (K - 1);
GroupBox.Top := 8 * (I + 1) + 50 * I;
GroupBox.Name := 'G' + GroupBox.Caption;
Edit := TEdit.Create(Self);
Edit.Parent := GroupBox;
Edit.Text := '无事件应答';
Edit.Left := 16;
Edit.Top := 16;
Edit.Width := 97;
Edit.Name := 'E' + InttoStr(N);
Edit.ReadOnly := True;
end;
end;
end;
ModLoad := TModLoad.Create('ModBusDll.dll',ShowData,IsSuccess);
if IsSuccess then
begin
AddLog('函数库加载完毕!');
//读取时间和超时次数在模拟时要调整大一些,模拟器随机数生成需要时间..
if ModLoad.Open(Comm,4800,0,3,0,PointStart,PointEnd,1,500,20) then
AddLog('串口打开成功!')
else
AddLog('串口打开失败!');
end;
end;
procedure TMainForm.AddLog(logContent:string);
begin
if (LogClear.Checked) and (Logs.Lines.Count >= 100) then
Logs.Lines.Clear;
Logs.Lines.Add(FormatDateTime('hh:mm:ss', now) + ' ' + logContent);
end;
procedure TMainForm.ShowData(Comm:string;MacAddress,Address,Value:Integer);
var
GroupBoxSrc :TControl;
Edit : TEdit;
begin
AddLog(Comm + '发生回调!');
GroupBoxSrc := PControl.FindChildControl('G' + InttoStr(Address));
if Assigned(GroupBoxSrc) then
begin
Edit := (GroupBoxSrc as TGroupBox).FindChildControl('E' + InttoStr(Address)) as TEdit;
if Value < 4 then
begin
(GroupBoxSrc as TGroupBox).Color := Colors[Value];
Edit.Text := Events[Value]
end
else
begin
(GroupBoxSrc as TGroupBox).Color := Colors[Value - 1];
Edit.Text := Events[Value - 1];
end;
end;
end;
end.
|
unit GLD3dsQuat;
interface
uses
Classes, GL, GLDTypes, GLDClasses, GLD3dsTypes;
type
TGLD3dsQuat = class(TGLDSysClass)
private
FA: GLfloat;
FB: GLfloat;
FC: GLfloat;
FD: GLfloat;
procedure SetA(Value: GLfloat);
procedure SetB(Value: GLfloat);
procedure SetC(Value: GLfloat);
procedure SetD(Value: GLfloat);
function GetQuat4f: TGLD3dsQuat4f;
procedure SetQuat4f(Value: TGLD3dsQuat4f);
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
property Quat4f: TGLD3dsQuat4f read GetQuat4f write SetQuat4f;
published
property A: GLfloat read FA write SetA;
property B: GLfloat read FB write SetB;
property C: GLfloat read FC write SetC;
property D: GLfloat read FD write SetD;
end;
procedure GLDX3DSQuatZero(var C: TGLD3dsQuat4f);
procedure GLDX3DSQuatIdentity(var C: TGLD3dsQuat4f);
procedure GLDX3DSQuatCopy(var Dest: TGLD3dsQuat4f; const Src: TGLD3dsQuat4f);
procedure GLDX3DSQuatAxisAngle(var C: TGLD3dsQuat4f; const Axis: TGLDVector3f; const Angle: GLfloat);
procedure GLDX3DSQuatNeg(var C: TGLD3dsQuat4f);
procedure GLDX3DSQuatAbs(var C: TGLD3dsQuat4f);
procedure GLDX3DSQuatCnj(var C: TGLD3dsQuat4f);
procedure GLDX3DSQuatMul(var C: TGLD3dsQuat4f; const A, B: TGLD3dsQuat4f);
procedure GLDX3DSQuatScalar(var C: TGLD3dsQuat4f; const K: GLfloat);
procedure GLDX3DSQuatNormalize(var C: TGLD3dsQuat4f);
procedure GLDX3DSQuatInv(var C: TGLD3dsQuat4f);
function GLDX3DSQuatDot(const A, B: TGLD3dsQuat4f): GLfloat;
function GLDX3DSQuatSquared(const C: TGLD3dsQuat4f): GLfloat;
function GLDX3DSQuatLength(const C: TGLD3dsQuat4f): GLfloat;
procedure GLDX3DSQuatLn(var C: TGLD3dsQuat4f);
procedure GLDX3DSQuatLnDif(var C: TGLD3dsQuat4f; const A, B: TGLD3dsQuat4f);
procedure GLDX3DSQuatExp(var C: TGLD3dsQuat4f);
procedure GLDX3DSQuatSlerp(var C: TGLD3dsQuat4f; const A, B: TGLD3dsQuat4f; const T: GLfloat);
procedure GLDX3DSQuatSquad(var C: TGLD3dsQuat4f; const A, P, Q, B: TGLD3dsQuat4f; T: GLfloat);
procedure GLDX3DSQuatTangent(var C: TGLD3dsQuat4f; const P, Q, N: TGLD3dsQuat4f);
implementation
uses
Math;
constructor TGLD3dsQuat.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
end;
destructor TGLD3dsQuat.Destroy;
begin
inherited Destroy;
end;
procedure TGLD3dsQuat.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLD3dsQuat) then Exit;
SetQuat4f(TGLD3dsQuat(Source).GetQuat4f);
end;
class function TGLD3dsQuat.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_3DS_QUAT;
end;
procedure TGLD3dsQuat.LoadFromStream(Stream: TStream);
begin
Stream.Read(FA, SizeOf(GLfloat));
Stream.Read(FB, SizeOf(GLfloat));
Stream.Read(FC, SizeOf(GLfloat));
Stream.Read(FD, SizeOf(GLfloat));
end;
procedure TGLD3dsQuat.SaveToStream(Stream: TStream);
begin
Stream.Write(FA, SizeOf(GLfloat));
Stream.Write(FB, SizeOf(GLfloat));
Stream.Write(FC, SizeOf(GLfloat));
Stream.Write(FD, SizeOf(GLfloat));
end;
procedure TGLD3dsQuat.SetA(Value: GLfloat);
begin
if FA = Value then Exit;
FA := Value;
Change;
end;
procedure TGLD3dsQuat.SetB(Value: GLfloat);
begin
if FB = Value then Exit;
FB := Value;
Change;
end;
procedure TGLD3dsQuat.SetC(Value: GLfloat);
begin
if FC = Value then Exit;
FC := Value;
Change;
end;
procedure TGLD3dsQuat.SetD(Value: GLfloat);
begin
if FD = Value then Exit;
FD := Value;
Change;
end;
function TGLD3dsQuat.GetQuat4f: TGLD3dsQuat4f;
begin
Result := GLDX3DSQuat4f(FA, FB, FC, FD);
end;
procedure TGLD3dsQuat.SetQuat4f(Value: TGLD3dsQuat4f);
begin
if GLDX3DSQuat4fEqual(GetQuat4f, Value) then Exit;
FA := Value[0];
FB := Value[1];
FC := Value[2];
FD := Value[3];
end;
procedure GLDX3DSQuatZero(var C: TGLD3dsQuat4f);
var
i: GLubyte;
begin
for i := 0 to 3 do C[i] := 0;
end;
procedure GLDX3DSQuatIdentity(var C: TGLD3dsQuat4f);
var
i: GLubyte;
begin
for i := 0 to 2 do C[i] := 0;
C[3] := 1;
end;
procedure GLDX3DSQuatCopy(var Dest: TGLD3dsQuat4f; const Src: TGLD3dsQuat4f);
var
i: GLubyte;
begin
for i := 0 to 3 do
Dest[i] := Src[i];
end;
procedure GLDX3DSQuatAxisAngle(var C: TGLD3dsQuat4f; const Axis: TGLDVector3f; const Angle: GLfloat);
var
Omega, S, L: GLdouble;
i: GLubyte;
begin
L := Sqrt(Axis.X * Axis.X + Axis.Y * Axis.Y + Axis.Z * Axis.Z);
if L < GLD3DS_EPSILON then
begin
for i := 0 to 2 do
C[i] := 0;
C[3] := 1;
end else
begin
Omega := -0.5 * Angle;
S := Sin(Omega) / L;
C[0] := S * Axis.X;
C[1] := S * Axis.Y;
C[2] := S * Axis.Z;
C[3] := Cos(Omega);
end;
end;
procedure GLDX3DSQuatNeg(var C: TGLD3dsQuat4f);
var
i: GLubyte;
begin
for i := 0 to 3 do
C[i] := -C[i];
end;
procedure GLDX3DSQuatAbs(var C: TGLD3dsQuat4f);
var
i: GLubyte;
begin
for i := 0 to 3 do
C[i] := Abs(C[i]);
end;
procedure GLDX3DSQuatCnj(var C: TGLD3dsQuat4f);
var
i: GLubyte;
begin
for i := 0 to 2 do
C[i] := -C[i];
end;
procedure GLDX3DSQuatMul(var C: TGLD3dsQuat4f; const A, B: TGLD3dsQuat4f);
begin
C[0] := A[3] * B[0] + A[0] * B[3] + A[1] * B[2] - A[2] * B[1];
C[1] := A[3] * B[1] + A[1] * B[3] + A[2] * B[0] - A[0] * B[2];
C[2] := A[3] * B[2] + A[2] * B[3] + A[0] * B[1] - A[1] * B[0];
C[3] := A[3] * B[3] - A[0] * B[0] - A[1] * B[1] - A[2] * B[2];
end;
procedure GLDX3DSQuatScalar(var C: TGLD3dsQuat4f; const K: GLfloat);
var
i: GLubyte;
begin
for i := 0 to 3 do
C[i] := C[i] * K;
end;
procedure GLDX3DSQuatNormalize(var C: TGLD3dsQuat4f);
var
L, M: GLdouble;
i: GLubyte;
begin
L := Sqrt(C[0] * C[0] + C[1] * C[1] + C[2] * C[2] + C[3] * C[3]);
if Abs(L)< GLD3DS_EPSILON then
begin
for i := 0 to 2 do
C[i] := 0;
C[3] := 1;
end else
begin
M := 1 / L;
for i := 0 to 3 do
C[i] := C[i] * M;
end;
end;
procedure GLDX3DSQuatInv(var C: TGLD3dsQuat4f);
var
L, M: GLdouble;
i: GLubyte;
begin
L := Sqrt(C[0] * C[0] + C[1] * C[1] + C[2] * C[2] + C[3] * C[3]);
if Abs(L) < GLD3DS_EPSILON then
begin
for i := 0 to 2 do
C[i] := 0;
C[3] := 1;
end else
begin
M := 1 / L;
C[0] := -C[0] * M;
C[1] := -C[1] * M;
C[2] := -C[2] * M;
C[3] := C[3] * M;
end;
end;
function GLDX3DSQuatDot(const A, B: TGLD3dsQuat4f): GLfloat;
begin
Result := A[0] * B[0] + A[1] * B[1] + A[2] * B[2] + A[3] * B[3];
end;
function GLDX3DSQuatSquared(const C: TGLD3dsQuat4f): GLfloat;
begin
Result := C[0] * C[0] + C[1] * C[1] + C[2] * C[2] + C[3] * C[3];
end;
function GLDX3DSQuatLength(const C: TGLD3dsQuat4f): GLfloat;
begin
Result := Sqrt(C[0] * C[0] + C[1] * C[1] + C[2] * C[2] + C[3] * C[3]);
end;
procedure GLDX3DSQuatLn(var C: TGLD3dsQuat4f);
var
Om, S, T: GLdouble;
i: GLubyte;
begin
S := Sqrt(C[0] * C[0] + C[1] * C[1] + C[2] * C[2]);
Om := ArcTan2(S, C[3]);
if Abs(S) < GLD3DS_EPSILON then
begin
T := 0;
end else
begin
T := Om / S;
end;
for i := 0 to 2 do
C[i] := C[i] * T;
C[3] := 0;
end;
procedure GLDX3DSQuatLnDif(var C: TGLD3dsQuat4f; const A, B: TGLD3dsQuat4f);
var
Invp: TGLD3dsQuat4f;
begin
GLDX3DSQuatCopy(Invp, A);
GLDX3DSQuatInv(Invp);
GLDX3DSQuatMul(C, Invp, B);
GLDX3DSQuatLn(C);
end;
procedure GLDX3DSQuatExp(var C: TGLD3dsQuat4f);
var
Om, Sinom: GLdouble;
i: GLubyte;
begin
Om := Sqrt(C[0] * C[0] + C[1] * C[1] + C[2] * C[2]);
if Abs(Om) < GLD3DS_EPSILON then
begin
Sinom := 1;
end else
begin
Sinom := Sin(Om) / Om;
end;
for i := 0 to 2 do
C[i] := C[i] * Sinom;
C[3] := Cos(Om);
end;
procedure GLDX3DSQuatSlerp(var C: TGLD3dsQuat4f; const A, B: TGLD3dsQuat4f; const T: GLfloat);
var
L, Om, Sinom, Sp, Sq: GLdouble;
Q: TGLD3dsQuat4f;
begin
L := A[0] * B[0] + A[1] * B[1] + A[2] * B[2] + A[3] * B[3];
if (1 + L) > GLD3DS_EPSILON then
begin
if Abs(L) > 1 then L := L / Abs(L);
Om := ArcCos(L);
Sinom := Sin(Om);
if Abs(Sinom) > GLD3DS_EPSILON then
begin
Sp := Sin((1 - T) * Om) / Sinom;
Sq := Sin(T * Om) / Sinom;
end else
begin
Sp := 1 - T;
Sq := T;
end;
C[0] := Sp * A[0] + Sq * B[0];
C[1] := Sp * A[1] + Sq * B[1];
C[2] := Sp * A[2] + Sq * B[2];
C[3] := Sp * A[3] + Sq * B[3];
end else
begin
Q[0] := -A[1];
Q[1] := A[0];
Q[2] := -A[3];
Q[3] := A[2];
Sp := Sin((1 - T) * GLD3DS_HALFPI);
Sq := Sin(T * GLD3DS_HALFPI);
C[0] := Sp * A[0] + Sq * Q[0];
C[1] := Sp * A[1] + Sq * Q[1];
C[2] := Sp * A[2] + Sq * Q[2];
C[3] := Sp * A[3] + Sq * Q[3];
end;
end;
procedure GLDX3DSQuatSquad(var C: TGLD3dsQuat4f; const A, P, Q, B: TGLD3dsQuat4f; T: GLfloat);
var
AB, PQ: TGLD3dsQuat4f;
begin
GLDX3DSQuatSlerp(AB, A, B, T);
GLDX3DSQuatSlerp(PQ, P, Q, T);
GLDX3DSQuatSlerp(C, AB, PQ, 2 * T * (1 - T));
end;
procedure GLDX3DSQuatTangent(var C: TGLD3dsQuat4f; const P, Q, N: TGLD3dsQuat4f);
var
Dn, Dp, X: TGLD3dsQuat4f;
i: GLubyte;
begin
GLDX3DSQuatLnDif(Dn, Q, N);
GLDX3DSQuatLnDif(Dp, Q, P);
for i := 0 to 3 do
X[i] := -1 / 4 * (Dn[i] + Dp[i]);
GLDX3DSQuatExp(X);
GLDX3DSQuatMul(C, Q, X);
end;
end.
|
//////////////////////////////////////////////////////////////////////////
// This file is a part of NotLimited.Framework.Common NuGet package.
// You are strongly discouraged from fiddling with it.
// If you do, all hell will break loose and living will envy the dead.
//////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace NotLimited.Framework.Common.Helpers
{
public class CollectionFilterDefinition<TItem, TParameter> : IComparer
{
private readonly TParameter _parameter;
public CollectionFilterDefinition(TParameter parameter)
{
_parameter = parameter;
}
public List<Func<TParameter, TItem, bool>> Filters { get; set; }
public Func<TParameter, TItem, TItem, int> Comparer { get; set; }
public static implicit operator Predicate<object>(CollectionFilterDefinition<TItem, TParameter> def)
{
return def.Filters == null ? (Predicate<object>)null : item => def.Filters.Any(filter => filter(def._parameter, (TItem)item));
}
public int Compare(object x, object y)
{
if (Comparer == null)
throw new InvalidOperationException("Comparer is not set");
return Comparer(_parameter, (TItem)x, (TItem)y);
}
}
} |
//
//TScrollPanel v1.0 - combines TPanel and TScrollBox capabilities
//Written by Andrew Anoshkin '1998
//
unit Dmitry.Controls.ScrollPanel;
interface
{$DEFINE A_D3} { Delphi 3.0 or higher }
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
ExtCtrls,
Themes,
Math;
type
TCustomScrollPanel = class(TScrollingWinControl)
private
//TCustomControl
FCanvas: TCanvas;
//TCustomPanel
FBevelInner: TPanelBevel;
FBevelOuter: TPanelBevel;
FBevelWidth: TBevelWidth;
FBorderWidth: TBorderWidth;
FBorderStyle: TBorderStyle;
FFullRepaint: Boolean;
FLocked: Boolean;
FOnResize: TNotifyEvent;
FAlignment: TAlignment;
FOnPaint: TNotifyEvent;
FDefaultDraw: boolean;
FBackGround: TBitmap;
FBackGroundTransparent: integer;
FOnReallign: TNotifyEvent;
FBackgroundLeft: integer;
FBackgroundTop: integer;
FUpdating: boolean;
procedure Erased(var Mes: TWMEraseBkgnd);message WM_ERASEBKGND;
//TCustomControl
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
//TCustomPanel
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED;
procedure CMIsToolControl(var Message: TMessage); message CM_ISTOOLCONTROL;
procedure WMWindowPosChanged(var Message: TWMWindowPosChanged); message WM_WINDOWPOSCHANGED;
procedure SetAlignment(Value: TAlignment);
procedure SetBevelInner(Value: TPanelBevel);
procedure SetBevelOuter(Value: TPanelBevel);
procedure SetBevelWidth(Value: TBevelWidth);
procedure SetBorderWidth(Value: TBorderWidth);
procedure SetBorderStyle(Value: TBorderStyle);
procedure SetOnPaint(const Value: TNotifyEvent);
procedure SetDefaultDraw(const Value: boolean);
procedure SetBackGround(const Value: TBitmap);
procedure SetBackGroundTransparent(const Value: integer);
procedure SetOnReallign(const Value: TNotifyEvent);
procedure SetBackgroundLeft(const Value: integer);
procedure SetBackgroundTop(const Value: integer);
procedure SetUpdating(const Value: boolean);
protected
//TCustomControl
procedure Paint; virtual;
procedure PaintWindow(DC: HDC); override;
property Canvas: TCanvas read FCanvas;
//TCustomPanel
procedure CreateParams(var Params: TCreateParams); override;
procedure AlignControls(AControl: TControl; var Rect: TRect); override;
procedure ResizePanel; dynamic;
//TCustomPanel
property Alignment: TAlignment read FAlignment write SetAlignment default taCenter;
property BevelInner: TPanelBevel read FBevelInner write SetBevelInner default bvNone;
property BevelOuter: TPanelBevel read FBevelOuter write SetBevelOuter default bvRaised;
property BevelWidth: TBevelWidth read FBevelWidth write SetBevelWidth default 1;
property BorderWidth: TBorderWidth read FBorderWidth write SetBorderWidth default 0;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsNone;
property Color default clBtnFace;
property FullRepaint: Boolean read FFullRepaint write FFullRepaint default True;
property Locked: Boolean read FLocked write FLocked default False;
property ParentColor default False;
property OnResize: TNotifyEvent read FOnResize write FOnResize;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
procedure GetBackGround(x,y,w,h : integer; var Bitmap : TBitmap);
//TScrollingWinControl
property AutoScroll;
property OnPaint : TNotifyEvent read FOnPaint write SetOnPaint;
property DefaultDraw : boolean read FDefaultDraw write SetDefaultDraw;
property BackGround : TBitmap read FBackGround Write SetBackGround;
property BackGroundTransparent : integer read FBackGroundTransparent Write SetBackGroundTransparent;
property OnReallign : TNotifyEvent read FOnReallign write SetOnReallign;
property BackgroundLeft : integer read FBackgroundLeft Write SetBackgroundLeft;
property BackgroundTop : integer read FBackgroundTop Write SetBackgroundTop;
property UpdatingPanel : boolean read FUpdating write SetUpdating;
end;
TScrollPanel = class(TCustomScrollPanel)
published
property Align;
property Alignment;
property BevelInner;
property BevelOuter;
property BevelWidth;
property BorderWidth;
property BorderStyle;
property DragCursor;
property DragMode;
property Enabled;
property FullRepaint;
property Caption;
property Canvas;
property Color;
property Ctl3D;
property Font;
property Locked;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDrag;
end;
procedure Register;
implementation
constructor TCustomScrollPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBackgroundLeft:=0;
FBackgroundTop:=0;
FUpdating:=false;
FBackGround:=TBitmap.create;
FBackGround.PixelFormat:=pf24bit;
FDefaultDraw:=true;
//TCustomControl
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
//TCustomPanel
ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents,
csSetCaption, csOpaque, csDoubleClicks, csReplicatable];
Width := 185;
Height := 41;
FAlignment := taCenter;
BevelOuter := bvRaised;
BevelWidth := 1;
FBorderStyle := bsNone;
Color := clBtnFace;
FFullRepaint := True;
end;
destructor TCustomScrollPanel.Destroy;
begin
FBackGround.free;
//TCustomControl
FCanvas.Free;
inherited Destroy;
end;
procedure TCustomScrollPanel.CreateParams(var Params: TCreateParams);
const
BorderStyles: array[TBorderStyle] of Longint = (0, WS_BORDER);
begin
inherited CreateParams(Params);
with Params do
begin
Style := Style or cardinal(BorderStyles[FBorderStyle]);
if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then
begin
Style := Style and not WS_BORDER;
ExStyle := ExStyle or WS_EX_CLIENTEDGE;
end;
WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW);
end;
end;
//
//From TCustomControl
//
procedure TCustomScrollPanel.WMPaint(var Message: TWMPaint);
begin
PaintHandler(Message);
end;
//
//From TCustomControl
//
procedure TCustomScrollPanel.PaintWindow(DC: HDC);
begin
{$IFDEF A_D3}
FCanvas.Lock;
{$ENDIF}
try
FCanvas.Handle := DC;
try
Paint;
finally
FCanvas.Handle := 0;
end;
finally
{$IFDEF A_D3}
FCanvas.Unlock;
{$ENDIF}
end;
end;
procedure TCustomScrollPanel.CMTextChanged(var Message: TMessage);
begin
Invalidate;
end;
procedure TCustomScrollPanel.CMCtl3DChanged(var Message: TMessage);
begin
if NewStyleControls and (FBorderStyle = bsSingle) then RecreateWnd;
inherited;
end;
procedure TCustomScrollPanel.CMIsToolControl(var Message: TMessage);
begin
if not FLocked then Message.Result := 1;
end;
procedure TCustomScrollPanel.ResizePanel;
begin
if Assigned(FOnResize) then FOnResize(Self);
end;
procedure TCustomScrollPanel.WMWindowPosChanged(var Message: TWMWindowPosChanged);
var
BevelPixels: Integer;
Rect, NewRect: TRect;
begin
if FullRepaint or (Caption <> '') then
Invalidate
else
begin
BevelPixels := BorderWidth;
if BevelInner <> bvNone then Inc(BevelPixels, BevelWidth);
if BevelOuter <> bvNone then Inc(BevelPixels, BevelWidth);
if BevelPixels > 0 then
begin
Rect.Right := Width;
Rect.Bottom := Height;
NewRect.Right := Message.WindowPos^.cx;
NewRect.Bottom := Message.WindowPos^.cy;
if Message.WindowPos^.cx <> Rect.Right then
begin
Rect.Top := 0;
Rect.Left := Rect.Right - BevelPixels - 1;
InvalidateRect(Handle, @Rect, True);
NewRect.Top := 0;
NewRect.Left := NewRect.Right - BevelPixels - 1;
InvalidateRect(Handle, @NewRect, True);
end;
if Message.WindowPos^.cy <> Rect.Bottom then
begin
Rect.Left := 0;
Rect.Top := Rect.Bottom - BevelPixels - 1;
InvalidateRect(Handle, @Rect, True);
NewRect.Left := 0;
NewRect.Top := NewRect.Bottom - BevelPixels - 1;
InvalidateRect(Handle, @NewRect, True);
end;
end;
end;
inherited;
if not (csLoading in ComponentState) then ResizePanel;
end;
procedure TCustomScrollPanel.AlignControls(AControl: TControl; var Rect: TRect);
var
BevelSize: Integer;
begin
if FUpdating then exit;
BevelSize := BorderWidth;
if BevelOuter <> bvNone then Inc(BevelSize, BevelWidth);
if BevelInner <> bvNone then Inc(BevelSize, BevelWidth);
InflateRect(Rect, -BevelSize, -BevelSize);
inherited AlignControls(AControl, Rect);
Invalidate;
if Assigned(FOnReallign) then FOnReallign(self);
end;
procedure TCustomScrollPanel.Paint;
var
Rect: TRect;
TopColor, BottomColor: TColor;
FontHeight: Integer;
const
Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER);
procedure AdjustColors(Bevel: TPanelBevel);
begin
TopColor := clBtnHighlight;
if Bevel = bvLowered then TopColor := clBtnShadow;
BottomColor := clBtnShadow;
if Bevel = bvLowered then BottomColor := clBtnHighlight;
end;
begin
if Assigned(FOnPaint) then FOnPaint(self);
if not DefaultDraw then exit;
Rect := GetClientRect;
if BevelOuter <> bvNone then
begin
AdjustColors(BevelOuter);
Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth);
end;
Frame3D(Canvas, Rect, Color, Color, BorderWidth);
if BevelInner <> bvNone then
begin
AdjustColors(BevelInner);
Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth);
end;
if StyleServices.Enabled then
Color := StyleServices.GetStyleColor(Themes.scPanel);
with Canvas do
begin
Brush.Color := Color;
FillRect(Rect);
Brush.Style := bsClear;
Font := Self.Font;
FontHeight := TextHeight('W');
with Rect do
begin
Top := ((Bottom + Top) - FontHeight) div 2;
Bottom := Top + FontHeight;
end;
Draw(FBackgroundLeft, FBackgroundTop, BackGround);
// Draw(Max(0,Width-BackGround.Width-5),Max(0,Height-BackGround.Height-2),BackGround);
//DrawText(Handle, PChar(Caption), -1, Rect, (DT_EXPANDTABS or
//DT_VCENTER) or Alignments[FAlignment]);
end;
end;
procedure TCustomScrollPanel.SetAlignment(Value: TAlignment);
begin
FAlignment := Value;
Invalidate;
end;
procedure TCustomScrollPanel.SetBevelInner(Value: TPanelBevel);
begin
FBevelInner := Value;
Realign;
Invalidate;
end;
procedure TCustomScrollPanel.SetBevelOuter(Value: TPanelBevel);
begin
FBevelOuter := Value;
Realign;
Invalidate;
end;
procedure TCustomScrollPanel.SetBevelWidth(Value: TBevelWidth);
begin
FBevelWidth := Value;
Realign;
Invalidate;
end;
procedure TCustomScrollPanel.SetBorderWidth(Value: TBorderWidth);
begin
FBorderWidth := Value;
Realign;
Invalidate;
end;
procedure TCustomScrollPanel.SetBorderStyle(Value: TBorderStyle);
begin
if FBorderStyle <> Value then
begin
FBorderStyle := Value;
RecreateWnd;
end;
end;
procedure TCustomScrollPanel.SetOnPaint(const Value: TNotifyEvent);
begin
FOnPaint := Value;
end;
procedure TCustomScrollPanel.SetDefaultDraw(const Value: boolean);
begin
FDefaultDraw := Value;
end;
procedure Register;
begin
RegisterComponents('AA', [TScrollPanel]);
end;
procedure TCustomScrollPanel.SetBackGround(const Value: TBitmap);
begin
FBackGround.Assign(Value);
Refresh;
end;
procedure TCustomScrollPanel.SetBackGroundTransparent(
const Value: integer);
begin
FBackGroundTransparent := Value;
Refresh;
end;
procedure TCustomScrollPanel.GetBackGround(X, Y, W, H: Integer; var Bitmap: TBitmap);
begin
Bitmap.Width := W;
Bitmap.Height := H;
if StyleServices.Enabled then
Color := StyleServices.GetStyleColor(Themes.scPanel);
Bitmap.Canvas.Brush.Color := Color;
Bitmap.Canvas.Pen.Color := Color;
Bitmap.Canvas.Rectangle(0, 0, W, H);
Bitmap.Canvas.Draw(-X + FBackgroundLeft, -Y + FBackgroundTop, FBackGround);
end;
procedure TCustomScrollPanel.SetOnReallign(const Value: TNotifyEvent);
begin
FOnReallign := Value;
end;
procedure TCustomScrollPanel.SetBackgroundLeft(const Value: integer);
begin
FBackgroundLeft := Value;
end;
procedure TCustomScrollPanel.SetBackgroundTop(const Value: integer);
begin
FBackgroundTop := Value;
end;
procedure TCustomScrollPanel.SetUpdating(const Value: boolean);
begin
FUpdating := Value;
end;
procedure TCustomScrollPanel.Erased(var Mes: TWMEraseBkgnd);
begin
Mes.Result := 1;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
GLScene,
GLObjects,
GLCadencer,
GLTexture,
GLWin32Viewer,
GLGeomObjects,
GLMaterial,
GLCoordinates,
GLCrossPlatform,
GLBaseClasses,
GLRenderContextInfo,
//
TerrainEngine;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLMaterialLibrary1: TGLMaterialLibrary;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
GLDummyCube1: TGLDummyCube;
GLDirectOpenGL1: TGLDirectOpenGL;
GLCone1: TGLCone;
procedure FormDestroy(Sender: TObject);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure FormCreate(Sender: TObject);
procedure GLDirectOpenGL1Render(Sender: TObject; var rci: TGLRenderContextInfo);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
private
FTerrain: TTerrain;
GPoint: TPoint;
FBrush: TTerrainBrush;
FModifier: TTerrainHeightModifier;
procedure UpdateCursor;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
GLSceneViewer1.Align:= alClient;
GLSceneViewer1.Cursor:= crNone;
FTerrain:= TTerrain.Create('debug.bmp', 0.05, 0.5);
GPoint.X:= FTerrain.Data.XDim div 2;
GPoint.Y:= FTerrain.Data.YDim div 2;
UpdateCursor;
FBrush:= TSmoothCircularBrush.Create;
FModifier:= TElevateModifier.Create(FTerrain.Data);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FBrush.Free;
FModifier.Free;
FTerrain.Free;
end;
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta/120));
end;
procedure TForm1.GLDirectOpenGL1Render(Sender: TObject; var rci: TGLRenderContextInfo);
begin
GLMaterialLibrary1.ApplyMaterial('TerrainMat', rci);
FTerrain.Render;
GLMaterialLibrary1.UnApplyMaterial(rci);
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
GPoint.X:= round(((X / ClientWidth - 0.2) * 1.5) * FTerrain.Data.XDim);
GPoint.Y:= round(((Y / ClientHeight - 0.2) * 1.5) * FTerrain.Data.YDim);
UpdateCursor;
if ssLeft in Shift then
begin
// increase elevation
FModifier.Modify(GPoint.X, GPoint.Y, FBrush, 0.1);
FTerrain.Data.CalculateNormals;
end
else if ssRight in Shift then
begin
// decrease elevation
FModifier.Modify(GPoint.X, GPoint.Y, FBrush, -0.1);
FTerrain.Data.CalculateNormals;
end;
end;
procedure TForm1.UpdateCursor;
begin
GLCone1.Position.AsAffineVector:= FTerrain.GridPointPosition(GPoint.X, GPoint.Y);
GLCone1.Position.Y:= GLCone1.Position.Y + GLCone1.Height / 2;
end;
end.
|
unit Main;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, Menus,
StdCtrls, Dialogs, Buttons, Messages, ExtCtrls;
type
TMainForm = class(TForm)
MainMenu1: TMainMenu;
Panel1: TPanel;
StatusLine: TPanel;
File1: TMenuItem;
FileOpenItem: TMenuItem;
Panel2: TPanel;
FileCloseItem: TMenuItem;
Window1: TMenuItem;
Help1: TMenuItem;
Line3: TMenuItem;
FileExitItem: TMenuItem;
WindowCascadeItem: TMenuItem;
WindowTileItem: TMenuItem;
WindowArrangeItem: TMenuItem;
HelpAboutItem: TMenuItem;
OpenDialog: TOpenDialog;
WindowMinimizeItem: TMenuItem;
SpeedPanel: TPanel;
OpenBtn: TSpeedButton;
ExitBtn: TSpeedButton;
CloseBtn: TSpeedButton;
Line1: TMenuItem;
FileExportReport: TMenuItem;
Line2: TMenuItem;
FilePrintReport: TMenuItem;
PrintUsingDefault: TMenuItem;
PrintSpecificPrinter: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure WindowCascadeItemClick(Sender: TObject);
procedure UpdateMenuItems(Sender: TObject);
procedure WindowTileItemClick(Sender: TObject);
procedure WindowArrangeItemClick(Sender: TObject);
procedure FileCloseItemClick(Sender: TObject);
procedure FileOpenItemClick(Sender: TObject);
procedure FileExitItemClick(Sender: TObject);
procedure WindowMinimizeItemClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure HelpAboutItemClick(Sender: TObject);
procedure FileExportReportClick(Sender: TObject);
procedure PrintUsingDefaultClick(Sender: TObject);
procedure PrintSpecificPrinterClick(Sender: TObject);
private
{ Private declarations }
procedure CreateMDIChild(const Name: string);
procedure ShowHint(Sender: TObject);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
uses ChildWin, About, ExportTo, PrintTo;
procedure TMainForm.FormCreate(Sender: TObject);
begin
Application.OnHint := ShowHint;
Screen.OnActiveFormChange := UpdateMenuItems;
end;
procedure TMainForm.ShowHint(Sender: TObject);
begin
StatusLine.Caption := Application.Hint;
end;
procedure TMainForm.CreateMDIChild(const Name: string);
var
Child: TMDIChild;
begin
{ create a new MDI child window }
Child := TMDIChild.Create(Application);
Child.Caption := Name;
end;
procedure TMainForm.FileOpenItemClick(Sender: TObject);
begin
if OpenDialog.Execute then
begin
Refresh;
CreateMDIChild(OpenDialog.FileName);
end;
end;
procedure TMainForm.FileCloseItemClick(Sender: TObject);
begin
if ActiveMDIChild <> nil then
ActiveMDIChild.Close;
end;
procedure TMainForm.FileExitItemClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.WindowCascadeItemClick(Sender: TObject);
begin
Cascade;
end;
procedure TMainForm.WindowTileItemClick(Sender: TObject);
begin
Tile;
end;
procedure TMainForm.WindowArrangeItemClick(Sender: TObject);
begin
ArrangeIcons;
end;
procedure TMainForm.WindowMinimizeItemClick(Sender: TObject);
var
I: Integer;
begin
{ Must be done backwards through the MDIChildren array }
for I := MDIChildCount - 1 downto 0 do
MDIChildren[I].WindowState := wsMinimized;
end;
procedure TMainForm.UpdateMenuItems(Sender: TObject);
begin
FileCloseItem.Enabled := MDIChildCount > 0;
WindowCascadeItem.Enabled := MDIChildCount > 0;
WindowTileItem.Enabled := MDIChildCount > 0;
WindowArrangeItem.Enabled := MDIChildCount > 0;
WindowMinimizeItem.Enabled := MDIChildCount > 0;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
Screen.OnActiveFormChange := nil;
end;
procedure TMainForm.HelpAboutItemClick(Sender: TObject);
var
About : TAboutBox;
begin
About := TAboutBox.Create(Self);
About.Show;
end;
procedure TMainForm.FileExportReportClick(Sender: TObject);
var
ExportForm : TExportForm;
begin
ExportForm := TExportForm.Create(Self);
ExportForm.ShowModal;
end;
procedure TMainForm.PrintUsingDefaultClick(Sender: TObject);
var
PrintForm : TPrinterForm;
begin
PrintForm := TPrinterForm.Create(Self);
PrintForm.Crpe1.Execute;
while not PrintForm.Crpe1.PrintEnded do
Application.ProcessMessages;
PrintForm.Close;
end;
procedure TMainForm.PrintSpecificPrinterClick(Sender: TObject);
var
PrintForm : TPrinterForm;
begin
PrintForm := TPrinterForm.Create(Self);
PrintForm.ShowModal;
end;
end.
|
//------------------------------------------------------------------------------
//FriendQueries UNIT
//------------------------------------------------------------------------------
// What it does-
// Friend related database routines
//
// Changes -
// February 12th, 2008
//
//------------------------------------------------------------------------------
unit FriendQueries;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
{Project}
Character,
QueryBase,
BeingList,
{3rd Party}
ZSqlUpdate
;
type
//------------------------------------------------------------------------------
//TFriendQueries CLASS
//------------------------------------------------------------------------------
TFriendQueries = class(TQueryBase)
protected
public
procedure LoadList(
const ACharacterList : TBeingList;
const ACharacter : TCharacter
);
procedure Delete(
const ReqID : LongWord;
const CharID : LongWord
);
procedure Add(
const OrigID : LongWord;
const CharID : LongWord
);
function IsFriend(
const CharID : LongWord;
const TargetID : LongWord
):Boolean;
end;
//------------------------------------------------------------------------------
implementation
uses
{RTL/VCL}
SysUtils,
Types,
{Project}
{3rd Party}
ZDataset,
DB
//none
;
//------------------------------------------------------------------------------
//LoadList PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Loads a character's friends
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
procedure TFriendQueries.LoadList(
const ACharacterList : TBeingList;
const ACharacter : TCharacter
);
const
GetFriendListQuery =
'SELECT `contacter_id`, `contactee_id` FROM characterfriendships '+
'WHERE contacter_id=:ID OR contactee_id=:ID;';
GetCharacterQuery =
'SELECT `account_id`, `name`, `last_map` FROM characters WHERE id=:FriendID;';
var
ADataSet : TZQuery;
ADataSet2 : TZQuery;
AParam : TParam;
AFriend : TCharacter;
begin
ADataSet := TZQuery.Create(nil);
ADataSet2 := TZQuery.Create(nil);
try
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := ACharacter.ID;
ADataSet.Params.AddParam(
AParam
);
Query(ADataSet, GetFriendListQuery);
ADataset.First;
while NOT ADataSet.Eof do
begin
AFriend := TCharacter.Create(ACharacter.ClientInfo);
if LongWord(ADataSet.Fields[0].AsInteger) = ACharacter.ID then
begin
AFriend.ID := ADataSet.Fields[1].AsInteger;
end else
begin
AFriend.ID := ADataSet.Fields[0].AsInteger;
end;
//FriendID
AParam := ADataset2.Params.CreateParam(ftInteger, 'FriendID', ptInput);
AParam.AsInteger := AFriend.ID;
ADataSet2.Params.AddParam(
AParam
);
Query(ADataSet2, GetCharacterQuery);
ADataset2.First;
if NOT ADataSet2.Eof then
begin
AFriend.AccountID := ADataSet2.Fields[0].AsInteger;
AFriend.Name := ADataSet2.Fields[1].AsString;
AFriend.Map := ADataSet2.Fields[2].AsString;
ACharacterList.Add(AFriend);
end else
begin
AFriend.Free;
end;
ADataSet2.Params.Clear;
ADataSet2.EmptyDataSet;
ADataSet.Next;
end;
finally
ADataSet.Free;
ADataSet2.Free;
end;
end;//LoadList
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Delete PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Deletes a friend
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
procedure TFriendQueries.Delete(
const ReqID : LongWord;
const CharID : LongWord
);
const
AQuery =
'DELETE FROM characterfriendships WHERE '+
'(contacter_id=:ID AND contactee_id=:OtherID) OR '+
'(contacter_id=:OtherID AND contactee_id=:ID);';
var
ADataSet : TZQuery;
AParam : TParam;
begin
ADataSet := TZQuery.Create(nil);
try
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := CharID;
ADataSet.Params.AddParam(
AParam
);
//OtherID
AParam := ADataset.Params.CreateParam(ftInteger, 'OtherID', ptInput);
AParam.AsInteger := ReqID;
ADataSet.Params.AddParam(
AParam
);
QueryNoResult(ADataSet, AQuery);
finally
ADataSet.Free;
end;
end;//Delete
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Add PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Add a friend
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
procedure TFriendQueries.Add(
const OrigID : LongWord;
const CharID : LongWord
);
const
AQuery =
'INSERT INTO characterfriendships '+
'(contacter_id, contactee_id) '+
'VALUES (:ID, :OtherID);';
var
ADataSet : TZQuery;
AParam : TParam;
begin
ADataSet := TZQuery.Create(nil);
try
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := OrigID;
ADataSet.Params.AddParam(
AParam
);
//OtherID
AParam := ADataset.Params.CreateParam(ftInteger, 'OtherID', ptInput);
AParam.AsInteger := CharID;
ADataSet.Params.AddParam(
AParam
);
QueryNoResult(ADataSet, AQuery);
finally
ADataSet.Free;
end;
end;//Add
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//IsFriend FUNCTION
//------------------------------------------------------------------------------
// What it does-
// checks to see if 2 char ids are friends
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
function TFriendQueries.IsFriend(
const CharID : LongWord;
const TargetID : LongWord
) : Boolean;
const
AQuery =
'SELECT contacter_id, contactee_id FROM characterfriendships WHERE '+
'(contacter_id=:ID AND contactee_id=:OtherID) OR '+
'(contacter_id=:OtherID AND contactee_id=:ID);';
var
ADataSet : TZQuery;
AParam : TParam;
begin
Result := FALSE;
ADataSet := TZQuery.Create(nil);
try
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := CharID;
ADataSet.Params.AddParam(
AParam
);
//OtherID
AParam := ADataset.Params.CreateParam(ftInteger, 'OtherID', ptInput);
AParam.AsInteger := TargetID;
ADataSet.Params.AddParam(
AParam
);
Query(ADataSet, AQuery);
ADataset.First;
if NOT ADataSet.Eof then
begin
Result := TRUE;
end;
finally
ADataSet.Free;
end;
end;//Add
//------------------------------------------------------------------------------
end.
|
unit uHTMLBuilder;
interface
uses
Classes, Contnrs, SysUtils, DB;
type
THTMLBase = class
end;
THTMLCell = class
private
Fstyle: string;
FName: string;
FItemList: TObjectList;
procedure Initialize(cellName:string = ''; cellStyle: string = '');
protected
public
property Style: string read FStyle write FStyle;
property Name: string read FName write FName;
property ItemList: TObjectList read FItemList write FItemList;
function Build: string;
constructor Create;overload;
constructor Create(cellName, cellStyle: string);overload;
destructor Destroy; override;
end;
TAfterAddRow = procedure (
Table: THTMLBase;
DataSet: TDataSet
) of object;
THTMLItem = class
private
FHtml: TStringList;
protected
public
property HTML: TStringList read FHtml write FHtml;
function Build: string;
constructor Create(itemHtml: string = '');
destructor Destroy;override;
end;
THTMLParagraph = class
private
Fstyle: string;
FName: string;
FItemList: TObjectList;
procedure Initialize(paragraphName:string = ''; style: string = '');
protected
public
property Style: string read FStyle write FStyle;
property Name: string read FName write FName;
property ItemList: TObjectList read FItemList write FItemList;
function Build: string;
constructor Create;overload;
constructor Create(paragraphName, style: string);overload;
destructor Destroy;override;
end;
THTMLRow = class
private
Fstyle: string;
FName: string;
FCellList: TObjectList;
procedure Initialize(rowCellList: array of THTMLCell; rowStyle: string = '');
protected
public
property Style: string read FStyle write FStyle;
property Name: string read FName write FName;
property CellList: TObjectList read FCellList write FCellList;
function Build: string;
function AddCell(cellName,cellStyle:string): THTMLCell;
constructor Create;overload;
constructor Create(rowCellList: array of THTMLCell);overload;
constructor Create(rowCellList: array of THTMLCell; rowStyle: string);overload;
destructor Destroy;override;
end;
THTMLTable = class(THTMLBase)
private
FRowList: TObjectList;
Fstyle: string;
protected
public
property Style: string read FStyle write FStyle;
property RowList: TObjectList read FRowList write FRowList;
function AddRow ( cellList: array of THTMLCell; rowStyle: string ): THTMLRow;overload;
function AddRow ( rowName, rowStyle: string ): THTMLRow;overload;
function AddEmptyRow(rowStyle:string = '') : THTMLRow;
function Build:string;
procedure SetDataSet(dataSet: TDataSet;
HeaderColor: string = '';
EvenColor: string = '';
OddColor: string = '';
EmptyValue: string = '';
AfterAddRow: TAfterAddRow = nil);
constructor Create(tableStyle: string = '');
destructor Destroy;override;
end;
THTMLReport = class
private
FHTMLItemList: TObjectList;
FStyle: string;
FStyleHTML: string;
FHead:string;
function BuildDefaultStyle: string;
procedure Initialize(reportStyle: string = '');
protected
procedure SetStyle(value: string);
public
property HTMLItemList: TObjectList read FHTMLItemList write FHTMLItemList;
property Style: string read FStyle write SetStyle;
property StyleHTML: string read FStyleHTML write FStyleHTML;
property Head: string read FHead write FHead;
procedure AddTable(table: THTMLTable);
procedure AddItem(item: THTMLItem);
function AddParagraph(paragraphName, paragraphStyle: string): THTMLParagraph;
function Build: string;
procedure SaveToFile(fileName: string);
procedure Clear;
constructor Create;overload;
constructor Create(reportStyle: string);overload;
destructor Destroy;override;
end;
TBuild = class
public
class function Build(item: TObject):string;
end;
implementation
{ THTMLTable }
function THTMLTable.AddRow(cellList: array of THTMLCell;
rowStyle: string): THTMLRow;
var
row: THTMLrow;
i: Integer;
begin
row := THTMLrow.Create;
row.Style := rowStyle;
for i := 0 to High(cellList) do
row.CellList.Add(cellList[i]);
FRowList.Add( row );
Result := row;
end;
function THTMLTable.AddEmptyRow(rowStyle:string = ''): THTMLRow;
var
row: THTMLrow;
begin
row := THTMLrow.Create;
row.Style := rowStyle;
row.CellList.Add(THTMLCell.Create(' ', 'colspan="100%"'));
FRowList.Add( row );
Result := row;
end;
function THTMLTable.Build: string;
var
i: Integer;
html: TStringList;
begin
html := TStringList.Create;
try
html.Clear;
html.Add('<table ' + Self.Style + '>');
for i := 0 to FRowList.Count - 1 do
//BUILD ROW
html.Add(TBuild.Build(FRowList[i]));
html.Add('</table>');
Result := html.Text;
finally
FreeAndNil(html);
end;
end;
constructor THTMLTable.Create(tableStyle: string = '');
begin
RowList := TObjectList.Create;
Style := tableStyle;
end;
destructor THTMLTable.Destroy;
begin
FreeAndNil(FRowList);
inherited Destroy;
end;
function THTMLTable.AddRow(rowName, rowStyle: string): THTMLRow;
begin
Result := THTMLRow.Create;
Result.Name := rowName;
Result.Style := rowStyle;
RowList.Add(Result);
end;
procedure THTMLTable.SetDataSet(
dataSet: TDataSet; HeaderColor: string = '';
EvenColor: string = ''; OddColor: string = '';
EmptyValue: string = ''; AfterAddRow: TAfterAddRow = nil);
const
StyleHeader='';
StyleData='';
var
i: Integer;
row: THTMLRow;
cell: THTMLCell;
begin
//prototipo
row := THTMLRow.Create;
row.Style := 'bgcolor="' + HeaderColor + '"';
for i := 0 to dataSet.FieldCount - 1 do
if dataSet.Fields[i].Visible then
row.AddCell('<b>' + dataSet.Fields[i].DisplayName + '</b>', StyleHeader);
Self.RowList.Add(row);
dataSet.DisableControls;
try
dataSet.First;
while not dataSet.Eof do
begin
row := THTMLRow.Create;
if ((dataSet.RecNo mod 2) <> 0) then
row.Style := 'bgcolor="' + EvenColor + '"'
else
row.Style := 'bgcolor="' + OddColor + '"';
for i := 0 to dataSet.FieldCount - 1 do
if dataSet.Fields[i].Visible then
begin
if dataSet.FieldByName(dataSet.Fields[i].FieldName).DataType = ftMemo then
cell := row.AddCell(dataSet.FieldByName(dataSet.Fields[i].FieldName).AsString, StyleData)
else
cell := row.AddCell(dataSet.FieldByName(dataSet.Fields[i].FieldName).DisplayText, StyleData);
if cell.Name = EmptyStr then
cell.Name := EmptyValue;
end;
Self.RowList.Add(row);
if Assigned(AfterAddRow) then
AfterAddRow(Self, dataSet);
dataSet.Next;
end;
finally
dataSet.EnableControls;
end;
end;
{ THTMLCell }
constructor THTMLCell.Create(cellName, cellStyle: string);
begin
Initialize(cellName, cellStyle);
end;
function THTMLCell.Build: string;
var
html: TStringList;
i: Integer;
begin
html := TStringList.Create;
try
html.Add(' <td ' + Self.Style + '>');
if Self.Name <> '' then
html.Add(' ' + Self.Name);
//BUILD CHILD ITEM, HTML, CELL, ETC
for i := 0 to Self.ItemList.Count - 1 do
html.Add(' ' + TBuild.Build(Self.ItemList[i]));
html.Add(' </td>');
Result := html.Text;
finally
FreeAndNil(html);
end;
end;
destructor THTMLCell.Destroy;
begin
FreeAndNil(FItemList);
inherited Destroy;
end;
constructor THTMLCell.Create;
begin
Initialize;
end;
procedure THTMLCell.Initialize(cellName:string = ''; cellStyle: string = '');
begin
FItemList := TObjectList.Create;
Name := cellName;
Style := cellStyle;
end;
{ THTMLRow }
function THTMLRow.AddCell(cellName, cellStyle: string): THTMLCell;
begin
Result := THTMLCell.Create(cellName, cellStyle);
CellList.Add(Result);
end;
function THTMLRow.Build: string;
var
i: Integer;
html: TStringList;
begin
html := TStringList.Create;
try
html.Clear;
//BUILD ROW
html.Add(' <tr ' + Self.Style + ' >');
for i := 0 to Self.CellList.Count - 1 do
begin
//BUILD CELL
html.Add(TBuild.Build(Self.CellList[i]));
end;
html.Add(' </tr>');
Result := html.Text;
finally
FreeAndNil(html);
end;
end;
constructor THTMLRow.Create;
begin
Initialize([]);
end;
constructor THTMLRow.Create(rowCellList: array of THTMLCell);
begin
Initialize(rowCellList);
end;
constructor THTMLRow.Create(rowCellList: array of THTMLCell;
rowStyle: string);
begin
Initialize(rowCellList, rowStyle);
end;
destructor THTMLRow.Destroy;
begin
FreeAndNil(FCellList);
inherited Destroy;
end;
procedure THTMLRow.Initialize(rowCellList: array of THTMLCell;
rowStyle: string = '');
var
i: Integer;
begin
FCellList := TObjectList.Create;
Self.Style := rowStyle;
for i := 0 to High(rowCellList) do
CellList.Add(rowCellList[i]);
end;
{ THTMLReport }
procedure THTMLReport.AddItem(item: THTMLItem);
begin
HTMLItemList.Add(item);
end;
function THTMLReport.AddParagraph(paragraphName,
paragraphStyle: string): THTMLParagraph;
begin
Result := THTMLParagraph.Create(paragraphName, paragraphStyle);
HTMLItemList.Add(Result);
end;
procedure THTMLReport.AddTable(table: THTMLTable);
begin
HTMLItemList.Add(table);
end;
function THTMLReport.Build: string;
var
i: Integer;
html: TstringList;
begin
html := TStringList.Create;
try
html.Clear;
html.Add('<html ' + StyleHTML + '>');
html.Add(' <head>');
html.Add(' <style>');
html.Add( Self.Style);
html.Add(' </style>');
html.Add(' '+Self.Head);
//html.Add(' <meta http-equiv="X-UA-Compatible" content="IE=7" />');
html.Add(' </head>');
html.Add(' <body>');
for i := 0 to HTMLItemList.Count - 1 do
html.Add(TBuild.Build(HTMLItemList[i]));
html.Add(' </body>');
html.Add('</html>');
result := html.Text;
finally
FreeAndNil(html);
end;
end;
constructor THTMLReport.Create;
begin
Initialize;
end;
function THTMLReport.BuildDefaultStyle: string;
var
html: TStringList;
begin
html := TStringList.Create;
try
html.Clear;
html.Add('html, body {height:100%;}');
html.Add('table {width:100% ;border-collapse: collapse;font-family:Arial;font-size:8pt}');
Result := html.Text;
finally
FreeAndNil(html);
end;
end;
procedure THTMLReport.Clear;
begin
FHTMLItemList.Clear;
end;
constructor THTMLReport.Create(reportStyle: string);
begin
Initialize(reportStyle);
end;
destructor THTMLReport.Destroy;
begin
FreeAndNil(FHTMLItemList);
inherited Destroy;
end;
procedure THTMLReport.SaveToFile(fileName: string);
var
toFile: TStringList;
begin
toFile := TStringList.Create;
try
toFile.Text := Self.Build;
toFile.SaveToFile(fileName);
finally
FreeAndNil(toFile);
end;
end;
procedure THTMLReport.SetStyle(value: string);
begin
if value = '' then
FStyle := BuildDefaultStyle
else
FStyle := value;
end;
procedure THTMLReport.Initialize(reportStyle: string = '');
begin
FHTMLItemList := TObjectList.Create;
Style := reportStyle;
StyleHTML := '';
Head := '';
end;
{ THTMLItem }
function THTMLItem.Build: string;
begin
Result := HTML.Text;
end;
constructor THTMLItem.Create(itemHtml: string);
begin
fHTML := TStringList.Create;
fHTML.Clear;
fHTML.Text := itemHtml;
end;
destructor THTMLItem.Destroy;
begin
FreeAndNil(fHTML);
inherited Destroy;
end;
{ TBuild }
class function TBuild.Build(item: TObject): string;
begin
if item is THTMLReport then
Result := THTMLReport(item).Build
else if item is THTMLTable then
Result := THTMLTable(item).Build
else if item is THTMLRow then
Result := THTMLRow(item).Build
else if item is THTMLCell then
Result := THTMLCell(item).Build
else if item is THTMLItem then
Result := THTMLItem(item).Build
else if item is THTMLParagraph then
Result := THTMLParagraph(item).Build;
end;
{ THTMLParagraph }
constructor THTMLParagraph.Create;
begin
Initialize;
end;
function THTMLParagraph.Build: string;
var
html: TStringList;
i: Integer;
begin
html := TStringList.Create;
try
html.Clear;
html.Add('<p ' + Style + '>');
html.Add(Self.Name);
for i := 0 to Self.ItemList.Count - 1 do
html.Add(TBuild.Build(Self.ItemList[i]));
html.Add('</p>');
Result := html.Text;
finally
FreeAndNil(html);
end;
end;
constructor THTMLParagraph.Create(paragraphName, style: string);
begin
Initialize(paragraphName, style);
end;
destructor THTMLParagraph.Destroy;
begin
FreeAndNil(FItemList);
inherited Destroy;
end;
procedure THTMLParagraph.Initialize(paragraphName: string = ''; style: string = '');
begin
FItemList := TObjectList.Create;
Self.Name := paragraphName;
Self.Style := style;
end;
end.
|
unit WorldControl;
interface
uses
SysUtils, Math, TypeControl, BonusControl, CarControl, DirectionControl, OilSlickControl,
PlayerControl, ProjectileControl, TileTypeControl;
type
TWorld = class
private
FTick: LongInt;
FTickCount: LongInt;
FLastTickIndex: LongInt;
FWidth: LongInt;
FHeight: LongInt;
FPlayers: TPlayerArray;
FCars: TCarArray;
FProjectiles: TProjectileArray;
FBonuses: TBonusArray;
FOilSlicks: TOilSlickArray;
FMapName: string;
FTilesXY: TTileTypeArray2D;
FWaypoints: TLongIntArray2D;
FStartingDirection: TDirection;
function GetTick: LongInt;
function GetTickCount: LongInt;
function GetLastTickIndex: LongInt;
function GetWidth: LongInt;
function GetHeight: LongInt;
function GetPlayers: TPlayerArray;
function GetCars: TCarArray;
function GetProjectiles: TProjectileArray;
function GetBonuses: TBonusArray;
function GetOilSlicks: TOilSlickArray;
function GetMapName: string;
function GetTilesXY: TTileTypeArray2D;
function GetWaypoints: TLongIntArray2D;
function GetStartingDirection: TDirection;
function GetMyPlayer: TPlayer;
public
property Tick: LongInt read GetTick;
property TickCount: LongInt read GetTickCount;
property LastTickIndex: LongInt read GetLastTickIndex;
property Width: LongInt read GetWidth;
property Height: LongInt read GetHeight;
property Players: TPlayerArray read GetPlayers;
property Cars: TCarArray read GetCars;
property Projectiles: TProjectileArray read GetProjectiles;
property Bonuses: TBonusArray read GetBonuses;
property OilSlicks: TOilSlickArray read GetOilSlicks;
property MapName: string read GetMapName;
property TilesXY: TTileTypeArray2D read GetTilesXY;
property Waypoints: TLongIntArray2D read GetWaypoints;
property StartingDirection: TDirection read GetStartingDirection;
property MyPlayer: TPlayer read GetMyPlayer;
constructor Create(const ATick: LongInt; const ATickCount: LongInt; const ALastTickIndex: LongInt;
const AWidth: LongInt; const AHeight: LongInt; const APlayers: TPlayerArray;
const ACars: TCarArray; const AProjecTiles: TProjectileArray; const ABonuses: TBonusArray;
const AOilSlicks: TOilSlickArray; const AMapName: string; const ATilesXY: TTileTypeArray2D;
const AWayPoints: TLongIntArray2D; const AStartingDirection: TDirection);
destructor Destroy; override;
end;
TWorldArray = array of TWorld;
implementation
function TWorld.GetTick: LongInt;
begin
Result := FTick;
end;
function TWorld.GetTickCount: LongInt;
begin
Result := FTickCount;
end;
function TWorld.GetLastTickIndex: LongInt;
begin
Result := FLastTickIndex;
end;
function TWorld.GetWidth: LongInt;
begin
Result := FWidth;
end;
function TWorld.GetHeight: LongInt;
begin
Result := FHeight;
end;
function TWorld.GetPlayers: TPlayerArray;
begin
if Assigned(FPlayers) then
Result := Copy(FPlayers, 0, Length(FPlayers))
else
Result := nil;
end;
function TWorld.GetCars: TCarArray;
begin
if Assigned(FCars) then
Result := Copy(FCars, 0, Length(FCars))
else
Result := nil;
end;
function TWorld.GetProjectiles: TProjectileArray;
begin
if Assigned(FProjectiles) then
Result := Copy(FProjectiles, 0, Length(FProjectiles))
else
Result := nil;
end;
function TWorld.GetBonuses: TBonusArray;
begin
if Assigned(FBonuses) then
Result := Copy(FBonuses, 0, Length(FBonuses))
else
Result := nil;
end;
function TWorld.GetOilSlicks: TOilSlickArray;
begin
if Assigned(FOilSlicks) then
Result := Copy(FOilSlicks, 0, Length(FOilSlicks))
else
Result := nil;
end;
function TWorld.GetMapName: string;
begin
Result := FMapName;
end;
function TWorld.GetTilesXY: TTileTypeArray2D;
var
I: LongInt;
begin
if Assigned(FTilesXY) then
begin
SetLength(Result, Length(FTilesXY));
if Length(FTilesXY) > 0 then
begin
for i := High(FTilesXY) downto 0 do
begin
if Assigned(FTilesXY[I]) then
Result[i] := Copy(FTilesXY[I], 0, Length(FTilesXY[I]))
else
Result[i] := nil;
end;
end;
end
else
Result := nil;
end;
function TWorld.GetWaypoints: TLongIntArray2D;
var
I: LongInt;
begin
if Assigned(FWaypoints) then
begin
SetLength(Result, Length(FWaypoints));
if Length(FWaypoints) > 0 then
begin
for I := High(FWaypoints) downto 0 do
begin
if Assigned(FWaypoints[I]) then
Result[I] := Copy(FWaypoints[I], 0, Length(FWaypoints[I]))
else
Result[I] := nil;
end;
end;
end
else
Result := nil;
end;
function TWorld.GetStartingDirection: TDirection;
begin
Result := FStartingDirection;
end;
function TWorld.GetMyPlayer: TPlayer;
var
I: LongInt;
begin
Result := nil;
if Length(FPlayers) > 0 then
begin
for I := High(FPlayers) downto 0 do
begin
if FPlayers[I].IsMe then
begin
Result := FPlayers[I];
Exit;
end;
end;
end;
end;
constructor TWorld.Create(const ATick: LongInt; const ATickCount: LongInt; const ALastTickIndex: LongInt;
const AWidth: LongInt; const AHeight: LongInt; const APlayers: TPlayerArray;
const ACars: TCarArray; const AProjectiles: TProjectileArray; const ABonuses: TBonusArray;
const AOilSlicks: TOilSlickArray; const AMapName: string; const ATilesXY: TTileTypeArray2D;
const AWayPoints: TLongIntArray2D; const AStartingDirection: TDirection);
var
I: LongInt;
begin
FTick := ATick;
FTickCount := ATickCount;
FLastTickIndex := ALastTickIndex;
FWidth := AWidth;
FHeight := AHeight;
if Assigned(APlayers) then
FPlayers := Copy(APlayers, 0, Length(APlayers))
else
FPlayers := nil;
if Assigned(ACars) then
FCars := Copy(ACars, 0, Length(ACars))
else
FCars := nil;
if Assigned(AProjectiles) then
FProjectiles := Copy(AProjectiles, 0, Length(AProjectiles))
else
FProjectiles := nil;
if Assigned(ABonuses) then
FBonuses := Copy(ABonuses, 0, Length(ABonuses))
else
FBonuses := nil;
if Assigned(AOilSlicks) then
FOilSlicks := Copy(AOilSlicks, 0, Length(AOilSlicks))
else
FOilSlicks := nil;
FMapName := AMapName;
if Assigned(ATilesXY) then
begin
SetLength(FTilesXY, Length(ATilesXY));
if Length(ATilesXY) > 0 then
begin
for I := High(ATilesXY) downto 0 do
begin
if Assigned(ATilesXY[I]) then
FTilesXY[I] := Copy(ATilesXY[I], 0, Length(ATilesXY[I]))
else
FTilesXY[I] := nil;
end;
end;
end
else
FTilesXY := nil;
if Assigned(AWaypoints) then
begin
SetLength(FWaypoints, Length(AWaypoints));
if Length(AWaypoints) > 0 then
begin
for I := High(AWaypoints) downto 0 do
begin
if Assigned(AWaypoints[I]) then
FWaypoints[I] := Copy(AWaypoints[I], 0, Length(AWaypoints[I]))
else
FWaypoints[I] := nil;
end;
end;
end
else
FWaypoints := nil;
FStartingDirection := AStartingDirection;
end;
destructor TWorld.Destroy;
var
I: LongInt;
begin
if Assigned(FPlayers) then
begin
if Length(FPlayers) > 0 then
begin
for I := High(FPlayers) downto 0 do
begin
if Assigned(FPlayers[I]) then
FPlayers[I].Free;
end;
SetLength(FPlayers, 0);
end;
end;
if Assigned(FCars) then
begin
if Length(FCars) > 0 then
begin
for I := High(FCars) downto 0 do
begin
if Assigned(FCars[I]) then
FCars[I].Free;
end;
SetLength(FCars, 0);
end;
end;
if Assigned(FProjectiles) then
begin
if Length(FProjectiles) > 0 then
begin
for I := High(FProjectiles) downto 0 do
begin
if Assigned(FProjectiles[I]) then
FProjectiles[I].Free;
end;
SetLength(FProjectiles, 0);
end;
end;
if Assigned(FBonuses) then
begin
if Length(FBonuses) > 0 then
begin
for I := High(FBonuses) downto 0 do
begin
if Assigned(FBonuses[I]) then
FBonuses[I].Free;
end;
SetLength(FBonuses, 0);
end;
end;
if Assigned(FOilSlicks) then
begin
if Length(FOilSlicks) > 0 then
begin
for I := High(FOilSlicks) downto 0 do
begin
if Assigned(FOilSlicks[I]) then
FOilSlicks[i].Free;
end;
SetLength(FOilSlicks, 0);
end;
end;
inherited;
end;
end.
|
{******************************************************************************}
{* frxMvxRTTI.pas *}
{* This module is part of Internal Project but is released under *}
{* the MIT License: http://www.opensource.org/licenses/mit-license.php *}
{* Copyright (c) 2006 by Jaimy Azle *}
{* All rights reserved. *}
{******************************************************************************}
{* Desc: *}
{******************************************************************************}
unit frxMvxRTTI;
interface
{$I frx.inc}
implementation
uses
Windows, Classes, fs_iinterpreter, frxMvxComponents, fs_imvxrtti
{$IFDEF Delphi6}
, Variants
{$ENDIF};
type
TFunctions = class(TfsRTTIModule)
private
function CallMethod(Instance: TObject; ClassType: TClass;
const MethodName: String; Caller: TfsMethodHelper): Variant;
function GetProp(Instance: TObject; ClassType: TClass;
const PropName: String): Variant;
public
constructor Create(AScript: TfsScript); override;
end;
{ TFunctions }
constructor TFunctions.Create(AScript: TfsScript);
begin
inherited Create(AScript);
with AScript do
begin
with AddClass(TfrxMvxDatabase, 'TfrxCustomDatabase') do
AddProperty('Database', 'TMvxConnection', GetProp, nil);
with AddClass(TfrxMvxDataset, 'TfrxCustomDataset') do
begin
AddProperty('MVXDATASET', 'TMvxDataset', GetProp, nil);
end;
end;
end;
function TFunctions.CallMethod(Instance: TObject; ClassType: TClass;
const MethodName: String; Caller: TfsMethodHelper): Variant;
begin
Result := 0;
end;
function TFunctions.GetProp(Instance: TObject; ClassType: TClass;
const PropName: String): Variant;
begin
Result := 0;
if ClassType = TfrxMvxDatabase then
begin
if PropName = 'DATABASE' then
Result := Integer(TfrxMvxDatabase(Instance).Database)
end
else if ClassType = TfrxMvxDataset then
begin
if PropName = 'MVXDATASET' then
Result := Integer(TfrxMvxDataset(Instance).MvxDataset)
end
end;
initialization
fsRTTIModules.Add(TFunctions);
finalization
if fsRTTIModules <> nil then
fsRTTIModules.Remove(TFunctions);
end.
|
unit Unit3;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.StdCtrls;
type
tarr_symbols = array of ansichar;
twords = array of string;
tID = record
id: string;
amount: integer;
end;
tIDs = array of tID;
TForm3 = class(TForm)
OpenDialog1: TOpenDialog;
all_text_memo: TMemo;
result_table: TStringGrid;
Open_button: TButton;
Result_button: TButton;
procedure FormCreate(Sender: TObject);
procedure Open_buttonClick(Sender: TObject);
procedure main;
procedure Result_buttonClick(Sender: TObject);
function input_text: tarr_symbols;
function delete_comments(all_text: tarr_symbols): tarr_symbols;
function input_main_words: twords;
function found_id(all_text: tarr_symbols; main_words: twords): tIDs;
function spen_id(all_text: tarr_symbols; ids: tIDs): tIDs;
function delete_space(ids: tIDs): tIDs;
function delete_unnecessary_ids(ids: tIDs): tIDs;
function delete_repeating_ids(ids: tIDs): tIDs;
procedure output(ids: tIDs);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
{$R *.dfm}
function TForm3.delete_comments(all_text: tarr_symbols): tarr_symbols;
var
i, j: integer;
text_without_comments: tarr_symbols;
begin
i := 1;
j := 1;
while i <> length(all_text) do
begin
if (all_text[i - 1] = '/') and (all_text[i] = '*') then
while (all_text[i - 1] <> '*') or (all_text[i] <> '/') do
inc(i);
if all_text[i - 1] = '"' then
begin
while (all_text[i - 1] <> '"') do
begin
inc(i);
if (all_text[i - 1] = '\') and (all_text[i] = '"') then
inc(i);
end;
end;
setlength(text_without_comments, j);
text_without_comments[j - 1] := all_text[i - 1];
inc(i);
inc(j);
end;
result := text_without_comments;
end;
function TForm3.delete_repeating_ids(ids: tIDs): tIDs;
var
i, j: integer;
begin
for i := 0 to length(ids) - 2 do
for j := i + 1 to length(ids) - 1 do
if ids[i].id = ids[j].id then
ids[j].id := 'null';
result := ids;
end;
function TForm3.delete_space(ids: tIDs): tIDs;
var
i, j: integer;
string_withot_spaces: string;
begin
for i := 0 to length(ids) - 1 do
begin
string_withot_spaces := '';
for j := 1 to length(ids[i].id) do
if ids[i].id[j] <> ' ' then
string_withot_spaces := string_withot_spaces + ids[i].id[j];
ids[i].id := string_withot_spaces;
end;
result := ids;
end;
function TForm3.delete_unnecessary_ids(ids: tIDs): tIDs;
const
symbols: set of char = ['a' .. 'z', 'A' .. 'Z', '_', '0' .. '9'];
var
i, j, count,numeber_of_elements: integer;
ids_without_useless: tIDs;
begin
numeber_of_elements := 0;
for i := 0 to length(ids) - 1 do
begin
inc(numeber_of_elements);
setlength(ids_without_useless,numeber_of_elements);
for j := 0 to length(ids[i].id) do
if ids[i].id[j] in symbols then
ids_without_useless[numeber_of_elements - 1].id := ids_without_useless[numeber_of_elements - 1].id +
ids[i].id[j];
end;
result := ids_without_useless;
end;
procedure TForm3.FormCreate(Sender: TObject);
begin
all_text_memo.Clear;
result_table.Cells[0, 0] := 'Идентефикатор:';
result_table.Cells[1, 0] := 'Спен:';
end;
function TForm3.found_id(all_text: tarr_symbols; main_words: twords): tIDs;
const
letters: set of ansichar = ['A' .. 'Z', 'a' .. 'z', '_'];
var
i, j, k: integer;
id_count: integer;
ids: tIDs;
temporarery_word, found_word: ansistring;
begin
id_count := 1;
for i := 0 to length(main_words) - 1 do
begin
j := 0;
while j <> length(all_text) - length(main_words[i]) - 1 do
begin
found_word := '';
temporarery_word := main_words[i];
for k := 1 to length(temporarery_word) do
begin
if (all_text[j + k - 1] = temporarery_word[k]) then
found_word := found_word + all_text[j + k - 1]
else
found_word := '';
end;
if found_word = temporarery_word then
begin
if (not(all_text[j - 1] in letters)) or
(not(all_text[j + k - 1] in letters)) then
begin
inc(j, k - 1);
setlength(ids, id_count);
while (all_text[j] <> ';') and (all_text[j] <> '{') do
begin
if all_text[j] = ',' then
begin
inc(id_count);
setlength(ids, id_count);
end
else if (all_text[j] <> ' ') or (all_text[j] <> '*') then
ids[id_count - 1].id := ids[id_count - 1].id + all_text[j];
inc(j);
end;
inc(id_count);
end;
end;
inc(j);
end;
end;
result := ids;
end;
function TForm3.input_main_words: twords;
var
words_file: textfile;
i: integer;
key_words: twords;
begin
assignfile(words_file, 'input.txt');
reset(words_file);
i := 1;
while not eof(words_file) do
begin
setlength(key_words, i);
readln(words_file, key_words[i - 1]);
inc(i);
end;
result := key_words;
end;
function TForm3.input_text: tarr_symbols;
var
file_name: textfile;
i: integer;
all_text: tarr_symbols;
temp_symbol, temp: ansichar;
begin
setlength(all_text, 0);
assignfile(file_name, OpenDialog1.FileName);
reset(file_name);
i := 1;
while not(eof(file_name)) do
begin
setlength(all_text, i);
read(file_name, temp_symbol);
if temp_symbol = '/' then
begin
read(file_name, temp);
if temp = '/' then
readln(file_name)
else
begin
all_text[i - 1] := temp_symbol;
inc(i);
setlength(all_text, i);
all_text[i - 1] := temp;
inc(i)
end;
end
else
begin
all_text[i - 1] := temp_symbol;
inc(i);
end;
end;
closefile(file_name);
result := all_text;
end;
procedure TForm3.main;
var
all_text: tarr_symbols;
main_words: twords;
ids: tIDs;
begin
all_text := input_text;
all_text := delete_comments(all_text);
main_words := input_main_words;
ids := found_id(all_text, main_words);
ids := delete_space(ids);
ids := delete_unnecessary_ids(ids);
ids := delete_repeating_ids(ids);
ids := spen_id(all_text, ids);
output(ids);
end;
procedure TForm3.Open_buttonClick(Sender: TObject);
begin
if OpenDialog1.Execute then
all_text_memo.lines.LoadFromFile(OpenDialog1.FileName);
end;
procedure TForm3.output(ids: tIDs);
var
i, j, all_spen: integer;
begin
result_table.RowCount := length(ids) + 1;
all_spen := 0;
j:=0;
for i := 0 to length(ids) - 1 do
begin
if (ids[i].id <> 'null') and (ids[i].amount<>0) then
begin
result_table.RowCount := i + 1-j;
result_table.Cells[0, i + 1-j] := ids[i].id;
result_table.Cells[1, i + 1-j] := inttostr(ids[i].amount-1);
inc(all_spen, ids[i].amount-1);
end
else
begin
inc(j);
end;
end;
inc(i);
result_table.RowCount := i + 1-j;
result_table.Cells[0, i - j] := 'Общий спен =';
result_table.Cells[1, i - j] := inttostr(all_spen);
end;
procedure TForm3.Result_buttonClick(Sender: TObject);
begin
main;
end;
function TForm3.spen_id(all_text: tarr_symbols; ids: tIDs): tIDs;
const
symbols: set of char = ['a' .. 'z', 'A' .. 'Z', '_', '1' .. '9'];
var
i, j, k, count_id: integer;
string_id: ansistring;
begin
for i := 0 to length(ids) - 1 do
begin
j := 0;
string_id := ids[i].id;
while (j <> length(all_text) - length(string_id) - 1) do
begin
count_id := 0;
for k := 1 to length(string_id) do
if all_text[j + k - 1] = string_id[k] then
inc(count_id)
else
count_id := 0;
if count_id = length(string_id) then
if (not(all_text[j - 1] in symbols)) and
(not(all_text[j + k - 1] in symbols)) then
inc(ids[i].amount);
inc(j)
end;
end;
result := ids;
end;
end.
|
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, System.Bluetooth,
System.Bluetooth.Components, FMX.Layouts, FMX.ListBox, FMX.Edit,
FMX.ScrollBox, FMX.Memo, FMX.ListView.Types, FMX.ListView.Appearances,
FMX.ListView.Adapters.Base, FMX.ListView;
type
TFormMain = class(TForm)
ButtonDiscover: TButton;
Bluetooth: TBluetooth;
ListBoxDevices: TListBox;
ListBoxServices: TListBox;
ButtonConnect: TButton;
Edit: TEdit;
Panel: TPanel;
ButtonSend: TButton;
Timer: TTimer;
ListViewReceive: TListView;
procedure ButtonDiscoverClick(Sender: TObject);
procedure BluetoothDiscoveryEnd(const Sender: TObject;
const ADeviceList: TBluetoothDeviceList);
procedure ButtonConnectClick(Sender: TObject);
procedure ButtonSendClick(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure ListBoxDevicesChange(Sender: TObject);
private
{ Private declarations }
DeviceList: TBluetoothDeviceList;
Device: TBluetoothDevice;
SerialPort: TBluetoothService;
Socket: TBluetoothSocket;
Connected: Boolean;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.fmx}
procedure TFormMain.ButtonDiscoverClick(Sender: TObject);
begin
SerialPort.Name := '';
Device := nil;
DeviceList := nil;
ButtonConnect.Enabled := False;
ListBoxDevices.Clear;
ListBoxServices.Clear;
Bluetooth.DiscoverDevices(10000);
end;
procedure TFormMain.BluetoothDiscoveryEnd(const Sender: TObject;
const ADeviceList: TBluetoothDeviceList);
var
I: Integer;
begin
ListBoxDevices.Clear;
for I := 0 to ADeviceList.Count - 1 do
ListBoxDevices.Items.Add(ADeviceList.Items[I].DeviceName);
DeviceList := ADeviceList;
end;
procedure TFormMain.ListBoxDevicesChange(Sender: TObject);
var
DeviceIndex: Integer;
LastServices: TBluetoothServiceList;
I: Integer;
begin
SerialPort.Name := '';
ListBoxServices.Clear;
ButtonConnect.Enabled := False;
DeviceIndex := ListBoxDevices.ItemIndex;
if DeviceIndex = -1 then
Exit;
// Selected device
Device := nil;
if DeviceList <> nil then
if (DeviceIndex >= 0) and (DeviceIndex < DeviceList.Count) then
Device := DeviceList.Items[DeviceIndex];
if Device = nil then
Exit;
Application.ProcessMessages;
// Checking if paired
if not Device.IsPaired then
if not Bluetooth.Pair(Device) or not Device.IsPaired then
begin
ListBoxDevices.ItemIndex := -1;
raise Exception.Create('Device ''' + Device.DeviceName +
''' not paired!');
end;
// Find the SPP service
LastServices := Device.LastServiceList;
ListBoxServices.Clear;
for I := 0 to LastServices.Count - 1 do
begin
ListBoxServices.Items.Add(LastServices[I].Name);
if LastServices[I].Name = 'SerialPort' then
SerialPort := LastServices[I];
end;
if SerialPort.Name = '' then
raise Exception.Create('SPP service not found!');
ButtonConnect.Enabled := True;
end;
procedure TFormMain.ButtonConnectClick(Sender: TObject);
begin
if Connected then
begin
Connected := False;
try
Socket.Close;
except
end;
Socket := nil;
end
else
begin
Socket := Device.CreateClientSocket(SerialPort.UUID, True);
Socket.Connect;
Connected := Socket.Connected;
end;
if Connected then
begin
ButtonConnect.Text := 'Disconnect';
ButtonDiscover.Enabled := False;
ListBoxDevices.Enabled := False;
Edit.Enabled := True;
ButtonSend.Enabled := True;
Timer.Enabled := True;
end
else
begin
ButtonConnect.Text := 'Connect';
ButtonDiscover.Enabled := True;
ListBoxDevices.Enabled := True;
Edit.Enabled := False;
ButtonSend.Enabled := False;
Timer.Enabled := False;
end;
end;
procedure TFormMain.ButtonSendClick(Sender: TObject);
begin
Socket.SendData(TEncoding.ANSI.GetBytes(Edit.Text));
end;
procedure TFormMain.TimerTimer(Sender: TObject);
var
Data: TBytes;
ItemList: TListViewItem;
begin
Data := Socket.ReceiveData(0);
if Data <> nil then
begin
ItemList := ListViewReceive.Items.Add;
ItemList.Text := TEncoding.ANSI.GetString(Data);
end;
end;
end.
|
unit BZK2_File;
interface
uses Windows, SysUtils, Voxel, Voxel_Engine, BZK2_Sector, BZK2_Camera, BZK2_Actor,
Palette, Normals;
type
TSectorMap = array of array of array of integer;
TBZK2Settings = record
UseBZKMapXSL : boolean;
LocalLighting : TVector3f;
UseTrueMasterSectorSize : Boolean;
MasterSectorColours : array [TBzkFacesDirection] of TVector3i;
InvertX, InvertY, InvertZ : Boolean;
ColoursWithNormals: Boolean;
end;
TBZK2PrivateMembers = record
xInc, yInc, zInc: Integer;
end;
TBZK2File = class
private
// Traditional File Atributes
Sectors : array of TBZK2Sector;
Actors : array of TBZK2Actor;
Cameras : array of TBZK2Camera;
// Burocratic Outerfile Additions
Filename : string;
SectorMap : TSectorMap;
VoxelSection : PVoxelSection;
Settings : TBZK2Settings;
PrivateMembers : TBZK2PrivateMembers;
Valid : Boolean;
BZKMap : Boolean;
// I/O
procedure WriteToFile (var MyFile : System.Text);
procedure WriteHeader (var MyFile : System.Text);
procedure WriteFooter (var MyFile : System.Text);
// Random
function CalculateColour(Value : TVector3i): TVector3i;
function MultiplyVectorI(Value,Scale : TVector3i): TVector3i;
procedure SetMeAConnection(SectorNum,x,y,z : integer; Direction : TBZKFacesDirection);
procedure SetFaceColour(SectorNum,x,y,z : integer; Direction : TBZKFacesDirection);
procedure SetFaceColourWithoutNormals(SectorNum,x,y,z : integer; Direction : TBZKFacesDirection);
function GetNormalX(V : TVoxelUnpacked) : single;
function GetNormalY(V : TVoxelUnpacked) : single;
function GetNormalZ(V : TVoxelUnpacked) : single;
public
// Constructors and Destructors
constructor Create( p_VoxelSection : PVoxelSection);
destructor Destroy; override;
// I/O
procedure SaveToFile(const _Filename : string);
// Gets
function GetNumSectors : integer;
function GetNumActors : integer;
function GetNumCameras : integer;
function GetFilename : string;
function GetVoxelSection : PVoxelSection;
function GetUseBZKMapXSL : Boolean;
function GetLocalLighting : TVector3f; overload;
procedure GetLocalLighting(var r,g,b : integer); overload;
function GetUseTrueMasterSectorSize: Boolean;
function GetInvertX : Boolean;
function GetInvertY : Boolean;
function GetInvertZ : Boolean;
function GetSector(ID : integer): TBZK2Sector;
function GetActor(ID : integer): TBZK2Actor;
function GetCamera(ID : integer): TBZK2Camera;
function GetColoursWithNormals: Boolean;
function GetMinBounds : TVector3i;
function GetMaxBounds : TVector3i;
function GetCenterPosition : TVector3i;
function IsValid : Boolean;
function IsBZKMap : Boolean;
// Sets
procedure SetFilename (Value : string);
procedure SetUseBZKMapXSL(Value : Boolean);
procedure SetLocalLighting( Value : TVector3f); overload;
procedure SetLocalLighting( r,g,b : integer); overload;
procedure SetUseTrueMasterSectorSize(Value : Boolean);
procedure SetInvertX(Value : Boolean);
procedure SetInvertY(Value : Boolean);
procedure SetInvertZ(Value : Boolean);
procedure SetColoursWithNormals(Value : Boolean);
procedure SetMinBounds( Value : TVector3i);
procedure SetMaxBounds( Value : TVector3i);
procedure SetIsBZKMap(Value : Boolean);
// Moves
procedure MoveCenterToPosition(Value : TVector3i);
procedure MoveSideToPosition(Direction : TBZKFacesDirection; Value : Integer);
// Adds
procedure AddSector;
procedure AddActor;
procedure AddCamera;
// Removes
function RemoveSector( ID: integer): Boolean;
function RemoveActor( ID: integer): Boolean;
function RemoveCamera( ID: integer): Boolean;
// Clears
procedure ClearSectors;
procedure ClearActors;
procedure ClearCameras;
procedure ClearSectorMap;
// Builds
procedure BuildSectorMap;
procedure BuildConnections;
procedure BuildColours;
// Attach
procedure Attach(var BZK2File : TBZK2File; Direction : TBZKFacesDirection; Offset : TVector3i);
end;
implementation
// Constructors and Destructors
constructor TBZK2File.Create( p_VoxelSection : PVoxelSection);
begin
SetLength(Sectors,0);
SetLength(Actors,0);
SetLength(Cameras,0);
SetLength(SectorMap,0,0,0);
VoxelSection := p_VoxelSection;
if VoxelSection <> nil then
begin
Filename := VoxelSection^.Header.Name;
Valid := true;
end
else
Valid := false;
BZKMap := Valid;
// Setup Basic Settings
Settings.UseBZKMapXSL := true;
Settings.LocalLighting.X := 1; // default, full red lighting
Settings.LocalLighting.Y := 1; // default, full green lighting
Settings.LocalLighting.Z := 1; // default, full blue lighting
Settings.UseTrueMasterSectorSize := true;
Settings.MasterSectorColours[bfdNorth] := SetVectorI(255,0,0);
Settings.MasterSectorColours[bfdEast] := SetVectorI(255,255,255);
Settings.MasterSectorColours[bfdSouth] := SetVectorI(0,255,0);
Settings.MasterSectorColours[bfdWest] := SetVectorI(0,0,255);
Settings.MasterSectorColours[bfdFloor] := SetVectorI(64,64,64);
Settings.MasterSectorColours[bfdCeiling] := SetVectorI(128,128,128);
Settings.InvertX := false;
Settings.InvertY := false;
Settings.InvertZ := false;
Settings.ColoursWithNormals := true;
end;
destructor TBZK2File.Destroy;
begin
ClearSectors;
ClearActors;
ClearCameras;
ClearSectorMap;
Finalize(Sectors);
Finalize(Actors);
Finalize(Cameras);
Finalize(SectorMap);
inherited Destroy;
end;
// I/O
procedure TBZK2File.SaveToFile(const _Filename : string);
var
MyFile : System.Text;
begin
if Valid and BZKMap then
begin
AssignFile(MyFile,_Filename);
Rewrite(MyFile);
WriteToFile(MyFile);
CloseFile(MyFile);
end;
end;
procedure TBZK2File.WriteToFile (var MyFile : System.Text);
var
i : integer;
begin
WriteHeader(MyFile);
if GetNumSectors > 0 then
begin
for i := Low(Sectors) to High(Sectors) do
Sectors[i].WriteToFile(MyFile);
end;
if GetNumActors > 0 then
begin
WriteLn(MyFile,'<Actors>');
for i := Low(Actors) to High(Actors) do
Actors[i].WriteToFile(MyFile);
WriteLn(MyFile,'</Actors>');
end;
if GetNumCameras > 0 then
begin
for i := Low(Cameras) to High(Cameras) do
Cameras[i].WriteToFile(MyFile);
end;
WriteFooter(MyFile);
end;
procedure TBZK2File.WriteHeader (var MyFile : System.Text);
begin
WriteLn(MyFile,'<?xml version="1.0" encoding="ISO-8859-1"?>');
if Settings.UseBZKMapXSL then
WriteLn(MyFile,'<?xml-stylesheet type="text/xsl" href="./bzkmap.xsl" ?>');
WriteLn(MyFile,'<BZK2>');
WriteLn(MyFile,'<Version>');
WriteLn(MyFile,'0.6');
WriteLn(MyFile,'</Version>');
WriteLn(MyFile,'<Number.of.Sectors>');
WriteLn(MyFile,GetNumSectors);
WriteLn(MyFile,'</Number.of.Sectors>');
end;
procedure TBZK2File.WriteFooter (var MyFile : System.Text);
begin
WriteLn(MyFile,'</BZK2>');
end;
// Gets
function TBZK2File.GetNumSectors: integer;
begin
Result := High(Sectors) + 1;
end;
function TBZK2File.GetNumActors: integer;
begin
Result := High(Actors) + 1;
end;
function TBZK2File.GetNumCameras: integer;
begin
Result := High(Cameras) + 1;
end;
function TBZK2File.GetFilename : string;
begin
Result := Filename;
end;
function TBZK2File.GetVoxelSection : PVoxelSection;
begin
Result := VoxelSection;
end;
function TBZK2File.GetUseBZKMapXSL : Boolean;
begin
Result := Settings.UseBZKMapXSL;
end;
function TBZK2File.GetLocalLighting : TVector3f;
begin
Result.X := Settings.LocalLighting.X;
Result.Y := Settings.LocalLighting.Y;
Result.Z := Settings.LocalLighting.Z;
end;
procedure TBZK2File.GetLocalLighting(var r,g,b : integer);
begin
r := Round(Settings.LocalLighting.X * 255);
g := Round(Settings.LocalLighting.Y * 255);
b := Round(Settings.LocalLighting.Z * 255);
end;
function TBZK2File.GetUseTrueMasterSectorSize: Boolean;
begin
Result := Settings.UseTrueMasterSectorSize;
end;
function TBZK2File.GetInvertX : Boolean;
begin
Result := Settings.InvertX;
end;
function TBZK2File.GetInvertY : Boolean;
begin
Result := Settings.InvertY;
end;
function TBZK2File.GetInvertZ : Boolean;
begin
Result := Settings.InvertZ;
end;
function TBZK2File.GetSector(ID : integer): TBZK2Sector;
begin
if ID <= High(Sectors) then
Result := Sectors[ID]
else
Result := nil;
end;
function TBZK2File.GetActor(ID : integer): TBZK2Actor;
begin
if ID <= High(Actors) then
Result := Actors[ID]
else
Result := nil;
end;
function TBZK2File.GetCamera(ID : integer): TBZK2Camera;
begin
if ID <= High(Cameras) then
Result := Cameras[ID]
else
Result := nil;
end;
function TBZK2File.GetColoursWithNormals : Boolean;
begin
Result := Settings.ColoursWithNormals;
end;
function TBZK2File.GetMinBounds : TVector3i;
begin
Result.X := Round(VoxelSection^.Tailer.MinBounds[1]);
Result.Y := Round(VoxelSection^.Tailer.MinBounds[2]);
Result.Z := Round(VoxelSection^.Tailer.MinBounds[3]);
end;
function TBZK2File.GetMaxBounds : TVector3i;
begin
Result.X := Round(VoxelSection^.Tailer.MaxBounds[1]);
Result.Y := Round(VoxelSection^.Tailer.MaxBounds[2]);
Result.Z := Round(VoxelSection^.Tailer.MaxBounds[3]);
end;
function TBZK2File.GetCenterPosition: TVector3i;
Var
MinBound,MaxBound : TVector3i;
begin
MinBound := GetMinBounds;
MaxBound := GetMaxBounds;
Result.X := (MinBound.X + MaxBound.X) div 2;
Result.Y := (MinBound.Y + MaxBound.Y) div 2;
Result.Z := (MinBound.Z + MaxBound.Z) div 2;
end;
function TBZK2File.IsValid : Boolean;
begin
Result := Valid;
end;
function TBZK2File.IsBZKMap : Boolean;
begin
Result := BZKMap;
end;
// Sets
procedure TBZK2File.SetFilename (Value : string);
begin
Filename := Value;
end;
procedure TBZK2File.SetUseBZKMapXSL(Value : Boolean);
begin
Settings.UseBZKMapXSL := Value;
end;
procedure TBZK2File.SetLocalLighting( Value : TVector3f);
begin
Settings.LocalLighting.X := Value.X;
Settings.LocalLighting.Y := Value.Y;
Settings.LocalLighting.Z := Value.Z;
end;
procedure TBZK2File.SetLocalLighting( r,g,b : integer);
begin
Settings.LocalLighting.X := r / 255;
Settings.LocalLighting.Y := g / 255;
Settings.LocalLighting.Z := b / 255;
end;
procedure TBZK2File.SetUseTrueMasterSectorSize(Value : Boolean);
begin
Settings.UseBZKMapXSL := Value;
end;
procedure TBZK2File.SetInvertX(Value : Boolean);
begin
Settings.InvertX := Value;
end;
procedure TBZK2File.SetInvertY(Value : Boolean);
begin
Settings.InvertY := Value;
end;
procedure TBZK2File.SetInvertZ(Value : Boolean);
begin
Settings.InvertZ := Value;
end;
procedure TBZK2File.SetColoursWithNormals(Value : Boolean);
begin
Settings.ColoursWithNormals := Value;
end;
procedure TBZK2File.SetMinBounds( Value : TVector3i);
begin
VoxelSection^.Tailer.MinBounds[1] := Value.X;
VoxelSection^.Tailer.MinBounds[2] := Value.Y;
VoxelSection^.Tailer.MinBounds[3] := Value.Z;
end;
procedure TBZK2File.SetMaxBounds( Value : TVector3i);
begin
VoxelSection^.Tailer.MaxBounds[1] := Value.X;
VoxelSection^.Tailer.MaxBounds[2] := Value.Y;
VoxelSection^.Tailer.MaxBounds[3] := Value.Z;
end;
procedure TBZK2File.SetIsBZKMap(Value : Boolean);
begin
BZKMap := Value;
end;
// Moves
procedure TBZK2File.MoveCenterToPosition(Value : TVector3i);
var
MinBound,MaxBound,Center,Offset : TVector3i;
begin
MinBound := GetMinBounds;
MaxBound := GetMaxBounds;
Center := GetCenterPosition;
Offset.X := Value.X - Center.X;
Offset.Y := Value.Y - Center.Y;
Offset.Z := Value.Z - Center.Z;
SetMinBounds(SetVectorI(MinBound.X + Offset.X,MinBound.Y + Offset.Y,MinBound.Z + Offset.Z));
SetMaxBounds(SetVectorI(MaxBound.X + Offset.X,MaxBound.Y + Offset.Y,MaxBound.Z + Offset.Z));
end;
// Adds
procedure TBZK2File.AddSector;
begin
SetLength(Sectors,High(Sectors)+2);
Sectors[High(Sectors)] := TBZK2Sector.Create;
end;
procedure TBZK2File.AddActor;
begin
SetLength(Actors,High(Actors)+2);
Actors[High(Actors)] := TBZK2Actor.Create;
end;
procedure TBZK2File.AddCamera;
begin
SetLength(Cameras,High(Cameras)+2);
Cameras[High(Cameras)] := TBZK2Camera.Create;
end;
// Removes
function TBZK2File.RemoveSector(ID : integer): Boolean;
var
i : integer;
Position : TVector3i;
begin
Result := false;
if ID <= High(Sectors) then
begin
i := ID;
Position := Sectors[i].GetVoxelPosition;
SectorMap[Position.X,Position.Y,Position.Z] := 0;
while i < High(Sectors) do
begin
Sectors[i].Assign(Sectors[i+1]);
Position := Sectors[i].GetVoxelPosition;
SectorMap[Position.X,Position.Y,Position.Z] := i;
inc(i);
end;
SetLength(Sectors,High(Sectors));
// Here we scan all authors to make sure they aren't located at an
// invalid place
for i := Low(Actors) to High(Actors) do
begin
if Actors[i].GetLocation > High(Sectors) then
Actors[i].SetLocation(High(Sectors));
end;
BuildConnections;
Result := true;
end;
end;
function TBZK2File.RemoveActor(ID : integer): Boolean;
var
i : integer;
Name : string;
begin
Result := false;
if ID <= High(Actors) then
begin
i := ID;
Name := Actors[i].GetName;
while i < High(Actors) do
begin
Actors[i].Assign(Actors[i+1]);
inc(i);
end;
SetLength(Actors,High(Actors));
// Here we scan all cameras to remove the ones that link this actor
if High(Cameras) > -1 then
if High(Actors) > -1 then
begin
for i := High(Cameras) downto Low(Cameras) do
begin
if Cameras[i].GetActor > High(Actors) then
Cameras[i].SetActor(High(Actors));
end;
end
else
begin
for i := High(Cameras) downto Low(Cameras) do
begin
RemoveCamera(i);
end;
end;
Result := true;
end;
end;
function TBZK2File.RemoveCamera(ID : integer): Boolean;
var
i : integer;
begin
Result := false;
if ID <= High(Cameras) then
begin
i := ID;
while i < High(Cameras) do
begin
Cameras[i].Assign(Cameras[i+1]);
inc(i);
end;
SetLength(Cameras,High(Cameras));
Result := true;
end;
end;
// Clears
procedure TBZK2File.ClearSectors;
var
i : integer;
begin
if High(Sectors) > -1 then
for i := High(Sectors) downto Low(Sectors) do
begin
RemoveSector(i);
end;
SetLength(Sectors,0);
end;
procedure TBZK2File.ClearActors;
var
i : integer;
begin
if High(Actors) > -1 then
for i := High(Actors) downto Low(Actors) do
begin
RemoveActor(i);
end;
SetLength(Actors,0);
end;
procedure TBZK2File.ClearCameras;
var
i : integer;
begin
if High(Cameras) > -1 then
for i := High(Cameras) downto Low(Cameras) do
begin
RemoveCamera(i);
end;
SetLength(Cameras,0);
end;
procedure TBZK2File.ClearSectorMap;
var
x,y : integer;
begin
if High(SectorMap) > -1 then
for x := Low(SectorMap) to High(SectorMap) do
begin
for y := Low(SectorMap[x]) to High(SectorMap[x]) do
SetLength(SectorMap[x,y],0);
SetLength(SectorMap[x],0);
end;
SetLength(SectorMap,0);
end;
// Random
function TBZK2File.CalculateColour(Value : TVector3i): TVector3i;
begin
Result.X := Round(Value.X * Settings.LocalLighting.X);
Result.Y := Round(Value.Y * Settings.LocalLighting.Y);
Result.Z := Round(Value.Z * Settings.LocalLighting.Z);
end;
function TBZK2File.MultiplyVectorI(Value,Scale : TVector3i): TVector3i;
begin
Result.X := Value.X * Scale.X;
Result.Y := Value.Y * Scale.Y;
Result.Z := Value.Z * Scale.Z;
end;
// Builds
procedure TBZK2File.BuildSectorMap;
var
Sector : TBZK2Sector;
Scale : TVector3i;
xcount, ycount, zcount, x, y, z, xmax, ymax, zmax: Integer;
v : TVoxelUnpacked;
begin
if VoxelSection <> nil then
begin
// Pre-calculate some basic values.
Scale.X := Round((VoxelSection^.Tailer.MaxBounds[1]-VoxelSection^.Tailer.MinBounds[1])/VoxelSection^.Tailer.xSize);
Scale.Y := Round((VoxelSection^.Tailer.MaxBounds[2]-VoxelSection^.Tailer.MinBounds[2])/VoxelSection^.Tailer.ySize);
Scale.Z := Round((VoxelSection^.Tailer.MaxBounds[3]-VoxelSection^.Tailer.MinBounds[3])/VoxelSection^.Tailer.zSize);
ClearSectors;
AddSector;
// Let's setup the MasterSector.
if not Settings.UseTrueMasterSectorSize then
Sectors[0].SetVolume(255)
else
Sectors[0].SetVolume(SetVectorI(VoxelSection^.Tailer.XSize * Scale.X,VoxelSection^.Tailer.YSize * Scale.Y,VoxelSection^.Tailer.ZSize * Scale.Z));
Sectors[0].SetName('location');
Sectors[0].SetConnectionColours(bfdNorth,CalculateColour(Settings.MasterSectorColours[bfdNorth]));
Sectors[0].SetConnectionColours(bfdEast,CalculateColour(Settings.MasterSectorColours[bfdEast]));
Sectors[0].SetConnectionColours(bfdSouth,CalculateColour(Settings.MasterSectorColours[bfdSouth]));
Sectors[0].SetConnectionColours(bfdWest,CalculateColour(Settings.MasterSectorColours[bfdWest]));
Sectors[0].SetConnectionColours(bfdFloor,CalculateColour(Settings.MasterSectorColours[bfdFloor]));
Sectors[0].SetConnectionColours(bfdCeiling,CalculateColour(Settings.MasterSectorColours[bfdCeiling]));
// Now that the MasterSector is over, let's start to build the map
// First, bringing back a feature from 1.2i
if Settings.InvertX then
begin
xmax := VoxelSection^.Tailer.xSize-1;
PrivateMembers.xInc := -1;
end
else
begin
xmax := 0;
PrivateMembers.xInc := 1;
end;
if Settings.InvertY then
begin
ymax := VoxelSection^.Tailer.ySize-1;
PrivateMembers.yInc := -1;
end
else
begin
ymax := 0;
PrivateMembers.yInc := 1;
end;
if Settings.InvertZ then
begin
zmax := VoxelSection^.Tailer.zSize-1;
PrivateMembers.zInc := -1;
end
else
begin
zmax := 0;
PrivateMembers.zInc := 1;
end;
SetLength(SectorMap,VoxelSection^.Tailer.xSize,VoxelSection^.Tailer.ySize,VoxelSection^.Tailer.zSize);
x := xmax;
for xcount := 0 to VoxelSection^.Tailer.xSize-1 do
begin
y := ymax;
for ycount := 0 to VoxelSection^.Tailer.ySize-1 do
begin
z := zmax;
for zcount := 0 to VoxelSection^.Tailer.zSize-1 do
begin
VoxelSection^.GetVoxel(x,y,z,v);
// If it's a blank space, then it's a sector.
if not v.Used then
begin
AddSector;
Sectors[High(Sectors)].SetVoxelPosition(SetVectorI(x,y,z));
Sectors[High(Sectors)].SetPosition(MultiplyVectorI(SetVectorI(x,y,z),Scale));
Sectors[High(Sectors)].SetVolume(Scale);
Sectors[High(Sectors)].SetName('location');
SectorMap[x,y,z] := High(Sectors);
end
else
SectorMap[x,y,z] := 0;
z := z + PrivateMembers.zInc;
end;
y := y + PrivateMembers.yInc;
end;
x := x + PrivateMembers.xInc;
end;
end;
end;
procedure TBZK2File.SetMeAConnection(SectorNum,x,y,z : integer; Direction : TBZKFacesDirection);
var
V : TVoxelUnpacked;
begin
// Check borders... North.
if VoxelSection^.GetVoxelSafe(X,Y,Z,V) then
begin
Sectors[SectorNum].SetConnection(Direction,SectorMap[X,Y,Z]);
end
else // Border.
begin
Sectors[SectorNum].SetConnection(Direction,0);
end;
end;
procedure TBZK2File.BuildConnections;
var
i : integer;
Position : TVector3i;
begin
// If we have sectors, let's connect the dots.
if High(Sectors) > -1 then
begin
for i := Low(Sectors) to High(Sectors) do
begin
Position := Sectors[i].GetVoxelPosition;
// Check borders...
SetMeAConnection(i,Position.X,Position.Y - PrivateMembers.yInc, Position.Z, bfdNorth);
SetMeAConnection(i,Position.X + PrivateMembers.xInc,Position.Y, Position.Z, bfdEast);
SetMeAConnection(i,Position.X,Position.Y + PrivateMembers.yInc, Position.Z, bfdSouth);
SetMeAConnection(i,Position.X - PrivateMembers.xInc,Position.Y, Position.Z, bfdWest);
SetMeAConnection(i,Position.X,Position.Y, Position.Z - PrivateMembers.zInc, bfdFloor);
SetMeAConnection(i,Position.X,Position.Y, Position.Z + PrivateMembers.zInc, bfdCeiling);
end;
end;
end;
function TBZK2File.GetNormalX(V : TVoxelUnpacked) : single;
begin
if VoxelSection^.Tailer.Unknown = 4 then
begin
Result := abs(RA2Normals[v.Normal].X);
end
else
begin
Result := abs(TSNormals[v.Normal].X);
end;
end;
function TBZK2File.GetNormalY(V : TVoxelUnpacked) : single;
begin
if VoxelSection^.Tailer.Unknown = 4 then
begin
Result := abs(RA2Normals[v.Normal].Y);
end
else
begin
Result := abs(TSNormals[v.Normal].Y);
end;
end;
function TBZK2File.GetNormalZ(V : TVoxelUnpacked) : single;
begin
if VoxelSection^.Tailer.Unknown = 4 then
begin
Result := abs(RA2Normals[v.Normal].Z);
end
else
begin
Result := abs(TSNormals[v.Normal].Z);
end;
end;
procedure TBZK2File.SetFaceColour(SectorNum,x,y,z : integer; Direction : TBZKFacesDirection);
var
V : TVoxelUnpacked;
Normal : single;
Colour : TVector3i;
begin
// Painting each face works in the following way. First, we check
// the neighboor.
if VoxelSection^.GetVoxelSafe(X,Y,Z,V) then
begin //Two options here: wall or not wall.
if v.Used then
begin // Wall
// First, we find the normal influence
Case (Direction) of
bfdNorth: Normal := GetNormalY(v);
bfdEast: Normal := GetNormalX(v);
bfdSouth: Normal := GetNormalY(v);
bfdWest: Normal := GetNormalX(v);
bfdFloor: Normal := GetNormalZ(v);
bfdCeiling: Normal := GetNormalZ(v);
end;
// We get the colour
Colour.X := Round(GetRValue(VXLPalette[V.Colour]) * Normal * Settings.LocalLighting.X);
Colour.Y := Round(GetGValue(VXLPalette[V.Colour]) * Normal * Settings.LocalLighting.Y);
Colour.Z := Round(GetBValue(VXLPalette[V.Colour]) * Normal * Settings.LocalLighting.Z);
Sectors[SectorNum].SetConnectionColours(Direction,Colour);
end
else // Transparent
begin
Sectors[SectorNum].SetConnectionColours(Direction,SetVectorI(0,0,0));
end;
end // Here we go with Master Sector colours...
else
begin
Sectors[SectorNum].SetConnectionColours(Direction,Sectors[0].GetConnectionColours(Direction));
end;
end;
procedure TBZK2File.SetFaceColourWithoutNormals(SectorNum,x,y,z : integer; Direction : TBZKFacesDirection);
var
V : TVoxelUnpacked;
Colour : TVector3i;
begin
// Painting each face works in the following way. First, we check
// the neighboor.
if VoxelSection^.GetVoxelSafe(X,Y,Z,V) then
begin //Two options here: wall or not wall.
if v.Used then
begin // Wall
// We get the colour
Colour.X := Round(GetRValue(VXLPalette[V.Colour]) * Settings.LocalLighting.X);
Colour.Y := Round(GetGValue(VXLPalette[V.Colour]) * Settings.LocalLighting.Y);
Colour.Z := Round(GetBValue(VXLPalette[V.Colour]) * Settings.LocalLighting.Z);
Sectors[SectorNum].SetConnectionColours(Direction,Colour);
end
else // Transparent
begin
Sectors[SectorNum].SetConnectionColours(Direction,SetVectorI(0,0,0));
end;
end // Here we go with Master Sector colours...
else
begin
Sectors[SectorNum].SetConnectionColours(Direction,Sectors[0].GetConnectionColours(Direction));
end;
end;
procedure TBZK2File.BuildColours;
var
i : integer;
Position : TVector3i;
begin
// If we have sectors, let's paint everyone, except the Master Sector.
if High(Sectors) > -1 then
begin
if Settings.ColoursWithNormals then
begin
for i := 1 to High(Sectors) do
begin
Position := Sectors[i].GetVoxelPosition;
// We have to paint 6 faces.
SetFaceColour(i,Position.X,Position.Y - PrivateMembers.YInc,Position.Z,bfdNorth);
SetFaceColour(i,Position.X + PrivateMembers.xInc,Position.Y,Position.Z,bfdEast);
SetFaceColour(i,Position.X,Position.Y + PrivateMembers.YInc,Position.Z,bfdSouth);
SetFaceColour(i,Position.X - PrivateMembers.xInc,Position.Y,Position.Z,bfdWest);
SetFaceColour(i,Position.X,Position.Y,Position.Z - PrivateMembers.zInc,bfdFloor);
SetFaceColour(i,Position.X,Position.Y,Position.Z + PrivateMembers.zInc,bfdCeiling);
end;
end
else
begin
for i := 1 to High(Sectors) do
begin
Position := Sectors[i].GetVoxelPosition;
// We have to paint 6 faces.
SetFaceColourWithoutNormals(i,Position.X,Position.Y - PrivateMembers.YInc,Position.Z,bfdNorth);
SetFaceColourWithoutNormals(i,Position.X + PrivateMembers.xInc,Position.Y,Position.Z,bfdEast);
SetFaceColourWithoutNormals(i,Position.X,Position.Y + PrivateMembers.YInc,Position.Z,bfdSouth);
SetFaceColourWithoutNormals(i,Position.X - PrivateMembers.xInc,Position.Y,Position.Z,bfdWest);
SetFaceColourWithoutNormals(i,Position.X,Position.Y,Position.Z - PrivateMembers.zInc,bfdFloor);
SetFaceColourWithoutNormals(i,Position.X,Position.Y,Position.Z + PrivateMembers.zInc,bfdCeiling);
end;
end;
end;
end;
procedure TBZK2File.MoveSideToPosition(Direction : TBZKFacesDirection; Value : Integer);
var
MinBound,MaxBound : TVector3i;
Offset : Integer;
begin
MinBound := GetMinBounds;
MaxBound := GetMaxBounds;
case (Direction) of
bfdNorth:
begin
Offset := Value - MinBound.Y;
MinBound.Y := Value;
MaxBound.Y := MaxBound.Y + Offset;
end;
bfdSouth:
begin
Offset := Value - MaxBound.Y;
MaxBound.Y := Value;
MinBound.Y := MinBound.Y + Offset;
end;
bfdEast:
begin
Offset := Value - MaxBound.X;
MaxBound.X := Value;
MinBound.X := MinBound.X + Offset;
end;
bfdWest:
begin
Offset := Value - MinBound.X;
MinBound.X := Value;
MaxBound.X := MaxBound.X + Offset;
end;
bfdFloor:
begin
Offset := Value - MinBound.Z;
MinBound.Z := Value;
MaxBound.Z := MaxBound.Z + Offset;
end;
bfdCeiling:
begin
Offset := Value - MaxBound.Z;
MaxBound.Z := Value;
MinBound.Z := MinBound.Z + Offset;
end;
end;
SetMinBounds(MinBound);
SetMaxBounds(MaxBound);
end;
// Attach
procedure TBZK2File.Attach(var BZK2File : TBZK2File; Direction : TBZKFacesDirection; Offset : TVector3i);
begin
if Valid and BZK2File.IsValid then
begin
case (Direction) of
bfdNorth:
begin
MoveSideToPosition(Direction,Offset.Y);
end;
bfdSouth:
begin
MoveSideToPosition(Direction,Offset.Y);
end;
bfdEast:
begin
MoveSideToPosition(Direction,Offset.X);
end;
bfdWest:
begin
MoveSideToPosition(Direction,Offset.X);
end;
bfdFloor:
begin
MoveSideToPosition(Direction,Offset.Z);
end;
bfdCeiling:
begin
MoveSideToPosition(Direction,Offset.Z);
end;
end;
end;
end;
end.
|
unit JO5_dmService;
interface
uses
SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, Jo5_Consts, IBase,
pFIBDatabase, RxMemDS, Jo5_Types, FIBQuery, pFIBQuery, pFIBStoredProc, Windows;
const
sMsgOKOpenSystem = 'Cистема успешно переведена в предыдущий период';
sMsgOKCloseSystem = 'Cистема успешно переведена в следующий период';
sMsgErrOpenSystem = 'Не удалось откатить систему в предыдущий период...'#13'Показать расшифровку ошибок для всех неоткатившихся счетов?';
sMsgErrCloseSystem = 'Не удалось перевести систему в следующий период...'#13'Показать расшифровку ошибок для всех непереведённых счетов?';
sMsgNoneOpenSystem = 'Не удалось откатить систему в предыдущий период,'#13'поскольку в текущем периоде отсутствуют закрытые счета';
sMsgNoneCloseSystem = 'Не удалось перевести систему в следующий период,'#13'поскольку в текущем периоде отсутствуют незакрытые счета';
sErrorText = ' Ошибка: ';
sErrorCode = 'Код ошибки: ';
sErrorAddr = 'Адрес ошибки: ';
sErrorSearch = ' не найден';
sErrorTextExt = 'Ошибка: ';
sMsgCaptionErr = 'Ошибка';
sMsgCaptionWrn = 'Предупреждение';
sMsgCaptionInf = 'Информация';
sMsgCaptionQst = 'Подтверждение';
type
TJO5_ServiceDM = class(TDataModule)
dbJO5: TpFIBDatabase;
dstMain: TpFIBDataSet;
trWrite: TpFIBTransaction;
spcMain: TpFIBStoredProc;
trRead: TpFIBTransaction;
dstBuffer: TRxMemoryData;
fldSCH_NUMBER: TStringField;
fldSCH_TITLE: TStringField;
fldSCH_ERROR: TStringField;
private
{ Private declarations }
public
{ Public declarations }
Handle:HWND;
function NextPeriod(id_system:Integer):Integer;
function PrevPeriod(id_system:Integer):Integer;
constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE); reintroduce;
end;
implementation
{$R *.dfm}
uses Jo5_ErrorSch, Kernel, ComObj;
constructor TJO5_ServiceDM.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE);
begin
inherited Create(AOwner);
//******************************************************************************
dbJO5.Handle:=DB_Handle;
trRead.Active:=True;
trWrite.Active:=True;
end;
//Переводим систему в следующий период
function TJO5_ServiceDM.NextPeriod(id_system:Integer):Integer;
var
i, n : Integer;
ModRes : Byte;
IsClose : Boolean;
// MonthNum : String;
fmErrSch : TfmErrorSch;
ResultSchStr : RESULT_STRUCTURE;
PKernelSchStr : PKERNEL_SCH_MNGR_STRUCTURE;
begin
IsClose := True;
Result:=-1;
try
try
//Получаем множество счетов, находящихся в текущем периоде для перевода системы в следующий период
dstMain.Close;
dstMain.SQLs.SelectSQL.Text := 'SELECT * FROM JO5_GET_INFO_TO_CLOSE_PERIOD('+IntToStr(id_system)+')';
dstMain.Open;
// dstMain.Last;
n := dstMain.RecordCount - 1;
// dstMain.First;
//Подготавливаем буфер для протоколирования возможных ошибок отката перевода системы
if dstBuffer.Active then dstBuffer.Close;
dstBuffer.Open;
//Пытаемся перевести систему в следующий период по всем счетам
for i := 0 to n
do begin
try
//Заполняем структуру для менеджера счетов
New( PKernelSchStr );
trWrite.StartTransaction;
PKernelSchStr^.MODE := Ord( mmCloseSch );
PKernelSchStr^.DBHANDLE := dbJO5.Handle;
PKernelSchStr^.TRHANDLE := trWrite.Handle;
PKernelSchStr^.ID_SCH := dstMain.FBN('OUT_ID_SUB_SCH' ).AsVariant;
PKernelSchStr^.DB_OBOR := dstMain.FBN('OUT_DB_OBOROT' ).AsCurrency;
PKernelSchStr^.KR_OBOR := dstMain.FBN('OUT_KR_OBOROT' ).AsCurrency;
PKernelSchStr^.DB_SALDO_IN := dstMain.FBN('OUT_DB_SALDO_INPUT' ).AsCurrency;
PKernelSchStr^.KR_SALDO_IN := dstMain.FBN('OUT_KR_SALDO_INPUT' ).AsCurrency;
PKernelSchStr^.DB_SALDO_OUT := dstMain.FBN('OUT_DB_SALDO_OUTPUT').AsCurrency;
PKernelSchStr^.KR_SALDO_OUT := dstMain.FBN('OUT_KR_SALDO_OUTPUT').AsCurrency;
//Вызываем менеджер счетов
ResultSchStr := SchManager( PKernelSchStr );
trWrite.Commit;
//Анализируем результат перевода текущего счёта
if ResultSchStr.RESULT_CODE = Ord( msrError )
then begin
//Запоминаем информацию для непереведённого счёта
dstBuffer.Insert;
dstBuffer.FieldByName('SCH_NUMBER').Value := dstMain.FBN('OUT_SUB_SCH_NUMBER').AsString;
dstBuffer.FieldByName('SCH_TITLE' ).Value := dstMain.FBN('OUT_SUB_SCH_TITLE' ).AsString;
dstBuffer.FieldByName('SCH_ERROR' ).Value := ResultSchStr.RESULT_MESSAGE;
dstBuffer.Post;
IsClose := False;
Break;
end;
finally
//Освобождаем динамически выделенную память
if PKernelSchStr <> nil
then begin
Dispose( PKernelSchStr );
PKernelSchStr := nil;
end;
end;
dstMain.Next;
end;
//Переводим систему в следующий период + изменяем значения сальдо по всем счетам
if IsClose
then begin
dstMain.First;
trWrite.StartTransaction;
//Обновляем значения сальдо по всем счетам
for i := 0 to n
do begin
//Удалям существующее вступительное сальдо для следующего периода
spcMain.StoredProcName := 'JO5_DT_SALDO_DEL_EXT';
spcMain.Prepare;
spcMain.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose );
spcMain.ParamByName('IN_ID_SCH' ).AsInt64 := dstMain.FBN('OUT_ID_SUB_SCH').AsVariant;
spcMain.ParamByName('ID_SYSTEM').asInteger := id_system;
spcMain.ExecProc;
//Добавляем пресчитанное вступительное сальдо для следующего периода
spcMain.StoredProcName := 'JO5_DT_SALDO_INS_EXT';
spcMain.Prepare;
spcMain.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose );
spcMain.ParamByName('IN_ID_SCH' ).AsInt64 := dstMain.FBN('OUT_ID_SUB_SCH').AsVariant;
spcMain.ParamByName('ID_SYSTEM').Value := id_system;
spcMain.ExecProc;
dstMain.Next;
end;
//Переводим систему в следующий период
if n <> -1
then begin
spcMain.StoredProcName := 'JO5_INI_SETUP_UPDATE_KOD_PERIOD';
spcMain.Prepare;
spcMain.ParamByName('IN_ID_SYSTEM').Value:=id_system;
spcMain.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smClose );
spcMain.Prepare;
spcMain.ExecProc;
//Получаем данные для текущего периода системы
Result := spcMain.FN('OUT_KOD_CURR_PERIOD').AsInteger;
end;
trWrite.Commit;
//Оповещаем пользователя о результатах перевода системы в следующий период
if n <> -1
then
MessageBox( Handle, PChar( sMsgOKCloseSystem ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION )
else
MessageBox( Handle, PChar( sMsgNoneCloseSystem ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING );
end
else begin
ModRes := MessageBox( Handle, PChar( sMsgErrCloseSystem ), PChar( sMsgCaptionErr ), MB_YESNO or MB_ICONERROR );
//Показываем расшифровку ошибок по счетам
if ModRes = ID_YES
then begin
try
fmErrSch := TfmErrorSch.Create( Self, dstBuffer );
fmErrSch.ShowModal;
finally
FreeAndNil( fmErrSch );
end;
end;
end;
dstBuffer.Close;
except
//Завершаем транзанкцию
if trWrite.InTransaction
then
trWrite.Rollback;
//Освобождаем память для НД
if dstBuffer.Active
then
dstBuffer.Close;
//Протоколируем ИС
// LogException( dmdDataModul.pSysOptions.LogFileName );
Raise;
end;
except
on E: Exception
do begin
MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR );
end;
end;
end;
//Откатываем систему в предыдущий период
function TJO5_ServiceDM.PrevPeriod(id_system:Integer):Integer;
var
i, n : Integer;
ModRes : Byte;
IsOpen : Boolean;
// MonthNum : String;
fmErrSch : TfmErrorSch;
ResultSchStr : RESULT_STRUCTURE;
PKernelSchStr : PKERNEL_SCH_MNGR_STRUCTURE;
begin
Result:=-1;
try
try
//Получаем множество счетов, находящихся в текущем периоде для отката системы в предыдущий период
dstMain.Close;
dstMain.SQLs.SelectSQL.Text := 'SELECT * FROM JO5_GET_ALL_SCH_TO_OPEN_PERIOD('+IntToStr(id_system)+')';
dstMain.Open;
// dstMain.Last;
n := dstMain.RecordCount - 1;
// dstMain.First;
//Подготавливаем буфер для протоколирования возможных ошибок отката системы
if dstBuffer.Active then dstBuffer.Close;
dstBuffer.Open;
IsOpen := True;
//Пытаемся откатить систему в предыдущий период по всем счетам
for i := 0 to n
do begin
try
//Заполняем структуру для менеджера счетов
New( PKernelSchStr );
trWrite.StartTransaction;
PKernelSchStr^.MODE := Ord( mmOpenSch );
PKernelSchStr^.DBHANDLE := dbJO5.Handle;
PKernelSchStr^.TRHANDLE := trWrite.Handle;
PKernelSchStr^.ID_SCH := dstMain.FBN('OUT_ID_SUB_SCH').AsVariant;
//Вызываем менеджер счетов
ResultSchStr := SchManager( PKernelSchStr );
trWrite.Commit;
//Анализируем результат отката текущего счёта
if ResultSchStr.RESULT_CODE = Ord( msrError )
then begin
//Запоминаем информацию для неоткатившегося счёта
dstBuffer.Insert;
dstBuffer.FieldByName('SCH_NUMBER').Value := dstMain.FBN('OUT_SUB_SCH_NUMBER').AsString;
dstBuffer.FieldByName('SCH_TITLE' ).Value := dstMain.FBN('OUT_SUB_SCH_TITLE' ).AsString;
dstBuffer.FieldByName('SCH_ERROR' ).Value := ResultSchStr.RESULT_MESSAGE;
dstBuffer.Post;
IsOpen := False;
end;
finally
//Освобождаем динамически выделенную память
if PKernelSchStr <> nil
then begin
Dispose( PKernelSchStr );
PKernelSchStr := nil;
end;
end;
dstMain.Next;
end;
//Оповещаем пользователя о результатах отката системы
if IsOpen
then begin
//Выполняем откат системы в предыдущий период
if n <> -1
then begin
//Подготавливаем к выполнению процедуру для отката системы в предыдущий период
spcMain.StoredProcName := 'JO5_INI_SETUP_UPDATE_KOD_PERIOD';
spcMain.ParamByName('IN_ID_SYSTEM').AsInteger := id_system;
spcMain.ParamByName('IN_CLOSE_PERIOD_BOOL').AsInteger := Ord( smOpen );
//Откатываем систему в предыдущий период
trWrite.StartTransaction;
spcMain.Prepare;
spcMain.ExecProc;
trWrite.Commit;
//Получаем данные для текущего периода системы
Result := spcMain.FN('OUT_KOD_CURR_PERIOD').AsInteger;
{ with dmdDataModul.pSysOptions
do begin
KodCurrPeriod := spcMain.FN('OUT_KOD_CURR_PERIOD' ).AsInteger;
DateCurrPeriod := spcMain.FN('OUT_DATE_CURR_PERIOD').AsDate;
//Обновляем значение текущего периода
MonthNum := IntToStr( MonthOf( DateCurrPeriod ) );
SetFirstZero( MonthNum );
mnuCurrPeriod.Caption := sMMenuCurrPeriodRUS + cBRAKET_OP + MonthNum + cBRAKET_CL + cSPACE + cMonthRUS[ StrToInt( MonthNum ) - 1 ] + cSPACE + IntToStr( YearOf( DateCurrPeriod ) ) + cYEAR_RUS_SHORT;
end; }
MessageBox( Handle, PChar( sMsgOKOpenSystem ), PChar( sMsgCaptionInf ), MB_OK or MB_ICONINFORMATION );
end
else begin
MessageBox( Handle, PChar( sMsgNoneOpenSystem ), PChar( sMsgCaptionWrn ), MB_OK or MB_ICONWARNING );
end;
end
else begin
ModRes := MessageBox( Handle, PChar( sMsgErrOpenSystem ), PChar( sMsgCaptionErr ), MB_YESNO or MB_ICONERROR );
//Показываем расшифровку ошибок по счетам
if ModRes = ID_YES
then begin
try
fmErrSch := TfmErrorSch.Create( Self, dstBuffer );
fmErrSch.ShowModal;
finally
FreeAndNil( fmErrSch );
end;
end;
end;
dstBuffer.Close;
except
//Завершаем транзанкцию
if trWrite.InTransaction
then
trWrite.Rollback;
//Освобождаем память для НД
if dstBuffer.Active
then
dstBuffer.Close;
//Протоколируем ИС
// LogException( dmdDataModul.pSysOptions.LogFileName );
Raise;
end;
except
on E: Exception
do begin
MessageBox( Handle, PChar( sErrorTextExt + E.Message ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR );
end;
end;
end;
end.
|
unit uAddCountry;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ActnList, StdCtrls, cxButtons, cxLabel,
cxControls, cxContainer, cxEdit, cxTextEdit, FIBDatabase, pFIBDatabase, IBase,
DB, FIBDataSet, pFIBDataSet, FIBQuery, pFIBQuery, pFIBStoredProc, Address_ZMessages,
AdrSp_Types;
type
TAdd_Country_Form = class(TAdrEditForm)
NameTE: TcxTextEdit;
NameLbl: TcxLabel;
AcceptBtn: TcxButton;
CancelBtn: TcxButton;
ActionList: TActionList;
AcceptAction: TAction;
CancelAction: TAction;
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
DSet: TpFIBDataSet;
StProc: TpFIBStoredProc;
procedure AcceptActionExecute(Sender: TObject);
procedure CancelActionExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
pIdCountry:Integer;
public
// Mode:TFormMode;
// constructor Create(AOwner: TComponent ; DMod: TAdrDM; Mode: TFormMode; Where: Variant);reintroduce;
constructor Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AIdCountry:Integer=-1);reintroduce;
end;
implementation
{$R *.dfm}
constructor TAdd_Country_Form.Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AIdCountry:Integer=-1);
begin
inherited Create(AOwner);
//******************************************************************************
DB.Handle:=ADB_HANDLE;
StartId:=AIdCountry;
end;
procedure TAdd_Country_Form.AcceptActionExecute(Sender: TObject);
begin
if NameTE.Text='' then
begin
ZShowMessage('Помилка','Вкажіть назву країни',mtError,[mbOK]);
NameTE.SetFocus;
Exit;
end;
try
StProc.StoredProcName:='ADR_COUNTRY_IU';
WriteTransaction.StartTransaction;
StProc.Prepare;
if pIdCountry>-1 then
StProc.ParamByName('ID_C').AsInteger:=pIdCountry;
StProc.ParamByName('NAME_COUNTRY').AsString:=NameTE.Text;
StProc.ExecProc;
ResultId:=StProc.FN('ID_COUNTRY').AsInteger;
WriteTransaction.Commit;
ModalResult:=mrOk;
except
on E:Exception do
begin
WriteTransaction.Rollback;
ZShowMessage('Помилка',E.Message,mtError,[mbOk]);
end;
end;
end;
procedure TAdd_Country_Form.CancelActionExecute(Sender: TObject);
begin
// Ничего не меняли, а, следовательно, обновлять ничего не надо
ResultId:=-1;
ModalResult:=mrCancel;
end;
procedure TAdd_Country_Form.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
ReadTransaction.Active:=False;
end;
procedure TAdd_Country_Form.FormShow(Sender: TObject);
begin
ReadTransaction.Active:=True;
pIdCountry:=StartId;
if pIdCountry>-1 then
begin
// изменение
Caption:='Змінити країну';
if DSet.Active then DSet.Close;
DSet.SQLs.SelectSQL.Text:='SELECT * FROM ADR_COUNTRY_S('+IntToStr(pIdCountry)+')';
DSet.Open;
NameTE.Text:=DSet['NAME_COUNTRY'];
end
else
Caption:='Додати країну';
end;
initialization
RegisterClass(TAdd_Country_Form);
end.
|
(*
Category: SWAG Title: MATH ROUTINES
Original name: 0004.PAS
Description: FIBONACC.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:50
*)
{
>The problem is to Write a recursive Program to calculate Fibonacci numbers.
>The rules For the Fibonacci numbers are:
>
> The Nth Fib number is:
>
> 1 if N = 1 or 2
> The sum of the previous two numbers in the series if N > 2
> N must always be > 0.
}
Function fib(n : LongInt) : LongInt;
begin
if n < 2 then
fib := n
else
fib := fib(n - 1) + fib(n - 2);
end;
Var
Count : Integer;
begin
Writeln('Fib: ');
For Count := 1 to 15 do
Write(Fib(Count),', ');
end.
|
unit fMyPrintDlg;
interface
{
Program Modifications:
-------------------------------------------------------------------------------
Date ID Name Description
-------------------------------------------------------------------------------
10-19-2005 GN01 George Nelson when the default DQCalcPrinter is not installed
the user get an error when trying to do a print mockup.
}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, DBRichEdit, Buttons, checklst, printers, ExtCtrls, Spin, ShellAPI, tMapping;
type
TfrmMyPrintDlg = class(TForm)
CheckListSections: TCheckListBox;
ComboCoverLtr: TComboBox;
cbIncludeQstns: TCheckBox;
btnClearAll: TBitBtn;
btnMarkAll: TBitBtn;
gbPrintWhat: TGroupBox;
lblCoverLtr: TLabel;
btnChangePrinter: TButton;
lblPrinter: TLabel;
PrintDialog: TPrintDialog;
btnPrint: TButton;
btnCancel: TButton;
GBPersonalization: TGroupBox;
pnlGB1: TPanel;
rbFemale: TRadioButton;
rbMale: TRadioButton;
pnlRG2: TPanel;
rbAdult: TRadioButton;
rbMinor: TRadioButton;
pnlRG3: TPanel;
rbDoc: TRadioButton;
rbGroup: TRadioButton;
cbPrintToFile: TCheckBox;
SaveDialog: TSaveDialog;
cbMockupLanguage: TComboBox;
cbQAInfo: TCheckBox;
gbCopies: TGroupBox;
Label1: TLabel;
seCopies: TSpinEdit;
btnPreview: TButton;
checkListSampleUnits: TCheckListBox;
lblSampleUnits: TLabel;
procedure btnChangePrinterClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ComboCoverLtrChange(Sender: TObject);
procedure cbIncludeQstnsClick(Sender: TObject);
procedure btnMarkAllClick(Sender: TObject);
procedure btnClearAllClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnPrintClick(Sender: TObject);
procedure seCopiesKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure seCopiesExit(Sender: TObject);
private
{ Private declarations }
SectionID,CoverID,SampleUnitID : array[0..100] of integer;
PageType : array[0..100] of byte;
CLMappings : MappingSet;
dirtyTag : integer;
procedure IncludeQstns(const PT:integer);
procedure CheckListSectionsEnable(const en:boolean);
function SetLanguage : integer;
procedure SetSections;
procedure ResetSections;
procedure SetCover;
procedure ResetCover;
function installDQCalcPrn : Boolean;
procedure SetupSampleUnits(coverLetterName : string);
public
{ Public declarations }
end;
var
frmMyPrintDlg: TfrmMyPrintDlg;
implementation
uses DOpenQ, uLayoutCalc, FDynaQ, common;
{$R *.DFM}
procedure TfrmMyPrintDlg.btnChangePrinterClick(Sender: TObject);
var dvc,drv,port:array[0..79] of char;
h:thandle;
begin
if PrintDialog.execute then begin
printer.getprinter(dvc,drv,port,h);
if (uppercase(copy(dvc,1,7)) = '\\NRC2\') or (uppercase(copy(port,1,7)) = '\\NRC2\')
or (uppercase(copy(dvc,1,10)) = '\\NEPTUNE\') or (uppercase(copy(port,1,10)) = '\\NEPTUNE\')
or (uppercase(copy(dvc,1,9)) = '\\NRCC02\') or (uppercase(copy(port,1,9)) = '\\NRCC02\') then begin
frmLayoutCalc.curDevice := dvc;
frmLayoutCalc.curPort := port;
if (uppercase(copy(dvc,1,7)) = '\\NRC2\') or (uppercase(copy(dvc,1,10)) = '\\NEPTUNE\') or (uppercase(copy(dvc,1,9)) = '\\NRCC02\') then
frmLayoutCalc.curPort := dvc;
lblPrinter.caption := frmLayoutCalc.curPort;
btnPrint.Enabled := ((uppercase(copy(frmLayoutCalc.curPort,1,7))='\\NRC2\') or (uppercase(copy(frmLayoutCalc.curPort,1,10))='\\NEPTUNE\') or (uppercase(copy(frmLayoutCalc.curPort,1,9))='\\NRCC02\'));
end else begin
messagedlg('Don''t use anything other than a printer on NRC''s network.'+#13+'(dvc='+dvc+' - '+'port='+port+')',mterror,[mbok],0);
end;
end;
end;
procedure tFrmMyPrintDlg.IncludeQstns(const PT:integer);
begin
cbIncludeQstns.enabled := (pt=1);
cbIncludeQstnsClick(self);
end;
procedure TfrmMyPrintDlg.FormCreate(Sender: TObject);
begin
with cbMockupLanguage, dmOpenQ.t_Language do begin
first;
Items.clear;
while not eof do begin
if fieldbyname('UseLang').asboolean then
items.add(trimleft(fieldbyname('Language').text+' '+fieldbyname('LangID').asstring));
next;
end;
if items.count<=1 then
visible := false
else
itemindex := 0;
end;
lblPrinter.caption := frmLayoutCalc.curPort;
btnPrint.Enabled := ((uppercase(copy(frmLayoutCalc.curPort,1,7))='\\NRC2\') or (uppercase(copy(frmLayoutCalc.curPort,1,10))='\\NEPTUNE\') or (uppercase(copy(frmLayoutCalc.curPort,1,9))='\\NRCC02\'));
rbFemale.checked := (vSex='Female');
rbMale.checked := (vSex='Male');
rbAdult.checked := (vAge='Adult');
rbMinor.checked := (vAge='Minor');
rbGroup.checked := (vDoc='Group');
rbDoc.checked := (vDoc='Doctor');
cbQAInfo.checked := false;
with dmOpenQ, wwt_Qstns do begin
disableControls;
filtered := false;
checkListSections.Items.clear;
first;
while not eof do begin
if (wwt_QstnsSubtype.value=stSection) and (wwt_QstnsSection.value>0) and (wwt_QstnsLanguage.value=1) then begin
checkListSections.Items.add(wwt_QstnsLabel.value);
checkListSections.checked[checkListSections.Items.count-1] := true;
SectionID[checkListSections.Items.count-1] := wwt_QstnsSection.value;
end;
next;
end;
filtered := true;
EnableControls;
end;
with dmOpenQ, wwt_Cover do begin
disablecontrols;
filtered := false;
ComboCoverLtr.Items.clear;
first;
while not eof do begin
if (wwt_Cover.fieldbyname('PageType').value <> 4 {ptArtifacts}) then begin
ComboCoverLtr.Items.add(fieldbyname('Description').value);
CoverID[ComboCoverLtr.Items.count-1] := wwt_Cover.fieldbyname('SelCover_ID').value;
PageType[ComboCoverLtr.Items.count-1] := wwt_Cover.fieldbyname('PageType').value;
end;
next;
end;
ComboCoverLtr.ItemIndex := 0;
cbIncludeQstns.checked := (PageType[0]=1);
IncludeQstns(PageType[0]);
filtered := true;
EnableControls;
end;
//TODO CJB Populate new checklistSampleUnits from mappings for the selected cover letter from dmOpenQ.MappedSampleUnitsByCL
SetupSampleUnits(ComboCoverLtr.Items[ComboCoverLtr.ItemIndex]);
end;
procedure TfrmMyPrintDlg.SetupSampleUnits(coverLetterName : string);
var sSampleUnits : string;
i : integer;
begin
sSampleUnits := dmOpenQ.MappedSampleUnitsByCL(coverLetterName);
checklistSampleUnits.Items.Clear();
i := 0;
fillchar(SampleUnitId, sizeof(SampleUnitId), #0);
while sSampleUnits <> '' do begin
SampleUnitId[i] := StrToInt(Copy(sSampleUnits,0,Pos('=',sSampleUnits) - 1));
checkListSampleUnits.Items.add(Copy(sSampleUnits,Pos('=',sSampleUnits) + 1, Pos(';',sSampleUnits) - Pos('=',sSampleUnits) - 1));
sSampleUnits := Copy(sSampleUnits, Pos(';', sSampleUnits) + 1, length(sSampleUnits) - Pos(';', sSampleUnits));
inc(i);
end ;
end;
procedure TfrmMyPrintDlg.ComboCoverLtrChange(Sender: TObject);
begin
IncludeQstns(PageType[ComboCoverLtr.itemindex]);
//TODO CJB update checklistSampleUnits from mappings for the selected cover letter
SetupSampleUnits(ComboCoverLtr.Items[ComboCoverLtr.ItemIndex]);
end;
procedure TfrmMyPrintDlg.cbIncludeQstnsClick(Sender: TObject);
begin
CheckListSections.enabled := (cbIncludeQstns.checked);
btnClearAll.enabled := (cbIncludeQstns.checked);
btnMarkAll.enabled := (cbIncludeQstns.checked);
CheckListSectionsEnable(cbIncludeQstns.checked);
end;
procedure TfrmMyPrintDlg.btnMarkAllClick(Sender: TObject);
var i : integer;
begin
for i := 0 to CheckListSections.Items.count-1 do
checklistsections.checked[i] := true;
end;
procedure TfrmMyPrintDlg.btnClearAllClick(Sender: TObject);
var i : integer;
begin
for i := 0 to CheckListSections.Items.count-1 do
checklistsections.checked[i] := false;
end;
procedure tfrmMyPrintDlg.CheckListSectionsEnable(const en:boolean);
begin
with checklistsections do
if en then
font.color := clWindowText
else
font.color := clGrayText;
end;
procedure TfrmMyPrintDlg.btnCancelClick(Sender: TObject);
begin
close;
end;
procedure TfrmMyPrintDlg.btnPrintClick(Sender: TObject);
procedure ViewPDF(fn:string);
var local : string;
i : integer;
begin
local := dmOpenQ.tempdir+'\'+extractFileName(fn);
i := 0;
while not fileexists(fn) do begin
pause(1);
inc(i);
if i=10 then begin
messagedlg('Can''t find ' + fn,mterror,[mbok],0);
break;
end;
end;
copyfile(pchar(fn),pchar(local),false);
deletefile(fn);
ShellExecute(Handle, PChar('Open'), PChar(local),nil , PChar(dmOpenQ.tempdir), SW_SHOWNORMAL);
end;
procedure deletepdf(fn:string);
begin
repeat
if fileexists(fn) and not deletefile(fn) then
if messagedlg('Please close any open print preview windows.'+#13+'('+fn+')',mtWarning,[mbok,mbCancel],0) = mrCancel then
raise Exception.create('Can''t delete '+fn);
until not fileexists(fn);
end;
var PrinterOn:boolean;
src2,cvr,prn : string;
copies : integer;
isPreview : boolean;
begin
try
isPreview := tButton(sender).name = 'btnPreview';
screen.cursor := crHourGlass;
btnPrint.enabled := false;
btnCancel.enabled := false;
btnPreview.enabled := false;
if rbFemale.checked then vSex:='Female' else vSex:='Male';
if rbAdult.checked then vAge:='Adult' else vAge:='Minor';
if rbGroup.checked then vDoc:='Group' else vDoc:='Doctor';
SetCover;
frmLayoutCalc.IncludeQstns := (cbIncludeQstns.checked) and (cbIncludeQstns.enabled);
//if frmLayoutCalc.IncludeQstns then
SetSections;
if cbQAInfo.checked then
frmLayoutCalc.mockup := ptCodeSheetMockup
else
frmLayoutCalc.mockup := ptMockup;
frmLayoutCalc.match := 'G';
PrinterOn := printer.printing;
if not PrinterOn then begin
if not installDQCalcPrn then exit;
frmLayoutCalc.StartCalc;
end;
src2 := dmOpenQ.tempdir+'\QPMockup.prn';
if fileexists(src2) then
deletefile(src2);
frmLayoutCalc.SetFonts;
frmLayoutCalc.SurveyGen('');
if not PrinterOn then frmLayoutCalc.EndCalc;
if not fileexists(src2) then
frmLayoutCalc.makeMockupFile('INITIALIZATION',src2);
if isPreview then begin
if fileexists(src2) then begin
deletepdf(dmopenq.tempdir + '\' + computername + '.pdf');
deletepdf(dmopenq.tempdir + '\' + computername + '_cover.pdf');
deletepdf(dmopenq.prndir + '\' + computername + '.pdf');
deletepdf(dmopenq.prndir + '\' + computername + '_cover.pdf');
prn := dmopenq.prndir + '\' + computername + '.prn';
copyfile(pchar(src2),pchar(prn),false);
if not frmLayoutCalc.integratedcover then begin
cvr := dmopenq.prndir + '\' + computername + '_cover.prn';
src2 := dmOpenQ.tempdir+'\QPMockup_cover.prn';
copyfile(pchar(src2),pchar(cvr),false);
cvr := copy(cvr,1,pos(extractfileext(cvr),cvr)) + 'pdf';
ViewPDF(cvr)
end;
prn := copy(prn,1,pos(extractfileext(prn),prn)) + 'pdf';
ViewPDF(prn);
end;
end else if cbPrintToFile.checked then begin
savedialog.DefaultExt := '*.prn';
savedialog.Filter := 'Print files (*.prn)|*.prn';
if fileexists(src2) and SaveDialog.execute then begin
copyfile(pchar(src2),pchar(savedialog.filename),false);
if not frmLayoutCalc.integratedcover then begin
cvr := extractfilename(savedialog.filename);
if extractfileext(cvr)='' then cvr := cvr + '.prn';
insert('_cover',cvr,pos(extractfileext(cvr),cvr));
cvr := extractfilepath(savedialog.filename)+cvr;
src2 := dmOpenQ.tempdir+'\QPMockup_cover.prn';
copyfile(pchar(src2),pchar(cvr),false);
end;
end;
end else begin
for copies := 1 to seCopies.Value do begin
if not frmLayoutCalc.integratedcover then begin
src2 := dmOpenQ.tempdir+'\QPMockup_cover.prn';
if fileexists(src2) then
copyfile(pchar(src2),pchar(frmLayoutCalc.curPort),false);
end;
src2 := dmOpenQ.tempdir+'\QPMockup.prn';
if fileexists(src2) then
copyfile(pchar(src2),pchar(frmLayoutCalc.curPort),false);
end;
end;
finally
ResetSections;
ResetCover;
dmopenq.wwt_QstnsEnableControls;
screen.cursor := crDefault;
if isPreview then begin
btnPrint.enabled := true;
btnCancel.enabled := true;
btnPreview.enabled := true;
end else
close;
end;
end;
procedure tfrmMyPrintDlg.SetCover;
var
i,j : integer;
SelectedSampleUnitID : array[0..100] of integer;
begin
with dmOpenQ do begin
CurrentLanguage := SetLanguage;
// TODO CJB copy desired cover letter to new cover letter which will include mapping substitutions
CLMappings := MappedTextBoxesByCL(ComboCoverLtr.Items[ComboCoverLtr.ItemIndex]);
if CLMappings[0].SampleUnit <> 0 then begin
dirtyTag := dmOpenQ.SaveDialog.Tag;
F_DynaQ.TabSet1.TabIndex := CoverID[ComboCoverLtr.Itemindex]; //CJB 11/18/2014 need this to copy from right cover letter
F_DynaQ.NewCoverLetter('[DynamicMockup]',true);
wwT_Cover.findkey([glbSurveyID,F_DynaQ.TabSet1.tabs.count - 1]);
fillchar(SelectedSampleUnitID, sizeof(SelectedSampleUnitID), #0);
j := 0;
for i := 0 to checkListSampleUnits.Items.Count - 1 do
if checkListSampleUnits.Checked[i] then begin
SelectedSampleUnitID[j] := SampleUnitId[i];
inc(j);
end;
F_DynaQ.SubstituteTextBoxContentsForSampleUnits(SelectedSampleUnitID, CLMappings);
end
else
wwT_Cover.findkey([glbSurveyID,CoverID[ComboCoverLtr.Itemindex]]);
wwt_Logo.IndexName := 'ByCover';
wwt_PCL.IndexName := 'ByCover';
wwt_TextBox.IndexName := 'ByCover';
wwt_Logo.masterSource := wwDS_Cover;
wwt_Logo.masterfields := 'Survey_ID;SelCover_ID';
wwt_PCL.MasterSource := wwDS_Cover;
wwt_PCL.Masterfields := 'Survey_ID;SelCover_ID';
wwt_TextBox.MasterSource := wwDS_Cover;
wwt_TextBox.Masterfields := 'Survey_ID;SelCover_ID';
end;
end;
function tfrmMyPrintDlg.SetLanguage : integer;
var i : integer;
begin
with cbMockupLanguage do
if visible then
i := strtointdef(trim(copy(items[itemindex],length(items[itemindex])-1,2)),1)
else
i := 1;
result := i;
end;
procedure tfrmMyPrintDlg.SetSections;
var
i : integer;
begin
i := SetLanguage;
if frmLayoutCalc.IncludeQstns then
with dmOpenq.ww_Query do begin
close;
Databasename := '_PRIV';
SQL.clear;
SQL.add('Update Sel_Qstns Set Type=''Mockup'' where Subtype=3 and language='+inttostr(i)+' and (');
for i := 0 to CheckListSections.Items.count-1 do
if CheckListSections.Checked[i] then
SQL.add(' '+qpc_Section+'='+inttostr(sectionid[i])+' OR ');
if SQL.count = 1 then
sql.add(' '+qpc_Section+'>0 OR ');
SQL.add(' 1=2)');
ExecSQL;
end;
dmOpenQ.wwt_Qstns.OnFilterRecord := dmOpenQ.LanguageFilterRecord;
dmOpenQ.wwt_Scls.OnFilterRecord := dmOpenQ.LanguageFilterRecord;
dmOpenQ.wwt_Textbox.OnFilterRecord := dmOpenQ.LanguageFilterRecord;
dmOpenQ.wwt_PCL.OnFilterRecord := dmOpenQ.LanguageFilterRecord;
end;
procedure tfrmMyPrintDlg.ResetCover;
begin
with dmOpenQ do begin
wwt_Logo.masterSource := nil;
wwt_PCL.MasterSource := nil;
wwt_TextBox.MasterSource := nil;
wwt_Logo.IndexFieldnames := '';
wwt_PCL.IndexFieldnames := '';
wwt_TextBox.IndexFieldnames := '';
if CLMappings[0].SampleUnit <> 0 then begin
F_DynaQ.DeleteCL(F_DynaQ.TabSet1.tabs.count - 1);
dmOpenQ.SaveDialog.Tag := dirtyTag;
end ;
end;
end;
procedure tfrmMyPrintDlg.ResetSections;
begin
if frmLayoutCalc.IncludeQstns then
with dmOpenq.ww_Query do begin
close;
Databasename := '_PRIV';
SQL.clear;
SQL.add('Update Sel_Qstns Set Type=''Question'' where Type=''Mockup''');
ExecSQL;
end;
dmOpenQ.wwt_Qstns.OnFilterRecord := dmOpenQ.wwt_QstnsFilterRecord;
dmOpenQ.wwt_Scls.OnFilterRecord := dmOpenQ.EnglishFilterRecord;
dmOpenQ.wwt_Textbox.OnFilterRecord := dmOpenQ.EnglishFilterRecord;
dmOpenQ.wwt_PCL.OnFilterRecord := dmOpenQ.EnglishFilterRecord;
end;
procedure TfrmMyPrintDlg.seCopiesKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if seCopies.value < 1 then seCopies.value := 1;
end;
procedure TfrmMyPrintDlg.seCopiesExit(Sender: TObject);
begin
if seCopies.value < 1 then seCopies.value := 1;
end;
//GN01: silent install DQCalcPrinter
function TfrmMyPrintDlg.installDQCalcPrn : Boolean;
var
i : integer;
SEInfo : TShellExecuteInfo;
// ExitCode : DWORD;
ExecuteFile,
ParamString : string;
// StartInString
begin
i := 0;
//check if the printer is installed
while (i<printer.printers.count-1) and (copy(printer.printers[i],1,13)<>'DQCalcPrinter') do
inc(i);
result := copy(printer.printers[i],1,13)='DQCalcPrinter';
if not result then begin
ChDir('C:\WINDOWS\system32');
//StartInString := 'C:\WINDOWS\system32';
ExecuteFile:='C:\WINDOWS\system32\cmd.exe';
ParamString := '/C cscript prnmngr.vbs -a -p DQCalcPrinter -m "HP LaserJet IIISi" -r c:\temp\pcl.prn ' + #0;
FillChar(SEInfo, SizeOf(SEInfo), 0);
SEInfo.cbSize := SizeOf(TShellExecuteInfo);
with SEInfo do begin
fMask := SEE_MASK_NOCLOSEPROCESS;
Wnd := Application.Handle;
lpFile := PChar(ExecuteFile);
//ParamString contains the application parameters.
lpParameters := PChar(ParamString);
//StartInString specifies the name of the working directory.
//If ommited, the current directory is used.
//lpDirectory := PChar(StartInString);
nShow := SW_HIDE; //SW_SHOWNORMAL;
end;
if ShellExecuteEx(@SEInfo) then begin
{
repeat
Application.ProcessMessages;
GetExitCodeProcess(SEInfo.hProcess, ExitCode);
until (ExitCode <> STILL_ACTIVE) or
Application.Terminated;
}
//You can force a rebuild of the printer list the hard way with
Printer.Free;
SetPrinter( TPrinter.Create );
result := true;
end
else begin
ShowMessage('Error installing DQCalc Printer. Please contact Helpdesk!');
result := false;
end;
end;
end;
end.
|
(*
-----------------------------------------------------------
Name: $File: //depot/Reporting/Mainline/sdk/VCL/Delphi/UCrpeUtl.pas $
Version: $Revision: #9 $
Last Modified Date: $Date: 2004/01/27 $
Copyright (c) 2001-2003 Crystal Decisions, Inc.
895 Emerson St., Palo Alto, California, USA 94301.
All rights reserved.
This file contains confidential, proprietary information, trade secrets and copyrighted expressions
that are the property of Crystal Decisions, Inc., 895 Emerson St., Palo Alto, California, USA 94301.
Any disclosure, reproduction, sale or license of all or any part of the information or expression
contained in this file is prohibited by California law and the United States copyright law, and may
be subject to criminal penalties.
If you are not an employee of Crystal Decisions or otherwise authorized in writing by Crystal Decisions
to possess this file, please contact Crystal Decisions immediately at the address listed above.
-----------------------------------------------------------
Utility Functions used with the Crystal Reports VCL (UCRPE32)
=============================================================
Language : Delphi 7 / C++ Builder 6
*)
unit UCrpeUtl;
{$I UCRPEDEF.INC}
interface
uses
Classes, Windows, Graphics, Forms, CRDynamic;
function IsNumeric(Value: string): boolean;
function IsFloating(Value: string): boolean;
function IsQuoted(Value: string): boolean;
function IsStrEmpty (const sValue: string): boolean;
function TruncStr (sValue: string): string;
function RemoveSpaces (const sValue: string): string;
procedure RemoveChar (var sValue: string; ch: Char);
function GetToken(var s: string; const sDelimiter: string): string;
function IsStringListEmpty (const sList : TStrings): boolean;
function RTrimList (const sList: TStrings): string;
function AddBackSlash(const sPath: string): string;
function MakeCRLF (Value: string): string;
function GetStrFromRsc(RscNum: integer): string;
function GetErrorNum(const sError: string): integer;
function GetErrorStr(const sError: string): string;
function GetPathFromAlias(const sAlias: string; var sPath: string): boolean;
function GetVersionInfo(const Filename: string; const Key: string; var sVersion: string): DWord;
procedure CopyDevMode(var SourceDM: TDevMode; var DestinationDM: TDevMode);
function ColorState(Enable: boolean): TColor;
function NameToCrFormulaFormat(const Name: string; InstanceName: string): string;
function CrFormulaFormatToName(const ffName: string): string;
function CrGetTempPath : string;
function CrGetTempName (const Extension: string) : string;
{String/Boolean/Integer/Floating/Date/Time conversion}
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 CrStrToDate (const sValue: string; var dValue: TDateTime): boolean;
function CrDateToStr (const dValue: TDateTime): string;
function CrStrToDateTime (const sValue: string; var dtValue: TDateTime): boolean;
function CrDateTimeToStr (const dtValue: TDateTime; bMSec: boolean): string;
function CrStrToTime (const sValue: string; var tValue: TDateTime): boolean;
function CrTimeToStr (const tValue: TDateTime): string;
function ExDateTimeStr (sValue: string; var sYear, sMonth,
sDay, sHour, sMin, sSec: string): boolean;
function ExDateStr (sValue: string; var sYear, sMonth, sDay: string): boolean;
function ExTimeStr (sValue: string; var sHour, sMin, sSec: string): boolean;
function StrToValueInfo (const sValue: string; var ValueInfo: PEValueInfo): boolean;
function ValueInfoToStr (var ValueInfo: PEValueInfo): string;
function DrillValueInfoToStr (var ValueInfo: PEDrillValueInfo): string;
procedure ValueInfoToDefault(var ValueInfo: PEValueInfo);
function StrToSectionCode(const Value: string; var nCode: Smallint): boolean;
function SectionCodeToStr(const Value: smallint): string;
function AreaCodeToStr(const Value: smallint): string;
{Twips/Inches/Points conversion}
function TwipsToInches(iValue: integer): double;
function InchesToTwips(fValue: double): integer;
function TwipsToInchesStr(iValue: integer): string;
function InchesStrToTwips(sValue: string): integer;
function CompareTwipsToInches(iTwips: integer; dInches: double): boolean;
function TwipsToPoints(iValue: integer): double;
function PointsToTwips(fValue: double): integer;
function TwipsToPointsStr(iValue: integer): string;
function PointsStrToTwips(sValue: string): integer;
function CompareTwipsToPoints(iTwips: integer; dPoints: double): boolean;
{Form Position}
procedure LoadFormPos(frmTemp: TForm);
procedure SaveFormPos(frmTemp: TForm);
procedure LoadFormSize(frmTemp: TForm);
procedure SaveFormSize(frmTemp: TForm);
{Crystal Specific}
function GetCommonFilesPath : string;
implementation
uses SysUtils, Registry, DBTables;
{******************************************************************************}
{ 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
if Ord(s[i]) = Ord(DecimalSeparator) then
begin
if HasDecimal then
begin
Result := False;
Exit;
end
else
begin
HasDecimal := True;
Continue;
end;
end
else
begin
Result := False;
Exit;
end;
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;
{------------------------------------------------------------------------------}
{ GetPathFromAlias function }
{ - Pulls a Path from a BDE Alias }
{------------------------------------------------------------------------------}
function GetPathFromAlias(const sAlias: string; var sPath: string): boolean;
var
sLoc : string;
N : integer;
AliasNames : TStringList;
AliasParms : TStringList;
begin
Result := False;
{Fill the Alias Names stringlist}
AliasNames := TStringList.Create;
Session.GetAliasNames(AliasNames);
{Pull the Alias name from the Alias string}
sLoc := Copy(sAlias, 2, Length(sAlias) - 2);
{Find Alias name in list}
N := AliasNames.IndexOf(sLoc);
{If it exists...}
if N <> -1 then
{Get the Alias Parameters}
begin
{Create AliasParms stringlist}
AliasParms := TStringList.Create;
Session.GetAliasParams(sLoc, AliasParms);
{Get the Path from the Parameters: Try Path}
sLoc := AliasParms.Values['PATH'];
{Get the Path from the Parameters: Try Database Name}
if sLoc = '' then
sLoc := ExtractFilePath(AliasParms.Values['DATABASE NAME']);
{Get the Path from the Parameters: Try Names[0]}
if sLoc = '' then
begin
sLoc := AliasParms.Names[0];
sLoc := ExtractFilePath(AliasParms.Values[sLoc]);
end;
AliasParms.Free;
end
else
begin
AliasNames.Free;
Exit;
end;
{Add trailing backslash to alias path}
if Length(sLoc) > 0 then
begin
if sLoc[Length(sLoc)] <> '\' then
sLoc := sLoc + '\';
end;
sPath := sLoc;
Result := True;
AliasNames.Free;
end;
{------------------------------------------------------------------------------}
{ StrToSectionCode function }
{------------------------------------------------------------------------------}
function StrToSectionCode(const Value: string; var nCode: Smallint): boolean;
const
AreaArray : array[0..6] of string = ('RH','PH','GH','D','GF','PF','RF');
PEAreaArray : array[0..6] of Integer = (1000, 2000, 3000, 4000, 5000, 7000, 8000);
SubArray : array[0..39] of string = ('a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s','t','u','v','w', 'x','y','z',
'aa','ab','ac','ad','ae','af','ag','ah','ai','aj','ak','al','am','an');
var
sTmp : string;
sArea : string; {Section Area string}
sGrp : string; {Group string}
nGrp : smallint; {Group Number}
sSub : string; {SubSection string}
nArea : smallint; {Section Area code}
nSub : smallint; {SubSection code}
sAreaList : TStringList;
sSubList : TStringList;
cnt : smallint;
begin
Result := False;
nCode := 0;
sAreaList := TStringList.Create;
sSubList := TStringList.Create;
{Fill temporary Section lists}
for cnt := Low(AreaArray) to High(AreaArray) do
sAreaList.Add(AreaArray[cnt]);
for cnt := Low(SubArray) to High(SubArray) do
sSubList.Add(SubArray[cnt]);
{Split up the Section string Value}
sTmp := Trim(Value);
if Length(sTmp) > 0 then
begin
{Details area}
sArea := Copy(sTmp,1,1);
if sArea = 'D' then
begin
nGrp := 0;
if Length(sTmp) > 1 then
sSub := Copy(Value,2,Length(sTmp))
else
sSub := 'a';
end
else
begin
{GroupHeader or GroupFooter area}
if sArea = 'G' then
begin
{Get the first two letters: GH, GF}
if Length(sTmp) > 1 then
sArea := Copy(sTmp,1,2)
else
sArea := 'GH';
{Get the group number}
sGrp := '';
for cnt := 3 to Length(sTmp) do
begin
{Pull out the numeric characters}
if IsNumeric(sTmp[cnt]) then
sGrp := sGrp + sTmp[cnt]
else
Break;
end;
{Convert the string to a number}
nGrp := 0;
if IsNumeric(sGrp) then
begin
nGrp := StrToInt(sGrp);
Dec(nGrp);
end;
{Get sub-section letters}
sSub := '';
while cnt <= Length(sTmp) do
begin
if Ord(sTmp[cnt]) > 64 then
sSub := sSub + sTmp[cnt];
Inc(cnt);
end;
if sSub = '' then
sSub := 'a';
end
{Any other Area type: RH, PH, etc.}
else
begin
if Length(sTmp) > 1 then
sArea := Copy(sTmp,1,2)
else
sArea := 'RH';
nGrp := 0;
if Length(sTmp) > 2 then
sSub := Copy(sTmp,3,Length(sTmp))
else
sSub := 'a';
end;
end;
{Translate to Section Code}
nArea := sAreaList.IndexOf(sArea);
if nArea > -1 then
nArea := PEAreaArray[nArea]
else
begin
sAreaList.Free;
sSubList.Free;
Exit;
end;
nSub := sSubList.IndexOf(sSub);
if nSub > -1 then
nSub := nSub * 25
else
begin
sAreaList.Free;
sSubList.Free;
Exit;
end;
nCode := nArea + nGrp + nSub;
end
else
begin
sAreaList.Free;
sSubList.Free;
Exit;
end;
sAreaList.Free;
sSubList.Free;
Result := True;
end; { StrToSectionCode }
{------------------------------------------------------------------------------}
{ AreaCodeToStr function }
{------------------------------------------------------------------------------}
function AreaCodeToStr(const Value: smallint): string;
var
nGroup : Smallint;
nType : Smallint;
sTmp : string;
begin
sTmp := '';
{Get Area}
nType := PE_SECTION_TYPE(Value);
case nType of
1: sTmp := 'RH'; {RH}
2: sTmp := 'PH'; {PH}
3: begin
sTmp := 'GH'; {GH}
nGroup := PE_GROUP_N(Value);
Inc(nGroup);
sTmp := sTmp + IntToStr(nGroup);
end;
4: sTmp := 'D'; {D}
5: begin
sTmp := 'GF'; {GF}
nGroup := PE_GROUP_N(Value);
Inc(nGroup);
sTmp := sTmp + IntToStr(nGroup);
end;
7: sTmp := 'PF'; {PF}
8: sTmp := 'RF'; {RF}
end;
Result := sTmp;
end;
{------------------------------------------------------------------------------}
{ SectionCodeToStr function }
{------------------------------------------------------------------------------}
function SectionCodeToStr(const Value: smallint): string;
const
SubArray : array[0..39] of string = ('a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s','t','u','v','w', 'x','y','z',
'aa','ab','ac','ad','ae','af','ag','ah','ai','aj','ak','al','am','an');
var
nType,
nGroup,
nSection : smallint;
sTmp : string;
begin
sTmp := '';
{Get Area}
nType := PE_SECTION_TYPE(Value);
case nType of
1: sTmp := 'RH'; {RH}
2: sTmp := 'PH'; {PH}
3: begin
sTmp := 'GH'; {GH}
nGroup := PE_GROUP_N(Value);
Inc(nGroup);
sTmp := sTmp + IntToStr(nGroup);
end;
4: sTmp := 'D'; {D}
5: begin
sTmp := 'GF'; {GF}
nGroup := PE_GROUP_N(Value);
Inc(nGroup);
sTmp := sTmp + IntToStr(nGroup);
end;
7: sTmp := 'PF'; {PF}
8: sTmp := 'RF'; {RF}
end;
{Get Section}
nSection := PE_SECTION_N(Value);
{Get Sub-Section}
if IsStrEmpty(sTmp) or (nSection > 39) or (nSection < 0) then
Result := ''
else
Result := sTmp + SubArray[nSection];
end; { SectionCodeToStr }
{------------------------------------------------------------------------------}
{ 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;
{------------------------------------------------------------------------------}
{ GetErrorNum function }
{ - Extract Error Num from Constant }
{------------------------------------------------------------------------------}
function GetErrorNum(const sError: string): integer;
var
s1,s2 : string;
begin
s1 := sError;
s2 := GetToken(s1, ':');
Result := StrToInt(s2);
end;
{------------------------------------------------------------------------------}
{ GetErrorStr function }
{ - Extract Error String from Constant }
{------------------------------------------------------------------------------}
function GetErrorStr(const sError: string): string;
var
s1,s2 : string;
begin
s1 := sError;
s2 := GetToken(s1, ':');
Result := s1;
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;
{------------------------------------------------------------------------------}
{ StrToValueInfo }
{------------------------------------------------------------------------------}
function StrToValueInfo (const sValue: string; var ValueInfo: PEValueInfo): boolean;
var
sTmp : string;
sY,sM,sD,
sH,sN,sS : string;
begin
Result := False;
sTmp := sValue;
case ValueInfo.valueType of
{Number}
PE_VI_NUMBER :
begin
if IsFloating(sTmp) then
begin
ValueInfo.viNumber := StrToFloat(sTmp);
Result := True;
end;
end;
{Currency}
PE_VI_CURRENCY :
begin
if IsFloating(sTmp) then
begin
ValueInfo.viCurrency := StrToFloat(sTmp);
Result := True;
end;
end;
{Boolean}
PE_VI_BOOLEAN :
begin
if Length(sTmp) > 0 then
begin
{Store boolean value to ValueInfo structure}
ValueInfo.viBoolean := CrStrToBoolean(sTmp);
Result := True;
end;
end;
{Date}
PE_VI_DATE :
begin
if ExDateStr(sTmp, sY, sM, sD) then
begin
ValueInfo.viDate[0] := StrToInt(sY);
ValueInfo.viDate[1] := StrToInt(sM);
ValueInfo.viDate[2] := StrToInt(sD);
Result := True;
end;
end;
{String}
PE_VI_STRING :
begin
StrCopy(PEVIStringType(ValueInfo.viString), PChar(sTmp));
Result := True;
end;
{DateTime}
PE_VI_DATETIME :
begin
if ExDateTimeStr(sTmp, sY, sM, sD, sH, sN, sS) then
begin
ValueInfo.viDateTime[0] := StrToInt(sY);
ValueInfo.viDateTime[1] := StrToInt(sM);
ValueInfo.viDateTime[2] := StrToInt(sD);
ValueInfo.viDateTime[3] := StrToInt(sH);
ValueInfo.viDateTime[4] := StrToInt(sN);
ValueInfo.viDateTime[5] := StrToInt(sS);
Result := True;
end;
end;
{Time}
PE_VI_TIME :
begin
{Store time value to ValueInfo structure}
if ExTimeStr(sTmp, sH, sN, sS) then
begin
ValueInfo.viTime[0] := StrToInt(sH);
ValueInfo.viTime[1] := StrToInt(sN);
ValueInfo.viTime[2] := StrToInt(sS);
Result := True;
end;
end;
PE_VI_INTEGER :
begin
if IsNumeric(sTmp) then
begin
ValueInfo.viInteger := StrToInt(sTmp);
Result := True;
end;
end;
PE_VI_COLOR :
begin
if IsNumeric(sTmp) then
ValueInfo.viColor := StrToInt(sTmp)
else
ValueInfo.viColor := PE_NO_COLOR;
Result := True;
end;
PE_VI_CHAR : ValueInfo.viC := sTmp[1];
PE_VI_LONG :
begin
if IsNumeric(sTmp) then
ValueInfo.viLong := StrToInt(sTmp)
else
ValueInfo.viLong := 0;
Result := True;
end;
end;
end;
{------------------------------------------------------------------------------}
{ ValueInfoToStr }
{------------------------------------------------------------------------------}
function ValueInfoToStr (var ValueInfo: PEValueInfo): string;
var
sTmp : string;
dValue : TDateTime;
tValue : TDateTime;
Year1,
Month1,
Day1,
Hour1,
Min1,
Sec1 : Word;
begin
sTmp := '';
case ValueInfo.ValueType of
{Number}
PE_VI_NUMBER : sTmp := FloatToStrF(ValueInfo.viNumber, ffGeneral, 15, 2);
{Currency}
PE_VI_CURRENCY : sTmp := FloatToStrF(ValueInfo.viCurrency, ffGeneral, 15, 2);
{Boolean}
PE_VI_BOOLEAN : sTmp := CrBooleanToStr(ValueInfo.viBoolean, False);
{Date}
PE_VI_DATE : {YYYY,MM,DD}
begin
if ValueInfo.viDate[0] < 1 then
sTmp := CrDateToStr(Now)
else
begin
Year1 := ValueInfo.viDate[0];
Month1 := ValueInfo.viDate[1];
Day1 := ValueInfo.viDate[2];
dValue := EncodeDate(Year1, Month1, Day1);
sTmp := CrDateToStr(dValue);
end;
end;
{String}
PE_VI_STRING : sTmp := String(ValueInfo.viString);
{DateTime}
PE_VI_DATETIME : {YYYY,MM,DD HH:MM:SS}
begin
if ValueInfo.viDateTime[0] < 1 then
sTmp := CrDateTimeToStr(Now, False)
else
begin
Year1 := ValueInfo.viDateTime[0];
Month1 := ValueInfo.viDateTime[1];
Day1 := ValueInfo.viDateTime[2];
Hour1 := ValueInfo.viDateTime[3];
Min1 := ValueInfo.viDateTime[4];
Sec1 := ValueInfo.viDateTime[5];
dValue := EncodeDate(Year1, Month1, Day1);
tValue := EncodeTime(Hour1, Min1, Sec1, 0);
dValue := dValue + tValue;
sTmp := CrDateTimeToStr(dValue, False);
end;
end;
{Time}
PE_VI_TIME : {HH:MM:SS}
begin
if ValueInfo.viTime[0] < 1 then
sTmp := CrTimeToStr(Now)
else
begin
Hour1 := ValueInfo.viTime[0];
Min1 := ValueInfo.viTime[1];
Sec1 := ValueInfo.viTime[2];
tValue := EncodeTime(Hour1, Min1, Sec1, 0);
sTmp := CrTimeToStr(tValue);
end;
end;
PE_VI_INTEGER : sTmp := IntToStr(ValueInfo.viInteger);
PE_VI_COLOR : sTmp := IntToStr(ValueInfo.viColor);
PE_VI_CHAR : sTmp := ValueInfo.viC;
PE_VI_LONG : sTmp := IntToStr(ValueInfo.viLong);
PE_VI_NOVALUE : sTmp := '';
end;
Result := sTmp;
end;
{------------------------------------------------------------------------------}
{ ValueInfoToStr }
{------------------------------------------------------------------------------}
function DrillValueInfoToStr (var ValueInfo: PEDrillValueInfo): string;
var
sTmp : string;
dValue : TDateTime;
tValue : TDateTime;
Year1,
Month1,
Day1,
Hour1,
Min1,
Sec1 : Word;
begin
sTmp := '';
case ValueInfo.ValueType of
{Number}
PE_VI_NUMBER : sTmp := FloatToStrF(ValueInfo.viNumber, ffGeneral, 15, 2);
{Currency}
PE_VI_CURRENCY : sTmp := FloatToStrF(ValueInfo.viCurrency, ffGeneral, 15, 2);
{Boolean}
PE_VI_BOOLEAN : sTmp := CrBooleanToStr(ValueInfo.viBoolean, False);
{Date}
PE_VI_DATE : {YYYY,MM,DD}
begin
if ValueInfo.viDate[0] < 1 then
sTmp := CrDateToStr(Now)
else
begin
Year1 := ValueInfo.viDate[0];
Month1 := ValueInfo.viDate[1];
Day1 := ValueInfo.viDate[2];
dValue := EncodeDate(Year1, Month1, Day1);
sTmp := CrDateToStr(dValue);
end;
end;
{String}
PE_VI_STRING : sTmp := WideCharToString(ValueInfo.viString);
{DateTime}
PE_VI_DATETIME : {YYYY,MM,DD HH:MM:SS}
begin
if ValueInfo.viDateTime[0] < 1 then
sTmp := CrDateTimeToStr(Now, False)
else
begin
Year1 := ValueInfo.viDateTime[0];
Month1 := ValueInfo.viDateTime[1];
Day1 := ValueInfo.viDateTime[2];
Hour1 := ValueInfo.viDateTime[3];
Min1 := ValueInfo.viDateTime[4];
Sec1 := ValueInfo.viDateTime[5];
dValue := EncodeDate(Year1, Month1, Day1);
tValue := EncodeTime(Hour1, Min1, Sec1, 0);
dValue := dValue + tValue;
sTmp := CrDateTimeToStr(dValue, False);
end;
end;
{Time}
PE_VI_TIME : {HH:MM:SS}
begin
if ValueInfo.viTime[0] < 1 then
sTmp := CrTimeToStr(Now)
else
begin
Hour1 := ValueInfo.viTime[0];
Min1 := ValueInfo.viTime[1];
Sec1 := ValueInfo.viTime[2];
tValue := EncodeTime(Hour1, Min1, Sec1, 0);
sTmp := CrTimeToStr(tValue);
end;
end;
PE_VI_INTEGER : sTmp := IntToStr(ValueInfo.viInteger);
PE_VI_COLOR : sTmp := IntToStr(ValueInfo.viColor);
PE_VI_CHAR : sTmp := ValueInfo.viC;
PE_VI_LONG : sTmp := IntToStr(ValueInfo.viLong);
PE_VI_NOVALUE : sTmp := '';
end;
Result := sTmp;
end;
{------------------------------------------------------------------------------}
{ ValueInfoToDefault }
{------------------------------------------------------------------------------}
procedure ValueInfoToDefault(var ValueInfo: PEValueInfo);
var
Year1, Month1, Day1,
Hour1, Min1, Sec1 : string;
begin
case ValueInfo.valueType of
{Changed Number, Currency, and Integer default to 1, otherwise adding
multiple PromptValues in a row caused an Print Engine error}
PE_VI_NUMBER : ValueInfo.viNumber := 1;
PE_VI_CURRENCY : ValueInfo.viCurrency := 1;
PE_VI_BOOLEAN : ValueInfo.viBoolean := True;
PE_VI_DATE : begin
Year1 := FormatDateTime('yyyy', Now);
ValueInfo.viDate[0] := StrToInt(Year1);
Month1 := FormatDateTime('mm', Now);
ValueInfo.viDate[1] := StrToInt(Month1);
Day1 := FormatDateTime('dd', Now);
ValueInfo.viDate[2] := StrToInt(Day1);
end;
PE_VI_STRING : ValueInfo.viString := '';
PE_VI_DATETIME : begin
Year1 := FormatDateTime('yyyy', Now);
ValueInfo.viDateTime[0] := StrToInt(Year1);
Month1 := FormatDateTime('mm', Now);
ValueInfo.viDateTime[1] := StrToInt(Month1);
Day1 := FormatDateTime('dd', Now);
ValueInfo.viDateTime[2] := StrToInt(Day1);
Hour1 := FormatDateTime('hh', Now);
ValueInfo.viDateTime[3] := StrToInt(Hour1);
Min1 := FormatDateTime('nn', Now);
ValueInfo.viDateTime[4] := StrToInt(Min1);
Sec1 := FormatDateTime('ss', Now);
ValueInfo.viDateTime[5] := StrToInt(Sec1);
end;
PE_VI_TIME : begin
Hour1 := FormatDateTime('hh', Now);
ValueInfo.viTime[0] := StrToInt(Hour1);
Min1 := FormatDateTime('nn', Now);
ValueInfo.viTime[1] := StrToInt(Min1);
Sec1 := FormatDateTime('ss', Now);
ValueInfo.viTime[2] := StrToInt(Sec1);
end;
PE_VI_INTEGER : ValueInfo.viInteger := 1;
PE_VI_COLOR : ValueInfo.viColor := 0;
PE_VI_CHAR : ValueInfo.viC := 'A';
PE_VI_LONG : ValueInfo.viLong := 0;
end;
end;
{------------------------------------------------------------------------------}
{ NameToCrFormulaFormat }
{------------------------------------------------------------------------------}
function NameToCrFormulaFormat(const Name: string; InstanceName: string): string;
var
s1 : string;
begin
Result := Name;
s1 := Trim(Name);
if Length(s1) < 1 then Exit;
if s1[1] <> '{' then
s1 := '{' + s1;
if s1[Length(s1)] <> '}' then
s1 := s1 + '}';
{Formulas}
if LowerCase(InstanceName) = 'formulas' then
begin
if s1[2] <> '@' then
s1 := s1[1] + '@' + Copy(s1, 2, Length(s1));
end;
{ParamFields}
if LowerCase(InstanceName) = 'paramfields' then
begin
if s1[2] <> '?' then
s1 := s1[1] + '?' + Copy(s1, 2, Length(s1));
end;
{RunningTotals}
if LowerCase(InstanceName) = 'runningtotals' then
begin
if s1[2] <> '%' then
s1 := s1[1] + '%' + Copy(s1, 2, Length(s1));
end;
{SQLExpressions}
if LowerCase(InstanceName) = 'sqlexpressions' then
begin
if s1[2] <> '#' then
s1 := s1[1] + '#' + Copy(s1, 2, Length(s1));
end;
Result := s1;
end;
{------------------------------------------------------------------------------}
{ CrFormulaFormatToName }
{------------------------------------------------------------------------------}
function CrFormulaFormatToName(const ffName: string): string;
var
s1 : string;
begin
Result := ffName;
s1 := Trim(ffName);
if Length(s1) < 3 then Exit;
if s1[1] = '{' then
s1 := Copy(s1, 2, Length(s1));
if s1[Length(s1)] = '}' then
s1 := Copy(s1, 1, Length(s1)-1);
{Formulas}
if s1[1] = '@' then
s1 := Copy(s1, 2, Length(s1));
{ParamFields}
if s1[1] = '?' then
s1 := Copy(s1, 2, Length(s1));
{RunningTotals}
if s1[1] = '%' then
s1 := Copy(s1, 2, Length(s1));
{SQLExpressions}
if s1[1] = '#' then
s1 := Copy(s1, 2, Length(s1));
Result := s1;
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;
{------------------------------------------------------------------------------}
{ CrStrToDate }
{------------------------------------------------------------------------------}
function CrStrToDate (const sValue: string; var dValue: TDateTime): boolean;
var
sYear1,
sMonth1,
sDay1 : string;
Year1,
Month1,
Day1 : Word;
sTmp : string;
cnt : integer;
begin
Result := False;
dValue := Now;
sTmp := sValue;
{If Length of string is less than 8, exit}
if Length(sTmp) < 5 then
Exit;
{Extract Year}
sYear1 := GetToken(sTmp, ',');
{If Length of year is zero, exit}
if Length(sYear1) = 0 then
Exit;
if IsNumeric(sYear1) then
Year1 := StrToInt(sYear1)
else
Exit;
{Extract Month}
sMonth1 := GetToken(sTmp, ',');
{If Length of month is less than 1, exit}
if Length(sMonth1) = 0 then
Exit;
if IsNumeric(sMonth1) then
Month1 := StrToInt(sMonth1)
else
Exit;
{Extract Day}
{Trim any leading space}
sTmp := Trim(sTmp);
{If Length of day is less than 1, exit}
if Length(sTmp) = 0 then
Exit;
{Pull out just the Day characters}
if Length(sTmp) > 1 then
begin
{Only the first two characters}
for cnt := 1 to 2 do
begin
{Only Numbers}
if (Ord(sTmp[cnt]) > 47) and (Ord(sTmp[cnt]) < 58) then
sDay1 := sDay1 + sTmp[cnt];
end;
end
else
sDay1 := sTmp;
if IsNumeric(sDay1) then
Day1 := StrToInt(sDay1)
else
Exit;
dValue := EncodeDate(Year1, Month1, Day1);
Result := True;
end;
{------------------------------------------------------------------------------}
{ CrDateToStr }
{------------------------------------------------------------------------------}
function CrDateToStr (const dValue: TDateTime): string;
begin
Result := FormatDateTime('yyyy,mm,dd', dValue);
end;
{------------------------------------------------------------------------------}
{ CrStrToDateTime }
{------------------------------------------------------------------------------}
function CrStrToDateTime (const sValue: string; var dtValue: TDateTime): boolean;
var
sYear1, sMonth1, sDay1,
sHour1, sMin1, sSec1 : string;
Year1, Month1, Day1 : Word;
Hour1, Min1, Sec1, MSec1 : Word;
sTmp : string;
Date1, Time1 : TDateTime;
begin
Result := False;
dtValue := Now;
sTmp := sValue;
if Length(sTmp) < 11 then
Exit;
{Extract Year}
sYear1 := GetToken(sTmp, ',');
{If Length of year is zero, exit}
if Length(sYear1) = 0 then
Exit;
if IsNumeric(sYear1) then
Year1 := StrToInt(sYear1)
else
Exit;
{Extract Month}
sMonth1 := GetToken(sTmp, ',');
{If blank, exit}
if Length(sMonth1) = 0 then
Exit;
if IsNumeric(sMonth1) then
Month1 := StrToInt(sMonth1)
else
Exit;
{Extract Day}
{Look for space between date and time}
sDay1 := GetToken(sTmp, ' ');
{If the space wasn't found...}
if Length(sDay1) = 0 then
begin
{Copy out the first two characters}
sDay1 := Copy(sTmp, 1, 2);
{Remove them from the temp string}
sTmp := Copy(sTmp, 3, Length(sTmp));
end;
{If Length of day is zero, exit}
if Length(sTmp) = 0 then
Exit;
if IsNumeric(sDay1) then
Day1 := StrToInt(sDay1)
else
Exit;
{Extract Hour}
{Just in case: trim out any space}
sTmp := TrimLeft(sTmp);
sHour1 := GetToken(sTmp, ':');
if Length(sHour1) = 0 then
Exit;
if IsNumeric(sHour1) then
Hour1 := StrToInt(sHour1)
else
Exit;
{Extract Min}
sMin1 := GetToken(sTmp, ':');
if Length(sMin1) = 0 then
Exit;
if IsNumeric(sMin1) then
Min1 := StrToInt(sMin1)
else
Exit;
{Extract Sec}
sSec1 := GetToken(sTmp, '.');
{If no milliseconds, take whole string}
if Length(sSec1) = 0 then
begin
sSec1 := sTmp;
sTmp := '';
end;
{If still blank, exit}
if Length(sSec1) = 0 then
Exit;
if IsNumeric(sSec1) then
Sec1 := StrToInt(sSec1)
else
Exit;
{Extract MSec}
{If not valid, make zero}
if Length(sTmp) = 0 then
sTmp := '0';
if IsNumeric(sTmp) then
MSec1 := StrToInt(sTmp)
else
Exit;
Date1 := EncodeDate(Year1, Month1, Day1);
Time1 := EncodeTime(Hour1, Min1, Sec1, MSec1);
dtValue := Date1 + Time1;
Result := True;
end;
{------------------------------------------------------------------------------}
{ CrDateTimeToStr }
{------------------------------------------------------------------------------}
function CrDateTimeToStr (const dtValue: TDateTime; bMSec: boolean): string;
var
Hour1,
Min1,
Sec1,
MSec1 : Word;
begin
if bMSec then
begin
DecodeTime(dtValue, Hour1, Min1, Sec1, MSec1);
Result := FormatDateTime('yyyy-mm-dd hh":"nn":"ss.', dtValue) +
FormatFloat('000', MSec1);
end
else
Result := FormatDateTime('yyyy,mm,dd hh:nn:ss', dtValue);
end;
{------------------------------------------------------------------------------}
{ CrStrToTime }
{------------------------------------------------------------------------------}
function CrStrToTime (const sValue: string; var tValue: TDateTime): boolean;
var
sHour1,
sMin1,
sSec1 : string;
Hour1,
Min1,
Sec1 : Word;
sTmp, sTmp2 : string;
begin
Result := False;
tValue := Now;
sTmp := sValue;
{Extract Hour}
sHour1 := GetToken(sTmp, ':');
{If the colon wasn't found...}
if Length(sHour1) = 0 then
begin
{Copy out the first two characters}
sHour1 := Copy(sTmp, 1, 2);
{Remove them from the temp string}
sTmp := Copy(sTmp, 3, Length(sTmp));
{If the string is still empty, exit}
if Length(sHour1) = 0 then
Exit;
end;
{Check if the string contains the date and remove it}
if Pos(' ', sHour1) > 0 then
sTmp2 := GetToken(sHour1, ' ');
{Try converting to integer}
if IsNumeric(sHour1) then
Hour1 := StrToInt(sHour1)
else
Exit;
{Extract Minute}
sMin1 := GetToken(sTmp, ':');
{If the colon wasn't found...}
if Length(sMin1) = 0 then
begin
{Copy out the first two characters}
sMin1 := Copy(sTmp, 1, 2);
{Remove them from the temp string}
sTmp := Copy(sTmp, 3, Length(sTmp));
end;
{If the string is still empty...}
if Length(sMin1) = 0 then
Exit;
if IsNumeric(sMin1) then
Min1 := StrToInt(sMin1)
else
Exit;
{Extract Seconds}
sSec1 := GetToken(sTmp, '.');
if Length(sSec1) = 0 then
sSec1 := sTmp;
if Length(sSec1) = 0 then
Exit;
if IsNumeric(sSec1) then
Sec1 := StrToInt(sSec1)
else
Exit;
tValue := EncodeTime(Hour1, Min1, Sec1, 0);
Result := True;
end;
{------------------------------------------------------------------------------}
{ CrTimeToStr }
{------------------------------------------------------------------------------}
function CrTimeToStr (const tValue: TDateTime): string;
begin
Result := FormatDateTime('hh:nn:ss', tValue);
end;
{------------------------------------------------------------------------------}
{ ExDateTimeStr }
{------------------------------------------------------------------------------}
function ExDateTimeStr (sValue: string; var sYear, sMonth,
sDay, sHour, sMin, sSec: string): boolean;
begin
Result := False;
{Extract Year}
sYear := GetToken(sValue, ',');
if Length(sYear) = 0 then
Exit;
{Extract Month}
sMonth := GetToken(sValue, ',');
if Length(sMonth) = 0 then
Exit;
{Extract Day}
{Look for space between date and time}
sDay := GetToken(sValue, ' ');
{If the space wasn't found...}
if Length(sDay) = 0 then
begin
{Copy out the first two characters}
sDay := Copy(sValue, 1, 2);
{Remove them from the temp string}
sValue := Copy(sValue, 3, Length(sValue));
end;
if Length(sDay) = 0 then
Exit;
{Extract Hour}
sValue := TrimLeft(sValue);
sHour := GetToken(sValue, ':');
if Length(sHour) = 0 then
Exit;
{Extract Min}
sMin := GetToken(sValue, ':');
if Length(sMin) = 0 then
Exit;
{Extract Sec}
sSec := GetToken(sValue, '.');
if Length(sSec) = 0 then
sSec := sValue;
if Length(sSec) = 0 then
Exit;
Result := True;
end;
{------------------------------------------------------------------------------}
{ ExDateStr }
{------------------------------------------------------------------------------}
function ExDateStr (sValue: string; var sYear, sMonth, sDay: string): boolean;
begin
Result := False;
{Extract Year}
sYear := GetToken(sValue, ',');
if Length(sYear) = 0 then
Exit;
{Extract Month}
sMonth := GetToken(sValue, ',');
if Length(sMonth) = 0 then
Exit;
{Extract Day}
{Look for space between date and time}
sDay := GetToken(sValue, ' ');
{If the space wasn't found...}
if Length(sDay) = 0 then
begin
{Copy out the first two characters}
sDay := Copy(sValue, 1, 2);
{Remove them from the temp string}
sValue := Copy(sValue, 3, Length(sValue));
end;
if Length(sDay) = 0 then
Exit;
Result := True;
end;
{------------------------------------------------------------------------------}
{ ExTimeStr }
{------------------------------------------------------------------------------}
function ExTimeStr (sValue: string; var sHour, sMin, sSec: string): boolean;
begin
Result := False;
{Extract Hour}
sHour := GetToken(sValue, ':');
if Length(sHour) = 0 then
Exit;
{Extract Min}
sMin := GetToken(sValue, ':');
if Length(sMin) = 0 then
Exit;
{Extract Sec}
sSec := GetToken(sValue, '.');
if Length(sSec) = 0 then
sSec := sValue;
if Length(sSec) = 0 then
Exit;
Result := True;
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;
{------------------------------------------------------------------------------}
{ RemoveChar }
{------------------------------------------------------------------------------}
procedure RemoveChar (var sValue: string; ch: Char);
var
i : integer;
s : string;
begin
s := '';
for i := 1 to Length(sValue) do
begin
if sValue[i] <> ch then
s := s + sValue[i];
end;
sValue := s;
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;
{------------------------------------------------------------------------------}
{ MakeCRLF }
{ - Replaces Linefeed/CarriageReturn with CarriageReturn/Linefeed }
{ - Replaces single LineFeed or Carriage Return with CRLF }
{------------------------------------------------------------------------------}
function MakeCRLF (Value: string): string;
var
i : integer;
s1,s2 : string;
begin
s1 := Value;
i := 1;
{Replace Chr(10) with Chr(13)}
while i > 0 do
begin
i := Pos(Chr(10), s1);
if i > 0 then
s1 := Copy(s1, 1, i-1) + Chr(13) + Copy(s1, i+1, Length(s1));
end;
i := 1;
{Replace Chr(13) + Chr(13) with Chr(13) + Chr(10)}
while i > 0 do
begin
i := Pos(Chr(13) + Chr(13), s1);
if i > 0 then
s1 := Copy(s1, 1, i-1) + Chr(13) + Chr(10) + Copy(s1, i+2, Length(s1));
end;
i := 1;
s2 := s1;
s1 := '';
{Replace Chr(13) with Chr(13) + Chr(10)}
while i > 0 do
begin
i := Pos(Chr(13), s2);
if i > 0 then
begin
if i = Length(s2) then
begin
s1 := s1 + Chr(13) + Chr(10);
Break;
end
else
begin
if s2[i+1] <> Chr(10) then
begin
s1 := s1 + Copy(s2, 1, i) + Chr(10);
s2 := Copy(s2, i+1, Length(s2));
end
else
begin
s1 := s1 + Copy(s2, 1, i+1);
s2 := Copy(s2, i+2, Length(s2));
end;
end;
end;
end;
s1 := s1 + s2;
Result := s1;
end;
{------------------------------------------------------------------------------}
{ CrGetTempPath }
{------------------------------------------------------------------------------}
function CrGetTempPath: string;
var
s1 : string;
p1 : PChar;
Len : DWord;
begin
Result := '';
p1 := StrAlloc(512);
Len := GetTempPath(0, p1);
if Len = 0 then Exit;
GetTempPath(Len, p1);
s1 := String(p1);
StrDispose(p1);
Result := s1;
end;
{------------------------------------------------------------------------------}
{ CopyDevMode Method }
{------------------------------------------------------------------------------}
procedure CopyDevMode(var SourceDM: TDevMode; var DestinationDM: TDevMode);
begin
DestinationDM.dmDeviceName := SourceDM.dmDeviceName;
DestinationDM.dmSpecVersion := SourceDM.dmSpecVersion;
DestinationDM.dmDriverVersion := SourceDM.dmDriverVersion;
DestinationDM.dmSize := SourceDM.dmSize;
DestinationDM.dmDriverExtra := SourceDM.dmDriverExtra;
DestinationDM.dmFields := SourceDM.dmFields;
DestinationDM.dmOrientation := SourceDM.dmOrientation;
DestinationDM.dmPaperSize := SourceDM.dmPaperSize;
DestinationDM.dmPaperLength := SourceDM.dmPaperLength;
DestinationDM.dmPaperWidth := SourceDM.dmPaperWidth;
DestinationDM.dmScale := SourceDM.dmScale;
DestinationDM.dmCopies := SourceDM.dmCopies;
DestinationDM.dmDefaultSource := SourceDM.dmDefaultSource;
DestinationDM.dmPrintQuality := SourceDM.dmPrintQuality;
DestinationDM.dmColor := SourceDM.dmColor;
DestinationDM.dmDuplex := SourceDM.dmDuplex;
DestinationDM.dmYResolution := SourceDM.dmYResolution;
DestinationDM.dmTTOption := SourceDM.dmTTOption;
DestinationDM.dmCollate := SourceDM.dmCollate;
DestinationDM.dmFormName := SourceDM.dmFormName;
DestinationDM.dmLogPixels := SourceDM.dmLogPixels;
DestinationDM.dmBitsPerPel := SourceDM.dmBitsPerPel;
DestinationDM.dmPelsWidth := SourceDM.dmPelsWidth;
DestinationDM.dmPelsHeight := SourceDM.dmPelsHeight;
DestinationDM.dmDisplayFlags := SourceDM.dmDisplayFlags;
DestinationDM.dmDisplayFrequency := SourceDM.dmDisplayFrequency;
DestinationDM.dmICMMethod := SourceDM.dmICMMethod;
DestinationDM.dmICMIntent := SourceDM.dmICMIntent;
DestinationDM.dmMediaType := SourceDM.dmMediaType;
DestinationDM.dmDitherType := SourceDM.dmDitherType;
DestinationDM.dmICCManufacturer := SourceDM.dmICCManufacturer;
DestinationDM.dmICCModel := SourceDM.dmICCModel;
DestinationDM.dmPanningWidth := SourceDM.dmPanningWidth;
DestinationDM.dmPanningHeight := SourceDM.dmPanningHeight;
end;
{------------------------------------------------------------------------------}
{ ColorState }
{ - Returns the active/inactive color of a component }
{------------------------------------------------------------------------------}
function ColorState(Enable: boolean): TColor;
begin
Result := clInactiveCaptionText;
if Enable then
Result := clWindow;
end;
{------------------------------------------------------------------------------}
{ TwipsToInches }
{------------------------------------------------------------------------------}
function TwipsToInches(iValue: integer): double;
begin
Result := iValue / 1440;
end;
{------------------------------------------------------------------------------}
{ InchesToTwips }
{------------------------------------------------------------------------------}
function InchesToTwips(fValue: double): integer;
begin
Result := Trunc(fValue * 1440);
end;
{------------------------------------------------------------------------------}
{ TwipsToInchesStr }
{------------------------------------------------------------------------------}
function TwipsToInchesStr(iValue: integer): string;
begin
Result := FloatToStrF(TwipsToInches(iValue),ffFixed,8,3);
end;
{------------------------------------------------------------------------------}
{ InchesStrToTwips }
{------------------------------------------------------------------------------}
function InchesStrToTwips(sValue: string): integer;
var
fValue : double;
begin
Result := 0;
if IsFloating(sValue) then
begin
fValue := StrToFloat(sValue);
Result := InchesToTwips(fValue);
end;
end;
{------------------------------------------------------------------------------}
{ CompareTwipsToInches }
{------------------------------------------------------------------------------}
function CompareTwipsToInches(iTwips: integer; dInches: double): boolean;
var
ixTwips : integer;
begin
Result := False;
ixTwips := InchesToTwips(dInches);
if iTwips <> ixTwips then
Result := True;
end;
{------------------------------------------------------------------------------}
{ TwipsToPoints }
{------------------------------------------------------------------------------}
function TwipsToPoints(iValue: integer): double;
begin
Result := iValue / 20;
end;
{------------------------------------------------------------------------------}
{ PointsToTwips }
{------------------------------------------------------------------------------}
function PointsToTwips(fValue: double): integer;
begin
Result := Trunc(fValue * 20);
end;
{------------------------------------------------------------------------------}
{ TwipsToPointsStr }
{------------------------------------------------------------------------------}
function TwipsToPointsStr(iValue: integer): string;
begin
Result := FloatToStrF(TwipsToPoints(iValue),ffFixed,8,3);
end;
{------------------------------------------------------------------------------}
{ PointsStrToTwips }
{------------------------------------------------------------------------------}
function PointsStrToTwips(sValue: string): integer;
var
fValue : double;
begin
Result := 0;
if IsFloating(sValue) then
begin
fValue := StrToFloat(sValue);
Result := PointsToTwips(fValue);
end;
end;
{------------------------------------------------------------------------------}
{ CompareTwipsToPoints }
{------------------------------------------------------------------------------}
function CompareTwipsToPoints(iTwips: integer; dPoints: double): boolean;
var
ixTwips : integer;
begin
Result := False;
ixTwips := PointsToTwips(dPoints);
if iTwips <> ixTwips then
Result := True;
end;
{------------------------------------------------------------------------------}
{ LoadFormPos }
{------------------------------------------------------------------------------}
procedure LoadFormPos(frmTemp: TForm);
var
RegIni : TRegIniFile;
begin
{Read the Registry}
RegIni := TRegIniFile.Create('Software\Business Objects\Suite 11.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\Business Objects\Suite 11.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\Business Objects\Suite 11.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
{Write to the Registry}
RegIni := TRegIniFile.Create('Software\Business Objects\Suite 11.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;
{------------------------------------------------------------------------------}
{ GetCommonFilesPath }
{------------------------------------------------------------------------------}
function GetCommonFilesPath : string;
var
regKey : TRegistry;
s : string;
begin
regKey := TRegistry.Create(KEY_READ);
try
regKey.RootKey := HKEY_LOCAL_MACHINE;
//regKey.OpenKey('SOFTWARE\Crystal Decisions\10.0\Crystal Reports', False);
regKey.OpenKey('SOFTWARE\Business Objects\Suite 11.0\Crystal Reports', False);
s := regKey.ReadString('CommonFiles');
Result := AddBackslash(s);
finally
regKey.Free;
end;
end;
{------------------------------------------------------------------------------}
{ CrGetTempName }
{------------------------------------------------------------------------------}
function CrGetTempName (const Extension: string) : string;
var
Buffer: array[0..MAX_PATH] of Char;
begin
repeat
GetTempPath(SizeOf(Buffer) - 1, Buffer);
GetTempFileName(Buffer, '~', 1, Buffer);
Result := ChangeFileExt(Buffer, Extension);
until not FileExists(Result);
end;
end.
|
unit UFrmCadastroStatusRequisicao;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCRUD, Menus, Buttons, StdCtrls, ExtCtrls
, UStatus
, URegraCRUDStatus
, UUtilitarios
;
type
TFrmCadastroStatusRequisicao = class(TFrmCRUD)
gbInformacoes: TGroupBox;
edNome: TLabeledEdit;
protected
FStatusRequisicao : TSTATUS;
FRegraCRUDStatusRequisicao : TRegraCrudStatus;
procedure Inicializa; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmCadastroStatusRequisicao: TFrmCadastroStatusRequisicao;
implementation
{$R *.dfm}
{ TFrmCadastroStatusRequisicao }
uses
UOpcaoPesquisa
, UEntidade
;
procedure TFrmCadastroStatusRequisicao.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
gbInformacoes.Enabled := ceTipoOperacaoUsuario in [touInsercao, touAtualizacao];
end;
procedure TFrmCadastroStatusRequisicao.Inicializa;
begin
inherited;
DefineEntidade(@FStatusRequisicao, TSTATUS);
DefineRegraCRUD(@FRegraCRUDStatusRequisicao, TRegraCrudStatus);
AdicionaOpcaoPesquisa(TOpcaoPesquisa.Create
.DefineVisao(VW_STATUS)
.DefineNomeCampoRetorno(VW_STATUS_ID)
.AdicionaFiltro(VW_STATUS_NOME_STATUS)
.DefineNomePesquisa(STR_STATUS));
AdicionaOpcaoPesquisa(TOpcaoPesquisa.Create
.DefineVisao(VW_STATUS)
.DefineNomeCampoRetorno(VW_STATUS_ID)
.AdicionaFiltro(VW_STATUS_NOME_STATUS)
.DefineNomePesquisa('Pesquisa X'));
end;
procedure TFrmCadastroStatusRequisicao.PosicionaCursorPrimeiroCampo;
begin
inherited;
edNome.SetFocus;
end;
procedure TFrmCadastroStatusRequisicao.PreencheEntidade;
begin
inherited;
FStatusRequisicao.NOME := edNome.Text;
end;
procedure TFrmCadastroStatusRequisicao.PreencheFormulario;
begin
inherited;
edNome.Text := FStatusRequisicao.NOME;
end;
end.
|
{------------------------------------
功能说明:工厂管理
创建日期:2014/08/12
作者:mx
版权:mx
-------------------------------------}
unit uSysFactoryMgr;
interface
uses SysUtils, Classes, uFactoryIntf;
type
TSysFactoryList = class(TInterfaceList)
private
function GetItems(Index: integer): ISysFactory;
protected
public
function Add(aFactory: ISysFactory): integer;
function IndexOfIID(const IID: TGUID): Integer;
function GetFactory(const IID: TGUID): ISysFactory;
function FindFactory(const IID: TGUID): ISysFactory;
property Items[Index: integer]: ISysFactory read GetItems; default;
end;
TSysFactoryManager = class(TObject)
private
FSysFactoryList: TSysFactoryList;
protected
public
procedure RegistryFactory(aIntfFactory: ISysFactory);
procedure UnRegistryFactory(aIntfFactory: ISysFactory); overload;
procedure UnRegistryFactory(IID: TGUID); overload;
procedure ReleaseInstances;
function FindFactory(const IID: TGUID): ISysFactory;
property FactoryList: TSysFactoryList read FSysFactoryList;
function Exists(const IID: TGUID): Boolean;
constructor Create;
destructor Destroy; override;
end;
//注册接口异常类
ERegistryIntfException = class(Exception);
function FactoryManager: TSysFactoryManager;
implementation
var FFactoryManager: TSysFactoryManager;
function FactoryManager: TSysFactoryManager;
begin
if FFactoryManager = nil then
FFactoryManager := TSysFactoryManager.Create;
Result := FFactoryManager;
end;
{ TSysFactoryList }
function TSysFactoryList.Add(aFactory: ISysFactory): integer;
begin
Result := inherited Add(aFactory);
end;
function TSysFactoryList.FindFactory(const IID: TGUID): ISysFactory;
var
idx: integer;
begin
result := nil;
idx := self.IndexOfIID(IID);
if idx <> -1 then
Result := Items[idx]
else
raise Exception.CreateFmt('未找到%s接口!', [GUIDToString(IID)]);
end;
function TSysFactoryList.GetFactory(const IID: TGUID): ISysFactory;
begin
Result := FindFactory(IID);
if not Assigned(result) then
raise Exception.CreateFmt('未找到%s接口!', [GUIDToString(IID)]);
end;
function TSysFactoryList.GetItems(Index: integer): ISysFactory;
begin
Result := inherited Items[Index] as ISysFactory
end;
function TSysFactoryList.IndexOfIID(const IID: TGUID): Integer;
var
i: integer;
begin
result := -1;
for i := 0 to (Count - 1) do
begin
if Items[i].Supports(IID) then
begin
result := i;
Break;
end;
end;
end;
{ TSysFactoryManager }
constructor TSysFactoryManager.Create;
begin
FSysFactoryList := TSysFactoryList.Create;
end;
destructor TSysFactoryManager.Destroy;
begin
FSysFactoryList.Free;
inherited;
end;
function TSysFactoryManager.Exists(const IID: TGUID): Boolean;
begin
Result := FSysFactoryList.IndexOfIID(IID) <> -1;
end;
function TSysFactoryManager.FindFactory(const IID: TGUID): ISysFactory;
begin
Result := FSysFactoryList.FindFactory(IID);
end;
procedure TSysFactoryManager.RegistryFactory(aIntfFactory: ISysFactory);
begin
FSysFactoryList.Add(aIntfFactory);
end;
procedure TSysFactoryManager.ReleaseInstances;
var i: Integer;
begin
for i := 0 to FSysFactoryList.Count - 1 do
FSysFactoryList.Items[i].ReleaseInstance;
end;
procedure TSysFactoryManager.UnRegistryFactory(aIntfFactory: ISysFactory);
begin
if Assigned(aIntfFactory) then
begin
aIntfFactory.ReleaseInstance;
FSysFactoryList.Remove(aIntfFactory);
end;
end;
procedure TSysFactoryManager.UnRegistryFactory(IID: TGUID);
begin
self.UnRegistryFactory(FSysFactoryList.GetFactory(IID));
end;
initialization
FFactoryManager := nil;
finalization
FreeAndNil(FFactoryManager);
end.
|
unit ufrmDialogMasterAgreement;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls,
Mask, StdCtrls, Grids,DateUtils,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils,
cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox,
cxCurrencyEdit, cxTextEdit, cxMaskEdit, cxCalendar, System.Actions,
Vcl.ActnList, ufraFooterDialog3Button, dxBarBuiltInMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData,
cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxClasses, cxGridCustomView, cxGrid, cxPC;
type
TFormMode = (fmAdd, fmEdit);
TfrmDialogMasterAgreement = class(TfrmMasterDialog)
pnl1: TPanel;
lblComboGrid: TLabel;
lbl9: TLabel;
lbl3: TLabel;
lbl4: TLabel;
lbl10: TLabel;
lbl7: TLabel;
lbl8: TLabel;
lbl1: TLabel;
lbl11: TLabel;
lbl12: TLabel;
lbl6: TLabel;
lbl13: TLabel;
edtCustName: TEdit;
edtNoAgreement: TEdit;
dtStart: TcxDateEdit;
dtEnd: TcxDateEdit;
edtDesc: TEdit;
cbbPKP: TComboBox;
cbbPPH: TComboBox;
intedtInvoice: TcxCurrencyEdit;
intedtPeriode: TcxCurrencyEdit;
lblTipeBayar: TLabel;
cbCustCode: TcxLookupComboBox;
cxGrid: TcxGrid;
cxcolGridViewColumn2: TcxGridDBColumn;
cxcolGridViewColumn3: TcxGridDBColumn;
cxcolGridViewColumn4: TcxGridDBColumn;
cxcolGridViewColumn5: TcxGridDBColumn;
cxcolDetilUnitPrice: TcxGridDBColumn;
cxcolDetilSubTotal: TcxGridDBColumn;
cbbTipeBayar: TComboBox;
cbPajak: TComboBox;
lbl14: TLabel;
curredtTotal: TcxCurrencyEdit;
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure cbpSupCodeCloseUp(Sender: TObject);
procedure strgGridCellValidate(Sender: TObject; ACol, ARow: Integer;
var Value: String; var Valid: Boolean);
procedure strgGridKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cbpSupCodeKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cbbPKPChange(Sender: TObject);
procedure strgGridCheckBoxClick(Sender: TObject; ACol, ARow: Integer;
State: Boolean);
procedure cbpPeriodeKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure intedtPeriodeKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure strgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer;
var IsFloat: Boolean; var FloatFormat: String);
procedure cbpSupCodeKeyPress(Sender: TObject; var Key: Char);
procedure intedtInvoiceExit(Sender: TObject);
procedure cbCustCodeCloseUp(Sender: TObject);
procedure cbpTipeBayarCloseUp(Sender: TObject);
procedure cbpTipeBayarKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cbpPeriodeCloseUp(Sender: TObject);
procedure cbpStaProCloseUp(Sender: TObject);
procedure cbpStaProKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lblSearchProductClick(Sender: TObject);
procedure cbCustCodeChange(Sender: TObject);
procedure lblNewRowClick(Sender: TObject);
procedure lblRemoveRowClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure footerDialogMasterbtnCloseClick(Sender: TObject);
procedure dtStartExit(Sender: TObject);
procedure cbpPajakChange(Sender: TObject);
procedure strgGrid2GetFloatFormat(Sender: TObject; ACol, ARow: Integer;
var IsFloat: Boolean; var FloatFormat: String);
private
{ Private declarations }
// hariPeriode: Integer;
isPKP,isPPN,isPPH: SmallInt;
// TOP: Integer;
FIsPajak: Boolean;
FPajakId: string;
FPajakName: string;
FCurrTipeProdukId: string;
// StaProID: Integer;
// procedure LoadDropDownData(ACombo: TcxLookupComboBox; aSQL: string);
procedure showDataEdit();
// function checkEmpty(): Boolean;
// function SaveAgreement(aAgreementID: Integer=0): Boolean;
// function AddDetilAgreement(AGR_ID: Integer): Boolean;
// function AddJadwalAgreement(AGR_ID: Integer): Boolean;
// function UpdateAgreement(): Boolean;
// function CountTotal(): Currency;
// procedure LoadDataPajak;
procedure CountEndEffectiveDate();
// function GetSQLsearchProjasByCode(AprojasCode: string): string;
procedure SetIsPajak(const Value: Boolean);
procedure SetPajakId(const Value: string);
procedure SetPajakName(const Value: string);
procedure SetCurrTipeProdukId(const Value: string);
public
{ Public declarations }
strDefaultPajakValue: string;
TpByrID: Integer;
PerID: Integer;
dayScale: Real;
FormMode: TFormMode;
AgreementID: Integer;
CustCode,SupCode,PerName: string;
OldTermPeriode: Integer;
OldPeriode: String;
OldNoOfInvoice: Integer;
OldInvoiceTotal: Double;
IsProcessSuccessfull: Boolean;
function getNewAgreementNo: string;
property IsPajak: Boolean read FIsPajak write SetIsPajak;
property PajakId: string read FPajakId write SetPajakId;
property PajakName: string read FPajakName write SetPajakName;
property CurrTipeProdukId: string read FCurrTipeProdukId write SetCurrTipeProdukId;
end;
var
frmDialogMasterAgreement: TfrmDialogMasterAgreement;
implementation
{$R *.dfm}
uses
ufrmPopupSelectCustomer, uTSCommonDlg, uConstanta, Math, StrUtils;
const
_KolCODE : byte = 0;
_KolDESCRIPTION : byte = 1;
_KolPRICE_PPN : byte = 2;
_KolQTY_ORDER : byte = 3;
_KolPROJAS_PRICE : byte = 4;
_KolSUB_TOTAL : byte = 5;
_KolTOTAL_AMOUNT : byte = 6;
_KolPER_DAYS : byte = 7;
_KolPJK_PPN : byte = 8;
_KolID_AGREEMENT : byte = 9;
_KolID_DETIL_AGREEMENT : byte = 10;
_Kol2No : byte = 0;
_Kol2INVOICE_DATE : byte = 1;
_Kol2INVOICE_TERM : byte = 2;
_Kol2INVOICE_NO : byte = 3;
_Kol2INVOICE_DUEDATE : byte = 4;
_Kol2STATUS : byte = 5;
_Kol2TOTAL_INVOICE : byte = 6;
_Kol2ID_JDWL_AGREEMENT : byte = 7;
_Kol2DESC_INVOICE : byte = 8;
_Kol2INVOICE_DATE_ID : byte = 9;
//function TfrmDialogMasterAgreement.AddJadwalAgreement(AGR_ID: Integer): Boolean;
//var
// countI: Integer;
// tempDate: TDateTime;
// {tempJmlPer,}tempJmlInv: Integer;
// tempInvNo: string;
// tempTotal: Currency;
// myDate: TDateTime;
// AGRJDWL_ID: Integer;
//begin
// //init
//// Result := False;
//
// tempJmlInv := Round(intedtInvoice.Value);
//
// tempTotal := CountTotal / intedtInvoice.Value;
//
// tempDate := dtStart.Date;
// myDate := dtStart.Date;
//
// if tempJmlInv > 0 then
// for countI := 1 to tempJmlInv do
// begin
// if IsValidDate(YearOf(myDate),MonthOf(myDate) + 1,DayOf(dtEnd.Date)) then
// begin
// myDate := EncodeDate(YearOf(myDate),MonthOf(myDate) + 1,DayOf(dtEnd.Date));
// end
// else
// begin
// if MonthOf(myDate) + 1 > 12 then
// myDate := EncodeDate(YearOf(myDate) + 1,1,DayOf(dtEnd.Date))
// else
// myDate := EncodeDate(YearOf(myDate),MonthOf(myDate) + 1,
// DaysInAMonth(YearOf(myDate),MonthOf(myDate) + 1));
// end;
//
//// if (strgGrid2.Ints[_Kol2ID_JDWL_AGREEMENT, countI]=0) or (AGR_ID=0) then
//// begin
//// AGRJDWL_ID := 0;
//// tempInvNo := GetInvoiceNumber(DialogUnit, tempDate);
//// end
//// else
//// begin
//// AGRJDWL_ID := strgGrid2.Ints[_Kol2ID_JDWL_AGREEMENT, countI];
//// tempInvNo := strgGrid2.Cells[_Kol2INVOICE_NO, countI];
//// end;
////
//// FNewMasterAgreement.UpdateNewAgreementJadwals(myDate, '',
//// '', '', tempTotal, AGRJDWL_ID, tempDate, edtDesc.Text, tempDate + TOP,
//// 0, 0, tempInvNo, 0, (countI), tempTotal, DialogUnit,
//// StaProID, DialogUnit);
//
// if IsValidDate(YearOf(tempDate),MonthOf(tempDate) + 1,DayOf(tempDate)) then
// begin
// tempDate := EncodeDate(YearOf(tempDate),MonthOf(tempDate) + 1,DayOf(dtStart.Date));
// end
// else
// begin
// if MonthOf(tempDate) + 1 > 12 then
// tempDate := EncodeDate(YearOf(tempDate) + 1,1,DayOf(dtStart.Date))
// else
// tempDate := EncodeDate(YearOf(tempDate),MonthOf(tempDate) + 1,
// DaysInAMonth(YearOf(tempDate),MonthOf(tempDate) + 1));
// end;
// end;
//
// Result := True;
//end;
//function TfrmDialogMasterAgreement.AddDetilAgreement(AGR_ID: Integer): Boolean;
//var AGRD_ID: Integer;
// intI: Integer;
// QTY_ORDER: Double;
// UNIT_PRICE, UNIT_PRICE_PPN, SUBTOTAL,TOTAL: Currency;
// PROJAS_CODE: string;
// staCek: Boolean;
//begin
// //init
// Result := False;
//// if strgGrid.RowCount = 1 then
//// begin
//// Result := True;
//// end
//// else
//// for intI := 1 to strgGrid.RowCount-1 do //dimulai dari row k2 [setelah header]
//// begin
//// if Trim(strgGrid.Cells[_KolCODE, intI]) = '' then
//// begin
//// Continue;
//// end;
//// PROJAS_CODE := strgGrid.Cells[_KolCODE,intI];
//// try
//// QTY_ORDER := (strgGrid.Floats[_KolQTY_ORDER,intI]);
//// except
//// QTY_ORDER := 0;
//// end;
//// try
//// UNIT_PRICE := (strgGrid.Floats[_KolPROJAS_PRICE,intI]);
//// except
//// UNIT_PRICE := 0;
//// end;
//// try
//// SUBTOTAL := (strgGrid.Floats[_KolSUB_TOTAL,intI]);
//// except
//// SUBTOTAL := 0;
//// end;
//// try
//// TOTAL := (strgGrid.Floats[_KolTOTAL_AMOUNT,intI]);
//// except
//// TOTAL := 0;
//// end;
//// try
//// if (strgGrid.Ints[_KolID_DETIL_AGREEMENT,intI] = 0) or (AGR_ID=0) then
//// AGRD_ID := 0
//// else
//// AGRD_ID := StrToInt(strgGrid.Cells[_KolID_DETIL_AGREEMENT,intI]);
//// except
//// AGRD_ID := 0;
//// end;
//// strgGrid.GetCheckBoxState(_KolPRICE_PPN,intI,staCek);
//// try
//// if staCek then
//// UNIT_PRICE_PPN := (strgGrid.Floats[_KolPJK_PPN,intI])
//// else
//// UNIT_PRICE_PPN := 0;
//// except
//// UNIT_PRICE_PPN := 10; //change with search to default
//// end;
////
//// FNewMasterAgreement.UpdateNewMasterAgreementItems(
//// AGRD_ID, DialogUnit, UNIT_PRICE,UNIT_PRICE_PPN,
//// PROJAS_CODE, DialogUnit, QTY_ORDER,SUBTOTAL,TOTAL
//// );
//// Result := True;
//// end;
//
//end;
//function TfrmDialogMasterAgreement.SaveAgreement(aAgreementID: Integer=0):
// Boolean;
//var {tempResult1,}tempResult2,tempResult3: Boolean;
// iSup_Unt_ID: Integer;
//begin
// if not Assigned(MasterAgreement) then MasterAgreement := TMasterAgreement.Create;
// AGR_ID := MasterAgreement.GetLastIDAgreement;
{ tempResult1 := MasterAgreement.InputDataMasterAgreement
(AGR_ID, DialogUnit,edtNoAgreement.Text,dtStart.Date,dtEnd.Date,intedtPeriode.Value,
PerID,intedtInvoice.Value,
isPKP,isPPN,isPPH,edtDesc.Text,CustCode,FLoginId, PajakId, DialogUnit);
}
// Result := False;
// if AgreementID>0 then
// FNewMasterAgreement.LoadByID(aAgreementID, DialogUnit);
// if Trim(cbSupCode.Text)='' then
// iSup_Unt_ID := 0
// else iSup_Unt_ID := DialogUnit;
// FNewMasterAgreement.UpdateData(CustCode, DialogUnit, dtEnd.Date,
// dtStart.Date, aAgreementID, intedtInvoice.Value,
// isPKP, StrToInt(PajakId), PerID, cbpSupCode.Text,
// iSup_Unt_ID, TpByrID, DialogUnit, edtNoAgreement.Text,
// DialogUnit, intedtPeriode.Value, DialogUnit, DialogUnit,
// isPPN, isPPH, edtDesc.Text);
// tempResult2 := AddDetilAgreement(aAgreementID);
// if (OldTermPeriode=intedtPeriode.Value)And(OldPeriode=cbpPeriode.Value)
// And(OldNoOfInvoice=intedtInvoice.Value)And(OldInvoiceTotal=curredtTotal.Value) then
// tempResult3 := True
// else
// tempResult3 := AddJadwalAgreement(aAgreementID);
// try
// if tempResult2 and tempResult3 then
// if FNewMasterAgreement.SaveToDB then
// begin
// cCommitTrans;
// edtDesc.Text := '';
// Result := True;
// end
// else
// begin
// cRollbackTrans;
// Result := False;
// end
// else
// begin
// CommonDlg.ShowError('Gagal Menyimpan Sebagian Data Detail');
// Result := False;
// end;
// finally
// if Not Result then
// CommonDlg.ShowError('Gagal Menyimpan Data');
// cRollBackTrans;
// Close;
// end;
//end;
//function TfrmDialogMasterAgreement.checkEmpty(): Boolean;
//var countChk: Integer;
// projasCode: string;
// errorField: string;
//begin
//init
// Result := True;
// errorField := ' ';
// //checking for empty field
// //agreement
// if cbCustCode.Text = '' then
// begin
// errorField := 'CUSTOMER CODE, ';
// cbCustCode.SetFocus;
// Result:= False;
// end;
// if edtNoAgreement.Text = '' then
// begin
// errorField := errorField + 'NO. AGREEMENT, ';
// edtNoAgreement.SetFocus;
// Result:= False;
// end;
// if (cbPeriode.Text = '') or (PerID = 0) then
// begin
// errorField := errorField + 'PERIODE, ';
// cbPeriode.SetFocus;
// Result:= False;
// end;
//
// if Result = False then
// begin
// SetLength(errorField,Length(errorField)-2);
// CommonDlg.ShowErrorEmpty(errorField);
// Exit;
// end;
//
// //detil agreement
//// if strgGrid.RowCount > 1 then
//// begin
//// for countChk := 2 to strgGrid.RowCount do
//// begin
//// projasCode := strgGrid.Cells[_KolCODE,countChk-1];
//// if countChk = 2 then
//// begin
//// if projasCode = '' then
//// begin
//// strgGrid.SelectRows(1,1);
//// strgGrid.RemoveSelectedRows;
//// end
//// else
//// begin
//// with cOpenQuery(GetSQLsearchProjasByCode(projasCode), False) do
//// begin
//// try
//// Last;
//// if RecordCount < 1 then
//// begin
//// CommonDlg.ShowError(' PRODUCT '+ projasCode +' IS NOT LISTED ');
//// Result := False;
//// Exit;
//// end;
////
//// finally
//// Free;
//// end;
//// end;
//// end; //else '' projas
//// end
//// else
//// begin
//// with cOpenQuery(GetSQLsearchProjasByCode(projasCode), False) do
//// begin
//// try
//// Last;
//// if RecordCount < 1 then
//// begin
//// CommonDlg.ShowError(' PRODUCT '+ projasCode +' IS NOT LISTED ');
//// Result := False;
//// Exit;
//// end;
////
//// finally
//// Free;
//// end;
//// end;
//// end;
//// end; // for to do
////
//// end; //f strgrid.rowcnt
//
// //jadwal agreement
//end;
procedure TfrmDialogMasterAgreement.footerDialogMasterbtnSaveClick(
Sender: TObject);
//var
// IDLokal: Integer;
begin
{
if not (checkEmpty) then Exit;
if cbbPKP.Text = 'PKP' then
isPKP := 1
else
isPKP := 0;
if cbbPPH.Text = 'PPH' then
isPPH := 1
else
isPPH := 0;
Try
Self.Enabled := False;
if (FormMode = fmAdd) then
begin
IsProcessSuccessfull := SaveAgreement;
end
else //edit mode
begin
IsProcessSuccessfull := SaveAgreement(AgreementID);
end;
Finally
Self.Enabled := True;
End;
if IsProcessSuccessfull then
Close;
}
end;
procedure TfrmDialogMasterAgreement.FormKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key = Ord('T')) and (ssctrl in Shift) then
begin
// if strgGrid.Cells[_KolCODE,strgGrid.RowCount-1] = '' then
// begin
// CommonDlg.ShowErrorEmpty('PRODUCT CODE');
// strgGrid.SetFocus;
// Exit;
// end
// else
// begin
// lbl18Click(Sender);
// end;
// end
// else if (Key = Ord('R')) and (ssctrl in Shift) then
// begin
// if strgGrid.RowCount = 2 then
// begin
// strgGrid.ClearRows(1, 1);
// CurrTipeProdukId := '';
// end
// else
// strgGrid.RemoveSelectedRows;
//
// curredtTotal.Text := FormatCurr('##,##0.00', CountTotal);
end
else if (Key = VK_ESCAPE) then
begin
footerDialogMasterbtnCloseClick(Sender);
end;
end;
procedure TfrmDialogMasterAgreement.showDataEdit();
begin
// cbPeriode.Value := PerName;
// cbPajak.Value := PajakName;
// cbPajak.SearchValue := PajakName;
// cbPajak.DoSearch;
// PajakId := cbpPajak.Cells[0, cbpPajak.Row];
edtNoAgreement.SetFocus;
end;
procedure TfrmDialogMasterAgreement.FormShow(Sender: TObject);
begin
inherited;
if FormMode = fmAdd then
begin
// dtStart.Date := cGetServerTime;
// dtEnd.Date := cGetServerTime;
edtNoAgreement.Text := getNewAgreementNo;
//Supplier
// LoadDropDownData(cbpSupCode, GetListSuplierByUnitId(DialogUnit));
end
else if (FormMode = fmEdit) then
begin
end;
// LoadDropDownData(cbCustCode, GetListCustomerByUnitId(DialogUnit));
//
// //Periode
// LoadDropDownData(cbpPeriode, GetListDataPeriode(DialogUnit));
// cbpPeriode.SearchValue := 'BULAN';
// cbpPeriode.Value := 'BULAN';
// cbpPeriode.DoSearch;
// PerID := StrToInt(cbpPeriode.Cells[0,cbpPeriode.Row]);
//
// //refStatus_Proses
// LoadDropDownData(cbpStaPro, GetListDataStatusProses(DialogUnit));
// if cbpStaPro.RowCount>3 then
// begin
// cbpStaPro.Value := 'OUTSTANDING';
// cbpStaPro.SearchValue := cbpStaPro.Value;
// cbpStaPro.CloseUp;
// StaProID := StrToInt(cbpStaPro.Cells[0, cbpStaPro.Row]);
// cbpStaPro.Enabled := True; ///False;
// end;
//
// LoadDropDownData(cbpTipeBayar, GetListDataTipePembayaran(DialogUnit));
// cbpTipeBayar.SearchValue := 'CASH';
// cbpTipeBayar.DoSearch;
// TpByrID := StrToInt(cbpTipeBayar.Cells[0, cbpTipeBayar.Row]);
//
// if TpByrID>=0 then
// cbpTipeBayar.Value := 'CASH';
//
// //Pajak
// LoadDropDownData(cbpPajak, GetListPajakByUnitId(DialogUnit));
// strDefaultPajakValue := GetDefaultPajak(DialogUnit);
//
// cbpPajak.Value := strDefaultPajakValue;
// cbpPajak.SearchValue := strDefaultPajakValue;
// cbpPajak.DoSearch;
// PajakId := cbpPajak.Cells[0, cbpPajak.Row];
//
// strgGrid.AddCheckBox(_KolPRICE_PPN,1,False,False);
//
// //Fill Data Customer
// if (CustCode<>'') and (cbCustCode.RowCount>0) then
// begin
// cbCustCode.Value := CustCode;
// cbCustCode.SearchValue := CustCode;
// cbCustCode.DoSearch;
// edtCustName.Text := cbCustCode.Cells[2, cbCustCode.Row];
// TryStrToInt(cbCustCode.Cells[3, cbCustCode.Row], TOP);
//
// LoadDropDownData(cbpSupCode, GetListSuplierByCustomerCode(CustCode));
//
// cbpSupCode.Value := SupCode;
// cbpSupCode.SearchValue := SupCode;
// cbpSupCode.DoSearch;
// edtSupName.Text := cbpSupCode.Cells[2, cbpSupCode.Row];
// end;
if FormMode = fmEdit then
showDataEdit();
//tsKontrak.Show;
CountEndEffectiveDate;
CurrTipeProdukId := '';
end;
procedure TfrmDialogMasterAgreement.FormDestroy(Sender: TObject);
begin
inherited;
frmDialogMasterAgreement := nil;
end;
//procedure TfrmDialogMasterAgreement.LoadDropDownData(ACombo: TcxLookupComboBox;
// aSQL: string);
//begin
// {Flush the old data}
// ACombo.ClearGridData;
//
// ACombo.ColCount := 3;
// {Load the data}
// if Acombo = cbCustCode then
// begin
// ACombo.ColCount := 4;
// with cOpenQuery(GetListCustomerByUnitId(DialogUnit), False)do
// begin
// try
// Last;
// {Make sure the allocated storage is big enough}
// ACombo.RowCount := RecordCount + 1;
// ACombo.AddRow(['ID','CODE','NAME', 'TOP']);
//
// if RecordCount > 0 then
// begin
// First;
// while not Eof do
// begin
// try
// ACombo.AddRow([FieldByName('CUST_ID').AsString,
// FieldByName('CUST_CODE').AsString,
// FieldByName('CUST_NAME').AsString,
// FieldByName('CUST_TOP').AsString]);
// except
// end;
//
// Next;
// end;
// end
// else
// begin
// ACombo.RowCount := 2;
// ACombo.AddRow([' ',' ',' ']);
// end;
//
// finally
// Free;
// end;
// end;
// end
// else if ACombo = cbpSupCode then
// begin
// with cOpenQuery(GetListSuplierByUnitId(DialogUnit), False) do
// begin
// try
// Last;
// ACombo.RowCount := RecordCount + 1;
// ACombo.AddRow(['','SUP CODE','SUP NAME']);
//
// if RecordCount > 0 then
// begin
// First;
// while not Eof do
// begin
// ACombo.AddRow(['', FieldByName('KODE SUPPLIER').AsString,
// FieldByName('NAMA SUPPLIER').AsString]);
//
// Next;
// end;
// end
// else
// begin
// ACombo.RowCount := 2;
// ACombo.AddRow([' ',' ',' ']);
// end;
//
// finally
// Free;
// end;
// end;
// end
// else if ACombo = cbpPeriode then
// begin
// with cOpenQuery(GetListDataPeriode(DialogUnit), False) do
// begin
// try
// Last;
// ACombo.RowCount := RecordCount + 1;
// ACombo.AddRow(['ID','PERIODE']);
//
// if RecordCount > 0 then
// begin
// First;
// while not Eof do
// begin
// try
// ACombo.AddRow([FieldByName('PER_ID').AsString,
// FieldByName('PER_NAME').AsString]);
// except
// end;
//
// Next;
// end;
// end
// else
// begin
// ACombo.RowCount := 2;
// ACombo.AddRow([' ',' ',' ']);
// end;
//
// finally
// Free;
// end;
// end;
// end
// else if ACombo = cbpPajak then
// begin
// with cOpenQuery(GetListPajakByUnitId(DialogUnit), False) do
// begin
// try
// Last;
// ACombo.RowCount := RecordCount + 1;
// ACombo.AddRow(['ID', 'NAMA PAJAK','PPN','KODE']);
//
// if RecordCount > 0 then
// begin
// First;
// while not Eof do
// begin
// try
// ACombo.AddRow([FieldByName('PJK_ID').AsString,
// FieldByName('PJK_NAME').AsString,
// FieldByName('PJK_PPN').AsString,
// FieldByName('PJK_CODE').AsString
// ]);
// except
// end;
//
// Next;
// end;
// end
// else
// begin
// ACombo.RowCount := 2;
// ACombo.AddRow([' ',' ',' ']);
// end;
//
// finally
// Free;
// end;
// end;
// end
// else if ACombo = cbpStaPro then
// begin
// with cOpenQuery(GetListDataStatusProses(DialogUnit), False) do
// begin
// try
// Last;
// ACombo.RowCount := RecordCount + 1;
// ACombo.AddRow(['ID','STATUS PROSES']);
//
// if RecordCount > 0 then
// begin
// First;
// while not Eof do
// begin
// try
// ACombo.AddRow([FieldByName('STAPRO_ID').AsString,
// FieldByName('STAPRO_NAME').AsString]);
// except
// end;
//
// Next;
// end;
// end
// else
// begin
// ACombo.RowCount := 2;
// ACombo.AddRow([' ',' ']);
// end;
//
// finally
// Free;
// end;
// end;
// end
// else if ACombo = cbpTipeBayar then
// begin
// with cOpenQuery(GetListDataTipePembayaran(DialogUnit), False) do
// begin
// try
// Last;
// ACombo.RowCount := RecordCount + 1;
// ACombo.AddRow(['','Tipe Pembayaran']);
//
// if RecordCount > 0 then
// begin
// First;
// while not Eof do
// begin
// try
// ACombo.AddRow([FieldByName('TPBYR_ID').AsString,
// FieldByName('TPBYR_NAME').AsString]);
// except
// end;
//
// Next;
// end;
// end
// else
// begin
// ACombo.RowCount := 2;
// ACombo.AddRow([' ',' ']);
// end;
//
// finally
// Free;
// end;
// end;
// end;
//
// {Now shring the grid so its just big enough for the data}
// ACombo.SizeGridToData;
// //trik to activate acombo
// ACombo.FixedRows := 1;
//end;
procedure TfrmDialogMasterAgreement.cbpSupCodeCloseUp(Sender: TObject);
begin
// if cbSupCode.ItemIndex>1 then
// begin
// SupCode := cbSupCode.Cells[1, cbpSupCode.Row];
// cbSupCode.Text := SupCode;
// edtSupName.Text := cbSupCode.Cells[2, cbpSupCode.Row];
// end;
end;
procedure TfrmDialogMasterAgreement.strgGridCellValidate(Sender: TObject;
ACol, ARow: Integer; var Value: String; var Valid: Boolean);
//var
// tempProjasCode: string;
// tempTotal: Currency;
// countVal: Integer;
// staCek: Boolean;
// tempPrice, tempPricePPN: Currency;
// tempPPN: Real;
begin
// if ACol = _KolCODE then
// begin
// tempProjasCode := strgGrid.Cells[_KolCODE,ARow];
//
// with cOpenQuery(GetSQLsearchProjasByCode(tempProjasCode), False) do
// begin
// try
// Last;
// First;
//
// if (ARow=strgGrid.FixedRows) and (strgGrid.Cells[_KolCODE, strgGrid.FixedRows+1]='') then
// begin
// CurrTipeProdukId := Fieldbyname('PROJAS_TPPRO_ID').AsString
// end;
//
// if (CurrTipeProdukId <> '') and
// (CurrTipeProdukId <> Fieldbyname('PROJAS_TPPRO_ID').AsString) then
// begin
// CommonDlg.ShowError('Untuk Agreement No: ' + edtNoAgreement.Text +
// ' Pilih Product dengan Type yang sama');
// strgGrid.SetFocus;
// strgGrid.Col := _KolCODE;
// end
// else
// begin
// if RecordCount > 0 then
// begin
// strgGrid.AddCheckBox(_KolPRICE_PPN, ARow, False, False);
// strgGrid.Alignments[_KolPRICE_PPN, ARow] := taCenter;
// strgGrid.Cells[_KolDESCRIPTION,ARow] := FieldByName('PROJAS_NAME').AsString;
// strgGrid.Ints[_KolPER_DAYS,ARow] := (FieldByName('PER_DAYS').AsInteger);
// strgGrid.Floats[_KolPJK_PPN,ARow] := (FieldByName('PJK_PPN').AsCurrency);
// strgGrid.Floats[_KolPROJAS_PRICE,ARow] := (FieldByName('PROJAS_PRICE').AsCurrency);
//
// if (ARow = strgGrid.FixedRows) then
// CurrTipeProdukId := Fieldbyname('PROJAS_TPPRO_ID').AsString;
//
// try
// tempPPN := (strgGrid.Floats[_KolPJK_PPN,ARow]);
// except
// tempPPN := 10; //change with search to default
// end;
//
// try
// tempPrice := (strgGrid.Floats[_KolPROJAS_PRICE,ARow]);
// except
// tempPrice := 0;
// end;
//
// strgGrid.GetCheckBoxState(_KolPRICE_PPN,ARow,staCek);
// if staCek then
// begin
// tempPricePPN := tempPrice / (1 + (tempPPN/100));
// end
// else
// tempPricePPN := tempPrice;
//
// strgGrid.Floats[_KolPROJAS_PRICE, ARow] := (tempPricePPN);
//
// if strgGrid.Cells[_KolQTY_ORDER, ARow]='' then
// strgGrid.Ints[_KolQTY_ORDER, ARow] := 0;
//
// strgGrid.Floats[_KolSUB_TOTAL,ARow] := (tempPricePPN * (strgGrid.Floats[_KolQTY_ORDER, ARow]));
// dayScale := intedtPeriode.Value;
// strgGrid.Floats[_KolTOTAL_AMOUNT,ARow] := dayScale*(strgGrid.Floats[_KolSUB_TOTAL,ARow]) ;
// edtUnitPrice.Text := FormatCurr('##,##0.00', (strgGrid.Floats[_KolPROJAS_PRICE,strgGrid.Row]));
//
// try
// strgGridCheckBoxClick(Sender, _KolPRICE_PPN, ARow, False);
// except
//
// end;
// strgGrid.Col := _KolQTY_ORDER;
// // if FormMode = fmAdd then
// // strgGrid.Col := 3;
// end;
// end;
//
// finally
// Free;
// end;
// end;
// end
// else if (ACol in [_KolQTY_ORDER, _KolPROJAS_PRICE]) then
// begin
// //jika subtotal = '' maka >> 0
// if strgGrid.Cells[_KolSUB_TOTAL,ARow] = '' then
// strgGrid.Floats[_KolSUB_TOTAL,ARow] := 0;
//
// strgGrid.Floats[_KolSUB_TOTAL, ARow] := (strgGrid.Floats[_KolQTY_ORDER, ARow] * strgGrid.Floats[_KolPROJAS_PRICE, ARow]);
// strgGrid.Floats[_KolTOTAL_AMOUNT,ARow] := (Round(dayScale) * (strgGrid.Floats[_KolSUB_TOTAL,ARow]));
//
// //sum total
// tempTotal := CountTotal;
//
// curredtTotal.Text := FormatCurr('##,##0.00',tempTotal);
// //strgGrid.Col := _KolPRICE_PPN;
// strgGrid.Alignments[_KolQTY_ORDER, ARow] := taRightJustify;
// strgGrid.Alignments[_KolSUB_TOTAL, ARow] := taRightJustify;
// strgGrid.Alignments[_KolTOTAL_AMOUNT, ARow] := taRightJustify;
// end;
end;
procedure TfrmDialogMasterAgreement.strgGridKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
//var staCek: Boolean;
// tempPrice,tempSubTotal: Currency;
// tempPPN: Real;
begin
if Key = VK_F5 then
begin
lblSearchProductClick(Sender);
end; //if vk_f5
end;
procedure TfrmDialogMasterAgreement.cbpSupCodeKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
//var arrParam: TArr;
begin
inherited;
// if Length(cbSupCode.Text) = 1 then
// begin
// supCode := UpperCase(cbSupCode.Text);
// LoadDropDownData(cbSupCode, GetListSuplierByUnitId(DialogUnit, supCode + '%'));
// end;
if (Key = Word(Ord(VK_F5))) then
begin
if not Assigned(frmPopUpSelectCustomer) then
frmPopUpSelectCustomer := TfrmPopUpSelectCustomer.Create(Application);
frmPopUpSelectCustomer.Modul := mMasterAgreement;
frmPopUpSelectCustomer.SuplierCode := SupCode;
frmPopUpSelectCustomer.ShowModal;
if (frmPopUpSelectCustomer.IsProcessSuccessfull) then
begin
cbCustCode.Text := frmPopUpSelectCustomer.CustomerCode;
cbCustCode.SetFocus;
// cbCustCodeCloseUp(Self);
end;
frmPopUpSelectCustomer.Free;
end; // end 13
end;
procedure TfrmDialogMasterAgreement.cbbPKPChange(Sender: TObject);
begin
inherited;
if cbbPKP.Text = 'PKP' then
begin
// cbbPPN.ItemIndex := 1;
// cbpPajak.Enabled := True;
// isPPN := 1;
isPKP := 1;
cbbPPH.Enabled := True;
cbbPPH.ItemIndex := 1;
if cbPajak.itemindex=1 then
cbPajak.Text := 'PPN 10%';
//** price PPN item ditutup dl.
{if strgGrid.RowCount > 1 then
for countI := 1 to strgGrid.RowCount-1 do
begin
strgGrid.AddCheckBox(_KolPRICE_PPN,countI,True,True);
strgGrid.Alignments[_KolPRICE_PPN, countI]:= taCenter;
end;
}
cbPajak.SetFocus;
end
else
begin
// cbbPPN.ItemIndex := 0;
// cbpPajak.Enabled := False;
// isPPN := 0;
isPKP := 0;
isPPH := 0;
// PajakId := cbPajak.Cells[0, 1];
cbbPPH.Enabled := False;
cbbPPH.ItemIndex := 0;
cbPajak.Text := 'NON PPN';
{**
if strgGrid.RowCount > 1 then
for countI := 1 to strgGrid.RowCount-1 do
begin
strgGrid.AddCheckBox(_KolPRICE_PPN,countI,False,False);
strgGrid.Alignments[_KolPRICE_PPN, countI]:= taCenter;
end;
}
end;
end;
procedure TfrmDialogMasterAgreement.strgGridCheckBoxClick(Sender: TObject;
ACol, ARow: Integer; State: Boolean);
//var staCek: Boolean;
// tempPrice,tempSubTotal,tempTotal: Currency;
// tempPPN, tempQTY: Real;
// countVal: Integer;
begin
if ACol = _KolPRICE_PPN then //qry total
begin
// try
// strgGrid.Cells[_KolPJK_PPN,ARow] := cbpPajak.Cells[2, cbpPajak.Row];
// tempPPN := StrToFloat(cbpPajak.Cells[2, cbpPajak.Row]);
// except
// tempPPN := 10; //change with search to default
// end;
// try
// tempQTY := (strgGrid.Floats[_KolQTY_ORDER,ARow]);
// except
// tempQTY := 0;
// end;
// try
// tempPrice := (strgGrid.Floats[_KolPROJAS_PRICE,ARow]);
// except
// tempPrice := 0;
// end;
// strgGrid.GetCheckBoxState(_KolPRICE_PPN,ARow,staCek);
// if staCek then
// begin
// tempSubTotal := tempPrice / (1 + (tempPPN/100));
//// tempSubTotal := tempPrice * (100 / (tempPPN+100));
// end
// else tempSubTotal := tempPrice + (tempPrice * (tempPPN/100));
//
// strgGrid.Cells[_KolPROJAS_PRICE,ARow] := CurrToStr(tempSubTotal) ;
// tempTotal := tempSubTotal * tempQTY;
// strgGrid.Cells[_KolSUB_TOTAL, ARow] := CurrToStr(tempTotal);
// strgGrid.Cells[_KolTOTAL_AMOUNT,ARow] := CurrToStr(Round(dayScale) * tempTotal);
//
// //sum total
// tempTotal := 0;
// if strgGrid.RowCount > 1 then
// for countVal := 1 to strgGrid.RowCount-1 do
// tempTotal := tempTotal + (strgGrid.Floats[_KolTOTAL_AMOUNT,countVal]);
//
// curredtTotal.Text := FormatCurr('##,##0.00',tempTotal);
// // FormatedStringToFloat(strgGrid.Cells[_KolPROJAS_PRICE,strgGrid.Row])
// edtUnitPrice.Text := FormatCurr('##,##0.00', tempSubTotal);
// curredtTotal.Text := FormatCurr('##,##0.00', CountTotal);
end;
end;
procedure TfrmDialogMasterAgreement.cbpPeriodeKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key = Word(Ord(VK_RETURN))) then
begin
cbpPeriodeCloseUp(Sender);
end;
CountEndEffectiveDate;
end;
procedure TfrmDialogMasterAgreement.CountEndEffectiveDate;
//var {tempHariPer,} countI, tempPeriode: Integer;
// tempSubTotal{, tempQTY}: Currency;
// tempDate: TDateTime;
// tempDay, tempMonth, tempYear: Word;
begin
// if (PerID = 0) then
// Exit;
//
// tempPeriode:= Round(intedtPeriode.Value);
//
// tempDay := DayOf(dtStart.Date);
// tempMonth := MonthOf(dtStart.Date);
// tempYear := YearOf(dtStart.Date);
//
//
// if cbPeriode.Text = 'BULAN' then
// begin
// tempMonth := tempMonth + tempPeriode;
// if tempMonth > 12 then
// begin
// tempYear := tempYear + 1;
// tempMonth := tempMonth - 12;
// end;
//
//
// if IsValidDate(tempYear, tempMonth, tempDay) then
// dtEnd.Date := EncodeDate(tempYear, tempMonth, tempDay)
// else
// dtEnd.Date := EncodeDate(tempYear, tempMonth + 1, tempDay - 1 - DaysInMonth(EncodeDate(tempYear, tempMonth, 1)));
// end
// else
// begin
// dtEnd.Date := dtStart.Date + intedtPeriode.Value;
// end;
//
//
// hariPeriode := DaysBetween(dtEnd.Date, dtStart.Date);
//
//// if (strgGrid.RowCount >= 2) and (strgGrid.Cells[_KolCODE, 1] <> '') then
//// for countI := 1 to strgGrid.RowCount-1 do
//// begin
//// try
//// tempSubTotal := (strgGrid.Floats[_KolSUB_TOTAL,countI]);
//// except
//// tempSubTotal := 0;
//// end;
////
//// dayScale := intedtPeriode.Value;
////
//// strgGrid.Cells[_KolTOTAL_AMOUNT,countI] := CurrToStr(dayScale * tempSubTotal);
//// end;// end for count to rowcount
// curredtTotal.Text := FormatCurr('##,##0.00',CountTotal);
end;
procedure TfrmDialogMasterAgreement.intedtPeriodeKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
// if Key = VK_RETURN then
// begin
// if (PerID = 0) then
// cbPeriode.SetFocus
// else
// CountEndEffectiveDate;
// end;
end;
procedure TfrmDialogMasterAgreement.SetIsPajak(const Value: Boolean);
begin
FIsPajak := Value;
end;
procedure TfrmDialogMasterAgreement.SetPajakId(const Value: string);
begin
FPajakId := Value;
end;
procedure TfrmDialogMasterAgreement.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmDialogMasterAgreement.SetPajakName(const Value: string);
begin
FPajakName := Value;
end;
procedure TfrmDialogMasterAgreement.strgGridGetFloatFormat(Sender: TObject;
ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: String);
begin
inherited;
FloatFormat := '%0.2n';
if (ARow>0) and (ACol in [_KolPROJAS_PRICE, _KolSUB_TOTAL,_KolTOTAL_AMOUNT]) then //, _KolPROJAS_PRICE] then
IsFloat := True
else
IsFloat := False;
end;
procedure TfrmDialogMasterAgreement.SetCurrTipeProdukId(
const Value: string);
begin
FCurrTipeProdukId := Value;
end;
procedure TfrmDialogMasterAgreement.cbpSupCodeKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := UpCase(Key);
end;
//function TfrmDialogMasterAgreement.CountTotal: Currency;
//var cTemp: Currency;
//// i: Integer;
//begin
// cTemp := 0;
//
//// for i := 1 to strgGrid.RowCount - 1 do
//// begin
//// if strgGrid.Cells[_KolTOTAL_AMOUNT, i] <> '' then
//// cTemp := cTemp + (strgGrid.Floats[_KolTOTAL_AMOUNT, i]);
//// end;
//
// Result := cTemp;
//end;
procedure TfrmDialogMasterAgreement.intedtInvoiceExit(Sender: TObject);
begin
inherited;
if intedtInvoice.Value > intedtPeriode.Value then
begin
CommonDlg.ShowError('Invoice can not be bigger than Term Periode');
intedtInvoice.Value := intedtPeriode.Value;
intedtPeriode.SetFocus;
end;
end;
procedure TfrmDialogMasterAgreement.cbCustCodeCloseUp(Sender: TObject);
//var
// aMasterCustomerId: Integer;
begin
inherited;
// if (cbCustCode.Text = '') or (cbCustCode.Value = ' ') then exit;
// edtCustName.Text := cbCustCode.Cells[2, cbCustCode.Row];
// try
// TOP := StrToInt(cbCustCode.Cells[3, cbCustCode.Row]);
// except
// TOP := 0;
// end;
// CustCode := cbCustCode.Cells[1, cbCustCode.Row];
// cbCustCode.Text := CustCode;
//
// //Supplier
// LoadDropDownData(cbpSupCode, GetListSuplierByCustomerCode(CustCode));
// FNewCustomer := TNewCustomer.CreateWithUser(Self, FLoginId, fLoginUnitId);
// If TryStrToInt(cbCustCode.Cells[0, cbCustCode.Row], aMasterCustomerId) then
// begin
// if FNewCustomer.LoadByID(aMasterCustomerId, DialogUnit) then
// begin
// cbbPKP.ItemIndex := FNewCustomer.IsPKP;
// cbbPPH.ItemIndex := FNewCustomer.ISPPH23;
// cbbPKPChange(Sender);
// if FNewCustomer.TipeBayar.Nama<>'' then
// begin
// cbpTipeBayar.Value := FNewCustomer.TipeBayar.Nama;
// end;
// End;
// end;
// FNewCustomer.Free;
CountEndEffectiveDate;
edtNoAgreement.SetFocus;
end;
procedure TfrmDialogMasterAgreement.cbpTipeBayarCloseUp(Sender: TObject);
begin
inherited;
// cbTipeBayar.Text := cbTipeBayar.Cells[1,cbTipeBayar.Row];
// try
// TpByrID := StrToInt(cbTipeBayar.Cells[0,cbTipeBayar.Row]);
// except
// TpByrID := 0;
// end;
end;
procedure TfrmDialogMasterAgreement.cbpTipeBayarKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key = VK_RETURN) then
begin
cbpTipeBayarCloseUp(Sender);
end;
end;
procedure TfrmDialogMasterAgreement.cbpPeriodeCloseUp(Sender: TObject);
begin
inherited;
// cbPeriode.Text := cbPeriode.Cells[1,cbPeriode.Row];
// try
// PerID := StrToInt(cbPeriode.Cells[0,cbPeriode.Row]);
// except
// PerID := 0;
// end;
end;
procedure TfrmDialogMasterAgreement.cbpStaProCloseUp(Sender: TObject);
begin
inherited;
// cbStaPro.Text := cbStaPro.Cells[1,cbStaPro.Row];
// try
// StaProID := StrToInt(cbStaPro.Cells[0,cbStaPro.Row]);
// except
// StaProID := 0;
// end;
end;
procedure TfrmDialogMasterAgreement.cbpStaProKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key = VK_RETURN) then
begin
cbpStaProCloseUp(Sender);
end;
end;
procedure TfrmDialogMasterAgreement.lblSearchProductClick(Sender: TObject);
//var
// tempProjasCode: string;
begin
inherited;
// if not Assigned(frmDialogSearchProductNBD) then
// frmDialogSearchProductNBD := TfrmDialogSearchProductNBD.Create(Self);
//
// frmDialogSearchProductNBD.DialogUnit := DialogUnit;
// frmDialogSearchProductNBD.DialogCompany := DialogCompany;
//
// frmDialogSearchProductNBD.ShowModal;
//
// if frmDialogSearchProductNBD.IsProcessSuccessfull then
// begin
// tempProjasCode := frmDialogSearchProductNBD.ProductNBDCode;
//
// with cOpenQuery(GetSQLsearchProjasByCode(tempProjasCode), False) do
// begin
// try
//
// if (strgGrid.Row=strgGrid.FixedRows) and
// (strgGrid.Cells[_KolCODE, strgGrid.FixedRows+1]='') then
// begin
// CurrTipeProdukId := Fieldbyname('PROJAS_TPPRO_ID').AsString
// end;
//
// if (CurrTipeProdukId <> '') and
// (CurrTipeProdukId <> Fieldbyname('PROJAS_TPPRO_ID').AsString) and
// (strgGrid.RowCount>2) then
// begin
// CommonDlg.ShowError('For Agreement No: ' + edtNoAgreement.Text +
// ' Select Product With Same Type');
// strgGrid.SetFocus;
// strgGrid.Col := _KolCODE;
// Exit;
// end;
//
// dayScale := intedtPeriode.Value;
// strgGrid.Cells[_KolCODE,strgGrid.Row] := frmDialogSearchProductNBD.ProductNBDCode;
// strgGrid.Cells[_KolDESCRIPTION,strgGrid.Row] := frmDialogSearchProductNBD.ProductNBDName;
// strgGrid.Cells[_KolPER_DAYS,strgGrid.Row] := frmDialogSearchProductNBD.ProductNBDDays;
// strgGrid.Alignments[_KolPRICE_PPN, strgGrid.Row] := taCenter;
// strgGrid.AddCheckBox(_KolPRICE_PPN, strgGrid.Row, False, False);
// // if CommonDlg.Confirm('Change Product Property ?')=mrYes then
// begin
// //=========================================================================
// strgGrid.Cells[_KolPER_DAYS,strgGrid.Row] := frmDialogSearchProductNBD.ProductNBDDays;
// strgGrid.Cells[_KolPJK_PPN,strgGrid.Row] := frmDialogSearchProductNBD.ProductNBDPPN;
// strgGrid.Cells[_KolPROJAS_PRICE,strgGrid.Row] := frmDialogSearchProductNBD.ProductNBDPrice;
// //=========================================================================
// strgGridCheckBoxClick(Sender, _KolPRICE_PPN, strgGrid.Row, False);
// end;
// finally
// Free;
// end;
// end;
// end; //if is succesful
end;
procedure TfrmDialogMasterAgreement.cbCustCodeChange(Sender: TObject);
begin
inherited;
// cbSupCode.Text := '';
// edtSupName.Text := '';
end;
procedure TfrmDialogMasterAgreement.lblNewRowClick(Sender: TObject);
begin
inherited;
// strgGrid.AddRow;
// strgGrid.AddCheckBox(_KolPRICE_PPN, strgGrid.Row + 1, False, False);
// strgGrid.Alignments[_KolPRICE_PPN, strgGrid.Row + 1]:= taCenter;
end;
procedure TfrmDialogMasterAgreement.lblRemoveRowClick(Sender: TObject);
//var
// iBaris: Integer;
begin
inherited;
// if strgGrid.RowCount <= 2 then
// begin
// iBaris:=strgGrid.Row;
// strgGrid.AddRow;
// strgGrid.Rows[iBaris].Clear;
// strgGrid.RemoveRows(ibaris,1);
// end
// else begin
// strgGrid.Rows[strgGrid.Row].Clear;
// strgGrid.RemoveSelectedRows;
// end;
end;
procedure TfrmDialogMasterAgreement.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (key = Ord('T')) and (ssCtrl in Shift) then
Begin
lblNewRowClick(sender);
End;
if (key = Ord('R')) and (ssCtrl in Shift) then
Begin
lblRemoveRowClick(sender);
End;
end;
procedure TfrmDialogMasterAgreement.footerDialogMasterbtnCloseClick(
Sender: TObject);
begin
inherited;
Self.ModalResult := mrCancel;
// if grdGridDetail.DataController.RecordCount > 0then
if CommonDlg.Confirm('Apakah Anda ingin menutup form ' + Self.Caption + '?') = mrNo then
begin
Self.ModalResult := mrNone;
end;
end;
function TfrmDialogMasterAgreement.getNewAgreementNo: string;
//var
// sSQL, aFormat : String;
// iLastNo, iLengthFormat : integer;
begin
// iLastNo := 0;
// aFormat := getGlobalVar('MAGM_NO');
// if aFormat='' then
// aFormat := '"AGM"YYMM';
// aFormat := FormatDateTime(aFormat, dtStart.Date);
// iLengthFormat := Length(aFormat);
// sSQL := 'Select AGR_NO from AGREEMENT '
// + ' where AGR_NO like ' + QuotedStr('%'+aFormat+'%')
// + ' order by AGR_NO Desc'; //tak mengenal Company
// with cOpenQuery(sSQL) do
// begin
// try
// if not FieldByName('AGR_NO').IsNull then
// iLastNo := StrToInt(RightStr(fieldbyname('AGR_NO').AsString,
// Length(fieldbyname('AGR_NO').AsString)-iLengthFormat));
// finally
// Free;
// end;
// end;
// Result := aFormat + StrPadLeft(IntToStr(iLastNo+1), 10-iLengthFormat, '0');
end;
procedure TfrmDialogMasterAgreement.dtStartExit(Sender: TObject);
begin
inherited;
if FormMode = fmAdd then
edtNoAgreement.Text := getNewAgreementNo;
end;
procedure TfrmDialogMasterAgreement.cbpPajakChange(Sender: TObject);
var
// i : integer;
sPajakCode : String;
begin
inherited;
if (cbPajak.ItemIndex = 1) AND (isPKP = 1) then
begin
CommonDlg.ShowError('Customer is PKP' + #13#10
+'Please Check your data');
end;
// PajakId := cbPajak.Cells[0, cbPajak.Row];
// sPajakCode := cbPajak.Cells[3, cbPajak.Row];
if sPajakCode <> '0' then
isPPN := 1
else
isPPN := 0;
// with strgGrid do
// begin
// for i := 1 to RowCount-1 do
// begin
// Cells[_KolPJK_PPN, i] := cbpPajak.Cells[2, cbpPajak.Row];
// end;
// end;
end;
//function TfrmDialogMasterAgreement.GetSQLsearchProjasByCode(AprojasCode:
// string): string;
//begin
// Result := 'SELECT PJ.*, PER.PER_NAME, PER.PER_DAYS, PJK.PJK_PPN'
// + ' FROM PRODUK_JASA PJ'
// + ' LEFT JOIN REF$PERIODE PER ON PER.PER_ID = PJ.PROJAS_PER_ID'
// + ' LEFT JOIN REF$PAJAK PJK ON PJK.PJK_ID = PJ.PROJAS_PJK_ID'
// + ' WHERE PJ.PROJAS_UNT_ID = '+ IntToStr(DialogUnit)
// + ' AND PJ.PROJAS_CODE = '+ QuotedStr(AprojasCode)
// + ' ORDER BY PJ.PROJAS_CODE';
//end;
procedure TfrmDialogMasterAgreement.strgGrid2GetFloatFormat(
Sender: TObject; ACol, ARow: Integer; var IsFloat: Boolean;
var FloatFormat: String);
begin
inherited;
if ARow=0 then exit;
try
FloatFormat := '%0.2n';
if ACol in [_Kol2TOTAL_INVOICE] then
IsFloat := True
else
IsFloat := False;
except
end;
end;
end.
|
//=============================================================================
// sgTrace.pas
//=============================================================================
//
// Support "tracing" and writing of messages to a trace file (Trace.log).
// "Trace" must be defined before these will be included (see sgTrace.inc).
//
// Change History:
//
// Version 3:
// - 2009-11-11: Andrew : Added code to cycle log files
// : Added code to make enter and exit verbose
// - 2009-11-06: Andrew : Fixed formatting
// - 2009-09-11: Andrew : Fixed io exceptions
// - 2009-06-23: Clinton: Comment formatting/cleanup
//
// Version 2:
// - 2008-12-17: Andrew : Moved all integers to Longint
//
// Version 1.1.6:
// - 2008-05-09: Andrew : Introduced unit
//=============================================================================
unit sgTrace;
//=============================================================================
interface
//=============================================================================
{$IFDEF Trace}
type
TraceLevel = (tlNone, tlError, tlWarning, tlInfo, tlVerbose);
procedure Trace(const unitname, action, routine, message: String);
procedure TraceIf(tl: TraceLevel;const unitname, action, routine, message: String);
procedure TraceEnter(const unitName, routine: String); overload;
procedure TraceEnter(const unitName, routine, message: String); overload;
procedure TraceExit(const unitName, routine: String); overload;
procedure TraceExit(const unitName, routine, message: String); overload;
{$ENDIF}
//=============================================================================
implementation
uses
Math,
SysUtils,
Classes,
{$IFDEF UNIX}
BaseUnix,
{$ENDIF}
StrUtils, StringHash, sgResources;
//=============================================================================
{$IFDEF Trace}
{$Info SwinGame Tracing Enabled}
// These vars are read in from the config file
var
MAX_LINES: Longint; //default 10000
MAX_LOGS: Longint; //default 10
TRACE_UNITS: TStringHash;
TRACE_LEVEL: TraceLevel;
var
indentLevel: Longint;
lineCount: Longint;
traceLog: Longint;
output: Text;
procedure ConfigureTrace();
const
MAX_LINES_DEFAULT = 10000;
MAX_LOGS_DEFAULT = 10;
var
input: Text;
line: String;
idx: Integer;
inUnits: Boolean;
function ReadInteger(start, default: Longint): Longint;
var
subStr: String;
begin
subStr := ExtractSubStr(line, start, []);
result := default;
TryStrToInt(subStr, result);
end;
begin
traceLog := 0;
lineCount := 0;
indentLevel := 0;
TRACE_LEVEL := tlNone;
MAX_LINES := MAX_LINES_DEFAULT;
MAX_LOGS := MAX_LOGS_DEFAULT;
if FileExists('Trace.cfg') or FileExists(PathToResource('Trace.cfg')) then
begin
inUnits := false;
try
if FileExists('Trace.cfg') then
Assign(input, 'Trace.cfg')
else
Assign(input, PathToResource('Trace.cfg'));
Reset(input);
while not EOF(input) do
begin
ReadLn(input, line);
if FindPart('#', line) = 1 then continue;
idx := FindPart('maxlines=', line);
if idx = 1 then
begin
MAX_LINES := ReadInteger(10, MAX_LINES_DEFAULT);
continue;
end;
idx := FindPart('maxlogs=', line);
if idx = 1 then
begin
MAX_LOGS := ReadInteger(9, MAX_LOGS_DEFAULT);
continue;
end;
idx := FindPart('tracelevel=', line);
if idx = 1 then
begin
TRACE_LEVEL := TraceLevel(ReadInteger(12, 0));
continue;
end;
if FindPart('units=', line) = 1 then
begin
inUnits := True;
continue;
end;
if inUnits then
begin
TRACE_UNITS.SetValue(line, nil);
end;
end;
Close(input);
except
end;
end
else
begin
//Trace SGSDK.dll by default
TRACE_UNITS.SetValue('SGSDK.dll', nil);
end;
end;
procedure AdvanceTrace();
var
newTrace: String;
begin
if (lineCount > MAX_LINES) and (indentLevel = 0) then
begin
traceLog += 1;
lineCount := 0;
newTrace := PathToResource('Trace ' + IntToStr(traceLog) + '.log');
WriteLn(output, 'Trace continues in ', newTrace);
if traceLog > MAX_LOGS then
begin
//Delete a log file
try
DeleteFile('Trace ' + IntToStr(traceLog - MAX_LOGS) + '.log');
except
WriteLn('Failed to delete log file ', 'Trace ' + IntToStr(traceLog - MAX_LOGS) + '.log')
end;
end;
Close(output);
try
{$IFDEF UNIX}
fpChmod (newTrace, S_IWUSR or S_IRUSR or S_IWGRP or S_IRGRP or S_IWOTH or S_IROTH);
{$ENDIF}
Assign(output, newTrace);
Rewrite(output);
WriteLn(output, 'Trace continued...');
except
WriteLn('ERROR: Unable to write to trace file. Please make Trace.log writable by this program.')
end;
end;
end;
procedure Trace(const unitname, action, routine, message: String);
begin
try
if (not Assigned(TRACE_UNITS)) or ((Length(unitname) > 0) and not TRACE_UNITS.containsKey(unitname)) then exit;
lineCount += 1;
{$IFDEF UNIX}
WriteLn(unitname, ': ':(15 - Length(unitname)), action, ': ':(8 - Length(action)), StringOfChar(' ', indentLevel * 2), routine, ': ', message);
{$ENDIF}
WriteLn(output, unitname, ': ':(15 - Length(unitname)), action, ': ':(8 - Length(action)), StringOfChar(' ', indentLevel * 2), routine, ': ', message);
Flush(output);
AdvanceTrace();
except
end;
end;
procedure TraceIf(tl: TraceLevel;const unitname, action, routine, message: String);
begin
if TRACE_LEVEL >= tl then
Trace(unitname, action, routine, message);
end;
procedure TraceEnter(const unitName, routine: String); overload;
begin
TraceEnter(unitName, routine, '');
end;
procedure TraceEnter(const unitName, routine, message: String); overload;
begin
Traceif(tlVerbose, unitName, 'Enter', routine, message);
indentLevel := indentLevel + 1;
end;
procedure TraceExit(const unitName, routine: String); overload;
begin
TraceExit(unitName, routine, '');
end;
procedure TraceExit(const unitName, routine, message: String); overload;
begin
indentLevel := indentLevel - 1;
if indentLevel = 0 then
TraceIf(tlVerbose, unitName, 'Exit', routine, message + Char(10) + StringOfChar('-', 50))
else
TraceIf(tlVerbose, unitName, 'Exit', routine, message);
end;
//=============================================================================
initialization
begin
SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]);
TRACE_UNITS := TStringHash.Create(False, 32);
ConfigureTrace();
{$IFDEF UNIX}
try
fpChmod (PathToResource('Trace.log'),S_IWUSR or S_IRUSR or S_IWGRP or S_IRGRP or S_IWOTH or S_IROTH);
except
end;
{$ENDIF}
try
Assign(output, PathToResource('Trace.log'));
Rewrite(output);
Trace('sgTrace', 'INFO', 'initialization', 'Tracing started in SwinGame.');
except on e: Exception do
WriteLn('ERROR: Unable to write to trace file. Please make Trace.log writable by this program. ' + e.Message)
end;
end;
//=============================================================================
finalization
begin
try
FreeAndNil(TRACE_UNITS);
Close(output);
except
end;
end;
{$ENDIF}
end.
|
unit Inventores_ViewModel_Implementation;
interface
uses
Inventores_Model;
type
TInventores_ViewModel_Class = class of TInventores_ViewModel;
TInventores_ViewModel = class
private
{ Private declarations }
fOnCambioPropiedades: TmvvmNotifyEvent;
fPropiedadesCambiadas: boolean;
fCambioPropiedadesDisabled: integer;
fTick: TmvvmNotifyEvent;
fModel: TdmInventores_Model;
function GetOnCambioPropiedades: TmvvmNotifyEvent;
procedure SetOnCambioPropiedades(const Value: TmvvmNotifyEvent);
procedure CreateModel;
protected
procedure CambioPropiedades;
procedure CambiarPropiedadesDisable;
procedure CambiarPropiedadesEnable;
function GetVistaOK: boolean; virtual;
function ModelClass:TdmInventores_Model_Class; virtual;
procedure AsignacionesIniciales; virtual;
procedure AsignarPropiedadesModelo; virtual;
property Model:TdmInventores_Model read fModel;
public
Constructor Create(const InjectedModel:TdmInventores_Model=nil);
procedure RealizarProceso;
procedure Iniciar(const aOnCambiosEnViewModel:TmvvmNotifyEvent); virtual;
destructor Destroy; override;
function InventoresCount:integer;
function ObtenValor(const Fila:integer;const NombreColumna:string):string;
property OnCambioPropiedades:TmvvmNotifyEvent read GetOnCambioPropiedades write SetOnCambioPropiedades;
property VistaOK:boolean read GetVistaOK;
property Tick:TmvvmNotifyEvent read fTick write fTick;
end;
implementation
uses
SysUtils;
procedure TInventores_ViewModel.Iniciar(const aOnCambiosEnViewModel:TmvvmNotifyEvent);
begin
AsignacionesIniciales;
fOnCambioPropiedades:=aOnCambiosEnViewModel;
end;
function TInventores_ViewModel.ModelClass: TdmInventores_Model_Class;
begin
result:=TdmInventores_Model
end;
procedure TInventores_ViewModel.AsignacionesIniciales;
begin
//Nada
end;
procedure TInventores_ViewModel.AsignarPropiedadesModelo;
begin
//
end;
procedure TInventores_ViewModel.CambiarPropiedadesDisable;
begin
inc(fCambioPropiedadesDisabled);
end;
procedure TInventores_ViewModel.CambiarPropiedadesEnable;
begin
dec(fCambioPropiedadesDisabled);
if (fCambioPropiedadesDisabled=0) and fPropiedadesCambiadas then
CambioPropiedades;
end;
procedure TInventores_ViewModel.CambioPropiedades;
begin
if (fCambioPropiedadesDisabled<>0) then
fPropiedadesCambiadas:=True
else begin
fPropiedadesCambiadas:=False;
CambiarPropiedadesDisable;
try
if Assigned(fOnCambioPropiedades) then
fOnCambioPropiedades(Self);
finally
CambiarPropiedadesEnable;
end;
end;
end;
function TInventores_ViewModel.GetVistaOK: boolean;
begin
result:=True;
end;
function TInventores_ViewModel.GetOnCambioPropiedades: TmvvmNotifyEvent;
begin
result:=fOnCambioPropiedades;
end;
procedure TInventores_ViewModel.SetOnCambioPropiedades(const Value: TmvvmNotifyEvent);
begin
fOnCambioPropiedades:=Value;
end;
destructor TInventores_ViewModel.Destroy;
begin
inherited;
end;
procedure TInventores_ViewModel.RealizarProceso;
begin
// CreateModel;
try
AsignarPropiedadesModelo;
fModel.RealizarProceso(fTick);
finally
// fModel.Free;
// fModel:=nil;
end;
end;
procedure TInventores_ViewModel.CreateModel;
begin
fModel:=ModelClass.CreateModel;
end;
function TInventores_ViewModel.InventoresCount: integer;
begin
result:=fModel.InventoresCuenta;
end;
function TInventores_ViewModel.ObtenValor(const Fila: integer;const NombreColumna: string): string;
var
aInventor: TInventor;
begin
aInventor:=fModel.LeerInventorIDX(Fila);
if NombreColumna='ID' then
result:=IntToStr(aInventor.ID)
else if NombreColumna='NOMBRE' then
result:=aInventor.Nombre
else if NombreColumna='INVENTO' then
result:=aInventor.INVENTO
else if NombreColumna='ANYO' then
result:=IntToStr(aInventor.Anyo)
else
result:='*ERROR*';
end;
constructor TInventores_ViewModel.Create(const InjectedModel: TdmInventores_Model);
begin
inherited Create;
fModel:=InjectedModel;
if not assigned(Model) then
CreateModel;
end;
end.
|
//
// Generated by JavaToPas v1.5 20150830 - 103216
////////////////////////////////////////////////////////////////////////////////
unit java.util.concurrent.ScheduledThreadPoolExecutor;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.util.concurrent.ThreadFactory,
java.util.concurrent.RejectedExecutionHandler,
java.util.concurrent.RunnableScheduledFuture,
java.util.concurrent.Callable,
java.util.concurrent.ScheduledFuture,
java.util.concurrent.TimeUnit,
java.util.concurrent.Future,
java.util.concurrent.BlockingQueue;
type
JScheduledThreadPoolExecutor = interface;
JScheduledThreadPoolExecutorClass = interface(JObjectClass)
['{97889B87-31D6-4CAB-87D0-D9169BE7C6D6}']
function getContinueExistingPeriodicTasksAfterShutdownPolicy : boolean; cdecl;// ()Z A: $1
function getExecuteExistingDelayedTasksAfterShutdownPolicy : boolean; cdecl;// ()Z A: $1
function getQueue : JBlockingQueue; cdecl; // ()Ljava/util/concurrent/BlockingQueue; A: $1
function getRemoveOnCancelPolicy : boolean; cdecl; // ()Z A: $1
function init(corePoolSize : Integer) : JScheduledThreadPoolExecutor; cdecl; overload;// (I)V A: $1
function init(corePoolSize : Integer; handler : JRejectedExecutionHandler) : JScheduledThreadPoolExecutor; cdecl; overload;// (ILjava/util/concurrent/RejectedExecutionHandler;)V A: $1
function init(corePoolSize : Integer; threadFactory : JThreadFactory) : JScheduledThreadPoolExecutor; cdecl; overload;// (ILjava/util/concurrent/ThreadFactory;)V A: $1
function init(corePoolSize : Integer; threadFactory : JThreadFactory; handler : JRejectedExecutionHandler) : JScheduledThreadPoolExecutor; cdecl; overload;// (ILjava/util/concurrent/ThreadFactory;Ljava/util/concurrent/RejectedExecutionHandler;)V A: $1
function schedule(callable : JCallable; delay : Int64; &unit : JTimeUnit) : JScheduledFuture; cdecl; overload;// (Ljava/util/concurrent/Callable;JLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/ScheduledFuture; A: $1
function schedule(command : JRunnable; delay : Int64; &unit : JTimeUnit) : JScheduledFuture; cdecl; overload;// (Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/ScheduledFuture; A: $1
function scheduleAtFixedRate(command : JRunnable; initialDelay : Int64; period : Int64; &unit : JTimeUnit) : JScheduledFuture; cdecl;// (Ljava/lang/Runnable;JJLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/ScheduledFuture; A: $1
function scheduleWithFixedDelay(command : JRunnable; initialDelay : Int64; delay : Int64; &unit : JTimeUnit) : JScheduledFuture; cdecl;// (Ljava/lang/Runnable;JJLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/ScheduledFuture; A: $1
function shutdownNow : JList; cdecl; // ()Ljava/util/List; A: $1
function submit(task : JCallable) : JFuture; cdecl; overload; // (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Future; A: $1
function submit(task : JRunnable) : JFuture; cdecl; overload; // (Ljava/lang/Runnable;)Ljava/util/concurrent/Future; A: $1
function submit(task : JRunnable; result : JObject) : JFuture; cdecl; overload;// (Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/Future; A: $1
procedure execute(command : JRunnable) ; cdecl; // (Ljava/lang/Runnable;)V A: $1
procedure setContinueExistingPeriodicTasksAfterShutdownPolicy(value : boolean) ; cdecl;// (Z)V A: $1
procedure setExecuteExistingDelayedTasksAfterShutdownPolicy(value : boolean) ; cdecl;// (Z)V A: $1
procedure setRemoveOnCancelPolicy(value : boolean) ; cdecl; // (Z)V A: $1
procedure shutdown ; cdecl; // ()V A: $1
end;
[JavaSignature('java/util/concurrent/ScheduledThreadPoolExecutor')]
JScheduledThreadPoolExecutor = interface(JObject)
['{0855F021-724A-434B-8907-303B5B363001}']
function getContinueExistingPeriodicTasksAfterShutdownPolicy : boolean; cdecl;// ()Z A: $1
function getExecuteExistingDelayedTasksAfterShutdownPolicy : boolean; cdecl;// ()Z A: $1
function getQueue : JBlockingQueue; cdecl; // ()Ljava/util/concurrent/BlockingQueue; A: $1
function getRemoveOnCancelPolicy : boolean; cdecl; // ()Z A: $1
function schedule(callable : JCallable; delay : Int64; &unit : JTimeUnit) : JScheduledFuture; cdecl; overload;// (Ljava/util/concurrent/Callable;JLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/ScheduledFuture; A: $1
function schedule(command : JRunnable; delay : Int64; &unit : JTimeUnit) : JScheduledFuture; cdecl; overload;// (Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/ScheduledFuture; A: $1
function scheduleAtFixedRate(command : JRunnable; initialDelay : Int64; period : Int64; &unit : JTimeUnit) : JScheduledFuture; cdecl;// (Ljava/lang/Runnable;JJLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/ScheduledFuture; A: $1
function scheduleWithFixedDelay(command : JRunnable; initialDelay : Int64; delay : Int64; &unit : JTimeUnit) : JScheduledFuture; cdecl;// (Ljava/lang/Runnable;JJLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/ScheduledFuture; A: $1
function shutdownNow : JList; cdecl; // ()Ljava/util/List; A: $1
function submit(task : JCallable) : JFuture; cdecl; overload; // (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Future; A: $1
function submit(task : JRunnable) : JFuture; cdecl; overload; // (Ljava/lang/Runnable;)Ljava/util/concurrent/Future; A: $1
function submit(task : JRunnable; result : JObject) : JFuture; cdecl; overload;// (Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/Future; A: $1
procedure execute(command : JRunnable) ; cdecl; // (Ljava/lang/Runnable;)V A: $1
procedure setContinueExistingPeriodicTasksAfterShutdownPolicy(value : boolean) ; cdecl;// (Z)V A: $1
procedure setExecuteExistingDelayedTasksAfterShutdownPolicy(value : boolean) ; cdecl;// (Z)V A: $1
procedure setRemoveOnCancelPolicy(value : boolean) ; cdecl; // (Z)V A: $1
procedure shutdown ; cdecl; // ()V A: $1
end;
TJScheduledThreadPoolExecutor = class(TJavaGenericImport<JScheduledThreadPoolExecutorClass, JScheduledThreadPoolExecutor>)
end;
implementation
end.
|
{ *************************************************************************** }
{ }
{ Kylix and Delphi Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 1997, 2001 Borland Software Corporation }
{ }
{ Русификация: 2001-02 Polaris Software }
{ http://polesoft.da.ru }
{ *************************************************************************** }
unit SqlConst;
interface
const
DRIVERS_KEY = 'Installed Drivers'; { Do not localize }
CONNECTIONS_KEY = 'Installed Connections'; { Do not localize }
DRIVERNAME_KEY = 'DriverName'; { Do not localize }
HOSTNAME_KEY = 'HostName'; { Do not localize }
ROLENAME_KEY = 'RoleName'; { Do not localize }
DATABASENAME_KEY = 'Database'; { Do not localize }
MAXBLOBSIZE_KEY = 'BlobSize'; { Do not localize }
VENDORLIB_KEY = 'VendorLib'; { Do not localize }
DLLLIB_KEY = 'LibraryName'; { Do not localize }
GETDRIVERFUNC_KEY = 'GetDriverFunc'; { Do not localize }
AUTOCOMMIT_KEY = 'AutoCommit'; { Do not localize }
BLOCKINGMODE_KEY = 'BlockingMode'; { Do not localize }
WAITONLOCKS_KEY= 'WaitOnLocks'; { Do not localize }
COMMITRETAIN_KEY = 'CommitRetain'; { Do not localize }
TRANSISOLATION_KEY = '%s TransIsolation'; { Do not localize }
SQLDIALECT_KEY = 'SqlDialect'; { Do not localize }
SQLLOCALE_CODE_KEY = 'LocaleCode'; { Do not localize }
ERROR_RESOURCE_KEY = 'ErrorResourceFile'; { Do not localize }
SQLSERVER_CHARSET_KEY = 'ServerCharSet'; { Do not localize }
SREADCOMMITTED = 'readcommited'; { Do not localize }
SREPEATREAD = 'repeatableread'; { Do not localize }
SDIRTYREAD = 'dirtyread'; { Do not localize }
SDRIVERREG_SETTING = 'Driver Registry File'; { Do not localize }
SCONNECTIONREG_SETTING = 'Connection Registry File'; { Do not localize }
szUSERNAME = 'USER_NAME'; { Do not localize }
szPASSWORD = 'PASSWORD'; { Do not localize }
SLocaleCode = 'LCID'; { Do not localize }
ROWSETSIZE_KEY = 'RowsetSize'; { Do not localize }
{$IFNDEF VER140}
OSAUTHENTICATION = 'OS Authentication'; { Do not localize }
SERVERPORT = 'Server Port'; { Do not localize }
MULTITRANSENABLED = 'Multiple Transaction'; { Do not localize }
TRIMCHAR = 'Trim Char'; { Do not localize }
CUSTOM_INFO = 'Custom String'; { Do not localize }
CONN_TIMEOUT = 'Connection Timeout'; { Do not localize }
{$ELSE}
OSAUTHENTICATION = 'Os Authentication'; { Do not localize }
{$ENDIF}
{$IFDEF MSWINDOWS}
SDriverConfigFile = 'dbxdrivers.ini'; { Do not localize }
SConnectionConfigFile = 'dbxconnections.ini'; { Do not localize }
SDBEXPRESSREG_SETTING = '\Software\Borland\DBExpress'; { Do not localize }
{$ENDIF}
{$IFDEF LINUX}
SDBEXPRESSREG_USERPATH = '/.borland/'; { Do not localize }
SDBEXPRESSREG_GLOBALPATH = '/usr/local/etc/'; { Do not localize }
SDriverConfigFile = 'dbxdrivers'; { Do not localize }
SConnectionConfigFile = 'dbxconnections'; { Do not localize }
SConfExtension = '.conf'; { Do not localize }
{$ENDIF}
resourcestring
SLoginError = 'Не могу присоединиться к базе данных ''%s''';
SMonitorActive = 'Не могу изменить соединение в Active Monitor';
SMissingConnection = 'Отсутствует свойство SQLConnection';
SDatabaseOpen = 'Не могу выполнить эту операцию при открытом соединении';
SDatabaseClosed = 'Не могу выполнить эту операцию при закрытом соединении';
SMissingSQLConnection = 'Свойство SQLConnection требуется для этой операции';
SConnectionNameMissing = 'Отсутствует имя соединения';
SEmptySQLStatement = 'Нет доступных SQL команд';
SNoParameterValue = 'Нет значения для параметра ''%s''';
SNoParameterType = 'Нет типа для параметра ''%s''';
SParameterTypes = ';Input;Output;Input/Output;Result';
SDataTypes = ';String;SmallInt;Integer;Word;Boolean;Float;Currency;BCD;Date;Time;DateTime;;;;Blob;Memo;Graphic;;;;;Cursor;';
SResultName = 'Result';
SNoTableName = 'Отсутствует свойство TableName';
SNoSqlStatement = 'Отсутствует запрос, имя таблицы или имя процедуры';
SNoDataSetField = 'Отсутствует свойство DataSetField';
SNoCachedUpdates = 'Не в режиме cached update';
SMissingDataBaseName = 'Отсутствует свойство Database';
SMissingDataSet = 'Отсутствует свойство DataSet';
SMissingDriverName = 'Отсутствует свойство DriverName';
SPrepareError = 'Не могу выполнить Запрос';
SObjectNameError = 'Таблица/процедура не найдена';
SSQLDataSetOpen = 'Не могу определить имена полей для %s';
SNoActiveTrans = 'Нет активной транзакции';
SActiveTrans = 'Транзакция уже активна';
SDllLoadError = 'Не могу загрузить %s';
SDllProcLoadError = 'Не могу найти процедуру %s';
SConnectionEditor = '&Изменить свойства соединения';
SCommandTextEditor = '&Изменить CommandText';
SMissingDLLName = 'Имя DLL/Shared Library не установлено';
SMissingDriverRegFile = 'Файл регитсрации драйвера/соединения ''%s'' не найден';
STableNameNotFound = 'Не могу найти TableName в CommandText';
SNoCursor = 'Курсор не возвращен из Запроса';
SMetaDataOpenError = 'Не могу открыть Metadata';
SErrorMappingError = 'Ошибка SQL: Error mapping failed';
SStoredProcsNotSupported = 'Хранимые процедуры не поддерживаются ''%s'' Server';
SPackagesNotSupported = 'Пакеты не поддерживаются ''%s'' сервером';
SDBXUNKNOWNERROR = 'Ошибка DBX: No Mapping for Error Code Found';
SDBXNOCONNECTION = 'Ошибка DBX: Соединение не найдено, сообщение об ошибке не может быть получено';
SDBXNOMETAOBJECT = 'Ошибка DBX: MetadataObject не найден, сообщение об ошибке не может быть получено';
SDBXNOCOMMAND = 'Ошибка DBX: Соединение не найдено, сообщение об ошибке не может быть получено';
SDBXNOCURSOR = 'Ошибка DBX: Соединение не найдено, сообщение об ошибке не может быть получено';
{$IFNDEF VER140}
SNOMEMORY = 'Ошибка dbExpress: Не хватает памяти для операции';
SINVALIDFLDTYPE = 'Ошибка dbExpress: Неверное тип поля';
SINVALIDHNDL = 'Ошибка dbExpress: Неверный дескриптор';
SINVALIDTIME = 'Ошибка dbExpress: Неверное время';
SNOTSUPPORTED = 'Ошибка dbExpress: Операция не поддерживается';
SINVALIDXLATION = 'Ошибка dbExpress: Неверное преобразование данных';
SINVALIDPARAM = 'Ошибка dbExpress: Неверный параметр';
SOUTOFRANGE = 'Ошибка dbExpress: Параметр/колонка вышла за границы';
SSQLPARAMNOTSET = 'Ошибка dbExpress: Параметр не установлен';
SEOF = 'Ошибка dbExpress: Результат находится в EOF';
SINVALIDUSRPASS = 'Ошибка dbExpress: Неверное имя/пароль';
SINVALIDPRECISION = 'Ошибка dbExpress: Неверная точность';
SINVALIDLEN = 'Ошибка dbExpress Error: Неверная длина';
SINVALIDXISOLEVEL = 'Ошибка dbExpress: Неверный Уровень Изоляции Транзакций';
SINVALIDTXNID = 'Ошибка dbExpress: Неверный ID транзакции';
SDUPLICATETXNID = 'Ошибка dbExpress: Дубликат ID транзакции';
SDRIVERRESTRICTED = 'Ошибка dbExpress: Приложение не лицензировано для использование этой возможности';
SLOCALTRANSACTIVE = 'Ошибка dbExpress: Локальная транзакция уже активна';
SMULTIPLETRANSNOTENABLED = 'Ошибка dbExpress: Несколько транзакций не доступно';
{$ELSE}
SNOMEMORY = 'Ошибка DBX: Не хватает памяти для операции';
SINVALIDFLDTYPE = 'Ошибка DBX: Неверное тип поля';
SINVALIDHNDL = 'Ошибка DBX: Неверный дескриптор';
SINVALIDTIME = 'Ошибка DBX: Неверное время';
SNOTSUPPORTED = 'Ошибка DBX: Операция не поддерживается';
SINVALIDXLATION = 'Ошибка DBX: Неверное преобразование';
SINVALIDPARAM = 'Ошибка DBX: Неверный параметр';
SOUTOFRANGE = 'Ошибка DBX: Аргумент вышел за границы';
SSQLPARAMNOTSET = 'Ошибка DBX: Параметр не установлен';
SEOF = 'Ошибка DBX: Результат находится в EOF';
SINVALIDUSRPASS = 'Ошибка DBX: Неверное имя/пароль';
SINVALIDPRECISION = 'Ошибка DBX: Неверная точность';
SINVALIDLEN = 'Ошибка DBX: Неверная длина';
SINVALIDXISOLEVEL = 'Ошибка DBX: Неверный Уровень Изоляции Транзакций';
SINVALIDTXNID = 'Ошибка DBX: Неверный ID транзакции';
SDUPLICATETXNID = 'Ошибка DBX: Дубликат ID транзакции';
SDRIVERRESTRICTED = 'dbExpress: Приложение не лицензировано для использование этой возможности';
SLOCALTRANSACTIVE = 'Ошибка DBX: Локальная транзакция уже активна';
{$ENDIF}
SMultiConnNotSupported = 'Многочисленные соединения не поддерживаются драйвером %s';
SConfFileMoveError = 'Не могу переместить %s в %s';
SMissingConfFile = 'Файл конфигурации %s не найден';
SObjectViewNotTrue = 'ObjectView должен быть True для таблиц с Object полями';
SDriverNotInConfigFile = 'Драйвер (%s) не найден в конфиг. файле (%s)';
SObjectTypenameRequired = 'Имя типа Object требуется как значение параметра';
SCannotCreateFile = 'Не могу создать файл %s';
{$IFDEF LINUX}
SCannotCreateParams = 'Предупреждение: Соединение закрыто, параметры не восстановлены';
{$ENDIF}
// used in SqlReg.pas
{$IFNDEF VER140}
SDlgOpenCaption = 'Открыть файл протокола трассировки';
{$ENDIF}
{$IFDEF MSWINDOWS}
SDlgFilterTxt = 'Текстовые файлы (*.txt)|*.txt|Все файлы (*.*)|*.*';
{$ENDIF}
{$IFDEF LINUX}
SDlgFilterTxt = 'Текстовые файлы (*.txt)|Все файлы (*)';
{$ENDIF}
SLogFileFilter = 'Файлы протокола (*.log)';
{$IFNDEF VER140}
SCircularProvider = 'Циклические ссылки провайдеров не допускаются.';
{$ENDIF}
const
{$IFNDEF VER140}
DbxError : array[0..19] of String = ( '', SNOMEMORY, SINVALIDFLDTYPE,
{$ELSE}
DbxError : array[0..18] of String = ( '', SNOMEMORY, SINVALIDFLDTYPE,
{$ENDIF}
SINVALIDHNDL, SINVALIDTIME,
SNOTSUPPORTED, SINVALIDXLATION, SINVALIDPARAM, SOUTOFRANGE,
SSQLPARAMNOTSET, SEOF, SINVALIDUSRPASS, SINVALIDPRECISION,
SINVALIDLEN, SINVALIDXISOLEVEL, SINVALIDTXNID, SDUPLICATETXNID,
{$IFNDEF VER140}
SDRIVERRESTRICTED, SLOCALTRANSACTIVE, SMULTIPLETRANSNOTENABLED );
{$ELSE}
SDRIVERRESTRICTED, SLOCALTRANSACTIVE );
{$ENDIF}
implementation
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLFileMS3D<p>
Support for MS3D file format.<p>
<b>History :</b><font size=-1><ul>
<li>16/10/08 - UweR - Compatibility fix for Delphi 2009: MaterialIndex is now Byte instead of Char
<li>31/03/07 - DaStr - Added $I GLScene.inc
<li>24/03/07 - DaStr - Added explicit pointer dereferencing
(thanks Burkhard Carstens) (Bugtracker ID = 1678644)
<li>19/12/04 - PhP - Added capabilities function
<li>28/10/03 - SG - Partly implemented skeletal animation,
asynchronous animations will fail however.
<li>03/06/03 - EG - Added header, now self-registers
</ul></font>
}
unit GLFileMS3D;
interface
{$I GLScene.inc}
uses
Classes, SysUtils, GLVectorFileObjects, GLVectorTypes, GLMaterial, GLVectorGeometry,
GLVectorLists, ApplicationFileIO;
type
// TGLMS3DVectorFile
//
{: The MilkShape vector file.<p>
By Mattias Fagerlund, mattias@cambrianlabs.com. Yada yada. Eric rules! }
TGLMS3DVectorFile = class(TVectorFile)
public
class function Capabilities: TDataFileCapabilities; override;
procedure LoadFromStream(aStream : TStream); override;
end;
implementation
uses
TypesMS3D;
{ TGLMS3DVectorFile }
// capabilities
//
class function TGLMS3DVectorFile.Capabilities: TDataFileCapabilities;
begin
Result := [dfcRead];
end;
// loadfromstream
//
procedure TGLMS3DVectorFile.LoadFromStream(aStream: TStream);
var
// GLScene
i, j, k, itemp: integer;
wtemp : word;
NormalID : integer;
TexCoordID : integer;
MO : TMeshObject;
FaceGroup : TFGVertexNormalTexIndexList;
GroupList : TList;
GLLibMaterial : TGLLibMaterial;
// Milkshape 3d
ms3d_header : TMS3DHeader;
nNumVertices : word;
ms3d_vertices : PMS3DVertexArray;
nNumTriangles : word;
ms3d_triangle : TMS3DTriangle;
ms3d_triangles : PMS3DTriangleArray;
nNumGroups : word;
Group : TMS3DGroup;
nNumMaterials : word;
ms3d_material : TMS3DMaterial;
fAnimationFPS : single;
fCurrentTime : single;
iTotalFrames : integer;
nNumJoints : word;
ms3d_joints : PMS3DJointArray;
bonelist : TStringList;
bone : TSkeletonBone;
frame : TSkeletonFrame;
rot, pos : TVector3f;
procedure AddFaceVertex(ID: integer);
begin
// Add the normal to the normals list
NormalID := MO.Normals.Add(ms3d_triangle.vertexNormals[ID].v);
// Add the texCoord
TexCoordID := MO.TexCoords.Add(ms3d_triangle.s[ID], -ms3d_triangle.t[ID]);
// Add the vertex to the vertex list
FaceGroup.Add(ms3d_triangle.vertexIndices[ID], NormalID, TexCoordID);
end;
function AddRotations(rot, baserot : TAffineVector) : TAffineVector;
var
mat1,mat2,rmat : TMatrix;
s,c : Single;
Trans : TTransformations;
begin
mat1:=IdentityHMGMatrix;
mat2:=IdentityHMGMatrix;
SinCos(rot[0],s,c);
rmat:=CreateRotationMatrixX(s,c);
mat1:=MatrixMultiply(mat1,rmat);
SinCos(rot[1],s,c);
rmat:=CreateRotationMatrixY(s,c);
mat1:=MatrixMultiply(mat1,rmat);
SinCos(rot[2],s,c);
rmat:=CreateRotationMatrixZ(s,c);
mat1:=MatrixMultiply(mat1,rmat);
SinCos(baserot[0],s,c);
rmat:=CreateRotationMatrixX(s,c);
mat2:=MatrixMultiply(mat2,rmat);
SinCos(baserot[1],s,c);
rmat:=CreateRotationMatrixY(s,c);
mat2:=MatrixMultiply(mat2,rmat);
SinCos(baserot[2],s,c);
rmat:=CreateRotationMatrixZ(s,c);
mat2:=MatrixMultiply(mat2,rmat);
mat1:=MatrixMultiply(mat1,mat2);
if MatrixDecompose(mat1,Trans) then
SetVector(Result,Trans[ttRotateX],Trans[ttRotateY],Trans[ttRotateZ])
else
Result:=NullVector;
end;
begin
GroupList := TList.Create;
FaceGroup := nil;
ms3d_vertices := nil;
ms3d_triangles := nil;
ms3d_joints := nil;
try
// First comes the header.
aStream.ReadBuffer(ms3d_header, sizeof(TMS3DHeader));
Assert(ms3d_header.version = 4, Format('The MilkShape3D importer can only handle MS3D files of version 4, this is version ', [ms3d_header.id]));
// Then comes the number of vertices
aStream.ReadBuffer(nNumVertices, sizeof(nNumVertices));
// Create the vertex list
if Owner is TGLActor then begin
MO := TSkeletonMeshObject.CreateOwned(Owner.MeshObjects);
TSkeletonMeshObject(MO).BonesPerVertex:=1;
end else
MO := TMeshObject.CreateOwned(Owner.MeshObjects);
MO.Mode := momFaceGroups;
// Then comes nNumVertices * sizeof (ms3d_vertex_t)
ms3d_vertices := AllocMem(sizeof(TMS3DVertex) * nNumVertices);
aStream.ReadBuffer(ms3d_vertices^, sizeof(TMS3DVertex) * nNumVertices);
for i := 0 to nNumVertices - 1 do
with ms3d_vertices^[i] do begin
// Add the vertex to the vertexlist
MO.Vertices.Add(vertex.v);
if Owner is TGLActor then
TSkeletonMeshObject(MO).AddWeightedBone(Byte(BoneID),1);
end;
// number of triangles
aStream.ReadBuffer(nNumTriangles, sizeof(nNumTriangles));
// nNumTriangles * sizeof (ms3d_triangle_t)
ms3d_triangles := AllocMem(sizeof(TMS3DTriangle) * nNumTriangles);
aStream.ReadBuffer(ms3d_triangles^, sizeof(TMS3DTriangle) * nNumTriangles);
// Don't do anything with the triangles / faces just yet
// number of groups
aStream.ReadBuffer(nNumGroups, sizeof(nNumGroups));
// nNumGroups * sizeof (ms3d_group_t)
for i := 0 to nNumGroups - 1 do
begin
// Read the first part of the group
Group := TMS3DGroup.Create;
GroupList.Add(Group);
aStream.ReadBuffer(Group.Flags, sizeof(Group.Flags));
aStream.ReadBuffer(Group.name, sizeof(Group.name));
aStream.ReadBuffer(Group.numtriangles, sizeof(Group.numtriangles));
for j := 0 to Group.numtriangles - 1 do
begin
aStream.ReadBuffer(wtemp, sizeof(wtemp));
itemp := wtemp;
Group.triangleIndices.Add(pointer(itemp));
end;
aStream.ReadBuffer(Group.materialIndex, sizeof(Group.materialIndex));
// if materialindex=-1, then there is no material, and all faces should
// be added to a base VIL
if Group.materialIndex = -1 then
begin
// If there's no base VIL, create one!
if FaceGroup = nil then
FaceGroup := TFGVertexNormalTexIndexList.CreateOwned(MO.FaceGroups);
for j := 0 to Group.numtriangles - 1 do
begin
ms3d_triangle := ms3d_triangles^[integer(Group.triangleIndices[j])];
AddFaceVertex(0);
AddFaceVertex(1);
AddFaceVertex(2);
end;
end;
end;
// number of materials
aStream.ReadBuffer(nNumMaterials, sizeof(nNumMaterials));
// nNumMaterials * sizeof (ms3d_material_t)
for i := 0 to nNumMaterials-1 do
begin
aStream.ReadBuffer(ms3d_material, sizeof(TMS3DMaterial));
// Create the material, if there's a materiallibrary!
if Assigned(Owner.MaterialLibrary) then
begin
if FileExists(ms3d_material.texture) then
GLLibMaterial := Owner.MaterialLibrary.AddTextureMaterial(ms3d_material.name, ms3d_material.texture)
else begin
if not Owner.IgnoreMissingTextures then
Exception.Create('Texture file not found: '+ms3d_material.texture);
GLLibMaterial := Owner.MaterialLibrary.Materials.Add;
GLLibMaterial.Name := ms3d_material.name;
end;
GLLibMaterial.Material.FrontProperties.Emission.Color := ms3d_material.emissive;
GLLibMaterial.Material.FrontProperties.Ambient.Color := ms3d_material.ambient;
GLLibMaterial.Material.FrontProperties.Diffuse.Color := ms3d_material.diffuse;
GLLibMaterial.Material.FrontProperties.Specular.Color := ms3d_material.specular;
// Shinintess is 0 to 128 in both MS3D and GLScene. Why not 0 to 127? Odd.
GLLibMaterial.Material.FrontProperties.Shininess := round(ms3d_material.shininess);
// ms3d_material.transparency is allready set as alpha channel on all
// colors above
if ms3d_material.transparency<1 then
GLLibMaterial.Material.BlendingMode := bmTransparency;//}
// Create a new face group and add all triangles for this material
// here. We must cycle through all groups that have this material
FaceGroup := TFGVertexNormalTexIndexList.CreateOwned(MO.FaceGroups);
FaceGroup.MaterialName := GLLibMaterial.Name;//}
for j := 0 to GroupList.Count-1 do
begin
Group := TMS3DGroup(GroupList[j]);
if Group.materialIndex = i then
for k := 0 to Group.numtriangles - 1 do
begin
ms3d_triangle := ms3d_triangles^[integer(Group.triangleIndices[k])];
AddFaceVertex(0);
AddFaceVertex(1);
AddFaceVertex(2);
end;
end;
end;
end;
// save some keyframer data
aStream.ReadBuffer(fAnimationFPS, sizeof(fAnimationFPS));
aStream.ReadBuffer(fCurrentTime, sizeof(fCurrentTime));
aStream.ReadBuffer(iTotalFrames, sizeof(iTotalFrames));
// NOTE NOTE NOTE!
// From here on, the info isn't used at all, it's only read so that a future
// enhancement of the loader can also use animations!
// number of joints
aStream.ReadBuffer(nNumJoints, sizeof(nNumJoints));
// nNumJoints * sizeof (ms3d_joint_t)
ms3d_joints := AllocMem(sizeof(TMS3DJoint) * nNumJoints);
// We have to read the joints one by one!
for i := 0 to nNumJoints-1 do
begin
// Read the joint base
aStream.ReadBuffer(ms3d_joints^[i].Base, sizeof(TMS3DJointBase));
if ms3d_joints^[i].base.numKeyFramesRot>0 then
begin
// ms3d_keyframe_rot_t keyFramesRot[numKeyFramesRot]; // local animation matrices
// Allocate memory for the rotations
ms3d_joints^[i].keyFramesRot := AllocMem(sizeof(TMS3DKeyframeRotation) * ms3d_joints^[i].base.numKeyFramesRot);
// Read the rotations
aStream.ReadBuffer(ms3d_joints^[i].keyFramesRot^, sizeof(TMS3DKeyframeRotation) * ms3d_joints^[i].base.numKeyFramesRot);
end else
ms3d_joints^[i].keyFramesRot := nil;
if ms3d_joints^[i].base.numKeyFramesTrans>0 then
begin
// ms3d_keyframe_pos_t keyFramesTrans[numKeyFramesTrans]; // local animation matrices
// Allocate memory for the translations
ms3d_joints^[i].keyFramesTrans := AllocMem(sizeof(TMS3DKeyframePosition) * ms3d_joints^[i].base.numKeyFramesTrans);
// Read the translations
aStream.ReadBuffer(ms3d_joints^[i].keyFramesTrans^, sizeof(TMS3DKeyframePosition) * ms3d_joints^[i].base.numKeyFramesTrans);
end else
ms3d_joints^[i].keyFramesTrans := nil;
end;
// Right here, it's time to use the joints - this from the ms3d spec;
// ***
// Mesh Transformation:
//
// 0. Build the transformation matrices from the rotation and position
// 1. Multiply the vertices by the inverse of local reference matrix (lmatrix0)
// 2. then translate the result by (lmatrix0 * keyFramesTrans)
// 3. then multiply the result by (lmatrix0 * keyFramesRot)
//
// For normals skip step 2.
//
//
//
// NOTE: this file format may change in future versions!
//
//
// - Mete Ciragan
// ***
if (Owner is TGLActor) and (nNumJoints>0) then
begin
// Bone names are added to a list initally to sort out parents
bonelist:=TStringList.Create;
for i := 0 to nNumJoints-1 do
bonelist.Add(ms3d_joints^[i].Base.Name);
// Find parent bones and add their children
for i := 0 to nNumJoints-1 do begin
j:=bonelist.IndexOf(ms3d_joints^[i].Base.ParentName);
if j = -1 then
bone:=TSkeletonBone.CreateOwned(Owner.Skeleton.RootBones)
else
bone:=TSkeletonBone.CreateOwned(Owner.Skeleton.RootBones.BoneByID(j));
bone.Name:=ms3d_joints^[i].Base.Name;
bone.BoneID:=i;
end;
bonelist.Free;
// Set up the base pose
frame:=TSkeletonFrame.CreateOwned(Owner.Skeleton.Frames);
for i := 0 to nNumJoints-1 do
begin
pos:=ms3d_joints^[i].Base.Position.V;
rot:=ms3d_joints^[i].Base.Rotation.V;
frame.Position.Add(pos);
frame.Rotation.Add(rot);
end;
// Now load the animations
for i:=0 to nNumJoints-1 do
begin
if ms3d_joints^[i].Base.NumKeyFramesTrans = ms3d_joints^[i].Base.NumKeyFramesRot then
begin
for j:=0 to ms3d_joints^[i].Base.NumKeyFramesTrans-1 do
begin
if (j+1) = Owner.Skeleton.Frames.Count then
frame:=TSkeletonFrame.CreateOwned(Owner.Skeleton.Frames)
else
frame:=Owner.Skeleton.Frames[j+1];
// Set rootbone values to base pose
if ms3d_joints^[i].Base.ParentName = '' then begin
pos:=ms3d_joints^[i].Base.Position.V;
rot:=ms3d_joints^[i].Base.Rotation.V;
end else begin
pos:=ms3d_joints^[i].KeyFramesTrans^[j].Position.V;
AddVector(pos,ms3d_joints^[i].Base.Position.V);
rot:=ms3d_joints^[i].KeyFramesRot^[j].Rotation.V;
rot:=AddRotations(rot,ms3d_joints^[i].Base.Rotation.V);
end;
frame.Position.Add(pos);
frame.Rotation.Add(rot);
end;
end;
end;
Owner.Skeleton.RootBones.PrepareGlobalMatrices;
TSkeletonMeshObject(MO).PrepareBoneMatrixInvertedMeshes;
end;
finally
if Assigned(ms3d_vertices) then
FreeMem(ms3d_vertices);
if Assigned(ms3d_triangles) then
FreeMem(ms3d_triangles);
if Assigned(ms3d_joints) then
begin
// Free the internal storage of the joint
for i := 0 to nNumJoints-1 do
begin
if Assigned(ms3d_joints^[i].keyFramesRot) then
FreeMem(ms3d_joints^[i].keyFramesRot);
if Assigned(ms3d_joints^[i].keyFramesTrans) then
FreeMem(ms3d_joints^[i].keyFramesTrans);
end;
FreeMem(ms3d_joints);
end;
// Finalize
for i := 0 to GroupList.Count-1 do
TMS3DGroup(GroupList[i]).Free;
GroupList.Free;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterVectorFileFormat('ms3d', 'MilkShape3D files', TGLMS3DVectorFile);
end.
|
unit Unit3;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls;
type
TForm3 = class(TForm)
Image1: TImage;
Panel1: TPanel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
{$R *.dfm}
function CreateRgnFromBitmap(rgnBitmap: TBitmap): HRGN;
var
TransColor: TColor;
i, j: Integer;
i_width, i_height: Integer;
i_left, i_right: Integer;
rectRgn: HRGN;
begin
Result := 0;
i_width := rgnBitmap.Width;
i_height := rgnBitmap.Height;
transColor := rgnBitmap.Canvas.Pixels[0, 0];
for i := 0 to i_height - 1 do
begin i_left := -1;
for j := 0 to i_width - 1 do
begin
if i_left < 0 then
begin
if rgnBitmap.Canvas.Pixels[j, i] <> transColor then
i_left := j;
end
else
if rgnBitmap.Canvas.Pixels[j, i] = transColor then
begin
i_right := j;
rectRgn := CreateRectRgn(i_left, i, i_right, i + 1);
if Result = 0 then
Result := rectRgn
else
begin
CombineRgn(Result, Result, rectRgn, RGN_OR);
DeleteObject(rectRgn);
end;
i_left := -1;
end;
end;
if i_left >= 0 then
begin
rectRgn := CreateRectRgn(i_left, i, i_width, i+1);
if Result = 0 then
Result := rectRgn
else
begin
CombineRgn(Result, Result, rectRgn, RGN_OR);
DeleteObject(rectRgn);
end;
end;
end;
end;
procedure TForm3.FormCreate(Sender: TObject);
var WindowRgn: HRGN;v:string;f:TextFile;l:real;
begin
BorderStyle := bsNone;
ClientWidth := Image1.Picture.Bitmap.Width;
ClientHeight := Image1.Picture.Bitmap.Height;
WindowRgn := CreateRgnFromBitmap(Image1.Picture.Bitmap);
SetWindowRgn(Handle, WindowRgn, True);
end;
end.
|
{************************************************}
{* *}
{* AIMP Programming Interface *}
{* v4.50 build 2000 *}
{* *}
{* Artem Izmaylov *}
{* (C) 2006-2017 *}
{* www.aimp.ru *}
{* Mail: support@aimp.ru *}
{* *}
{************************************************}
unit apiMUI;
{$I apiConfig.inc}
interface
uses
Windows, apiObjects;
const
SID_IAIMPServiceMUI = '{41494D50-5372-764D-5549-000000000000}';
IID_IAIMPServiceMUI: TGUID = SID_IAIMPServiceMUI;
type
{ IAIMPServiceMUI }
IAIMPServiceMUI = interface(IUnknown)
[SID_IAIMPServiceMUI]
function GetName(out Value: IAIMPString): HRESULT; stdcall;
function GetValue(KeyPath: IAIMPString; out Value: IAIMPString): HRESULT; stdcall;
function GetValuePart(KeyPath: IAIMPString; Part: Integer; out Value: IAIMPString): HRESULT; stdcall;
end;
implementation
end.
|
unit DataSetExport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,IBase, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet,
Halcn6db, ComCtrls, StdCtrls, cxLookAndFeelPainters, cxButtons,
cxControls, cxContainer, cxEdit, cxProgressBar, cxTextEdit, ZMessages,
zProc, cxMaskEdit, cxButtonEdit, cxLabel, pfibquery, cxShellDlgs,
cxShellBrowserDialog, XLSReadWriteII2, BIFFRecsII2, ComObj, ShlObj;
function ExpBankDataSet(AOwner:TComponent;DataSet:TpFIBDataSet;IdBank:integer):Variant;stdcall;
exports ExpBankDataSet;
type
TBankExportForm = class(TForm)
DSet: TpFIBDataSet;
DbfExport: THalcyonDataSet;
SaveDialog: TSaveDialog;
CreateDBUniver: TCreateHalcyonDataSet;
LabelFile: TcxLabel;
ProgressBar: TcxProgressBar;
StartBtn: TcxButton;
ExitBtn: TcxButton;
eFileNameEdit: TcxButtonEdit;
DataSetConst: TpFIBDataSet;
procedure StartBtnClick(Sender: TObject);
procedure FileNameEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure ExitBtnClick(Sender: TObject);
private
pIdBank:integer;
fType : integer;
pl_num : integer;
procedure GenFileName(Path : string);
public
constructor Create(AOwner:TComponent;DataSet:TpFIBDataSet;IdBank:integer);reintroduce;
procedure ExportDefault(DataSet : TpFIBDataSet);
procedure ExportExim(DataSet : TpFIBDataSet);
procedure ExportProminvest(DataSet: TpFIBDataSet);
procedure ExportProminvest2(DataSet: TpFIBDataSet);
procedure ExportPumb(DataSet: TpFIBDataSet);
procedure ExportPrivat(DataSet: TpFIBDataSet);
procedure ExportUkrSib(DataSet : TpFIBDataSet);
procedure ExportAval(DataSet : TpFIBDataSet);
procedure ExportTxt(DataSet: TpFIBDataSet);
procedure ExportTxt2(DataSet: TpFIBDataSet);
procedure ExportProminvestKiev(DataSet: TpFIBDataSet);
procedure ExportVTB(DataSet: TpFIBDataSet);
procedure ExportPrivatKiev(DataSet: TpFIBDataSet);
procedure ExportKiev(DataSet: TpFIBDataSet);
procedure ExportImex(DataSet: TpFIBDataSet);
procedure ExportPravex(DataSet: TpFIBDataSet);
procedure ExportUniCreditDBF(DataSet: TpFIBDataSet);
procedure ExportUkrKomunBankFict(DataSet: TpFIBDataSet);
procedure ExportUkrKomunBank(DataSet: TpFIBDataSet);
procedure ExportUkrsibbankSimple(DataSet: TpFIBDataSet);
procedure ExportOschad(DataSet: TpFIBDataSet);
procedure ExportOschad2(DataSet: TpFIBDataSet);
procedure ExportUkrSib2(DataSet: TpFIBDataSet);
procedure ExportAlfa(DataSet: TpFIBDataSet);
function ChangeByte(const FilePath: String; OldByte,NewByte: Byte; SetPos: int64): Boolean;
end;
implementation
uses StrUtils, DateUtils, MaskUtils;
const year : array[2000..2020] of string =('0','1','2','3','4','5','6','7','8','9','a',
'b','c','d','e','f','g','h','i','j','k');
const month : array[1..12] of string =('1','2','3','4','5','6','7','8','9','a','b','c');
const day : array[0..35] of string =('0','1','2','3','4','5','6','7','8','9','a',
'b','c','d','e','f','g','h','i','j','k',
'l','m','n','o','p','q','r','s','t','u',
'v','w','x','y','z');
function ExpBankDataSet(AOwner:TComponent;DataSet:TpFIBDataSet;IdBank:integer):Variant;
var
form : TBankExportForm;
q : TpFIBQuery;
begin
form := TBankExportForm.Create(AOwner, DataSet, IdBank);
q := TpFIBQuery.Create(form);
q.Database := DataSet.Database;
q.Transaction := DataSet.Transaction;
q.SQL.Text := 'select DEFAULT_PATH, EXPORT_PROC from z_sp_type_payment where id_mfo = :id_bank';
q.Prepare;
q.ParamByName('ID_BANK').AsInt64 := IdBank;
try
q.ExecQuery;
except
ZShowMessage('Помилка!', 'Неможливо получити шлях за замовчуванням!', mtError, [mbOk]);
q.Close;
form.free;
exit;
end;
form.fType := 0;
if q.RecordCount = 0 then
begin
ZShowMessage('Помилка!', 'Неможливо получити шлях за замовчуванням!', mtError, [mbOk]);
q.Close;
form.free;
exit;
end;
if VarIsNull(q['DEFAULT_PATH'].AsVariant) then
begin
ZShowMessage('Помилка!', 'Неможливо получити шлях за замовчуванням!', mtError, [mbOk]);
q.Close;
form.free;
exit;
end;
if q['EXPORT_PROC'].AsString = 'ExportExim' then form.fType := 1;
if q['EXPORT_PROC'].AsString = 'ExportProminvest' then form.fType := 2;
if q['EXPORT_PROC'].AsString = 'ExportPrivat' then form.fType := 3;
if q['EXPORT_PROC'].AsString = 'ExportUkrSib' then form.fType := 4;
if q['EXPORT_PROC'].AsString = 'ExportAval' then form.fType := 5;
if q['EXPORT_PROC'].AsString = 'ExportUniCreditDBF' then form.fType := 6;
if q['EXPORT_PROC'].AsString = 'ExportTxt2' then form.fType := 7;
if q['EXPORT_PROC'].AsString = 'ExportProminvestKiev' then form.fType := 8;
if q['EXPORT_PROC'].AsString = 'ExportVTB' then form.fType := 9;
if q['EXPORT_PROC'].AsString = 'ExportPrivatKiev' then form.fType := 10;
if q['EXPORT_PROC'].AsString = 'ExportKiev' then form.fType := 11;
if q['EXPORT_PROC'].AsString = 'ExportImex' then form.fType := 12;
if q['EXPORT_PROC'].AsString = 'ExportPravex' then form.fType := 13;
if q['EXPORT_PROC'].AsString = 'ExportProminvest2' then form.fType := 14;
if q['EXPORT_PROC'].AsString = 'ExportUkrKomunBank' then form.fType := 15;
if q['EXPORT_PROC'].AsString = 'ExportOschad' then form.fType := 16;
if q['EXPORT_PROC'].AsString = 'ExportUkrSib2' then form.fType := 17;
if q['EXPORT_PROC'].AsString = 'ExportPumb' then form.fType := 18;
if q['EXPORT_PROC'].AsString = 'ExportAlfa' then form.fType := 19;
if q['EXPORT_PROC'].AsString = 'ExportOschad2' then form.fType := 20;
form.GenFileName(q['DEFAULT_PATH'].AsString);
q.Close;
form.ShowModal;
form.Free;
end;
Constructor TBankExportForm.Create(AOwner:TComponent;DataSet:TpFIBDataSet;IdBank:integer);
begin
inherited Create(AOwner);
DSet := DataSet;
pl_num := DataSet['NUM_DOC'];
pIdBank := IdBank;
end;
{$R *.dfm}
procedure TBankExportForm.StartBtnClick(Sender: TObject);
begin
if eFileNameEdit.Text<>'' then
begin
case fType of
0 : ExportDefault(DSet);
1 : ExportExim(DSet);
2 : ExportProminvest(DSet);
3 : ExportPrivat(DSet);
4 : ExportUkrSib(DSet);
5 : ExportAval(DSet);
6 : ExportUniCreditDBF(DSet);
7 : ExportTxt2(DSet);
8 : ExportProminvestKiev(DSet);
9 : ExportVTB(DSet);
10: ExportPrivatKiev(DSet);
11: ExportKiev(DSet);
12: ExportImex(DSet);
13: ExportPravex(DSet);
14: ExportProminvest2(DSet);
15: ExportUkrKomunBank(DSet);
16: ExportOschad(DSet);
17: ExportUkrSib2(DSet);
18: ExportPumb(DSet);
19: ExportAlfa(DSet);
20: ExportOschad2(DSet);
end;
end else ZShowMessage('Увага!','Не знайден шлях експорту!', mtInformation, [mbOk]);
end;
function BrowseCallbackProc(hwnd: HWND; uMsg: UINT; lParam: LPARAM; lpData: LPARAM): Integer; stdcall;
begin
if (uMsg = BFFM_INITIALIZED) then
SendMessage(hwnd, BFFM_SETSELECTION, 1, lpData);
BrowseCallbackProc:= 0;
end;
function GetFolderDialog(Handle: Integer; Caption: string; var strFolder: string): Boolean;
const
BIF_STATUSTEXT = $0004;
BIF_NEWDIALOGSTYLE = $0040;
BIF_RETURNONLYFSDIRS = $0080;
BIF_SHAREABLE = $0100;
BIF_USENEWUI = BIF_EDITBOX or BIF_NEWDIALOGSTYLE;
var
BrowseInfo: TBrowseInfo;
ItemIDList: PItemIDList;
JtemIDList: PItemIDList;
Path: PAnsiChar;
begin
Result:= False;
Path:= StrAlloc(MAX_PATH);
SHGetSpecialFolderLocation(Handle, CSIDL_DRIVES, JtemIDList);
with BrowseInfo do
begin
hwndOwner:= GetActiveWindow;
pidlRoot:= JtemIDList;
SHGetSpecialFolderLocation(hwndOwner, CSIDL_DRIVES, JtemIDList);
{ Возврат названия выбранного элемента }
pszDisplayName:= StrAlloc(MAX_PATH);
{ Установка названия диалога выбора папки }
lpszTitle:= PChar(Caption); // 'Выбрать папку на Delphi (Дельфи)';
{ Флаги, контролирующие возврат }
lpfn:= @BrowseCallbackProc;
{ Дополнительная информация, которая отдаётся обратно в обратный вызов (callback) }
lParam:= LongInt(PChar(strFolder));
end;
ItemIDList:= SHBrowseForFolder(BrowseInfo);
if (ItemIDList <> nil) then
if SHGetPathFromIDList(ItemIDList, Path) then
begin
strFolder:= Path;
Result:= True;
end;
end;
procedure TBankExportForm.FileNameEditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
var sFolder: String;
begin
sFolder:= '';
if GetFolderDialog(Application.Handle, '', sFolder) then
GenFileName(sFolder)
else exit;
end;
procedure TBankExportForm.ExitBtnClick(Sender: TObject);
begin
DSet := nil;
Close;
end;
procedure TBankExportForm.ExportExim(DataSet: TpFIBDataSet);
var
RecordCount : integer;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('TRAN_DATE;D;8;0');
CreateDBUniver.CreateFields.Add('CARD_ACCT;C;10;0');
CreateDBUniver.CreateFields.Add('AMOUNT;N;10;2');
CreateDBUniver.CreateFields.Add('CURRENCY;C;3;0');
CreateDBUniver.CreateFields.Add('FIO;C;50;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['TRAN_DATE'] := DSet['EXPORT_DAY'];
DbfExport['CARD_ACCT'] := DSet['ACCT_CARD'];
DbfExport['AMOUNT'] := DSet['SUMMA'];
DbfExport['CURRENCY'] := 'UAH';
DbfExport['FIO'] := DSet['FIO'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportProminvest(DataSet: TpFIBDataSet);
var
RecordCount : integer;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('A;C;16;0');
CreateDBUniver.CreateFields.Add('B;C;45;0');
CreateDBUniver.CreateFields.Add('C;N;11;2');
CreateDBUniver.CreateFields.Add('COMPANY;C;30;0');
CreateDBUniver.CreateFields.Add('INN;C;10;0');
CreateDBUniver.CreateFields.Add('T_N;C;32;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['A'] := DSet['ACCT_CARD'];
DbfExport['B'] := DSet['FIO'];
DbfExport['C'] := DSet['SUMMA'];
DbfExport['COMPANY'] := DSet['NAME_CUSTOMER_NATIVE'];
DbfExport['INN'] := DSet['TIN'];
DbfExport['T_N'] := '';
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportUkrKomunBankFict(DataSet: TpFIBDataSet);
var //не адекватная постановка(нада было выбрать людей 1 раз а не делать экспорт)
RecordCount,t : integer;
xls: TXLSReadWriteII2;
// MyExcel: Variant;
PathTem, PathRes:string;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
{CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('A;C;16;0');
CreateDBUniver.CreateFields.Add('B;C;45;0');
CreateDBUniver.CreateFields.Add('C;N;11;2');
CreateDBUniver.CreateFields.Add('COMPANY;C;30;0');
CreateDBUniver.CreateFields.Add('INN;C;10;0');
CreateDBUniver.CreateFields.Add('T_N;C;32;0'); }
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
{if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.Exclusive:=False;
DbfExport.Open; }
{MyExcel:=CreateOleObject('Excel.Application');
MyExcel.Visible := False;
MyExcel.WorkBooks.Add;
MyExcel.Save(DbfExport.DatabaseName + '\' + DbfExport.TableName);
MyExcel.Quit;}
xls:= TXLSReadWriteII2.Create(Application);
PathTem:= ExtractFilePath(Application.ExeName)+'Reports/Zarplata/Obrazec.xls';
PathRes:= DbfExport.DatabaseName + '\' + DbfExport.TableName;
if FileExists(PathRes) then DeleteFile(PathRes);
CopyFile(pansichar(PathTem), pansichar(PathRes),true);
xls.Filename:=PChar(PathRes);
xls.Read;
xls.Sheet[0].AsString[0,0]:='П.І.Б.';
xls.Sheet[0].Cell[0,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[1,0]:='Рід';
xls.Sheet[0].Cell[1,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[2,0]:='Дата народження';
xls.Sheet[0].Cell[2,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[3,0]:='Серія паспорта';
xls.Sheet[0].Cell[3,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[4,0]:='Номер паспорта';
xls.Sheet[0].Cell[4,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[5,0]:='Дата выдачі';
xls.Sheet[0].Cell[5,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[6,0]:='Місце видачі паспорта';
xls.Sheet[0].Cell[6,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[7,0]:='Иден.код';
xls.Sheet[0].Cell[7,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[8,0]:='Тип';
xls.Sheet[0].Cell[8,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[9,0]:='Назва міста (або смт. та ін.)';
xls.Sheet[0].Cell[9,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[10,0]:='Вулица';
xls.Sheet[0].Cell[10,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[11,0]:='Дом';
xls.Sheet[0].Cell[11,0].FillPatternForeColor:=xcGreen;
xls.Sheet[0].AsString[12,0]:='Квартира';
xls.Sheet[0].Cell[12,0].FillPatternForeColor:=xcGreen;
for t:=1 to 13 do
xls.Sheet[0].AsInteger[t-1,1]:=t;
t:=1;
try
While not(DSet.Eof) do
begin
xls.Sheet[0].AsString[0,t]:=VarToStrDef(DSet['FIO'], '');
xls.Sheet[0].AsString[1,t]:=IfThen(DSet['SEX']=1,'м','ж');
xls.Sheet[0].AsDateTime[2,t]:=DSet['BIRTH_DATE'];
xls.Sheet[0].AsString[3,t]:=VarToStrDef(DSet['SERIA'],'');
xls.Sheet[0].AsString[4,t]:=VarToStrDef(DSet['NUMBER'],'');
xls.Sheet[0].AsString[5,t]:=VarToStrDef(DSet['DATE_BEG'],'');
xls.Sheet[0].AsString[6,t]:=VarToStrDef(DSet['vidan'],'');
xls.Sheet[0].AsString[7,t]:=VarToStrDef(DSet['TIN'],'');
xls.Sheet[0].AsString[8,t]:=VarToStrDef(DSet['NAME_SHORT'],'');
xls.Sheet[0].AsString[9,t]:=VarToStrDef(DSet['NAME_PLACE'],'');
xls.Sheet[0].AsString[10,t]:=VarToStrDef(DSet['NAME_STREET'],'');
xls.Sheet[0].AsString[11,t]:=VarToStrDef(DSet['HOUSE'],'');
xls.Sheet[0].AsString[12,t]:=VarToStrDef(DSet['FLAT'],'');
t:=t+1;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
xls.Write;
xls.Destroy;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
//DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportProminvest2(DataSet: TpFIBDataSet);
var
RecordCount : integer;
str:string;
c:char;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('ACCT_CARD;C;16;0');
CreateDBUniver.CreateFields.Add('FIO;C;50;0');
CreateDBUniver.CreateFields.Add('ID_CODE;C;10;0');
CreateDBUniver.CreateFields.Add('SUMA;N;10;2');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.TranslateASCII:=True;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do // chr(ord(178))
begin
DbfExport.Append;
DbfExport['ACCT_CARD'] := DSet['ACCT_CARD'];
DbfExport['FIO'] := StringReplace(VarToStr(DSet['FIO']),chr(178),'I',[rfReplaceAll, rfIgnoreCase]);
DbfExport['SUMA'] := DSet['SUMMA'];
DbfExport['ID_CODE'] := ifthen((DSet['TIN']<0),'0000000000',DSet['TIN']);
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportPumb(DataSet: TpFIBDataSet);
var
RecordCount : integer;
str:string;
c:char;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('TNUM;C;10;0');
CreateDBUniver.CreateFields.Add('MFO;C;6;0');
CreateDBUniver.CreateFields.Add('ACCOUNT;C;14;0');
CreateDBUniver.CreateFields.Add('LASTNAME;C;40;0');
CreateDBUniver.CreateFields.Add('FIRSTNAME;C;40;0');
CreateDBUniver.CreateFields.Add('SURNAME;C;40;0');
CreateDBUniver.CreateFields.Add('AMOUNT;C;15;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.TranslateASCII:=True;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do // chr(ord(178))
begin
DbfExport.Append;
DbfExport['TNUM'] := DSet['TIN'];
DbfExport['MFO'] := DSet['MFO_CUST'];
DbfExport['ACCOUNT'] := DSet['ACCT_CARD'];
DbfExport['LASTNAME'] := DSet['FAMILIYA'];
DbfExport['FIRSTNAME'] := DSet['IMYA'];
DbfExport['SURNAME'] := DSet['OTCHESTVO'];
DbfExport['AMOUNT'] := StringReplace(FormatFloat('0.00', DSet['SUMMA']), ',', '.', [rfReplaceAll]);
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportDefault(DataSet: TpFIBDataSet);
var
TotalRecord:Integer;
Flag:boolean;
begin
DbfExport.Close;
DSet.Open;
DSet.Last;
Totalrecord := DSet.RecordCount;
DSet.First;
ProgressBar.Properties.Max:=TotalRecord;
Flag := CreateDBUniver.Execute;
if Flag then
begin
DbfExport.Exclusive:=True;
DbfExport.Open;
end
else
begin
ZShowMessage('Помилка!','Неможливо створити файл!',mtError,[mbOk]);
Exit;
end;
while(not DbfExport.Eof) do
begin
DbfExport.Delete;
DbfExport.Next;
end;
DbfExport.Close;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['ID_MAN'] := DSet['ID_MAN'];
DbfExport['TN'] := DSet['TN'];
DbfExport['FIO'] := DSet['FIO'];
DbfExport['SUMMA'] := DSet['SUMMA'];
DbfExport['ACCT_CARD'] := DSet['ACCT_CARD'];
DbfExport['TIN'] := DSet['TIN'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position+1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportPrivat(DataSet: TpFIBDataSet);
var
RecordCount : integer;
s : string;
TIN : string;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('PERIOD;C;22;0');
CreateDBUniver.CreateFields.Add('TN;N;8;0');
CreateDBUniver.CreateFields.Add('LSTBL;C;16;0');
CreateDBUniver.CreateFields.Add('FAM;C;20;0');
CreateDBUniver.CreateFields.Add('NAME;C;20;0');
CreateDBUniver.CreateFields.Add('OT;C;20;0');
CreateDBUniver.CreateFields.Add('RLSUM;N;16;2');
CreateDBUniver.CreateFields.Add('RLKOD;C;30;0');
CreateDBUniver.CreateFields.Add('TIN;C;10;0');
CreateDBUniver.CreateFields.Add('DATE_RO;D;8;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.TranslateASCII:=True;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
s := '';
case MonthOf(DSet['EXPORT_DAY'])of
1: s := 'январь';
2: s := 'февраль';
3: s := 'март';
4: s := 'апрель';
5: s := 'май';
6: s := 'июнь';
7: s := 'июль';
8: s := 'август';
9: s := 'сентябрь';
10: s := 'октябрь';
11: s := 'ноябрь';
12: s := 'декабрь';
end;
DbfExport['PERIOD'] := s + ' месяц ' + IntToStr(YearOf(DSet['EXPORT_DAY'])) + ' год';
DbfExport['TN'] := DSet['TN'];
DbfExport['LSTBL'] := DSet['ACCT_CARD'];
DbfExport['FAM'] := DSet['FAMILIYA'];
DbfExport['NAME'] := DSet['IMYA'];
DbfExport['OT'] := DSet['OTCHESTVO'];
DbfExport['RLSUM'] := DSet['SUMMA'];
DbfExport['RLKOD'] := DSet['PRIZNAK'];
TIN:=DSet['TIN'];
if(Pos('-',TIN)>0)then
begin
ShowMessage(TIN);
TIN:=FormatDateTime('ddmmyyyy"00"',DSet['BIRTH_DATE']);
end;
DbfExport['TIN']:= TIN;
DbfExport['DATE_RO'] := DSet['BIRTH_DATE'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportAlfa(DataSet: TpFIBDataSet);
var
RecordCount : integer;
s : string;
TIN : string;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('IDCODE;C;10;0');
CreateDBUniver.CreateFields.Add('TABNO;C;15;0');
CreateDBUniver.CreateFields.Add('ACCOUNTNO;C;14;0');
CreateDBUniver.CreateFields.Add('LASTNAME;C;38;0');
CreateDBUniver.CreateFields.Add('FIRSTNAME;C;38;0');
CreateDBUniver.CreateFields.Add('MIDDLENAME;C;38;0');
CreateDBUniver.CreateFields.Add('AMOUNT;N;19;2');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.TranslateASCII:=True;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
TIN:=DSet['TIN'];
if(Pos('-',TIN)>0)then
begin
ShowMessage(TIN);
TIN:=FormatDateTime('ddmmyyyy"00"',DSet['BIRTH_DATE']);
end;
DbfExport['IDCODE']:= TIN;
DbfExport['TABNO'] := DSet['TN'];
DbfExport['ACCOUNTNO'] := DSet['ACCT_CARD'];
DbfExport['LASTNAME'] := DSet['FAMILIYA'];
DbfExport['FIRSTNAME'] := DSet['IMYA'];
DbfExport['MIDDLENAME'] := DSet['OTCHESTVO'];
DbfExport['AMOUNT'] := DSet['SUMMA'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportUkrSib(DataSet: TpFIBDataSet);
var
RecordCount : integer;
num : integer;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
num := 1;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('TRAN_DATE;D;8;0');
CreateDBUniver.CreateFields.Add('SLIP_NR;C;7;0');
CreateDBUniver.CreateFields.Add('TRAN_TYPE;C;2;0');
CreateDBUniver.CreateFields.Add('CARD_ACCT;C;14;0');
CreateDBUniver.CreateFields.Add('AMOUNT;N;15;2');
CreateDBUniver.CreateFields.Add('CURRENCY;C;3;0');
CreateDBUniver.CreateFields.Add('OPERATOR;C;10;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['TRAN_DATE'] := DSet['EXPORT_DAY'];
DbfExport['SLIP_NR'] := inttostr(num);//IntToStr(pl_num);
DbfExport['TRAN_TYPE'] := '20';
DbfExport['CARD_ACCT'] := DSet['ACCT_CARD'];
DbfExport['AMOUNT'] := DSet['SUMMA'];
DbfExport['CURRENCY'] := 'UAH';
if(DSet['EXPORT_OPERATOR']<>null) then
DbfExport['OPERATOR'] := DSet['EXPORT_OPERATOR']
else
DbfExport['OPERATOR'] := '';
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
num := num+1;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportUkrSib2(DataSet: TpFIBDataSet);
var
RecordCount : integer;
num : integer;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
num := 1;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('SBK_FIO;C;40;0');
CreateDBUniver.CreateFields.Add('SBK_INN;C;10;0');
CreateDBUniver.CreateFields.Add('SBK_NUM;C;20;0');
CreateDBUniver.CreateFields.Add('SBK_SUM;N;10;2');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['SBK_FIO'] := DSet['FIO'];
DbfExport['SBK_INN'] := DSet['TIN'];
DbfExport['SBK_NUM'] := DSet['ACCT_CARD'];
DbfExport['SBK_SUM']:= DSet['SUMMA'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
num := num+1;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportAval(DataSet: TpFIBDataSet);
var
RecordCount : integer;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('ACCT_CARD;C;10;0');
CreateDBUniver.CreateFields.Add('FIO;C;50;0');
CreateDBUniver.CreateFields.Add('ID_CODE;C;10;0');
CreateDBUniver.CreateFields.Add('SUMA;N;10;2');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['ACCT_CARD'] := DSet['ACCT_CARD'];
DbfExport['FIO'] := DSet['FIO'];
DbfExport['SUMA'] := DSet['SUMMA'];
DbfExport['ID_CODE'] := DSet['TIN'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportTxt(DataSet: TpFIBDataSet);
var
RecordCount : integer;
sl : TStringList;
i : integer;
str, s : PAnsiChar;
begin
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(eFileNameEdit.Text));
sl := TStringList.Create;
sl.Add('Реєстр зарахувань на картрахунки');
sl.Add('органiзацiї ' + AnsiUpperCase(DSet['NAME_CUSTOMER_NATIVE']));
sl.Add('до платiжного документа N ' + IntToStr(DSet['NUM_DOC']));
sl.Add('вiд ' + StringReplace(FormatDateTime('dd/mm/yy', DSet['EXPORT_DAY']), '.', '/', [rfReplaceAll]));
sl.Add('iм''я файлу: ' + ExtractFileName(eFileNameEdit.Text));
sl.Add('МФО банку платника: ' + DSet['MFO_CUST']);
sl.Add('Поточний рахунок платника: ' + DSet['RATE_ACCOUNT_CUST']);
sl.Add('Код ЕДРПОУ платника: ' + DSet['KOD_EDRPOU_CUST']);
sl.Add('Загальна суму до зарахування: ' + FormatFloat('0.00', DSet['SUMMA_ALL']));
sl.Add('Валюта зарахування: 980');
//Если вызывается из договоров то это відрядження
if Owner.ClassName = 'TplatForm' then
sl.Add('Призначення: зарахування видатків на відрядження')
else
sl.Add('Призначення: зарахування зароботной плати');
sl.Add('---------------------------------------------------------------------');
try
While not(DSet.Eof) do
begin
sl.Add(DSet.FBN('TN').AsString + ' ' + DSet['ACCT_CARD'] + ' ' + StringReplace(FormatFloat('0.00', DSet.FBN('SUMMA').AsCurrency),',', '.', [rfReplaceAll]) + ' ' + DSet['FIO']);
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
for i := 0 to sl.Count - 1 do
begin
s := PAnsiChar(sl.Strings[i]);
GetMem(str, Length(s) + 2);
CharToOem(s, Str);
sl.Strings[i] := StrPas(Str);;
end;
sl.SaveToFile(eFileNameEdit.Text);
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
sl.Free;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportOschad(DataSet: TpFIBDataSet);
var
RecordCount : integer;
sl : TStringList;
i : integer;
count : integer;
begin
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(eFileNameEdit.Text));
sl := TStringList.Create;
sl.Add(IntToStr(RecordCount)+'|'+ StringReplace(FormatFloat('0.00', DSet['SUMMA_ALL']), ',', '.', [rfReplaceAll])+'|');
try
While not(DSet.Eof) do
begin
sl.Add('20|'+varToStr(DSet['ACCT_CARD'])+'|'+varToStr(DSet['FIO'])+'|'+StringReplace(FormatFloat('0.00', DSet['SUMMA']), ',', '.', [rfReplaceAll])+'|');
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
sl.SaveToFile(eFileNameEdit.Text);
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
sl.Free;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportOschad2(DataSet: TpFIBDataSet);
var
RecordCount,i : integer;
buf0,S,Res:string;
buf1:WideString;
Source : array[0..255] of Char;
Dest:PChar;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('NSC;C;15;0');
CreateDBUniver.CreateFields.Add('SUMMA;N;20;2');
CreateDBUniver.CreateFields.Add('FIO;C;38;0');
CreateDBUniver.CreateFields.Add('ID_KOD;C;14;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.TranslateASCII:=True;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
// DbfExport.TranslateASCII:=False;
DbfExport.Append;
DbfExport['NSC'] := DSet['ACCT_CARD'];
DbfExport['SUMMA'] := DSet['SUMMA'];
DbfExport['FIO'] := DSet['FIO']; //(buf0);
DbfExport['ID_KOD'] := ifthen((DSet['TIN']<0),'0000000000',DSet['TIN']);
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
// ChangeByte(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName),$026,$0C9,29);
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportTxt2(DataSet: TpFIBDataSet);
var
RecordCount : integer;
sl : TStringList;
i : integer;
count : integer;
begin
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(eFileNameEdit.Text));
sl := TStringList.Create;
sl.Add('Реєстр зарахувань на картрахунки');
sl.Add('органiзацiї ' + AnsiUpperCase(DSet['NAME_CUSTOMER_NATIVE']));
sl.Add('до платiжного документа N ' + IntToStr(DSet['NUM_DOC']));
sl.Add('вiд ' + StringReplace(FormatDateTime('dd.mm.yy', DSet['EXPORT_DAY']), '.', '.', [rfReplaceAll]));
sl.Add('iм''я файлу: ' + ExtractFileName(eFileNameEdit.Text));
sl.Add('МФО банку платника: ' + DSet['MFO_CUST']);
sl.Add('Поточний рахунок платника: ' + DSet['RATE_ACCOUNT_CUST']);
sl.Add('Код ЕДРПОУ платника: ' + DSet['KOD_EDRPOU_CUST']);
sl.Add('Загальна суму до зарахування: ' + StringReplace(FormatFloat('0.00', DSet['SUMMA_ALL']), ',', '.', [rfReplaceAll]));
sl.Add('Валюта зарахування: 980');
//Если вызывается из договоров то это відрядження
if Owner.ClassName = 'TplatForm' then
sl.Add('Призначення: зарахування видатків на відрядження')
else
sl.Add('Призначення: зарахування зароботной плати');
sl.Add('---------------------------------------------------------------------');
count:=1;
try
While not(DSet.Eof) do
begin
sl.Add(' '+Copy(IntToStr(count)+' ',0,10) + ' ' + DSet['ACCT_CARD'] + ' ' + StringReplace(FormatFloat('0.00', DSet.FBN('SUMMA').AsCurrency), ',', '.', [rfReplaceAll]) + ' ' + DSet['FIO']);
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
Inc(count);
end;
for i := 0 to sl.Count - 1 do
begin
{ s := PAnsiChar(sl.Strings[i]);
GetMem(str, Length(s) + 2);
CharToOem(s, Str);
sl.Strings[i] := StrPas(Str);;}
end;
sl.SaveToFile(eFileNameEdit.Text);
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
sl.Free;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportProminvestkiev(DataSet: TpFIBDataSet);
var
RecordCount : integer;
sl : TStringList;
count : integer;
begin
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(eFileNameEdit.Text));
sl := TStringList.Create;
count:=0;
while not(DSet.Eof) do
begin
DSet.Next;
Inc(count);
end;
sl.Add('Розпорядження на списання коштiв для поповнення карткових рахункiв');
sl.Add('Ф Вiдд. ПАТ Промiнвестбанк в м.Черкаси');
sl.Add('');
sl.Add('CODE: 074');
sl.Add('FILE: uObluian.F01');
sl.Add('DATE: '+StringReplace(FormatDateTime('dd.mm.yy', DSet['EXPORT_DAY']), '.', '/', [rfReplaceAll]));
sl.Add('CURR: 980');
sl.Add('CARD: ' + IntToStr(count));
sl.Add('AMNT: ' + StringReplace(FormatFloat('0.00', DSet['SUMMA_ALL']), ',', '.', [rfReplaceAll]));
sl.Add('TEXT: ' + IntToStr(DSet['NUM_DOC'])+' від '+StringReplace(FormatDateTime('dd.mm.yy', DSet['EXPORT_DAY']), '.', '.', [rfReplaceAll]));
sl.Add('START: ');
sl.Add('');
DSet.First;
try
while not(DSet.Eof) do
begin
sl.Add(DSet['ACCT_CARD'] + ' ' + StringReplace(FormatFloat('0.00', DSet.FBN('SUMMA').AsCurrency), ',', '.', [rfReplaceAll]));
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
sl.Add('');
sl.Add('END:');
sl.SaveToFile(eFileNameEdit.Text);
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
sl.Free;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportVTB(DataSet: TpFIBDataSet);
var
RecordCount : integer;
count : integer;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('NNP;N;5;0');
CreateDBUniver.CreateFields.Add('FAM;C;20;0');
CreateDBUniver.CreateFields.Add('NAME;C;20;0');
CreateDBUniver.CreateFields.Add('SURNAME;C;20;0');
CreateDBUniver.CreateFields.Add('INN;C;10;0');
CreateDBUniver.CreateFields.Add('CARDNO;C;16;0');
CreateDBUniver.CreateFields.Add('SUMMA;N;16;2');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.TranslateASCII:=false;
DbfExport.Exclusive:=False;
DbfExport.Open;
count:=1;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['NNP'] := count;
DbfExport['FAM'] := DSet['FAMILIYA'];
DbfExport['NAME'] := DSet['IMYA'];
DbfExport['SURNAME'] := DSet['OTCHESTVO'];
DbfExport['INN'] := DSet['TIN'];
DbfExport['CARDNO'] := DSet['ACCT_CARD'];
DbfExport['SUMMA'] := DSet['SUMMA'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
Inc(count);
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportPrivatKiev(DataSet: TpFIBDataSet);
var
RecordCount : integer;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('LSTBL;C;10;0');
CreateDBUniver.CreateFields.Add('RLSUM;N;16;2');
CreateDBUniver.CreateFields.Add('RLKOD;C;30;0');
CreateDBUniver.CreateFields.Add('FAM;C;50;0');
CreateDBUniver.CreateFields.Add('NAME;C;50;0');
CreateDBUniver.CreateFields.Add('OT;C;50;0');
CreateDBUniver.CreateFields.Add('CARD_NO;C;16;0');
CreateDBUniver.CreateFields.Add('INN;C;10;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.TranslateASCII:=true;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['LSTBL'] := DSet['TIN'];
DbfExport['RLSUM'] := DSet['SUMMA'];
DbfExport['RLKOD'] := '750';
DbfExport['FAM'] := DSet['FAMILIYA'];
DbfExport['NAME'] := DSet['IMYA'];
DbfExport['OT'] := DSet['OTCHESTVO'];
DbfExport['CARD_NO'] := DSet['ACCT_CARD'];
{TIN:=DSet['TIN'];
if(Pos('-',TIN)>0)then
begin
ShowMessage(TIN);
TIN:=FormatDateTime('yyyymmdd"00"',DSet['BIRTH_DATE']);
end; }
DbfExport['INN']:= DSet['TIN'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportKiev(DataSet: TpFIBDataSet);
var
RecordCount : integer;
sl : TStringList;
count : integer;
begin
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(eFileNameEdit.Text));
sl := TStringList.Create;
sl.Add(eFileNameEdit.Text+' 001'+FormatDateTime('yyyymmdd', DSet['EXPORT_DAY']));
DSet.First;
count:=0;
try
while not(DSet.Eof) do
begin
sl.Add(DSet['ACCT_CARD'] + ' ' + StringReplace(FormatFloat('0.00', DSet.FBN('SUMMA').AsCurrency), ',', '', [rfReplaceAll])+'980'+FormatDateTime('yyyymmdd', DSet['EXPORT_DAY']));
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
Inc(count);
end;
sl.Add(eFileNameEdit.Text+' '+IntToStr(count+2)+' '+StringReplace(FormatFloat('0.00', DSet['SUMMA_ALL']), ',', '', [rfReplaceAll]));
sl.SaveToFile(eFileNameEdit.Text);
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
sl.Free;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportImex(DataSet: TpFIBDataSet);
var
RecordCount : integer;
sl : TStringList;
count : integer;
begin
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(eFileNameEdit.Text));
sl := TStringList.Create;
count:=0;
while not(DSet.Eof) do
begin
DSet.Next;
Inc(count);
end;
sl.Add('ВЕДОМОСТЬ 1 '+IntToStr(count)+' '+DSet['KOD_EDRPOU_CUST']+' '+DSet['RATE_ACCOUNT_CUST']+
' '+FormatDateTime('dd.mm.yyyy', DSet['EXPORT_DAY'])+' '+StringReplace(FormatFloat('0.00', DSet['SUMMA_ALL']), ',', '', [rfReplaceAll]));
DSet.First;
try
while not(DSet.Eof) do
begin
sl.Add(FormatMaskText('LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL',DSet['FAMILIYA'])+
FormatMaskText('LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL',DSet['IMYA'])+
FormatMaskText('LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL',DSet['OTCHESTVO'])+
FormatMaskText('AAAAAAAAAAAAAAAAAA',DSet['ACCT_CARD'])+
FormatMaskText('AAAAAAAA',StringReplace(FormatFloat('0.00', DSet.FBN('SUMMA').AsCurrency), ',','', [rfReplaceAll]))+
FormatMaskText('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',IntToStr(DSet['NUM_DOC'])+' від '+StringReplace(FormatDateTime('dd.mm.yy', DSet['EXPORT_DAY']), '.', '.', [rfReplaceAll])));
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
sl.SaveToFile(eFileNameEdit.Text);
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
sl.Free;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportPravex(DataSet: TpFIBDataSet);
var
RecordCount : integer;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('ACCOUNT;C;14;0');
CreateDBUniver.CreateFields.Add('SUM;N;12;0');
CreateDBUniver.CreateFields.Add('LAST;C;20;0');
CreateDBUniver.CreateFields.Add('NAME;C;20;0');
CreateDBUniver.CreateFields.Add('SNAME;C;20;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['ACCOUNT'] := DSet['ACCT_CARD'];
DbfExport['SUM'] := StringReplace(FormatFloat('0.00', DSet.FBN('SUMMA').AsCurrency), ',','', [rfReplaceAll]);
DbfExport['LAST'] := DSet['FAMILIYA'];
DbfExport['NAME'] := DSet['IMYA'];
DbfExport['SNAME'] := DSet['OTCHESTVO'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.GenFileName(Path : string);
var
s : string;
function GetExt : string;
begin
if (fType=12) or (fType=16) then Result := '.txt'
else
begin
if (fType = 7) then Result := '.828' else Result := '.dbf';
end
end;
begin
if path[Length(path)] <> '\' then path := path + '\';
// s := FormatDateTime('mmdd', date);
s := IntToStr(pl_num);
case fType of
0 : s := 'DF' + s;
1 : s := 'EX' + s;
2 : s := 'PR' + s;
3 : s := 'PV' + S;
4 : s := 'US' + s;
5 : s := 'AV' + s;
6 : s := 'US' + s;
7 : s := '^001';
12: s := 'IMEX' + s;
15 : s := 'US' + s;
17 : s := 'US' +s;
18 : s := 'PUMB' +s;
19: s := 'ALF' +s;
20: s := 'OSC' + s;
end;
{ num := 0;
while FileExists(path + s + IfThen(num < 10, '0' + IntToStr(num), IntToStr(num)) + GetExt) do
begin
inc(num);
end;}
// s := path + s + IfThen(num < 10, '0' + IntToStr(num), IntToStr(num)) + GetExt;\
if(ftype<>18) then
begin
if(ftype<>7) then s := path + s + 'P' + GetExt
else
begin
s := s + year[YearOf(Date)]+day[DayOf(Date)]+month[MonthOf(Date)]+day[pl_num mod 36];
s := path + s + GetExt;
end;
end
else s := path + s + GetExt;
if(fType=8)then
s:=path+'uObluian.F01';
if(fType=9)then
s:=path+'D'+FormatDateTime('yymmdd', date)+'S.dbf';
if(fType=10)then
s:=path+'28E_0291.dbf';
if(fType=11)then
s:=path+'p0010071.iss';
if(fType=13)then
s:=path+'xbase.dbf';
//if(fType=18)then
// s:=path+'.dbf';
eFileNameEdit.Text := s;
DbfExport.DatabaseName := ExtractFilePath(s);
DbfExport.TableName := ExtractFileName(s);
end;
procedure TBankExportForm.ExportUniCreditDBF(DataSet: TpFIBDataSet);
var
RecordCount,i : integer;
buf0,S,Res:string;
buf1:WideString;
Source : array[0..255] of Char;
Dest:PChar;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('PAN;C;15;0');
CreateDBUniver.CreateFields.Add('SUMA;N;12;2');
CreateDBUniver.CreateFields.Add('FIO;C;80;0');
CreateDBUniver.CreateFields.Add('IDEN;C;10;0');
CreateDBUniver.CreateFields.Add('TN;C;20;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.TranslateASCII:=True;
DbfExport.Exclusive:=False;
DbfExport.Open;
DbfExport.Append;
buf0:= '@'+ VarToStr(DSet['RATE_ACCOUNT_CUST']);
OemToAnsi(PAnsiChar(buf0), PAnsiChar(buf0));
DbfExport['PAN'] := buf0;
DbfExport['SUMA']:= DSet['SUMMA_ALL'];
buf0:=IfThen(Owner.ClassName = 'TplatForm','зарахування видатків на відр.','зарахування зар. плати');
OemToAnsi(PAnsiChar(buf0), PAnsiChar(buf0));
DbfExport['FIO'] := buf0;
DbfExport['IDEN'] := DSet['OKPO'];
DbfExport['TN'] := DSet['MFO_CUST'];
DbfExport.Post;
try
While not(DSet.Eof) do
begin
DbfExport.TranslateASCII:=False;
DbfExport.Append;
DbfExport['PAN'] := DSet['ACCT_CARD'];
DbfExport['SUMA'] := DSet['SUMMA'];
DbfExport['FIO'] := DSet['FIO']; //(buf0);
DbfExport['IDEN'] := ifthen((DSet['TIN']<0),'0000000000',DSet['TIN']);
DbfExport['TN'] := DSet['TN'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
// ChangeByte(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName),$026,$0C9,29);
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
function TBankExportForm.ChangeByte(const FilePath: String; OldByte,NewByte: Byte; SetPos: int64): Boolean;
var
FS: TFileStream;
B: Byte;
begin
Result := False;
FS := TFileStream.Create(FilePath,FMOpenReadWrite);
//try
if FS.Size<SetPos then Exit;
FS.Position := SetPos;
FS.Read(B,1);
// if B=OldByte then
begin
FS.Position := SetPos;
Result := FS.Write(newByte,1)=1;
end;
//finally
FS.Free;
//end;
end;
procedure TBankExportForm.ExportUkrKomunBank(DataSet: TpFIBDataSet);
var
RecordCount,i : integer;
buf0,S,Res:string;
buf1:WideString;
Source : array[0..255] of Char;
Dest:PChar;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('FIO;C;80;0');
CreateDBUniver.CreateFields.Add('PAN;C;16;0');
CreateDBUniver.CreateFields.Add('SUMA;N;16;2');
CreateDBUniver.CreateFields.Add('IDEN;C;10;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.TranslateASCII:=True;
DbfExport.Exclusive:=False;
DbfExport.Open;
{DbfExport.Append;
//buf0:= '@'+ VarToStr(DSet['RATE_ACCOUNT_CUST']);
//OemToAnsi(PAnsiChar(buf0), PAnsiChar(buf0));
//DbfExport['PAN'] := buf0;
DbfExport['PAN'] := DSet['RATE_ACCOUNT_CUST'];
DbfExport['SUMA']:= DSet['SUMMA_ALL'];
//buf0:=IfThen(Owner.ClassName = 'TplatForm','зарахування видатків на відр.','зарахування зар. плати');
//OemToAnsi(PAnsiChar(buf0), PAnsiChar(buf0));
DbfExport['FIO'] := buf0;
DbfExport['IDEN'] := DSet['OKPO'];
DbfExport['TN'] := DSet['MFO_CUST'];
DbfExport.Post; }
try
While not(DSet.Eof) do
begin
DbfExport.TranslateASCII:=False;
DbfExport.Append;
DbfExport['PAN'] := DSet['ACCT_CARD'];
DbfExport['SUMA'] := DSet['SUMMA'];
DbfExport['FIO'] := DSet['FIO']; //(buf0);
DbfExport['IDEN'] := ifthen((DSet['TIN']<0),'0000000000',DSet['TIN']);
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
// ChangeByte(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName),$026,$0C9,29);
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportUkrsibbankSimple(DataSet: TpFIBDataSet);
var
TotalRecord:Integer;
Flag:boolean;
begin
DbfExport.Close;
DSet.Open;
DSet.Last;
Totalrecord := DSet.RecordCount;
DSet.First;
ProgressBar.Properties.Max:=TotalRecord;
Flag := CreateDBUniver.Execute;
if Flag then
begin
DbfExport.Exclusive:=True;
DbfExport.Open;
end
else
begin
ZShowMessage('Помилка!','Неможливо створити файл!',mtError,[mbOk]);
Exit;
end;
while(not DbfExport.Eof) do
begin
DbfExport.Delete;
DbfExport.Next;
end;
DbfExport.Close;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['ID_MAN'] := DSet['ID_MAN'];
DbfExport['TN'] := DSet['TN'];
DbfExport['FIO'] := DSet['FIO'];
DbfExport['SUMMA'] := DSet['SUMMA'];
DbfExport['ACCT_CARD'] := DSet['ACCT_CARD'];
DbfExport['TIN'] := DSet['TIN'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position+1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
end.
|
unit SpeechStringConstants;
interface
const SpeechAddRemoveWord = 'AddRemoveWord';
const SpeechAudioFormatGUIDText = '{7CEEF9F9-3D13-11d2-9EE7-00C04F797396}';
const SpeechAudioFormatGUIDWave = '{C31ADBAE-527F-4ff5-A230-F62BB61FF70C}';
const SpeechAudioProperties = 'AudioProperties';
const SpeechAudioVolume = 'AudioVolume';
const SpeechCategoryAppLexicons = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\AppLexicons';
const SpeechCategoryAudioIn = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\AudioInput';
const SpeechCategoryAudioOut = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\AudioOutput';
const SpeechCategoryPhoneConverters = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\PhoneConverters';
const SpeechCategoryRecognizers = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Recognizers';
const SpeechCategoryRecoProfiles = 'HKEY_CURRENT_USER\SOFTWARE\Microsoft\Speech\RecoProfiles';
const SpeechCategoryVoices = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices';
const SpeechDictationTopicSpelling = 'Spelling';
const SpeechEngineProperties = 'EngineProperties';
const SpeechGrammarTagDictation = '*';
const SpeechGrammarTagUnlimitedDictation = '*+';
const SpeechGrammarTagWildcard = '...';
const SpeechMicTraining = 'MicTraining';
const SpeechPropertyAdaptationOn = 'AdaptationOn';
const SpeechPropertyComplexResponseSpeed = 'ComplexResponseSpeed';
const SpeechPropertyHighConfidenceThreshold = 'HighConfidenceThreshold';
const SpeechPropertyLowConfidenceThreshold = 'LowConfidenceThreshold';
const SpeechPropertyNormalConfidenceThreshold = 'NormalConfidenceThreshold';
const SpeechPropertyResourceUsage = 'ResourceUsage';
const SpeechPropertyResponseSpeed = 'ResponseSpeed';
const SpeechRecoProfileProperties = 'RecoProfileProperties';
const SpeechRegistryLocalMachineRoot = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech';
const SpeechRegistryUserRoot = 'HKEY_CURRENT_USER\SOFTWARE\Microsoft\Speech';
const SpeechTokenIdUserLexicon = 'HKEY_CURRENT_USER\SOFTWARE\Microsoft\Speech\CurrentUserLexicon';
const SpeechTokenKeyAttributes = 'Attributes';
const SpeechTokenKeyFiles = 'Files';
const SpeechTokenKeyUI = 'UI';
const SpeechTokenValueCLSID = 'CLSID';
const SpeechUserTraining = 'UserTraining';
const SpeechVoiceCategoryTTSRate = 'DefaultTTSRate';
const SpeechVoiceSkipTypeSentence = 'Sentence';
implementation
end.
|
PROGRAM Pythagoras;
FUNCTION Power(x: REAL; n: INTEGER): REAL;
VAR
counter: INTEGER;
result: REAL;
BEGIN
counter := 1;
result := x; {* Schritt 1 *}
if n = 1 THEN {* Schritt 2 *}
result := x;
if n = 0 THEN {* Schritt 3 *}
result := 1;
WHILE (counter < n) DO {* Schritt 4 *}
BEGIN
result := result * x;
counter := counter + 1;
END;
Power := result;
END;
FUNCTION SquareRoot(a: REAL; iterations: INTEGER): REAL;
VAR
result: REAL;
counter: INTEGER;
BEGIN
IF a > 0 THEN
BEGIN
counter := 1;
result := (a + 1) / 2; {* Schritt 1 *}
WHILE counter <= iterations DO {* Schritt 2 *}
BEGIN
result := (result + (a/result)) / 2;
counter := counter + 1;
END;
END
ELSE result := 0;
SquareRoot := result;
END;
FUNCTION Hypotenuse(a, b: REAL; iterations: INTEGER): REAL;
BEGIN
Hypotenuse := SquareRoot((Power(a,2) + Power(b,2)), iterations);
END;
PROCEDURE AssertPower(term: STRING; x: REAL; n: INTEGER; expectedResult: REAL);
BEGIN
IF Power(x,n) = expectedResult THEN
WriteLn(term, ' -> ' , expectedResult , ' --> OK')
ELSE WriteLn(term, ' -> ' , expectedResult , ' --> X')
END;
PROCEDURE AssertSquareRoot(term: STRING; a: REAL; iterations: INTEGER; expectedResult: REAL);
BEGIN
WriteLn(term, ' -> ', SquareRoot(a,iterations) , ' | expected ', expectedResult);
END;
PROCEDURE AssertHypotenuse(term: STRING; a, b: REAL; iterations: INTEGER; expectedResult: REAL);
BEGIN
WriteLn(term, ' -> ', Hypotenuse(a, b, iterations) , ' | expected ', expectedResult);
END;
BEGIN
AssertPower('Power(2,3)', 2, 3, 8);
AssertPower('Power(-2,3)', -2, 3, -8);
AssertPower('Power(0,1)', 0, 1, 0);
AssertPower('Power(5,1)', 5, 1, 5);
AssertPower('Power(5,0)', 5, 0, 1);
AssertPower('Power(1.5,2)', 1.5, 2, 2.25);
AssertPower('Power(0,0)', 0, 0, 1);
AssertSquareRoot('SquareRoot(2,10)', 2, 10, 1.4142135623730949);
AssertSquareRoot('SquareRoot(2,-3)', 2, -3, 1.5);
AssertSquareRoot('SquareRoot(2,0)', 2, 0, 1.5);
AssertSquareRoot('SquareRoot(-4,10)', -4, 10, 0);
AssertSquareRoot('SquareRoot(0,10)', 0, 10, 0);
AssertHypotenuse('Hypotenuse(5,0,10)', 5, 0, 10, 5);
AssertHypotenuse('Hypotenuse(5,5,10)', 5, 5, 10, 7.0710678118654755);
AssertHypotenuse('Hypotenuse(0,5,10)', 0, 5, 10, 5);
AssertHypotenuse('Hypotenuse(-5,5,10)', -5, 5, 10, 7.0710678118654755);
END. |
unit CatEntities;
{
Catarinka - HTML Entity Decoder & Encoder
Copyright (c) 2003-2017 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
System.SysUtils,
{$IFDEF DXE7_OR_UP}
System.NetEncoding,
{$ELSE}
Web.HTTPApp,
{$ENDIF}
CatMatch;
{$ELSE}
SysUtils, HTTPApp, CatMatch;
{$ENDIF}
type
THTMLEntity = record
char: string;
name: string;
code: integer;
od: boolean; // true if compatibe with non-unicode
end;
type
THTMLEntities = class
private
function CanEncodeEntity(const e:THTMLEntity): boolean;
function EntityAllowed(const e:THTMLEntity): boolean;
function HextoDec(ARegExpr : TCatRegExpr): string;
function DecodeEntity(ARegExpr : TCatRegExpr): string;
function RemoveLeadingZeros(ARegExpr : TCatRegExpr): string;
public
function Decode(const s:string):string;
function Encode(const s:string):string;
constructor Create;
destructor Destroy; override;
end;
function HTML_Entity_Decode(const s: string): string;
function HTML_Entity_Encode(const s: string): string;
implementation
uses
CatStrings;
const
reUnicodeSymbol = '\&#(x|X)([A-Fa-f0-9]+){1,4}\;';
reDecimalSymbol = '\&#([0-9]+){1,4}\;';
const
THTMLEntityMap: array[1..276] of THTMLEntity = (
(char: '"'; name: 'quot'; code: 34),
(char: ''''; name: 'apos'; code: 39),
(char: '<'; name: 'lt'; code: 60),
(char: '>'; name: 'gt'; code: 62),
// Codes 128-159 contain the Windows Latin-1 extended characters
(char: '€'; name: 'euro'; code: 128),
(char: '‚'; name: 'sbquo'; code: 130),
(char: 'ƒ'; name: 'fnof'; code: 131),
(char: '„'; name: 'bdquo'; code: 132),
(char: '…'; name: 'hellip'; code: 133),
(char: '†'; name: 'dagger'; code: 134),
(char: '‡'; name: 'Dagger'; code: 135),
(char: 'ˆ'; name: 'circ'; code: 136),
(char: '‰'; name: 'permil'; code: 137),
(char: 'Š'; name: 'Scaron'; code: 138),
(char: '‹'; name: 'lsaquo'; code: 139),
(char: 'Œ'; name: 'OElig'; code: 140),
(char: '‘'; name: 'lsquo'; code: 145),
(char: '’'; name: 'rsquo'; code: 146),
(char: '“'; name: 'ldquo'; code: 147),
(char: '”'; name: 'rdquo'; code: 148),
(char: '•'; name: 'bull'; code: 149),
(char: '–'; name: 'ndash'; code: 150),
(char: '—'; name: 'mdash'; code: 151),
(char: '˜'; name: 'tilde'; code: 152),
(char: '™'; name: 'trade'; code: 153),
(char: 'š'; name: 'scaron'; code: 154),
(char: '›'; name: 'rsaquo'; code: 155),
(char: 'œ'; name: 'oelig'; code: 156),
(char: 'Ÿ'; name: 'Yuml'; code: 159),
// End of Latin-1 extended characters
(char: ' '; name: 'nbsp'; code: 160),
(char: '¡'; name: 'iexcl'; code: 161),
(char: '¢'; name: 'cent'; code: 162),
(char: '£'; name: 'pound'; code: 163),
(char: '¤'; name: 'curren'; code: 164),
(char: '¥'; name: 'yen'; code: 165),
(char: '¦'; name: 'brvbar'; code: 166),
(char: '§'; name: 'sect'; code: 167),
(char: '¨'; name: 'uml'; code: 168),
(char: '©'; name: 'copy'; code: 169),
(char: 'ª'; name: 'ordf'; code: 170),
(char: '«'; name: 'laquo'; code: 171),
(char: '¬'; name: 'not'; code: 172),
(char: ''; name: 'shy'; code: 173),
(char: '®'; name: 'reg'; code: 174),
(char: '¯'; name: 'macr'; code: 175),
(char: '°'; name: 'deg'; code: 176),
(char: '±'; name: 'plusmn'; code: 177),
(char: '²'; name: 'sup2'; code: 178),
(char: '³'; name: 'sup3'; code: 179),
(char: '´'; name: 'acute'; code: 180),
(char: 'µ'; name: 'micro'; code: 181),
(char: '¶'; name: 'para'; code: 182),
(char: '·'; name: 'middot'; code: 183),
(char: '¸'; name: 'cedil'; code: 184),
(char: '¹'; name: 'sup1'; code: 185),
(char: 'º'; name: 'ordm'; code: 186),
(char: '»'; name: 'raquo'; code: 187),
(char: '¼'; name: 'frac14'; code: 188),
(char: '½'; name: 'frac12'; code: 189),
(char: '¾'; name: 'frac34'; code: 190),
(char: '¿'; name: 'iquest'; code: 191),
(char: 'À'; name: 'Agrave'; code: 192),
(char: 'Á'; name: 'Aacute'; code: 193),
(char: 'Â'; name: 'Acirc'; code: 194),
(char: 'Ã'; name: 'Atilde'; code: 195),
(char: 'Ä'; name: 'Auml'; code: 196),
(char: 'Å'; name: 'Aring'; code: 197),
(char: 'Æ'; name: 'AElig'; code: 198),
(char: 'Ç'; name: 'Ccedil'; code: 199),
(char: 'È'; name: 'Egrave'; code: 200),
(char: 'É'; name: 'Eacute'; code: 201),
(char: 'Ê'; name: 'Ecirc'; code: 202),
(char: 'Ë'; name: 'Euml'; code: 203),
(char: 'Ì'; name: 'Igrave'; code: 204),
(char: 'Í'; name: 'Iacute'; code: 205),
(char: 'Î'; name: 'Icirc'; code: 206),
(char: 'Ï'; name: 'Iuml'; code: 207),
(char: 'Ð'; name: 'ETH'; code: 208),
(char: 'Ñ'; name: 'Ntilde'; code: 209),
(char: 'Ò'; name: 'Ograve'; code: 210),
(char: 'Ó'; name: 'Oacute'; code: 211),
(char: 'Ô'; name: 'Ocirc'; code: 212),
(char: 'Õ'; name: 'Otilde'; code: 213),
(char: 'Ö'; name: 'Ouml'; code: 214),
(char: '×'; name: 'times'; code: 215),
(char: 'Ø'; name: 'Oslash'; code: 216),
(char: 'Ù'; name: 'Ugrave'; code: 217),
(char: 'Ú'; name: 'Uacute'; code: 218),
(char: 'Û'; name: 'Ucirc'; code: 219),
(char: 'Ü'; name: 'Uuml'; code: 220),
(char: 'Ý'; name: 'Yacute'; code: 221),
(char: 'Þ'; name: 'THORN'; code: 222),
(char: 'ß'; name: 'szlig'; code: 223),
(char: 'à'; name: 'agrave'; code: 224),
(char: 'á'; name: 'aacute'; code: 225),
(char: 'â'; name: 'acirc'; code: 226),
(char: 'ã'; name: 'atilde'; code: 227),
(char: 'ä'; name: 'auml'; code: 228),
(char: 'å'; name: 'aring'; code: 229),
(char: 'æ'; name: 'aelig'; code: 230),
(char: 'ç'; name: 'ccedil'; code: 231),
(char: 'è'; name: 'egrave'; code: 232),
(char: 'é'; name: 'eacute'; code: 233),
(char: 'ê'; name: 'ecirc'; code: 234),
(char: 'ë'; name: 'euml'; code: 235),
(char: 'ì'; name: 'igrave'; code: 236),
(char: 'í'; name: 'iacute'; code: 237),
(char: 'î'; name: 'icirc'; code: 238),
(char: 'ï'; name: 'iuml'; code: 239),
(char: 'ð'; name: 'eth'; code: 240),
(char: 'ñ'; name: 'ntilde'; code: 241),
(char: 'ò'; name: 'ograve'; code: 242),
(char: 'ó'; name: 'oacute'; code: 243),
(char: 'ô'; name: 'ocirc'; code: 244),
(char: 'õ'; name: 'otilde'; code: 245),
(char: 'ö'; name: 'ouml'; code: 246),
(char: '÷'; name: 'divide'; code: 247),
(char: 'ø'; name: 'oslash'; code: 248),
(char: 'ù'; name: 'ugrave'; code: 249),
(char: 'ú'; name: 'uacute'; code: 250),
(char: 'û'; name: 'ucirc'; code: 251),
(char: 'ü'; name: 'uuml'; code: 252),
(char: 'ý'; name: 'yacute'; code: 253),
(char: 'þ'; name: 'thorn'; code: 254),
(char: 'ÿ'; name: 'yuml'; code: 255),
(char: 'Œ'; name: 'OElig'; code: 338; od: true),
(char: 'œ'; name: 'oelig'; code: 339; od: true),
(char: 'Š'; name: 'Scaron'; code: 352; od: true),
(char: 'š'; name: 'scaron'; code: 353; od: true),
(char: 'Ÿ'; name: 'Yuml'; code: 376; od: true),
(char: 'ƒ'; name: 'fnof'; code: 402; od: true),
(char: 'ˆ'; name: 'circ'; code: 710; od: true),
(char: '˜'; name: 'tilde'; code: 732; od: true),
// ISOgrk3 starts
(char: #913; name: 'Alpha'; code: 913),
(char: #914; name: 'Beta'; code: 914),
(char: #915; name: 'Gamma'; code: 915),
(char: #916; name: 'Delta'; code: 916),
(char: #917; name: 'Epsilon'; code: 917),
(char: #918; name: 'Zeta'; code: 918),
(char: #919; name: 'Eta'; code: 919),
(char: #920; name: 'Theta'; code: 920),
(char: #921; name: 'Iota'; code: 921),
(char: #922; name: 'Kappa'; code: 922),
(char: #923; name: 'Lambda'; code: 923),
(char: #924; name: 'Mu'; code: 924),
(char: #925; name: 'Nu'; code: 925),
(char: #926; name: 'Xi'; code: 926),
(char: #927; name: 'Omicron'; code: 927),
(char: #928; name: 'Pi'; code: 928),
(char: #929; name: 'Rho'; code: 929),
(char: #931; name: 'Sigma'; code: 931),
(char: #932; name: 'Tau'; code: 932),
(char: #933; name: 'Upsilon'; code: 933),
(char: #934; name: 'Phi'; code: 934),
(char: #935; name: 'Chi'; code: 935),
(char: #936; name: 'Psi'; code: 936),
(char: #937; name: 'Omega'; code: 937),
(char: #945; name: 'alpha'; code: 945),
(char: #946; name: 'beta'; code: 946),
(char: #947; name: 'gamma'; code: 947),
(char: #948; name: 'delta'; code: 948),
(char: #949; name: 'epsilon'; code: 949),
(char: #950; name: 'zeta'; code: 950),
(char: #951; name: 'eta'; code: 951),
(char: #952; name: 'theta'; code: 952),
(char: #953; name: 'iota'; code: 953),
(char: #954; name: 'kappa'; code: 954),
(char: #955; name: 'lambda'; code: 955),
(char: #956; name: 'mu'; code: 956),
(char: #957; name: 'nu'; code: 957),
(char: #958; name: 'xi'; code: 958),
(char: #959; name: 'omicron'; code: 959),
(char: #960; name: 'pi'; code: 960),
(char: #961; name: 'rho'; code: 961),
(char: #962; name: 'sigmaf'; code: 962),
(char: #963; name: 'sigma'; code: 963),
(char: #964; name: 'tau'; code: 964),
(char: #965; name: 'upsilon'; code: 965),
(char: #966; name: 'phi'; code: 966),
(char: #967; name: 'chi'; code: 967),
(char: #968; name: 'psi'; code: 968),
(char: #969; name: 'omega'; code: 969),
(char: #977; name: 'thetasym'; code: 977),
(char: #978; name: 'upsih'; code: 978),
(char: #982; name: 'piv'; code: 982),
// greek end
//ISOpub
(char: #8194; name: 'ensp'; code: 8194),
(char: #8195; name: 'emsp'; code: 8195),
(char: #8201; name: 'thinsp'; code: 8201),
(char: #8204; name: 'zwnj'; code: 8204),
(char: #8205; name: 'zwj'; code: 8205),
(char: #8206; name: 'lrm'; code: 8206),
(char: #8207; name: 'rlm'; code: 8207),
(char: '–'; name: 'ndash'; code: 8211; od: true),
(char: '—'; name: 'mdash'; code: 8212; od: true),
(char: '‘'; name: 'lsquo'; code: 8216; od: true),
(char: '’'; name: 'rsquo'; code: 8217; od: true),
(char: '‚'; name: 'sbquo'; code: 8218; od: true),
(char: '“'; name: 'ldquo'; code: 8220; od: true),
(char: '”'; name: 'rdquo'; code: 8221; od: true),
(char: '„'; name: 'bdquo'; code: 8222; od: true),
(char: '†'; name: 'dagger'; code: 8224; od: true),
(char: '‡'; name: 'Dagger'; code: 8225; od: true),
(char: '•'; name: 'bull'; code: 8226; od: true),
(char: '…'; name: 'hellip'; code: 8230; od: true),
(char: '‰'; name: 'permil'; code: 8240; od: true),
(char: ''''; name: 'prime'; code: 8242; od: true),
(char: #8243; name: 'Prime'; code: 8243),
(char: '‹'; name: 'lsaquo'; code: 8249; od: true),
(char: '›'; name: 'rsaquo'; code: 8250; od: true),
(char: #8254; name: 'oline'; code: 8254),
(char: '/'; name: 'frasl'; code: 8260; od: true),
(char: '€'; name: 'euro'; code: 8364; od: true),
(char: #8465; name: 'image'; code: 8465),
(char: #8472; name: 'weierp'; code: 8472),
(char: #8476; name: 'real'; code: 8476),
(char: '™'; name: 'trade'; code: 8482; od: true),
(char: #8501; name: 'alefsym'; code: 8501),
(char: #8592; name: 'larr'; code: 8592),
(char: #8593; name: 'uarr'; code: 8593),
(char: #8594; name: 'rarr'; code: 8594),
(char: #8595; name: 'darr'; code: 8595),
(char: #8596; name: 'harr'; code: 8596),
(char: #8629; name: 'crarr'; code: 8629),
(char: #8656; name: 'lArr'; code: 8656),
(char: #8657; name: 'uArr'; code: 8657),
(char: #8658; name: 'rArr'; code: 8658),
(char: #8659; name: 'dArr'; code: 8659),
(char: #8660; name: 'hArr'; code: 8660),
(char: #8704; name: 'forall'; code: 8704),
(char: #8706; name: 'part'; code: 8706),
(char: #8707; name: 'exist'; code: 8707),
(char: 'Ø'; name: 'empty'; code: 8709; od: true),
(char: #8711; name: 'nabla'; code: 8711),
(char: #8712; name: 'isin'; code: 8712),
(char: #8713; name: 'notin'; code: 8713),
(char: #8715; name: 'ni'; code: 8715),
(char: #8719; name: 'prod'; code: 8719),
(char: #8721; name: 'sum'; code: 8721),
(char: '-'; name: 'minus'; code: 8722; od: true),
(char: '*'; name: 'lowast'; code: 8727; od: true),
(char: #8730; name: 'radic'; code: 8730),
(char: #8733; name: 'prop'; code: 8733),
(char: #8734; name: 'infin'; code: 8734),
(char: #8736; name: 'ang'; code: 8736),
(char: #8743; name: 'and'; code: 8743),
(char: #8744; name: 'or'; code: 8744),
(char: #8745; name: 'cap'; code: 8745),
(char: #8746; name: 'cup'; code: 8746),
(char: #8747; name: 'int'; code: 8747),
(char: #8756; name: 'there4'; code: 8756),
(char: '~'; name: 'sim'; code: 8764; od: true),
(char: #8773; name: 'cong'; code: 8773),
(char: #8776; name: 'asymp'; code: 8776),
(char: #8800; name: 'ne'; code: 8800),
(char: #8801; name: 'equiv'; code: 8801),
(char: #8804; name: 'le'; code: 8804),
(char: #8805; name: 'ge'; code: 8805),
(char: #8834; name: 'sub'; code: 8834),
(char: #8835; name: 'sup'; code: 8835),
(char: #8836; name: 'nsub'; code: 8836),
(char: #8838; name: 'sube'; code: 8838),
(char: #8853; name: 'oplus'; code: 8853),
(char: #8855; name: 'otimes'; code: 8855),
(char: #8869; name: 'perp'; code: 8869),
(char: '·'; name: 'sdot'; code: 8901; od: true),
(char: #8968; name: 'lceil'; code: 8968),
(char: #8969; name: 'rceil'; code: 8969),
(char: #8970; name: 'lfloor'; code: 8970),
(char: #8971; name: 'rfloor'; code: 8971),
(char: #9001; name: 'lang'; code: 9001),
(char: #9002; name: 'rang'; code: 9002),
(char: #9674; name: 'loz'; code: 9674),
(char: #9824; name: 'spades'; code: 9824),
(char: #9827; name: 'clubs'; code: 9827),
(char: #9829; name: 'hearts'; code: 9829),
(char: #9830; name: 'diams'; code: 9830)
);
function HTML_Entity_Decode(const s: string): string;
var
d:THTMLEntities;
begin
d := THTMLEntities.Create;
result := d.Decode(s);
d.Free;
end;
function HTML_Entity_Encode(const s: string): string;
var
d:THTMLEntities;
begin
d := THTMLEntities.Create;
result := d.Encode(s);
d.Free;
end;
function THTMLEntities.EntityAllowed(const e:THTMLEntity): boolean;
begin
{$IFDEF UNICODE}
// always replace when unicode Delphi
result := true;
{$ELSE}
result := false;
// only replace if character plays well with non-unicode Delphi
if e.code <= 255 then
result := true;
if e.od = true then
result := true;
{$ENDIF}
end;
function THTMLEntities.CanEncodeEntity(const e:THTMLEntity): boolean;
begin
result := true;
if EntityAllowed(e) = false then
result := false;
case e.code of
160 : result := false; // do not encode nbsp
end;
end;
function THTMLEntities.Encode(const s:string):string;
var
i: integer;
begin
result := replacestr(s, '&', '&');
// The symbolic entity ' was originally not included in the HTML spec and
// might therefore not be supported by all browsers, so use '
result := replacestr(result, '''', ''');
for i := Low(THTMLEntityMap) to High(THTMLEntityMap) do
if CanEncodeEntity(THTMLEntityMap[I]) then
result := ReplaceStr(result, THTMLEntityMap[I].char, '&'+THTMLEntityMap[I].name+';');
end;
function THTMLEntities.Decode(const s:string):string;
var
i: integer;
begin
result := s;
// converts named entities ", ©, etc
for i := Low(THTMLEntityMap) to High(THTMLEntityMap) do begin
if EntityAllowed(THTMLEntityMap[I]) then
result := ReplaceStr(result, '&'+THTMLEntityMap[I].name+';', THTMLEntityMap[I].char);
end;
// converts &#nnnn; and &#xhhhh; (if any)
if pos('&#', result) <> 0 then begin
// converts an unicode code point like ' or ' to decimal like '
if pos('&#x', lowercase(result)) <> 0 then
result := RegExpReplace(result, reUnicodeSymbol, HextoDec);
// remove leading zeros (if any) from decimal code (eg ')
if pos('�', result) <> 0 then
result := RegExpReplace(result, reDecimalSymbol, RemoveLeadingZeros);
// converts the decimal code points to their corresponding characters
for i := 0 to 255 do
result := ReplaceStr(result, '&#'+ IntToStr(i)+';', chr(i));
for i := Low(THTMLEntityMap) to High(THTMLEntityMap) do begin
if EntityAllowed(THTMLEntityMap[I]) then
result := ReplaceStr(result, '&#'+IntToStr(THTMLEntityMap[I].code)+';', THTMLEntityMap[I].char);
end;
end;
// handles entities not covered by the above entity map (if any)
if pos('&#', result) <> 0 then
result := RegExpReplace(result, reDecimalSymbol, DecodeEntity);
// finally, converts the amp
result := replacestr(result, '&', '&');
result := replacestr(result, '&', '&');
end;
function THTMLEntities.HextoDec(ARegExpr : TCatRegExpr): string;
var
code:string;
begin
code := StripChars(aregexpr.Match[0], ['&','#','x','X',';']);
result := '&#'+InttoStr(HexToInt(code))+';';
end;
function THTMLEntities.DecodeEntity(ARegExpr : TCatRegExpr): string;
var
match:string;
begin
match := aregexpr.Match[0];
{$IFDEF UNICODE}
{$IFDEF DXE7_OR_UP}
result := TNetEncoding.HTML.Decode(match);
{$ELSE}
result := HtmlDecode(match);
{$ENDIF}
{$ELSE}
// HtmlDecode() is not reliable with non-unicode Delphi, so return untouched
result := match;
{$ENDIF}
end;
function THTMLEntities.RemoveLeadingZeros(ARegExpr : TCatRegExpr): string;
var
match, code:string;
begin
match := aregexpr.Match[0];
if pos('�', match)<>0 then begin
code := StripChars(match, ['&','#',';']);
result := '&#'+InttoStr(StrToInt(code))+';';
end else
result := match;
end;
constructor THTMLEntities.Create;
begin
//
end;
destructor THTMLEntities.Destroy;
begin
inherited;
end;
// ------------------------------------------------------------------------//
end.
|
unit UContadorVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UPessoasVO, UCondominioVO;
type
[TEntity]
[TTable('Contador')]
TContadorVO = class(TGenericVO)
private
FidContador : Integer;
FidCondominio : Integer;
FidPessoa : Integer;
FCrc : String;
FOcupacao : String;
FdtEntrada : TDateTime;
FdtSaida : TDateTime;
FCertidaoReg : String;
FdtValidade : TDateTime;
Fnome : String;
public
PessoaVO : TPessoasVO;
CondominioVO : TCondominioVO;
[TId('idContador')]
[TGeneratedValue(sAuto)]
property idContador : Integer read FidContador write FidContador;
[TColumn('nome','Pessoa',250,[ldGrid], True, 'Pessoa', 'idPessoa', 'idPessoa')]
property Nome: string read FNome write FNome;
[TColumn('idCondominio','Condominio',0,[ldLookup,ldComboBox], False)]
property idCondominio: integer read FidCondominio write FidCondominio;
[TColumn('idPessoa','Pessoa',0,[ldLookup,ldComboBox], False)]
property idPessoa: integer read FidPessoa write FidPessoa;
[TColumn('Crc','CRC',100,[ldGrid,ldLookup,ldComboBox], False)]
property Crc: String read FCrc write FCrc;
[TColumn('Ocupacao','Ocupação',180,[ldGrid,ldLookup,ldComboBox], False)]
property Ocupacao: string read FOcupacao write FOcupacao;
[TColumn('dtEntrada','Data Entrada',20,[ldGrid, ldLookup,ldComboBox], False)]
property dtEntrada: TDateTime read FdtEntrada write FdtEntrada;
[TColumn('dtSaida','Data Saida',0,[ ldLookup,ldComboBox], False)]
property dtSaida: TDateTime read FdtSaida write FdtSaida;
[TColumn('certidaoReg','Certidão',100,[ldLookup,ldComboBox], False)]
property CertidaoReg: String read FCertidaoReg write FCertidaoReg;
[TColumn('dtValidade','Data Validade',0,[ldLookup,ldComboBox], False)]
property dtValidade: TDateTime read FdtValidade write FdtValidade;
procedure ValidarCamposObrigatorios;
end;
implementation
{ TContadorVO }
procedure TContadorVO.ValidarCamposObrigatorios;
begin
if (Self.FidPessoa = 0) then
begin
raise Exception.Create('O campo Pessoa é obrigatório!');
end;
if (Self.Crc = '') then
begin
raise Exception.Create('O campo CRC é obrigatório!');
end;
if (Self.dtEntrada= 0) then
begin
raise Exception.Create('O campo Data Entrada é obrigatório!');
end;
end;
end.
|
(**
This module contains common function for use throughout the application.
@Author David Hoyle
@Version 1.0
@Date 17 Feb 2018
**)
Unit JVTGFunctions;
Interface
Type
(** A record to describe the EXE version information. **)
TJVTGBuildInfo = Record
FMajor : Integer;
FMinor : Integer;
FRelease : Integer;
FBuild : Integer;
End;
Procedure GetBuildInfo(Var BuildInfo : TJVTGBuildInfo);
Implementation
Uses
WinAPI.Windows;
(**
This method updates the application caption to include the applications version number and build
information.
@precon None.
@postcon The applications caption is updated with version and build information.
@param BuildInfo as a TJVTGBuildInfo as a reference
**)
Procedure GetBuildInfo(Var BuildInfo : TJVTGBuildInfo);
Const
iWordMask = $FFFF;
iShift16 = 16;
Var
VerInfoSize: DWORD;
VerInfo: Pointer;
VerValueSize: DWORD;
VerValue: PVSFixedFileInfo;
Dummy: DWORD;
Begin
BuildInfo.FMajor := 0;
BuildInfo.FMinor := 0;
BuildInfo.FRelease := 0;
BuildInfo.FBuild := 0;
VerInfoSize := GetFileVersionInfoSize(PChar(ParamStr(0)), Dummy);
If VerInfoSize <> 0 Then
Begin
GetMem(VerInfo, VerInfoSize);
GetFileVersionInfo(PChar(ParamStr(0)), 0, VerInfoSize, VerInfo);
VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize);
BuildInfo.FMajor := VerValue^.dwFileVersionMS Shr iShift16;
BuildInfo.FMinor := VerValue^.dwFileVersionMS And iWordMask;
BuildInfo.FRelease := VerValue^.dwFileVersionLS Shr iShift16;
BuildInfo.FBuild := VerValue^.dwFileVersionLS And iWordMask;
FreeMem(VerInfo, VerInfoSize);
End;
End;
End.
|
unit main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, TeEngine, Series, StdCtrls, ExtCtrls, TeeProcs, Chart;
type
TForm1 = class(TForm)
AtomGroup: TRadioGroup;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
EditQuantumN: TEdit;
EditQuantumL: TEdit;
GroupBox2: TGroupBox;
cbWavefunction: TCheckBox;
cbProbability: TCheckBox;
ButtonVisualize: TButton;
Chart1: TChart;
MemoDebug: TMemo;
LabelDebug: TLabel;
Series1: TLineSeries;
Series2: TLineSeries;
CheckBox1: TCheckBox;
ScrollBar1: TScrollBar;
Label3: TLabel;
procedure ButtonVisualizeClick(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure ScrollBar1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
function GetZetta(): double;
function CekSign(A: double; B: double): double;
procedure DoMesh();
procedure InitPot();
procedure SolveSheq();
procedure PlotWaveFunction();
procedure PlotProbability();
procedure PlotPotential();
public
{ Public declarations }
end;
var
Form1: TForm1;
mesh, n, l: integer;
zeta, zmesh, rmax, xmin, dx, e: double;
r, akar, r2, y, vpot: array of double;
implementation
uses Math;
{$R *.dfm}
function TForm1.CekSign(A: double; B: double): double;
begin
if B > 0 then
CekSign := abs(A)
else
CekSign := -abs(A);
end;
function TForm1.GetZetta(): double;
var number: double;
begin
number := 0;
case AtomGroup.ItemIndex of
0: number := 1.000000;
1: number := 2.000000;
2: number := 1.259286;
3: number := 1.655890;
4: number := 1.562241;
5: number := 1.819850;
6: number := 2.067546;
7: number := 2.001328;
end;
GetZetta := number;
end;
procedure TForm1.ButtonVisualizeClick(Sender: TObject);
var i: integer;
begin
// init
zeta := GetZetta();
zmesh := zeta;
rmax := 100.0;
xmin := -8.0;
dx := 0.01;
mesh := trunc((ln(zmesh * rmax)-xmin) / dx);
n := StrToInt(EditQuantumN.Text);
l := StrToInt(EditQuantumL.Text);
SetLength(r, mesh+1);
SetLength(akar, mesh+1);
SetLength(r2, mesh+1);
SetLength(y, mesh+1);
SetLength(vpot, mesh+1);
// debug init
MemoDebug.Lines.Clear;
MemoDebug.Lines.Add('---------------------');
MemoDebug.Lines.Add(' Initialization ');
MemoDebug.Lines.Add('---------------------');
MemoDebug.Lines.Add('zmesh = ' + FloatToStr(zmesh));
MemoDebug.Lines.Add('rmax = ' + FloatToStr(rmax));
MemoDebug.Lines.Add('xmin = ' + FloatToStr(xmin));
MemoDebug.Lines.Add('dx = ' + FloatToStr(dx));
MemoDebug.Lines.Add('mesh = ' + IntToStr(mesh));
MemoDebug.Lines.Add('');
// calc
DoMesh;
InitPot;
SolveSheq;
// visualize
for i := 0 to Chart1.SeriesCount-1 do
Chart1.Series[i].Clear;
if cbWavefunction.Checked then
PlotWaveFunction;
//PlotPotential;
if cbProbability.Checked then
PlotProbability;
end;
procedure TForm1.DoMesh;
var
i: integer;
x: double;
begin
for i:=0 to mesh do
begin
x := xmin + dx * i;
r[i] := exp(x) / zmesh;
akar[i] := sqrt(r[i]);
r2[i] := r[i] * r[i];
//MemoDebug.Lines.Add('r[' + IntToStr(i) + '] = ' + FloatToStr(r[i]));
end;
end;
procedure TForm1.InitPot;
var
i: integer;
begin
for i:=0 to mesh do
begin
vpot[i] := -2 * zeta / r[i];
//MemoDebug.Lines.Add('vpot[' + IntToStr(i) + '] = ' + FloatToStr(vpot[i]));
end;
end;
procedure TForm1.SolveSheq;
var
i,j,kkk,maxiter,icl,nodes,ncross: integer;
ddx12, sqlhf, x2l2, ycusp, dfcusp, fac, norm, eup, elw, de, eps, tmp: double;
f: array of double;
begin
maxiter := 100;
eps := 1.0e-10;
icl := 0;
de := 0;
ncross := 0;
nodes := 0;
MemoDebug.Lines.Add('eps = ' + FloatToStr(eps));
SetLength(f, mesh+1);
ddx12 := (dx * dx) / 12.0;
sqlhf := sqr((l + 0.5));
x2l2 := 2 * l + 2;
eup := vpot[mesh];
elw := MaxDouble;
for i := 0 to mesh do
begin
tmp := sqlhf / r2[i] + vpot[i];
if(tmp < elw) then
elw := tmp;
end;
if(eup - elw < eps) then
begin
MemoDebug.Lines.Add('eup = ' + FloatToStr(eup));
MemoDebug.Lines.Add('elw = ' + FloatToStr(elw));
ShowMessage('solve_sheq: lower and upper bounds are equal');
exit;
end;
e := 0.5 * (elw + eup);
for kkk := 1 to maxiter do
begin
// set up the f-function and determine the position of its last
// change of sign
// f < 0 (approximately) means classically allowed region
// f > 0 " " " forbidden "
icl := -1;
f[0] := ddx12 * (sqlhf + r2[0] * (vpot[0]-e));
for i := 1 to mesh do
begin
f[i] := ddx12 * (sqlhf + r2[i] * (vpot[i]-e));
// beware: if f(i) is exactly zero the change of sign is not observed
// the following line is a trick to prevent missing a change of sign
// in this unlikely but not impossible case:
if(f[i] = 0.0) then f[i] := 1.0e-20;
if(f[i] <> CekSign(f[i], f[i-1])) then icl := i;
end;
if((icl < 0) or (icl >= mesh-2)) then
begin
// classical turning point not found or too far away
// no panic: it may follow from a bad choice of eup in
// the first iterations. Update e and eup and re-try
eup := e;
e := 0.5 * (eup+elw);
Continue;
end;
// f function as required by numerov method
for i := 0 to mesh do
begin
f[i] := 1.0 - f[i];
y[i] := 0;
end;
// determination of the wave-function in the first two points
// (asymptotic behaviour - second term depends upon the potential)
nodes := n - l - 1;
y[0] := Power(r[0], l+1) * (1.0 - 2.0*zeta*r[0]/x2l2) / akar[0];
y[1] := Power(r[1], l+1) * (1.0 - 2.0*zeta*r[1]/x2l2) / akar[1];
// outward integration, count number of crossings
ncross := 0;
for i:=1 to icl-1 do
begin
y[i+1] := ((12.0-10.0*f[i])*y[i]-f[i-1]*y[i-1])/f[i+1];
if(y[i] <> CekSign(y[i],y[i+1])) then ncross := ncross + 1;
end;
fac := y[icl];
// check number of crossing
if(ncross <> nodes) then
begin
if(ncross > nodes) then
eup := e
else
elw := e;
e := 0.5 * (eup + elw);
continue;
end;
// determination of the wave-function in the last two points
// assuming y(mesh+1) = 0 and y(mesh) = dx
y[mesh] := dx;
y[mesh-1] := (12.0-10.0*f[mesh])*y[mesh]/f[mesh-1];
// inward integration
for i := mesh-1 downto icl+1 do
begin
y[i-1] := ((12.0-10.0*f[i])*y[i]-f[i+1]*y[i+1])/f[i-1];
if (y[i-1] > 1.0e10) then
for j := mesh downto i-1 do
y[j] := y[j] / y[i-1];
end;
// rescale function to match at the classical turning point (icl)
//MemoDebug.Lines.Add('iter #'+IntToStr(kkk)+': ');
//MemoDebug.Lines.Add('n: '+IntToStr(n));
//MemoDebug.Lines.Add('l: '+IntToStr(l));
//MemoDebug.Lines.Add('fac: '+FloatToStr(fac));
//MemoDebug.Lines.Add('icl: '+IntToStr(icl));
//MemoDebug.Lines.Add('y[icl]: '+FloatToStr(y[icl]));
if(y[icl] <> 0) then
fac := fac / y[icl];
for i:=icl to mesh-1 do
y[i] := y[i] * fac;
// normalization
norm := 0;
for i := 0 to mesh-1 do
norm := norm + y[i]*y[i] * r2[i] * dx;
norm := sqrt(norm);
for i := 0 to mesh-1 do
y[i] := y[i] / norm;
// find the value of the cusp at the matching point (icl)
i := icl;
ycusp := (y[i-1]*f[i-1] + y[i+1]*f[i+1]+10.0*f[i]*y[i]) / 12.0;
dfcusp := f[i] * (y[i] / ycusp - 1.0);
// eigenvalue update using perturbation theory
de := dfcusp / ddx12 * ycusp * ycusp * dx;
if (de > 0.0) then elw := e;
if (de < 0.0) then eup := e;
// prevent e to go out of bounds, i.e. e > eup or e < elw
e := max(min(e+de,eup),elw);
// convergence check
if(abs(de) < eps) then break;
end;
// was convergence archieved?
if(abs(de) > 1.0e-10) then
begin
if(ncross <> nodes) then
begin
MemoDebug.Lines.Add('e = ' + FloatToStr(e));
MemoDebug.Lines.Add('elw = ' + FloatToStr(elw));
MemoDebug.Lines.Add('eup = ' + FloatToStr(eup));
MemoDebug.Lines.Add('ncross = ' + FloatToStr(ncross));
MemoDebug.Lines.Add('nodes = ' + FloatToStr(nodes));
MemoDebug.Lines.Add('icl = ' + FloatToStr(icl));
end
else
begin
MemoDebug.Lines.Add('e = ' + FloatToStr(e));
MemoDebug.Lines.Add('de = ' + FloatToStr(de));
end;
MemoDebug.Lines.Add('error in solve_sheq: too many iteration');
end
else
begin
MemoDebug.Lines.Add('Convergence achieved at iter #' + IntToStr(kkk) + ', de = ' + FloatToStr(de));
end;
MemoDebug.Lines.Add('');
end;
procedure TForm1.PlotWaveFunction;
var
i: integer;
begin
//MemoDebug.Lines.Add('------------------------');
//MemoDebug.Lines.Add(' Wavefunction data');
//MemoDebug.Lines.Add('------------------------');
for i:=0 to mesh-1 do
begin
Chart1.Series[0].AddXY(r[i], y[i]/akar[i]);
//MemoDebug.Lines.Add(IntToStr(i)+': '+FloatToStr(r[i])+','+FloatToStr(y[i]/akar[i]));
end;
end;
procedure TForm1.PlotProbability;
var
i: integer;
begin
//MemoDebug.Lines.Add('------------------------');
//MemoDebug.Lines.Add(' Probability data');
//MemoDebug.Lines.Add('------------------------');
for i:=0 to mesh-1 do
begin
Chart1.Series[1].AddXY(r[i], power(y[i]*akar[i],2));
//MemoDebug.Lines.Add(IntToStr(i)+': '+FloatToStr(r[i])+','+FloatToStr(power(y[i]*akar[i],2)));
end;
end;
procedure TForm1.PlotPotential;
var
i: integer;
begin
Chart1.Series[0].Clear;
MemoDebug.Lines.Add('------------------------');
MemoDebug.Lines.Add(' Potential data');
MemoDebug.Lines.Add('------------------------');
for i:=0 to mesh-1 do
begin
Chart1.Series[0].AddXY(r[i], vpot[i]);
//MemoDebug.Lines.Add(IntToStr(i)+': '+FloatToStr(r[i])+','+FloatToStr(vpot[i]));
end;
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
ScrollBar1.Enabled := not CheckBox1.Checked;
Chart1.BottomAxis.Automatic := CheckBox1.Checked;
if CheckBox1.Checked then
begin
Label3.Caption := '100';
ScrollBar1.Position := 100;
end;
end;
procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
if(ScrollBar1.Position > 0) then
begin
Label3.Caption := IntToStr(ScrollBar1.Position);
Chart1.BottomAxis.Maximum := ScrollBar1.Position;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ScrollBar1.Enabled := false;
end;
end.
|
unit TestPreimageAPIUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Generics.Collections,
// API
AIMPCustomPlugin, apiCore, apiWrappers, apiPlugin, apiPlaylists, apiObjects, apiMusicLibrary, apiThreading,
// VCL
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TfrmTestPreimage = class;
TTestPreimage = class;
{ TTestPreimageAPIPlugin }
TTestPreimageAPIPlugin = class(TAIMPCustomPlugin)
strict private
FForm: TfrmTestPreimage;
protected
function InfoGet(Index: Integer): PWideChar; override; stdcall;
function InfoGetCategories: Cardinal; override; stdcall;
function Initialize(Core: IAIMPCore): HRESULT; override; stdcall;
procedure Finalize; override; stdcall;
end;
{ ITestPreimageFactory }
ITestPreimageFactory = interface
['{5FF0D01D-A956-47AE-80DA-76E10DDEA1C1}']
procedure DataChanged;
end;
{ TTestPreimageFactory }
TTestPreimageFactory = class(TInterfacedObject,
ITestPreimageFactory,
IAIMPExtensionPlaylistPreimageFactory)
protected
FPreimages: TList<TTestPreimage>;
public
constructor Create;
destructor Destroy; override;
procedure DataChanged;
// IAIMPExtensionPlaylistPreimageFactory
function CreatePreimage(out Intf: IAIMPPlaylistPreimage): HRESULT; stdcall;
function GetID(out ID: IAIMPString): HRESULT; stdcall;
function GetName(out Name: IAIMPString): HRESULT; stdcall;
function GetFlags: DWORD; stdcall;
end;
{ TTestPreimage }
TTestPreimage = class(TAIMPPropertyList,
IAIMPPlaylistPreimageDataProvider,
IAIMPPlaylistPreimage)
strict private
FFactory: TTestPreimageFactory;
FManager: IAIMPPlaylistPreimageListener;
protected
procedure DoGetValueAsInt32(PropertyID: Integer; out Value: Integer; var Result: HRESULT); override;
function DoGetValueAsObject(PropertyID: Integer): IInterface; override;
public
constructor Create(AFactory: TTestPreimageFactory); virtual;
destructor Destroy; override;
procedure DataChanged;
// IAIMPPlaylistPreimage
procedure Finalize; stdcall;
procedure Initialize(Manager: IAIMPPlaylistPreimageListener); stdcall;
function ConfigLoad(Stream: IAIMPStream): HRESULT; stdcall;
function ConfigSave(Stream: IAIMPStream): HRESULT; stdcall;
function ExecuteDialog(OwnerWndHanle: HWND): HRESULT; stdcall;
// IAIMPPlaylistPreimageDataProvider
function GetFiles(Owner: IAIMPTaskOwner; out Flags: Cardinal; out List: IAIMPObjectList): HRESULT; stdcall;
end;
{ TfrmTestPreimage }
TfrmTestPreimage = class(TForm, IAIMPExtensionPlaylistManagerListener)
btnRelease: TButton;
btnReload: TButton;
btnSetCustom: TButton;
btnTestIO: TButton;
GroupBox1: TGroupBox;
lbPlaylists: TListBox;
lbPreimageInfo: TLabel;
Panel1: TPanel;
GroupBox2: TGroupBox;
btnDataChanged: TButton;
procedure btnDataChangedClick(Sender: TObject);
procedure btnReleaseClick(Sender: TObject);
procedure btnReloadClick(Sender: TObject);
procedure btnSetCustomClick(Sender: TObject);
procedure btnTestIOClick(Sender: TObject);
procedure lbPlaylistsClick(Sender: TObject);
strict private
FFactory: ITestPreimageFactory;
FService: IAIMPServicePlaylistManager2;
function GetSelectedPlaylist(out APlaylist: IAIMPPlaylist): Boolean;
function GetPlaylistPreimage(APlaylist: IAIMPPlaylist; out APreimage: IAIMPPlaylistPreimage): Boolean;
procedure SetPlaylistPreimage(APlaylist: IAIMPPlaylist; APreimage: IAIMPPlaylistPreimage);
// IAIMPExtensionPlaylistManagerListener
procedure PlaylistActivated(Playlist: IAIMPPlaylist); stdcall;
procedure PlaylistAdded(Playlist: IAIMPPlaylist); stdcall;
procedure PlaylistRemoved(Playlist: IAIMPPlaylist); stdcall;
public
constructor Create(AService: IAIMPServicePlaylistManager2); reintroduce;
destructor Destroy; override;
end;
implementation
uses
ShellAPI, ShlObj;
{$R *.dfm}
function ShellGetPathOfMyMusic: UnicodeString;
var
ABuf: array[0..MAX_PATH] of WideChar;
begin
if SHGetSpecialFolderPathW(0, @ABuf[0], CSIDL_MYMUSIC, False) then
Result := IncludeTrailingPathDelimiter(ABuf)
else
Result := '';
end;
{ TTestPreimageAPIPlugin }
procedure TTestPreimageAPIPlugin.Finalize;
begin
FreeAndNil(FForm);
inherited;
end;
function TTestPreimageAPIPlugin.InfoGet(Index: Integer): PWideChar;
begin
Result := PChar(ClassName);
end;
function TTestPreimageAPIPlugin.InfoGetCategories: Cardinal;
begin
Result := AIMP_PLUGIN_CATEGORY_ADDONS;
end;
function TTestPreimageAPIPlugin.Initialize(Core: IAIMPCore): HRESULT;
var
AService: IAIMPServicePlaylistManager2;
begin
Result := inherited Initialize(Core);
if Succeeded(Result) then
begin
if CoreGetService(IAIMPServicePlaylistManager2, AService) then
begin
FForm := TfrmTestPreimage.Create(AService);
FForm.Show;
end;
end;
end;
{ TTestPreimage }
constructor TTestPreimage.Create(AFactory: TTestPreimageFactory);
begin
inherited Create;
FFactory := AFactory;
FFactory.FPreimages.Add(Self);
end;
destructor TTestPreimage.Destroy;
begin
FFactory.FPreimages.Remove(Self);
FManager := nil;
inherited Destroy;
end;
procedure TTestPreimage.DataChanged;
begin
if FManager <> nil then
FManager.DataChanged;
end;
procedure TTestPreimage.Finalize;
begin
FManager := nil;
end;
procedure TTestPreimage.Initialize(Manager: IAIMPPlaylistPreimageListener);
begin
FManager := Manager;
end;
function TTestPreimage.ConfigLoad(Stream: IAIMPStream): HRESULT;
begin
Result := S_OK;
end;
function TTestPreimage.ConfigSave(Stream: IAIMPStream): HRESULT;
begin
Result := S_OK;
end;
function TTestPreimage.ExecuteDialog(OwnerWndHanle: HWND): HRESULT;
begin
MessageDlg('Yep!', mtInformation, [mbOK], 0);
Result := S_OK;
end;
procedure TTestPreimage.DoGetValueAsInt32(PropertyID: Integer; out Value: Integer; var Result: HRESULT);
begin
case PropertyID of
AIMP_PLAYLISTPREIMAGE_PROPID_HASDIALOG, AIMP_PLAYLISTPREIMAGE_PROPID_AUTOSYNC:
begin
Result := S_OK;
Value := 1;
end;
else
inherited DoGetValueAsInt32(PropertyID, Value, Result);
end;
end;
function TTestPreimage.DoGetValueAsObject(PropertyID: Integer): IInterface;
var
ID: IAIMPString;
begin
if PropertyID = AIMP_PLAYLISTPREIMAGE_PROPID_FACTORYID then
begin
if Succeeded(FFactory.GetID(ID)) then
Result := ID
else
Result := nil;
end
else
Result := inherited DoGetValueAsObject(PropertyID);
end;
function TTestPreimage.GetFiles(Owner: IAIMPTaskOwner; out Flags: Cardinal; out List: IAIMPObjectList): HRESULT;
begin
Flags := 0; // Combination of AIMP_PLAYLIST_ADD_FLAGS_XXX
CoreCreateObject(IAIMPObjectList, List);
CheckResult(List.Add(MakeString(ShellGetPathOfMyMusic)));
Result := S_OK;
end;
{ TTestPreimageFactory }
constructor TTestPreimageFactory.Create;
begin
inherited Create;
FPreimages := TList<TTestPreimage>.Create;
end;
destructor TTestPreimageFactory.Destroy;
begin
FreeAndNil(FPreimages);
inherited Destroy;
end;
procedure TTestPreimageFactory.DataChanged;
var
I: Integer;
begin
for I := FPreimages.Count - 1 downto 0 do
FPreimages[I].DataChanged;
end;
function TTestPreimageFactory.CreatePreimage(out Intf: IAIMPPlaylistPreimage): HRESULT;
begin
Intf := TTestPreimage.Create(Self);
Result := S_OK;
end;
function TTestPreimageFactory.GetID(out ID: IAIMPString): HRESULT;
begin
ID := MakeString(ClassName);
Result := S_OK;
end;
function TTestPreimageFactory.GetName(out Name: IAIMPString): HRESULT;
begin
Name := MakeString('Test Preimage');
Result := S_OK;
end;
function TTestPreimageFactory.GetFlags: DWORD;
begin
Result := 0;
end;
{ TfrmTestPreimage }
constructor TfrmTestPreimage.Create(AService: IAIMPServicePlaylistManager2);
var
AIntf: IAIMPPlaylist;
I: Integer;
begin
inherited Create(nil);
FService := AService;
FFactory := TTestPreimageFactory.Create;
CoreIntf.RegisterExtension(IAIMPServicePlaylistManager, Self);
CoreIntf.RegisterExtension(IAIMPServicePlaylistManager, FFactory);
for I := 0 to AService.GetLoadedPlaylistCount - 1 do
begin
if Succeeded(AService.GetLoadedPlaylist(I, AIntf)) then
PlaylistAdded(AIntf);
end;
end;
destructor TfrmTestPreimage.Destroy;
begin
CoreIntf.UnregisterExtension(FFactory);
CoreIntf.UnregisterExtension(Self);
FFactory := nil;
FService := nil;
inherited Destroy;
end;
function TfrmTestPreimage.GetSelectedPlaylist(out APlaylist: IAIMPPlaylist): Boolean;
begin
Result := (lbPlaylists.ItemIndex >= 0) and Succeeded(
FService.GetLoadedPlaylistByID(MakeString(lbPlaylists.Items.Names[lbPlaylists.ItemIndex]), APlaylist))
end;
function TfrmTestPreimage.GetPlaylistPreimage(APlaylist: IAIMPPlaylist; out APreimage: IAIMPPlaylistPreimage): Boolean;
begin
Result := Succeeded((APlaylist as IAIMPPropertyList).GetValueAsObject(
AIMP_PLAYLIST_PROPID_PREIMAGE, IAIMPPlaylistPreimage, APreimage));
end;
procedure TfrmTestPreimage.PlaylistActivated(Playlist: IAIMPPlaylist);
begin
// do nothing
end;
procedure TfrmTestPreimage.PlaylistAdded(Playlist: IAIMPPlaylist);
begin
lbPlaylists.Items.Add(
PropListGetStr(Playlist as IAIMPPropertyList, AIMP_PLAYLIST_PROPID_ID) + lbPlaylists.Items.NameValueSeparator +
PropListGetStr(Playlist as IAIMPPropertyList, AIMP_PLAYLIST_PROPID_NAME));
end;
procedure TfrmTestPreimage.PlaylistRemoved(Playlist: IAIMPPlaylist);
var
AIndex: Integer;
begin
AIndex := lbPlaylists.Items.IndexOfName(PropListGetStr(Playlist as IAIMPPropertyList, AIMP_PLAYLIST_PROPID_ID));
if AIndex >= 0 then
lbPlaylists.Items.Delete(AIndex);
end;
procedure TfrmTestPreimage.SetPlaylistPreimage(APlaylist: IAIMPPlaylist; APreimage: IAIMPPlaylistPreimage);
begin
(APlaylist as IAIMPPropertyList).SetValueAsObject(AIMP_PLAYLIST_PROPID_PREIMAGE, APreimage);
end;
procedure TfrmTestPreimage.btnDataChangedClick(Sender: TObject);
begin
FFactory.DataChanged;
end;
procedure TfrmTestPreimage.btnReleaseClick(Sender: TObject);
var
APlaylist: IAIMPPlaylist;
begin
if GetSelectedPlaylist(APlaylist) then
SetPlaylistPreimage(APlaylist, nil);
end;
procedure TfrmTestPreimage.btnReloadClick(Sender: TObject);
var
APlaylist: IAIMPPlaylist;
APreimage: IAIMPPlaylistPreimage;
begin
if GetSelectedPlaylist(APlaylist) then
begin
{$REGION 'Test putting yourself'}
if GetPlaylistPreimage(APlaylist, APreimage) then
SetPlaylistPreimage(APlaylist, APreimage);
{$ENDREGION}
APlaylist.ReloadFromPreimage;
end;
end;
procedure TfrmTestPreimage.btnSetCustomClick(Sender: TObject);
var
AFactory: IAIMPExtensionPlaylistPreimageFactory;
APlaylist: IAIMPPlaylist;
APreimage: IAIMPPlaylistPreimage;
APreimageFolders: IAIMPPlaylistPreimageFolders;
begin
if GetSelectedPlaylist(APlaylist) then
begin
CheckResult(FService.GetPreimageFactoryByID(MakeString(AIMP_PREIMAGEFACTORY_FOLDERS_ID), AFactory));
CheckResult(AFactory.CreatePreimage(APreimage));
APreimageFolders := APreimage as IAIMPPlaylistPreimageFolders;
APreimageFolders.SetValueAsInt32(AIMP_PLAYLISTPREIMAGE_PROPID_AUTOSYNC, 1);
APreimageFolders.ItemsAdd(MakeString(ShellGetPathOfMyMusic), True);
SetPlaylistPreimage(APlaylist, APreimageFolders);
end;
end;
procedure TfrmTestPreimage.btnTestIOClick(Sender: TObject);
var
APlaylist: IAIMPPlaylist;
APlaylistPreimage: IAIMPPlaylistPreimage;
AStream: IAIMPMemoryStream;
begin
if GetSelectedPlaylist(APlaylist) and GetPlaylistPreimage(APlaylist, APlaylistPreimage) then
begin
CoreCreateObject(IAIMPMemoryStream, AStream);
CheckResult(APlaylistPreimage.ConfigSave(AStream));
CheckResult(APlaylistPreimage.Reset);
CheckResult(AStream.Seek(0, AIMP_STREAM_SEEKMODE_FROM_BEGINNING));
CheckResult(APlaylistPreimage.ConfigLoad(AStream));
end;
end;
procedure TfrmTestPreimage.lbPlaylistsClick(Sender: TObject);
var
APlaylist: IAIMPPlaylist;
APlaylistPreimage: IAIMPPlaylistPreimage;
APlaylistPreimageType: string;
begin
if GetSelectedPlaylist(APlaylist) and GetPlaylistPreimage(APlaylist, APlaylistPreimage) then
begin
APlaylistPreimageType := PropListGetStr(APlaylistPreimage, AIMP_PLAYLISTPREIMAGE_PROPID_FACTORYID);
{$REGION 'Test the interface extensions'}
if Supports(APlaylistPreimage, IAIMPPlaylistPreimageFolders) then
APlaylistPreimageType := APlaylistPreimageType + '(Folders)';
if Supports(APlaylistPreimage, IAIMPMLPlaylistPreimage) then
APlaylistPreimageType := APlaylistPreimageType + '(Music Library)';
{$ENDREGION}
lbPreimageInfo.Caption := Format('Preimage: %s [%x]', [APlaylistPreimageType, NativeUInt(APlaylistPreimage)]);
end
else
lbPreimageInfo.Caption := 'Playlist has no preimage';
end;
end.
|
Unit UnitMudarIcone;
interface
uses
Windows;
function MudarIcone(FileName, IconFile: string): boolean;
implementation
uses
Sysutils,
Classes,
ShellApi,
MadRes,
IconChanger;
function SaveApplicationIconGroup(icofile: PChar; exefile: PChar): Boolean;
function EnumResourceNamesProc(Module: HMODULE; ResType: PChar; ResName:
PChar; lParam: TStringList): Integer; stdcall;
var
ResourceName: string;
begin
if hiword(Cardinal(ResName)) = 0 then
begin
ResourceName := IntToStr(loword(Cardinal(ResName)));
end
else
begin
ResourceName := ResName;
end;
lParam.Add(ResourceName);
Result := 1;
end;
function ExtractIconFromFile(ResFileName: string; IcoFileName: string; nIndex:
string): Boolean;
type
PMEMICONDIRENTRY = ^TMEMICONDIRENTRY;
TMEMICONDIRENTRY = packed record
bWidth: Byte;
bHeight: Byte;
bColorCount: Byte;
bReserved: Byte;
wPlanes: Word;
wBitCount: Word;
dwBytesInRes: DWORD;
nID: Word;
end;
type
PMEMICONDIR = ^TMEMICONDIR;
TMEMICONDIR = packed record
idReserved: Word;
idType: Word;
idCount: Word;
idEntries: array[0..15] of TMEMICONDIRENTRY;
end;
type
PICONDIRENTRY = ^TICONDIRENTRY;
TICONDIRENTRY = packed record
bWidth: Byte;
bHeight: Byte;
bColorCount: Byte;
bReserved: Byte;
wPlanes: Word;
wBitCount: Word;
dwBytesInRes: DWORD;
dwImageOffset: DWORD;
end;
type
PICONIMAGE = ^TICONIMAGE;
TICONIMAGE = packed record
Width,
Height,
Colors: UINT;
lpBits: Pointer;
dwNumBytes: DWORD;
pBmpInfo: PBitmapInfo;
end;
type
PICONRESOURCE = ^TICONRESOURCE;
TICONRESOURCE = packed record
nNumImages: UINT;
IconImages: array[0..15] of TICONIMAGE;
end;
function AdjustIconImagePointers(lpImage: PICONIMAGE): Bool;
begin
if lpImage = nil then
begin
Result := False;
exit;
end;
lpImage.pBmpInfo := PBitMapInfo(lpImage^.lpBits);
lpImage.Width := lpImage^.pBmpInfo^.bmiHeader.biWidth;
lpImage.Height := (lpImage^.pBmpInfo^.bmiHeader.biHeight) div 2;
lpImage.Colors := lpImage^.pBmpInfo^.bmiHeader.biPlanes *
lpImage^.pBmpInfo^.bmiHeader.biBitCount;
Result := true;
end;
function WriteICOHeader(hFile: THandle; nNumEntries: UINT): Boolean;
type
TFIcoHeader = record
wReserved: WORD;
wType: WORD;
wNumEntries: WORD;
end;
var
IcoHeader: TFIcoHeader;
dwBytesWritten: DWORD;
begin
Result := False;
IcoHeader.wReserved := 0;
IcoHeader.wType := 1;
IcoHeader.wNumEntries := WORD(nNumEntries);
if not windows.WriteFile(hFile, IcoHeader, SizeOf(IcoHeader), dwBytesWritten, nil)
then
begin
MessageBox(0, pchar(SysErrorMessage(GetLastError)), 'Error',
MB_ICONERROR);
Result := False;
Exit;
end;
if dwBytesWritten <> SizeOf(IcoHeader) then
Exit;
Result := True;
end;
function CalculateImageOffset(lpIR: PICONRESOURCE; nIndex: UINT): DWORD;
var
dwSize: DWORD;
i: Integer;
begin
dwSize := 3 * SizeOf(WORD);
inc(dwSize, lpIR.nNumImages * SizeOf(TICONDIRENTRY));
for i := 0 to nIndex - 1 do
inc(dwSize, lpIR.IconImages[i].dwNumBytes);
Result := dwSize;
end;
function WriteIconResourceToFile(hFile: hwnd; lpIR: PICONRESOURCE): Boolean;
var
i: UINT;
dwBytesWritten: DWORD;
ide: TICONDIRENTRY;
dwTemp: DWORD;
begin
Result := False;
for i := 0 to lpIR^.nNumImages - 1 do
begin
/// Convert internal format to ICONDIRENTRY
ide.bWidth := lpIR^.IconImages[i].Width;
ide.bHeight := lpIR^.IconImages[i].Height;
ide.bReserved := 0;
ide.wPlanes := lpIR^.IconImages[i].pBmpInfo.bmiHeader.biPlanes;
ide.wBitCount := lpIR^.IconImages[i].pBmpInfo.bmiHeader.biBitCount;
if ide.wPlanes * ide.wBitCount >= 8 then
ide.bColorCount := 0
else
ide.bColorCount := 1 shl (ide.wPlanes * ide.wBitCount);
ide.dwBytesInRes := lpIR^.IconImages[i].dwNumBytes;
ide.dwImageOffset := CalculateImageOffset(lpIR, i);
if not windows.WriteFile(hFile, ide, sizeof(TICONDIRENTRY), dwBytesWritten, nil)
then
Exit;
if dwBytesWritten <> sizeof(TICONDIRENTRY) then
Exit;
end;
for i := 0 to lpIR^.nNumImages - 1 do
begin
dwTemp := lpIR^.IconImages[i].pBmpInfo^.bmiHeader.biSizeImage;
lpIR^.IconImages[i].pBmpInfo^.bmiHeader.biSizeImage := 0;
if not windows.WriteFile(hFile, lpIR^.IconImages[i].lpBits^,
lpIR^.IconImages[i].dwNumBytes, dwBytesWritten, nil) then
Exit;
if dwBytesWritten <> lpIR^.IconImages[i].dwNumBytes then
Exit;
lpIR^.IconImages[i].pBmpInfo^.bmiHeader.biSizeImage := dwTemp;
end;
Result := True;
end;
var
h: HMODULE;
lpMemIcon: PMEMICONDIR;
lpIR: TICONRESOURCE;
src: HRSRC;
Global: HGLOBAL;
i: integer;
hFile: hwnd;
begin
Result := False;
hFile := CreateFile(pchar(IcoFileName), GENERIC_WRITE, 0, nil,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if hFile = INVALID_HANDLE_VALUE then
Exit;
h := LoadLibraryEx(pchar(ResFileName), 0, LOAD_LIBRARY_AS_DATAFILE);
if h = 0 then
exit;
try
src := FindResource(h, pchar(nIndex), RT_GROUP_ICON);
if src = 0 then
Src := FindResource(h, Pointer(StrToInt(nIndex)), RT_GROUP_ICON);
if src <> 0 then
begin
Global := windows.LoadResource(h, src);
if Global <> 0 then
begin
lpMemIcon := windows.LockResource(Global);
if Global <> 0 then
begin
try
lpIR.nNumImages := lpMemIcon.idCount;
// Write the header
for i := 0 to lpMemIcon^.idCount - 1 do
begin
src := FindResource(h,
MakeIntResource(lpMemIcon^.idEntries[i].nID), RT_ICON);
if src <> 0 then
begin
Global := windows.LoadResource(h, src);
if Global <> 0 then
begin
try
lpIR.IconImages[i].dwNumBytes := windows.SizeofResource(h, src);
except
MessageBox(0, PChar('Unable to Read Icon'), 'NTPacker',
MB_ICONERROR);
Result := False;
ExitProcess(0);
end;
GetMem(lpIR.IconImages[i].lpBits,
lpIR.IconImages[i].dwNumBytes);
windows.CopyMemory(lpIR.IconImages[i].lpBits, windows.LockResource(Global),
lpIR.IconImages[i].dwNumBytes);
if not AdjustIconImagePointers(@(lpIR.IconImages[i])) then
exit;
end;
end;
end;
if WriteICOHeader(hFile, lpIR.nNumImages) then
if WriteIconResourceToFile(hFile, @lpIR) then
Result := True;
finally
for i := 0 to lpIR.nNumImages - 1 do
if assigned(lpIR.IconImages[i].lpBits) then
FreeMem(lpIR.IconImages[i].lpBits);
end;
end;
end;
end;
finally
FreeLibrary(h);
end;
windows.CloseHandle(hFile);
end;
var
hExe: THandle;
i: Integer;
SL: TStringList;
begin
Result := False;
SL := TStringList.Create;
hExe := LoadLibraryEx(PChar(exefile), 0, LOAD_LIBRARY_AS_DATAFILE);
if hExe = 0 then
Exit;
EnumResourceNames(hExe, RT_GROUP_ICON, @EnumResourceNamesProc, Integer(SL));
if SL.Count = 0 then
begin
SL.Free;
//MessageBox(0, 'No Icons found in the EXE/DLL', 'Error', MB_ICONERROR);
Exit;
end;
ExtractIconFromFile(exefile, icofile, SL.Strings[0]);
FreeLibrary(hExe);
SL.Free;
Result := True;
end;
// Aqui foi usado a Unit "MadRes"
function UpdateExeIcon(exeFile, iconGroup, icoFile: string) : boolean;
//Copy-Pasted from Madshi's forums by Wack-a-Mole. [October/25/2006]
var resUpdateHandle : dword;
begin
resUpdateHandle := BeginUpdateResourceW(PWideChar(wideString(exeFile)), false);
if resUpdateHandle <> 0 then
begin
result := LoadIconGroupResourceW(resUpdateHandle, PWideChar(wideString(iconGroup)), 0, PWideChar(wideString(icoFile)));
result := EndUpdateResourceW(resUpdateHandle, false) and result;
end
else
result := false;
end;
function MyGetTemp(nBufferLength: DWORD; lpBuffer: PChar): DWORD;
var
xGetTemp: function(nBufferLength: DWORD; lpBuffer: PChar): DWORD; stdcall;
begin
xGetTemp := GetProcAddress(LoadLibrary(pchar('kernel32.dll')), pchar('GetTempPathA'));
Result := xGetTemp(nBufferLength, lpBuffer);
end;
function MyTempFolder: String;
var
lpBuffer: Array[0..MAX_PATH] of Char;
begin
MyGetTemp(sizeof(lpBuffer), lpBuffer);
Result := String(lpBuffer);
end;
function MudarIcone(FileName, IconFile: string): boolean;
var
TempIco: string;
begin
Result := true;
TempIco := MyTempFolder + inttostr(gettickcount) + '.ico';
if lowercase(extractfileext(IconFile)) = '.ico' then
begin
if UpdateExeIcon(pchar(FileName), 'MAINICON', pchar(IconFile)) = false then Result := false;
if UpdateExeIcon(pchar(FileName), 'ICON_STANDARD', pchar(IconFile)) = false then Result := false;
//if UpdateApplicationIcon(pchar(IconFile), pchar(FileName)) = false then Result := false;
end else
if lowercase(extractfileext(IconFile)) = '.exe' then
begin
try
if SaveApplicationIconGroup(pchar(TempIco), pchar(IconFile)) = false then Result := false;
(*******************************************************
Quando vocÍ abre o stub no ResourceHacker aparece o nome
do "icon group" que ť MAINICON
*******************************************************)
if UpdateExeIcon(pchar(FileName), 'MAINICON', pchar(TempIco)) = false then Result := false;
if UpdateExeIcon(pchar(FileName), 'ICON_STANDARD', pchar(TempIco)) = false then Result := false;
except
end;
if fileexists(pchar(TempIco)) then deletefile(pchar(TempIco));
end else Result := false;
end;
end. |
namespace WinFormsApplication;
//Sample WinForms application
//by Brian Long, 2009
//A re-working of a GTK# example program, based on treeview example in the Gtk#
//docs (http://www.go-mono.com/docs/) on the Mono site http://tinyurl.com/Gtk-TreeView
//{$define TEST_MODE} //Test mode causes quicker startup, skipping the majority of the methods, types & assemblies
interface
uses
System.Threading,
System.Windows.Forms,
System.Reflection;
type
Program = assembly static class
private
mainForm: MainForm;
updateDialog: UpdateDialog;
class method ProcessAssembly(parent: TreeNode; asm: &Assembly);
class method ProcessType(parent: TreeNode; t: &Type);
class method UpdateProgress(format: String; params args: Array of object);
class method OnThreadException(sender: Object; e: ThreadExceptionEventArgs);
public
class method Main;
class method AddAssembly(FileName: String);
end;
implementation
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
class method Program.Main;
begin
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += OnThreadException;
mainForm := new MainForm;
//Populate the treeview
for each asm: &Assembly in AppDomain.CurrentDomain.GetAssemblies() do
begin
var asmName: String := asm.GetName().Name;
UpdateProgress('Loading {0}', asmName);
ProcessAssembly(mainForm.GetTreeViewNodes.Add(asmName), asm);
{$ifdef TEST_MODE}
Break;
{$endif}
end;
updateDialog.Hide();
updateDialog := nil;
Application.Run(mainForm);
end;
class method Program.ProcessAssembly(parent: TreeNode; asm: &Assembly);
begin
var asmName: String := asm.GetName().Name;
for each t: &Type in asm.GetTypes() do
begin
UpdateProgress('Loading from {0}:'#10'{1}', asmName, t.ToString());
ProcessType(parent.Nodes.Add(t.ToString()), t);
end;
end;
class method Program.ProcessType(parent: TreeNode; t: &Type);
begin
for each mi: MemberInfo in t.GetMembers() do
parent.Nodes.Add(mi.ToString())
end;
class method Program.UpdateProgress(format: String; params args: Array of object);
begin
var Text := string.Format(format, args);
if updateDialog = nil then
begin
//First run through needs a new dialog set up and launched
updateDialog := new UpdateDialog();
updateDialog.UpdateDialogLabelText(Text);
updateDialog.Show();
end
else
begin
//Update dialog text and process pending events to look responsive
updateDialog.UpdateDialogLabelText(Text);
Application.DoEvents();
end;
end;
/// <summary>
/// Default exception handler
/// </summary>
class method Program.OnThreadException(sender: Object; e: ThreadExceptionEventArgs);
begin
MessageBox.Show(e.Exception.Message);
end;
class method Program.AddAssembly(FileName: String);
begin
var asm: &Assembly := &Assembly.LoadFrom(FileName);
var asmName: String := asm.GetName().Name;
//Run the update cycle to add to treeview
UpdateProgress('Loading {0}', asmName);
ProcessAssembly(mainForm.GetTreeViewNodes.Add(asmName), asm);
updateDialog.Hide();
updateDialog := nil;
end;
end.
|
unit TpSelect;
interface
uses
Windows, SysUtils, Classes, Controls, Graphics,
Types,
ThWebControl, ThTag, ThSelect,
TpControls;
type
TTpSelect = class(TThSelect)
private
FListSource: TComponent;
FOnSubmit: TTpEvent;
FOnGenerate: TTpEvent;
protected
procedure SetListSource(const Value: TComponent);
protected
procedure SourceRemoved; override;
procedure Tag(inTag: TThTag); override;
published
property ListSource: TComponent read FListSource write SetListSource;
property OnSubmit: TTpEvent read FOnSubmit write FOnSubmit;
property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate;
end;
//
TTpListBox = class(TThListBox)
private
FListSource: TComponent;
FOnSubmit: TTpEvent;
FOnGenerate: TTpEvent;
protected
procedure SetListSource(const Value: TComponent);
protected
procedure SourceRemoved; override;
procedure Tag(inTag: TThTag); override;
published
property ListSource: TComponent read FListSource write SetListSource;
property OnSubmit: TTpEvent read FOnSubmit write FOnSubmit;
property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate;
end;
implementation
uses
ThVclUtils, ThListSource;
{ TTpSelect }
procedure TTpSelect.SetListSource(const Value: TComponent);
begin
FListSource := Value;
if (FListSource = nil) or (not ThIsAs(Value, IThListSource, FSource)) then
begin
FListSource := nil;
FSource := nil;
end;
UpdateItems;
end;
procedure TTpSelect.SourceRemoved;
begin
FListSource := nil;
inherited;
end;
procedure TTpSelect.Tag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Add(tpClass, 'TTpSelect');
Add('tpName', Name);
if (Source <> nil) then
Add('tpSource', Source.Name);
Add('tpOnSubmit', OnSubmit);
Add('tpOnGenerate', OnGenerate);
end;
end;
{ TTpListBox }
procedure TTpListBox.SetListSource(const Value: TComponent);
begin
FListSource := Value;
if (FListSource = nil) or (not ThIsAs(Value, IThListSource, FSource)) then
begin
FListSource := nil;
FSource := nil;
end;
UpdateItems;
end;
procedure TTpListBox.SourceRemoved;
begin
FListSource := nil;
inherited;
end;
procedure TTpListBox.Tag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Add(tpClass, 'TTpSelect');
Add('tpName', Name);
if (Source <> nil) then
Add('tpSource', Source.Name);
Add('tpOnSubmit', OnSubmit);
Add('tpOnGenerate', OnGenerate);
end;
end;
end.
|
unit uniteServeur;
interface
uses
SysUtils,
uniteConsigneur,
uniteConnexionHTTPServeur,
uniteProtocole,
uniteRequete,
uniteReponse;
type
//Un serveur HTTP minimaliste, supportant la méthode GET du protocole HTTP 1.1 uniquement.
Serveur = class
private
// Le chemin par lequel les requêtes sont envoyées au serveur
// et les réponses sont retournées au client
laConnexion : ConnexionHTTPServeur;
// Le protocole HTTP par lequel les requêtes sont traitées
leProtocole : Protocole;
//Le consigneur qui réachemine les messages d'erreur et de succès dans un format précis.
//FormatDateTime('c', now) permet d'afficher la date sous la forme jj/mm/aaaa hh:mm:ss
leConsigneur : Consigneur;
public
// Permet d'initialiser le serveur en créant la connexion et le protocole
// @param unPort le numéro du port sur lequel le serveur écoute les requêtes
// @param unConsigneur qui est de type Consigneur qui consigne les messages d'erreur et de connexion dans un format standardisé.
// @param unRepertoireDeBase qui est de type string qui représente un répertore existant sur le serveur.
constructor create(unPort:Word; unConsigneur:Consigneur; unRepertoireDeBase:String);
// Destructeur qui détruit les objet connexion, protocole et consigneur.
// @param unConsigneur de type Consigneur qui représente le consigneur à détruire.
destructor destroy;
// Démarre le traitement des requêtes
procedure demarrer;
end;
implementation
constructor Serveur.create(unPort:Word; unConsigneur:Consigneur; unRepertoireDeBase:String);
begin
// Instanciation de l'objet ConnexionHTTPServeur
laConnexion := ConnexionHTTPServeur.create(unPort);
// Instanciation de l'objet Protocole
leProtocole := Protocole.create(unRepertoireDeBase,unConsigneur);
leConsigneur:=unConsigneur;
// Affichage d'un message standardisé pour confirmer l'initialisation (Instanciation) du serveur.
leConsigneur.consigner('Serveur',' Le serveur est connecte sur le port '+ intToStr(unPort));
end;
procedure Serveur.demarrer;
var
uneRequete: Requete;
uneReponse: Reponse;
begin
// Boucler infiniment
while true do
begin
// Ouvre la connexion et attend une requête
try
uneRequete := laConnexion.lireRequete;
// Message de confirmation de la réception de la requête
leConsigneur.consigner('Serveur',' Requête reçue de '+laConnexion.getAdresseDistante+'.');
except on e : Exception do
leConsigneur.consignerErreur('Serveur',' Erreur d''entrée/sortie: '+ e.Message);
end;
// Le protocole traite la requête
try
uneReponse := leProtocole.traiterRequete(uneRequete);
except on e : Exception do
leConsigneur.consignerErreur('Serveur',' Erreur d''entrée/sortie: '+ e.Message);
//Les consignes sur moodle parlais d'un lancement d'exception mais je ne savais pas ou le mettre
// ou même si je devais le mettre?
//raise Exception.create('Numéro de port invalide ou déjà utilisé');
end;
// Renvoie de la reponse au client
laConnexion.ecrireReponse(uneReponse);
// Fermeture de la connexion
laConnexion.fermerConnexion;
end;
end;
//Le destructeur qui détruit les objets de la classe serveur.
destructor Serveur.destroy;
begin
laConnexion.destroy;
leProtocole.destroy;
end;
end.
|
unit ideSHSysInit;
interface
uses
Classes, SysUtils,
SHDesignIntf, SHDevelopIntf,
ideSHDesignIntf, ideSHConsts, ideSHSystem, ideSHSysUtils, ideSHMain,
ideSHRegistry, ideSHDesigner,
ideSHMegaEditor, ideSHComponentFactory;
type
TSHBranchInfo = class(TSHComponent, ISHDemon, ISHBranchInfo, ISHBranch)
private
function GetBranchName: string;
protected
function GetBranchIID: TGUID; override;
function GetCaption: string; override;
function GetCaptionExt: string; override;
public
class function GetHintClassFnc: string; override;
class function GetAssociationClassFnc: string; override;
class function GetClassIIDClassFnc: TGUID; override;
end;
procedure GlobalFinalization;
implementation
{ TSHBranchInfo }
class function TSHBranchInfo.GetHintClassFnc: string;
begin
Result := Format('%s', [SSHCommonBranch])
end;
class function TSHBranchInfo.GetAssociationClassFnc: string;
begin
Result := GetHintClassFnc;
end;
class function TSHBranchInfo.GetClassIIDClassFnc: TGUID;
begin
Result := ISHBranch;
end;
function TSHBranchInfo.GetBranchIID: TGUID;
begin
Result := ISHBranch;
end;
function TSHBranchInfo.GetCaption: string;
begin
Result := GetBranchName;
end;
function TSHBranchInfo.GetCaptionExt: string;
begin
Result := Format('%s Information', [Caption]);
end;
function TSHBranchInfo.GetBranchName: string;
begin
Result := GetHintClassFnc;
end;
procedure GlobalFinalization;
begin
{ Обниливание МегаГлобальных переменных системы и освобождение
}
RegistryIntf := nil;
{ TODO -oBuzz -cСреда : Почему то стало бить АВ. Разобраться }
// FreeAndNil(Registry);
ObjectEditorIntf := nil;
MegaEditorIntf := nil;
MainIntf := nil;
ComponentFactoryIntf := nil;
DesignerIntf := nil;
FreeAndNil(Designer);
FreeAndNil(ComponentFactory);
FreeAndNil(MegaEditor);
FreeAndNil(Main);
end;
initialization
{ Архивирование конфига
}
ideSHSysUtils.BackupConfigFile(ideSHSysUtils.GetFilePath(SFileConfig), ideSHSysUtils.GetFilePath(SFileConfigBackup));
ideSHSysUtils.BackupConfigFile(ideSHSysUtils.GetFilePath(SFileAliases), ideSHSysUtils.GetFilePath(SFileAliasesBackup));
ideSHSysUtils.ForceConfigFile(ideSHSysUtils.GetFilePath(SFileConfig));
ideSHSysUtils.ForceConfigFile(ideSHSysUtils.GetFilePath(SFileAliases));
ideSHSysUtils.ForceConfigFile(ideSHSysUtils.GetFilePath(SFileEnvironment));
ideSHSysUtils.ForceConfigFile(ideSHSysUtils.GetFilePath(SFileForms));
{ Инициализация папок
}
ForceDirectories(ideSHSysUtils.GetDirPath(SDirData));
{ Инициализация BTDesignIntf
}
SHRegisterInterfaceProc := @ideBTRegisterInterface;
SHSupportsFunc := @ideBTSupportInterface;
SHRegisterActionsProc := @ideBTRegisterActions;
SHRegisterComponentsProc := @ideBTRegisterComponents;
SHRegisterPropertyEditorProc := @ideBTRegisterPropertyEditor;
SHRegisterComponentFormProc := @ideBTRegisterComponentForm;
SHRegisterImageProc := @ideBTRegisterImage;
{ Инициализация Мегаглобальных переменных системы
}
Registry := TideBTRegistry.Create(nil);
Main := TideBTMain.Create(nil);
MegaEditor := TideBTMegaEditor.Create(nil);
ComponentFactory := TideSHComponentFactory.Create(nil);
Designer := TideBTDesigner.Create(nil);
Supports(Registry, IideBTRegistry, RegistryIntf);
Supports(Main, IideBTMain, MainIntf);
Supports(MegaEditor, IideBTMegaEditor, MegaEditorIntf);
Supports(ComponentFactory, IideSHComponentFactory, ComponentFactoryIntf);
Supports(Designer, ISHDesigner, DesignerIntf);
if Assigned(DesignerIntf) then
begin
SHRegisterInterface(DesignerIntf);
//SHDesignIntf.SHRegisterComponents([TSHBranchInfo]);
end;
finalization
GlobalFinalization;
end.
|
unit MainWindow;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Math.Vectors,
Vcl.ExtCtrls, Math, Generics.Collections,
Nullable, Camera, Ray, Scene, Light, Shape, Material, Intersection, OBJLoader;
type
TImage = array of array of TColor;
type
TForm1 = class(TForm)
PaintBox1: TPaintBox;
Button1: TButton;
Label1: TLabel;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
end;
type
TRayTraceThread = class(TThread)
protected
xMax, yMax, tIdx, mIdx: Word;
cam: TCamera;
Scene: TScene;
img: TImage;
Stre: TStore;
procedure Execute; override;
public
constructor Create(img: TImage; const xMax, yMax, tIdx, mIdx: Word;
cam: TCamera; Stre: TStore; Scene: TScene);
end;
type
TThreads = array [0 .. 6] of TRayTraceThread;
type
TMainTaskThread = class(TThread)
protected
threads: TThreads;
img: TImage;
procedure Execute; override;
public
constructor Create(threads: TThreads; img: TImage);
end;
var
Form1: TForm1;
img: TImage;
implementation
{ TRunProcessThread }
constructor TRayTraceThread.Create(img: TImage;
const xMax, yMax, tIdx, mIdx: Word; cam: TCamera; Stre: TStore;
Scene: TScene);
begin
inherited Create(True);
Priority := tpHighest;
// Props
Self.tIdx := tIdx;
Self.mIdx := mIdx;
Self.cam := cam;
Self.Scene := Scene;
Self.img := img;
Self.yMax := yMax;
Self.xMax := xMax;
Self.Stre := Stre;
FreeOnTerminate := False;
Resume;
end;
{ TMainTaskThread }
constructor TMainTaskThread.Create(threads: TThreads; img: TImage);
begin
inherited Create(True);
Priority := tpHighest;
// Props
Self.threads := threads;
Self.img := img;
FreeOnTerminate := False;
Resume;
end;
procedure TMainTaskThread.Execute;
var
tIdx, x, y, xMax, yMax: Word;
time: DWORD;
begin
Form1.Label1.Caption := 'TRACING';
time := GetTickCount;
tIdx := 0;
while tIdx < Length(threads) do
begin
threads[tIdx].WaitFor;
tIdx := tIdx + 1;
end;
time := GetTickCount - time;
Form1.Label1.Caption := IntToStr(time) + 'ms';
xMax := Form1.PaintBox1.Width;
yMax := Form1.PaintBox1.Height;
// Copy pixels
x := 0;
while x < xMax do
begin
y := 0;
while y < yMax do
begin
Form1.PaintBox1.Canvas.Pixels[x, y] := img[x, y];
y := y + 1;
end;
x := x + 1;
end;
end;
{ TForm }
{$R *.dfm}
function Inv(v: Single): Single;
begin
if v <> 0 then
begin
Result := 1 / v;
end
else
Result := Single.PositiveInfinity;
end;
function InvVec3(v: TVector): TVector;
begin
Result := TVector.Create(Inv(v.x), Inv(v.y), Inv(v.W));
end;
function OriginRay(cam: TCamera; x, y, xMax, yMax: Word): TRay;
var
aspRat, fX, fZ: Single;
p0, up, right, dir: TVector;
begin
// Find up and right vectors
up := TVector.Create(0, 0, 1);
right := up.CrossProduct(cam.look).Normalize;
up := cam.look.CrossProduct(right);
// Caluclate camera stuff
aspRat := xMax / yMax;
p0 := cam.pos + cam.look * cam.canvasDist; // p0 is incorrect
// Calculate origin ray
fX := (x / xMax) - 0.5;
fZ := (y / yMax) - 0.5;
dir := (cam.pos + p0 + fX * aspRat * right - fZ * up).Normalize;
OriginRay := TRay.Create(cam.pos, dir, InvVec3(dir), 0);
end;
function LightIntersect(Stre: TStore; Scene: TScene; lr: TRay; ld: Single): Boolean;
var
intsct: TNullable<TIntersection>;
I: Integer;
begin
Result := False;
I := 0;
while I < Length(Scene.shapes) do
begin
intsct := Intersect(Stre, Stre.Shps[Scene.shapes[I]], lr, ld);
if intsct.HasValue and (intsct.Value.d < ld) then
Exit;
I := I + 1;
end;
Result := True;
end;
function ColClamp(v: Single): Byte;
begin
Result := Min(253, Round(v));
end;
function PowInt(n: Single; e: Integer): Single;
begin
Result := 1;
while (True) do
begin
if (e and 1 <> 0) then
Result := Result * n;
e := e shr 1;
e := e - 1;
if (e < 1) then
break;
n := n * n;
end;
end;
function RayTrace(Stre: TStore; Scene: TScene; cam: TCamera; Ray: TRay): TVector;
var
NRay: TRay;
Shape: TShape;
Light: TLight;
intsct, hit: TNullable<TIntersection>;
lv, col, s: TVector;
d, ld, attn, pow: Single;
I: Integer;
begin
// Intersect the scene
d := Single.PositiveInfinity;
I := 0;
while I < Length(Scene.shapes) do
begin
intsct := Intersect(Stre, Stre.Shps[Scene.shapes[I]], Ray, d);
if intsct.HasValue and (intsct.Value.d < d) then
begin
d := intsct.Value.d;
hit := intsct;
end;
I := I + 1;
end;
// Calculate the color
if (d < Single.MaxValue) and hit.HasValue then
begin
col := TVector.Create(0, 0, 0);
I := 0;
while I < Length(Scene.ligths) do
begin
lv := Scene.ligths[I].pos - hit.Value.point;
ld := lv.Length;
lv := lv.Normalize;
if LightIntersect(Stre, Scene, TRay.Create(hit.Value.point + 0.01 *
hit.Value.normal, lv, InvVec3(lv), 0), ld) then
begin
// Diffuse light
attn := Scene.ligths[I].pow / (ld * ld);
pow := Min(1, Max(0, lv.DotProduct(hit.Value.normal) * attn));
col := col + pow * hit.Value.mat.color *
(1.0 - hit.Value.mat.reflective);
// Specular light
s := lv - 2.0 * lv.DotProduct(hit.Value.normal) * hit.Value.normal;
col := col + PowInt(Max(Ray.dir.DotProduct(s), 0), 200) * Scene.ligths
[I].lum * attn;
end;
I := I + 1;
end;
// Ambient
col := col + hit.Value.mat.color * 0.05 * (1.0 - hit.Value.mat.reflective);
// Reflections
if (Ray.bounces < 5) and (hit.Value.mat.reflective > 0) then
begin
// Create reflected ray
Ray.dir := Ray.dir - 2 * hit.Value.normal *
hit.Value.normal.DotProduct(Ray.dir);
Ray.dir := Ray.dir.Normalize;
Ray.invDir := InvVec3(Ray.dir);
Ray.org := hit.Value.point + 0.01 * hit.Value.normal;
Ray.bounces := Ray.bounces + 1;
// Calculate color
col := col + hit.Value.mat.reflective * RayTrace(Stre, Scene, cam, Ray);
end;
Result := col;
end
else
begin // No intersect, background color
Result := TVector.Create(10, 25, 25);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
cam: TCamera;
Scene: TScene;
xMax, yMax, tIdx: Word;
PIdx, SIdx: Cardinal;
tArr: TThreads;
Bnds: TBounds;
Stre: TDynStore;
FStr: TStore;
Shps: TList<Cardinal>;
Lgts: TList<TLight>;
begin
// Define scene
Shps := TList<Cardinal>.Create;
Lgts := TList<TLight>.Create;
// Initialize store
Stre := TDynStore.Create;
// Add shapes
PIdx := Stre.VPos.Add(TVector.Create(6, 30, -2));
SIdx := Stre.Shps.Add(SphrCreate(PIdx, 2, TMaterial.Create(TVector.Create(0,
255, 255), 0, 0, 0)));
Shps.Add(SIdx);
PIdx := Stre.VPos.Add(TVector.Create(-8, 35, 0));
SIdx := Stre.Shps.Add(SphrCreate(PIdx, 3, TMaterial.Create(TVector.Create(0,
255, 0), 0.5, 0, 0)));
Shps.Add(SIdx);
PIdx := Stre.VPos.Add(TVector.Create(0, 28, -3));
SIdx := Stre.Shps.Add(SphrCreate(PIdx, 2, TMaterial.Create(TVector.Create(255,
0, 0), 0, 0, 0)));
Shps.Add(SIdx);
PIdx := Stre.VPos.Add(TVector.Create(1, 26, 1));
SIdx := Stre.Shps.Add(SphrCreate(PIdx, 0.5,
TMaterial.Create(TVector.Create(255, 255, 0), 0, 0, 0)));
Shps.Add(SIdx);
// Add objs
// Scene.shapes.Add(LoadOBJ(Stre, 'C:\Repos\Delphi_RayTracer\house.obj',
//// TVector.Create(-10, 50, -5)));
// Shps.Add(LoadOBJ(Stre, 'C:\Repos\Delphi_RayTracer\horse.obj',
// TVector.Create(0, 300, -40)));
Shps.Add(LoadOBJ(Stre, 'C:\Repos\Delphi_RayTracer\teapot.obj',
TVector.Create(10, 40, 3)));
Shps.Add(LoadOBJ(Stre, 'C:\Repos\Delphi_RayTracer\cow.obj',
TVector.Create(0, 30, 0)));
// // Octree scene
// Bnds := Rebound(Stre, Scene.shapes);
// SIdx := SubDevide(Stre, 0, Stre.VPos.Add(Bnds.PMin), Stre.VPos.Add(Bnds.PMax),
// Scene.shapes);
// Scene.shapes := TList<Cardinal>.Create();
// Scene.shapes.Add(SIdx);
// Add lights
Lgts.Add(TLight.Create(TVector.Create(-2, 0, 10), TVector.Create(255,
255, 255), 50));
// Define camera & scene
Scene := TScene.Create(Shps.ToArray,Lgts.ToArray);
cam := TCamera.Create(TVector.Create(0, 0, 0), TVector.Create(0, 1, 0), 3);
// Get canvasSize
xMax := Form1.PaintBox1.Width;
yMax := Form1.PaintBox1.Height;
SetLength(img, xMax, yMax);
// Convert the store to fixed arrays
FStr := Stre.ToFixStore;
Stre.Destroy;
// Create threads
tIdx := 0;
while tIdx < Length(tArr) do
begin
tArr[tIdx] := TRayTraceThread.Create(img, xMax, yMax, tIdx, Length(tArr), cam,
FStr, Scene);
tIdx := tIdx + 1;
end;
TMainTaskThread.Create(tArr, img);
end;
procedure TRayTraceThread.Execute;
var
x, y: Word;
org: TRay;
col: TVector;
I: Integer;
begin
NameThreadForDebugging('RT_' + IntToStr(tIdx));
// Raytrace all the pixels for this thread
x := 0;
while x < xMax do
begin
y := tIdx;
while y < yMax do
begin
col := TVector.Zero;
for I := 0 to 1 do
begin
org := OriginRay(cam, x, y, xMax, yMax);
col := col + RayTrace(Stre, Scene, cam, org);
end;
img[x, y] := RGB(ColClamp(col.x), ColClamp(col.y), ColClamp(col.W));
y := y + mIdx;
end;
x := x + 1;
end;
inherited;
end;
procedure TForm1.Button2Click(Sender: TObject);
var xMax, yMax, x, y: Word;
begin
xMax := Form1.PaintBox1.Width;
yMax := Form1.PaintBox1.Height;
// Copy pixels
x := 0;
while x < xMax do
begin
y := 0;
while y < yMax do
begin
Form1.PaintBox1.Canvas.Pixels[x, y] := img[x, y];
y := y + 1;
end;
x := x + 1;
end;
end;
end.
|
unit DSA.Sorts.HeapSort;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Interfaces.Comparer,
DSA.Utils,
DSA.Tree.Heap;
type
{ THeapSort }
generic THeapSort<T> = class
private
type
TArr_T = specialize TArray<T>;
ICmp_T = specialize IDSA_Comparer<T>;
TCmp_T = specialize TComparer<T>;
THeap_T = specialize THeap<T, TCmp_T>;
var
class var __cmp: ICmp_T;
class procedure __shiftDwon(var arr: TArr_T; k: integer; Count: integer);
public
/// <summary> 使用THeap类 </summary>
class procedure Sort(var arr: TArr_T; cmp: ICmp_T);
/// <summary> 原地排序 </summary>
class procedure Sort_Adv(var arr: TArr_T; cmp: ICmp_T);
end;
procedure Main;
implementation
uses
DSA.Sorts.QuickSort,
DSA.Sorts.MergeSort;
type
THeapSort_int = specialize THeapSort<integer>;
TMergeSort_int = specialize TMergeSort<integer>;
TQuickSort_int = specialize TQuickSort<integer>;
procedure Main;
var
sourceArr, targetArr: TArray_int;
n, swapTimes: integer;
begin
n := 1000000;
WriteLn('Test for random array, size = ', n, ', random range [0, ', n, ']');
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateRandomArray(n, n);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, @TMergeSort_int(nil).Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, @TQuickSort_int(nil).Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort'#9#9, targetArr, @THeapSort_int(nil).Sort);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort_Adv'#9#9, targetArr, @THeapSort_int(nil).Sort_Adv);
Free;
end;
swapTimes := 100;
WriteLn('Test for nearly ordered array, size = ', n, ', swap time = ', swapTimes);
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateNearlyOrderedArray(n, swapTimes);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, @TMergeSort_int(nil).Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, @TQuickSort_int(nil).Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort'#9#9, targetArr, @THeapSort_int(nil).Sort);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort_Adv'#9#9, targetArr, @THeapSort_int(nil).Sort_Adv);
Free;
end;
WriteLn('Test for random array, size = ', n, ', random range [0, ', 10, ']');
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateRandomArray(n, 10);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, @TMergeSort_int(nil).Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, @TQuickSort_int(nil).Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort'#9#9, targetArr, @THeapSort_int(nil).Sort);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort_Adv'#9#9, targetArr, @THeapSort_int(nil).Sort_Adv);
Free;
end;
end;
{ THeapSort }
class procedure THeapSort.Sort(var arr: TArr_T; cmp: ICmp_T);
var
heapMin: THeap_T;
i: integer;
begin
heapMin := THeap_T.Create(arr, cmp, THeapkind.Min);
for i := 0 to Length(arr) - 1 do
arr[i] := heapMin.ExtractFirst;
end;
class procedure THeapSort.Sort_Adv(var arr: TArr_T; cmp: ICmp_T);
var
i: integer;
tmp: T;
begin
__cmp := cmp;
for i := (Length(arr) - 1 - 1) div 2 downto 0 do
__shiftDwon(arr, i, Length(arr));
for i := Length(arr) - 1 downto 1 do
begin
tmp := arr[0];
arr[0] := arr[i];
arr[i] := tmp;
__shiftDwon(arr, 0, i);
end;
end;
class procedure THeapSort.__shiftDwon(var arr: TArr_T; k: integer; Count: integer);
var
j: integer;
e: T;
begin
e := arr[k];
while 2 * k + 1 < Count do
begin
j := 2 * k + 1;
if (j + 1 < Count) and (__cmp.Compare(arr[j + 1], arr[j]) > 0) then
j += 1;
if __cmp.Compare(e, arr[j]) >= 0 then
Break;
arr[k] := arr[j];
k := j;
end;
arr[k] := e;
end;
end.
|
unit uMenuItem;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uTools;
type
{ TMenuItemParser }
TMenuItemType = (MITprog, MITmenu, MITmenudefault,
MITrunonce,
{$IFDEF Windows}
MITmenuwindow, MITwindow, MITwinkey, MITwinignore,
{$ENDIF}
MITmenufile, MITmenuprog, MITmenuprogreload, MITseparator, MITEndMenu, MITNone,
MITmenupath);
TMenuItemParser = class(TObject)
private
FCmd: string;
FInputLine: string;
FItemType: TMenuItemType;
FMenuId: integer;
FName: String;
FShortCut: string;
FSubMenuCmd: string;
FSubMenuId: integer;
FSubMenuPath: string;
FSubMenuReloadInterval: integer;
function GetSearch: string;
function GetSubMenuChar: string;
Procedure QuoteTrim(Var lName: String); // remove leading and ending quotes
Procedure setNameAndShotrCutKey(Const aName: String);
function SplitMenuLine(const aLine: string): TStringList;
procedure startNewMenu(const aLine: string);
procedure startNewMenuDefault(const aLine: string);
procedure endMenu;
procedure prepareProg(const aLine: string);
procedure prepareWindow(const aName, hWindow: string);
procedure prepareRunOnce(const aLine: string);
procedure prepareProgreload(const aLine: string);
procedure prepareWindowmenu(const aLine: string);
procedure preparePathmenu(const aLine: string);
procedure prepareWinKey(const aLine: string);
procedure prepareWinIgnore(const aLine: string);
procedure prepareSeparator(const aLine: string);
procedure includeItems(const aLine: string);
public
constructor Create(const aLine: string);
constructor Create(const aName, hWindow, aShortcut: String); // window item
destructor Destroy; override;
property Name: String read FName;
property cmd: string read FCmd;
property menuId: integer read FMenuId;
property itemType: TMenuItemType read FItemType;
property search: string read GetSearch;
property shortcut: string read FShortCut;
property subMenuId: integer read FSubMenuId;
property subMenuPath: string read FSubMenuPath;
property subMenuCmd: string read FSubMenuCmd;
property subMenuReloadInterval: integer read FSubMenuReloadInterval;
property subMenuChar: string read GetSubMenuChar;
end;
function MitToStr(const aMenuType: TMenuItemType): string;
function strToMit(const aMenuTypeStr: string): TMenuItemType;
implementation
uses Dialogs, uMainForm, strutils, clipbrd;
function MitToStr(const aMenuType: TMenuItemType): string;
begin
WriteStr(Result, aMenuType);
end;
function strToMit(const aMenuTypeStr: string): TMenuItemType;
begin
ReadStr(aMenuTypeStr, Result);
end;
{ TMenuItemParser }
procedure TMenuItemParser.prepareProg(const aLine: string);
var
lSl: TStringList;
i: integer;
begin
lSl := SplitMenuLine(aLine);
try
FItemType := MITprog;
setNameAndShotrCutKey(lSl[1]);
for i := 2 to lsl.Count - 1 do
FCmd := FCmd + ' ' + lsl[i];
fCmd := Trim(FCmd);
finally
FreeAndNil(lSl);
end;
end;
procedure TMenuItemParser.prepareWindow(const aName, hWindow: string);
begin
FItemType := MITwindow;
setNameAndShotrCutKey(aName);
FCmd := hWindow;
end;
procedure TMenuItemParser.prepareRunOnce(const aLine: string);
var
lSl: TStringList;
i: integer;
begin
lSl := SplitMenuLine(aLine);
try
FItemType := MITprog; // on linux simple run
{$IFDEF Windows}
FItemType := MITrunonce;
{$ENDIF}
setNameAndShotrCutKey(lSl[1]);
for i := 2 to lsl.Count - 1 do
FCmd := FCmd + ' ' + lsl[i];
fCmd := Trim(FCmd);
finally
FreeAndNil(lSl);
end;
End;
procedure TMenuItemParser.prepareProgreload(const aLine: string);
var
lSl: TStringList;
i: integer;
begin
lSl := SplitMenuLine(aLine);
try
FItemType := MITmenuprogreload;
setNameAndShotrCutKey(lSl[1]);
FSubMenuReloadInterval := StrToInt(lSl[2]);
for i := 3 to lsl.Count - 1 do
FSubMenuCmd := FSubMenuCmd + ' ' + lsl[i];
FSubMenuCmd := Trim(FSubMenuCmd);
finally
FreeAndNil(lSl);
end;
end;
{ TODO -cWM : jen pro windows}
procedure TMenuItemParser.prepareWindowmenu(const aLine: string);
var
lSl: TStringList;
i: integer;
begin
lSl := SplitMenuLine(aLine);
try
FItemType := MITmenuwindow;
setNameAndShotrCutKey(lSl[1]);
FSubMenuReloadInterval := -1; // const 0s
for i := 2 to lsl.Count - 1 do
FSubMenuCmd := FSubMenuCmd + ' ' + lsl[i];
//FSubMenuCmd := Trim(FSubMenuCmd);
finally
FreeAndNil(lSl);
end;
end;
procedure TMenuItemParser.preparePathmenu(const aLine: string);
var
lSl: TStringList;
i: integer;
begin
lSl := SplitMenuLine(aLine);
try
FItemType := MITmenupath;
setNameAndShotrCutKey(lSl[1]);
FSubMenuReloadInterval := -1; // const 0s
// for i := 2 to lsl.Count - 1 do
{ #todo : check size of lsl }
FSubMenuPath := Trim(ReplaceStr(lSl[2],'"','')); { #todo : replace only on start and end }
for i := 3 to lsl.Count - 1 do
FSubMenuCmd := FSubMenuCmd + ' ' + lsl[i];
FSubMenuCmd := Trim(ReplaceStr(FSubMenuCmd,'"','')); { #todo : replace only on start and end }
finally
FreeAndNil(lSl);
end;
end;
procedure TMenuItemParser.prepareWinKey(const aLine: string);
var
lSl: TStringList;
begin
lSl := SplitMenuLine(aLine);
try
FItemType := MITwinkey;
FName := lSl[1];
QuoteTrim(FName);
FName := Trim(FName);
FCmd := FName;
FShortCut := lSl[2];
finally
FreeAndNil(lSl);
end;
end;
procedure TMenuItemParser.prepareWinIgnore(const aLine: string);
var
lSl: TStringList;
begin
lSl := SplitMenuLine(aLine);
try
FItemType := MITwinignore;
FName := lSl[1];
QuoteTrim(FName);
FName := Trim(FName);
FCmd := FName;
finally
FreeAndNil(lSl);
end;
end;
procedure TMenuItemParser.prepareSeparator(const aLine: string);
var
lSl: TStringList;
begin
lSl := SplitMenuLine(aLine);
try
FItemType := MITseparator;
if lSl.Count >= 2 then
begin
FName := lSl[1];
FName := FName.Replace('%clipbrd%', Clipboard.AsText);
end;
If (Length(FName) > 0) and (FName[1] = '#') Then
Delete(FName, 1, 1);
FName := FName.Replace('"', '');
finally
FreeAndNil(lSl);
end;
end;
procedure TMenuItemParser.includeItems(const aLine: string);
var
lSl: TStringList;
lFileName, lFileNameCfg: string;
begin
lSl := SplitMenuLine(aLine);
try
FItemType := MITNone;
lFileName := lSl[1];
lFileNameCfg := '';
{$IFNDEF Windows}
lFileNameCfg := GetEnvironmentVariable('HOME') + '/.icewm/' + lFileName; {TODO -oLebeda -cNone: správnou cestu}
{$ENDIF}
if FileExists(lFileName) then
MainForm.LoadMenuFromFile(lFileName)
else if FileExists(lFileNameCfg) then
MainForm.LoadMenuFromFile(lFileNameCfg);
finally
FreeAndNil(lSl);
end;
end;
function TMenuItemParser.SplitMenuLine(const aLine: string): TStringList;
Var
lLine: String;
begin
Result := TStringList.Create;
Result.Delimiter := ' ';
lLine := StringReplace(aLine, '"', '"""', [rfReplaceAll]);
Result.DelimitedText := lLine;
end;
procedure TMenuItemParser.startNewMenu(const aLine: string);
var
lSl: TStringList;
begin
lSl := SplitMenuLine(aLine);
try
FItemType := MITmenu;
setNameAndShotrCutKey(lSl[1]);
FSubMenuId := MainForm.AddMenu(FName, FMenuId, MITmenu);
finally
FreeAndNil(lSl);
end;
end;
procedure TMenuItemParser.startNewMenuDefault(const aLine: string);
var
lSl: TStringList;
begin
lSl := SplitMenuLine(aLine);
try
FItemType := MITmenudefault;
setNameAndShotrCutKey(lSl[1]);
FSubMenuId := MainForm.AddMenu(FName, FMenuId, MITmenudefault);
finally
FreeAndNil(lSl);
end;
end;
procedure TMenuItemParser.endMenu;
var
lUpMenuId: integer;
begin
lUpMenuId := MainForm.SQLMenu.FieldByName('upMenuId').AsInteger;
FItemType := MITEndMenu;
MainForm.setActiveMenu(lUpMenuId);
end;
function TMenuItemParser.GetSearch: string;
begin
Result := NormalizeTerm(FName); // lowercase and remove diacritics
end;
function TMenuItemParser.GetSubMenuChar: string;
begin
if FItemType in [MITmenu, MITmenufile, MITmenuprog, MITmenuprogreload, MITmenuwindow, MITmenupath] then
Result := '>'
else if FItemType = MITMenudefault then
Result := '|'
else
Result := '';
end;
procedure TMenuItemParser.QuoteTrim(var lName: String);
Begin
If lName[1] = '"' Then
Delete(lName, 1, 1);
If lName[Length(lName)] = '"' Then
Delete(lName, Length(lName), 1);
End;
procedure TMenuItemParser.setNameAndShotrCutKey(const aName: String);
Var
i: Integer;
lName: String;
Begin
// identify explicit shortcut
for i := 1 to Length(aName) do
begin
if (aName[i] = '_') and (FShortCut = '') and (aName[i + 1] <> '_') then
FShortCut := LowerCase(aName[i + 1])
else
lName := lName + aName[i];
End;
QuoteTrim(lName);
lName := lName.Replace('%clipbrd%', Clipboard.AsText);
lName := Trim(lName);
FName := lName;
End;
constructor TMenuItemParser.Create(const aLine: string);
begin
FInputLine := aLine;
FMenuId := MainForm.SQLMenu.FieldByName('id').AsInteger;
if AnsiStartsText('prog ', aLine) then
prepareProg(aLine)
else if AnsiStartsText('runonce ', aLine) then { TODO -cfeat : implementace pro windows }
prepareRunOnce(aLine)
else if AnsiStartsText('separator', aLine) then
prepareSeparator(aLine)
else if AnsiStartsText('menuwindow ', aLine) then
prepareWindowmenu(aLine)
else if AnsiStartsText('menupath ', aLine) then
preparePathmenu(aLine)
else if AnsiStartsText('winkey ', aLine) then
prepareWinKey(aLine)
else if AnsiStartsText('winignore ', aLine) then
prepareWinIgnore(aLine)
else if AnsiStartsText('menu ', aLine) then
startNewMenu(aLine)
else if AnsiStartsText('menudefault ', aLine) then
startNewMenuDefault(aLine)
else if AnsiStartsText('}', aLine) then
endMenu
else if AnsiStartsText('include ', aLine) then
includeItems(aLine)
else if AnsiStartsText('menuprogreload ', aLine) then
prepareProgreload(aLine)
//else if AnsiStartsText('menusearch ', aLine) then
// prepareSearch(aLine) {TODO -oLebeda -cNone: menusearch}
// menufile
// menuprog
else
begin
FItemType := MITNone;
WriteLn('!!!!!' + aLine);
end;
end;
constructor TMenuItemParser.Create(const aName, hWindow, aShortcut: String);
begin
FMenuId := MainForm.SQLMenu.FieldByName('id').AsInteger;
FShortCut := aShortcut;
prepareWindow(aName, hWindow)
end;
destructor TMenuItemParser.Destroy;
begin
inherited Destroy;
end;
end.
|
unit ufrmMaster;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Vcl.StdCtrls, Vcl.ExtCtrls, uCompany, uFormProperty, ufrmMasterDialog,
ActnList;
type
TfrmMaster = class(TForm)
pnlBody: TPanel;
pnlHeader: TPanel;
lblHeader: TLabel;
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
//procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FMasterCompany: TCompany;
FMasterNewUnit: integer;//TUnit;
TList: TStrings;
function GetMasterCompany: TCompany;
function GetMasterNewUnit: integer;//TUnit;
procedure GetUserModule;
protected
public
FLoginFullname : string;
FLoginRole : string;
FLoginUsername : string;
FLoginId : Integer;
FLoginUnitId : Integer;
FMasterIsStore : Integer;
FMasterIsHO : Integer;
FFilePathReport : String;
FHostClient : string;
FIpClient : string;
FLoginIsStore : Integer;
FTipeApp : TTipeApp;
property MasterCompany: TCompany read GetMasterCompany write FMasterCompany;
property MasterNewUnit: integer{TUnit} read GetMasterNewUnit write FMasterNewUnit;
constructor Create(AOwner: TComponent); override;
constructor CreateWithUser(aOwner: TComponent; aFormProperty : TFormProperty);
overload;
procedure Authenticate;
function SetFormPropertyAndShowDialog(aFrmMasterDialog : TFrmMasterDialog;
aIsModal: Boolean = True): Boolean;
end;
var
frmMaster: TfrmMaster;
implementation
uses uTSCommonDlg;
{$R *.dfm}
constructor TfrmMaster.Create(AOwner: TComponent);
begin
KeyPreview := true;
TList := TStringList.Create;
with FormatSettings do
begin
CurrencyString := 'Rp. ';
CurrencyFormat := 2;
CurrencyDecimals := 2;
DecimalSeparator := '.';
ThousandSeparator := ',';
end;
inherited Create(AOwner);
end;
constructor TfrmMaster.CreateWithUser(aOwner: TComponent; aFormProperty :
TFormProperty);
begin
// MasterCompany := TCompany.Create(Self);
// MasterNewUnit := 0;//TUnit.Create(Self);
//
// FMasterIsStore := aFormProperty.FMasterIsStore;
// FMasterIsHO := aFormProperty.FMasterIsHo;
// FLoginFullname := aFormProperty.FLoginFullname;
// FLoginRole := aFormProperty.FLoginRole;
// FLoginUsername := aFormProperty.FLoginUsername;
// FLoginId := aFormProperty.FLoginId;
// FLoginUnitId := aFormProperty.FLoginUnitId;
// FLoginIsStore := aFormProperty.FLoginIsStore;
// FTipeApp := aFormProperty.FTipeApp;
//
// FFilePathReport := aFormProperty.FFilePathReport;
// FHostClient := aFormProperty.FHostClient;
// FIpClient := aFormProperty.FIpClient;
// if MasterCompany.LoadByID(aFormProperty.FSelfCompanyID) then
// begin
//// if not MasterNewUnit.LoadByID(aFormProperty.FSelfUnitID) then
// begin
// CommonDlg.ShowError('Unit Belum Dipilih');
// //Self := nil;
// Exit;
// end;
// end else begin
// CommonDlg.ShowError('Company Belum Dipilih');
// //Self := nil;
// Exit;
// end;
Create(aOwner);
end;
//constructor TfrmMaster.CreateWithUser(aOwner: TComponent; afrmMaster :
// TfrmMaster);
//begin
// MasterCompany := TCompany.Create(Self);
// MasterNewUnit := TUnit.Create(Self);
//
// FMasterIsStore := afrmMaster.FMasterIsStore;
// FLoginFullname := afrmMaster.FLoginFullname;
// FLoginRole := afrmMaster.FLoginRole;
// FLoginUsername := afrmMaster.FLoginUsername;
// FLoginId := afrmMaster.FLoginId;
// FLoginUnitId := afrmMaster.FLoginUnitId;
// FLoginIsStore := afrmMaster.FLoginIsStore;
//
// FFilePathReport := afrmMaster.FFilePathReport;
// FHostClient := afrmMaster.FHostClient;
// FIpClient := afrmMaster.FIpClient;
//
// if MasterCompany.LoadByID(afrmMaster.MasterCompany.ID) then
// begin
// if not MasterNewUnit.LoadByID(afrmMaster.MasterNewUnit.ID) then
// begin
// CommonDlg.ShowError('Unit Belum Dipilih');
// //Self := nil;
// Exit;
// end;
// end
// else
// begin
// CommonDlg.ShowError('Company Belum Dipilih');
// //Self := nil;
// Exit;
// end;
//
// Create(aOwner);
//end;
procedure TfrmMaster.FormDestroy(Sender: TObject);
begin
FreeAndNil(TList);
FreeAndNil(frmMaster); // := nil;
end;
procedure TfrmMaster.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmMaster.Authenticate;
var
i: word;
idx: integer;
begin
GetUserModule;
for i := 0 to ComponentCount-1 do
if Components[i] is TAction then begin
idx := TList.IndexOf(LowerCase(Components[i].Name));
if idx <> -1 then
(Components[i] as TAction).Enabled := true
else
(Components[i] as TAction).Enabled := false;
end;
end;
function TfrmMaster.SetFormPropertyAndShowDialog(aFrmMasterDialog :
TFrmMasterDialog; aIsModal: Boolean = True): Boolean;
begin
Result := False;
if Assigned(aFrmMasterDialog) then
begin
aFrmMasterDialog.FMasterIsStore := FMasterIsStore;
aFrmMasterDialog.FLoginFullname := FLoginFullname;
aFrmMasterDialog.FLoginRole := FLoginRole;
aFrmMasterDialog.FLoginUsername := FLoginUsername;
aFrmMasterDialog.FLoginId := FLoginId;
aFrmMasterDialog.FLoginUnitId := FLoginUnitId;
aFrmMasterDialog.FLoginIsStore := FLoginIsStore;
aFrmMasterDialog.FFilePathReport := FFilePathReport;
// aFrmMasterDialog.DialogCompany := MasterCompany.ID;
aFrmMasterDialog.DialogUnit := 0;//MasterNewUnit.ID;
aFrmMasterDialog.FDialogUnitCOde := '';//MasterNewUnit.Kode;
aFrmMasterDialog.FDialogUnitName := '';//MasterNewUnit.Nama;
Result := True;
end else begin
CommonDlg.ShowError('Form Belum Dicreate' +#13 + 'Kesalahan Ada Pada Developer');
Exit;
end;
if ((Result) and (aIsModal)) then
aFrmMasterDialog.ShowModal
else if (Result and (aIsModal = False)) then
aFrmMasterDialog.Show
else if not Result then
begin
CommonDlg.ShowError('Gagal Melakukan Setting Property Form');
Exit;
end;
end;
procedure TfrmMaster.GetUserModule;
var
sTipe: string;
sSQL : string;
strNama : string;
begin
strNama := Name;
sTipe := 'View';
// sSQL := 'SELECT m.mod_action'
// + ' FROM aut$module m'
// + ' LEFT JOIN aut$group_module gm ON m.mod_id = gm.gmod_mod_id'
// + ' and m.MOD_UNT_ID = gm.GMOD_MOD_UNT_ID'
// + ' LEFT JOIN aut$user_group ug ON gm.gmod_gro_id = ug.ug_gro_id'
// + ' and gm.GMOD_GRO_UNT_ID = ug.UG_GRO_UNT_ID'
// + ' LEFT JOIN aut$user u ON ug.ug_usr_id = u.usr_id'
// + ' and ug.UG_USR_UNT_ID = u.USR_UNT_ID'
// + ' WHERE m.mod_name = '+ QuotedStr(strNama)
// + ' AND u.usr_username = '+ QuotedStr(FLoginUsername)
// + ' AND ( u.USR_UNT_ID = ' + IntToStr(FLoginUnitId) +')';
sSQL := 'SELECT MOD.MOD_ACTION '
+ ' FROM AUT$MENU_STRUCTURE MS '
+ ' LEFT OUTER JOIN AUT$MENU M ON (MS.MENUS_ID = M.MENU_ID) '
+ ' AND (MS.MENUS_UNT_ID = M.MENU_UNT_ID) '
+ ' LEFT OUTER JOIN AUT$USER_GROUP UG ON (M.MENU_GRO_ID = UG.UG_GRO_ID) '
+ ' AND (M.MENU_GRO_UNT_ID = UG.UG_GRO_UNT_ID) '
+ ' LEFT OUTER JOIN AUT$USER U ON (UG.UG_USR_ID = U.USR_ID) '
+ ' AND (UG.UG_USR_UNT_ID = U.USR_UNT_ID) '
+ ' INNER JOIN AUT$MODULE MOD ON (MS.MENUS_MOD_ID = MOD.MOD_ID) '
+ ' AND (MS.MENUS_MOD_UNT_ID = MOD.MOD_UNT_ID) '
+ ' WHERE U.USR_USERNAME = '+ QuotedStr(FLoginUsername)
+ ' AND U.USR_UNT_ID = '+ IntToStr(FLoginUnitId)
+ ' AND MOD.MOD_LABEL <> ' + QuotedStr(sTipe)
+ ' AND UPPER(MOD.MOD_NAME) = ' + QuotedStr(UpperCase(strNama));
{
with dmMain.qrMultiPurpose do begin
SQL.Text := sSQL;
// 'SELECT m.mod_action FROM aut$module m ' +
// 'LEFT JOIN aut$group_module gm ON m.mod_id = gm.gmod_mod_id ' +
// 'LEFT JOIN aut$user_group ug ON gm.gmod_gro_id = ug.ug_gro_id ' +
// 'LEFT JOIN aut$user u ON ug.ug_usr_id = u.usr_id ' +
// 'WHERE m.mod_name = :module AND u.usr_username = :username';
// Params[0].AsString := strNama;
// Params[1].AsString := FLoginUsername;
Open;
if not IsEmpty then
while not Eof do begin
TList.Add(LowerCase(Fields[0].AsString));
Next;
end;
end;
}
end;
{procedure TfrmMaster.FormCreate(Sender: TObject);
begin
FFormState := FFormState - [fsVisible];
KeyPreview := true;
TList := TStringList.Create;
CurrencyString := 'Rp. ';
CurrencyFormat := 2;
CurrencyDecimals := 2;
DecimalSeparator := '.';
ThousandSeparator := ',';
MasterCompany := TCompany.Create(Self);
MasterNewUnit := TUnit.Create(Self);
end;
}
procedure TfrmMaster.FormShow(Sender: TObject);
begin
// Authenticate;
// frmMain.pnlHeader.Hide;
end;
procedure TfrmMaster.FormActivate(Sender: TObject);
begin
//frmMain.pnlHeader.Hide;
end;
function TfrmMaster.GetMasterCompany: TCompany;
begin
Result := FMasterCompany;
if not Assigned(FMasterCompany) then
begin
CommonDlg.ShowError('Company Belum Dipilih');
Application.Terminate;
end{ else if FMasterCompany.ID = 0 then
begin
CommonDlg.ShowError('Company Belum Dipilih');
Application.Terminate;
end};
end;
function TfrmMaster.GetMasterNewUnit: integer;//TUnit;
begin
Result := FMasterNewUnit;
// if not Assigned(FMasterNewUnit) then
begin
CommonDlg.ShowError('Unit Belum Dipilih');
Application.Terminate;
end{ else if FMasterNewUnit.ID = 0 then
begin
CommonDlg.ShowError('Unit Belum Dipilih');
Application.Terminate;
end};
end;
procedure TfrmMaster.FormCreate(Sender: TObject);
begin
// do nothing, jangan diilangi ya
end;
end.
|
unit Odontologia.Controlador.Agenda;
interface
uses
Data.DB,
System.SysUtils,
System.Generics.Collections,
Odontologia.Controlador.Estado.Cita,
Odontologia.Controlador.Estado.Cita.Interfaces,
Odontologia.Controlador.Medico,
Odontologia.Controlador.Medico.Interfaces,
Odontologia.Controlador.Agenda.Interfaces,
Odontologia.Controlador.Paciente,
Odontologia.Controlador.Paciente.Interfaces,
Odontologia.Modelo,
Odontologia.Modelo.Entidades.Agenda,
Odontologia.Modelo.Agenda.Interfaces,
Odontologia.Modelo.Paciente.Interfaces;
type
TControllerAgenda = class(TInterfacedObject, iControllerAgenda)
private
FModel : iModelAgenda;
FDataSource : TDataSource;
FMedico : iControllerMedico;
FPaciente : iControllerPaciente;
FEstadoCita : iControllerEstadoCita;
procedure DataChange (sender : tobject ; field : Tfield) ;
public
constructor Create;
destructor Destroy; override;
class function New: iControllerAgenda;
function DataSource (aDataSource : TDataSource) : iControllerAgenda;
function Buscar (aFecha : String) : iControllerAgenda; overload;
function Buscar (aFecha, aMedico, aPaciente : String) : iControllerAgenda; overload;
function Buscar (aFecha, aMedico, aPaciente, aEstado : String) : iControllerAgenda; overload;
function Buscar : iControllerAgenda; overload;
function Insertar : iControllerAgenda;
function Modificar : iControllerAgenda;
function Eliminar : iControllerAgenda;
function Entidad : TDAGENDA;
function Medico : iControllerMedico;
function Paciente : iControllerPaciente;
function EstadoCita : iControllerEstadoCita;
end;
implementation
{ TControllerAgenda }
function TControllerAgenda.Buscar: iControllerAgenda;
begin
Result := Self;
FDataSource.dataset.DisableControls;
FModel.DAO.SQL.Fields('DAGENDA.AGE_CODIGO AS CODIGO,')
.Fields('DAGENDA.AGE_FECHA AS FECHA,')
.Fields('DAGENDA.AGE_HORA AS HORA,')
.Fields('DAGENDA.AGE_PACIENTE AS CODPAC,')
.Fields('DAGENDA.AGE_MEDICO AS CODMED,')
.Fields('DAGENDA.AGE_COD_ESTADO_CITA AS CODESTADO,')
.Fields('DPACIENTE.PAC_NOMBRE AS PACIENTE,')
.Fields('DMEDICO.MED_NOMBRE AS MEDICO,')
.Fields('FESTADO_CITA.CIT_DESCRIPCION AS ESTADO')
.Join('INNER JOIN DPACIENTE ON DPACIENTE.PAC_CODIGO = DAGENDA.AGE_PACIENTE')
.Join('INNER JOIN DMEDICO ON DMEDICO.MED_CODIGO = DAGENDA.AGE_MEDICO')
.Join('INNER JOIN FESTADO_CITA ON FESTADO_CITA.CIT_CODIGO = DAGENDA.AGE_COD_ESTADO_CITA')
.Where('')
.OrderBy('FECHA')
.&End.Find;
FDataSource.dataset.EnableControls;
FDataSource.dataset.FieldByName('CODIGO').Visible := false;
FDataSource.dataset.FieldByName('CODPAC').Visible := false;
FDataSource.dataset.FieldByName('CODMED').Visible := false;
FDataSource.dataset.FieldByName('CODESTADO').Visible := false;
FDataSource.dataset.FieldByName('FECHA').DisplayWidth := 20;
FDataSource.dataset.FieldByName('MEDICO').DisplayWidth := 30;
FDataSource.dataset.FieldByName('PACIENTE').DisplayWidth := 30;
end;
function TControllerAgenda.Buscar(aFecha, aMedico, aPaciente, aEstado : String) : iControllerAgenda;
begin
Result := Self;
FDataSource.dataset.DisableControls;
FModel.DAO.SQL.Fields('DAGENDA.AGE_CODIGO AS CODIGO,')
.Fields('DAGENDA.AGE_FECHA AS FECHA,')
.Fields('DAGENDA.AGE_HORA AS HORA,')
.Fields('DAGENDA.AGE_PACIENTE AS CODPAC,')
.Fields('DAGENDA.AGE_MEDICO AS CODMED,')
.Fields('DAGENDA.AGE_COD_ESTADO_CITA AS CODESTADO,')
.Fields('DPACIENTE.PAC_NOMBRE AS PACIENTE,')
.Fields('DMEDICO.MED_NOMBRE AS MEDICO,')
.Fields('FESTADO_CITA.CIT_DESCRIPCION AS ESTADO')
.Join('INNER JOIN DPACIENTE ON DPACIENTE.PAC_CODIGO = DAGENDA.AGE_PACIENTE')
.Join('INNER JOIN DMEDICO ON DMEDICO.MED_CODIGO = DAGENDA.AGE_MEDICO')
.Join('INNER JOIN FESTADO_CITA ON FESTADO_CITA.CIT_CODIGO = DAGENDA.AGE_COD_ESTADO_CITA')
.Where('DAGENDA.AGE_FECHA = ' + QuotedStr(aFecha) + ' AND DMEDICO.MED_NOMBRE LIKE ' + QuotedStr(aMedico) + ' AND DPACIENTE.PAC_NOMBRE LIKE ' + QuotedStr(aPaciente) + ' AND FESTADO_CITA.CIT_DESCRIPCION LIKE ' + QuotedStr(AESTADO) + '')
.OrderBy('FECHA')
.&End.Find;
FDataSource.dataset.EnableControls;
FDataSource.dataset.FieldByName('CODIGO').Visible := false;
FDataSource.dataset.FieldByName('CODPAC').Visible := false;
FDataSource.dataset.FieldByName('CODMED').Visible := false;
FDataSource.dataset.FieldByName('CODESTADO').Visible := false;
FDataSource.dataset.FieldByName('FECHA').DisplayWidth := 20;
FDataSource.dataset.FieldByName('MEDICO').DisplayWidth := 30;
FDataSource.dataset.FieldByName('PACIENTE').DisplayWidth := 30;
end;
function TControllerAgenda.Buscar(aFecha, aMedico,
aPaciente: String): iControllerAgenda;
begin
end;
function TControllerAgenda.Buscar(aFecha: String): iControllerAgenda;
begin
Result := Self;
FDataSource.dataset.DisableControls;
FModel.DAO.SQL.Fields('DAGENDA.AGE_CODIGO AS CODIGO,')
.Fields('DAGENDA.AGE_FECHA AS FECHA,')
.Fields('DAGENDA.AGE_HORA AS HORA,')
.Fields('DAGENDA.AGE_PACIENTE AS CODPAC,')
.Fields('DAGENDA.AGE_MEDICO AS CODMED,')
.Fields('DAGENDA.AGE_COD_ESTADO_CITA AS CODESTADO,')
.Fields('DPACIENTE.PAC_NOMBRE AS PACIENTE,')
.Fields('DMEDICO.MED_NOMBRE AS MEDICO,')
.Fields('FESTADO_CITA.CIT_DESCRIPCION AS ESTADO')
.Join('INNER JOIN DPACIENTE ON DPACIENTE.PAC_CODIGO = DAGENDA.AGE_PACIENTE')
.Join('INNER JOIN DMEDICO ON DMEDICO.MED_CODIGO = DAGENDA.AGE_MEDICO')
.Join('INNER JOIN FESTADO_CITA ON FESTADO_CITA.CIT_CODIGO = DAGENDA.AGE_COD_ESTADO_CITA')
.Where('DAGENDA.AGE_FECHA = ' + QuotedStr(aFecha))
.OrderBy('FECHA')
.&End.Find;
FDataSource.dataset.EnableControls;
FDataSource.dataset.FieldByName('CODIGO').Visible := false;
FDataSource.dataset.FieldByName('CODPAC').Visible := false;
FDataSource.dataset.FieldByName('CODMED').Visible := false;
FDataSource.dataset.FieldByName('CODESTADO').Visible := false;
FDataSource.dataset.FieldByName('FECHA').DisplayWidth := 20;
FDataSource.dataset.FieldByName('MEDICO').DisplayWidth := 30;
FDataSource.dataset.FieldByName('PACIENTE').DisplayWidth := 30;
end;
constructor TControllerAgenda.Create;
begin
FModel := TModel.New.Agenda;
FMedico := TControllerMEDICO.New;
FPaciente := TControllerPaciente.New;
FEstadoCita := TControllerEstadoCita.New;
end;
procedure TControllerAgenda.DataChange(sender: tobject; field: Tfield);
begin
end;
function TControllerAgenda.DataSource(aDataSource: TDataSource) : iControllerAgenda;
begin
Result := Self;
FDataSource := aDataSource;
FModel.DataSource(FDataSource);
FDataSource.OnDataChange := DataChange;
end;
destructor TControllerAgenda.Destroy;
begin
inherited;
end;
function TControllerAgenda.Eliminar: iControllerAgenda;
begin
Result := Self;
FModel.DAO.Delete(FModel.Entidad);
end;
function TControllerAgenda.Paciente: iControllerPaciente;
begin
Result := FPaciente;
end;
function TControllerAgenda.Entidad: TDAGENDA;
begin
Result := FModel.Entidad;
end;
function TControllerAgenda.EstadoCita: iControllerEstadoCita;
begin
Result := FEstadoCita;
end;
function TControllerAgenda.Insertar: iControllerAgenda;
begin
Result := Self;
FModel.DAO.Insert(FModel.Entidad);
end;
function TControllerAgenda.Medico: iControllerMedico;
begin
Result := FMedico;
end;
function TControllerAgenda.Modificar: iControllerAgenda;
begin
Result := Self;
FModel.DAO.Update(FModel.Entidad);
end;
class function TControllerAgenda.New: iControllerAgenda;
begin
Result := Self.Create;
end;
end.
|
unit uMultiplyManager;
{$I ..\Include\IntXLib.inc}
interface
uses
uIMultiplier,
uClassicMultiplier,
uAutoFhtMultiplier,
uEnums,
uIntX,
uIntXLibTypes;
type
/// <summary>
/// Used to retrieve needed multiplier.
/// </summary>
TMultiplyManager = class sealed(TObject)
public
/// <summary>
/// Constructor.
/// </summary>
class constructor Create();
/// <summary>
/// Returns multiplier instance for given multiply mode.
/// </summary>
/// <param name="mode">Multiply mode.</param>
/// <returns>Multiplier instance.</returns>
/// <exception cref="EArgumentOutOfRangeException"><paramref name="mode" /> is out of range.</exception>
class function GetMultiplier(mode: TMultiplyMode): IIMultiplier; static;
/// <summary>
/// Returns current multiplier instance.
/// </summary>
/// <returns>Current multiplier instance.</returns>
class function GetCurrentMultiplier(): IIMultiplier; static;
class var
/// <summary>
/// Classic multiplier instance.
/// </summary>
FClassicMultiplier: IIMultiplier;
/// <summary>
/// FHT multiplier instance.
/// </summary>
FAutoFhtMultiplier: IIMultiplier;
end;
implementation
// static class constructor
class constructor TMultiplyManager.Create();
var
mclassicMultiplier: IIMultiplier;
begin
// Create new classic multiplier instance
mclassicMultiplier := TClassicMultiplier.Create;
// Fill publicity visible multiplier fields
FClassicMultiplier := mclassicMultiplier;
FAutoFhtMultiplier := TAutoFhtMultiplier.Create(mclassicMultiplier);
end;
class function TMultiplyManager.GetMultiplier(mode: TMultiplyMode)
: IIMultiplier;
begin
case (mode) of
TMultiplyMode.mmAutoFht:
begin
result := FAutoFhtMultiplier;
Exit;
end;
TMultiplyMode.mmClassic:
begin
result := FClassicMultiplier;
Exit;
end;
else
begin
raise EArgumentOutOfRangeException.Create('mode');
end;
end;
end;
class function TMultiplyManager.GetCurrentMultiplier(): IIMultiplier;
begin
result := GetMultiplier(TIntX.GlobalSettings.MultiplyMode);
end;
end.
|
Unit RequestFilter;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
Interface
Uses
Generics.Collections, INIFiles,
IRPMonRequest, IRPMonDll, DLLDecider;
Type
RequestFilterOperatorSet = Set Of ERequestFilterOperator;
Const
RequestFilterOperatorNames : Array [0..Ord(rfoDLLDecider)] Of WideString = (
'==',
'<=',
'>=',
'<',
'>',
'contains',
'begins',
'ends',
'true',
'DLL'
);
RequestFilterIntegerOperators : RequestFilterOperatorSet = [
rfoEquals,
rfoLowerEquals,
rfoGreaterEquals,
rfoLower,
rfoGreater,
rfoAlwaysTrue,
rfoDLLDecider
];
RequestFilterStringOperators : RequestFilterOperatorSet = [
rfoEquals,
rfoContains,
rfoBegins,
rfoEnds,
rfoAlwaysTrue,
rfoDLLDecider
];
Const
RequestFilterActionNames : Array [0..Ord(ffaPassToFilter)] Of WideString = (
'Highlight',
'Include',
'Exclude',
'Pass'
);
Type
TRequestFilter = Class
Private
FDLLDecider : TDLLDecider;
FHighlightColor : Cardinal;
FNextFilter : TRequestFilter;
FPreviousFilter : TRequestFilter;
FName : WideString;
FField : ERequestListModelColumnType;
FOp : ERequestFilterOperator;
FStringValue : WideString;
FIntValue : UInt64;
FRequestType : ERequestType;
FEnabled : Boolean;
FEphemeral : Boolean;
FAction : EFilterAction;
FNegate : Boolean;
FColumnName : WideString;
FRequestPrototype : TDriverRequest;
Protected
Procedure SetEnable(AValue:Boolean);
Procedure RemoveFromChain;
Procedure AddMapping(ASources:TList<UInt64>; ATargets:TList<WideString>; AIntValue:UInt64; AStringValue:WideString);
Public
Constructor Create(AName:WideString; ARequestType:ERequestType = ertUndefined); Reintroduce;
Destructor Destroy; Override;
Procedure GenerateName(AList:TObjectList<TRequestFilter> = Nil);
Function GetPossibleValues(ASources:TList<UInt64>; ATargets:TList<WideString>; Var ABitmask:Boolean):Boolean; Virtual;
Function SupportedOperators:RequestFilterOperatorSet; Virtual;
Function Copy:TRequestFilter;
Function Match(ARequest:TDriverRequest; Var AResultAction:EFilterAction; Var AHiglightColor:Cardinal; AChainStart:Boolean = True):TRequestFilter;
Function SetAction(AAction:EFilterAction; AHighlightColor:Cardinal = $FFFFFF):Cardinal;
Function AddNext(AFilter:TRequestFilter):Cardinal;
Function SetCondition(AColumn:ERequestListModelColumnType; AOperator:ERequestFilterOperator; AValue:UInt64):Boolean; Overload;
Function SetCondition(AColumn:ERequestListModelColumnType; AOperator:ERequestFilterOperator; AValue:WideString):Boolean; Overload;
Function HasPredecessor:Boolean;
Class Function NewInstance(ARequestType:ERequestType):TRequestFilter; Reintroduce; Overload;
Class Function LoadList(AFileName:WideString; AList:TList<TRequestFilter>):Boolean;
Class Function SaveList(AFileName:WideString; AList:TList<TRequestFilter>):Boolean;
Class Function GetByName(AName:WideString; AList:TList<TRequestFilter>):TRequestFilter;
Function Save(AFile:TIniFile):Boolean;
Property Name : WideString Read FName Write FName;
Property Field : ERequestListModelColumnType Read FField;
Property Op : ERequestFilterOperator Read FOp;
Property StringValue : WideString Read FStringValue;
Property IntValue : UInt64 Read FIntValue;
Property RequestType : ERequesttype Read FRequestType;
Property Enabled : Boolean Read FEnabled Write SetEnable;
Property Ephemeral : Boolean Read FEphemeral Write FEphemeral;
Property Action : EFilterAction Read FAction;
Property HighlightColor : Cardinal Read FHighlightColor;
Property Negate : Boolean Read FNegate Write FNegate;
Property ColumnName : WideString Read FColumnName;
Property NextFilter : TRequestFilter Read FNextFilter;
end;
TIRPRequestFilter = Class (TRequestFilter)
Public
Constructor Create(AName:WideString); Reintroduce;
Function GetPossibleValues(ASources:TList<UInt64>; ATargets:TList<WideString>; Var ABitmask:Boolean):Boolean; Override;
end;
TIRPCompletionRequestFilter = Class (TRequestFilter)
Public
Constructor Create(AName:WideString); Reintroduce;
Function GetPossibleValues(ASources:TList<UInt64>; ATargets:TList<WideString>; Var ABitmask:Boolean):Boolean; Override;
end;
Implementation
Uses
Classes, SysUtils, IRPRequest, FastIoRequest, FileObjectNameXXXRequest,
XXXDetectedRequests, ProcessXXXRequests,
Utils;
(** TRequestFilter **)
Constructor TRequestFilter.Create(AName:WideString; ARequestType:ERequestType = ertUndefined);
begin
Inherited Create;
FName := AName;
FRequestType := ARequestType;
FOp := rfoAlwaysTrue;
FAction := ffaInclude;
FNextFilter := Nil;
FPreviousFilter := Nil;
FHighlightColor := $FFFFFF;
FRequestPrototype := TDriverRequest.CreatePrototype(FRequestType);
end;
Destructor TRequestFilter.Destroy;
begin
RemoveFromChain;
If Assigned(FRequestPrototype) Then
FRequestPrototype.Free;
If Assigned(FDLLDecider) Then
FDLLDecider.Free;
Inherited Destroy;
end;
Function TRequestFilter.Save(AFile:TIniFile):Boolean;
begin
Try
AFile.WriteInteger(FName, 'RequestType', Ord(FRequestType));
AFile.WriteInteger(FName, 'Column', Ord(FField));
AFile.WriteInteger(FName, 'Operator', Ord(FOp));
AFile.WriteString(FName, 'Value', FStringValue);
AFile.WriteInteger(FName, 'Action', Ord(FAction));
AFile.WriteBool(FName, 'Enabled', FEnabled);
AFIle.WriteBool(FName, 'Negate', FNegate);
AFile.WriteInteger(FName, 'Color', FHighlightCOlor);
If Assigned(FNextFilter) Then
AFile.WriteString(FName, 'Next', FNextFilter.Name);
Result := True;
Except
Result := False;
end;
end;
Procedure TRequestFilter.GenerateName(AList:TObjectList<TRequestFilter> = Nil);
Var
I : Integer;
tmpName : WideString;
begin
I := 0;
tmpName := FName;
While (tmpName = '') Or (Assigned(AList) And Assigned(GetByName(tmpName, AList))) Do
begin
tmpName := TDriverRequest.RequestTypeToString(FRequestType) + '-' +
FColumnName + '-' +
RequestFilterOperatorNames[Ord(FOp)] + '-' +
FStringValue + '-' +
BoolToStr(FNegate) + '-' +
RequestFilterActionNames[Ord(FAction)];
If I <> 0 Then
tmpName := tmpName + '-' + IntToStr(Int64(I));
Inc(I);
end;
FName := tmpName;
end;
Class Function TRequestFilter.LoadList(AFileName:WideString; AList:TList<TRequestFilter>):Boolean;
Var
names : TStringList;
rf : TRequestFilter;
tmp : TRequestFilter;
I : Integer;
_name : WideString;
_enabled : Boolean;
_negate : Boolean;
_type : ERequestType;
_column : ERequestListModelColumnType;
_op : ERequestFilterOperator;
_value : WideString;
_action : EFilterAction;
_color : Cardinal;
_next : WideString;
nextNames : TStringList;
iniFile : TIniFile;
begin
Result := True;
iniFile := Nil;
nextNames := Nil;
names := Nil;
Try
iniFile := TIniFile.Create(AFileName);
nextNames := TStringList.Create;
names := TStringList.Create;
Try
iniFile.ReadSections(names);
For _name In names Do
begin
Try
_type := ERequestType(iniFile.ReadInteger(_name, 'RequestType', -1));
_column := ERequestListModelColumnType(iniFile.ReadInteger(_name, 'Column', -1));
_op := ERequestFilterOperator(iniFile.ReadInteger(_name, 'Operator', -1));
_value := iniFile.ReadString(_name, 'Value', '');
_action := EFilterAction(iniFile.ReadInteger(_name, 'Action', -1));
_enabled := iniFile.ReadBool(_name, 'Enabled', True);
_negate := iniFile.ReadBool(_name, 'Negate', False);
_color := iniFile.ReadInteger(_name, 'Color', $FFFFFF);
_next := iniFile.ReadString(_name, 'Next', '');
rf := GetByName(_name, AList);
If Assigned(rf) Then
Continue;
rf := TRequestFilter.NewInstance(_type);
rf.Name := _name;
rf.Enabled := _enabled;
rf.Negate := _negate;
rf.SetCondition(_column, _op, _value);
rf.SetAction(_action, _color);
AList.Add(rf);
nextNames.Add(_next);
Except
Result := False;
end;
end;
If Result Then
begin
For I := 0 To AList.Count - 1 Do
begin
_next := nextNames[I];
If _next <> '' Then
begin
rf := AList[I];
tmp := GetByName(_next, AList);
If (Assigned(tmp)) And (rf.Action = ffaPassToFilter) THen
rf.AddNext(tmp);
end;
end;
end;
Except
Result := False;
end;
Finally
names.Free;
nextNames.Free;
iniFile.Free;
end;
end;
Class Function TRequestFilter.SaveList(AFileName:WideString; AList:TList<TRequestFilter>):Boolean;
Var
section : WideString;
names : TStringList;
rf : TRequestFilter;
iniFile : TIniFile;
begin
Result := True;
iniFile := Nil;
names := Nil;
Try
iniFile := TIniFile.Create(AFileName);
names := TStringList.Create;
Try
iniFile.ReadSections(names);
For section In names Do
iniFile.EraseSection(section);
For rf In AList Do
begin
If Not rf.Ephemeral Then
begin
Result := rf.Save(iniFile);
If Not Result Then
Break;
end;
end;
Except
Result := False;
end;
Finally
names.Free;
iniFile.Free;
end;
end;
Class Function TRequestFilter.GetByName(AName:WideString; AList:TList<TRequestFilter>):TRequestFilter;
Var
tmp : TRequestFilter;
begin
Result := Nil;
For tmp In AList Do
begin
If tmp.Name = AName Then
begin
Result := tmp;
Break;
end;
end;
end;
Function TRequestFilter.HasPredecessor:Boolean;
begin
Result := Assigned(FPreviousFilter);
end;
Function TRequestFilter.Match(ARequest:TDriverRequest; Var AResultAction:EFilterAction; Var AHiglightColor:Cardinal; AChainStart:Boolean = True):TRequestFilter;
Var
ret : Boolean;
d : Pointer;
l : Cardinal;
iValue : UInt64;
sValue : WideString;
stringConstant : WideString;
dllDecision : DLL_DECIDER_DECISION;
begin
Result := Nil;
If (FEnabled) And
((Not AChainStart) Or (Not Assigned(FPreviousFIlter))) And
((FRequestType = ertUndefined) Or (ARequest.RequestType = FRequestType)) Then
begin
If FOp <> rfoDLLDecider Then
begin
ret := ARequest.GetColumnValueRaw(FField, d, l);
If ret Then
begin
iValue := 0;
sValue := '';
ret := False;
Case RequestListModelColumnValueTypes[Ord(FField)] Of
rlmcvtInteger,
rlmcvtTime,
rlmcvtMajorFunction,
rlmcvtMinorFunction,
rlmcvtProcessorMode,
rlmcvtRequestType,
rlmcvtIRQL : begin
Move(d^, iValue, l);
Case FOp Of
rfoEquals: ret := (iValue = FIntValue);
rfoLowerEquals: ret := (iValue <= FIntValue);
rfoGreaterEquals: ret := (iValue >= FIntValue);
rfoLower: ret := (iValue < FIntValue);
rfoGreater: ret := (iValue > FIntValue);
rfoAlwaysTrue: ret := True;
end;
end;
rlmcvtString : begin
sValue := WideUpperCase(WideCharToString(d));
stringConstant := WideUpperCase(FStringValue);
Case FOp Of
rfoEquals: ret := (WideCompareText(sValue, stringConstant) = 0);
rfoContains: ret := (Pos(stringConstant, sValue) > 0);
rfoBegins: ret := (Pos(stringConstant, sValue) = 1);
rfoEnds: ret := (Pos(stringConstant, sValue) = Length(sValue) - Length(stringConstant) + 1);
rfoAlwaysTrue: ret := True;
end;
end;
end;
If FNegate Then
ret := Not ret;
If ret Then
begin
AResultAction := FAction;
AHiglightColor := FHighlightColor;
end;
end;
end
Else begin
dllDecision.Action := FAction;
dllDecision.HiglightColor := FHighlightColor;
dllDecision.Decided := False;
dllDecision.OverrideFilter := False;
ret := (FDLLDecider.Decide(ARequest, dllDecision) = 0);
If ret Then
ret := dllDecision.Decided;
If ret Then
begin
AResultAction := FAction;
AHiglightColor := FHighlightColor;
If dllDecision.OverrideFilter Then
begin
AResultAction := dllDecision.Action;
AHiglightColor := dllDecision.HiglightColor;
end;
end;
end;
If ret Then
begin
Result := Self;
If (AResultAction = ffaPassToFilter) And (Assigned(FNextFilter)) Then
Result := FNextFilter.Match(ARequest, AResultAction, AHiglightColor, False);
end;
end;
end;
Procedure TRequestFilter.SetEnable(AValue:Boolean);
Var
tmp : TRequestFilter;
begin
FEnabled := AValue;
tmp := FPreviousFilter;
While Assigned(tmp) And (tmp <> Self) Do
begin
tmp.FEnabled := AValue;
tmp := tmp.FPreviousFilter;
end;
tmp := FNextFilter;
While Assigned(tmp) And (tmp <> Self) Do
begin
tmp.FEnabled := AValue;
tmp := tmp.FNextFilter;
end;
end;
Function TRequestFilter.AddNext(AFilter:TRequestFilter):Cardinal;
begin
Result := 0;
If (FRequestType = ertUndefined) Or (FRequestType = AFilter.FRequestType) Then
begin
If Assigned(AFilter.FPreviousFilter) Then
begin
AFilter.FPreviousFilter.FNextFilter := Nil;
AFilter.FPreviousFilter := Nil;
end;
If Assigned(FNextFilter) Then
begin
FNextFilter.FPreviousFilter := Nil;
FNextFilter := Nil;
end;
FAction := ffaPassToFilter;
AFilter.FPreviousFilter := Self;
FNextFilter := AFIlter;
end
Else Result := 1;
end;
Procedure TRequestFilter.RemoveFromChain;
begin
If (Assigned(FNextFilter)) Or (Assigned(FPreviousFilter)) Then
begin
If Assigned(FPreviousFilter) Then
begin
FPreviousFilter.FNextFilter := FNextFilter;
If Not Assigned(FNextFilter) Then
FPreviousFilter.FAction := ffaInclude;
end;
If Assigned(FNextFilter) Then
begin
FNextFilter.FPreviousFilter := FPreviousFilter;
FAction := ffaInclude;
end;
FNextFilter := Nil;
FPreviousFilter := Nil;
end;
end;
Function TRequestFilter.SetAction(AAction:EFilterAction; AHighlightColor:Cardinal = $FFFFFF):Cardinal;
begin
Result := 0;
If (FAction = ffaPassToFilter) And (FAction <> AAction) Then
begin
If Assigned(FNextFilter) Then
begin
FNextFilter.FPreviousFilter := Nil;
FNextFilter := Nil;
end;
end;
FAction := AAction;
FHighlightColor := AHighlightColor;
end;
Function TRequestFilter.SetCondition(AColumn:ERequestListModelColumnType; AOperator:ERequestFilterOperator; AValue:UInt64):Boolean;
begin
Case RequestListModelColumnValueTypes[Ord(AColumn)] Of
rlmcvtInteger,
rlmcvtTime,
rlmcvtMajorFunction,
rlmcvtMinorFunction,
rlmcvtProcessorMode,
rlmcvtRequestType,
rlmcvtIRQL : begin
Result := (AOperator In RequestFilterIntegerOperators);
If Result Then
begin
FField := AColumn;
FOp := AOperator;
FIntValue := AValue;
FstringValue := UIntToStr(AValue);
end;
end;
Else Result := False;
end;
If Result Then
FColumnName := FRequestPrototype.GetColumnName(AColumn);
end;
Function TRequestFilter.SetCondition(AColumn:ERequestListModelColumnType; AOperator:ERequestFilterOperator; AValue:WideString):Boolean;
Var
tmpDecider : TDLLDecider;
dllSeparatorIndex : Integer;
modName : WideString;
routineName : WideString;
begin
Result := False;
If AOperator <> rfoDLLDecider Then
begin
Case RequestListModelColumnValueTypes[Ord(AColumn)] Of
rlmcvtInteger,
rlmcvtTime,
rlmcvtMajorFunction,
rlmcvtMinorFunction,
rlmcvtProcessorMode,
rlmcvtRequestType,
rlmcvtIRQL : begin
Result := (AOperator In RequestFilterIntegerOperators);
If Result Then
begin
Try
FIntValue := StrToInt64(AValue);
FstringValue := AValue;
FField := AColumn;
FOp := AOperator;
Except
Result := False;
end;
end;
end;
rlmcvtString : begin
Result := (AOperator In RequestFilterStringOperators);
If Result Then
begin
FField := AColumn;
FOp := AOperator;
FStringValue := AValue;
end;
end;
end;
end
Else begin
FField := AColumn;
FOp := AOperator;
FStringValue := AValue;
dllSeparatorIndex := Pos('!', FStringValue);
If dllSeparatorIndex >= 1 Then
begin
modName := System.Copy(FStringValue, 1, dllSeparatorIndex - 1);
routineName := System.Copy(FStringValue, dllSeparatorIndex + 1, Length(FStringValue) - dllSeparatorIndex);
tmpDecider := TDLLDecider.NewInstance(modName, routineName);
end
Else tmpDecider := TDLLDecider.NewInstance(FStringValue);
Result := Assigned(tmpDecider);
If Result Then
begin
If Assigned(FDLLDecider) Then
FDLLDecider.Free;
FDLLDecider := tmpDecider;
end;
end;
If Result Then
FColumnName := FRequestPrototype.GetColumnName(AColumn);
end;
Function TRequestFilter.SupportedOperators:RequestFilterOperatorSet;
begin
Case RequestListModelColumnValueTypes[Ord(FField)] Of
rlmcvtInteger,
rlmcvtTime,
rlmcvtMajorFunction,
rlmcvtMinorFunction,
rlmcvtProcessorMode,
rlmcvtIRQL,
rlmcvtRequestType : Result := RequestFilterIntegerOperators;
rlmcvtString : Result := RequestFilterStringOperators;
Else Result := [rfoAlwaysTrue];
end;
end;
Procedure TRequestFilter.AddMapping(ASources:TList<UInt64>; ATargets:TList<WideString>; AIntValue:UInt64; AStringValue:WideString);
begin
ASources.Add(AIntValue);
ATargets.Add(AStringValue);
end;
Function TRequestFIlter.GetPossibleValues(ASources:TList<UInt64>; ATargets:TList<WideString>; Var ABitmask:Boolean):Boolean;
begin
ABitmask := False;
Result := True;
Case RequestListModelColumnValueTypes[Ord(FField)] Of
rlmcvtProcessorMode : begin
AddMapping(ASources, ATargets, 0, 'KernelMode');
AddMapping(ASources, ATargets, 1, 'UserMode');
end;
rlmcvtIRQL : begin
AddMapping(ASources, ATargets, 0, 'Passive');
AddMapping(ASources, ATargets, 1, 'APC');
AddMapping(ASources, ATargets, 2, 'Dispatch');
{$IFDEF WIN32}
AddMapping(ASources, ATargets, 27, 'Profile');
AddMapping(ASources, ATargets, 28, 'Clock');
AddMapping(ASources, ATargets, 29, 'IPI');
AddMapping(ASources, ATargets, 30, 'Power');
AddMapping(ASources, ATargets, 31, 'High');
{$ELSE}
AddMapping(ASources, ATargets, 13, 'Clock');
AddMapping(ASources, ATargets, 14, 'Profile, IPI, Power');
AddMapping(ASources, ATargets, 15, 'High');
{$ENDIF}
end;
rlmcvtRequestType : begin
AddMapping(ASources, ATargets, Ord(ertUndefined), '<all>');
AddMapping(ASources, ATargets, Ord(ertIRP), 'IRP');
AddMapping(ASources, ATargets, Ord(ertIRPCompletion), 'IRPComp');
AddMapping(ASources, ATargets, Ord(ertAddDevice), 'AddDevice');
AddMapping(ASources, ATargets, Ord(ertDriverUnload), 'Unload');
AddMapping(ASources, ATargets, Ord(ertFastIo), 'FastIo');
AddMapping(ASources, ATargets, Ord(ertStartIo), 'StartIo');
AddMapping(ASources, ATargets, Ord(ertDriverDetected), 'DriverDetected');
AddMapping(ASources, ATargets, Ord(ertDeviceDetected), 'DeviceDetected');
AddMapping(ASources, ATargets, Ord(ertFileObjectNameAssigned), 'FONameAssigned');
AddMapping(ASources, ATargets, Ord(ertFileObjectNameDeleted), 'FONameDeleted');
AddMapping(ASources, ATargets, Ord(ertProcessCreated), 'ProcessCreate');
AddMapping(ASources, ATargets, Ord(ertProcessExitted), 'ProcessExit');
AddMapping(ASources, ATargets, Ord(ertImageLoad), 'ImageLoad');
end;
Else Result := False;
end;
end;
Class Function TRequestFilter.NewInstance(ARequestType:ERequestType):TRequestFilter;
begin
Case ARequestType Of
ertUndefined: Result := TRequestFilter.Create('', ARequestType);
ertIRP: Result := TIRPRequestFilter.Create('');
ertIRPCompletion : Result := TIRPCompletionRequestFilter.Create('');
Else Result := TRequestFilter.Create('', ARequestType);
end;
end;
Function TRequestFilter.Copy:TRequestFilter;
begin
Result := NewInstance(FRequestType);
If Assigned(Result) Then
begin
Result.FName := FName;
Result.FHighlightColor := FHighlightColor;
Result.FField := FField;
Result.FOp := FOp;
Result.FStringValue := FStringValue;
Result.FIntValue := FIntValue;
Result.FEnabled := FEnabled;
Result.FEphemeral := FEphemeral;
Result.FAction := FAction;
Result.FNegate := FNegate;
Result.FColumnName := FColumnName;
If Assigned(FDLLDecider) Then
Result.FDLLDecider := TDLLDecider.NewInstance(FDLLDecider.ModuleName, FDLLDecider.DecideRoutineName);
end;
end;
(** TIRPRequestFilter **)
Constructor TIRPRequestFilter.Create(AName:WideString);
begin
Inherited Create(AName, ertIRP);
end;
Function TIRPRequestFilter.GetPossibleValues(ASources:TList<UInt64>; ATargets:TList<WideString>; Var ABitmask:Boolean):Boolean;
begin
ABitmask := False;
Result := True;
Case RequestListModelColumnValueTypes[Ord(FField)] Of
rlmcvtMajorFunction : begin
AddMapping(ASources, ATargets, 0, 'Create');
AddMapping(ASources, ATargets, 1, 'CreateNamedPipe');
AddMapping(ASources, ATargets, 2, 'Close');
AddMapping(ASources, ATargets, 3, 'Read');
AddMapping(ASources, ATargets, 4, 'Write');
AddMapping(ASources, ATargets, 5, 'Query');
AddMapping(ASources, ATargets, 6, 'Set');
AddMapping(ASources, ATargets, 7, 'QueryEA');
AddMapping(ASources, ATargets, 8, 'SetEA');
AddMapping(ASources, ATargets, 9, 'Flush');
AddMapping(ASources, ATargets, 10, 'QueryVolume');
AddMapping(ASources, ATargets, 11, 'SetVolume');
AddMapping(ASources, ATargets, 12, 'DirectoryControl');
AddMapping(ASources, ATargets, 13, 'FSControl');
AddMapping(ASources, ATargets, 14, 'DeviceControl');
AddMapping(ASources, ATargets, 15, 'InternalDeviceControl');
AddMapping(ASources, ATargets, 16, 'Shutdown');
AddMapping(ASources, ATargets, 17, 'Lock');
AddMapping(ASources, ATargets, 18, 'Cleanup');
AddMapping(ASources, ATargets, 19, 'CreateMailslot');
AddMapping(ASources, ATargets, 20, 'QuerySecurity');
AddMapping(ASources, ATargets, 21, 'SetSecurity');
AddMapping(ASources, ATargets, 22, 'Power');
AddMapping(ASources, ATargets, 23, 'SystemControl');
AddMapping(ASources, ATargets, 24, 'DeviceChange');
AddMapping(ASources, ATargets, 25, 'QueryQuota');
AddMapping(ASources, ATargets, 26, 'SetQuota');
AddMapping(ASources, ATargets, 27, 'PnP');
end;
Else Result := Inherited GetPossibleValues(ASources, ATargets, ABitmask);
end;
end;
(** TIRPCompletionRequestFilter **)
Constructor TIRPCompletionRequestFilter.Create(AName:WideString);
begin
Inherited Create(AName, ertIRPCompletion);
end;
Function TIRPCompletionRequestFilter.GetPossibleValues(ASources:TList<UInt64>; ATargets:TList<WideString>; Var ABitmask:Boolean):Boolean;
begin
ABitmask := False;
Result := True;
Case RequestListModelColumnValueTypes[Ord(FField)] Of
rlmcvtMajorFunction : begin
AddMapping(ASources, ATargets, 0, 'Create');
AddMapping(ASources, ATargets, 1, 'CreateNamedPipe');
AddMapping(ASources, ATargets, 2, 'Close');
AddMapping(ASources, ATargets, 3, 'Read');
AddMapping(ASources, ATargets, 4, 'Write');
AddMapping(ASources, ATargets, 5, 'Query');
AddMapping(ASources, ATargets, 6, 'Set');
AddMapping(ASources, ATargets, 7, 'QueryEA');
AddMapping(ASources, ATargets, 8, 'SetEA');
AddMapping(ASources, ATargets, 9, 'Flush');
AddMapping(ASources, ATargets, 10, 'QueryVolume');
AddMapping(ASources, ATargets, 11, 'SetVolume');
AddMapping(ASources, ATargets, 12, 'DirectoryControl');
AddMapping(ASources, ATargets, 13, 'FSControl');
AddMapping(ASources, ATargets, 14, 'DeviceControl');
AddMapping(ASources, ATargets, 15, 'InternalDeviceControl');
AddMapping(ASources, ATargets, 16, 'Shutdown');
AddMapping(ASources, ATargets, 17, 'Lock');
AddMapping(ASources, ATargets, 18, 'Cleanup');
AddMapping(ASources, ATargets, 19, 'CreateMailslot');
AddMapping(ASources, ATargets, 20, 'QuerySecurity');
AddMapping(ASources, ATargets, 21, 'SetSecurity');
AddMapping(ASources, ATargets, 22, 'Power');
AddMapping(ASources, ATargets, 23, 'SystemControl');
AddMapping(ASources, ATargets, 24, 'DeviceChange');
AddMapping(ASources, ATargets, 25, 'QueryQuota');
AddMapping(ASources, ATargets, 26, 'SetQuota');
AddMapping(ASources, ATargets, 27, 'PnP');
end;
Else Result := Inherited GetPossibleValues(ASources, ATargets, ABitmask);
end;
end;
End.
|
unit uPlotStyles;
{
*****************************************************************************
* This file is part of Multiple Acronym Math and Audio Plot - MAAPlot *
* *
* See the file COPYING. *
* for details about the copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
* MAAplot for Lazarus/fpc *
* (C) 2014 Stefan Junghans *
*****************************************************************************
}
interface
uses
Graphics, Types, uPlotClass, GraphMath,
LCLType, IntfGraphics, FPimage, FPCanvas; // lazcanvas
type
TPointStyleShape = (shapeDot, shapeCircle, shapeSquareSolid, shapeSquare, shapeCross, shapePlus, shapeMarkerTriangle);
{ TPlotStyles }
TPlotStyle = class(uPlotClass.TPlotStyleBase)
private
procedure SetBrush(const AValue: TBrush);
procedure SetFont(const AValue: TFont);
procedure SetPen(const AValue: TPen);
function GetTextHeight(AText: String; ACanvas: TCanvas): Integer;
function GetTextWidth(AText: String; ACanvas: TCanvas): Integer;
// for Dataimage:
procedure ClipDrawPixel(X, Y: Integer; ADataImage: TLazIntfImage; AColor: TColor);
procedure ClipDrawPixel(X, Y: Integer; ADataImage: TLazIntfImage; AFPColor: TFPColor; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false);
// Note: AlphaBlend does alphablending like in TLazINtfImage (alpha untouched, check this)
// AlphaMergeOnly additively merges alpha channels but draws full AFPColors !
procedure ClipDrawLineold(A, B: TPoint; ALineWidth: Integer; ADataImage: TLazIntfImage; AColor: TColor);
procedure ClipDrawLine(A, B: TPoint; ALineWidth: Integer; ADataImage: TLazIntfImage; AColor: TColor);
procedure ClipDrawLine(A, B: TPoint; ALineWidth: Integer; ADataImage: TLazIntfImage; AFPColor: TFPColor; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false);
protected
FBrush: TBrush;
FColor: TColor;
FFont: TFont;
FPen: TPen;
procedure DrawCircleEx(Pt: TPoint; ADataImage: TLazIntfImage; AColor: TColor; Filled: Boolean; ADiameter: Integer);
procedure DrawCircleEx(Pt: TPoint; ADataImage: TLazIntfImage; AFPColor: TFPColor; Filled: Boolean; ADiameter: Integer; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false);
procedure SetColor(const AValue: TColor); virtual;
procedure DrawPoint(Pt: TPoint; Canvas: TCanvas); override; overload;
procedure DrawPoint(Pt: TPoint; Canvas: TCanvas; AColor: TColor); override; overload;
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage); override; overload;
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage; AColor: TColor); override; overload;
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage; AFPColor: TFPColor; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false); override;overload;
public
constructor Create; override;
destructor Destroy; override;
property Color: TColor read FColor write SetColor;
property Pen: TPen read FPen; //write SetPen; use assign instead !
property Font: TFont read FFont; //write SetFont;
property Brush: TBrush read FBrush; //write SetBrush;
property TextHeigth[AText: String; ACanvas: TCanvas]: Integer read GetTextHeight;
property TextWidth[AText: String; ACanvas: TCanvas]: Integer read GetTextWidth;
procedure DrawText(X,Y: Integer; AText: String; ACanvas: TCanvas);
procedure DrawTextEx(X, Y: Integer; Angle: Double; AText: String;
ACanvas: TCanvas);
end;
{ TSeriesStyle }
TSeriesStyle = class(uPlotStyles.TPlotStyle)
private
FOwnerSeries: uPlotClass.TPlotSeriesBase;
procedure SetOwnerSeries(ASeries: uPlotClass.TPlotSeriesBase);
protected
procedure DrawSamplePoint(Pt: TPoint; Canvas: TCanvas; BeginNew: Boolean); override;
public
property OwnerSeries: uPlotClass.TPlotSeriesBase read FOwnerSeries write SetOwnerSeries;
end;
{ TSeriesStylePoints }
TSeriesStylePoints = class(uPlotStyles.TSeriesStyle)
private
FDiameter: Integer;
FShape: TPointStyleShape;
procedure SetDiameter(const AValue: Integer);
procedure DrawCircle(Pt: TPoint; Canvas: TCanvas; AColor: TColor; Filled: Boolean);
// LazintFImage with TColor
procedure DrawCircle(Pt: TPoint; ADataImage: TLazIntfImage; AColor: TColor; Filled: Boolean);
// LazINtfImage with TFPColor
procedure DrawCircle(Pt: TPoint; ADataImage: TLazIntfImage; AFPColor: TFPColor; Filled: Boolean; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false);
//
procedure DrawSquare(Pt: TPoint; Canvas: TCanvas; AColor: TColor; Filled: Boolean); // TODO: overload for DataImage
procedure DrawCross(Pt: TPoint; Canvas: TCanvas; AColor: TColor); // TODO: overload for DataImage
procedure DrawPlus(Pt: TPoint; Canvas: TCanvas; AColor: TColor); // TODO: overload for DataImage
procedure DrawMarkerTriangle(Pt: TPoint; Canvas: TCanvas; AColor: TColor; Filled: Boolean); // TODO: overload for DataImage
protected
FLastSamplePt: TPoint;
procedure DrawPoint(Pt: TPoint; Canvas: TCanvas); override; overload;
procedure DrawPoint(Pt: TPoint; Canvas: TCanvas; AColor: TColor); override; overload;
// overloads for drawing on TLazIntfImage
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage); override; overload;
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage; AColor: TColor); override; overload;
// overloads for drawing on TLazIntfImage with FPColor (01.08.14)
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage; AFPColor: TFPColor; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false); override;overload;
//
procedure DrawSamplePoint(Pt: TPoint; Canvas: TCanvas; BeginNew: Boolean); override;
public
constructor Create; override;
property Diameter: Integer read FDiameter write SetDiameter;
property Shape: TPointStyleShape read FShape write FShape;
end;
{ TSeriesStyleLines }
TSeriesStyleLines = class(uPlotStyles.TSeriesStylePoints)
private
FLineWidth: Integer;
procedure SetLineWidth(const AValue: Integer);
protected
procedure DrawPoint(Pt: TPoint; Canvas: TCanvas); override; overload;
procedure DrawPoint(Pt: TPoint; Canvas: TCanvas; AColor: TColor); override; overload;
// overloads for drawing on TLazIntfImage
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage); override; overload;
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage; AColor: TColor); override; overload;
// LazINtfImage with TFPColor
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage; AFPColor: TFPColor; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false);override;overload;
procedure DrawSamplePoint(Pt: TPoint; Canvas: TCanvas; BeginNew: Boolean); override;
public
constructor Create; override;
property LineWidth: Integer read FLineWidth write SetLineWidth;
end;
{ TAxisStyle }
TAxisStyle = class(uPlotStyles.TPlotStyle)
private
FPenInnerGrid: TPen;
procedure SetPenInnerGrid(const AValue: TPen);
protected
procedure SetColor(const AValue: TColor); override;
procedure DrawPoint(Pt: TPoint; Canvas: TCanvas); override;
public
constructor Create; override;
destructor Destroy; override;
procedure DrawInnerGridLine(ptA, ptB: TPoint; Canvas: TCanvas);
procedure DrawLine(ptA, ptB: TPoint; Canvas: TCanvas);
procedure DrawLine(ptA, ptB: TPoint; ADataImage: TLazIntfImage; AFPColor: TFPColor); // not used by now 08.08.14!
property PenInnerGrid: TPen read FPenInnerGrid write SetPenInnerGrid;
end;
const
TPointStyleShapeName : array[shapeDot..shapeMarkerTriangle] of String = (
'Dot', 'Circle', 'Square solid', 'Square', 'Cross', 'Plus', 'MarkerTriangle');
implementation
uses
uPlotSeries;
resourcestring
S_PointStyleNotImplemented = 'This PointStyle is not yet implemented.'#13#10+
'Please use Dot instead';
{ TPlotStyle }
// *********************************************************************
procedure TPlotStyle.SetBrush(const AValue: TBrush);
begin
if FBrush=AValue then exit;
FBrush:=AValue;
end;
procedure TPlotStyle.SetColor(const AValue: TColor);
begin
if FColor=AValue then exit;
FColor:=AValue;
Pen.Color := Color;
Brush.Color := Color;
Font.Color := Color;
end;
procedure TPlotStyle.SetFont(const AValue: TFont);
begin
if FFont=AValue then exit;
FFont:=AValue;
end;
procedure TPlotStyle.SetPen(const AValue: TPen);
begin
if FPen=AValue then exit;
FPen:=AValue;
end;
function TPlotStyle.GetTextHeight(AText: String; ACanvas: TCanvas): Integer;
begin
//ACanvas.Pen := Pen;
//ACanvas.Font := Font;
Result := ACanvas.TextHeight(AText);
end;
function TPlotStyle.GetTextWidth(AText: String; ACanvas: TCanvas): Integer;
begin
//ACanvas.Pen := Pen;
//ACanvas.Font := Font;
Result := ACanvas.TextWidth(AText);
end;
procedure TPlotStyle.ClipDrawPixel(X, Y: Integer; ADataImage: TLazIntfImage;
AColor: TColor);
begin
IF (X >= 0) and (X <= ADataImage.Width-1) and (Y >= 0) and (Y <= ADataImage.Height-1) THEN
ADataImage.TColors[X, Y] := AColor;
end;
procedure TPlotStyle.ClipDrawPixel(X, Y: Integer; ADataImage: TLazIntfImage;
AFPColor: TFPColor; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false);
var
vAlpha, vInverseAlpha: Word;
CurColor: TFPColor;
begin
IF (X >= 0) and (X <= ADataImage.Width-1) and (Y >= 0) and (Y <= ADataImage.Height-1) THEN
//ADataImage.TColors[X, Y] := AColor;
BEGIN
if (not AAlphaBlend) and (not AAlphaMergeOnly) then
ADataImage.Colors[X, Y] := AFPColor
else
begin
// TODO: this is from LazIntfImage... is this correct blending ?
vAlpha := AFPColor.alpha;
vInverseAlpha := $FFFF - vAlpha;
if vAlpha = $FFFF then
begin
ADataImage.Colors[X, Y] := AFPColor;
end
else if vAlpha > $00 then
begin
if AAlphaBlend then begin // TODO: why is Alpha untouched with AlphaBlend ??
CurColor := ADataImage.Colors[X, Y];
CurColor.Red := Round(
CurColor.Red * vInverseAlpha / $FFFF +
AFPColor.Red * vAlpha / $FFFF);
CurColor.Green := Round(
CurColor.Green * vInverseAlpha / $FFFF +
AFPColor.Green * vAlpha / $FFFF);
CurColor.Blue := Round(
CurColor.Blue * vInverseAlpha / $FFFF +
AFPColor.Blue * vAlpha / $FFFF);
ADataImage.Colors[X, Y] := CurColor;
end else begin // here is AAlphaMergeOnly ;
CurColor := ADataImage.Colors[X, Y];
CurColor.Red := AFPColor.Red;
CurColor.Green := AFPColor.green;
CurColor.Blue := AFPColor.blue;
// new 02.08.ju: merge alpha channels otherwise alpha stays as background(=0)
CurColor.alpha := $FFFF - (round( ($FFFF - CurColor.alpha) / $FFFF + vInverseAlpha)) DIV 2;
ADataImage.Colors[X, Y] := CurColor;
end;
end;
end;
END;
end;
procedure TPlotStyle.ClipDrawLineold(A, B: TPoint; ALineWidth: Integer; ADataImage: TLazIntfImage;
AColor: TColor);
{var
vX, vY: Integer;
vLoop: Integer;
vTempPoint: TPoint;
//begin
// -----------------------------------
procedure DrawSolidLine (ADataImage: TLazIntfImage; x1,y1, x2,y2:integer; const color:TColor);
//var PutPixelProc : TPutPixelProc; // see also PixTools
procedure HorizontalLine (x1,x2,y:integer);
var x, vLoopWidth : integer;
begin
for x := x1 to x2 do
//PutPixelProc (Canv, x,y, color);
//ClipDrawPixel(x,y, ADataImage, color);
IF LineWidth = 1 THEN
ClipDrawPixel(x,y, ADataImage, color) ELSE BEGIN
for vLoopWidth := (-LineWidth DIV 2) to (LineWidth DIV 2) do
ClipDrawPixel(x,y+vLoopWidth, ADataImage, color);
END;
end;
procedure VerticalLine (x,y1,y2:integer);
var y, vLoopWidth : integer;
begin
for y := y1 to y2 do
//PutPixelProc (Canv, x,y, color);
//ClipDrawPixel(x,y, ADataImage, color);
IF LineWidth = 1 THEN
ClipDrawPixel(x,y, ADataImage, color) ELSE BEGIN
for vLoopWidth := (-LineWidth DIV 2) to (LineWidth DIV 2) do
ClipDrawPixel(x+vLoopWidth,y, ADataImage, color);
END;
end;
procedure SlopedLine;
var npixels,xinc1,yinc1,xinc2,yinc2,dx,dy,d,dinc1,dinc2, vLoopWidth : integer;
procedure initialize;
begin // precalculations
dx := abs(x2-x1);
dy := abs(y2-y1);
if dx > dy then // determining independent variable
begin // x is independent
npixels := dx + 1;
d := (2 * dy) - dx;
dinc1 := dy * 2;
dinc2:= (dy - dx) * 2;
xinc1 := 1;
xinc2 := 1;
yinc1 := 0;
yinc2 := 1;
end
else
begin // y is independent
npixels := dy + 1;
d := (2 * dx) - dy;
dinc1 := dx * 2;
dinc2:= (dx - dy) * 2;
xinc1 := 0;
xinc2 := 1;
yinc1 := 1;
yinc2 := 1;
end;
// going into the correct direction
if x1 > x2 then
begin
xinc1 := - xinc1;
xinc2 := - xinc2;
end;
if y1 > y2 then
begin
yinc1 := - yinc1;
yinc2 := - yinc2;
end;
end;
var r,x,y : integer;
begin
initialize;
x := x1;
y := y1;
for r := 1 to nPixels do
begin
//PutPixelProc (Canv, x,y, color);
IF LineWidth = 1 THEN
ClipDrawPixel(x,y, ADataImage, color) ELSE BEGIN
for vLoopWidth := (-LineWidth DIV 2) to (LineWidth DIV 2) do begin
IF dx > dy THEN ClipDrawPixel(x,y+vLoopWidth, ADataImage, color)
ELSE ClipDrawPixel(x+vLoopWidth,y, ADataImage, color) END;
END;
if d < 0 then
begin
d := d + dinc1;
x := x + xinc1;
y := y + yinc1;
end
else
begin
d := d + dinc2;
x := x + xinc2;
y := y + yinc2;
end;
end;
end;
begin
//with canv.pen do
// case mode of
// pmMerge : PutPixelProc := @PutPixelAnd;
// pmMask : PutPixelProc := @PutPixelOr;
// pmXor : PutPixelProc := @PutPixelXor;
// else PutPixelProc := @PutPixelCopy;
// end;
if x1 = x2 then // vertical line
if y1 < y2 then
VerticalLine (x1, y1, y2)
else
VerticalLine (x1, y2, y1)
else if y1 = y2 then
if x1 < x2 then
HorizontalLine (x1, x2, y1)
else
HorizontalLine (x2, x1, y1)
else // sloped line
SlopedLine;
end;
// -----------------------------------
}
begin
//DrawSolidLine(ADataImage, A.x, A.y, B.x,B.y, AColor);
ClipDrawLine(A, B, ALineWidth, ADataImage, AColor);
end;
procedure TPlotStyle.ClipDrawLine(A, B: TPoint; ALineWidth: Integer; ADataImage: TLazIntfImage;
AColor: TColor);
var
dx,dy: Integer;
vXleading: Boolean;
vLoop: Integer;
vX1, vX2: Integer;
vY1, vY2: Integer;
vPoint: TPoint;
begin
dx := (B.X-A.X);
dy := (B.Y-A.Y);
IF (dx = 0) and (dy = 0 ) THEN begin
ClipDrawPixel(A.X, A.Y, ADataImage,AColor);
exit;
end;
IF abs(dx) > abs(dy) THEN vXleading := TRUE ELSE vXleading := FALSE;
IF vXleading THEN BEGIN
IF B.X > A.X THEN begin
vX1 := A.X;
vY1 := A.Y;
vX2 := B.X;
end else begin
vX1 := B.X;
vY1 := B.Y;
vX2 := A.X;
end;
for vLoop := vX1 to vX2 do begin
vY2 := trunc(dy/dx * (vLoop-vX1) + 1) + vY1;
vPoint.X := vLoop; vPoint.Y := vY2;
DrawCircleEx(vPoint, ADataImage, AColor, TRUE, ALineWidth);
end;
END ELSE BEGIN
IF B.Y > A.Y THEN begin
vY1 := A.Y;
vX1 := A.X;
vY2 := B.Y;
end else begin
vY1 := B.Y;
vX1 := B.X;
vY2 := A.Y;
end;
for vLoop := vY1 to vY2 do begin
vX2 := trunc(dx/dy * (vLoop-vY1)) + vX1;
vPoint.X := vX2; vPoint.Y := vLoop;
DrawCircleEx(vPoint, ADataImage, AColor, TRUE, ALineWidth);
end;
END;
end;
procedure TPlotStyle.ClipDrawLine(A, B: TPoint; ALineWidth: Integer; ADataImage: TLazIntfImage;
AFPColor: TFPColor; AAlphaBlend: Boolean; AAlphaMergeOnly: Boolean);
var
dx,dy: Integer;
vXleading: Boolean;
vLoop: Integer;
vX1, vX2: Integer;
vY1, vY2: Integer;
vPoint: TPoint;
begin
dx := (B.X-A.X);
dy := (B.Y-A.Y);
IF (dx = 0) and (dy = 0 ) THEN begin
ClipDrawPixel(A.X, A.Y, ADataImage,AFPColor, AAlphaBlend, AAlphaMergeOnly);
exit;
end;
IF abs(dx) > abs(dy) THEN vXleading := TRUE ELSE vXleading := FALSE;
IF vXleading THEN BEGIN
IF B.X > A.X THEN begin
vX1 := A.X;
vY1 := A.Y;
vX2 := B.X;
end else begin
vX1 := B.X;
vY1 := B.Y;
vX2 := A.X;
end;
for vLoop := vX1 to vX2 do begin
vY2 := trunc(dy/dx * (vLoop-vX1) + 1) + vY1;
vPoint.X := vLoop; vPoint.Y := vY2;
DrawCircleEx(vPoint, ADataImage, AFPColor, TRUE, ALineWidth, AAlphaBlend, AAlphaMergeOnly);
end;
END ELSE BEGIN
IF B.Y > A.Y THEN begin
vY1 := A.Y;
vX1 := A.X;
vY2 := B.Y;
end else begin
vY1 := B.Y;
vX1 := B.X;
vY2 := A.Y;
end;
for vLoop := vY1 to vY2 do begin
vX2 := trunc(dx/dy * (vLoop-vY1)) + vX1;
vPoint.X := vX2; vPoint.Y := vLoop;
DrawCircleEx(vPoint, ADataImage, AFPColor, TRUE, ALineWidth, AAlphaBlend, AAlphaMergeOnly);
end;
END;
end;
procedure TPlotStyle.DrawCircleEx(Pt: TPoint; ADataImage: TLazIntfImage;
AColor: TColor; Filled: Boolean; ADiameter: Integer);
var
vRadius, vRy: Integer;
vLoop, vLoopy: Integer;
vLastY: Integer;
begin
CASE ADiameter of
0: exit;
1,2: ClipDrawPixel(Pt.X, Pt.Y, ADataImage, AColor);
3,4: begin
ClipDrawPixel(Pt.X-1, Pt.Y, ADataImage, AColor);
ClipDrawPixel(Pt.X+1, Pt.Y, ADataImage, AColor);
ClipDrawPixel(Pt.X, Pt.Y-1, ADataImage, AColor);
ClipDrawPixel(Pt.X, Pt.Y+1, ADataImage, AColor);
if Filled then begin
ClipDrawPixel(Pt.X, Pt.Y, ADataImage, AColor);
end;
end;
5: begin
ClipDrawPixel(Pt.X-2, Pt.Y, ADataImage, AColor);
ClipDrawPixel(Pt.X+2, Pt.Y, ADataImage, AColor);
ClipDrawPixel(Pt.X-1, Pt.Y-1, ADataImage, AColor);
ClipDrawPixel(Pt.X+1, Pt.Y-1, ADataImage, AColor);
ClipDrawPixel(Pt.X, Pt.Y-2, ADataImage, AColor);
ClipDrawPixel(Pt.X-1, Pt.Y+1, ADataImage, AColor);
ClipDrawPixel(Pt.X+1, Pt.Y+1, ADataImage, AColor);
ClipDrawPixel(Pt.X, Pt.Y+2, ADataImage, AColor);
if Filled then begin
ClipDrawPixel(Pt.X, Pt.Y, ADataImage, AColor); ;
ClipDrawPixel(Pt.X-1, Pt.Y, ADataImage, AColor);
ClipDrawPixel(Pt.X+1, Pt.Y, ADataImage, AColor);
ClipDrawPixel(Pt.X, Pt.Y-1, ADataImage, AColor);
ClipDrawPixel(Pt.X, Pt.Y+1, ADataImage, AColor);
end;
end;
END;
IF ADiameter < 6 THEN exit ELSE BEGIN
vRadius := ADiameter DIV 2;
vLastY := vRadius;
IF Filled THEN BEGIN
for vLoop := -vRadius to vRadius do begin
vRy := trunc( sqrt( sqr(vRadius) - sqr(vLoop)));
for vLoopy := -vRy to vRy do ClipDrawPixel(Pt.x+ vLoop, Pt.y+vLoopy, ADataImage, AColor);
end;
END ELSE BEGIN
for vLoop := 0 to vRadius do begin
vRy := round( sqrt( sqr(vRadius) - sqr(vLoop)));
for vLoopy := vLastY downto vRy do begin
ClipDrawPixel(Pt.x+ vLoop, Pt.y-vLoopy, ADataImage, AColor); // Q1
ClipDrawPixel(Pt.x- vLoop, Pt.y-vLoopy, ADataImage, AColor); // Q2
ClipDrawPixel(Pt.x- vLoop, Pt.y+vLoopy, ADataImage, AColor); // Q3
ClipDrawPixel(Pt.x+ vLoop, Pt.y+vLoopy, ADataImage, AColor); // Q4
end;
vLastY := vRy;
end;
END;
END;
end;
procedure TPlotStyle.DrawCircleEx(Pt: TPoint; ADataImage: TLazIntfImage;
AFPColor: TFPColor; Filled: Boolean; ADiameter: Integer;
AAlphaBlend: Boolean; AAlphaMergeOnly: Boolean);
var
vRadius, vRy: Integer;
vLoop, vLoopy: Integer; // TODO FPColor
vLastY: Integer;
begin
CASE ADiameter of
0: exit;
1,2: ClipDrawPixel(Pt.X, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
3,4: begin
ClipDrawPixel(Pt.X-1, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X+1, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X, Pt.Y-1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X, Pt.Y+1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
if Filled then begin
ClipDrawPixel(Pt.X, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
end;
end;
5: begin
ClipDrawPixel(Pt.X-2, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X+2, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X-1, Pt.Y-1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X+1, Pt.Y-1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X, Pt.Y-2, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X-1, Pt.Y+1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X+1, Pt.Y+1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X, Pt.Y+2, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
if Filled then begin
ClipDrawPixel(Pt.X, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X-1, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X+1, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X, Pt.Y-1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
ClipDrawPixel(Pt.X, Pt.Y+1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
end;
end;
END;
IF ADiameter < 6 THEN exit ELSE BEGIN
vRadius := ADiameter DIV 2;
vLastY := vRadius;
IF Filled THEN BEGIN
for vLoop := -vRadius to vRadius do begin
vRy := trunc( sqrt( sqr(vRadius) - sqr(vLoop)));
for vLoopy := -vRy to vRy do ClipDrawPixel(Pt.x+ vLoop, Pt.y+vLoopy, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
end;
END ELSE BEGIN
for vLoop := 0 to vRadius do begin
vRy := round( sqrt( sqr(vRadius) - sqr(vLoop)));
for vLoopy := vLastY downto vRy do begin
ClipDrawPixel(Pt.x+ vLoop, Pt.y-vLoopy, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); // Q1
ClipDrawPixel(Pt.x- vLoop, Pt.y-vLoopy, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); // Q2
ClipDrawPixel(Pt.x- vLoop, Pt.y+vLoopy, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); // Q3
ClipDrawPixel(Pt.x+ vLoop, Pt.y+vLoopy, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); // Q4
end;
vLastY := vRy;
end;
END;
END;
end;
procedure TPlotStyle.DrawPoint(Pt: TPoint; Canvas: TCanvas);
begin
//Canvas.Pixels[Pt.X, Pt.Y] := FColor;
DrawPoint(Pt, Canvas, FColor);
end;
procedure TPlotStyle.DrawPoint(Pt: TPoint; Canvas: TCanvas; AColor: TColor);
begin
Canvas.Pixels[Pt.X, Pt.Y] := AColor;
end;
procedure TPlotStyle.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage);
begin
DrawPoint(Pt, ADataImage, FColor);
end;
procedure TPlotStyle.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage;
AColor: TColor);
begin
//ADataImage.TColors[Pt.X, Pt.Y] := AColor;
ClipDrawPixel(Pt.x, Pt.y, ADataImage, AColor);
end;
procedure TPlotStyle.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage;
AFPColor: TFPColor; AAlphaBlend: Boolean; AAlphaMergeOnly: Boolean = false);
begin
ClipDrawPixel(Pt.x, Pt.y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
end;
constructor TPlotStyle.Create;
begin
inherited Create;
FColor := clBlack;
FPen := TPen.Create;
FPen.Width := 1;
FPen.Style := psSolid;
FPen.Color := clBlack;
FFont := TFont.Create;
Font.Color:= clBlack;
Font.Size := 10;
FBrush:= TBrush.Create;
FBrush.Style:=bsSolid;
FBrush.Color:= clBlack;
end;
destructor TPlotStyle.Destroy;
begin
FPen.Free;
FFont.Free;
FBrush.Free;
inherited Destroy;
end;
procedure TPlotStyle.DrawText(X, Y: Integer; AText: String; ACanvas: TCanvas);
begin
DrawTextEx(X, Y, 0, AText, ACanvas);
end;
procedure TPlotStyle.DrawTextEx(X, Y: Integer; Angle: Double; AText: String; ACanvas: TCanvas);
var vBrush: TBrush;
begin
//ACanvas.Pen := Pen;
vBrush := TBrush.Create;
try
vBrush.Assign(ACanvas.Brush);
try
ACanvas.Brush.Color := clNone;
ACanvas.Brush.Style := bsClear;
ACanvas.Font := Font;
ACanvas.Font.Orientation := Round(Angle * 10);
ACanvas.TextOut(x,y,AText);
finally ACanvas.Brush.Assign(vBrush); end;
finally vBrush.Free; end;
end;
{ TAxisStyle }
// *********************************************************************
procedure TAxisStyle.SetPenInnerGrid(const AValue: TPen);
begin
if FPen=AValue then exit;
FPen:=AValue;
end;
procedure TAxisStyle.SetColor(const AValue: TColor);
begin
inherited SetColor(AValue);
PenInnerGrid.Color := Color;
end;
constructor TAxisStyle.Create;
begin
inherited Create;
FPenInnerGrid := TPen.Create;
PenInnerGrid.Width := 1;
PenInnerGrid.Style := psDot;
PenInnerGrid.Color := clBlack;
end;
destructor TAxisStyle.Destroy;
begin
FPenInnerGrid.Free;
inherited Destroy;
end;
procedure TAxisStyle.DrawInnerGridLine(ptA, ptB: TPoint; Canvas: TCanvas);
begin
Canvas.Pen.Assign(Self.PenInnerGrid);
Canvas.Line(ptA, ptB);
end;
procedure TAxisStyle.DrawPoint(Pt: TPoint; Canvas: TCanvas);
begin
Canvas.Pen.Assign(TPlotStyle(Self).Pen);
inherited DrawPoint(Pt, Canvas);
end;
procedure TAxisStyle.DrawLine(ptA, ptB: TPoint; Canvas: TCanvas);
begin
Canvas.Pen.Assign(uPlotStyles.TPlotStyle(Self).Pen);
Canvas.Line(ptA, ptB);
end;
procedure TAxisStyle.DrawLine(ptA, ptB: TPoint; ADataImage: TLazIntfImage;
AFPColor: TFPColor);
begin
ClipDrawLine(ptA, ptB, 1, ADataImage, AFPColor, false, false);
end;
{ TSeriesStylePoints }
// *********************************************************************
procedure TSeriesStylePoints.SetDiameter(const AValue: Integer);
begin
if FDiameter=AValue then exit;
IF odd(AValue) THEN FDiameter:=AValue ELSE FDiameter := AValue-1; // round down to odd number
end;
procedure TSeriesStylePoints.DrawCircle(Pt: TPoint; Canvas: TCanvas;
AColor: TColor; Filled: Boolean);
var
vRadius: Integer;
begin
CASE Diameter of
0: exit;
1: Canvas.Pixels[Pt.X, Pt.Y] := AColor;
3: begin
Canvas.Pixels[Pt.X-1, Pt.Y] := AColor;
Canvas.Pixels[Pt.X+1, Pt.Y] := AColor;
Canvas.Pixels[Pt.X, Pt.Y-1] := AColor;
Canvas.Pixels[Pt.X, Pt.Y+1] := AColor;
if Filled then begin
Canvas.Pixels[Pt.X, Pt.Y] := AColor;
end;
end;
5: begin
Canvas.Pixels[Pt.X-2, Pt.Y] := AColor;
Canvas.Pixels[Pt.X+2, Pt.Y] := AColor;
Canvas.Pixels[Pt.X-1, Pt.Y-1] := AColor;
Canvas.Pixels[Pt.X+1, Pt.Y-1] := AColor;
Canvas.Pixels[Pt.X, Pt.Y-2] := AColor;
Canvas.Pixels[Pt.X-1, Pt.Y+1] := AColor;
Canvas.Pixels[Pt.X+1, Pt.Y+1] := AColor;
Canvas.Pixels[Pt.X, Pt.Y+2] := AColor;
if Filled then begin
Canvas.Pixels[Pt.X, Pt.Y] := AColor;
Canvas.Pixels[Pt.X-1, Pt.Y] := AColor;
Canvas.Pixels[Pt.X+1, Pt.Y] := AColor;
Canvas.Pixels[Pt.X, Pt.Y-1] := AColor;
Canvas.Pixels[Pt.X, Pt.Y+1] := AColor;
end;
end;
END;
IF Diameter < 6 THEN exit ELSE BEGIN
vRadius := Diameter DIV 2;
Canvas.Pen.Color := AColor;
Canvas.Pen.Width := 1;
Canvas.Pen.Mode := pmCopy;
//Canvas.Pen.Assign(TPlotStyle(Self).Pen);
// set brush for filled ellipse
IF Filled THEN BEGIN
Canvas.Brush := Brush;
Canvas.Brush.Color:=AColor;
END ELSE Canvas.Brush.Style := bsClear;
//Canvas.Brush.Assign(TPlotStyle(Self).Brush);
Canvas.Ellipse(Pt.X-vRadius, Pt.Y-vRadius, Pt.X+vRadius, Pt.Y+vRadius); // we do not use EllipseC as radius is integer and we dont know if diameter is odd then
END;
end;
procedure TSeriesStylePoints.DrawCircle(Pt: TPoint; ADataImage: TLazIntfImage;
AColor: TColor; Filled: Boolean); // TODO: implement
begin
DrawCircleEx(Pt, ADataImage, AColor, Filled, Diameter);
end;
procedure TSeriesStylePoints.DrawCircle(Pt: TPoint; ADataImage: TLazIntfImage;
AFPColor: TFPColor; Filled: Boolean; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false);
begin
DrawCircleEx(Pt, ADataImage, AFPColor, Filled, Diameter, AAlphaBlend, AAlphaMergeOnly);
end;
procedure TSeriesStylePoints.DrawSquare(Pt: TPoint; Canvas: TCanvas;
AColor: TColor; Filled: Boolean);
var vRadius: Integer;
begin
vRadius := Diameter DIV 2;
//raise EPlot.CreateRes(@S_PointStyleNotImplemented);
// set pen properties
Canvas.Pen.Color := AColor;
Canvas.Pen.Width := (Diameter DIV 8) + 1;
Canvas.Pen.Mode := pmCopy;
// set brush properties
IF Filled THEN BEGIN
Canvas.Brush := Brush;
Canvas.Brush.Color:=AColor;
END ELSE Canvas.Brush.Style := bsClear;
Canvas.Rectangle(Pt.X - vRadius, Pt.Y - vRadius, Pt.X + vRadius, Pt.Y + vRadius);
end;
procedure TSeriesStylePoints.DrawCross(Pt: TPoint; Canvas: TCanvas;
AColor: TColor);
var vRadius: Integer;
begin
CASE Diameter of
0: exit;
1: Canvas.Pixels[Pt.X, Pt.Y] := AColor;
3: begin
Canvas.Pixels[Pt.X, Pt.Y] := AColor;
Canvas.Pixels[Pt.X-1, Pt.Y-1] := AColor;
Canvas.Pixels[Pt.X+1, Pt.Y-1] := AColor;
Canvas.Pixels[Pt.X-1, Pt.Y+1] := AColor;
Canvas.Pixels[Pt.X+1, Pt.Y+1] := AColor;
end;
5: begin
Canvas.Pixels[Pt.X, Pt.Y] := AColor;
Canvas.Pixels[Pt.X-1, Pt.Y-1] := AColor;
Canvas.Pixels[Pt.X+1, Pt.Y-1] := AColor;
Canvas.Pixels[Pt.X-1, Pt.Y+1] := AColor;
Canvas.Pixels[Pt.X+1, Pt.Y+1] := AColor;
Canvas.Pixels[Pt.X-2, Pt.Y-2] := AColor;
Canvas.Pixels[Pt.X+2, Pt.Y-2] := AColor;
Canvas.Pixels[Pt.X-2, Pt.Y+2] := AColor;
Canvas.Pixels[Pt.X+2, Pt.Y+2] := AColor;
end;
END;
IF Diameter < 6 THEN exit ELSE BEGIN
vRadius := Diameter DIV 2;
Canvas.Pen.Color := AColor;
Canvas.Pen.Width := (Diameter DIV 8) + 1;
Canvas.Pen.Mode := pmCopy;
Canvas.Line(Pt.X - vRadius, Pt.Y - vRadius, Pt.X + vRadius, Pt.Y + vRadius);
Canvas.Line(Pt.X - vRadius, Pt.Y + vRadius, Pt.X + vRadius, Pt.Y - vRadius);
END;
end;
procedure TSeriesStylePoints.DrawPlus(Pt: TPoint; Canvas: TCanvas;
AColor: TColor);
var vRadius: Integer;
begin
CASE Diameter of
0: exit;
1: Canvas.Pixels[Pt.X, Pt.Y] := AColor;
3: begin
Canvas.Pixels[Pt.X, Pt.Y] := AColor;
Canvas.Pixels[Pt.X, Pt.Y-1] := AColor;
Canvas.Pixels[Pt.X, Pt.Y+1] := AColor;
Canvas.Pixels[Pt.X-1, Pt.Y] := AColor;
Canvas.Pixels[Pt.X+1, Pt.Y] := AColor;
end;
5: begin
Canvas.Pixels[Pt.X, Pt.Y] := AColor;
Canvas.Pixels[Pt.X, Pt.Y-1] := AColor;
Canvas.Pixels[Pt.X, Pt.Y+1] := AColor;
Canvas.Pixels[Pt.X-1, Pt.Y] := AColor;
Canvas.Pixels[Pt.X+1, Pt.Y] := AColor;
Canvas.Pixels[Pt.X-2, Pt.Y] := AColor;
Canvas.Pixels[Pt.X+2, Pt.Y] := AColor;
Canvas.Pixels[Pt.X, Pt.Y-2] := AColor;
Canvas.Pixels[Pt.X, Pt.Y+2] := AColor;
end;
END;
IF Diameter < 6 THEN exit ELSE BEGIN
vRadius := Diameter DIV 2;
Canvas.Pen.Color := AColor;
Canvas.Pen.Width := (Diameter DIV 8) + 1;
Canvas.Pen.Mode := pmCopy;
Canvas.Line(Pt.X - vRadius, Pt.Y, Pt.X + vRadius, Pt.Y);
Canvas.Line(Pt.X, Pt.Y + vRadius, Pt.X, Pt.Y - vRadius);
END;
end;
procedure TSeriesStylePoints.DrawMarkerTriangle(Pt: TPoint; Canvas: TCanvas;
AColor: TColor; Filled: Boolean);
var vPointArray: array of TPoint;
begin
//raise EPlot.CreateRes(@S_PointStyleNotImplemented);
// set pen properties
Canvas.Pen.Color := AColor;
Canvas.Pen.Width := (Diameter DIV 8) + 1;
Canvas.Pen.Mode := pmCopy;
// set brush properties
IF Filled THEN BEGIN
Canvas.Brush := Brush;
Canvas.Brush.Color:=AColor;
END ELSE Canvas.Brush.Style := bsClear;
setlength(vPointArray, 3);
vPointArray[0].X := Pt.X;
vPointArray[0].Y := Pt.Y;
vPointArray[1].X := Pt.X - (Diameter DIV 2); // cos 30°
vPointArray[1].Y := Pt.Y - Diameter; // sin 60° is 0,86 not 1 so we are 14% high
vPointArray[2].X := Pt.X + (Diameter DIV 2); // cos 30°
vPointArray[2].Y := Pt.Y - Diameter;
Canvas.Polygon(vPointArray); // other overloaded funcs available
end;
constructor TSeriesStylePoints.Create;
begin
inherited Create;
FDiameter := 1;
FShape := shapeDot;
end;
procedure TSeriesStylePoints.DrawPoint(Pt: TPoint; Canvas: TCanvas);
begin
//inherited DrawPoint(Pt, Canvas); // TODO: use colored routine instead and call with AColor = FColor
DrawPoint(Pt, Canvas, Color);
end;
procedure TSeriesStylePoints.DrawPoint(Pt: TPoint; Canvas: TCanvas; AColor: TColor
);
begin
// we have (Dot, Circle, Square, Cross, Plus, MarkerTriangle)
IF Diameter = 0 THEN exit;
CASE Shape OF
shapeDot: BEGIN
DrawCircle(Pt, Canvas, AColor, TRUE);
END;
shapeCircle: BEGIN
DrawCircle(Pt, Canvas, AColor, FALSE);
END;
shapeSquare: BEGIN
DrawSquare(Pt, Canvas, AColor, FALSE);
END;
shapeSquareSolid: BEGIN
DrawSquare(Pt, Canvas, AColor, TRUE);
END;
shapeCross: BEGIN
DrawCross(Pt, Canvas, AColor);
END;
shapePlus: BEGIN
DrawPlus(Pt, Canvas, AColor);
END;
shapeMarkerTriangle: BEGIN
DrawMarkerTriangle(Pt, Canvas, AColor, FALSE);
END;
END;
end;
procedure TSeriesStylePoints.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage);
begin
DrawPoint(Pt, ADataImage, FColor);
end;
procedure TSeriesStylePoints.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage;
AColor: TColor);
begin
// we have (Dot, Circle, Square, Cross, Plus, MarkerTriangle)
IF Diameter = 0 THEN exit;
CASE Shape OF
shapeDot: BEGIN
DrawCircle(Pt, ADataImage, AColor, TRUE);
END;
shapeCircle: BEGIN
DrawCircle(Pt, ADataImage, AColor, FALSE);
END;
//shapeSquare: BEGIN
// DrawSquare(Pt, ADataImage, AColor, FALSE);
// END;
//shapeSquareSolid: BEGIN
// DrawSquare(Pt, ADataImage, AColor, TRUE);
// END;
//shapeCross: BEGIN
// DrawCross(Pt, ADataImage, AColor);
// END;
//shapePlus: BEGIN
// DrawPlus(Pt, ADataImage, AColor);
// END;
//shapeMarkerTriangle: BEGIN
// DrawMarkerTriangle(Pt, ADataImage, AColor, FALSE);
// END;
ELSE
DrawCircle(Pt, ADataImage, AColor, TRUE);
END;
// attention: only point(circle) and line is implemented for drawing on TLazINtfImage !
end;
procedure TSeriesStylePoints.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage;
AFPColor: TFPColor; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false);
begin
// we have (Dot, Circle, Square, Cross, Plus, MarkerTriangle)
IF Diameter = 0 THEN exit;
CASE Shape OF
shapeDot: BEGIN
DrawCircle(Pt, ADataImage, AFPColor, TRUE, AAlphaBlend, AAlphaMergeOnly);
END;
shapeCircle: BEGIN
DrawCircle(Pt, ADataImage, AFPColor, FALSE, AAlphaBlend, AAlphaMergeOnly);
END;
//shapeSquare: BEGIN
// DrawSquare(Pt, ADataImage, AFPColor, FALSE);
// END;
//shapeSquareSolid: BEGIN
// DrawSquare(Pt, ADataImage, AFPColor, TRUE);
// END;
//shapeCross: BEGIN
// DrawCross(Pt, ADataImage, AFPColor);
// END;
//shapePlus: BEGIN
// DrawPlus(Pt, ADataImage, AFPColor);
// END;
//shapeMarkerTriangle: BEGIN
// DrawMarkerTriangle(Pt, ADataImage, AFPColor, FALSE);
// END;
ELSE
DrawCircle(Pt, ADataImage, AFPColor, TRUE, AAlphaBlend, AAlphaMergeOnly);
END;
// attention: only point(circle) and line is implemented for drawing on TLazINtfImage !
end;
procedure TSeriesStylePoints.DrawSamplePoint(Pt: TPoint; Canvas: TCanvas;
BeginNew: Boolean);
begin
DrawPoint(Pt, Canvas, Color);
end;
{ TSeriesStyle }
procedure TSeriesStyle.SetOwnerSeries(ASeries: uPlotClass.TPlotSeriesBase);
begin
if FOwnerSeries=ASeries then exit;
FOwnerSeries:=ASeries;
end;
procedure TSeriesStyle.DrawSamplePoint(Pt: TPoint; Canvas: TCanvas;
BeginNew: Boolean);
begin
DrawPoint(Pt, Canvas);
end;
{ TSeriesStyleLines }
procedure TSeriesStyleLines.SetLineWidth(const AValue: Integer);
begin
if FLineWidth=AValue then exit;
FLineWidth:=AValue;
Pen.Width := FLineWidth;
IF FLineWidth > 1 THEN Pen.Cosmetic := FALSE ELSE Pen.Cosmetic := TRUE;
end;
constructor TSeriesStyleLines.Create;
begin
inherited Create;
FLineWidth := 1;
FDiameter := 0;
end;
procedure TSeriesStyleLines.DrawPoint(Pt: TPoint; Canvas: TCanvas);
begin
//inherited DrawPoint(Pt, Canvas); // TODO: check this ??
DrawPoint(Pt, Canvas, FColor);
end;
procedure TSeriesStyleLines.DrawPoint(Pt: TPoint; Canvas: TCanvas;
AColor: TColor);
var
vPt2: TPoint; // interpolated point
vError: Integer;
begin
inherited DrawPoint(Pt, Canvas, AColor); // this draws points also, but diameter can be set to 0
//new version
vError := TPlotSeries(OwnerSeries).GetLineEndpoint(vPt2);
IF (vError < 0) OR (vPt2 = Pt) THEN exit;
Canvas.Pen.Style := TPlotStyle(Self).Pen.Style;
//Canvas.Pen.Cosmetic := Pen.Cosmetic;
Canvas.Pen.EndCap := pecFlat;
Canvas.Pen.Width := Pen.Width;
Canvas.Pen.Color := AColor;
Canvas.Line(vPt2, Pt)
end;
procedure TSeriesStyleLines.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage);
begin
DrawPoint(Pt, ADataImage, FColor);
end;
procedure TSeriesStyleLines.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage;
AColor: TColor);
begin
DrawPoint(Pt, ADataImage, TColorToFPColor(AColor), false, false);
end;
procedure TSeriesStyleLines.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage;
AFPColor: TFPColor; AAlphaBlend: Boolean; AAlphaMergeOnly: Boolean);
var
vPt2: TPoint;
vError: Integer;
begin
inherited DrawPoint(Pt, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
vError := TPlotSeries(OwnerSeries).GetLineEndpoint(vPt2);
IF (vError < 0) OR (vPt2 = Pt) THEN exit;
ClipDrawLine(Pt, vPt2, LineWidth, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
end;
procedure TSeriesStyleLines.DrawSamplePoint(Pt: TPoint; Canvas: TCanvas; BeginNew: Boolean);
begin
inherited DrawPoint(Pt, Canvas, TPlotStyle(Self).Color); // this draws points also, but diameter can be set to 0
Canvas.Pen.Assign(TPlotStyle(Self).Pen);
Canvas.Pen.Color:=TPlotStyle(Self).Color;
IF BeginNew THEN FLastSamplePt := Pt;
Canvas.Line(FLastSamplePt, Pt);
FLastSamplePt := Pt;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OpenGL, Menus, StdCtrls;
type
TForm1 = class(TForm)
MainMenu1: TMainMenu;
N1: TMenuItem;
N2: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure N2Click(Sender: TObject);
procedure N1Click(Sender: TObject);
private
{ Private declarations }
hrc: HGLRC;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
//Процедура заповнення полів структури PIXELFORMATDESCRIPTOR
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPIXELFORMATDESCRIPTOR; // данні формату пікселів
nPixelFormat : Integer;
Begin
With pfd do begin
nSize := sizeof (TPIXELFORMATDESCRIPTOR); // розмір структури
nVersion := 1; // номер версії
dwFlags := PFD_DRAW_TO_WINDOW OR PFD_SUPPORT_OPENGL OR PFD_DOUBLEBUFFER;
// множина бітових прапорців, що визначають пристрій та інтерфейс
iPixelType := PFD_TYPE_RGBA; // режим для зображення кольорів
cColorBits := 16; // число бітових площин в кожному буфері кольору
cDepthBits := 32; // розмір буфера глибини (вісь z)
iLayerType := PFD_MAIN_PLANE;// тип площини
end;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
// запит до системи - чи підтримується обраний формат пікселів
SetPixelFormat (hdc, nPixelFormat, @pfd);
// встановлюємо формат пікселів в контексті пристрою
End;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetDCPixelFormat(Canvas.Handle);// встановлюємо формат пікселів
hrc := wglCreateContext(Canvas.Handle);//створюємо контекст відтворення
wglMakeCurrent(Canvas.Handle, hrc);//встановлюємо контекст відтворення
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0); // звільняємо контекст відтворення
wglDeleteContext (hrc); // видалення контексту OpenGL
end;
procedure TForm1.FormPaint(Sender: TObject);
var ps: PAINTSTRUCT;
begin
BeginPaint(Self.Handle,ps);
glLoadIdentity; //Заміна матриці одиничною
glTranslatef(0.0, 0.0, -10.0);
{Власне побудова малюнка в OpenGL}
glClearColor(0.1, 0.4, 0.0, 1.0); //Визначення кольору фону - зелений
glClear(GL_COLOR_BUFFER_BIT); //Встановлення кольору фону
glColor(0.0,0.0,0.7,1.0); //Встановлюємо колір малювання - синій
glPointSize(10); //Встановлюємо розмір точки
glLineWidth(15.0); //Встановлюємо ширину лінії
glBegin(GL_LINES); //Будуємо лінію(ліве око)
glVertex2d(-2.8, 1.5);
glVertex2d(-1.9, 1.5);
glEnd;
glBegin(GL_LINES); //Будуємо лінію(праве око)
glVertex2d(0.4, 1.5);
glVertex2d(1.7, 1.5);
glEnd;
glColor(0.8,0.0,0.0,1.0); //Встановлюємо колір малювання - червоний
glBegin(GL_LINES); //Будуємо лінії(обличчя)
glVertex2d(-3.8, 1.6);
glVertex2d(-2.3, -2.5);
glEnd;
glBegin(GL_LINES); //Будуємо лінії(обличчя)
glVertex2d(-2.3, -2.5);
glVertex2d(2.0, -2.5);
glEnd;
glBegin(GL_LINES); //Будуємо лінії(обличчя)
glVertex2d(2.0, -2.5);
glVertex2d(3.1, 1.6);
glEnd;
glColor(1.0,1.0,0.0,1.0); //Встановлюємо колір малювання - жовтий
glBegin(GL_TRIANGLES); //Будуємо трикутник
glVertex2d(-0.7, 1.6);
glVertex2d(-1.8, -1.5);
glVertex2d(1.3, -1.5);
glEnd;
SwapBuffers(Canvas.Handle);
EndPaint(Self.Handle,ps);
end;
procedure TForm1.FormResize(Sender: TObject);
begin
glMatrixMode(GL_PROJECTION); //Даною матрицею встановлюється матриця проекцій
glLoadIdentity; //Заміна даної матриці одиничною
gluPerspective(30.0, Width/Height, 1.0, 15.0);
//Визначення зрізаного конуса видимості у видовій системі координат. Перші 2 параметри
//задають кути видимості відносно вісей х та у, а останні 2 параметри - ближню та
//дальню границі видимости
glViewport(0, 0, Width, Height); //Визначення області видимості
glMatrixMode(GL_MODELVIEW); //Даною матрицею встановлюється видова матриця
InvalidateRect(Handle, nil, False); //Принудительная перерисовка формы
end;
procedure TForm1.N2Click(Sender: TObject);
begin
close;
end;
procedure TForm1.N1Click(Sender: TObject);
begin
showmessage('Автор програми: студент групи КВ-92 Степанюк Михайло Федорович');
end;
end.
|
unit com.example.android.accelerometerplay;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*}
interface
uses
java.util,
android.os,
android.app,
android.content,
android.view,
android.graphics,
android.hardware;
type
//A particle system is just a collection of particles
ParticleSystem = class
private
const NUM_PARTICLES = 3;
var mBalls: array of Particle := new Particle[NUM_PARTICLES];
method updatePositions(sx, sy: Single; timestamp: LongInt);
var mView: SimulationView;
public
constructor(v: SimulationView);
method update(sx, sy: Single; now: LongInt);
property ParticleCount: Integer read mBalls.length;
property PosX[i: Integer]: Single read mBalls[i].PosX;
property PosY[i: Integer]: Single read mBalls[i].PosY;
end;
implementation
constructor ParticleSystem(v: SimulationView);
begin
mView := v;
{*
* Initially our particles have no speed or acceleration
*}
for i: Integer := 0 to mBalls.length-1 do
mBalls[i] := new Particle(mView);
end;
{*
* Update the position of each particle in the system using the
* Verlet integrator.
*}
method ParticleSystem.updatePositions(sx, sy: Single; timestamp: LongInt);
begin
var t := timestamp;
if mView.LastT <> 0 then
begin
var dT := Single((t - mView.LastT) * (1.0 / 1000000000.0));
if mView.LastDeltaT <> 0 then
begin
var dTC := dT / mView.LastDeltaT;
for i: Integer := 0 to mBalls.length - 1 do
mBalls[i].computePhysics(sx, sy, dT, dTC)
end;
mView.LastDeltaT := dT
end;
mView.LastT := t
end;
{*
* Performs one iteration of the simulation. First updating the
* position of all the particles and resolving the constraints and
* collisions.
*}
method ParticleSystem.update(sx, sy: Single; now: LongInt);
const
NUM_MAX_ITERATIONS = 10;
MinSpringSpeed = 0.05;
begin
// update the system's positions
updatePositions(sx, sy, now);
// We do no more than a limited number of iterations
{*
* Resolve collisions, each particle is tested against every
* other particle for collision. If a collision is detected the
* particle is moved away using a virtual spring of infinite
* stiffness.
*}
var more := true;
var count := mBalls.length;
for k: Integer := 0 to NUM_MAX_ITERATIONS - 1 do
begin
if not more then
break;
more := false;
for i: Integer := 0 to count - 1 do
begin
var curr := mBalls[i];
for j: Integer := i + 1 to count - 1 do
begin
var ball := mBalls[j];
var dx := ball.PosX - curr.PosX;
var dy := ball.PosY - curr.PosY;
var dd := dx * dx + dy * dy;
// Check for collisions
if dd < SimulationView.sBallDiameter2 then
begin
//add a little bit of entropy, after all nothing is
//perfect in the universe.
//if (ball.Speed > MinSpringSpeed) or (curr.Speed > MinSpringSpeed) then
begin
dx := dx + (Single(Math.random) - 0.5) * 0.0001;
dy := dy + (Single(Math.random) - 0.5) * 0.0001;
end;
dd := dx * dx + dy * dy;
// simulate the spring
var d := Single(Math.sqrt(dd));
var c := (0.5 * (SimulationView.sBallDiameter - d)) / d;
curr.PosX := curr.PosX - (dx * c);
curr.PosY := curr.PosY - (dy * c);
ball.PosX := ball.PosX + (dx * c);
ball.PosY := ball.PosY + (dy * c);
more := true
end;
end;
{*
* Finally make sure the particle doesn't intersects
* with the walls.
*}
curr.resolveCollisionWithBounds;
end;
end;
end;
end. |
//------------------------------------------------------------------------------
//Version UNIT
//------------------------------------------------------------------------------
// What it does-
// Holds our version value for easy access. MUST be updated to match the
// current Revision committed for each commit.
//
// Changes -
// December 22nd, 2006 - RaX - Created Header.
// [2007/03/28] CR - Updated description of the unit.
//
//------------------------------------------------------------------------------
unit Version;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
var
HeliosVersion : String = 'Helios Ragnarok Server Version 0.0.2.690';
implementation
end.
|
unit UConfigIni;
interface
uses
System.SysUtils;
type
TConfigIni = class
private
FCaminhoBD: string;
FPortBD: Integer;
FPasswordBD: string;
FSenhaServ: string;
FHostBD: string;
FUsuarioBD: string;
FUsuarioServ: string;
FPortaServ: string;
FDriverID: string;
public
constructor Create;
destructor Destroy; override;
procedure WriteIni;
procedure ReadIni;
property DriverID: string read FDriverID write FDriverID;
property CaminhoBD: string read FCaminhoBD write FCaminhoBD;
property UsuarioBD: string read FUsuarioBD write FUsuarioBD;
property PasswordBD: string read FPasswordBD write FPasswordBD;
property HostBD: string read FHostBD write FHostBD;
property PortBD: Integer read FPortBD write FPortBD;
property PortaServ: string read FPortaServ write FPortaServ;
property UsuarioServ: string read FUsuarioServ write FUsuarioServ;
property SenhaServ: string read FSenhaServ write FSenhaServ;
end;
implementation
uses
System.IniFiles;
{ TConfigIni }
procedure TConfigIni.WriteIni;
var
arquivoIni: TIniFile;
begin
if not DirectoryExists('C:\MaxSystemConfig') then
begin
ForceDirectories('C:\MaxSystemConfig');
end;
if FileExists('C:\MaxSystemConfig\ConfiguracaoRemota.ini') then
begin
arquivoIni := TIniFile.Create('C:\MaxSystemConfig\ConfiguracaoRemota.ini');
try
if (FDriverID <> 'FB') then
FDriverID := 'FB';
arquivoIni.WriteString('config', 'Driver', FDriverID);
arquivoIni.WriteString('config', 'Caminho', Trim(FCaminhoBD));
arquivoIni.WriteString('config', 'User', FUsuarioBD);
arquivoIni.WriteString('config', 'Key', FPasswordBD);
arquivoIni.WriteString('config', 'Server', FHostBD);
arquivoIni.WriteString('config', 'Port', IntToStr(FPortBD));
arquivoIni.WriteString('config', 'UserSv', FUsuarioServ);
arquivoIni.WriteString('config', 'KeySv', FSenhaServ);
arquivoIni.WriteString('config', 'PortSv', FPortaServ);
finally
arquivoIni.Free;
end;
end;
end;
constructor TConfigIni.Create;
begin
end;
destructor TConfigIni.Destroy;
begin
inherited;
end;
procedure TConfigIni.ReadIni;
var
arquivoIni: TIniFile;
begin
if FileExists('C:\MaxSystemConfig\ConfiguracaoRemota.ini') then
begin
arquivoIni := TIniFile.Create('C:\MaxSystemConfig\ConfiguracaoRemota.ini');
try
FDriverID := arquivoIni.ReadString('config', 'Driver', 'FB');
FCaminhoBD := arquivoIni.ReadString('config', 'Caminho', '');
FUsuarioBD := arquivoIni.ReadString('config', 'User', '');
FPasswordBD := arquivoIni.ReadString('config', 'Key', '');
FHostBD := arquivoIni.ReadString('config', 'Server', '');
FPortBD := StrToInt( arquivoIni.ReadString('config', 'Port', '0') );
FPortaServ := arquivoIni.ReadString('config', 'PortSv', '');
FUsuarioServ := arquivoIni.ReadString('config', 'UserSv', '');
FSenhaServ := arquivoIni.ReadString('config', 'KeySv', '');
FPortaServ := arquivoIni.ReadString('config', 'PortSv', '');
finally
arquivoIni.Free;
end;
end;
end;
end.
|
//
// Generated by JavaToPas v1.4 20140526 - 133610
////////////////////////////////////////////////////////////////////////////////
unit org.apache.http.impl.conn.tsccm.WaitingThread;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
org.apache.http.impl.conn.tsccm.RouteSpecificPool;
type
JWaitingThread = interface;
JWaitingThreadClass = interface(JObjectClass)
['{2D188A7F-924F-46B0-8A17-8D252F89BA2C}']
function await(deadline : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $1
function getCondition : JCondition; cdecl; // ()Ljava/util/concurrent/locks/Condition; A: $11
function getPool : JRouteSpecificPool; cdecl; // ()Lorg/apache/http/impl/conn/tsccm/RouteSpecificPool; A: $11
function getThread : JThread; cdecl; // ()Ljava/lang/Thread; A: $11
function init(cond : JCondition; pool : JRouteSpecificPool) : JWaitingThread; cdecl;// (Ljava/util/concurrent/locks/Condition;Lorg/apache/http/impl/conn/tsccm/RouteSpecificPool;)V A: $1
procedure interrupt ; cdecl; // ()V A: $1
procedure wakeup ; cdecl; // ()V A: $1
end;
[JavaSignature('org/apache/http/impl/conn/tsccm/WaitingThread')]
JWaitingThread = interface(JObject)
['{FD60386F-0342-42A9-8E91-679623BEB8D0}']
function await(deadline : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $1
procedure interrupt ; cdecl; // ()V A: $1
procedure wakeup ; cdecl; // ()V A: $1
end;
TJWaitingThread = class(TJavaGenericImport<JWaitingThreadClass, JWaitingThread>)
end;
implementation
end.
|
unit uTefDedicadoInterface;
interface
uses classes, uTEFTypes;
type
TTefDedicadoInterface = class(TComponent)
private
FOnExecutaComando11: TExecutaComando;
FOnExecutaComando13: TExecutaComando;
FOnExecutaComando12: TExecutaComando;
FOnExecutaComando1: TExecutaComandoMsg;
FOnExecutaComando3: TExecutaComandoMsg;
FOnExecutaComando2: TExecutaComandoMsg;
FOnExecutaComando22: TExecutaComandoMsg;
FOnLimpaMsg: TNotifyEvent;
public
published
property OnExecutaComando1: TExecutaComandoMsg read FOnExecutaComando1 write FOnExecutaComando1;
property OnExecutaComando2: TExecutaComandoMsg read FOnExecutaComando2 write FOnExecutaComando2;
property OnExecutaComando3: TExecutaComandoMsg read FOnExecutaComando3 write FOnExecutaComando3;
property OnExecutaComando22: TExecutaComandoMsg read FOnExecutaComando22 write FOnExecutaComando22;
property OnExecutaComando11: TExecutaComando read FOnExecutaComando11 write FOnExecutaComando11;
property OnExecutaComando12: TExecutaComando read FOnExecutaComando12 write FOnExecutaComando12;
property OnExecutaComando13: TExecutaComando read FOnExecutaComando13 write FOnExecutaComando13;
property OnLimpaMsg: TNotifyEvent read FOnLimpaMsg write FOnLimpaMsg;
procedure DoExecutaComando11(Sender: TObject);
procedure DoExecutaComando13(Sender: TObject);
procedure DoExecutaComando12(Sender: TObject);
procedure DoExecutaComando1(Sender: TObject; Msg: String);
procedure DoExecutaComando3(Sender: TObject; Msg: String);
procedure DoExecutaComando2(Sender: TObject; Msg: String);
procedure DoExecutaComando22(Sender: TObject; Msg: String);
procedure DoLimpaMsg(Sender: TObject);
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('MainRetail', [TTefDedicadoInterface]);
end;
{ TTefDedicadoInterface }
procedure TTefDedicadoInterface.DoExecutaComando1(Sender: TObject; Msg: String);
begin
if Assigned(FOnExecutaComando1) then
FOnExecutaComando1(Sender, Msg);
end;
procedure TTefDedicadoInterface.DoExecutaComando11(Sender: TObject);
begin
if Assigned(FOnExecutaComando11) then
FOnExecutaComando11(Sender);
end;
procedure TTefDedicadoInterface.DoExecutaComando12(Sender: TObject);
begin
if Assigned(FOnExecutaComando12) then
FOnExecutaComando12(Sender);
end;
procedure TTefDedicadoInterface.DoExecutaComando13(Sender: TObject);
begin
if Assigned(FOnExecutaComando13) then
FOnExecutaComando13(Sender);
end;
procedure TTefDedicadoInterface.DoExecutaComando2(Sender: TObject; Msg: String);
begin
if Assigned(FOnExecutaComando2) then
FOnExecutaComando2(Sender, Msg);
end;
procedure TTefDedicadoInterface.DoExecutaComando22(Sender: TObject; Msg: String);
begin
if Assigned(FOnExecutaComando22) then
FOnExecutaComando22(Sender, Msg);
end;
procedure TTefDedicadoInterface.DoExecutaComando3(Sender: TObject; Msg: String);
begin
if Assigned(FOnExecutaComando3) then
FOnExecutaComando3(Sender, Msg);
end;
procedure TTefDedicadoInterface.DoLimpaMsg(Sender: TObject);
begin
if Assigned(FOnLimpaMsg) then
FOnLimpaMsg(Sender);
end;
end.
|
unit Results;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Grids;
type
TResForm = class(TForm)
pnBottom: TPanel;
bbOK: TButton;
sgResults: TStringGrid;
procedure bbOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ResForm: TResForm;
implementation
{$R *.DFM}
procedure TResForm.bbOKClick(Sender: TObject);
begin
ResForm.ModalResult:=1;
end;
procedure TResForm.FormCreate(Sender: TObject);
begin
With sgResults Do
Begin
Cells [0,0]:= 'Задание';
Cells [1,0]:= 'Всего';
Cells [2,0]:= 'Сделано';
Cells [3,0]:= 'Осталось';
Cells [4,0]:= 'Ошибок';
Cells [0,1]:= 'Восьмиричное кодирование';
Cells [0,2]:= 'Восьмиричное декодирование';
Cells [0,3]:= 'Шестнадцатиричное кодирование';
Cells [0,4]:= 'Шестнадцатиричное декодирование';
Cells [0,5]:= 'Двоично-десятичное кодирование';
Cells [0,6]:= 'Двоично-десятичное декодирование';
Cells [0,7]:= 'Целое без знака (кодирование)';
Cells [0,8]:= 'Целое без знака (декодирование)';
Cells [0,9]:= 'Целое со знаком (кодирование)';
Cells [0,10]:= 'Целое со знаком (декодирование)';
Cells [0,11]:= 'С фиксированной запятой (кодирование)';
Cells [0,12]:= 'С фиксированной запятой (декодирование)';
Cells [0,13]:= 'С плавающей запятой (кодирование)';
Cells [0,14]:= 'С плавающей запятой (декодирование)';
Cells [0,15]:= 'Логическое умножение';
Cells [0,16]:= 'Логическое сложение';
Cells [0,17]:= 'Сложение по модулю 2';
Cells [0,18]:= 'Смена знака числа';
Cells [0,19]:= 'Арифметическое сложение';
Cells [0,20]:= 'Арифметическое вычитание';
End;
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 083239
////////////////////////////////////////////////////////////////////////////////
unit java.nio.file.FileVisitor;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.nio.file.FileVisitResult,
java.nio.file.attribute.BasicFileAttributes,
java.io.IOException;
type
JFileVisitor = interface;
JFileVisitorClass = interface(JObjectClass)
['{9BC018E2-C3BA-42F9-8ABF-EE574D2D48C3}']
function postVisitDirectory(JObjectparam0 : JObject; JIOExceptionparam1 : JIOException) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/io/IOException;)Ljava/nio/file/FileVisitResult; A: $401
function preVisitDirectory(JObjectparam0 : JObject; JBasicFileAttributesparam1 : JBasicFileAttributes) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/nio/file/attribute/BasicFileAttributes;)Ljava/nio/file/FileVisitResult; A: $401
function visitFile(JObjectparam0 : JObject; JBasicFileAttributesparam1 : JBasicFileAttributes) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/nio/file/attribute/BasicFileAttributes;)Ljava/nio/file/FileVisitResult; A: $401
function visitFileFailed(JObjectparam0 : JObject; JIOExceptionparam1 : JIOException) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/io/IOException;)Ljava/nio/file/FileVisitResult; A: $401
end;
[JavaSignature('java/nio/file/FileVisitor')]
JFileVisitor = interface(JObject)
['{58A29BA6-A588-4144-95B4-E792EFE8CFCE}']
function postVisitDirectory(JObjectparam0 : JObject; JIOExceptionparam1 : JIOException) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/io/IOException;)Ljava/nio/file/FileVisitResult; A: $401
function preVisitDirectory(JObjectparam0 : JObject; JBasicFileAttributesparam1 : JBasicFileAttributes) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/nio/file/attribute/BasicFileAttributes;)Ljava/nio/file/FileVisitResult; A: $401
function visitFile(JObjectparam0 : JObject; JBasicFileAttributesparam1 : JBasicFileAttributes) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/nio/file/attribute/BasicFileAttributes;)Ljava/nio/file/FileVisitResult; A: $401
function visitFileFailed(JObjectparam0 : JObject; JIOExceptionparam1 : JIOException) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/io/IOException;)Ljava/nio/file/FileVisitResult; A: $401
end;
TJFileVisitor = class(TJavaGenericImport<JFileVisitorClass, JFileVisitor>)
end;
implementation
end.
|
namespace InterfacesSample;
interface
uses
System.Windows.Forms,
System.Drawing,
InterfacesSample.SampleClasses;
type
MainForm = class(System.Windows.Forms.Form)
{$REGION Windows Form Designer generated fields}
private
textBox1: System.Windows.Forms.TextBox;
button2: System.Windows.Forms.Button;
button1: System.Windows.Forms.Button;
components: System.ComponentModel.Container := nil;
method button1_Click(sender: System.Object; e: System.EventArgs);
method MainForm_Load(sender: System.Object; e: System.EventArgs);
method InitializeComponent;
{$ENDREGION}
protected
fButtonWithInfo: SampleButton;
fTextBoxWithInfo: SampleTextBox;
method Dispose(aDisposing: Boolean); override;
method GetVersionInfoString(aVersionInfo: IVersionInfo): String;
public
constructor;
class method Main;
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
InitializeComponent();
end;
method MainForm.Dispose(aDisposing: boolean);
begin
if aDisposing then begin
if assigned(components) then
components.Dispose();
end;
inherited Dispose(aDisposing);
end;
{$ENDREGION}
{$REGION Windows Form Designer generated code}
method MainForm.InitializeComponent;
begin
var resources: System.ComponentModel.ComponentResourceManager := new System.ComponentModel.ComponentResourceManager(typeOf(MainForm));
self.button1 := new System.Windows.Forms.Button();
self.button2 := new System.Windows.Forms.Button();
self.textBox1 := new System.Windows.Forms.TextBox();
self.SuspendLayout();
//
// button1
//
self.button1.Location := new System.Drawing.Point(8, 12);
self.button1.Name := 'button1';
self.button1.Size := new System.Drawing.Size(136, 23);
self.button1.TabIndex := 0;
self.button1.Text := 'Display Version Info';
self.button1.Click += new System.EventHandler(@self.button1_Click);
//
// button2
//
self.button2.Location := new System.Drawing.Point(8, 41);
self.button2.Name := 'button2';
self.button2.Size := new System.Drawing.Size(136, 23);
self.button2.TabIndex := 1;
self.button2.Text := 'Regular Button';
//
// textBox1
//
self.textBox1.Location := new System.Drawing.Point(150, 43);
self.textBox1.Name := 'textBox1';
self.textBox1.Size := new System.Drawing.Size(130, 20);
self.textBox1.TabIndex := 2;
self.textBox1.Text := 'Regular TextBox';
//
// MainForm
//
self.AutoScaleBaseSize := new System.Drawing.Size(5, 13);
self.ClientSize := new System.Drawing.Size(292, 79);
self.Controls.Add(self.textBox1);
self.Controls.Add(self.button2);
self.Controls.Add(self.button1);
self.FormBorderStyle := System.Windows.Forms.FormBorderStyle.FixedDialog;
self.Icon := (resources.GetObject('$this.Icon') as System.Drawing.Icon);
self.MaximizeBox := false;
self.Name := 'MainForm';
self.Text := 'Interfaces Sample';
self.Load += new System.EventHandler(@self.MainForm_Load);
self.ResumeLayout(false);
self.PerformLayout();
end;
{$ENDREGION}
{$REGION Application Entry Point}
[STAThread]
class method MainForm.Main;
begin
Application.EnableVisualStyles();
try
with lForm := new MainForm() do
Application.Run(lForm);
except
on E: Exception do begin
MessageBox.Show(E.Message);
end;
end;
end;
{$ENDREGION}
method MainForm.MainForm_Load(sender: System.Object; e: System.EventArgs);
begin
{ Creates the button and textbox that support IVersionInfo }
SuspendLayout();
try
fButtonWithInfo := new SampleButton();
fButtonWithInfo.Location := new System.Drawing.Point(70, 80);
fButtonWithInfo.Name := 'ButtonWithInfo';
fButtonWithInfo.Text := 'Button with VersionInfo';
fButtonWithInfo.Width := 150;
Controls.Add(fButtonWithInfo);
fTextBoxWithInfo := new SampleTextBox();
fTextBoxWithInfo.Location := new System.Drawing.Point(70, 120);
fTextBoxWithInfo.Name := 'TextBoxWithInfo';
fTextBoxWithInfo.Text := 'TextBox with VersionInfo';
fTextBoxWithInfo.Width := 150;
Controls.Add(fTextBoxWithInfo);
finally
ResumeLayout();
end;
end;
method MainForm.button1_Click(sender: System.Object; e: System.EventArgs);
const
CRLF = #13#10;
var
lInfo: String := 'The following controls support IVersionInfo:'+CRLF;
begin
{ Iterates through all the controls in the form that support IVersionInfo
and calls GetVersionInfoString on each of them.
Notice how the regular Button and TextBox are not included in this for each loop,
as they don't implement IVersionInfo. }
for each matching lVersionInfo: IVersionInfo in Controls do
lInfo := lInfo+GetVersionInfoString(lVersionInfo)+CRLF;
MessageBox.Show(lInfo);
end;
method MainForm.GetVersionInfoString(aVersionInfo: IVersionInfo): string;
begin
{ This method is a key example why the use of interfaces is essential in OO programming.
Without the use of interfaces, we could not have treated Button and TextBox descendants
as a unique type (IVersionInfo in this case) and we would have needed to write code such as:
method GetVersionInfoString(aControl : Control) : string;
begin
if (aControl is SampleControl)
then <use property (aControl as SampleControl).VersionInfo>
else if (aControl is SampleTextBox)
then <use property (aControl as SampleTextBox).VersionInfo>
etc.
end;
Interfaces break the dependencies with ancestors and allow us to treat objects as if they
were of the same type, regardless of their position in the class hierarchy.
}
result := String.Format('{0}: {1}, Version {2}.{3}',
[aVersionInfo.Name,
aVersionInfo.Description,
aVersionInfo.MajVersion.ToString,
aVersionInfo.MinVersion.ToString]);
end;
end. |
namespace com.example.android.bluetoothchat;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*}
interface
uses
java.io,
java.util,
android.bluetooth,
android.content,
android.os,
android.util,
android.widget;
type
BluetoothChatService = public class
private
// Debugging
const TAG = 'BluetoothChatService';
const D = true;
// Name for the SDP record when creating server socket
const NAME_SECURE = 'BluetoothChatSecure';
const NAME_INSECURE = 'BluetoothChatInsecure';
// Member fields
var mSecureAcceptThread: AcceptThread;
//NOTE: this thread won't get set up on Android versions that do not
//support Bluetooth insecure connections (they were introduced in
//Android 2.3.3 - API level 10)
var mInsecureAcceptThread: AcceptThread;
var mConnectedThread: ConnectedThread;
//NOTE: this field is not in the original Android SDK demo. It has been introduced to fix a
//bug whereby exiting the app recreates threads, which then get in the way if the app is
//restarted - the UI doesn't see new connections made by those old threads
var mStopping: Boolean := false;
// Member fields
var mAdapter: BluetoothAdapter; readonly;
var mConnectThread: ConnectThread;
var mHandler: Handler; readonly;
var mState: Integer;
// Unique UUID for this application
var MY_UUID_SECURE: UUID := UUID.fromString('fa87c0d0-afac-11de-8a39-0800200c9a66'); readonly;
var MY_UUID_INSECURE: UUID := UUID.fromString('8ce255c0-200a-11e0-ac64-0800200c9a66'); readonly;
method setState(state: Integer); locked;
method connectionFailed;
method connectionLost;
public
var mContext: Context;
// Constants that indicate the current connection state
const STATE_NONE = 0; // we're doing nothing
const STATE_LISTEN = 1; // now listening for incoming connections
const STATE_CONNECTING = 2; // now initiating an outgoing connection
const STATE_CONNECTED = 3; // now connected to a remote device
constructor (ctx: Context; hndlr: Handler);
method getState: Integer; locked;
method start; locked;
method connect(device: BluetoothDevice; secure: Boolean); locked;
method connected(socket: BluetoothSocket; device: BluetoothDevice; socketType: String); locked;
method stop; locked;
method &write(&out: array of SByte);
end;
/// <summary>
/// This thread runs while listening for incoming connections. It behaves
/// like a server-side client. It runs until a connection is accepted
/// (or until cancelled).
/// </summary>
AcceptThread nested in BluetoothChatService = public class(Thread)
private
var mService: BluetoothChatService;
// The local server socket
var mmServerSocket: BluetoothServerSocket; readonly;
var mSocketType: String;
public
constructor (service: BluetoothChatService; secure: Boolean);
method run; override;
method cancel;
end;
/// <summary>
/// This thread runs while attempting to make an outgoing connection
/// with a device. It runs straight through; the connection either
/// succeeds or fails.
/// </summary>
ConnectThread nested in BluetoothChatService = public class(Thread)
private
var mService: BluetoothChatService;
var mmSocket: BluetoothSocket; readonly;
var mmDevice: BluetoothDevice; readonly;
var mSocketType: String;
public
constructor (service: BluetoothChatService; device: BluetoothDevice; secure: Boolean);
method run; override;
method cancel;
end;
/// <summary>
/// This thread runs during a connection with a remote device.
/// It handles all incoming and outgoing transmissions.
/// </summary>
ConnectedThread nested in BluetoothChatService = public class(Thread)
private
var mService: BluetoothChatService;
var mmSocket: BluetoothSocket; readonly;
var mmInStream: InputStream; readonly;
var mmOutStream: OutputStream; readonly;
public
constructor (service: BluetoothChatService; socket: BluetoothSocket; socketType: String);
method run; override;
method cancel;
method &write(buffer: array of SByte);
end;
implementation
/// <summary>
/// Constructor. Prepares a new BluetoothChat session.
/// </summary>
/// <param name="ctx">The UI Activity Context</param>
/// <param name="hndlr">A Handler to send messages back to the UI Activity</param>
constructor BluetoothChatService(ctx: Context; hndlr: Handler);
begin
mAdapter := BluetoothAdapter.DefaultAdapter;
mState := STATE_NONE;
mHandler := hndlr;
mContext := ctx;
end;
/// <summary>
/// Set the current state of the chat connection
/// </summary>
/// <param name="state">An integer defining the current connection state</param>
method BluetoothChatService.setState(state: Integer);
begin
if D then
Log.d(TAG, 'setState() ' + mState + ' -> ' + state);
mState := state;
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, - 1).sendToTarget;
end;
/// <summary>
/// Indicate that the connection attempt failed and notify the UI Activity.
/// </summary>
method BluetoothChatService.connectionFailed;
begin
var msg: Message := mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
var bundle: Bundle := new Bundle();
bundle.putString(BluetoothChat.TOAST_MSG, 'Unable to connect device');
msg.Data := bundle;
mHandler.sendMessage(msg);
// Start the service over to restart listening mode
start;
end;
/// <summary>
/// Indicate that the connection was lost and notify the UI Activity.
/// </summary>
method BluetoothChatService.connectionLost;
begin
var msg: Message := mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
var bundle: Bundle := new Bundle();
bundle.putString(BluetoothChat.TOAST_MSG, 'Device connection was lost');
msg.Data := bundle;
mHandler.sendMessage(msg);
// Start the service over to restart listening mode
start;
end;
/// <summary>
/// Return the current connection state.
/// </summary>
/// <returns></returns>
method BluetoothChatService.getState: Integer;
begin
exit mState
end;
/// <summary>
/// Start the chat service. Specifically start AcceptThread to begin a
/// session in listening (server) mode. Called by the Activity onResume()
/// </summary>
method BluetoothChatService.start;
begin
if mStopping then
exit;
if D then
Log.d(TAG, 'start');
// Cancel any thread attempting to make a connection
if mConnectThread <> nil then
begin
mConnectThread.cancel;
mConnectThread := nil
end;
// Cancel any thread currently running a connection
if mConnectedThread <> nil then
begin
mConnectedThread.cancel;
mConnectedThread := nil
end;
setState(STATE_LISTEN);
// Start the thread to listen on a BluetoothServerSocket
if mSecureAcceptThread = nil then
begin
mSecureAcceptThread := new AcceptThread(self, true);
mSecureAcceptThread.start
end;
//NOTE: only set up the insecure connection thread if the Android
//version supports insecure connections
if Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1 then
if mInsecureAcceptThread = nil then
begin
mInsecureAcceptThread := new AcceptThread(self, false);
mInsecureAcceptThread.start
end;
end;
/// <summary>
/// Start the ConnectThread to initiate a connection to a remote device.
/// </summary>
/// <param name="device">The BluetoothDevice to connect</param>
/// <param name="secure">Socket Security type - Secure (true) , Insecure (false)</param>
method BluetoothChatService.connect(device: BluetoothDevice; secure: Boolean);
begin
if D then
Log.d(TAG, ('connect to: ' + device));
// Cancel any thread attempting to make a connection
if mState = STATE_CONNECTING then
begin
if mConnectThread <> nil then
begin
mConnectThread.cancel;
mConnectThread := nil
end
end;
// Cancel any thread currently running a connection
if mConnectedThread <> nil then
begin
mConnectedThread.cancel;
mConnectedThread := nil
end;
// Start the thread to connect with the given device
mConnectThread := new ConnectThread(self, device, secure);
mConnectThread.start;
setState(STATE_CONNECTING);
end;
/// <summary>
/// Start the ConnectedThread to begin managing a Bluetooth connection
/// </summary>
/// <param name="socket">The BluetoothSocket on which the connection was made</param>
/// <param name="device">The BluetoothDevice that has been connected</param>
/// <param name="socketType"></param>
method BluetoothChatService.connected(socket: BluetoothSocket; device: BluetoothDevice; socketType: String);
begin
if D then
Log.d(TAG, 'connected, Socket Type: ' + socketType);
// Cancel the thread that completed the connection
if mConnectThread <> nil then
begin
mConnectThread.cancel;
mConnectThread := nil
end;
// Cancel any thread currently running a connection
if mConnectedThread <> nil then
begin
mConnectedThread.cancel;
mConnectedThread := nil
end;
// Cancel the accept thread because we only want to connect to one device
if mSecureAcceptThread <> nil then
begin
mSecureAcceptThread.cancel;
mSecureAcceptThread := nil
end;
if mInsecureAcceptThread <> nil then
begin
mInsecureAcceptThread.cancel;
mInsecureAcceptThread := nil
end;
// Start the thread to manage the connection and perform transmissions
mConnectedThread := new ConnectedThread(self, socket, socketType);
mConnectedThread.start;
// Send the name of the connected device back to the UI Activity
var msg: Message := mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
var bundle: Bundle := new Bundle;
bundle.putString(BluetoothChat.DEVICE_NAME, device.Name);
msg.Data := bundle;
Log.i(TAG, 'Sending MESSAGE_DEVICE_NAME message');
mHandler.sendMessage(msg);
Log.i(TAG, 'Setting STATE_CONNECTED message');
setState(STATE_CONNECTED);
end;
/// <summary>
/// Stop all threads
/// </summary>
method BluetoothChatService.stop;
begin
if D then
Log.d(TAG, 'stop');
mStopping := true;
if mConnectThread <> nil then
begin
mConnectThread.cancel;
mConnectThread := nil
end;
if mConnectedThread <> nil then
begin
mConnectedThread.cancel;
mConnectedThread := nil
end;
if mSecureAcceptThread <> nil then
begin
mSecureAcceptThread.cancel;
mSecureAcceptThread := nil
end;
if mInsecureAcceptThread <> nil then
begin
mInsecureAcceptThread.cancel;
mInsecureAcceptThread := nil
end;
setState(STATE_NONE);
end;
/// <summary>
/// Write to the ConnectedThread in an unsynchronized manner
/// </summary>
/// <param name="out">The bytes to write</param>
method BluetoothChatService.&write(&out: array of SByte);
begin
// Create temporary object
var r: ConnectedThread;
// Synchronize a copy of the ConnectedThread
locking self do
begin
if mState <> STATE_CONNECTED then
exit;
r := mConnectedThread
end;
// Perform the write unsynchronized
r.&write(&out);
end;
/// <summary>
/// Write to the ConnectedThread in an unsynchronized manner
/// </summary>
/// <param name="out">The bytes to write</param>
/// <see>ConnectedThread#write(byte[])</see>
//TODO: seealso
constructor BluetoothChatService.AcceptThread(service: BluetoothChatService; secure: Boolean);
begin
mService := service;
var tmp: BluetoothServerSocket := nil;
mSocketType := if secure then 'Secure' else 'Insecure';
// Create a new listening server socket
try
if secure then
tmp := mService.mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, mService.MY_UUID_SECURE)
else
begin
//NOTE: extra check to make sure an API is not called
//on an Android version that does not support it
if Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1 then
tmp := mService.mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME_INSECURE, mService.MY_UUID_INSECURE)
else
Toast.makeText(mService.mContext, mService.mContext.String[R.string.no_insecure_support], Toast.LENGTH_LONG).show
end
except
on e: IOException do
Log.e(TAG, 'Socket Type: ' + mSocketType + ' - listen() failed', e)
end;
mmServerSocket := tmp;
end;
method BluetoothChatService.AcceptThread.run;
begin
if D then
Log.d(TAG, 'Socket Type: ' + mSocketType + ' BEGIN mAcceptThread ' + self);
Name := 'AcceptThread-' + mSocketType;
var socket: BluetoothSocket := nil;
// Listen to the server socket if we're not connected
while mService.mState <> STATE_CONNECTED do
begin
try
// This is a blocking call and will only return on a
// successful connection or an exception
socket := mmServerSocket.accept;
except
on e: IOException do
begin
Log.e(TAG, 'Socket Type: ' + mSocketType + ' - accept() failed', e);
break
end
end;
// If a connection was accepted
if socket <> nil then
locking mService do
case mService.mState of
STATE_LISTEN, STATE_CONNECTING:
// Situation normal. Start the connected thread.
mService.connected(socket, socket.RemoteDevice, mSocketType);
STATE_NONE, STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try
socket.close;
except
on e: IOException do
Log.e(TAG, 'Could not close unwanted socket', e)
end;
end
end;
if D then
Log.i(TAG, ('END mAcceptThread, socket Type: ' + mSocketType));
end;
method BluetoothChatService.AcceptThread.cancel;
begin
if D then
Log.d(TAG, 'Socket Type ' + mSocketType + ' - cancel ' + self);
try
mmServerSocket.close;
except
on e: IOException do
Log.e(TAG, 'Socket Type ' + mSocketType + ' - close() of server failed', e)
end;
end;
constructor BluetoothChatService.ConnectThread(service: BluetoothChatService; device: BluetoothDevice; secure: Boolean);
begin
mService := service;
mmDevice := device;
var tmp: BluetoothSocket := nil;
mSocketType := if secure then 'Secure' else 'Insecure';
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try
if secure then
tmp := device.createRfcommSocketToServiceRecord(mService.MY_UUID_SECURE)
else
begin
//NOTE: extra check to make sure an API is not called
//on an Android version that does not support it
if Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1 then
tmp := device.createInsecureRfcommSocketToServiceRecord(mService.MY_UUID_INSECURE)
else
Toast.makeText(mService.mContext, mService.mContext.String[R.string.no_insecure_support], Toast.LENGTH_LONG).show
end
except
on e: IOException do
Log.e(TAG, 'Socket Type: ' + mSocketType + ' - create() failed', e)
end;
mmSocket := tmp;
end;
method BluetoothChatService.ConnectThread.run;
begin
Log.i(TAG, 'BEGIN mConnectThread SocketType: ' + mSocketType);
Name := 'ConnectThread-' + mSocketType;
// Always cancel discovery because it will slow down a connection
mService.mAdapter.cancelDiscovery;
// Make a connection to the BluetoothSocket
try
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect;
except
on e: IOException do
begin
// Close the socket
try
mmSocket.close;
except
on e2: IOException do
Log.e(TAG, 'unable to close() ' + mSocketType + ' socket during connection failure', e2)
end;
mService.connectionFailed;
exit
end
end;
// Reset the ConnectThread because we're done
locking mService do
mService.mConnectThread := nil;
// Start the connected thread
mService.connected(mmSocket, mmDevice, mSocketType);
end;
method BluetoothChatService.ConnectThread.cancel;
begin
try
mmSocket.close;
except
on e: IOException do
Log.e(TAG, 'close() of connect ' + mSocketType + ' socket failed', e)
end;
end;
constructor BluetoothChatService.ConnectedThread(service: BluetoothChatService; socket: BluetoothSocket; socketType: String);
begin
Log.d(TAG, 'create ConnectedThread: ' + socketType);
Name := 'ConnectedThread-' + socketType;
mService := service;
mmSocket := socket;
var tmpIn: InputStream := nil;
var tmpOut: OutputStream := nil;
// Get the BluetoothSocket input and output streams
try
tmpIn := socket.InputStream;
tmpOut := socket.OutputStream;
except
on e: IOException do
Log.e(TAG, 'temp sockets not created', e)
end;
mmInStream := tmpIn;
mmOutStream := tmpOut;
end;
method BluetoothChatService.ConnectedThread.run;
begin
Log.i(TAG, 'BEGIN mConnectedThread');
var buffer := new SByte[1024];
var bytes: Integer;
// Keep listening to the InputStream while connected
while true do
try
// Read from the InputStream
bytes := mmInStream.&read(buffer);
// Send the obtained bytes to the UI Activity
mService.mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, - 1, buffer).sendToTarget;
except
on e: IOException do
begin
Log.e(TAG, 'disconnected', e);
mService.connectionLost;
break
end
end;
end;
method BluetoothChatService.ConnectedThread.&write(buffer: array of SByte);
begin
try
mmOutStream.&write(buffer);
// Share the sent message back to the UI Activity
mService.mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, - 1, - 1, buffer).sendToTarget();
except
on e: IOException do
Log.e(TAG, 'Exception during write', e)
end;
end;
method BluetoothChatService.ConnectedThread.cancel;
begin
try
mmSocket.close;
except
on e: IOException do
Log.e(TAG, 'close() of connect socket failed', e)
end;
end;
end. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.