text
stringlengths
14
6.51M
unit GetRouteUnit; interface uses SysUtils, BaseExampleUnit; type TGetRoute = class(TBaseExample) public procedure Execute(RouteId: String; GetRouteDirections, GetRoutePathPoints: boolean); end; implementation uses RouteParametersQueryUnit, DataObjectUnit, EnumsUnit; procedure TGetRoute.Execute(RouteId: String; GetRouteDirections, GetRoutePathPoints: boolean); var ErrorString: String; Route: TDataObjectRoute; begin Route := Route4MeManager.Route.Get( RouteId, GetRouteDirections, GetRoutePathPoints, ErrorString); WriteLn(''); try if (Route <> nil) then begin WriteLn('GetRoute executed successfully'); WriteLn(Format('Route ID: %s', [Route.RouteId])); WriteLn(Format('State: %s', [TOptimizationDescription[TOptimizationState(Route.State)]])); if (Length(Route.Directions) > 0) then WriteLn(Format('Directions: length = %d', [Length(Route.Directions)])); if (Length(Route.Path) > 0) then WriteLn(Format('Path: length = %d', [Length(Route.Path)])); end else WriteLn(Format('GetRoute error: "%s"', [ErrorString])); finally FreeAndNil(Route); end; end; end.
unit StatusBarWordsPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\StatusBarWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "StatusBarWordsPack" MUID: (552E3E7E023A) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , vtStatusBar , tfwClassLike , tfwScriptingInterfaces , TypInfo , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *552E3E7E023Aimpl_uses* //#UC END# *552E3E7E023Aimpl_uses* ; type TkwPopStatusBarGetPanel = {final} class(TtfwClassLike) {* Слово скрипта pop:vtStatusBar:GetPanel } private function GetPanel(const aCtx: TtfwContext; aStatusBar: TvtStatusBar; anIndex: Integer): TvtStatusPanel; {* Реализация слова скрипта pop:vtStatusBar:GetPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopStatusBarGetPanel function TkwPopStatusBarGetPanel.GetPanel(const aCtx: TtfwContext; aStatusBar: TvtStatusBar; anIndex: Integer): TvtStatusPanel; {* Реализация слова скрипта pop:vtStatusBar:GetPanel } //#UC START# *552E3EE00284_552E3EE00284_4E15A00502A3_Word_var* //#UC END# *552E3EE00284_552E3EE00284_4E15A00502A3_Word_var* begin //#UC START# *552E3EE00284_552E3EE00284_4E15A00502A3_Word_impl* Result := aStatusBar.Panels.Items[anIndex]; //#UC END# *552E3EE00284_552E3EE00284_4E15A00502A3_Word_impl* end;//TkwPopStatusBarGetPanel.GetPanel class function TkwPopStatusBarGetPanel.GetWordNameForRegister: AnsiString; begin Result := 'pop:vtStatusBar:GetPanel'; end;//TkwPopStatusBarGetPanel.GetWordNameForRegister function TkwPopStatusBarGetPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtStatusPanel); end;//TkwPopStatusBarGetPanel.GetResultTypeInfo function TkwPopStatusBarGetPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopStatusBarGetPanel.GetAllParamsCount function TkwPopStatusBarGetPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TvtStatusBar), TypeInfo(Integer)]); end;//TkwPopStatusBarGetPanel.ParamsTypes procedure TkwPopStatusBarGetPanel.DoDoIt(const aCtx: TtfwContext); var l_aStatusBar: TvtStatusBar; var l_anIndex: Integer; begin try l_aStatusBar := TvtStatusBar(aCtx.rEngine.PopObjAs(TvtStatusBar)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aStatusBar: TvtStatusBar : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(GetPanel(aCtx, l_aStatusBar, l_anIndex)); end;//TkwPopStatusBarGetPanel.DoDoIt initialization TkwPopStatusBarGetPanel.RegisterInEngine; {* Регистрация pop_StatusBar_GetPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtStatusBar)); {* Регистрация типа TvtStatusBar } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtStatusPanel)); {* Регистрация типа TvtStatusPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(Integer)); {* Регистрация типа Integer } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit MainForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls, ExptIntf, ToolIntf, ComCtrls; type TExpert = class(TForm) RichEdit1: TRichEdit; MainMenu1: TMainMenu; Tools1: TMenuItem; private { Private declarations } public { Public declarations } end; TMerchiseExpert = class( TIExpert ) private MenuItem: TIMenuItemIntf; protected procedure OnClick( Sender: TIMenuItemIntf); virtual; public constructor Create; virtual; destructor Destroy; override; function GetName: string; override; function GetAuthor: string; override; function GetStyle: TExpertStyle; override; function GetIDString: string; override; end; procedure Register; implementation {$R *.DFM} procedure Register; begin RegisterLibraryExpert( TMerchiseExpert.Create ); end; function TMerchiseExpert.GetName: string; begin Result := 'Merchise' end; function TMerchiseExpert.GetAuthor: string; begin Result := 'Roberto Alonso Gómez'; end; function TMerchiseExpert.GetStyle: TExpertStyle; begin Result := esAddIn; end; function TMerchiseExpert.GetIDString: String; begin Result := 'private.Merchise'; end; constructor TMerchiseExpert.Create; var Main: TIMainMenuIntf; ReferenceMenuItem: TIMenuItemIntf; Menu: TIMenuItemIntf; begin inherited Create; MenuItem := nil; if Assigned( ToolServices ) then begin Main := ToolServices.GetMainMenu; if Assigned( Main ) then try ReferenceMenuItem := Main.FindMenuItem('ToolsOptionsItem'); if Assigned( ReferenceMenuItem ) then try Menu := ReferenceMenuItem.GetParent; if Assigned( Menu ) then try MenuItem := Menu.InsertItem(ReferenceMenuItem.GetIndex+1, 'MyIDEExpert', 'MyIDEExpertExpertItem','', 0,0,0, [mfEnabled, mfVisible], OnClick); finally Menu.DestroyMenuItem; end; finally ReferenceMenuItem.DestroyMenuItem; end; finally Main.Free; end; end; end; destructor TMerchiseExpert.Destroy; begin if Assigned( MenuItem ) then MenuItem.DestroyMenuItem; inherited Destroy; end; procedure TMerchiseExpert.OnClick( Sender: TIMenuItemIntf); begin with TExpert.Create(Application) do try ShowModal; finally Free; end; end; end.
{******************************************************************************* 作者: dmzn@163.com 2010-8-6 描述: 服务器模块 *******************************************************************************} unit UROModule; interface uses SysUtils, Classes, SyncObjs, uROIndyTCPServer, uROClient, uROServer, IdContext, uROClassFactories, UMgrDBConn, uROIndyHTTPServer, uROSOAPMessage, uROBinMessage, uROServerIntf; type TROServerType = (stTcp, stHttp); TROServerTypes = set of TROServerType; //服务类型 TROModuleParam = record FPortTCP: Integer; FPortHttp: Integer; //监听端口 FPoolSizeSrvConn: Integer; FPoolSizeSrvDB: Integer; //缓冲池 FPoolBehaviorSrvConn: TROPoolBehavior; FPoolBehaviorSrvDB: TROPoolBehavior; //缓冲模式 FMaxRecordCount: Integer; //最大记录数 FReloadInterval: Cardinal; //重载间隔 FEnableSrvConn: Boolean; FEnableSrvDB: Boolean; //服务开关 FURLLocalMIT: string; FVerLocalMIT: string; //本地中间件 FURLClient : string; FVerClient : string; //终端店客户端 end; PROModuleStatus = ^TROModuleStatus; TROModuleStatus = record FSrvTCP: Boolean; FSrvHttp: Boolean; //服务状态 FNumTCPActive: Cardinal; FNumTCPTotal: Cardinal; FNumTCPMax: Cardinal; FNumHttpActive: Cardinal; FNumHttpMax: Cardinal; FNumHttpTotal: Cardinal; //连接计数 FNumConn: Cardinal; FNumDB: Cardinal; FNumSweetHeart: Cardinal; FNumSignIn: Cardinal; FNumRegister: Cardinal; FNumSQLQuery: Cardinal; FNumSQLExecute: Cardinal; FNumSQLUpdates: Cardinal; //请求计数 FNumActionError: Cardinal;//执行错误计数 end; TROModule = class(TDataModule) ROBinMsg: TROBinMessage; ROSOAPMsg: TROSOAPMessage; ROHttp1: TROIndyHTTPServer; ROTcp1: TROIndyTCPServer; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure ROHttp1AfterServerActivate(Sender: TObject); procedure ROHttp1InternalIndyServerConnect(AContext: TIdContext); procedure ROTcp1InternalIndyServerConnect(AContext: TIdContext); procedure ROHttp1InternalIndyServerDisconnect(AContext: TIdContext); procedure ROTcp1InternalIndyServerDisconnect(AContext: TIdContext); private { Private declarations } FLastReload: Cardinal; //上次载入 FStatus: TROModuleStatus; //运行状态 FSrvConn: IROClassFactory; //连接服务类厂 FSrvDB: IROClassFactory; //数据服务类厂 FSyncLock: TCriticalSection; //同步锁 procedure RegClassFactories; //注册类厂 procedure UnregClassFactories; //反注册 procedure BeforeStartServer; procedure AfterStopServer; //准备,善后 public { Public declarations } function ActiveServer(const nServer: TROServerTypes; const nActive: Boolean; var nMsg: string): Boolean; //服务操作 function LockModuleStatus: PROModuleStatus; procedure ReleaseStatusLock; //获取状态 procedure ActionROModuleParam(const nIsRead: Boolean); //处理参数 function LoadDBConfigParam: Boolean; //载入数据配置 function LockDBWorker(const nAgent: string; var nHint: string): PDBWorker; procedure ReleaseDBWorker(const nAgent: string; const nWorker: PDBWorker); //数据库连接 function VerifyMAC(const nZID,nDID,nMAC: string; const nWorker: PDBWorker): Boolean; //验证MAC有效性 end; var ROModule: TROModule; gROModuleParam: TROModuleParam; implementation {$R *.dfm} uses Windows, IniFiles, UDataModule, USysConst, USysDB, SrvConn_Impl, SrvDB_Impl, FZSale_Invk; const cParam = 'ServiceParam'; cUpdate = 'SoftUpdate'; procedure TROModule.ActionROModuleParam(const nIsRead: Boolean); var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sConfigFile); try with gROModuleParam,nIni do begin if nIsRead then begin FPortTCP := ReadInteger(cParam, 'PortTCP', 8081); FPortHttp := ReadInteger(cParam, 'PortHttp', 8082); FPoolSizeSrvConn := ReadInteger(cParam, 'PoolSizeSrvConn', 5); FPoolSizeSrvDB := ReadInteger(cParam, 'PoolSizeSrvDB', 20); FPoolBehaviorSrvConn := TROPoolBehavior(ReadInteger(cParam, 'PoolBehaviorSrvConn', Ord(pbWait))); FPoolBehaviorSrvDB := TROPoolBehavior(ReadInteger(cParam, 'PoolBehaviorSrvDB', Ord(pbWait))); FMaxRecordCount := ReadInteger(cParam, 'MaxRecordCount', 100); FReloadInterval := ReadInteger(cParam, 'ReloadInterval', 300); FEnableSrvConn := ReadBool(cParam, 'EnableSrvConn', True); FEnableSrvDB := ReadBool(cParam, 'EnableSrvDB', True); FURLLocalMIT := ReadString(cUpdate, 'URLLocalMIT', ''); FVerLocalMIT := ReadString(cUpdate, 'VerLocalMIT', ''); FURLClient := ReadString(cUpdate, 'URLClient', ''); FVerClient := ReadString(cUpdate, 'VerClient', ''); end else begin WriteInteger(cParam, 'PortTCP', FPortTCP); WriteInteger(cParam, 'PortHttp', FPortHttp); WriteInteger(cParam, 'PoolSizeSrvConn', FPoolSizeSrvConn); WriteInteger(cParam, 'PoolSizeSrvDB', FPoolSizeSrvDB); WriteInteger(cParam, 'PoolBehaviorSrvConn', Ord(FPoolBehaviorSrvConn)); WriteInteger(cParam, 'PoolBehaviorSrvDB', Ord(FPoolBehaviorSrvDB)); WriteInteger(cParam, 'MaxRecordCount', FMaxRecordCount); WriteInteger(cParam, 'ReloadInterval', FReloadInterval); WriteBool(cParam, 'EnableSrvConn', FEnableSrvConn); WriteBool(cParam, 'EnableSrvDB', FEnableSrvDB); WriteString(cUpdate, 'URLLocalMIT', FURLLocalMIT); WriteString(cUpdate, 'VerLocalMIT', FVerLocalMIT); WriteString(cUpdate, 'URLClient', FURLClient); WriteString(cUpdate, 'VerClient', FVerClient); end; end; finally nIni.Free; end; end; //------------------------------------------------------------------------------ procedure TROModule.DataModuleCreate(Sender: TObject); begin FSrvConn := nil; FSrvDB := nil; FillChar(FStatus, SizeOf(FStatus), #0); FSyncLock := TCriticalSection.Create; ActionROModuleParam(True); end; procedure TROModule.DataModuleDestroy(Sender: TObject); var nStr: string; begin ActiveServer([stTcp, stHttp], False, nStr); UnregClassFactories; FSyncLock.Free; end; //Desc: 同步锁定模块状态 function TROModule.LockModuleStatus: PROModuleStatus; begin FSyncLock.Enter; Result := @FStatus; end; //Desc: 释放模块同步锁 procedure TROModule.ReleaseStatusLock; begin FSyncLock.Leave; end; //Desc: 服务器启动 procedure TROModule.ROHttp1AfterServerActivate(Sender: TObject); begin with gROModuleParam, LockModuleStatus^ do begin FSrvTCP := ROTcp1.Active; FSrvHttp := ROHttp1.Active; ReleaseStatusLock; end; if not (csDestroying in ComponentState) then AdminStatusChange(gSysParam.FIsAdmin); //xxxxx end; //Desc: TCP新连接 procedure TROModule.ROTcp1InternalIndyServerConnect(AContext: TIdContext); begin with gROModuleParam, LockModuleStatus^ do begin FNumTCPTotal := FNumTCPTotal + 1; FNumTCPActive := FNumTCPActive + 1; if FNumTCPActive > FNumTCPMax then FNumTCPMax := FNumTCPActive; ReleaseStatusLock; end; end; //Desc: Http新连接 procedure TROModule.ROHttp1InternalIndyServerConnect(AContext: TIdContext); begin with gROModuleParam, LockModuleStatus^ do begin FNumHttpTotal := FNumHttpTotal + 1; FNumHttpActive := FNumHttpActive + 1; if FNumHttpActive > FNumHttpMax then FNumHttpMax := FNumHttpActive; ReleaseStatusLock; end; end; //Desc: TCP断开 procedure TROModule.ROTcp1InternalIndyServerDisconnect(AContext: TIdContext); begin with gROModuleParam, LockModuleStatus^ do begin FNumTCPActive := FNumTCPActive - 1; ReleaseStatusLock; end; end; //Desc: HTTP断开 procedure TROModule.ROHttp1InternalIndyServerDisconnect(AContext: TIdContext); begin with gROModuleParam, LockModuleStatus^ do begin FNumHttpActive := FNumHttpActive - 1; ReleaseStatusLock; end; end; //------------------------------------------------------------------------------ procedure Create_SrvDB(out anInstance : IUnknown); begin anInstance := TSrvDB.Create; end; procedure Create_SrvConn(out anInstance : IUnknown); begin anInstance := TSrvConn.Create; end; //Desc: 注册类厂 procedure TROModule.RegClassFactories; begin UnregClassFactories; with gROModuleParam do begin FSrvConn := TROPooledClassFactory.Create('SrvConn', Create_SrvConn, TSrvConn_Invoker, FPoolSizeSrvConn, FPoolBehaviorSrvConn); FSrvDB := TROPooledClassFactory.Create('SrvDB', Create_SrvDB, TSrvDB_Invoker, FPoolSizeSrvDB, FPoolBehaviorSrvDB); end; end; //Desc: 注销类厂 procedure TROModule.UnregClassFactories; begin if Assigned(FSrvConn) then begin UnRegisterClassFactory(FSrvConn); FSrvConn := nil; end; if Assigned(FSrvDB) then begin UnRegisterClassFactory(FSrvDB); FSrvDB := nil; end; end; //Date: 2010-8-7 //Parm: 服务类型;动作;提示信息 //Desc: 对nServer执行nActive动作 function TROModule.ActiveServer(const nServer: TROServerTypes; const nActive: Boolean; var nMsg: string): Boolean; begin try if nActive and ((not ROTcp1.Active) and (not ROHttp1.Active)) then BeforeStartServer; //启动前准备 if stTcp in nServer then begin if nActive then ROTcp1.Active := False; ROTcp1.Port := gROModuleParam.FPortTCP; ROTcp1.Active := nActive; end; if stHttp in nServer then begin if nActive then ROHttp1.Active := False; ROHttp1.Port := gROModuleParam.FPortHttp; ROHttp1.Active := nActive; end; if (not ROTcp1.Active) and (not ROHttp1.Active) then begin UnregClassFactories; //卸载类厂 AfterStopServer; //关闭善后 end; Result := True; nMsg := ''; except on nE:Exception do begin Result := False; nMsg := nE.Message; ShowDebugLog(nMsg, True); end; end; end; //Desc: 启动前准备工作 procedure TROModule.BeforeStartServer; var nParam: TDBParam; begin with nParam, gSysParam, FDM do begin begin FHost := FLocalHost; FPort := FLocalPort; FDB := FLocalDB; FUser := FLocalUser; FPwd := FLocalPwd; FConn := FLocalConn; end; LocalConn.Close; LocalConn.ConnectionString := gDBConnManager.MakeDBConnection(nParam); LocalConn.Connected := True; AdjustAllSystemTables; //重置系统表 LoadDBConfigParam; //读取数据配置 end; if (FSrvConn = nil) or (FSrvDB = nil) then RegClassFactories; //xxxxx end; //Desc: 服务关闭后善后工作 procedure TROModule.AfterStopServer; begin gDBConnManager.ClearParam; //清理参数 gDBConnManager.Disconnection(); //关闭连接 end; //------------------------------------------------------------------------------ //Desc: 重载数据库连接参数 function TROModule.LoadDBConfigParam: Boolean; var nStr: string; nParam: TDBParam; begin Result := False; FSyncLock.Enter; try if (GetTickCount - FLastReload) >= (gROModuleParam.FReloadInterval * 1000) then FLastReload := GetTickCount else Exit; finally FSyncLock.Leave; end; nStr := 'Select * From ' + sTable_MITDB; with FDM.QuerySQL(nStr) do if RecordCount > 0 then begin gDBConnManager.ClearParam; First; while not Eof do begin with nParam do if FieldByName('D_Invalid').AsString <> sFlag_Yes then begin FID := FieldByName('D_Agent').AsString; FHost := FieldByName('D_Host').AsString; FPort := FieldByName('D_Port').AsInteger; FDB := FieldByName('D_DBName').AsString; FUser := FieldByName('D_User').AsString; FPwd := FieldByName('D_Pwd').AsString; FConn := FieldByName('D_ConnStr').AsString; gDBConnManager.AddParam(nParam); end; Next; end; Result := True; end; end; //Desc: 获取nAgent代理商的数据库连接 function TROModule.LockDBWorker(const nAgent: string; var nHint: string): PDBWorker; var nErr,nInt: Integer; begin Result := nil; try nInt := 2; while nInt > 0 do begin Result := gDBConnManager.GetConnection(nAgent, nErr); if Assigned(Result) then Exit; Dec(nInt); if (nInt = 1) and (nErr = cErr_GetConn_NoParam) then if LoadDBConfigParam then Continue; Dec(nInt); case nErr of cErr_GetConn_NoAllowed: nHint := '数据连接池已关闭!'; cErr_GetConn_Closing: nHint := '数据连接池正在关闭!'; cErr_GetConn_NoParam: nHint := '没有找到指定连接池!' else nHint := '检索连接池对象错误!'; end; end; except on e:Exception do begin nHint := e.Message; end; end; end; //Desc: 释放数据库连接 procedure TROModule.ReleaseDBWorker(const nAgent: string; const nWorker: PDBWorker); begin gDBConnManager.ReleaseConnection(nAgent, nWorker); end; //Desc: 验证终端店的MAC地址是否有效 function TROModule.VerifyMAC(const nZID, nDID, nMAC: string; const nWorker: PDBWorker): Boolean; begin Result := True; end; end.
{$optimization off} unit Unit2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,Dialogs, StdCtrls, Unit3; type LongArithmeticOperation = class(LongArithmetic) {extend} public constructor Create(s_number_param: string); public function sum(o_number_a: LongArithmeticOperation; o_number_b: LongArithmeticOperation): LongArithmeticOperation; public function sub(o_number_a: LongArithmeticOperation; o_number_b: LongArithmeticOperation): LongArithmeticOperation; public function multiplication(o_number_a: LongArithmeticOperation; o_number_b: LongArithmeticOperation): LongArithmeticOperation; public function divisionDiv(o_number_a: LongArithmeticOperation; o_number_b: LongArithmeticOperation): LongArithmeticOperation; public function divisionMod(o_number_a: LongArithmeticOperation; o_number_b: LongArithmeticOperation): LongArithmeticOperation; end; implementation constructor LongArithmeticOperation.Create(s_number_param: string); begin Inherited Create(s_number_param); end; function LongArithmeticOperation.sum(o_number_a: LongArithmeticOperation; o_number_b: LongArithmeticOperation): LongArithmeticOperation; var i,i_length,i_length_difference,i_template: integer; a_number_a, a_number_b,a_template_a,a_template_b: TArray; o_result: LongArithmeticOperation; begin i_template := 0; a_number_a := o_number_a.GetNumber(); a_number_b := o_number_b.GetNumber(); i_length := o_number_a.GetLengthNumber(); i_length_difference:= o_number_a.GetLengthNumber() - o_number_b.GetLengthNumber(); if(i_length_difference > 0) then begin a_number_b := o_result.BalanceArray(a_number_b, i_length_difference); i_length := o_number_a.GetLengthNumber(); end else if(i_length_difference < 0) then begin a_number_a := o_result.BalanceArray(a_number_a, abs(i_length_difference)); i_length := o_number_b.GetLengthNumber(); end; setLength(a_template_a, i_length+1); for i:= i_length-1 downto 0 do begin i_template := i_template+a_number_a[i]+a_number_b[i]; a_template_a[i+1] := i_template mod 10; i_template := i_template div 10; end; if(i_template > 0) then a_template_a[0] := i_template; a_template_a := o_result.ClearZero(a_template_a); o_result := LongArithmeticOperation.Create(ArrayToString(a_template_a)); Result := o_result; end; function LongArithmeticOperation.sub(o_number_a: LongArithmeticOperation; o_number_b: LongArithmeticOperation): LongArithmeticOperation; var i,i_length,i_length_difference,i_template,i_more: integer; a_number_a, a_number_b,a_template_a,a_template_b: TArray; o_result: LongArithmeticOperation; s_sign: char; begin s_sign := ' '; i_template := 0; a_template_a := o_number_a.GetNumber(); a_template_b := o_number_b.GetNumber(); i_length_difference := o_number_a.GetLengthNumber() - o_number_b.GetLengthNumber(); i_length := o_number_a.GetLengthNumber(); if(i_length_difference > 0) then begin a_number_b := o_result.BalanceArray(a_template_b, i_length_difference); a_number_a := a_template_a; i_length := o_number_a.GetLengthNumber(); end else if(i_length_difference < 0) then begin s_sign := '-'; a_number_b := o_result.BalanceArray(a_template_a, abs(i_length_difference)); a_number_a := a_template_b; i_length := o_number_b.GetLengthNumber(); end else begin i_more:= o_result.CompLong(a_template_a,a_template_b); if(i_more > -1) then begin a_number_a := a_template_a; a_number_b := a_template_b; end else if(i_more < 0) then begin s_sign := '-'; a_number_a := a_template_b; a_number_b := a_template_a; end; end; SetLength(a_template_a, i_length); for i := i_length-1 downto 0 do begin i_template := i_template + a_number_a[i] - a_number_b[i] + 10; a_template_a[i] := i_template mod 10; if(i_template < 10) then i_template := -1 else i_template := 0; end; for i := 0 to i_length do begin if(a_template_a[i] > 0) then begin i_template := i; break; end; end; a_template_b := o_result.ClearZero(a_template_a); i_length := Length(a_template_b); o_result:= LongArithmeticOperation.Create(ArrayToString(a_template_b)); o_result.SetSign(s_sign); Result := o_result; end; function LongArithmeticOperation.multiplication(o_number_a: LongArithmeticOperation; o_number_b: LongArithmeticOperation): LongArithmeticOperation; var i,j,i_length,i_length_number_a,i_length_number_b,i_template,i_length_difference: integer; a_number_a, a_number_b,a_template_a,a_template_b: TArray; o_result: LongArithmeticOperation; begin i_template := 0; a_number_a := o_number_a.GetNumber(); a_number_b := o_number_b.GetNumber(); i_length_number_b := o_number_b.GetLengthNumber(); i_length_number_a := o_number_a.GetLengthNumber(); SetLength(a_template_a,i_length_number_b+i_length_number_a); for i := i_length_number_b-1 downto 0 do begin i_template := 0; for j:= i_length_number_a-1 downto 0 do begin a_template_a[j + i + 1] := a_template_a[j + i + 1]+i_template + a_number_a[j] * a_number_b[i]; i_template := a_template_a[j + i + 1] div 10; a_template_a[j + i + 1] := a_template_a[j + i + 1] mod 10; end; a_template_a[i] := i_template; end; a_template_b := o_result.ClearZero(a_template_a); i_length := Length(a_template_b); o_result:= LongArithmeticOperation.Create(ArrayToString(a_template_b)); Result := o_result; end; function LongArithmeticOperation.divisionDiv(o_number_a: LongArithmeticOperation; o_number_b: LongArithmeticOperation): LongArithmeticOperation; var i,j,i_length,i_length_difference,i_template,is_more,i_result: integer; a_number_a, a_number_b,a_template_a,a_template_b,a_template_c,a_template, b_template: TArray; o_result, o_template_a,o_template_b,o_template_c,o_sum,o_sub,o_template_sub: LongArithmeticOperation; s_result,s_number: string; begin a_number_b := o_number_b.GetNumber(); o_result.CheckDivider(a_number_b); a_number_a := o_number_a.GetNumber(); a_template_b := a_number_b; i_length := o_number_a.GetLengthNumber(); i_length_difference:= o_number_a.GetLengthNumber() - o_number_b.GetLengthNumber(); if(i_length_difference < 0) then begin o_result:= LongArithmeticOperation.Create('0'); Result := o_result; end else if(i_length_difference = 0) then begin is_more := o_result.CompLong(a_number_a,a_number_b); if(is_more = -1) then begin o_result:= LongArithmeticOperation.Create('0'); Result := o_result; end else if(is_more = 0) then begin o_result:= LongArithmeticOperation.Create('1'); Result := o_result; end else begin i := 1; o_template_a := o_result.sum(o_number_b,o_number_b); a_template_a := o_template_a.GetNumber(); a_template_b := a_number_b; while(CompLong(a_number_a,a_template_a) >= 0) do begin inc(i); a_template_b := a_template_a; o_template_a := LongArithmeticOperation.Create(ArrayToString(a_template_a)); o_sum := o_result.sum(o_number_b,o_template_a); i_length := o_sum.GetLengthNumber; if(i_length > Length(a_template_a)) then break; a_template_a := o_sum.GetNumber(); end; o_result:= LongArithmeticOperation.Create(IntToStr(i)); Result := o_result; end; end else begin i_length := o_number_b.GetLengthNumber(); SetLength(a_template_a,i_length); for i:=0 to i_length-1 do begin a_template_a[i] := a_number_a[i]; end; if(CompLong(a_template_a, a_number_b) = -1) then begin Inc(i_length); SetLength(a_template_a,i_length); for i := 0 to i_length-1 do begin a_template_a[i] := a_number_a[i]; a_number_b := BalanceArray(a_number_b,1); end; end; o_template_a := LongArithmeticOperation.Create(ArrayToString(a_template_a)); for i := i_length to Length(a_number_a) do begin s_number := ''; i_result := 0; a_template_b := a_number_b; if(CompLong(a_template_a,a_template_b) >= 0) then begin inc(i_result); o_template_b := o_result.sum(o_number_b,o_number_b); a_template_c := a_template_b; o_template_c := o_number_b; a_template_b := o_template_b.GetNumber(); while(CompLong(a_template_a,a_template_b) >= 0) do begin if(Length(a_template_b) > Length(a_template_a)) then break; inc(i_result); o_template_b := LongArithmeticOperation.Create(ArrayToString(a_template_b)); o_template_c := o_template_b; o_sum := o_result.sum(o_number_b,o_template_b); i_length := o_sum.GetLengthNumber; if(i_length > Length(a_template_a)) then break; a_template_b := o_sum.GetNumber(); end; o_sub := o_result.sub(o_template_a,o_template_c); o_template_a.Destroy(); a_template_a := o_sub.GetNumber(); end; a_template_a := o_result.ClearZero(a_template_a); s_number := o_result.ArrayToString(a_template_a); s_number := s_number + IntToStr(a_number_a[i]); o_template_a := LongArithmeticOperation.Create(s_number); a_template_a := o_template_a.GetNumber(); i_length_difference := Length(a_template_a) - Length(a_number_b); if(i_length_difference > 0) then begin a_number_b := o_result.BalanceArray(a_number_b, i_length_difference); end else if(i_length_difference < 0) then begin a_number_a := o_result.BalanceArray(a_number_a, Abs(i_length_difference)); end; s_result := s_result + IntToStr(i_result); end; o_result:= LongArithmeticOperation.Create(s_result); Result := o_result; end; end; function LongArithmeticOperation.divisionMod(o_number_a: LongArithmeticOperation; o_number_b: LongArithmeticOperation): LongArithmeticOperation; var o_result,o_div,o_template: LongArithmeticOperation; begin o_div := o_result.divisionDiv(o_number_a,o_number_b); o_template := o_result.multiplication(o_number_b,o_div); Result := o_result.sub(o_number_a,o_template); end; end.
unit SwitchBranchStatementParsingTest; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FpcUnit, TestRegistry, ParserBaseTestCase, WpcScriptCommons, WpcStatements, WpcScriptParser, WpcExceptions; type { TSwitchBranchStatementParsingTest } TSwitchBranchStatementParsingTest = class(TParserBaseTestCase) public const SWITCH_TO_BRANCH = SWITCH_KEYWORD + ' ' + TO_KEYWORD + ' ' + BRANCH_KEYWORD + ' '; ADDITIONAL_BRANCH_NAME = 'SomeBranch'; protected SwitchBranchStatement : TWpcSwitchBranchStatement; published procedure ShouldParseBaseSwitchBranchStatement(); procedure ShouldParseSwitchBranchStatementWithProbabilityProperty(); procedure SholudRaiseScriptParseExceptionWhenStatementKeywordsUncompleted(); procedure SholudRaiseScriptParseExceptionWhenNoBranchSpecified(); procedure SholudRaiseScriptParseExceptionWhenReferencedBranchDoesntExist(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfBase(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeProperties(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterProperties(); end; implementation { TSwitchBranchStatementParsingTest } // SWITCH TO BRANCH SomeBranch procedure TSwitchBranchStatementParsingTest.ShouldParseBaseSwitchBranchStatement(); begin ScriptLines.Add(SWITCH_TO_BRANCH + ADDITIONAL_BRANCH_NAME); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_SWITCH_BRANCH_STATEMENT_ID = MainBranchStatements[0].GetId()); SwitchBranchStatement := TWpcSwitchBranchStatement(MainBranchStatements[0]); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, ADDITIONAL_BRANCH_NAME, SwitchBranchStatement.GetBranchName()); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, DEFAULT_PROBABILITY, SwitchBranchStatement.GetProbability()); end; // SWITCH TO BRANCH SomeBranch WITH PROBABILITY 50 procedure TSwitchBranchStatementParsingTest.ShouldParseSwitchBranchStatementWithProbabilityProperty(); begin ScriptLines.Add(SWITCH_TO_BRANCH + ADDITIONAL_BRANCH_NAME + WITH_PROBABILITY_PROPERTY); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); AssertTrue(WRONG_STATEMENT, WPC_SWITCH_BRANCH_STATEMENT_ID = MainBranchStatements[0].GetId()); SwitchBranchStatement := TWpcSwitchBranchStatement(MainBranchStatements[0]); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, ADDITIONAL_BRANCH_NAME, SwitchBranchStatement.GetBranchName()); AssertEquals(WRONG_STATEMENT_PROPRTY_VALUE, TEST_DEFAULT_PROBABILITY_VALUE, SwitchBranchStatement.GetProbability()); end; // SWITCH TO SomeBranch procedure TSwitchBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenStatementKeywordsUncompleted; begin ScriptLines.Add(SWITCH_KEYWORD + ' ' + TO_KEYWORD + ' ' + ADDITIONAL_BRANCH_NAME); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(1, 2); end; // SWITCH TO RANCH procedure TSwitchBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenNoBranchSpecified(); begin ScriptLines.Add(SWITCH_TO_BRANCH); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(1, 3); end; // SWITCH TO BRANCH SomeNonexistentBranch procedure TSwitchBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenReferencedBranchDoesntExist(); begin ScriptLines.Add(SWITCH_TO_BRANCH + ' SomeNonexistentBranch '); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(); end; // SWITCH TO BRANCH SomeBranch ONCE procedure TSwitchBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfBase(); begin ScriptLines.Add(SWITCH_TO_BRANCH + ADDITIONAL_BRANCH_NAME + ' ONCE '); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(1, 4); end; // SWITCH TO BRANCH SomeBranch ONCE WITH PROBABILITY 50 procedure TSwitchBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeProperties(); begin ScriptLines.Add(SWITCH_TO_BRANCH + ADDITIONAL_BRANCH_NAME + ' ONCE ' + WITH_PROBABILITY_PROPERTY); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(1, 4); end; // SWITCH TO BRANCH SomeBranch WITH PROBABILITY 50 ONCE procedure TSwitchBranchStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterProperties(); begin ScriptLines.Add(SWITCH_TO_BRANCH + ADDITIONAL_BRANCH_NAME + WITH_PROBABILITY_PROPERTY + ' ONCE '); WrapInMainBranch(ScriptLines); AddEmptyBranch(ScriptLines, ADDITIONAL_BRANCH_NAME); AssertScriptParseExceptionOnParse(1, 7); end; initialization RegisterTest(PARSER_TEST_SUITE_NAME, TSwitchBranchStatementParsingTest); end.
unit FacilityControl; interface uses Math, TypeControl, FacilityTypeControl, VehicleTypeControl; type TFacility = class private FId: Int64; FType: TFacilityType; FOwnerPlayerId: Int64; FLeft: Double; FTop: Double; FCapturePoints: Double; FVehicleType: TVehicleType; FProductionProgress: LongInt; public constructor Create(const id: Int64; const facilityType: TFacilityType; const ownerPlayerId: Int64; const left: Double; const top: Double; const capturePoints: Double; const vehicleType: TVehicleType; const productionProgress: LongInt); overload; constructor Create(const facility: TFacility); overload; function GetId: Int64; property Id: Int64 read GetId; function GetType: TFacilityType; property FacilityType: TFacilityType read GetType; function GetOwnerPlayerId: Int64; property OwnerPlayerId: Int64 read GetOwnerPlayerId; function GetLeft: Double; property Left: Double read GetLeft; function GetTop: Double; property Top: Double read GetTop; function GetCapturePoints: Double; property CapturePoints: Double read GetCapturePoints; function GetVehicleType: TVehicleType; property VehicleType: TVehicleType read GetVehicleType; function GetProductionProgress: LongInt; property ProductionProgress: LongInt read GetProductionProgress; destructor Destroy; override; end; TFacilityArray = array of TFacility; implementation constructor TFacility.Create(const id: Int64; const facilityType: TFacilityType; const ownerPlayerId: Int64; const left: Double; const top: Double; const capturePoints: Double; const vehicleType: TVehicleType; const productionProgress: LongInt); begin FId := id; FType := facilityType; FOwnerPlayerId := ownerPlayerId; FLeft := left; FTop := top; FCapturePoints := capturePoints; FVehicleType := vehicleType; FProductionProgress := productionProgress; end; constructor TFacility.Create(const facility: TFacility); begin FId := facility.Id; FType := facility.FacilityType; FOwnerPlayerId := facility.OwnerPlayerId; FLeft := facility.Left; FTop := facility.Top; FCapturePoints := facility.CapturePoints; FVehicleType := facility.VehicleType; FProductionProgress := facility.ProductionProgress; end; function TFacility.GetId: Int64; begin result := FId; end; function TFacility.GetType: TFacilityType; begin result := FType; end; function TFacility.GetOwnerPlayerId: Int64; begin result := FOwnerPlayerId; end; function TFacility.GetLeft: Double; begin result := FLeft; end; function TFacility.GetTop: Double; begin result := FTop; end; function TFacility.GetCapturePoints: Double; begin result := FCapturePoints; end; function TFacility.GetVehicleType: TVehicleType; begin result := FVehicleType; end; function TFacility.GetProductionProgress: LongInt; begin result := FProductionProgress; end; destructor TFacility.Destroy; begin inherited; end; end.
'Routines Public Function Log1P(ByVal x As Double) As Double Dim Result As Double Dim z As Double Dim LP As Double Dim LQ As Double z = 1.0+x If z<0.70710678118654752440 Or z>1.41421356237309504880 then Result = Log(z) Log1P = Result Exit Function End If z = x*x LP = 4.5270000862445199635215E-5 LP = LP*x+4.9854102823193375972212E-1 LP = LP*x+6.5787325942061044846969E0 LP = LP*x+2.9911919328553073277375E1 LP = LP*x+6.0949667980987787057556E1 LP = LP*x+5.7112963590585538103336E1 LP = LP*x+2.0039553499201281259648E1 LQ = 1.0000000000000000000000E0 LQ = LQ*x+1.5062909083469192043167E1 LQ = LQ*x+8.3047565967967209469434E1 LQ = LQ*x+2.2176239823732856465394E2 LQ = LQ*x+3.0909872225312059774938E2 LQ = LQ*x+2.1642788614495947685003E2 LQ = LQ*x+6.0118660497603843919306E1 z = -(0.5*z)+x*(z*LP/LQ) Result = x+z Log1P = Result End Function Public Function ExpM1(ByVal x As Double) As Double Dim Result As Double Dim r As Double Dim xx As Double Dim EP As Double Dim EQ As Double If x<-0.5 Or x>0.5 then Result = exp(x)-1.0 ExpM1 = Result Exit Function End If xx = x*x EP = 1.2617719307481059087798E-4 EP = EP*xx+3.0299440770744196129956E-2 EP = EP*xx+9.9999999999999999991025E-1 EQ = 3.0019850513866445504159E-6 EQ = EQ*xx+2.5244834034968410419224E-3 EQ = EQ*xx+2.2726554820815502876593E-1 EQ = EQ*xx+2.0000000000000000000897E0 r = x*EP r = r/(EQ-r) Result = r+r ExpM1 = Result End Function Public Function CosM1(ByVal x As Double) As Double Dim Result As Double Dim xx As Double Dim C As Double If x<-(0.25*Pi()) Or x>0.25*Pi() then Result = Cos(x)-1# CosM1 = Result Exit Function End If xx = x*x C = 4.7377507964246204691685E-14 C = C*xx-1.1470284843425359765671E-11 C = C*xx+2.0876754287081521758361E-9 C = C*xx-2.7557319214999787979814E-7 C = C*xx+2.4801587301570552304991E-5 C = C*xx-1.3888888888888872993737E-3 C = C*xx+4.1666666666666666609054E-2 Result = -(0.5*xx)+xx*xx*C CosM1 = Result End Function
unit Model.Expedicao; interface uses Common.ENum, FireDAC.Comp.Client; type TExpedicao = class private FAcao: Tacao; FContainer: Integer; FPeso: Double; FUnitizador: Integer; FConferencia: TDateTime; FNN: String; FExecucao: TDateTime; FExecutor: String; FVolumes: Integer; FID: Integer; FEmbarcador: Integer; FBase: Integer; FCCEP: String; FRecebedor: String; FConferente: String; FRecebimento: TDateTime; FData: TDateTime; public property ID: Integer read FID write FID; property Data: TDateTime read FData write FData; property CCEP: String read FCCEP write FCCEP; property Base: Integer read FBase write FBase; property Container: Integer read FContainer write FContainer; property Unitizador: Integer read FUnitizador write FUnitizador; property NN: String read FNN write FNN; property Embarcador: Integer read FEmbarcador write FEmbarcador; property Volumes: Integer read FVolumes write FVolumes; property Peso: Double read FPeso write FPeso; property Executor: String read FExecutor write FExecutor; property Execucao: TDateTime read FExecucao write FExecucao; property Conferente: String read FConferente write FConferente; property Conferencia: TDateTime read FConferencia write FConferencia; property Recebedor: String read FRecebedor write FRecebedor; property Recebimento: TDateTime read FRecebimento write FRecebimento; property Acao: Tacao read FAcao write FAcao; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; implementation { TExpedicao } function TExpedicao.Gravar: Boolean; begin end; function TExpedicao.Localizar(aParam: array of variant): TFDQuery; begin end; end.
unit MSCacheSpool; interface procedure Init; procedure Done; procedure BackgroundCache(Obj : TObject; rcLinks : boolean); procedure BackgroundUncache(Obj : TObject); procedure BackgroundInvalidateCache(Obj : TObject); implementation uses Classes, SyncObjs, Collection, MSObjectCacher, MSCacher, CacheAgent; const SPOOL_TIMEOUT = 5*1000; type TLockedStringList = class(TStringList) public constructor Create; destructor Destroy; override; private fLock : TCriticalSection; public function Add(const S: string): Integer; override; procedure Lock; procedure Unlock; end; // TLockedStringList constructor TLockedStringList.Create; begin inherited Create; fLock := TCriticalSection.Create; end; destructor TLockedStringList.Destroy; begin fLock.Free; inherited; end; function TLockedStringList.Add(const S: string): Integer; begin fLock.Enter; try result := inherited Add(S); finally fLock.Leave; end; end; procedure TLockedStringList.Lock; begin fLock.Enter; end; procedure TLockedStringList.Unlock; begin fLock.Leave; end; type TCacheSpoolThread = class(TThread) public constructor Create; destructor Destroy; override; private fCacheQueue : TLockableCollection; fLnkCacheQueue : TLockableCollection; fUncacheQueue : TLockedStringList; fInvalQueue : TLockedStringList; fSpoolEvent : TEvent; public procedure CacheObject(Obj : TObject; rcLinks : boolean); procedure UncacheObject(Obj : TObject); procedure InvalidateObject(Obj : TObject); private procedure Uncache; procedure InvalidateCache; procedure Cache; procedure RecLinkCache; protected procedure Execute; override; end; // TCacheSpoolThread constructor TCacheSpoolThread.Create; begin inherited Create(false); Priority := tpLower; //tpIdle; fCacheQueue := TLockableCollection.Create(0, rkUse); fLnkCacheQueue := TLockableCollection.Create(0, rkUse); fUncacheQueue := TLockedStringList.Create; fInvalQueue := TLockedStringList.Create; fSpoolEvent := TEvent.Create(nil, true, false, ''); Resume; end; destructor TCacheSpoolThread.Destroy; begin Terminate; fSpoolEvent.SetEvent; WaitFor; fCacheQueue.Free; fLnkCacheQueue.Free; fUncacheQueue.Free; fSpoolEvent.Free; inherited; end; procedure TCacheSpoolThread.CacheObject(Obj : TObject; rcLinks : boolean); begin if not rcLinks then begin fCacheQueue.Lock; try if fCacheQueue.IndexOf(Obj) = noIndex then fCacheQueue.Insert(Obj); fSpoolEvent.SetEvent; finally fCacheQueue.Unlock; end; end else begin fLnkCacheQueue.Lock; try if fLnkCacheQueue.IndexOf(Obj) = noIndex then fLnkCacheQueue.Insert(Obj); fSpoolEvent.SetEvent; finally fLnkCacheQueue.Unlock; end; end; end; procedure TCacheSpoolThread.UncacheObject(Obj : TObject); var path : string; begin try path := MSObjectCacher.GetObjectPath(Obj, noKind, noInfo); fUncacheQueue.Add(path); fSpoolEvent.SetEvent; except end; end; procedure TCacheSpoolThread.InvalidateObject(Obj : TObject); var path : string; begin try path := MSObjectCacher.GetObjectPath(Obj, noKind, noInfo); fInvalQueue.Add(path); fSpoolEvent.SetEvent; except end; end; procedure TCacheSpoolThread.Uncache; var path : string; begin try while fUncacheQueue.Count > 0 do begin fUncacheQueue.Lock; try path := fUncacheQueue[0]; fUncacheQueue.Delete(0); finally fUncacheQueue.Unlock; end; MSObjectCacher.UncacheObjectByPath(path); end; except // >> end; end; procedure TCacheSpoolThread.InvalidateCache; var path : string; begin try while fInvalQueue.Count > 0 do begin fInvalQueue.Lock; try path := fInvalQueue[0]; fInvalQueue.Delete(0); finally fInvalQueue.Unlock; end; MSObjectCacher.InvalidateObjectByPath(path); end; except // >> end; end; procedure TCacheSpoolThread.Cache; var Obj : TObject; begin try while fCacheQueue.Count > 0 do begin Obj := fCacheQueue[0]; MSObjectCacher.CacheObject(Obj, noKind, noInfo); fCacheQueue.AtDelete(0); end; except // >> end; end; procedure TCacheSpoolThread.RecLinkCache; var Obj : TObject; begin try while fLnkCacheQueue.Count > 0 do begin Obj := fLnkCacheQueue[0]; MSObjectCacher.CacheObject(Obj, noKind, recLinks); fLnkCacheQueue.AtDelete(0); end; except // >> end; end; procedure TCacheSpoolThread.Execute; begin while not Terminated do try fSpoolEvent.WaitFor(SPOOL_TIMEOUT); if not Terminated then begin fSpoolEvent.ResetEvent; Uncache; InvalidateCache; RecLinkCache; Cache; end; except // >> end; end; var TheSpoolThread : TCacheSpoolThread = nil; procedure Init; begin TheSpoolThread := TCacheSpoolThread.Create; end; procedure Done; begin TheSpoolThread.Free; TheSpoolThread := nil; end; procedure BackgroundCache(Obj : TObject; rcLinks : boolean); begin if Obj <> nil then TheSpoolThread.CacheObject(Obj, rcLinks); end; procedure BackgroundUncache(Obj : TObject); begin if Obj <> nil then TheSpoolThread.UncacheObject(Obj); end; procedure BackgroundInvalidateCache(Obj : TObject); begin if Obj <> nil then TheSpoolThread.InvalidateObject(Obj); end; end.
program TEST1 ( OUTPUT ) ; /********/ /*$N+,A+*/ /********/ type CHARSET = packed array [ CHAR ] of CHAR ; MNEM_TABLE = array [ 0 .. 255 ] of array [ 1 .. 4 ] of CHAR ; INTPTR = -> INTEGER ; (*****************************************************************) (* *) (* WIR TESTEN HIER MAL EINEN GROESSEREN KOMMENTAR *) (* DER UEBER MEHRERE ZEILEN GEHT .................. *) (* *) (*****************************************************************) var CH : CHAR ; X : CHARSET ; F : packed array [ 1 .. 6 ] of CHAR ; I : INTEGER ; ZTBLN : MNEM_TABLE ; const Y : array [ 1 .. 5 ] of INTEGER = ( 4 , 5 , 7 , 9 , 12 ) ; XTBLN : MNEM_TABLE = ( '(00)' , '(01)' , '(02)' , '(03)' , 'SPM ' , 'BALR' , 'BCTR' , 'BCR ' , 'SSK ' , 'ISK ' , 'SVC ' , '(0B)' , '(0C)' , '(0D)' , 'MVCL' , 'CLCL' , 'LPR ' , 'LNR ' , 'LTR ' , 'LCR ' , 'NR ' , 'CLR ' , 'OR ' , 'XR ' , 'LR ' , 'CR ' , 'AR ' , 'SR ' , 'MR ' , 'DR ' , 'ALR ' , 'SLR ' , 'LPDR' , 'LNDR' , 'LTDR' , 'LCDR' , 'HDR ' , 'LRDR' , 'MXR ' , 'MXDR' , 'LDR ' , 'CDR ' , 'ADR ' , 'SDR ' , 'MDR ' , 'DDR ' , 'AWR ' , 'SWR ' , 'LPER' , 'LNER' , 'LTER' , 'LCER' , 'HER ' , 'LRER' , 'AXR ' , 'SXR ' , 'LER ' , 'CER ' , 'AER ' , 'SER ' , 'MER ' , 'DER ' , 'AUR ' , 'SUR ' , 'STH ' , 'LA ' , 'STC ' , 'IC ' , 'EX ' , 'BAL ' , 'BCT ' , 'BC ' , 'LH ' , 'CH ' , 'AH ' , 'SH ' , 'MH ' , '(4D)' , 'CVD ' , 'CVB ' , 'ST ' , '(51)' , '(52)' , '(53)' , 'N ' , 'CL ' , 'O ' , 'X ' , 'L ' , 'C ' , 'A ' , 'S ' , 'M ' , 'D ' , 'AL ' , 'SL ' , 'STD ' , '(61)' , '(62)' , '(63)' , '(64)' , '(65)' , '(66)' , 'MXD ' , 'LD ' , 'CD ' , 'AD ' , 'SD ' , 'MD ' , 'DD ' , 'AW ' , 'SW ' , 'STE ' , '(71)' , '(72)' , '(73)' , '(74)' , '(75)' , '(76)' , '(77)' , 'LE ' , 'CE ' , 'AE ' , 'SE ' , 'ME ' , 'DE ' , 'AU ' , 'SU ' , 'SSM ' , '(81)' , 'LPSW' , 'DIAG' , 'WRD ' , 'RDD ' , 'BXH ' , 'BXLE' , 'SRL ' , 'SLL ' , 'SRA ' , 'SLA ' , 'SRDL' , 'SLDL' , 'SRDA' , 'SLDA' , 'STM ' , 'TM ' , 'MVI ' , 'TS ' , 'NI ' , 'CLI ' , 'OI ' , 'XI ' , 'LM ' , '(99)' , '(9A)' , '(9B)' , 'SIO ' , 'TIO ' , 'HIO ' , 'TCH ' , '(A0)' , '(A1)' , '(A2)' , '(A3)' , '(A4)' , '(A5)' , '(A6)' , '(A7)' , '(A8)' , '(A9)' , '(AA)' , '(AB)' , '(AC)' , '(AD)' , '(AE)' , '(AF)' , '(B0)' , 'LRA ' , 'STCK' , '(B3)' , '(B4)' , '(B5)' , 'STCT' , 'LCTL' , '(B8)' , '(B9)' , '(BA)' , '(BB)' , '(BC)' , 'CLM ' , 'STCM' , 'ICM ' , '(C0)' , '(C1)' , '(C2)' , '(C3)' , '(C4)' , '(C5)' , '(C6)' , '(C7)' , '(C8)' , '(C9)' , '(CA)' , '(CB)' , '(CC)' , '(CD)' , '(CE)' , '(CF)' , '(D0)' , 'MVN ' , 'MVC ' , 'MVZ ' , 'NC ' , 'CLC ' , 'OC ' , 'XC ' , '(D8)' , '(D9)' , '(DA)' , '(DB)' , 'TR ' , 'TRT ' , 'ED ' , 'EDMK' , '(E0)' , '(E1)' , '(E2)' , '(E3)' , '(E4)' , '(E5)' , '(E6)' , '(E7)' , '(E8)' , '(E9)' , '(EA)' , '(EB)' , '(EC)' , '(ED)' , '(EE)' , '(EF)' , 'SRP ' , 'MVO ' , 'PACK' , 'UNPK' , '(F4)' , '(F5)' , '(F6)' , '(F7)' , 'ZAP ' , 'CP ' , 'AP ' , 'SP ' , 'MP ' , 'DP ' , '(FE)' , '(FF)' ) ; procedure CHARSET_INI ( var X : CHARSET ) ; var CH : CHAR ; begin (* CHARSET_INI *) (********************************************) (* HIER SIND NEUERDINGS KOMMENTARE MOEGLICH *) (********************************************) for CH := CHR ( 0 ) to CHR ( 255 ) do X [ CH ] := ' ' end (* CHARSET_INI *) ; procedure CHARSET_ADD ( var X : CHARSET ; VON : CHAR ; BIS : CHAR ) ; var CH : CHAR ; begin (* CHARSET_ADD *) for CH := VON to BIS do begin if CH = 'F' then return ; X [ CH ] := 'J' end (* for *) end (* CHARSET_ADD *) ; function IN_CHARSET ( var X : CHARSET ; SUCH : CHAR ) : BOOLEAN ; begin (* IN_CHARSET *) SNAPSHOT ( 5 , 10 ) ; IN_CHARSET := ( X [ SUCH ] <> ' ' ) ; end (* IN_CHARSET *) ; function IN_CHARSET1 ( var X : CHARSET ; SUCH : CHAR ; ZUSATZ : CHAR ) : BOOLEAN ; begin (* IN_CHARSET1 *) IN_CHARSET1 := ( X [ SUCH ] <> ' ' ) or ( SUCH = ZUSATZ ) ; end (* IN_CHARSET1 *) ; begin (* HAUPTPROGRAMM *) (***********************************) (* DIESER KOMM SOLL STEHEN BLEIBEN *) (***********************************) WRITELN ( 'DATE=' , DATE ) ; /*****************************************/ /* CONTINUE; /* -- YIELDS ERROR E71 -- */*/ /*****************************************/ ZTBLN := XTBLN ; F := 'BERND ' ; for I := 1 to 6 do begin if F [ I ] = 'D' then break ; if F [ I ] = 'E' then continue ; WRITELN ( 'FOR-SCHLEIFE: I = ' , I : 3 , ' F(I) = ' , F [ I ] ) ; end (* for *) ; WRITELN ( 'I NACH DER SCHLEIFE =' , I : 5 ) ; I := 1 ; while F [ I ] <> ' ' do begin if F [ I ] = 'D' then break ; if F [ I ] = 'R' then begin I := I + 1 ; continue end (* then *) ; WRITELN ( 'WHILE-SCHLEIFE: I = ' , I : 3 ) ; I := I + 1 ; end (* while *) ; WRITELN ( 'I NACH DER SCHLEIFE =' , I : 5 ) ; I := 1 ; repeat if F [ I ] = 'D' then break ; if F [ I ] = 'R' then begin I := I + 1 ; continue end (* then *) ; WRITELN ( 'REPEAT-SCHLEIFE: I = ' , I : 3 ) ; I := I + 1 ; until F [ I ] = ' ' ; WRITELN ( 'I NACH DER SCHLEIFE =' , I : 5 ) ; F := 'BERND ' ; for I := 1 to 6 do begin WRITELN ( 'FOR-SCHLEIFE: I = ' , I : 3 , ' F(I) = ' , F [ I ] ) ; break ; (*****************************) (* DIESER KOMM BLEIBT STEHEN *) (*****************************) end (* for *) ; WRITELN ( 'I NACH DER SCHLEIFE =' , I : 5 ) ; I := 1 ; while F [ I ] <> ' ' do begin WRITELN ( 'WHILE-SCHLEIFE: I = ' , I : 3 ) ; I := I + 1 ; break ; end (* while *) ; WRITELN ( 'I NACH DER SCHLEIFE =' , I : 5 ) ; I := 1 ; repeat WRITELN ( 'REPEAT-SCHLEIFE: I = ' , I : 3 ) ; I := I + 1 ; break ; until F [ I ] = ' ' ; WRITELN ( 'I NACH DER SCHLEIFE =' , I : 5 ) ; F := 'BERND ' ; for I := 1 to 6 do begin WRITELN ( 'FOR-SCHLEIFE: I = ' , I : 3 , ' F(I) = ' , F [ I ] ) ; continue ; end (* for *) ; WRITELN ( 'I NACH DER SCHLEIFE =' , I : 5 ) ; I := 1 ; while F [ I ] <> ' ' do begin WRITELN ( 'WHILE-SCHLEIFE: I = ' , I : 3 ) ; I := I + 1 ; continue ; end (* while *) ; WRITELN ( 'I NACH DER SCHLEIFE =' , I : 5 ) ; I := 1 ; repeat WRITELN ( 'REPEAT-SCHLEIFE: I = ' , I : 3 ) ; I := I + 1 ; continue ; until F [ I ] = ' ' ; WRITELN ( 'I NACH DER SCHLEIFE =' , I : 5 ) ; CHARSET_INI ( X ) ; CHARSET_ADD ( X , 'A' , 'Z' ) ; CH := 'A' ; WRITELN ( 'ORD VON A = ' , ORD ( CH ) ) ; WRITELN ( 'AUSGABE VON X:' ) ; WRITELN ( X ) ; WRITELN ( 'ENDE AUSGABE VON X' ) ; WRITELN ( F ) ; /*********/ /*RETURN;*/ /*********/ WRITELN ( 'BUCHSTABE A IN X: ' , IN_CHARSET ( X , 'A' ) ) ; WRITELN ( 'ZIFFER 5 IN X: ' , IN_CHARSET ( X , '5' ) ) ; (*************************) (* KOMMENTAR ZUM SCHLUSS *) (*************************) for I := 0 to 255 do WRITELN ( I , ' = ' , XTBLN [ I ] ) ; end (* HAUPTPROGRAMM *) .
unit TrackingDataUnit; interface uses REST.Json.Types, System.Generics.Collections, Generics.Defaults, JSONNullableAttributeUnit, NullableBasicTypesUnit, EnumsUnit, CommonTypesUnit, GenericParametersUnit, JSONDictionaryIntermediateObjectUnit; type TStatusHistory = class(TGenericParameters) private [JSONName('unix_timestamp')] [Nullable] FUnixTimestamp: NullableInteger; [JSONName('info')] [Nullable] FInfo: NullableString; function GetInfo: TTrackingInfo; public constructor Create; override; property Timestamp: NullableInteger read FUnixTimestamp; property Info: TTrackingInfo read GetInfo; end; TStatusHistoryArray = TArray<TStatusHistory>; TTimeWindow = class(TGenericParameters) private [JSONName('start_time')] [Nullable] FStartTime: NullableString; [JSONName('end_time')] [Nullable] FEndTime: NullableString; public constructor Create; override; property StartTime: NullableString read FStartTime; property EndTime: NullableString read FEndTime; end; TTimeWindowArray = TArray<TTimeWindow>; TTrackingArrival = class(TGenericParameters) private [JSONName('from_unix_timestamp')] [Nullable] FFromUnixTimestamp: NullableInteger; [JSONName('to_unix_timestamp')] [Nullable] FToUnixTimestamp: NullableInteger; public constructor Create; override; property FromUnixTimestamp: NullableInteger read FFromUnixTimestamp; property ToUnixTimestamp: NullableInteger read FToUnixTimestamp; end; TTrackingArrivalArray = TArray<TTrackingArrival>; TTrackingLocation = class(TGenericParameters) private [JSONName('lat')] [Nullable] FLatitude: NullableDouble; [JSONName('lng')] [Nullable] FLongitude: NullableDouble; [JSONName('info')] [Nullable] FInfo: NullableString; [JSONName('show_info')] [Nullable] FShowInfo: NullableBoolean; [JSONName('icon')] [Nullable] FIcon: NullableString; [JSONName('size')] [Nullable] FSize: NullableInteger; [JSONName('anchor')] FAnchors: TIntegerArray; [JSONName('popupAnchor')] FPopupAnchor: TIntegerArray; [JSONName('angle')] [Nullable] FAngle: NullableInteger; [JSONName('custom_data')] FCustomData: TStringArray; [JSONName('time_windows')] [NullableArray(TTimeWindow)] FTimeWindows: TTimeWindowArray; public constructor Create; override; property Latitude: NullableDouble read FLatitude; property Longitude: NullableDouble read FLongitude; property Info: NullableString read FInfo; property ShowInfo: NullableBoolean read FShowInfo; property Icon: NullableString read FIcon; property Size: NullableInteger read FSize; property Anchors: TIntegerArray read FAnchors; property PopupAnchor: TIntegerArray read FPopupAnchor; property Angle: NullableInteger read FAngle; property CustomData: TStringArray read FCustomData; property TimeWindows: TTimeWindowArray read FTimeWindows; end; TTrackingLocationArray = TArray<TTrackingLocation>; /// <summary> /// Tracking numbers are numbers given to packages when they are shipped /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Tracking_number.dtd /// </remarks> TTrackingData = class(TGenericParameters) private [JSONName('tracking_number')] [Nullable] FTrackingNumber: NullableString; [JSONName('status_history')] [NullableArray(TStatusHistory)] FStatusHistory: TStatusHistoryArray; [JSONName('locations')] [NullableArray(TTrackingLocation)] FLocations: TTrackingLocationArray; [JSONName('custom_data')] [NullableObject(TDictionaryStringIntermediateObject)] FCustomData: NullableObject; [JSONName('arrival')] [NullableArray(TTrackingArrival)] FArrivals: TTrackingArrivalArray; [JSONName('delivered')] [Nullable] FDelivered: NullableBoolean; public /// <remarks> /// Constructor with 0-arguments must be and be public. /// For JSON-deserialization. /// </remarks> constructor Create; override; /// <summary> /// An unique internal ID of a tracking number object /// </summary> property TrackingNumber: NullableString read FTrackingNumber write FTrackingNumber; /// <summary> /// Status History /// </summary> property StatusHistory: TStatusHistoryArray read FStatusHistory; /// <summary> /// Locations /// </summary> property Locations: TTrackingLocationArray read FLocations; /// <summary> /// CustomData /// </summary> property CustomData: NullableObject read FCustomData; /// <summary> /// Arrivals /// </summary> property Arrivals: TTrackingArrivalArray read FArrivals; /// <summary> /// The original timestamp in unix timestamp format at the moment location transaction event /// </summary> property Delivered: NullableBoolean read FDelivered; end; TTrackingDataArray = TArray<TTrackingData>; TTrackingDataList = TObjectList<TTrackingData>; implementation { TTrackingData } constructor TTrackingData.Create; begin FTrackingNumber := NullableString.Null; FCustomData := NullableObject.Null; FDelivered := NullableBoolean.Null; SetLength(FStatusHistory, 0); SetLength(FLocations, 0); SetLength(FArrivals, 0); end; { TStatusHistory } constructor TStatusHistory.Create; begin inherited; FUnixTimestamp := NullableInteger.Null; FInfo := NullableString.Null; end; function TStatusHistory.GetInfo: TTrackingInfo; var TrackingInfo: TTrackingInfo; begin Result := TTrackingInfo.tiUnknown; if FInfo.IsNotNull then for TrackingInfo := Low(TTrackingInfo) to High(TTrackingInfo) do if (FInfo = TTrackingInfoDescription[TrackingInfo]) then Exit(TrackingInfo); end; { TTimeWindow } constructor TTimeWindow.Create; begin inherited; FStartTime := NullableString.Null; FEndTime := NullableString.Null; end; { TTrackingLocation } constructor TTrackingLocation.Create; begin inherited; FLatitude := NullableDouble.Null; FLongitude := NullableDouble.Null; FInfo := NullableString.Null; FShowInfo := NullableBoolean.Null; FIcon := NullableString.Null; FSize := NullableInteger.Null; FAngle := NullableInteger.Null; SetLength(FAnchors, 0); SetLength(FPopupAnchor, 0); SetLength(FCustomData, 0); SetLength(FTimeWindows, 0); end; { TTrackingArrival } constructor TTrackingArrival.Create; begin inherited; FFromUnixTimestamp := NullableInteger.Null; FToUnixTimestamp := NullableInteger.Null; end; end.
{ Private include file for the Pascal front end to the source to source * translator. } %include 'sys.ins.pas'; %include 'util.ins.pas'; %include 'string.ins.pas'; %include 'file.ins.pas'; %include 'syo.ins.pas'; %include 'sst.ins.pas'; const max_cvar_length = 32; {max allowable compiler variable length} type { * Intrinsic functions in Domain Pascal. } ifunc_k_t = ( {list of the Pascal intrinsic functions} ifunc_abs_k, {absolute value of arg1} ifunc_addr_k, {universal pointer to arg1} ifunc_arctan_k, {arctangent of arg1} ifunc_arshft_k, {arithmetic shift arg1 right by arg2 bits} ifunc_chr_k, {convert integer to CHAR, use low 8 bits} ifunc_cos_k, {cosine of arg1} ifunc_exp_k, {E**arg1} ifunc_firstof_k, {first possible value of arg1 data type} ifunc_lastof_k, {last possible value of arg1 data type} ifunc_ln_k, {natural log of arg1} ifunc_lshft_k, {shift arg1 left arg2 bits} ifunc_max_k, {maximum of args 1-N, two args minimum} ifunc_min_k, {minimum of args 1-N, two args minimum} ifunc_odd_k, {TRUE if arg1 is odd} ifunc_ord_k, {ordinal value of arg1} ifunc_pred_k, {next lower (predecessor) value of arg1} ifunc_round_k, {convert arg1 to integer, round to nearest} ifunc_rshft_k, {shift arg1 right arg2 bits} ifunc_sin_k, {sine of arg1} ifunc_sizeof_k, {align-padded size of arg1 data type} ifunc_sqr_k, {square of arg1} ifunc_sqrt_k, {square root of arg1} ifunc_succ_k, {next higher (successor) value of arg1} ifunc_trunc_k, {convert arg1 to integer, round towards zero} ifunc_xor_k, {excluse or of args 1-N, two args minimum} { * Other intrinsic functions that are "extensions" to Domain Pascal. } ifunc_alignof_k, {minimum alignment needed by arg1 data type} ifunc_arctan2_k, {arctangent of arg1/arg2} ifunc_offset_k, {machine address offset of field in record} ifunc_shift_k, {shift arg1 right arg2 bits, arg2 signed} ifunc_szchar_k, {num chars storable in arg1 data type} ifunc_szmin_k, {unpadded size of arg1 data type} ifunc_setof_k, {creates explicitly typed set expression} { * Temporary intrinsic functions that help test the translator. } ifunc_val_k); {returns argument value as direct constant} top_block_k_t = ( {what kind of structure is top nested block} top_block_none_k, {undetermined, or not in top block yet} top_block_prog_k, {top block is PROGRAM} top_block_module_k); {top block is MODULE} sst_sym_front_t = record {data for our private symbols} ifunc: ifunc_k_t; end; var (sst_r_pas) error_syo_found: boolean; {TRUE on syntax error} addr_of: boolean; {TRUE if processing ADDR function argument} top_block: top_block_k_t; {what kind of structure is top nested block} nest_level: sys_int_machine_t; {nesting level, module/program = 1} { * Pointers to data type definition blocks for the PASCAL pre-defined data types. } dtype_i16_p: sst_dtype_p_t; {INTEGER16} dtype_i32_p: sst_dtype_p_t; {INTEGER32} dtype_str_p: sst_dtype_p_t; {STRING} { * Entry point declarations. } procedure sst_r_pas_data_type ( {process DATA_TYPE} in out dtype_p: sst_dtype_p_t); {returned pointer to new or reused data type} extern; procedure sst_r_pas_dtype_record ( {process RECORD_DATA_TYPE} in out d: sst_dtype_t); {returned pointer to newly created data type} extern; procedure sst_r_pas_doit ( {read input source code into in-memory data} in fnam: univ string_var_arg_t; {raw input file name} in out gnam: univ string_var_arg_t; {returned as generic name of input file} out stat: sys_err_t); {completion status code} extern; procedure sst_r_pas_exp ( {create compiled expression from input stream} in exp_str_h: syo_string_t; {SYO string handle for whole EXPRESSION syntax} in nval_err: boolean; {unknown value at compile time is err if TRUE} out exp_p: sst_exp_p_t); {returned pointer to new expression def} extern; procedure sst_r_pas_exp_eval ( {find constant value of EXPRESSION syntax} out val: sst_var_value_t); {value of EXPRESSION} extern; procedure sst_r_pas_exp_sym ( {point to symbol that is EXPRESSION} out sym_p: sst_symbol_p_t); {error if EXPRESSION is not just one symbol} extern; procedure sst_r_pas_exp_term ( {read and process next term in expression} in term_str_h: syo_string_t; {SYO string handle for whole term} in nval_err: boolean; {unknown value at compile time is err if TRUE} out term: sst_exp_term_t); {term descriptor to fill in} extern; procedure sst_r_pas_ifunc ( {process intrinsic function call} in sym: sst_symbol_t; {symbol descriptor for intrinsic function} in out term: sst_exp_term_t); {filled in descriptor for term in expression} extern; procedure sst_r_pas_integer ( {read UNSIGNED_LIT_INTEGER and return value} out ival: sys_int_max_t); {returned integer value} extern; procedure sst_r_pas_item ( {create compiled item from input stream} out term: sst_exp_term_t); {expression term descriptor to fill in} extern; procedure sst_r_pas_item_eval ( {find constant value of ITEM syntax} out val: sst_var_value_t); {returned value of ITEM} extern; procedure sst_r_pas_lit_string ( {read LIT_STRING syntax and return string} in out str: univ string_var_arg_t); {returned string} extern; procedure sst_r_pas_preproc ( {pre-processor before syntaxer interpretation} out line_p: syo_line_p_t; {points to descriptor for line chars are from} out start_char: sys_int_machine_t; {starting char within line, first = 1} out n_chars: sys_int_machine_t); {number of characters returned by this call} extern; procedure sst_r_pas_preproc_init; {init our pre-syntaxer processor} extern; procedure sst_r_pas_proc_args ( {process PARAMETER_DECLARATION syntax} in out proc: sst_proc_t); {top level procedure descriptor} extern; procedure sst_r_pas_raw_sment; {build opcodes from RAW_STATEMENT syntax} extern; procedure sst_r_pas_routine ( {create routine descriptor} in str_rout_h: syo_string_t; {string handle to whole call} in v: sst_var_t; {"variable" descriptor for routine name} in args_here: boolean; {TRUE if FUNCTION_ARGUMENTS syntax exists} out proc_p: sst_proc_p_t); {will point to new routine descriptor} extern; procedure sst_r_pas_statement ( {process STATEMENT syntax} out stat: sys_err_t); extern; procedure sst_r_pas_statements; {build opcodes from STATEMENTS syntax} extern; procedure sst_r_pas_sment_case ( {CASE statement, inside RAW_STATEMENT syntax} in str_all_h: syo_string_t); {string handle for whole CASE statement} extern; procedure sst_r_pas_sment_const; {process CONST_STATEMENT syntax} extern; procedure sst_r_pas_sment_define; {process DEFINE_STATEMENT syntax} extern; procedure sst_r_pas_sment_label; {process LABEL_STATEMENT syntax} extern; procedure sst_r_pas_sment_module ( {proces MODULE_STATEMENT syntax} in str_mod_h: syo_string_t); {string handle to MODULE_STATEMENT syntax} extern; procedure sst_r_pas_sment_prog ( {process PROGRAM_STATEMENT syntax} in str_prog_h: syo_string_t); {string handle to PROGRAM_STATEMENT syntax} extern; procedure sst_r_pas_sment_rout ( {process ROUTINE_HEADING syntax} in str_all_h: syo_string_t); {string handle for whole statement} extern; procedure sst_r_pas_sment_type; {process TYPE_STATEMENT syntax} extern; procedure sst_r_pas_sment_var; {process VAR_STATEMENT syntax} extern; procedure sst_r_pas_syn_pad ( {implements PAD syntax} out mflag: syo_mflag_k_t); {syntax matched yes/no, use SYO_MFLAG_xxx_K} extern; procedure sst_r_pas_syn_type ( {run TYPE_SUBSTATEMENT syntax} out mflag: syo_mflag_k_t); {syntax matched yes/no, use SYO_MFLAG_xxx_K} extern; procedure sst_r_pas_syn_var ( {run VAR_SUBSTATEMENT syntax} out mflag: syo_mflag_k_t); {syntax matched yes/no, use SYO_MFLAG_xxx_K} extern; procedure sst_r_pas_var_init ( {process VAR_INITIALIZER syntax} in dtype: sst_dtype_t; {data type that init value must match} out exp_p: sst_exp_p_t); {returned pointing to initial value expression} extern; procedure sst_r_pas_variable ( {process VARIABLE syntax} out var_p: sst_var_p_t); {returned pointer to VAR descriptor} extern; procedure sst_r_pas_vparam ( {apply VAL_PARAM to routine template} in out proc: sst_proc_t); {routine descriptor that will have args fixed} extern; procedure sst_r_pas_write; {process WRITE and WRITELN statements} extern;
unit ssDBComboBox; interface uses SysUtils, Classes, Controls, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxDBLookupComboBox, ssMemDS, DB; type TssDBComboBox = class(TcxDBLookupComboBox) private FmdData: TssMemoryData; FsrcData: TDataSource; FLoading: boolean; FDefFieldName: string; procedure ReloadData; procedure SetDefFieldName(const Value: string); protected procedure PropertiesChanged(Sender: TObject); override; public property DataBinding; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property DefFieldName: string read FDefFieldName write SetDefFieldName; end; implementation { TssDBComboBox } constructor TssDBComboBox.Create(AOwner: TComponent); begin inherited; FmdData:=TssMemoryData.Create(nil); FsrcData:=TDataSource.Create(nil); FsrcData.DataSet:=FmdData; end; destructor TssDBComboBox.Destroy; begin FmdData.Free; FsrcData.Free; inherited; end; procedure TssDBComboBox.PropertiesChanged(Sender: TObject); begin ReloadData; inherited; end; procedure TssDBComboBox.ReloadData; var DS: TDataSet; i: integer; begin if not FLoading and not (csDesigning in ComponentState) then try FLoading:=True; DS:=nil; if (Self.Properties.ListSource<>nil) then DS:=Self.Properties.ListSource.DataSet; with FmdData do begin Close; if Assigned(DS) then begin CopyStructure(DS); Open; if DS.Active then begin for i:=0 to Fields.Count-1 do Fields[i].ReadOnly:=False; LoadFromDataSet(DS, DS.RecordCount, lmAppend); end; DataBinding.DataSource:=FsrcData; DataBinding.DataField:=Properties.KeyFieldNames; try if DefFieldName<>'' then Self.Properties.ListSource.DataSet.Locate(DefFieldName, 1, []); except end; end; end; finally FLoading:=False; end; end; procedure TssDBComboBox.SetDefFieldName(const Value: string); begin FDefFieldName := Value; try if not (csDesigning in ComponentState) then Properties.ListSource.DataSet.Locate(Value, 1, []); except end; end; end.
unit format_tms32; {$mode delphi} interface uses eeg_type, sysutils,dialogs, DateUtils; //function LoadTMS32(lFilename: string; var lEEG: TEEG): boolean; function WriteTMS32(lFilename: string; var lEEG: TEEG): boolean; implementation const kSig = chr($0d)+chr($0a)+chr($1a); type TDOSTIME = packed record //Next: Poly5 header Year,Month,Day,DayofWeek,Hour,Minute,Second: smallint; end; TEEGHdr = packed record //Next: Poly5 header //ID: array [1..32] of char; //unused //VER: Word; //unused ` MeasureName: array [1..81] of char; //unused SR: smallint; //samplerate ` StoreFreq: smallint; //must eqaul sample freq ` StoreType: byte; //Must be 0 (Hz) ` NS: smallint; //number of channels ` NP: integer; // number of periods ` NPpad: integer; //pads nPeriods to 8 bytes DOSTIME: TDOSTIME; //unused NB: integer; //num blocks ` PB: smallint; //periods per block (multiple of 16) ` SD: smallint; //size of sample data Compression: Word; //unused -must be zero ReservedTxt: array [1..64] of char; //unused ` end; //TNIFTIhdr Header Structure TLeadHdr = packed record //Next: Poly5 header LeadName: array [1..41] of char; Reserved: DWord; UN: array [1..11] of char; UL: single; // ` UH: single; // AL: single; // ` AH: single; // SI: smallint; Unused: smallint; UnusedStr: array [1..60] of char; end; TBlockHdr = packed record //Next: Poly5 header PI: integer; Reserved: integer; //pad for PI DOSTIME: TDOSTIME; //unused Reserved2: array [1..64] of char; end; procedure Str2Array(lIn: string; var lOut: array of char); var Len,i: integer; begin Len := length(lIn); if length(lOut) < Len then Len := length(lOut); if Len < 1 then exit; for i := 1 to Len do lOut[i] := lIn[i]; if Len < length(lOut) then for i := Len+1 to length(lOut) do lOut[i] := chr(0); lOut[0] := chr(Len); end; function TDate2Dos (lTime: TDateTime): TDOSTIME; begin result.Day := DayOf(lTime); result.Month := MonthOf(lTime); result.Year := YearOf(lTime); result.Hour := HourOf(lTime); result.Minute := MinuteOf(lTime); result.Second := SecondOf(lTime); end; (*function LoadTMS32(lFilename: string; var lEEG: TEEG): boolean; //The Poly5 data format can store 16-bit int data //The TMS32 version can store 32-bit float, 16-bit int or mixture of data //This function currently only supports pure 32-bit float... //... will report incompatible variants to the user. //I would rather add support when I have same files to test. function DOSTIMEToStr (lDOS: TDOSTIME; var lTIME: TDateTime): string; begin if not IsValidDateTime(lDOS.Year, lDOS.Month, lDOS.Day, lDOS.Hour, lDOS.Minute, lDOS.Second, 0) then begin lTime := Now; result := (FormatDateTime('yyyymmdd_hhnnss', (Now))) ; exit; end; lTime := EncodeDateTime(lDOS.Year, lDOS.Month, lDOS.Day, lDOS.Hour, lDOS.Minute, lDOS.Second,0); result := (FormatDateTime('yyyymmdd_hhnnss', (lTime))) end; function ParseLeadName(LeadHdr: TLeadHdr): string; var j: integer; c: char; begin result := ''; for j := 1 to 41 do begin c := LeadHdr.LeadName[j]; if c in ['0'..'9','a'..'z','A'..'Z'] then //if LeadHdr.LeadName[j] <> chr(0) then result := result+LeadHdr.LeadName[j]; end; result := result; end; FUNCTION specialsingle (var s:single): boolean; //returns true if s is Infinity, NAN or Indeterminate //4byte IEEE: msb[31] = signbit, bits[23-30] exponent, bits[0..22] mantissa //exponent of all 1s = Infinity, NAN or Indeterminate CONST kSpecialExponent = 255 shl 23; VAR Overlay: LongInt ABSOLUTE s; BEGIN IF ((Overlay AND kSpecialExponent) = kSpecialExponent) THEN RESULT := true ELSE RESULT := false; END; function ClipStr (lStr: string; NumChar: integer): string; var i,len: integer; begin result := lStr; len := length(lStr); if len<= NumChar then exit; result := ''; for i := NumChar+1 to len do result := result + lStr[i]; end; var fp: file; EEGHdr: TEEGHdr; LeadHdr: TLeadHdr; BlockHdr:TBlockHdr; lVers: word; lChan, I, Block,lSample,lLead,q: integer; lStr: string; DataRA : array of single; lSig: array[1..3] of char; begin result := false; FileMode := 0; //set to readonly AssignFile(fp, lFileName); Reset(fp, 1); if FileSize(fp) < sizeof(TEEGHdr) then begin Showmessage('To small to be an TMS32 file :'+lFilename); exit; end; seek(fp, 28); BlockRead(fp, lSig, 3); if lSig <> kSig then begin seek(fp, 29); BlockRead(fp, lSig, 3); if lSig <> kSig then begin Showmessage('Incorrect signature for TMS32'); exit; end; end; BlockRead(fp, lVers,sizeof(lVers)); //fx(lvers); BlockRead(fp, EEGHdr, SizeOf(TEEGHdr)); if EEGHdr.StoreType<>0 then raise Exception.Create('TMS32 Storage type not supported '+inttostr(EEGHdr.StoreType)); if EEGHdr.Compression<>0 then raise Exception.Create('TMS32 compression not supported'); if EEGHdr.SR<>EEGHdr.StoreFreq then raise Exception.Create('TMS32 Sample Freqeuncy is not the Store Frequency'); //lEEG.SequenceInfo := //fx(EEGHdr.SR,EEGHdr.NB,EEGHdr.PB); // fx(EEGHdr.SD); DOSTIMEToStr(EEGHdr.DOSTIME, lEEG.Time); setlength(lEEG.Channels,EEGHdr.NS div 2); ClearEEGHdr (lEEG); lChan := 0; for I:=1 to EEGHdr.NS do begin BlockRead(fp, LeadHdr,SizeOf(TLeadHdr)); //fx(LeadHdr.AL,LeadHdr.AH); lStr := ParseLeadName(LeadHdr); if odd(I) and (lStr[1] = 'L') and (lStr[2] = 'o') then else if not (odd(I)) and (lStr[1] = 'H') and (lStr[2] = 'i') then else raise Exception.Create('Current version only supports 32-bit data.'); if odd(I) then begin lEEG.Channels[lChan].info := ClipStr(lStr,2); lEEG.Channels[lChan].unittype := Trim(LeadHdr.UN); lEEG.Channels[lChan].SampleRate :=EEGHdr.SR; lEEG.Channels[lChan].SignalLead := (Trim(LeadHdr.UN)[1] = 'µ'); inc(lChan); end; end; //now read data.... setlength(lEEG.Samples,lChan,EEGHdr.NP); setlength(DataRA,EEGHdr.PB*lChan); //next read data i := 0; for Block := 1 to (EEGHdr.NB) do begin BlockRead(fp,BlockHdr,SizeOf(TBlockHdr)); if i <> BlockHdr.PI then showmessage('Data not contiguous: expected sample '+inttostr(i)+', but found sample '+ inttostr(BlockHdr.PI)); BlockRead(fp,DataRA[0],EEGHdr.PB*lChan * sizeof(single)); for lSample := 0 to (EEGHdr.PB*lChan)-1 do if specialsingle (DataRA[lSample]) then DataRA[lSample] := 0; q := 0; for lSample := 1 to EEGHdr.PB do begin if i < EEGHdr.NP then begin //the final block may not be filled with samples, e.g. if 128 samples per block, and only 200 samples collected for lLead:=0 to lChan-1 do begin lEEG.Samples[lLead][i] := DataRA[q]; inc(q); end; end; //if i inc(i); end; end;//for each block CloseFile(fp); FileMode := 2; //set to read-write result := true; end; //LoadTMS32 *) function WriteTMS32(lFilename: string; var lEEG: TEEG): boolean; const kSig3= 'POLY SAMPLE FILEversion 2.03'+kSig+chr(203)+chr(0); kSig4= 'POLY SAMPLE FILE version 2.04'+kSig+chr(204)+chr(0); kBlockSize = 336; var fp: file; EEGHdr: TEEGHdr; LeadHdr: TLeadHdr; BlockHdr:TBlockHdr; lChan, I, Block,lSample,lLead,q: integer; DataRA : array of single; begin result := false; if MaxNumSamples(lEEG) < 1 then exit; FillChar(EEGHdr, SizeOf(TEEGHdr), 0); FillChar(LeadHdr, SizeOf(TLeadHdr), 0); FillChar(BlockHdr, SizeOf(TBlockHdr), 0); FileMode := 2; //set to read/write AssignFile(fp, lFileName); Rewrite(fp, 1); //if Format203 then BlockWrite(fp, kSig3, length(kSig3)); //else //format 204 // BlockWrite(fp, kSig4, length(kSig4)); Str2Array('Poly5 File',EEGHdr.MeasureName); EEGHdr.DOSTIME := TDate2Dos(lEEG.Time); EEGHdr.NS := NumChannels(lEEG)*2; EEGHdr.NP := MaxNumSamples(lEEG); EEGHdr.NB := (EEGHdr.NP+kBlockSize-1) div kBlockSize; //Number of blocks EEGHdr.PB := kBlockSize; //per block EEGHdr.StoreType:= 0; EEGHdr.Compression := 0; EEGHdr.SR := round(lEEG.Channels[0].SampleRate); EEGHdr.StoreFreq := EEGHdr.SR; EEGHdr.SD := EEGHdr.PB * EEGHdr.NS * 2; BlockWrite(fp, EEGHdr, SizeOf(TEEGHdr)); lChan := 0; LeadHdr.UL := 0.0; LeadHdr.UH := 1.0; LeadHdr.AL := 0.0; LeadHdr.AH := 1.0; for I:=1 to EEGHdr.NS do begin if odd(I) then Str2Array('(Lo) '+lEEG.Channels[lChan].info,LeadHdr.LeadName) else begin Str2Array('(Hi) '+lEEG.Channels[lChan].info,LeadHdr.LeadName); end; // EEGHdr.SR := round(lEEG.Channels[lChan].SampleRate); //lEEG.Channels[lChan].UnitType := '1234'; Str2Array(lEEG.Channels[lChan].unittype,LeadHdr.UN); //TLeadHdr; BlockHdr.PI := i; BlockWrite(fp, LeadHdr,SizeOf(TLeadHdr)); if not odd(i) then inc(lChan); end; setlength(DataRA,EEGHdr.PB*lChan); //next write data i := 0; lChan := NumChannels(lEEG); for Block := 1 to (EEGHdr.NB) do begin BlockHdr.PI := i; BlockWrite(fp,BlockHdr,SizeOf(TBlockHdr)); q := 0; for lSample := 1 to EEGHdr.PB do begin if i < EEGHdr.NP then begin //the final block may not be filled with samples, e.g. if 128 samples per block, and only 200 samples collected for lLead:=0 to lChan-1 do begin DataRA[q] := (lEEG.Samples[lLead][i]); inc(q); end; end; //if i inc(i); end; BlockWrite(fp,DataRA[0],EEGHdr.PB*lChan * sizeof(single)); end;//for each block CloseFile(fp); result := true; end; //WriteTMS32 end.
unit table_func_lib; interface uses SysUtils,math,TeEngine, Series, ExtCtrls, TeeProcs, Chart,classes,streaming_class_lib,streamio,simple_parser_lib,Graphics; type TAbstractMathFunc=class(TStreamingClass) private ftitle,fXname,fYname: string; fDescription: TStrings; procedure SetDescription(value: TStrings); function get_xmin: Real; virtual; abstract; function get_xmax: Real; virtual; abstract; function get_ymin: Real; virtual; abstract; function get_ymax: Real; virtual; abstract; protected fXunit,fYunit: string; function GetValue(xi: Real): Real; virtual; abstract; public constructor Create(owner: TComponent); override; destructor Destroy; override; property xmin: Real read get_xmin; property xmax: Real read get_xmax; property ymin: Real read get_ymin; property ymax: Real read get_ymax; property value[xi: Real]: Real read GetValue; default; published property title: string read ftitle write ftitle; property Xname: string read fXname write fXName; property Yname: string read fYname write fYname; property Xunit: string read fXunit write fXunit; property Yunit: string read fYunit write fYunit; property Description: Tstrings read fdescription write SetDescription; end; FourierSeriesRec = record dc: Real; //постоянная составляющая c,s: array of Real; //0 соотв. первой гармонике end; TFourierSeriesWindowType=(wtFullPeriodsRect,wtRect); //wtRect - для нахождения ряда Фурье используем все доступные данные, при этом последний период может оказаться с нулями //wtFullPeriodsRect - обрезаем справа до целого числа периодов, только по ним ищем разложение table_func=class(TAbstractMathFunc) private iOrder: Integer; fTolerance: Real; fCyclic: Boolean; _length: Integer; allocated_length: Integer; ixmin,ixmax,iymin,iymax: Real; b,c,d :array of Real; {a==Y} _oub: Boolean; changed: boolean; fIsMonotonic: Boolean; fIsIncreasing: Boolean; fchart_series: TLineSeries; procedure plus_one; //приготовить место для еще одного числа procedure update_spline(); procedure update_order(new_value: Integer); function isen: Boolean; function get_xmin: Real; override; function get_xmax: Real; override; function get_ymin: Real; override; function get_ymax: Real; override; procedure WriteData(Writer: TWriter); procedure ReadData(Reader: TReader); procedure write_to_stream(var F: Textfile); procedure read_from_stream(var F: TextFile); protected function Getvalue(xi:Real): Real; override; function InverseValue(yi: Real): Real; procedure DefineProperties(Filer: TFiler); override; function IsNonZeroTolerance: boolean; function IsMonotonic: Boolean; function IsIncreasing: Boolean; public X,Y: array of Real; function LoadFromTextFile(filename: string): Boolean; procedure LoadFromTextTable(filename: string; x_column,y_column: Integer); procedure LoadConstant(new_Y:Real;new_xmin:Real;new_xmax:Real); procedure Clear; override; procedure ClearPoints; function SaveToTextFile(filename: string): Boolean; function AsTabbedText: string; procedure normalize(); function addpoint(Xn:Real;Yn:Real): Boolean; function deletepoint(Xn:Real): Boolean; function FindPoint(val: Real;var pX,pY: Real): Boolean; property enabled: Boolean read isen; constructor Create(owner: TComponent); overload; override; constructor Create; reintroduce; overload; constructor Create(filename: string); reintroduce; overload; function GetInverse: table_func; //на свой страх и риск! procedure draw; procedure Add(c: Real); overload; procedure Add(term: table_func); overload; procedure Sub(c: Real); overload; procedure Sub(term: table_func); overload; procedure Shift(amount: Real); procedure multiply(by: table_func); overload; procedure multiply(by: Real); overload; procedure multiply_argument(by: Real); procedure assign(Source:TPersistent); override; function CalculateArea: Real; procedure morepoints; procedure derivative; overload; function derivative(xi: Real): Real; overload; function FindInterval(xi: Real): Integer; //между какими табл. значениями лежит нужное нам function InverseFindInterval(yi: Real): Integer; function FindNearestPoint(ax,ay: Real;out dist: Real): Integer; //точка, ближ. к данным коорд. function Average: Real; function RMSValue: Real; //dist - квадрат расстояния до этой точки procedure integrate; function IsEqual(t: table_func): Boolean; reintroduce; function GetB(index: Integer): Real; function GetC(index: Integer): Real; function GetD(index: Integer): Real; procedure FourierSeries(var storage: FourierSeriesRec;Period: Real=0; WindowType: TFourierSeriesWindowType=wtFullPeriodsRect); property chart_series: TLineSeries read fchart_series write fchart_series; published property order: Integer read iorder write update_order default 3; property zero_out_of_bounds: boolean read _oub write _oub default true; //поведение за границами обл. опред property Cyclic: boolean read fCyclic write fCyclic default false; property count: Integer read _length stored false; property Tolerance: Real read fTolerance write fTolerance stored IsNonZeroTolerance; // property LineColor: TColor read fLineColor write fLineColor default clBlack; end; procedure SwapReals(var X,Y: Real); implementation const eol: string=#13+#10; procedure SwapReals(var X,Y: Real); var tmp: Real; begin tmp:=X; X:=Y; Y:=tmp; end; (* TAbstractMathFunc *) constructor TAbstractMathFunc.Create(owner: TComponent); begin inherited Create(owner); fdescription:=TStringList.Create; SetSubComponent(true); end; destructor TAbstractMathFunc.Destroy; begin fdescription.Free; inherited Destroy; end; procedure TAbstractMathFunc.SetDescription(value: TStrings); begin fdescription.Assign(value); end; (* table_func *) procedure table_func.DefineProperties(Filer: TFiler); begin Filer.DefineProperty('data',ReadData,WriteData,isen); end; procedure table_func.WriteData(Writer: TWriter); var i: Integer; begin Writer.WriteListBegin; for I := 0 to Count - 1 do Writer.WriteString('('+FloatToStr(X[i])+';'+FloatToStr(Y[i])+')'); Writer.WriteListEnd; end; procedure table_func.ReadData(Reader: TReader); var p: TSimpleParser; i: Integer; begin p:=TSimpleParser.Create; _length:=0; i:=0; Reader.ReadListBegin; while not Reader.EndOfList do begin plus_one; p.AssignString(Reader.readstring); p.getChar; X[i]:=p.getFloat; Y[i]:=p.getFloat; inc(i); end; Reader.ReadListEnd; p.Free; changed:=true; end; function table_func.IsNonZeroTolerance: Boolean; begin Result:=(fTolerance<>0); end; procedure table_func.plus_one; begin inc(_length); if _length>allocated_length then begin allocated_length:=(allocated_length shl 1)+1; SetLength(X,allocated_length); SetLength(Y,allocated_length); end; end; constructor table_func.Create; begin Create(nil); end; constructor table_func.Create(owner: TComponent); begin inherited Create(owner); iorder:=3; tolerance:=1e-27; _oub:=true; Clear; chart_series:=nil; end; constructor table_func.Create(filename: string); begin Create(owner); LoadFromTextFile(filename); end; function table_func.isen: Boolean; begin isen:=(count>0); end; function table_func.FindInterval(xi: Real): Integer; var i,j,k: Integer; label found; begin if changed then update_spline; {сначала двоичный поиск нужного отрезка сплайна} i:=0; j:=count-1; //цикл может не выполниться, если массив пустой (High(X)=-1) if j<i then begin Result:=-2; Exit; end; if xi>xmax then begin Result:=count; exit; end else if xi<xmin then begin Result:=-1; exit; end; k:=0; while j>=i do begin k:=(i+j) shr 1; if xi<X[k] then j:=k-1 else if xi>X[k] then i:=k+1 else goto found; end; if xi<X[k] then dec(k); found: Result:=k; end; function table_func.InverseFindInterval(yi: Real): Integer; var i,j,k: Integer; label inc_found,dec_found; begin if changed then update_spline; if not IsMonotonic then Raise Exception.Create('table_func: function should be monotonic to find inverse interval'); i:=0; j:=count-1; //цикл может не выполниться, если массив пустой (High(X)=-1) if j<i then begin Result:=-2; Exit; end; if IsIncreasing then begin if yi>ymax then begin Result:=count; exit; end else if yi<ymin then begin Result:=-1; exit; end; k:=0; while j>=i do begin k:=(i+j) shr 1; if yi<Y[k] then j:=k-1 else if yi>Y[k] then i:=k+1 else goto inc_found; end; if yi<Y[k] then dec(k); inc_found: Result:=k; end else begin if yi<ymin then begin Result:=count; exit; end else if yi>ymax then begin Result:=-1; exit; end; k:=0; while j>=i do begin k:=(i+j) shr 1; if yi>Y[k] then j:=k-1 else if yi<Y[k] then i:=k+1 else goto dec_found; end; if yi>Y[k] then dec(k); dec_found: Result:=k; end; end; function table_func.GetValue(xi: Real): Real; var k: Integer; r: Real; begin k:=FindInterval(xi); if k=-2 then if _oub then Result:=0 else Result:=NAN else if (k=-1) then if _oub then Result:=0 else Result:=Y[0] else if k>=count then if _oub then Result:=0 else Result:=Y[count-1] else begin r:=xi-X[k]; Result:=Y[k]+r*(b[k]+r*(c[k]+r*d[k])); end; end; function table_func.InverseValue(yi: Real): Real; var k: Integer; begin if not IsMonotonic then Raise Exception.Create('table_func: can''t inverse non-monotonic function'); k:=InverseFindInterval(yi); if k=-2 then if _oub then Result:=0 else Result:=NAN //вообще пустая функция, ни одного знач else if (k=-1) then if _oub then Result:=0 else Result:=X[0] else if k>=count then if _oub then Result:=0 else Result:=X[count-1] else begin // if (k<0) or (k>=count) then Result:=NAN; //плевать на zero_out_of_bounds, все равно //по Y значения вне интервала недопустимы if order=0 then Result:=X[k] else if order=1 then Result:=X[k]+(yi-Y[k])/b[k] else Raise Exception.Create('sorry'); end; end; procedure table_func.draw; var i,w: Integer; t,st,t_xmin,t_xmax: Real; begin if (chart_series<>nil) and isen then begin // w:=chart_series.ParentChart.ClientWidth; w:=1280; if chart_series.GetHorizAxis.AutomaticMinimum then t_xmin:=xmin else t_xmin:=max(chart_series.GetHorizAxis.Minimum,xmin); if chart_series.GetHorizAxis.AutomaticMaximum then t_xmax:=xmax else t_xmax:=min(chart_series.GetHorizAxis.Maximum,xmax); st:=(t_xmax-t_xmin)/w; (* if chart_series.ParentChart.BottomAxis.Automatic then begin t_xmin:=xmin; st:=(xmax-t_xmin)/w; end else begin t_xmin:=chart_series.ParentChart.BottomAxis.Minimum; st:=(chart_series.ParentChart.BottomAxis.Maximum-t_xmin)/w; end; *) chart_series.Clear; for i:=0 to w do begin t:=t_xmin+st*i; chart_series.AddXY(t,GetValue(t)); end; end; end; procedure table_func.update_spline; var i,j: Integer; h,alpha,l,mu,z: array of Real; {для вычисления сплайнов} begin changed:=false; j:=count-1; allocated_length:=count; SetLength(X,count); //самое время сократить расход памяти SetLength(Y,count); Setlength(b,count); Setlength(c,count); Setlength(d,count); if not enabled then Exit; //макс и мин значения ixmin:=X[0]; ixmax:=ixmin; iymin:=Y[0]; iymax:=iymin; for i:=1 to j do begin if X[i]<ixmin then ixmin:=X[i]; if X[i]>ixmax then ixmax:=X[i]; if Y[i]<iymin then iymin:=Y[i]; if Y[i]>iymax then iymax:=Y[i]; end; //собственно сплайны for i:=0 to j do begin b[i]:=0; c[i]:=0; d[i]:=0; end; fisIncreasing:=Y[j]>Y[0]; //это будет верно в случае монотон. роста но не обязано, если не монотон fisMonotonic:=true; if (order and 2)=0 then begin //т.е order=0 или order=1 for i:=1 to j do if (fIsIncreasing and (Y[i]<=Y[i-1])) or (not fIsIncreasing and (Y[i]>=Y[i-1])) then begin fIsMonotonic:=false; break; end; end; if iorder=0 then exit else begin SetLength(h,count); for i:=0 to j-1 do h[i]:=X[i+1]-X[i]; if iorder=1 then begin for i:=0 to j-1 do b[i]:=(Y[i+1]-Y[i])/h[i]; exit; end; fIsMonotonic:=false; //пока возможность инверсии отключим тем самым if iorder=2 then begin if j=0 then Exit; // c[0]:=0; это и так выполняется b[0]:=(Y[1]-Y[0])/h[0]; for i:=1 to j-1 do begin b[i]:=b[i-1]+2*c[i-1]*h[i-1]; c[i]:=(y[i+1]-y[i]-b[i]*h[i])/h[i]/h[i]; end; Exit; end; Setlength(alpha,count); SetLength(l,count); SetLength(mu,count); SetLength(z,count); for i:=1 to j-1 do alpha[i]:=3/h[i]*(Y[i+1]-Y[i])-3/h[i-1]*(Y[i]-Y[i-1]); l[0]:=1; mu[0]:=0; z[0]:=0; for i:=1 to j-1 do begin l[i]:=2*(X[i+1]-X[i-1])-h[i-1]*mu[i-1]; mu[i]:=h[i]/l[i]; z[i]:=(alpha[i]-h[i-1]*z[i-1])/l[i]; end; l[j]:=1; z[j]:=0; c[j]:=0; for i:=j-1 downto 0 do begin c[i]:=z[i]-mu[i]*c[i+1]; b[i]:=(Y[i+1]-Y[i])/h[i]-h[i]*(c[i+1]+2*c[i])/3; d[i]:=(c[i+1]-c[i])/3/h[i]; end; end; end; procedure table_func.update_order(new_value: Integer); begin iOrder:=new_value; changed:=true; end; function table_func.addpoint(Xn:Real;Yn:Real): boolean; //это для правильной работы undo var i,k: Integer; begin i:=count-1; //сейчас указывает на последний элемент в массиве plus_one; while (i>=0) and (Xn<X[i]) do dec(i); //i будет указывать на максимальный элемент, меньший Xn //проверим, а вдруг совпадает if (i>=0) and (abs(Xn-X[i])<=Tolerance) then begin dec(_length); if abs(Yn-Y[i])<=Tolerance then begin result:=false; //ничего не изменилось exit; end else begin Y[i]:=Yn; changed:=true; result:=true; Exit; end; end; //i указывает на максимальный элемент, меньший вставляемого //теперь вставляем в нужное место inc(i); k:=count-1; while k>i do begin X[k]:=X[k-1]; Y[k]:=Y[k-1]; dec(k); end; X[i]:=Xn; Y[i]:=Yn; changed:=true; result:=true; end; function table_func.FindPoint(val: Real;var pX,pY: Real): boolean; //существует ли уже такая точка? var i,l: Integer; begin if not enabled then begin result:=false; exit; end; l:=count-1; i:=l; while (abs(val-X[i])>Tolerance) do begin dec(i); if i=-1 then begin result:=false; exit; end; end; pX:=X[i]; pY:=Y[i]; Result:=true; end; function table_func.deletepoint(Xn: Real): boolean; var i,l: Integer; begin if not enabled then begin result:=false; exit; end; l:=count-1; i:=l; while (abs(Xn-X[i])>Tolerance) do begin dec(i); if i=-1 then begin result:=false; exit; end; end; //на этом месте i указывает на элемент, который надо удалить. while i<l do begin X[i]:=X[i+1]; Y[i]:=Y[i+1]; inc(i); end; dec(_length); changed:=true; result:=true; end; procedure table_func.read_from_stream(var F: TextFile); var s0,s,t: string; i,j,k: Integer; section: (general,descr,data); separator: char; begin separator:=DecimalSeparator; Reset(F); _length:=0; section:=data; i:=0; repeat ReadLn(F,s); //пропустим пробелы и табуляцию j:=1; while (j<=Length(s)) and ((s[j]=' ') or (s[j]=#9)) do inc(j); //и в конце строки тоже k:=Length(s); while (k>=j) and ((s[k]=' ') and (s[k]=#9)) do dec(k); t:=copy(s,j,k+1-j); s0:=uppercase(t); if (s0='[GENERAL]') then begin section:=general; continue; end; if (s0='[DESCRIPTION]') then begin section:=descr; continue; end; if (s0='[DATA]') then begin section:=data; continue; end; if section=general then begin k:=Length(t); s0:=copy(s0,1,6); if (s0='TITLE=') then begin title:=copy(t,7,k); continue; end; if (s0='XNAME=') then begin Xname:=copy(t,7,k); continue; end; if (s0='YNAME=') then begin Yname:=copy(t,7,k); continue; end; if (s0='XUNIT=') then begin Xunit:=copy(t,7,k); continue; end; if (s0='YUNIT=') then begin Yunit:=copy(t,7,k); continue; end; if (s0='ORDER=') then begin order:=StrToInt(copy(t,7,k)); continue; end; if (s0='BOUND=') then begin zero_out_of_bounds:=(StrToInt(copy(t,7,k))=1); continue; end; end; if section=descr then begin description.Add(s); end; if section=data then begin if Length(s)=0 then begin if eof(F) then break else continue; end; if ((s[1]<>'/') or (s[2]<>'/')) and (s[1]<>'[') and (length(s)>2) then begin {skip spaces} j:=1; while (j<=Length(s)) and ((s[j]=' ') or (s[j]=#9)) do inc(j); {find end of number} k:=j; while (k<=Length(s)) and ((s[k]<>' ') and (s[k]<>#9)) do begin if (s[k]='.') or (s[k]=',') then s[k]:=separator; inc(k); end; {manage dynamic array in asimptotically fast way} plus_one; {assigning values} X[i]:=StrToFloat(copy(s,j,k-j)); {skip spaces} j:=k; while (j<=Length(s)) and ((s[j]=' ') or (s[j]=#9)) do inc(j); {find end of number} k:=j; while (k<=Length(s)) and ((s[k]<>' ') and (s[k]<>#9)) do begin if (s[k]='.') or (s[k]=',') then s[k]:=separator; inc(k); end; Y[i]:=StrToFloat(copy(s,j,k-j)); inc(i); end; end; until eof(F); if i>0 then begin changed:=true; {Теперь определить макс/мин значения, посчитать коэф. сплайнов} end; end; function table_func.LoadFromTextFile(filename: string): Boolean; var F: TextFile; begin try Result:=false; AssignFile(F,filename); read_from_stream(F); Result:=true; finally CloseFile(F); end; end; (*$WARNINGS OFF*) //компилятор боится, что cX и cY будут не определены. Что ж, в этом есть смысл //если x_column/y_column бред содержат, то так и будет procedure table_func.LoadFromTextTable(filename: string; x_column,y_column: Integer); var p: TSimpleParser; F: TextFile; s: string; i: Integer; cX,cY: Real; begin Clear; p:=TSimpleParser.Create; p.delimiter:=' '+#9; //возможно, придется новый парам. ввести в парсере-игнорировать пустые знач p.spaces:=''; AssignFile(F,filename); Reset(F); while not eof(F) do begin ReadLn(F,s); p.AssignString(s); i:=1; //первый столбец именно первый, а не нулевой, будем так считать while i<=max(x_column,y_column) do begin if i=x_column then cX:=p.getFloat else if i=y_column then cY:=p.getFloat else p.getFloat; inc(i); end; AddPoint(cX,cY); //мы точно знаем, что cX,cY инициализированы, жаль компилятор этого не понимает end; p.Free; CloseFile(F); end; (*$WARNINGS ON*) procedure table_func.write_to_stream(var F: Textfile); var old_format: boolean; i: Integer; begin Rewrite(F); old_format:=true; if (title<>'') or (Xname<>'') or (Yname<>'') or (Xunit<>'') or (Yunit<>'') or (iorder<>3) then begin Writeln(F,'[general]'); if (title<>'') then Writeln(F,'title='+title); if (Xname<>'') then Writeln(F,'Xname='+Xname); if (Yname<>'') then Writeln(F,'Yname='+Yname); if (Xunit<>'') then Writeln(F,'Xunit='+Xunit); if (Yunit<>'') then WriteLn(F,'Yunit='+Yunit); if Zero_out_of_bounds then WriteLn(F,'bound=1'); WriteLn(F,'order='+IntToStr(order)); old_format:=false; end; if description.Count>0 then begin WriteLn(F,'[description]'); for i:=0 to description.Count-1 do WriteLn(F,description[i]); old_format:=false; end; if (old_format=false) then WriteLn(F,'[data]'); for i:=0 to count-1 do begin WriteLn(F,FloatToStr(X[i])+#9+FloatToStr(Y[i])); end; end; function table_func.SaveToTextFile(filename: string): Boolean; var F: TextFile; begin try Result:=false; assignFile(F,filename); write_to_stream(F); Result:=true; finally Closefile(F); end; end; procedure table_func.LoadConstant(new_Y:Real;new_xmin:Real;new_xmax:Real); begin Setlength(X,1); SetLength(Y,1); Setlength(b,1); Setlength(c,1); Setlength(d,1); _length:=1; ixmin:=new_xmin; ixmax:=new_xmax; iymin:=new_Y; iymax:=iymin; X[0]:=ixmin; Y[0]:=iymin; b[0]:=0; c[0]:=0; d[0]:=0; changed:=false; end; procedure table_func.normalize; var i: Integer; begin if ymax>0 then begin for i:=0 to count-1 do begin Y[i]:=Y[i]/ymax; end; changed:=true; end; end; function table_func.Average: Real; begin Result:=CalculateArea/(xmax-xmin); end; function table_func.RMSValue: Real; var tmp: table_func; begin tmp:=table_func.Create; tmp.assign(self); tmp.multiply(Self); Result:=sqrt(tmp.Average); tmp.Free; end; procedure table_func.multiply(by: table_func); var i,ls,ld: Integer; Yt: array of Real; begin if not by.enabled then begin Clear; Exit; end; if not enabled then Exit; //xmin, xmax и прочее переделает update_spline //нам надо лишь перемножить отдельные точки ls:=by.count-1; SetLength(Yt,ls+1); for i:=0 to ls do Yt[i]:=by.Y[i]*GetValue(by.X[i]); ld:=count-1; for i:=0 to ld do Y[i]:=Y[i]*by[X[i]]; for i:=0 to ls do addpoint(by.X[i],Yt[i]); changed:=true; end; procedure table_func.Add(term: table_func); var i,ls,ld: Integer; Yt: array of Real; begin if not (term.enabled and enabled) then Exit; ls:=term.count-1; SetLength(Yt,ls+1); for i:=0 to ls do Yt[i]:=term.Y[i]+GetValue(term.X[i]); ld:=count-1; for i:=0 to ld do Y[i]:=Y[i]+term[X[i]]; for i:=0 to ls do addpoint(term.X[i],Yt[i]); changed:=true; end; procedure table_func.Sub(term: table_func); var i,ls,ld: Integer; Yt: array of Real; begin if not (term.enabled and enabled) then Exit; ls:=term.count-1; SetLength(Yt,ls+1); for i:=0 to ls do Yt[i]:=-term.Y[i]+GetValue(term.X[i]); ld:=count-1; for i:=0 to ld do Y[i]:=Y[i]-term[X[i]]; for i:=0 to ls do addpoint(term.X[i],Yt[i]); changed:=true; end; procedure table_func.multiply(by: Real); var i,ld: Integer; begin if changed then update_spline; ld:=count-1; for i:=0 to ld do begin Y[i]:=Y[i]*by; b[i]:=b[i]*by; c[i]:=c[i]*by; d[i]:=d[i]*by; end; iymin:=iymin*by; iymax:=iymax*by; end; procedure table_func.assign(source: TPersistent); var s: table_func absolute source; begin if Source is table_func then begin ixmin:=S.ixmin; ixmax:=s.ixmax; iymin:=s.iymin; iymax:=s.iymax; iOrder:=s.iOrder; _oub:=s._oub; _length:=s.count; allocated_length:=_length; title:=s.title; XName:=s.Xname; YName:=s.Yname; XUnit:=s.Xunit; YUnit:=s.Yunit; description.Assign(s.Description); //chart_series НЕ ТРОГАЕМ! Копируем функцию, но не интерфейс X:=copy(s.X,0,count); Y:=copy(s.Y,0,count); changed:=true; end else inherited Assign(Source); end; function table_func.CalculateArea: Real; var i,l: Integer; dif: Real; begin if changed then update_spline; Result:=0; l:=count-2; for i:=0 to l do begin dif:=X[i+1]-X[i]; Result:=Result+dif*(Y[i]+dif*(b[i]/2+dif*(c[i]/3+dif*d[i]/4))); end; end; procedure table_func.Clear; begin //очищаем функцию, но не интерфейс! title:=''; Xname:=''; Yname:=''; Xunit:=''; Yunit:=''; description.Clear; changed:=false; ClearPoints; end; procedure table_func.ClearPoints; begin //очищаем только точки, названия оставляем SetLength(X,0); SetLength(Y,0); SetLength(b,0); SetLength(c,0); SetLength(d,0); _length:=0; allocated_length:=0; ixmin:=0; ixmax:=0; iymin:=0; iymax:=0; end; procedure table_func.morepoints; var i,j,k: Integer; Yt: array of Real; begin //увеличить в 2 раза количество точек update_spline; j:=count-1; if j<=0 then exit; i:=2*j; //конец массива SetLength(Yt,j); for k:=0 to j-1 do begin Yt[k]:=GetValue((X[k]+X[k+1])/2); end; _length:=i+1; allocated_length:=_length; SetLength(X,_length); SetLength(Y,_length); for k:=j downto 1 do begin X[i]:=X[k]; Y[i]:=Y[k]; dec(i); X[i]:=(X[k]+X[k-1])/2; Y[i]:=Yt[k-1]; dec(i); end; changed:=true; end; function table_func.get_xmin :Real; begin if changed then update_spline; get_xmin:=ixmin; end; function table_func.get_xmax :Real; begin if changed then update_spline; get_xmax:=ixmax; end; function table_func.get_ymin :Real; begin if changed then update_spline; get_ymin:=iymin; end; function table_func.get_ymax :Real; begin if changed then update_spline; get_ymax:=iymax; end; function table_func.IsMonotonic: Boolean; begin if changed then update_spline; Result:=fIsMonotonic; end; function table_func.IsIncreasing: Boolean; begin if changed then update_spline; Result:=fIsIncreasing; end; procedure table_func.derivative; var i,j :Integer; begin if changed then update_spline; j:=count-1; dec(iOrder); if iOrder=-1 then begin iOrder:=0; end; for i:=0 to j do begin Y[i]:=b[i]; b[i]:=2*c[i]; c[i]:=3*d[i]; d[i]:=0; end; changed:=true; end; function table_func.derivative(xi: Real): Real; var k: Integer; r: Real; begin k:=FindInterval(xi); if (k<0) or (k>=count) then Result:=0 else begin r:=xi-X[k]; Result:=b[k]+r*(2*c[k]+3*d[k]*r); end; end; procedure table_func.integrate; var i,j :Integer; acc,prev_acc,r: Real; begin if not enabled then Exit; if changed then update_spline; j:=count-1; if iOrder<3 then begin //интегрируем честно, коэф. хватает, чтобы записать результат //первую итерацию "вручную", чтобы не вводить if внутрь цикла d[0]:=c[0]/3; c[0]:=b[0]/2; b[0]:=Y[0]; Y[0]:=0; for i:=1 to j do begin r:=X[i]-X[i-1]; d[i]:=c[i]/3; c[i]:=b[i]/2; b[i]:=Y[i]; Y[i]:=Y[i-1]+r*(b[i-1]+r*(c[i-1]+r*d[i-1])); end; inc(iOrder); end else begin //не хватает коэффициентов, значит, считаем узловые точки, а остальное интерполируем prev_acc:=d[0]/4; d[0]:=c[0]/3; c[0]:=b[0]/2; b[0]:=Y[0]; Y[0]:=0; for i:=1 to j do begin r:=X[i]-X[i-1]; acc:=d[i]/4; d[i]:=c[i]/3; c[i]:=b[i]/2; b[i]:=Y[i]; Y[i]:=Y[i-1]+r*(b[i-1]+r*(c[i-1]+r*(d[i-1]+r*prev_acc))); prev_acc:=acc; end; changed:=true; //значит, потом пройдет интерполяция кубическими сплайнами end; end; procedure Table_func.Add(c: Real); var i: Integer; begin for i:=0 to Count-1 do begin Y[i]:=Y[i]+c; end; end; procedure Table_func.Sub(c: Real); begin Add(-c); end; procedure table_func.Shift(amount: Real); var i: Integer; begin for i:=0 to count-1 do X[i]:=X[i]+amount; end; procedure table_func.multiply_argument(by: Real); var i: Integer; begin for i:=0 to count-1 do begin X[i]:=X[i]*by; end; if by<0 then begin for i:=0 to (count div 2)-1 do begin SwapReals(X[i],X[count-1-i]); SwapReals(Y[i],Y[count-1-i]); end; end; changed:=true; end; function table_func.AsTabbedText: string; var i: Integer; m: TStringList; begin m:=TStringList.Create; for i:=0 to Length(X)-1 do begin m.Add(FloatToStr(X[i])+#9+FloatToStr(Y[i])); end; Result:=m.Text; m.Free; end; function table_func.IsEqual(t: table_func): boolean; var tol: Real; i: Integer; begin Result:=false; if (t.count=count) and (order=t.order) and (cyclic=t.Cyclic) and (zero_out_of_bounds=t.zero_out_of_bounds) then begin tol:=tolerance+t.Tolerance; for i:=0 to count-1 do if (abs(X[i]-t.X[i])>tol) or (abs(Y[i]-t.Y[i])>tol) then Exit; Result:=true; end; end; function table_func.FindNearestPoint(ax,ay: Real; out dist: Real): Integer; var i,j: Integer; begin j:=FindInterval(ax); //нашли ближ. слева if j<0 then begin Result:=-1; Exit; end; Result:=j; //потом мы оставим j неизменным чтобы не потерять, откуда начали, но Result будем менять dist:=Sqr(ax-X[j])+Sqr(ay-Y[j]); //теперь наши подозреваемые - чуть влево и чуть вправо, пока заведомо не выйдем за пределы окр. i:=j-1; while (i>=0) and (Sqr(ax-X[i])<dist) do begin if Sqr(ax-X[i])+Sqr(ay-Y[i])<dist then begin Result:=i; dist:=Sqr(ax-X[i])+Sqr(ay-Y[i]); end; dec(i); end; //теперь пора направо i:=j+1; while (i<count) and (Sqr(ax-X[i])<dist) do begin if Sqr(ax-X[i])+Sqr(ay-Y[i])<dist then begin Result:=i; dist:=Sqr(ax-X[i])+Sqr(ay-Y[i]); end; inc(i); end; end; function table_func.GetB(index: Integer): Real; begin if changed then update_spline; Result:=b[index]; end; function table_func.GetC(index: Integer): Real; begin if changed then update_spline; Result:=c[index]; end; function table_func.GetD(index: Integer): Real; begin if changed then update_spline; Result:=d[index]; end; procedure table_func.FourierSeries(var storage: FourierSeriesRec; Period: real=0; WindowType: TFourierSeriesWindowType=wtFullPeriodsRect); var i,clen,slen: Integer; start_x,end_x,cur_x,increment,cur_val: Real; alpha,alpha_incr: Real; scale: Real; begin //находит ряд Фурье до тех гармоник, под которые выделено место в хранилище //если ничего другого не указано, за один период считает всю область определения функции if Period=0 then Period:=xmax-xmin; case WindowType of wtFullPeriodsRect: begin start_x:=xmin; scale:=Floor((xmax-xmin)/Period)*Period; end_x:=start_x+scale; end; wtRect: begin start_x:=xmin; end_x:=xmax; scale:=Ceil((xmax-xmin)/Period)*Period; // end_x:=start_x+scale; end; else Raise Exception.Create('Table_func.FourierSeries: unsupported window type'); end; cur_x:=start_x; increment:=Period/100; with storage do begin dc:=Average; clen:=Length(c)-1; slen:=Length(s)-1; //метод трапеций - первый и последний член половинные, остальные целые // dc:=value[cur_x]/2; for i:=0 to clen do c[i]:=(value[cur_x]-dc)/2; //*cos(0) for i:=0 to slen do s[i]:=0; //*sin(0) alpha:=0; alpha_incr:=2*pi/100; cur_val:=0; while cur_x<end_X do begin cur_x:=cur_x+increment; alpha:=alpha+alpha_incr; cur_val:=value[cur_x]-dc; for i:=0 to clen do c[i]:=c[i]+cur_val*cos(alpha*(i+1)); for i:=0 to slen do s[i]:=s[i]+cur_val*sin(alpha*(i+1)); end; //посчитаны все, а последний вместо половинного знач. полное получилось //плюс, надо смасштабировать // dc:=(dc-cur_val/2)*increment/(end_x-start_x); //просто среднее значение scale:=increment*2/scale; for i:=0 to clen do c[i]:=(c[i]-cur_val*cos(alpha*(i+1))/2)*scale; for i:=0 to slen do s[i]:=(s[i]-cur_val*sin(alpha*(i+1))/2)*scale; end; end; function table_func.GetInverse: table_func; var i: Integer; begin Result:=table_func.Create; Result.zero_out_of_bounds:=zero_out_of_bounds; Result.order:=order; for i:=0 to count-1 do Result.addpoint(Y[i],X[i]); end; initialization RegisterClass(Table_func); end.
unit WebBrowser; { This file contains pascal declarations imported from a type library. This file will be written during each import or refresh of the type library editor. Changes to this file will be discarded during the refresh process. } { Microsoft Internet Controls } { Version 1.0 } { Conversion log: Warning: 'Type' is a reserved word. IWebBrowser.Type changed to Type_ } interface uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL; const LIBID_WebBrowser : TGUID = '{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}'; const { Constants for WebBrowser navigation flags } { BrowserNavConstants } navOpenInNewWindow = 1; navNoHistory = 2; navNoReadFromCache = 4; navNoWriteToCache = 8; { Constants for Refresh } { RefreshConstants } REFRESH_NORMAL = 0; REFRESH_IFEXPIRED = 1; REFRESH_COMPLETELY = 3; { Constants for WebBrowser CommandStateChange } { CommandStateChangeConstants } CSC_UPDATECOMMANDS = -1; CSC_NAVIGATEFORWARD = 1; CSC_NAVIGATEBACK = 2; const { Component class GUIDs } Class_WebBrowser: TGUID = '{EAB22AC3-30C1-11CF-A7EB-0000C05BAE0B}'; Class_InternetExplorer: TGUID = '{0002DF01-0000-0000-C000-000000000046}'; type { Forward declarations: Interfaces } IWebBrowser = interface; IWebBrowserDisp = dispinterface; DWebBrowserEvents = dispinterface; IWebBrowserApp = interface; IWebBrowserAppDisp = dispinterface; { Forward declarations: CoClasses } WebBrowserX = IWebBrowser; InternetExplorer = IWebBrowserApp; { Forward declarations: Enums } BrowserNavConstants = TOleEnum; RefreshConstants = TOleEnum; CommandStateChangeConstants = TOleEnum; { Web Browser interface } IWebBrowser = interface(IDispatch) ['{EAB22AC1-30C1-11CF-A7EB-0000C05BAE0B}'] procedure GoBack; safecall; procedure GoForward; safecall; procedure GoHome; safecall; procedure GoSearch; safecall; procedure Navigate(const URL: WideString; var Flags, TargetFrameName, PostData, Headers: OleVariant); safecall; procedure Refresh; safecall; procedure Refresh2(var Level: OleVariant); safecall; procedure Stop; safecall; function Get_Application: IDispatch; safecall; function Get_Parent: IDispatch; safecall; function Get_Container: IDispatch; safecall; function Get_Document: IDispatch; safecall; function Get_TopLevelContainer: WordBool; safecall; function Get_Type_: WideString; safecall; function Get_Left: Integer; safecall; procedure Set_Left(Value: Integer); safecall; function Get_Top: Integer; safecall; procedure Set_Top(Value: Integer); safecall; function Get_Width: Integer; safecall; procedure Set_Width(Value: Integer); safecall; function Get_Height: Integer; safecall; procedure Set_Height(Value: Integer); safecall; function Get_LocationName: WideString; safecall; function Get_LocationURL: WideString; safecall; function Get_Busy: WordBool; safecall; property Application: IDispatch read Get_Application; property Parent: IDispatch read Get_Parent; property Container: IDispatch read Get_Container; property Document: IDispatch read Get_Document; property TopLevelContainer: WordBool read Get_TopLevelContainer; property Type_: WideString read Get_Type_; property Left: Integer read Get_Left write Set_Left; property Top: Integer read Get_Top write Set_Top; property Width: Integer read Get_Width write Set_Width; property Height: Integer read Get_Height write Set_Height; property LocationName: WideString read Get_LocationName; property LocationURL: WideString read Get_LocationURL; property Busy: WordBool read Get_Busy; end; { DispInterface declaration for Dual Interface IWebBrowser } IWebBrowserDisp = dispinterface ['{EAB22AC1-30C1-11CF-A7EB-0000C05BAE0B}'] procedure GoBack; dispid 100; procedure GoForward; dispid 101; procedure GoHome; dispid 102; procedure GoSearch; dispid 103; procedure Navigate(const URL: WideString; var Flags, TargetFrameName, PostData, Headers: OleVariant); dispid 104; procedure Refresh; dispid -550; procedure Refresh2(var Level: OleVariant); dispid 105; procedure Stop; dispid 106; property Application: IDispatch readonly dispid 200; property Parent: IDispatch readonly dispid 201; property Container: IDispatch readonly dispid 202; property Document: IDispatch readonly dispid 203; property TopLevelContainer: WordBool readonly dispid 204; property Type_: WideString readonly dispid 205; property Left: Integer dispid 206; property Top: Integer dispid 207; property Width: Integer dispid 208; property Height: Integer dispid 209; property LocationName: WideString readonly dispid 210; property LocationURL: WideString readonly dispid 211; property Busy: WordBool readonly dispid 212; end; { Event interface for Web Browser Control } DWebBrowserEvents = dispinterface ['{EAB22AC2-30C1-11CF-A7EB-0000C05BAE0B}'] procedure BeforeNavigate(const URL: WideString; Flags: Integer; const TargetFrameName: WideString; var PostData: OleVariant; const Headers: WideString; var Cancel: WordBool); dispid 100; procedure NavigateComplete(const URL: WideString); dispid 101; procedure StatusTextChange(const Text: WideString); dispid 102; procedure ProgressChange(Progress, ProgressMax: Integer); dispid 108; procedure DownloadComplete; dispid 104; procedure CommandStateChange(Command: Integer; Enable: WordBool); dispid 105; procedure DownloadBegin; dispid 106; procedure NewWindow(const URL: WideString; Flags: Integer; const TargetFrameName: WideString; var PostData: OleVariant; const Headers: WideString; var Processed: WordBool); dispid 107; procedure TitleChange(const Text: WideString); dispid 113; procedure FrameBeforeNavigate(const URL: WideString; Flags: Integer; const TargetFrameName: WideString; var PostData: OleVariant; const Headers: WideString; var Cancel: WordBool); dispid 200; procedure FrameNavigateComplete(const URL: WideString); dispid 201; procedure FrameNewWindow(const URL: WideString; Flags: Integer; const TargetFrameName: WideString; var PostData: OleVariant; const Headers: WideString; var Processed: WordBool); dispid 204; procedure Quit(var Cancel: WordBool); dispid 103; procedure WindowMove; dispid 109; procedure WindowResize; dispid 110; procedure WindowActivate; dispid 111; procedure PropertyChange(const szProperty: WideString); dispid 112; end; { Web Browser Application Interface. } IWebBrowserApp = interface(IWebBrowser) ['{0002DF05-0000-0000-C000-000000000046}'] procedure Quit; safecall; procedure ClientToWindow(var pcx, pcy: SYSINT); safecall; procedure PutProperty(const szProperty: WideString; vtValue: OleVariant); safecall; function GetProperty(const szProperty: WideString): OleVariant; safecall; function Get_Name: WideString; safecall; function Get_HWND: Integer; safecall; function Get_FullName: WideString; safecall; function Get_Path: WideString; safecall; function Get_Visible: WordBool; safecall; procedure Set_Visible(Value: WordBool); safecall; function Get_StatusBar: WordBool; safecall; procedure Set_StatusBar(Value: WordBool); safecall; function Get_StatusText: WideString; safecall; procedure Set_StatusText(const Value: WideString); safecall; function Get_ToolBar: SYSINT; safecall; procedure Set_ToolBar(Value: SYSINT); safecall; function Get_MenuBar: WordBool; safecall; procedure Set_MenuBar(Value: WordBool); safecall; function Get_FullScreen: WordBool; safecall; procedure Set_FullScreen(Value: WordBool); safecall; property Name: WideString read Get_Name; property HWND: Integer read Get_HWND; property FullName: WideString read Get_FullName; property Path: WideString read Get_Path; property Visible: WordBool read Get_Visible write Set_Visible; property StatusBar: WordBool read Get_StatusBar write Set_StatusBar; property StatusText: WideString read Get_StatusText write Set_StatusText; property ToolBar: SYSINT read Get_ToolBar write Set_ToolBar; property MenuBar: WordBool read Get_MenuBar write Set_MenuBar; property FullScreen: WordBool read Get_FullScreen write Set_FullScreen; end; { DispInterface declaration for Dual Interface IWebBrowserApp } IWebBrowserAppDisp = dispinterface ['{0002DF05-0000-0000-C000-000000000046}'] procedure GoBack; dispid 100; procedure GoForward; dispid 101; procedure GoHome; dispid 102; procedure GoSearch; dispid 103; procedure Navigate(const URL: WideString; var Flags, TargetFrameName, PostData, Headers: OleVariant); dispid 104; procedure Refresh; dispid -550; procedure Refresh2(var Level: OleVariant); dispid 105; procedure Stop; dispid 106; property Application: IDispatch readonly dispid 200; property Parent: IDispatch readonly dispid 201; property Container: IDispatch readonly dispid 202; property Document: IDispatch readonly dispid 203; property TopLevelContainer: WordBool readonly dispid 204; property Type_: WideString readonly dispid 205; property Left: Integer dispid 206; property Top: Integer dispid 207; property Width: Integer dispid 208; property Height: Integer dispid 209; property LocationName: WideString readonly dispid 210; property LocationURL: WideString readonly dispid 211; property Busy: WordBool readonly dispid 212; procedure Quit; dispid 300; procedure ClientToWindow(var pcx, pcy: SYSINT); dispid 301; procedure PutProperty(const szProperty: WideString; vtValue: OleVariant); dispid 302; function GetProperty(const szProperty: WideString): OleVariant; dispid 303; property Name: WideString readonly dispid 0; property HWND: Integer readonly dispid -515; property FullName: WideString readonly dispid 400; property Path: WideString readonly dispid 401; property Visible: WordBool dispid 402; property StatusBar: WordBool dispid 403; property StatusText: WideString dispid 404; property ToolBar: SYSINT dispid 405; property MenuBar: WordBool dispid 406; property FullScreen: WordBool dispid 407; end; { WebBrowser Control } TWebBrowserBeforeNavigate = procedure(Sender: TObject; const URL: WideString; Flags: Integer; const TargetFrameName: WideString; var PostData: OleVariant; const Headers: WideString; var Cancel: WordBool) of object; TWebBrowserNavigateComplete = procedure(Sender: TObject; const URL: WideString) of object; TWebBrowserStatusTextChange = procedure(Sender: TObject; const Text: WideString) of object; TWebBrowserProgressChange = procedure(Sender: TObject; Progress, ProgressMax: Integer) of object; TWebBrowserCommandStateChange = procedure(Sender: TObject; Command: Integer; Enable: WordBool) of object; TWebBrowserNewWindow = procedure(Sender: TObject; const URL: WideString; Flags: Integer; const TargetFrameName: WideString; var PostData: OleVariant; const Headers: WideString; var Processed: WordBool) of object; TWebBrowserTitleChange = procedure(Sender: TObject; const Text: WideString) of object; TWebBrowserFrameBeforeNavigate = procedure(Sender: TObject; const URL: WideString; Flags: Integer; const TargetFrameName: WideString; var PostData: OleVariant; const Headers: WideString; var Cancel: WordBool) of object; TWebBrowserFrameNavigateComplete = procedure(Sender: TObject; const URL: WideString) of object; TWebBrowserFrameNewWindow = procedure(Sender: TObject; const URL: WideString; Flags: Integer; const TargetFrameName: WideString; var PostData: OleVariant; const Headers: WideString; var Processed: WordBool) of object; TWebBrowserQuit = procedure(Sender: TObject; var Cancel: WordBool) of object; TWebBrowserPropertyChange = procedure(Sender: TObject; const szProperty: WideString) of object; TWebBrowser = class(TOleControl) private FOnBeforeNavigate: TWebBrowserBeforeNavigate; FOnNavigateComplete: TWebBrowserNavigateComplete; FOnStatusTextChange: TWebBrowserStatusTextChange; FOnProgressChange: TWebBrowserProgressChange; FOnDownloadComplete: TNotifyEvent; FOnCommandStateChange: TWebBrowserCommandStateChange; FOnDownloadBegin: TNotifyEvent; FOnNewWindow: TWebBrowserNewWindow; FOnTitleChange: TWebBrowserTitleChange; FOnFrameBeforeNavigate: TWebBrowserFrameBeforeNavigate; FOnFrameNavigateComplete: TWebBrowserFrameNavigateComplete; FOnFrameNewWindow: TWebBrowserFrameNewWindow; FOnQuit: TWebBrowserQuit; FOnWindowMove: TNotifyEvent; FOnWindowResize: TNotifyEvent; FOnWindowActivate: TNotifyEvent; FOnPropertyChange: TWebBrowserPropertyChange; FIntf: IWebBrowser; protected procedure InitControlData; override; procedure InitControlInterface(const Obj: IUnknown); override; public procedure GoBack; procedure GoForward; procedure GoHome; procedure GoSearch; procedure Navigate(const URL: WideString; var Flags, TargetFrameName, PostData, Headers: OleVariant); procedure Refresh; procedure Refresh2(var Level: OleVariant); procedure Stop; property ControlInterface: IWebBrowser read FIntf; property Application: IDispatch index 200 read GetIDispatchProp; property Parent: IDispatch index 201 read GetIDispatchProp; property Container: IDispatch index 202 read GetIDispatchProp; property Document: IDispatch index 203 read GetIDispatchProp; property TopLevelContainer: WordBool index 204 read GetWordBoolProp; property Type_: WideString index 205 read GetWideStringProp; property LocationName: WideString index 210 read GetWideStringProp; property LocationURL: WideString index 211 read GetWideStringProp; property Busy: WordBool index 212 read GetWordBoolProp; published property TabStop; property Align; property DragCursor; property DragMode; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property Visible; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnStartDrag; property OnBeforeNavigate: TWebBrowserBeforeNavigate read FOnBeforeNavigate write FOnBeforeNavigate; property OnNavigateComplete: TWebBrowserNavigateComplete read FOnNavigateComplete write FOnNavigateComplete; property OnStatusTextChange: TWebBrowserStatusTextChange read FOnStatusTextChange write FOnStatusTextChange; property OnProgressChange: TWebBrowserProgressChange read FOnProgressChange write FOnProgressChange; property OnDownloadComplete: TNotifyEvent read FOnDownloadComplete write FOnDownloadComplete; property OnCommandStateChange: TWebBrowserCommandStateChange read FOnCommandStateChange write FOnCommandStateChange; property OnDownloadBegin: TNotifyEvent read FOnDownloadBegin write FOnDownloadBegin; property OnNewWindow: TWebBrowserNewWindow read FOnNewWindow write FOnNewWindow; property OnTitleChange: TWebBrowserTitleChange read FOnTitleChange write FOnTitleChange; property OnFrameBeforeNavigate: TWebBrowserFrameBeforeNavigate read FOnFrameBeforeNavigate write FOnFrameBeforeNavigate; property OnFrameNavigateComplete: TWebBrowserFrameNavigateComplete read FOnFrameNavigateComplete write FOnFrameNavigateComplete; property OnFrameNewWindow: TWebBrowserFrameNewWindow read FOnFrameNewWindow write FOnFrameNewWindow; property OnQuit: TWebBrowserQuit read FOnQuit write FOnQuit; property OnWindowMove: TNotifyEvent read FOnWindowMove write FOnWindowMove; property OnWindowResize: TNotifyEvent read FOnWindowResize write FOnWindowResize; property OnWindowActivate: TNotifyEvent read FOnWindowActivate write FOnWindowActivate; property OnPropertyChange: TWebBrowserPropertyChange read FOnPropertyChange write FOnPropertyChange; end; type TExplorer = TWebBrowser; procedure Register; implementation uses ComObj; procedure TWebBrowser.InitControlData; const CEventDispIDs: array[0..16] of Integer = ( $00000064, $00000065, $00000066, $0000006C, $00000068, $00000069, $0000006A, $0000006B, $00000071, $000000C8, $000000C9, $000000CC, $00000067, $0000006D, $0000006E, $0000006F, $00000070); CControlData: TControlData = ( ClassID: '{EAB22AC3-30C1-11CF-A7EB-0000C05BAE0B}'; EventIID: '{EAB22AC2-30C1-11CF-A7EB-0000C05BAE0B}'; EventCount: 17; EventDispIDs: @CEventDispIDs; LicenseKey: nil; Flags: $00000000; Version: 300); begin ControlData := @CControlData; end; procedure TWebBrowser.InitControlInterface(const Obj: IUnknown); begin FIntf := Obj as IWebBrowser; end; procedure TWebBrowser.GoBack; begin ControlInterface.GoBack; end; procedure TWebBrowser.GoForward; begin ControlInterface.GoForward; end; procedure TWebBrowser.GoHome; begin ControlInterface.GoHome; end; procedure TWebBrowser.GoSearch; begin ControlInterface.GoSearch; end; procedure TWebBrowser.Navigate(const URL: WideString; var Flags, TargetFrameName, PostData, Headers: OleVariant); begin ControlInterface.Navigate(URL, Flags, TargetFrameName, PostData, Headers); end; procedure TWebBrowser.Refresh; begin ControlInterface.Refresh; end; procedure TWebBrowser.Refresh2(var Level: OleVariant); begin ControlInterface.Refresh2(Level); end; procedure TWebBrowser.Stop; begin ControlInterface.Stop; end; procedure Register; begin RegisterComponents('ActiveX', [TWebBrowser]); end; end.
uses uBignumArithmetic; var fi, fo: text; a, b: TLongReal; errA, errB: boolean; begin assign(fi, 'input.txt'); reset(fi); assign(fo, 'output.txt'); rewrite(fo); a.init(); b.init(); readTLongReal(fi, a, errA); readTLongReal(fi, b, errB); if not errA and not errB then begin write(fo, 'a + b: '); writeTLongReal(fo, addTLongReal(a, b)); writeln(fo); if a = b then writeln(fo, 'Numbers are equal.') else begin write(fo, 'a - b: '); writeTLongReal(fo, absSubTLongReal(a, b)); end; end else writeln(fo, 'Input error.'); close(fi); close(fo); end.
var x:real; const q=0.00001; begin x:=0.999999; while abs(cos(x)-4*x)>q do begin x:=x-0.000001; if x<-0.999999 then break else if not(abs(cos(x)-4*x)>q) then writeln('X = ',x) else continue end; end.
unit StockDayData_Parse_Sina; interface uses Sysutils, define_stockday_sina, define_stock_quotes, define_price; procedure ParseSinaCellData(AHeadCol: TDealDayDataHeadName_Sina; ADealDayData: PRT_Quote_Day; AStringData: string); implementation //uses // UtilsLog; {$IFNDEF RELEASE} const LOGTAG = 'StockDayData_Parse_Sina.pas'; {$ENDIF} function tryGetSinaIntValue(AStringData: string): integer; var tmpPos: integer; tmpPrefix: string; tmpSuffix: string; begin Result := 0; tmpPos := Pos('.', AStringData); if 0 < tmpPos then begin tmpPrefix := Copy(AStringData, 1, tmpPos - 1); tmpSuffix := Copy(AStringData, tmpPos + 1, maxint); if 3 = Length(tmpSuffix) then begin Result := StrToIntDef(tmpPrefix + tmpSuffix, 0); end; end; end; procedure ParseSinaCellData(AHeadCol: TDealDayDataHeadName_Sina; ADealDayData: PRT_Quote_Day; AStringData: string); var tmpPos: integer; tmpDate: TDateTime; begin if AStringData <> '' then begin case AHeadCol of headDay: begin //Log('headDay', '' + AStringData); tmpDate := StrToDateDef(AStringData, 0, DateFormat_Sina); ADealDayData.DealDate.Value := Trunc(tmpDate); end; // 1 日期, headPrice_Open: begin // 7开盘价, ADealDayData.PriceRange.PriceOpen.Value := tryGetSinaIntValue(AStringData); //if 0 = ADealDayData.PriceRange.PriceOpen.Value then // SetRTPricePack(@ADealDayData.PriceRange.PriceOpen, StrToFloatDef(AStringData, 0.00)); end; headPrice_High: begin // 5最高价, //Log('headPrice_High', '' + AStringData); ADealDayData.PriceRange.PriceHigh.Value := tryGetSinaIntValue(AStringData); //if 0 = ADealDayData.PriceRange.PriceHigh.Value then // SetRTPricePack(@ADealDayData.PriceRange.PriceHigh, StrToFloatDef(AStringData, 0.00)); end; headPrice_Close: begin // 4收盘价, ADealDayData.PriceRange.PriceClose.Value := tryGetSinaIntValue(AStringData); //if 0 = ADealDayData.PriceRange.PriceClose.Value then // SetRTPricePack(@ADealDayData.PriceRange.PriceClose, StrToFloatDef(AStringData, 0.00)); end; headPrice_Low: begin // 6最低价, //Log('headPrice_Low', '' + AStringData); ADealDayData.PriceRange.PriceLow.Value := tryGetSinaIntValue(AStringData); //if 0 = ADealDayData.PriceRange.PriceLow.Value then // SetRTPricePack(@ADealDayData.PriceRange.PriceLow, StrToFloatDef(AStringData, 0.00)); end; headDeal_Volume: begin // 12成交量, tmpPos := Sysutils.LastDelimiter('.', AStringData); if tmpPos > 0 then begin AStringData := Copy(AStringData, 1, tmpPos - 1); end; ADealDayData.DealVolume := StrToInt64Def(AStringData, 0); end; headDeal_Amount: begin // 13成交金额, tmpPos := Sysutils.LastDelimiter('.', AStringData); if tmpPos > 0 then begin AStringData := Copy(AStringData, 1, tmpPos - 1); end; ADealDayData.DealAmount := StrToInt64Def(AStringData, 0); end; headDeal_WeightFactor: begin ADealDayData.Weight.Value := tryGetSinaIntValue(AStringData); if 0 = ADealDayData.Weight.Value then ADealDayData.Weight.Value := Trunc(StrToFloatDef(AStringData, 0.00) * 1000); end; end; end; end; end.
{-------------------------------------------------- Progressive Path Tracing --------------------------------------------------- This unit implements a camera, which takes as a parameter a camera position and a camera target, and allows one to project the scene as viewed from the camera's point of view onto a 2D plane. Since this class is the only one which requires matrix math, the matrix code has been merged into this unit for convenience. -------------------------------------------------------------------------------------------------------------------------------} unit Camera; interface uses VectorTypes, VectorMath, Math; type TMatrix = array [0..3, 0..3] of Double; TCamera = class private FCameraPosition: TVector; FInverseViewMatrix: TMatrix; FCorners: array [0..3] of TVector; public constructor Create(ACameraPosition, ACameraTarget: TVector; AspectRatio: Double); reintroduce; function TraceCameraRay(U, V: Double): TRay; end; PCamera = ^TCamera; implementation { Multiplication of a matrix with a vector (returns a vector). } function MulMatrix(A: TMatrix; B: TVector): TVector; begin Result.X := A[0, 0] * B.X + A[1, 0] * B.Y + A[2, 0] * B.Z + A[3, 0]; Result.Y := A[0, 1] * B.X + A[1, 1] * B.Y + A[2, 1] * B.Z + A[3, 1]; Result.Z := A[0, 2] * B.X + A[1, 2] * B.Y + A[2, 2] * B.Z + A[3, 2]; // W := A[0, 3] * B.X + A[1, 3] * B.Y + A[2, 3] * B.Z + A[3, 3]; // perspective division redundant because of ray normalization end; { This function creates an orthogonal view matrix, using a position point and a target vector. } function LookAt(Position, Target: TVector): TMatrix; Var Up, XAxis, YAxis, ZAxis: TVector; begin { Create the Up vector. } Up := NormalizeVector(CrossVector(CrossVector(SubVector(Target, Position), Vector(0, 1, 0)), SubVector(Target, Position))); { Create the rotation axis basis. } zAxis := NormalizeVector(SubVector(Target, Position)); xAxis := NormalizeVector(CrossVector(Up, zAxis)); yAxis := NormalizeVector(CrossVector(zAxis, xAxis)); { Build the matrix from those vectors. } Result[0][0] := xAxis.X; Result[0][1] := xAxis.Y; Result[0][2] := xAxis.Z; Result[0][3] := -DotVector(xAxis, Position); Result[1][0] := yAxis.X; Result[1][1] := yAxis.Y; Result[1][2] := yAxis.Z; Result[1][3] := -DotVector(yAxis, Position); Result[2][0] := zAxis.X; Result[2][1] := zAxis.Y; Result[2][2] := zAxis.Z; Result[2][3] := -DotVector(zAxis, Position); Result[3][0] := 0; Result[3][1] := 0; Result[3][2] := 0; Result[3][3] := 1; end; { Creates the camera, taking into account the camera position, target and aspect ratio. } constructor TCamera.Create(ACameraPosition, ACameraTarget: TVector; AspectRatio: Double); begin { Create the matrix. } inherited Create; FCameraPosition := ACameraPosition; FInverseViewMatrix := LookAt(FCameraPosition, ACameraTarget); { Find the corner points (all the others can be interpolated with a bilinear interpolation). } FCorners[0] := MulMatrix(FInverseViewMatrix, Vector(-(-1) * AspectRatio, (-1), 1)); FCorners[1] := MulMatrix(FInverseViewMatrix, Vector(-(+1) * AspectRatio, (-1), 1)); FCorners[2] := MulMatrix(FInverseViewMatrix, Vector(-(+1) * AspectRatio, (+1), 1)); FCorners[3] := MulMatrix(FInverseViewMatrix, Vector(-(-1) * AspectRatio, (+1), 1)); end; { Returns the camera ray going through the pixel at U, V. } function TCamera.TraceCameraRay(U, V: Double): TRay; begin { Interpolate the focal plane point and trace the ray from it. } Result.Direction := NormalizeVector(LerpVector(LerpVector(FCorners[0], FCorners[1], U), LerpVector(FCorners[3], FCorners[2], U), V)); Result.Origin := FCameraPosition; end; end.
unit UThreadDiscoverConnection; interface uses UThread, UNodeServerAddress, Classes; type TThreadDiscoverConnection = Class(TPCThread) FNodeServerAddress : TNodeServerAddress; protected procedure BCExecute; override; public Constructor Create(NodeServerAddress: TNodeServerAddress; NotifyOnTerminate : TNotifyEvent); End; implementation uses UNetClient, ULog, SysUtils, UNetData; { TThreadDiscoverConnection } procedure TThreadDiscoverConnection.BCExecute; Var NC : TNetClient; ok : Boolean; ns : TNodeServerAddress; begin Repeat // Face to face conflict when 2 nodes connecting together Sleep(Random(1000)); until (Terminated) Or (Random(5)=0); if Terminated then exit; TLog.NewLog(ltInfo,Classname,'Starting discovery of connection '+FNodeServerAddress.ip+':'+InttoStr(FNodeServerAddress.port)); DebugStep := 'Locking list'; // Register attempt If PascalNetData.NodeServersAddresses.GetNodeServerAddress(FNodeServerAddress.ip,FNodeServerAddress.port,true,ns) then begin ns.last_attempt_to_connect := Now; inc(ns.total_failed_attemps_to_connect); PascalNetData.NodeServersAddresses.SetNodeServerAddress(ns); end; DebugStep := 'Synchronizing notify'; if Terminated then exit; PascalNetData.NotifyNodeServersUpdated; // Try to connect ok := false; DebugStep := 'Trying to connect'; if Terminated then exit; NC := TNetClient.Create; Try DebugStep := 'Connecting'; If NC.ConnectTo(FNodeServerAddress.ip,FNodeServerAddress.port) then begin if Terminated then exit; Sleep(500); DebugStep := 'Is connected now?'; if Terminated then exit; ok :=NC.Connected; end; if Terminated then exit; Finally if (not ok) And (Not Terminated) then begin DebugStep := 'Destroying non connected'; NC.FinalizeConnection; end; End; DebugStep := 'Synchronizing notify final'; if Terminated then exit; PascalNetData.NotifyNodeServersUpdated; end; constructor TThreadDiscoverConnection.Create(NodeServerAddress: TNodeServerAddress; NotifyOnTerminate : TNotifyEvent); begin FNodeServerAddress := NodeServerAddress; inherited Create(true); OnTerminate := NotifyOnTerminate; FreeOnTerminate := true; Suspended := false; end; end.
unit MFichas.Model.Venda.Metodos.Finalizar; interface uses System.SysUtils, System.Generics.Collections, MFichas.Controller.Types, MFichas.Model.Entidade.VENDA, MFichas.Model.Venda.Interfaces, MFichas.Model.Venda.State.Factory, MFichas.Controller.Venda.Interfaces; type TModelVendaMetodosFinalizar = class(TInterfacedObject, iModelVendaMetodosFinalizar) private [weak] FParent : iModelVenda; FListaVendas: TObjectList<TVENDA>; FVenda : TVENDA; FVendaController: iControllerVenda; constructor Create(AParent: iModelVenda); procedure LimparEntidadeDeVenda; procedure RecuperarVendaAtual; procedure GravarVendaNoBanco; procedure Gravar; public destructor Destroy; override; class function New(AParent: iModelVenda): iModelVendaMetodosFinalizar; function Executar: iModelVendaMetodosFinalizar; function &End : iModelVendaMetodos; end; implementation uses MFichas.Controller.Venda; { TModelVendaMetodosFinalizar } function TModelVendaMetodosFinalizar.&End: iModelVendaMetodos; begin Result := FParent.Metodos; end; procedure TModelVendaMetodosFinalizar.Gravar; begin FParent.Item.GravarNoBanco.Executar; FVendaController.Metodos.EfetuarPagamento.Executar; GravarVendaNoBanco; end; procedure TModelVendaMetodosFinalizar.GravarVendaNoBanco; begin RecuperarVendaAtual; FParent.DAO.Modify(FVenda); FVenda.DATAFECHAMENTO := Now; FVenda.STATUS := Integer(svFechada); FParent.DAO.Update(FVenda); end; procedure TModelVendaMetodosFinalizar.RecuperarVendaAtual; begin FListaVendas := FParent.DAO.FindWhere('', 'DATAABERTURA DESC'); FVenda.GUUID := FListaVendas.Items[0].GUUID; FVenda.CAIXA := FListaVendas.Items[0].CAIXA; FVenda.NUMERO := FListaVendas.Items[0].NUMERO; FVenda.DATAABERTURA := FListaVendas.Items[0].DATAABERTURA; end; constructor TModelVendaMetodosFinalizar.Create(AParent: iModelVenda); begin FParent := AParent; FVenda := TVENDA.Create; FVendaController := TControllerVenda.New(nil); end; destructor TModelVendaMetodosFinalizar.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FVenda); if Assigned(FListaVendas) then FreeAndNil(FListaVendas); {$ELSE} FVenda.Free; FVenda.DisposeOf; if Assigned(FListaVendas) then begin FListaVendas.Free; FListaVendas.DisposeOf; end; {$ENDIF} inherited; end; function TModelVendaMetodosFinalizar.Executar: iModelVendaMetodosFinalizar; begin //TODO: IMPLEMENTAR METODO DE FINALIZAÇÃO DA VENDA. Result := Self; Gravar; LimparEntidadeDeVenda; FParent.SetState(TModelVendaStateFactory.New.Fechada); end; procedure TModelVendaMetodosFinalizar.LimparEntidadeDeVenda; begin FParent.Entidade.CleanupInstance; FParent.Entidade.DATAABERTURA := StrToDateTime('30/12/1899'); end; class function TModelVendaMetodosFinalizar.New(AParent: iModelVenda): iModelVendaMetodosFinalizar; begin Result := Self.Create(AParent); end; end.
unit DropListBox; { Inno Setup Copyright (C) 1997-2004 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. This unit provides a listbox with drop files support. $jrsoftware: issrc/Components/DropListBox.pas,v 1.1 2004/06/05 16:07:10 mlaan Exp $ } interface uses StdCtrls, Messages; type TDropListBox = class; TDropFileEvent = procedure(Sender: TDropListBox; const FileName: String) of object; TDropListBox = class(TCustomListBox) private FOnDropFile: TDropFileEvent; protected procedure CreateWnd; override; procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES; published property Align; property BorderStyle; property Color; property Columns; property Ctl3D; property DragCursor; property DragMode; property Enabled; property ExtendedSelect; property Font; property ImeMode; property ImeName; property IntegralHeight; property ItemHeight; property Items; property MultiSelect; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Sorted; property Style; property TabOrder; property TabStop; property TabWidth; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnDropFile: TDropFileEvent read FOnDropFile write FOnDropFile; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMeasureItem; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation uses Classes, Windows, ShellAPI; procedure TDropListBox.CreateWnd; begin inherited; if csDesigning in ComponentState then Exit; DragAcceptFiles(Handle, True); end; procedure TDropListBox.WMDropFiles(var Msg: TWMDropFiles); var FileName: array[0..MAX_PATH] of Char; I, FileCount: Integer; begin try if Assigned(FOnDropFile) then begin FileCount := DragQueryFile(Msg.Drop, $FFFFFFFF, nil, 0); for I := 0 to FileCount-1 do if DragQueryFile(Msg.Drop, I, FileName, SizeOf(FileName)) > 0 then FOnDropFile(Self, FileName); end; Msg.Result := 0; finally DragFinish(Msg.Drop); end; end; procedure Register; begin RegisterComponents('JR', [TDropListBox]); end; end.
unit GX_ProjDependFilter; interface uses Classes, Controls, Forms, Dialogs, StdCtrls, Menus, ExtCtrls, GX_BaseForm; type TfmProjDependFilter = class(TfmBaseForm) dlgOpen: TOpenDialog; mnuPopup: TPopupMenu; mitAddFiles: TMenuItem; mitDeleteFiles: TMenuItem; mitClear: TMenuItem; mitSep1: TMenuItem; mitSave: TMenuItem; mitLoad: TMenuItem; dlgFilterOpen: TOpenDialog; dlgFilterSave: TSaveDialog; pnlFooter: TPanel; pnlFilters: TPanel; pnlListFooter: TPanel; btnAdd: TButton; edtUnitName: TEdit; pnlUnits: TPanel; lbFilter: TListBox; pnlUnitsHeader: TPanel; btnOK: TButton; btnCancel: TButton; procedure mitAddFilesClick(Sender: TObject); procedure mitDeleteFilesClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure mitClearClick(Sender: TObject); procedure mitSaveClick(Sender: TObject); procedure mitLoadClick(Sender: TObject); procedure mnuPopupPopup(Sender: TObject); procedure edtUnitNameChange(Sender: TObject); procedure FormShow(Sender: TObject); private function GetUnitList: TStrings; procedure SetUnitList(const Value: TStrings); procedure UpdateButtonState; public property UnitList: TStrings read GetUnitList write SetUnitList; end; implementation {$R *.dfm} uses SysUtils, GX_GenericUtils; procedure TfmProjDependFilter.mitAddFilesClick(Sender: TObject); var i: Integer; TempStr: string; begin if dlgOpen.Execute then begin for i := 0 to dlgOpen.Files.Count - 1 do begin TempStr := ExtractPureFileName(dlgOpen.Files[i]); EnsureStringInList(lbFilter.Items, TempStr); end; end; end; procedure TfmProjDependFilter.mitDeleteFilesClick(Sender: TObject); var i: Integer; begin if lbFilter.SelCount > 0 then for i := lbFilter.Items.Count - 1 downto 0 do if lbFilter.Selected[i] then lbFilter.Items.Delete(i); end; function TfmProjDependFilter.GetUnitList: TStrings; begin Result := lbFilter.Items; end; procedure TfmProjDependFilter.SetUnitList(const Value: TStrings); begin lbFilter.Items.Assign(Value); end; procedure TfmProjDependFilter.btnAddClick(Sender: TObject); var TempStr: string; begin TempStr := edtUnitName.Text; if Trim(TempStr) = '' then Exit; if lbFilter.Items.IndexOf(TempStr) = -1 then lbFilter.Items.Add(TempStr); edtUnitName.Clear; edtUnitName.SetFocus; end; procedure TfmProjDependFilter.mitClearClick(Sender: TObject); resourcestring sConfirmClear = 'Clear the filter list?'; begin if MessageDlg(sConfirmClear, mtConfirmation, [mbYes, mbNo], 0) = mrYes then lbFilter.Clear; end; procedure TfmProjDependFilter.mitSaveClick(Sender: TObject); begin if dlgFilterSave.Execute then lbFilter.Items.SaveToFile(dlgFilterSave.FileName); end; procedure TfmProjDependFilter.mitLoadClick(Sender: TObject); begin if dlgFilterOpen.Execute then lbFilter.Items.LoadFromFile(dlgFilterOpen.FileName); end; procedure TfmProjDependFilter.mnuPopupPopup(Sender: TObject); begin mitDeleteFiles.Enabled := lbFilter.SelCount > 0; end; procedure TfmProjDependFilter.edtUnitNameChange(Sender: TObject); begin UpdateButtonState; end; procedure TfmProjDependFilter.FormShow(Sender: TObject); begin UpdateButtonState; end; procedure TfmProjDependFilter.UpdateButtonState; begin btnAdd.Enabled := Trim(edtUnitName.Text) <> ''; end; end.
unit gradtabcontroleditor; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ComCtrls, ugradtabcontrol, ComponentEditors, Menus, PropEdits; type { TGradTabControlComponentEditor The default component editor for TGradTabControl. } TGradTabControlComponentEditor = class(TDefaultComponentEditor) protected procedure AddNewPageToDesigner(Index: integer); virtual; procedure DoAddPage; virtual; procedure DoInsertPage; virtual; procedure DoDeletePage; virtual; procedure DoMoveActivePageLeft; virtual; procedure DoMoveActivePageRight; virtual; procedure DoMovePage(CurIndex, NewIndex: Integer); virtual; procedure AddMenuItemsForPages(ParentMenuItem: TMenuItem); virtual; procedure ShowPageMenuItemClick(Sender: TObject); public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; procedure PrepareItem(Index: Integer; const AnItem: TMenuItem); override; function GradTabControl: TGradTabControl; virtual; end; { TPageComponentEditor The default component editor for TCustomPage. } TGradTabPageComponentEditor = class(TGradTabControlComponentEditor) protected public function GradTabControl: TGradTabControl; override; function Page: TGradTabPage; virtual; end; implementation uses ObjInspStrConsts; { TNotebookComponentEditor } const nbvAddPage = 0; nbvInsertPage = 1; nbvDeletePage = 2; nbvMovePageLeft = 3; nbvMovePageRight = 4; nbvShowPage = 5; procedure TGradTabControlComponentEditor.ShowPageMenuItemClick(Sender: TObject); var AMenuItem: TMenuItem; NewPageIndex: integer; begin AMenuItem:=TMenuItem(Sender); if (AMenuItem=nil) or (not (AMenuItem is TMenuItem)) then exit; NewPageIndex:=AMenuItem.MenuIndex; if (NewPageIndex<0) or (NewPageIndex>=GradTabControl.PageCount) then exit; GradTabControl.PageIndex:=NewPageIndex; GetDesigner.SelectOnlyThisComponent(GradTabControl.Page[GradTabControl.PageIndex]); end; procedure TGradTabControlComponentEditor.AddNewPageToDesigner(Index: integer); var Hook: TPropertyEditorHook; NewPage: TGradTabPage; NewName: string; begin Hook:=nil; if not GetHook(Hook) then exit; NewPage:=GradTabControl.Page[Index]; NewName:=GetDesigner.CreateUniqueComponentName(NewPage.ClassName); NewPage.Caption:=NewName; NewPage.Name:=NewName; GradTabControl.PageIndex:=Index; Hook.PersistentAdded(NewPage,true); Modified; end; procedure TGradTabControlComponentEditor.DoAddPage; begin if not HasHook then exit; GradTabControl.Tabs.Add(''); AddNewPageToDesigner(GradTabControl.PageCount-1); end; procedure TGradTabControlComponentEditor.DoInsertPage; var NewIndex: integer; begin if not HasHook then exit; NewIndex:=GradTabControl.PageIndex; if NewIndex<0 then NewIndex:=0; GradTabControl.Tabs.Insert(NewIndex,''); AddNewPageToDesigner(NewIndex); end; procedure TGradTabControlComponentEditor.DoDeletePage; var Hook: TPropertyEditorHook; OldIndex: integer; PageComponent: TComponent; begin OldIndex:=GradTabControl.PageIndex; if (OldIndex>=0) and (OldIndex<GradTabControl.PageCount) then begin if not GetHook(Hook) then exit; PageComponent:=TComponent(GradTabControl.Tabs.Objects[OldIndex]); Hook.DeletePersistent(TPersistent(PageComponent)); end; end; procedure TGradTabControlComponentEditor.DoMoveActivePageLeft; var Index: integer; begin Index:=GradTabControl.PageIndex; if (Index<0) then exit; DoMovePage(Index,Index-1); end; procedure TGradTabControlComponentEditor.DoMoveActivePageRight; var Index: integer; begin Index:=GradTabControl.PageIndex; if (Index>=0) and (Index>=GradTabControl.PageCount-1) then exit; DoMovePage(Index,Index+1); end; procedure TGradTabControlComponentEditor.DoMovePage( CurIndex, NewIndex: Integer); begin GradTabControl.Tabs.Move(CurIndex,NewIndex); Modified; end; procedure TGradTabControlComponentEditor.AddMenuItemsForPages( ParentMenuItem: TMenuItem); var i: integer; NewMenuItem: TMenuItem; begin ParentMenuItem.Enabled:=GradTabControl.PageCount>0; for i:=0 to GradTabControl.PageCount-1 do begin NewMenuItem:=TMenuItem.Create(ParentMenuItem); NewMenuItem.Name:='ShowPage'+IntToStr(i); NewMenuItem.Caption:=GradTabControl.Page[i].Name+' "'+GradTabControl.Tabs[i]+'"'; NewMenuItem.OnClick:=@ShowPageMenuItemClick; ParentMenuItem.Add(NewMenuItem); end; end; procedure TGradTabControlComponentEditor.ExecuteVerb(Index: Integer); begin case Index of nbvAddPage: DoAddPage; nbvInsertPage: DoInsertPage; nbvDeletePage: DoDeletePage; // beware: this can free the editor itself nbvMovePageLeft: DoMoveActivePageLeft; nbvMovePageRight: DoMoveActivePageRight; end; end; function TGradTabControlComponentEditor.GetVerb(Index: Integer): string; begin case Index of nbvAddPage: Result:=nbcesAddPage; nbvInsertPage: Result:=nbcesInsertPage; nbvDeletePage: Result:=nbcesDeletePage; nbvMovePageLeft: Result:=nbcesMovePageLeft; nbvMovePageRight: Result:=nbcesMovePageRight; nbvShowPage: Result:=nbcesShowPage; else Result:=''; end; end; function TGradTabControlComponentEditor.GetVerbCount: Integer; begin Result:=6; end; procedure TGradTabControlComponentEditor.PrepareItem(Index: Integer; const AnItem: TMenuItem); begin inherited PrepareItem(Index, AnItem); case Index of nbvAddPage: ; nbvInsertPage: AnItem.Enabled:=GradTabControl.PageIndex>=0; nbvDeletePage: AnItem.Enabled:=GradTabControl.PageIndex>=0; nbvMovePageLeft: AnItem.Enabled:=GradTabControl.PageIndex>0; nbvMovePageRight: AnItem.Enabled:=GradTabControl.PageIndex<GradTabControl.PageCount-1; nbvShowPage: AddMenuItemsForPages(AnItem); end; end; function TGradTabControlComponentEditor.GradTabControl: TGradTabControl; begin Result:=TGradTabControl(GetComponent); end; function TGradTabPageComponentEditor.GradTabControl: TGradTabControl; var APage: TGradTabPage; begin APage:=Page; if (APage.Parent<>nil) and (APage.Parent is TGradTabControl) then Result:=TGradTabControl(APage.Parent); end; function TGradTabPageComponentEditor.Page: TGradTabPage; begin Result:=TGradTabPage(GetComponent); end; end.
unit BaseFutureApp; interface uses BaseWinApp, BaseApp, db_dealitem; type TBaseFutureAppData = record DealItemDB: TDBDealItem; end; TBaseFutureApp = class(TBaseWinApp) protected fBaseFutureAppData: TBaseFutureAppData; function GetPath: TBaseAppPath; override; public constructor Create(AppClassId: AnsiString); override; destructor Destroy; override; procedure InitializeDBDealItem; property DealItemDB: TDBDealItem read fBaseFutureAppData.DealItemDB; end; implementation uses FutureAppPath, db_dealitem_Load; constructor TBaseFutureApp.Create(AppClassId: AnsiString); begin inherited; FillChar(fBaseFutureAppData, SizeOf(fBaseFutureAppData), 0); end; destructor TBaseFutureApp.Destroy; begin if nil <> fBaseFutureAppData.DealItemDB then begin fBaseFutureAppData.DealItemDB.Free; fBaseFutureAppData.DealItemDB := nil; end; inherited; end; function TBaseFutureApp.GetPath: TBaseAppPath; begin if nil = fBaseWinAppData.AppPath then fBaseWinAppData.AppPath := TFutureAppPath.Create(Self); Result := fBaseWinAppData.AppPath; end; procedure TBaseFutureApp.InitializeDBDealItem; begin if nil = fBaseFutureAppData.DealItemDB then begin fBaseFutureAppData.DealItemDB := TDBDealItem.Create(FilePath_DBType_Future, FilePath_DataType_Item, 0); end; end; end.
unit uHTTPWebsocketServer; interface uses Classes, IdServerIOHandlerWebsocket, IdIOHandlerWebsocket, IdThread, IdHTTPServer, IdContext, IdCustomHTTPServer, IdCustomTCPServer, IdHashSHA1; type TWSMessageNotify = procedure(const aDataCode: TWSDataCode; const aRequest: TMemoryStream; out aResponse: TStream) of object; TIndyHTTPWebsocketServer = class(TIdHTTPServer) private FOnWSMessage: TWSMessageNotify; protected FHash: TIdHashSHA1; procedure DoCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); override; procedure DoWSExecute(AContext: TIdContext); public procedure AfterConstruction; override; destructor Destroy; override; procedure Loaded; override; published property OnWSMessage: TWSMessageNotify read FOnWSMessage write FOnWSMessage; end; TIdServerWSContext = class(TIdServerContext) private FWebSocketKey: string; FWebSocketVersion: Integer; FPath: string; FWebSocketProtocol: string; FResourceName: string; FOrigin: string; FQuery: string; FHost: string; FWebSocketExtensions: string; FCookie: string; public function IOHandler: TIdIOHandlerWebsocket; public property Path : string read FPath write FPath; property Query : string read FQuery write FQuery; property ResourceName: string read FResourceName write FResourceName; property Host : string read FHost write FHost; property Origin : string read FOrigin write FOrigin; property Cookie : string read FCookie write FCookie; property WebSocketKey : string read FWebSocketKey write FWebSocketKey; property WebSocketProtocol : string read FWebSocketProtocol write FWebSocketProtocol; property WebSocketVersion : Integer read FWebSocketVersion write FWebSocketVersion; property WebSocketExtensions: string read FWebSocketExtensions write FWebSocketExtensions; end; implementation uses SysUtils, IdCoderMIME, Windows; procedure TIndyHTTPWebsocketServer.AfterConstruction; begin inherited; //set special WebSockets stuff Self.ContextClass := TIdServerWSContext; if Self.IOHandler = nil then Self.IOHandler := TIdServerIOHandlerWebsocket.Create(Self); FHash := TIdHashSHA1.Create; end; destructor TIndyHTTPWebsocketServer.Destroy; begin FHash.Free; inherited; end; procedure TIndyHTTPWebsocketServer.DoWSExecute(AContext: TIdContext); var strmRequest: TMemoryStream; strmResponse: TStream; wscode: TWSDataCode; wsIO: TIdIOHandlerWebsocket; begin try while AContext.Connection.Connected do begin if (AContext.Connection.IOHandler.InputBuffer.Size > 0) or //already some data? AContext.Connection.IOHandler.Readable(5 * 1000) then //else wait some time (5s) begin strmResponse := TMemoryStream.Create; strmRequest := TMemoryStream.Create; try wsIO := AContext.Connection.IOHandler as TIdIOHandlerWebsocket; strmRequest.Position := 0; //first is the type: text or bin wscode := TWSDataCode(wsIO.ReadLongWord); //then the length + data = stream wsIO.ReadStream(strmRequest); //ignore ping/pong messages if wscode in [wdcPing, wdcPong] then Continue; //EXECUTE FUNCTION if Assigned(OnWSMessage) then begin strmRequest.Position := 0; OnWSMessage(wscode, strmRequest, strmResponse); if strmResponse <> nil then begin strmResponse.Position := 0; //write result back (of the same type: text or bin) if wscode = wdcText then wsIO.Write(strmResponse, wdtText) else wsIO.Write(strmResponse, wdtBinary) end; end; finally strmRequest.Free; strmResponse.Free; end; end else //keep alive: send a ping each 5s begin wsIO := AContext.Connection.IOHandler as TIdIOHandlerWebsocket; //ping wsIO.WriteData(nil, wdcPing); end; end; finally AContext.Data := nil; end; end; procedure TIndyHTTPWebsocketServer.DoCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var sValue: string; context: TIdServerWSContext; begin (* GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 *) (* GET ws://echo.websocket.org/?encoding=text HTTP/1.1 Origin: http://websocket.org Cookie: __utma=99as Connection: Upgrade Host: echo.websocket.org Sec-WebSocket-Key: uRovscZjNol/umbTt5uKmw== Upgrade: websocket Sec-WebSocket-Version: 13 *) //Connection: Upgrade //Connection: keep-alive, Upgrade (firefox etc)) if Pos('upgrade', LowerCase(ARequestInfo.Connection)) <= 0 then //if not SameText('Upgrade', ARequestInfo.Connection) then inherited DoCommandGet(AContext, ARequestInfo, AResponseInfo) else begin context := AContext as TIdServerWSContext; //Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== sValue := ARequestInfo.RawHeaders.Values['sec-websocket-key']; //"The value of this header field MUST be a nonce consisting of a randomly // selected 16-byte value that has been base64-encoded" if (sValue <> '') then begin if (Length(TIdDecoderMIME.DecodeString(sValue)) = 16) then context.WebSocketKey := sValue else Abort; //invalid length end else //important: key must exists, otherwise stop! Abort; (* ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ] wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ] 2. The method of the request MUST be GET, and the HTTP version MUST be at least 1.1. For example, if the WebSocket URI is "ws://example.com/chat", the first line sent should be "GET /chat HTTP/1.1". 3. The "Request-URI" part of the request MUST match the /resource name/ defined in Section 3 (a relative URI) or be an absolute http/https URI that, when parsed, has a /resource name/, /host/, and /port/ that match the corresponding ws/wss URI. *) context.ResourceName := ARequestInfo.Document; if ARequestInfo.UnparsedParams <> '' then context.ResourceName := context.ResourceName + '?' + ARequestInfo.UnparsedParams; //seperate parts context.Path := ARequestInfo.Document; context.Query := ARequestInfo.UnparsedParams; //Host: server.example.com context.Host := ARequestInfo.RawHeaders.Values['host']; //Origin: http://example.com context.Origin := ARequestInfo.RawHeaders.Values['origin']; //Cookie: __utma=99as context.Cookie := ARequestInfo.RawHeaders.Values['cookie']; //Sec-WebSocket-Version: 13 //"The value of this header field MUST be 13" sValue := ARequestInfo.RawHeaders.Values['sec-websocket-version']; if (sValue <> '') then begin context.WebSocketVersion := StrToIntDef(sValue, 0); if context.WebSocketVersion < 13 then Abort; //must be at least 13 end else Abort; //must exist context.WebSocketProtocol := ARequestInfo.RawHeaders.Values['sec-websocket-protocol']; context.WebSocketExtensions := ARequestInfo.RawHeaders.Values['sec-websocket-extensions']; //Response (* HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= *) AResponseInfo.ResponseNo := 101; AResponseInfo.ResponseText := 'Switching Protocols'; AResponseInfo.CloseConnection := False; //Connection: Upgrade AResponseInfo.Connection := 'Upgrade'; //Upgrade: websocket AResponseInfo.CustomHeaders.Values['Upgrade'] := 'websocket'; //Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= sValue := Trim(context.WebSocketKey) + //... "minus any leading and trailing whitespace" '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; //special GUID sValue := TIdEncoderMIME.EncodeBytes( //Base64 FHash.HashString(sValue) ); //SHA1 //sValue := string(FHash.CalcString(AnsiString(sValue))); //SHA1 + Base64 AResponseInfo.CustomHeaders.Values['Sec-WebSocket-Accept'] := sValue; //send same protocol back? AResponseInfo.CustomHeaders.Values['Sec-WebSocket-Protocol'] := context.WebSocketProtocol; //we do not support extensions yet (gzip deflate compression etc) //AResponseInfo.CustomHeaders.Values['Sec-WebSocket-Extensions'] := context.WebSocketExtensions; //http://www.lenholgate.com/blog/2011/07/websockets---the-deflate-stream-extension-is-broken-and-badly-designed.html //but is could be done using idZlib.pas and DecompressGZipStream etc //send response back AContext.Connection.IOHandler.InputBuffer.Clear; (AContext.Connection.IOHandler as TIdIOHandlerWebsocket).BusyUpgrading := True; AResponseInfo.WriteHeader; //handle all WS communication in seperate loop DoWSExecute(AContext); end; end; procedure TIndyHTTPWebsocketServer.Loaded; begin inherited; if Self.IOHandler = nil then Self.IOHandler := TIdServerIOHandlerWebsocket.Create(Self); end; { TIdServerWSContext } function TIdServerWSContext.IOHandler: TIdIOHandlerWebsocket; begin Result := Self.Connection.IOHandler as TIdIOHandlerWebsocket; end; end.
unit OrderActionsUnit; interface uses SysUtils, BaseActionUnit, System.Generics.Collections, OrderUnit, OrderParametersUnit, CommonTypesUnit; type // TOrdersCustomFields = TList<TPair<string, string>>; TOrdersCustomFields = TList<TDictionary<string, string>>; TOrderActions = class(TBaseAction) private function GetDateStr(Date: TDate): String; function GetOrdersByAddedDate(AddedDate: TDate; out ErrorString: String): TOrderList; public function Get(OrderQuery: TOrderParameters; out Total: integer; out ErrorString: String): TOrderList; overload; function Get(OrderId: integer; out ErrorString: String): TOrder; overload; /// <summary> /// Retrieve orders inserted on a specified date. /// </summary> function Get(AddedDate: TDate; out ErrorString: String): TOrderList; overload; /// <summary> /// Retrieve orders scheduled for a specified date. /// </summary> function GetOrdersScheduledFor(ScheduledDate: TDate; out ErrorString: String): TOrderList; /// <summary> /// Searching all Orders with specified custom fields /// </summary> function GetOrdersWithCustomFields(Fields: TArray<String>; Limit, Offset: integer; out Total: integer; out ErrorString: String): TOrdersCustomFields; /// <summary> /// Search for all order records which contain specified text in any field /// </summary> function GetOrdersWithSpecifiedText(SpecifiedText: String; Limit, Offset: integer; out Total: integer; out ErrorString: String): TOrderList; function Add(Order: TOrder; out ErrorString: String): TOrder; function Update(Order: TOrder; out ErrorString: String): TOrder; function Remove(OrderIds: TIntegerArray; out ErrorString: String): boolean; procedure ScheduleOrder(OrderId: integer; ScheduleDate: TDate; out ErrorString: String); end; implementation { TOrderActions } uses System.NetEncoding, DateUtils, SettingsUnit, GetOrdersResponseUnit, RemoveOrdersRequestUnit, StatusResponseUnit, GenericParametersUnit, GetOrdersWithCustomFieldsResponseUnit; function TOrderActions.Add(Order: TOrder; out ErrorString: String): TOrder; begin Result := FConnection.Post(TSettings.EndPoints.Order, Order, TOrder, ErrorString) as TOrder; end; function TOrderActions.Get(OrderQuery: TOrderParameters; out Total: integer; out ErrorString: String): TOrderList; var Response: TGetOrdersResponse; i: integer; begin Result := TOrderList.Create; Total := 0; Response := FConnection.Get(TSettings.EndPoints.Order, OrderQuery, TGetOrdersResponse, ErrorString) as TGetOrdersResponse; try if (Response <> nil) then begin for i := 0 to Length(Response.Results) - 1 do Result.Add(Response.Results[i]); Total := Response.Total; end; finally FreeAndNil(Response); end; end; function TOrderActions.Get(OrderId: integer; out ErrorString: String): TOrder; var Request: TGenericParameters; begin Request := TGenericParameters.Create; try Request.AddParameter('order_id', IntToStr(OrderId)); Result := FConnection.Get(TSettings.EndPoints.Order, Request, TOrder, ErrorString) as TOrder; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Order details not got'; finally FreeAndNil(Request); end; end; function TOrderActions.Remove(OrderIds: TIntegerArray; out ErrorString: String): boolean; var Request: TRemoveOrdersRequest; Response: TStatusResponse; begin Request := TRemoveOrdersRequest.Create(); try Request.OrderIds := OrderIds; Response := FConnection.Delete(TSettings.EndPoints.Order, Request, TStatusResponse, ErrorString) as TStatusResponse; try Result := (Response <> nil) and (Response.Status); finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; procedure TOrderActions.ScheduleOrder(OrderId: integer; ScheduleDate: TDate; out ErrorString: String); var Order: TOrder; UpdatedOrder: TOrder; begin Order := Get(OrderId, ErrorString); try if (Order = nil) then Exit; Order.ScheduleDate := ScheduleDate; UpdatedOrder := Update(Order, ErrorString); try if (Order.ScheduleDate <> UpdatedOrder.ScheduleDate) then ErrorString := 'Set schedule order error'; finally FreeAndNil(UpdatedOrder); end; finally FreeAndNil(Order); end; end; function TOrderActions.Update(Order: TOrder; out ErrorString: String): TOrder; begin Result := FConnection.Put(TSettings.EndPoints.Order, Order, TOrder, ErrorString) as TOrder; end; function TOrderActions.Get(AddedDate: TDate; out ErrorString: String): TOrderList; var Orders, TempOrders: TOrderList; Order: TOrder; StartToday, FinishToday: Int64; TempErrorString: String; begin // "Today" orders Orders := GetOrdersByAddedDate(AddedDate, ErrorString); try // "Yesterday" orders TempOrders := GetOrdersByAddedDate(IncDay(AddedDate, -1), TempErrorString); try Orders.AddRange(TempOrders); TempOrders.OwnsObjects := False; finally FreeAndNil(TempOrders); end; // "Tomorrow" orders TempOrders := GetOrdersByAddedDate(IncDay(AddedDate, +1), TempErrorString); try Orders.AddRange(TempOrders); TempOrders.OwnsObjects := False; finally FreeAndNil(TempOrders); end; Result := TOrderList.Create; StartToday := DateTimeToUnix(StartOfTheDay(AddedDate), False); FinishToday := DateTimeToUnix(EndOfTheDay(AddedDate), False); for Order in Orders do begin if (Order.CreatedTimestamp >= StartToday) and (Order.CreatedTimestamp <= FinishToday) then begin Result.Add(Order); Orders.Extract(Order); end; end; finally FreeAndNil(Orders); end; end; function TOrderActions.GetDateStr(Date: TDate): String; var FormatSettings: TFormatSettings; begin FormatSettings := TFormatSettings.Create; FormatSettings.ShortDateFormat := 'yyyy-mm-dd'; FormatSettings.DateSeparator := '-'; Result := DateToStr(Date, FormatSettings); end; function TOrderActions.GetOrdersByAddedDate(AddedDate: TDate; out ErrorString: String): TOrderList; var Response: TGetOrdersResponse; Request: TGenericParameters; i: integer; begin Result := TOrderList.Create; Request := TGenericParameters.Create; try Request.AddParameter('day_added_YYMMDD', GetDateStr(AddedDate)); Response := FConnection.Get(TSettings.EndPoints.Order, Request, TGetOrdersResponse, ErrorString) as TGetOrdersResponse; try if (Response <> nil) then for i := 0 to Length(Response.Results) - 1 do Result.Add(Response.Results[i]) else if (ErrorString = EmptyStr) then ErrorString := 'Order details not got'; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TOrderActions.GetOrdersScheduledFor(ScheduledDate: TDate; out ErrorString: String): TOrderList; var Response: TGetOrdersResponse; Request: TGenericParameters; i: integer; begin Result := TOrderList.Create; Request := TGenericParameters.Create; try Request.AddParameter('scheduled_for_YYMMDD', GetDateStr(ScheduledDate)); Response := FConnection.Get(TSettings.EndPoints.Order, Request, TGetOrdersResponse, ErrorString) as TGetOrdersResponse; try if (Response <> nil) then for i := 0 to Length(Response.Results) - 1 do Result.Add(Response.Results[i]) else if (ErrorString = EmptyStr) then ErrorString := 'Order details not got'; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TOrderActions.GetOrdersWithCustomFields(Fields: TArray<String>; Limit, Offset: integer; out Total: integer; out ErrorString: String): TOrdersCustomFields; var Response: TGetOrdersWithCustomFieldsResponse; Request: TGenericParameters; i, j: integer; FieldsStr: String; Item: TStringArray; Dict: TDictionary<string,string>; begin Result := TOrdersCustomFields.Create(); Total := 0; FieldsStr := EmptyStr; for i := 0 to High(Fields) do begin if (i <> 0) then FieldsStr := FieldsStr + ','; FieldsStr := FieldsStr + Fields[i]; end; Request := TGenericParameters.Create; try Request.AddParameter('fields', FieldsStr); Request.AddParameter('offset', IntToStr(Offset)); Request.AddParameter('limit', IntToStr(Limit)); Response := FConnection.Get(TSettings.EndPoints.Order, Request, TGetOrdersWithCustomFieldsResponse, ErrorString) as TGetOrdersWithCustomFieldsResponse; try if (Response <> nil) then begin for i := 0 to Response.ResultCount - 1 do begin Item := Response.Results[i]; { if (Length(Item) = 0) then Continue;} if (Length(Item) < Length(Fields)) then raise Exception.Create('Some fields not existing in a database!'); Dict := TDictionary<string,string>.Create; for j := 0 to High(Response.Fields) do Dict.Add(Response.Fields[j], Item[j]); Result.Add(Dict); end; Total := Response.Total; end else if (ErrorString = EmptyStr) then ErrorString := 'Order details not got'; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; // TOrdersCustomFields = TList<TPair<string, string>>; end; function TOrderActions.GetOrdersWithSpecifiedText(SpecifiedText: String; Limit, Offset: integer; out Total: integer; out ErrorString: String): TOrderList; var Response: TGetOrdersResponse; Request: TGenericParameters; i: integer; begin Result := TOrderList.Create; Total := 0; Request := TGenericParameters.Create; try Request.AddParameter('query', TNetEncoding.URL.Encode(SpecifiedText)); Request.AddParameter('offset', IntToStr(Offset)); Request.AddParameter('limit', IntToStr(Limit)); Response := FConnection.Get(TSettings.EndPoints.Order, Request, TGetOrdersResponse, ErrorString) as TGetOrdersResponse; try if (Response <> nil) then begin for i := 0 to Length(Response.Results) - 1 do Result.Add(Response.Results[i]); Total := Response.Total; end else if (ErrorString = EmptyStr) then ErrorString := 'Order details not got'; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; end.
unit ChromeLikeDrawingContext; // Модуль: "w:\common\components\gui\Garant\ChromeLikeControls\ChromeLikeDrawingContext.pas" // Стереотип: "SimpleClass" // Элемент модели: "TChromeLikeDrawingContext" MUID: (5507C7FA00EE) interface {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3IntfUses , l3ProtoObject , ChromeLikeTabSetTypes , GDIPOBJ , Graphics ; type TChromeLikeDrawingContext = class(Tl3ProtoObject, IChromeLkeTabSetDrawingContext) private f_Graphics: TGPGraphics; f_Canvas: TCanvas; protected function pm_GetCanvas: TCanvas; function pm_GetGraphics: TGPGraphics; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aCanvas: TCanvas); reintroduce; class function Make(aCanvas: TCanvas): IChromeLkeTabSetDrawingContext; reintroduce; end;//TChromeLikeDrawingContext {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) implementation {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3ImplUses , ChromeLikeTabSetUtils , SysUtils //#UC START# *5507C7FA00EEimpl_uses* //#UC END# *5507C7FA00EEimpl_uses* ; constructor TChromeLikeDrawingContext.Create(aCanvas: TCanvas); //#UC START# *5507E6C202EE_5507C7FA00EE_var* //#UC END# *5507E6C202EE_5507C7FA00EE_var* begin //#UC START# *5507E6C202EE_5507C7FA00EE_impl* inherited Create; f_Canvas := aCanvas; f_Graphics := nil; //#UC END# *5507E6C202EE_5507C7FA00EE_impl* end;//TChromeLikeDrawingContext.Create class function TChromeLikeDrawingContext.Make(aCanvas: TCanvas): IChromeLkeTabSetDrawingContext; var l_Inst : TChromeLikeDrawingContext; begin l_Inst := Create(aCanvas); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TChromeLikeDrawingContext.Make function TChromeLikeDrawingContext.pm_GetCanvas: TCanvas; //#UC START# *5507DFFF038B_5507C7FA00EEget_var* //#UC END# *5507DFFF038B_5507C7FA00EEget_var* begin //#UC START# *5507DFFF038B_5507C7FA00EEget_impl* Result := f_Canvas; //#UC END# *5507DFFF038B_5507C7FA00EEget_impl* end;//TChromeLikeDrawingContext.pm_GetCanvas function TChromeLikeDrawingContext.pm_GetGraphics: TGPGraphics; //#UC START# *5507E011038E_5507C7FA00EEget_var* //#UC END# *5507E011038E_5507C7FA00EEget_var* begin //#UC START# *5507E011038E_5507C7FA00EEget_impl* if (f_Graphics = nil) then f_Graphics := TGPGraphics.Create(f_Canvas.Handle); Result := f_Graphics; //#UC END# *5507E011038E_5507C7FA00EEget_impl* end;//TChromeLikeDrawingContext.pm_GetGraphics procedure TChromeLikeDrawingContext.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5507C7FA00EE_var* //#UC END# *479731C50290_5507C7FA00EE_var* begin //#UC START# *479731C50290_5507C7FA00EE_impl* FreeAndNil(f_Graphics); inherited; //#UC END# *479731C50290_5507C7FA00EE_impl* end;//TChromeLikeDrawingContext.Cleanup {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) end.
unit GetLocationUnit; interface uses SysUtils, BaseExampleUnit; type TGetLocation = class(TBaseExample) public procedure Execute(Query: String); end; implementation uses AddressBookContactUnit; procedure TGetLocation.Execute(Query: String); var ErrorString: String; Total: integer; Contacts: TAddressBookContactList; Limit, Offset: integer; begin Limit := 10; Offset := 0; Contacts := Route4MeManager.AddressBookContact.Find( Query, Limit, Offset, Total, ErrorString); try WriteLn(''); if (Contacts.Count > 0) then begin WriteLn(Format('GetLocation executed successfully, ' + '%d contacts returned, total = %d', [Contacts.Count, Total])); WriteLn(''); end else WriteLn(Format('GetLocation error: "%s"', [ErrorString])); finally FreeAndNil(Contacts); end; end; end.
unit CompResUpdate; { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Resource update functions used by the compiler only $jrsoftware: issrc/Projects/CompResUpdate.pas,v 1.25 2010/04/05 20:53:41 jr Exp $ } interface uses Windows, SysUtils, FileClass, VerInfo; {$I VERSION.INC} procedure UpdateIcons(const FileName, IcoFileName: String); procedure UpdateVersionInfo(const F: TFile; const NewBinaryFileVersion, NewBinaryProductVersion: TFileVersionNumbers; const NewCompanyName, NewFileDescription, NewTextFileVersion, NewLegalCopyright, NewProductName, NewTextProductVersion: String); implementation uses ResUpdate{$IFDEF UNICODE}, Math{$ENDIF}; procedure Error(const Msg: String); begin raise Exception.Create('Resource update error: ' + Msg); end; procedure ErrorWithLastError(const Msg: String); begin Error(Msg + ' (' + IntToStr(GetLastError) + ')'); end; procedure UpdateVersionInfo(const F: TFile; const NewBinaryFileVersion, NewBinaryProductVersion: TFileVersionNumbers; const NewCompanyName, NewFileDescription, NewTextFileVersion, NewLegalCopyright, NewProductName, NewTextProductVersion: String); function WideStrsEqual(P1, P2: PWideChar): Boolean; function WideUpCase(C: WideChar): WideChar; begin Result := C; if (Result >= 'a') and (Result <= 'z') then Dec(Result, Ord('a') - Ord('A')); end; begin while True do begin if WideUpCase(P1^) <> WideUpCase(P2^) then begin Result := False; Exit; end; if P1^ = #0 then Break; Inc(P1); Inc(P2); end; Result := True; end; procedure BumpToDWordBoundary(var P: Pointer); begin if Cardinal(P) and 3 <> 0 then Cardinal(P) := (Cardinal(P) or 3) + 1; end; function QueryValue(P: Pointer; Path: PWideChar; var Buf: Pointer; var BufLen: Cardinal): Boolean; var EndP: Pointer; ValueLength: Cardinal; begin Result := False; Cardinal(EndP) := Cardinal(P) + PWord(P)^; Inc(PWord(P)); ValueLength := PWord(P)^; Inc(PWord(P)); Inc(PWord(P)); if WideStrsEqual(PWideChar(P), Path) then begin Inc(PWideChar(P), lstrlenW(P) + 1); BumpToDWordBoundary(P); Inc(Path, lstrlenW(Path) + 1); if Path^ = #0 then begin { Found the requested value } Buf := P; BufLen := ValueLength; Result := True; end else begin { Handle children. Note: Like VerQueryValue, we always treat ValueLength as a byte count when looking for child nodes. Many resource compilers, including Borland's, wrongly set ValueLength to a *character* count on string nodes. But since we never try to query for a child of a string node, that doesn't matter here. } Inc(Cardinal(P), ValueLength); BumpToDWordBoundary(P); while Cardinal(P) < Cardinal(EndP) do begin Result := QueryValue(P, Path, Buf, BufLen); if Result then Exit; Inc(Cardinal(P), PWord(P)^); BumpToDWordBoundary(P); end; end; end; end; procedure ReplaceWithRealCopyrightSymbols(const Value: PWideChar); var Len, I, J: Integer; begin Len := lstrlenW(Value); for I := 0 to Len-3 do begin if (Value[I] = '(') and (Value[I+1] = 'C') and (Value[I+2] = ')') then begin Value[I] := WideChar($00A9); { Shift back two characters } for J := I+1 to Len-3 do Value[J] := Value[J+2]; Value[Len-2] := ' '; Value[Len-1] := ' '; end; end; end; procedure UpdateStringValue(P: Pointer; const Path: PWideChar; NewValue: String); var Value: PWideChar; ValueLen: Cardinal; begin if not QueryValue(P, Path, Pointer(Value), ValueLen) then Error('Unexpected version resource format (1)'); {$IFDEF UNICODE} Move(Pointer(NewValue)^, Value^, (Min(Length(NewValue), lstrlenW(Value)))*SizeOf(Char)); {$ELSE} MultiByteToWideChar(CP_ACP, 0, PChar(NewValue), Length(NewValue), Value, lstrlenW(Value)); {$ENDIF} ReplaceWithRealCopyrightSymbols(Value); end; procedure UpdateFixedFileInfo(P: Pointer; const Path: PWideChar; NewFileVersion, NewProductVersion: TFileVersionNumbers); var FixedFileInfo: PVSFixedFileInfo; ValueLen: Cardinal; begin if not QueryValue(P, Path, Pointer(FixedFileInfo), ValueLen) then Error('Unexpected version resource format (2)'); if FixedFileInfo.dwSignature <> $FEEF04BD then Error('Unexpected version resource format (3)'); FixedFileInfo.dwFileVersionLS := NewFileVersion.LS; FixedFileInfo.dwFileVersionMS := NewFileVersion.MS; FixedFileInfo.dwProductVersionLS := NewProductVersion.LS; FixedFileInfo.dwProductVersionMS := NewProductVersion.MS; end; var ResOffset, ResSize: Cardinal; VersRes: Pointer; begin { Locate the resource } ResSize := SeekToResourceData(F, Cardinal(RT_VERSION), 1); ResOffset := F.Position.Lo; GetMem(VersRes, ResSize); try { Read the resource } F.ReadBuffer(VersRes^, ResSize); { Update the resource } UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'CompanyName'#0, NewCompanyName); UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'FileDescription'#0, NewFileDescription); UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'FileVersion'#0, NewTextFileVersion); UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'LegalCopyright'#0, NewLegalCopyright); UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'ProductName'#0, NewProductName); UpdateStringValue(VersRes, 'VS_VERSION_INFO'#0'StringFileInfo'#0'000004b0'#0'ProductVersion'#0, NewTextProductVersion); UpdateFixedFileInfo(VersRes, 'VS_VERSION_INFO'#0, NewBinaryFileVersion, NewBinaryProductVersion); { Write the updated resource } F.Seek(ResOffset); F.WriteBuffer(VersRes^, ResSize); finally FreeMem(VersRes); end; end; function EnumLangsFunc(hModule: Cardinal; lpType, lpName: PAnsiChar; wLanguage: Word; lParam: Integer): BOOL; stdcall; begin PWord(lParam)^ := wLanguage; Result := False; end; function GetResourceLanguage(hModule: Cardinal; lpType, lpName: PChar; var wLanguage: Word): Boolean; begin wLanguage := 0; EnumResourceLanguages(hModule, lpType, lpName, @EnumLangsFunc, Integer(@wLanguage)); Result := True; end; procedure UpdateIcons(const FileName, IcoFileName: String); type PIcoItemHeader = ^TIcoItemHeader; TIcoItemHeader = packed record Width: Byte; Height: Byte; Colors: Byte; Reserved: Byte; Planes: Word; BitCount: Word; ImageSize: DWORD; end; PIcoItem = ^TIcoItem; TIcoItem = packed record Header: TIcoItemHeader; Offset: DWORD; end; PIcoHeader = ^TIcoHeader; TIcoHeader = packed record Reserved: Word; Typ: Word; ItemCount: Word; Items: array [0..MaxInt shr 4 - 1] of TIcoItem; end; PGroupIconDirItem = ^TGroupIconDirItem; TGroupIconDirItem = packed record Header: TIcoItemHeader; Id: Word; end; PGroupIconDir = ^TGroupIconDir; TGroupIconDir = packed record Reserved: Word; Typ: Word; ItemCount: Word; Items: array [0..MaxInt shr 4 - 1] of TGroupIconDirItem; end; function IsValidIcon(P: Pointer; Size: Cardinal): Boolean; var ItemCount: Cardinal; begin Result := False; if Size < Cardinal(SizeOf(Word) * 3) then Exit; if (PChar(P)[0] = 'M') and (PChar(P)[1] = 'Z') then Exit; ItemCount := PIcoHeader(P).ItemCount; if Size < Cardinal((SizeOf(Word) * 3) + (ItemCount * SizeOf(TIcoItem))) then Exit; P := @PIcoHeader(P).Items; while ItemCount > Cardinal(0) do begin if (Cardinal(PIcoItem(P).Offset + PIcoItem(P).Header.ImageSize) < Cardinal(PIcoItem(P).Offset)) or (Cardinal(PIcoItem(P).Offset + PIcoItem(P).Header.ImageSize) > Cardinal(Size)) then Exit; Inc(PIcoItem(P)); Dec(ItemCount); end; Result := True; end; var H: THandle; M: HMODULE; R: HRSRC; Res: HGLOBAL; GroupIconDir, NewGroupIconDir: PGroupIconDir; I: Integer; wLanguage: Word; F: TFile; Ico: PIcoHeader; N: Cardinal; NewGroupIconDirSize: LongInt; begin if Win32Platform <> VER_PLATFORM_WIN32_NT then Error('Only supported on Windows NT and above'); Ico := nil; try { Load the icons } F := TFile.Create(IcoFileName, fdOpenExisting, faRead, fsRead); try N := F.CappedSize; if Cardinal(N) > Cardinal($100000) then { sanity check } Error('Icon file is too large'); GetMem(Ico, N); F.ReadBuffer(Ico^, N); finally F.Free; end; { Ensure the icon is valid } if not IsValidIcon(Ico, N) then Error('Icon file is invalid'); { Update the resources } H := BeginUpdateResource(PChar(FileName), False); if H = 0 then ErrorWithLastError('BeginUpdateResource failed (1)'); try M := LoadLibraryEx(PChar(FileName), 0, LOAD_LIBRARY_AS_DATAFILE); if M = 0 then ErrorWithLastError('LoadLibraryEx failed (1)'); try { Load the 'MAINICON' group icon resource } R := FindResource(M, 'MAINICON', RT_GROUP_ICON); if R = 0 then ErrorWithLastError('FindResource failed (1)'); Res := LoadResource(M, R); if Res = 0 then ErrorWithLastError('LoadResource failed (1)'); GroupIconDir := LockResource(Res); if GroupIconDir = nil then ErrorWithLastError('LockResource failed (1)'); { Delete 'MAINICON' } if not GetResourceLanguage(M, RT_GROUP_ICON, 'MAINICON', wLanguage) then Error('GetResourceLanguage failed (1)'); if not UpdateResource(H, RT_GROUP_ICON, 'MAINICON', wLanguage, nil, 0) then ErrorWithLastError('UpdateResource failed (1)'); { Delete the RT_ICON icon resources that belonged to 'MAINICON' } for I := 0 to GroupIconDir.ItemCount-1 do begin if not GetResourceLanguage(M, RT_ICON, MakeIntResource(GroupIconDir.Items[I].Id), wLanguage) then Error('GetResourceLanguage failed (2)'); if not UpdateResource(H, RT_ICON, MakeIntResource(GroupIconDir.Items[I].Id), wLanguage, nil, 0) then ErrorWithLastError('UpdateResource failed (2)'); end; { Build the new group icon resource } NewGroupIconDirSize := 3*SizeOf(Word)+Ico.ItemCount*SizeOf(TGroupIconDirItem); GetMem(NewGroupIconDir, NewGroupIconDirSize); try { Build the new group icon resource } NewGroupIconDir.Reserved := GroupIconDir.Reserved; NewGroupIconDir.Typ := GroupIconDir.Typ; NewGroupIconDir.ItemCount := Ico.ItemCount; for I := 0 to NewGroupIconDir.ItemCount-1 do begin NewGroupIconDir.Items[I].Header := Ico.Items[I].Header; NewGroupIconDir.Items[I].Id := I+1; //assumes that there aren't any icons left end; { Update 'MAINICON' } for I := 0 to NewGroupIconDir.ItemCount-1 do if not UpdateResource(H, RT_ICON, MakeIntResource(NewGroupIconDir.Items[I].Id), 1033, Pointer(DWORD(Ico) + Ico.Items[I].Offset), Ico.Items[I].Header.ImageSize) then ErrorWithLastError('UpdateResource failed (3)'); { Update the icons } if not UpdateResource(H, RT_GROUP_ICON, 'MAINICON', 1033, NewGroupIconDir, NewGroupIconDirSize) then ErrorWithLastError('UpdateResource failed (4)'); finally FreeMem(NewGroupIconDir); end; finally FreeLibrary(M); end; except EndUpdateResource(H, True); { discard changes } raise; end; if not EndUpdateResource(H, False) then ErrorWithLastError('EndUpdateResource failed'); finally FreeMem(Ico); end; end; end.
//Exercício 4: Escreva um algoritmo que receba as medidas de frente e fundo de um terreno. Calcule e //exiba a área do terreno. { Solução em Portugol Algoritmo Exercicio; Var frente,fundo,area: inteiro; Inicio exiba("Programa que calcula a área de um terreno."); exiba("Digite a medida da frente do terreno: "); leia(frente); exiba("Digite a medida do fundo do terreno: "); leia(fundo); area <- frente * fundo; exiba("A área do terreno é de ", area,"unidades de área."); // Unidades de área podem ser, por exemplo, m². Fim. } // Solução em Pascal Program Exercicio; uses crt; var frente,fundo,area: integer; begin clrscr; writeln('Programa que calcula a área de um terreno.'); writeln('Digite a medida da frente do terreno: '); readln(frente); writeln('Digite a medida do fundo do terreno: '); readln(fundo); area := frente * fundo; writeln('A área do terreno é de ', area,' unidades de área.'); // Unidades de área podem ser, por exemplo, m². repeat until keypressed; end.
unit LinksUnit; interface uses REST.Json.Types, System.Generics.Collections, JSONNullableAttributeUnit, NullableBasicTypesUnit; type /// <summary> /// Links /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Links.dtd /// </remarks> TLinks = class private [JSONName('route')] [Nullable] FRoute: NullableString; [JSONName('view')] [Nullable] FView: NullableString; [JSONName('optimization_problem_id')] [Nullable] FOptimizationProblemId: NullableString; public constructor Create; function Equals(Obj: TObject): Boolean; override; property Route: NullableString read FRoute write FRoute; property View: NullableString read FView write FView; property OptimizationProblemId: NullableString read FOptimizationProblemId write FOptimizationProblemId; end; implementation { TLinks } constructor TLinks.Create; begin FRoute := NullableString.Null; FView := NullableString.Null; FOptimizationProblemId := NullableString.Null; end; function TLinks.Equals(Obj: TObject): Boolean; var Other: TLinks; begin Result := False; if not (Obj is TLinks) then Exit; Other := TLinks(Obj); Result := (FRoute = Other.FRoute) and (FView = Other.FView) and (FOptimizationProblemId = Other.FOptimizationProblemId); end; end.
unit DW.iOSapi.PushKit; {*******************************************************} { } { Kastri } { } { Delphi Worlds Cross-Platform Library } { } { Copyright 2020-2021 Dave Nottage under MIT license } { which is located in the root folder of this library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // macOS Macapi.ObjectiveC, Macapi.Dispatch, // iOS iOSapi.CocoaTypes, iOSapi.Foundation; type PKPushCredentials = interface; PKPushPayload = interface; PKPushRegistry = interface; PKPushRegistryDelegate = interface; PKPushType = NSString; PKPushCredentialsClass = interface(NSObjectClass) ['{3E434925-7A0F-47F3-A1C6-0D7AE1C8543B}'] end; PKPushCredentials = interface(NSObject) ['{BBACB9D2-98D3-4048-BA6D-AF4E5128FFBA}'] function &type: PKPushType; cdecl; function token: NSData; cdecl; end; TPKPushCredentials = class(TOCGenericImport<PKPushCredentialsClass, PKPushCredentials>) end; PKPushPayloadClass = interface(NSObjectClass) ['{F066DA5B-5D3D-43F7-9E5D-8AE3C7C216B2}'] end; PKPushPayload = interface(NSObject) ['{1F805F0D-D8EB-4694-A2CB-76504F2B8C37}'] function &type: PKPushType; cdecl; function dictionaryPayload: NSDictionary; cdecl; end; TPKPushPayload = class(TOCGenericImport<PKPushPayloadClass, PKPushPayload>) end; PKPushRegistryClass = interface(NSObjectClass) ['{98807B48-7926-4FCF-8901-1F9CCB96C606}'] end; PKPushRegistry = interface(NSObject) ['{45145A11-AA0F-4BF5-A2C5-3A66B67D23F9}'] function delegate: Pointer; cdecl; function desiredPushTypes: NSSet; cdecl; function initWithQueue(queue: dispatch_queue_t): Pointer; cdecl; function pushTokenForType(&type: PKPushType): NSData; cdecl; procedure setDelegate(delegate: Pointer); cdecl; procedure setDesiredPushTypes(desiredPushTypes: NSSet); cdecl; end; TPKPushRegistry = class(TOCGenericImport<PKPushRegistryClass, PKPushRegistry>) end; PKPushRegistryDelegate = interface(IObjectiveC) ['{15106303-561D-47D6-9E76-C32C5B842E00}'] procedure pushRegistry(registry: PKPushRegistry; didInvalidatePushTokenForType: PKPushType); overload; cdecl; procedure pushRegistry(registry: PKPushRegistry; didReceiveIncomingPushWithPayload: PKPushPayload; forType: PKPushType; withCompletionHandler: Pointer); overload; cdecl; // procedure of object // API_DEPRECATED_WITH_REPLACEMENT("-pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload // forType:(PKPushType)type withCompletionHandler:(void(^)(void))completion", ios(8.0, 11.0)) // procedure pushRegistry(registry: PKPushRegistry; didReceiveIncomingPushWithPayload: PKPushPayload; forType: PKPushType); overload; cdecl; procedure pushRegistry(registry: PKPushRegistry; didUpdatePushCredentials: PKPushCredentials; forType: PKPushType); overload; cdecl; end; function PKPushTypeVoIP: PKPushType; function PKPushTypeComplication: PKPushType; function PKPushTypeFileProvider: PKPushType; const libPushKit = '/System/Library/Frameworks/PushKit.framework/PushKit'; implementation {$IF Defined(IOS) and not Defined(CPUARM)} uses Posix.Dlfcn; var PushKitModule: THandle; {$ENDIF} function PKPushTypeVoIP: PKPushType; begin Result := CocoaNSStringConst(libPushKit, 'PKPushTypeVoIP'); end; function PKPushTypeComplication: PKPushType; begin Result := CocoaNSStringConst(libPushKit, 'PKPushTypeComplication'); end; function PKPushTypeFileProvider: PKPushType; begin Result := CocoaNSStringConst(libPushKit, 'PKPushTypeFileProvider'); end; {$IF Defined(IOS) and not Defined(CPUARM)} initialization PushKitModule := dlopen(MarshaledAString(libPushKit), RTLD_LAZY); finalization dlclose(PushKitModule) {$ENDIF} end.
unit uIni; interface uses // Own units UCommon; type TIni = class(THODObject) private FFileName: string; public //** Конструктор. constructor Create(const FileName: string); destructor Destroy; override; function Read(const Section, Ident, Default: string): string; overload; function Read(const Section, Ident: string; Default: Integer): Integer; overload; function Read(const FileName, Section, Ident, Default: string): string; overload; function Read(const FileName, Section, Ident: string; Default: Integer): Integer; overload; procedure Write(const Section, Ident, Value: string); overload; procedure Write(const Section, Ident: string; Value: Integer); overload; procedure Write(const FileName, Section, Ident, Value: string); overload; procedure Write(const FileName, Section, Ident: string; Value: Integer); overload; function FontName: string; end; var Ini: TIni; implementation uses IniFiles, uUtils; { TIni } constructor TIni.Create(const FileName: string); begin FFileName := FileName; end; destructor TIni.Destroy; begin inherited; end; function TIni.FontName: string; var I: TIniFile; begin I := TIniFile.Create(FFileName); try Result := I.ReadString('Font', 'FontFileName', 'Heinrich Text.ttf'); finally I.Free; end; end; function TIni.Read(const Section, Ident, Default: string): string; begin Result := Read(FFileName, Section, Ident, Default); end; function TIni.Read(const Section, Ident: string; Default: Integer): Integer; begin Result := Read(FFileName, Section, Ident, Default); end; procedure TIni.Write(const Section, Ident, Value: string); begin Write(FFileName, Section, Ident, Value); end; procedure TIni.Write(const Section, Ident: string; Value: Integer); begin Write(FFileName, Section, Ident, Value); end; function TIni.Read(const FileName, Section, Ident: string; Default: Integer): Integer; var I: TIniFile; begin I := TIniFile.Create(FileName); try Result := I.ReadInteger(Section, Ident, Default); finally I.Free; end; end; function TIni.Read(const FileName, Section, Ident, Default: string): string; var I: TIniFile; begin I := TIniFile.Create(FileName); try Result := I.ReadString(Section, Ident, Default); finally I.Free; end; end; procedure TIni.Write(const FileName, Section, Ident: string; Value: Integer); var I: TIniFile; begin I := TIniFile.Create(FileName); try I.WriteInteger(Section, Ident, Value); finally I.Free; end; end; procedure TIni.Write(const FileName, Section, Ident, Value: string); var I: TIniFile; begin I := TIniFile.Create(FileName); try I.WriteString(Section, Ident, Value); finally I.Free; end; end; initialization Ini := TIni.Create(Path + 'Data\HoD.ini'); finalization Ini.Free; end.
unit GX_EditorExpert; interface uses Classes, Graphics, GX_Actions, GX_ConfigurationInfo, GX_BaseExpert; type TEditorExpert = class(TGX_BaseExpert) private FGxAction: IGxAction; FActionName: string; protected function GetShortCut: TShortCut; override; procedure SetShortCut(Value: TShortCut); override; // defaults to ClassName function GetBitmapFileName: string; override; // you usually don't need to override this procedure LoadActiveAndShortCut(Settings: TGExpertsSettings); override; // you usually don't need to override this procedure SaveActiveAndShortCut(Settings: TGExpertsSettings); override; procedure ActionOnUpdate(Sender: TObject); public constructor Create; virtual; destructor Destroy; override; // returns true function CanHaveShortCut: boolean; override; procedure DoExecute(Sender: TObject); function GetActionName: string; // you usually don't need to override this function GetOptionsBaseRegistryKey: string; override; end; TEditorExpertClass = class of TEditorExpert; function EditorExpertClassList: TList; procedure RegisterEditorExpert(AClass: TEditorExpertClass); function GetExpertClass(const ClassName: string): TEditorExpertClass; function GetExpertClassByIndex(const Index: Integer): TEditorExpertClass; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} SysUtils, Dialogs, ActnList, GX_ActionBroker, GX_OtaUtils, GX_GxUtils, GX_GenericUtils, GX_MessageBox, GX_IconMessageBox; { Global utility functions } procedure RegisterEditorExpert(AClass: TEditorExpertClass); var ClassName: string; begin Assert(Assigned(AClass)); ClassName := AClass.ClassName; if GetExpertClass(ClassName) <> nil then begin {raise EFilerError.CreateFmt(SDuplicateClass, [ClassName]);} Exit; end; EditorExpertClassList.Add(AClass); end; function GetExpertClass(const ClassName: string): TEditorExpertClass; var I: Integer; begin Assert(Length(ClassName) > 0); for I := 0 to EditorExpertClassList.Count - 1 do begin Result := EditorExpertClassList[I]; if Result.ClassNameIs(ClassName) then Exit; end; Result := nil; end; function GetExpertClassByIndex(const Index: Integer): TEditorExpertClass; begin Assert((Index >= 0) and (Index <= EditorExpertClassList.Count - 1)); Result := EditorExpertClassList[Index]; end; { TEditorExpert } constructor TEditorExpert.Create; const EditorExpertPrefix = 'EditorExpert'; // Do not localize. begin inherited Create; Assert(IsValidIdent(GetName), Format('%s needs to specify a valid name; currently it is "%s"', [Self.ClassName, GetName])); FActionName := EditorExpertPrefix + GetName; FGxAction := GxActionBroker.RequestAction(FActionName, GetBitmap); FGxAction.OnExecute := Self.DoExecute; FGxAction.Caption := GetDisplayName; FGxAction.OnUpdate := ActionOnUpdate; ShortCut := GetDefaultShortCut; end; destructor TEditorExpert.Destroy; begin FGxAction := nil; // Clear out interface reference. inherited Destroy; end; function TEditorExpert.GetOptionsBaseRegistryKey: string; begin Result := AddSlash(ConfigInfo.GExpertsIdeRootRegistryKey) + 'EditorExperts'; // Do not localize. end; function TEditorExpert.GetShortCut: TShortCut; begin Assert(Assigned(FGxAction)); Result := FGxAction.ShortCut end; procedure TEditorExpert.LoadActiveAndShortCut(Settings: TGExpertsSettings); begin inherited; ShortCut := Settings.ReadInteger(ConfigurationKey, 'ShortCut', ShortCut); Active := Settings.ReadBool(ConfigurationKey, 'Active', IsDefaultActive); end; procedure TEditorExpert.SaveActiveAndShortCut(Settings: TGExpertsSettings); begin inherited; Settings.WriteInteger(ConfigurationKey, 'ShortCut', ShortCut); Settings.WriteBool(ConfigurationKey, 'Active', Active); end; procedure TEditorExpert.SetShortCut(Value: TShortCut); begin Assert(Assigned(FGxAction)); FGxAction.ShortCut := Value; end; function TEditorExpert.CanHaveShortCut: boolean; begin Result := True; end; var PrivateEditorExpertClassList: TList; function EditorExpertClassList: TList; begin Result := PrivateEditorExpertClassList; end; function TEditorExpert.GetBitmapFileName: string; begin Result := ClassName; end; function TEditorExpert.GetActionName: string; begin Result := GExpertsActionCategory + GxGenericActionQualifier + FActionName; end; procedure TEditorExpert.ActionOnUpdate(Sender: TObject); var SendingAction: TCustomAction; begin // All editor experts require a current edit view SendingAction := Sender as TCustomAction; Assert(Assigned(SendingAction)); SendingAction.Enabled := (GxOtaGetTopMostEditView <> nil); end; procedure TEditorExpert.DoExecute(Sender: TObject); begin try Execute(Sender); except // Trap exceptions because the editor will continue to insert the pressed // shortcut character into the editor (in D6 at least) on E: Exception do ShowError(E.Message); end; end; initialization PrivateEditorExpertClassList := TList.Create; finalization FreeAndNil(PrivateEditorExpertClassList); end.
unit udmCartasDeCorrecao; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmCartasDeCorrecao = class(TdmPadrao) qryManutencaoFIL_CARTA: TStringField; qryManutencaoNRO_CARTA: TIntegerField; qryManutencaoEMISSAO: TDateTimeField; qryManutencaoCGC: TStringField; qryManutencaoCTO_DOCUMENTO: TStringField; qryManutencaoCTO_FILIAL: TStringField; qryManutencaoCTO_NUMERO: TIntegerField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryManutencaoNM_CLIENTE: TStringField; qryManutencaoCTO_EMISSAO: TDateTimeField; qryLocalizacaoFIL_CARTA: TStringField; qryLocalizacaoNRO_CARTA: TIntegerField; qryLocalizacaoEMISSAO: TDateTimeField; qryLocalizacaoCGC: TStringField; qryLocalizacaoCTO_DOCUMENTO: TStringField; qryLocalizacaoCTO_FILIAL: TStringField; qryLocalizacaoCTO_NUMERO: TIntegerField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoNM_CLIENTE: TStringField; qryLocalizacaoCTO_EMISSAO: TDateTimeField; protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FCto_Numero: Real; FNro_Carta: Real; FCto_Emissora: string; FCto_Documento: string; FEmissora: string; public property Emissora: string read FEmissora write FEmissora; property Nro_Carta: Real read FNro_Carta write FNro_Carta; property Cto_Documento: string read FCto_Documento write FCto_Documento; property Cto_Emissora: string read FCto_Emissora write FCto_Emissora; property Cto_Numero: Real read FCto_Numero write FCto_Numero; function LocalizarPorDocumento(DataSet: TDataSet = nil): Boolean; end; const SQL_DEFAULT = ' SELECT ' + ' CAR.FIL_CARTA, ' + ' CAR.NRO_CARTA, ' + ' CAR.EMISSAO, ' + ' CAR.CGC, ' + ' CAR.CTO_DOCUMENTO, ' + ' CAR.CTO_FILIAL, ' + ' CAR.CTO_NUMERO, ' + ' CAR.DT_ALTERACAO, ' + ' CAR.OPERADOR, ' + ' CLI.NOME NM_CLIENTE, ' + ' MOV.DT_EMISSAO CTO_EMISSAO ' + ' FROM STWFATTCRTA CAR ' + ' LEFT JOIN STWOPETCLI CLI ON CAR.CGC = CLI.CGC ' + ' LEFT JOIN STWOPETMOV MOV ON CAR.CTO_DOCUMENTO = MOV.DOCUMENTO ' + ' AND CAR.CTO_FILIAL = MOV.FIL_ORIG ' + ' AND CAR.CTO_NUMERO = MOV.NR_CTO '; var dmCartasDeCorrecao: TdmCartasDeCorrecao; implementation {$R *.dfm} { TdmCartasDeCorrecao } function TdmCartasDeCorrecao.LocalizarPorDocumento(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE CAR.CTO_DOCUMENTO = :CTO_DOCUMENTO'); SQL.Add(' AND CAR.CTO_FILIAL = :CTO_FILIAL'); SQL.Add(' AND CAR.CTO_NUMERO = :CTO_NUMERO'); SQL.Add('ORDER BY FIL_CARTA, NRO_CARTA'); Params[0].AsString := FCto_Documento; Params[1].AsString := FCto_Emissora; Params[2].AsFloat := FCto_Numero; Open; Result := not IsEmpty; end; end; procedure TdmCartasDeCorrecao.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE CAR.FIL_CARTA = :FIL_CARTA'); SQL.Add(' AND CAR.NRO_CARTA = :NRO_CARTA'); SQL.Add('ORDER BY CAR.FIL_CARTA, CAR.NRO_CARTA'); Params[0].AsString := FCto_Emissora; Params[1].AsFloat := FNro_Carta; end; end; procedure TdmCartasDeCorrecao.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('ORDER BY CAR.FIL_CARTA, CAR.NRO_CARTA'); end; end; end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit Variables; interface const // Constantes para insertar fechas a la base de datos FECHA_DBMS = 'mm/dd/yyyy'; FECHA_HORA_DBMS = 'mm/dd/yyyy hh:nn:ss.zzz'; // Constantes para formateo de valores FORMATO_FLOTANTE = '#,###,##0.000'; FORMATO_DINERO = '$#,###,##0.000'; FORMATO_ENTERO = '#,##0'; FORMATO_PORCENTAJE = '#,##0.00%'; FORMATO_HORA = 'hh:mm:ss'; // Constantes para campos de estatus en la base de datos ACTIVO = 'A'; INACTIVO = 'I'; CANCELADO = 'C'; // Constantes para valores afirmativos y negativos VALOR_SI = 'S'; VALOR_NO = 'N'; // Teclas TABULADOR = #8; RETROCESO = #9; ENTER = #13; implementation end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIAsn1StreamParser; {$I ..\Include\CryptoLib.inc} interface uses ClpIProxiedInterface, ClpIAsn1EncodableVector; type IAsn1StreamParser = interface(IInterface) ['{D6FF970C-F5B0-4B62-8585-F5F499A18597}'] procedure Set00Check(enabled: Boolean); function ReadIndef(tagValue: Int32): IAsn1Convertible; function ReadImplicit(constructed: Boolean; tag: Int32): IAsn1Convertible; function ReadTaggedObject(constructed: Boolean; tag: Int32): IAsn1Object; function ReadObject(): IAsn1Convertible; function ReadVector(): IAsn1EncodableVector; end; implementation end.
program aerolinea; type _vuelo = record codigo :integer; salida :string; llegada :string; distancia :integer; ocupacion :real; end; _pico = record codigo :integer; acumuladorDistancia :integer; contadorPaises :integer; end; _picos = record primero: _pico; segundo: _pico; end; _actual = record codigo: integer; acumuladorDistancia :integer; pais :string; contadorPaises :integer; end; // Utilidades procedure acumular(var a:integer; val:integer); begin a := a + val; end; procedure incrementar(var c:integer); begin c := c + 1; end; // Datos procedure leerDatos(var vuelo:_vuelo); begin with vuelo do begin write('Ingrese el código del avión: '); readln(codigo); write('Ingrese el país de salida: '); readln(salida); write('Ingrese el país de llegada: '); readln(llegada); write('Ingrese la distancia recorrida en kms: '); readln(distancia); write('Ingrese el porcentaje de ocupación del vuelo: '); readln(ocupacion); end; end; // Cond 1 function mismoAvion(codigo, codigoActual:integer):boolean; begin mismoAvion := codigo = codigoActual; end; procedure reiniciarCond1(var avionActual:_actual; nuevoCodigo:integer); begin with avionActual do begin codigo := nuevoCodigo; acumuladorDistancia := 0; end; end; procedure comprobarCond1(var maximos, minimos :_picos; avionActual:_actual); begin with avionActual do begin if (acumuladorDistancia >= maximos.primero.acumuladorDistancia) then begin maximos.segundo.codigo := maximos.primero.codigo; maximos.segundo.acumuladorDistancia := maximos.primero.acumuladorDistancia; maximos.primero.codigo := codigo; maximos.primero.acumuladorDistancia := acumuladorDistancia; end else if (acumuladorDistancia >= maximos.segundo.acumuladorDistancia) then begin maximos.segundo.codigo := codigo; maximos.segundo.acumuladorDistancia := acumuladorDistancia; end; if (acumuladorDistancia <= minimos.primero.acumuladorDistancia) then begin minimos.segundo.codigo := minimos.primero.codigo; minimos.segundo.acumuladorDistancia := minimos.primero.acumuladorDistancia; minimos.primero.codigo := codigo; minimos.primero.acumuladorDistancia := acumuladorDistancia; end else if (acumuladorDistancia <= minimos.segundo.acumuladorDistancia) then begin minimos.segundo.codigo := codigo; minimos.segundo.acumuladorDistancia := acumuladorDistancia; end; end; end; // Cond 2 function mismoPais(pais, paisActual:string):boolean; begin mismoPais := pais = paisActual; end; procedure reiniciarPais(var avionActual:_actual; nuevoPais:string); begin with avionActual do begin pais := nuevoPais; contadorPaises := 0; end; end; procedure comprobarCond2(var max:_pico; avionActual :_actual); begin if (avionActual.contadorPaises >= max.contadorPaises) then begin max.codigo := avionActual.codigo; max.contadorPaises := avionActual.contadorPaises; end; end; // Cond 3 procedure comprobarCond3(var cantidad:integer; vuelo:_vuelo); begin with vuelo do begin if ((distancia > 5000) and (ocupacion > 60)) then incrementar(cantidad); end; end; // Cond 4 procedure comprobarCond4(var cantidad:integer; vuelo:_vuelo); begin with vuelo do begin if ((distancia < 10000) and ((llegada = 'Australia')or (llegada = 'Nueva Zelanda'))) then incrementar(cantidad); end; end; var vuelo :_vuelo; maximosCond1, minimosCond1 :_picos; maximoCond2 :_pico; avionActual :_actual; cantidadCond3, cantidadCond4 :integer; begin avionActual.codigo := 0; maximosCond1.primero.acumuladorDistancia := 0; maximosCond1.segundo.acumuladorDistancia := 0; minimosCond1.primero.acumuladorDistancia := 0; minimosCond1.segundo.acumuladorDistancia := 0; maximoCond2.contadorPaises := 0; cantidadCond3 := 0; cantidadCond4 := 0; repeat leerDatos(vuelo); if (not mismoAvion(vuelo.codigo, avionActual.codigo)) then begin comprobarCond1(maximosCond1, minimosCond1, avionActual); // Cumple cond1 reiniciarCond1(avionActual, vuelo.codigo); end; if (not mismoPais(vuelo.salida, avionActual.pais)) then begin comprobarCond2(maximoCond2, avionActual); // Cumple cond2 reiniciarPais(avionActual, vuelo.salida); end; acumular(avionActual.acumuladorDistancia, vuelo.distancia); incrementar(avionActual.contadorPaises); comprobarCond3(cantidadCond3, vuelo); // Cumple cond3 comprobarCond4(cantidadCond4, vuelo); // Cumple cond4 until (vuelo.codigo = 44); writeln( 'Los aviones que más km recorrieron son: ', maximosCond1.primero.codigo, ' y ', maximosCond1.segundo.codigo, '.' ); writeln( 'Los aviones que menos km recorrieron son: ', maximosCond1.primero.codigo, ' y ', maximosCond1.segundo.codigo, '.' ); writeln( 'El avión que salió desde más países diferentes es: ', maximoCond2.codigo, '.' ); writeln( 'La cantidad de vuelos de más de 5.000 km que no alcanzaronel 60% de ocupación del avión es: ', cantidadCond3, '.' ); writeln( 'La cantidad de vuelos de menos de 10.000 km que llegarona Australia o a Nueva Zelanda.', cantidadCond4, '.' ); end.
unit Vcl.EditExtends; interface uses Vcl.StdCtrls, Vcl.Controls, System.Classes; type TEdit = class(Vcl.StdCtrls.TEdit) private function GetPlainText: string; procedure SetPlainText(const Value: string); protected procedure KeyUp(var Key: Word; Shift: TShiftState); override; public property PlainText: string read GetPlainText write SetPlainText; end; implementation uses SysUtils; { TEditEx } procedure TEdit.KeyUp(var Key: Word; Shift: TShiftState); var S: string; begin inherited; S := Text; S := S.Replace(',', '').Replace('.', ''); Text := FormatFloat('#.###,##', StrToFloatDef(S, 0)); selStart := Length(Text) + 1; end; function TEdit.GetPlainText: string; var S: string; begin S := Text; Result := S.Replace(',', '').Replace('.', ''); end; procedure TEdit.SetPlainText(const Value: string); var Key: Word; begin Text := Value; KeyUp(Key, []); end; end.
unit Buffer; // Copyright (c) 1996 Jorge Romero Gomez, Merchise // Notes & Tips: // // - If you know the images you are using do not touch the system color entries (eg. were designed by // you with this in mind), call Buffer.ForcePaletteIndentity( true ) to make sure these reserved // entries match the ones in the system. You may also want (if you know it's safe) to turn off // IdentityLock check for speed. // interface uses Classes, Consts, Windows, SysUtils, Graphics, MemUtils, Rects, Gdi, Dibs, BitBlt, Palettes; type ESpeedBitmapError = class( Exception ); type TOnGetPalette = function : CBufferPalette of object; const // ParamsChanged mask pcmPaletteChanged = $00000000; pcmPaletteNotChanged = $00000001; pcmPaletteFromDib = $00000002; pcmPaletteFromSource = $00000004; pcmSizeChanged = $00000008; pcmUseDefaultPalette = pcmSizeChanged; pcmUseCurrentPalette = pcmSizeChanged or pcmPaletteNotChanged; pcmUseDibPalette = pcmSizeChanged or pcmPaletteFromDib; pcmUseSourcePalette = pcmSizeChanged or pcmPaletteFromSource; // TBuffer ========================================================================================= {$TYPEINFO ON} type TBuffer = class( TPersistent ) protected fOnChange : TNotifyEvent; fOnProgress : TProgressEvent; fBufferPalette : TBufferPalette; fClientRect : TRect; fWidth : integer; fHeight : integer; fBitCount : integer; fOriginalHeight : integer; fDibHeader : PDib; fDibPixels : pointer; fRgbEntries : PRgbPalette; fBytesPerPixel : integer; fStorageWidth : integer; fOnGetPalette : TOnGetPalette; fTransparent : boolean; fTransparentMode : TTransparentMode; fTransparentColor : TColor; fTransparentIndx : integer; fIgnorePalette : boolean; fTopDown : boolean; procedure SetBitCount( aBitCount : integer ); procedure SetWidth( aWidth : integer ); procedure SetHeight( aHeight : integer ); procedure SetTopDown( aTopDown : boolean ); procedure SetEmpty( Value : boolean ); function TransparentColorStored : boolean; protected function GetPixelAddr( x, y : integer ) : pbyte; function GetScanLine( Row : integer ) : pointer; function GetPaletteEntry( Indx : integer ) : longint; procedure SetPaletteEntry( Indx : integer; anRgb : longint ); protected fUsesPalette : boolean; fIdentityLock : boolean; fPaletteModified : boolean; procedure SetBufferPalette( Value : TBufferPalette ); virtual; procedure SetUsesPalette( Value : boolean ); virtual; procedure ParamsChanged( Mask : integer ); virtual; procedure ReleaseImage( aReleasePalette : boolean ); virtual; procedure PaletteNeeded; procedure CreateBitmap( aWidth, aHeight : integer; aBitCount : integer; aRgbEntries : pointer ); virtual; abstract; procedure AssignBitmap( Source : TBuffer ); virtual; abstract; procedure FreeContext; virtual; abstract; function GetPixelFormat : TPixelFormat; procedure SetPixelFormat( Value : TPixelFormat ); protected function GetHandleType : TBitmapHandleType; virtual; procedure DefineProperties( Filer : TFiler ); override; procedure ReadData( Stream : TStream ); virtual; procedure WriteData( Stream : TStream ); virtual; function GetEmpty : boolean; virtual; procedure SetMonochrome( Value : boolean ); virtual; function GetMonochrome : boolean; virtual; procedure GetRgbEntries( Indx, Count : integer; RgbQuads : pointer ); virtual; abstract; procedure SetRgbEntries( Indx, Count : integer; RgbQuads : pointer ); virtual; abstract; function GetTransparentColor : TColor; virtual; procedure SetTransparent( Value : boolean ); virtual; procedure SetTransparentColor( Value : TColor ); virtual; procedure SetTransparentMode( Value : TTransparentMode ); virtual; function GetPixels( x, y : integer ) : TColor; virtual; abstract; procedure SetPixels( x, y : integer; Value : TColor ); virtual; abstract; public constructor Create; virtual; constructor CreateSized( aWidth, aHeight : integer; aBitCount : integer ); virtual; destructor Destroy; override; function PaletteClass : CBufferPalette; virtual; procedure SetPaletteEntries( Indx : integer; Colors : array of longint ); procedure GetPaletteEntries( Indx : integer; Count : integer; var Colors ); virtual; procedure ChangePaletteEntries( Indx, Count : integer; var RgbQuads ); virtual; procedure ForcePaletteIdentity( IdentityWanted : boolean; LockEntries : boolean ); virtual; procedure SyncPalette; virtual; procedure RecreatePalette; virtual; procedure FreeImage; virtual; procedure Release; virtual; procedure Changed( Sender : TObject ); virtual; procedure Progress( Sender : TObject; Stage : TProgressStage; PercentDone : byte; RedrawNow : boolean; const R : TRect; const Msg : string ); dynamic; public property DibHeader : PDib read fDibHeader; property RgbEntries : PRgbPalette read fRgbEntries; property ScanLines : pointer read fDibPixels; property ScanLine[Row : integer] : pointer read GetScanLine; property PixelAddr[x, y : integer] : pbyte read GetPixelAddr; property BytesPerPixel : integer read fBytesPerPixel; property PixelFormat : TPixelFormat read GetPixelFormat write SetPixelFormat; property StorageWidth : integer read fStorageWidth; property Rgb[ Indx : integer ] : longint read GetPaletteEntry write SetPaletteEntry; property Pixels[x, y : integer] : TColor read GetPixels write SetPixels; default; property IdentityLock : boolean read fIdentityLock write fIdentityLock; property UsesPalette : boolean read fUsesPalette write SetUsesPalette; property Empty : boolean read GetEmpty write SetEmpty; property ClientRect : TRect read fClientRect; property OriginalHeight : integer read fOriginalHeight; property BufferPalette : TBufferPalette read fBufferPalette write SetBufferPalette; property OnGetPalette : TOnGetPalette read fOnGetPalette write fOnGetPalette; property PaletteModified : boolean read fPaletteModified write fPaletteModified; public function Equals( Value : TBuffer ) : boolean; virtual; procedure NewSize( NewWidth, NewHeight : integer; NewBitCount : integer ); virtual; abstract; procedure LoadFromDib( DibHeader : PDib; DibPixels : pointer ); virtual; abstract; procedure LoadFromStream( Stream : TStream ); virtual; abstract; procedure Halftone; virtual; procedure Flip( fFlipHorizontal : boolean ); virtual; procedure LoadFromFile( const Filename : string ); virtual; procedure LoadFromResourceName( Instance : THandle; const ResourceName : string ); procedure LoadFromResourceID( Instance : THandle; ResourceId : integer ); procedure SaveToStream( Stream : TStream ); virtual; procedure SaveToFile( const Filename : string ); virtual; // Only accepts the CF_DIB clipboard format. Win32 takes cares of translating it when CF_BITMAP is requested procedure SaveToClipboardFormat( var Format : word; var Data : THandle; var aPalette : HPALETTE ); virtual; procedure LoadFromClipboardFormat( aFormat : word; aData : THandle; aPalette : HPALETTE); virtual; procedure Flush; virtual; abstract; published property IgnorePalette : boolean read fIgnorePalette write fIgnorePalette default false; property TopDown : boolean read fTopDown write SetTopDown stored false; property Height : integer read fHeight write SetHeight stored false; property Width : integer read fWidth write SetWidth stored false; property BitCount : integer read fBitCount write SetBitCount stored false; property Monochrome : boolean read GetMonochrome write SetMonochrome stored false; property OnChange : TNotifyEvent read fOnChange write fOnChange; property OnProgress : TProgressEvent read fOnProgress write fOnProgress; property TransparentIndx : integer read fTransparentIndx stored false; property TransparentColor : TColor read GetTransparentColor write SetTransparentColor stored TransparentColorStored; property TransparentMode : TTransparentMode read fTransparentMode write SetTransparentMode default tmAuto; property Transparent : boolean read fTransparent write SetTransparent; end; {$TYPEINFO OFF} // Helper Functions ====================================================================================== function BitmapCreateRegion( Source : TBuffer; ColorIndx : integer ): HRGN; // Use with SetWindowRgn // Returns an 8-bit halftoned bitmap function BitmapHalftone( Source : TBuffer ) : TBuffer; procedure BitmapFakeInvert( Source : TBuffer ); procedure BitmapSnapshotPalette( dc : HDC; Dest : TBuffer ); // Copy the palette from a given DC procedure BitmapSetPaletteSize( Dest : TBuffer; aNewSize : integer ); function BitmapRotate( Source : TBuffer; Angle : integer ) : TBuffer; function BitmapFlip( Source : TBuffer; FlipHorizontal : boolean ) : TBuffer; function BitmapCopy( Source : TBuffer; Width, Height : integer; BitCount : integer; ForceTopDown : boolean ) : TBuffer; function BitmapCopyPiece( Source : TBuffer; const Rect : TRect; Width, Height : integer; BitCount : integer; ForceTopDown : boolean; UseColors : boolean ) : TBuffer; function BitmapColor( Source : TBuffer; Color : TColor ) : dword; // Convert a TColor in a ColorIndx implementation uses StreamUtils; // TBuffer =========================================================================================== constructor TBuffer.Create; begin inherited; fIgnorePalette := ScreenDeviceBitsPerPixel > 8; fBitCount := 8; fTransparentColor := clDefault; end; destructor TBuffer.Destroy; begin Release; inherited; end; procedure TBuffer.Release; begin ReleaseImage( true ); end; constructor TBuffer.CreateSized( aWidth, aHeight : integer; aBitCount : integer ); begin Create; CreateBitmap( aWidth, aHeight, aBitCount, nil ); end; procedure TBuffer.SaveToClipboardFormat( var Format : word; var Data : THandle; var aPalette : HPALETTE ); begin Format := CF_DIB; Data := DibClipboardFormat( DibHeader, ScanLines ); aPalette := 0; end; procedure TBuffer.LoadFromClipboardFormat( aFormat : word; aData : THandle; aPalette : HPALETTE ); var NewDib : PDib; begin if ( aFormat <> CF_DIB ) or ( aData = 0 ) then raise EInvalidGraphic.Create( SUnknownClipboardFormat ); NewDib := GlobalLock( aData ); try LoadFromDib( NewDib, nil ); finally GlobalUnlock( aData ); end; end; procedure TBuffer.Changed( Sender : TObject ); begin if Assigned( fOnChange ) then fOnChange( Self ); end; procedure TBuffer.Progress( Sender : TObject; Stage : TProgressStage; PercentDone : byte; RedrawNow : Boolean; const R : TRect; const Msg : string ); begin if Assigned( fOnProgress ) then fOnProgress( Sender, Stage, PercentDone, RedrawNow, R, Msg ); end; function TBuffer.GetPixelFormat : TPixelFormat; begin Result := pfCustom; case BitCount of 1 : Result := pf1Bit; 4 : Result := pf4Bit; 8 : Result := pf8Bit; 16 : case DibHeader.biCompression of BI_RGB : Result := pf15Bit; BI_BITFIELDS: case pdword( @RgbEntries[1] )^ of $3E0 : Result := pf16Bit; $7E0 : Result := pf16Bit; end; end; 24 : Result := pf24Bit; 32: if DibHeader.biCompression = BI_RGB then Result := pf32Bit; end; end; procedure TBuffer.SetPixelFormat( Value : TPixelFormat ); begin // Unfinished!! end; procedure TBuffer.ReleaseImage( aReleasePalette : boolean ); begin if Assigned( fDibHeader ) then begin DibFree( fDibHeader ); fDibHeader := nil; end; FreeContext; if aReleasePalette then UsesPalette := false; end; procedure TBuffer.FreeImage; begin // Since we must keep anyway the DIBSECTION info & pixels, do nothing. end; procedure TBuffer.ReadData( Stream : TStream ); begin LoadFromStream( Stream ); end; procedure TBuffer.WriteData( Stream : TStream ); begin SaveToStream( Stream ); end; function TBuffer.Equals( Value : TBuffer ) : boolean; var MyImage, ValueImage : TMemoryStream; begin if Value = nil then Result := false else if Empty or Value.Empty then Result := Empty and Value.Empty else begin Result := ClassType = Value.ClassType; if Result then begin MyImage := TMemoryStream.Create; try WriteData( MyImage ); ValueImage := TMemoryStream.Create; try Value.WriteData( ValueImage ); Result := ( MyImage.Size = ValueImage.Size ) and CompareMem( MyImage.Memory, ValueImage.Memory, MyImage.Size ); finally ValueImage.Free; end; finally MyImage.Free; end; end; end; end; procedure TBuffer.DefineProperties( Filer : TFiler ); function DoWrite : boolean; begin if Filer.Ancestor <> nil then Result := not (Filer.Ancestor is TBuffer) or not Equals( TBuffer( Filer.Ancestor ) ) else Result := not Empty; end; begin Filer.DefineBinaryProperty( 'Data', ReadData, WriteData, DoWrite ); end; procedure TBuffer.ParamsChanged( Mask : integer ); begin if Assigned( fDibHeader ) then begin fUsesPalette := DibUsesPalette( fDibHeader ); fRgbEntries := DibColors( fDibHeader ); with fDibHeader^ do begin if Mask and pcmSizeChanged <> 0 then begin fTopDown := (biHeight < 0); fBytesPerPixel := biBitCount div 8; fStorageWidth := DibStorageWidth( biWidth, biBitCount ); fWidth := biWidth; fHeight := abs(biHeight); fBitCount := biBitCount; fOriginalHeight := biHeight; with fClientRect do begin Left := 0; Top := 0; Right := fWidth; Bottom := fHeight; end; end; if Mask and (pcmPaletteNotChanged or pcmPaletteFromSource) = 0 then begin FreeObject( fBufferPalette ); if UsesPalette then begin PaletteModified := true; if Mask and pcmPaletteFromDib <> 0 then begin fBufferPalette := PaletteClass.CreateFromRgbPalette( fRgbEntries^, biClrUsed ); SetRgbEntries( 0, biClrUsed, fRgbEntries ); end; end; end; if not Assigned( fBufferPalette ) then fBufferPalette := PaletteClass.CreateFromRgbPalette( fRgbEntries^, biClrUsed ); end; end; end; procedure TBuffer.RecreatePalette; begin ParamsChanged( pcmPaletteChanged ); end; procedure TBuffer.ForcePaletteIdentity( IdentityWanted : boolean; LockEntries : boolean ); begin if IdentityWanted and (AvailableColors < 256) then begin fIdentityLock := true; ChangePaletteEntries( 0, DibHeader.biClrUsed, fRgbEntries^ ); fIdentityLock := LockEntries; end else fIdentityLock := false; end; procedure TBuffer.ChangePaletteEntries( Indx, Count : integer; var RgbQuads ); var Entries : TRgbPalette absolute RgbQuads; begin if UsesPalette then begin if IdentityLock then begin if Indx < FirstAvailColor then GetRgbSysPalette( 0, FirstAvailColor, Entries ); if Indx + Count > LastAvailColor then GetRgbSysPalette( LastAvailColor + 1, FirstAvailColor, Entries ); end; if @Entries <> fRgbEntries then Move( Entries[Indx], fRgbEntries[Indx], Count * sizeof(TRGBQuad) ); BufferPalette.AssignRgbEntries( Indx, Count, Entries ); SetRgbEntries( Indx, Count, @Entries ); PaletteModified := true; end; end; procedure TBuffer.SyncPalette; begin if UsesPalette then with fDibHeader^ do begin GetRgbPalette( BufferPalette.Handle, 0, biClrUsed, fRgbEntries^ ); SetRgbEntries( 0, biClrUsed, fRgbEntries ); PaletteModified := true; end; end; procedure TBuffer.SetTransparentMode( Value : TTransparentMode ); begin if Value <> TransparentMode then if Value = tmAuto then SetTransparentColor( clDefault ) else SetTransparentColor( TransparentColor ); end; procedure TBuffer.PaletteNeeded; begin if UsesPalette then BufferPalette.HandleNeeded; end; function TBuffer.GetMonochrome : boolean; begin Result := ( BitCount = 1 ); end; procedure TBuffer.SetMonochrome( Value : boolean ); begin if (Value <> Monochrome) then if Value then BitCount := 1 // Convert color bitmap to monochrome else BitCount := 4; // Convert monochrome bitmap to a 16 color end; procedure TBuffer.Flip( fFlipHorizontal : boolean ); begin if fFlipHorizontal then DibFlipHorizontal( DibHeader, ScanLines, Width, Height ) else FlipVertical( ScanLines, StorageWidth, Height, StorageWidth ); end; procedure TBuffer.Halftone; var TmpBuffer : TBuffer; begin TmpBuffer := TBuffer( ClassType.Create ); try TmpBuffer.CreateBitmap( Width, Height, 8, nil ); DibCopyHalftoned( DibHeader, ScanLines, TmpBuffer.DibHeader, TmpBuffer.ScanLines ); finally TmpBuffer.Free; end; end; procedure TBuffer.SaveToStream( Stream : TStream ); begin DibSaveToStream( Stream, DibHeader, ScanLines ); end; procedure TBuffer.LoadFromFile( const Filename : string ); begin StreamObject( TFileStream.Create( Filename, fmOpenRead or fmShareDenyWrite ), LoadFromStream ); end; procedure TBuffer.SaveToFile( const Filename : string ); var Stream : TStream; begin Stream := TFileStream.Create( Filename, fmCreate ); DibWriteFileHeader( DibHeader, Stream ); StreamObject( Stream, SaveToStream ); end; procedure TBuffer.LoadFromResourceName( Instance : THandle; const ResourceName : string ); begin StreamObject( TResourceStream.Create( Instance, ResourceName, RT_BITMAP ), LoadFromStream ); end; procedure TBuffer.LoadFromResourceID( Instance : THandle; ResourceId : Integer ); begin StreamObject( TResourceStream.CreateFromID( Instance, ResourceId, RT_BITMAP ), LoadFromStream ); end; procedure TBuffer.SetBitCount( aBitCount : integer ); begin if BitCount <> aBitCount then NewSize( Width, OriginalHeight, aBitCount ); end; procedure TBuffer.SetWidth( aWidth : integer ); begin if Width <> aWidth then NewSize( aWidth, OriginalHeight, BitCount ); end; procedure TBuffer.SetHeight( aHeight : integer ); begin if OriginalHeight <> aHeight then NewSize( Width, aHeight, BitCount ); end; procedure TBuffer.SetTopDown( aTopDown : boolean ); begin if aTopDown <> TopDown then if aTopDown then NewSize( Width, -Height, BitCount ) else NewSize( Width, Height, BitCount ); end; procedure TBuffer.SetUsesPalette( Value : boolean ); begin if Value <> UsesPalette then begin if UsesPalette then FreeObject( fBufferPalette ) else ParamsChanged( pcmPaletteChanged ); fUsesPalette := Value; end; end; procedure TBuffer.SetBufferPalette( Value : TBufferPalette ); begin if (Value <> BufferPalette) then begin if Assigned( Value ) and (not Empty) then with Value do begin if BufferPalette = nil then fBufferPalette := TBufferPalette( ClassType ).Create; BufferPalette.Assign( Value ); SyncPalette; end else begin fUsesPalette := false; FreeObject( fBufferPalette ); end; Changed( Self ); end; end; function TBuffer.GetPixelAddr( x, y : integer ) : pbyte; begin if TopDown then Result := pointer( pchar(fDibPixels) + y * fStorageWidth + x * BytesPerPixel ) else Result := pointer( pchar(fDibPixels) + ( pred(fHeight) - y ) * fStorageWidth + x * BytesPerPixel ); end; function TBuffer.GetScanLine( Row : integer ) : pointer; begin if TopDown then Result := pchar(fDibPixels) + Row * fStorageWidth else Result := pchar(fDibPixels) + ( pred(fHeight) - Row ) * fStorageWidth; end; function TBuffer.GetPaletteEntry( Indx : integer ) : longint; begin Result := longint( fRgbEntries[Indx] ); end; procedure TBuffer.GetPaletteEntries( Indx : integer; Count : integer; var Colors ); begin Move( fRgbEntries[Indx], Colors, Count * sizeof(TRGBQuad) ); end; procedure TBuffer.SetPaletteEntry( Indx : integer; anRgb : longint ); begin ChangePaletteEntries( Indx, 1, anRgb ); end; procedure TBuffer.SetPaletteEntries( Indx : integer; Colors : array of longint ); begin ChangePaletteEntries( Indx, High(Colors) - Low(Colors) + 1, Colors ); end; procedure TBuffer.SetEmpty( Value : boolean ); begin if Value and (not Empty) then begin ReleaseImage( true ); Changed( Self ); end; end; function TBuffer.GetEmpty : boolean; begin Result := not Assigned( DibHeader ); end; function TBuffer.PaletteClass : CBufferPalette; begin if Assigned( fOnGetPalette ) then Result := fOnGetPalette else Result := TBufferPalette; end; function TBuffer.GetHandleType : TBitmapHandleType; begin Result := bmDIB; end; function TBuffer.TransparentColorStored : boolean; begin Result := TransparentMode = tmFixed; end; procedure TBuffer.SetTransparent( Value : boolean ); begin if Value <> Transparent then begin fTransparent := Value; Changed( Self ); end; end; function TBuffer.GetTransparentColor : TColor; begin if fTransparentColor = clDefault then if Monochrome then Result := clWhite else Result := Pixels[0, Height - 1] else Result := ColorToRgb( fTransparentColor ); end; procedure TBuffer.SetTransparentColor( Value : TColor ); begin if Value <> fTransparentColor then begin fTransparentColor := Value; if Value = clDefault then fTransparentMode := tmAuto else fTransparentMode := tmFixed; fTransparentIndx := BitmapColor( Self, Value ); Changed( Self ); end; end; // Helper Functions ======================================================================== function BitmapCreateRegion( Source : TBuffer; ColorIndx : integer ): HRGN; var Pix : pchar; y, x : integer; OldX : integer; TempRgn : HRGN; bColorIndx : byte absolute ColorIndx; wColorIndx : word absolute ColorIndx; begin with Source do begin Result := CreateRectRgn( 0, 0, 0, 0 ); y := 0; while y < Height do begin x := 0; Pix := ScanLine[ y ]; while x < Width do begin // Skip over transparent space case BitCount of 1 : while ( x < Width ) and ( bColorIndx = byte( GetPixelMono( Pix, x ) ) ) do inc( x ); 4 : while ( x < Width ) and ( bColorIndx = GetPixel4( Pix, x ) ) do inc( x ); 8 : while ( x < Width ) and ( bColorIndx = byte( Pix[x] ) ) do inc( x ); 16 : while ( x < Width ) and ( wColorIndx = pword( Pix + 2 * x )^ ) do inc( x ); 24 : while ( x < Width ) and ( ColorIndx = pdword( Pix + 3 * x )^ and mskColorKey ) do inc( x ); 32 : while ( x < Width ) and ( ColorIndx = pdword( Pix + 4 * x )^ ) do inc( x ); end; OldX := x; // Find the opaque area size case BitCount of 1 : while ( x < Width ) and ( bColorIndx <> byte( GetPixelMono( Pix, x ) ) ) do inc( x ); 4 : while ( x < Width ) and ( bColorIndx <> GetPixel4( Pix, x ) ) do inc( x ); 8 : while ( x < Width ) and ( bColorIndx <> byte( Pix[x] ) ) do inc( x ); 16 : while ( x < Width ) and ( wColorIndx <> pword( Pix + 2 * x )^ ) do inc( x ); 24 : while ( x < Width ) and ( ColorIndx <> pdword( Pix + 3 * x )^ and mskColorKey ) do inc( x ); 32 : while ( x < Width ) and ( ColorIndx <> pdword( Pix + 4 * x )^ ) do inc( x ); end; // Combine the new region TempRgn := CreateRectRgn( OldX, y, x, y + 1 ); CombineRgn( Result, Result, TempRgn, RGN_OR ); DeleteObject( TempRgn ); end; inc( y ); end; end; end; function BitmapHalftone( Source : TBuffer ) : TBuffer; begin try with Source do begin Result := TBuffer( ClassType ).Create; Result.CreateBitmap( Width, Height, 8, nil ); DibCopyHalftoned( DibHeader, ScanLines, Result.DibHeader, Result.ScanLines ); end; except FreeObject( Result ); end; end; function BitmapRotate( Source : TBuffer; Angle : integer ) : TBuffer; begin assert( ( Angle div 90 ) mod 4 in [1, 2, 3], 'Bad angle in Buffer.BitmapRotate!!' ); try with Source do begin Result := TBuffer( ClassType ).Create; if ( Angle div 90 ) mod 4 in [1, 3] then Result.CreateBitmap( Height, Width * (OriginalHeight div Height), BitCount, RgbEntries ) else Result.CreateBitmap( Width, OriginalHeight, BitCount, RgbEntries ); DibCopyRotated( DibHeader, ScanLines, Result.ScanLines, Angle ); end; except FreeObject( Result ); end; end; function BitmapFlip( Source : TBuffer; FlipHorizontal : boolean ) : TBuffer; begin try with Source do begin Result := TBuffer( ClassType ).Create; Result.CreateBitmap( Width, OriginalHeight, BitCount, RgbEntries ); if FlipHorizontal then DibCopyFlippedHor( DibHeader, ScanLines, Result.ScanLines ) else DibCopyFlippedVert( DibHeader, ScanLines, Result.ScanLines ); end; except FreeObject( Result ); end; end; function BitmapCopy( Source : TBuffer; Width, Height : integer; BitCount : integer; ForceTopDown : boolean ) : TBuffer; begin Result := BitmapCopyPiece( Source, Source.ClientRect, Width, Height, BitCount, ForceTopDown, true ); end; function BitmapCopyPiece( Source : TBuffer; const Rect : TRect; Width, Height : integer; BitCount : integer; ForceTopDown : boolean; UseColors : boolean ) : TBuffer; begin assert( Assigned( Source ), 'NULL Source in Buffer.BitmapCopyPiece!!' ); try if ForceTopDown or Source.TopDown then Result := TBuffer( Source.ClassType ).CreateSized( Width, -Height, BitCount ) else Result := TBuffer( Source.ClassType ).CreateSized( Width, Height, BitCount ); //!! Result.StretchSnapshotDC( Source.Canvas.Handle, Rect, UseColors ); except FreeObject( Result ); end; end; function BitmapColor( Source : TBuffer; Color : TColor ) : dword; var Data : PGetRgbData; RgbColor : TColorRec absolute Color; begin Color := Color and mskColorKey; Result := 0; with Source do if BitCount <= 8 then Result := GetNearestEntry( RgbEntries^, 255, Color ) else if BitCount = 24 then Result := Color else begin DibGetRgbBegin( DibHeader, pointer( Data ) ); with RgbColor, Data^ do case BitCount of 16 : Result := ( (crRed shr rLeft) shl rRight ) or ( (crGreen shr gLeft) shl gRight ) or ( (crBlue shr bLeft) shl bRight ); 32 : Result := (crRed shl rRight) or (crGreen shl gRight) or (crBlue shl bRight); end; DibGetRgbFree( Data ); end; end; procedure BitmapFakeInvert( Source : TBuffer ); begin with Source do begin DibHeader.biHeight := -DibHeader.biHeight; fTopDown := not fTopDown; end; end; procedure BitmapSnapshotPalette( dc : HDC; Dest : TBuffer ); var hpal : HPALETTE; begin assert( Dest.UsesPalette, 'Modifying non-existant palette in Buffer.BitmapSnapshotPalette' ); hpal := GetPaletteHandle( dc ); try with Dest, DibHeader^ do begin BufferPalette.Handle := hpal; GetRgbPalette( hpal, 0, biClrUsed, RgbEntries^ ); ChangePaletteEntries( 0, biClrUsed, RgbEntries^ ); end; finally DeleteObject( hpal ); end; end; procedure BitmapSetPaletteSize( Dest : TBuffer; aNewSize : integer ); begin with Dest do begin ReallocMem( fDibHeader, DibHeader.biSize + aNewSize * sizeof( TRGBQuad ) ); fRgbEntries := DibColors( DibHeader ); DibHeader.biClrUsed := aNewSize; end; end; end.
{***************************************************************************\ * * Module Name: PMTYPES.H * * OS/2 Presentation Manager Datatypes include file * * This is conditionally included from PMWIN.H * * Copyright (c) International Business Machines Corporation 1981, 1988-1990 * *****************************************************************************} {| Version: 1.00 | Original translation: Peter Sawatzki ps | Contributing: | Peter Sawatzki ps | | change history: | Date: Ver: Author: | 11/11/93 1.00 ps original translation by ps } Unit PmTypes; Interface Const DTYP_USER = 16384; DTYP_CTL_ARRAY = 1; DTYP_CTL_PARRAY = -1; DTYP_CTL_OFFSET = 2; DTYP_CTL_LENGTH = 3; {********************************************************************} { Ordinary datatypes } {********************************************************************} DTYP_ACCEL = 28; DTYP_ACCELTABLE = 29; DTYP_ARCPARAMS = 38; DTYP_AREABUNDLE = 139; DTYP_ATOM = 90; DTYP_BITMAPINFO = 60; DTYP_BITMAPINFOHEADER = 61; DTYP_BIT16 = 20; DTYP_BIT32 = 21; DTYP_BIT8 = 19; DTYP_BOOL = 18; DTYP_BTNCDATA = 35; DTYP_BYTE = 13; DTYP_CATCHBUF = 141; DTYP_CHAR = 15; DTYP_CHARBUNDLE = 135; DTYP_CLASSINFO = 95; DTYP_COUNT2 = 93; DTYP_COUNT2B = 70; DTYP_COUNT2CH = 82; DTYP_COUNT4 = 152; DTYP_COUNT4B = 42; DTYP_CPID = 57; DTYP_CREATESTRUCT = 98; DTYP_CURSORINFO = 34; DTYP_DEVOPENSTRUC = 124; DTYP_DLGTEMPLATE = 96; DTYP_DLGTITEM = 97; DTYP_ENTRYFDATA = 127; DTYP_ERRORID = 45; DTYP_FATTRS = 75; DTYP_FFDESCS = 142; DTYP_FIXED = 99; DTYP_FONTMETRICS = 74; DTYP_FRAMECDATA = 144; DTYP_GRADIENTL = 48; DTYP_HAB = 10; DTYP_HACCEL = 30; DTYP_HAPP = 146; DTYP_HATOMTBL = 91; DTYP_HBITMAP = 62; DTYP_HCINFO = 46; DTYP_HDC = 132; DTYP_HENUM = 117; DTYP_HHEAP = 109; DTYP_HINI = 53; DTYP_HLIB = 147; DTYP_HMF = 85; DTYP_HMQ = 86; DTYP_HPOINTER = 106; DTYP_HPROGRAM = 131; DTYP_HPS = 12; DTYP_HRGN = 116; DTYP_HSEM = 140; DTYP_HSPL = 32; DTYP_HSWITCH = 66; DTYP_HVPS = 58; DTYP_HWND = 11; DTYP_IDENTITY = 133; DTYP_IDENTITY4 = 169; DTYP_IMAGEBUNDLE = 136; DTYP_INDEX2 = 81; DTYP_IPT = 155; DTYP_KERNINGPAIRS = 118; DTYP_LENGTH2 = 68; DTYP_LENGTH4 = 69; DTYP_LINEBUNDLE = 137; DTYP_LONG = 25; DTYP_MARKERBUNDLE = 138; DTYP_MATRIXLF = 113; DTYP_MLECTLDATA = 161; DTYP_MLEMARGSTRUCT = 157; DTYP_MLEOVERFLOW = 158; DTYP_OFFSET2B = 112; DTYP_OWNERITEM = 154; DTYP_PID = 92; DTYP_PIX = 156; DTYP_POINTERINFO = 105; DTYP_POINTL = 77; DTYP_PROGCATEGORY = 129; DTYP_PROGRAMENTRY = 128; DTYP_PROGTYPE = 130; DTYP_PROPERTY2 = 88; DTYP_PROPERTY4 = 89; DTYP_QMSG = 87; DTYP_RECTL = 121; DTYP_RESID = 125; DTYP_RGB = 111; DTYP_RGNRECT = 115; DTYP_SBCDATA = 159; DTYP_SEGOFF = 126; DTYP_SHORT = 23; DTYP_SIZEF = 101; DTYP_SIZEL = 102; DTYP_STRL = 17; DTYP_STR16 = 40; DTYP_STR32 = 37; DTYP_STR64 = 47; DTYP_STR8 = 33; DTYP_SWBLOCK = 63; DTYP_SWCNTRL = 64; DTYP_SWENTRY = 65; DTYP_SWP = 31; DTYP_TID = 104; DTYP_TIME = 107; DTYP_TRACKINFO = 73; DTYP_UCHAR = 22; DTYP_ULONG = 26; DTYP_USERBUTTON = 36; DTYP_USHORT = 24; DTYP_WIDTH4 = 108; DTYP_WNDPARAMS = 83; DTYP_WNDPROC = 84; DTYP_WPOINT = 59; DTYP_WRECT = 55; DTYP_XYWINSIZE = 52; {********************************************************************} { Pointer datatypes } {********************************************************************} DTYP_PACCEL = -28; DTYP_PACCELTABLE = -29; DTYP_PARCPARAMS = -38; DTYP_PAREABUNDLE = -139; DTYP_PATOM = -90; DTYP_PBITMAPINFO = -60; DTYP_PBITMAPINFOHEADER= -61; DTYP_PBIT16 = -20; DTYP_PBIT32 = -21; DTYP_PBIT8 = -19; DTYP_PBOOL = -18; DTYP_PBTNCDATA = -35; DTYP_PBYTE = -13; DTYP_PCATCHBUF = -141; DTYP_PCHAR = -15; DTYP_PCHARBUNDLE = -135; DTYP_PCLASSINFO = -95; DTYP_PCOUNT2 = -93; DTYP_PCOUNT2B = -70; DTYP_PCOUNT2CH = -82; DTYP_PCOUNT4 = -152; DTYP_PCOUNT4B = -42; DTYP_PCPID = -57; DTYP_PCREATESTRUCT = -98; DTYP_PCURSORINFO = -34; DTYP_PDEVOPENSTRUC = -124; DTYP_PDLGTEMPLATE = -96; DTYP_PDLGTITEM = -97; DTYP_PENTRYFDATA = -127; DTYP_PERRORID = -45; DTYP_PFATTRS = -75; DTYP_PFFDESCS = -142; DTYP_PFIXED = -99; DTYP_PFONTMETRICS = -74; DTYP_PFRAMECDATA = -144; DTYP_PGRADIENTL = -48; DTYP_PHAB = -10; DTYP_PHACCEL = -30; DTYP_PHAPP = -146; DTYP_PHATOMTBL = -91; DTYP_PHBITMAP = -62; DTYP_PHCINFO = -46; DTYP_PHDC = -132; DTYP_PHENUM = -117; DTYP_PHHEAP = -109; DTYP_PHINI = -53; DTYP_PHLIB = -147; DTYP_PHMF = -85; DTYP_PHMQ = -86; DTYP_PHPOINTER = -106; DTYP_PHPROGRAM = -131; DTYP_PHPS = -12; DTYP_PHRGN = -116; DTYP_PHSEM = -140; DTYP_PHSPL = -32; DTYP_PHSWITCH = -66; DTYP_PHVPS = -58; DTYP_PHWND = -11; DTYP_PIDENTITY = -133; DTYP_PIDENTITY4 = -169; DTYP_PIMAGEBUNDLE = -136; DTYP_PINDEX2 = -81; DTYP_PIPT = -155; DTYP_PKERNINGPAIRS = -118; DTYP_PLENGTH2 = -68; DTYP_PLENGTH4 = -69; DTYP_PLINEBUNDLE = -137; DTYP_PLONG = -25; DTYP_PMARKERBUNDLE = -138; DTYP_PMATRIXLF = -113; DTYP_PMLECTLDATA = -161; DTYP_PMLEMARGSTRUCT = -157; DTYP_PMLEOVERFLOW = -158; DTYP_POFFSET2B = -112; DTYP_POWNERITEM = -154; DTYP_PPID = -92; DTYP_PPIX = -156; DTYP_PPOINTERINFO = -105; DTYP_PPOINTL = -77; DTYP_PPROGCATEGORY = -129; DTYP_PPROGRAMENTRY = -128; DTYP_PPROGTYPE = -130; DTYP_PPROPERTY2 = -88; DTYP_PPROPERTY4 = -89; DTYP_PQMSG = -87; DTYP_PRECTL = -121; DTYP_PRESID = -125; DTYP_PRGB = -111; DTYP_PRGNRECT = -115; DTYP_PSBCDATA = -159; DTYP_PSEGOFF = -126; DTYP_PSHORT = -23; DTYP_PSIZEF = -101; DTYP_PSIZEL = -102; DTYP_PSTRL = -17; DTYP_PSTR16 = -40; DTYP_PSTR32 = -37; DTYP_PSTR64 = -47; DTYP_PSTR8 = -33; DTYP_PSWBLOCK = -63; DTYP_PSWCNTRL = -64; DTYP_PSWENTRY = -65; DTYP_PSWP = -31; DTYP_PTID = -104; DTYP_PTIME = -107; DTYP_PTRACKINFO = -73; DTYP_PUCHAR = -22; DTYP_PULONG = -26; DTYP_PUSERBUTTON = -36; DTYP_PUSHORT = -24; DTYP_PWIDTH4 = -108; DTYP_PWNDPARAMS = -83; DTYP_PWNDPROC = -84; DTYP_PWPOINT = -59; DTYP_PWRECT = -55; DTYP_PXYWINSIZE = -52; Implementation End.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit OraIndex; interface uses Classes, SysUtils, Ora, OraStorage, DB, OraPartitions, DBQuery, Forms, Dialogs, VirtualTable; type TTableIndex = class(TObject) private FIndexName, FIndexSchema, FTableSchema, FTableName : string; FIndexType: TIndexType; FIndexClause: TIndexClause; //0-TableIndex, 1-ClusterIndex FPartitionClause: TPartitionClause; //0-NonPartition, 1-Global FOnline: boolean; FParalel: boolean; FParalelDegree: integer; FParalelInstances: integer; FComputeStatistic: boolean; FLoggingType: TLoggingType; FBitmap, FReverse, FNoSorted, FFunctions: Boolean; FFunctionCnt: string; FCompress: Boolean; //True-compres, False-non compress FCompressColumns: integer; FPhsicalAttributes : TPhsicalAttributes; FBitmapIndexFromClause, FBitmapIndexWhereClause: string; FIndexPartitionLists: TIndexPartitionList; FIndexPartitionType: TIndexPartitionType; FIndexSubpartitionType: TIndexPartitionType; FIndexHashPartitionType: string; FIndexColumnLists: TColumnList; FOraSession: TOraSession; FDSIndex: TVirtualTable; FDSIndexColumns: TVirtualTable; FDSIndexPartitions: TVirtualTable; function GetTableIndexPartitions: string; function GetTableIndexExpressions(IndexOwner, IndexName, TableOwner, TableName, ColumnPosition: string): string; function GetIndexStatus: string; public property IndexName: string read FIndexName write FIndexName; property IndexSchema: string read FIndexSchema write FIndexSchema; property TableSchema: string read FTableSchema write FTableSchema; property TableName: string read FTableName write FTableName; property IndexType: TIndexType read FIndexType write FIndexType; property IndexClause: TIndexClause read FIndexClause write FIndexClause; property PartitionClause: TPartitionClause read FPartitionClause write FPartitionClause; property Online: boolean read FOnline write FOnline; property Paralel: boolean read FParalel write FParalel; property ParalelDegree: integer read FParalelDegree write FParalelDegree; property ParalelInstances: integer read FParalelInstances write FParalelInstances; property ComputeStatistic: boolean read FComputeStatistic write FComputeStatistic; property LoggingType: TLoggingType read FLoggingType write FLoggingType; property Bitmap: boolean read FBitmap write FBitmap; property Reverse: boolean read FReverse write FReverse; property NoSorted: boolean read FNoSorted write FNoSorted; property Functions: boolean read FFunctions write FFunctions; property FunctionCnt: string read FFunctionCnt write FFunctionCnt; property Compress: boolean read FCompress write FCompress; property CompressColumns: integer read FCompressColumns write FCompressColumns; property PhsicalAttributes : TPhsicalAttributes read FPhsicalAttributes write FPhsicalAttributes; property BitmapIndexFromClause: string read FBitmapIndexFromClause write FBitmapIndexFromClause; property BitmapIndexWhereClause: string read FBitmapIndexWhereClause write FBitmapIndexWhereClause; property IndexPartitionLists : TIndexPartitionList read FIndexPartitionLists write FIndexPartitionLists; property IndexPartitionType: TIndexPartitionType read FIndexPartitionType write FIndexPartitionType; property IndexSubpartitionType: TIndexPartitionType read FIndexSubpartitionType write FIndexSubpartitionType; property IndexHashPartitionType: string read FIndexHashPartitionType write FIndexHashPartitionType; property IndexColumnLists : TColumnList read FIndexColumnLists write FIndexColumnLists; property DSIndex: TVirtualTable read FDSIndex; property DSIndexColumns: TVirtualTable read FDSIndexColumns; property DSIndexPartitions: TVirtualTable read FDSIndexPartitions; property IndexStatus: String read GetIndexStatus; property OraSession: TOraSession read FOraSession write FOraSession; constructor Create; destructor destroy; override; procedure SetDDL; function GetDDL: string; function GetTableIndexDetail: string; function GetAlterDDL(NewValue: TTableIndex): string; function CreateIndex(IndexScript: string) : boolean; function DropIndex: boolean; function RebuildIndex: boolean; function CoalesceIndex: boolean; function AnalyzeTable(AnalyzeFunction: TAnalyzeFunction; Sample: integer; SampleType: integer): boolean; function AlterIndex(IndexScript: string) : boolean; end; TIndexList = class(TObject) private FInnerList: TList; FOraSession: TOraSession; FTableName: string; FOwner: string; function GetItem(Index: Integer): TTableIndex; procedure SetItem(Index: Integer; TableIndex: TTableIndex); function GetCount: Integer; function GetTableIndexes: string; public property OraSession: TOraSession read FOraSession write FOraSession; property TableName: string read FTableName write FTableName; property Owner: string read FOwner write FOwner; constructor Create; destructor Destroy; override; procedure Add(TableIndex: TTableIndex); procedure Delete(Index: Integer); property Count: Integer read GetCount; property Items[Index: Integer]: TTableIndex read GetItem write SetItem; procedure SetDDL; function GetDDL: string; end; function GetTableIndexs: string; function GetIndexes(OwnerName: string): string; implementation uses Util, frmSchemaBrowser, OraScripts, Languages; resourcestring strIndexAnalyzed = 'Index %s has been analyzed.'; strIndexCoalesced = 'Index % has been Coalesced.'; strIndexRebuilt = 'Index %s has been rebuilt.'; strIndexDropped = 'Index %s has been dropped.'; strIndexAltered = 'Index %s has been altered.'; strIndexCreated = 'Index %s has been created.'; //schema browser išin function GetIndexes(OwnerName: string): string; begin result := 'Select * FROM ALL_INDEXES ' +' WHERE OWNER = '+Str(OwnerName) +' ORDER BY INDEX_NAME '; end; function GetTableIndexs: string; begin result := 'Select C.*, ' +'(Select uniqueness ' +' from ALL_INDEXES I ' +' WHERE I.INDEX_NAME = C.INDEX_NAME ' +' and I.OWNER = C.INDEX_OWNER ) ISUNIQE ' +'from ALL_IND_COLUMNS C ' +'where TABLE_OWNER = :pOwner ' +' and TABLE_NAME = :pTable ' +' and INDEX_OWNER = TABLE_OWNER ' end; function GetTableIndexColumn: string; begin result := 'Select C.*, ' +'(Select uniqueness ' +' from ALL_INDEXES I ' +' WHERE I.INDEX_NAME = C.INDEX_NAME ' +' and I.OWNER = C.INDEX_OWNER ) ISUNIQE ' +'from ALL_IND_COLUMNS C ' +'where TABLE_OWNER = :pOwner ' +' and TABLE_NAME = :pTable ' +' and INDEX_OWNER = TABLE_OWNER ' +' and INDEX_NAME = :pIndex'; end; {**************************** TIndexList **************************************} constructor TIndexList.Create; begin FInnerList := TList.Create; end; destructor TIndexList.Destroy; var i : Integer; begin try if FInnerList.Count > 0 then begin for i := FInnerList.Count - 1 downto 0 do begin TObject(FInnerList.Items[i]).Free; end; end; finally FInnerList.Free; end; inherited; end; procedure TIndexList.Add(TableIndex: TTableIndex); begin FInnerList.Add(TableIndex); end; procedure TIndexList.Delete(Index: Integer); begin TObject(FInnerList.Items[Index]).Free; FinnerList.Delete(Index); end; function TIndexList.GetItem(Index: Integer): TTableIndex; begin Result := FInnerList.Items[Index]; end; procedure TIndexList.SetItem(Index: Integer; TableIndex: TTableIndex); begin if Assigned(TableIndex) then FInnerList.Items[Index] := TableIndex end; function TIndexList.GetCount: Integer; begin Result := FInnerList.Count; end; function TIndexList.GetTableIndexes: string; begin result := 'Select * FROM ALL_INDEXES ' +' WHERE TABLE_NAME = :pTable ' +' AND TABLE_OWNER = :pOwner'; end; procedure TIndexList.SetDDL; var q1: TOraQuery; FTableIndex: TTableIndex; begin if FTableName = '' then exit; q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetTableIndexes; q1.ParamByName('pTable').AsString := FTableName; q1.ParamByName('pOwner').AsString := FOwner; q1.Open; while Not q1.Eof do begin FTableIndex := TTableIndex.Create; FTableIndex.TableName := FTableName; FTableIndex.TableSchema := FOwner; FTableIndex.OraSession := OraSession; FTableIndex.IndexName := q1.FieldByName('INDEX_NAME').AsString; FTableIndex.IndexSchema := FOwner; FTableIndex.SetDDL; Add(FTableIndex); FTableIndex.NewInstance; NewInstance; q1.Next; end; q1.close; end; function TIndexList.GetDDL: string; var i: integer; begin result := ''; if Count > 0 then begin for i := 0 to Count -1 do begin result := result + Items[i].GetDDL+ln+ln; end; end; end; {**************************** TTableIndex **************************************} constructor TTableIndex.Create; begin inherited; FIndexPartitionLists := TIndexPartitionList.Create; FIndexColumnLists := TColumnList.Create; FDSIndex := TVirtualTable.Create(nil); FDSIndexColumns := TVirtualTable.Create(nil); FDSIndexPartitions := TVirtualTable.Create(nil); end; destructor TTableIndex.destroy; begin FIndexPartitionLists.Free; FIndexColumnLists.Free; FDSIndex.Free; FDSIndexColumns.Free; FDSIndexPartitions.Free; inherited; end; function TTableIndex.GetIndexStatus: string; var q1: TOraQuery; begin q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetObjectStatusSQL; q1.ParamByName('pOName').AsString := FIndexName; q1.ParamByName('pOType').AsString := 'INDEX'; q1.ParamByName('pOwner').AsString := FIndexSchema; q1.Open; result := FIndexName+' ( Created: '+q1.FieldByName('CREATED').AsString +' Last DDL: '+q1.FieldByName('LAST_DDL_TIME').AsString +' Status: '+q1.FieldByName('STATUS').AsString +' )'; q1.Close; end; function TTableIndex.GetTableIndexDetail: string; begin result := 'Select * FROM ALL_INDEXES ' +' WHERE INDEX_NAME = :pIndex ' +' AND OWNER = :pOwner '; end; function TTableIndex.GetTableIndexPartitions: string; begin result := 'Select pii.* ' +' from ( Select i.owner, pi.index_name, i.table_owner, i.table_name, pi.partitioning_type, ' +' pi.subpartitioning_type, ' +' pi.partition_count, pi.locality, pi.def_tablespace_name, ' +' pi.DEF_BUFFER_POOL, pi.DEF_INI_TRANS, pi.DEF_MAX_TRANS, pi.DEF_INITIAL_EXTENT, ' +' pi.DEF_NEXT_EXTENT, pi.DEF_MIN_EXTENTS, pi.DEF_MAX_EXTENTS, pi.DEF_FREELISTS, ' +' pi.DEF_FREELIST_GROUPS, pi.DEF_PCT_INCREASE, pi.DEF_PCT_FREE, pi.DEF_LOGGING ' +' from ALL_PART_INDEXES pi, ALL_INDEXES i ' +' where i.OWNER = pi.owner ' +' and i.INDEX_NAME = pi.INDEX_NAME ' +' and i.TABLE_NAME = pi.TABLE_NAME ' +' and i.PARTITIONED = ''YES'') pii ' +' where pii.owner = :pOwner ' +' and pii.index_name = :pIndex '; end; function TTableIndex.GetTableIndexExpressions(IndexOwner, IndexName, TableOwner, TableName, ColumnPosition: string): string; begin result := 'Select IE.* ' +' FROM ALL_IND_EXPRESSIONS IE ' +' WHERE IE.INDEX_OWNER = '+Str(IndexOwner) +' AND IE.INDEX_NAME = '+Str(IndexName) +' AND IE.TABLE_OWNER = '+Str(TableOwner) +' AND IE.TABLE_NAME = '+Str(TableName) +' AND IE.COLUMN_POSITION = '+ColumnPosition; end; procedure TTableIndex.SetDDL; var qDetail,q,q2: TOraQuery; FColumn: TColumn; FColumnList : TColumnList; begin if FIndexName = '' then exit; qDetail := TOraQuery.Create(nil); q := TOraQuery.Create(nil); q2 := TOraQuery.Create(nil); qDetail.Session := OraSession; q.Session := OraSession; q2.Session := OraSession; qDetail.SQL.Text := GetTableIndexDetail; qDetail.ParamByName('pIndex').AsString := FIndexName; qDetail.ParamByName('pOwner').AsString := FIndexSchema; qDetail.Open; {open} CopyDataSet(qDetail, FDSIndex); FBitmap := qDetail.FieldByName('INDEX_TYPE').AsString = 'BITMAP'; if qDetail.FieldByName('UNIQUENESS').AsString = 'UNIQUE' then FIndexType := Uniqe; FTableName := qDetail.FieldByName('TABLE_NAME').AsString; FTableSchema := qDetail.FieldByName('TABLE_OWNER').AsString; FFunctions := qDetail.FieldByName('FUNCIDX_STATUS').AsString = 'ENABLED'; FLoggingType := ltDefault; if qDetail.FieldByName('LOGGING').AsString = 'YES' then FLoggingType := ltLogging; if qDetail.FieldByName('LOGGING').AsString = 'NO' then FLoggingType := ltNoLogging; FParalel := (isNullorZero(qDetail.FieldByName('DEGREE').AsString,'1')) or (isNullorZero(qDetail.FieldByName('INSTANCES').AsString,'1')); FParalelInstances := StrToInt(isNull(qDetail.FieldByName('INSTANCES').AsString)); FParalelDegree := StrToInt(isNull(qDetail.FieldByName('DEGREE').AsString)); FCompress := qDetail.FieldByName('PREFIX_LENGTH').AsInteger > 0; FCompressColumns := qDetail.FieldByName('PREFIX_LENGTH').AsInteger; FPhsicalAttributes.Tablespace := qDetail.FieldByName('TABLESPACE_NAME').AsString; FPhsicalAttributes.PercentFree := qDetail.FieldByName('PCT_FREE').AsString; FPhsicalAttributes.InitialTrans := qDetail.FieldByName('INI_TRANS').AsString; FPhsicalAttributes.MaxTrans := qDetail.FieldByName('MAX_TRANS').AsString; FPhsicalAttributes.InitialExtent:= qDetail.FieldByName('INITIAL_EXTENT').AsString; FPhsicalAttributes.MinExtent := qDetail.FieldByName('MIN_EXTENTS').AsString; FPhsicalAttributes.MaxExtent := qDetail.FieldByName('MAX_EXTENTS').AsString; FPhsicalAttributes.PctIncrease := qDetail.FieldByName('PCT_INCREASE').AsString; FPhsicalAttributes.FreeLists := qDetail.FieldByName('FREELISTS').AsString; FPhsicalAttributes.FreeGroups := qDetail.FieldByName('FREELIST_GROUPS').AsString; FPhsicalAttributes.BufferPool := bpDefault; if qDetail.FieldByName('BUFFER_POOL').AsString = 'RECYCLE' then FPhsicalAttributes.BufferPool := bpRecycle; if qDetail.FieldByName('BUFFER_POOL').AsString = 'KEEP' then FPhsicalAttributes.BufferPool := bpKeep; if qDetail.FieldByName('PARTITIONED').AsString = 'NO' then FPartitionClause := pcNonPartition else FPartitionClause := pcGlobal; if FPartitionClause <> pcNonPartition then begin q.close; q.SQL.Text := GetTableIndexPartitions; q.ParamByName('pOwner').AsString := FIndexSchema; q.ParamByName('pIndex').AsString := FIndexName; q.Open; if q.RecordCount > 0 then begin if q.FieldByName('LOCALITY').AsString = 'LOCAL' then FPartitionClause := pcLocal else FPartitionClause := pcGlobal; if q.FieldByName('PARTITIONING_TYPE').AsString = 'RANGE' then FIndexPartitionType := ptRange else FIndexPartitionType := ptHash; if q.FieldByName('SUBPARTITIONING_TYPE').AsString = 'RANGE' then FIndexSubpartitionType := ptRange else FIndexSubpartitionType := ptHash; IndexHashPartitionType := 'User Named'; end; FIndexPartitionLists.ObjectName := FIndexName; FIndexPartitionLists.ObjectOwner := FIndexSchema; FIndexPartitionLists.OraSession := OraSession; FIndexPartitionLists.SetDDL; CopyDataSet(FIndexPartitionLists.DSPartitionList, FDSIndexPartitions); end; qDetail.Close;{close} FColumnList := TColumnList.Create; q.close; q.SQL.Text := GetTableIndexColumn; q.ParamByName('pTable').AsString := FTableName; q.ParamByName('pOwner').AsString := FTableSchema; q.ParamByName('pIndex').AsString := FIndexName; q.Open; CopyDataSet(q, FDSIndexColumns); while not q.Eof do begin FColumn := TColumn.Create; if copy(q.FieldByName('COLUMN_NAME').AsString,1,4) = 'SYS_' then begin q2.close; q2.SQL.Text := GetTableIndexExpressions(q.FieldByName('INDEX_OWNER').AsString, q.FieldByName('INDEX_NAME').AsString, q.FieldByName('TABLE_OWNER').AsString, q.FieldByName('TABLE_NAME').AsString, q.FieldByName('COLUMN_POSITION').AsString); Q2.Open; if Q2.RecordCount > 0 then FColumn.ColumnName := q2.FieldByName('COLUMN_EXPRESSION').AsString else FColumn.ColumnName := q.FieldByName('COLUMN_NAME').AsString; end else FColumn.ColumnName := q.FieldByName('COLUMN_NAME').AsString; FColumn.DataType := ''; FColumnList.Add(FColumn); FColumn.NewInstance; FColumnList.NewInstance; q.Next; end; FIndexColumnLists := FColumnList; qDetail.close; q.close; q2.close; end; function TTableIndex.GetDDL: string; var strTypes, indexHeader, strColumns, strBody, strPartitions: string; i : integer; begin //header strTypes := ''; with self do begin if Bitmap then strTypes := 'BITMAP'; if IndexType = Uniqe then strTypes := 'UNIQUE'; indexHeader := 'CREATE '+strTypes+' INDEX '+IndexSchema+'.'+ IndexName+ln +' ON ' +TableSchema+'.' +TableName+' ' ; if IndexColumnLists.Count > 0 then begin strColumns := '('; for I := 0 to IndexColumnLists.Count -1 do begin //if copy(indexColumns[I].ColumnName,1,4) = 'SYS_' then if Functions then begin if length(FunctionCnt) > 0 then strColumns := strColumns + FunctionCnt else strColumns := strColumns + IndexColumnLists.Items[I].ColumnName; end else strColumns := strColumns + IndexColumnLists.Items[I].ColumnName; if i <> IndexColumnLists.Count-1 then strColumns := strColumns +','; end; //IndexColumnLists.Count strColumns := strColumns +')'; end; //IndexColumns //BODY if LoggingType = ltLogging then strBody := strBody +ln+ ' LOGGING'; if LoggingType = ltNoLogging then strBody := strBody +ln+ ' NOLOGGING'; if ComputeStatistic then strBody := strBody +ln +' COMPUTE STATISTICS'; if Paralel then strBody := strBody +ln+' PARALLEL( DEGREE '+IntToStr(ParalelDegree) +' INSTANCES '+IntToStr(ParalelInstances) +' ) ' else strBody := strBody +ln+' NOPARALLEL'; if Compress then strBody := strBody +ln+' COMPRESS '+IntToStr(CompressColumns) ; if NoSorted then strBody := strBody +ln+' NOSORT '; if Reverse then strBody := strBody +ln+' REVERSE '; strBody := strBody + GenerateStorage(PhsicalAttributes); if PartitionClause <> pcNonPartition then begin FIndexPartitionLists.IndexHashPartitionType := FIndexHashPartitionType; FIndexPartitionLists.PartitionClause := FPartitionClause; FIndexPartitionLists.IndexPartitionType := FIndexPartitionType; FIndexPartitionLists.IndexPartitionRangeType := rpRange; strPartitions := FIndexPartitionLists.GetDDL; //(FIndexHashPartitionType, FPartitionClause, FIndexPartitionType, rpRange) end;//PartitionClause <> NonPartition end; //with TTableIndex do result := indexHeader + strColumns + strBody + strPartitions +';' end; //GetDDL function TTableIndex.GetAlterDDL(NewValue: TTableIndex): string; var strHeader, header: string; begin result := ''; strHeader := ''; with self do begin Header := 'ALTER INDEX '+IndexSchema+'.'+IndexName+ln; if ParalelDegree <> NewValue.ParalelDegree then begin if (isNullorZero(NewValue.ParalelDegree,1)) or (isNullorZero(NewValue.ParalelInstances,1)) then strHeader := strHeader + Header + ' PARALLEL ( DEGREE '+IntToStr(NewValue.ParalelDegree)+' INSTANCES '+IntTOStr(NewValue.ParalelInstances)+' );'+ln else strHeader := strHeader + Header + ' NOPARALLEL;'+ln; end; if LoggingType <> NewValue.LoggingType then begin if NewValue.LoggingType = ltLogging then strHeader := strHeader + Header + ' LOGGING;'+ln; if NewValue.LoggingType = ltNoLogging then strHeader := strHeader + Header + ' NOLOGGING;'+ln; end; strHeader := strHeader + GenerateDiffStorage(ooIndex, Header, PhsicalAttributes, NewValue.PhsicalAttributes); end; //with result := strHeader; end; //GetAlterDDL function TTableIndex.CreateIndex(IndexScript: string) : boolean; begin result := false; if FIndexName = '' then exit; result := ExecSQL(IndexScript, Format(ChangeSentence('strIndexCreated',strIndexCreated),[FIndexName]), FOraSession); end; function TTableIndex.AlterIndex(IndexScript: string) : boolean; begin result := false; if FIndexName = '' then exit; result := ExecSQL(IndexScript, Format(ChangeSentence('strIndexAltered',strIndexAltered),[FIndexName]), FOraSession); end; function TTableIndex.DropIndex: boolean; var FSQL: string; begin result := false; if FIndexName = '' then exit; FSQL := 'drop index '+FIndexSchema+'.'+FIndexName; result := ExecSQL(FSQL, Format(ChangeSentence('strIndexDropped',strIndexDropped),[FIndexName]), FOraSession); end; function TTableIndex.RebuildIndex: boolean; var FSQL: string; begin result := false; if FIndexName = '' then exit; FSQL := 'alter index '+FIndexSchema+'.'+FIndexName+' rebuild '; result := ExecSQL(FSQL, Format(ChangeSentence('strIndexRebuilt',strIndexRebuilt),[FIndexName]), FOraSession); end; function TTableIndex.CoalesceIndex: boolean; var FSQL: string; begin result := false; if FIndexName = '' then exit; FSQL := 'alter index '+FIndexSchema+'.'+FIndexName+' Coalesce '; result := ExecSQL(FSQL, Format(ChangeSentence('strIndexCoalesced',strIndexCoalesced),[FIndexName]), FOraSession); end; function TTableIndex.AnalyzeTable(AnalyzeFunction: TAnalyzeFunction; Sample: integer; SampleType: integer): boolean; var FSQL, s: string; begin result := false; if FIndexName = '' then exit; if SampleType = 0 then s := IntToStr(Sample)+' ROWS ' else s := IntToStr(Sample)+' PERCENT '; case AnalyzeFunction of afCompute: FSQL := 'ANALYZE INDEX '+FIndexSchema+'.'+FIndexName + ' COMPUTE STATISTICS '; afEstimate: FSQL := 'ANALYZE INDEX '+FIndexSchema+'.'+FIndexName + ' ESTIMATE STATISTICS SAMPLE '+s; afDelete: FSQL := 'ANALYZE INDEX '+FIndexSchema+'.'+FIndexName + ' DELETE STATISTICS '; end; result := ExecSQL(FSQL, Format(ChangeSentence('strIndexAnalyzed',strIndexAnalyzed),[FIndexName]), FOraSession); end; end.
unit udmCtasBancarias; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS, uMatVars; type TdmCtasBancarias = class(TdmPadrao) qryManutencaoBANCO: TStringField; qryManutencaoAGENCIA: TStringField; qryManutencaoCONTA: TStringField; qryManutencaoNOME_AGENCIA: TStringField; qryManutencaoNOME_CONTA: TStringField; qryManutencaoENDERECO: TStringField; qryManutencaoCTA_CONTABIL: TStringField; qryManutencaoBAIRRO: TStringField; qryManutencaoCIDADE: TStringField; qryManutencaoESTADO: TStringField; qryManutencaoCEP: TStringField; qryManutencaoTELEFONE: TStringField; qryManutencaoCONTATO: TStringField; qryManutencaoNR_CEDENTE: TStringField; qryManutencaoULT_BLOQUETO: TFloatField; qryManutencaoULT_REMESSA: TFloatField; qryManutencaoULT_CHEQUE: TFloatField; qryManutencaoULT_ENTRADA: TFloatField; qryManutencaoCARTEIRA: TStringField; qryManutencaoTP_ESCRITURAL: TStringField; qryManutencaoTX_BANCARIA: TFloatField; qryManutencaoLIMITE_CREDITO: TFloatField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryManutencaoNOME_BCO: TStringField; qryLocalizacaoBANCO: TStringField; qryLocalizacaoAGENCIA: TStringField; qryLocalizacaoCONTA: TStringField; qryLocalizacaoNOME_AGENCIA: TStringField; qryLocalizacaoNOME_CONTA: TStringField; qryLocalizacaoENDERECO: TStringField; qryLocalizacaoCTA_CONTABIL: TStringField; qryLocalizacaoBAIRRO: TStringField; qryLocalizacaoCIDADE: TStringField; qryLocalizacaoESTADO: TStringField; qryLocalizacaoCEP: TStringField; qryLocalizacaoTELEFONE: TStringField; qryLocalizacaoCONTATO: TStringField; qryLocalizacaoNR_CEDENTE: TStringField; qryLocalizacaoULT_BLOQUETO: TFloatField; qryLocalizacaoULT_REMESSA: TFloatField; qryLocalizacaoULT_CHEQUE: TFloatField; qryLocalizacaoULT_ENTRADA: TFloatField; qryLocalizacaoCARTEIRA: TStringField; qryLocalizacaoTP_ESCRITURAL: TStringField; qryLocalizacaoTX_BANCARIA: TFloatField; qryLocalizacaoLIMITE_CREDITO: TFloatField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoNOME_BCO: TStringField; private FCod_Banco: string; FCod_Agencia: string; FNro_Conta: string; function GetSqlDefault: string; public procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; property SqlDefault: string read GetSqlDefault; property Banco: string read FCod_Banco write FCod_Banco; property Agencia: string read FCod_Agencia write FCod_Agencia; property Conta: string read FNro_Conta write FNro_Conta; function LocalizaAgencia(DataSet: TDataSet = nil): Boolean; function LocalizaConta(DataSet: TDataSet = nil): Boolean; end; const C_SQL_DEFAUT = 'SELECT ' + ' CTA.BANCO, ' + ' CTA.AGENCIA, ' + ' CTA.CONTA, ' + ' CTA.NOME_AGENCIA, ' + ' CTA.NOME_CONTA, ' + ' CTA.ENDERECO, ' + ' CTA.CTA_CONTABIL, ' + ' CTA.BAIRRO, ' + ' CTA.CIDADE, ' + ' CTA.ESTADO, ' + ' CTA.CEP, ' + ' CTA.TELEFONE, ' + ' CTA.CONTATO, ' + ' CTA.NR_CEDENTE, ' + ' CTA.ULT_BLOQUETO, ' + ' CTA.ULT_REMESSA, ' + ' CTA.ULT_CHEQUE, ' + ' CTA.ULT_ENTRADA, ' + ' CTA.CARTEIRA, ' + ' CTA.TP_ESCRITURAL, ' + ' CTA.TX_BANCARIA, ' + ' CTA.LIMITE_CREDITO, ' + ' CTA.DT_ALTERACAO, ' + ' CTA.OPERADOR, ' + ' BCO.NOME_BCO ' + ' FROM STWCPGTCTA CTA ' + ' LEFT JOIN STWFATTBCO BCO ON BCO.COD_BCO = CTA.BANCO '; var dmCtasBancarias: TdmCtasBancarias; implementation uses udmPrincipal; {$R *.dfm} { TdmCtasBancarias } { TdmCtasBancarias } function TdmCtasBancarias.GetSqlDefault: string; begin result := C_SQL_DEFAUT; end; function TdmCtasBancarias.LocalizaAgencia(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(C_SQL_DEFAUT); SQL.Add('WHERE ( CTA.BANCO = :BANCO )'); SQL.Add('ORDER BY CTA.BANCO, CTA.AGENCIA, CTA.CONTA'); Params[0].AsString := FCod_Banco; Open; Result := not IsEmpty; end; end; function TdmCtasBancarias.LocalizaConta(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(C_SQL_DEFAUT); SQL.Add('WHERE ( CTA.BANCO = :BANCO ) AND ( CTA.AGENCIA = :AGENCIA )'); SQL.Add('ORDER BY CTA.BANCO, CTA.AGENCIA, CTA.CONTA'); Params[0].AsString := FCod_Banco; Params[1].AsString := FCod_Agencia; Open; Result := not IsEmpty; end; end; procedure TdmCtasBancarias.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(C_SQL_DEFAUT); SQL.Add('WHERE ( CTA.BANCO = :BANCO ) AND ( CTA.AGENCIA = :AGENCIA ) AND ( CTA.CONTA = :CONTA )'); SQL.Add('ORDER BY CTA.BANCO, CTA.AGENCIA, CTA.CONTA'); Params[0].AsString := FCod_Banco; Params[1].AsString := FCod_Agencia; Params[2].AsString := FNro_Conta; end; end; procedure TdmCtasBancarias.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(C_SQL_DEFAUT); SQL.Add('ORDER BY CTA.BANCO, CTA.AGENCIA, CTA.CONTA'); end; end; end.
Program diagonales; const max=30; type matriz = array [1..max,1..max] of integer; Var A:matriz; n:integer; Procedure LlenarMatrizCuadrada(var A:matriz; n:integer); var i,j:integer; begin for i:=1 to n do begin for j:=1 to n do begin A[i,j]:= random(9)+1; end; end; end; Procedure MostrarMatrizCuadrada(A:matriz; n:integer); var i,j:integer; begin for i:=1 to n do begin for j:=1 to n do begin write(A[i,j], ' '); end; writeln; end; end; Procedure RecorridoDiagonalPrincipalAlReves(A:matriz; n:integer); var i,j,k: integer; begin for i:=n downto 1 do begin j:=1; k:=i; while(k<=n)do begin write(A[k,j], ' '); j:=j+1; k:=k+1; end; end; for j:=2 to n do begin i:=1; k:=j; while(k<=n)do begin write(A[i,k], ' '); k:=k+1; i:=i+1; end; end; end; Begin repeat writeln('Introduzca dimension de la matriz cuadrada'); read(n); until (n<30); LlenarMatrizCuadrada(A,n); writeln('La matriz es:'); MostrarMatrizCuadrada(A,n); writeln('El recorrido por la diagonal principal es:'); RecorridoDiagonalPrincipalAlReves(A,n); End.
unit fmuReceipt; interface uses // VCL ComCtrls, StdCtrls, Controls, Classes, SysUtils, ExtCtrls, Graphics, // This untPages, untUtil, untDriver, Spin; type { TfmReceipt } TfmReceipt = class(TPage) btnSale: TButton; btnReturnSale: TButton; btnReturnBuy: TButton; btnBuy: TButton; btnStorno: TButton; btnCheckSubTotal: TButton; btnCashOutCome: TButton; btnCashInCome: TButton; btnCharge: TButton; btnStornoCharge: TButton; btnStornoDiscount: TButton; btnDiscount: TButton; btnOpenCheck: TButton; btnCloseCheck: TButton; btnRepeatDocument: TButton; btnSysAdminCancelCheck: TButton; btnCancelCheck: TButton; edtStringForPrint: TEdit; lblStringForPrint: TLabel; edtChange: TEdit; edtCheckSubTotal: TEdit; edtDiscountOnCheck: TEdit; cbTax4: TComboBox; cbTax3: TComboBox; cbTax2: TComboBox; cbTax1: TComboBox; edtSumm4: TEdit; edtSumm3: TEdit; edtSumm2: TEdit; lblSumm1: TLabel; lblSumm2: TLabel; lblSumm3: TLabel; lblSumm4: TLabel; lblTax1: TLabel; lblTax2: TLabel; lblTax3: TLabel; lblTax4: TLabel; lblDiscountOnCheck: TLabel; lblCheckSubTotal: TLabel; lblChange: TLabel; cbCheckType: TComboBox; lblCheckType: TLabel; lblDepartment: TLabel; edtQuantity: TEdit; lblQuantity: TLabel; lblPrice: TLabel; edtPrice: TEdit; edtNumber: TEdit; edtName: TEdit; Label50: TLabel; Label1: TLabel; cbNumber: TComboBox; lblNumber: TLabel; btnSaleEx: TButton; seDepartment: TSpinEdit; btnBeep: TButton; edtSumm1: TEdit; btnCloseCheckKPK: TButton; lblKPKStr: TLabel; edtKPKStr: TEdit; procedure btnSaleClick(Sender: TObject); procedure btnBuyClick(Sender: TObject); procedure btnStornoClick(Sender: TObject); procedure btnReturnSaleClick(Sender: TObject); procedure btnReturnBuyClick(Sender: TObject); procedure btnCheckSubTotalClick(Sender: TObject); procedure btnCashInComeClick(Sender: TObject); procedure btnCashOutComeClick(Sender: TObject); procedure btnChargeClick(Sender: TObject); procedure btnStornoChargeClick(Sender: TObject); procedure btnDiscountClick(Sender: TObject); procedure btnStornoDiscountClick(Sender: TObject); procedure btnOpenCheckClick(Sender: TObject); procedure btnCloseCheckClick(Sender: TObject); procedure btnSysAdminCancelCheckClick(Sender: TObject); procedure btnRepeatDocumentClick(Sender: TObject); procedure btnCancelCheckClick(Sender: TObject); procedure cbNumberChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnSaleExClick(Sender: TObject); procedure btnBeepClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure btnCloseCheckKPKClick(Sender: TObject); private procedure SetParams; function GetPrintWidth: Integer; end; implementation {$R *.DFM} { TfmReceipt } function TfmReceipt.GetPrintWidth: Integer; begin case Driver.UModel of 0: Result := 36; // ØÒÐÈÕ-ÔÐ-Ô 1: Result := 36; // ØÒÐÈÕ-ÔÐ-Ô (Êàçàõñòàí) 2: Result := 24; // ÝËÂÅÑ-ÌÈÍÈ-ÔÐ-Ô 3: Result := 20; // ÔÅËÈÊÑ-Ð Ô 4: Result := 36; // ØÒÐÈÕ-ÔÐ-Ê 5: Result := 40; // ØÒÐÈÕ-950Ê 6: Result := 32; // ÝËÂÅÑ-ÔÐ-Ê 7: Result := 50; // ØÒÐÈÕ-ÌÈÍÈ-ÔÐ-Ê 8: Result := 36; // ØÒÐÈÕ-ÔÐ-Ô (Áåëîðóññèÿ) 9: Result := 48; // ØÒÐÈÕ-ÊÎÌÁÎ-ÔÐ-Ê âåðñèè 1 10: Result := 40; // Ôèñêàëüíûé áëîê Øòðèõ-POS-Ô 11: Result := 40; // Øòðèõ950K âåðñèÿ 2 12: Result := 40; // ØÒÐÈÕ-ÊÎÌÁÎ-ÔÐ-Ê âåðñèè 2 14: Result := 50; // ØÒÐÈÕ-ÌÈÍÈ-ÔÐ-Ê 2 else Result := 40; end; end; procedure TfmReceipt.SetParams; var S: string; W: Integer; begin CheckIntStr(edtSumm1.Text, 'Ñóììà 1'); CheckIntStr(edtPrice.Text, 'Öåíà'); CheckIntStr(edtQuantity.Text, 'Êîëè÷åñòâî'); CheckIntStr(edtNumber.Text, 'Íîìåð'); Driver.Summ1 := StrToCurr(edtSumm1.text); Driver.Price := StrToCurr(edtPrice.text); Driver.Quantity := StrToFloat(edtQuantity.Text); Driver.Department := seDepartment.Value; Driver.Tax1 := cbTax1.ItemIndex; Driver.Tax2 := cbTax2.ItemIndex; Driver.Tax3 := cbTax3.ItemIndex; Driver.Tax4 := cbTax4.ItemIndex; Driver.Connect; W := GetPrintWidth; case cbNumber.ItemIndex of 0: S := edtName.Text; 1: S := Format('%-*.*s%-4s%3d',[W-8, W-9, edtName.Text, 'ÒÐÊ', StrToInt(edtNumber.Text)]); 2: S := Format('%-*.*s%-5s%4d',[W-9, W-10, edtName.Text, 'Ñ×ÅÒ', StrToInt(edtNumber.Text)]); end; Driver.StringforPrinting := S; end; procedure TfmReceipt.btnSaleClick(Sender: TObject); begin EnableButtons(False); try UpdateObject; SetParams; Driver.Sale; UpdatePage; finally EnableButtons(True); end; end; procedure TfmReceipt.btnBuyClick(Sender: TObject); begin EnableButtons(False); try SetParams; Driver.Buy; finally EnableButtons(True); end; end; procedure TfmReceipt.btnStornoClick(Sender: TObject); begin EnableButtons(False); try SetParams; Driver.Storno; finally EnableButtons(True); end; end; procedure TfmReceipt.btnReturnSaleClick(Sender: TObject); begin EnableButtons(False); try SetParams; Driver.ReturnSale; finally EnableButtons(True); end; end; procedure TfmReceipt.btnReturnBuyClick(Sender: TObject); begin EnableButtons(False); try SetParams; Driver.ReturnBuy; finally EnableButtons(True); end; end; procedure TfmReceipt.btnCheckSubTotalClick(Sender: TObject); begin EnableButtons(False); try if Driver.CheckSubTotal = 0 then edtCheckSubTotal.Text := FloatToStr(Driver.Summ1) else edtCheckSubTotal.Clear; finally EnableButtons(True); end; end; procedure TfmReceipt.btnCashInComeClick(Sender: TObject); begin EnableButtons(False); try CheckIntStr(edtSumm1.Text, 'Ñóììà 1'); Driver.Summ1 := StrToCurr(edtSumm1.Text); Driver.CashInCome; finally EnableButtons(True); end; end; procedure TfmReceipt.btnCashOutComeClick(Sender: TObject); begin EnableButtons(False); try CheckIntStr(edtSumm1.Text, 'Ñóììà 1'); Driver.Summ1 := StrToCurr(edtSumm1.text); Driver.CashOutCome; finally EnableButtons(True); end; end; procedure TfmReceipt.btnChargeClick(Sender: TObject); begin EnableButtons(False); try SetParams; Driver.Charge; finally EnableButtons(True); end; end; procedure TfmReceipt.btnStornoChargeClick(Sender: TObject); begin EnableButtons(False); try SetParams; Driver.StornoCharge; finally EnableButtons(True); end; end; procedure TfmReceipt.btnDiscountClick(Sender: TObject); begin EnableButtons(False); try SetParams; Driver.Discount; finally EnableButtons(True); end; end; procedure TfmReceipt.btnStornoDiscountClick(Sender: TObject); begin EnableButtons(False); try SetParams; Driver.StornoDiscount; finally EnableButtons(True); end; end; procedure TfmReceipt.btnOpenCheckClick(Sender: TObject); begin EnableButtons(False); try Driver.CheckType := cbCheckType.ItemIndex; Driver.OpenCheck; finally EnableButtons(True); end; end; procedure TfmReceipt.btnCloseCheckClick(Sender: TObject); begin EnableButtons(False); try CheckIntStr(edtSumm1.Text, 'Ñóììà 1'); CheckIntStr(edtSumm2.Text, 'Ñóììà 2'); CheckIntStr(edtSumm3.Text, 'Ñóììà 3'); CheckIntStr(edtSumm4.Text, 'Ñóììà 4'); CheckIntStr(edtDiscountOnCheck.Text, 'Ñêèäêà íà ÷åê'); Driver.Summ1 := StrToCurr(edtSumm1.Text); Driver.Summ2 := StrToCurr(edtSumm2.Text); Driver.Summ3 := StrToCurr(edtSumm3.Text); Driver.Summ4 := StrToCurr(edtSumm4.Text); Driver.Tax1 := cbTax1.ItemIndex; Driver.Tax2 := cbTax2.ItemIndex; Driver.Tax3 := cbTax3.ItemIndex; Driver.Tax4 := cbTax4.ItemIndex; Driver.DiscountOnCheck := StrToFloat(edtDiscountOnCheck.Text); Driver.StringforPrinting := edtStringForPrint.Text; if Driver.CloseCheck <> 0 then edtChange.Clear else edtChange.Text := CurrToStr(Driver.Change); finally EnableButtons(True); end; end; procedure TfmReceipt.btnSysAdminCancelCheckClick(Sender: TObject); begin EnableButtons(False); try Driver.SysAdminCancelCheck; Driver.OperationBlockFirstString := 0; finally EnableButtons(True); end; end; procedure TfmReceipt.btnRepeatDocumentClick(Sender: TObject); begin EnableButtons(False); try Driver.RepeatDocument; finally EnableButtons(True); end; end; procedure TfmReceipt.btnCancelCheckClick(Sender: TObject); begin EnableButtons(False); try Driver.CancelCheck; Driver.OperationBlockFirstString := 0; finally EnableButtons(True); end; end; procedure TfmReceipt.cbNumberChange(Sender: TObject); begin if cbNumber.ItemIndex = 0 then begin edtNumber.Enabled := False; edtNumber.Color := clBtnFace; end else begin edtNumber.Enabled := True; edtNumber.Color := clWindow; end; end; procedure TfmReceipt.FormCreate(Sender: TObject); begin cbNumber.ItemIndex := 0; cbNumberChange(Self); end; procedure TfmReceipt.btnSaleExClick(Sender: TObject); begin EnableButtons(False); try SetParams; Driver.SaleEx; finally EnableButtons(True); end; end; procedure TfmReceipt.btnBeepClick(Sender: TObject); begin EnableButtons(False); try Driver.Beep; finally EnableButtons(True); end; end; procedure TfmReceipt.FormResize(Sender: TObject); var W: Integer; begin W := btnSale.Left - edtSumm1.Left - 7; edtSumm1.Width := W; edtSumm2.Width := W; edtSumm3.Width := W; edtSumm4.Width := W; edtCheckSubTotal.Width := W; edtChange.Width := W; edtDiscountOnCheck.Width := btnSale.Left - edtDiscountOnCheck.Left - 7; edtKPKStr.Width := W; end; procedure TfmReceipt.btnCloseCheckKPKClick(Sender: TObject); begin EnableButtons(False); try CheckIntStr(edtSumm1.Text, 'Ñóììà 1'); CheckIntStr(edtSumm2.Text, 'Ñóììà 2'); CheckIntStr(edtSumm3.Text, 'Ñóììà 3'); CheckIntStr(edtSumm4.Text, 'Ñóììà 4'); CheckIntStr(edtDiscountOnCheck.Text, 'Ñêèäêà íà ÷åê'); Driver.Summ1 := StrToCurr(edtSumm1.Text); Driver.Summ2 := StrToCurr(edtSumm2.Text); Driver.Summ3 := StrToCurr(edtSumm3.Text); Driver.Summ4 := StrToCurr(edtSumm4.Text); Driver.Tax1 := cbTax1.ItemIndex; Driver.Tax2 := cbTax2.ItemIndex; Driver.Tax3 := cbTax3.ItemIndex; Driver.Tax4 := cbTax4.ItemIndex; Driver.DiscountOnCheck := StrToFloat(edtDiscountOnCheck.Text); Driver.StringforPrinting := edtStringForPrint.Text; if Driver.CloseCheckWithKPK <> 0 then begin edtChange.Clear; edtKPKStr.Clear; end else begin edtChange.Text := CurrToStr(Driver.Change); edtKPKStr.Text := Driver.KPKStr; end; finally EnableButtons(True); end; end; end.
{ *************************************************************************** Copyright (c) 2016-2021 Kike Pérez Unit : Quick.HttpServer.Request Description : Http Server Request Author : Kike Pérez Version : 1.8 Created : 30/08/2019 Modified : 07/02/2021 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.HttpServer.Request; {$i QuickLib.inc} interface uses {$IFDEF DEBUG_HTTPSERVER} Quick.Debug.Utils, {$ENDIF} Classes, SysUtils, Quick.Commons, Quick.Arrays, Quick.Value, Quick.HttpServer.Types; type EHttpRequestError = class(Exception); type IHttpRequest = interface ['{D6B236A5-9D04-4380-8A89-5BD4CC60A1A6}'] function GetPathSegment(aIndex : Integer) : string; function GetQuery(const aName : string) : TFlexValue; function GetURL: string; function GetMethod: TMethodVerb; function GetCacheControl: string; function GetClientIP: string; function GetContent: TStream; function GetHeaders: TPairList; function GetHost: string; function GetPort: Integer; function GetReferer: string; function GetUnparsedParams: string; function GetUserAgent: string; property URL : string read GetURL; property Method : TMethodVerb read GetMethod; property Host : string read GetHost; property Port : Integer read GetPort; property Referer : string read GetReferer; property UserAgent : string read GetUserAgent; property CacheControl : string read GetCacheControl; property PathSegment[aIndex : Integer] : string read GetPathSegment; property UnparsedParams : string read GetUnparsedParams; property Query[const aName : string] : TFlexValue read GetQuery; property ClientIP : string read GetClientIP; property Headers : TPairList read GetHeaders; property Content : TStream read GetContent; function ContentAsString : string; function GetMethodAsString: string; end; THttpRequest = class(TInterfacedObject,IHttpRequest) private fURL : string; fMethod : TMethodVerb; fHost : string; fPort : Integer; fReferer : string; fUserAgent : string; fCacheControl : string; fUnparsedParams : string; fParsedQuery : TFlexPairArray; fClientIP : string; fHeaders : TPairList; fContent : TStream; fContentType : string; fContentEncoding : string; fContentLength : Int64; function GetPathSegment(aIndex : Integer) : string; function GetQuery(const aName : string) : TFlexValue; procedure ParseQuery; function GetURL: string; function GetMethod: TMethodVerb; function GetCacheControl: string; function GetClientIP: string; function GetContent: TStream; function GetHeaders: TPairList; function GetHost: string; function GetPort: Integer; function GetReferer: string; function GetUnparsedParams: string; function GetUserAgent: string; procedure SetURL(const Value: string); function GetContentEncoding: string; function GetContentLength: Int64; function GetContentType: string; procedure SetContentEncoding(const Value: string); procedure SetContentLength(const Value: Int64); procedure SetContentType(const Value: string); public constructor Create; destructor Destroy; override; property URL : string read GetURL write SetURL; property Method : TMethodVerb read GetMethod write fMethod; property Host : string read GetHost write fHost; property Port : Integer read GetPort write fPort; property Referer : string read GetReferer write fReferer; property UserAgent : string read GetUserAgent write fUserAgent; property CacheControl : string read GetCacheControl write fCacheControl; property PathSegment[aIndex : Integer] : string read GetPathSegment; property UnparsedParams : string read GetUnparsedParams write fUnparsedParams; property Query[const aName : string] : TFlexValue read GetQuery; property ClientIP : string read GetClientIP write fClientIP; property Headers : TPairList read GetHeaders write fHeaders; property Content : TStream read GetContent write fContent; property ContentType : string read GetContentType write SetContentType; property ContentEncoding : string read GetContentEncoding write SetContentEncoding; property ContentLength : Int64 read GetContentLength write SetContentLength; procedure SetMethodFromString(const aVerbMethod : string); function GetMethodAsString: string; function ContentAsString : string; end; implementation function THttpRequest.ContentAsString: string; begin {$IFDEF DEBUG_HTTPSERVER} TDebugger.Trace(Self,'ContentAsString Encode: %s',[ContentEncoding]); {$ENDIF} if fContent <> nil then Result := StreamToString(fContent,TEncoding.UTF8); end; constructor THttpRequest.Create; begin fHeaders := TPairList.Create; end; destructor THttpRequest.Destroy; begin fHeaders.Free; inherited; end; function THttpRequest.GetCacheControl: string; begin Result := fCacheControl; end; function THttpRequest.GetClientIP: string; begin Result := fClientIP; end; function THttpRequest.GetContent: TStream; begin Result := fContent; end; function THttpRequest.GetContentEncoding: string; begin Result := fContentEncoding; end; function THttpRequest.GetContentLength: Int64; begin Result := fContentLength; end; function THttpRequest.GetContentType: string; begin Result := fContentType; end; function THttpRequest.GetHeaders: TPairList; begin Result := fHeaders; end; function THttpRequest.GetHost: string; begin Result := fHost; end; function THttpRequest.GetMethod: TMethodVerb; begin Result := fMethod; end; function THttpRequest.GetMethodAsString: string; begin Result := MethodVerbStr[Integer(fMethod)]; end; function THttpRequest.GetPathSegment(aIndex: Integer): string; var upath : string; segment : TArray<string>; begin try if fURL.StartsWith('/') then upath := furl.Substring(1) else upath := fURL; segment := upath.Split(['/']); if (High(segment) < aIndex) or (aIndex < 0) then raise EHttpRequestError.CreateFmt('param out of bounds (%d)',[aIndex]); Result := segment[aIndex]; except on E : Exception do raise EHttpRequestError.CreateFmt('Error getting url path param : %s',[e.message]); end; end; function THttpRequest.GetPort: Integer; begin Result := fPort; end; function THttpRequest.GetQuery(const aName: string): TFlexValue; begin if fParsedQuery.Count = 0 then ParseQuery; Result := fParsedQuery.GetValue(aName); end; function THttpRequest.GetReferer: string; begin Result := fReferer; end; function THttpRequest.GetUnparsedParams: string; begin Result := fUnparsedParams; end; function THttpRequest.GetURL: string; begin Result := fURL; end; function THttpRequest.GetUserAgent: string; begin Result := fUserAgent; end; procedure THttpRequest.ParseQuery; var param : string; pair : TFlexPair; posi : Integer; begin for param in fUnparsedParams.Split(['&']) do begin posi := Pos('=',param); pair.Name := Copy(param,1,posi - 1); pair.Value := param.Substring(posi); fParsedQuery.Add(pair); end; end; procedure THttpRequest.SetContentEncoding(const Value: string); begin fContentEncoding := Value; end; procedure THttpRequest.SetContentLength(const Value: Int64); begin fContentLength := Value; end; procedure THttpRequest.SetContentType(const Value: string); begin fContentType := Value; end; procedure THttpRequest.SetMethodFromString(const aVerbMethod: string); var i : Integer; begin fMethod := TMethodVerb.mUNKNOWN; for i := 0 to Ord(High(TMethodVerb)) do begin if CompareText(aVerbMethod,MethodVerbStr[i]) = 0 then begin fMethod := TMethodVerb(i); Exit; end; end; end; procedure THttpRequest.SetURL(const Value: string); begin //remove first slash if Value.StartsWith('/') then fURL := Value.Substring(1) else fURL := Value; //remove last slash if fURL.EndsWith('/') then fURL := Copy(fURL,0,fURL.Length -1); end; end.
unit Banks; interface uses ClassStorageInt, Kernel, WorkCenterBlock, CacheAgent, BackupInterfaces; const tidCachePath_Banks = 'Banks\'; type TMetaBankBlock = class( TMetaWorkCenter ) public constructor Create( anId : string; aCapacities : array of TFluidValue; aBlockClass : CBlock ); end; TBankBlock = class( TFinanciatedWorkCenter ) protected constructor Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); override; public destructor Destroy; override; private fBank : TBank; public procedure AutoConnect( loaded : boolean ); override; private function GetBudgetPerc : integer; function GetInterest : integer; function GetTerm : integer; procedure SetBudgetPerc( Value : integer ); procedure SetInterest ( Value : integer ); procedure SetTerm ( Value : integer ); published property BudgetPerc : integer read GetBudgetPerc write SetBudgetPerc; property Interest : integer read GetInterest write SetInterest; property Term : integer read GetTerm write SetTerm; public procedure EndOfPeriod( PeriodType : TPeriodType; PeriodCount : integer ); override; published function RDOEstimateLoan( ClientId : integer ) : olevariant; function RDOAskLoan ( ClientId : integer; Amount : widestring ) : olevariant; procedure RDOSetLoanPerc ( Percent : integer ); public procedure StoreLinksToCache(Cache : TObjectCache); override; procedure StoreToCache(Cache : TObjectCache); override; procedure FacNameChanged; override; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; public procedure BlockLoaded; override; procedure Deleted; override; end; const DefBankInterest = 2; DefBankTerm = 30; procedure RegisterBackup; implementation uses SysUtils, ModelServerCache, MetaInstances, BasicAccounts, MathUtils, Logs; // TMetaBankBlock constructor TMetaBankBlock.Create( anId : string; aCapacities : array of TFluidValue; aBlockClass : CBlock ); begin inherited Create( anId, aCapacities, accIdx_None, accIdx_None, accIdx_Bank_Salaries, aBlockClass ); end; // TBankBlock constructor TBankBlock.Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); begin inherited; fBank := TBank.Create( Facility.Company.Owner ); fBank.Interest := DefBankInterest; fBank.Term := DefBankTerm; end; destructor TBankBlock.Destroy; begin fBank.Free; inherited; end; procedure TBankBlock.AutoConnect( loaded : boolean ); begin inherited; if not loaded then Facility.Name := 'Bank of ' + Facility.Company.Owner.Name; fBank.Name := 'Bank of ' + Facility.Company.Owner.Name; fBank.Timer := Facility.Town.Timer; fBank.Locator := Facility.Town.WorldLocator; end; function TBankBlock.GetBudgetPerc : integer; begin result := Facility.Company.Owner.BankLoanPerc; end; function TBankBlock.GetInterest : integer; begin result := fBank.Interest; end; function TBankBlock.GetTerm : integer; begin result := fBank.Term; end; procedure TBankBlock.SetBudgetPerc( Value : integer ); begin Facility.Company.Owner.BankLoanPerc := min( 100, Value ); end; procedure TBankBlock.SetInterest( Value : integer ); begin fBank.Interest := min( high(fBank.Interest), Value ); end; procedure TBankBlock.SetTerm( Value : integer ); begin fBank.Term := Value; end; procedure TBankBlock.EndOfPeriod( PeriodType : TPeriodType; PeriodCount : integer ); begin inherited; fBank.EndOfPeriod( PeriodType, PeriodCount ); end; function TBankBlock.RDOEstimateLoan( ClientId : integer ) : olevariant; var LoanCurr : currency; Loan : string; begin Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' - Fac(' + IntToStr(XPos) + ',' + IntToStr(YPos) + ') ' + 'EstimateLoan' ); try LoanCurr := fBank.EstimateLoan( TMoneyDealer(ClientId) ); if LoanCurr < 0 then Loan := FormatMoney(0) else Loan := FormatMoney(fBank.EstimateLoan( TMoneyDealer(ClientId) )); result := Loan; except end; end; function TBankBlock.RDOAskLoan( ClientId : integer; Amount : widestring ) : olevariant; begin Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' - Fac(' + IntToStr(XPos) + ',' + IntToStr(YPos) + ') ' + 'AskLoan' ); try if not Facility.CriticalTrouble and Facility.HasTechnology then result := fBank.AskLoan(TMoneyDealer(ClientId), StrToFloat(Amount)) else result := brqRejected; except Logs.Log(tidLog_Survival, DateTimeToStr(Now) + ' Error in AskLoan' ); result := brqRejected; end; end; procedure TBankBlock.RDOSetLoanPerc( Percent : integer ); begin try Facility.Company.Owner.BankLoanPerc := Percent; ModelServerCache.BackgroundInvalidateCache(Facility.Company.Owner); //CacheObject( Facility.Company.Owner, noKind, noInfo ) except end; end; procedure TBankBlock.StoreLinksToCache(Cache : TObjectCache); begin inherited; Cache.AddLink(GetGlobalPath(tidCachePath_Banks)); end; procedure TBankBlock.StoreToCache( Cache : TObjectCache ); var i : integer; begin inherited; // Cache.WriteInteger( 'BankBudget', Facility.Company.Owner.BankLoanPerc ); Cache.WriteInteger( 'LoanCount', fBank.Loans.Count ); for i := 0 to pred(fBank.Loans.Count) do with TLoan(fBank.Loans[i]) do if ObjectIs( TTycoon.ClassName, Debtor ) then begin Cache.WriteString( 'Debtor' + IntToStr(i), TTycoon(Debtor).Name ); Cache.WriteInteger( 'Interest' + IntToStr(i), Interest ); Cache.WriteCurrency( 'Amount' + IntToStr(i), Amount ); Cache.WriteCurrency( 'Slice' + IntToStr(i), Slice ); Cache.WriteInteger( 'Term' + IntToStr(i), Term ); end; end; procedure TBankBlock.FacNameChanged; begin fBank.Name := Facility.Name; end; procedure TBankBlock.LoadFromBackup( Reader : IBackupReader ); begin inherited; Reader.ReadObject( 'Bank', fBank, nil ); end; procedure TBankBlock.BlockLoaded; begin inherited; fBank.Loaded; end; procedure TBankBlock.Deleted; begin inherited; Facility.Town.WorldLocator.RedeemBank(fBank); end; procedure TBankBlock.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteObject( 'Bank', fBank ); end; // RegisterBackup procedure RegisterBackup; begin RegisterClass( TBankBlock ); end; end.
unit uFrmTouchBase; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, System.Actions, FMX.ActnList , QJSON; type TFrmTouchBase = class(TForm) raGoBack: TRectangle; raPriorPage: TRectangle; raNextPage: TRectangle; ActionList1: TActionList; actAction: TAction; actGoBack: TAction; actNextPage: TAction; actPriorPage: TAction; procedure actActionExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure actGoBackExecute(Sender: TObject); procedure actPriorPageExecute(Sender: TObject); procedure actNextPageExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); private { Private declarations } FID: Integer; FImgIndex: Integer; FQJson: TQJson; FGestureX: Single; /// <summary> /// 是否使用手势翻页 /// </summary> FUseGesture: Boolean; procedure LoadImage(AImgName: string); procedure InitEvent(); procedure SetImgIndex(const Value: Integer); public { Public declarations } property ID: Integer read FID write FID; property ImgIndex: Integer read FImgIndex write SetImgIndex; property UseGesture: Boolean read FUseGesture write FUseGesture default True; end; /// <summary> /// 创建一个窗口 /// </summary> /// <param name="AOwner"></param> /// <param name="AFormName"></param> /// <param name="APageIndex"></param> procedure CreateForm(AOwner: TComponent; AFormName: string; AID: Integer); var FrmTouchBase: TFrmTouchBase; implementation uses Winapi.Windows, FMX.Platform.Win; {$R *.fmx} procedure CreateForm(AOwner: TComponent; AFormName: string; AID: Integer); function GetFormByName(AFormName: string): TFrmTouchBase; var i: Integer; begin Result := nil; for I:=0 to Screen.FormCount-1 do begin if not (Screen.Forms[I].ClassNameIs(AFormName)) then Continue; Result := TFrmTouchBase(Screen.Forms[I]); Break; end; end; type TFormBaseClass = class of TFrmTouchBase; var vForm: TFrmTouchBase; sClassName, s: string; begin vForm := GetFormByName(AFormName); if vForm = nil then begin //创建 s := Copy(Trim(AFormName), 1, 1); if (s <> 'T') and (s <> 't') then sClassName := 'T' + Trim(AFormName) else sClassName := Trim(AFormName); if GetClass(sClassName)<>nil then vForm := TFormBaseClass(FindClass(sClassName)).Create(AOwner); end; if vForm = nil then begin {$IFDEF DEBUG} ShowMessage('没有找到类,可能类名不对'); {$ENDIF} Exit; end; //显示Form try vForm.ID := AID; vForm.ImgIndex := AID mod 100; vForm.ShowModal; finally FreeAndNil(vForm); end; end; procedure TFrmTouchBase.actActionExecute(Sender: TObject); begin FID := TAction(Sender).Tag; ImgIndex := 0; end; procedure TFrmTouchBase.actGoBackExecute(Sender: TObject); begin Self.Close; end; procedure TFrmTouchBase.actNextPageExecute(Sender: TObject); begin ImgIndex := ImgIndex + 1; end; procedure TFrmTouchBase.actPriorPageExecute(Sender: TObject); begin ImgIndex := ImgIndex - 1; end; procedure TFrmTouchBase.FormClose(Sender: TObject; var Action: TCloseAction); begin FreeAndNil(FQJson); end; procedure TFrmTouchBase.FormCreate(Sender: TObject); begin FQJson := TQJson.Create; FQJson.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'cfg.dat'); Self.Fill.Kind := TBrushKind.Bitmap; InitEvent; FUseGesture := True; end; procedure TFrmTouchBase.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = 27 then begin Key := 0; Self.Close; end; end; procedure TFrmTouchBase.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin FGestureX := X; end; procedure TFrmTouchBase.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); var vTmp: Single; begin if not UseGesture then Exit; vTmp := X - FGestureX; if Abs(vTmp) < 80 then Exit; if vTmp < 0 then actNextPage.Execute else actPriorPage.Execute; end; procedure TFrmTouchBase.InitEvent; var I: Integer; begin // for I := 0 to Self.ComponentCount - 1 do begin if (Self.Components[I] is TRectangle) or (Self.Components[I] is TRoundRect) then begin {$IFNDEF DEBUG} TShape(Self.Components[I]).Stroke.Kind := TBrushKind.None; {$ENDIF} //上一页 if Self.Components[i].Name = 'raPriorPage' then begin TRectangle(Self.Components[I]).OnClick := actPriorPageExecute; TShape(Self.Components[I]).Cursor := crHandPoint; end; //下一页 if Self.Components[i].Name = 'raNextPage' then begin TRectangle(Self.Components[I]).OnClick := actNextPageExecute; TShape(Self.Components[I]).Cursor := crHandPoint; end; //返回 if Self.Components[i].Name = 'raGoBack' then begin TRectangle(Self.Components[I]).OnClick := actGoBackExecute; TShape(Self.Components[I]).Cursor := crHandPoint; end; //打开一个新页面 if Self.Components[I].Tag >= 1000000 then begin TShape(Self.Components[I]).OnClick := actActionExecute; TShape(Self.Components[I]).Cursor := crHandPoint; end; end; OutputDebugString(PWideChar(Format('MS - %s', [Self.Components[I].Name]))); end; end; procedure TFrmTouchBase.LoadImage(AImgName: string); var sImgFile: string; begin try //tcPage.TabIndex := 0; //这句话必须加,因为基类里边设置了TabIndex sImgFile := Format('%s\Image\%s', [ExtractFilePath(ParamStr(0)), AImgName]); if not FileExists(sImgFile) then begin MessageBox(FormToHWND(Self), PWideChar(Format('缺少图片!'#13'%s', [sImgFile])), '提示', MB_ICONWARNING); Exit; end; Self.Fill.Kind := TBrushKind.Bitmap; Self.Fill.Bitmap.Bitmap.LoadFromFile(sImgFile); except on E: Exception do //DebugInf('MS - [%s-LoadImage] fail [%s]', [Self.ClassName, E.Message]); end; end; procedure TFrmTouchBase.SetImgIndex(const Value: Integer); var vJson: TQJson; begin try vJson := FQJson.ForcePath(Format('%d.Imgs', [ID])); if vJson = nil then Exit; if vJson.Count = 0 then Exit; if Value < 0 then Exit; if Value > vJson.Count - 1 then Exit; FImgIndex := Value; LoadImage(vJson[FImgIndex].AsString); except end; end; end.
{ Classes for interpreting the output of svn commands Copyright (C) 2007 Vincent Snijders vincents@freepascal.org This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit SvnCommand; {$mode objfpc}{$H+} interface uses Classes, SysUtils, process, FileUtil; function ExecuteSvnCommand(const Command: string; Output: TStream): integer; function ExecuteSvnCommand(const Command: string): integer; procedure DumpStream(const AStream: TStream); function GetSvnVersionNumber: string; property SvnVersion: string read GetSvnVersionNumber; var SvnExecutable: string; implementation var SvnVersionNumber: string; procedure InitializeSvnVersionNumber; var OutputStream: TStream; FirstDot, SecondDot: integer; begin OutputStream := TMemoryStream.Create; try ExecuteSvnCommand('--version --quiet', OutputStream); SetLength(SvnVersionNumber, OutputStream.Size); OutputStream.Seek(0,soBeginning); OutputStream.Read(SvnVersionNumber[1],Length(SvnVersionNumber)); finally OutputStream.Free; end; end; procedure InitializeSvnExecutable; begin if FileExists(SvnExecutable) then exit; {$IFDEF windows} SvnExecutable := GetEnvironmentVariable('ProgramFiles') + '\Subversion\bin\svn.exe'; {$ENDIF} if not FileExists(SvnExecutable) then SvnExecutable := FindDefaultExecutablePath('svn'); if not FileExists(SvnExecutable) then raise Exception.Create('No svn executable found'); end; function ExecuteSvnCommand(const Command: string; Output: TStream): integer; var SvnProcess: TProcess; function ReadOutput: boolean; // returns true if output was actually read const BufSize = 4096; var Buffer: array[0..BufSize-1] of byte; ReadBytes: integer; begin Result := false; while SvnProcess.Output.NumBytesAvailable>0 do begin ReadBytes := SvnProcess.Output.Read(Buffer, BufSize); Output.Write(Buffer, ReadBytes); Result := true; end; end; function GetOutput: string; begin SetLength(Result, Output.Size); Output.Seek(0,soBeginning); Output.Read(Result[1],Length(Result)); end; begin if SvnExecutable='' then InitializeSvnExecutable; SvnProcess := TProcess.Create(nil); try SvnProcess.CommandLine := SvnExecutable + ' ' + Command; SvnProcess.Options := [poUsePipes]; SvnProcess.ShowWindow := swoHIDE; SvnProcess.Execute; while SvnProcess.Running do begin if not ReadOutput then Sleep(100); end; ReadOutput; Result := SvnProcess.ExitStatus; if Result<>0 then begin Raise Exception.CreateFmt( 'svn %s failed: Result %d' + LineEnding + '%s', [Command, Result, GetOutput]); end; finally SvnProcess.Free; end; end; function ExecuteSvnCommand(const Command: string): integer; var Output: TMemoryStream; begin Output := TMemoryStream.Create; try Result := ExecuteSvnCommand(Command, Output); finally Output.Free; end; end; procedure DumpStream(const AStream: TStream); var lines: TStrings; begin lines := TStringList.Create; AStream.Position := 0; lines.LoadFromStream(AStream); writeln(lines.Text); lines.Free; end; function GetSvnVersionNumber: string; begin if SvnVersionNumber='' then InitializeSvnVersionNumber; Result := SvnVersionNumber; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.1 10/26/2004 11:21:16 PM JPMugaas Updated refs. Rev 1.0 10/21/2004 10:27:32 PM JPMugaas } unit IdFTPListParseWfFTP; { BayNetworks WfFTP FTP Server. WfFTP is a FTP interface for Bay Network's Wellfleet router. } interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListTypes; { WfFTP is a FTP interface for BayNetwork's Wellfleet Routers. Based on: Configuration Guide Contivity Secure IP Services Gateway CG040301 from Nortell Networks Dated March 2004 Notation, the dir format is like this: === Volume - drive 1: Directory of 1: File Name Size Date Day Time ------------------------------------------------------ startup.cfg 2116 03/06/03 Thur. 07:38:50 configPppChap 2996 03/12/03 Wed. 16:43:58 bgpOspf.log 32428 03/20/03 Thur. 13:08:26 an.exe 7112672 03/20/03 Thur. 13:18:09 bcc.help 492551 03/20/03 Thur. 13:21:43 debug.al 12319 03/20/03 Thur. 13:22:46 install.bat 236499 03/20/03 Thur. 13:22:54 ti.cfg 132 03/20/03 Thur. 13:23:09 log2.log 32428 03/20/03 Thur. 14:31:46 configFrRip 386 07/18/03 Fri. 12:02:25 config 1720 07/25/03 Fri. 08:52:00 hosts 17 09/04/03 Thur. 15:56:51 33554432 bytes - Total size 25627726 bytes - Available free space 17672120 bytes - Contiguous free space 226 ASCII Transfer Complete. === === Volume - drive 2: Directory of 2: File Name Size Date Day Time ------------------------------------------------------ config.isp 45016 08/22/97 Fri. 17:05:51 startup.cfg 7472 08/24/97 Sun. 23:31:31 asnboot.exe 237212 08/24/97 Sun. 23:31:41 asndiag.exe 259268 08/24/97 Sun. 23:32:28 debug.al 12372 08/24/97 Sun. 23:33:17 ti_asn.cfg 504 08/24/97 Sun. 23:33:31 install.bat 189114 08/24/97 Sun. 23:33:41 config 50140 04/20/98 Mon. 22:08:01 4194304 bytes - Total size 3375190 bytes - Available free space 3239088 bytes - Contiguous free space ==== From: http://www.insecure.org/sploits/bay-networks.baynets.html } type TIdWfFTPFTPListItem = class(TIdOwnerFTPListItem) end; TIdFTPLPWfFTP = class(TIdFTPListBaseHeader) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function IsHeader(const AData: String): Boolean; override; class function IsFooter(const AData : String): Boolean; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; end; const WFFTP = 'WfFTP'; // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseWfFTP"'*) implementation uses IdFTPCommon, IdGlobal, SysUtils; { TIdFTPLPWfFTP } class function TIdFTPLPWfFTP.GetIdent: String; begin Result := WFFTP; end; class function TIdFTPLPWfFTP.IsFooter(const AData: String): Boolean; var s : TStrings; begin Result := (IndyPos('bytes - Total size', AData) > 1) or {do not localize} (IndyPos('bytes - Contiguous free space', AData) > 1) or {do not localize} (IndyPos('bytes - Available free space', AData) > 1); {do not localize} if not Result then begin s := TStringList.Create; try SplitColumns(AData, s); if s.Count = 6 then begin Result := (s[0] = 'File') and {do not localize} (s[1] = 'Name') and {do not localize} (s[2] = 'Size') and {do not localize} (s[3] = 'Date') and {do not localize} (s[4] = 'Day') and {do not localize} (s[5] = 'Time'); {do not localize} end; finally FreeAndNil(s); end; end; end; class function TIdFTPLPWfFTP.IsHeader(const AData: String): Boolean; begin Result := TextStartsWith(AData, ' Volume - drive ') or TextStartsWith(AData, ' Directory of '); {Do not translate} end; class function TIdFTPLPWfFTP.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdWfFTPFTPListItem.Create(AOwner); end; class function TIdFTPLPWfFTP.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LLine : String; begin Result := True; //we'll assume that this is flat - not unusual in some routers AItem.ItemType := ditFile; //config 50140 04/20/98 Mon. 22:08:01 LLine := AItem.Data; //file name AItem.FileName := Fetch(LLine); //size LLine := TrimLeft(LLine); AItem.Size := IndyStrToInt64(Fetch(LLine), 0); // date LLine := TrimLeft(LLine); AItem.ModifiedDate := DateMMDDYY(Fetch(LLine)); //day of week - discard LLine := TrimLeft(LLine); Fetch(LLine); LLine := TrimLeft(LLine); //time AItem.ModifiedDate := AItem.ModifiedDate + TimeHHMMSS(Fetch(LLine)); end; initialization RegisterFTPListParser(TIdFTPLPWfFTP); finalization UnRegisterFTPListParser(TIdFTPLPWfFTP); end.
Unit: U_BlobImageFB.pas Versão: 1.0 Autor: Enio Rodrigo Marconcini Email: [EMAIL PROTECTED] Msn: [EMAIL PROTECTED] GoogleTalk: [EMAIL PROTECTED] Skype: eniorm DELFOS Desenvolvimento de Sistemas www.delfosdesenvolvimentos.com [EMAIL PROTECTED] ** DESCRICAO ** Unit específica para trabalhar com imagens em banco de dados Firebird/Interbase, utilizando campos BLOB. Funciona com os componentes de acesso IBX (palheta Interbase) e com o Mercury Data Objects (MDO). Não foi testado com outros componentes de acesso. Visa compatibilidade apenas com os citados acima. Suporta arquivos JPEG (*.jpg ou *.jpeg) ou Bitmaps (*.bmp). Imagens Bitmap, antes de serem gravadas no banco, são convertidas em Jpeg e comprensadas pelo procedimento Compress do TJpegImage. Um bitmap de 1.30 Mb fica reduzido a um jpg de cerca de 150 Kb. ** a taxa de compressão varia de acordo com a imagem ** Os códigos para gravar a imagem no campo blob foram copiados de tópicos dos foruns ClubeDelphi (www.clubedelphi.net) Após ter criado esses procedimentos numa unit U_CadastroClientes.pas resolvi criar uma unit somente para manipular imagens. ============================================================================== ** Modus Operandi ** PARA EXIBIR UM CAMPO BLOB COM IMAGEM NUM TImage procedure ExibeFoto(DataSet : TDataSet; BlobFieldName : String; ImageExibicao : TImage); ExibeFoto(qryCliente,'FOTO',Image1); qryCliente - é a query/dataset com os dados 'FOTO' - string com o nome do campo blob Image1 - componente TImage onde será exibido a foto ----- GRAVAR UMA IMAGEM NUM CAMPO BLOB (a query/dataset deve estar com State in [dsEdit,dsInsert] procedure GravaFoto(DataSet : TDataSet; BlobFieldName, FileName : String); GravaFoto(qryCliente,'FOTO','filename.jpg'); qryCliente - é a query/dataset com os dados 'FOTO' - string com o nome do campo blob 'filename' - string com o nome de arquivo jpg ou bmp ** você poderá substituir o 'filename' por: OpenPictureDialog1.FileName ----- EXCLUIR A FOTO DE UM CAMPO BLOB procedure ExcluiFoto(DataSet : TDataSet; BlobFieldName : String); ExcluiFoto(qryCliente,'FOTO'); qryCliente - é a query/dataset com os dados 'FOTO' - string com o nome do campo blob ** para limpar a imagem do TImage: TImage1.Picture := Nil ** ** não coloquei o codigo nessa unit, talvez você poderá não querer que a imagem ** seja limpada do TImage apos ter sido excluida do campo. ----- PARA EXPORTAR UMA IMAGEM DE UM CAMPO BLOB PARA UM ARQUIVO procedure ExportaFoto(DataSet : TDataSet; BlobFieldName, FileName : String; TipoImagem : TTipoImagem); ExportaFoto(qryCliente,'FOTO','filename.jpg',tiJpeg); qryCliente - é a query/dataset com os dados 'FOTO' - string com o nome do campo blob 'filename' - string com o nome de arquivo jpg ou bmp a ser exportado tiJpeg/tiBitmap - tipo do arquivo a ser exportado: Bitmap ou Jpeg ** você poderá substituir o 'filename' por: OpenPictureDialog1.FileName } unit U_BlobImageFB; interface uses Jpeg, Graphics, ExtDlgs, Classes, DB, SysUtils, ExtCtrls, Dialogs, Consts; const OffsetMemoryStream : Int64 = 0; type TTipoImagem = (tiBitmap, tiJpeg); procedure ExibeFoto(DataSet : TDataSet; BlobFieldName : String; ImageExibicao : TImage); procedure GravaFoto(DataSet : TDataSet; BlobFieldName, FileName : String); procedure ExcluiFoto(DataSet : TDataSet; BlobFieldName : String); procedure ExportaFoto(DataSet : TDataSet; BlobFieldName, FileName : String; TipoImagem : TTipoImagem); var MemoryStream : TMemoryStream; Jpg : TJpegImage; Bitmap : TBitmap; implementation procedure ExibeFoto(DataSet : TDataSet; BlobFieldName : String; ImageExibicao : TImage); begin if not(DataSet.IsEmpty) and not((DataSet.FieldByName(BlobFieldName) as TBlobField).IsNull) then try MemoryStream := TMemoryStream.Create; Jpg := TJpegImage.Create; (DataSet.FieldByName(BlobFieldName) as TBlobField).SaveToStream(MemoryStream); MemoryStream.Position := OffsetMemoryStream; Jpg.LoadFromStream(MemoryStream); ImageExibicao.Picture.Assign(Jpg); finally Jpg.Free; MemoryStream.Free; end else // o Else faz com que, caso o campo esteja Null, o TImage seja limpado ImageExibicao.Picture := Nil; end; procedure GravaFoto(DataSet : TDataSet; BlobFieldName, FileName : String); var ext : string; begin if (DataSet.State in [dsEdit,dsInsert]) then begin ext := UpperCase(ExtractFileExt(FileName)); if (ext <> '.BMP') and (ext <> '.JPG') and (ext <> '.JPEG') then begin raise EAccessViolation.Create('Formato de imagem não suportado! Formato suportado: Jpeg ou Bitmap'); Abort; end; try Jpg := TJpegImage.Create; MemoryStream := TMemoryStream.Create; Bitmap := TBitmap.Create; if (ext = '.BMP') then begin Bitmap.LoadFromFile(FileName); Jpg.Assign(Bitmap); Jpg.Compress; end else Jpg.LoadFromFile(FileName); Jpg.SaveToStream(MemoryStream); MemoryStream.Position := OffsetMemoryStream; (DataSet.FieldByName(BlobFieldName) as TBlobField).BlobType := ftTypedBinary; (DataSet.FieldByName(BlobFieldName) as TBlobField).LoadFromStream(MemoryStream); finally MemoryStream.Free; Bitmap.Free; Jpg.Free; end; end; end; procedure ExcluiFoto(DataSet : TDataSet; BlobFieldName : String); begin if (DataSet.State in [dsEdit,dsInsert]) and not((DataSet.FieldByName(BlobFieldName) as TBlobField).IsNull) then (DataSet.FieldByName(BlobFieldName) as TBlobField).Clear; // para limpar o TImage use // Image1.Picture := Nil; end; procedure ExportaFoto(DataSet : TDataSet; BlobFieldName, FileName : string; TipoImagem : TTipoImagem); begin // SERÁ IMPLEMENTADO FUTURAMENTE // ME FALTA TEMPO :) end; end.
unit TickServCore; interface uses System.Types, System.Classes, System.Sysutils, Vcl.ExtCtrls, ProgramSettings, TickServMidware, TTSDirectDaapi; type TTickCoreServer = class private fActive: Boolean; fMidwareServer: TTickMidwareServer; fDaapi: TTTSDirectDaapi; fIdxRunning: Boolean; fAutoDCStart: String; fDataCaddyTimer: TTimer; fJobRunnerTimer: TTimer; procedure DataCaddyTimer(Sender: TObject); procedure JobRunnerTimer(Sender: TObject); procedure WriteLogFile(const aLine: String); procedure WritePausefile(const aLine: String); public constructor Create(const aDirWork, aPort: String); destructor Destroy; override; procedure Start; procedure Stop; property Active: Boolean read fActive; property PrivDaapi: TTTSDirectDaapi read fDaapi; property MidwareServer: TTickMidwareServer read fMidwareServer; end; implementation uses TicklerTypes, FFSUtils; procedure TTickCoreServer.DataCaddyTimer(Sender: TObject); var Diff: TDateTime; DiffInMin: Integer; DcApp: String; begin WriteLogFile('DC Timer'); Diff := Time - StrTotime(fAutoDCStart); DiffInMin := Round(Diff * 24 * 60); if DiffInMin = 0 then begin DcApp := IncludeTrailingBackslash(ExtractFilePath(ParamStr(0))) + 'DCRunner.exe'; if FileExists(DcApp) then begin ExecNewProcess(DcApp, True); WriteLogFile('Auto Datacaddy Run Executed '); end; // wait while datacaddy is done... // reindex if fMidwareServer.ClientCount = 0 then begin // Check if job runner is running if not ProcessExists('JobRunner.exe') then begin fIdxRunning := True; Stop; fDaapi.RepairTables; end else begin WriteLogFile('JobRunner Running - Waiting for job to finish- wrote PauseJR.txt'); // wait till the process finishes... WritePausefile('waiting for JR to close'); while processExists('JobRunner.exe') do WaitSleep(3000); fIdxRunning := True; Stop; fDaapi.RepairTables; if DeleteFile('PauseJR.txt') then WriteLogFile('Deleted PauseJr.txt') else WriteLogFile('Couldnot delete PauseJR.txt -- Jobrunner will not start..'); end; end else WriteLogFile('Users on the system - Reindex could not be Executed '); end; if (fDaapi.InRepair = false) then begin if fIdxRunning = True then begin WriteLogFile('Reindex Executed '); Start; fIdxRunning := false; end; end; end; procedure TTickCoreServer.JobRunnerTimer(Sender: TObject); var JrApp, PauseFile: string; begin WriteLogFile('JR Timer'); JrApp := IncludeTrailingBackslash(ExtractFilePath(ParamStr(0))) + 'JobRunner.exe'; PauseFile := IncludeTrailingBackslash(ExtractFilePath(ParamStr(0))) + 'PauseJR.txt'; if FileExists(JrApp) and not ProcessExists('JobRunner.exe') and not FileExists(PauseFile) and not fIdxRunning then ExecNewProcess(JrApp, False); end; procedure TTickCoreServer.WriteLogFile(const aLine: String); var logFile: TextFile; begin // VG 030718: TODO Add a proper logging library for the app and the server. Something online? MadExcept also? AssignFile(logFile, 'TickLog.txt'); if FileExists('TickLog.txt') then Append(logFile) else Rewrite(logFile); WriteLn(logFile, FormatDateTime('c', Now) + ' Event : ' + aLine); CloseFile(logFile); end; procedure TTickCoreServer.WritePausefile(const aLine: String); var pfile: TextFile; begin // VG 030718: TODO This file used as a flag is unreliable(folder permissions?). Move it to another location or replace with semaphore or something AssignFile(pfile, 'PauseJR.txt'); if FileExists('PauseJR.txt') then Append(pfile) else Rewrite(pfile); WriteLn(pfile, FormatDateTime('c', Now) + ' Event : ' + aLine); CloseFile(pfile); end; constructor TTickCoreServer.Create(const aDirWork, aPort: String); begin inherited Create; WriteLogFile(Format('Core Server created, Dir: %s, Port: %s', [aDirWork, aPort])); fDaapi := TTTSDirectDaapi.Create(nil, aDirWork); fMidwareServer := TTickMidwareServer.Create(Integer(fDaapi), TTSVERSIONCOMPAT); fMidwareServer.Port := aPort; fJobRunnerTimer := TTimer.Create(nil); fJobRunnerTimer.Interval := 300000; fJobRunnerTimer.Enabled := false; fJobRunnerTimer.OnTimer := JobRunnerTimer; fDataCaddyTimer := TTimer.Create(nil); fDataCaddyTimer.Interval := 60000; fDataCaddyTimer.Enabled := false; fDataCaddyTimer.OnTimer := DataCaddyTimer; end; destructor TTickCoreServer.Destroy; begin inherited; fDataCaddyTimer.Free; fJobRunnerTimer.Free; fMidwareServer.Free; fDaapi.Free; end; procedure TTickCoreServer.Start; begin fDaapi.OpenBaseTables; fMidwareServer.Start; fAutoDCStart := fDaapi.GetSetupRecord1.AutoDCStart; fDataCaddyTimer.Enabled := not fAutoDCStart.IsEmpty and FileExists(ExtractFilePath(ParamStr(0)) + 'DCRunner.exe'); fJobRunnerTimer.Enabled := not fDaapi.GetSetupRecord1.DisableJobRunner and FileExists(ExtractFilePath(ParamStr(0)) + 'JobRunner.exe'); fActive := true; end; procedure TTickCoreServer.Stop; begin fMidwareServer.Stop; fDaapi.CloseBaseTables; fDataCaddyTimer.Enabled := false; fJobRunnerTimer.Enabled := false; fActive := false; end; end.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: Arno Garrels <arno.garrels@gmx.de> Creation: Oct 25, 2005 Description: Fast streams for ICS tested on D5 and D7. Version: 6.18 Legal issues: Copyright (C) 2005-2012 by Arno Garrels, Berlin, Germany, contact: <arno.garrels@gmx.de> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. History: Jan 05, 2006 V1.01 F. Piette added missing resourcestring for Delphi 6 Mar 26, 2006 V6.00 F. Piette started new version 6 Jun 26, 2006 V6.01 A. Garrels fixed corrupted data when Mode contained fmOpenWrite. Even in case of fmOpenWrite is set the class needs to be able to read from file to keep it's buffer in sync. Aug 28, 2006 V6.02 Tobias Giesen <tobias_subscriber@tgtools.com> fixed a bug in SetSize. Aug 31, 2006 V6.03 A. Garrels added TMultipartFileReader, a read only file stream capable to merge a custom header as well as a footer with the file. For instance usefull as a HTTP-POST-stream. Aug 31, 2006 V6.04 Do not call SetSize in destroy by A. Garrels. Jun 01, 2007 V6.05 A. Garrels added TTextStream. A very fast stream wrapper, optimized to read and write lines. Methods ReadLn as well as WriteLn benefit from internal buffering as long as the same method is called more than once in sequence, intended as a replacement of ReadLn(TextFile) and WriteLn(TextFile). Jan 22, 2008 V6.06 Angus allow for read file shrinking with fmShareDenyNone Mar 24, 2008 V6.07 Francois Piette made some changes to prepare code for Unicode: TTextStream use AnsiString. Apr 15, 2008 V6.08 A. Garrels, in FBuf of TBufferedFileStream changed to PAnsiChar Aug 27, 2008 V6.09 Arno added a WideString overload to TBufferedFileStream Jan 20, 2009 V6.10 Arno added property Mode to TBufferedFileStream. Apr 17, 2009 V6.11 Arno fixed a bug in TBufferedFileStream that could corrupt data on writes after seeks. Size and Position now behave exactly as TFileStream, this is a fix as well a *Breaking Change*. Fixed some 'false' ERangeErrors when range checking was turned on. New class TIcsBufferedStream is compatible with TBufferedFileStream, it writes a little bit slower than TBufferedFileStream, however contains cleaner code, is hopefully less error prone and can also be used as a stream-wrapper in order to buffer any TStream descendant. New classes TIcsStreamReader and TIcsStreamWriter derived from TIcsBufferedStream ease reading and writing text from/to streams, both are still experimental. Removed plenty of old conditional code. May 03, 2009 V6.12 Arno fixed forced line breaks in TIcsStreamReader. On forced line breaks a multi-byte character code point including UTF-8 will be preserved. Added method ReadToEnd. May 07, 2009 V6.13 TIcsStreamWriter did not convert from ANSI to UTF-7. Note that on forced line breaks (MaxLineLength) TIcsStreamReader may still break UTF-7 code points, however UTF-7 should normally be used only in the context of 7 bit transports, such as e-mail where line length restrictions exist, so setting property MaxLineLength to >= 1024 should work around this issue. Dec 05, 2009 V6.14 Use IcsSwap16Buf() and global code page ID constants. Oct 20, 2010 V6.15 Fixed a bug in TIcsStreamReader.InternalReadLn. Oct 20, 2010 V6.16 Fixed a bug in TIcsStreamReader.ReadLn. Feb 08, 2012 V6.17 Fixed a 64-bit bug and a memory leak in TBufferedFileStream. TIcsBufferedStream, TIcsStreamReader and TIcsStreamWriter removed some default parameter values from constructors, verify that existing code calls the right overload. Mar 31, 2012 V6.18 Fixed TMultiPartFileReader. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsStreams; interface {$Q-} { Disable overflow checking } {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$I OverbyteIcsDefs.inc} {$IFDEF COMPILER14_UP} {$IFDEF NO_EXTENDED_RTTI} {$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])} {$ENDIF} {$ENDIF} {$WARN SYMBOL_PLATFORM OFF} {$WARN SYMBOL_LIBRARY OFF} {$WARN SYMBOL_DEPRECATED OFF} {$I OverbyteIcsDefs.inc} {$ObjExportAll On} { Comment next line in order to replace TBufferedFileStream by TIcsBufferedStream } {$Define USE_OLD_BUFFERED_FILESTREAM} uses Windows, SysUtils, Classes, RTLConsts, Math, OverbyteIcsTypes, // for TBytes OverbyteIcsUtils; resourcestring SFCreateErrorEx = 'Cannot create file "%s". %s'; SFOpenErrorEx = 'Cannot open file "%s". %s'; const DEFAULT_BUFSIZE = 4096; MIN_BUFSIZE = 128; { V6.11 } MAX_BUFSIZE = 1024 * 64; type BigInt = Int64; EBufferedStreamError = class(Exception); TIcsBufferedStream = class; // forward {$IFNDEF USE_OLD_BUFFERED_FILESTREAM} TBufferedFileStream = TIcsBufferedStream; {$ELSE} TBufferedFileStream = class(TStream) private FHandle : {$IFDEF COMPILER16_UP} THandle {$ELSE} Integer {$ENDIF}; FFileSize : BigInt; FFileOffset : BigInt; FBuf : TBytes; { V6.11 } FBufSize : Longint; FBufCount : Longint; FBufPos : Longint; FDirty : Boolean; FMode : Word; protected procedure SetSize(NewSize: Longint); override; procedure SetSize(const NewSize: Int64); override; function GetFileSize: BigInt; procedure Init(BufSize: Longint); procedure ReadFromFile; procedure WriteToFile; public constructor Create(const FileName: String; Mode: Word; BufferSize: Longint); overload; constructor Create(const FileName: WideString; Mode: Word; BufferSize: Longint); overload; constructor Create(const FileName: String; Mode: Word; Rights: Cardinal; BufferSize: Longint); overload; constructor Create(const FileName: WideString; Mode: Word; Rights: Cardinal; BufferSize: Longint); overload; destructor Destroy; override; procedure Flush; function Read(var Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; function Write(const Buffer; Count: Longint): Longint; override; property FastSize : BigInt read FFileSize; property Mode : Word read FMode; end; {$ENDIF USE_OLD_BUFFERED_FILESTREAM} EMultiPartFileReaderException = class(Exception); { Read only file stream capable to merge a custom header as well as a footer } { with the file. For instance usefull as a HTTP-POST-stream. } TMultiPartFileReader = class(TFileStream) private FHeader : RawByteString; FFooter : RawByteString; FFooterLen : Integer; FHeaderLen : Integer; FCurrentPos : BigInt; FFileSize : BigInt; FTotSize : BigInt; function GetFooter: String; function GetHeader: String; protected function GetSize: Int64; override; public {$IFDEF UNICODE} constructor Create(const FileName: String; const Header, Footer: RawByteString) overload; {$ENDIF} constructor Create(const FileName: String; const Header, Footer: String {$IFDEF UNICODE}; AStringCodePage: LongWord = CP_ACP {$ENDIF}); overload; constructor Create(const FileName: String; Mode: Word; const Header, Footer: String {$IFDEF UNICODE}; AStringCodePage: LongWord = CP_ACP {$ENDIF}); overload; constructor Create(const FileName: String; Mode: Word; Rights: Cardinal; const Header, Footer: String {$IFDEF UNICODE}; AStringCodePage: LongWord = CP_ACP {$ENDIF}); overload; procedure SetSize(const NewSize: Int64); override; function Seek(Offset: Longint; Origin: Word): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; property Header : String read GetHeader; property Footer : String read GetFooter; end; TTextStreamMode = (tsmReadLn, tsmWriteLn, tsmRead, tsmWrite); TTextStream = class(TStream) private FStream : TStream; FBuf : array of AnsiChar; TF : TextFile; FMode : TTextStreamMode; procedure SetRealPos; procedure SetMode(NewMode: TTextStreamMode); protected procedure SetSize(const NewSize: Int64); override; public constructor Create(AStream : TStream; BufferSize : Integer = 256 ; Style: TTextLineBreakStyle = tlbsCRLF); destructor Destroy; override; procedure Flush; function ReadLn: Boolean; overload; function ReadLn(var S: AnsiString): Boolean; overload; function ReadLn(var WS: WideString): Boolean; overload; procedure WriteLn(const S: AnsiString); overload; procedure WriteLn(const WS: WideString); overload; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; end; { .todo a base stream wrapper class TIcsStreamWrapper to derive } { TIcsBufferedStream from. } TIcsBufferedStream = class(TStream) private FStream : TStream; FOwnsStream : Boolean; FBuffer : TBytes; FBufferSize : Integer; FBufferedDataSize : Integer; // Number of bytes currently buffered FDirtyCount : Integer; // Range of dirty bytes in buffer counted from buffer index zero FStreamBufPos : Int64; // First byte of the buffer in stream FPosition : Int64; // Helper var, partly calculated FFastSize : Int64; // Size of FStream at the time IsReadOnly is set to TRUE. See property IsReadOnly below FIsReadOnly : Boolean; // See property IsReadOnly below protected procedure SetIsReadOnly(const Value: Boolean); procedure SetSize(NewSize: Integer); override; procedure SetSize(const NewSize: Int64); override; function InternalGetSize: Int64; {$IFDEF USE_INLINE} inline;{$ENDIF} function GetSize: Int64; override; procedure Init; virtual; function FillBuffer: Boolean; {$IFDEF USE_INLINE} inline;{$ENDIF} public constructor Create; overload; // Dummy, don't call! constructor Create(Stream : TStream; BufferSize : Integer; OwnsStream : Boolean = FALSE); overload; virtual; constructor Create(const FileName : String; Mode : Word; Rights : Cardinal; BufferSize : Integer); overload; virtual; constructor Create(const FileName : WideString; Mode : Word; Rights : Cardinal; BufferSize : Integer); overload; virtual; constructor Create(const FileName: String; Mode: Word; BufferSize: Integer); overload; virtual; constructor Create(const FileName: WideString; Mode: Word; BufferSize: Integer); overload; virtual; destructor Destroy; override; procedure Flush; {$IFDEF USE_INLINE} inline;{$ENDIF} function Read(var Buffer; Count: Integer): Integer; override; function Seek(Offset: Integer; Origin: Word): Integer; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; function Write(const Buffer; Count: Integer): Integer; override; { Set IsReadOnly if you are sure you will never write to the stream } { and nobody else will do, this speeds up getter Size and in turn } { Seeks as well. IsReadOnly is set to TRUE if a constructor with } { filename is called with a read only mode and a share lock. } property IsReadOnly: Boolean read FIsReadOnly write SetIsReadOnly; property FastSize: Int64 read GetSize; // For compatibility with old TBufferedFileStream; end; EStreamReaderError = class(Exception); TIcsLineBreakStyle = (ilbsCRLF, ilbsLF, ilbsCR); TIcsStreamReader = class(TIcsBufferedStream) private FReadBuffer : TBytes; FReadBufSize : Integer; FCodePage : LongWord; FLeadBytes : set of AnsiChar; FDetectBOM : Boolean; { Max. number of chars (elements) forcing a new line even though } { none of the break chars was found. Note that this value is not } { accurate since multi-byte code points including UTF-8 will be } { preserved. Default = 2048 } FMaxLineLength : Integer; function InternalReadLn: Boolean; function InternalReadLnWLe: Boolean; function InternalReadLnWBe: Boolean; procedure EnsureReadBufferW(Size: Integer; var P: PWideChar); {$IFDEF USE_INLINE} inline;{$ENDIF} procedure EnsureReadBufferA(Size: Integer; var P: PAnsiChar); {$IFDEF USE_INLINE} inline;{$ENDIF} procedure SetMaxLineLength(const Value: Integer); procedure SetCodePage(const Value : LongWord); protected function GetCodePageFromBOM: LongWord; virtual; procedure Init; override; public constructor Create(Stream : TStream; BufferSize : Integer = DEFAULT_BUFSIZE; OwnsStream : Boolean = FALSE); override; constructor Create(Stream : TStream; DetectBOM : Boolean = FALSE; CodePage : LongWord = CP_ACP; OwnsStream : Boolean = FALSE; BufferSize : Integer = DEFAULT_BUFSIZE); overload; constructor Create(const FileName : String; Mode : Word; BufferSize : Integer = DEFAULT_BUFSIZE); override; constructor Create(const FileName : String; DetectBOM : Boolean = TRUE; CodePage : LongWord = CP_ACP; BufferSize : Integer = DEFAULT_BUFSIZE); overload; constructor Create(const FileName : WideString; Mode : Word; BufferSize : Integer = DEFAULT_BUFSIZE); override; constructor Create(const FileName : WideString; DetectBOM : Boolean = TRUE; CodePage : LongWord = CP_ACP; BufferSize : Integer = DEFAULT_BUFSIZE); overload; function DetectLineBreakStyle: TIcsLineBreakStyle; function ReadLine(var S: RawByteString): Boolean; overload; virtual; function ReadLine(var S: UnicodeString): Boolean; overload; virtual; procedure ReadToEnd(var S: RawByteString); overload; virtual; procedure ReadToEnd(var S: UnicodeString); overload; virtual; property CurrentCodePage: LongWord read FCodePage write SetCodePage; property MaxLineLength: Integer read FMaxLineLength write SetMaxLineLength; end; TIcsStreamWriter = class(TIcsBufferedStream) private FWriteBuffer : TBytes; // For charset conversion FWriteBufSize : Integer; FReadBuffer : TBytes; // For charset conversion FReadBufSize : Integer; FLineBreakStyle : TIcsLineBreakStyle; FCodePage : LongWord; FLineBreak : AnsiString; procedure SetLineBreakStyle(Value: TIcsLineBreakStyle); procedure EnsureWriteBuffer(Size: Integer); {$IFDEF USE_INLINE} inline; {$ENDIF} procedure EnsureReadBuffer(Size: Integer); {$IFDEF USE_INLINE} inline; {$ENDIF} protected function GetBomFromCodePage(ACodePage: LongWord) : TBytes; virtual; function GetCodePageFromBOM: LongWord; virtual; procedure Init; override; public constructor Create(Stream : TStream; BufferSize : Integer = DEFAULT_BUFSIZE; OwnsStream : Boolean = FALSE); override; constructor Create(Stream : TStream; Append : Boolean = TRUE; DetectBOM : Boolean = FALSE; CodePage : LongWord = CP_ACP; OwnsStream : Boolean = FALSE; BufferSize : Longint = DEFAULT_BUFSIZE); overload; constructor Create(const FileName : String; Mode : Word; Rights : Cardinal; BufferSize : Integer); override; constructor Create(const FileName : String; Append : Boolean = TRUE; DetectBOM : Boolean = TRUE; CodePage : LongWord = CP_ACP; BufferSize : Integer = DEFAULT_BUFSIZE); overload; constructor Create(const FileName : WideString; Mode : Word; Rights : Cardinal; BufferSize : Integer); override; constructor Create(const FileName : WideString; Append : Boolean = TRUE; DetectBOM : Boolean = TRUE; CodePage : LongWord = CP_ACP; BufferSize : Integer = DEFAULT_BUFSIZE); overload; function DetectLineBreakStyle: TIcsLineBreakStyle; procedure Write(const S : UnicodeString); reintroduce; overload; virtual; procedure Write(const S : RawByteString; SrcCodePage : LongWord = CP_ACP); reintroduce; overload; virtual; { procedure Write(Value: Boolean); reintroduce; overload; procedure Write(Value: WideChar); reintroduce; overload; procedure Write(Value: AnsiChar); reintroduce; overload; .. } procedure WriteLine(const S : UnicodeString); overload; {$IFDEF USE_INLINE} inline; {$ENDIF} procedure WriteLine(const S : RawByteString; SrcCodePage : LongWord = CP_ACP); overload; {$IFDEF USE_INLINE} inline; {$ENDIF} procedure WriteBOM; property CurrentCodePage : LongWord read FCodePage write FCodePage; property LineBreakStyle : TIcsLineBreakStyle read FLineBreakStyle write SetLineBreakStyle; end; implementation {$IFOPT R+} { V6.11 } {$DEFINE SETRANGECHECKSBACK} { We'll turn off range checking temporarily } {$ENDIF} type TDummyByteArray = array [0..0] of Byte; { Casts require range checks OFF }{ V6.11 } const {$IFDEF COMPILER16_UP} ICS_INVALID_FILE_HANDLE = INVALID_HANDLE_VALUE; {$ELSE} ICS_INVALID_FILE_HANDLE = -1; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure CheckAddFileModeReadWrite(var AMode: Word); {$IFDEF USE_INLINE} inline; {$ENDIF} var LSMode, LOMode: Word; begin LOMode := AMode and 3; if LOMode = fmOpenWrite then begin LSMode := AMode and $F0; AMode := fmOpenReadWrite or LSMode; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function IsFileModeReadOnly(AMode: Word): Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} var LOMode: Word; LSMode: Word; begin LOMode := AMode and 3; LSMode := AMode and $F0; Result := (AMode and fmCreate <> fmCreate) and (LOMode = fmOpenRead) and ((LSMode = fmShareDenyWrite) or (LSMode = fmShareExclusive)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF USE_OLD_BUFFERED_FILESTREAM} procedure TBufferedFileStream.Init(BufSize: Longint); begin FBufSize := BufSize; if FBufSize < MIN_BUFSIZE then FBufsize := MIN_BUFSIZE else if FBufSize > MAX_BUFSIZE then FBufSize := MAX_BUFSIZE else FBufSize := (BufSize div MIN_BUFSIZE) * MIN_BUFSIZE; { V6.11 } SetLength(FBuf, FBufSize); FFileSize := GetFileSize; FBufCount := 0; FFileOffset := 0; FBufPos := 0; FDirty := False; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TBufferedFileStream.Create(const FileName: String; Mode: Word; BufferSize: Longint); begin Create(Filename, Mode, 0, BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TBufferedFileStream.Create(const FileName : String; Mode: Word; Rights: Cardinal; BufferSize: Longint); {$IFDEF COMPILER16_UP} var LMode: Word; {$ENDIF} begin inherited Create; FHandle := ICS_INVALID_FILE_HANDLE; FBuf := nil; //FmWriteFlag := FALSE; { V1.04 } if Mode and fmCreate = fmCreate then begin {$IFDEF COMPILER16_UP} LMode := Mode and $FF; if LMode = $FF then LMode := fmShareExclusive; {$ENDIF} FHandle := FileCreate(FileName, {$IFDEF COMPILER16_UP} LMode, {$ENDIF} Rights); if FHandle = ICS_INVALID_FILE_HANDLE then raise EFCreateError.CreateResFmt(@SFCreateErrorEx, [ExpandFileName(FileName), SysErrorMessage(GetLastError)]); end else begin { Even in mode fmOpenWrite we need to read from file as well } CheckAddFileModeReadWrite(Mode); FHandle := FileOpen(FileName, Mode); if FHandle = ICS_INVALID_FILE_HANDLE then raise EFOpenError.CreateResFmt(@SFOpenErrorEx, [ExpandFileName(FileName), SysErrorMessage(GetLastError)]); end; FMode := Mode; Init(BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TBufferedFileStream.Create(const FileName: WideString; Mode: Word; BufferSize: Longint); begin Create(Filename, Mode, 0, BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TBufferedFileStream.Create(const FileName : WideString; Mode: Word; Rights: Cardinal; BufferSize: Longint); begin inherited Create; FHandle := ICS_INVALID_FILE_HANDLE; FBuf := nil; if Mode and fmCreate = fmCreate then begin FHandle := IcsFileCreateW(FileName, Rights); if FHandle = ICS_INVALID_FILE_HANDLE then raise EFCreateError.CreateResFmt(@SFCreateErrorEx, [ExpandFileName(FileName), SysErrorMessage(GetLastError)]); end else begin { Even in mode fmOpenWrite we need to read from file as well } CheckAddFileModeReadWrite(Mode); FHandle := IcsFileOpenW(FileName, Mode); if FHandle = ICS_INVALID_FILE_HANDLE then raise EFOpenError.CreateResFmt(@SFOpenErrorEx, [ExpandFileName(FileName), SysErrorMessage(GetLastError)]); end; FMode := Mode; Init(BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TBufferedFileStream.Destroy; begin if FHandle <> ICS_INVALID_FILE_HANDLE then begin if FDirty then WriteToFile; FileClose(FHandle); end; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TBufferedFileStream.GetFileSize: BigInt; var OldPos : BigInt; begin OldPos := FileSeek(FHandle, Int64(0), sofromCurrent); Result := FileSeek(FHandle, Int64(0), sofromEnd); FileSeek(FHandle, OldPos, sofromBeginning); if Result < 0 then raise EBufferedStreamError.Create('Cannot determine correct file size'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TBufferedFileStream.ReadFromFile; begin if FileSeek(FHandle, FFileOffset, sofromBeginning) <> FFileOffset then raise EBufferedStreamError.Create('Seek before read from file failed'); FBufCount := FileRead(FHandle, FBuf[0], FBufSize); if FBufCount = -1 then raise EBufferedStreamError.Create(SysErrorMessage(GetLastError)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TBufferedFileStream.WriteToFile; begin if FileSeek(FHandle, FFileOffset, soFromBeginning) <> FFileOffset then raise EBufferedStreamError.Create('Seek before write to file failed'); if FileWrite(FHandle, FBuf[0], FBufCount) <> FBufCount then raise EBufferedStreamError.Create('Could not write to file'); {$IFDEF DEBUG} //FillChar(FBuf[0], FBufCount, #0); {$ENDIF} FDirty := False; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TBufferedFileStream.Flush; begin if FDirty and (FHandle <> ICS_INVALID_FILE_HANDLE) and (FBuf <> nil) then WriteToFile; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$R-} { V6.11 } function TBufferedFileStream.Read(var Buffer; Count: Longint): Longint; var Remaining : Longint; Copied : Longint; DestPos : Longint; begin Result := 0; if FHandle = ICS_INVALID_FILE_HANDLE then Exit; Remaining := Min(Count, FFileSize - (FFileOffset + FBufPos)); Result := Remaining; if (Remaining > 0) then begin if (FBufCount = 0) then ReadFromFile; Copied := Min(Remaining, FBufCount - FBufPos); Move(FBuf[FBufPos], TDummyByteArray(Buffer)[0], Copied); { V6.11 } Inc(FBufPos, Copied); Dec(Remaining, Copied); DestPos := 0; while Remaining > 0 do begin if FDirty then WriteToFile; FBufPos := 0; Inc(FFileOffset, FBufSize); ReadFromFile; Inc(DestPos, Copied); Copied := Min(Remaining, FBufCount - FBufPos); if Copied <= 0 then break; { V6.06 angus, nothing more to read, break loop } Move(FBuf[FBufPos], TDummyByteArray(Buffer)[DestPos], Copied); { V6.11 } Inc(FBufPos, Copied); Dec(Remaining, Copied); end; end; end; {$IFDEF SETRANGECHECKSBACK} { V6.11 } {$R+} {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$R-} { V6.11 } function TBufferedFileStream.Write(const Buffer; Count: Longint): Longint; var Remaining : Longint; Copied : Longint; DestPos : Longint; begin Result := 0; if FHandle = ICS_INVALID_FILE_HANDLE then Exit; Remaining := Count; Result := Remaining; if (Remaining > 0) then begin if (FBufCount = 0) and ((FFileOffset {+ FBufPos} ) <= FFileSize) then { V6.11 } ReadFromFile; Copied := Min(Remaining, FBufSize - FBufPos); Move(TDummyByteArray(Buffer)[0], FBuf[FBufPos], Copied); { V6.11 } FDirty := True; Inc(FBufPos, Copied); if (FBufCount < FBufPos) then begin FBufCount := FBufPos; FFileSize := FFileOffset + FBufPos; end; Dec(Remaining, Copied); DestPos := 0; while Remaining > 0 do begin WriteToFile; FBufPos := 0; Inc(FFileOffset, FBufSize); if (FFileOffset < FFileSize) then ReadFromFile else FBufCount := 0; Inc(DestPos, Copied); Copied := Min(Remaining, FBufSize - FBufPos); if Copied <= 0 then break; { V6.06 angus, nothing more to read, break loop } Move(TDummyByteArray(Buffer)[DestPos], FBuf[0], Copied); { V6.11 } FDirty := True; Inc(FBufPos, Copied); if (FBufCount < FBufPos) then begin FBufCount := FBufPos; FFileSize := FFileOffset + FBufPos; end; Dec(Remaining, Copied); end; end; end; {$IFDEF SETRANGECHECKSBACK} { V6.11 } {$R+} {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TBufferedFileStream.Seek(Offset: Longint; Origin: Word): Longint; begin Result := Seek(Int64(Offset), TSeekOrigin(Origin)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TBufferedFileStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; var NewPos : BigInt; NewFileOffset : BigInt; begin Result := 0; if FHandle = ICS_INVALID_FILE_HANDLE then Exit; {if (Offset = 0) and (Origin = soCurrent) then begin V6.11 Result := FFileOffset + FBufPos; Exit; end;} case Origin of soBeginning : NewPos := Offset; soCurrent : NewPos := (FFileOffset + FBufPos) + Offset; soEnd : NewPos := FFileSize + Offset; else NewPos := -1; { V6.11 } end; if (NewPos < 0) then begin //NewPos := 0; { V6.11 } Result := -1; { V6.11 } Exit; end; {else if (NewPos > FFileSize) then // FileSeek now called in SetSize() V6.11 FFileSize := FileSeek(FHandle, NewPos - FFileSize, soFromEnd);} NewFileOffset := (NewPos div FBufSize) * FBufSize; if (NewFileOffset <> FFileOffset) then begin if FDirty then WriteToFile; FFileOffset := NewFileOffset; FBufCount := 0; end; FBufPos := NewPos - FFileOffset; Result := NewPos; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TBufferedFileStream.SetSize(NewSize: Integer); begin SetSize(Int64(NewSize)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TBufferedFileStream.SetSize(const NewSize: Int64); var NSize : Int64; { V6.11 } begin if FHandle = ICS_INVALID_FILE_HANDLE then Exit; Seek(NewSize, {sofromBeginning} soBeginning); {TG 08/28/2006} { V1.03 } // if NewSize < FFileSize then { V6.11 } NSize := FileSeek(FHandle, NewSize, soFromBeginning); { V6.11 } //{$IFDEF MSWINDOWS} { V6.11 } if not SetEndOfFile(FHandle) then raise EBufferedStreamError.Create(sStreamSetSize); { V6.17 } if NSize >= 0 then { V6.11 } FFileSize := NSize; { V6.11 } (*{$ELSE} { V6.11 } if ftruncate(FHandle, Position) = -1 then raise EStreamError(sStreamSetSize); {$ENDIF}*) end; {$ENDIF USE_OLD_BUFFERED_FILESTREAM} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { TMultiPartFileReader } {$IFDEF UNICODE} constructor TMultiPartFileReader.Create(const FileName: String; const Header, Footer: RawByteString); begin inherited Create(FileName, fmOpenRead or fmShareDenyNone); FHeader := Header; FFooter := Footer; FFooterLen := Length(FFooter); FHeaderLen := Length(FHeader); FCurrentPos := 0; FFileSize := inherited Seek(0, soEnd); FTotSize := FHeaderLen + FFileSize + FFooterLen; inherited Seek(0, soBeginning); end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TMultiPartFileReader.Create(const FileName: String; const Header, Footer: String {$IFDEF UNICODE}; AStringCodePage: LongWord = CP_ACP {$ENDIF}); begin Create(Filename, fmOpenRead or fmShareDenyWrite, Header, Footer {$IFDEF UNICODE}, AStringCodePage {$ENDIF}); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TMultiPartFileReader.Create(const FileName: String; Mode: Word; const Header, Footer: String {$IFDEF UNICODE}; AStringCodePage: LongWord = CP_ACP {$ENDIF}); begin {$IFDEF POSIX} Create(Filename, Mode, FileAccessRights, Header, Footer, AStringCodePage); {$ENDIF} {$IFDEF MSWINDOWS} Create(Filename, Mode, 0, Header, Footer {$IFDEF UNICODE}, AStringCodePage {$ENDIF}); {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TMultiPartFileReader.Create(const FileName: String; Mode: Word; Rights: Cardinal; const Header, Footer: String {$IFDEF UNICODE}; AStringCodePage: LongWord = CP_ACP {$ENDIF}); begin if (Mode and fmOpenWrite <> 0) or (Mode and fmOpenReadWrite <> 0) then raise EMultiPartFileReaderException.Create('Invalid open mode'); inherited Create(FileName, Mode, Rights); {$IFDEF UNICODE} FHeader := UnicodeToAnsi(Header, AStringCodePage, True); FFooter := UnicodeToAnsi(Footer, AStringCodePage, True); {$ELSE} FHeader := Header; FFooter := Footer; {$ENDIF} FFooterLen := Length(FFooter); FHeaderLen := Length(FHeader); FCurrentPos := 0; FFileSize := inherited Seek(0, soEnd); FTotSize := FHeaderLen + FFileSize + FFooterLen; inherited Seek(0, soBeginning); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMultiPartFileReader.GetFooter: String; begin {$IFDEF UNICODE} Result := UnicodeString(FFooter); {$ELSE} Result := FFooter; {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMultiPartFileReader.GetHeader: String; begin {$IFDEF UNICODE} Result := UnicodeString(FHeader); {$ELSE} Result := FHeader; {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMultiPartFileReader.GetSize: Int64; begin Result := FTotSize; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultiPartFileReader.SetSize(const NewSize: Int64); begin raise EMultiPartFileReaderException.Create('Class is read only'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMultiPartFileReader.Read(var Buffer; Count: Integer): Longint; var ToRead : Integer; FooterPos : Integer; POutBuf : PAnsiChar; begin Result := 0; if (Count <= 0) or (FCurrentPos >= FTotSize) then Exit; POutBuf := @Buffer; if FCurrentPos < FHeaderLen then begin ToRead := FHeaderLen - FCurrentPos; if Count < ToRead then ToRead := Count; Move(FHeader[FCurrentPos + 1], POutBuf[0], ToRead); Inc(Result, ToRead); Inc(FCurrentPos, ToRead); Dec(Count, ToRead); end; if (Count > 0) and (FCurrentPos < FHeaderLen + FFileSize) then begin ToRead := inherited Read(POutBuf[Result], Count); Inc(Result, ToRead); Inc(FCurrentPos, ToRead); Dec(Count, ToRead); end; if (Count > 0) and (FCurrentPos >= FHeaderLen + FFileSize) and (FCurrentPos < FTotSize) then begin FooterPos := FCurrentPos - (FHeaderLen + FFileSize); ToRead := FTotSize - FCurrentPos; if ToRead > Count then ToRead := Count; Move(FFooter[FooterPos + 1], POutBuf[Result], ToRead); Inc(Result, ToRead); Inc(FCurrentPos, ToRead); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMultiPartFileReader.Write(const Buffer; Count: Integer): Longint; begin Result := 0; // Read only! end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMultiPartFileReader.Seek(Offset: Integer; Origin: Word): Longint; begin Result := Seek(Int64(Offset), TSeekOrigin(Origin)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMultiPartFileReader.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; var NewPos : Int64; begin case Origin of soBeginning : if Offset < 0 then NewPos := 0 else NewPos := Offset; soCurrent : NewPos := FCurrentPos + Offset; soEnd : NewPos := (FFileSize + FFooterLen + FHeaderLen) + Offset; else raise EMultiPartFileReaderException.Create('Invalid seek origin'); end; if NewPos < 0 then NewPos := 0; if NewPos <> FCurrentPos then begin if NewPos > FHeaderLen then begin if NewPos <= (FHeaderLen + FFileSize) then inherited Seek(NewPos - FHeaderLen , soBeginning) else if NewPos >= (FHeaderLen + FFileSize + FFooterLen) then begin inherited Seek(NewPos - FHeaderLen - FFooterLen, soBeginning); NewPos := FHeaderLen + FFileSize + FFooterLen; end else inherited Seek(NewPos - FHeaderLen, soBeginning); end else inherited Seek(0, soBeginning); end; FCurrentPos := NewPos; Result := NewPos; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { TTextStream } type { 32 bytes max } TTextStreamUserData = record Stream : TStream; StreamPos : BigInt; end; PTextStreamUserData = ^TTextStreamUserData; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TextStreamDummy(var TR: TTextRec ): Integer; begin Result := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetTextStream(var TR: TTextRec): TStream; begin Result := PTextStreamUserData(@TR.Userdata)^.Stream; if Result = nil then raise Exception.Create('Stream not assigned'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TextStreamIn(var TR: TTextRec): Integer; begin Result := 0; TR.BufEnd := GetTextStream(TR).Read(TR.BufPtr^, TR.BufSize); Inc(PTextStreamUserData(@TR.Userdata)^.StreamPos, TR.BufEnd); TR.BufPos := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TextStreamOut(var TR: TTextRec): Integer; var Len : Cardinal; begin Result := 0; if TR.BufPos > 0 then begin Len := GetTextStream(TR).Write(TR.BufPtr^, TR.BufPos); if Len <> TR.BufPos then Result := GetLastError; Inc(PTextStreamUserData(@TR.Userdata)^.StreamPos, Len); TR.BufPos := TR.BufPos - Len; if Result <> 0 then raise Exception.Create(SWriteError + ' ' + SysErrorMessage(Result)); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TextStreamFlushOut(var TR: TTextRec): Integer; begin Result := TextStreamOut(TR); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TTextStream.Create( AStream : TStream; BufferSize : Integer; Style : TTextLineBreakStyle); var UData : TTextStreamUserData; begin inherited Create; FStream := AStream; if not Assigned(FStream) then raise Exception.Create('Stream not assigned'); // FStream.Position := 0; FillChar(TTextRec(TF), Sizeof(TFileRec), #0); with TTextRec(TF) do begin { Init TextRec and put it into input mode } Mode := fmInput; InOutFunc := @TextStreamIn; FlushFunc := @TextStreamDummy; //BufPos := 0; //BufEnd := 0; Flags := (Flags and not tfCRLF) or (tfCRLF * Byte(Style)); OpenFunc := @TextStreamDummy; CloseFunc := @TextStreamDummy; //Name[0] := #0; {Set and allocate buffer } BufSize := BufferSize; if BufSize < SizeOf(Buffer) then BufSize := SizeOf(Buffer) else if BufSize mod SizeOf(Buffer) <> 0 then BufSize := ((BufSize div SizeOf(Buffer)) * SizeOf(Buffer)); if BufSize > SizeOf(Buffer) then begin SetLength(FBuf, BufSize); BufPtr := PAnsiChar(FBuf); end else begin BufSize := SizeOf(Buffer); BufPtr := @Buffer; end; { Userdata } UData.Stream := FStream; UData.StreamPos := 0; Move(UData, Userdata, Sizeof(UData)); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TTextStream.Destroy; begin try System.CloseFile(TF); finally SetLength(FBuf, 0); inherited Destroy; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTextStream.SetRealPos; begin PTextStreamUserData(@TTextRec(TF).UserData)^.StreamPos := FStream.Seek(- BigInt(TTextRec(TF).BufSize - TTextRec(TF).BufPos), soCurrent); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTextStream.SetMode(NewMode: TTextStreamMode); begin if (FMode = NewMode) then Exit; case NewMode of tsmReadLn : with TTextRec(TF) do begin if FMode = tsmWriteLn then System.Flush(TF); Mode := fmInput; InOutFunc := @TextStreamIn; FlushFunc := @TextStreamDummy; BufPos := 0; BufEnd := 0; end; tsmWriteLn : with TTextRec(TF) do begin if FMode = tsmReadLn then SetRealPos; Mode := fmOutput; InOutFunc := @TextStreamOut; FlushFunc := @TextStreamFlushOut; BufPos := 0; BufEnd := 0; end; tsmWrite, tsmRead : if FMode = tsmReadLn then SetRealPos else if FMode = tsmWriteLn then System.Flush(TF); end; FMode := NewMode end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTextStream.ReadLn : Boolean; begin SetMode(tsmReadLn); if not System.Eof(TF) then begin System.ReadLn(TF); Result := TRUE; end else Result := FALSE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTextStream.ReadLn(var S: AnsiString): Boolean; begin SetMode(tsmReadLn); if not System.Eof(TF) then begin System.ReadLn(TF, S); Result := TRUE; end else Result := FALSE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTextStream.ReadLn(var WS: WideString): Boolean; begin SetMode(tsmReadLn); if not System.Eof(TF) then begin System.ReadLn(TF, WS); Result := TRUE; end else Result := FALSE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTextStream.WriteLn(const S: AnsiString); begin SetMode(tsmWriteLn); System.Writeln(TF, S); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTextStream.WriteLn(const WS: WideString); begin SetMode(tsmWriteLn); System.Writeln(TF, WS); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTextStream.Read(var Buffer; Count: Integer): Longint; begin SetMode(tsmRead); Result := FStream.Read(Buffer, Count) end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTextStream.Write(const Buffer; Count: Integer): Longint; begin SetMode(tsmWrite); Result := FStream.Write(Buffer, Count); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTextStream.Seek(Offset: Longint; Origin: Word): Longint; begin Result := Seek(Int64(Offset), TSeekOrigin(Origin)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TTextStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin SetMode(tsmRead); Result := FStream.Seek(Offset, Origin); PTextStreamUserData(@TTextRec(TF).UserData)^.StreamPos := Result; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTextStream.SetSize(const NewSize: Int64); begin FStream.Size := NewSize; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TTextStream.Flush; begin if FMode = tsmWriteLn then System.Flush(TF); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { TIcsBufferedStream } {$IFDEF MSWINDOWS} var FileAccessRights : Cardinal = 0; {$ENDIF} constructor TIcsBufferedStream.Create(Stream: TStream; BufferSize: Longint; OwnsStream: Boolean = FALSE); begin inherited Create; Assert(Stream <> nil, 'Stream must be assigned'); FStream := Stream; FOwnsStream := OwnsStream; FBufferSize := BufferSize; Init; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsBufferedStream.Create; begin Create(nil, 0); // dummy! end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsBufferedStream.Create(const FileName: String; Mode: Word; BufferSize: Integer); begin Create(FileName, Mode, FileAccessRights, BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsBufferedStream.Create(const FileName: WideString; Mode: Word; BufferSize: Integer); begin Create(FileName, Mode, FileAccessRights, BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsBufferedStream.Create(const FileName: String; Mode: Word; Rights: Cardinal; BufferSize: Integer); begin inherited Create; { Even in mode fmOpenWrite we need to read from file as well } CheckAddFileModeReadWrite(Mode); FStream := TFileStream.Create(FileName, Mode, Rights); FBufferSize := BufferSize; FOwnsStream := True; IsReadOnly := IsFileModeReadOnly(Mode); Init; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsBufferedStream.Create(const FileName: WideString; Mode: Word; Rights: Cardinal; BufferSize: Integer); begin inherited Create; { Even in mode fmOpenWrite we need to read from file as well } CheckAddFileModeReadWrite(Mode); FStream := TIcsFileStreamW.Create(FileName, Mode, Rights); FBufferSize := BufferSize; FOwnsStream := True; IsReadOnly := IsFileModeReadOnly(Mode); Init; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TIcsBufferedStream.Destroy; begin Flush; if FOwnsStream then FreeAndNil(FStream); inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferedStream.Flush; begin if FDirtyCount > 0 then begin FStream.Position := FStreamBufPos; FStream.WriteBuffer(FBuffer[0], FDirtyCount); FDirtyCount := 0; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferedStream.Init; begin if FBufferSize < MIN_BUFSIZE then FBufferSize := MIN_BUFSIZE else if FBufferSize > MAX_BUFSIZE then FBufferSize := MAX_BUFSIZE else FBufferSize := (FBufferSize div MIN_BUFSIZE) * MIN_BUFSIZE; SetLength(FBuffer, FBufferSize); FPosition := FStream.Position; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferedStream.Read(var Buffer; Count: Integer): Longint; var BufPos : Integer; SrcIndex : Integer; Remaining: Integer; begin Result := Count; while Count > 0 do begin if not ((FStreamBufPos <= FPosition) and (FPosition < (FStreamBufPos + FBufferedDataSize))) then if not FillBuffer then Break; { Read from buffer } SrcIndex := Result - Count; Remaining := Count; BufPos := FPosition - FStreamBufPos; if Remaining > FBufferedDataSize - BufPos then Remaining := FBufferedDataSize - BufPos; {$R-} Move(FBuffer[BufPos], TDummyByteArray(Buffer)[SrcIndex], Remaining); {$IFDEF SETRANGECHECKSBACK} {$R+} {$ENDIF} Inc(FPosition, Remaining); Dec(Count, Remaining); end; Result := Result - Count; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferedStream.FillBuffer: Boolean; begin Flush; FStream.Position := FPosition; FStreamBufPos := FPosition; FBufferedDataSize := FStream.Read(FBuffer[0], FBufferSize); Result := FBufferedDataSize > 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferedStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; var NewPos: Int64; begin case Origin of soBeginning : NewPos := Offset; soCurrent : NewPos := FPosition + Offset; soEnd : begin NewPos := InternalGetSize + Offset; if (FDirtyCount > 0) and (NewPos < FStreamBufPos + FDirtyCount) then begin Flush; NewPos := FStream.Size + Offset; end; end; else NewPos := -1; end; if NewPos < 0 then NewPos := -1 else FPosition := NewPos; Result := NewPos; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferedStream.Seek(Offset: Integer; Origin: Word): Integer; begin Result := Seek(Int64(Offset), TSeekOrigin(Origin)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferedStream.SetIsReadOnly(const Value: Boolean); begin FIsReadOnly := Value; if FIsReadOnly then FFastSize := FStream.Size else FFastSize := -1; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferedStream.InternalGetSize: Int64; begin if IsReadOnly then Result := FFastSize else Result := FStream.Size; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferedStream.GetSize: Int64; begin { Gets the calculated size in order to not trigger Flush in method } { Seek which was wasted time. Do not call inherited. } Result := InternalGetSize; if Result < FStreamBufPos + FDirtyCount then Result := FStreamBufPos + FDirtyCount; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferedStream.SetSize(const NewSize: Int64); begin FStream.Size := NewSize; FPosition := FStream.Position; if NewSize < (FStreamBufPos + FDirtyCount) then begin FDirtyCount := NewSize - FStreamBufPos; if FDirtyCount < 0 then FDirtyCount := 0; end; if NewSize < (FStreamBufPos + FBufferedDataSize) then begin FBufferedDataSize := NewSize - FStreamBufPos; if FBufferedDataSize < 0 then FBufferedDataSize := 0; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferedStream.SetSize(NewSize: Integer); begin SetSize(Int64(NewSize)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferedStream.Write(const Buffer; Count: Integer): Longint; var DestPos : Integer; SrcIndex : Integer; Remaining : Integer; begin Result := Count; while Count > 0 do begin if not ((FStreamBufPos <= FPosition) and (FPosition < (FStreamBufPos + FBufferedDataSize))) then if not ((FStreamBufPos <= FPosition) and (FPosition < (FStreamBufPos + FBufferSize))) then FillBuffer; { Write to buffer } SrcIndex := Result - Count; Remaining := Count; DestPos := FPosition - FStreamBufPos; if Remaining > FBufferSize - DestPos then Remaining := FBufferSize - DestPos; if FBufferedDataSize < DestPos + Remaining then FBufferedDataSize := DestPos + Remaining; {$R-} Move(TDummyByteArray(Buffer)[SrcIndex], FBuffer[DestPos], Remaining); {$IFDEF SETRANGECHECKSBACK} {$R+} {$ENDIF} FDirtyCount := DestPos + Remaining; Inc(FPosition, Remaining); Dec(Count, Remaining); end; Result := Result - Count; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { TIcsStreamReader } const DefaultBufferSize = 1024 * SizeOf(Char); {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamReader.Create(Stream: TStream; BufferSize: Integer = DEFAULT_BUFSIZE; OwnsStream: Boolean = FALSE); begin Create(Stream, False); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamReader.Create(Stream: TStream; DetectBOM: Boolean = FALSE; CodePage: LongWord = CP_ACP; OwnsStream: Boolean = FALSE; BufferSize: Integer = DEFAULT_BUFSIZE); begin FDetectBOM := DetectBOM; FCodePage := CodePage; inherited Create(Stream, BufferSize, OwnsStream); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamReader.Create(const FileName: String; Mode: Word; BufferSize: Integer = DEFAULT_BUFSIZE); begin Create(FileName, FALSE, CP_ACP, BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamReader.Create(const FileName: String; DetectBOM: Boolean = TRUE; CodePage: LongWord = CP_ACP; BufferSize: Integer = DEFAULT_BUFSIZE); begin FDetectBOM := DetectBOM; FCodePage := CodePage; inherited Create(FileName, fmOpenRead or fmShareDenyWrite, FileAccessRights, BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamReader.Create(const FileName: WideString; Mode: Word; BufferSize: Integer = DEFAULT_BUFSIZE); begin Create(FileName, FALSE, CP_ACP, BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamReader.Create(const FileName: WideString; DetectBOM: Boolean = TRUE; CodePage: LongWord = CP_ACP; BufferSize: Integer = DEFAULT_BUFSIZE); begin FDetectBOM := DetectBOM; FCodePage := CodePage; inherited Create(FileName, fmOpenRead or fmShareDenyWrite, FileAccessRights, BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamReader.Init; begin inherited; FReadBufSize := DefaultBufferSize; SetMaxLineLength(2048); SetLength(FReadBuffer, FReadBufSize + SizeOf(Char)); if FDetectBom then SetCodePage(GetCodePageFromBOM) else SetCodePage(FCodePage); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamReader.SetMaxLineLength(const Value: Integer); begin if Value < 1 then FMaxLineLength := 1 else FMaxLineLength := Value end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamReader.SetCodePage(const Value: LongWord); var CPInfo : TCPInfo; I : Integer; J : Byte; begin case Value of CP_ACP : begin FLeadBytes := SysUtils.Leadbytes; FCodePage := Value; end; CP_UTF8, CP_UTF16, CP_UTF16Be : begin FLeadBytes := []; FCodePage := Value; end; else if GetCPInfo(Value, CPInfo) then begin FCodePage := Value; if CPInfo.MaxCharSize > 1 then begin I := 0; while (I < MAX_LEADBYTES) and ((CPInfo.LeadByte[I] or CPInfo.LeadByte[I + 1]) <> 0) do begin for J := CPInfo.LeadByte[I] to CPInfo.LeadByte[I + 1] do Include(FLeadBytes, AnsiChar(J)); Inc(I, 2); end; end else FLeadBytes := []; end else raise EStreamReaderError.Create(SysErrorMessage(GetLastError)); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsStreamReader.GetCodePageFromBOM: LongWord; var OldPos : Int64; A : array [0..2] of Byte; BomLen : Integer; begin FillChar(A, 3, #0); OldPos := Position; Seek(0, soBeginning); Read(A, 3); if (A[0] = $FF) and (A[1] = $FE) then begin Result := CP_UTF16; BomLen := 2; end else if (A[0] = $FE) and (A[1] = $FF) then begin Result := CP_UTF16Be; BomLen := 2; end else if (A[0] = $EF) and (A[1] = $BB) and (A[2] = $BF) then begin Result := CP_UTF8; BomLen := 3; end else begin Result := CP_ACP; BomLen := 0; end; if OldPos > BomLen then Position := OldPos else Position := BomLen; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsStreamReader.DetectLineBreakStyle: TIcsLineBreakStyle; var OldPos : Int64; ChA : AnsiChar; ChW : WideChar; CodePage : LongWord; begin Result := ilbsCRLF; OldPos := Position; CodePage := GetCodePageFromBOM; try case CodePage of CP_UTF16, CP_UTF16Be : begin Seek(2, soBeginning); while Read(ChW, SizeOf(ChW)) = SizeOf(ChW) do begin if CodePage = CP_UTF16Be then ChW := WideChar((Word(ChW) shl 8) or (Word(ChW) shr 8)); case ChW of #10 : begin if Result = ilbsCRLF then begin Result := ilbsLF; Exit; end else if Result = ilbsCR then begin Result := ilbsCRLF; Exit; end; end; #13 : begin Result := ilbsCR; end; else if Result = ilbsCR then Exit; Result := ilbsCRLF; end; end; end; else // case if CodePage = CP_UTF8 then Seek(3, soBeginning); while Read(ChA, SizeOf(ChA)) = SizeOf(ChA) do begin case ChA of #10 : begin if Result = ilbsCRLF then begin Result := ilbsLF; Exit; end else if Result = ilbsCR then begin Result := ilbsCRLF; Exit; end; end; #13 : begin Result := ilbsCR; end; else if Result = ilbsCR then Exit; Result := ilbsCRLF; end; end; end; finally Position := OldPos; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsStreamReader.InternalReadLn: Boolean; var Ch : AnsiChar; Idx : Integer; P : PAnsiChar; Flag : Boolean; begin Flag := FALSE; Idx := -1; P := PAnsiChar(@FReadBuffer[0]); while Read(Ch, SizeOf(AnsiChar)) = SizeOf(AnsiChar) do begin Inc(Idx); if (Idx >= FMaxLineLength) then begin if ((FCodePage <> CP_UTF8) and (not (Ch in FLeadBytes))) or ((FCodePage = CP_UTF8) and (not IsUtf8TrailByte(Byte(Ch)))) then begin Seek(-1, soCurrent); Result := TRUE; Exit; end; end; EnsureReadBufferA(Idx + 1, P); case Ch of #10 : begin P[Idx] := #0; Result := TRUE; Exit; end; #13 : begin if Flag then begin Seek(-1, soCurrent); Result := TRUE; Exit; end; P[Idx] := #0; Flag := TRUE; end else if Flag then begin Seek(-1, soCurrent); Result := TRUE; Exit; end; P[Idx] := Ch; end; end; if Idx >= 0 then begin P[Idx + 1] := #0; Result := TRUE; end else begin P[0] := #0; Result := FALSE; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsStreamReader.InternalReadLnWLe: Boolean; var Ch : WideChar; Idx : Integer; P : PWideChar; Flag : Boolean; begin Flag := FALSE; Idx := -1; P := PWideChar(@FReadBuffer[0]); while Read(Ch, SizeOf(WideChar)) = SizeOf(WideChar) do begin Inc(Idx); if (Idx >= FMaxLineLength) and (not IsLeadChar(Ch)) then begin Seek(-2, soCurrent); Result := TRUE; Exit; end; EnsureReadBufferW((Idx + 1) * 2, P); case Ch of #10 : begin P[Idx] := #0; Result := TRUE; Exit; end; #13 : begin if Flag then begin Seek(-2, soCurrent); Result := TRUE; Exit; end; P[Idx] := #0; Flag := TRUE; end else if Flag then begin Seek(-2, soCurrent); Result := TRUE; Exit; end; P[Idx] := Ch; end; end; if Idx >= 0 then begin P[Idx + 1] := #0; Result := TRUE; end else begin P[0] := #0; Result := FALSE; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsStreamReader.InternalReadLnWBe: Boolean; var Ch : WideChar; Wrd : Word; Idx : Integer; P : PWideChar; Flag : Boolean; begin Flag := FALSE; Idx := -1; P := PWideChar(@FReadBuffer[0]); while Read(Wrd, SizeOf(Word)) = SizeOf(Word) do begin Inc(Idx); Ch := WideChar((Wrd shr 8) or (Wrd shl 8)); if (Idx >= FMaxLineLength) and (not IsLeadChar(Ch)) then begin Seek(-2, soCurrent); Result := TRUE; Exit; end; EnsureReadBufferW((Idx + 1) * 2, P); case Ch of #10 : begin P[Idx] := #0; Result := TRUE; Exit; end; #13 : begin if Flag then begin Seek(-2, soCurrent); Result := TRUE; Exit; end; P[Idx] := #0; Flag := TRUE; end else if Flag then begin Seek(-2, soCurrent); Result := TRUE; Exit; end; P[Idx] := Ch; end; end; if Idx >= 0 then begin P[Idx + 1] := #0; Result := TRUE; end else begin P[0] := #0; Result := FALSE; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsStreamReader.ReadLine(var S: UnicodeString): Boolean; begin case FCodePage of CP_UTF16 : begin Result := InternalReadLnWLe; S := PWideChar(@FReadBuffer[0]); end; CP_UTF16Be : begin Result := InternalReadLnWBe; S := PWideChar(@FReadBuffer[0]); end; else Result := InternalReadLn; S := AnsiToUnicode(PAnsiChar(@FReadBuffer[0]), FCodePage); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsStreamReader.ReadLine(var S: RawByteString): Boolean; begin case FCodePage of CP_UTF16 : begin Result := InternalReadLnWLe; S := UnicodeToAnsi(PWideChar(@FReadBuffer[0]), CP_ACP, TRUE); end; CP_UTF16Be : begin Result := InternalReadLnWBe; S := UnicodeToAnsi(PWideChar(@FReadBuffer[0]), CP_ACP, TRUE); end; else Result := InternalReadLn; S := RawByteString(PAnsiChar(@FReadBuffer[0])); {$IFDEF COMPILER12_UP} if (S <> '') and (FCodePage <> CP_ACP) then PWord(INT_PTR(S) - 12)^ := FCodePage; {$ENDIF} end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamReader.ReadToEnd(var S: RawByteString); var Buf : TBytes; begin case FCodePage of CP_UTF16 : begin SetLength(Buf, (Size - Position) + 2); Read(Buf[0], Length(Buf) - 2); Buf[Length(Buf) - 1] := 0; Buf[Length(Buf) - 2] := 0; S := UnicodeToAnsi(PWideChar(@Buf[0]), CP_ACP, TRUE); end; CP_UTF16Be : begin SetLength(Buf, (Size - Position) + 2); Read(Buf[0], Length(Buf) - 2); Buf[Length(Buf) - 1] := 0; Buf[Length(Buf) - 2] := 0; IcsSwap16Buf(@Buf[0], @Buf[0], (Length(Buf) - 2) div 2); S := UnicodeToAnsi(PWideChar(@Buf[0]), CP_ACP, TRUE); end; else SetLength(S, Size - Position); Read(PAnsiChar(S)^, Length(S)); {$IFDEF COMPILER12_UP} if (S <> '') and (FCodePage <> CP_ACP) then PWord(INT_PTR(S) - 12)^ := FCodePage; {$ENDIF} end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamReader.ReadToEnd(var S: UnicodeString); var Buf : TBytes; begin case FCodePage of CP_UTF16 : begin SetLength(S, (Size - Position) div 2); Read(PWideChar(S)^, Length(S) * 2); end; CP_UTF16Be : begin SetLength(S, (Size - Position) div 2); Read(PWideChar(S)^, Length(S) * 2); IcsSwap16Buf(Pointer(S), Pointer(S), Length(S)); end; else SetLength(Buf, (Size - Position) + 1); Read(Buf[0], Length(Buf) - 1); Buf[Length(Buf) - 1] := 0; S := AnsiToUnicode(PAnsiChar(@Buf[0]), FCodePage); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamReader.EnsureReadBufferW(Size: Integer; var P: PWideChar); begin if Size > FReadBufSize then begin while Size > FReadBufSize do Inc(FReadBufSize, DefaultBufferSize); SetLength(FReadBuffer, FReadBufSize); P := @FReadBuffer[0]; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamReader.EnsureReadBufferA(Size: Integer; var P: PAnsiChar); begin if Size > FReadBufSize then begin while Size > FReadBufSize do Inc(FReadBufSize, DefaultBufferSize); SetLength(FReadBuffer, FReadBufSize); P := @FReadBuffer[0]; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { TIcsStreamWriter } {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamWriter.Create(Stream: TStream; BufferSize: Integer = DEFAULT_BUFSIZE; OwnsStream: Boolean = FALSE); begin Create(Stream, TRUE, FALSE, CP_ACP, FALSE, BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamWriter.Create(Stream: TStream; Append: Boolean = TRUE; DetectBOM: Boolean = FALSE; CodePage: LongWord = CP_ACP; OwnsStream: Boolean = FALSE; BufferSize: Integer = DEFAULT_BUFSIZE); begin FCodePage := CodePage; inherited Create(Stream, BufferSize, OwnsStream); if DetectBom then FCodePage := GetCodePageFromBOM; if Append then Seek(0, soEnd); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamWriter.Create(const FileName: String; Mode: Word; Rights: Cardinal; BufferSize: Integer); begin FCodePage := CP_ACP; inherited Create(FileName, Mode, Rights, BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamWriter.Create(const FileName: String; Append: Boolean = TRUE; DetectBOM: Boolean = TRUE; CodePage: LongWord = CP_ACP; BufferSize: Integer = DEFAULT_BUFSIZE); var Mode : Word; begin FCodePage := CodePage; if Append and FileExists(FileName) then begin Mode := fmOpenReadWrite or fmShareDenyWrite; inherited Create(FileName, Mode, FileAccessRights, BufferSize); if DetectBom then FCodePage := GetCodePageFromBOM; Seek(0, soEnd); end else begin Mode := fmCreate; inherited Create(FileName, Mode, FileAccessRights, BufferSize); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamWriter.Create(const FileName: WideString; Mode: Word; Rights: Cardinal; BufferSize: Integer); begin FCodePage := CP_ACP; inherited Create(FileName, Mode, Rights, BufferSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsStreamWriter.Create(const FileName: WideString; Append: Boolean = TRUE; DetectBOM: Boolean = TRUE; CodePage: LongWord = CP_ACP; BufferSize: Integer = DEFAULT_BUFSIZE); var Mode : Word; begin FCodePage := CodePage; if Append and FileExists(FileName) then begin Mode := fmOpenReadWrite or fmShareDenyWrite; inherited Create(FileName, Mode, FileAccessRights, BufferSize); if DetectBom then FCodePage := GetCodePageFromBOM; Seek(0, soEnd); end else begin Mode := fmCreate; inherited Create(FileName, Mode, FileAccessRights, BufferSize); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamWriter.Init; begin inherited; FReadBufSize := DefaultBufferSize; SetLength(FReadBuffer, FReadBufSize); FWriteBufSize := DefaultBufferSize; SetLength(FWriteBuffer, FWriteBufSize); LineBreakStyle := ilbsCRLF; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsStreamWriter.GetCodePageFromBOM: LongWord; var OldPos: Int64; A : array [0..2] of Byte; BomLen : Integer; begin FillChar(a, 3, #0); OldPos := Position; Seek(0, sofromBeginning); Read(A, 3); if (A[0] = $FF) and (A[1] = $FE) then begin Result := CP_UTF16; BomLen := 2; end else if (A[0] = $FE) and (A[1] = $FF) then begin Result := CP_UTF16Be; BomLen := 2; end else if (A[0] = $EF) and (A[1] = $BB) and (A[2] = $BF) then begin Result := CP_UTF8; BomLen := 3; end else begin Result := CP_ACP; BomLen := 0; end; if OldPos > BomLen then Position := OldPos else Position := BomLen; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsStreamWriter.GetBomFromCodePage(ACodePage: LongWord) : TBytes; begin case ACodePage of CP_UTF16 : begin SetLength(Result, 2); Result[0] := $FF; Result[1] := $FE; end; CP_UTF16Be : begin SetLength(Result, 2); Result[0] := $FE; Result[1] := $FF; end; CP_UTF8 : begin SetLength(Result, 3); Result[0] := $EF; Result[1] := $BB; Result[2] := $BF; end; else SetLength(Result, 0); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsStreamWriter.DetectLineBreakStyle: TIcsLineBreakStyle; var OldPos : Int64; ChA : AnsiChar; ChW : WideChar; CodePage : LongWord; begin Result := ilbsCRLF; OldPos := Position; CodePage := GetCodePageFromBOM; try case CodePage of CP_UTF16, CP_UTF16Be : begin Seek(2, soBeginning); while Read(ChW, SizeOf(ChW)) = SizeOf(ChW) do begin if CodePage = CP_UTF16Be then ChW := WideChar((Word(ChW) shl 8) or (Word(ChW) shr 8)); case ChW of #10 : begin if Result = ilbsCRLF then begin Result := ilbsLF; Exit; end else if Result = ilbsCR then begin Result := ilbsCRLF; Exit; end; end; #13 : begin Result := ilbsCR; end; else if Result = ilbsCR then Exit; Result := ilbsCRLF; end; end; end; else // case if CodePage = CP_UTF8 then Seek(3, soBeginning); while Read(ChA, SizeOf(ChA)) = SizeOf(ChA) do begin case ChA of #10 : begin if Result = ilbsCRLF then begin Result := ilbsLF; Exit; end else if Result = ilbsCR then begin Result := ilbsCRLF; Exit; end; end; #13 : begin Result := ilbsCR; end; else if Result = ilbsCR then Exit; Result := ilbsCRLF; end; end; end; finally Position := OldPos; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} (* procedure TXStreamWriter.Write(Value: Boolean); begin Write(BoolToStr(Value, True)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TXStreamWriter.Write(Value: WideChar); begin Write(UnicodeString(Value)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TXStreamWriter.Write(Value: AnsiChar); begin Write(RawByteString(Value)); end; *) {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamWriter.WriteBOM; var Bom : TBytes; begin Bom := GetBomFromCodePage(FCodePage); if Length(Bom) > 0 then begin Seek(0, soBeginning); Write(Bom[0], Length(Bom)); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamWriter.EnsureWriteBuffer(Size: Integer); begin if Size > FWriteBufSize then begin while Size > FWriteBufSize do Inc(FWriteBufSize, DefaultBufferSize); SetLength(FWriteBuffer, FWriteBufSize); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamWriter.EnsureReadBuffer(Size: Integer); begin if Size > FReadBufSize then begin while Size > FReadBufSize do Inc(FReadBufSize, DefaultBufferSize); SetLength(FReadBuffer, FReadBufSize); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamWriter.Write(const S: UnicodeString); var Len : Integer; SLen : Integer; begin SLen := Length(S); if SLen = 0 then Exit; case FCodePage of CP_UTF16 : begin WriteBuffer(Pointer(S)^, SLen * 2); end; CP_UTF16Be : begin EnsureWriteBuffer((SLen + 1) * 2); Move(Pointer(S)^, FWriteBuffer[0], SLen * 2); PWideChar(FWriteBuffer)[SLen] := #0; IcsSwap16Buf(@FWriteBuffer[0], @FWriteBuffer[0], SLen); WriteBuffer(FWriteBuffer[0], SLen * 2); end; else Len := IcsWcToMb{WideCharToMultiByte}(FCodePage, 0, Pointer(S), SLen, nil, 0, nil, nil); EnsureWriteBuffer(Len); Len := IcsWcToMb{WideCharToMultiByte}(FCodePage, 0, Pointer(S), SLen, @FWriteBuffer[0], Len, nil, nil); WriteBuffer(FWriteBuffer[0], Len); end; //case end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamWriter.Write(const S: RawByteString; SrcCodePage: LongWord = CP_ACP); var Len : Integer; Len1 : Integer; SLen : Integer; begin SLen := Length(S); if SLen = 0 then Exit; case FCodePage of CP_UTF8, CP_UTF7 : begin if SrcCodePage <> FCodePage then begin Len := IcsMbToWc{MultibyteToWideChar}(SrcCodePage, 0, Pointer(S), SLen, nil, 0); EnsureReadBuffer(Len); Len := IcsMbToWc{MultibyteToWideChar}(SrcCodePage, 0, Pointer(S), SLen, @FReadBuffer[0], Len); Len1 := IcsWcToMb{WideCharToMultibyte}(FCodePage, 0, @FReadBuffer[0], Len, nil, 0, nil, nil); EnsureWriteBuffer(Len1); Len1 := IcsWcToMb{WideCharToMultibyte}(FCodePage, 0, @FReadBuffer[0], Len, @FWriteBuffer[0], Len1, nil, nil); WriteBuffer(FWriteBuffer[0], Len1); end else WriteBuffer(Pointer(S)^, SLen); end; CP_UTF16 : begin Len := IcsMbToWc{MultibyteToWideChar}(SrcCodePage, 0, Pointer(S), SLen, nil, 0); EnsureWriteBuffer(Len * 2); Len := IcsMbToWc{MultibyteToWideChar}(SrcCodePage, 0, Pointer(S), SLen, @FWriteBuffer[0], Len); WriteBuffer(FWriteBuffer[0], Len * 2); end; CP_UTF16Be : begin Len := IcsMbToWc{MultibyteToWideChar}(SrcCodePage, 0, Pointer(S), SLen, nil, 0); EnsureWriteBuffer((Len + 1) * 2); Len := IcsMbToWc{MultibyteToWideChar}(SrcCodePage, 0, Pointer(S), SLen, @FWriteBuffer[0], Len); PWideChar(FWriteBuffer)[Len] := #0; IcsSwap16Buf(@FWriteBuffer[0], @FWriteBuffer[0], Len); WriteBuffer(FWriteBuffer[0], Len * 2); end; else WriteBuffer(Pointer(S)^, SLen); end; //case end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamWriter.WriteLine(const S: RawByteString; SrcCodePage: LongWord = CP_ACP); begin Write(S, SrcCodePage); Write(FLineBreak, SrcCodePage); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamWriter.WriteLine(const S: UnicodeString); begin Write(S); Write(UnicodeString(FLineBreak)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsStreamWriter.SetLineBreakStyle(Value: TIcsLineBreakStyle); begin FLineBreakStyle := Value; case FLineBreakStyle of ilbsCRLF : FLineBreak := #13#10; ilbsLF : FLineBreak := #10; else FLineBreak := #13; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit uSceneRace; interface uses uScene, Graphics, uGraph, uButton, uResFont, uHint; type TBtnEnum = (biPrev, biLeft, biMale, biGenName, biFemale, biRight, biNext); const LenTimeMessage = 300; EnterName = 'Введите имя'; BL = ((Ord(biNext) - 1) * 52) div 2; type TSceneRace = class(TSceneCustom) private FHint: THint; FHintBack: TBitmap; FShowPCSelCursor: Boolean; FPCSellectGenderID: Integer; FPCSellectRaceID: Integer; FFont: TResFont; FLogo: TBitmap; FGraph: TGraph; FGraphGUI: TGraph; FRGraph: TGraph; FIsLoad: Boolean; FTime, FShowMessageTimer: Integer; FTemp: TBitmap; ImgRacePict, ImgRacePict2, ImgRacePict3: array[0..15] of TBitmap; FButton: array [biPrev..biNext] of TButton; procedure Load; procedure DoNext; procedure DoPrev; procedure RaceImages(const I: Integer); procedure DoHint; function GetRaceID(A: ShortInt): Byte; public //** Конструктор. constructor Create; destructor Destroy; override; procedure Draw(); override; function Click(Button: TMouseBtn): Boolean; override; function Keys(var Key: Word): Boolean; override; function KeyPress(var Key: Char): Boolean; override; function MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; override; function MouseMove(X, Y: Integer): Boolean; override; procedure Added(); override; procedure Removed(); override; procedure OnTimer(Sender: TObject); end; var SceneRace: TSceneRace; implementation uses SysUtils, Classes, uMain, uVars, uUtils, uGUI, Types, uScript, uScr, uCommon, uSceneSellect, uSaveLoad, uSceneMenu, uGUIBorder, uSounds, uBox, uIni; { TSceneRace } procedure TSceneRace.DoHint; procedure ShowHint(A: ShortInt); var SL: TStringList; begin SL := TStringList.Create; VM.SetInt('Hero.Race', GetRaceID(A)); Run('Init.pas'); SL.Append(VM.GetStr('Hero.RaceName')); SL.Append('Сила ' + VM.GetStrInt('Hero.Strength')); SL.Append('Ловкость ' + VM.GetStrInt('Hero.Agility')); SL.Append('Телосложение ' + VM.GetStrInt('Hero.Stamina')); SL.Append('Интеллект ' + VM.GetStrInt('Hero.Intellect')); SL.Append('Дуx ' + VM.GetStrInt('Hero.Spirit')); SL.Append('Обзор ' + VM.GetStrInt('Hero.Rad')); SL.Append('Здоровье ' + VM.GetStrInt('Hero.MHP')); SL.Append('Мана ' + VM.GetStrInt('Hero.MMP')); // Сюда можно вывести много чего из калькулятора :) FHint.Show(MouseX, MouseY, 32, SL, False, Point(0, 0), FHintBack); SL.Free; end; begin if IsMouseInRect(57, 90, 161, 252) then ShowHint(-2); if IsMouseInRect(190, 80, 306, 260) then ShowHint(-1); if IsMouseInRect(336, 70, 464, 270) then ShowHint(0); if (MouseX > 400 + (64 + 30)) and (MouseX <= 400 + (64 + 30) + 115) and (MouseY >= 80) and (MouseY <= 80 + 180) then ShowHint(1); if (MouseX > 400 + (64 + 30 + 115 + 30)) and (MouseX <= 400 + (64 + 30 + 115 + 30) + 104) and (MouseY >= 90) and (MouseY <= 90 + 162) then ShowHint(2); end; function TSceneRace.Click(Button: TMouseBtn): Boolean; var I: Integer; begin if IsMouseInRect(190, 80, 306, 260) then begin Dec(FPCSellectRaceID); if (FPCSellectRaceID < 0) then FPCSellectRaceID := 7; Sound.PlayClick(4); SceneManager.Draw(); end; if IsMouseInRect(57, 90, 161, 252) then for I := 1 to 2 do begin Dec(FPCSellectRaceID); if (FPCSellectRaceID < 0) then FPCSellectRaceID := 7; Sound.PlayClick(4); SceneManager.Draw(); end; // if (MouseX > 400 + (64 + 30)) and (MouseX <= 400 + (64 + 30) + 115) and (MouseY >= 80) and (MouseY <= 80 + 180) then begin Inc(FPCSellectRaceID); if (FPCSellectRaceID > 7) then FPCSellectRaceID := 0; Sound.PlayClick(4); SceneManager.Draw(); end; if (MouseX > 400 + (64 + 30 + 115 + 30)) and (MouseX <= 400 + (64 + 30 + 115 + 30) + 104) and (MouseY >= 90) and (MouseY <= 90 + 162) then for I := 1 to 2 do begin Inc(FPCSellectRaceID); if (FPCSellectRaceID > 7) then FPCSellectRaceID := 0; Sound.PlayClick(4); SceneManager.Draw(); end; // Кнопки назад... if FButton[biPrev].MouseOver then DoPrev; // ... и вперед if FButton[biNext].MouseOver then DoNext; // // Выбор расы... if FButton[biLeft].MouseOver then begin Dec(FPCSellectRaceID); if (FPCSellectRaceID < 0) then FPCSellectRaceID := 7; Sound.PlayClick(4); SceneManager.Draw(); end; if FButton[biRight].MouseOver then begin Inc(FPCSellectRaceID); if (FPCSellectRaceID > 7) then FPCSellectRaceID := 0; Sound.PlayClick(4); SceneManager.Draw(); end; // ... и пола if FButton[biMale].MouseOver then begin FPCSellectGenderID := 0; Sound.PlayClick(4); SceneManager.Draw(); end; if FButton[biFemale].MouseOver then begin FPCSellectGenderID := 1; Sound.PlayClick(4); SceneManager.Draw(); end; // Генерация имени... if FButton[biGenName].MouseOver then begin Sound.PlayClick(4); PCName := GenName(FPCSellectGenderID); VM.SetStr('Hero.Name', Trim(PCName)); end; Result := False; end; constructor TSceneRace.Create; begin FPCSellectGenderID := 1; FPCSellectRaceID := 0; FIsLoad := False; end; destructor TSceneRace.Destroy; var I: TBtnEnum; k: Integer; begin FHintBack.Free; FHint.Free; for k := 0 to High(ImgRacePict) do begin ImgRacePict[k].Free(); ImgRacePict2[k].Free(); ImgRacePict3[k].Free(); end; for I := biPrev to biNext do FButton[I].Free; FGraphGUI.Free; FRGraph.Free; FGraph.Free; FFont.Free; FLogo.Free; inherited; end; procedure TSceneRace.Draw; const VX = 440; VY = -50; var I: TBtnEnum; J, K: Integer; SZ: TSize; S: string; PCImg: TBitMap; // SC: Integer; begin if not FIsLoad then Load; PCImg := TBitMap.Create; PCImg.Transparent := True; FButton[biMale].Sellected := (FPCSellectGenderID = 0); FButton[biFemale].Sellected := (FPCSellectGenderID = 1); for I := biPrev to biNext do FButton[I].Draw; // FTemp := Graphics.TBitmap.Create; FTemp.Assign(FLogo); with FTemp.Canvas do begin Brush.Style := bsClear; IsGame := False; S := 'Выберите расу...'; Font.Size := 32; Font.Style := [fsBold]; Font.Color := $003C3E3F; Font.Name := FFont.FontName; SZ := TextExtent(S); TextOut(400 - (SZ.cx div 2), 10, S); // Изображения RaceImages(FPCSellectRaceID); // Ввод имени Font.Size := 24; Font.Style := [fsBold]; Font.Color := $003C3E3F; S := EnterName + ': '; K := TextExtent(S).cx; TextOut(200, 485, S); S := PCName; if FileExists(SavePath) then Font.Color := clRed; TextOut(200 + K, 485, S); J := TextExtent(S).cx; Font.Color := $000000FF; if FShowPCSelCursor then TextOut(200 + K + J, 485, '_'); Font.Color := clRed; Font.Size := 45; if FShowMessageTimer <> 0 then TextOut(400 - (TextExtent(EnterName + '!').CX div 2), 400, EnterName + '!'); DoHint(); end; SCR.BG.Canvas.Draw(0, 0, FTemp); FTemp.Free; PCImg.Free; end; function TSceneRace.Keys(var Key: Word): Boolean; begin TransKeys(Key); Result := True; case Key of 8: begin if (Length(PCName) > 0) then begin Delete(PCName, Length(PCName), 1); VM.SetStr('Hero.Name', Trim(PCName)); SceneManager.Draw(); end; end; 13: DoNext; 27: DoPrev; 37: begin Dec(FPCSellectRaceID); if (FPCSellectRaceID < 0) then FPCSellectRaceID := 7; Sound.PlayClick(4); SceneManager.Draw(); end; 39: begin Inc(FPCSellectRaceID); if (FPCSellectRaceID > 7) then FPCSellectRaceID := 0; Sound.PlayClick(4); SceneManager.Draw(); end; 38, 40: begin FPCSellectGenderID := FPCSellectGenderID + (Key - 39); if FPCSellectGenderID > 1 then FPCSellectGenderID := 0; if FPCSellectGenderID < 0 then FPCSellectGenderID := 1; Sound.PlayClick(4); SceneManager.Draw(); end; end; end; procedure TSceneRace.Load; var I: Integer; E: TBtnEnum; begin FIsLoad := True; FFont := TResFont.Create; FFont.LoadFromFile(Path + 'Data\Fonts\' + Ini.FontName); FGraph := TGraph.Create(Path + 'Data\Images\Screens\'); FRGraph := TGraph.Create(Path + 'Data\Images\Races\'); FGraphGUI := TGraph.Create(Path + 'Data\Images\GUI\'); FHint := THint.Create; FHintBack := Graphics.TBitmap.Create; FGraphGUI.LoadImage('BG.bmp', FHintBack); FLogo := Graphics.TBitmap.Create; FGraph.LoadImage('Blank.jpg', FLogo); GUIBorder.Make(FLogo); FButton[biPrev] := TButton.Create(10, 540, FLogo.Canvas, 'Назад'); for E := biLeft to biRight do FButton[E] := TButton.Create((400 - BL) + ((Ord(E) - 1) * 52), 540, FLogo.Canvas, 'FB' + IntToStr(Ord(E)) + '.bmp', btShort); FButton[biNext] := TButton.Create(590, 540, FLogo.Canvas, 'Игра'); FButton[biNext].Sellected := True; for i := 0 to High(ImgRacePict) do begin // #1 ImgRacePict[i] := TBitMap.Create; FRGraph.LoadImage('Race' + IntToStr(i + 1) + '.jpg', ImgRacePict[i]); GUIBorder.Make(ImgRacePict[i]); // #2 ImgRacePict2[i] := TBitMap.Create; FRGraph.LoadImage('Race' + IntToStr(i + 1) + '-2.jpg', ImgRacePict2[i]); GUIBorder.Make(ImgRacePict2[i]); // #3 ImgRacePict3[i] := TBitMap.Create; FRGraph.LoadImage('Race' + IntToStr(i + 1) + '-3.jpg', ImgRacePict3[i]); GUIBorder.Make(ImgRacePict3[i]); end; end; procedure TSceneRace.Added; begin inherited; fMain.AddTimerEvent(OnTimer); end; procedure TSceneRace.Removed; begin inherited; fMain.DeleteTimerEvent(OnTimer); end; procedure TSceneRace.OnTimer(Sender: TObject); begin // Мигание курсора при вводе имени PC Inc(FTime, TimerTick); if FShowMessageTimer <> 0 then if FShowMessageTimer < TimerTick then FShowMessageTimer := 0 else Dec(FShowMessageTimer, TimerTick); if (FTime <> TimerTick * 10) then Exit; FTime := 0; FShowPCSelCursor := not FShowPCSelCursor; SceneManager.Draw(); end; function TSceneRace.KeyPress(var Key: Char): Boolean; begin Result := True; KeysName(Key); SceneManager.Draw(); end; procedure TSceneRace.RaceImages(const I: Integer); var S: string; SZ: TSize; B, R: TBitmap; CLID, CLID2, CRID, CRID2: ShortInt; begin CLID := I - 1; if (CLID < 0) then CLID := 7; CLID2 := CLID - 1; if (CLID2 < 0) then CLID2 := 7; CRID := I + 1; if (CRID > 7) then CRID := 0; CRID2 := CRID + 1; if (CRID2 > 7) then CRID2 := 0; B := TBitmap.Create; R := TBitmap.Create; with GUI do with FTemp.Canvas do begin // Цент. изображение Draw(400 - 64, 70, ImgRacePict[(I * 2) + FPCSellectGenderID]); // Левые изобр. Draw(400 - (64 + 30 + 115), 80, ImgRacePict2[(CLID * 2) + FPCSellectGenderID]); Draw(400 - (64 + 30 + 115 + 30 + 104), 90, ImgRacePict3[(CLID2 * 2) + FPCSellectGenderID]); // Прав. изобр. Draw(400 + (64 + 30), 80, ImgRacePict2[(CRID * 2) + FPCSellectGenderID]); Draw(400 + (64 + 30 + 115 + 30), 90, ImgRacePict3[(CRID2 * 2) + FPCSellectGenderID]); // VM.SetInt('Hero.Race', FPCSellectRaceID); Run('Init.pas'); S := VM.GetStr('Hero.RaceName'); SZ := TextExtent(S); TextOut(400 - (SZ.cx div 2), 280, S); Font.Size := 20; Font.Style := []; AddMultiLineText(VM.GetStr('Hero.RaceDescr'), FTemp.Canvas, Rect(10, 325, 790, 400)); S := ''; Font.Size := 14; Font.Style := [fsBold]; Font.Color := $0000243E; S := S + 'Сила ' + VM.GetStrInt('Hero.Strength') + ', '; S := S + 'Ловкость ' + VM.GetStrInt('Hero.Agility') + ', '; S := S + 'Телосложение ' + VM.GetStrInt('Hero.Stamina') + ', '; S := S + 'Интеллект ' + VM.GetStrInt('Hero.Intellect') + ', '; S := S + 'Дуx ' + VM.GetStrInt('Hero.Spirit') + ', '; S := S + 'Обзор ' + VM.GetStrInt('Hero.Rad') + '.'; SZ := TextExtent(S); TextOut(400 - (SZ.cx div 2), 468, S); end; B.Free; R.Free; end; function TSceneRace.MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; var I: TBtnEnum; begin Result := False; for I := biPrev to biNext do FButton[I].MouseDown(X, Y); SceneManager.Draw; end; function TSceneRace.MouseMove(X, Y: Integer): Boolean; var I: TBtnEnum; begin Result := False; for I := biPrev to biNext do FButton[I].Draw; SceneManager.Draw; end; procedure TSceneRace.DoNext; begin VM.SetInt('Hero.Race', FPCSellectRaceID); VM.SetInt('Hero.Gender', FPCSellectGenderID); if (PCName <> '') then begin Sound.PlayClick(); SceneSellect.DoGame; end else Inc(FShowMessageTimer, LenTimeMessage); end; procedure TSceneRace.DoPrev; begin if (GetSavePCCount = 0) then SceneManager.SetScene(SceneMenu) else SceneManager.SetScene(SceneSellect); Sound.PlayClick(); end; function TSceneRace.GetRaceID(A: ShortInt): Byte; var K: ShortInt; I: Byte; begin Result := FPCSellectRaceID; K := FPCSellectRaceID; if (A = 0) then Exit; if (A < 0) then for I := 1 to Abs(A) do begin Dec(K); if (K < 0) then K := 7; end; if (A > 0) then for I := 1 to A do begin Inc(K); if (K > 7) then K := 0; end; Result := K; end; initialization SceneRace := TSceneRace.Create; finalization SceneRace.Free; end.
{ ******************************************************************************* Copyright (c) 2004-2010 by Edyard Tolmachev IMadering project http://imadering.com ICQ: 118648 E-mail: imadering@mail.ru ******************************************************************************* } unit ProfileUnit; interface {$REGION 'Uses'} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Pngimage, Menus, StdCtrls, JvSimpleXml, Buttons, ShellApi, IOUtils, ImgList; type TProfileForm = class(TForm) LogoImage: TImage; CenterPanel: TPanel; ProfileComboBox: TComboBox; ProfileLabel: TLabel; LoginButton: TBitBtn; SiteLabel: TLabel; AutoSignCheckBox: TCheckBox; OpenProfilesSpeedButton: TSpeedButton; LangsPopupMenu: TPopupMenu; LangsImageList: TImageList; LangsSpeedButton: TSpeedButton; DellProfileSpeedButton: TSpeedButton; FlagImage: TImage; VersionLabel: TLabel; AutoDellProfileCheckBox: TCheckBox; procedure SiteLabelMouseEnter(Sender: TObject); procedure SiteLabelMouseLeave(Sender: TObject); procedure SiteLabelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure LoginButtonClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure ProfileComboBoxChange(Sender: TObject); procedure OpenProfilesSpeedButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure DellProfileSpeedButtonClick(Sender: TObject); procedure LangsSpeedButtonClick(Sender: TObject); procedure LangsSpeedButtonMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure AutoDellProfileCheckBoxClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } FClose: Boolean; procedure SaveSettings; procedure LoadSettings; procedure LangMenuClick(Sender: TObject); public { Public declarations } procedure TranslateForm; end; {$ENDREGION} var ProfileForm: TProfileForm; implementation {$R *.dfm} {$REGION 'MyUses'} uses MainUnit, VarsUnit, UtilsUnit, SettingsUnit, LogUnit, ProfilesFolderUnit, OverbyteIcsUtils, RosterUnit; {$ENDREGION} {$REGION 'SaveSettings'} procedure TProfileForm.SaveSettings; var JvXML: TJvSimpleXml; XML_Node: TJvSimpleXmlElem; begin // Создаём необходимые папки ForceDirectories(V_ProfilePath); // Сохраняем настройки положения главного окна в xml JvXML_Create(JvXML); try with JvXML do begin // Сохраняем язык по умолчанию Root.Items.Add(C_Lang, V_CurrentLang); // Сохраняем автовход в профиль Root.Items.Add(C_Auto, AutoSignCheckBox.Checked); V_ProfileAuto := AutoSignCheckBox.Checked; // Сохраняем автоудаление профиля Root.Items.Add(C_AutoDell, AutoDellProfileCheckBox.Checked); // Сохраняем профиль по умолчанию XML_Node := Root.Items.Add(C_Profile); XML_Node.Value := V_Profile; // Записываем сам файл SaveToFile(V_ProfilePath + C_ProfilesFileName); end; finally JvXML.Free; end; end; {$ENDREGION} {$REGION 'LoadSettings'} procedure TProfileForm.LoadSettings; var JvXML: TJvSimpleXml; XML_Node: TJvSimpleXmlElem; begin // Инициализируем XML JvXML_Create(JvXML); try with JvXML do begin // Загружаем настройки if FileExists(V_ProfilePath + C_ProfilesFileName) then begin LoadFromFile(V_ProfilePath + C_ProfilesFileName); if Root <> nil then begin // Загружаем язык по умолчанию XML_Node := Root.Items.ItemNamed[C_Lang]; if XML_Node <> nil then V_CurrentLang := XML_Node.Value; // Загружаем автовход в профиль XML_Node := Root.Items.ItemNamed[C_Auto]; if XML_Node <> nil then AutoSignCheckBox.Checked := XML_Node.BoolValue; V_ProfileAuto := AutoSignCheckBox.Checked; // Загружаем автоудаление профиля XML_Node := Root.Items.ItemNamed[C_AutoDell]; if XML_Node <> nil then AutoDellProfileCheckBox.Checked := XML_Node.BoolValue; V_AutoDellProfile := AutoDellProfileCheckBox.Checked; // Получаем имя последнего профиля XML_Node := Root.Items.ItemNamed[C_Profile]; if XML_Node <> nil then ProfileComboBox.Text := XML_Node.Value; end; end; end; finally JvXML.Free; end; end; {$ENDREGION} {$REGION 'LoginButtonClick'} procedure TProfileForm.LoginButtonClick(Sender: TObject); var PR: string; begin // Нормализуем имя профиля ProfileComboBox.Text := Trim(RafinePath(ProfileComboBox.Text)); // Запускаем выбранный профиль if ProfileComboBox.Text = EmptyStr then begin // Выводим сообщение о том, что нужно ввести или выбрать профиль DAShow(Lang_Vars[17].L_S, Lang_Vars[5].L_S, EmptyStr, 134, 2, 0); Exit; end; // Скрываем окно профиля Hide; // Запоминаем имя профиля V_Profile := ProfileComboBox.Text; if ProfileComboBox.Items.IndexOf(V_Profile) = -1 then ProfileComboBox.Items.Add(V_Profile); // Сохраняем настройки профиля SaveSettings; // Делаем заголовок окна КЛ и иконки в трэе по имени профиля with MainForm do begin Caption := V_Profile; TrayIcon.Hint := V_Profile; end; V_YouAt := V_Profile; // Инициализируем папку с профилем PR := V_ProfilePath; V_ProfilePath := V_ProfilePath + V_Profile + C_SN; V_Profile := PR; V_StartLog := V_StartLog + C_RN + LogProfile + C_TN + C_BN + V_ProfilePath; if Assigned(LogForm) then LogForm.LoadStartLog; // Создаём форму с настройками для применения настроек Application.CreateForm(TSettingsForm, SettingsForm); SettingsForm.ApplySettings; // Модифицируем меню в трэе with MainForm do begin Status_MenuTray.Visible := True; Settings_MenuTray.Visible := True; SwitchProfile_MenuTray.Visible := True; end; // Загружаем настройки главного окна MainForm.LoadMainFormSettings; if V_AllSesDataTraf = EmptyStr then V_AllSesDataTraf := DateTimeToStr(Now); // Создаём Ростер и загружаем контакты в него JvXML_Create(V_Roster); if FileExists(V_ProfilePath + C_ContactListFileName) then V_Roster.LoadFromFile(V_ProfilePath + C_ContactListFileName); // Если автоматически проверять новые версии при старте if SettingsForm.AutoUpdateCheckBox.Checked then MainForm.JvTimerList.Events[2].Enabled := True; // Создаём необходимые листы V_AccountToNick := TStringList.Create; V_AccountToNick.NameValueSeparator := C_LN; V_InMessList := TStringList.Create; V_SmilesList := TStringList.Create; if FileExists(V_ProfilePath + C_Nick_BD_FileName) then V_AccountToNick.LoadFromFile(V_ProfilePath + C_Nick_BD_FileName, TEncoding.Unicode); if FileExists(V_MyPath + Format(C_SmiliesPath, [V_CurrentSmiles])) then V_SmilesList.LoadFromFile(V_MyPath + Format(C_SmiliesPath, [V_CurrentSmiles]), TEncoding.UTF8); // Запускаем обработку Ростера UpdateFullCL; // Если не активно запускаться свёрнутой в трэй то показываем клавное окно if not SettingsForm.HideInTrayProgramStartCheckBox.Checked then begin XShowForm(MainForm); // Выводим окно на самый передний план, против глюков в вин и вайн Application.BringToFront; end else begin MainForm.HideInTray_MenuTray.Caption := Lang_Vars[0].L_S; MainForm.HideInTray_MenuTray.ImageIndex := 5; end; // Инициализируем переменную времени начала статистики трафика сессии V_SesDataTraf := Now; // Если это первый старт программы то запускаем выбор протоколов if not V_FirstStart then begin XShowForm(SettingsForm); SettingsForm.SettingsJvPageList.ActivePageIndex := 12; SettingsForm.SettingButtonGroup.ItemIndex := 12; end; // Запускаем таймер индикации событий в КЛ и чате with MainForm do begin JvTimerList.Events[1].Enabled := True; // Запускаем таймер перерисовки иконки в трэе JvTimerList.Events[12].Enabled := True; // В фоне создаём окно смайлов JvTimerList.Events[7].Enabled := True; end; // Закрываем окно FClose := True; Close; end; {$ENDREGION} {$REGION 'Other'} procedure TProfileForm.AutoDellProfileCheckBoxClick(Sender: TObject); begin // Активируем удаление профиля при выходе V_AutoDellProfile := AutoDellProfileCheckBox.Checked; end; procedure TProfileForm.OpenProfilesSpeedButtonClick(Sender: TObject); begin // Открываем папку с профилями ShellExecute(0, 'open', PChar(V_ProfilePath), nil, nil, SW_SHOW); end; procedure TProfileForm.ProfileComboBoxChange(Sender: TObject); begin // Пишем в всплывающей подсказке путь к профилю ProfileComboBox.Hint := V_ProfilePath + ProfileComboBox.Text; end; procedure TProfileForm.LangsSpeedButtonMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin // Открываем меню над этим элементом if Button = MbRight then LangsSpeedButtonClick(Sender); end; {$ENDREGION} {$REGION 'LangsSpeedButtonClick'} procedure TProfileForm.LangsSpeedButtonClick(Sender: TObject); var XPoint: TPoint; begin // Открываем меню над этим элементом GetParentForm(TWinControl(LangsSpeedButton)).SendCancelMode(nil); LangsPopupMenu.PopUpComponent := TWinControl(LangsSpeedButton); XPoint := Point(TWinControl(LangsSpeedButton).Width, TWinControl(LangsSpeedButton).Top - (CenterPanel.Top + CenterPanel.Height)); with TWinControl(LangsSpeedButton).ClientToScreen(XPoint) do LangsPopupMenu.PopUp(X, Y); end; {$ENDREGION} {$REGION 'LangMenuClick'} procedure TProfileForm.LangMenuClick(Sender: TObject); begin // Применяем язык выбранный в меню TMenuItem(Sender).Default := true; V_CurrentLang := IsolateTextString(TMenuItem(Sender).Caption, C_QN, C_EN); // Подгружаем переменные языка SetLangVars; // Переводим форму TranslateForm; // Применяем язык к форме лога if Assigned(LogForm) then LogForm.TranslateForm; // Применяем язык к главной форме MainForm.TranslateForm; // Устанавливаем иконку флага страны на кнопку LangsSpeedButton.Glyph.Assign(nil); LangsImageList.GetBitmap(TMenuItem(Sender).ImageIndex, LangsSpeedButton.Glyph); end; {$ENDREGION} {$REGION 'TranslateForm'} procedure TProfileForm.TranslateForm; begin // Создаём шаблон для перевода // CreateLang(Self); // Применяем язык SetLang(Self); // Сведения о версии программы VersionLabel.Caption := Format(Lang_Vars[4].L_S, [V_FullVersion]); end; {$ENDREGION} {$REGION 'FormCreate'} procedure TProfileForm.FormCreate(Sender: TObject); const Logo = '\logo.png'; label A; var FrmFolder: TProfilesFolderForm; Folder, Langs, LangCode, FlagFile: string; JvXML: TJvSimpleXml; XML_Node: TJvSimpleXmlElem; FlagImg: TBitmap; I: integer; begin // Присваиваем иконку окну и кнопкам with MainForm.AllImageList do begin GetIcon(253, Icon); GetBitmap(227, OpenProfilesSpeedButton.Glyph); GetBitmap(140, LoginButton.Glyph); GetBitmap(139, DellProfileSpeedButton.Glyph); end; // Загружаем логотип программы if FileExists(V_MyPath + C_IconsFolder + V_CurrentIcons + Logo) then LogoImage.Picture.LoadFromFile(V_MyPath + C_IconsFolder + V_CurrentIcons + Logo); // Помещаем кнопку формы в таскбар и делаем независимой SetWindowLong(Handle, GWL_HWNDPARENT, 0); SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW); // Загружаем настройки LoadSettings; // Устанавливаем язык LangsSpeedButton.Glyph.TransparentColor := clNone; JvXML_Create(JvXML); try with JvXML do begin for Langs in TDirectory.GetFiles(V_MyPath + C_LangsFolder, C_XML_Files) do begin LangCode := IcsExtractNameOnlyW(Langs); if FileExists(Langs) then begin // Загружаем файл языка LoadFromFile(Langs); if Root <> nil then begin // Получаем название языка XML_Node := Root.Items.ItemNamed[C_LangVars]; if XML_Node <> nil then begin // Добавляем пункт этого языка в меню LangsPopupMenu.Items.Add(NewItem(C_QN + LangCode + C_EN + C_BN + XML_Node.Properties.Value(C_Lang), 0, False, True, LangMenuClick, 0, LangCode)); LangsPopupMenu.Items[LangsPopupMenu.Items.Count - 1].Hint := LangCode; // Получаем флаг страны этого языка FlagFile := V_MyPath + C_FlagsFolder + GetFlagFile(V_MyPath + C_FlagsFolder, EmptyStr, LangCode); if FileExists(FlagFile) then begin // Добавляем иконку флага ImageList FlagImg := TBitmap.Create; FlagImage.Picture.Assign(nil); FlagImage.Picture.LoadFromFile(FlagFile); try FlagImg.Height := 11; FlagImg.Width := 16; FlagImg.Canvas.Draw(0, 0, FlagImage.Picture.Graphic); LangsImageList.Add(FlagImg, nil); finally FlagImg.Free; end; // Подставляем иконку флага страны этого языка в пункт меню LangsPopupMenu.Items[LangsPopupMenu.Items.Count - 1].ImageIndex := LangsImageList.Count - 1; end else LangsImageList.Add(nil, nil); end; end; end; end; end; finally JvXML.Free; end; // Применяем текущий язык for I := 0 to LangsPopupMenu.Items.Count - 1 do begin if LangsPopupMenu.Items[I].Hint = V_CurrentLang then LangMenuClick(LangsPopupMenu.Items[I]); end; A: ; // Проверяем если ли папки профилей и если нету, то спрашиваем где их хранить if not DirectoryExists(V_ProfilePath) then begin FrmFolder := TProfilesFolderForm.Create(MainForm); try FrmFolder.ShowModal; if FrmFolder.Folder1RadioButton.Checked then V_ProfilePath := FrmFolder.Folder1Edit.Text else V_ProfilePath := FrmFolder.Folder2Edit.Text; finally FreeAndNil(FrmFolder); end; end; // Создаём папку для профилей if not ForceDirectories(V_ProfilePath) then begin // Сообщаем, что прав на запись обновления у нас нет DAShow(Lang_Vars[17].L_S, Lang_Vars[63].L_S, EmptyStr, 134, 2, 0); goto A; end; // Подгружаем список всех папок профилей for Folder in TDirectory.GetDirectories(V_ProfilePath) do ProfileComboBox.Items.Add(IcsExtractLastDir(Folder)); ProfileComboBox.Hint := V_ProfilePath + ProfileComboBox.Text; end; {$ENDREGION} {$REGION 'DellProfile'} procedure TProfileForm.DellProfileSpeedButtonClick(Sender: TObject); var N: Integer; begin // Удаляем профиль из списка и с диска if ProfileComboBox.Text = EmptyStr then Exit; if MessageBox(Handle, PChar(Format(Lang_Vars[127].L_S, [ProfileComboBox.Text])), PChar(Lang_Vars[19].L_S), MB_TOPMOST or MB_YESNO or MB_ICONQUESTION) = MrYes then begin if DirectoryExists(V_ProfilePath + ProfileComboBox.Text) then TDirectory.Delete(V_ProfilePath + ProfileComboBox.Text, True); N := ProfileComboBox.Items.IndexOf(ProfileComboBox.Text); if N > -1 then ProfileComboBox.Items.Delete(N); ProfileComboBox.Text := EmptyStr; ProfileComboBox.Hint := EmptyStr; SaveSettings; end; end; {$ENDREGION} {$REGION 'Other'} procedure TProfileForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if FClose then begin // Уничтожаем форму при закрытии Action := caFree; ProfileForm := nil; end; end; procedure TProfileForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if not FClose then begin // Спрашиваем выйти из программы или свернуть в трэй if MessageBox(Handle, PChar(Lang_Vars[2].L_S), PChar(Application.Title), MB_YESNO or MB_ICONQUESTION) = mrYes then MainForm.CloseProgram_MenuClick(nil) else MainForm.MainFormHideInTray; end; end; procedure TProfileForm.SiteLabelClick(Sender: TObject); begin // Открываем сайт в браузере по умолчанию OpenURL(C_SitePage); end; procedure TProfileForm.SiteLabelMouseEnter(Sender: TObject); begin (Sender as TLabel) .Font.Color := ClBlue; end; procedure TProfileForm.SiteLabelMouseLeave(Sender: TObject); begin (Sender as TLabel) .Font.Color := ClNavy; end; procedure TProfileForm.FormShow(Sender: TObject); begin // Скрываем кнопку приложения на панели задачь ShowWindow(Application.Handle, SW_HIDE); end; {$ENDREGION} end.
unit AgentEngine; interface uses windows, aeSceneNode, sysutils, dialogs, forms, aeConst, graphics, aeSceneGraph, aeOGLRenderer, System.Generics.Collections, aeCamera, aeLoaderManager, aeLoggingManager, classes, types; type TAgentEngine = class SceneGraph: TaeSceneGraph; Renderer: TaeOGLRenderer; Loader: TaeLoaderManager; constructor Create(); procedure enableRenderer(renderHandle: THandle; width, height: cardinal); procedure testNodes(nodeCount: cardinal); procedure CreatePlayerNodeAndCamera(name: string; start_position: TPoint3D); procedure SwapSceneGraph(newGraph: TaeSceneGraph); private end; implementation constructor TAgentEngine.Create(); begin Randomize; self.SceneGraph := TaeSceneGraph.Create; self.Loader := TaeLoaderManager.Create; AE_LOGGING.AddEntry('TAgentEngine.Create() : Startup!', AE_LOG_MESSAGE_ENTRY_TYPE_NORMAL); end; procedure TAgentEngine.CreatePlayerNodeAndCamera(name: string; start_position: TPoint3D); var PlayerNode: TaeSceneNode; Camera: TaeCamera; begin PlayerNode := TaeSceneNode.Create(name); PlayerNode.Move(start_position.Negative); Camera := TaeCamera.Create(PlayerNode); // Camera.SetCameraViewType(AE_CAMERA_VIEW_LOOKFROMCENTER); Camera.SetDistance(30.0); self.Renderer.setCamera(Camera); self.SceneGraph.AddChild(PlayerNode); end; procedure TAgentEngine.enableRenderer(renderHandle: THandle; width, height: cardinal); begin self.Renderer := TaeOGLRenderer.Create(renderHandle, width, height); end; procedure TAgentEngine.SwapSceneGraph(newGraph: TaeSceneGraph); begin self.SceneGraph.Free; self.SceneGraph := newGraph; self.Renderer.setSceneGraph(self.SceneGraph); end; procedure TAgentEngine.testNodes(nodeCount: cardinal); var nodeArray: array of TaeSceneNode; i: integer; begin // first, let's generate some random nodes. SetLength(nodeArray, nodeCount); for i := 0 to nodeCount - 1 do begin nodeArray[i] := TaeSceneNode.Create('TestNode_' + inttostr(i)); end; nodeArray[0].AddChild(nodeArray[1]); nodeArray[0].AddChild(nodeArray[2]); nodeArray[1].AddChild(nodeArray[4]); nodeArray[1].AddChild(nodeArray[5]); nodeArray[1].AddChild(nodeArray[8]); nodeArray[4].AddChild(nodeArray[8]); nodeArray[4].AddChild(nodeArray[10]); nodeArray[4].AddChild(nodeArray[4]); ShowMessage('Number of children : ' + inttostr(nodeArray[0].ListChildren.Count)); end; end.
unit GradientUtils; interface uses Windows, Graphics; procedure Gradient(Canvas : TCanvas; frColor, toColor : TColor; horizontal : boolean; R : TRect); implementation procedure Gradient(Canvas : TCanvas; frColor, toColor : TColor; horizontal : boolean; R : TRect); type TRGBRec = record R : byte; B : byte; G : byte; I : byte; end; var ri : single; gi : single; bi : single; fr : single; fg : single; fb : single; Color : TColor; dist : integer; procedure VerticalGradient; var j : integer; D : TRect; S : TRect; begin for j := R.Top to pred(R.Bottom) do begin Canvas.Pixels[R.Left, j] := Color; with TRGBRec(Color) do begin fr := fr + ri; R := round(fr); fg := fg + gi; G := round(fg); fb := fb + bi; B := round(fb); end; end; D := R; D.Right := succ(D.Left); S := D; for j := succ(R.Left) to pred(R.Right) do begin OffsetRect(D, 1, 0); Canvas.CopyRect(D, Canvas, S); end; end; procedure HorizontalGradient; var i : integer; j : integer; D : TRect; S : TRect; begin for j := R.Left to pred(R.Right) do begin Canvas.Pixels[j, R.Top] := Color; with TRGBRec(Color) do begin fr := fr + ri; R := round(fr); fg := fg + gi; G := round(fg); fb := fb + bi; B := round(fb); end; end; D := R; D.Bottom := succ(D.Top); S := D; for i := succ(R.Top) to pred(R.Bottom) do begin OffsetRect(D, 0, 1); Canvas.CopyRect(D, Canvas, S); end; end; begin if horizontal then dist := R.Right - R.Left + 1 else dist := R.Bottom - R.Top + 1; if dist > 0 then begin ri := (TRGBRec(toColor).R - TRGBRec(frColor).R)/dist; gi := (TRGBRec(toColor).G - TRGBRec(frColor).G)/dist; bi := (TRGBRec(toColor).B - TRGBRec(frColor).B)/dist; Color := frColor; with TRGBRec(Color) do begin fr := R; fg := G; fb := B; end; if horizontal then HorizontalGradient else VerticalGradient; end; end; end.
{ CSI 1101-X, Winter, 1999 } { Assignment 1 } { Identification: Mark Sattolo, student# 428500 } { tutorial group DGD-4, t.a. = Manon Sanscartier } program a1 (input,output) ; label 185; const max_list_length = 20 ; points_nowhere = -9999 ; type element_type = real ; pointer = integer ; { array index } node = record value: element_type ; next: pointer end ; list = record nodes: array [1..max_list_length] of node ; first: pointer ; size: integer ; end; { variable for the main program - NOT to be referenced anywhere else } var YESorNO: char ; {************************************************************} { create_empty - sets list L to be empty. } procedure create_empty ( var L: list ) ; begin L.first := points_nowhere ; L.size := 0 ; end ; procedure write_array_order ( var L:list ); var i,j,rowsize: integer ; begin for j := 1 to (L.size div 8)+1 do begin if (j*8) <= L.size then rowsize := 8 else rowsize := L.size - ((j-1)*8) ; write('index: '); for i := 1 to rowsize do write( (j-1)*8+i:5,' '); writeln; write('value: '); for i := 1 to rowsize do write( L.nodes[(j-1)*8+i].value:5:1,' '); writeln; write(' next: '); for i := 1 to rowsize do write( L.nodes[(j-1)*8+i].next:5,' '); writeln end end ; procedure write_list ( var L:list ); var p: pointer ; begin if L.size = 0 then writeln('empty list') else begin p := L.first ; while p <> points_nowhere do begin write( ' ',L.nodes[p].value:3:1 ); p := L.nodes[p].next end ; writeln end end ; procedure insert_at_front(var L:list; V: element_type) ; var P: pointer; begin P := L.size + 1; L.nodes[p].value := V; L.nodes[p].next := L.first; L.first := P; L.size := L.size + 1; end; { procedure } procedure insert_after_P(var L:list; V: element_type; P:pointer) ; var Q: pointer; begin if (L.size = 0) then begin writeln('Error: The list provided is empty.'); goto 185; { halt } end { if } else if (P > L.size) or (P < 1) then begin writeln('Error: Pointer "', P, '" does not point to an element in this list.'); goto 185; { halt } end { else if } else begin Q := L.size + 1; L.nodes[q].value := V; L.nodes[q].next := L.nodes[p].next; L.nodes[p].next := Q; L.size := L.size + 1; end; { else } end; { procedure } procedure pointer_to_Nth(var L:list; N: integer; var P:pointer); var counter: integer; begin if (N < 1) or (N > L.size) then begin writeln('Error: Position "', N, '" is outside the range [0 - ', L.size, '] of the list.'); goto 185; { halt } end { if } else begin P := L.first; for counter := 1 to N-1 do P := L.nodes[p].next; end; { else } end; { procedure } procedure assignment1 ; var L:list ; P: pointer ; position: integer ; val: element_type ; done: boolean ; begin create_empty( L ); repeat writeln('enter a position (0 to ',L.size:0, ') and number (empty line to quit)' ) ; done := eoln ; if not done then begin readln(position,val) ; if position = 0 then insert_at_front(L,val) else begin pointer_to_Nth(L,position,P); insert_after_P(L,val,P) end ; writeln; writeln('here is the list after this insertion:'); write_list( L ); writeln; writeln('Here is the array used to represent the list:'); write_array_order( L ) end else readln { clear the empty line } until done end; {**** CHANGE THIS PROCEDURE TO DESCRIBE YOURSELF ****} procedure identify_myself ; { Writes who you are to the screen } begin writeln ; writeln('CSI 1101-X (winter, 1999). Assignment #1.') ; writeln('Mark Sattolo, student# 428500.') ; writeln('tutorial section DGD-4, t.a. = Manon Sanscartier'); writeln end ; begin { main program } identify_myself ; repeat assignment1 ; 185: writeln('Do you wish to continue (y or n) ?') ; readln(YESorNO); until (YESorNO <> 'y'); end.
unit uaftextfile; {$mode delphi} {$H+} interface uses uafudfs; {Creates descriptor to work with a text file FileName} function CreateTextFile (FileName: PChar): PtrUdf; cdecl; {Opens for reading text file} function ResetTextFile (var Handle: PtrUdf): integer; cdecl; {Opens a text file for writing} function RewriteTextFile (var Handle: PtrUdf): integer; cdecl; {Close the handle to work with the file Attention } function CloseTextFile (var Handle: PtrUdf): integer; cdecl; {Writes a text string in a file} function WriteToTextFile (var Handle: PtrUdf; S: Pchar): integer; cdecl; {Writes a text string in a file with a carriage return} function WriteLnToTextFile (var Handle: PtrUdf; S: Pchar): integer; cdecl; {Gets line from the textual version of the file} function ReadLnFromTextFile (var Handle: PtrUdf): Pchar; cdecl; {Checks for the end of file when reading} function EofTextFile (var Handle: PtrUdf): integer; cdecl; {Flush buffer contents to a file Handle recording} function FlushTextFile (var Handle: PtrUdf): integer; cdecl; {Opens a text file for writing at end of file} function AppendTextFile (var Handle: PtrUdf): integer; cdecl; {Gets char from the textfile} function ReadCharFromTextFile (var Handle: PtrUdf): Pchar; cdecl; {Gets int32 from the textfile} function ReadInt32FromTextFile (var Handle: PtrUdf): Integer; cdecl; {Gets int64 from the textfile} function ReadInt64FromTextFile (var Handle: PtrUdf): Int64; cdecl; {Writes a integer in a file} function WriteInt32ToTextFile (var Handle: PtrUdf; var Num: Integer): integer; cdecl; {Writes a integer 64bit in a file} function WriteInt64ToTextFile (var Handle: PtrUdf; var Num: Int64): integer; cdecl; implementation uses SysUtils,ioresdecode, ib_util; procedure CheckIOResult; var lastio: Word; begin lastio:=IOResult; if lastio<>0 then raise Exception.Create(IOResultDecode(lastio)); end; function CreateTextFile(FileName:PChar):PtrUdf;cdecl; var F:^TextFile; begin Result := 0; try Getmem(F,Sizeof(TextFile)); AssignFile(F^,string(FileName)); except if F<>nil then Dispose(F); exit; end; result :=TAFObj.Create(F,SizeOf(F^)).Handle; end; Type TExecCommonTextFile=Procedure(var t:Text); function ExecuteCommon(var Handle:PtrUdf;func:TExecCommonTextFile):integer; var afobj:TAFObj; begin result := 0; try afobj := HandleToAfObj(Handle,taoMem); {$I-} func(TextFile(afobj.Memory^)); {$I+} CheckIOResult; Result := 1; except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; { ResetTextFile } procedure DoReset(var t:text); begin Reset(t); end; function ResetTextFile(var Handle:PtrUdf):integer;cdecl; begin result := ExecuteCommon(Handle,@DoReset); end; { CloseTextFile } procedure DoCloseFile(var t:text); begin CloseFile(t); end; function CloseTextFile(var Handle:PtrUdf):integer;cdecl; begin result := ExecuteCommon(Handle,@DoCloseFile); end; { RewriteTextFile } procedure DoRewriteTextFile(var t:text); begin Rewrite(t); end; function RewriteTextFile(var Handle:PtrUdf):integer;cdecl; begin result := ExecuteCommon(Handle,@DoRewriteTextFile); end; { AppendTextFile } procedure DoAppendTextFile(var t:text); begin Append(t); end; function AppendTextFile(var Handle:PtrUdf):integer;cdecl; begin result := ExecuteCommon(Handle,@DoAppendTextFile); end; { FlushTextFile } procedure DoFlushTextFile(var t:text); begin Flush(t); end; function FlushTextFile(var Handle:PtrUdf):integer;cdecl; begin result := ExecuteCommon(Handle,@DoFlushTextFile); end; Type TWriteToFunc=procedure(var t:text;s:Pointer); function WriteToCommon(var Handle:PtrUdf;S:Pointer;fn:TWriteToFunc):integer;cdecl; var afobj:TAFObj; begin result := 0; try afobj := HandleToAfObj(Handle,taoMem); {$I-} fn(TextFile(afobj.Memory^),S); {$I+} CheckIOResult; Result := 1; except on e:Exception do begin if Assigned(afobj) then afobj.FixedError(e); end end; end; { WriteToTextFile } procedure DoWriteToTextFile(var t:text;s:Pchar); begin Write(t,s); end; function WriteToTextFile(var Handle:PtrUdf;S:Pchar):integer;cdecl; begin result := WriteToCommon(Handle,S,@DoWriteToTextFile); end; {WriteLnToTextFile} procedure DoWriteLnToTextFile(var t:text;s:Pchar); begin WriteLn(t,s); end; function WriteLnToTextFile(var Handle:PtrUdf;S:Pchar):integer;cdecl; begin result := WriteToCommon(Handle,S,@DoWriteLnToTextFile); end; {WriteInt32ToTextFile} procedure DoWriteInt32ToTextFile(var t:text;s:PInteger); begin Write(t, s^); end; function WriteInt32ToTextFile (var Handle: PtrUdf; var Num: Integer): integer; cdecl; begin result := WriteToCommon(Handle,@Num,@DoWriteInt32ToTextFile); end; {WriteInt64ToTextFile} procedure DoWriteInt64ToTextFile(var t:text;s:PInt64); begin Write(t, s^); end; function WriteInt64ToTextFile (var Handle: PtrUdf; var Num: Int64): integer; cdecl; begin result := WriteToCommon(Handle,@Num,@DoWriteInt64ToTextFile); end; function ReadLnFromTextFile(var Handle:PtrUdf):Pchar;cdecl; var afobj:TAFObj; s:string; begin result := nil; try afobj := HandleToAfObj(Handle,taoMem); {$I-} ReadLn(TextFile(afobj.Memory^),s); {$I+} CheckIOResult; result := ib_util.ib_util_malloc(Length(s)+1); StrPCopy(result,s); except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; {Gets char from the textual version of the file} function ReadCharFromTextFile (var Handle: PtrUdf): Pchar; cdecl; var afobj:TAFObj; ch:Char; begin result := nil; try afobj := HandleToAfObj(Handle,taoMem); {$I-} Read(TextFile(afobj.Memory^),ch); {$I+} CheckIOResult; result := ib_util.ib_util_malloc(Length(ch)+1); StrPCopy(result,ch); except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function ReadInt32FromTextFile (var Handle: PtrUdf): Integer; cdecl; var afobj:TAFObj; begin result := 0; try afobj := HandleToAfObj(Handle,taoMem); {$I-} Read(TextFile(afobj.Memory^),result); {$I+} CheckIOResult; except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function ReadInt64FromTextFile (var Handle: PtrUdf): Int64; cdecl; var afobj:TAFObj; begin result := 0; try afobj := HandleToAfObj(Handle,taoMem); {$I-} Read(TextFile(afobj.Memory^),Result); {$I+} CheckIOResult; except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; function EofTextFile(var Handle:PtrUdf):integer;cdecl; var afobj:TAFObj; begin result := 0; try afobj := HandleToAfObj(Handle,taoMem); {$I-} Result := Integer(Eof(TextFile(afobj.Memory^))); {$I+} CheckIOResult; except on e:Exception do if Assigned(afobj) then afobj.FixedError(e); end; end; end.
program HelloAudio; {$mode objfpc}{$H+} { VideoCore IV example - Hello Audio } { } { A very simple example showing audio output over HDMI } { } { To compile the example select Run, Compile (or Run, Build) from the menu. } { } { Once compiled copy the kernel7.img file to an SD card along with the } { firmware files and use it to boot your Raspberry Pi. } { } { This version is for Raspberry Pi 2B and will also work on a 3B. } uses RaspberryPi2, {Include RaspberryPi2 to make sure all standard functions are included} GlobalConst, GlobalTypes, Threads, Console, HTTP, {Include HTTP and WebStatus so we can see from a web browser what is happening} WebStatus, SysUtils, { TimeToStr & Time } Logging, uTFTP, Winsock2, { needed to use ultibo-tftp } { needed for telnet } Shell, ShellFilesystem, ShellUpdate, RemoteShell, { needed for telnet } UltiboUtils, {Include Ultibo utils for some command line manipulation} Syscalls, {Include the Syscalls unit to provide C library support} VC4; {Include the VC4 unit to enable access to the GPU} var argc:int; {Some command line arguments to pass to the C code} argv:PPChar; WindowHandle:TWindowHandle; HTTPListener:THTTPListener; { needed to use ultibo-tftp } TCP : TWinsock2TCPClient; IPAddress : string; {Link our C library to include the original example} {$linklib hello_audio} {Import the main function of the example so we can call it from Ultibo} function hello_audio(argc: int; argv: PPChar): int; cdecl; external 'hello_audio' name 'hello_audio'; function WaitForIPComplete : string; var TCP : TWinsock2TCPClient; begin TCP := TWinsock2TCPClient.Create; Result := TCP.LocalAddress; if (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') then begin while (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') do begin sleep (1500); Result := TCP.LocalAddress; end; end; TCP.Free; end; procedure Msg (Sender : TObject; s : string); begin ConsoleWindowWriteLn (WindowHandle, s); end; procedure WaitForSDDrive; begin while not DirectoryExists ('C:\') do sleep (500); end; begin {The following 3 lines are logging to the console CONSOLE_REGISTER_LOGGING:=True; LoggingConsoleDeviceAdd(ConsoleDeviceGetDefault); LoggingDeviceSetDefault(LoggingDeviceFindByType(LOGGING_TYPE_CONSOLE)); } {The following 2 lines are logging to a file LoggingDeviceSetTarget(LoggingDeviceFindByType(LOGGING_TYPE_FILE),'c:\ultibologging.log'); LoggingDeviceSetDefault(LoggingDeviceFindByType(LOGGING_TYPE_FILE)); } {Create a console window as usual} WindowHandle:=ConsoleWindowCreate(ConsoleDeviceGetDefault,CONSOLE_POSITION_FULL,True); ConsoleWindowWriteLn(WindowHandle,'Starting Hello Audio'); // wait for IP address and SD Card to be initialised. WaitForSDDrive; IPAddress := WaitForIPComplete; {Create and start the HTTP Listener for our web status page} HTTPListener:=THTTPListener.Create; HTTPListener.Active:=True; ConsoleWindowWriteLn (WindowHandle, 'Local Address ' + IPAddress); SetOnMsg (@Msg); {Register the web status page, the "Thread List" page will allow us to see what is happening in the example} WebStatusRegister(HTTPListener,'','',True); {Allocate a command line for the C code, this function just takes a string and creates a properly formatted argv and argc which can be used to pass parameters to the example} argv:=AllocateCommandLine('1',argc); {Call the main function of the example, it will return here when completed (if ever)} hello_audio(argc, argv); {Release the C command line} ReleaseCommandLine(argv); ConsoleWindowWriteLn(WindowHandle,'Completed Hello Audio'); {Halt the main thread here} ThreadHalt(0); end.
unit uSceneStat; interface uses Graphics, uScene; type TSceneStat = class(TSceneFrame) private public //** Конструктор. constructor Create; //** Деструктор. destructor Destroy; override; procedure Draw(); override; function Enum(): TSceneEnum; override; end; var SceneStat: TSceneStat; implementation uses SysUtils, uVars, uEffects, uUtils; { TSceneStat } constructor TSceneStat.Create; begin inherited Create(spLeft); end; destructor TSceneStat.Destroy; begin inherited; end; procedure TSceneStat.Draw; begin inherited; with Back.Canvas do begin Font.Color := $006089A2; Font.Size := 20; TextOut(200 - (TextExtent('Статистика').cx div 2), 5, 'Статистика'); Font.Size := 14; Draw(5, 37, Effects.Effect[24]); TextOut(25, 35, 'Побед: ' + VM.GetStrInt('Hero.Kills')); Draw(5, 57, Effects.Effect[48]); TextOut(25, 55, 'Поражений: ' + VM.GetStrInt('Hero.Deads')); Draw(5, 77, Effects.Effect[72]); TextOut(25, 75, 'Подземелье: ' + VM.GetStrInt('Hero.Deep')); Draw(5, 97, Effects.Effect[31]); TextOut(25, 95, 'Шаги: ' + VM.GetStrInt('Hero.Step')); Draw(5, 117, Effects.Effect[51]); TextOut(25, 115, 'Время: ' + GetTimeStr); end; Refresh; end; function TSceneStat.Enum: TSceneEnum; begin Result := scStat; end; initialization SceneStat := TSceneStat.Create; finalization SceneStat.Free; end.
unit Thread.ImportarBaixasDIRECT; interface uses System.Classes, Control.Entregas, System.SysUtils, System.DateUtils, Control.VerbasExpressas, Control.Bases, Control.EntregadoresExpressas, Generics.Collections, System.StrUtils, Model.VerbasExpressas, Control.PlanilhaBaixasDIRECT; type TThread_ImportarBaixasDIRECT = class(TThread) private { Private declarations } FPlanilha: TPlanilhaBaixasDIRECTControl; FEntregas: TEntregasControl; FVerbas: TVerbasExpressasControl; FBases: TBasesControl; FEntregadores: TEntregadoresExpressasControl; protected procedure Execute; override; procedure UpdateLOG(sMensagem: string); procedure UpdateProgress(dPosition: Double); procedure BeginProcesso; procedure TerminateProcess; function RetornaVerba(aParam: array of variant): double; function RetornaAgente(sChave: string): integer; function RetornaEntregador(sChave: string): integer; public FFile: String; iCodigoCliente: Integer; bCancel : Boolean; bLojas: boolean; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TThread_ImportarBaixasDIRECT.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } uses Common.ENum, Global.Parametros; { TThread_ImportarBaixasDIRECT } procedure TThread_ImportarBaixasDIRECT.BeginProcesso; var sMensagem: String; begin Global.Parametros.psLOG := ''; bCancel := False; Global.Parametros.pbProcess := True; sMensagem := ''; sMensagem := '>> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' > iniciando importação do arquivo ' + FFile; UpdateLog(sMensagem); sMensagem := '>> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' > tratando os dados da planilha. Aguarde...'; UpdateLog(sMensagem); end; procedure TThread_ImportarBaixasDIRECT.Execute; var aParam: Array of variant; iPos, iPosition, iTotal, iTabela, iFaixa, iAgente, iEntregador,i: Integer; sCEP, sMensagem: String; dPos, dPerformance, dVerba, dVerbaTabela, dPeso: double; slParam: TStringList; bProcess: Boolean; begin try try Synchronize(BeginProcesso); FPlanilha := TPlanilhaBaixasDIRECTControl.Create; sMensagem := '>>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importando os dados. Aguarde...'; UpdateLog(sMensagem); if FPLanilha.GetPlanilha(FFile) then begin iPos := 0; iPosition := 0; dPos := 0; dPeso := 0; iTotal := FPlanilha.Planilha.Planilha.Count; for i := 0 to Pred(iTotal) do begin FEntregas := TEntregasControl.Create; SetLength(aParam,3); aParam := ['NNCLIENTE', FPlanilha.Planilha.Planilha[i].Remessa, iCodigoCliente]; if not FEntregas.LocalizarExata(aParam) then begin if UpperCase(FPlanilha.Planilha.Planilha[iPos].Tipo) = 'REVERSA' then begin FEntregas.Entregas.NN := FPlanilha.Planilha.Planilha[i].Remessa; FEntregas.Entregas.Distribuidor := RetornaAgente(FPlanilha.Planilha.Planilha[i].Documento); FEntregas.Entregas.Entregador := RetornaEntregador(FPlanilha.Planilha.Planilha[i].Documento); FEntregas.Entregas.NF := FPlanilha.Planilha.Planilha[i].NF; FEntregas.Entregas.Consumidor := 'REVERSA'; FEntregas.Entregas.Cidade := FPlanilha.Planilha.Planilha[i].Municipio; FEntregas.Entregas.Cep :=FPlanilha.Planilha.Planilha[i].CEP; FEntregas.Entregas.Expedicao := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Previsao := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Volumes := 1; FEntregas.Entregas.Atribuicao := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Baixa := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Baixado := 'S'; FEntregas.Entregas.Status := 909; FEntregas.Entregas.Entrega := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.TipoPeso := FPlanilha.Planilha.Planilha[i].Tipo; FEntregas.Entregas.PesoReal := FPlanilha.Planilha.Planilha[i].PesoNominal; FEntregas.Entregas.PesoFranquia := FPlanilha.Planilha.Planilha[i].PesoAferido; FEntregas.Entregas.PesoCobrado := 0; FEntregas.Entregas.Advalorem := 0; FEntregas.Entregas.PagoFranquia := 0; FEntregas.Entregas.VerbaEntregador := 0; FEntregas.Entregas.Extrato := '0'; FEntregas.Entregas.Atraso := 0; FEntregas.Entregas.VolumesExtra := 0; FEntregas.Entregas.ValorVolumes := 0; FEntregas.Entregas.Recebimento := StrToDate('30/12/1899'); FEntregas.Entregas.Recebido := 'S'; FEntregas.Entregas.Pedido := FPlanilha.Planilha.Planilha[i].Pedido; FEntregas.Entregas.CodCliente := iCodigoCliente; Finalize(aParam); dPeso := 0; if FEntregas.Entregas.PesoCobrado > 0 then dPeso := FEntregas.Entregas.PesoCobrado else if FEntregas.Entregas.PesoFranquia > 0 then dPeso := FEntregas.Entregas.PesoFranquia else dPeso := FEntregas.Entregas.PesoReal; SetLength(aParam,7); aParam := [FEntregas.Entregas.Distribuidor, FEntregas.Entregas.Entregador, FEntregas.Entregas.CEP, dPeso, FEntregas.Entregas.Baixa, 0, 0]; FEntregas.Entregas.VerbaEntregador := RetornaVerba(aParam); FEntregas.Entregas.Acao := tacIncluir; Finalize(aParam); if FEntregas.Entregas.VerbaEntregador = 0 then begin sMensagem := '>>> Verba do NN ' + FEntregas.Entregas.NN + ' do entregador ' + FPlanilha.Planilha.Planilha[i].Motorista + ' não atribuida !'; UpdateLog(sMensagem); end; if not FEntregas.Gravar() then begin sMensagem := '>>> Erro ao gravar o NN ' + Fentregas.Entregas.NN + ' !'; UpdateLog(sMensagem); end; end else begin sMensagem := '>>> Entrega NN ' + FPlanilha.Planilha.Planilha[i].Remessa + ' do entregador ' + FPlanilha.Planilha.Planilha[i].Motorista + ' não encontrada no banco de dados !'; UpdateLog(sMensagem); end; end else begin FEntregas.Entregas.Distribuidor := RetornaAgente(FPlanilha.Planilha.Planilha[i].Documento); FEntregas.Entregas.Entregador := RetornaEntregador(FPlanilha.Planilha.Planilha[i].Documento); FEntregas.Entregas.Baixa := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Baixado := 'S'; FEntregas.Entregas.Status := 909; FEntregas.Entregas.Entrega := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Atraso := 0; FEntregas.Entregas.PesoReal := FPlanilha.Planilha.Planilha[i].PesoNominal; FEntregas.Entregas.PesoFranquia := FPlanilha.Planilha.Planilha[i].PesoAferido; FEntregas.Entregas.CodigoFeedback := 0; FEntregas.Entregas.TipoPeso := 'ENTREGA'; Finalize(aParam); dPeso := 0; if FEntregas.Entregas.PesoCobrado > 0 then dPeso := FEntregas.Entregas.PesoCobrado else if FEntregas.Entregas.PesoFranquia > 0 then dPeso := FEntregas.Entregas.PesoFranquia else dPeso := FEntregas.Entregas.PesoReal; SetLength(aParam,7); aParam := [FEntregas.Entregas.Distribuidor, FEntregas.Entregas.Entregador, FEntregas.Entregas.CEP, dPeso, FEntregas.Entregas.Baixa, 0, 0]; FEntregas.Entregas.VerbaEntregador := RetornaVerba(aParam); Finalize(aParam); if FEntregas.Entregas.VerbaEntregador = 0 then begin sMensagem := '>>> Verba do NN ' + FEntregas.Entregas.NN + ' do entregador ' + FPlanilha.Planilha.Planilha[i].Motorista + ' não atribuida !'; UpdateLog(sMensagem); end else begin if bLojas then begin if FPlanilha.Planilha.Planilha[i].Loja = 'S' then begin dVerba := FEntregas.Entregas.VerbaEntregador; FEntregas.Entregas.VerbaEntregador := (dVerba / 2); FEntregas.Entregas.CodigoFeedback := 99318; FEntregas.Entregas.TipoPeso := 'LOJA'; end; end; end; FEntregas.Entregas.Acao := tacAlterar; if not FEntregas.Gravar() then begin sMensagem := '>>> Erro ao gravar o NN ' + Fentregas.Entregas.NN + ' !'; UpdateLog(sMensagem); end; end; FEntregas.Free; inc(iPos, 1); dPos := (iPos / iTotal) * 100; if not(Self.Terminated) then begin UpdateProgress(dPos); end else begin Abort; end; end; Synchronize(TerminateProcess); end; Except on E: Exception do begin sMensagem := '** ERROR **' + Chr(13) + 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message; UpdateLog(sMensagem); bCancel := True; end; end; finally FPlanilha.Free; end; end; function TThread_ImportarBaixasDIRECT.RetornaAgente(sChave: string): integer; var FEntregadores: TEntregadoresExpressasControl; aParam: array of variant; iRetorno: integer; begin try Result := 0; iRetorno := 0; FEntregadores := TEntregadoresExpressasControl.Create; SetLength(aParam, 3); aParam := ['CHAVECLIENTE', sChave, iCodigoCliente]; if FEntregadores.LocalizarExato(aParam) then begin iRetorno := FEntregadores.Entregadores.Agente; end else begin iRetorno := 1; end; Result := iRetorno; finally Fentregadores.Free; end; end; function TThread_ImportarBaixasDIRECT.RetornaEntregador(sChave: string): integer; var FEntregadores: TEntregadoresExpressasControl; aParam: array of variant; iRetorno: integer; begin try Result := 0; iRetorno := 0; FEntregadores := TEntregadoresExpressasControl.Create; SetLength(aParam, 3); aParam := ['CHAVECLIENTE', sChave, iCodigoCliente]; if Fentregadores.LocalizarExato(aParam) then begin iRetorno := FEntregadores.Entregadores.Entregador; end else begin iRetorno := 1; end; Finalize(aParam); Result := iRetorno; finally Fentregadores.Free; end; end; function TThread_ImportarBaixasDIRECT.RetornaVerba(aParam: array of variant): double; var FBase: TBasesControl; FEntregador: TEntregadoresExpressasControl; FVerbas: TVerbasExpressasControl; iTabela, iFaixa: Integer; dVerba, dVerbaEntregador: Double; FParam: array of variant; begin Result := 0; iTabela := 0; iFaixa := 0; dVerba := 0; dVerbaEntregador := 0; FBase := TBasesControl.Create; SetLength(FParam,2); FParam := ['CODIGO',aParam[0]]; if FBase.LocalizarExato(FParam) then begin iTabela := FBase.Bases.Tabela; iFaixa := FBase.Bases.Grupo; dVerba := FBase.Bases.ValorVerba; end; Finalize(FParam); FBase.Free; // se a base não possui uma verba fixa, verifica se a base possui uma vinculação a uma // tabela e faixa. if dVerba = 0 then begin if iTabela <> 0 then begin if iFaixa <> 0 then begin FVerbas := TVerbasExpressasControl.Create; FVerbas.Verbas.Tipo := iTabela; FVerbas.Verbas.Cliente := iCodigoCliente; FVerbas.Verbas.Grupo := iFaixa; FVerbas.Verbas.Vigencia := aParam[4]; FVerbas.Verbas.CepInicial := aParam[2]; FVerbas.Verbas.PesoInicial := aParam[3]; FVerbas.Verbas.Roteiro := aParam[5]; FVerbas.Verbas.Performance := aParam[6]; dVerba := FVerbas.RetornaVerba(); FVerbas.Free; end; end; end; // pesquisa a tabela de entregadores e apanha os dados referente à verba FEntregador := TEntregadoresExpressasControl.Create; SetLength(FParam,2); FParam := ['ENTREGADOR', aParam[1]]; if not Fentregador.Localizar(FParam).IsEmpty then begin iTabela := FEntregador.Entregadores.Tabela; iFaixa := FEntregador.Entregadores.Grupo; dVerbaEntregador := FEntregador.Entregadores.Verba; end; Finalize(FParam); FEntregador.Free; // verifica se o entregador possui uma verba fixa, se estiver zerada, verifica com as informações // de tabela e faixa. if dVerbaEntregador = 0 then begin if iTabela <> 0 then begin if iFaixa <> 0 then begin FVerbas := TVerbasExpressasControl.Create; FVerbas.Verbas.Tipo := iTabela; FVerbas.Verbas.Cliente := iCodigoCliente; FVerbas.Verbas.Grupo := iFaixa; FVerbas.Verbas.Vigencia := aParam[4]; FVerbas.Verbas.CepInicial := aParam[2]; FVerbas.Verbas.PesoInicial := aParam[3]; FVerbas.Verbas.Roteiro := aParam[5]; FVerbas.Verbas.Performance := aParam[6]; dVerbaEntregador := FVerbas.RetornaVerba(); FVerbas.Free; end; end; end; if dVerbaEntregador > 0 then begin dVerba := dVerbaEntregador; end; Result := dVerba; end; procedure TThread_ImportarBaixasDIRECT.TerminateProcess; begin Global.Parametros.pbProcess := False; end; procedure TThread_ImportarBaixasDIRECT.UpdateLOG(sMensagem: string); begin if Global.Parametros.psLOG <> '' then begin Global.Parametros.psLOG := Global.Parametros.psLOG + #13; end; Global.Parametros.psLOG := Global.Parametros.psLOG + sMensagem; end; procedure TThread_ImportarBaixasDIRECT.UpdateProgress(dPosition: Double); begin Global.Parametros.pdPos := dPosition; end; end.
{ Модуль подсистемы базы данных. !! в TDbItem массив значений больше необходимого } unit DbUnit; interface uses SysUtils, Classes, Contnrs, MkSqLite3, MkSqLite3Api; type // Информация о таблице БД // - сведения о колонках и типах данных в колонках // - название таблицы TDbTableInfo = class(TObject) private AFieldNames: array of string; AFieldTypes: array of string; AFieldsCount: integer; function GetField(Index: integer): string; function GetType(Index: integer): string; function GetFieldsCount(): integer; public DBName: string; // Имя базы данных TableName: string; // Имя таблицы KeyFieldName: string; // Имя ключевого поля (ID) // Признак, того, что таблица соответствует своему аналогу в базе данных Checked: boolean; constructor Create(); // Список имен полей таблицы property Fields[Index: integer]: string read GetField; // Список типов полей таблицы property Types[Index: integer]: string read GetType; // Количество полей property FieldsCount: integer read GetFieldsCount; // Создает поле с указаным именем и типом procedure AddField(const FieldName, FieldType: string); // Возвращает номер поля по его имени function FieldIndex(FName: string): Integer; end; // элемент таблицы БД, один ряд таблицы TDbItem = class(TObject) private // Массив значений (полей) элемента FValues: array of string; // Инициализирует массив значений, заполняет их пустыми значениями procedure InitValues(); public ID: integer; // идентификатор элемента Name: string; // строковое представление значения Actual: boolean; // признак соответствия данных элемента и БД TimeStamp: TDateTime; // дата последнего изменения DbTableInfo: TDbTableInfo; // информация о таблице // Возвращает значение по имени колонки // Должно быть переопределено в потомках function GetValue(const FName: string): string; virtual; // Возвращает DBItem по имени колонки // Должно быть переопределено в потомках //function GetDBItem(FName: string): TDBItem; virtual; // Устанавливает значение по имени колонки // Должно быть переопределено в потомках procedure SetValue(const FName, FValue: string); virtual; // доступ к значению поля по его имени property Values[const FName: string]: string read GetValue write SetValue; default; // function GetInteger(const FName: string): integer; procedure SetInteger(const FName: string; Value: integer); protected procedure GetLocal(); procedure SetLocal(); procedure GetGlobal(); procedure SetGlobal(); end; // Список однотипных элементов базы данных // Проще говоря - таблица TDbItemList = class(TObjectList) protected ALastID: integer; public DbTableInfo: TDbTableInfo; constructor Create(ADbTableInfo: TDbTableInfo); virtual; function AddItem(AItem: TDbItem; SetNewID: boolean = false): integer; function GetItemByID(ItemID: integer): TDbItem; function GetItemByName(ItemName: string; Wildcard: Boolean = false): TDbItem; function GetItemIDByName(ItemName: string; Wildcard: Boolean = false): Integer; function GetItemNameByID(ItemID: integer): string; function NewItem(): TDbItem; virtual; procedure LoadLocal(); procedure SaveLocal(); end; // Драйвер базы данных - для доступа к хранилищу данных // Это базовый класс, должен быть переопределено для конкретных видов БД TDbDriver = class(TObject) public DbName: string; // Список описаний таблиц TDbTableInfo TablesList: TObjectList; constructor Create(); destructor Destroy(); override; // Открывает указанную базу данных function Open(ADbName: string): boolean; virtual; abstract; // Закрывает указанную базу данных function Close(): boolean; virtual; abstract; // Возвращает описание таблицы по ее имени function GetDbTableInfo(TableName: String): TDbTableInfo; // Заполняет указанную таблицу элементами из базы данных, по заданному фильтру // Фильтр в виде comma-delimited string как поле=значение function GetTable(AItemList: TDbItemList; Filter: string=''): boolean; virtual; abstract; // Заполняет базу данных элементами из указанной таблицы, по заданному фильтру function SetTable(AItemList: TDbItemList; Filter: string=''): boolean; virtual; abstract; // Возвращает DBItem по значению вида Table_name~id // Должно быть переопределено в потомках function GetDBItem(FValue: string): TDBItem; virtual; abstract; function SetDBItem(FItem: TDBItem): boolean; virtual; abstract; end; TDbDriverSQLite = class(TDbDriver) private db: TMkSqLite; Active: boolean; procedure CheckTable(TableInfo: TDbTableInfo); public constructor Create(); //destructor Destroy(); override; function Open(ADbName: string): boolean; override; function Close(): boolean; override; function GetTable(AItemList: TDbItemList; Filter: string=''): boolean; override; function SetTable(AItemList: TDbItemList; Filter: string=''): boolean; override; function GetDBItem(FValue: string): TDBItem; override; function SetDBItem(FItem: TDBItem): boolean; override; end; TDbDriverCSV = class(TDbDriver) private dbPath: string; procedure CheckTable(TableInfo: TDbTableInfo); public function Open(ADbName: string): boolean; override; function Close(): boolean; override; function GetTable(AItemList: TDbItemList; Filter: string=''): boolean; override; function SetTable(AItemList: TDbItemList; Filter: string=''): boolean; override; function GetDBItem(FValue: string): TDBItem; override; function SetDBItem(FItem: TDBItem): boolean; override; end; implementation uses MainFunc; // === TDbTableInfo === function TDbTableInfo.GetField(Index: integer): string; begin result:=''; if (Index >= AFieldsCount) or (Index<0) then Exit; result:=AFieldNames[Index]; end; function TDbTableInfo.GetType(Index: integer): string; begin result:=''; if (Index >= AFieldsCount) or (Index<0) then Exit; result:=AFieldTypes[Index]; end; function TDbTableInfo.GetFieldsCount(): integer; begin result:=self.AFieldsCount; end; procedure TDbTableInfo.AddField(const FieldName, FieldType: string); var i: Integer; s: string; begin for i:=0 to AFieldsCount-1 do begin if AFieldNames[i] = FieldName then Exit; end; Inc(AFieldsCount); SetLength(AFieldNames, AFieldsCount); SetLength(AFieldTypes, AFieldsCount); AFieldNames[AFieldsCount-1]:=FieldName; s:=FieldType; if Length(s)<1 then s:='S'; AFieldTypes[AFieldsCount-1]:=s; end; function TDbTableInfo.FieldIndex(FName: string): Integer; var i: Integer; begin result:=-1; for i:=0 to AFieldsCount do begin if AFieldNames[i] = FName then begin result:=i; Exit; end; end; end; constructor TDbTableInfo.Create(); begin self.Checked:=false; self.AFieldsCount:=0; SetLength(AFieldNames, AFieldsCount); SetLength(AFieldTypes, AFieldsCount); // AddField('id','I'); // AddField('name','S'); // AddField('timestamp','D'); end; // === TDbItem === procedure TDbItem.GetLocal(); begin end; procedure TDbItem.SetLocal(); begin end; procedure TDbItem.GetGlobal(); begin end; procedure TDbItem.SetGlobal(); begin end; procedure TDbItem.InitValues(); var i: Integer; begin SetLength(Self.FValues, Self.DbTableInfo.FieldsCount); for i:=0 to Self.DbTableInfo.FieldsCount-1 do Self.FValues[i]:=''; end; function TDbItem.GetValue(const FName: string): string; var i: Integer; begin if FName='id' then result:=IntToStr(self.ID) else if FName='timestamp' then result:=DateTimeToStr(self.Timestamp) else if FName='name' then result:=self.Name else begin if Length(Self.FValues)=0 then InitValues(); i:=Self.DbTableInfo.FieldIndex(FName); if i<0 then result:='' else result:=Self.FValues[i]; end; end; //function TDbItem.GetDBItem(FName: string): TDBItem; //begin // result:=nil; // if FName='id' then result:=self; //end; procedure TDbItem.SetValue(const FName, FValue: string); var i: Integer; begin if FName='id' then self.ID:=StrToIntDef(FValue, 0) else if FName='timestamp' then self.Timestamp:=StrToDateTimeDef(FValue, self.Timestamp) else if FName='name' then self.Name:=FValue else begin if Length(Self.FValues)=0 then InitValues(); i:=Self.DbTableInfo.FieldIndex(FName); if i>=0 then Self.FValues[i]:=FValue; end; end; function TDbItem.GetInteger(const FName: string): integer; begin result:=StrToIntDef(self.GetValue(FName), 0); end; procedure TDbItem.SetInteger(const FName: string; Value: integer); begin self.SetValue(FName, IntToStr(Value)); end; // === TDbItemList === constructor TDbItemList.Create(ADbTableInfo: TDbTableInfo); begin self.DbTableInfo:=ADbTableInfo; end; procedure TDbItemList.LoadLocal(); begin DbDriver.GetTable(self); end; procedure TDbItemList.SaveLocal(); begin DbDriver.SetTable(self); end; function TDbItemList.AddItem(AItem: TDbItem; SetNewID: boolean = false): integer; begin if SetNewID then begin Inc(self.ALastID); AItem.ID:=self.ALastID; end else begin if self.ALastID < AItem.ID then self.ALastID := AItem.ID; end; AItem.DbTableInfo:=self.DbTableInfo; result:=self.Add(AItem); end; function TDbItemList.GetItemByID(ItemID: integer): TDbItem; var i: integer; begin for i:=0 to self.Count-1 do begin if (self.Items[i] as TDbItem).ID = ItemID then begin result := (self.Items[i] as TDbItem); Exit; end; end; result := nil; end; function TDbItemList.GetItemByName(ItemName: string; Wildcard: Boolean = false): TDbItem; var i: integer; begin if Wildcard then begin for i:=0 to self.Count-1 do begin if Pos(ItemName, (self.Items[i] as TDbItem).Name) > 0 then begin result := (self.Items[i] as TDbItem); Exit; end; end; end else begin for i:=0 to self.Count-1 do begin if (self.Items[i] as TDbItem).Name = ItemName then begin result := (self.Items[i] as TDbItem); Exit; end; end; end; result := nil; end; function TDbItemList.GetItemIDByName(ItemName: string; Wildcard: Boolean = false): Integer; var Item: TDbItem; begin Result:=-1; Item:=Self.GetItemByName(ItemName, Wildcard); if Assigned(Item) then Result:=Item.ID; end; function TDbItemList.GetItemNameByID(ItemID: integer): string; var Item: TDbItem; begin Result:=''; Item:=Self.GetItemByID(ItemID); if Assigned(Item) then Result:=Item.Name; end; function TDbItemList.NewItem(): TDbItem; var NewItem: TDbItem; begin NewItem:=TDbItem.Create(); self.AddItem(NewItem, true); result:=NewItem; end; // === TDbDriver === constructor TDbDriver.Create(); begin self.TablesList:=TObjectList.Create(false); end; destructor TDbDriver.Destroy(); begin self.Close(); self.TablesList.Free(); end; function TDbDriver.GetDbTableInfo(TableName: String): TDbTableInfo; var i: integer; begin Result:=nil; for i:=0 to Self.TablesList.Count-1 do begin if (Self.TablesList[i] as TDbTableInfo).TableName = TableName then begin Result:=(Self.TablesList[i] as TDbTableInfo); Exit; end; end; end; // === TDbDriverSQLite === constructor TDbDriverSQLite.Create(); begin inherited Create(); self.Active:=false; end; procedure TDbDriverSQLite.CheckTable(TableInfo: TDbTableInfo); var rs: IMkSqlStmt; s, sn, st, sql: string; i: integer; begin if not Assigned(db) then Exit; if TableInfo.Checked then Exit; if Self.TablesList.IndexOf(TableInfo)>=0 then Exit; //sql:='SELECT * FROM sqlite_master WHERE type=''table'' and name='''+TableInfo.TableName+''''; //DebugSQL(sql); rs:=db.SchemaTableInfo(TableInfo.TableName); if rs.rowCount<=0 then begin s:=''; for i:=0 to TableInfo.FieldsCount-1 do begin sn:=TableInfo.Fields[i]; st:=TableInfo.Types[i]; if Length(s)>0 then s:=s+','; s:=s+''''+sn+''''; if sn='id' then begin s:=s+' INTEGER PRIMARY KEY NOT NULL'; TableInfo.KeyFieldName:=sn; end else if st='I' then s:=s+' INTEGER NOT NULL' else if st='S' then s:=s+' TEXT NOT NULL' else if st='B' then s:=s+' INTEGER NOT NULL' else if st='D' then s:=s+' TEXT NOT NULL' else if st='' then // nothing; else if st[1]='L' then s:=s+' INTEGER NOT NULL'; end; rs.close(); sql:='CREATE TABLE '''+TableInfo.TableName+''' ('+s+')'; DebugSQL(sql); rs:=db.Exec(sql); end; rs.close(); TableInfo.Checked:=true; Self.TablesList.Add(TableInfo); end; function TDbDriverSQLite.Open(ADbName: string): boolean; begin DbName:= ADbName; result:=true; if Assigned(db) then FreeAndNil(db); try db:=TMkSqLite.Create(nil); db.dbName:=ExtractFileDir(ParamStr(0))+'\Data\'+ADbName+'.sqlite'; db.Open(); except Close(); result:=false; end; Active:=result; end; function TDbDriverSQLite.Close(): boolean; begin result:=true; TablesList.Clear(); if not Active then Exit; if not Assigned(db) then Exit; db.close(); FreeAndNil(db); end; function TDbDriverSQLite.GetTable(AItemList: TDbItemList; Filter: string=''): boolean; var rs: IMkSqlStmt; i, n, m: integer; Item: TDbItem; fn, sql: string; fl: TStringList; FilterOk: boolean; begin result:=false; if not Active then Exit; if not Assigned(AItemList) then Exit; if not Assigned(db) then Exit; CheckTable(AItemList.DbTableInfo); fl:=TStringList.Create(); // filters fl.CommaText:=Filter; sql:='SELECT * FROM "'+AItemList.DbTableInfo.TableName+'"'; // filters if fl.Count > 0 then sql:=sql+' WHERE '; for m:=0 to fl.Count-1 do begin if m>0 then sql:=sql+' AND '; sql:=sql+'"'+fl.Names[m]+'"="'+fl.ValueFromIndex[m]+'"'; end; DebugSQL(sql); rs:=db.Exec(sql); while not rs.eof do begin i := rs.ValueOf['id']; Item := AItemList.GetItemByID(i); if not Assigned(Item) then Item:=AItemList.NewItem(); for n:=0 to AItemList.DbTableInfo.FieldsCount-1 do begin fn:=AItemList.DbTableInfo.GetField(n); Item.SetValue(fn, rs.ValueOf[fn]); end; rs.Next(); end; result:=true; end; function TDbDriverSQLite.SetTable(AItemList: TDbItemList; Filter: string=''): boolean; var i, n: integer; Item: TDbItem; fn, iv, vl, sql: string; begin result:=false; if not Active then Exit; if not Assigned(AItemList) then Exit; if not Assigned(db) then Exit; CheckTable(AItemList.DbTableInfo); for i:=0 to AItemList.Count-1 do begin vl:=''; Item:=(AItemList[i] as TDbItem); for n:=0 to AItemList.DbTableInfo.FieldsCount-1 do begin fn:=AItemList.DbTableInfo.GetField(n); iv:=Item.GetValue(fn); if n > 0 then vl:=vl+','; vl:=vl+'"'+iv+'"'; //vl:=vl+fn+'='''+iv+''''; end; sql:='INSERT OR REPLACE INTO "'+AItemList.DbTableInfo.TableName+'" VALUES ('+vl+')'; DebugSQL(sql); //sql:='UPDATE '+AItemList.DbTableInfo.TableName+' SET '+vl+' WHERE ROWID='+IntToStr(Item.ID); db.exec(sql); end; end; function TDbDriverSQLite.GetDBItem(FValue: String): TDbItem; var sTableName, sItemID, fn, sql: string; i: Integer; TableInfo: TDbTableInfo; rs: IMkSqlStmt; begin Result:=nil; if not Assigned(db) then Exit; i:=Pos('~', FValue); sTableName:=Copy(FValue, 1, i-1); sItemID:=Copy(FValue, i+1, MaxInt); TableInfo:=Self.GetDbTableInfo(sTableName); if not Assigned(TableInfo) then Exit; sql:='SELECT * FROM '+TableInfo.TableName+' WHERE id="'+sItemID+'"'; DebugSQL(sql); rs:=db.Exec(sql); if not rs.eof then begin Result:=TDbItem.Create(); for i:=0 to TableInfo.FieldsCount-1 do begin fn:=TableInfo.GetField(i); Result.SetValue(fn, rs.ValueOf[fn]); end; end; end; function TDbDriverSQLite.SetDBItem(FItem: TDBItem): boolean; var n: integer; Item: TDbItem; TableInfo: TDbTableInfo; fn, iv, vl, sql: string; begin result:=false; if not Active then Exit; if not Assigned(FItem) then Exit; if not Assigned(db) then Exit; TableInfo:=FItem.DbTableInfo; if not Assigned(TableInfo) then Exit; CheckTable(TableInfo); vl:=''; for n:=0 to TableInfo.FieldsCount-1 do begin fn:=TableInfo.GetField(n); iv:=FItem.GetValue(fn); if n > 0 then vl:=vl+','; vl:=vl+'"'+iv+'"'; //vl:=vl+fn+'='''+iv+''''; end; sql:='INSERT OR REPLACE INTO "'+TableInfo.TableName+'" VALUES ('+vl+')'; DebugSQL(sql); //sql:='UPDATE '+AItemList.DbTableInfo.TableName+' SET '+vl+' WHERE ROWID='+IntToStr(Item.ID); db.exec(sql); result:=true; end; // === TDbDriverCSV === function TDbDriverCSV.Open(ADbName: string): boolean; begin self.DbName:=ADbName; self.dbPath:=ExtractFileDir(ParamStr(0))+'\Data\'; result:=true; end; function TDbDriverCSV.Close(): boolean; begin result:=true; end; procedure TDbDriverCSV.CheckTable(TableInfo: TDbTableInfo); begin if TableInfo.Checked then Exit; if Self.TablesList.IndexOf(TableInfo)>=0 then Exit; TableInfo.Checked:=true; Self.TablesList.Add(TableInfo); end; function TDbDriverCSV.GetTable(AItemList: TDbItemList; Filter: string=''): boolean; var sl, vl, fl: TStringList; i, n, m, id: integer; Item: TDbItem; fn: string; FilterOk: boolean; begin result:=false; if not Assigned(AItemList) then Exit; CheckTable(AItemList.DbTableInfo); fn:=self.dbPath+'\'+AItemList.DbTableInfo.TableName+'.lst'; if not FileExists(fn) then Exit; sl:=TStringList.Create(); try sl.LoadFromFile(fn); except sl.Free(); Exit; end; vl:=TStringList.Create(); // row values fl:=TStringList.Create(); // filters fl.CommaText:=Filter; // первая строка - список колонок! for i:=1 to sl.Count-1 do begin vl.Clear(); vl.CommaText:=StringReplace(sl[i], '~>', #13+#10, [rfReplaceAll]); if vl.Count=0 then Continue; if vl.Count < AItemList.DbTableInfo.FieldsCount then Continue; //!! // check filters FilterOk:=true; if fl.Count>0 then begin for n:=0 to AItemList.DbTableInfo.FieldsCount-1 do begin fn:=AItemList.DbTableInfo.GetField(n); for m:=0 to fl.Count-1 do begin if fl.Names[m]=fn then begin if fl.ValueFromIndex[m]<>vl[n] then FilterOk:=false; Break; end; end; end; end; if not FilterOk then Continue; // Create new item id:=StrToInt(vl[0]); Item := AItemList.GetItemByID(id); if not Assigned(Item) then Item:=AItemList.NewItem(); // fill item values for n:=0 to AItemList.DbTableInfo.FieldsCount-1 do begin fn:=AItemList.DbTableInfo.GetField(n); Item.SetValue(fn, vl[n]); end; end; fl.Free(); vl.Free(); sl.Free(); result:=true; end; function TDbDriverCSV.SetTable(AItemList: TDbItemList; Filter: string=''): boolean; var sl, vl: TStringList; i, n: integer; Item: TDbItem; fn: string; begin result:=false; if not Assigned(AItemList) then Exit; CheckTable(AItemList.DbTableInfo); sl:=TStringList.Create(); vl:=TStringList.Create(); // columns headers for n:=0 to AItemList.DbTableInfo.FieldsCount-1 do begin fn:=AItemList.DbTableInfo.GetField(n); vl.Add(fn); end; sl.Add(vl.CommaText); // rows for i:=0 to AItemList.Count-1 do begin vl.Clear(); Item:=(AItemList[i] as TDbItem); for n:=0 to AItemList.DbTableInfo.FieldsCount-1 do begin fn:=AItemList.DbTableInfo.GetField(n); vl.Add(Item.GetValue(fn)); end; sl.Add(StringReplace(vl.CommaText, #13+#10, '~>', [rfReplaceAll])); end; vl.Free(); try sl.SaveToFile(self.dbPath+'\'+AItemList.DbTableInfo.TableName+'.lst'); finally sl.Free(); end; end; function TDbDriverCSV.GetDBItem(FValue: String): TDbItem; var sTableName, sItemID, fn, sql: string; i: Integer; TableInfo: TDbTableInfo; ItemList: TDbItemList; Filter: string; begin Result:=nil; i:=Pos('~', FValue); sTableName:=Copy(FValue, 1, i-1); sItemID:=Copy(FValue, i+1, MaxInt); TableInfo:=Self.GetDbTableInfo(sTableName); if not Assigned(TableInfo) then Exit; ItemList:=TDbItemList.Create(TableInfo); Filter:='id='+sItemID; if not GetTable(ItemList, Filter) then Exit; if ItemList.Count=0 then Exit; result:=(ItemList[0] as TDbItem); end; function TDbDriverCSV.SetDBItem(FItem: TDBItem): boolean; var AItemList: TDbItemList; AItem: TDbItem; i: Integer; fn: string; begin Result:=False; AItemList:=TDbItemList.Create(FItem.DbTableInfo); Self.GetTable(AItemList); AItem:=AItemList.GetItemByID(FItem.ID); if not Assigned(AItem) then begin FreeAndNil(AItemList); Exit; end; for i:=0 to FItem.DbTableInfo.FieldsCount-1 do begin fn:=FItem.DbTableInfo.GetField(i); AItem.Values[fn]:=FItem.Values[fn]; end; Self.SetTable(AItemList); FreeAndNil(AItemList); result:=true; end; end.
unit ConsultingUnit; {* Интерфейсы для работы со службой ПП } // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\ConsultingUnit.pas" // Стереотип: "Interfaces" // Элемент модели: "Consulting" MUID: (457007DB002E) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , IOUnit , BaseTypesUnit , StartUnit , DynamicDocListUnit , FoldersUnit , DocumentUnit //#UC START# *457007DB002Eintf_uses* //#UC END# *457007DB002Eintf_uses* ; type TEstimationValue = ( {* Возможные оценки } EV_UNDEFINED {* оценка не выставлена } , EV_VERY_GOOD {* супер!!! } , EV_GOOD {* хорошо } , EV_NORMAL {* сойдёт } , EV_BAD {* полная фигня... } );//TEstimationValue NoDocumentList = class {* Нет списка документов в ответе } end;//NoDocumentList NoConnection = class {* Нет связи с сервером консультаций } end;//NoConnection NoSubscription = class {* Нет доступа с сервису - вы не подписаны на услугу } end;//NoSubscription PaymentForbidden = class {* У пользователя нет прав оплачивать консультации } end;//PaymentForbidden NotDeleted = class {* Нельзя удалить консультацию } end;//NotDeleted Deleted = class {* Консультация удалена - все операции запрещены } end;//Deleted IEstimation = interface {* Оценка } ['{DD01B380-09FE-4476-8789-20B2291FE41B}'] function GetValue: TEstimationValue; stdcall; procedure SetValue(aValue: TEstimationValue); stdcall; procedure GetText; stdcall; procedure SetText(const aValue); stdcall; property Value: TEstimationValue read GetValue write SetValue; {* оценка } property Text: read GetText write SetText; {* комментарий к оценке } end;//IEstimation OldFormatConsultation = class {* консультация старого формата } end;//OldFormatConsultation TConsultationStatus = Cardinal; IParasList = array of IString; IConsultation = interface(IEntityBase) {* Консультация } ['{69D87373-CAC1-4228-9F26-4E46D2A8CBE9}'] function GetStatus: TConsultationStatus; stdcall; { can raise Deleted } procedure GetId; stdcall; { can raise Deleted } procedure GetCreationDate; stdcall; { can raise Deleted } procedure GetModificationDate; stdcall; { can raise Deleted } procedure GetName; stdcall; { can raise Deleted } procedure GetQueryData; stdcall; { can raise Deleted } procedure GetUserName; stdcall; { can raise Deleted } procedure GetExpertInfo; stdcall; { can raise Deleted } procedure GetExpertName; stdcall; { can raise Deleted } procedure GetReplyDate; stdcall; { can raise Deleted } procedure GetType; stdcall; { can raise Deleted } procedure GetAnswer(out aRet {* IDocument }); stdcall; { can raise Deleted, OldFormatConsultation } {* Получить уведомление или ответ на запрос } procedure GetQuery(out aRet {* IDocument }); stdcall; { can raise Deleted, OldFormatConsultation } {* Получить запрос } procedure GetDocumentList(out aRet {* IDynList }); stdcall; { can raise NoDocumentList, Deleted, OldFormatConsultation } {* Получить список документов ответа } procedure SendEstimation(const value: IEstimation); stdcall; { can raise NoConnection, NoSubscription, Deleted } {* Отправить оценку } procedure CreateEstimation(out aRet {* IEstimation }); stdcall; {* создать оценку } procedure PaymentConfirm(answer: Boolean); stdcall; { can raise NoConnection, PaymentForbidden } {* Подвердить (answer = true)/отказаться (false) от оплаты } procedure Read; stdcall; { can raise Deleted } {* Помечают консультацию как прочитанную } function HasList: ByteBool; stdcall; { can raise Deleted } function HasEstimation: ByteBool; stdcall; { can raise Deleted } function HasPaymentInformation: ByteBool; stdcall; { can raise Deleted } procedure GetQueryByParas(out aRet {* IParasList }); stdcall; {* получить запрос в виде списка параграфов } procedure GetAnswerData(out is_evd: Boolean; out aRet {* IParasList }); stdcall; property Status: TConsultationStatus read GetStatus; {* Статус консультации } property Id: read GetId; {* Идентификатор консультации } property CreationDate: read GetCreationDate; {* Дата создания } property ModificationDate: read GetModificationDate; {* Дата последнего изменения статуса } property Name: read GetName; {* Имя консультации (текст запроса) } property QueryData: read GetQueryData; property UserName: read GetUserName; property ExpertInfo: read GetExpertInfo; property ExpertName: read GetExpertName; property ReplyDate: read GetReplyDate; property Type: read GetType; end;//IConsultation TTemplateType = ( {* тип шаблона } PREANSWER_TEMPLATE {* шаблон запроса об оплате } , ANSWER_TEMPLATE {* шаблон ответа } , QUERY_TEMPLATE {* шаблон запроса } );//TTemplateType IConsultationManager = interface {* Менеджер консультаций } ['{713794D3-0F90-4EE5-AF5D-644D9091DA0C}'] function CheckInternetChannel: ByteBool; stdcall; {* Проверка интернет канала } function CheckConsultingAvailable: ByteBool; stdcall; {* Проверка досутпности консультационных услуг } procedure DeleteConsultation(var for_delete: IConsultation); stdcall; { can raise NotDeleted, Deleted } {* Удалить консультацию } function UpdateNotReadedConsultations: Cardinal; stdcall; {* Возвращает количество непрочитанных консультаций } procedure LoadFromXml(file_name: PAnsiChar); stdcall; { can raise AccessDenied, InvalidXMLType } {* загрузить консультацию из файла } function CantReceiveAnswer: ByteBool; stdcall; {* Сообщает о невозможности получать ответы (true - когда лампочку надо включать) } procedure CreateQueryWithNoticeUser; stdcall; {* Создание уведомления пользователя о консалтинге } end;//IConsultationManager IConsultingTemplateInfo = interface {* Информация для шаблонов консалтинга. Сейчас в базе есть 2 шаблона (preanswer и answer). Какой шаблон нужен для консультации спрашиваем у get_template_type } ['{3613E72E-8CD0-4D45-B517-BD45F9764A82}'] procedure GetPreanswerTemplate(out aRet {* IStream }); stdcall; procedure GetAnswerTemplate(out aRet {* IStream }); stdcall; procedure GetDealerInfo(out aRet {* IString }); stdcall; {* информация о комплекте, которая может быть нужна для шаблона. См. [$100008775] } function GetTemplateType(const consultation: IConsultation): TTemplateType; stdcall; { can raise Deleted } {* определяет какой шаблон нужен для отображения консультации } procedure GetQueryTemplate(out aRet {* IStream }); stdcall; {* получить шаблон для запроса } end;//IConsultingTemplateInfo const {* Статусы консультаций } CS_SENT: TConsultationStatus = 1024; {* Отправлена } CS_PAYMENT_REQUEST: TConsultationStatus = 1; {* Запрос на оплату } CS_ANSWER_RECEIVED: TConsultationStatus = 2; {* Получен ответ } CS_READ: TConsultationStatus = 4; CS_ESTIMATION_SENT: TConsultationStatus = 8; {* Отправлена оценка } CS_DRAFTS: TConsultationStatus = 16; {* Создана, но не отправлена } CS_PAYMENT_REFUSAL: TConsultationStatus = 32; {* Оплата отклонена } CS_PAYMENT_CONFIRM: TConsultationStatus = 64; CS_VALIDATION_FAILED: TConsultationStatus = 128; CS_ANSWER_NOT_CONFIRM: TConsultationStatus = 256; CS_READ_NOT_CONFIRM: TConsultationStatus = 512; implementation uses l3ImplUses //#UC START# *457007DB002Eimpl_uses* //#UC END# *457007DB002Eimpl_uses* ; end.
{******************************************************************************* 作者: dmzn@163.com 2011-11-21 描述: 产品订单验收 *******************************************************************************} unit UFrameProductBillYS; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameBase, UGridPainter, cxControls, cxLookAndFeels, cxLookAndFeelPainters, Grids, UGridExPainter, cxPC, StdCtrls, ExtCtrls, cxGraphics, Menus, cxButtons; type TfFrameProductBillYS = class(TfFrameBase) PanelR: TPanel; LabelHint: TLabel; wPage: TcxPageControl; Sheet1: TcxTabSheet; Sheet2: TcxTabSheet; GridBill: TDrawGridEx; GridDone: TDrawGridEx; procedure BtnExitClick(Sender: TObject); procedure wPageChange(Sender: TObject); private { Private declarations } FPainter: TGridPainter; FPainter2: TGridPainter; //绘图对象 FDoneLoaded: Boolean; //载入标记 procedure LoadProductBill; procedure LoadProductBillDone; //产品列表 procedure OnBtnClick(Sender: TObject); procedure OnBtnClick2(Sender: TObject); //点击按钮 public { Public declarations } procedure OnCreateFrame; override; procedure OnDestroyFrame; override; class function FrameID: integer; override; end; implementation {$R *.dfm} uses IniFiles, ULibFun, UDataModule, DB, UMgrControl, USysConst, USysDB, USysFun, UFormProductBillView, UFormProductBillSH, UFormProductBillDeal; class function TfFrameProductBillYS.FrameID: integer; begin Result := cFI_FrameBillYS; end; procedure TfFrameProductBillYS.OnCreateFrame; var nIni: TIniFile; begin FDoneLoaded := False; Name := MakeFrameName(FrameID); FPainter := TGridPainter.Create(GridBill); FPainter2 := TGridPainter.Create(GridDone); with FPainter do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('序号', 50); AddHeader('订单编号', 50); AddHeader('简要说明', 50); AddHeader('订货件数', 50); AddHeader('待收件数', 50); AddHeader('订货人', 50); AddHeader('订货时间', 50); AddHeader('操作', 50); end; with FPainter2 do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('序号', 50); AddHeader('订单编号', 50); AddHeader('简要说明', 50); AddHeader('订货件数', 50); AddHeader('订货人', 50); AddHeader('订货时间', 50); AddHeader('收货时间', 50); AddHeader('操作', 50); end; nIni := TIniFile.Create(gPath + sFormConfig); try LoadDrawGridConfig(Name, GridBill, nIni); LoadDrawGridConfig(Name, GridDone, nIni); wPage.ActivePage := Sheet1; LoadProductBill; finally nIni.Free; end; end; procedure TfFrameProductBillYS.OnDestroyFrame; var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try SaveDrawGridConfig(Name, GridBill, nIni); SaveDrawGridConfig(Name, GridDone, nIni); finally nIni.Free; end; FPainter.Free; FPainter2.Free; end; procedure TfFrameProductBillYS.BtnExitClick(Sender: TObject); begin Close; end; //Desc: 载入待验收订单 procedure TfFrameProductBillYS.LoadProductBill; var nStr,nHint: string; nDS: TDataSet; nIdx,nInt: Integer; nBtn: TcxButton; nData: TGridDataArray; begin nStr := 'Select dt.*,StyleName,ColorName,SizeName,O_Man,O_Date From $DT dt ' + ' Left Join $PT pt On pt.ProductID=dt.D_Product ' + ' Left Join $ST st On st.StyleID=pt.StyleID ' + ' Left Join $SZ sz On sz.SizeID=pt.SizeID ' + ' Left Join $CR cr On cr.ColorID=pt.ColorID ' + ' Left Join $OD od On od.O_ID=dt.D_Order ' + 'Where O_TerminalId=''$ID'' And (O_Status=''$DL'' Or ' + ' O_Status=''$TD'') ' + 'Order By D_Order DESC'; //xxxxx nStr := MacroValue(nStr, [MI('$DT', sTable_OrderDtl), MI('$PT', sTable_DL_Product), MI('$ST', sTable_DL_Style), MI('$SZ', sTable_DL_Size), MI('$CR', sTable_DL_Color), MI('$OD', sTable_Order), MI('$ID', gSysParam.FTerminalID), MI('$FH', sFlag_BillLock), MI('$DL', sFlag_BillDeliver), MI('$TD', sFlag_BillTakeDeliv)]); //xxxxx nDS := FDM.LockDataSet(nStr, nHint); try if not Assigned(nDS) then begin ShowDlg(nHint, sWarn); Exit; end; FPainter.ClearData; if nDS.RecordCount < 1 then Exit; with nDS do begin First; nInt := 1; while not Eof do begin SetLength(nData, 9); for nIdx:=Low(nData) to High(nData) do begin nData[nIdx].FCtrls := nil; nData[nIdx].FAlign := taCenter; end; nData[0].FText := IntToStr(nInt); Inc(nInt); nData[1].FText := FieldByName('D_Order').AsString; nStr := Format('%s_%s_%s', [FieldByName('StyleName').AsString, FieldByName('ColorName').AsString, FieldByName('SizeName').AsString]); nData[2].FText := nStr; nData[3].FText := FieldByName('D_Number').AsString; nData[4].FText := IntToStr(FieldByName('D_Number').AsInteger - FieldByName('D_HasIn').AsInteger); //xxxxx nData[5].FText := FieldByName('O_Man').AsString; nData[6].FText := DateTime2Str(FieldByName('O_Date').AsDateTime); with nData[7] do begin FText := ''; FAlign := taLeftJustify; FCtrls := TList.Create; nBtn := TcxButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Caption := '查看'; Width := 35; Height := 18; OnClick := OnBtnClick; Tag := FPainter.DataCount; end; nBtn := TcxButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Caption := '收货'; Width := 35; Height := 18; OnClick := OnBtnClick; Tag := FPainter.DataCount; end; if FieldByName('D_HasIn').AsInteger > 0 then begin nBtn := TcxButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Caption := '明细'; Width := 35; Height := 18; OnClick := OnBtnClick; Tag := FPainter.DataCount; end; end; end; nData[8].FText := FieldByName('R_ID').AsString; FPainter.AddData(nData); Next; end; end; FDoneLoaded := False; finally FDM.ReleaseDataSet(nDS); end; end; //Desc: 载入已完成订单 procedure TfFrameProductBillYS.LoadProductBillDone; var nStr,nHint: string; nDS: TDataSet; nIdx,nInt: Integer; nBtn: TcxButton; nData: TGridDataArray; begin if FDoneLoaded then Exit; //重复载入判定 nStr := 'Select Top 50 dt.*,StyleName,ColorName,SizeName,O_Man,O_Date From $DT dt ' + ' Left Join $PT pt On pt.ProductID=dt.D_Product ' + ' Left Join $ST st On st.StyleID=pt.StyleID ' + ' Left Join $SZ sz On sz.SizeID=pt.SizeID ' + ' Left Join $CR cr On cr.ColorID=pt.ColorID ' + ' Left Join $OD od On od.O_ID=dt.D_Order ' + 'Where O_TerminalId=''$ID'' And O_Status=''$OK'' ' + 'Order By D_Order DESC'; //xxxxx nStr := MacroValue(nStr, [MI('$DT', sTable_OrderDtl), MI('$PT', sTable_DL_Product), MI('$ST', sTable_DL_Style), MI('$SZ', sTable_DL_Size), MI('$CR', sTable_DL_Color), MI('$OD', sTable_Order), MI('$ID', gSysParam.FTerminalID), MI('$OK', sFlag_BillDone)]); //xxxxx nDS := FDM.LockDataSet(nStr, nHint); try if not Assigned(nDS) then begin ShowDlg(nHint, sWarn); Exit; end; FPainter2.ClearData; if nDS.RecordCount < 1 then Exit; with nDS do begin First; nInt := 1; while not Eof do begin SetLength(nData, 8); for nIdx:=Low(nData) to High(nData) do begin nData[nIdx].FCtrls := nil; nData[nIdx].FAlign := taCenter; end; nData[0].FText := IntToStr(nInt); Inc(nInt); nData[1].FText := FieldByName('D_Order').AsString; nStr := Format('%s_%s_%s', [FieldByName('StyleName').AsString, FieldByName('ColorName').AsString, FieldByName('SizeName').AsString]); nData[2].FText := nStr; nData[3].FText := FieldByName('D_Number').AsString; nData[4].FText := IntToStr(FieldByName('D_Number').AsInteger - FieldByName('D_HasIn').AsInteger); //xxxxx nData[4].FText := FieldByName('O_Man').AsString; nData[5].FText := DateTime2Str(FieldByName('O_Date').AsDateTime); nData[6].FText := DateTime2Str(FieldByName('D_InDate').AsDateTime); with nData[7] do begin FText := ''; FCtrls := TList.Create; nBtn := TcxButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Caption := '查看'; Width := 35; Height := 18; OnClick := OnBtnClick2; Tag := FPainter2.DataCount; end; nBtn := TcxButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Caption := '明细'; Width := 35; Height := 18; OnClick := OnBtnClick2; Tag := FPainter2.DataCount; end; end; FPainter2.AddData(nData); Next; end; end; FDoneLoaded := True; finally FDM.ReleaseDataSet(nDS); end; end; //Desc: 页面切换 procedure TfFrameProductBillYS.wPageChange(Sender: TObject); begin if wPage.ActivePage = Sheet2 then LoadProductBillDone; end; //Desc: 按钮 procedure TfFrameProductBillYS.OnBtnClick(Sender: TObject); var nTag: Integer; begin nTag := TComponent(Sender).Tag; if Sender = FPainter.Data[nTag][7].FCtrls[0] then begin if ShowProductBillView(FPainter.Data[nTag][1].FText) then begin TcxButton(Sender).Enabled := False; LoadProductBill; end; end else //查看订单 if Sender = FPainter.Data[nTag][7].FCtrls[1] then begin if ShowProductBillSH(FPainter.Data[nTag][1].FText, FPainter.Data[nTag][8].FText) then begin TcxButton(Sender).Enabled := False; LoadProductBill; end; end else //收货 if Sender = FPainter.Data[nTag][7].FCtrls[2] then begin ShowProductBillDealView(FPainter.Data[nTag][1].FText); end; //收货明细 end; //Desc: 完成列表按钮 procedure TfFrameProductBillYS.OnBtnClick2(Sender: TObject); var nTag: Integer; begin nTag := TComponent(Sender).Tag; if Sender = FPainter2.Data[nTag][7].FCtrls[0] then begin ShowProductBillView(FPainter2.Data[nTag][1].FText, False); end else //查看订单 if Sender = FPainter2.Data[nTag][7].FCtrls[1] then begin ShowProductBillDealView(FPainter2.Data[nTag][1].FText); end; //收货明细 end; initialization gControlManager.RegCtrl(TfFrameProductBillYS, TfFrameProductBillYS.FrameID); end.
{ *************************************************************************** } { } { NLDSnapPanel - www.nldelphi.com Open Source designtime component } { } { Initiator: Albert de Weerd (aka NGLN) } { License: Free to use, free to modify } { SVN path: http://svn.nldelphi.com/nldelphi/opensource/ngln/NLDSnapPanel } { } { *************************************************************************** } { } { Edit by: Albert de Weerd } { Date: May 23, 2008 } { Version: 1.0.0.0 } { } { *************************************************************************** } unit NLDSnapPanel; interface uses Windows, Classes, Graphics, ExtCtrls, Messages, Controls, Buttons; const DefMaxWidth = 105; DefMinWidth = 5; type TNLDSnapPanel = class(TCustomPanel) private FAutoHide: Boolean; FGhostWin: TWinControl; FMaxWidth: Integer; FMinWidth: Integer; FMouseCaptured: Boolean; FPinButton: TSpeedButton; FPinButtonDownHint: String; FPinButtonUpHint: String; FTimer: TTimer; FUnhiding: Boolean; function GetShowHint: Boolean; function GetWidth: Integer; function IsShowHintStored: Boolean; procedure PinButtonClick(Sender: TObject); procedure SetAutoHide(const Value: Boolean); procedure SetMinWidth(const Value: Integer); procedure SetPinButtonDownHint(const Value: String); procedure SetPinButtonUpHint(const Value: String); procedure SetShowHint(const Value: Boolean); procedure SetWidth(const Value: Integer); procedure Timer(Sender: TObject); procedure UpdatePinButtonHint; procedure CMControlListChange(var Message: TCMControlListChange); message CM_CONTROLLISTCHANGE; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; protected procedure AdjustClientRect(var Rect: TRect); override; procedure Paint; override; procedure SetParent(AParent: TWinControl); override; public constructor Create(AOwner: TComponent); override; published property AutoHide: Boolean read FAutoHide write SetAutoHide default False; property MinWidth: Integer read FMinWidth write SetMinWidth default DefMinWidth; property PinButtonDownHint: String read FPinButtonDownHint write SetPinButtonDownHint; property PinButtonUpHint: String read FPinButtonUpHint write SetPinButtonUpHint; property ShowHint: Boolean read GetShowHint write SetShowHint stored IsShowHintStored; property Width: Integer read GetWidth write SetWidth default DefMaxWidth; published property Alignment default taLeftJustify; property BevelInner; property BevelOuter; property BevelWidth; property BorderWidth; property BorderStyle; property Caption; property Color; property Font; property Hint; property ParentBackground; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property TabOrder; property Visible; end; procedure Register; implementation {$R *.res} uses Math, Themes; procedure Register; begin RegisterComponents('NLDelphi', [TNLDSnapPanel]); end; { TNLDSnapPanel } resourcestring SPinButtonBmpResName = 'PINBUTTON'; const DefPinButtonSize = 20; DefPinButtonMargin = 3; DefResizeStep = 15; DefTimerInterval = 20; procedure TNLDSnapPanel.AdjustClientRect(var Rect: TRect); begin inherited AdjustClientRect(Rect); Inc(Rect.Top, DefPinButtonSize + 2 * DefPinButtonMargin); end; procedure TNLDSnapPanel.CMControlListChange( var Message: TCMControlListChange); begin if Message.Inserting then with Message.Control do Anchors := Anchors - [akLeft] + [akRight]; end; procedure TNLDSnapPanel.CMMouseEnter(var Message: TMessage); begin inherited; if FAutoHide then if not FMouseCaptured then begin FMouseCaptured := True; FUnhiding := True; FTimer.Enabled := True; end; end; procedure TNLDSnapPanel.CMMouseLeave(var Message: TMessage); begin inherited; if FAutoHide then begin FMouseCaptured := PtInRect(ClientRect, ScreenToClient(Mouse.CursorPos)); if not FMouseCaptured then begin FUnhiding := False; FTimer.Enabled := True; end; end; end; constructor TNLDSnapPanel.Create(AOwner: TComponent); begin inherited Create(AOwner); FMaxWidth := DefMaxWidth; FMinWidth := DefMinWidth; Alignment := taLeftJustify; Align := alLeft; Left := 0; Top := 0; inherited Width := FMaxWidth; FTimer := TTimer.Create(Self); FTimer.Enabled := False; FTimer.Interval := DefTimerInterval; FTimer.OnTimer := Timer; FPinButton := TSpeedButton.Create(Self); FPinButton.Glyph.LoadFromResourceName(HInstance, SPinButtonBmpResName); FPinButton.GroupIndex := -1; FPinButton.AllowAllUp := True; FPinButton.Down := True; FPinButton.Anchors := [akTop, akRight]; FPinButton.SetBounds(DefMaxWidth - DefPinButtonSize - FMinWidth, DefPinButtonMargin, DefPinButtonSize, DefPinButtonSize); FPinButton.OnClick := PinButtonClick; FPinButton.Parent := Self; end; function TNLDSnapPanel.GetShowHint: Boolean; begin Result := inherited ShowHint; end; function TNLDSnapPanel.GetWidth: Integer; begin Result := inherited Width; end; function TNLDSnapPanel.IsShowHintStored: Boolean; begin Result := not ParentShowHint; end; procedure TNLDSnapPanel.Paint; const Alignments: array[TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER); var Rect: TRect; TopColor, BottomColor: TColor; FontHeight: Integer; Flags: Longint; procedure AdjustColors(Bevel: TPanelBevel); begin TopColor := clBtnHighlight; if Bevel = bvLowered then TopColor := clBtnShadow; BottomColor := clBtnShadow; if Bevel = bvLowered then BottomColor := clBtnHighlight; end; begin 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; with Canvas do begin if not ThemeServices.ThemesEnabled or not ParentBackground then begin Brush.Color := Color; FillRect(Rect); end; Brush.Style := bsClear; Font := Self.Font; FontHeight := TextHeight('W'); with Rect do begin Left := Width - FMaxWidth + FMinWidth; Top := 5; Bottom := Top + FontHeight; Right := Width - DefPinButtonSize - FMinWidth - 5; end; Flags := DT_EXPANDTABS or Alignments[Alignment]; Flags := DrawTextBiDiModeFlags(Flags); DrawText(Handle, PChar(Caption), -1, Rect, Flags); Pen.Color := clBtnShadow; MoveTo(Rect.Left, Rect.Bottom + DefPinButtonMargin); LineTo(Rect.Right, PenPos.Y); end; end; procedure TNLDSnapPanel.PinButtonClick(Sender: TObject); begin AutoHide := not FPinButton.Down; end; procedure TNLDSnapPanel.SetAutoHide(const Value: Boolean); begin if FAutoHide <> Value then begin FAutoHide := Value; FPinButton.Down := not FAutoHide; if FAutoHide then begin Align := alNone; Anchors := [akLeft, akTop, akBottom]; FGhostWin := TWinControl.Create(Self); FGhostWin.Align := alLeft; FGhostWin.Width := FMinWidth; FGhostWin.Parent := Parent; FGhostWin.SendToBack; end else begin Align := alLeft; FGhostWin.Free; FGhostWin := nil; end; UpdatePinButtonHint; end; end; procedure TNLDSnapPanel.SetMinWidth(const Value: Integer); begin if FMinWidth <> Value then begin FPinButton.Left := FPinButton.Left + FMinWidth - Value; FMinWidth := Value; if FAutoHide and not FUnhiding then begin inherited Width := FMinWidth; FGhostWin.Width := FMinWidth; end; end; end; procedure TNLDSnapPanel.SetParent(AParent: TWinControl); begin inherited SetParent(AParent); if FGhostWin <> nil then begin FGhostWin.Parent := AParent; FGhostWin.SendToBack; end; end; procedure TNLDSnapPanel.SetPinButtonDownHint(const Value: String); begin if FPinButtonDownHint <> Value then begin FPinButtonDownHint := Value; UpdatePinButtonHint; end; end; procedure TNLDSnapPanel.SetPinButtonUpHint(const Value: String); begin if FPinButtonUpHint <> Value then begin FPinButtonUpHint := Value; UpdatePinButtonHint; end; end; procedure TNLDSnapPanel.SetShowHint(const Value: Boolean); begin inherited ShowHint := Value; FPinButton.ShowHint := Value; end; procedure TNLDSnapPanel.SetWidth(const Value: Integer); begin if FMaxWidth <> Value then begin FMaxWidth := Value; if not FAutoHide then inherited Width := FMaxWidth; end; end; procedure TNLDSnapPanel.Timer(Sender: TObject); var CalcWidth: Integer; begin if FUnhiding then CalcWidth := Width + DefResizeStep else CalcWidth := Width - DefResizeStep; inherited Width := Max(FMinWidth, Min(CalcWidth, FMaxWidth)); if (Width = FMinWidth) or (Width = FMaxWidth) then FTimer.Enabled := False; end; procedure TNLDSnapPanel.UpdatePinButtonHint; begin if FPinButton.Down then FPinButton.Hint := FPinButtonDownHint else FPinButton.Hint := FPinButtonUpHint; end; end.
unit uScaleControlsEx; interface implementation {$define sf_colorpickerbutton} {$define sf_dnSplitter} // define, if using DBCtrlsEh {.$define sf_EhLib} // define, if using Vcl.Grids.pas {.$define sf_Grids} //{$define sf_StdCtrls} // define, if using tb2k components {$define sf_tb2k} {$define sf_tbx} {$define sf_VirtualTrees} uses {$ifdef HAS_UNITSCOPE} System.Classes, Vcl.Controls, {$else} Classes, Controls, {$endif} {$ifdef sf_colorpickerbutton}ColorPickerButton,{$endif} {$ifdef sf_dnSplitter}dnSplitter,{$endif} {$ifdef sf_EhLib}DBCtrlsEh,{$endif} {$ifdef sf_Grids}{$ifdef HAS_UNITSCOPE}Vcl.Grids,{$else}Grids,{$endif}{$endif} // {$ifdef sf_StdCtrls}{$ifdef HAS_UNITSCOPE}Vcl.StdCtrls,{$else}StdCtrls,{$endif}{$endif} {$ifdef sf_tb2k}TB2Item, TB2Toolbar, TB2ToolWindow,{$endif} {$ifdef sf_tbx}TBXDkPanels, TBXStatusBars, TBXExtItems,{$endif} {$ifdef sf_VirtualTrees}VirtualTrees,{$endif} uScaleControls; {$ifdef sf_colorpickerbutton} procedure ScaleColorPickerButton(AControl: TControl; const AScaler: TIntScaler; var AHandled: Boolean); begin if not (AControl is TColorPickerButton) then Exit; with TColorPickerButton(AControl) do begin DropDownWidth := AScaler.Scale(DropDownWidth); BoxSize := AScaler.Scale(BoxSize); //Margin := -1; PopupSpacing := AScaler.Scale(PopupSpacing); Spacing := AScaler.Scale(Spacing); Changed; end; end; {$endif} {$ifdef sf_dnSplitter} procedure ScalednSplitter(AControl: TControl; const AScaler: TIntScaler; var AHandled: Boolean); begin if not (AControl is TdnSplitter) then Exit; with TdnSplitter(AControl) do begin if ButtonWidthType = btwPixels then ButtonWidth := AScaler.Scale(ButtonWidth); MinSize := AScaler.Scale(MinSize); Size := AScaler.Scale(Size); end; end; {$endif} {$ifdef sf_EhLib} procedure ScaleDBEditEh(AControl: TControl; const AScaler: TIntScaler; var AHandled: Boolean); begin if not (AControl is TCustomDBEditEh) then Exit; with TCustomDBEditEh(AControl).ControlLabelLocation do begin Offset := AScaler.Scale(Offset); Spacing := AScaler.Scale(Spacing); end; end; {$endif} {$ifdef sf_Grids} type TFriendlyCustomGrid = class(TCustomGrid); procedure ScaleCustomGrid(AControl: TControl; const AScaler: TIntScaler; var AHandled: Boolean); var i: Integer; begin if not (AControl is TCustomGrid) then Exit; with TFriendlyCustomGrid(AControl) do begin for i := 0 to ColCount - 1 do ColWidths[i] := AScaler.Scale(ColWidths[i]); DefaultColWidth := AScaler.Scale(DefaultColWidth); for i := 0 to RowCount - 1 do RowHeights[i] := AScaler.Scale(RowHeights[i]); DefaultRowHeight := AScaler.Scale(DefaultRowHeight); end; end; {$endif} //{$ifdef sf_StdCtrls} //procedure ScaleStdCtrls(AControl: TControl; const AScaler: TIntScaler; var AHandled: Boolean); //begin // if AControl is TCustomComboBox then // begin // with TComboBox(AControl) do // ItemHeight := AScaler.Scale(ItemHeight); // end; //end; //{$endif} {$ifdef sf_tb2k} procedure ScaleTBToolWindow(AControl: TControl; const AScaler: TIntScaler; var AHandled: Boolean); begin if not (AControl is TTBToolWindow) then Exit; with TTBToolWindow(AControl) do begin MaxClientWidth := AScaler.Scale(MaxClientWidth); MinClientWidth := AScaler.Scale(MinClientWidth); MaxClientHeight := AScaler.Scale(MaxClientHeight); MinClientHeight := AScaler.Scale(MinClientHeight); end; end; {$endif} {$ifdef sf_tbx} procedure ScaleTBX(AControl: TControl; const AScaler: TIntScaler; var AHandled: Boolean); var i: Integer; LSize: Integer; LPanel: TTBXStatusPanel; LToolBar: TTBCustomToolbar; LTBItem: TTBCustomItem; begin if AControl is TTBXAlignmentPanel then begin with TTBXAlignmentPanel(AControl) do begin Margins.Left := AScaler.Scale(Margins.Left); Margins.Top := AScaler.Scale(Margins.Top); Margins.Right := AScaler.Scale(Margins.Right); Margins.Bottom := AScaler.Scale(Margins.Bottom); end end else if AControl is TTBXCustomStatusBar then begin with TTBXCustomStatusBar(AControl) do if Panels.Count > 0 then begin Panels.BeginUpdate; try for i := 0 to Panels.Count - 1 do begin LPanel := Panels[i]; LSize := AScaler.Scale(LPanel.Size); LPanel.MaxSize := AScaler.Scale(LPanel.MaxSize); LPanel.Size := LSize; end; finally Panels.EndUpdate; end; end end else if AControl is TTBCustomToolbar then begin LToolBar := TTBCustomToolbar(AControl); for i := 0 to LToolBar.Items.Count - 1 do begin LTBItem := LToolBar.Items.Items[i]; if LTBItem is TTBXComboBoxItem then with TTBXComboBoxItem(LTBItem) do begin EditWidth := AScaler.Scale(EditWidth); MinListWidth := AScaler.Scale(MinListWidth); MaxListWidth := AScaler.Scale(MaxListWidth); end; end; end; end; {$endif} {$ifdef sf_VirtualTrees} type TfrBVT = class(TBaseVirtualTree); procedure ScaleVirtualTree(AControl: TControl; const AScaler: TIntScaler; var AHandled: Boolean); var LTree: TBaseVirtualTree; LHeader: TVTHeader; LColumn: TVirtualTreeColumn; i: Integer; begin if not (AControl is TBaseVirtualTree) then Exit; LTree := TBaseVirtualTree(AControl); LTree.BeginUpdate; try TfrBVT(LTree).BackgroundOffsetX := AScaler.Scale(TfrBVT(LTree).BackgroundOffsetX); TfrBVT(LTree).BackgroundOffsetY := AScaler.Scale(TfrBVT(LTree).BackgroundOffsetY); TfrBVT(LTree).DefaultNodeHeight := AScaler.Scale(TfrBVT(LTree).DefaultNodeHeight); // DragHeight // DragWidth TfrBVT(LTree).Indent := AScaler.Scale(TfrBVT(LTree).Indent); TfrBVT(LTree).Margin := AScaler.Scale(TfrBVT(LTree).Margin); // TextMargin не учитывается при отрисовки хинта, баг в VTV? //TfrBVT(LTree).TextMargin := AScaler.Scale(TfrBVT(LTree).TextMargin); LHeader := LTree.Header; LHeader.DefaultHeight := AScaler.Scale(LHeader.DefaultHeight); //LHeader.FixedAreaConstraints. LHeader.Height := AScaler.Scale(LHeader.Height); LHeader.MaxHeight := AScaler.Scale(LHeader.MaxHeight); LHeader.MinHeight := AScaler.Scale(LHeader.MinHeight); LHeader.SplitterHitTolerance := AScaler.Scale(LHeader.SplitterHitTolerance); if LHeader.Columns.Count > 0 then begin LHeader.Columns.BeginUpdate; try for i := 0 to LHeader.Columns.Count - 1 do begin LColumn := LTree.Header.Columns.Items[i]; LColumn.Margin := AScaler.Scale(LColumn.Margin); LColumn.MaxWidth := AScaler.Scale(LColumn.MaxWidth); LColumn.MinWidth := AScaler.Scale(LColumn.MinWidth); LColumn.Spacing := AScaler.Scale(LColumn.Spacing); LColumn.Width := AScaler.Scale(LColumn.Width); end; finally LTree.Header.Columns.EndUpdate; end; end; finally LTree.EndUpdate; end; end; {$endif} initialization {$ifdef sf_colorpickerbutton} TScaleControls.RegisterScaleCallback(ScaleColorPickerButton); {$endif} {$ifdef sf_dnSplitter} TScaleControls.RegisterScaleCallback(ScalednSplitter); {$endif} {$ifdef sf_EhLib} TScaleControls.RegisterScaleCallback(ScaleDBEditEh); {$endif} {$ifdef sf_Grids} TScaleControls.RegisterScaleCallback(ScaleCustomGrid); {$endif} // {$ifdef sf_StdCtrls} // TScaleControls.RegisterScaleCallback(ScaleStdCtrls); // {$endif} {$ifdef sf_tb2k} TScaleControls.RegisterScaleCallback(ScaleTBToolWindow); {$endif} {$ifdef sf_tbx} TScaleControls.RegisterScaleCallback(ScaleTBX); {$endif} {$ifdef sf_VirtualTrees} TScaleControls.RegisterScaleCallback(ScaleVirtualTree); {$endif} end.
unit l3ValLst; {* Список значений. } { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3ValLst - } { Начат: 15.10.1999 14:35 } { $Id: l3ValLst.pas,v 1.13 2010/02/27 10:12:37 lulin Exp $ } // $Log: l3ValLst.pas,v $ // Revision 1.13 2010/02/27 10:12:37 lulin // {RequestLink:193822954}. // - упрощаем структуры. // // Revision 1.12 2009/12/28 16:24:03 lulin // - определяем локализуемые строки на модели. // // Revision 1.11 2008/02/19 11:06:00 lulin // - восстановил всякие экзотические поиски в списках объектов. // // Revision 1.10 2008/02/13 16:03:14 lulin // - убраны излишне гибкие методы поиска. // // Revision 1.9 2008/02/12 19:32:36 lulin // - избавляемся от универсальности списков. // // Revision 1.8 2001/09/11 10:12:55 law // - new behavior: реализован метод Assign для Tl3NamedString. // // Revision 1.7 2001/07/27 15:46:05 law // - comments: xHelpGen. // // Revision 1.6 2000/12/15 15:19:02 law // - вставлены директивы Log. // {$I l3Define.inc } interface uses Classes, l3Types, l3Base, l3Dict, l3PrimString ; type Tl3NamedString = class(Tl3String) {* Строка с привязанным к ней значением. } private {property fields} f_Value : string; public // public methods procedure AssignString(P: Tl3PrimString); override; {-} public {public properties} property Value: string read f_Value write f_Value; {* - привезанное значение. } end;{Tl3NamedString} Tl3CustomValueList = class(Tl3Dictionary) {* Список значений. } protected {property methods} function pm_GetValues(const Name: string): string; procedure pm_SetValues(const Name, Value: string); {-} // function StringItemClass: Rl3String; override; public {public properties} property Values[const Name: string]: string read pm_GetValues write pm_SetValues; {* - значения. } end;{Tl3CustomValueList} Tl3ValueList = class(Tl3CustomValueList) {*! Список значений. Для конечного использования. } public {public properties} property Values; default; {-} end;{Tl3ValueList} implementation // start class Tl3CustomValueList function Tl3CustomValueList.pm_GetValues(const Name: string): string; {-} var i : Long; begin if FindData(Name, i) then Result := Tl3NamedString(Items[i]).Value else Result := ''; end; procedure Tl3CustomValueList.pm_SetValues(const Name, Value: string); {-} var i : Long; NS : Tl3NamedString; begin if FindData(Name, i) then Tl3NamedString(Items[i]).Value := Value else begin NS := Tl3NamedString.Create{StringItemClass.Create As Tl3NamedString}; try NS.AsString := Name; NS.Value := Value; Add(NS); finally l3Free(NS); end;{try..finally} end; end; (*function Tl3CustomValueList.StringItemClass: Rl3String; begin Result := Tl3NamedString; end;*) // start class Tl3NamedString procedure Tl3NamedString.AssignString(P: Tl3PrimString); //override; {-} begin inherited; if (P Is Tl3NamedString) then Value := Tl3NamedString(P).Value; end; end.
(*==========================================================================; * * Copyright (C) 1995-1997 Microsoft Corporation. All Rights Reserved. * * File: d3drm.h * Content: Direct3DRM include file * * DirectX 6 Delphi adaptation by Erik Unger * * Modyfied: 23.8.98 * * Download: http://www.bigfoot.com/~ungerik/ * E-Mail: ungerik@bigfoot.com * ***************************************************************************) unit D3DRM; interface uses {$IFDEF D2COM} OLE2, {$ENDIF} Windows, D3DRMObj, D3DRMDef, DirectDraw, Direct3D; function ErrorString(Value: HResult) : string; type TD3DRMDevicePaletteCallback = procedure (lpDirect3DRMDev: IDirect3DRMDevice; lpArg: Pointer; dwIndex: DWORD; red, green, blue: LongInt); cdecl; const IID_IDirect3DRM: TGUID = (D1:$2bc49361;D2:$8327;D3:$11cf;D4:($ac,$4a,$00,$00,$c0,$38,$25,$a1)); IID_IDirect3DRM2: TGUID = (D1:$4516ecc8;D2:$8f20;D3:$11d0;D4:($9b,$6d,$00,$00,$c0,$78,$1b,$c3)); IID_IDirect3DRM3: TGUID = (D1:$4516ec83;D2:$8f20;D3:$11d0;D4:($9b,$6d,$00,$00,$c0,$78,$1b,$c3)); // old (D1:$02e34065;D2:$c243;D3:$11d1;D4:($8e,$d8,$00,$a0,$c9,$67,$a4,$82)); (* * Direct3DRM Object Class (for CoCreateInstance()) *) CLSID_CDirect3DRM: TGUID = (D1:$4516ec41;D2:$8f20;D3:$11d0;D4:($9b,$6d,$00,$00,$c0,$78,$1b,$c3)); type {$IFDEF D2COM} IDirect3DRM = class (IUnknown) {$ELSE} IDirect3DRM = interface (IUnknown) ['{2bc49361-8327-11cf-ac4a-0000c03825a1}'] {$ENDIF} function CreateObject (rclsid: TGUID; pUnkOuter: IUnknown; riid: TGUID; var ppv: Pointer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateFrame (lpD3DRMFrame: IDirect3DRMFrame; var lplpD3DRMFrame: IDirect3DRMFrame) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateMesh (var lplpD3DRMMesh: IDirect3DRMMesh) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateMeshBuilder (var lplpD3DRMMeshBuilder: IDirect3DRMMeshBuilder) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateFace (var lplpd3drmFace: IDirect3DRMFace) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateAnimation (var lplpD3DRMAnimation: IDirect3DRMAnimation) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateAnimationSet (var lplpD3DRMAnimationSet: IDirect3DRMAnimationSet) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateTexture (const lpImage: TD3DRMImage; var lplpD3DRMTexture: IDirect3DRMTexture) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateLight (d3drmltLightType: TD3DRMLightType; cColor: TD3DColor; var lplpD3DRMLight: IDirect3DRMLight) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateLightRGB (ltLightType: TD3DRMLightType; vRed, vGreen, vBlue: TD3DValue; var lplpD3DRMLight: IDirect3DRMLight) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateMaterial (vPower: TD3DValue; var lplpD3DRMMaterial: IDirect3DRMMaterial) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateDevice (dwWidth, dwHeight: DWORD; var lplpD3DRMDevice: IDirect3DRMDevice) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} (* Create a Windows Device using DirectDraw surfaces *) function CreateDeviceFromSurface (lpGUID: PGUID; lpDD: IDirectDraw; lpDDSBack: IDirectDrawSurface; var lplpD3DRMDevice: IDirect3DRMDevice) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} (* Create a Windows Device using D3D objects *) function CreateDeviceFromD3D (lpD3D: IDirect3D; lpD3DDev: IDirect3DDevice; var lplpD3DRMDevice: IDirect3DRMDevice) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateDeviceFromClipper (lpDDClipper: IDirectDrawClipper; lpGUID: PGUID; width, height: Integer; var lplpD3DRMDevice: IDirect3DRMDevice) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateTextureFromSurface ( lpDDS: IDirectDrawSurface; var lplpD3DRMTexture: IDirect3DRMTexture) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateShadow (lpVisual: IDirect3DRMVisual; lpLight: IDirect3DRMLight; px, py, pz, nx, ny, nz: TD3DValue; var lplpShadow: IDirect3DRMVisual) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateViewport (lpDev: IDirect3DRMDevice; lpCamera: IDirect3DRMFrame; dwXPos, dwYPos, dwWidth, dwHeight: DWORD; var lplpD3DRMViewport: IDirect3DRMViewport) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateWrap (wraptype: TD3DRMWrapType; lpRef: IDirect3DRMFrame; ox, oy, oz, dx, dy, dz, ux, uy, uz, ou, ov, su, sv: TD3DValue; var lplpD3DRMWrap: IDirect3DRMWrap) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateUserVisual (fn: TD3DRMUserVisualCallback; lpArg: Pointer; var lplpD3DRMUV: IDirect3DRMUserVisual) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function LoadTexture (lpFileName: PAnsiChar; var lplpD3DRMTexture: IDirect3DRMTexture) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function LoadTextureFromResource (rs: HRSRC; var lplpD3DRMTexture: IDirect3DRMTexture) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetSearchPath (lpPath: PAnsiChar) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function AddSearchPath (lpPath: PAnsiChar) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetSearchPath (var lpdwSize: DWORD; lpszPath: PAnsiChar) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetDefaultTextureColors (dwColors: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetDefaultTextureShades (dwShades: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetDevices (var lplpDevArray: IDirect3DRMDeviceArray) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetNamedObject (lpName: PAnsiChar; var lplpD3DRMObject: IDirect3DRMObject) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function EnumerateObjects (func: TD3DRMObjectCallback; lpArg: Pointer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Load (lpvObjSource, lpvObjID: Pointer; var lplpGUIDs: PGUID; dwcGUIDs: DWORD; d3drmLOFlags: TD3DRMLoadOptions; d3drmLoadProc: TD3DRMLoadCallback; lpArgLP: Pointer; d3drmLoadTextureProc: TD3DRMLoadTextureCallback; lpArgLTP: Pointer; lpParentFrame: IDirect3DRMFrame) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Tick (d3dvalTick: TD3DValue) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; // Moved from D3DRMObj, to avoid circular unit reference: {$IFDEF D2COM} IDirect3DRMObject2 = class (IUnknown) {$ELSE} IDirect3DRMObject2 = interface (IUnknown) ['{4516ec7c-8f20-11d0-9b6d-0000c0781bc3}'] {$ENDIF} (* * IDirect3DRMObject2 methods *) function AddDestroyCallback (lpCallback: TD3DRMObjectCallback; lpArg: Pointer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Clone (pUnkOuter: IUnknown; riid: TGUID; var ppvObj: Pointer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function DeleteDestroyCallback (d3drmObjProc: TD3DRMObjectCallback; lpArg: Pointer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetClientData (dwID: DWORD; var lplpvData: pointer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetDirect3DRM (var lplpDirect3DRM: IDirect3DRM) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetName (var lpdwSize: DWORD; lpName: PAnsiChar) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetClientData (dwID: DWORD; lpvData: pointer; dwFlags: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetName (lpName: PAnsiChar) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetAge (dwFlags: DWORD; var pdwAge: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; {$IFDEF D2COM} IDirect3DRM2 = class (IUnknown) {$ELSE} IDirect3DRM2 = interface (IUnknown) ['{4516ecc8-8f20-11d0-9b6d-0000c0781bc3}'] {$ENDIF} function CreateObject (rclsid: TGUID; pUnkOuter: IUnknown; riid: TGUID; var ppv: Pointer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateFrame (lpD3DRMFrame: IDirect3DRMFrame2; var lplpD3DRMFrame: IDirect3DRMFrame2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateMesh (var lplpD3DRMMesh: IDirect3DRMMesh) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateMeshBuilder (var lplpD3DRMMeshBuilder: IDirect3DRMMeshBuilder2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateFace (var lplpd3drmFace: IDirect3DRMFace) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateAnimation (var lplpD3DRMAnimation: IDirect3DRMAnimation) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateAnimationSet (var lplpD3DRMAnimationSet: IDirect3DRMAnimationSet) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateTexture (const lpImage: TD3DRMImage; var lplpD3DRMTexture: IDirect3DRMTexture2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateLight (d3drmltLightType: TD3DRMLightType; cColor: TD3DColor; var lplpD3DRMLight: IDirect3DRMLight) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateLightRGB (ltLightType: TD3DRMLightType; vRed, vGreen, vBlue: TD3DValue; var lplpD3DRMLight: IDirect3DRMLight) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateMaterial (vPower: TD3DValue; var lplpD3DRMMaterial: IDirect3DRMMaterial) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateDevice (dwWidth, dwHeight: DWORD; var lplpD3DRMDevice: IDirect3DRMDevice2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} (* Create a Windows Device using DirectDraw surfaces *) function CreateDeviceFromSurface (lpGUID: PGUID; lpDD: IDirectDraw; lpDDSBack: IDirectDrawSurface; var lplpD3DRMDevice: IDirect3DRMDevice2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} (* Create a Windows Device using D3D objects *) function CreateDeviceFromD3D (lpD3D: IDirect3D2; lpD3DDev: IDirect3DDevice2; var lplpD3DRMDevice: IDirect3DRMDevice2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateDeviceFromClipper (lpDDClipper: IDirectDrawClipper; lpGUID: PGUID; width, height: Integer; var lplpD3DRMDevice: IDirect3DRMDevice2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateTextureFromSurface ( lpDDS: IDirectDrawSurface; var lplpD3DRMTexture: IDirect3DRMTexture2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateShadow (lpVisual: IDirect3DRMVisual; lpLight: IDirect3DRMLight; px, py, pz, nx, ny, nz: TD3DValue; var lplpShadow: IDirect3DRMVisual) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateViewport (lpDev: IDirect3DRMDevice; lpCamera: IDirect3DRMFrame; dwXPos, dwYPos, dwWidth, dwHeight: DWORD; var lplpD3DRMViewport: IDirect3DRMViewport) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateWrap (wraptype: TD3DRMWrapType; lpRef: IDirect3DRMFrame; ox, oy, oz, dx, dy, dz, ux, uy, uz, ou, ov, su, sv: TD3DValue; var lplpD3DRMWrap: IDirect3DRMWrap) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateUserVisual (fn: TD3DRMUserVisualCallback; lpArg: Pointer; var lplpD3DRMUV: IDirect3DRMUserVisual) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function LoadTexture (lpFileName: PAnsiChar; var lplpD3DRMTexture: IDirect3DRMTexture2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function LoadTextureFromResource (rs: HRSRC; var lplpD3DRMTexture: IDirect3DRMTexture2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetSearchPath (lpPath: PAnsiChar) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function AddSearchPath (lpPath: PAnsiChar) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetSearchPath (var lpdwSize: DWORD; lpszPath: PAnsiChar) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetDefaultTextureColors (dwColors: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetDefaultTextureShades (dwShades: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetDevices (var lplpDevArray: IDirect3DRMDeviceArray) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetNamedObject (lpName: PAnsiChar; var lplpD3DRMObject: IDirect3DRMObject) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function EnumerateObjects (func: TD3DRMObjectCallback; lpArg: Pointer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Load (lpvObjSource, lpvObjID: Pointer; var lplpGUIDs: PGUID; dwcGUIDs: DWORD; d3drmLOFlags: TD3DRMLoadOptions; d3drmLoadProc: TD3DRMLoadCallback; lpArgLP: Pointer; d3drmLoadTextureProc: TD3DRMLoadTextureCallback; lpArgLTP: Pointer; lpParentFrame: IDirect3DRMFrame) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Tick (d3dvalTick: TD3DValue) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateProgressiveMesh (var lplpD3DRMProgressiveMesh: IDirect3DRMProgressiveMesh) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; {$IFDEF D2COM} IDirect3DRM3 = class (IUnknown) {$ELSE} IDirect3DRM3 = interface (IUnknown) ['{4516EC83-8f20-11d0-9B6D-0000c0781bc3}'] // old ['{02e34065-c243-11d1-8ed8-00a0c967a482}'] {$ENDIF} function CreateObject (rclsid: TGUID; pUnkOuter: IUnknown; riid: TGUID; var ppv: Pointer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateFrame (lpD3DRMFrame: IDirect3DRMFrame3; var lplpD3DRMFrame: IDirect3DRMFrame3) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateMesh (var lplpD3DRMMesh: IDirect3DRMMesh) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateMeshBuilder (var lplpD3DRMMeshBuilder: IDirect3DRMMeshBuilder3) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateFace (var lplpd3drmFace: IDirect3DRMFace) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateAnimation (var lplpD3DRMAnimation: IDirect3DRMAnimation2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateAnimationSet (var lplpD3DRMAnimationSet: IDirect3DRMAnimationSet2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateTexture (const lpImage: TD3DRMImage; var lplpD3DRMTexture: IDirect3DRMTexture3) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateLight (d3drmltLightType: TD3DRMLightType; cColor: TD3DColor; var lplpD3DRMLight: IDirect3DRMLight) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateLightRGB (ltLightType: TD3DRMLightType; vRed, vGreen, vBlue: TD3DValue; var lplpD3DRMLight: IDirect3DRMLight) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateMaterial (vPower: TD3DValue; var lplpD3DRMMaterial: IDirect3DRMMaterial2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateDevice (dwWidth, dwHeight: DWORD; var lplpD3DRMDevice: IDirect3DRMDevice3) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} (* Create a Windows Device using DirectDraw surfaces *) function CreateDeviceFromSurface (lpGUID: PGUID; lpDD: IDirectDraw; lpDDSBack: IDirectDrawSurface; dwFlags: DWORD; var lplpD3DRMDevice: IDirect3DRMDevice3) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} (* Create a Windows Device using D3D objects *) function CreateDeviceFromD3D (lpD3D: IDirect3D2; lpD3DDev: IDirect3DDevice2; var lplpD3DRMDevice: IDirect3DRMDevice3) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateDeviceFromClipper (lpDDClipper: IDirectDrawClipper; lpGUID: PGUID; width, height: Integer; var lplpD3DRMDevice: IDirect3DRMDevice3) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateTextureFromSurface ( lpDDS: IDirectDrawSurface; var lplpD3DRMTexture: IDirect3DRMTexture3) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateShadow (pUnk: IUnknown; lpLight: IDirect3DRMLight; px, py, pz, nx, ny, nz: TD3DValue; var lplpShadow: IDirect3DRMShadow2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateViewport (lpDev: IDirect3DRMDevice3; lpCamera: IDirect3DRMFrame3; dwXPos, dwYPos, dwWidth, dwHeight: DWORD; var lplpD3DRMViewport: IDirect3DRMViewport2) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateWrap (wraptype: TD3DRMWrapType; lpRef: IDirect3DRMFrame3; ox, oy, oz, dx, dy, dz, ux, uy, uz, ou, ov, su, sv: TD3DValue; var lplpD3DRMWrap: IDirect3DRMWrap) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateUserVisual (fn: TD3DRMUserVisualCallback; lpArg: Pointer; var lplpD3DRMUV: IDirect3DRMUserVisual) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function LoadTexture (lpFileName: PAnsiChar; var lplpD3DRMTexture: IDirect3DRMTexture3) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function LoadTextureFromResource (rs: HRSRC; var lplpD3DRMTexture: IDirect3DRMTexture3) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetSearchPath (lpPath: PAnsiChar) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function AddSearchPath (lpPath: PAnsiChar) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetSearchPath (var lpdwSize: DWORD; lpszPath: PAnsiChar) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetDefaultTextureColors (dwColors: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetDefaultTextureShades (dwShades: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetDevices (var lplpDevArray: IDirect3DRMDeviceArray) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetNamedObject (lpName: PAnsiChar; var lplpD3DRMObject: IDirect3DRMObject) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function EnumerateObjects (func: TD3DRMObjectCallback; lpArg: Pointer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Load (lpvObjSource, lpvObjID: Pointer; var lplpGUIDs: PGUID; dwcGUIDs: DWORD; d3drmLOFlags: TD3DRMLoadOptions; d3drmLoadProc: TD3DRMLoadCallback; lpArgLP: Pointer; d3drmLoadTextureProc: TD3DRMLoadTexture3Callback; lpArgLTP: Pointer; lpParentFrame: IDirect3DRMFrame3) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Tick (d3dvalTick: TD3DValue) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateProgressiveMesh (var lplpD3DRMProgressiveMesh: IDirect3DRMProgressiveMesh) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} (* Used with IDirect3DRMObject2 *) function RegisterClient (const rguid: TGUID; var lpdwID: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function UnregisterClient (const rguid: TGUID) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CreateClippedVisual (lpVisual: IDirect3DRMVisual; lpClippedVisual: IDirect3DRMClippedVisual) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetOptions (dwOptions: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetOptions (var lpdwOptions: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; const D3DRMERR_GENERIC = HRESULT($88760000); const D3DRM_OK = DD_OK; D3DRMERR_BADOBJECT = D3DRMERR_GENERIC + 781; D3DRMERR_BADTYPE = D3DRMERR_GENERIC + 782; D3DRMERR_BADALLOC = D3DRMERR_GENERIC + 783; D3DRMERR_FACEUSED = D3DRMERR_GENERIC + 784; D3DRMERR_NOTFOUND = D3DRMERR_GENERIC + 785; D3DRMERR_NOTDONEYET = D3DRMERR_GENERIC + 786; D3DRMERR_FILENOTFOUND = D3DRMERR_GENERIC + 787; D3DRMERR_BADFILE = D3DRMERR_GENERIC + 788; D3DRMERR_BADDEVICE = D3DRMERR_GENERIC + 789; D3DRMERR_BADVALUE = D3DRMERR_GENERIC + 790; D3DRMERR_BADMAJORVERSION = D3DRMERR_GENERIC + 791; D3DRMERR_BADMINORVERSION = D3DRMERR_GENERIC + 792; D3DRMERR_UNABLETOEXECUTE = D3DRMERR_GENERIC + 793; D3DRMERR_LIBRARYNOTFOUND = D3DRMERR_GENERIC + 794; D3DRMERR_INVALIDLIBRARY = D3DRMERR_GENERIC + 795; D3DRMERR_PENDING = D3DRMERR_GENERIC + 796; D3DRMERR_NOTENOUGHDATA = D3DRMERR_GENERIC + 797; D3DRMERR_REQUESTTOOLARGE = D3DRMERR_GENERIC + 798; D3DRMERR_REQUESTTOOSMALL = D3DRMERR_GENERIC + 799; D3DRMERR_CONNECTIONLOST = D3DRMERR_GENERIC + 800; D3DRMERR_LOADABORTED = D3DRMERR_GENERIC + 801; D3DRMERR_NOINTERNET = D3DRMERR_GENERIC + 802; D3DRMERR_BADCACHEFILE = D3DRMERR_GENERIC + 803; D3DRMERR_BOXNOTSET = D3DRMERR_GENERIC + 804; D3DRMERR_BADPMDATA = D3DRMERR_GENERIC + 805; D3DRMERR_CLIENTNOTREGISTERED = D3DRMERR_GENERIC + 806; D3DRMERR_NOTCREATEDFROMDDS = D3DRMERR_GENERIC + 807; D3DRMERR_NOSUCHKEY = D3DRMERR_GENERIC + 808; D3DRMERR_INCOMPATABLEKEY = D3DRMERR_GENERIC + 809; D3DRMERR_ELEMENTINUSE = D3DRMERR_GENERIC + 810; D3DRMERR_TEXTUREFORMATNOTFOUND = D3DRMERR_GENERIC + 811; (* Create a Direct3DRM API *) function Direct3DRMCreate (var lplpDirect3DRM: IDirect3DRM) : HResult; stdcall; implementation function Direct3DRMCreate; external 'D3DRM.DLL'; function ErrorString(Value: HResult) : string; begin case Value of D3DRM_OK: Result := 'No error. Equivalent to DD_OK.'; D3DRMERR_BADALLOC: Result := 'Out of memory.'; D3DRMERR_BADDEVICE: Result := 'Device is not compatible with renderer.'; D3DRMERR_BADFILE: Result := 'Data file is corrupt.'; D3DRMERR_BADMAJORVERSION: Result := 'Bad DLL major version.'; D3DRMERR_BADMINORVERSION: Result := 'Bad DLL minor version.'; D3DRMERR_BADOBJECT: Result := 'Object expected in argument.'; D3DRMERR_BADPMDATA: Result := 'The data in the .x file is corrupted. The conversion to a progressive mesh succeeded but produced an invalid progressive mesh in the .x file.'; D3DRMERR_BADTYPE: Result := 'Bad argument type passed.'; D3DRMERR_BADVALUE: Result := 'Bad argument value passed.'; D3DRMERR_BOXNOTSET: Result := 'An attempt was made to access a bounding box (for example, with IDirect3DRMFrame3::GetBox) when no bounding box was set on the frame.'; D3DRMERR_CLIENTNOTREGISTERED: Result := 'Client has not been registered. Call IDirect3DRM3::RegisterClient.'; D3DRMERR_CONNECTIONLOST: Result := 'Data connection was lost during a load, clone, or duplicate.'; D3DRMERR_ELEMENTINUSE: Result := 'Element canīt be modified or deleted while in use. To empty a submesh, call Empty() against its parent.'; // D3DRMERR_ENTRYINUSE: Result := 'Vertex or normal entries are currently in use by a face and cannot be deleted.'; D3DRMERR_FACEUSED: Result := 'Face already used in a mesh.'; D3DRMERR_FILENOTFOUND: Result := 'File cannot be opened.'; // D3DRMERR_INCOMPATIBLEKEY: Result := 'Specified animation key is incompatible. The key cannot be modified.'; D3DRMERR_INVALIDLIBRARY: Result := 'Specified libary is invalid.'; // D3DRMERR_INVALIDOBJECT: Result := 'Method received a pointer to an object that is invalid.'; // D3DRMERR_INVALIDPARAMS: Result := 'One of the parameters passed to the method is invalid.'; D3DRMERR_LIBRARYNOTFOUND: Result := 'Specified libary not found.'; D3DRMERR_LOADABORTED: Result := 'Load aborted by user.'; D3DRMERR_NOSUCHKEY: Result := 'Specified animation key does not exist.'; D3DRMERR_NOTCREATEDFROMDDS: Result := 'Specified texture was not created from a DirectDraw Surface.'; D3DRMERR_NOTDONEYET: Result := 'Unimplemented.'; D3DRMERR_NOTENOUGHDATA: Result := 'Not enough data has been loaded to perform the requested operation.'; D3DRMERR_NOTFOUND: Result := 'Object not found in specified place.'; // D3DRMERR_OUTOFRANGE: Result := 'Specified value is out of range.'; D3DRMERR_PENDING: Result := 'Data required to supply the requested information has not finished loading.'; D3DRMERR_REQUESTTOOLARGE: Result := 'Attempt was made to set a level of detail in a progressive mesh greater than the maximum available.'; D3DRMERR_REQUESTTOOSMALL: Result := 'Attempt was made to set the minimum rendering detail of a progressive mesh smaller than the detail in the base mesh (the minimum for rendering).'; D3DRMERR_TEXTUREFORMATNOTFOUND: Result := 'Texture format could not be found that meets the specified criteria and that the underlying Immediate Mode device supports.'; D3DRMERR_UNABLETOEXECUTE: Result := 'Unable to carry out procedure.'; DDERR_INVALIDOBJECT: Result := 'Received pointer that was an invalid object.'; DDERR_INVALIDPARAMS: Result := 'One or more of the parameters passed to the method are incorrect.'; DDERR_NOTFOUND: Result := 'The requested item was not found.'; DDERR_NOTINITIALIZED: Result := 'An attempt was made to call an interface method of an object created by CoCreateInstance before the object was initialized.'; DDERR_OUTOFMEMORY: Result := 'DirectDraw does not have enough memory to perform the operation.'; else Result := 'Unrecognized Error'; end; end; end.
unit EditableObjects; interface uses classes, Collection; const // options OPT_ALLOWNEW = 1; OPT_EVENT = 2; OPT_NUMERABLE = 4; const // visual options VOP_SHOWINMAINCONTROL = 1; VOP_EDITCHILDREN = 2; VOP_ALLOWPROPERTYEDITING = 4; VOP_DONOTSHOWEVENTS = 8; const // msgs MSG_GETSELOBJECT = 1; type TEditableObject = class; CEditableObject = class of TEditableObject; TObjectEditor = class; TMetaEditableObject = class; TObjectEditor = class public function SendMessage( control : TObject; msg : integer; var data ) : boolean; virtual; abstract; procedure HideEditor( const visualcontext; visualEditor : TObject ); virtual; abstract; procedure ShowEditor( const visualcontext; visualEditor : TObject ); virtual; abstract; function CreateVisualEditor( options : integer; const visualcontext; obj : TEditableObject ) : TObject; virtual; abstract; procedure UpdateObject( VisualEditor : TObject; obj : TObject ); virtual; abstract; function CreateNewObject : TEditableObject; virtual; abstract; procedure DestroyEditor( editor : TObject ); virtual; abstract; protected fName : string; public property Name : string read fName; end; TEditableObject = class public constructor Create; public function Edit( options : integer; const visualcontext ) : TObject; public function getChildren( name : string ) : TEditableObject; function getProperty( propName : string ) : TEditableObject; protected fName : string; fValue : string; fChildren : TCollection; fOptions : integer; fProperties : TCollection; fObjectEditor : TObjectEditor; fMetaClass : TMetaEditableObject; public property Name : string read fName write fName; property Value : string read fValue write fValue; property Options : integer read fOptions write fOptions; property Properties : TCollection read fProperties; property Children : TCollection read fChildren; property ObjectEditor : TObjectEditor read fObjectEditor write fObjectEditor; property MetaClass : TMetaEditableObject read fMetaClass write fMetaClass; end; TMetaEditableObject = class(TEditableObject) public function Instantiate( aName, aValue : string; const data ) : TEditableObject; virtual; abstract; procedure Clone( aMetaEditableObject : TMetaEditableObject ); virtual; function getFullName : string; private fParent : TMetaEditableObject; public property Parent : TMetaEditableObject read fParent write fParent; end; TMetaObjectPool = class public constructor Create; destructor Destroy; override; public procedure Init( const data ); virtual; abstract; function get( cname : string ) : TMetaEditableObject; procedure registerEditor( ObjectEditor : TObjectEditor ); function getEditor( name : string ): TObjectEditor; protected fMetaObjects : TCollection; fEditors : TCollection; end; implementation uses stringUtils, sysUtils; // TEditableObject constructor TEditableObject.Create; begin inherited Create; fChildren := TCollection.Create( 1, rkBelonguer ); fProperties := TCollection.Create( 10, rkBelonguer ); end; function TEditableObject.Edit( options : integer; const visualcontext ) : TObject; begin result := nil; if fObjectEditor <> nil then result := fObjectEditor.CreateVisualEditor( options, visualcontext, self ); end; function TEditableObject.getChildren( name : string ) : TEditableObject; var i : integer; begin i := 0; while (i < fChildren.Count) and (CompareText(TEditableObject(fChildren[i]).Name, name) <> 0) do inc( i ); if i < fChildren.Count then result := TEditableObject(fChildren[i]) else result := nil; end; function TEditableObject.getProperty( propName : string ) : TEditableObject; var i : integer; begin i := 0; while (i < fProperties.Count) and (TEditableObject(fProperties[i]).Name <> propName) do inc( i ); if i < fProperties.Count then result := TEditableObject(fProperties[i]) else result := nil; end; // TMetaEditableObject procedure TMetaEditableObject.Clone( aMetaEditableObject : TMetaEditableObject ); begin end; function TMetaEditableObject.getFullName : string; var aux : TMetaEditableObject; names : TStringList; i : integer; begin names := TStringList.Create; try aux := self; while aux <> nil do begin names.Add( aux.Name ); aux := aux.Parent; end; result := names[pred(names.Count)]; for i := names.Count -2 downto 0 do result := result + '.' + names[i]; finally names.Free; end; end; // TMetaObjectPool constructor TMetaObjectPool.Create; begin inherited; fMetaObjects := TCollection.Create( 20, rkBelonguer ); fEditors := TCollection.Create( 20, rkBelonguer ); end; destructor TMetaObjectPool.Destroy; begin fMetaObjects.Free; fEditors.Free; inherited; end; function TMetaObjectPool.get( cname : string ) : TMetaEditableObject; function getRootClass( name : string ) : TMetaEditableObject; var i : integer; begin i := 0; while (i < fMetaObjects.Count) and (TEditableObject(fMetaObjects[i]).Name <> name) do inc( i ); if i < fMetaObjects.Count then result := TMetaEditableObject(fMetaObjects[i]) else result := nil; end; var i : integer; classInfo : TStringList; c : TMetaEditableObject; begin classInfo := TStringList.Create; try SymbolSeparated( cname, '.', classinfo ); c := nil; if classinfo.Count > 0 then begin c := getRootClass( classinfo[0] ); for i := 1 to pred(classinfo.Count) do c := TMetaEditableObject(c.getChildren( classinfo[i] )); end; result := c; finally classInfo.Free; end; end; procedure TMetaObjectPool.registerEditor( ObjectEditor : TObjectEditor ); begin fEditors.Insert( ObjectEditor ); end; function TMetaObjectPool.getEditor( name : string ): TObjectEditor; var i : integer; begin i := 0; while (i < fEditors.Count) and (CompareText(TObjectEditor(fEditors[i]).Name, name) <> 0) do inc( i ); if i < fEditors.Count then result := TObjectEditor(fEditors[i]) else result := nil; end; end.
{ Subroutine SST_MEM_ALLOC_SCOPE (SIZE,P) * * Allocate memory that will be tied to the current most local scope. SIZE * is the amount of memory to allocate, and P is returned pointing to the * start of the new memory area. } module sst_MEM_ALLOC_SCOPE; define sst_mem_alloc_scope; %include 'sst2.ins.pas'; procedure sst_mem_alloc_scope ( {allocate memory tied to current scope} in size: sys_int_adr_t; {amount of memory to allocate} out p: univ_ptr); {pointer to start of new memory area} begin util_mem_grab (size, sst_scope_p^.mem_p^, false, p); end;
unit uRfMemoryProfiler; interface {$Include RfMemoryProfilerOptions.inc} uses Classes, SyncObjs {$IFDEF UNITTEST}, uUnitTestHeader {$ENDIF}; {It's a simple output to save the report of memory usage on the disk. It'll create a file called test.txt in the executable directory} procedure SaveMemoryProfileToFile(AFilePath: string = ''); {Get the current list of instances (TClassVars)} function RfGetInstanceList: TList; {$IFDEF UNITTEST} procedure InitializeRfMemoryProfiler; {$ENDIF} {$IFDEF UNITTEST} var SDefaultGetMem: function(Size: Integer): Pointer; SDefaultFreeMem: function(P: Pointer): Integer; SDefaultReallocMem: function(P: Pointer; Size: Integer): Pointer; SDefaultAllocMem: function(Size: Cardinal): Pointer; {$ENDIF} const SIZE_OF_MAP = 65365; type TArrayOfMap = array [0..SIZE_OF_MAP] of Integer; PCallerAllocator = ^TCallerAllocator; TCallerAllocator = record MemAddress: Integer; NumAllocations: Integer; end; TCriticalSectionIgnore = class(TCriticalSection); TAllocationMap = class strict private FCriticalSection: TCriticalSectionIgnore; FItems: array of TCallerAllocator; function BinarySearch(const ACallerAddr: Cardinal): Integer; function FindOrAdd(const ACallerAddr: Integer): Integer; procedure QuickSortInternal(ALow, AHigh: Integer); procedure QuickSort; private function GetItems(Index: Integer): TCallerAllocator; public constructor Create; destructor Destroy; override; procedure IncCounter(ACallerAddr: Integer); procedure DecCounter(ACallerAddr: Integer); function GetAllocationCounterByCallerAddr(ACallerAddr: Cardinal): TCallerAllocator; function Count: Integer; property Items[Index: Integer]: TCallerAllocator read GetItems; end; PRfClassController = ^TRfClassController; TRfClassController = class(TObject) private OldVMTFreeInstance: Pointer; public BaseClassType: TClass; BaseInstanceCount: Integer; BaseClassName: string; BaseParentClassName: string; BaseInstanceSize: Integer; AllocationMap: TAllocationMap; constructor Create; destructor Destroy; override; end; TRfObjectHack = class(TObject) private class procedure SetRfClassController(ARfClassController: TRfClassController); //inline; procedure IncCounter; inline; procedure DecCounter; inline; procedure CallOldFunction; function GetAllocationAddress: Integer; procedure SetAllocationAddress(const Value: Integer); class function NNewInstance: TObject; class function NNewInstanceTrace: TObject; procedure NFreeInstance; public class function GetRfClassController: TRfClassController; inline; {$IFDEF INSTANCES_TRACKER} property AllocationAddress: Integer read GetAllocationAddress write SetAllocationAddress; {$ENDIF} end; TMemoryAddressBuffer = class AllocationAddr: Integer; NumAllocations: Integer; Next: TMemoryAddressBuffer; end; TArrayOfMapAddress = array [0..SIZE_OF_MAP] of TMemoryAddressBuffer; procedure RegisterRfClassController(const Classes: array of TRfObjectHack); function GetAmountOfBufferAllocations(ACallerAddr: Cardinal; ABufferSize: Cardinal): Integer; function GetAmountOfAllocationOfClass(AClassType: TClass): Integer; function GetBytesAmountOfInstanceAllocation: Integer; function GetBytesAmountOfBufferAllocation: Integer; function GetBytesAmountOfUsedMemory: Integer; var RfIsMemoryProfilerActive: Boolean; RfIsObjectAllocantionTraceOn: Boolean; RfIsBufferAllocationTraceOn: Boolean; RfMapOfBufferAllocation: TArrayOfMap; RfMapofBufferAddressAllocation: TArrayOfMapAddress; implementation uses Windows, SysUtils, TypInfo, PsAPI; const SIZE_OF_INT = SizeOf(Integer); PARITY_BYTE = 7777777; GAP_SIZE = SizeOf(PARITY_BYTE) + SIZE_OF_INT {$IFDEF BUFFER_TRACKER} + SIZE_OF_INT {$ENDIF}; /// Delphi linker starts the code section at this fixed offset CODE_SECTION = $1000; type TThreadMemory = array [0..SIZE_OF_MAP] of Integer; PJump = ^TJump; TJump = packed record OpCode: Byte; Distance: Pointer; end; PMappedRecord = ^TMappedRecord; TMappedRecord = packed record Parity: Integer; SizeCounterAddr: Integer; {$IFDEF BUFFER_TRACKER} AllocationAddr: Integer; {$ENDIF} procedure SetParityByte; inline; procedure IncMapSizeCounter; inline; {$IFDEF BUFFER_TRACKER} procedure IncAllocationMap; inline; {$ENDIF} procedure ClearParityByte; inline; procedure DecMapSizeCounter; inline; function Size: Integer; inline; {$IFDEF BUFFER_TRACKER} procedure DecAllocationMap; inline; {$ENDIF} end; var {$IFNDEF UNITTEST} SDefaultGetMem: function(Size: Integer): Pointer; SDefaultFreeMem: function(P: Pointer): Integer; SDefaultReallocMem: function(P: Pointer; Size: Integer): Pointer; SDefaultAllocMem: function(Size: Cardinal): Pointer; {$ENDIF} SThreadMemory: TThreadMemory; SListRfClassController: TList; SGetModuleHandle: Cardinal; SInitialSection: Cardinal; SFinalSection: Cardinal; SRCBufferCounter: TCriticalSection; {$REGION 'Util'} {FastMM resource} procedure GetStackRange(var AStackBaseAddress, ACurrentStackPointer: NativeUInt); asm mov ecx, fs:[4] mov [eax], ecx mov [edx], ebp end; {FastMM resource} procedure GetFrameBasedStackTrace(AReturnAddresses: PNativeUInt; AMaxDepth, ASkipFrames: Cardinal); var LStackTop, LStackBottom, LCurrentFrame: NativeUInt; begin {Get the call stack top and current bottom} GetStackRange(LStackTop, LStackBottom); Dec(LStackTop, SizeOf(Pointer) - 1); {Get the current frame start} LCurrentFrame := LStackBottom; {Fill the call stack} while (AMaxDepth > 0) and (LCurrentFrame >= LStackBottom) and (LCurrentFrame < LStackTop) do begin {Ignore the requested number of levels} if ASkipFrames = 0 then begin AReturnAddresses^ := PNativeUInt(LCurrentFrame + SizeOf(Pointer))^; Inc(AReturnAddresses); Dec(AMaxDepth); end else Dec(ASkipFrames); {Get the next frame} LCurrentFrame := PNativeUInt(LCurrentFrame)^; end; {Clear the remaining entries} while AMaxDepth > 0 do begin AReturnAddresses^ := 0; Inc(AReturnAddresses); Dec(AMaxDepth); end; end; procedure GetCodeOffset; var LMapFile: string; begin LMapFile := GetModuleName(hInstance); SGetModuleHandle := GetModuleHandle(Pointer(ExtractFileName(LMapFile))) + CODE_SECTION; end; {FastCode source} function GetMethodAddress(AStub: Pointer): Pointer; const CALL_OPCODE = $E8; begin if PBYTE(AStub)^ = CALL_OPCODE then begin Inc(Integer(AStub)); Result := Pointer(Integer(AStub) + SizeOf(Pointer) + PInteger(AStub)^); end else Result := nil; end; {FastCode source} procedure AddressPatch(const ASource, ADestination: Pointer); const JMP_OPCODE = $E9; SIZE = SizeOf(TJump); var NewJump: PJump; OldProtect: Cardinal; begin if VirtualProtect(ASource, SIZE, PAGE_EXECUTE_READWRITE, OldProtect) then begin NewJump := PJump(ASource); NewJump.OpCode := JMP_OPCODE; NewJump.Distance := Pointer(Integer(ADestination) - Integer(ASource) - 5); FlushInstructionCache(GetCurrentProcess, ASource, SizeOf(TJump)); VirtualProtect(ASource, SIZE, OldProtect, @OldProtect); end; end; function PatchCodeDWORD(ACode: PDWORD; AValue: DWORD): Boolean; var LRestoreProtection, LIgnore: DWORD; begin Result := False; if VirtualProtect(ACode, SizeOf(ACode^), PAGE_EXECUTE_READWRITE, LRestoreProtection) then begin Result := True; ACode^ := AValue; Result := VirtualProtect(ACode, SizeOf(ACode^), LRestoreProtection, LIgnore); if not Result then Exit; Result := FlushInstructionCache(GetCurrentProcess, ACode, SizeOf(ACode^)); end; end; function CurrentMemoryUsage: Cardinal; var LProcessMemoryCounters: TProcessMemoryCounters; begin LProcessMemoryCounters.cb := SizeOf(LProcessMemoryCounters) ; if GetProcessMemoryInfo(GetCurrentProcess, @LProcessMemoryCounters, SizeOf(LProcessMemoryCounters)) then Result := LProcessMemoryCounters.WorkingSetSize; end; procedure SaveMemoryProfileToFile(AFilePath: string); var LStringList: TStringList; i: Integer; LClassVar: TRfClassController; iMem: Integer; LItemMemory: TCallerAllocator; LBufferAllocation: TMemoryAddressBuffer; begin if AFilePath = '' then AFilePath := ExtractFilePath(ParamStr(0)) + 'RfMemoryReport.txt'; LStringList := TStringList.Create; try LStringList.Add('Application Path: ' + ParamStr(0)); LStringList.Add(Format('Total Memory Used By App: %d Mbs', [(CurrentMemoryUsage div 1024) div 1024])); {$IFDEF INSTANCES_TRACKER} LStringList.Add(Format('Module Handle: %d', [SGetModuleHandle])); {$ENDIF} LStringList.Add({$IFDEF INSTANCES_TRACKER}'ALLOC ADDR | ' {$ENDIF} + 'CLASS | INSTANCE SIZE | NUMBER OF INSTANCES | TOTAL'); {$IFDEF INSTANCES_COUNTER} for i := 0 to SListRfClassController.Count -1 do begin LClassVar := TRfClassController(SListRfClassController.Items[I]); if LClassVar.BaseInstanceCount > 0 then begin {$IFDEF INSTANCES_TRACKER} for iMem := 0 to LClassVar.AllocationMap.Count -1 do begin LItemMemory := LClassVar.AllocationMap.Items[iMem]; if LItemMemory.NumAllocations > 0 then LStringList.Add(Format('%d | %s | %d bytes | %d | %d bytes', [LItemMemory.MemAddress, LClassVar.BaseClassName, LClassVar.BaseInstanceSize, LClassVar.BaseInstanceCount, LClassVar.BaseInstanceSize * LItemMemory.NumAllocations])); end; {$ELSE} LStringList.Add(Format('%s | %d bytes | %d | %d bytes', [LClassVar.BaseClassName, LClassVar.BaseInstanceSize, LClassVar.BaseInstanceCount, LClassVar.BaseInstanceSize * LClassVar.BaseInstanceCount])); {$ENDIF} end; end; {$ENDIF} {$IFDEF BUFFER_COUNTER} for I := 0 to SIZE_OF_MAP do if RfMapOfBufferAllocation[I] > 0 then begin {$IFDEF BUFFER_TRACKER} LBufferAllocation := RfMapofBufferAddressAllocation[I]; while LBufferAllocation <> nil do begin if LBufferAllocation.NumAllocations > 0 then LStringList.Add(Format('%d | Buffer | %d bytes | %d | %d bytes', [LBufferAllocation.AllocationAddr, I, LBufferAllocation.NumAllocations, LBufferAllocation.NumAllocations * I])); LBufferAllocation := LBufferAllocation.Next; end; {$ELSE} LStringList.Add(Format('Buffer | %d bytes | %d | %d bytes', [I, RfMapOfBufferAllocation[I], RfMapOfBufferAllocation[I] * I])); {$ENDIF} end; {$ENDIF} LStringList.SaveToFile(AFilePath); finally FreeAndNil(LStringList); end; end; type PStackFrame = ^TStackFrame; TStackFrame = record CallerFrame: Cardinal; CallerAddr: Cardinal; end; function GetSectorIdentificator: Integer; begin GetFrameBasedStackTrace(@Result, 1, 3); end; function GetMemAllocIdentificator: Integer; begin GetFrameBasedStackTrace(@Result, 1, 4); end; function RfGetInstanceList: TList; begin Result := SListRfClassController; end; function _InitializeHook(AClass: TClass; AOffset: Integer; HookAddress: Pointer): Boolean; var lAddress: Pointer; lProtect: DWord; begin lAddress := Pointer(Integer(AClass) + AOffset); Result := VirtualProtect(lAddress, SIZE_OF_INT, PAGE_READWRITE, @lProtect); if not Result then Exit; CopyMemory(lAddress, @HookAddress, SIZE_OF_INT); Result := VirtualProtect(lAddress, SIZE_OF_INT, lProtect, @lProtect); end; procedure RegisterRfClassController(const Classes: array of TRfObjectHack); var LClass: TRfObjectHack; begin for LClass in Classes do if LClass.GetRfClassController = nil then LClass.SetRfClassController(TRfClassController.Create) else raise Exception.CreateFmt('Class %s has automated section or duplicated registration.', [LClass.ClassName]); end; {$ENDREGION} {$REGION 'Override Methods'} procedure OldNewInstance; asm call TObject.NewInstance; end; procedure OldInstanceSize; asm call TObject.InstanceSize end; {$ENDREGION} {$REGION 'Instances Control'} { TObjectHack } type TExecute = procedure of object; procedure TRfObjectHack.CallOldFunction; var Routine: TMethod; Execute: TExecute; begin Routine.Data := Pointer(Self); Routine.Code := GetRfClassController.OldVMTFreeInstance; Execute := TExecute(Routine); Execute; end; procedure TRfObjectHack.DecCounter; begin {$IFDEF INSTANCES_TRACKER} GetRfClassController.AllocationMap.DecCounter(AllocationAddress); {$ENDIF} GetRfClassController.BaseInstanceCount := GetRfClassController.BaseInstanceCount - 1; CallOldFunction; end; function TRfObjectHack.GetAllocationAddress: Integer; begin Result := PInteger(Integer(Self) + Self.InstanceSize)^; end; class function TRfObjectHack.GetRfClassController: TRfClassController; begin Result := PRfClassController(Integer(Self) + vmtAutoTable)^; end; procedure TRfObjectHack.SetAllocationAddress(const Value: Integer); begin PInteger(Integer(Self) + Self.InstanceSize)^ := Value; end; class procedure TRfObjectHack.SetRfClassController(ARfClassController: TRfClassController); begin ARfClassController.BaseClassName := Self.ClassName; ARfClassController.BaseInstanceSize := Self.InstanceSize; ARfClassController.BaseClassType := Self; ARfClassController.OldVMTFreeInstance := PPointer(Integer(TClass(Self)) + vmtFreeInstance)^; if Self.ClassParent <> nil then ARfClassController.BaseParentClassName := Self.ClassParent.ClassName; PatchCodeDWORD(PDWORD(Integer(Self) + vmtAutoTable), DWORD(ARfClassController)); _InitializeHook(Self, vmtFreeInstance, @TRfObjectHack.DecCounter); end; procedure TRfObjectHack.NFreeInstance; begin CleanupInstance; SDefaultFreeMem(Self); end; class function TRfObjectHack.NNewInstance: TObject; begin Result := InitInstance(SDefaultGetMem(Self.InstanceSize)); end; class function TRfObjectHack.NNewInstanceTrace: TObject; begin Result := InitInstance(SDefaultGetMem(Self.InstanceSize {$IFDEF INSTANCES_TRACKER} + SIZE_OF_INT {$ENDIF})); if (Result.ClassType = TObject) or (Result.ClassType = TRfClassController) or (Result.ClassType = TAllocationMap) or (Result.ClassType = TMemoryAddressBuffer) or (Result.ClassType = TCriticalSectionIgnore) or (Result is EExternal) then begin Exit; end; {$IFDEF INSTANCES_TRACKER} TRfObjectHack(Result).AllocationAddress := GetSectorIdentificator; {$ENDIF} TRfObjectHack(Result).IncCounter; end; procedure TRfObjectHack.IncCounter; begin if GetRfClassController = nil then RegisterRfClassController(Self); GetRfClassController.BaseInstanceCount := GetRfClassController.BaseInstanceCount + 1; {$IFDEF INSTANCES_TRACKER} GetRfClassController.AllocationMap.IncCounter(AllocationAddress); {$ENDIF} end; { TClassVars } constructor TRfClassController.Create; begin SListRfClassController.Add(Self); {$IFDEF INSTANCES_TRACKER} AllocationMap := TAllocationMap.Create; {$ENDIF} end; { TAllocationMap } procedure TAllocationMap.QuickSort; begin QuickSortInternal(Low(FItems), High(FItems)); end; procedure TAllocationMap.QuickSortInternal(ALow, AHigh: Integer); var LLow, LHigh, LPivot, LValue: Integer; begin LLow := ALow; LHigh := AHigh; LPivot := FItems[(LLow + LHigh) div 2].MemAddress; repeat while FItems[LLow].MemAddress < LPivot do Inc(LLow); while FItems[LHigh].MemAddress > LPivot do Dec(LHigh); if LLow <= LHigh then begin LValue := FItems[LLow].MemAddress; FItems[LLow].MemAddress := FItems[LHigh].MemAddress; FItems[LHigh].MemAddress := LValue; Inc(LLow); Dec(LHigh); end; until LLow > LHigh; if LHigh > ALow then QuickSortInternal(ALow, LHigh); if LLow < AHigh then QuickSortInternal(LLow, AHigh); end; function TAllocationMap.BinarySearch(const ACallerAddr: Cardinal): Integer; var LMinIndex, LMaxIndex: Cardinal; LMedianIndex, LMedianValue: Cardinal; begin LMinIndex := Low(FItems); LMaxIndex := Length(FItems); while LMinIndex <= LMaxIndex do begin LMedianIndex := (LMinIndex + LMaxIndex) div 2; LMedianValue := FItems[LMedianIndex].MemAddress; if ACallerAddr < LMedianValue then LMaxIndex := Pred(LMedianIndex) else if ACallerAddr = LMedianValue then begin Result := LMedianIndex; Exit; end else LMinIndex := Succ(LMedianIndex); end; Result := -1; end; function TAllocationMap.Count: Integer; begin Result := Length(FItems); end; constructor TAllocationMap.Create; begin inherited; SetLength(FItems, 1); FItems[0].MemAddress := 0; FItems[0].NumAllocations := 0; FCriticalSection := TCriticalSectionIgnore.Create; end; procedure TAllocationMap.DecCounter(ACallerAddr: Integer); var LItem: PCallerAllocator; begin LItem := @FItems[FindOrAdd(ACallerAddr)]; LItem^.NumAllocations := LItem^.NumAllocations - 1; end; destructor TAllocationMap.Destroy; begin FCriticalSection.Free; inherited; end; function TAllocationMap.FindOrAdd(const ACallerAddr: Integer): Integer; begin Result := BinarySearch(ACallerAddr); if Result = -1 then begin FCriticalSection.Acquire; SetLength(FItems, Length(FItems) + 1); FItems[Length(FItems) - 1].MemAddress := ACallerAddr; FItems[Length(FItems) - 1].NumAllocations := 0; QuickSort; FCriticalSection.Release; end; Result := BinarySearch(ACallerAddr); end; function TAllocationMap.GetAllocationCounterByCallerAddr(ACallerAddr: Cardinal): TCallerAllocator; begin Result := Items[BinarySearch(ACallerAddr)]; end; function TAllocationMap.GetItems(Index: Integer): TCallerAllocator; begin Result := FItems[Index]; end; procedure TAllocationMap.IncCounter(ACallerAddr: Integer); var LItem: PCallerAllocator; begin LItem := @FItems[FindOrAdd(ACallerAddr)]; LItem^.NumAllocations := LItem^.NumAllocations + 1; end; {$ENDREGION} {$REGION 'Buffer Control'} function IsInMap(AValue: Integer): Boolean; inline; begin try Result := (AValue = PARITY_BYTE); except Result := False; end; end; function MemorySizeOfPos(APos: Integer): Integer; inline; begin Result := (APos - Integer(@RfMapOfBufferAllocation)) div SIZE_OF_INT; end; function GetAmountOfAllocationOfClass(AClassType: TClass): Integer; var I: Integer; LRfClassController: TRfClassController; begin Result := 0; for I := 0 to SListRfClassController.Count -1 do begin LRfClassController := TRfClassController(SListRfClassController.Items[I]); if LRfClassController.BaseClassType = AClassType then begin Result := LRfClassController.BaseInstanceCount; Exit; end; end; end; function GetBytesAmountOfInstanceAllocation: Integer; var I: Integer; LRfClassController: TRfClassController; begin Result := 0; for I := 0 to SListRfClassController.Count -1 do begin LRfClassController := TRfClassController(SListRfClassController.Items[I]); if LRfClassController.BaseInstanceCount > 0 then Result := (LRfClassController.BaseInstanceCount * LRfClassController.BaseInstanceSize)+ Result; end; end; function GetBytesAmountOfBufferAllocation: Integer; var I: Integer; begin Result := 0; for I := 0 to SIZE_OF_MAP do if RfMapOfBufferAllocation[I] > 0 then Result := (I * RfMapOfBufferAllocation[I]) + Result; end; function GetBytesAmountOfUsedMemory: Integer; begin Result := GetBytesAmountOfInstanceAllocation + GetBytesAmountOfBufferAllocation; end; function GetAmountOfBufferAllocations(ACallerAddr: Cardinal; ABufferSize: Cardinal): Integer; var LMemoryBufferAddress: TMemoryAddressBuffer; LLastMemoryBufferAddress: TMemoryAddressBuffer; begin if RfMapofBufferAddressAllocation[ABufferSize] = nil then begin Result := 0; Exit; end; LLastMemoryBufferAddress := RfMapofBufferAddressAllocation[ABufferSize]; LMemoryBufferAddress := LLastMemoryBufferAddress; while (LMemoryBufferAddress <> nil) do begin {$IFDEF BUFFER_TRACKER} if LMemoryBufferAddress.AllocationAddr <> ACallerAddr then begin LLastMemoryBufferAddress := LMemoryBufferAddress; LMemoryBufferAddress := LMemoryBufferAddress.Next; Continue; end; {$ENDIF} Result := LMemoryBufferAddress.NumAllocations; Exit; end; Result := 0; end; procedure MemoryBufferCounter(ABufSize: Integer; AInitialPointer: PMappedRecord; AValue: Integer); var LMemoryBufferAddress: TMemoryAddressBuffer; LLastMemoryBufferAddress: TMemoryAddressBuffer; begin if RfMapofBufferAddressAllocation[ABufSize] = nil then begin RfMapofBufferAddressAllocation[ABufSize] := TMemoryAddressBuffer.Create; RfMapofBufferAddressAllocation[ABufSize].NumAllocations := AValue; {$IFDEF BUFFER_TRACKER} RfMapofBufferAddressAllocation[ABufSize].AllocationAddr := AInitialPointer.AllocationAddr; {$ENDIF} Exit; end; LLastMemoryBufferAddress := RfMapofBufferAddressAllocation[ABufSize]; LMemoryBufferAddress := LLastMemoryBufferAddress; while (LMemoryBufferAddress <> nil) do begin {$IFDEF BUFFER_TRACKER} if LMemoryBufferAddress.AllocationAddr <> AInitialPointer.AllocationAddr then begin LLastMemoryBufferAddress := LMemoryBufferAddress; LMemoryBufferAddress := LMemoryBufferAddress.Next; Continue; end; {$ENDIF} SRCBufferCounter.Acquire; try LMemoryBufferAddress.NumAllocations := LMemoryBufferAddress.NumAllocations + AValue; finally SRCBufferCounter.Release; end; Exit; end; SRCBufferCounter.Acquire; try LMemoryBufferAddress := TMemoryAddressBuffer.Create; {$IFDEF BUFFER_TRACKER} LMemoryBufferAddress.AllocationAddr := AInitialPointer.AllocationAddr; {$ENDIF} LMemoryBufferAddress.NumAllocations := LMemoryBufferAddress.NumAllocations + AValue; LLastMemoryBufferAddress.Next := LMemoryBufferAddress; finally SRCBufferCounter.Release; end; end; function NGetMem(Size: Integer): Pointer; var MapSize: Integer; LMappedRecord: PMappedRecord; begin if (Size = SIZE_OF_INT) then begin Result := SDefaultAllocMem(Size); Exit; end; if Size >= SIZE_OF_MAP then MapSize := SIZE_OF_MAP else MapSize := Size; Result := SDefaultGetMem(Size + GAP_SIZE); LMappedRecord := Result; LMappedRecord^.SetParityByte; LMappedRecord^.SizeCounterAddr := Integer(@RfMapOfBufferAllocation[MapSize]); LMappedRecord^.IncMapSizeCounter; {$IFDEF BUFFER_TRACKER} LMappedRecord^.AllocationAddr := GetMemAllocIdentificator; LMappedRecord^.IncAllocationMap; {$ENDIF} {$IFDEF UNITTEST} if LMappedRecord.Size = BUFFER_TEST_SIZE then SetAllocationAddress(LMappedRecord); {$ENDIF} Result := Pointer(Integer(Result) + GAP_SIZE); end; function NAllocMem(Size: Cardinal): Pointer; var MapSize: Integer; LMappedRecord: PMappedRecord; begin if (Size = SIZE_OF_INT) then begin Result := SDefaultAllocMem(Size); Exit; end; if Size > SIZE_OF_MAP then MapSize := SIZE_OF_MAP else MapSize := Size; Result := SDefaultAllocMem(Size + GAP_SIZE); LMappedRecord := Result; LMappedRecord^.SetParityByte; LMappedRecord^.SizeCounterAddr := Integer(@RfMapOfBufferAllocation[MapSize]); LMappedRecord^.IncMapSizeCounter; {$IFDEF BUFFER_TRACKER} LMappedRecord^.AllocationAddr := GetMemAllocIdentificator; LMappedRecord^.IncAllocationMap; {$ENDIF} {$IFDEF UNITTEST} if Size = BUFFER_TEST_SIZE then SetAllocationAddress(Result); {$ENDIF} Result := Pointer(Integer(Result) + GAP_SIZE); end; function NFreeMem(P: Pointer): Integer; var LMappedRecord: PMappedRecord; begin LMappedRecord := Pointer(Integer(P) - GAP_SIZE); if IsInMap(LMappedRecord^.Parity) then begin LMappedRecord^.ClearParityByte; LMappedRecord^.DecMapSizeCounter; {$IFDEF BUFFER_TRACKER} LMappedRecord^.DecAllocationMap; {$ENDIF} {$IFDEF UNITTEST} if LMappedRecord.Size = BUFFER_TEST_SIZE then SetDeallocationAddress(LMappedRecord); {$ENDIF} Result := SDefaultFreeMem(LMappedRecord); end else Result := SDefaultFreeMem(P); end; function NReallocMem(P: Pointer; Size: Integer): Pointer; var LMappedRecord: PMappedRecord; LSizeMap: Integer; begin LMappedRecord := Pointer(Integer(P) - GAP_SIZE); if not IsInMap(LMappedRecord^.Parity) then begin Result := SDefaultReallocMem(P, Size); Exit; end; if Size > SIZE_OF_MAP then LSizeMap := SIZE_OF_MAP else LSizeMap := Size; LMappedRecord^.ClearParityByte; LMappedRecord^.DecMapSizeCounter; {$IFDEF BUFFER_TRACKER} LMappedRecord^.DecAllocationMap; {$ENDIF} Result := SDefaultReallocMem(LMappedRecord, Size + GAP_SIZE); LMappedRecord := Result; LMappedRecord^.SetParityByte; LMappedRecord^.SizeCounterAddr := Integer(@RfMapOfBufferAllocation[LSizeMap]); LMappedRecord^.IncMapSizeCounter; {$IFDEF BUFFER_TRACKER} LMappedRecord^.IncAllocationMap; {$ENDIF} Result := Pointer(Integer(LMappedRecord) + GAP_SIZE); end; procedure InitializeArray; var I: Integer; begin for I := 0 to SIZE_OF_MAP do RfMapOfBufferAllocation[I] := 0; end; {$ENDREGION} procedure ApplyMemoryManager; var LMemoryManager: TMemoryManagerEx; begin GetMemoryManager(LMemoryManager); SDefaultGetMem := LMemoryManager.GetMem; {$IFNDEF BUFFER_COUNTER} Exit; {$ENDIF} LMemoryManager.GetMem := NGetMem; SDefaultFreeMem := LMemoryManager.FreeMem; LMemoryManager.FreeMem := NFreeMem; SDefaultReallocMem := LMemoryManager.ReallocMem; LMemoryManager.ReallocMem := NReallocMem; SDefaultAllocMem := LMemoryManager.AllocMem; LMemoryManager.AllocMem := NAllocMem; SetMemoryManager(LMemoryManager); end; destructor TRfClassController.Destroy; begin {$IFDEF INSTANCES_TRACKER} AllocationMap.Free; AllocationMap := nil; {$ENDIF} inherited; end; { MappedRecord } {$IFDEF BUFFER_TRACKER} procedure TMappedRecord.DecAllocationMap; begin MemoryBufferCounter(MemorySizeOfPos(SizeCounterAddr), PMappedRecord(@Self), -1); end; {$ENDIF} procedure TMappedRecord.DecMapSizeCounter; begin SRCBufferCounter.Acquire; try Integer(Pointer(SizeCounterAddr)^) := Integer(Pointer(SizeCounterAddr)^) - 1; finally SRCBufferCounter.Release; end; end; {$IFDEF BUFFER_TRACKER} procedure TMappedRecord.IncAllocationMap; begin MemoryBufferCounter(MemorySizeOfPos(SizeCounterAddr), PMappedRecord(@Self), +1); end; {$ENDIF} procedure TMappedRecord.IncMapSizeCounter; begin SRCBufferCounter.Acquire; try Integer(Pointer(SizeCounterAddr)^) := Integer(Pointer(SizeCounterAddr)^) + 1; finally SRCBufferCounter.Release; end; end; procedure TMappedRecord.SetParityByte; begin Parity := PARITY_BYTE; end; function TMappedRecord.Size: Integer; begin Result := (Self.SizeCounterAddr - Integer(@RfMapOfBufferAllocation)) div SIZE_OF_INT; end; procedure TMappedRecord.ClearParityByte; begin Parity := 0; end; procedure InitializeRfMemoryProfiler; begin if RfIsMemoryProfilerActive then Exit; RfIsMemoryProfilerActive := True; SRCBufferCounter := TCriticalSection.Create; GetCodeOffset; RfIsObjectAllocantionTraceOn := False; {$IFDEF INSTANCES_TRACKER} RfIsObjectAllocantionTraceOn := True; {$ENDIF} RfIsBufferAllocationTraceOn := False; {$IFDEF BUFFER_TRACKER} RfIsBufferAllocationTraceOn := True; {$ENDIF} {$IFDEF INSTANCES_COUNTER} SListRfClassController := TList.Create; {$ENDIF} {$IFDEF BUFFER_COUNTER} InitializeArray; {$ENDIF} ApplyMemoryManager; /// Buffer wrapper {$IFDEF BUFFER_COUNTER} {$IFNDEF INSTANCES_COUNTER} AddressPatch(GetMethodAddress(@OldNewInstance), @TObjectHack.NNewInstance); {$ENDIF} {$ENDIF} ///Class wrapper {$IFDEF INSTANCES_COUNTER} AddressPatch(GetMethodAddress(@OldNewInstance), @TRfObjectHack.NNewInstanceTrace); {$ENDIF} end; initialization RfIsMemoryProfilerActive := False; {$IFNDEF UNITTEST} {$IFNDEF FASTMM} InitializeRfMemoryProfiler; {$ENDIF} {$ENDIF} end.
unit uAmdGpu; interface uses uTypes, adl_defines, adl_sdk, adl_structures; type TADL_MAIN_CONTROL_CREATE = function(param1: ADL_MAIN_MALLOC_CALLBACK; param2: Integer): Integer; cdecl; TADL_MAIN_CONTROL_DESTROY = function: Integer; cdecl; TADL_FAN_CONTROL_GET = function(pContext: Pointer; iAdapterIndex: Integer; var FanControl: ADLODNFanControl): Integer; cdecl; TADL_FAN_CONTROL_SET = function(pContext: Pointer; iAdapterIndex: Integer; PFanControl: Pointer): Integer; cdecl; TADL_OVERDRIVE5_TEMPERATURE_GET = function (iAdapterIndex, iThermalControllerIndex : integer; var lpTemperature : ADLTemperature) : integer; cdecl; TADL_OVERDRIVE5_FANSPEED_GET = function (iAdapterIndex, iThermalControllerIndex: integer; var lpFanSpeedValue: ADLFanSpeedValue): integer; cdecl; TADL_ADAPTER_NUMBEROFADAPTERS_GET = function (var lpNumAdapters: integer): integer; cdecl; TADL_ADAPTER_ACTIVE_GET = function(iAdapterIndex: integer; var lpStatus: Integer): Integer; cdecl; TADL_ADAPTER_ADAPTERINFO_GET = function(AInfo : Pointer; iInputSize: Integer): integer; cdecl; TAmdGpu = class(TGpu) private protected function GetFanSpeed(idx: Integer): Integer; override; function GetTemperature(idx: Integer): Integer; override; function GetTargetTemperature(idx: Integer): Integer; override; procedure SetTargetTemperature(idx: Integer; ATargetTemp: Integer); override; function GetAdapterActive(idx: Integer): Boolean; override; public class function GetNumberOfAdapters(): Integer; override; class function GetAdapterInfo(idx: Integer): LPAdapterInfo; override; constructor Create(); destructor Destroy(); override; end; var AmdCardsPresent: Boolean; implementation uses Windows; const ATI_DLL = 'atiadlxy.dll'; var hDLL: Integer; ADL_context: Pointer; ADL_Fan_Control_Get: TADL_Fan_Control_Get; ADL_Fan_Control_Set: TADL_Fan_Control_Set; ADL_Overdrive5_Temperature_Get: TADL_OVERDRIVE5_TEMPERATURE_GET; ADL_Adapter_NumberOfAdapters_Get: TADL_ADAPTER_NUMBEROFADAPTERS_GET; ADL_Adapter_Active_Get: TADL_ADAPTER_ACTIVE_GET; ADL_Adapter_AdapterInfo_Get: TADL_ADAPTER_ADAPTERINFO_GET; ADL_Overdrive5_FanSpeed_Get: TADL_OVERDRIVE5_FANSPEED_GET; { TAmdGpu } constructor TAmdGpu.Create(); begin inherited; end; destructor TAmdGpu.Destroy(); begin inherited; end; function TAmdGpu.GetAdapterActive(idx: Integer): Boolean; var status: Integer; begin ADL_Adapter_Active_Get(idx, status); Result := status = ADL_OK; end; class function TAmdGpu.GetAdapterInfo(idx: Integer): LPAdapterInfo; var size: Integer; ADL_PInfo: LPAdapterInfo; begin size := sizeof(AdapterInfo) * GetNumberOfAdapters(); ADL_PInfo := AllocMem(size); ADL_Adapter_AdapterInfo_Get(ADL_PInfo, size); for size := 1 to idx do inc(ADL_PInfo); Result := ADL_PInfo; end; function TAmdGpu.GetFanSpeed(idx: Integer): Integer; var fanSpeed: ADLFanSpeedValue; begin fanSpeed.iSize := sizeof(fanSpeed); ADL_Overdrive5_Fanspeed_Get(idx, 0, fanSpeed); Result := fanSpeed.iFanSpeed; end; class function TAmdGpu.GetNumberOfAdapters(): Integer; begin ADL_Adapter_NumberOfAdapters_Get(Result); end; function TAmdGpu.GetTemperature(idx: Integer): Integer; var temperature: ADLTemperature; begin temperature.iSize := sizeof(temperature); ADL_Overdrive5_Temperature_Get(idx, 0, temperature); Result := Round(temperature.iTemperature / 1000); end; function TAmdGpu.GetTargetTemperature(idx: Integer): Integer; var fan: ADLODNFanControl; begin ADL_Fan_Control_Get(nil, idx, fan); Result := fan.iTargetTemperature; end; procedure TAmdGpu.SetTargetTemperature(idx: Integer; ATargetTemp: Integer); var fan: ADLODNFanControl; begin ADL_Fan_Control_Get(nil, idx, fan); fan.iTargetTemperature := ATargetTemp; ADL_Fan_Control_Set(nil, idx, @fan); end; var ADL_Main_Control_Create: TADL_MAIN_CONTROL_CREATE; ADL_Main_Control_Destroy: TADL_MAIN_CONTROL_DESTROY; function ADL_Main_Memory_Alloc(iSize: Integer): Pointer; stdcall; begin Result := AllocMem(iSize); end; initialization begin AmdCardsPresent := False; try hDLL := LoadLibrary(ATI_DLL); if hDLL <> 0 then begin ADL_Main_Control_Create := GetProcAddress(hDLL, 'ADL_Main_Control_Create'); if Assigned(ADL_Main_Control_Create) then begin ADL_context := @ADL_Main_Memory_Alloc; AmdCardsPresent := ADL_Main_Control_Create(ADL_context, 1) = ADL_OK; end; end; ADL_Fan_Control_Get := GetProcAddress(hDLL, 'ADL2_OverdriveN_FanControl_Get'); ADL_Fan_Control_Set := GetProcAddress(hDLL, 'ADL2_OverdriveN_FanControl_Set'); ADL_Adapter_NumberOfAdapters_Get := GetProcAddress(hDLL, 'ADL_Adapter_NumberOfAdapters_Get'); ADL_Overdrive5_Temperature_Get := GetProcAddress(hDLL, 'ADL_Overdrive5_Temperature_Get'); ADL_Adapter_AdapterInfo_Get := GetProcAddress(hDLL, 'ADL_Adapter_AdapterInfo_Get'); ADL_Adapter_Active_Get := GetProcAddress(hDLL, 'ADL_Adapter_Active_Get'); ADL_Overdrive5_Fanspeed_Get := GetProcAddress(hDLL, 'ADL_Overdrive5_FanSpeed_Get'); except end; end; finalization begin if AmdCardsPresent then begin ADL_Main_Control_Destroy := GetProcAddress(hDLL, 'ADL_Main_Control_Destroy'); if Assigned(ADL_Main_Control_Destroy) then ADL_Main_Control_Destroy(); end; end; end.
unit clControleKM; interface uses clConexao; type TControleKM = Class(TObject) private function getData: TDateTime; function getEntregador: Integer; function getExecutor: String; function getHoraRetorno: String; function getHoraSaida: String; function getKMFinal: Integer; function getKMInicial: Integer; function getManutencao: TDateTime; function getObs: String; function getPlaca: String; function getSequencia: Integer; procedure setData(const Value: TDateTime); procedure setEntregador(const Value: Integer); procedure setExecutor(const Value: String); procedure setHoraRetorno(const Value: String); procedure setHoraSaida(const Value: String); procedure setKMFinal(const Value: Integer); procedure setKMInicial(const Value: Integer); procedure setManutencao(const Value: TDateTime); procedure setObs(const Value: String); procedure setPlaca(const Value: String); procedure setSequencia(const Value: Integer); constructor Create; destructor Destroy; protected _sequencia: Integer; _data: TDateTime; _placa: String; _kminicial: Integer; _horasaida: String; _kmfinal: Integer; _horaretorno: String; _entregador: Integer; _obs: String; _executor: String; _manutencao: TDateTime; _conexao: TConexao; public property Sequencia: Integer read getSequencia write setSequencia; property Data: TDateTime read getData write setData; property Placa: String read getPlaca write setPlaca; property KMInicial: Integer read getKMInicial write setKMInicial; property HoraSaida: String read getHoraSaida write setHoraSaida; property KMFinal: Integer read getKMFinal write setKMFinal; property HoraRetorno: String read getHoraRetorno write setHoraRetorno; property Entregador: Integer read getEntregador write setEntregador; property Obs: String read getObs write setObs; property Executor: String read getExecutor write setExecutor; property Manutencao: TDateTime read getManutencao write setManutencao; function Validar(): Boolean; function Delete(filtro: String): Boolean; function getObject(id, filtro: String): Boolean; function Insert(): Boolean; function Update(): Boolean; function getField(campo, coluna: String): String; function getObjects(): Boolean; function getSeq(iKm1, iKm2, sData, sPlaca: String): Integer; function Exist(): Boolean; procedure MaxSequencia; end; const TABLENAME = 'TBCONTROLEKM'; implementation { TControleKM } uses udm, ufrmMain, clUtil, Math, ufrmListaApoio, uGlobais, Dialogs, SysUtils, DB; constructor TControleKM.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TControleKM.Destroy; begin _conexao.Free; end; function TControleKM.getData: TDateTime; begin Result := _data; end; function TControleKM.getEntregador: Integer; begin Result := _entregador; end; function TControleKM.getExecutor: String; begin Result := _executor; end; function TControleKM.getHoraRetorno: String; begin Result := _horaretorno; end; function TControleKM.getHoraSaida: String; begin Result := _horasaida; end; function TControleKM.getKMFinal: Integer; begin Result := _kmfinal; end; function TControleKM.getKMInicial: Integer; begin Result := _kminicial; end; function TControleKM.getManutencao: TDateTime; begin Result := _manutencao; end; function TControleKM.getObs: String; begin Result := _obs; end; function TControleKM.getPlaca: String; begin Result := _placa; end; function TControleKM.getSequencia: Integer; begin Result := _sequencia; end; function TControleKM.Validar(): Boolean; begin try Result := False; if TUtil.Empty(Self.Placa) then begin MessageDlg('Informe a Placa do Veículo!', mtWarning, [mbOK], 0); Exit; end; if Self.KMInicial > Self.KMFinal then begin MessageDlg('KM Inicial não pode ser maior que KM Final!', mtWarning, [mbOK], 0); Exit; end; if Self.Entregador = 0 then begin MessageDlg('Informe o Entregador / Funcionário!', mtWarning, [mbOK], 0); Exit; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TControleKM.Delete(filtro: String): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'PLACA' then begin SQL.Add('WHERE DES_PLACA = :PLACA'); ParamByName('PLACA').AsString := Self.Placa; end else if filtro = 'ENTREGADOR' then begin SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); ParamByName('ENTREGADOR').AsInteger := Self.Entregador; end else if filtro = 'CODIGO' then begin SQL.Add('WHERE SEQ_CONTROLE = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Sequencia; end; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TControleKM.getObject(id, filtro: String): Boolean; begin try Result := False; if TUtil.Empty(id) then Exit; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'PLACA' then begin SQL.Add('WHERE DES_PLACA = :PLACA'); ParamByName('PLACA').AsString := id; end else if filtro = 'CODIGO' then begin SQL.Add('WHERE SEQ_CONTROLE = :CODIGO'); ParamByName('CODIGO').AsInteger := StrToInt(id); end else if filtro = 'ENTREGADOR' then begin SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); ParamByName('ENTREGADOR').AsInteger := StrToInt(id); end else if filtro = 'FILTRO' then begin dm.qrygetObject.SQL.Add('WHERE ' + Id); end else if filtro = 'DATA' then begin SQL.Add('WHERE DAT_CONTROLE = :DATA'); ParamByName('DATA').AsDate := StrToDate(id); end; dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then begin Self.Sequencia := dm.QryGetObject.FieldByName('SEQ_CONTROLE').AsInteger; Self.Data := dm.QryGetObject.FieldByName('DAT_CONTROLE').AsDateTime; Self.Placa := dm.QryGetObject.FieldByName('DES_PLACA').AsString; Self.KMInicial := dm.QryGetObject.FieldByName('QTD_KM_INICIAL').AsInteger; Self.HoraSaida := dm.QryGetObject.FieldByName('DES_HORA_SAIDA').AsString; Self.KMFinal := dm.QryGetObject.FieldByName('QTD_KM_FINAL').AsInteger; Self.HoraRetorno := dm.QryGetObject.FieldByName('DES_HORA_RETORNO').AsString; Self.Entregador := dm.QryGetObject.FieldByName('COD_ENTREGADOR').AsInteger; Self.Obs := dm.QryGetObject.FieldByName('DES_OBSERVACOES').AsString; Self.Executor := dm.QryGetObject.FieldByName('NOM_EXECUTOR').AsString; Self.Manutencao := dm.QryGetObject.FieldByName('DAT_MANUTENCAO').AsDateTime; Result := True; end else begin dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TControleKM.Insert(): Boolean; begin Try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'SEQ_CONTROLE, ' + 'DAT_CONTROLE, ' + 'DES_PLACA, ' + 'QTD_KM_INICIAL, ' + 'DES_HORA_SAIDA, ' + 'QTD_KM_FINAL, ' + 'DES_HORA_RETORNO, ' + 'COD_ENTREGADOR, ' + 'DES_OBSERVACOES, ' + 'NOM_EXECUTOR, ' + 'DAT_MANUTENCAO) ' + 'VALUES (' + ':CODIGO, ' + ':DATA, ' + ':PLACA, ' + ':KMINICIAL, ' + ':HORASAIDA, ' + ':KMFINAL, ' + ':HORARETORNO, ' + ':ENTREGADOR, ' + ':OBS, ' + ':EXECUTOR, ' + ':MANUTENCAO)'; MaxSequencia; ParamByName('CODIGO').AsInteger := Self.Sequencia; ParamByName('DATA').AsDate := Self.Data; ParamByName('PLACA').AsString := Self.Placa; ParamByName('KMINICIAL').AsInteger := Self.KMInicial; ParamByName('HORASAIDA').AsString := Self.HoraSaida; ParamByName('KMFINAL').AsInteger := Self.KMFinal; ParamByName('HORARETORNO').AsString := Self.HoraRetorno; ParamByName('ENTREGADOR').AsInteger := Self.Entregador; ParamByName('OBS').AsString := Self.Obs; ParamByName('EXECUTOR').AsString := Self.Executor; ParamByName('MANUTENCAO').AsDateTime := Self.Manutencao; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TControleKM.Update(): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DAT_CONTROLE = :DATA, ' + 'DES_PLACA = :PLACA, ' + 'QTD_KM_INICIAL = :KMINICIAL, ' + 'DES_HORA_SAIDA = :HORASAIDA, ' + 'QTD_KM_FINAL = :KMFINAL, ' + 'DES_HORA_RETORNO = :HORARETORNO, ' + 'COD_ENTREGADOR = :ENTREGADOR, ' + 'DES_OBSERVACOES = :OBS, ' + 'NOM_EXECUTOR = :EXECUTOR, ' + 'DAT_MANUTENCAO = :MANUTENCAO ' + 'WHERE ' + 'SEQ_CONTROLE = :CODIGO'; ParamByName('CODIGO').AsInteger := Self.Sequencia; ParamByName('DATA').AsDate := Self.Data; ParamByName('PLACA').AsString := Self.Placa; ParamByName('KMINICIAL').AsInteger := Self.KMInicial; ParamByName('HORASAIDA').AsString := Self.HoraSaida; ParamByName('KMFINAL').AsInteger := Self.KMFinal; ParamByName('HORARETORNO').AsString := Self.HoraRetorno; ParamByName('ENTREGADOR').AsInteger := Self.Entregador; ParamByName('OBS').AsString := Self.Obs; ParamByName('EXECUTOR').AsString := Self.Executor; ParamByName('MANUTENCAO').AsDateTime := Self.Manutencao; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TControleKM.getField(campo, coluna: String): String; begin Try Result := ''; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME; if coluna = 'CODIGO' then begin SQL.Add(' WHERE SEQ_CONTROLE = :CODIGO '); ParamByName('CODIGO').AsInteger := Self.Sequencia; end else if coluna = 'PLACA' then begin SQL.Add(' WHERE DES_PLACA = :PLACA '); ParamByName('PLACA').AsString := Self.Placa; end; dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then Result := dm.QryGetObject.FieldByName(campo).AsString; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TControleKM.getObjects(): Boolean; begin Try Result := False; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if not(dm.QryGetObject.IsEmpty) then begin dm.QryGetObject.First; Result := True; end else begin dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TControleKM.MaxSequencia; begin try with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT MAX(SEQ_CONTROLE) AS CODIGO FROM ' + TABLENAME; dm.ZConn.PingServer; Open; if not(IsEmpty) then First; end; Self.Sequencia := (dm.QryGetObject.FieldByName('CODIGO').AsInteger + 1); dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TControleKM.getSeq(iKm1, iKm2, sData, sPlaca: String): Integer; begin try Result := 0; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); SQL.Add('WHERE QTD_KM_INICIAL = :KM1 AND '); SQL.Add('QTD_KM_FINAL = :KM2 AND '); SQL.Add('DAT_CONTROLE = :DATA AND '); SQL.Add('DES_PLACA = :PLACA'); ParamByName('KM1').AsInteger := StrToInt(iKm1); ParamByName('KM2').AsInteger := StrToInt(iKm2); ParamByName('DATA').AsDate := StrToDate(sData); ParamByName('PLACA').AsString := sPlaca; dm.ZConn.PingServer; Open; if not IsEmpty then begin First; Result := FieldByName('SEQ_CONTROLE').AsInteger; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TControleKM.Exist: Boolean; begin Result := False; With dm.qryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); SQL.Add('WHERE DAT_CONTROLE = :DATA '); SQL.Add('AND COD_ENTREGADOR = :ENTREGADOR '); SQL.Add('AND DES_PLACA = :PLACA '); SQL.Add('AND QTD_KM_INICIAL = :KMINICIAL ' ); SQL.Add('AND QTD_KM_FINAL = :KMFINAL'); ParamByName('DATA').AsDate := Self.Data; ParamByName('ENTREGADOR').AsInteger := Self.Entregador; ParamByName('PLACA').AsString := Self.Placa; ParamByName('KMINICIAL').AsInteger := Self.KMInicial; ParamByName('KMFINAL').AsInteger := Self.KMFinal; dm.ZConn.PingServer; Open; if IsEmpty then begin Close; SQL.Clear; Exit; end; Close; SQL.Clear; end; Result := True; end; procedure TControleKM.setData(const Value: TDateTime); begin _data := Value; end; procedure TControleKM.setEntregador(const Value: Integer); begin _entregador := Value; end; procedure TControleKM.setExecutor(const Value: String); begin _executor := Value; end; procedure TControleKM.setHoraRetorno(const Value: String); begin _horaretorno := Value; end; procedure TControleKM.setHoraSaida(const Value: String); begin _horasaida := Value; end; procedure TControleKM.setKMFinal(const Value: Integer); begin _kmfinal := Value; end; procedure TControleKM.setKMInicial(const Value: Integer); begin _kminicial := Value; end; procedure TControleKM.setManutencao(const Value: TDateTime); begin _manutencao := Value; end; procedure TControleKM.setObs(const Value: String); begin _obs := Value; end; procedure TControleKM.setPlaca(const Value: String); begin _placa := Value; end; procedure TControleKM.setSequencia(const Value: Integer); begin _sequencia := Value; end; end.
program ejercicio10; uses crt; type cliente = record dni : Integer; turno: Integer; end; lista = ^nodo; nodo = record datos : cliente; sig : lista; end; procedure recibirCliente(var c:cliente; var cont:Integer); begin write('Ingrese el DNI del cliente: '); readln(c.dni); cont:= cont + 1; c.turno:= cont; end; procedure agregarAlFinal(var l,ult:lista; c:cliente); var nue: lista; begin new(nue); nue^.datos:= c; nue^.sig:= nil; if (l = nil) then begin l:= nue; ult:= nue; end else ult^.sig:= nue; ult:= nue; end; procedure imprimirLista(l:lista); begin writeln('-----------------------'); while (l <> nil) do begin writeln('DNI: ', l^.datos.dni); writeln('TURNO: ', l^.datos.turno); writeln('--------------'); l:= l^.sig; end; end; procedure verTurnoSig(l:lista; c:cliente); var aux: lista; begin writeln('### TURNO SIGUENTE ###'); writeln('DNI: ', l^.datos.dni); writeln('TURNO: ', l^.datos.turno); aux:= l; l:= aux^.sig; end; procedure atenderCliente(var l:lista; c:cliente); var aux: lista; begin writeln('### TURNO SIGUENTE ###'); writeln('DNI: ', l^.datos.dni); writeln('TURNO: ', l^.datos.turno); aux:= l; l:= aux^.sig; dispose(aux); end; procedure tomarTurno(var c:cliente; var cont:Integer; var l,ult:lista); begin recibirCliente(c,cont); agregarAlFinal(l,ult,c); end; procedure menu(var opc:Integer); begin writeln('#########MENU#########'); writeln('1 para tomar TURNO: '); writeln('2 ver lista de espera: '); writeln('3 Ver Siguiente: '); writeln('4 Atender Cliente: '); writeln('5 para SALIR: '); writeln('######################'); readln(opc); end; var l,ult: lista; c:cliente; opc,cont:Integer; exit: Boolean; begin l:= nil; ult:= nil; exit:= false; cont:=0; opc:= 0; menu(opc); while not exit do begin case opc of 1 : tomarTurno(c,cont,l,ult); 2 : imprimirLista(l); 3 : verTurnoSig(l,c); 4 : atenderCliente(l,c); 5 : exit:= true; else writeln('Ingreso una opcion erronea '); end; menu(opc); clrscr; end; end.
unit DataController; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, db, dbCtrls, ffsException, DataBuf; type TDataController = class; TdcStringList = class(TStringList) private function GetBoolVal(const Name: string): boolean; function GetIntVal(const Name: string): integer; function GetStrVal(const Name: string): string; procedure SetBoolVal(const Name: string; const Value: boolean); procedure SetIntVal(const Name: string; const Value: integer); procedure SetStrVal(const Name, Value: string); function GetCurrVal(const Name: string): currency; function GetFloatVal(const Name: string): Real; procedure SetCurrVal(const Name: string; const Value: currency); procedure SetFloatVal(const Name: string; const Value: Real); public property BoolVal[const Name: string]: boolean read GetBoolVal write SetBoolVal; property IntVal[const Name: string]: integer read GetIntVal write SetIntVal; property StrVal[const Name: string]: string read GetStrVal write SetStrVal; property CurrVal[const Name: string]: currency read GetCurrVal write SetCurrVal; property FloatVal[const Name: string]: real read GetFloatVal write SetFloatVal; end; TdcLink = class(TPersistent) private fDataController : TDataController; fOnReadData : TNotifyEvent; fOnWriteData : TNotifyEvent; fOnClearData : TNotifyEvent; fdcOwner : TControl; fdataLink : TFieldDataLink; procedure SetDataController(value:TDatacontroller); function GetDataSource:TDataSource; function GetFieldName:String; procedure SetFieldName(value:string); function GetField:TField; public constructor create(AOwner:TControl); destructor Destroy; override; property DataController : TDataController read fDataController write setDataController; property OnReadData : TNotifyEvent read FOnReadData write FOnReadData; property OnWriteData : TNotifyEvent read FOnWriteData write FOnWriteData; property OnClearData : TNotifyEvent read FOnClearData write FOnClearData; property dcOwner : TControl read fdcOwner; property DataSource : TDataSource read GetDataSource; property FieldName : String read GetFieldName write SetFieldName; property Field : TField read GetField; procedure BeginEdit; end; TDataController = class(TComponent) private FOnReadData: TNotifyEvent; FReadOnly: boolean; FOnBeforePost: TNotifyEvent; FDataBuf: TDataBuf; FOnWriteData: TNotifyEvent; FOnCancelEdit: TNotifyEvent; FIsWriting: boolean; FIsReading: boolean; procedure SetOnReadData(const Value: TNotifyEvent); procedure SetReadOnly(const Value: boolean); procedure SetOnBeforePost(const Value: TNotifyEvent); procedure SetDataBuf(const Value: TDataBuf); procedure SetOnWriteData(const Value: TNotifyEvent); procedure SetOnCancelEdit(const Value: TNotifyEvent); private FModified: boolean; private { Private declarations } fdcLinks : TList; fDataSource : TDataSource; FOnStartEdit : TNotifyEvent; FOnFinishEdit : TNotifyEvent; procedure AddDataLink(dcLink:TdcLink); procedure RemoveDataLink(dcLink:TdcLink); procedure SetOnStartEdit(const Value: TNotifyEvent); procedure SetOnFinishEdit(const Value: TNotifyEvent); protected { Protected declarations } procedure SetDataSource(value:TDataSource); public { Public declarations } dcStrings : TdcStringList; constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure ClearData; procedure ReadData; procedure WriteData; procedure StartEdit; procedure CancelEdit; procedure FinishEdit; property Modified:boolean read FModified; property IsReading:boolean read FIsReading; property IsWriting:boolean read FIsWriting; published { Published declarations } property DataSource : TDataSource read fDataSource write SetDataSource; property OnStartEdit : TNotifyEvent read FOnStartEdit write SetOnStartEdit; property OnFinishEdit : TNotifyEvent read FOnFinishEdit write SetOnFinishEdit; property OnCancelEdit : TNotifyEvent read FOnCancelEdit write SetOnCancelEdit; property OnReadData : TNotifyEvent read FOnReadData write SetOnReadData; property OnWriteData : TNotifyEvent read FOnWriteData write SetOnWriteData; property OnBeforePost : TNotifyEvent read FOnBeforePost write SetOnBeforePost; property ReadOnly:boolean read FReadOnly write SetReadOnly; property DataBuf:TDataBuf read FDataBuf write SetDataBuf; end; procedure Register; implementation uses ffsutils; //******** TdcLink ************ constructor TdcLink.create(AOwner:TControl); begin inherited create; fdatalink := TFieldDataLink.create; fdatacontroller := nil; fOnReadData := nil; fOnWriteData := nil; fdcOwner := AOwner; end; destructor TdcLink.Destroy; begin fdatalink.Free; if fDataController <> nil then begin fdatacontroller.RemoveDataLink(self); fdatacontroller := nil; end; inherited Destroy; end; function TdcLink.GetFieldName:String; begin result := fdatalink.FieldName; end; procedure TdcLink.SetFieldName(value:string); begin fdatalink.FieldName := value; end; function TdcLink.GetField; begin result := fdatalink.Field; end; function TdcLink.GetDataSource:TDataSource; begin if assigned(fdatacontroller) then result := fdatacontroller.datasource else result := nil; end; procedure TdcLink.SetDataController(value:TDatacontroller); begin if FDataController <> value then begin if FDataController <> nil then FDataController.RemoveDataLink(Self); if value <> nil then begin value.AddDataLink(Self); fdatalink.DataSource := value.DataSource; end; end; end; // ************* data controller *********** constructor TDataController.create(AOwner:TComponent); begin inherited; fdcLinks := TList.Create; dcStrings := TdcStringList.Create; end; destructor TDataController.destroy; begin while FdcLinks.Count > 0 do RemoveDataLink(FdcLinks.Last); dcStrings.Free; fdcLinks.Free; inherited; end; procedure TDataController.SetDataSource(value:TDataSource); var x : integer; begin if value <> fdatasource then begin fDataSource := value; for x := 0 to fdclinks.Count - 1 do begin with TdcLink(fdclinks[x]) do fdatalink.datasource := value; end; end; end; procedure TDataController.AddDataLink(dcLink: TdcLink); begin FdcLinks.Add(dcLink); dcLink.fDataController := Self; end; procedure TDataController.RemoveDataLink(dcLink: TdcLink); begin dcLink.fDataController := nil; FdcLinks.Remove(dcLink); end; procedure TDataController.ReadData; var x : integer; link : TDcLink; begin FIsReading := true; for x := 0 to fdclinks.Count - 1 do begin Link := TdcLink(fDcLinks[x]); if Assigned(Link.FOnReadData) then Link.FOnReadData(self); end; if Assigned(FOnReadData) then FOnReadData(self); FIsReading := false; FModified := false; end; procedure TDataController.WriteData; var x : integer; begin FIsWriting := true; for x := 0 to fdclinks.Count - 1 do begin with TdcLink(fdclinks[x]) do if Assigned(FOnWriteData) then FOnWriteData(self); end; if Assigned(FOnWriteData) then FOnWriteData(self); FIsWriting := false; FinishEdit; end; procedure TDataController.ClearData; var x : integer; begin for x := 0 to fdclinks.Count - 1 do begin with TdcLink(fdclinks[x]) do if Assigned(FOnClearData) then FOnClearData(self); end; dcStrings.Clear; end; procedure Register; begin RegisterComponents('FFS Data Entry', [TDataController]); end; procedure TDataController.SetOnStartEdit(const Value: TNotifyEvent); begin FOnStartEdit := Value; end; procedure TDataController.SetOnFinishEdit(const Value: TNotifyEvent); begin FOnFinishEdit := Value; end; procedure TdcLink.BeginEdit; begin if assigned(datacontroller) then datacontroller.StartEdit; end; procedure TDataController.StartEdit; begin if IsReading then exit; if modified then exit; FModified := true; if assigned(fOnStartEdit) then FOnStartEdit(self); end; procedure TDataController.FinishEdit; begin FModified := false; if assigned(fOnFinishEdit) then fOnFinishEdit(self); end; procedure TDataController.CancelEdit; begin FModified := false; if assigned(FOnCancelEdit) then FOnCancelEdit(self); end; procedure TDataController.SetOnCancelEdit(const Value: TNotifyEvent); begin FOnCancelEdit := Value; end; procedure TDataController.SetOnReadData(const Value: TNotifyEvent); begin FOnReadData := Value; end; procedure TDataController.SetReadOnly(const Value: boolean); begin FReadOnly := Value; end; procedure TDataController.SetOnBeforePost(const Value: TNotifyEvent); begin FOnBeforePost := Value; end; procedure TDataController.SetDataBuf(const Value: TDataBuf); begin FDataBuf := Value; end; procedure TDataController.SetOnWriteData(const Value: TNotifyEvent); begin FOnWriteData := Value; end; { TdcStringList } function TdcStringList.GetBoolVal(const Name: string): boolean; begin result := strtobool(values[Name]); end; function TdcStringList.GetCurrVal(const Name: string): currency; begin try result := StrToCurr(Values[Name]); except result := 0; end; end; function TdcStringList.GetFloatVal(const Name: string): real; begin try result := StrToFloat(Values[Name]); except result := 0; end; end; function TdcStringList.GetIntVal(const Name: string): integer; begin result := strtointdef(values[Name],0); end; function TdcStringList.GetStrVal(const Name: string): string; begin result := values[Name]; end; procedure TdcStringList.SetBoolVal(const Name: string; const Value: boolean); begin values[Name] := iif(value, booltoyn(Value), ''); end; procedure TdcStringList.SetCurrVal(const Name: string; const Value: currency); begin values[Name] := iif(value <> 0, FloatToStr(Value), ''); end; procedure TdcStringList.SetFloatVal(const Name: string; const Value: real); begin values[Name] := iif(value <> 0, FloatToStr(Value), ''); end; procedure TdcStringList.SetIntVal(const Name: string; const Value: integer); begin values[Name] := iif(value <> 0, inttostr(Value), ''); end; procedure TdcStringList.SetStrVal(const Name, Value: string); begin Values[Name] := Value; end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Xml, RemObjects.Elements.EUnit; type DocumentTest = public class (Test) private Data: XmlDocument; public method Setup; override; method DocumentElement; method DocumentType; method NodeType; method Element; method AddChild; method RemoveChild; method ReplaceChild; method CreateAttribute; method CreateXmlNs; method CreateCDataSection; method CreateComment; method CreateElement; method CreateProcessingInstruction; method CreateTextNode; method GetElementsByTagName; method FromFile; method FromBinary; method FromString; method CreateDocument; method Save; end; implementation method DocumentTest.Setup; begin Data := XmlDocument.CreateDocument; Assert.IsNotNil(Data); end; method DocumentTest.AddChild; begin Assert.IsNil(Data.DocumentElement); Assert.AreEqual(Data.ChildCount, 0); Data.AddChild(Data.CreateElement("root")); Assert.IsNotNil(Data.DocumentElement); Assert.AreEqual(Data.ChildCount, 1); Assert.Throws(->Data.AddChild(Data.CreateElement("root"))); //only one root element Assert.Throws(->Data.AddChild(nil)); Assert.Throws(->Data.AddChild(Data.CreateAttribute("id"))); Assert.Throws(->Data.AddChild(Data.CreateTextNode("Test"))); Data.AddChild(Data.CreateComment("Comment")); Assert.AreEqual(Data.ChildCount, 2); Data.AddChild(Data.CreateProcessingInstruction("xml-stylesheet", "type=""text/xsl"" href=""style.xsl""")); end; method DocumentTest.CreateAttribute; begin var Item := Data.CreateElement("root"); Assert.IsNotNil(Item); Data.AddChild(Item); Item.AddChild(Data.CreateXmlNs("cfg", "http://example.com/config/")); Assert.AreEqual(length(Item.GetAttributes), 1); Item := Data.CreateElement("item"); Data.DocumentElement.AddChild(Item); var Value := Data.CreateAttribute("id"); Value.Value := "0"; Assert.IsNotNil(Value); Item.SetAttributeNode(Value); Assert.AreEqual(length(Item.GetAttributes), 1); Assert.AreEqual(Item.GetAttribute("id"), "0"); Value := Data.CreateAttribute("cfg:Saved", "http://example.com/config/"); Value.Value := "true"; Assert.IsNotNil(Value); Item.SetAttributeNode(Value); Assert.AreEqual(length(Item.GetAttributes), 2); Assert.AreEqual(Item.GetAttribute("Saved", "http://example.com/config/"), "true"); Assert.Throws(->Data.CreateAttribute(nil)); Assert.Throws(->Data.CreateAttribute("<xml>")); Assert.Throws(->Data.CreateAttribute(nil, "http://example.com/config/")); Assert.Throws(->Data.CreateAttribute("cfg:Saved", nil)); Assert.Throws(->Data.CreateAttribute("<abc>", "http://example.com/config/")); end; method DocumentTest.CreateXmlNs; begin var Item := Data.CreateElement("root"); Assert.IsNotNil(Item); Data.AddChild(Item); Item.AddChild(Data.CreateXmlNs("cfg", "http://example.com/config/")); Assert.AreEqual(length(Item.GetAttributes), 1); Assert.Throws(->Data.CreateXmlNs(nil, "http://example.com/config/")); Assert.Throws(->Data.CreateXmlNs("cfg", nil)); Assert.Throws(->Data.CreateXmlNs("<xml>", "http://example.com/config/")); end; method DocumentTest.CreateCDataSection; begin var Item := Data.CreateElement("root"); Assert.IsNotNil(Item); Data.AddChild(Item); var Value := Data.CreateCDataSection("Text"); Assert.IsNotNil(Value); Item.AddChild(Value); Assert.AreEqual(Item.ChildCount, 1); Assert.AreEqual(Item[0].NodeType, XmlNodeType.CDATA); Assert.AreEqual(Item.ChildNodes[0].Value, "Text"); end; method DocumentTest.CreateComment; begin var Item := Data.CreateElement("root"); Assert.IsNotNil(Item); Data.AddChild(Item); var Value := Data.CreateComment("Comment"); Assert.IsNotNil(Value); Item.AddChild(Value); Assert.AreEqual(Item.ChildCount, 1); Assert.AreEqual(Item[0].NodeType, XmlNodeType.Comment); Assert.AreEqual(Item.ChildNodes[0].Value, "Comment"); end; method DocumentTest.CreateDocument; begin var Item := XmlDocument.CreateDocument; Assert.IsNotNil(Item); end; method DocumentTest.CreateElement; begin var Item := Data.CreateElement("root"); Assert.IsNotNil(Item); Data.AddChild(Item); Assert.AreEqual(Data.ChildCount, 1); Assert.AreEqual(Data.Item[0].NodeType, XmlNodeType.Element); Assert.AreEqual(Data.Item[0].LocalName, "root"); end; method DocumentTest.CreateProcessingInstruction; begin var Item := Data.CreateElement("root"); Assert.IsNotNil(Item); Data.AddChild(Item); var Value := Data.CreateProcessingInstruction("Custom", "Save=""true"""); Assert.IsNotNil(Value); Item.AddChild(Value); Assert.AreEqual(Item.ChildCount, 1); Assert.AreEqual(Item[0].NodeType, XmlNodeType.ProcessingInstruction); Value := Item[0] as XmlProcessingInstruction; Assert.AreEqual(Value.Target, "Custom"); Assert.AreEqual(Value.Data, "Save=""true"""); end; method DocumentTest.CreateTextNode; begin var Item := Data.CreateElement("root"); Assert.IsNotNil(Item); Data.AddChild(Item); var Value := Data.CreateTextNode("Text"); Assert.IsNotNil(Value); Item.AddChild(Value); Assert.AreEqual(Item.ChildCount, 1); Assert.AreEqual(Item[0].NodeType, XmlNodeType.Text); Assert.AreEqual(Item.ChildNodes[0].Value, "Text"); end; method DocumentTest.DocumentElement; begin Assert.IsNil(Data.DocumentElement); Assert.AreEqual(Data.ChildCount, 0); var Value := Data.CreateElement("root"); Assert.IsNotNil(Value); Data.AddChild(Value); Assert.IsNotNil(Data.DocumentElement); Assert.AreEqual(Data.ChildCount, 1); Assert.IsTrue(Data.DocumentElement.Equals(Value)); end; method DocumentTest.DocumentType; begin Assert.IsNil(Data.DocumentType); Data := XmlDocument.FromString(XmlTestData.CharXml); Assert.IsNotNil(Data.DocumentType); Assert.AreEqual(Data.DocumentType.PublicId, "-//W3C//DTD XHTML 1.0 Transitional//EN"); Assert.AreEqual(Data.DocumentType.SystemId, "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"); end; method DocumentTest.Element; begin Data := XmlDocument.FromString(XmlTestData.PIXml); Assert.IsNotNil(Data.Element["Root"]); Assert.IsNotNil(Data["Readers"]); var Value := Data["User"]; Assert.IsNotNil(Value); Assert.AreEqual(Value.GetAttribute("Name"), "First"); Assert.IsNil(Data[nil]); end; method DocumentTest.FromBinary; begin var Bin := new Binary(XmlTestData.PIXml.ToByteArray); Data := XmlDocument.FromBinary(Bin); Assert.IsNotNil(Data); Assert.AreEqual(Data.ChildCount, 3); Assert.IsNotNil(Data.Element["Root"]); Assert.IsNotNil(Data["Readers"]); end; method DocumentTest.FromFile; begin var File := Sugar.IO.Folder.UserLocal.CreateFile("sugartest.xml", false); try //File.WriteText(XmlTestData.PIXml); Sugar.IO.FileUtils.WriteText(File.Path, XmlTestData.PIXml); Data := XmlDocument.FromFile(File); Assert.IsNotNil(Data); Assert.AreEqual(Data.ChildCount, 3); Assert.IsNotNil(Data.Element["Root"]); Assert.IsNotNil(Data["Readers"]); finally File.Delete; end; end; method DocumentTest.FromString; begin Data := XmlDocument.FromString(XmlTestData.PIXml); Assert.IsNotNil(Data); Assert.AreEqual(Data.ChildCount, 3); Assert.IsNotNil(Data.Element["Root"]); Assert.IsNotNil(Data["Readers"]); end; method DocumentTest.GetElementsByTagName; begin Data := XmlDocument.FromString(XmlTestData.PIXml); var Actual := Data.GetElementsByTagName("User"); var Expected := new Sugar.Collections.List<String>; Expected.Add("First"); Expected.Add("Second"); Expected.Add("Third"); Expected.Add("Admin"); Assert.AreEqual(length(Actual), 4); for i: Integer := 0 to length(Actual) - 1 do begin Assert.AreEqual(Actual[i].NodeType, XmlNodeType.Element); Assert.IsTrue(Expected.Contains(Actual[i].GetAttribute("Name"))); end; Actual := Data.GetElementsByTagName("mail", "http://example.com/config/"); Assert.AreEqual(length(Actual), 1); Assert.AreEqual(Actual[0].NodeType, XmlNodeType.Element); Assert.AreEqual(Actual[0].Value, "first@example.com"); end; method DocumentTest.NodeType; begin Assert.AreEqual(Data.NodeType, XmlNodeType.Document); end; method DocumentTest.RemoveChild; begin Assert.IsNil(Data.DocumentElement); Assert.AreEqual(Data.ChildCount, 0); Data.AddChild(Data.CreateElement("root")); Assert.IsNotNil(Data.DocumentElement); Assert.AreEqual(Data.ChildCount, 1); Data.RemoveChild(Data.DocumentElement); Assert.IsNil(Data.DocumentElement); Assert.AreEqual(Data.ChildCount, 0); Assert.Throws(->Data.RemoveChild(nil)); end; method DocumentTest.ReplaceChild; begin Assert.IsNil(Data.DocumentElement); Assert.AreEqual(Data.ChildCount, 0); Data.AddChild(Data.CreateElement("root")); Assert.IsNotNil(Data.DocumentElement); Assert.AreEqual(Data.ChildCount, 1); Assert.AreEqual(Data.DocumentElement.LocalName, "root"); var Value := Data.CreateElement("items"); Data.ReplaceChild(Data.DocumentElement, Value); Assert.AreEqual(Data.ChildCount, 1); Assert.AreEqual(Data.DocumentElement.LocalName, "items"); Assert.Throws(->Data.ReplaceChild(nil, Data.DocumentElement)); Assert.Throws(->Data.ReplaceChild(Data.DocumentElement, nil)); Assert.Throws(->Data.ReplaceChild(Data.CreateElement("NotExisting"), Data.DocumentElement)); end; method DocumentTest.Save; begin var File := Sugar.IO.Folder.UserLocal.CreateFile("sugartest.xml", false); try Data := XmlDocument.FromString(XmlTestData.CharXml); Assert.IsNotNil(Data); Data.Save(File); Data := XmlDocument.FromFile(File); Assert.IsNotNil(Data); Assert.IsNotNil(Data.DocumentType); Assert.AreEqual(Data.DocumentType.PublicId, "-//W3C//DTD XHTML 1.0 Transitional//EN"); Assert.AreEqual(Data.DocumentType.SystemId, "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"); Assert.IsNotNil(Data["Book"]); Data := XmlDocument.CreateDocument; Data.AddChild(Data.CreateElement("items")); Data.DocumentElement.AddChild(Data.CreateElement("item")); Data.DocumentElement.AddChild(Data.CreateElement("item")); Data.DocumentElement.AddChild(Data.CreateElement("item")); Data.Save(File, new XmlDocumentDeclaration("1.0", "UTF-8", true)); Data := XmlDocument.FromFile(File); Assert.IsNotNil(Data); Assert.IsNil(Data.DocumentType); Assert.IsNotNil(Data.DocumentElement); Assert.AreEqual(Data.DocumentElement.LocalName, "items"); Assert.AreEqual(Data.DocumentElement.ChildCount, 3); finally File.Delete; end; end; end.
inherited dmOrdsAbastecimento: TdmOrdsAbastecimento OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWABSTORD' ' (FIL_ORIGEM, NRO_ABASTECIMENTO, PTO_ABASTECIMENTO, EMISSAO, BA' + 'IXA, VEICULO, MOTORISTA, COMBUSTIVEL, KM_INICIAL, KM_FINAL, BMB_' + 'INICIAL, BMB_FINAL, LITRAGEM, VLR_UNITARIO, VLR_TOTAL, LIBERADO_' + 'POR, FRENTISTA, IMPRESSA, N_FISCAL, DT_ALTERACAO, OPERADOR)' 'VALUES' ' (:FIL_ORIGEM, :NRO_ABASTECIMENTO, :PTO_ABASTECIMENTO, :EMISSAO' + ', :BAIXA, :VEICULO, :MOTORISTA, :COMBUSTIVEL, :KM_INICIAL, :KM_F' + 'INAL, :BMB_INICIAL, :BMB_FINAL, :LITRAGEM, :VLR_UNITARIO, :VLR_T' + 'OTAL, :LIBERADO_POR, :FRENTISTA, :IMPRESSA, :N_FISCAL, :DT_ALTER' + 'ACAO, :OPERADOR)') SQLDelete.Strings = ( 'DELETE FROM STWABSTORD' 'WHERE' ' FIL_ORIGEM = :Old_FIL_ORIGEM AND NRO_ABASTECIMENTO = :Old_NRO_' + 'ABASTECIMENTO') SQLUpdate.Strings = ( 'UPDATE STWABSTORD' 'SET' ' FIL_ORIGEM = :FIL_ORIGEM, NRO_ABASTECIMENTO = :NRO_ABASTECIMEN' + 'TO, PTO_ABASTECIMENTO = :PTO_ABASTECIMENTO, EMISSAO = :EMISSAO, ' + 'BAIXA = :BAIXA, VEICULO = :VEICULO, MOTORISTA = :MOTORISTA, COMB' + 'USTIVEL = :COMBUSTIVEL, KM_INICIAL = :KM_INICIAL, KM_FINAL = :KM' + '_FINAL, BMB_INICIAL = :BMB_INICIAL, BMB_FINAL = :BMB_FINAL, LITR' + 'AGEM = :LITRAGEM, VLR_UNITARIO = :VLR_UNITARIO, VLR_TOTAL = :VLR' + '_TOTAL, LIBERADO_POR = :LIBERADO_POR, FRENTISTA = :FRENTISTA, IM' + 'PRESSA = :IMPRESSA, N_FISCAL = :N_FISCAL, DT_ALTERACAO = :DT_ALT' + 'ERACAO, OPERADOR = :OPERADOR' 'WHERE' ' FIL_ORIGEM = :Old_FIL_ORIGEM AND NRO_ABASTECIMENTO = :Old_NRO_' + 'ABASTECIMENTO') SQLRefresh.Strings = ( 'SELECT FIL_ORIGEM, NRO_ABASTECIMENTO, PTO_ABASTECIMENTO, EMISSAO' + ', BAIXA, VEICULO, MOTORISTA, COMBUSTIVEL, KM_INICIAL, KM_FINAL, ' + 'BMB_INICIAL, BMB_FINAL, LITRAGEM, VLR_UNITARIO, VLR_TOTAL, LIBER' + 'ADO_POR, FRENTISTA, IMPRESSA, N_FISCAL, DT_ALTERACAO, OPERADOR F' + 'ROM STWABSTORD' 'WHERE' ' FIL_ORIGEM = :Old_FIL_ORIGEM AND NRO_ABASTECIMENTO = :Old_NRO_' + 'ABASTECIMENTO') SQLLock.Strings = ( 'SELECT NULL FROM STWABSTORD' 'WHERE' 'FIL_ORIGEM = :Old_FIL_ORIGEM AND NRO_ABASTECIMENTO = :Old_NRO_AB' + 'ASTECIMENTO' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT ORD.FIL_ORIGEM, ' ' ORD.NRO_ABASTECIMENTO, ' ' ORD.PTO_ABASTECIMENTO, ' ' ORD.EMISSAO, ' ' ORD.BAIXA, ' ' ORD.VEICULO, ' ' ORD.MOTORISTA, ' ' ORD.COMBUSTIVEL, ' ' ORD.KM_INICIAL, ' ' ORD.KM_FINAL, ' ' ORD.BMB_INICIAL, ' ' ORD.BMB_FINAL, ' ' ORD.LITRAGEM, ' ' ORD.VLR_UNITARIO, ' ' ORD.VLR_TOTAL, ' ' ORD.LIBERADO_POR, ' ' ORD.FRENTISTA, ' ' ORD.IMPRESSA, ' ' ORD.N_FISCAL, ' ' ORD.DT_ALTERACAO, ' ' ORD.OPERADOR,' ' VEI.PLACA PLC_VEICULO,' ' VEI.MARCA MRC_VEICULO,' ' VEI.MODELO MOD_VEICULO,' ' IIF(VAR.CGC = VEI.CGC_PRO, '#39'PRP'#39','#39'TRC'#39') SITUACAO,' ' TPV.DESCRICAO DESC_VEICULO,' ' MOT.NOME NM_MOTORISTA,' ' MOT.RG RG_MOTORISTA,' ' PTO.NOME NM_PTOABASTECIMENTO' '' 'FROM STWABSTORD ORD' 'LEFT JOIN STWOPETVEI VEI ON VEI.FROTA = ORD.VEICULO' 'LEFT JOIN STWOPETVAR VAR ON VAR.CGC = VEI.CGC_PRO AND VAR.FILIAL' + ' = ORD.FIL_ORIGEM' 'LEFT JOIN STWOPETTPVE TPV ON TPV.CODIGO = VEI.TIPO' 'LEFT JOIN STWOPETMOT MOT ON MOT.CPF = ORD.MOTORISTA' 'LEFT JOIN STWABSTPTO PTO ON PTO.CODIGO = ORD.PTO_ABASTECIMENTO') object qryManutencaoFIL_ORIGEM: TStringField FieldName = 'FIL_ORIGEM' Required = True Size = 3 end object qryManutencaoNRO_ABASTECIMENTO: TFloatField FieldName = 'NRO_ABASTECIMENTO' Required = True end object qryManutencaoPTO_ABASTECIMENTO: TStringField FieldName = 'PTO_ABASTECIMENTO' Size = 9 end object qryManutencaoEMISSAO: TDateTimeField FieldName = 'EMISSAO' end object qryManutencaoBAIXA: TDateTimeField FieldName = 'BAIXA' end object qryManutencaoVEICULO: TStringField FieldName = 'VEICULO' Size = 8 end object qryManutencaoMOTORISTA: TStringField FieldName = 'MOTORISTA' Size = 18 end object qryManutencaoCOMBUSTIVEL: TStringField FieldName = 'COMBUSTIVEL' Size = 1 end object qryManutencaoKM_INICIAL: TFloatField FieldName = 'KM_INICIAL' end object qryManutencaoKM_FINAL: TFloatField FieldName = 'KM_FINAL' end object qryManutencaoBMB_INICIAL: TFloatField FieldName = 'BMB_INICIAL' end object qryManutencaoBMB_FINAL: TFloatField FieldName = 'BMB_FINAL' end object qryManutencaoLITRAGEM: TFloatField FieldName = 'LITRAGEM' end object qryManutencaoVLR_UNITARIO: TFloatField FieldName = 'VLR_UNITARIO' end object qryManutencaoVLR_TOTAL: TFloatField FieldName = 'VLR_TOTAL' end object qryManutencaoLIBERADO_POR: TStringField FieldName = 'LIBERADO_POR' end object qryManutencaoFRENTISTA: TStringField FieldName = 'FRENTISTA' end object qryManutencaoIMPRESSA: TStringField FieldName = 'IMPRESSA' Size = 1 end object qryManutencaoN_FISCAL: TIntegerField FieldName = 'N_FISCAL' end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryManutencaoPLC_VEICULO: TStringField FieldName = 'PLC_VEICULO' ProviderFlags = [pfInWhere] Size = 8 end object qryManutencaoMRC_VEICULO: TStringField FieldName = 'MRC_VEICULO' ProviderFlags = [pfInWhere] Size = 15 end object qryManutencaoMOD_VEICULO: TStringField FieldName = 'MOD_VEICULO' ProviderFlags = [pfInWhere] Size = 15 end object qryManutencaoSITUACAO: TStringField FieldName = 'SITUACAO' ProviderFlags = [pfInWhere] FixedChar = True Size = 3 end object qryManutencaoDESC_VEICULO: TStringField FieldName = 'DESC_VEICULO' ProviderFlags = [pfInWhere] end object qryManutencaoNM_MOTORISTA: TStringField FieldName = 'NM_MOTORISTA' ProviderFlags = [pfInWhere] Size = 40 end object qryManutencaoRG_MOTORISTA: TStringField FieldName = 'RG_MOTORISTA' ProviderFlags = [pfInWhere] Size = 14 end object qryManutencaoNM_PTOABASTECIMENTO: TStringField FieldName = 'NM_PTOABASTECIMENTO' ProviderFlags = [pfInWhere] Size = 40 end end inherited qryLocalizacao: TIBCQuery SQL.Strings = ( 'SELECT ORD.FIL_ORIGEM, ' ' ORD.NRO_ABASTECIMENTO, ' ' ORD.PTO_ABASTECIMENTO, ' ' ORD.EMISSAO, ' ' ORD.BAIXA, ' ' ORD.VEICULO, ' ' ORD.MOTORISTA, ' ' ORD.COMBUSTIVEL, ' ' ORD.KM_INICIAL, ' ' ORD.KM_FINAL, ' ' ORD.BMB_INICIAL, ' ' ORD.BMB_FINAL, ' ' ORD.LITRAGEM, ' ' ORD.VLR_UNITARIO, ' ' ORD.VLR_TOTAL, ' ' ORD.LIBERADO_POR, ' ' ORD.FRENTISTA, ' ' ORD.IMPRESSA, ' ' ORD.N_FISCAL, ' ' ORD.DT_ALTERACAO, ' ' ORD.OPERADOR,' ' VEI.PLACA PLC_VEICULO,' ' VEI.MARCA MRC_VEICULO,' ' VEI.MODELO MOD_VEICULO,' ' IIF(VAR.CGC = VEI.CGC_PRO, '#39'PRP'#39','#39'TRC'#39') SITUACAO,' ' TPV.DESCRICAO DESC_VEICULO,' ' MOT.NOME NM_MOTORISTA,' ' MOT.RG RG_MOTORISTA,' ' PTO.NOME NM_PTOABASTECIMENTO' '' 'FROM STWABSTORD ORD' 'LEFT JOIN STWOPETVEI VEI ON VEI.FROTA = ORD.VEICULO' 'LEFT JOIN STWOPETVAR VAR ON VAR.CGC = VEI.CGC_PRO AND VAR.FILIAL' + ' = ORD.FIL_ORIGEM' 'LEFT JOIN STWOPETTPVE TPV ON TPV.CODIGO = VEI.TIPO' 'LEFT JOIN STWOPETMOT MOT ON MOT.CPF = ORD.MOTORISTA' 'LEFT JOIN STWABSTPTO PTO ON PTO.CODIGO = ORD.PTO_ABASTECIMENTO') object qryLocalizacaoFIL_ORIGEM: TStringField FieldName = 'FIL_ORIGEM' Required = True Size = 3 end object qryLocalizacaoNRO_ABASTECIMENTO: TFloatField FieldName = 'NRO_ABASTECIMENTO' Required = True end object qryLocalizacaoPTO_ABASTECIMENTO: TStringField FieldName = 'PTO_ABASTECIMENTO' Size = 9 end object qryLocalizacaoEMISSAO: TDateTimeField FieldName = 'EMISSAO' end object qryLocalizacaoBAIXA: TDateTimeField FieldName = 'BAIXA' end object qryLocalizacaoVEICULO: TStringField FieldName = 'VEICULO' Size = 8 end object qryLocalizacaoMOTORISTA: TStringField FieldName = 'MOTORISTA' Size = 18 end object qryLocalizacaoCOMBUSTIVEL: TStringField FieldName = 'COMBUSTIVEL' Size = 1 end object qryLocalizacaoKM_INICIAL: TFloatField FieldName = 'KM_INICIAL' end object qryLocalizacaoKM_FINAL: TFloatField FieldName = 'KM_FINAL' end object qryLocalizacaoBMB_INICIAL: TFloatField FieldName = 'BMB_INICIAL' end object qryLocalizacaoBMB_FINAL: TFloatField FieldName = 'BMB_FINAL' end object qryLocalizacaoLITRAGEM: TFloatField FieldName = 'LITRAGEM' end object qryLocalizacaoVLR_UNITARIO: TFloatField FieldName = 'VLR_UNITARIO' end object qryLocalizacaoVLR_TOTAL: TFloatField FieldName = 'VLR_TOTAL' end object qryLocalizacaoLIBERADO_POR: TStringField FieldName = 'LIBERADO_POR' end object qryLocalizacaoFRENTISTA: TStringField FieldName = 'FRENTISTA' end object qryLocalizacaoIMPRESSA: TStringField FieldName = 'IMPRESSA' Size = 1 end object qryLocalizacaoN_FISCAL: TIntegerField FieldName = 'N_FISCAL' end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryLocalizacaoPLC_VEICULO: TStringField FieldName = 'PLC_VEICULO' ReadOnly = True Size = 8 end object qryLocalizacaoMRC_VEICULO: TStringField FieldName = 'MRC_VEICULO' ReadOnly = True Size = 15 end object qryLocalizacaoMOD_VEICULO: TStringField FieldName = 'MOD_VEICULO' ReadOnly = True Size = 15 end object qryLocalizacaoSITUACAO: TStringField FieldName = 'SITUACAO' ReadOnly = True FixedChar = True Size = 3 end object qryLocalizacaoDESC_VEICULO: TStringField FieldName = 'DESC_VEICULO' ReadOnly = True end object qryLocalizacaoNM_MOTORISTA: TStringField FieldName = 'NM_MOTORISTA' ReadOnly = True Size = 40 end object qryLocalizacaoRG_MOTORISTA: TStringField FieldName = 'RG_MOTORISTA' ReadOnly = True Size = 14 end object qryLocalizacaoNM_PTOABASTECIMENTO: TStringField FieldName = 'NM_PTOABASTECIMENTO' ReadOnly = True Size = 40 end end end
unit eepromser; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} main_engine; const //tipos E93CXX=0; ER5911=1; X24c44=2; procedure eepromser_init(tipo,epr_bits:byte); procedure eepromser_reset; procedure eepromser_load_data(datos:pbyte;size:word); function er5911_do_read:byte; function er5911_ready_read:byte; procedure er5911_cs_write(epr_state:byte); procedure er5911_clk_write(epr_state:byte); procedure er5911_di_write(epr_state:byte); procedure er5911_parse_command_and_address; implementation const COMMAND_INVALID=0; COMMAND_READ=1; COMMAND_WRITE=2; COMMAND_ERASE=3; COMMAND_LOCK=4; COMMAND_UNLOCK=5; COMMAND_WRITEALL=6; COMMAND_ERASEALL=7; COMMAND_COPY_EEPROM_TO_RAM=8; COMMAND_COPY_RAM_TO_EEPROM=9; // states STATE_IN_RESET=0; STATE_WAIT_FOR_START_BIT=1; STATE_WAIT_FOR_COMMAND=2; STATE_READING_DATA=3; STATE_WAIT_FOR_DATA=4; STATE_WAIT_FOR_COMPLETION=5; // events EVENT_CS_RISING_EDGE=1 shl 0; EVENT_CS_FALLING_EDGE = 1 shl 1; EVENT_CLK_RISING_EDGE = 1 shl 2; EVENT_CLK_FALLING_EDGE = 1 shl 3; type t_parse_command_and_address=procedure; var state,cs_state,clk_state,di_state,bits_accum,command_address_bits:byte; shift_register,command_address_accum:dword; locked,streaming_enabled:boolean; command,data_bits,address_bits:byte; address:word; parse_command_and_address:t_parse_command_and_address; addrspace:array[0..$7ff] of byte; procedure eepromser_load_data(datos:pbyte;size:word); begin copymemory(@addrspace[0],datos,size); end; function eeprom_ready:boolean; begin eeprom_ready:=true; //implementar... end; //------------------------------------------------- // internal_read - read data at the given address //------------------------------------------------- function internal_read(direccion:word):word; begin if (data_bits=16) then internal_read:=(addrspace[direccion*2] shl 8)+addrspace[(direccion*2)+1] else internal_read:=addrspace[direccion]; end; //------------------------------------------------- // internal_write - write data at the given // address //------------------------------------------------- procedure internal_write(direccion,valor:word); begin if (data_bits=16) then begin addrspace[direccion*2]:=valor shr 8; addrspace[(direccion*2)]:=valor and $ff; end else addrspace[direccion]:=valor; end; //------------------------------------------------- // read - read data at the given address //------------------------------------------------- function read_(direccion:word):word; begin //if not(eeprom_ready) then logerror("EEPROM: Read performed before previous operation completed!"); read_:=internal_read(direccion); end; //------------------------------------------------- // write - write data at the given address //------------------------------------------------- procedure write_(direccion,valor:word); begin //if not(eeprom_ready) then logerror("EEPROM: Write performed before previous operation completed!"); internal_write(direccion,valor); //m_completion_time = machine().time() + m_operation_time[WRITE_TIME]; end; //------------------------------------------------- // write_all - write data at all addresses // (assumes an erase has previously been // performed) //------------------------------------------------- procedure write_all(valor:word); var f:word; begin //if not (eeprm_ready) then logerror("EEPROM: Write all performed before previous operation completed!"); for f:=0 to ((1 shl address_bits)-1) do internal_write(f,internal_read(f) and valor); //m_completion_time = machine().time() + m_operation_time[WRITE_ALL_TIME]; end; //------------------------------------------------- // erase - erase data at the given address //------------------------------------------------- procedure erase_(direccion:word); begin //if not(eeprom_ready) then logerror("EEPROM: Erase performed before previous operation completed!"); internal_write(direccion,$ffff); //m_completion_time = machine().time() + m_operation_time[ERASE_TIME]; end; //------------------------------------------------- // erase_all - erase data at all addresses //------------------------------------------------- procedure erase_all; var f:word; begin //if not(eeprom_ready) then logerror("EEPROM: Erase all performed before previous operation completed!"); for f:=0 to ((1 shl address_bits)-1) do internal_write(f,$ffff); //m_completion_time = machine().time() + m_operation_time[ERASE_ALL_TIME]; end; //------------------------------------------------- // set_state - update the state to a new one //------------------------------------------------- procedure set_state(newstate:byte); begin // switch to the new state state:=newstate; end; //------------------------------------------------- // execute_write_command - execute a write // command after receiving the data bits //------------------------------------------------- procedure execute_write_command; begin // each command advances differently case command of // reset the shift register and wait for enough data to be clocked through COMMAND_WRITE:begin if locked then begin set_state(STATE_IN_RESET); exit; end; write_(address,shift_register); set_state(STATE_WAIT_FOR_COMPLETION); end; // write the entire EEPROM with the same data; ERASEALL is required before so we // AND against the already-present data COMMAND_WRITEALL:begin if locked then begin set_state(STATE_IN_RESET); exit; end; write_all(shift_register); set_state(STATE_WAIT_FOR_COMPLETION); end; end; end; //------------------------------------------------- // execute_command - execute a command once we // have enough bits for one //------------------------------------------------- procedure execute_command; begin // parse into a generic command and reset the accumulator count parse_command_and_address; bits_accum:=0; // each command advances differently case (command) of // advance to the READING_DATA state; data is fetched after first CLK // reset the shift register to 0 to simulate the dummy 0 bit that happens prior // to the first clock COMMAND_READ:begin shift_register:=0; set_state(STATE_READING_DATA); end; // reset the shift register and wait for enough data to be clocked through COMMAND_WRITE,COMMAND_WRITEALL:begin shift_register:=0; set_state(STATE_WAIT_FOR_DATA); end; // erase the parsed address (unless locked) and wait for it to complete COMMAND_ERASE:begin if (locked) then begin set_state(STATE_IN_RESET); exit; end; erase_(address); set_state(STATE_WAIT_FOR_COMPLETION); end; // lock the chip; return to IN_RESET state COMMAND_LOCK:begin locked:=true; set_state(STATE_IN_RESET); end; // unlock the chip; return to IN_RESET state COMMAND_UNLOCK:begin locked:=false; set_state(STATE_IN_RESET); end; // erase the entire chip (unless locked) and wait for it to complete COMMAND_ERASEALL:begin if (locked) then begin set_state(STATE_IN_RESET); exit; end; erase_all(); set_state(STATE_WAIT_FOR_COMPLETION); end; end; end; //------------------------------------------------- // handle_event - handle an event via the state // machine //------------------------------------------------- procedure handle_event(event:byte); var bit_index:byte; begin // switch off the current state case state of // CS is not asserted; wait for a rising CS to move us forward, ignoring all clocks STATE_IN_RESET:begin if (event=EVENT_CS_RISING_EDGE) then set_state(STATE_WAIT_FOR_START_BIT); end; // CS is asserted; wait for rising clock with a 1 start bit; falling CS will reset us // note that because each bit is written independently, it is possible for us to receive // a false rising CLK edge at the exact same time as a rising CS edge; it appears we // should ignore these edges (makes sense really) STATE_WAIT_FOR_START_BIT:begin if ((event=EVENT_CLK_RISING_EDGE) and (di_state=ASSERT_LINE) and eeprom_ready) then begin //--> and machine().time() > m_last_cs_rising_edge_time) command_address_accum:=0; bits_accum:=0; set_state(STATE_WAIT_FOR_COMMAND); end else begin if (event=EVENT_CS_FALLING_EDGE) then set_state(STATE_IN_RESET); end; end; // CS is asserted; wait for a command to come through; falling CS will reset us STATE_WAIT_FOR_COMMAND:begin if (event=EVENT_CLK_RISING_EDGE) then begin // if we have enough bits for a command + address, check it out command_address_accum:=(command_address_accum shl 1) or di_state; bits_accum:=bits_accum+1; if (bits_accum=(2+command_address_bits)) then execute_command(); end else begin if (event=EVENT_CS_FALLING_EDGE) then set_state(STATE_IN_RESET); end; end; // CS is asserted; reading data, clock the shift register; falling CS will reset us STATE_READING_DATA:begin if (event=EVENT_CLK_RISING_EDGE) then begin bit_index:=bits_accum; bits_accum:=bits_accum+1; // wrapping the address on multi-read is required by pacslot(cave.c) if ((((bit_index mod data_bits))=0) and (bit_index=0) or streaming_enabled) then shift_register:=read_((address+bits_accum div data_bits) and ((1 shl address_bits)-1)) shl (32-data_bits) else shift_register:=(shift_register shl 1) or 1; end else begin if (event=EVENT_CS_FALLING_EDGE) then begin set_state(STATE_IN_RESET); {if (m_streaming_enabled) LOG1((" (%d cells read)\n", m_bits_accum / m_data_bits)); if (!m_streaming_enabled && m_bits_accum > m_data_bits + 1) LOG0(("EEPROM: Overclocked read by %d bits\n", m_bits_accum - m_data_bits)); else if (m_streaming_enabled && m_bits_accum > m_data_bits + 1 && m_bits_accum % m_data_bits > 2) LOG0(("EEPROM: Overclocked read by %d bits\n", m_bits_accum % m_data_bits)); else if (m_bits_accum < m_data_bits) LOG0(("EEPROM: CS deasserted in READING_DATA after %d bits\n", m_bits_accum));} end; end; end; // CS is asserted; waiting for data; clock data through until we accumulate enough; falling CS will reset us STATE_WAIT_FOR_DATA:begin if (event=EVENT_CLK_RISING_EDGE) then begin shift_register:=(shift_register shl 1) or di_state; bits_accum:=bits_accum+1; if (bits_accum=data_bits) then execute_write_command(); end else begin if (event=EVENT_CS_FALLING_EDGE) then begin set_state(STATE_IN_RESET); end; end; end; // CS is asserted; waiting for completion; watch for CS falling STATE_WAIT_FOR_COMPLETION:begin if (event=EVENT_CS_FALLING_EDGE) then set_state(STATE_IN_RESET); end; end; end; //------------------------------------------------- // base_do_read - read the state of the data // output (DO) line //------------------------------------------------- function base_do_read:byte; var res:byte; begin // in most states, the output is tristated, and generally connected to a pull up // to send back a 1 value; the only exception is if reading data and the current output // bit is a 0 if ((state=STATE_READING_DATA) and ((shift_register and $80000000)=0)) then res:=CLEAR_LINE else res:=ASSERT_LINE; base_do_read:=res; end; //------------------------------------------------- // base_ready_read - read the state of the // READY/BUSY line //------------------------------------------------- function base_ready_read:byte; var res:byte; begin // ready by default, except during long operations if eeprom_ready then res:=ASSERT_LINE else res:=CLEAR_LINE; base_ready_read:=res; end; //------------------------------------------------- // base_cs_write - set the state of the chip // select (CS) line //------------------------------------------------- procedure base_cs_write(epr_state:byte); begin // ignore if the state is not changing epr_state:=epr_state and 1; if (epr_state=cs_state) then exit; // set the new state cs_state:=epr_state; // remember the rising edge time so we don't process CLK signals at the same time // --> if (epr_state=ASSERT_LINE) then m_last_cs_rising_edge_time = machine().time(); if (cs_state=ASSERT_LINE) then handle_event(EVENT_CS_RISING_EDGE) else handle_event(EVENT_CS_FALLING_EDGE); end; //------------------------------------------------- // base_clk_write - set the state of the clock // (CLK) line //------------------------------------------------- procedure base_clk_write(epr_state:byte); begin // ignore if the state is not changing epr_state:=epr_state and 1; if (epr_state=clk_state) then exit; // set the new state clk_state:=epr_state; if (clk_state=ASSERT_LINE) then handle_event(EVENT_CLK_RISING_EDGE) else handle_event(EVENT_CLK_FALLING_EDGE); end; //------------------------------------------------- // base_di_write - set the state of the data input // (DI) line //------------------------------------------------- procedure base_di_write(epr_state:byte); begin //if ((epr_state<>0) and (epr_state<>1)) LOG0(("EEPROM: Unexpected data at input 0x%X treated as %d\n", state, state & 1)); di_state:=epr_state and 1; end; procedure eepromser_init(tipo,epr_bits:byte); function calc_address_bits(cells:byte):byte; var res:byte; begin cells:=cells-1; res:=0; while (cells<>0) do begin cells:=cells shr 1; res:=res+1; end; calc_address_bits:=res; end; begin case tipo of ER5911:begin parse_command_and_address:=er5911_parse_command_and_address; if epr_bits=8 then begin command_address_bits:=9; address_bits:=calc_address_bits(128); end else begin command_address_bits:=8; address_bits:=calc_address_bits(64); end; end; end; data_bits:=epr_bits; streaming_enabled:=false; end; procedure eepromser_reset; begin // reset the state set_state(STATE_IN_RESET); locked:=true; bits_accum:=0; command_address_accum:=0; command:=COMMAND_INVALID; address:=0; shift_register:=0; end; function er5911_do_read:byte; begin er5911_do_read:=base_do_read; end; function er5911_ready_read; begin er5911_ready_read:=base_ready_read; end; procedure er5911_cs_write(epr_state:byte); begin base_cs_write(epr_state); end; procedure er5911_clk_write(epr_state:byte); begin base_clk_write(epr_state); end; procedure er5911_di_write(epr_state:byte); begin base_di_write(epr_state); end; //------------------------------------------------- // parse_command_and_address - extract the // command and address from a bitstream //------------------------------------------------- procedure er5911_parse_command_and_address; begin // set the defaults command:=COMMAND_INVALID; address:=command_address_accum and ((1 shl command_address_bits)-1); // extract the command portion and handle it case (command_address_accum shr command_address_bits) of // opcode 0 needs two more bits to decode the operation 0:begin case (address shr (command_address_bits-2)) of 0:command:=COMMAND_LOCK; 1:command:=COMMAND_INVALID;// not on ER5911 2:command:=COMMAND_ERASEALL; 3:command:=COMMAND_UNLOCK; end; address:=0; end; 1:command:=COMMAND_WRITE; 2:command:=COMMAND_READ; 3:command:=COMMAND_WRITE; // WRITE instead of ERASE on ER5911 end; end; end.
{ Double Commander ------------------------------------------------------------------------- Unix implementation of one-way IPC between 2 processes Copyright (C) 2015 Alexander Koblov (alexx2000@mail.ru) Based on simpleipc.inc from Free Component Library. Copyright (c) 2005 by Michael Van Canneyt, member of the Free Pascal development team See the file COPYING.FPC.txt, included in this distribution, 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. } unit uPipeServer; {$mode objfpc}{$H+} interface uses Classes, SysUtils, SimpleIPC, BaseUnix; Type { TPipeServerComm } TPipeServerComm = Class(TIPCServerComm) Private FFileName: String; FStream: TFileStream; private procedure Handler(Sender: TObject); Public Constructor Create(AOWner : TSimpleIPCServer); override; Procedure StartServer; override; Procedure StopServer; override; Function PeekMessage(TimeOut : Integer) : Boolean; override; Procedure ReadMessage ; override; Function GetInstanceID : String;override; Property FileName : String Read FFileName; Property Stream : TFileStream Read FStream; end; implementation uses uPollThread; ResourceString SErrFailedToCreatePipe = 'Failed to create named pipe: %s'; SErrFailedToRemovePipe = 'Failed to remove named pipe: %s'; type TUnixIPCServer = class(TSimpleIPCServer); procedure TPipeServerComm.Handler(Sender: TObject); begin TThread.Synchronize(nil, @TUnixIPCServer(Owner).ReadMessage); end; constructor TPipeServerComm.Create(AOWner: TSimpleIPCServer); Var D : String; begin inherited Create(AOWner); FFileName:=Owner.ServerID; If Not Owner.Global then FFileName:=FFileName+'-'+IntToStr(fpGetPID); D:='/tmp/'; // Change to something better later FFileName:=D+FFileName; end; procedure TPipeServerComm.StartServer; const PrivateRights = S_IRUSR or S_IWUSR; GlobalRights = PrivateRights or S_IRGRP or S_IWGRP or S_IROTH or S_IWOTH; Rights : Array [Boolean] of Integer = (PrivateRights,GlobalRights); begin If not FileExists(FFileName) then If (fpmkFifo(FFileName,438)<>0) then DoError(SErrFailedToCreatePipe,[FFileName]); FStream:=TFileStream.Create(FFileName,fmOpenReadWrite+fmShareDenyNone,Rights[Owner.Global]); AddPoll(FStream.Handle, POLLIN, @Handler, False); end; procedure TPipeServerComm.StopServer; begin RemovePoll(FStream.Handle); FreeAndNil(FStream); if Not DeleteFile(FFileName) then DoError(SErrFailedtoRemovePipe,[FFileName]); end; function TPipeServerComm.PeekMessage(TimeOut: Integer): Boolean; Var FDS : TFDSet; begin fpfd_zero(FDS); fpfd_set(FStream.Handle,FDS); Result:=fpSelect(FStream.Handle+1,@FDS,Nil,Nil,TimeOut)>0; end; procedure TPipeServerComm.ReadMessage; var {$IF (FPC_FULLVERSION < 030001)} M : TStream; Count : Integer; {$ENDIF} Hdr : TMsgHeader; begin FStream.ReadBuffer(Hdr,SizeOf(Hdr)); {$IF (FPC_FULLVERSION >= 030001)} PushMessage(Hdr,FStream); {$ELSE} SetMsgType(Hdr.MsgType); Count:=Hdr.MsgLen; M:=MsgData; if count > 0 then begin M.Seek(0,soFrombeginning); M.CopyFrom(FStream,Count); end else M.Size := 0; {$ENDIF} end; function TPipeServerComm.GetInstanceID: String; begin Result:=IntToStr(fpGetPID); end; initialization DefaultIPCServerClass:= TPipeServerComm; end.
program project1; {$mode objfpc}{$H+} uses SysUtils, UnicodeData; function IsCharLetter(ch: widechar): boolean; begin Result:= (Ord(ch) < LOW_SURROGATE_BEGIN) and (GetProps(word(ch))^.Category <= UGC_OtherLetter); end; procedure t(ch: widechar); const bb: array[boolean] of string=('false', 'true'); begin writeln('IsCharLetter(0x', IntToHex(Ord(ch), 4), '): ', bb[IsCharLetter(ch)]); end; begin t(#$17e5); //wrong- khmer letter t(#$1784); //ok- khmer t(#$3377); //wrong- CJK t(#$06F7); //wrong- arabic letter end.
unit GX_eWarn; interface {$I GX_CondDefine.inc} uses Windows, SysUtils, Classes, Controls, Forms, Graphics, StdCtrls, GX_EditorExpert, GX_ConfigurationInfo, GX_BaseForm, GX_BaseExpert; type TWarnExpert = class(TEditorExpert) private public class function GetName: string; override; constructor Create; override; function GetDisplayName: string; override; procedure Execute(Sender: TObject); override; function GetHelpString: string; override; function HasConfigOptions: Boolean; override; end; type TWarnStatusEnum = (wseON, wseOFF, wseDEFAULT {$IFDEF GX_VER200_up}, wseERROR{$ENDIF}); type TfmConfigureWarning = class(TfmBaseForm) lb_Warn: TListBox; b_ON: TButton; b_OFF: TButton; b_Default: TButton; b_Cancel: TButton; ed_Filter: TEdit; l_Filter: TLabel; b_ERROR: TButton; procedure b_ONClick(Sender: TObject); procedure b_OFFClick(Sender: TObject); procedure b_DefaultClick(Sender: TObject); procedure b_ERRORClick(Sender: TObject); procedure ed_FilterKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ed_FilterChange(Sender: TObject); private FAvailable: TStringList; FStatus: TWarnStatusEnum; function GetMessage: string; function GetStatus: TWarnStatusEnum; procedure SelectBestItem; procedure InitWarnings; public class function Execute(_bmp: TBitmap; out _Message: string; out _Status: TWarnStatusEnum): Boolean; constructor Create(_Owner: TComponent); override; destructor Destroy; override; end; implementation uses Messages, GX_OtaUtils, GX_dzVclUtils, GX_GenericUtils; {$R *.dfm} { TWarnExpert } constructor TWarnExpert.Create; begin inherited Create; end; function WarnStatusToStr(_Status: TWarnStatusEnum): string; begin case _Status of {$IFDEF GX_VER200_up}wseERROR: Result := 'ERROR'; {$ENDIF} wseOFF: Result := 'OFF'; wseDEFAULT: Result := 'DEFAULT'; else // wseON: Result := 'ON'; end; end; procedure TWarnExpert.Execute(Sender: TObject); var InsertString: string; Msg: string; Status: TWarnStatusEnum; begin if not TfmConfigureWarning.Execute(GetBitmap, Msg, Status) then Exit; //==> InsertString := Format('{$WARN %s %s}', [Msg, WarnStatusToStr(Status)]); GxOtaInsertLineIntoEditor(InsertString); end; function TWarnExpert.GetDisplayName: string; resourcestring SWarnExpertName = 'WARN Directive'; begin Result := SWarnExpertName; end; function TWarnExpert.GetHelpString: string; resourcestring SWarnExpertHelp = ' This expert inserts a {$WARN xxxx ON/OFF} directive into the source code'; begin Result := SWarnExpertHelp; end; class function TWarnExpert.GetName: string; begin Result := 'Warn'; end; function TWarnExpert.HasConfigOptions: Boolean; begin Result := False; end; { TfmConfigureWarning } class function TfmConfigureWarning.Execute(_bmp: TBitmap; out _Message: string; out _Status: TWarnStatusEnum): Boolean; var frm: TfmConfigureWarning; begin frm := TfmConfigureWarning.Create(Application); try ConvertBitmapToIcon(_bmp, frm.Icon); Result := frm.ShowModal = mrOk; if Result then begin _Message := frm.GetMessage; _Status := frm.GetStatus; end; finally FreeAndNil(frm); end; end; {$IFDEF GX_VER240_up} // Delphi XE3 procedure TfmConfigureWarning.InitWarnings; begin FAvailable.Add('SYMBOL_DEPRECATED'); FAvailable.Add('SYMBOL_LIBRARY'); FAvailable.Add('SYMBOL_PLATFORM'); FAvailable.Add('SYMBOL_EXPERIMENTAL'); FAvailable.Add('UNIT_LIBRARY'); FAvailable.Add('UNIT_PLATFORM'); FAvailable.Add('UNIT_DEPRECATED'); FAvailable.Add('UNIT_EXPERIMENTAL'); FAvailable.Add('HRESULT_COMPAT'); FAvailable.Add('HIDING_MEMBER'); FAvailable.Add('HIDDEN_VIRTUAL'); FAvailable.Add('GARBAGE'); FAvailable.Add('BOUNDS_ERROR'); FAvailable.Add('ZERO_NIL_COMPAT'); FAvailable.Add('STRING_CONST_TRUNCED'); FAvailable.Add('FOR_LOOP_VAR_VARPAR'); FAvailable.Add('TYPED_CONST_VARPAR'); FAvailable.Add('ASG_TO_TYPED_CONST'); FAvailable.Add('CASE_LABEL_RANGE'); FAvailable.Add('FOR_VARIABLE'); FAvailable.Add('CONSTRUCTING_ABSTRACT'); FAvailable.Add('COMPARISON_FALSE'); FAvailable.Add('COMPARISON_TRUE'); FAvailable.Add('COMPARING_SIGNED_UNSIGNED'); FAvailable.Add('COMBINING_SIGNED_UNSIGNED'); FAvailable.Add('UNSUPPORTED_CONSTRUCT'); FAvailable.Add('FILE_OPEN'); FAvailable.Add('FILE_OPEN_UNITSRC'); FAvailable.Add('BAD_GLOBAL_SYMBOL'); FAvailable.Add('DUPLICATE_CTOR_DTOR'); FAvailable.Add('INVALID_DIRECTIVE'); FAvailable.Add('PACKAGE_NO_LINK'); FAvailable.Add('PACKAGED_THREADVAR'); FAvailable.Add('IMPLICIT_IMPORT'); FAvailable.Add('HPPEMIT_IGNORED'); FAvailable.Add('NO_RETVAL'); FAvailable.Add('USE_BEFORE_DEF'); FAvailable.Add('FOR_LOOP_VAR_UNDEF'); FAvailable.Add('UNIT_NAME_MISMATCH'); FAvailable.Add('NO_CFG_FILE_FOUND'); FAvailable.Add('IMPLICIT_VARIANTS'); FAvailable.Add('UNICODE_TO_LOCALE'); FAvailable.Add('LOCALE_TO_UNICODE'); FAvailable.Add('IMAGEBASE_MULTIPLE'); FAvailable.Add('SUSPICIOUS_TYPECAST'); FAvailable.Add('PRIVATE_PROPACCESSOR'); FAvailable.Add('UNSAFE_TYPE'); FAvailable.Add('UNSAFE_CODE'); FAvailable.Add('UNSAFE_CAST'); FAvailable.Add('OPTION_TRUNCATED'); FAvailable.Add('WIDECHAR_REDUCED'); FAvailable.Add('DUPLICATES_IGNORED'); FAvailable.Add('UNIT_INIT_SEQ'); FAvailable.Add('LOCAL_PINVOKE'); FAvailable.Add('MESSAGE_DIRECTIVE'); FAvailable.Add('TYPEINFO_IMPLICITLY_ADDED'); FAvailable.Add('RLINK_WARNING'); FAvailable.Add('IMPLICIT_STRING_CAST'); FAvailable.Add('IMPLICIT_STRING_CAST_LOSS'); FAvailable.Add('EXPLICIT_STRING_CAST'); FAvailable.Add('EXPLICIT_STRING_CAST_LOSS'); FAvailable.Add('CVT_WCHAR_TO_ACHAR'); FAvailable.Add('CVT_NARROWING_STRING_LOST'); FAvailable.Add('CVT_ACHAR_TO_WCHAR'); FAvailable.Add('CVT_WIDENING_STRING_LOST'); FAvailable.Add('NON_PORTABLE_TYPECAST'); FAvailable.Add('LOST_EXTENDED_PRECISION'); FAvailable.Add('LNKDFM_NOTFOUND'); FAvailable.Add('IMMUTABLE_STRINGS'); FAvailable.Add('MOBILE_DELPHI'); FAvailable.Add('UNSAFE_VOID_POINTER'); FAvailable.Add('XML_WHITESPACE_NOT_ALLOWED'); FAvailable.Add('XML_UNKNOWN_ENTITY'); FAvailable.Add('XML_INVALID_NAME_START'); FAvailable.Add('XML_INVALID_NAME'); FAvailable.Add('XML_EXPECTED_CHARACTER'); FAvailable.Add('XML_CREF_NO_RESOLVE'); FAvailable.Add('XML_NO_PARM'); FAvailable.Add('XML_NO_MATCHING_PARM'); end; {$ELSE} {$IFDEF GX_VER230_up} // Delphi XE2 procedure TfmConfigureWarning.InitWarnings; begin FAvailable.Add('SYMBOL_DEPRECATED'); FAvailable.Add('SYMBOL_LIBRARY'); FAvailable.Add('SYMBOL_PLATFORM'); FAvailable.Add('SYMBOL_EXPERIMENTAL'); FAvailable.Add('UNIT_LIBRARY'); FAvailable.Add('UNIT_PLATFORM'); FAvailable.Add('UNIT_DEPRECATED'); FAvailable.Add('UNIT_EXPERIMENTAL'); FAvailable.Add('HRESULT_COMPAT'); FAvailable.Add('HIDING_MEMBER'); FAvailable.Add('HIDDEN_VIRTUAL'); FAvailable.Add('GARBAGE'); FAvailable.Add('BOUNDS_ERROR'); FAvailable.Add('ZERO_NIL_COMPAT'); FAvailable.Add('STRING_CONST_TRUNCED'); FAvailable.Add('FOR_LOOP_VAR_VARPAR'); FAvailable.Add('TYPED_CONST_VARPAR'); FAvailable.Add('ASG_TO_TYPED_CONST'); FAvailable.Add('CASE_LABEL_RANGE'); FAvailable.Add('FOR_VARIABLE'); FAvailable.Add('CONSTRUCTING_ABSTRACT'); FAvailable.Add('COMPARISON_FALSE'); FAvailable.Add('COMPARISON_TRUE'); FAvailable.Add('COMPARING_SIGNED_UNSIGNED'); FAvailable.Add('COMBINING_SIGNED_UNSIGNED'); FAvailable.Add('UNSUPPORTED_CONSTRUCT'); FAvailable.Add('FILE_OPEN'); FAvailable.Add('FILE_OPEN_UNITSRC'); FAvailable.Add('BAD_GLOBAL_SYMBOL'); FAvailable.Add('DUPLICATE_CTOR_DTOR'); FAvailable.Add('INVALID_DIRECTIVE'); FAvailable.Add('PACKAGE_NO_LINK'); FAvailable.Add('PACKAGED_THREADVAR'); FAvailable.Add('IMPLICIT_IMPORT'); FAvailable.Add('HPPEMIT_IGNORED'); FAvailable.Add('NO_RETVAL'); FAvailable.Add('USE_BEFORE_DEF'); FAvailable.Add('FOR_LOOP_VAR_UNDEF'); FAvailable.Add('UNIT_NAME_MISMATCH'); FAvailable.Add('NO_CFG_FILE_FOUND'); FAvailable.Add('IMPLICIT_VARIANTS'); FAvailable.Add('UNICODE_TO_LOCALE'); FAvailable.Add('LOCALE_TO_UNICODE'); FAvailable.Add('IMAGEBASE_MULTIPLE'); FAvailable.Add('SUSPICIOUS_TYPECAST'); FAvailable.Add('PRIVATE_PROPACCESSOR'); FAvailable.Add('UNSAFE_TYPE'); FAvailable.Add('UNSAFE_CODE'); FAvailable.Add('UNSAFE_CAST'); FAvailable.Add('OPTION_TRUNCATED'); FAvailable.Add('WIDECHAR_REDUCED'); FAvailable.Add('DUPLICATES_IGNORED'); FAvailable.Add('UNIT_INIT_SEQ'); FAvailable.Add('LOCAL_PINVOKE'); FAvailable.Add('MESSAGE_DIRECTIVE'); FAvailable.Add('TYPEINFO_IMPLICITLY_ADDED'); FAvailable.Add('RLINK_WARNING'); FAvailable.Add('IMPLICIT_STRING_CAST'); FAvailable.Add('IMPLICIT_STRING_CAST_LOSS'); FAvailable.Add('EXPLICIT_STRING_CAST'); FAvailable.Add('EXPLICIT_STRING_CAST_LOSS'); FAvailable.Add('CVT_WCHAR_TO_ACHAR'); FAvailable.Add('CVT_NARROWING_STRING_LOST'); FAvailable.Add('CVT_ACHAR_TO_WCHAR'); FAvailable.Add('CVT_WIDENING_STRING_LOST'); FAvailable.Add('NON_PORTABLE_TYPECAST'); FAvailable.Add('LOST_EXTENDED_PRECISION'); FAvailable.Add('LNKDFM_NOTFOUND'); FAvailable.Add('XML_WHITESPACE_NOT_ALLOWED'); FAvailable.Add('XML_UNKNOWN_ENTITY'); FAvailable.Add('XML_INVALID_NAME_START'); FAvailable.Add('XML_INVALID_NAME'); FAvailable.Add('XML_EXPECTED_CHARACTER'); FAvailable.Add('XML_CREF_NO_RESOLVE'); FAvailable.Add('XML_NO_PARM'); FAvailable.Add('XML_NO_MATCHING_PARM'); end; {$ELSE} {$IFDEF GX_VER220_up} // Delphi XE procedure TfmConfigureWarning.InitWarnings; begin FAvailable.Add('SYMBOL_DEPRECATED'); FAvailable.Add('SYMBOL_LIBRARY'); FAvailable.Add('SYMBOL_PLATFORM'); FAvailable.Add('SYMBOL_EXPERIMENTAL'); FAvailable.Add('UNIT_LIBRARY'); FAvailable.Add('UNIT_PLATFORM'); FAvailable.Add('UNIT_DEPRECATED'); FAvailable.Add('UNIT_EXPERIMENTAL'); FAvailable.Add('HRESULT_COMPAT'); FAvailable.Add('HIDING_MEMBER'); FAvailable.Add('HIDDEN_VIRTUAL'); FAvailable.Add('GARBAGE'); FAvailable.Add('BOUNDS_ERROR'); FAvailable.Add('ZERO_NIL_COMPAT'); FAvailable.Add('STRING_CONST_TRUNCED'); FAvailable.Add('FOR_LOOP_VAR_VARPAR'); FAvailable.Add('TYPED_CONST_VARPAR'); FAvailable.Add('ASG_TO_TYPED_CONST'); FAvailable.Add('CASE_LABEL_RANGE'); FAvailable.Add('FOR_VARIABLE'); FAvailable.Add('CONSTRUCTING_ABSTRACT'); FAvailable.Add('COMPARISON_FALSE'); FAvailable.Add('COMPARISON_TRUE'); FAvailable.Add('COMPARING_SIGNED_UNSIGNED'); FAvailable.Add('COMBINING_SIGNED_UNSIGNED'); FAvailable.Add('UNSUPPORTED_CONSTRUCT'); FAvailable.Add('FILE_OPEN'); FAvailable.Add('FILE_OPEN_UNITSRC'); FAvailable.Add('BAD_GLOBAL_SYMBOL'); FAvailable.Add('DUPLICATE_CTOR_DTOR'); FAvailable.Add('INVALID_DIRECTIVE'); FAvailable.Add('PACKAGE_NO_LINK'); FAvailable.Add('PACKAGED_THREADVAR'); FAvailable.Add('IMPLICIT_IMPORT'); FAvailable.Add('HPPEMIT_IGNORED'); FAvailable.Add('NO_RETVAL'); FAvailable.Add('USE_BEFORE_DEF'); FAvailable.Add('FOR_LOOP_VAR_UNDEF'); FAvailable.Add('UNIT_NAME_MISMATCH'); FAvailable.Add('NO_CFG_FILE_FOUND'); FAvailable.Add('IMPLICIT_VARIANTS'); FAvailable.Add('UNICODE_TO_LOCALE'); FAvailable.Add('LOCALE_TO_UNICODE'); FAvailable.Add('IMAGEBASE_MULTIPLE'); FAvailable.Add('SUSPICIOUS_TYPECAST'); FAvailable.Add('PRIVATE_PROPACCESSOR'); FAvailable.Add('UNSAFE_TYPE'); FAvailable.Add('UNSAFE_CODE'); FAvailable.Add('UNSAFE_CAST'); FAvailable.Add('OPTION_TRUNCATED'); FAvailable.Add('WIDECHAR_REDUCED'); FAvailable.Add('DUPLICATES_IGNORED'); FAvailable.Add('UNIT_INIT_SEQ'); FAvailable.Add('LOCAL_PINVOKE'); FAvailable.Add('MESSAGE_DIRECTIVE'); FAvailable.Add('TYPEINFO_IMPLICITLY_ADDED'); FAvailable.Add('RLINK_WARNING'); FAvailable.Add('IMPLICIT_STRING_CAST'); FAvailable.Add('IMPLICIT_STRING_CAST_LOSS'); FAvailable.Add('EXPLICIT_STRING_CAST'); FAvailable.Add('EXPLICIT_STRING_CAST_LOSS'); FAvailable.Add('CVT_WCHAR_TO_ACHAR'); FAvailable.Add('CVT_NARROWING_STRING_LOST'); FAvailable.Add('CVT_ACHAR_TO_WCHAR'); FAvailable.Add('CVT_WIDENING_STRING_LOST'); FAvailable.Add('XML_WHITESPACE_NOT_ALLOWED'); FAvailable.Add('XML_UNKNOWN_ENTITY'); FAvailable.Add('XML_INVALID_NAME_START'); FAvailable.Add('XML_INVALID_NAME'); FAvailable.Add('XML_EXPECTED_CHARACTER'); FAvailable.Add('XML_CREF_NO_RESOLVE'); FAvailable.Add('XML_NO_PARM'); FAvailable.Add('XML_NO_MATCHING_PARM'); end; {$ELSE} {$IFDEF GX_VER210_up} // Delphi 2010 procedure TfmConfigureWarning.InitWarnings; begin FAvailable.Add('SYMBOL_DEPRECATED'); FAvailable.Add('SYMBOL_LIBRARY'); FAvailable.Add('SYMBOL_PLATFORM'); FAvailable.Add('SYMBOL_EXPERIMENTAL'); FAvailable.Add('UNIT_LIBRARY'); FAvailable.Add('UNIT_PLATFORM'); FAvailable.Add('UNIT_DEPRECATED'); FAvailable.Add('UNIT_EXPERIMENTAL'); FAvailable.Add('HRESULT_COMPAT'); FAvailable.Add('HIDING_MEMBER'); FAvailable.Add('HIDDEN_VIRTUAL'); FAvailable.Add('GARBAGE'); FAvailable.Add('BOUNDS_ERROR'); FAvailable.Add('ZERO_NIL_COMPAT'); FAvailable.Add('STRING_CONST_TRUNCED'); FAvailable.Add('FOR_LOOP_VAR_VARPAR'); FAvailable.Add('TYPED_CONST_VARPAR'); FAvailable.Add('ASG_TO_TYPED_CONST'); FAvailable.Add('CASE_LABEL_RANGE'); FAvailable.Add('FOR_VARIABLE'); FAvailable.Add('CONSTRUCTING_ABSTRACT'); FAvailable.Add('COMPARISON_FALSE'); FAvailable.Add('COMPARISON_TRUE'); FAvailable.Add('COMPARING_SIGNED_UNSIGNED'); FAvailable.Add('COMBINING_SIGNED_UNSIGNED'); FAvailable.Add('UNSUPPORTED_CONSTRUCT'); FAvailable.Add('FILE_OPEN'); FAvailable.Add('FILE_OPEN_UNITSRC'); FAvailable.Add('BAD_GLOBAL_SYMBOL'); FAvailable.Add('DUPLICATE_CTOR_DTOR'); FAvailable.Add('INVALID_DIRECTIVE'); FAvailable.Add('PACKAGE_NO_LINK'); FAvailable.Add('PACKAGED_THREADVAR'); FAvailable.Add('IMPLICIT_IMPORT'); FAvailable.Add('HPPEMIT_IGNORED'); FAvailable.Add('NO_RETVAL'); FAvailable.Add('USE_BEFORE_DEF'); FAvailable.Add('FOR_LOOP_VAR_UNDEF'); FAvailable.Add('UNIT_NAME_MISMATCH'); FAvailable.Add('NO_CFG_FILE_FOUND'); FAvailable.Add('IMPLICIT_VARIANTS'); FAvailable.Add('UNICODE_TO_LOCALE'); FAvailable.Add('LOCALE_TO_UNICODE'); FAvailable.Add('IMAGEBASE_MULTIPLE'); FAvailable.Add('SUSPICIOUS_TYPECAST'); FAvailable.Add('PRIVATE_PROPACCESSOR'); FAvailable.Add('UNSAFE_TYPE'); FAvailable.Add('UNSAFE_CODE'); FAvailable.Add('UNSAFE_CAST'); FAvailable.Add('OPTION_TRUNCATED'); FAvailable.Add('WIDECHAR_REDUCED'); FAvailable.Add('DUPLICATES_IGNORED'); FAvailable.Add('UNIT_INIT_SEQ'); FAvailable.Add('LOCAL_PINVOKE'); FAvailable.Add('MESSAGE_DIRECTIVE'); FAvailable.Add('TYPEINFO_IMPLICITLY_ADDED'); FAvailable.Add('RLINK_WARNING'); FAvailable.Add('IMPLICIT_STRING_CAST'); FAvailable.Add('IMPLICIT_STRING_CAST_LOSS'); FAvailable.Add('EXPLICIT_STRING_CAST'); FAvailable.Add('EXPLICIT_STRING_CAST_LOSS'); FAvailable.Add('CVT_WCHAR_TO_ACHAR'); FAvailable.Add('CVT_NARROWING_STRING_LOST'); FAvailable.Add('CVT_ACHAR_TO_WCHAR'); FAvailable.Add('CVT_WIDENING_STRING_LOST'); FAvailable.Add('XML_WHITESPACE_NOT_ALLOWED'); FAvailable.Add('XML_UNKNOWN_ENTITY'); FAvailable.Add('XML_INVALID_NAME_START'); FAvailable.Add('XML_INVALID_NAME'); FAvailable.Add('XML_EXPECTED_CHARACTER'); FAvailable.Add('XML_CREF_NO_RESOLVE'); FAvailable.Add('XML_NO_PARM'); FAvailable.Add('XML_NO_MATCHING_PARM'); end; {$ELSE} {$IFDEF GX_VER200_up} // Delphi 2009 procedure TfmConfigureWarning.InitWarnings; begin FAvailable.Add('SYMBOL_DEPRECATED'); FAvailable.Add('SYMBOL_LIBRARY'); FAvailable.Add('SYMBOL_PLATFORM'); FAvailable.Add('SYMBOL_EXPERIMENTAL'); FAvailable.Add('UNIT_LIBRARY'); FAvailable.Add('UNIT_PLATFORM'); FAvailable.Add('UNIT_DEPRECATED'); FAvailable.Add('UNIT_EXPERIMENTAL'); FAvailable.Add('HRESULT_COMPAT'); FAvailable.Add('HIDING_MEMBER'); FAvailable.Add('HIDDEN_VIRTUAL'); FAvailable.Add('GARBAGE'); FAvailable.Add('BOUNDS_ERROR'); FAvailable.Add('ZERO_NIL_COMPAT'); FAvailable.Add('STRING_CONST_TRUNCED'); FAvailable.Add('FOR_LOOP_VAR_VARPAR'); FAvailable.Add('TYPED_CONST_VARPAR'); FAvailable.Add('ASG_TO_TYPED_CONST'); FAvailable.Add('CASE_LABEL_RANGE'); FAvailable.Add('FOR_VARIABLE'); FAvailable.Add('CONSTRUCTING_ABSTRACT'); FAvailable.Add('COMPARISON_FALSE'); FAvailable.Add('COMPARISON_TRUE'); FAvailable.Add('COMPARING_SIGNED_UNSIGNED'); FAvailable.Add('COMBINING_SIGNED_UNSIGNED'); FAvailable.Add('UNSUPPORTED_CONSTRUCT'); FAvailable.Add('FILE_OPEN'); FAvailable.Add('FILE_OPEN_UNITSRC'); FAvailable.Add('BAD_GLOBAL_SYMBOL'); FAvailable.Add('DUPLICATE_CTOR_DTOR'); FAvailable.Add('INVALID_DIRECTIVE'); FAvailable.Add('PACKAGE_NO_LINK'); FAvailable.Add('PACKAGED_THREADVAR'); FAvailable.Add('IMPLICIT_IMPORT'); FAvailable.Add('HPPEMIT_IGNORED'); FAvailable.Add('NO_RETVAL'); FAvailable.Add('USE_BEFORE_DEF'); FAvailable.Add('FOR_LOOP_VAR_UNDEF'); FAvailable.Add('UNIT_NAME_MISMATCH'); FAvailable.Add('NO_CFG_FILE_FOUND'); FAvailable.Add('IMPLICIT_VARIANTS'); FAvailable.Add('UNICODE_TO_LOCALE'); FAvailable.Add('LOCALE_TO_UNICODE'); FAvailable.Add('IMAGEBASE_MULTIPLE'); FAvailable.Add('SUSPICIOUS_TYPECAST'); FAvailable.Add('PRIVATE_PROPACCESSOR'); FAvailable.Add('UNSAFE_TYPE'); FAvailable.Add('UNSAFE_CODE'); FAvailable.Add('UNSAFE_CAST'); FAvailable.Add('OPTION_TRUNCATED'); FAvailable.Add('WIDECHAR_REDUCED'); FAvailable.Add('DUPLICATES_IGNORED'); FAvailable.Add('UNIT_INIT_SEQ'); FAvailable.Add('LOCAL_PINVOKE'); FAvailable.Add('MESSAGE_DIRECTIVE'); FAvailable.Add('TYPEINFO_IMPLICITLY_ADDED'); FAvailable.Add('RLINK_WARNING'); FAvailable.Add('IMPLICIT_STRING_CAST'); FAvailable.Add('IMPLICIT_STRING_CAST_LOSS'); FAvailable.Add('EXPLICIT_STRING_CAST'); FAvailable.Add('EXPLICIT_STRING_CAST_LOSS'); FAvailable.Add('CVT_WCHAR_TO_ACHAR'); FAvailable.Add('CVT_NARROWING_STRING_LOST'); FAvailable.Add('CVT_ACHAR_TO_WCHAR'); FAvailable.Add('CVT_WIDENING_STRING_LOST'); FAvailable.Add('XML_WHITESPACE_NOT_ALLOWED'); FAvailable.Add('XML_UNKNOWN_ENTITY'); FAvailable.Add('XML_INVALID_NAME_START'); FAvailable.Add('XML_INVALID_NAME'); FAvailable.Add('XML_EXPECTED_CHARACTER'); FAvailable.Add('XML_CREF_NO_RESOLVE'); FAvailable.Add('XML_NO_PARM'); FAvailable.Add('XML_NO_MATCHING_PARM'); end; {$ELSE} {$IFDEF GX_VER185_up} // Delphi 2007 procedure TfmConfigureWarning.InitWarnings; begin FAvailable.Add('SYMBOL_DEPRECATED'); FAvailable.Add('SYMBOL_LIBRARY'); FAvailable.Add('SYMBOL_PLATFORM'); FAvailable.Add('SYMBOL_EXPERIMENTAL'); FAvailable.Add('UNIT_LIBRARY'); FAvailable.Add('UNIT_PLATFORM'); FAvailable.Add('UNIT_DEPRECATED'); FAvailable.Add('UNIT_EXPERIMENTAL'); FAvailable.Add('HRESULT_COMPAT'); FAvailable.Add('HIDING_MEMBER'); FAvailable.Add('HIDDEN_VIRTUAL'); FAvailable.Add('GARBAGE'); FAvailable.Add('BOUNDS_ERROR'); FAvailable.Add('ZERO_NIL_COMPAT'); FAvailable.Add('STRING_CONST_TRUNCED'); FAvailable.Add('FOR_LOOP_VAR_VARPAR'); FAvailable.Add('TYPED_CONST_VARPAR'); FAvailable.Add('ASG_TO_TYPED_CONST'); FAvailable.Add('CASE_LABEL_RANGE'); FAvailable.Add('FOR_VARIABLE'); FAvailable.Add('CONSTRUCTING_ABSTRACT'); FAvailable.Add('COMPARISON_FALSE'); FAvailable.Add('COMPARISON_TRUE'); FAvailable.Add('COMPARING_SIGNED_UNSIGNED'); FAvailable.Add('COMBINING_SIGNED_UNSIGNED'); FAvailable.Add('UNSUPPORTED_CONSTRUCT'); FAvailable.Add('FILE_OPEN'); FAvailable.Add('FILE_OPEN_UNITSRC'); FAvailable.Add('BAD_GLOBAL_SYMBOL'); FAvailable.Add('DUPLICATE_CTOR_DTOR'); FAvailable.Add('INVALID_DIRECTIVE'); FAvailable.Add('PACKAGE_NO_LINK'); FAvailable.Add('PACKAGED_THREADVAR'); FAvailable.Add('IMPLICIT_IMPORT'); FAvailable.Add('HPPEMIT_IGNORED'); FAvailable.Add('NO_RETVAL'); FAvailable.Add('USE_BEFORE_DEF'); FAvailable.Add('FOR_LOOP_VAR_UNDEF'); FAvailable.Add('UNIT_NAME_MISMATCH'); FAvailable.Add('NO_CFG_FILE_FOUND'); FAvailable.Add('IMPLICIT_VARIANTS'); FAvailable.Add('UNICODE_TO_LOCALE'); FAvailable.Add('LOCALE_TO_UNICODE'); FAvailable.Add('IMAGEBASE_MULTIPLE'); FAvailable.Add('SUSPICIOUS_TYPECAST'); FAvailable.Add('PRIVATE_PROPACCESSOR'); FAvailable.Add('UNSAFE_TYPE'); FAvailable.Add('UNSAFE_CODE'); FAvailable.Add('UNSAFE_CAST'); FAvailable.Add('OPTION_TRUNCATED'); FAvailable.Add('WIDECHAR_REDUCED'); FAvailable.Add('DUPLICATES_IGNORED'); FAvailable.Add('UNIT_INIT_SEQ'); FAvailable.Add('LOCAL_PINVOKE'); FAvailable.Add('MESSAGE_DIRECTIVE'); FAvailable.Add('TYPEINFO_IMPLICITLY_ADDED'); FAvailable.Add('XML_WHITESPACE_NOT_ALLOWED'); FAvailable.Add('XML_UNKNOWN_ENTITY'); FAvailable.Add('XML_INVALID_NAME_START'); FAvailable.Add('XML_INVALID_NAME'); FAvailable.Add('XML_EXPECTED_CHARACTER'); FAvailable.Add('XML_CREF_NO_RESOLVE'); FAvailable.Add('XML_NO_PARM'); FAvailable.Add('XML_NO_MATCHING_PARM'); end; {$ELSE} {$IFDEF GX_VER180_up} // Delphi 2006 procedure TfmConfigureWarning.InitWarnings; begin FAvailable.Add('SYMBOL_DEPRECATED'); FAvailable.Add('SYMBOL_LIBRARY'); FAvailable.Add('SYMBOL_PLATFORM'); FAvailable.Add('SYMBOL_EXPERIMENTAL'); FAvailable.Add('UNIT_LIBRARY'); FAvailable.Add('UNIT_PLATFORM'); FAvailable.Add('UNIT_DEPRECATED'); FAvailable.Add('UNIT_EXPERIMENTAL'); FAvailable.Add('HRESULT_COMPAT'); FAvailable.Add('HIDING_MEMBER'); FAvailable.Add('HIDDEN_VIRTUAL'); FAvailable.Add('GARBAGE'); FAvailable.Add('BOUNDS_ERROR'); FAvailable.Add('ZERO_NIL_COMPAT'); FAvailable.Add('STRING_CONST_TRUNCED'); FAvailable.Add('FOR_LOOP_VAR_VARPAR'); FAvailable.Add('TYPED_CONST_VARPAR'); FAvailable.Add('ASG_TO_TYPED_CONST'); FAvailable.Add('CASE_LABEL_RANGE'); FAvailable.Add('FOR_VARIABLE'); FAvailable.Add('CONSTRUCTING_ABSTRACT'); FAvailable.Add('COMPARISON_FALSE'); FAvailable.Add('COMPARISON_TRUE'); FAvailable.Add('COMPARING_SIGNED_UNSIGNED'); FAvailable.Add('COMBINING_SIGNED_UNSIGNED'); FAvailable.Add('UNSUPPORTED_CONSTRUCT'); FAvailable.Add('FILE_OPEN'); FAvailable.Add('FILE_OPEN_UNITSRC'); FAvailable.Add('BAD_GLOBAL_SYMBOL'); FAvailable.Add('DUPLICATE_CTOR_DTOR'); FAvailable.Add('INVALID_DIRECTIVE'); FAvailable.Add('PACKAGE_NO_LINK'); FAvailable.Add('PACKAGED_THREADVAR'); FAvailable.Add('IMPLICIT_IMPORT'); FAvailable.Add('HPPEMIT_IGNORED'); FAvailable.Add('NO_RETVAL'); FAvailable.Add('USE_BEFORE_DEF'); FAvailable.Add('FOR_LOOP_VAR_UNDEF'); FAvailable.Add('UNIT_NAME_MISMATCH'); FAvailable.Add('NO_CFG_FILE_FOUND'); FAvailable.Add('IMPLICIT_VARIANTS'); FAvailable.Add('UNICODE_TO_LOCALE'); FAvailable.Add('LOCALE_TO_UNICODE'); FAvailable.Add('IMAGEBASE_MULTIPLE'); FAvailable.Add('SUSPICIOUS_TYPECAST'); FAvailable.Add('PRIVATE_PROPACCESSOR'); FAvailable.Add('UNSAFE_TYPE'); FAvailable.Add('UNSAFE_CODE'); FAvailable.Add('UNSAFE_CAST'); FAvailable.Add('OPTION_TRUNCATED'); FAvailable.Add('WIDECHAR_REDUCED'); FAvailable.Add('DUPLICATES_IGNORED'); FAvailable.Add('UNIT_INIT_SEQ'); FAvailable.Add('LOCAL_PINVOKE'); FAvailable.Add('MESSAGE_DIRECTIVE'); end; {$ELSE} {$IFDEF GX_VER170_up} // Delphi 2005 procedure TfmConfigureWarning.InitWarnings; begin FAvailable.Add('SYMBOL_DEPRECATED'); FAvailable.Add('SYMBOL_LIBRARY'); FAvailable.Add('SYMBOL_PLATFORM'); FAvailable.Add('SYMBOL_EXPERIMENTAL'); FAvailable.Add('UNIT_LIBRARY'); FAvailable.Add('UNIT_PLATFORM'); FAvailable.Add('UNIT_DEPRECATED'); FAvailable.Add('UNIT_EXPERIMENTAL'); FAvailable.Add('HRESULT_COMPAT'); FAvailable.Add('HIDING_MEMBER'); FAvailable.Add('HIDDEN_VIRTUAL'); FAvailable.Add('GARBAGE'); FAvailable.Add('BOUNDS_ERROR'); FAvailable.Add('ZERO_NIL_COMPAT'); FAvailable.Add('STRING_CONST_TRUNCED'); FAvailable.Add('FOR_LOOP_VAR_VARPAR'); FAvailable.Add('TYPED_CONST_VARPAR'); FAvailable.Add('ASG_TO_TYPED_CONST'); FAvailable.Add('CASE_LABEL_RANGE'); FAvailable.Add('FOR_VARIABLE'); FAvailable.Add('CONSTRUCTING_ABSTRACT'); FAvailable.Add('COMPARISON_FALSE'); FAvailable.Add('COMPARISON_TRUE'); FAvailable.Add('COMPARING_SIGNED_UNSIGNED'); FAvailable.Add('COMBINING_SIGNED_UNSIGNED'); FAvailable.Add('UNSUPPORTED_CONSTRUCT'); FAvailable.Add('FILE_OPEN'); FAvailable.Add('FILE_OPEN_UNITSRC'); FAvailable.Add('BAD_GLOBAL_SYMBOL'); FAvailable.Add('DUPLICATE_CTOR_DTOR'); FAvailable.Add('INVALID_DIRECTIVE'); FAvailable.Add('PACKAGE_NO_LINK'); FAvailable.Add('PACKAGED_THREADVAR'); FAvailable.Add('IMPLICIT_IMPORT'); FAvailable.Add('HPPEMIT_IGNORED'); FAvailable.Add('NO_RETVAL'); FAvailable.Add('USE_BEFORE_DEF'); FAvailable.Add('FOR_LOOP_VAR_UNDEF'); FAvailable.Add('UNIT_NAME_MISMATCH'); FAvailable.Add('NO_CFG_FILE_FOUND'); FAvailable.Add('IMPLICIT_VARIANTS'); FAvailable.Add('UNICODE_TO_LOCALE'); FAvailable.Add('LOCALE_TO_UNICODE'); FAvailable.Add('IMAGEBASE_MULTIPLE'); FAvailable.Add('SUSPICIOUS_TYPECAST'); FAvailable.Add('PRIVATE_PROPACCESSOR'); FAvailable.Add('UNSAFE_TYPE'); FAvailable.Add('UNSAFE_CODE'); FAvailable.Add('UNSAFE_CAST'); FAvailable.Add('OPTION_TRUNCATED'); FAvailable.Add('WIDECHAR_REDUCED'); FAvailable.Add('DUPLICATES_IGNORED'); FAvailable.Add('MESSAGE_DIRECTIVE'); end; {$ELSE} {$IFDEF GX_VER150_up} // Delphi 7 procedure TfmConfigureWarning.InitWarnings; begin FAvailable.Add('SYMBOL_DEPRECATED'); FAvailable.Add('SYMBOL_LIBRARY'); FAvailable.Add('SYMBOL_PLATFORM'); FAvailable.Add('UNIT_LIBRARY'); FAvailable.Add('UNIT_PLATFORM'); FAvailable.Add('UNIT_DEPRECATED'); FAvailable.Add('HRESULT_COMPAT'); FAvailable.Add('HIDING_MEMBER'); FAvailable.Add('HIDDEN_VIRTUAL'); FAvailable.Add('GARBAGE'); FAvailable.Add('BOUNDS_ERROR'); FAvailable.Add('ZERO_NIL_COMPAT'); FAvailable.Add('STRING_CONST_TRUNCED'); FAvailable.Add('FOR_LOOP_VAR_VARPAR'); FAvailable.Add('TYPED_CONST_VARPAR'); FAvailable.Add('ASG_TO_TYPED_CONST'); FAvailable.Add('CASE_LABEL_RANGE'); FAvailable.Add('FOR_VARIABLE'); FAvailable.Add('CONSTRUCTING_ABSTRACT'); FAvailable.Add('COMPARISON_FALSE'); FAvailable.Add('COMPARISON_TRUE'); FAvailable.Add('COMPARING_SIGNED_UNSIGNED'); FAvailable.Add('COMBINING_SIGNED_UNSIGNED'); FAvailable.Add('UNSUPPORTED_CONSTRUCT'); FAvailable.Add('FILE_OPEN'); FAvailable.Add('FILE_OPEN_UNITSRC'); FAvailable.Add('BAD_GLOBAL_SYMBOL'); FAvailable.Add('DUPLICATE_CTOR_DTOR'); FAvailable.Add('INVALID_DIRECTIVE'); FAvailable.Add('PACKAGE_NO_LINK'); FAvailable.Add('PACKAGED_THREADVAR'); FAvailable.Add('IMPLICIT_IMPORT'); FAvailable.Add('HPPEMIT_IGNORED'); FAvailable.Add('NO_RETVAL'); FAvailable.Add('USE_BEFORE_DEF'); FAvailable.Add('FOR_LOOP_VAR_UNDEF'); FAvailable.Add('UNIT_NAME_MISMATCH'); FAvailable.Add('NO_CFG_FILE_FOUND'); FAvailable.Add('IMPLICIT_VARIANTS'); FAvailable.Add('UNICODE_TO_LOCALE'); FAvailable.Add('LOCALE_TO_UNICODE'); FAvailable.Add('IMAGEBASE_MULTIPLE'); FAvailable.Add('SUSPICIOUS_TYPECAST'); FAvailable.Add('PRIVATE_PROPACCESSOR'); FAvailable.Add('UNSAFE_TYPE'); FAvailable.Add('UNSAFE_CODE'); FAvailable.Add('UNSAFE_CAST'); FAvailable.Add('MESSAGE_DIRECTIVE'); end; {$ELSE} {$IFDEF GX_VER140_up} // Delphi 6 procedure TfmConfigureWarning.InitWarnings; begin FAvailable.Add('SYMBOL_DEPRECATED'); FAvailable.Add('SYMBOL_LIBRARY'); FAvailable.Add('SYMBOL_PLATFORM'); FAvailable.Add('UNIT_LIBRARY'); FAvailable.Add('UNIT_PLATFORM'); FAvailable.Add('UNIT_DEPRECATED'); end; {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} constructor TfmConfigureWarning.Create(_Owner: TComponent); begin inherited; {$IFNDEF GX_VER200_up} b_ERROR.Visible := False; {$ENDIF} TControl_SetMinConstraints(Self); FAvailable := TStringList.Create; InitWarnings; lb_Warn.Items.Assign(FAvailable); end; destructor TfmConfigureWarning.Destroy; begin FreeAndNil(FAvailable); inherited; end; function TfmConfigureWarning.GetMessage: string; begin if not TListBox_GetSelected(lb_Warn, Result) then Result := ''; end; function TfmConfigureWarning.GetStatus: TWarnStatusEnum; begin Result := FStatus; end; procedure TfmConfigureWarning.SelectBestItem; var Filter: string; MatchIndex: Integer; begin if lb_Warn.Items.Count > 0 then begin Filter := Trim(ed_Filter.Text); MatchIndex := lb_Warn.Items.IndexOf(Filter); if MatchIndex = -1 then MatchIndex := 0; lb_Warn.ItemIndex := MatchIndex; end; end; procedure TfmConfigureWarning.ed_FilterChange(Sender: TObject); var Filter: string; begin Filter := Trim(ed_Filter.Text); FilterStringList(FAvailable, lb_Warn.Items, Filter, False); SelectBestItem; end; procedure TfmConfigureWarning.ed_FilterKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key in [VK_DOWN, VK_UP, VK_NEXT, VK_PRIOR]) then begin lb_Warn.Perform(WM_KEYDOWN, Key, 0); Key := 0; end; end; procedure TfmConfigureWarning.b_DefaultClick(Sender: TObject); begin FStatus := wseDEFAULT; end; procedure TfmConfigureWarning.b_ERRORClick(Sender: TObject); begin {$IFDEF GX_VER200_up}FStatus := wseERROR; {$ENDIF} end; procedure TfmConfigureWarning.b_OFFClick(Sender: TObject); begin FStatus := wseOFF; end; procedure TfmConfigureWarning.b_ONClick(Sender: TObject); begin FStatus := wseON; end; initialization RegisterEditorExpert(TWarnExpert); end.
// Copyright (c) 2017 Embarcadero Technologies, Inc. All rights reserved. // // This software is the copyrighted property of Embarcadero Technologies, Inc. // ("Embarcadero") and its licensors. You may only use this software if you // are an authorized licensee of Delphi, C++Builder or RAD Studio // (the "Embarcadero Products"). This software is subject to Embarcadero's // standard software license and support agreement that accompanied your // purchase of the Embarcadero Products and is considered a Redistributable, // as such term is defined thereunder. Your use of this software constitutes // your acknowledgement of your agreement to the foregoing software license // and support agreement. //--------------------------------------------------------------------------- unit CommonDataModule; interface uses System.SysUtils, System.Classes, 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.IB, FireDAC.Phys.IBDef, FireDAC.ConsoleUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Phys.IBBase, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.ScriptCommands, FireDAC.Stan.Util, FireDAC.Comp.Script; type TCommonDM = class(TDataModule) IBConnection: TFDConnection; FDPhysIBDriverLink: TFDPhysIBDriverLink; QuerySetupDatabase: TFDQuery; FDTransaction: TFDTransaction; FDScript: TFDScript; private { Private declarations } procedure SetupDataBase; function IsTablesExist: Boolean; function NeedRecreate: Boolean; procedure RunScript(const AScriptText: string; AWithTransaction: Boolean = True); procedure DropExisting; public { Public declarations } procedure CheckConnected; procedure CheckDatabase; end; function CommonDM: TCommonDM; implementation {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} uses SQLScripts; const RECREATE_NEEDED = False; var _CommonDM: TCommonDM; function CommonDM: TCommonDM; begin Result := _CommonDM; end; { TCommonDM } procedure TCommonDM.CheckConnected; begin IBConnection.Connected := True; end; procedure TCommonDM.CheckDatabase; begin if NeedRecreate then begin if IsTablesExist then DropExisting; SetupDataBase; end; end; procedure TCommonDM.DropExisting; begin RunScript(SCRIPT_CLEAR_DATA); end; procedure TCommonDM.SetupDataBase; begin RunScript(SCRIPT_CREATE_TABLE, False); RunScript(SCRIPT_INSERT_TENANTS); RunScript(SCRIPT_INSERT_ITEMS); end; function TCommonDM.IsTablesExist: Boolean; const SQL_CHECK_TABLE_EXISTS = 'SELECT True AS EXT FROM RDB$RELATIONS WHERE RDB$RELATION_NAME = %s'; begin if QuerySetupDatabase.Active then QuerySetupDatabase.Active := False; QuerySetupDatabase.SQL.Text := Format(SQL_CHECK_TABLE_EXISTS, [QuotedStr('STORE_ITEMS')]); QuerySetupDatabase.Open; Result := (QuerySetupDatabase.RecordCount > 0) and QuerySetupDatabase.Fields[0].AsBoolean; end; function TCommonDM.NeedRecreate: Boolean; begin Result := RECREATE_NEEDED or not IsTablesExist; end; procedure TCommonDM.RunScript(const AScriptText: string; AWithTransaction: Boolean = True); var Scripts: TFDSQLScripts; begin AWithTransaction := False; Scripts := TFDSQLScripts.Create(nil); try Scripts.Add.SQL.Text := AScriptText; FDScript.SQLScripts := Scripts; if AWithTransaction then FDTransaction.StartTransaction; try FDScript.ScriptOptions.CommandSeparator := '\'; FDScript.ValidateAll; FDScript.ExecuteAll; if AWithTransaction then FDTransaction.Commit; except if AWithTransaction then FDTransaction.Rollback; raise; end; finally Scripts.Free; end; end; procedure InitCommonDM; begin if not Assigned(_CommonDM) then begin _CommonDM := TCommonDM.Create(nil); _CommonDM.CheckConnected; _CommonDM.CheckDatabase; end; end; initialization InitCommonDM; finalization FreeAndNil(_CommonDM); end.
unit enet_protocol; (** @file protocol.c @brief ENet protocol functions 1.3.14 freepascal *) {$GOTO ON} interface uses enet_consts; procedure enet_host_flush (host : pENetHost); function enet_host_service (host : pENetHost; event : pENetEvent; timeout : enet_uint32):integer; function enet_protocol_check_timeouts (host : pENetHost; peer : pENetPeer; event : pENetEvent):integer; function enet_protocol_command_size (commandNumber : enet_uint8):enet_size_t; function enet_protocol_dispatch_incoming_commands (host : pENetHost;event : pENetEvent):integer; function enet_protocol_handle_acknowledge (host : pENetHost; event : pENetEvent; peer : pENetPeer; command : pENetProtocol):integer; function enet_protocol_handle_bandwidth_limit (host : pENetHost; peer : pENetPeer; command : pENetProtocol):integer; function enet_protocol_handle_connect (host : pENetHost;header : pENetProtocolHeader;command : pENetProtocol):pENetPeer; function enet_protocol_handle_disconnect (host : pENetHost; peer : pENetPeer; command : pENetProtocol):integer; function enet_protocol_handle_incoming_commands (host : pENetHost; event : pENetEvent):integer; function enet_protocol_handle_ping (host : pENetHost; peer : pENetPeer; command : pENetProtocol):integer; function enet_protocol_handle_send_fragment (host : pENetHost; peer : pENetPeer; command : pENetProtocol; currentData : ppenet_uint8):integer; function enet_protocol_handle_send_reliable (host : pENetHost; peer : pENetPeer; command : pENetProtocol; currentData : ppenet_uint8):integer; function enet_protocol_handle_send_unreliable (host : pENetHost; peer : pENetPeer;command : pENetProtocol;currentData : ppenet_uint8):integer; function enet_protocol_handle_send_unsequenced (host : pENetHost; peer : pENetPeer; command : pENetProtocol; currentData : ppenet_uint8):integer; function enet_protocol_handle_throttle_configure (host : pENetHost; peer : pENetPeer; command : pENetProtocol):integer; function enet_protocol_handle_verify_connect (host : pENetHost; event : pENetEvent; peer : pENetPeer; command : pENetProtocol):integer; procedure enet_protocol_notify_connect (host : pENetHost;peer : pENetPeer;event : pENetEvent); procedure enet_protocol_notify_disconnect (host : pENetHost;peer : pENetPeer;event : pENetEvent); function enet_protocol_receive_incoming_commands (host : pENetHost; event : pENetEvent):integer; function enet_protocol_remove_sent_reliable_command (peer : pENetPeer;reliableSequenceNumber : enet_uint16;channelID : enet_uint8):ENetProtocolCommand; procedure enet_protocol_remove_sent_unreliable_commands (peer : pENetPeer); procedure enet_protocol_send_acknowledgements (host : pENetHost; peer : pENetPeer); function enet_protocol_send_outgoing_commands (host : pENetHost; event : pENetEvent; checkForTimeouts : integer):integer; function enet_protocol_send_reliable_outgoing_commands (host : pENetHost; peer : pENetPeer):Integer; procedure enet_protocol_send_unreliable_outgoing_commands (host : pENetHost;peer : pENetPeer); function enet_host_check_events (host : pENetHost; event : pENetEvent):integer; procedure enet_protocol_change_state (host:pENetHost; peer:pENetPeer; state: (*ENetPeerState*)enet_uint32 ); procedure enet_protocol_dispatch_state (host:pENetHost; peer:pENetPeer; state: (*ENetPeerState*)enet_uint32); const commandSizes : array[0..(ENET_PROTOCOL_COMMAND_COUNT)-1] of enet_size_t = ( 0, sizeof (ENetProtocolAcknowledge), sizeof (ENetProtocolConnect), sizeof (ENetProtocolVerifyConnect), sizeof (ENetProtocolDisconnect), sizeof (ENetProtocolPing), sizeof (ENetProtocolSendReliable), sizeof (ENetProtocolSendUnreliable), sizeof (ENetProtocolSendFragment), sizeof (ENetProtocolSendUnsequenced), sizeof (ENetProtocolBandwidthLimit), sizeof (ENetProtocolThrottleConfigure), sizeof (ENetProtocolSendFragment) ); implementation uses enet_packet, enet_host, enet_callbacks, enet_list, enet_socket, enet_peer; function enet_protocol_command_size (commandNumber : enet_uint8):enet_size_t; begin result := commandSizes [commandNumber and ENET_PROTOCOL_COMMAND_MASK]; end; procedure enet_protocol_change_state (host:pENetHost; peer:pENetPeer; state: (*ENetPeerState*)enet_uint32); begin if ((state = ENET_PEER_STATE_CONNECTED) or (state = ENET_PEER_STATE_DISCONNECT_LATER)) then enet_peer_on_connect (peer) else enet_peer_on_disconnect (peer); peer ^. state := state; end; procedure enet_protocol_dispatch_state (host:pENetHost; peer:pENetPeer; state: (*ENetPeerState*)enet_uint32); begin enet_protocol_change_state (host, peer, state); if (peer ^. needsDispatch = 0) then begin enet_list_insert (enet_list_end (@ host ^. dispatchQueue), @ peer ^. dispatchList); peer ^. needsDispatch := 1; end; end; function enet_protocol_dispatch_incoming_commands (host : pENetHost;event : pENetEvent):integer; var peer : pENetPeer; begin while (not enet_list_empty (@ host ^. dispatchQueue)) do begin peer := pENetPeer ( enet_list_remove (enet_list_begin (@ host ^. dispatchQueue))); peer ^. needsDispatch := 0; case (peer ^. state) of ENET_PEER_STATE_CONNECTION_PENDING, ENET_PEER_STATE_CONNECTION_SUCCEEDED: begin enet_protocol_change_state (host, peer, ENET_PEER_STATE_CONNECTED); event ^. EventType := ENET_EVENT_TYPE_CONNECT; event ^. peer := peer; event ^. data := peer ^. eventData; Result:=1; exit; end; ENET_PEER_STATE_ZOMBIE: begin host ^. recalculateBandwidthLimits := 1; event ^. EventType := ENET_EVENT_TYPE_DISCONNECT; event ^. peer := peer; event ^. data := peer ^. eventData; enet_peer_reset (peer); Result:=1; exit; end; ENET_PEER_STATE_CONNECTED: begin if (enet_list_empty (@ peer ^. dispatchedCommands)) then continue; event ^. packet := enet_peer_receive (peer, @ event ^. channelID); if (event ^. packet = nil) then continue; event ^. EventType := ENET_EVENT_TYPE_RECEIVE; event ^. peer := peer; if (not enet_list_empty (@ peer ^. dispatchedCommands)) then begin peer ^. needsDispatch := 1; enet_list_insert (enet_list_end (@ host ^. dispatchQueue), @ peer ^. dispatchList); end; Result:=1; exit; end; end; end; Result:=0; end; procedure enet_protocol_notify_connect (host : pENetHost;peer : pENetPeer;event : pENetEvent); var state : Integer; begin host ^. recalculateBandwidthLimits := 1; if (event <> nil) then begin enet_protocol_change_state (host, peer, ENET_PEER_STATE_CONNECTED); event ^. EventType := ENET_EVENT_TYPE_CONNECT; event ^. peer := peer; event ^. data := peer ^. eventData; end else begin if peer ^. state = ENET_PEER_STATE_CONNECTING then state := ENET_PEER_STATE_CONNECTION_SUCCEEDED else state := ENET_PEER_STATE_CONNECTION_PENDING; enet_protocol_dispatch_state (host, peer, state); end; end; procedure enet_protocol_notify_disconnect (host : pENetHost;peer : pENetPeer;event : pENetEvent); begin if (peer ^. state >= ENET_PEER_STATE_CONNECTION_PENDING) then host ^. recalculateBandwidthLimits := 1; if (peer ^. state <> ENET_PEER_STATE_CONNECTING) and (peer ^. state < ENET_PEER_STATE_CONNECTION_SUCCEEDED) then enet_peer_reset (peer) else if (event <> nil) then begin event ^. EventType := ENET_EVENT_TYPE_DISCONNECT; event ^. peer := peer; event ^. data := 0; enet_peer_reset (peer); end else begin peer ^. eventData := 0; enet_protocol_dispatch_state (host, peer, ENET_PEER_STATE_ZOMBIE); end; end; procedure enet_protocol_remove_sent_unreliable_commands (peer : pENetPeer); var outgoingCommand : pENetOutgoingCommand; begin if (enet_list_empty (@ peer ^. sentUnreliableCommands)) then exit; repeat outgoingCommand := pENetOutgoingCommand(enet_list_front (@ peer ^. sentUnreliableCommands)); enet_list_remove (@ outgoingCommand ^. outgoingCommandList); if (outgoingCommand ^. packet <> nil) then begin Dec(outgoingCommand ^. packet ^. referenceCount); if (outgoingCommand ^. packet ^. referenceCount = 0) then begin outgoingCommand ^. packet ^. flags := outgoingCommand ^. packet ^. flags or ENET_PACKET_FLAG_SENT; enet_packet_destroy (outgoingCommand ^. packet); end; end; enet_free (outgoingCommand); until (enet_list_empty (@ peer ^. sentUnreliableCommands)); if ((peer ^. state = ENET_PEER_STATE_DISCONNECT_LATER) and enet_list_empty (@ peer ^. outgoingReliableCommands) and enet_list_empty (@ peer ^. outgoingUnreliableCommands) and enet_list_empty (@ peer ^. sentReliableCommands)) then enet_peer_disconnect (peer, peer ^. eventData); end; function enet_protocol_remove_sent_reliable_command (peer : pENetPeer;reliableSequenceNumber : enet_uint16;channelID : enet_uint8):ENetProtocolCommand; var outgoingCommand : pENetOutgoingCommand; currentCommand : ENetListIterator; commandNumber : ENetProtocolCommand; channel : pENetChannel; reliableWindow : enet_uint16; wasSent : Integer; begin outgoingCommand:=nil; wasSent:=1; currentCommand := enet_list_begin (@ peer ^. sentReliableCommands); while PChar(currentCommand)<>PChar(enet_list_end (@ peer ^. sentReliableCommands)) do begin outgoingCommand := pENetOutgoingCommand (currentCommand); if (outgoingCommand ^. reliableSequenceNumber = reliableSequenceNumber) and (outgoingCommand ^. command.header.channelID = channelID) then break; currentCommand := enet_list_next (currentCommand); end; if PChar(currentCommand)=PChar(enet_list_end (@ peer ^. sentReliableCommands)) then begin currentCommand := enet_list_begin (@ peer ^. outgoingReliableCommands); while PChar(currentCommand)<>PChar(enet_list_end (@ peer ^. outgoingReliableCommands)) do begin outgoingCommand := pENetOutgoingCommand (currentCommand); if (outgoingCommand ^. sendAttempts < 1) then begin result := ENET_PROTOCOL_COMMAND_NONE; exit; end; if (outgoingCommand ^. reliableSequenceNumber = reliableSequenceNumber) and (outgoingCommand ^. command.header.channelID = channelID) then break; currentCommand := enet_list_next (currentCommand); end; if PChar(currentCommand)=PChar(enet_list_end (@ peer ^. outgoingReliableCommands)) then begin result := ENET_PROTOCOL_COMMAND_NONE; exit; end; wasSent:=0; end; if (outgoingCommand = nil) then begin Result:= ENET_PROTOCOL_COMMAND_NONE; exit; end; if (channelID < peer ^. channelCount) then begin channel := @ (pENetChannelArray(peer ^. channels)^[channelID]); reliableWindow := reliableSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE; if (channel ^. reliableWindows [reliableWindow] > 0) then begin Dec( channel ^. reliableWindows [reliableWindow]); if (0 = channel ^. reliableWindows [reliableWindow]) then channel ^. usedReliableWindows := channel ^. usedReliableWindows and not(1 shl reliableWindow); end; end; commandNumber := ENetProtocolCommand(outgoingCommand ^. command.header.command and ENET_PROTOCOL_COMMAND_MASK); enet_list_remove (@ outgoingCommand ^. outgoingCommandList); if (outgoingCommand ^. packet <> nil) then begin if wasSent<>0 then Dec(peer ^. reliableDataInTransit , outgoingCommand ^. fragmentLength); Dec( outgoingCommand ^. packet ^. referenceCount); if (outgoingCommand ^. packet ^. referenceCount = 0) then begin outgoingCommand ^. packet ^. flags := outgoingCommand ^. packet ^. flags or ENET_PACKET_FLAG_SENT; enet_packet_destroy (outgoingCommand ^. packet); end; end; enet_free (outgoingCommand); if (enet_list_empty (@ peer ^. sentReliableCommands)) then begin result := commandNumber; exit; end; outgoingCommand := pENetOutgoingCommand (enet_list_front (@ peer ^. sentReliableCommands)); peer ^. nextTimeout := outgoingCommand ^. sentTime + outgoingCommand ^. roundTripTimeout; result := commandNumber; end; function enet_protocol_handle_connect (host : pENetHost;header : pENetProtocolHeader;command : pENetProtocol):pENetPeer; var incomingSessionID, outgoingSessionID : enet_uint8; mtu, windowSize : enet_uint32; channel : pENetChannel; channelCount, duplicatePeers : enet_size_t; currentPeer, peer : pENetPeer; verifyCommand : ENetProtocol; begin duplicatePeers :=0; peer :=nil; channelCount := ENET_NET_TO_HOST_32 (command ^. connect.channelCount); if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT) or (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT) then begin result := nil; exit; end; currentPeer := host ^. peers; while PChar(currentPeer)< PChar(@(pENetPeerArray(host ^. peers)^[host ^. peerCount])) do begin if (currentPeer ^. state = ENET_PEER_STATE_DISCONNECTED) then begin if (peer = nil) then peer := currentPeer; end else if ((currentPeer ^. state <> ENET_PEER_STATE_CONNECTING) and (currentPeer ^. address.host = host ^. receivedAddress.host)) then begin if ((currentPeer ^. address.port = host ^. receivedAddress.port) and (currentPeer ^. connectID = command ^. connect.connectID)) then begin Result:=nil; exit; end; Inc(duplicatePeers); end; inc(currentPeer); end; if ((peer = nil) or (duplicatePeers >= host ^. duplicatePeers)) then begin result := nil; exit; end; if (channelCount > host ^. channelLimit) then channelCount := host ^. channelLimit; peer ^. channels := pENetChannel (enet_malloc (channelCount * sizeof (ENetChannel))); if (peer ^. channels = nil) then begin Result:=nil; exit; end; peer ^. channelCount := channelCount; peer ^. state := ENET_PEER_STATE_ACKNOWLEDGING_CONNECT; peer ^. connectID := command ^. connect.connectID; peer ^. address := host ^. receivedAddress; peer ^. outgoingPeerID := ENET_NET_TO_HOST_16 (command ^. connect.outgoingPeerID); peer ^. incomingBandwidth := ENET_NET_TO_HOST_32 (command ^. connect.incomingBandwidth); peer ^. outgoingBandwidth := ENET_NET_TO_HOST_32 (command ^. connect.outgoingBandwidth); peer ^. packetThrottleInterval := ENET_NET_TO_HOST_32 (command ^. connect.packetThrottleInterval); peer ^. packetThrottleAcceleration := ENET_NET_TO_HOST_32 (command ^. connect.packetThrottleAcceleration); peer ^. packetThrottleDeceleration := ENET_NET_TO_HOST_32 (command ^. connect.packetThrottleDeceleration); peer ^. eventData := ENET_NET_TO_HOST_32 (command ^. connect.data); if command ^. connect.incomingSessionID=$0ff then incomingSessionID:= Peer ^. outgoingSessionID else incomingSessionID:=command ^. connect.incomingSessionID; incomingSessionID := (incomingSessionID + 1) and (ENET_PROTOCOL_HEADER_SESSION_MASK shr ENET_PROTOCOL_HEADER_SESSION_SHIFT); if (incomingSessionID = Peer ^. outgoingSessionID) then incomingSessionID := (incomingSessionID + 1) and (ENET_PROTOCOL_HEADER_SESSION_MASK shr ENET_PROTOCOL_HEADER_SESSION_SHIFT); Peer ^. outgoingSessionID := incomingSessionID; if command ^. connect.outgoingSessionID=$0ff then outgoingSessionID:=Peer ^. incomingSessionID else outgoingSessionID:=command ^. connect.outgoingSessionID; outgoingSessionID := (outgoingSessionID + 1) and (ENET_PROTOCOL_HEADER_SESSION_MASK shr ENET_PROTOCOL_HEADER_SESSION_SHIFT); if (outgoingSessionID = Peer ^. incomingSessionID) then outgoingSessionID := (outgoingSessionID + 1) and (ENET_PROTOCOL_HEADER_SESSION_MASK shr ENET_PROTOCOL_HEADER_SESSION_SHIFT); Peer ^. incomingSessionID := outgoingSessionID; channel := Peer ^. channels; while PChar(channel)< PChar(@(pENetChannelArray(Peer ^. channels)^[channelCount])) do begin channel ^. outgoingReliableSequenceNumber := 0; channel ^. outgoingUnreliableSequenceNumber := 0; channel ^. incomingReliableSequenceNumber := 0; channel ^. incomingUnreliableSequenceNumber := 0; enet_list_clear (@ channel ^. incomingReliableCommands); enet_list_clear (@ channel ^. incomingUnreliableCommands); channel ^. usedReliableWindows := 0; FillChar(channel ^. reliableWindows, sizeof (channel ^. reliableWindows), 0); inc(channel); end; mtu := ENET_NET_TO_HOST_32 (command ^. connect.mtu); if (mtu < ENET_PROTOCOL_MINIMUM_MTU) then mtu := ENET_PROTOCOL_MINIMUM_MTU else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU) then mtu := ENET_PROTOCOL_MAXIMUM_MTU; Peer ^. mtu := mtu; if (host ^. outgoingBandwidth = 0) and (Peer ^. incomingBandwidth = 0) then Peer ^. windowSize := ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE else if (host ^. outgoingBandwidth = 0) or (Peer ^. incomingBandwidth = 0) then Peer ^. windowSize := (ENET_MAX (host ^. outgoingBandwidth, Peer ^. incomingBandwidth) div ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE else Peer ^. windowSize := (ENET_MIN (host ^. outgoingBandwidth, Peer ^. incomingBandwidth) div ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; if (Peer ^. windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) then Peer ^. windowSize := ENET_PROTOCOL_MINIMUM_WINDOW_SIZE else if (Peer ^. windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) then Peer ^. windowSize := ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; if (host ^. incomingBandwidth = 0) then windowSize := ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE else windowSize := (host ^. incomingBandwidth div ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; if (windowSize > ENET_NET_TO_HOST_32 (command ^. connect.windowSize)) then windowSize := ENET_NET_TO_HOST_32 (command ^. connect.windowSize); if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) then windowSize := ENET_PROTOCOL_MINIMUM_WINDOW_SIZE else if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) then windowSize := ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; verifyCommand.header.command := ENET_PROTOCOL_COMMAND_VERIFY_CONNECT or ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE; verifyCommand.header.channelID := $FF; verifyCommand.verifyConnect.outgoingPeerID := ENET_HOST_TO_NET_16 (Peer ^. incomingPeerID); verifyCommand.verifyConnect.incomingSessionID := incomingSessionID; verifyCommand.verifyConnect.outgoingSessionID := outgoingSessionID; verifyCommand.verifyConnect.mtu := ENET_HOST_TO_NET_32 (Peer ^. mtu); verifyCommand.verifyConnect.windowSize := ENET_HOST_TO_NET_32 (windowSize); verifyCommand.verifyConnect.channelCount := ENET_HOST_TO_NET_32 (channelCount); verifyCommand.verifyConnect.incomingBandwidth := ENET_HOST_TO_NET_32 (host ^. incomingBandwidth); verifyCommand.verifyConnect.outgoingBandwidth := ENET_HOST_TO_NET_32 (host ^. outgoingBandwidth); verifyCommand.verifyConnect.packetThrottleInterval := ENET_HOST_TO_NET_32 (Peer ^. packetThrottleInterval); verifyCommand.verifyConnect.packetThrottleAcceleration := ENET_HOST_TO_NET_32 (Peer ^. packetThrottleAcceleration); verifyCommand.verifyConnect.packetThrottleDeceleration := ENET_HOST_TO_NET_32 (Peer ^. packetThrottleDeceleration); verifyCommand.verifyConnect.connectID := Peer ^. connectID; enet_peer_queue_outgoing_command (Peer, @ verifyCommand, nil, 0, 0); result := Peer; end; function enet_protocol_handle_send_reliable (host : pENetHost; peer : pENetPeer; command : pENetProtocol; currentData : ppenet_uint8):integer; var dataLength : enet_size_t; begin if (command ^. header.channelID >= peer ^. channelCount) or ((peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER)) then begin result := -1; exit; end; dataLength := ENET_NET_TO_HOST_16 (command ^. sendReliable.dataLength); Inc(PChar(currentData^) , dataLength); if (dataLength > host ^. maximumPacketSize) or (currentData^ < host ^. receivedData) or (currentData^ > @ penet_uint8array(host ^. receivedData)[host ^. receivedDataLength]) then begin result := -1; exit; end; if (enet_peer_queue_incoming_command (peer, command, pchar(command) + sizeof (ENetProtocolSendReliable), dataLength, ENET_PACKET_FLAG_RELIABLE, 0) = nil) then begin result := -1; exit; end; result := 0; end; function enet_protocol_handle_send_unsequenced (host : pENetHost; peer : pENetPeer; command : pENetProtocol; currentData : ppenet_uint8):integer; var unsequencedGroup, index : enet_uint32; dataLength : enet_size_t; begin if (command ^. header.channelID >= peer ^. channelCount) or ((peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER)) then begin result := -1; exit; end; dataLength := ENET_NET_TO_HOST_16 (command ^. sendUnsequenced.dataLength); inc(PChar(currentData^) , dataLength); if (dataLength > host ^. maximumPacketSize) or (currentData^ < host ^. receivedData) or (currentData^ > @ penet_uint8array(host ^. receivedData)[host ^. receivedDataLength]) then begin result := -1; exit; end; unsequencedGroup := ENET_NET_TO_HOST_16 (command ^. sendUnsequenced.unsequencedGroup); index := unsequencedGroup mod ENET_PEER_UNSEQUENCED_WINDOW_SIZE; if (unsequencedGroup < peer ^. incomingUnsequencedGroup) then inc(unsequencedGroup , $10000); if (unsequencedGroup >= enet_uint32(peer ^. incomingUnsequencedGroup + ENET_PEER_FREE_UNSEQUENCED_WINDOWS * ENET_PEER_UNSEQUENCED_WINDOW_SIZE)) then begin result := 0; exit; end; unsequencedGroup := unsequencedGroup and $FFFF; if ((unsequencedGroup - index) <> peer ^. incomingUnsequencedGroup) then begin peer ^. incomingUnsequencedGroup := unsequencedGroup - index; FillChar (peer ^. unsequencedWindow, sizeof (peer ^. unsequencedWindow), 0); end else if 0<>(peer ^. unsequencedWindow [index div 32] and (1 shl (index mod 32))) then begin result := 0; exit; end; if (enet_peer_queue_incoming_command (peer, command, pchar(command) + sizeof (ENetProtocolSendUnsequenced), dataLength, ENET_PACKET_FLAG_UNSEQUENCED, 0) = nil) then begin result := -1; exit; end; peer ^. unsequencedWindow [index div 32] := peer ^. unsequencedWindow [index div 32] or enet_uint32(1 shl (index mod 32)); result := 0; end; function enet_protocol_handle_send_unreliable (host : pENetHost; peer : pENetPeer;command : pENetProtocol;currentData : ppenet_uint8):integer; var dataLength : enet_size_t; begin if (command ^. header.channelID >= peer ^. channelCount) or ((peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER)) then begin result := -1; exit; end; dataLength := ENET_NET_TO_HOST_16 (command ^. sendUnreliable.dataLength); inc(PChar(currentData^), dataLength); if (dataLength > host ^. maximumPacketSize) or (currentData^ < host ^. receivedData) or (currentData^ > @ penet_uint8array(host ^. receivedData)[host ^. receivedDataLength]) then begin result := -1; exit; end; if (enet_peer_queue_incoming_command (peer, command, pchar(command) + sizeof (ENetProtocolSendUnreliable), dataLength, 0, 0) = nil) then begin result:=-1; exit; end; result := 0; end; function enet_protocol_handle_send_fragment (host : pENetHost; peer : pENetPeer; command : pENetProtocol; currentData : ppenet_uint8):integer; var fragmentNumber , fragmentCount, fragmentOffset, fragmentLength, startSequenceNumber, totalLength : enet_uint32; channel : pENetChannel; startWindow, currentWindow : enet_uint16; currentCommand : ENetListIterator; startCommand : pENetIncomingCommand; packet : pENetPacket; hostCommand : ENetProtocol; incomingCommand : pENetIncomingCommand; label continuework1; begin startCommand := nil; if (command ^. header.channelID >= peer ^. channelCount) or ((peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER)) then begin result := -1; exit; end; fragmentLength := ENET_NET_TO_HOST_16 (command ^. sendFragment.dataLength); inc( currentData^ , fragmentLength); if (fragmentLength > host ^. maximumPacketSize) or (currentData^ < host ^. receivedData) or (currentData^ > @ penet_uint8array(host ^. receivedData)[host ^. receivedDataLength]) then begin result := -1; exit; end; channel := @ pENetChannelArray(peer ^. channels)^[command ^. header.channelID]; startSequenceNumber := ENET_NET_TO_HOST_16 (command ^. sendFragment.startSequenceNumber); startWindow := startSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE; currentWindow := channel ^. incomingReliableSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE; if (startSequenceNumber < channel ^. incomingReliableSequenceNumber) then inc(startWindow , ENET_PEER_RELIABLE_WINDOWS); if (startWindow < currentWindow) or (startWindow >= (currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)) then begin result := 0; exit; end; fragmentNumber := ENET_NET_TO_HOST_32 (command ^. sendFragment.fragmentNumber); fragmentCount := ENET_NET_TO_HOST_32 (command ^. sendFragment.fragmentCount); fragmentOffset := ENET_NET_TO_HOST_32 (command ^. sendFragment.fragmentOffset); totalLength := ENET_NET_TO_HOST_32 (command ^. sendFragment.totalLength); if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT) or (fragmentNumber >= fragmentCount) or (totalLength > host ^. maximumPacketSize) or (fragmentOffset >= totalLength) or (fragmentLength > totalLength - fragmentOffset) then begin result := -1; exit; end; currentCommand := enet_list_previous (enet_list_end (@channel ^. incomingReliableCommands)); while PChar(currentCommand) <> PChar(enet_list_end (@ channel ^. incomingReliableCommands)) do begin incomingCommand := pENetIncomingCommand(currentCommand); if (startSequenceNumber >= channel ^. incomingReliableSequenceNumber) then begin if (incomingCommand ^. reliableSequenceNumber < channel ^. incomingReliableSequenceNumber) then goto continuework1; end else if (incomingCommand ^. reliableSequenceNumber >= channel ^. incomingReliableSequenceNumber) then break; if (incomingCommand ^. reliableSequenceNumber <= startSequenceNumber) then begin if (incomingCommand ^. reliableSequenceNumber < startSequenceNumber) then break; if ((incomingCommand ^. command.header.command and ENET_PROTOCOL_COMMAND_MASK) <> ENET_PROTOCOL_COMMAND_SEND_FRAGMENT) or (totalLength <> incomingCommand ^. packet ^. dataLength) or (fragmentCount <> incomingCommand ^. fragmentCount) then begin result := -1; exit; end; startCommand := incomingCommand; break; end; continuework1: currentCommand := enet_list_previous (currentCommand); end; if (startCommand = nil) then begin hostCommand := command^; hostCommand.header.reliableSequenceNumber := startSequenceNumber; startCommand := enet_peer_queue_incoming_command (peer, @ hostCommand, nil, totalLength, ENET_PACKET_FLAG_RELIABLE, fragmentCount); if (startCommand = nil) then begin result := -1; exit; end; end; if enet_uint32(pIntegerArray(startCommand ^. fragments)^[fragmentNumber div 32]) and (1 shl (fragmentNumber mod 32)) = 0 then begin dec(startCommand ^. fragmentsRemaining); PIntegerArray(startCommand ^. fragments)^[fragmentNumber div 32] := PIntegerArray(startCommand ^. fragments)^[fragmentNumber div 32] or (1 shl (fragmentNumber mod 32)); if (fragmentOffset + fragmentLength > startCommand ^. packet ^. dataLength) then fragmentLength := startCommand ^. packet ^. dataLength - fragmentOffset; system.Move ((PChar(command) + sizeof (ENetProtocolSendFragment))^, (PChar(startCommand ^. packet ^. data) + fragmentOffset)^, fragmentLength); if (startCommand ^. fragmentsRemaining <= 0) then enet_peer_dispatch_incoming_reliable_commands (peer, channel); end; result := 0; end; function enet_protocol_handle_send_unreliable_fragment (host:pENetHost; peer:pENetPeer; command : pENetProtocol; currentData : ppenet_uint8):Integer; var fragmentNumber, fragmentCount, fragmentOffset, fragmentLength, reliableSequenceNumber, startSequenceNumber, totalLength : enet_uint32; reliableWindow, currentWindow : enet_uint16; channel : pENetChannel; currentCommand : ENetListIterator; startCommand : pENetIncomingCommand; incomingCommand : pENetIncomingCommand; packet : pENetPacket; label continue1; begin startCommand := nil; if (command ^. header.channelID >= peer ^. channelCount) or ((peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER)) then begin Result:=-1; exit; end; fragmentLength := ENET_NET_TO_HOST_16 (command ^. sendFragment.dataLength); Inc(currentData^, fragmentLength); if (fragmentLength > host ^. maximumPacketSize) or (currentData^ < host ^. receivedData) or (currentData^ > @ penet_uint8array(host ^. receivedData )[host ^. receivedDataLength]) then begin Result:=-1; exit; end; channel := @ peer ^. channels [command ^. header.channelID]; reliableSequenceNumber := command ^. header.reliableSequenceNumber; startSequenceNumber := ENET_NET_TO_HOST_16 (command ^. sendFragment.startSequenceNumber); reliableWindow := reliableSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE; currentWindow := channel ^. incomingReliableSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE; if (reliableSequenceNumber < channel ^. incomingReliableSequenceNumber) then Inc(reliableWindow , ENET_PEER_RELIABLE_WINDOWS); if (reliableWindow < currentWindow) or (reliableWindow >= currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1) then begin Result:=0; exit; end; if (reliableSequenceNumber = channel ^. incomingReliableSequenceNumber) and (startSequenceNumber <= channel ^. incomingUnreliableSequenceNumber) then begin Result:=0; exit; end; fragmentNumber := ENET_NET_TO_HOST_32 (command ^. sendFragment.fragmentNumber); fragmentCount := ENET_NET_TO_HOST_32 (command ^. sendFragment.fragmentCount); fragmentOffset := ENET_NET_TO_HOST_32 (command ^. sendFragment.fragmentOffset); totalLength := ENET_NET_TO_HOST_32 (command ^. sendFragment.totalLength); if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT) or (fragmentNumber >= fragmentCount) or (totalLength > host ^. maximumPacketSize) or (fragmentOffset >= totalLength) or (fragmentLength > totalLength - fragmentOffset) then begin Result:=-1; exit; end; currentCommand := enet_list_previous (enet_list_end (@ channel ^. incomingUnreliableCommands)); while (currentCommand <> enet_list_end (@ channel ^. incomingUnreliableCommands)) do begin incomingCommand := pENetIncomingCommand ( currentCommand ); if (reliableSequenceNumber >= channel ^. incomingReliableSequenceNumber) then begin if (incomingCommand ^. reliableSequenceNumber < channel ^. incomingReliableSequenceNumber) then goto continue1; end else if (incomingCommand ^. reliableSequenceNumber >= channel ^. incomingReliableSequenceNumber) then break; if (incomingCommand ^. reliableSequenceNumber < reliableSequenceNumber) then break; if (incomingCommand ^. reliableSequenceNumber > reliableSequenceNumber) then goto continue1; if (incomingCommand ^. unreliableSequenceNumber <= startSequenceNumber) then begin if (incomingCommand ^. unreliableSequenceNumber < startSequenceNumber) then break; if ((incomingCommand ^. command.header.command and ENET_PROTOCOL_COMMAND_MASK) <> ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT) or (totalLength <> incomingCommand ^. packet ^. dataLength) or (fragmentCount <> incomingCommand ^. fragmentCount) then begin Result:=-1; exit; end; startCommand := incomingCommand; break; end; continue1: currentCommand := enet_list_previous (currentCommand); end; if (startCommand = nil) then begin startCommand := enet_peer_queue_incoming_command (peer, command, nil, totalLength, ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT, fragmentCount); if (startCommand = nil) then begin Result:=-1; exit; end; end; if ((PIntegerArray(startCommand ^. fragments)^ [fragmentNumber div 32] and (1 shl (fragmentNumber mod 32))) = 0) then begin Dec( startCommand ^. fragmentsRemaining); PIntegerArray(startCommand ^. fragments)^[fragmentNumber div 32] := PIntegerArray(startCommand ^. fragments)^[fragmentNumber div 32] or (1 shl (fragmentNumber mod 32)); if (fragmentOffset + fragmentLength > startCommand ^. packet ^. dataLength) then fragmentLength := startCommand ^. packet ^. dataLength - fragmentOffset; system.Move((PChar(command) + sizeof (ENetProtocolSendFragment))^, (PChar(startCommand ^. packet ^. data) + fragmentOffset)^, fragmentLength); if (startCommand ^. fragmentsRemaining <= 0) then enet_peer_dispatch_incoming_unreliable_commands (peer, channel); end; Result:=0; end; function enet_protocol_handle_ping (host : pENetHost; peer : pENetPeer; command : pENetProtocol):integer; begin if (peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER) then begin Result:=-1; exit; end; result := 0; end; function enet_protocol_handle_bandwidth_limit (host : pENetHost; peer : pENetPeer; command : pENetProtocol):integer; begin if (peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER) then begin Result:=-1; exit; end; if (peer ^. incomingBandwidth <> 0) then Dec(host ^. bandwidthLimitedPeers); peer ^. incomingBandwidth := ENET_NET_TO_HOST_32 (command ^. bandwidthLimit.incomingBandwidth); peer ^. outgoingBandwidth := ENET_NET_TO_HOST_32 (command ^. bandwidthLimit.outgoingBandwidth); if (peer ^. incomingBandwidth <> 0) then Inc(host ^. bandwidthLimitedPeers); if (peer ^. incomingBandwidth = 0) and (host ^. outgoingBandwidth = 0) then peer ^. windowSize := ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE else if (peer ^. incomingBandwidth = 0) or (host ^. outgoingBandwidth = 0) then peer ^. windowSize := (ENET_MAX (peer ^. incomingBandwidth, host ^. outgoingBandwidth) div ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE else peer ^. windowSize := (ENET_MIN (peer ^. incomingBandwidth, host ^. outgoingBandwidth) div ENET_PEER_WINDOW_SIZE_SCALE) * ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; if (peer ^. windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) then peer ^. windowSize := ENET_PROTOCOL_MINIMUM_WINDOW_SIZE else if (peer ^. windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) then peer ^. windowSize := ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; result := 0; end; function enet_protocol_handle_throttle_configure (host : pENetHost; peer : pENetPeer; command : pENetProtocol):integer; begin if (peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER) then begin Result:=-1; exit; end; peer ^. packetThrottleInterval := ENET_NET_TO_HOST_32 (command ^. throttleConfigure.packetThrottleInterval); peer ^. packetThrottleAcceleration := ENET_NET_TO_HOST_32 (command ^. throttleConfigure.packetThrottleAcceleration); peer ^. packetThrottleDeceleration := ENET_NET_TO_HOST_32 (command ^. throttleConfigure.packetThrottleDeceleration); result := 0; end; function enet_protocol_handle_disconnect (host : pENetHost; peer : pENetPeer; command : pENetProtocol):integer; begin if (peer ^. state = ENET_PEER_STATE_DISCONNECTED) or (peer ^. state = ENET_PEER_STATE_ZOMBIE) or (peer ^. state = ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT) then begin Result:=0; exit; end; enet_peer_reset_queues (peer); if ((peer ^. state = ENET_PEER_STATE_CONNECTION_SUCCEEDED) or (peer ^. state = ENET_PEER_STATE_DISCONNECTING) or (peer ^. state = ENET_PEER_STATE_CONNECTING)) then enet_protocol_dispatch_state (host, peer, ENET_PEER_STATE_ZOMBIE) else if (peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER) then begin if (peer ^. state = ENET_PEER_STATE_CONNECTION_PENDING) then host ^. recalculateBandwidthLimits := 1; enet_peer_reset (peer); end else if (command ^. header.command and ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE)<>0 then enet_protocol_change_state (host, peer, ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT) else enet_protocol_dispatch_state (host, peer, ENET_PEER_STATE_ZOMBIE); if (peer ^. state <> ENET_PEER_STATE_DISCONNECTED) then peer ^. eventData := ENET_NET_TO_HOST_32 (command ^. disconnect.data); result := 0; end; function enet_protocol_handle_acknowledge (host : pENetHost; event : pENetEvent; peer : pENetPeer; command : pENetProtocol):integer; var roundTripTime, receivedSentTime, receivedReliableSequenceNumber : enet_uint32; commandNumber : ENetProtocolCommand; begin if (peer ^. state = ENET_PEER_STATE_DISCONNECTED) or (peer ^. state = ENET_PEER_STATE_ZOMBIE) then begin Result:=0; exit; end; receivedSentTime := ENET_NET_TO_HOST_16 (command ^. acknowledge.receivedSentTime); receivedSentTime := receivedSentTime or (host ^. serviceTime and $FFFF0000); if ((receivedSentTime and $8000) > (host ^. serviceTime and $8000)) then dec(receivedSentTime , $10000); if (ENET_TIME_LESS (host ^. serviceTime, receivedSentTime)) then begin result := 0; exit; end; peer ^. lastReceiveTime := host ^. serviceTime; peer ^. earliestTimeout := 0; roundTripTime := ENET_TIME_DIFFERENCE (host ^. serviceTime, receivedSentTime); enet_peer_throttle (peer, roundTripTime); dec(peer ^. roundTripTimeVariance , peer ^. roundTripTimeVariance div 4); if (roundTripTime >= peer ^. roundTripTime) then begin inc(peer ^. roundTripTime , (roundTripTime - peer ^. roundTripTime) div 8); inc(peer ^. roundTripTimeVariance , (roundTripTime - peer ^. roundTripTime) div 4); end else begin dec(peer ^. roundTripTime , (peer ^. roundTripTime - roundTripTime) div 8); inc(peer ^. roundTripTimeVariance , (peer ^. roundTripTime - roundTripTime) div 4); end; if (peer ^. roundTripTime < peer ^. lowestRoundTripTime) then peer ^. lowestRoundTripTime := peer ^. roundTripTime; if (peer ^. roundTripTimeVariance > peer ^. highestRoundTripTimeVariance) then peer ^. highestRoundTripTimeVariance := peer ^. roundTripTimeVariance; if (peer ^. packetThrottleEpoch = 0) or (ENET_TIME_DIFFERENCE (host ^. serviceTime, peer ^. packetThrottleEpoch) >= peer ^. packetThrottleInterval) then begin peer ^. lastRoundTripTime := peer ^. lowestRoundTripTime; peer ^. lastRoundTripTimeVariance := peer ^. highestRoundTripTimeVariance; peer ^. lowestRoundTripTime := peer ^. roundTripTime; peer ^. highestRoundTripTimeVariance := peer ^. roundTripTimeVariance; peer ^. packetThrottleEpoch := host ^. serviceTime; end; receivedReliableSequenceNumber := ENET_NET_TO_HOST_16 (command ^. acknowledge.receivedReliableSequenceNumber); commandNumber := enet_protocol_remove_sent_reliable_command (peer, receivedReliableSequenceNumber, command ^. header.channelID); case peer ^. state of ENET_PEER_STATE_ACKNOWLEDGING_CONNECT: begin if (commandNumber <> ENET_PROTOCOL_COMMAND_VERIFY_CONNECT) then begin result := -1; exit; end; enet_protocol_notify_connect (host, peer, event); end; // break; ENET_PEER_STATE_DISCONNECTING: begin if (commandNumber <> ENET_PROTOCOL_COMMAND_DISCONNECT) then begin result := -1; exit; end; enet_protocol_notify_disconnect (host, peer, event); end; // break; ENET_PEER_STATE_DISCONNECT_LATER: begin if (enet_list_empty (@ peer ^. outgoingReliableCommands) and enet_list_empty (@ peer ^. outgoingUnreliableCommands) and enet_list_empty (@ peer ^. sentReliableCommands)) then enet_peer_disconnect (peer, peer ^. eventData); end; // break else ; end; result := 0; end; function enet_protocol_handle_verify_connect (host : pENetHost; event : pENetEvent; peer : pENetPeer; command : pENetProtocol):integer; var mtu, windowSize : enet_uint32; channelCount : enet_size_t; begin if (peer ^. state <> ENET_PEER_STATE_CONNECTING) then begin result := 0; exit; end; channelCount := ENET_NET_TO_HOST_32 (command ^. verifyConnect.channelCount); if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT) or (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT) or (ENET_NET_TO_HOST_32 (command ^. verifyConnect.packetThrottleInterval) <> peer ^. packetThrottleInterval) or (ENET_NET_TO_HOST_32 (command ^. verifyConnect.packetThrottleAcceleration) <> peer ^. packetThrottleAcceleration) or (ENET_NET_TO_HOST_32 (command ^. verifyConnect.packetThrottleDeceleration) <> peer ^. packetThrottleDeceleration) or (command ^. verifyConnect.connectID <> peer ^. connectID) then begin peer ^. eventData := 0; enet_protocol_dispatch_state (host, peer, ENET_PEER_STATE_ZOMBIE); result := -1; exit; end; enet_protocol_remove_sent_reliable_command (peer, 1, $FF); if (channelCount < peer ^. channelCount) then peer ^. channelCount := channelCount; peer ^. outgoingPeerID := ENET_NET_TO_HOST_16 (command ^. verifyConnect.outgoingPeerID); peer ^. incomingSessionID := command ^. verifyConnect.incomingSessionID; peer ^. outgoingSessionID := command ^. verifyConnect.outgoingSessionID; mtu := ENET_NET_TO_HOST_32 (command ^. verifyConnect.mtu); if (mtu < ENET_PROTOCOL_MINIMUM_MTU) then mtu := ENET_PROTOCOL_MINIMUM_MTU else if (mtu > ENET_PROTOCOL_MAXIMUM_MTU) then mtu := ENET_PROTOCOL_MAXIMUM_MTU; if (mtu < peer ^. mtu) then peer ^. mtu := mtu; windowSize := ENET_NET_TO_HOST_32 (command ^. verifyConnect.windowSize); if (windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE) then windowSize := ENET_PROTOCOL_MINIMUM_WINDOW_SIZE; if (windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE) then windowSize := ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE; if (windowSize < peer ^. windowSize) then peer ^. windowSize := windowSize; peer ^. incomingBandwidth := ENET_NET_TO_HOST_32 (command ^. verifyConnect.incomingBandwidth); peer ^. outgoingBandwidth := ENET_NET_TO_HOST_32 (command ^. verifyConnect.outgoingBandwidth); enet_protocol_notify_connect (host, peer, event); result := 0; end; function enet_protocol_handle_incoming_commands (host : pENetHost; event : pENetEvent):integer; var header : pENetProtocolHeader; command : pENetProtocol; peer : pENetPeer; currentData : penet_uint8; headerSize : enet_size_t; peerID, flags : enet_uint16; sessionID : enet_uint8; commandNumber : enet_uint8; commandSize : enet_size_t; sentTime : enet_uint16; originalSize : enet_size_t; checksum : penet_uint32; desiredChecksum : enet_uint32; buffer : ENetBuffer; label commandError; const _ENetProtocolHeadMin = sizeof(ENetProtocolHeader)-sizeof(ENetProtocolHeader.sentTime); begin if (host ^. receivedDataLength < enet_size_t( _ENetProtocolHeadMin )) then begin result := 0; exit; end; header := pENetProtocolHeader(@host ^. receivedData[0]); peerID := ENET_NET_TO_HOST_16 (header ^. peerID); sessionID := (peerID and ENET_PROTOCOL_HEADER_SESSION_MASK) shr ENET_PROTOCOL_HEADER_SESSION_SHIFT; flags := peerID and ENET_PROTOCOL_HEADER_FLAG_MASK; peerID := peerID and not (ENET_PROTOCOL_HEADER_FLAG_MASK or ENET_PROTOCOL_HEADER_SESSION_MASK); if flags and ENET_PROTOCOL_HEADER_FLAG_SENT_TIME <> 0 then headerSize:= sizeof (ENetProtocolHeader) else headerSize:=_ENetProtocolHeadMin; if (host ^. checksumfunc <> nil) then Inc(headerSize, sizeof (enet_uint32)); if (peerID = ENET_PROTOCOL_MAXIMUM_PEER_ID) then peer := nil else if (peerID >= host ^. peerCount) then begin result := 0; exit; end else begin peer := @ pENetPeerArray(host ^. peers)^[peerID]; if (peer ^. state = ENET_PEER_STATE_DISCONNECTED) or (peer ^. state = ENET_PEER_STATE_ZOMBIE) or ( ( (host ^. receivedAddress.host <> peer ^. address.host) or (host ^. receivedAddress.port <> peer ^. address.port) ) and (peer ^. address.host <> ENET_HOST_BROADCAST_) ) or ( (peer ^. outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID) and (sessionID <> peer ^. incomingSessionID) ) then begin Result:=0; exit; end; end; if (flags and ENET_PROTOCOL_HEADER_FLAG_COMPRESSED<>0) then begin if (host ^. compressor.context = nil ) or ( host ^. compressor.decompress = nil) then begin Result:=0; exit; end; originalSize := host ^. compressor.decompress (host ^. compressor.context, host ^. receivedData + headerSize, host ^. receivedDataLength - headerSize, @ (host ^. packetData [1][0]) + headerSize, sizeof (host ^. packetData [1]) - headerSize); if (originalSize <= 0) or (originalSize > sizeof (host ^. packetData [1]) - headerSize) then begin result := 0; exit; end; system.Move (header^, host ^. packetData [1][0], headerSize); host ^. receivedData := @ host ^. packetData [1][0]; host ^. receivedDataLength := headerSize + originalSize; end; if (host ^. checksumfunc <> nil) then begin checksum := penet_uint32 ( @ penet_uint8array(host ^. receivedData)[headerSize - sizeof (enet_uint32)]); desiredChecksum := checksum^; if peer<>nil then checksum^ := peer ^. connectID else checksum^ := 0; buffer.data := host ^. receivedData; buffer.dataLength := host ^. receivedDataLength; if (ENET_CALLBACK_ENetChecksumCallback(host ^. checksumfunc)(@ buffer, 1) <> desiredChecksum) then begin Result:=0; exit; end; end; if (peer <> nil) then begin peer ^. address.host := host ^. receivedAddress.host; peer ^. address.port := host ^. receivedAddress.port; inc(peer ^. incomingDataTotal , host ^. receivedDataLength); end; currentData := penet_uint8(PChar(@host ^. receivedData[0]) + headerSize); while PChar(currentData)< PChar(@ penet_uint8array(host ^. receivedData)[host ^. receivedDataLength]) do begin command := pENetProtocol (currentData); if (PChar(currentData) + sizeof (ENetProtocolCommandHeader) > PChar(@ penet_uint8array(host ^. receivedData)[host ^. receivedDataLength])) then break; commandNumber := command ^. header.command and ENET_PROTOCOL_COMMAND_MASK; if (commandNumber >= ENET_PROTOCOL_COMMAND_COUNT) then break; commandSize := commandSizes [commandNumber]; if (commandSize = 0) or (PChar(currentData) + commandSize > PChar(@ penet_uint8array(host ^. receivedData)[host ^. receivedDataLength])) then break; inc(PChar(currentData), commandSize); if (peer = nil) and (commandNumber <> ENET_PROTOCOL_COMMAND_CONNECT) then break; command ^. header.reliableSequenceNumber := ENET_NET_TO_HOST_16 (command ^. header.reliableSequenceNumber); case (commandNumber) of ENET_PROTOCOL_COMMAND_ACKNOWLEDGE: begin if 0<>enet_protocol_handle_acknowledge (host, event, peer, command) then goto commandError; end; // break; ENET_PROTOCOL_COMMAND_CONNECT: begin if (peer <> nil) then goto commandError; peer := enet_protocol_handle_connect (host, header, command); if (peer = nil) then goto commandError; end; // break; ENET_PROTOCOL_COMMAND_VERIFY_CONNECT: begin if 0<>enet_protocol_handle_verify_connect (host, event, peer, command) then goto commandError; end; // break; ENET_PROTOCOL_COMMAND_DISCONNECT: begin if longbool(enet_protocol_handle_disconnect (host, peer, command)) then goto commandError; end; // break; ENET_PROTOCOL_COMMAND_PING: begin if longbool(enet_protocol_handle_ping (host, peer, command)) then goto commandError; end; // break; ENET_PROTOCOL_COMMAND_SEND_RELIABLE: begin if longbool(enet_protocol_handle_send_reliable (host, peer, command, @ currentData)) then goto commandError; end; // break; ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE: begin if longbool(enet_protocol_handle_send_unreliable (host, peer, command, @ currentData)) then goto commandError; end; // break; ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED: begin if longbool(enet_protocol_handle_send_unsequenced (host, peer, command, @ currentData)) then goto commandError; end; // break; ENET_PROTOCOL_COMMAND_SEND_FRAGMENT: begin if longbool(enet_protocol_handle_send_fragment (host, peer, command, @ currentData)) then goto commandError; end; // break; ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT: begin if longbool(enet_protocol_handle_bandwidth_limit (host, peer, command)) then goto commandError; end; // break; ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE: begin if longbool(enet_protocol_handle_throttle_configure (host, peer, command)) then goto commandError; end; // break; ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT: begin if (enet_protocol_handle_send_unreliable_fragment (host, peer, command, @ currentData)<>0) then goto commandError; end; // break; else goto commandError; end; if (peer <> nil) and ((command ^. header.command and ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE) <> 0) then begin if (flags and ENET_PROTOCOL_HEADER_FLAG_SENT_TIME)=0 then break; sentTime := ENET_NET_TO_HOST_16 (header ^. sentTime); case peer ^. state of ENET_PEER_STATE_DISCONNECTING, ENET_PEER_STATE_ACKNOWLEDGING_CONNECT, ENET_PEER_STATE_DISCONNECTED, ENET_PEER_STATE_ZOMBIE: ; // break; ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT: if ((command ^. header.command and ENET_PROTOCOL_COMMAND_MASK) = ENET_PROTOCOL_COMMAND_DISCONNECT) then enet_peer_queue_acknowledgement (peer, command, sentTime); else enet_peer_queue_acknowledgement (peer, command, sentTime); end; end; end; commandError: if (event <> nil) and (event ^. EventType <> ENET_EVENT_TYPE_NONE) then begin result:=1; exit; end; result := 0; end; function enet_protocol_receive_incoming_commands (host : pENetHost; event : pENetEvent):integer; var receivedLength : integer; buffer : ENetBuffer; packets : Integer; begin for packets:=0 to 255 do begin buffer.data := @ host ^. packetData [0][0]; buffer.dataLength := sizeof (host ^. packetData [0]); receivedLength := enet_socket_receive (host ^. socket, @ host ^. receivedAddress, @ buffer, 1); if (receivedLength < 0) then begin result:=-1; exit; end; if (receivedLength = 0) then begin result :=0; exit; end; host ^. receivedData := @host ^. packetData [0][0]; host ^. receivedDataLength := receivedLength; Inc(host ^. totalReceivedData, longword(receivedLength)); Inc(host ^. totalReceivedPackets); if (host ^. interceptfunc <> nil) then begin case ( ENET_CALLBACK_ENetInterceptCallback(host ^. interceptfunc)(host, event)) of 1: begin if (event<>nil) and (event ^. EventType <> ENET_EVENT_TYPE_NONE) then begin Result:=1; exit; end; continue; end; -1: begin Result:=-1; exit; end; else ; // break; end; end; case enet_protocol_handle_incoming_commands (host, event) of 1: begin result := 1; exit; end; -1: begin result := -1; exit; end; else ; // break end; end; result := -1; end; {$push} {$R-} procedure enet_protocol_send_acknowledgements (host : pENetHost; peer : pENetPeer); var command : pENetProtocol; buffer : pENetBuffer; acknowledgement : pENetAcknowledgement; currentAcknowledgement : ENetListIterator; reliableSequenceNumber : enet_uint16; begin command := @ host ^. commands [host ^. commandCount]; buffer := @ host ^. buffers [host ^. bufferCount]; currentAcknowledgement := enet_list_begin (@ peer ^. acknowledgements); while (currentAcknowledgement <> enet_list_end (@ peer ^. acknowledgements)) do begin (* if (PChar(command) >= PChar( @ host ^. commands [sizeof(host ^. commands) div sizeof(ENetProtocol)])) or (PChar(buffer) >= PChar( @ host ^. buffers [sizeof(host ^. buffers) div sizeof(ENetBuffer)])) or *) if (PChar(command) >= PChar( @ host ^. commands[0]) + sizeof(host ^. commands) div sizeof(ENetProtocol) * sizeof(ENetProtocol)) or (PChar(buffer) >= PChar( @ host ^. buffers [0]) + sizeof(host ^. buffers) div sizeof(ENetBuffer) * sizeof(ENetBuffer)) or (peer ^. mtu - host ^. packetSize < sizeof (ENetProtocolAcknowledge)) then begin host ^. continueSending := 1; break; end; acknowledgement := pENetAcknowledgement( currentAcknowledgement); currentAcknowledgement := enet_list_next (currentAcknowledgement); buffer ^. data := command; buffer ^. dataLength := sizeof (ENetProtocolAcknowledge); inc(host ^. packetSize , buffer ^. dataLength); reliableSequenceNumber := ENET_HOST_TO_NET_16 (acknowledgement ^. command.header.reliableSequenceNumber); command ^. header.command := ENET_PROTOCOL_COMMAND_ACKNOWLEDGE; command ^. header.channelID := acknowledgement ^. command.header.channelID; command ^. header.reliableSequenceNumber := reliableSequenceNumber; command ^. acknowledge.receivedReliableSequenceNumber := reliableSequenceNumber; command ^. acknowledge.receivedSentTime := ENET_HOST_TO_NET_16 (acknowledgement ^. sentTime); if ((acknowledgement ^. command.header.command and ENET_PROTOCOL_COMMAND_MASK) = ENET_PROTOCOL_COMMAND_DISCONNECT) then enet_protocol_dispatch_state (host, peer, ENET_PEER_STATE_ZOMBIE); enet_list_remove (@ acknowledgement ^. acknowledgementList); enet_free (acknowledgement); inc(command); inc(buffer); end; host ^. commandCount := (PChar(command)-PChar( @host ^. commands[0])) div sizeof(ENetProtocol); host ^. bufferCount := (PChar(buffer)-PChar( @host ^. buffers[0])) div sizeof(ENetBuffer); end; procedure enet_protocol_send_unreliable_outgoing_commands (host : pENetHost;peer : pENetPeer); var command : pENetProtocol; buffer : pENetBuffer; outgoingCommand : pENetOutgoingCommand; currentCommand : ENetListIterator; commandSize : enet_size_t; reliableSequenceNumber, unreliableSequenceNumber : enet_uint16; begin command := @ host ^. commands [host ^. commandCount]; buffer := @ host ^. buffers [host ^. bufferCount]; currentCommand := enet_list_begin (@ peer ^. outgoingUnreliableCommands); while (PChar(currentCommand) <> PChar(enet_list_end (@ peer ^. outgoingUnreliableCommands))) do begin outgoingCommand := pENetOutgoingCommand (currentCommand); commandSize := commandSizes [outgoingCommand ^. command.header.command and ENET_PROTOCOL_COMMAND_MASK]; (* if (PChar(command) >= PChar( @ host ^.commands [sizeof(host ^. commands) div sizeof(ENetProtocol)])) or (PChar(buffer)+sizeof(ENetBuffer) >= PChar( @ host ^. buffers [sizeof(host ^. buffers) div sizeof(ENetBuffer)])) or *) if (PChar(command) >= PChar( @ host ^.commands[0]) + sizeof(host ^. commands) div sizeof(ENetProtocol) * sizeof(ENetProtocol)) or (PChar(buffer)+sizeof(ENetBuffer) >= PChar( @ host ^. buffers[0]) + sizeof(host ^. buffers) div sizeof(ENetBuffer) * sizeof(ENetBuffer)) or (peer ^. mtu - host ^. packetSize < commandSize) or ( (outgoingCommand ^. packet <> nil) and (peer ^. mtu - host ^. packetSize < commandSize + outgoingCommand ^. fragmentLength) ) then begin host ^. continueSending := 1; break; end; currentCommand := enet_list_next (currentCommand); if (outgoingCommand ^. packet <> nil) and (outgoingCommand ^. fragmentOffset = 0) then begin inc(peer ^. packetThrottleCounter , ENET_PEER_PACKET_THROTTLE_COUNTER); peer ^. packetThrottleCounter := peer ^. packetThrottleCounter mod ENET_PEER_PACKET_THROTTLE_SCALE; if (peer ^. packetThrottleCounter > peer ^. packetThrottle) then begin reliableSequenceNumber := outgoingCommand ^. reliableSequenceNumber; unreliableSequenceNumber := outgoingCommand ^. unreliableSequenceNumber; while True do begin dec( outgoingCommand ^. packet ^. referenceCount ); if (outgoingCommand ^. packet ^. referenceCount = 0) then enet_packet_destroy (outgoingCommand ^. packet); enet_list_remove (@ outgoingCommand ^. outgoingCommandList); enet_free (outgoingCommand); if (PChar(currentCommand) = PChar(enet_list_end (@ peer ^. outgoingUnreliableCommands))) then break; outgoingCommand := pENetOutgoingCommand (currentCommand); if (outgoingCommand ^. reliableSequenceNumber <> reliableSequenceNumber) or (outgoingCommand ^. unreliableSequenceNumber <> unreliableSequenceNumber) then break; currentCommand := enet_list_next (currentCommand); end; continue; end; end; buffer ^. data := command; buffer ^. dataLength := commandSize; inc(host ^. packetSize , buffer ^. dataLength); command^ := outgoingCommand ^. command; enet_list_remove (@ outgoingCommand ^. outgoingCommandList); if (outgoingCommand ^. packet <> nil) then begin inc( buffer ); buffer ^. data := PChar(outgoingCommand ^. packet ^. data) + outgoingCommand ^. fragmentOffset; buffer ^. dataLength := outgoingCommand ^. fragmentLength; inc(host ^. packetSize , buffer ^. dataLength); enet_list_insert (enet_list_end (@ peer ^. sentUnreliableCommands), outgoingCommand); end else enet_free (outgoingCommand); inc(command); inc(buffer); end; host ^. commandCount := (PChar(command) - PChar( @host ^. commands[0])) div sizeof(ENetProtocol); host ^. bufferCount := (PChar(buffer) - PChar( @host ^. buffers[0])) div sizeof(ENetBuffer); if (peer ^. state = ENET_PEER_STATE_DISCONNECT_LATER) and enet_list_empty (@ peer ^. outgoingReliableCommands) and enet_list_empty (@ peer ^. outgoingUnreliableCommands) and enet_list_empty (@ peer ^. sentReliableCommands) and enet_list_empty (@ peer ^. sentUnreliableCommands) then enet_peer_disconnect (peer, peer ^. eventData); end; function enet_protocol_check_timeouts (host : pENetHost; peer : pENetPeer; event : pENetEvent):integer; var outgoingCommand : pENetOutgoingCommand; currentCommand, insertPosition : ENetListIterator; begin currentCommand := enet_list_begin (@ peer ^. sentReliableCommands); insertPosition := enet_list_begin (@ peer ^. outgoingReliableCommands); while (PChar(currentCommand) <> PChar(enet_list_end (@ peer ^. sentReliableCommands))) do begin outgoingCommand := pENetOutgoingCommand(currentCommand); currentCommand := enet_list_next (currentCommand); if (ENET_TIME_DIFFERENCE (host ^. serviceTime, outgoingCommand ^. sentTime) < outgoingCommand ^. roundTripTimeout) then continue; if(peer ^. earliestTimeout = 0) or ENET_TIME_LESS(outgoingCommand ^. sentTime, peer ^. earliestTimeout) then peer ^. earliestTimeout := outgoingCommand ^. sentTime; if (peer ^. earliestTimeout <> 0) and ( (ENET_TIME_DIFFERENCE (host ^. serviceTime, peer ^. earliestTimeout) >= peer ^. timeoutMaximum) or ( (outgoingCommand ^. roundTripTimeout >= outgoingCommand ^. roundTripTimeoutLimit) and (ENET_TIME_DIFFERENCE (host ^. serviceTime, peer ^. earliestTimeout) >= peer ^. timeoutMinimum) ) ) then begin enet_protocol_notify_disconnect (host, peer, event); result := 1; exit; end; if (outgoingCommand ^. packet <> nil) then dec(peer ^. reliableDataInTransit , outgoingCommand ^. fragmentLength); inc(peer ^. packetsLost); outgoingCommand ^. roundTripTimeout := outgoingCommand ^. roundTripTimeout * 2; enet_list_insert (insertPosition, enet_list_remove (@ outgoingCommand ^. outgoingCommandList)); // 2007/10/12 if (currentCommand = enet_list_begin (@ peer ^. sentReliableCommands)) and (not enet_list_empty (@ peer ^. sentReliableCommands)) then begin outgoingCommand := pENetOutgoingCommand( currentCommand); peer ^. nextTimeout := outgoingCommand ^. sentTime + outgoingCommand ^. roundTripTimeout; end; end; result := 0; end; function enet_protocol_send_reliable_outgoing_commands (host : pENetHost; peer : pENetPeer):Integer; var command : pENetProtocol; buffer : pENetBuffer; outgoingCommand : pENetOutgoingCommand; currentCommand : ENetListIterator; channel : pENetChannel; reliableWindow : enet_uint16; commandSize : enet_size_t; windowExceeded, windowWrap, canPing: Integer; windowSize : enet_uint32; begin command := @ host ^. commands [host ^. commandCount]; buffer := @ host ^. buffers [host ^. bufferCount]; windowExceeded := 0; windowWrap := 0; canPing := 1; currentCommand := enet_list_begin (@ peer ^. outgoingReliableCommands); while (PChar(currentCommand) <> PChar(enet_list_end (@ peer ^. outgoingReliableCommands))) do begin outgoingCommand := pENetOutgoingCommand(currentCommand); if (outgoingCommand ^. command.header.channelID < peer ^. channelCount) then channel := @ pENetChannelArray(peer ^. channels)^[outgoingCommand ^. command.header.channelID] else channel := nil; reliableWindow := outgoingCommand ^. reliableSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE; if (channel <> nil) then begin if (windowWrap=0) and (outgoingCommand ^. sendAttempts < 1) and (outgoingCommand ^. reliableSequenceNumber mod ENET_PEER_RELIABLE_WINDOW_SIZE = 0) and ( (channel ^. reliableWindows [(reliableWindow + ENET_PEER_RELIABLE_WINDOWS - 1) mod ENET_PEER_RELIABLE_WINDOWS] >= ENET_PEER_RELIABLE_WINDOW_SIZE) or ((channel ^. usedReliableWindows and ((((1 shl ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) shl reliableWindow) or (((1 shl ENET_PEER_FREE_RELIABLE_WINDOWS) - 1) shr (ENET_PEER_RELIABLE_WINDOWS - reliableWindow))))<>0) ) then windowWrap := 1; if (windowWrap<>0) then begin currentCommand := enet_list_next (currentCommand); continue; end; end; if (outgoingCommand ^. packet <> nil) then begin if (windowExceeded=0) then begin windowSize := (peer ^. packetThrottle * peer ^. windowSize) div ENET_PEER_PACKET_THROTTLE_SCALE; if (peer ^. reliableDataInTransit + outgoingCommand ^. fragmentLength > ENET_MAX (windowSize, peer ^. mtu)) then windowExceeded := 1; end; if (windowExceeded<>0) then begin currentCommand := enet_list_next (currentCommand); continue; end; end; canPing := 0; commandSize := commandSizes [outgoingCommand ^. command.header.command and ENET_PROTOCOL_COMMAND_MASK]; (* if (PChar(command) >= PChar( @ host ^. commands [sizeof (host ^. commands) div sizeof (ENetProtocol)])) or (PChar(buffer)+SizeOf(ENetBuffer) >= PChar( @ host ^. buffers [sizeof (host ^. buffers) div sizeof (ENetBuffer)])) or *) if (PChar(command) >= PChar( @ host ^. commands [0]) + sizeof (host ^. commands) div sizeof (ENetProtocol) * sizeof(ENetProtocol)) or (PChar(buffer)+SizeOf(ENetBuffer) >= PChar( @ host ^. buffers [0]) + sizeof (host ^. buffers) div sizeof (ENetBuffer) * sizeof(ENetBuffer)) or (peer ^. mtu - host ^. packetSize < commandSize) or ((outgoingCommand ^. packet <> nil) and (enet_uint16(peer ^. mtu - host ^. packetSize) < enet_uint16(commandSize + outgoingCommand ^. fragmentLength))) then begin host ^. continueSending := 1; break; end; currentCommand := enet_list_next (currentCommand); if (channel <> nil) and (outgoingCommand ^. sendAttempts < 1) then begin channel ^. usedReliableWindows := channel ^. usedReliableWindows or (1 shl reliableWindow); inc( channel ^. reliableWindows [reliableWindow]); end; inc( outgoingCommand ^. sendAttempts); if (outgoingCommand ^. roundTripTimeout = 0) then begin outgoingCommand ^. roundTripTimeout := peer ^. roundTripTime + 4 * peer ^. roundTripTimeVariance; outgoingCommand ^. roundTripTimeoutLimit := peer ^. timeoutLimit * outgoingCommand ^. roundTripTimeout; end; if (enet_list_empty (@ peer ^. sentReliableCommands)) then peer ^. nextTimeout := host ^. serviceTime + outgoingCommand ^. roundTripTimeout; enet_list_insert (enet_list_end (@ peer ^. sentReliableCommands), enet_list_remove (@ outgoingCommand ^. outgoingCommandList)); outgoingCommand ^. sentTime := host ^. serviceTime; buffer ^. data := command; buffer ^. dataLength := commandSize; inc(host ^. packetSize , buffer ^. dataLength); host ^. headerFlags := host ^. headerFlags or ENET_PROTOCOL_HEADER_FLAG_SENT_TIME; command^ := outgoingCommand ^. command; if (outgoingCommand ^. packet <> nil) then begin inc(buffer); buffer ^. data := PChar(outgoingCommand ^. packet ^. data) + outgoingCommand ^. fragmentOffset; buffer ^. dataLength := outgoingCommand ^. fragmentLength; inc(host ^. packetSize , outgoingCommand ^. fragmentLength); inc(peer ^. reliableDataInTransit , outgoingCommand ^. fragmentLength); end; inc(peer ^. packetsSent); inc(command); inc(buffer); end; host ^. commandCount := (PChar(command)-PChar( @host ^. commands[0])) div sizeof(ENetProtocol); host ^. bufferCount := (PChar(buffer)-PChar( @host ^. buffers[0])) div sizeof(ENetBuffer); Result:=canPing; end; {$pop} function enet_protocol_send_outgoing_commands (host : pENetHost; event : pENetEvent; checkForTimeouts : integer):integer; var headerData : array[0..sizeof (ENetProtocolHeader) + sizeof (enet_uint32)-1] of enet_uint8; header : pENetProtocolHeader; currentPeer : pENetPeer; sentLength : integer; packetLoss : enet_uint32; shouldCompress : enet_size_t; originalSize, compressedSize : enet_size_t; checksum : penet_uint32; label continuework; begin header := pENetProtocolHeader (@headerData); shouldCompress := 0; host ^. continueSending := 1; while (host ^. continueSending <> 0) do begin host ^. continueSending := 0; currentPeer := host ^. peers; while PChar(currentPeer) < PChar(@ pENetPeerArray(host ^. peers)^[host ^. peerCount]) do begin if (currentPeer ^. state = ENET_PEER_STATE_DISCONNECTED) or (currentPeer ^. state = ENET_PEER_STATE_ZOMBIE) then goto continuework; host ^. headerFlags := 0; host ^. commandCount := 0; host ^. bufferCount := 1; host ^. packetSize := sizeof (ENetProtocolHeader); if (not enet_list_empty (@ currentPeer ^. acknowledgements)) then enet_protocol_send_acknowledgements (host, currentPeer); if (checkForTimeouts <> 0) and not enet_list_empty (@ currentPeer ^. sentReliableCommands) and ENET_TIME_GREATER_EQUAL (host ^. serviceTime, currentPeer ^. nextTimeout) and (enet_protocol_check_timeouts (host, currentPeer, event) = 1) then begin if (event <> nil) and (event ^. EventType <> ENET_EVENT_TYPE_NONE) then begin result:=1; exit; end else goto continuework; end; if ( enet_list_empty (@ currentPeer ^. outgoingReliableCommands) or (enet_protocol_send_reliable_outgoing_commands (host, currentPeer)<>0) ) and enet_list_empty (@ currentPeer ^. sentReliableCommands) and (ENET_TIME_DIFFERENCE (host ^. serviceTime, currentPeer ^. lastReceiveTime) >= currentPeer ^. pingInterval) and (currentPeer ^. mtu - host ^. packetSize >= sizeof (ENetProtocolPing)) then begin enet_peer_ping (currentPeer); enet_protocol_send_reliable_outgoing_commands (host, currentPeer); end; if (not enet_list_empty (@ currentPeer ^. outgoingUnreliableCommands)) then enet_protocol_send_unreliable_outgoing_commands (host, currentPeer); if (host ^. commandCount = 0) then goto continuework; if (currentPeer ^. packetLossEpoch = 0) then currentPeer ^. packetLossEpoch := host ^. serviceTime else if (ENET_TIME_DIFFERENCE (host ^. serviceTime, currentPeer ^. packetLossEpoch) >= ENET_PEER_PACKET_LOSS_INTERVAL) and (currentPeer ^. packetsSent > 0) then begin packetLoss := currentPeer ^. packetsLost * ENET_PEER_PACKET_LOSS_SCALE div currentPeer ^. packetsSent; dec(currentPeer ^. packetLossVariance , currentPeer ^. packetLossVariance div 4); if (packetLoss >= currentPeer ^. packetLoss) then begin inc(currentPeer ^. packetLoss , (packetLoss - currentPeer ^. packetLoss) div 8); inc(currentPeer ^. packetLossVariance , (packetLoss - currentPeer ^. packetLoss) div 4); end else begin dec(currentPeer ^. packetLoss , (currentPeer ^. packetLoss - packetLoss) div 8); inc(currentPeer ^. packetLossVariance , (currentPeer ^. packetLoss - packetLoss) div 4); end; currentPeer ^. packetLossEpoch := host ^. serviceTime; currentPeer ^. packetsSent := 0; currentPeer ^. packetsLost := 0; end; host ^. buffers[0] . data := @headerData; if (host ^. headerFlags and ENET_PROTOCOL_HEADER_FLAG_SENT_TIME)<>0 then begin header ^. sentTime := ENET_HOST_TO_NET_16 (host ^. serviceTime and $0FFFF); host ^. buffers[0] . dataLength := sizeof (ENetProtocolHeader); end else host ^. buffers[0] . dataLength := sizeof(ENetProtocolHeader)-sizeof(ENetProtocolHeader.sentTime); shouldCompress := 0; if (host ^. compressor.context <> nil) and (host ^. compressor.compress <> nil) then begin originalSize := host ^. packetSize - sizeof(ENetProtocolHeader); compressedSize := host ^. compressor.compress (host ^. compressor.context, @ host ^. buffers [1], host ^. bufferCount - 1, originalSize, @ host ^. packetData [1][0], originalSize); if (compressedSize > 0) and (compressedSize < originalSize) then begin host ^. headerFlags := host ^. headerFlags or ENET_PROTOCOL_HEADER_FLAG_COMPRESSED; shouldCompress := compressedSize; end; end; if (currentPeer ^. outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID) then host ^. headerFlags := host ^. headerFlags or (currentPeer ^. outgoingSessionID shl ENET_PROTOCOL_HEADER_SESSION_SHIFT); header ^. peerID := ENET_HOST_TO_NET_16 (currentPeer ^. outgoingPeerID or host ^. headerFlags); if (host ^. checksumfunc <> nil) then begin checksum := penet_uint32 ( @ headerData [host ^. buffers[0] . dataLength] ); if (currentPeer ^. outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID) then checksum^ := currentPeer ^. connectID else checksum^ := 0; Inc(host ^. buffers[0] . dataLength , sizeof (enet_uint32)); checksum^ := ENET_CALLBACK_ENetChecksumCallback(host ^. checksumfunc) (host ^. buffers, host ^. bufferCount); end; if (shouldCompress > 0) then begin host ^. buffers [1].data := @host ^. packetData [1][0]; host ^. buffers [1].dataLength := shouldCompress; host ^. bufferCount := 2; end; currentPeer ^. lastSendTime := host ^. serviceTime; sentLength := enet_socket_send (host ^. socket, @ currentPeer ^. address, @host ^. buffers[0], host ^. bufferCount); enet_protocol_remove_sent_unreliable_commands (currentPeer); if (sentLength < 0) then begin result:=-1; exit; end; Inc(host ^. totalSentData , longword(sentLength)); Inc(host ^. totalSentPackets); continuework: inc(currentPeer); end; end; // while result := 0; end; (** Sends any queued packets on the host specified to its designated peers. @param host host to flush @remarks this function need only be used in circumstances where one wishes to send queued packets earlier than in a call to enet_host_service(). @ingroup host *) procedure enet_host_flush (host : pENetHost); begin host ^. serviceTime := enet_time_get (); enet_protocol_send_outgoing_commands (host, nil, 0); end; (** Checks for any queued events on the host and dispatches one if available. @param host host to check for events @param event an event structure where event details will be placed if available @retval > 0 if an event was dispatched @retval 0 if no events are available @retval < 0 on failure @ingroup host *) function enet_host_check_events (host : pENetHost; event : pENetEvent):integer; begin if (event = nil) then begin result := -1; exit; end; event ^. EventType := ENET_EVENT_TYPE_NONE; event ^. peer := nil; event ^. packet := nil; result := enet_protocol_dispatch_incoming_commands (host, event); end; (** Waits for events on the host specified and shuttles packets between the host and its peers. @param host host to service @param event an event structure where event details will be placed if one occurs if event = NULL then no events will be delivered @param timeout number of milliseconds that ENet should wait for events @retval > 0 if an event occurred within the specified time limit @retval 0 if no event occurred @retval < 0 on failure @remarks enet_host_service should be called fairly regularly for adequate performance @ingroup host *) function enet_host_service (host : pENetHost; event : pENetEvent; timeout : enet_uint32):integer; var waitCondition : enet_uint32; begin if (event <> nil) then begin event ^. EventType := ENET_EVENT_TYPE_NONE; event ^. peer := nil; event ^. packet := nil; case enet_protocol_dispatch_incoming_commands (host, event) of 1: begin result := 1; exit; end; -1: begin //raise exception.Create('Error dispatching incoming packets'); result := -1; exit; end; else ; end; end; host ^. serviceTime := enet_time_get (); inc(timeout , host ^. serviceTime); repeat if (ENET_TIME_DIFFERENCE (host ^. serviceTime, host ^. bandwidthThrottleEpoch) >= ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL) then // enet_host_bandwidth_throttle (host); case enet_protocol_send_outgoing_commands (host, event, 1) of 1: begin result :=1; exit; end; -1: begin //perror ("Error sending outgoing packets"); result := -1; exit; end; else ; end; case enet_protocol_receive_incoming_commands (host, event) of 1: begin result :=1; exit; end; -1: begin //perror ("Error receiving incoming packets"); result:=-1; exit; end; else ; end; case enet_protocol_send_outgoing_commands (host, event, 1) of 1: begin result :=1; exit; end; -1: begin //perror ("Error sending outgoing packets"); result :=-1; exit; end; else ; end; if (event <> nil) then begin case enet_protocol_dispatch_incoming_commands (host, event) of 1: begin result :=1; exit; end; -1: begin //perror ("Error dispatching incoming packets"); result := -1; exit; end; end; end; host ^. serviceTime := enet_time_get (); if (ENET_TIME_GREATER_EQUAL (host ^. serviceTime, timeout)) then begin result:=0; exit; end; repeat host ^. serviceTime := enet_time_get (); if (ENET_TIME_GREATER_EQUAL (host ^. serviceTime, timeout)) then begin result:=0; exit; end; waitCondition := ENET_SOCKET_WAIT_RECEIVE or ENET_SOCKET_WAIT_INTERRUPT; if (enet_socket_wait (host ^. socket, @ waitCondition, ENET_TIME_DIFFERENCE (timeout, host ^. serviceTime)) <> 0) then begin result:=-1; exit; end; until (waitCondition and ENET_SOCKET_WAIT_INTERRUPT = 0); host ^. serviceTime := enet_time_get (); until (waitCondition and ENET_SOCKET_WAIT_RECEIVE = 0); result := 0; end; end.
unit Configuracion; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Menus, StdCtrls, cxButtons, cxCheckBox, ExtCtrls, IniFiles, Registry; type TMConfiguracion = class(TForm) pnl1: TPanel; chkEjecutarInicio: TcxCheckBox; btnAceptar: TcxButton; procedure btnAceptarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); private { Private declarations } procedure EjecutarInicio; procedure QuitarEjecutarInicio; procedure GuardarConfiguracion; procedure CargarConfiguracion; public { Public declarations } end; var MConfiguracion: TMConfiguracion; implementation {$R *.dfm} procedure TMConfiguracion.btnAceptarClick(Sender: TObject); begin Close; end; procedure TMConfiguracion.CargarConfiguracion; var Ini: TIniFile; begin Ini := TIniFile.Create (ChangeFileExt(Application.ExeName, '.ini')); with Ini do begin try chkEjecutarInicio.Checked := ReadBool('Configuración', 'Ejecutar al iniciar Windows', false); finally Free; end; end; end; procedure TMConfiguracion.EjecutarInicio; var reg : tregistry; begin Reg := TRegistry.Create(KEY_WRITE); try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.Access := KEY_WRITE; if Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', True) then begin try Reg.WriteString(Application.Title, ExtractFilePath(ParamStr(0)) + ExtractFileName(ParamStr(0))); except Reg.CloseKey; raise; end; end; Reg.CloseKey; finally Reg.Free; end; end; { procedure TMConfiguracion.EjecutarInicio2; var reg : tregistry; begin // Reg := TRegistry.Create(KEY_WRITE); Reg := TRegistry.Create(KEY_WRITE OR KEY_WOW64_64KEY); try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.Access := KEY_ALL_ACCESS; if Reg.OpenKey('\Software\Microsoft\Windows\CurrentVersion\Run', True) then begin try Reg.WriteString(Application.Title, ExtractFilePath(ParamStr(0)) + ExtractFileName(ParamStr(0))); except Reg.CloseKey; raise; end; end; Reg.CloseKey; finally Reg.Free; end; end; } procedure TMConfiguracion.FormClose(Sender: TObject; var Action: TCloseAction); begin if chkEjecutarInicio.Checked then EjecutarInicio else QuitarEjecutarInicio; GuardarConfiguracion; end; procedure TMConfiguracion.FormCreate(Sender: TObject); begin CargarConfiguracion; end; procedure TMConfiguracion.GuardarConfiguracion; var Ini: TIniFile; begin Ini := TIniFile.Create (ChangeFileExt(Application.ExeName, '.ini')); with Ini do begin try WriteBool('Configuración', 'Ejecutar al iniciar Windows', chkEjecutarInicio.Checked); finally free; end; end; end; procedure TMConfiguracion.QuitarEjecutarInicio; var reg: TRegistry; begin reg := TRegistry.Create(KEY_WRITE); reg.RootKey := HKEY_LOCAL_MACHINE; reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', false); reg.DeleteValue(Application.Title); reg.CloseKey; reg.Free; end; { procedure TMConfiguracion.QuitarEjecutarInicio2; var reg: TRegistry; begin reg := TRegistry.Create(KEY_WRITE); reg.RootKey := HKEY_CURRENT_USER; reg.Access := KEY_ALL_ACCESS; reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', false); reg.DeleteValue(Application.Title); reg.CloseKey; reg.Free; end; } end.
{ *************************************************************************** Copyright (c) 2016-2022 Kike Pérez Unit : Quick.Collections Description : Generic Collections Author : Kike Pérez Version : 1.2 Created : 07/03/2020 Modified : 27/01/2022 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Collections; {$i QuickLib.inc} interface uses System.SysUtils, TypInfo, System.Types, System.Generics.Defaults, System.Generics.Collections, Quick.Linq; type IListBase<T> = interface ['{9A9B2DB9-14E4-49DD-A628-F84F50539F41}'] function GetList: TArray<T>; function GetCapacity: Integer; procedure SetCapacity(Value: Integer); overload; function GetCount : Integer; procedure SetCount(Value: Integer); function GetItem(Index: Integer): T; procedure SetItem(Index: Integer; const Value: T); function GetEnumerator : TEnumerator<T>; function Add(const Value: T): Integer; procedure AddRange(const Values: array of T); overload; procedure AddRange(const Collection: IEnumerable<T>); overload; procedure AddRange(const Collection: TEnumerable<T>); overload; procedure Insert(Index: Integer; const Value: T); procedure InsertRange(Index: Integer; const Values: array of T; Count: Integer); overload; procedure InsertRange(Index: Integer; const Values: array of T); overload; procedure InsertRange(Index: Integer; const Collection: IEnumerable<T>); overload; procedure InsertRange(Index: Integer; const Collection: TEnumerable<T>); overload; function Remove(const Value: T): Integer; function RemoveItem(const Value: T; Direction: TDirection): Integer; procedure Delete(Index: Integer); procedure DeleteRange(AIndex, ACount: Integer); function ExtractItem(const Value: T; Direction: TDirection): T; function Extract(const Value: T): T; function ExtractAt(Index: Integer): T; procedure Exchange(Index1, Index2: Integer); procedure Move(CurIndex, NewIndex: Integer); function First: T; function Last: T; procedure Clear; function Contains(const Value: T): Boolean; function IndexOf(const Value: T): Integer; function IndexOfItem(const Value: T; Direction: TDirection): Integer; function LastIndexOf(const Value: T): Integer; procedure Reverse; procedure Sort; overload; procedure Sort(const AComparer: IComparer<T>); overload; function BinarySearch(const Item: T; out Index: Integer): Boolean; overload; function BinarySearch(const Item: T; out Index: Integer; const AComparer: IComparer<T>): Boolean; overload; procedure TrimExcess; function ToArray: TArray<T>; procedure FromList(const aList : TList<T>); procedure FromArray(const aArray: TArray<T>); function ToList : TList<T>; property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount write SetCount; property Items[Index: Integer]: T read GetItem write SetItem; default; property List: TArray<T> read GetList; function Any : Boolean; overload; end; IList<T> = interface(IListBase<T>) ['{78952BD5-7D15-42BB-ADCB-2F835DF879A0}'] function Any(const aMatchString : string; aUseRegEx : Boolean) : Boolean; overload; function Any(const aWhereClause : string; aValues : array of const) : Boolean; overload; function Where(const aMatchString : string; aUseRegEx : Boolean) : ILinqArray<T>; overload; function Where(const aWhereClause : string; aWhereValues : array of const) : ILinqQuery<T>; overload; function Where(const aWhereClause: string): ILinqQuery<T>; overload; {$IFNDEF FPC} function Where(aPredicate : TPredicate<T>) : ILinqQuery<T>; overload; {$ENDIF} end; IObjectList<T : class> = interface(IListBase<T>) ['{7380847B-9F94-4FB8-8B73-DC8ACAFF1729}'] function Any(const aWhereClause : string; aValues : array of const) : Boolean; overload; function Where(const aWhereClause : string; aWhereValues : array of const) : ILinqQuery<T>; overload; function Where(const aWhereClause: string): ILinqQuery<T>; overload; function Where(aPredicate : TPredicate<T>): ILinqQuery<T>; overload; end; TxList<T> = class(TInterfacedObject,IList<T>) private type arrayofT = array of T; private fList : TList<T>; function GetList: TArray<T>; function GetCapacity: Integer; procedure SetCapacity(Value: Integer); overload; function GetCount : Integer; procedure SetCount(Value: Integer); function GetItem(Index: Integer): T; procedure SetItem(Index: Integer; const Value: T); function GetEnumerator : TEnumerator<T>; public constructor Create; destructor Destroy; override; function Add(const Value: T): Integer; inline; procedure AddRange(const Values: array of T); overload; procedure AddRange(const Collection: IEnumerable<T>); overload; inline; procedure AddRange(const Collection: TEnumerable<T>); overload; procedure Insert(Index: Integer; const Value: T); inline; procedure InsertRange(Index: Integer; const Values: array of T; Count: Integer); overload; procedure InsertRange(Index: Integer; const Values: array of T); overload; procedure InsertRange(Index: Integer; const Collection: IEnumerable<T>); overload; procedure InsertRange(Index: Integer; const Collection: TEnumerable<T>); overload; function Remove(const Value: T): Integer; inline; function RemoveItem(const Value: T; Direction: TDirection): Integer; inline; procedure Delete(Index: Integer); inline; procedure DeleteRange(AIndex, ACount: Integer); inline; function ExtractItem(const Value: T; Direction: TDirection): T; inline; function Extract(const Value: T): T; inline; function ExtractAt(Index: Integer): T; inline; procedure Exchange(Index1, Index2: Integer); inline; procedure Move(CurIndex, NewIndex: Integer); inline; function First: T; inline; function Last: T; inline; procedure Clear; inline; function Contains(const Value: T): Boolean; inline; function IndexOf(const Value: T): Integer; inline; function IndexOfItem(const Value: T; Direction: TDirection): Integer; inline; function LastIndexOf(const Value: T): Integer; inline; procedure Reverse; inline; procedure Sort; overload; inline; procedure Sort(const AComparer: IComparer<T>); overload; inline; function BinarySearch(const Item: T; out Index: Integer): Boolean; overload; inline; function BinarySearch(const Item: T; out Index: Integer; const AComparer: IComparer<T>): Boolean; overload; inline; procedure TrimExcess; inline; function ToArray: TArray<T>; inline; property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount write SetCount; property Items[Index: Integer]: T read GetItem write SetItem; default; property List: arrayofT read GetList; procedure FromList(const aList : TList<T>); procedure FromArray(const aArray: TArray<T>); function ToList : TList<T>; function Any : Boolean; overload; virtual; function Where(const aWhereClause : string; aWhereValues : array of const) : ILinqQuery<T>; overload; function Where(const aWhereClause: string): ILinqQuery<T>; overload; function Any(const aMatchString : string; aUseRegEx : Boolean) : Boolean; overload; function Any(const aWhereClause : string; aValues : array of const) : Boolean; overload; virtual; function Where(const aMatchString : string; aUseRegEx : Boolean) : ILinqArray<T>; overload; {$IFNDEF FPC} function Where(aPredicate : TPredicate<T>) : ILinqQuery<T>; overload; {$ENDIF} end; TxObjectList<T : class> = class(TxList<T>,IObjectList<T>) private fOwnsObjects : Boolean; procedure InternalOnNotify(Sender: TObject; const Item: T; Action: TCollectionNotification); public constructor Create(aOwnedObjects : Boolean = True); destructor Destroy; override; function Any(const aWhereClause : string; aValues : array of const) : Boolean; overload; override; function Where(const aWhereClause : string; aWhereValues : array of const) : ILinqQuery<T>; overload; function Where(const aWhereClause: string): ILinqQuery<T>; overload; function Where(aPredicate : TPredicate<T>): ILinqQuery<T>; overload; end; ECollectionError = class(Exception); ECollectionNotSupported = class(Exception); implementation { TXList<T> } constructor TxList<T>.Create; begin fList := TList<T>.Create; end; destructor TxList<T>.Destroy; begin fList.Free; inherited; end; function TxList<T>.Add(const Value: T): Integer; begin Result := fList.Add(Value); end; procedure TxList<T>.AddRange(const Values: array of T); begin fList.AddRange(Values); end; procedure TxList<T>.AddRange(const Collection: IEnumerable<T>); begin fList.AddRange(Collection); end; procedure TxList<T>.AddRange(const Collection: TEnumerable<T>); begin fList.AddRange(Collection); end; function TxList<T>.Any(const aMatchString: string; aUseRegEx: Boolean): Boolean; begin Result := Where(aMatchString,aUseRegEx).Any; end; function TxList<T>.Any: Boolean; begin Result := fList.Count > 0; end; function TxList<T>.BinarySearch(const Item: T; out Index: Integer): Boolean; begin Result := fList.BinarySearch(Item,Index); end; function TxList<T>.BinarySearch(const Item: T; out Index: Integer; const AComparer: IComparer<T>): Boolean; begin Result := fList.BinarySearch(Item,Index,AComparer); end; procedure TxList<T>.Clear; begin fList.Clear; end; function TxList<T>.Contains(const Value: T): Boolean; begin Result := fList.Contains(Value); end; procedure TxList<T>.Delete(Index: Integer); begin fList.Delete(Index); end; procedure TxList<T>.DeleteRange(AIndex, ACount: Integer); begin fList.DeleteRange(aIndex,aCount); end; procedure TxList<T>.Exchange(Index1, Index2: Integer); begin fList.Exchange(Index1,Index2); end; function TxList<T>.Extract(const Value: T): T; begin Result := fList.Extract(Value); end; function TxList<T>.ExtractAt(Index: Integer): T; begin {$If Defined(FPC) OR Defined(DELPHIRX102_UP)} Result := fList.ExtractAt(Index); {$ELSE} Result := fList.Extract(fList[Index]); {$ENDIF} end; function TxList<T>.ExtractItem(const Value: T; Direction: TDirection): T; begin Result := fList.ExtractItem(Value,Direction); end; function TxList<T>.First: T; begin if fList.Count > 0 then Result := fList.First else Result := default(T); end; procedure TxList<T>.FromList(const aList: TList<T>); var value : T; begin fList.Capacity := aList.Count; for value in aList do fList.Add(value); end; procedure TxList<T>.FromArray(const aArray: TArray<T>); var value : T; begin fList.Capacity := High(aArray); for value in aArray do fList.Add(value); end; function TxList<T>.GetCapacity: Integer; begin Result := fList.Capacity; end; function TxList<T>.GetCount: Integer; begin Result := fList.Count; end; function TxList<T>.GetEnumerator: TEnumerator<T>; begin Result := fList.GetEnumerator; end; function TxList<T>.GetItem(Index: Integer): T; begin Result := fList.Items[Index]; end; function TxList<T>.GetList: TArray<T>; begin Result := fList.ToArray; end; function TxList<T>.IndexOf(const Value: T): Integer; begin Result := fList.IndexOf(Value); end; function TxList<T>.IndexOfItem(const Value: T; Direction: TDirection): Integer; begin Result := fList.IndexOfItem(Value,Direction); end; procedure TxList<T>.Insert(Index: Integer; const Value: T); begin fList.Insert(Index,Value); end; procedure TxList<T>.InsertRange(Index: Integer; const Collection: IEnumerable<T>); begin fList.InsertRange(Index,Collection); end; procedure TxList<T>.InsertRange(Index: Integer; const Collection: TEnumerable<T>); begin fList.InsertRange(index,Collection); end; procedure TxList<T>.InsertRange(Index: Integer; const Values: array of T; Count: Integer); begin {$If Defined(FPC) OR Defined(DELPHIRX102_UP)} fList.InsertRange(Index,Values,Count); {$ELSE} fList.InsertRange(Index,Values); {$ENDIF} end; procedure TxList<T>.InsertRange(Index: Integer; const Values: array of T); begin fList.InsertRange(index,Values); end; function TxList<T>.Last: T; begin if fList.Count > 0 then Result := fList.Last else Result := default(T) end; function TxList<T>.LastIndexOf(const Value: T): Integer; begin Result := fList.LastIndexOf(Value); end; procedure TxList<T>.Move(CurIndex, NewIndex: Integer); begin fList.Move(CurIndex,NewIndex); end; function TxList<T>.Remove(const Value: T): Integer; begin Result := fList.Remove(Value); end; function TxList<T>.RemoveItem(const Value: T; Direction: TDirection): Integer; begin Result := fList.RemoveItem(Value,Direction); end; procedure TxList<T>.Reverse; begin fList.Reverse; end; procedure TxList<T>.SetCapacity(Value: Integer); begin fList.Capacity := Value; end; procedure TxList<T>.SetCount(Value: Integer); begin fList.Count := Value; end; procedure TxList<T>.SetItem(Index: Integer; const Value: T); begin fList.Items[Index] := Value; end; procedure TxList<T>.Sort(const AComparer: IComparer<T>); begin fList.Sort(AComparer); end; procedure TxList<T>.Sort; begin fList.Sort; end; function TxList<T>.ToArray: TArray<T>; begin Result := fList.ToArray; end; function TxList<T>.ToList: TList<T>; var value : T; begin Result := TList<T>.Create; Result.Capacity := fList.Count; for value in fList do Result.Add(value); end; procedure TxList<T>.TrimExcess; begin fList.TrimExcess; end; function TxList<T>.Where(const aMatchString: string; aUseRegEx: Boolean): ILinqArray<T>; begin {$IFDEF DELPHIRX104_UP} Result := TLinqArray<T>.Create(fList.PList^); {$ELSE} Result := TLinqArray<T>.Create(fList.ToArray); {$ENDIF} Result.Where(aMatchString, aUseRegEx); end; function TxList<T>.Where(const aWhereClause: string; aWhereValues: array of const): ILinqQuery<T>; begin if PTypeInfo(typeInfo(T)).Kind <> tkClass then raise ECollectionNotSupported.Create('TXList<T>.Where only supports classes. Use MatchString overload method instead!'); Result := TLinqQuery<TObject>.Create(TObjectList<TObject>(Self.fList)).Where(aWhereClause,aWhereValues) as ILinqQuery<T>; end; function TxList<T>.Where(const aWhereClause: string): ILinqQuery<T>; begin if PTypeInfo(typeInfo(T)).Kind <> tkClass then raise ECollectionNotSupported.Create('TXList<T>.Where only supports classes. Use MatchString overload method instead!'); Result := TLinqQuery<TObject>.Create(TObjectList<TObject>(Self.fList)).Where(aWhereClause) as ILinqQuery<T>; end; function TxList<T>.Where(aPredicate: TPredicate<T>): ILinqQuery<T>; begin if PTypeInfo(typeInfo(T)).Kind <> tkClass then raise ECollectionNotSupported.Create('TXList<T>.Where only supports classes. Use MatchString overload method instead!'); Result := TLinqQuery<TObject>.Create(TObjectList<TObject>(Self.fList)).Where(TPredicate<TObject>(aPredicate)) as ILinqQuery<T>; end; function TxList<T>.Any(const aWhereClause: string; aValues: array of const): Boolean; begin Result := Where(aWhereClause,aValues).Count > 0; end; { TXObjectList<T> } function TxObjectList<T>.Any(const aWhereClause: string; aValues: array of const): Boolean; var query : ILinqQuery<T>; begin query := TLinqQuery<T>.Create(Self.fList); Result := query.Where(aWhereClause,aValues).Count > 0; end; constructor TxObjectList<T>.Create(aOwnedObjects: Boolean = True); begin inherited Create; fOwnsObjects := aOwnedObjects; fList.OnNotify := InternalOnNotify; end; destructor TxObjectList<T>.Destroy; begin inherited; end; procedure TxObjectList<T>.InternalOnNotify(Sender: TObject; const Item: T; Action: TCollectionNotification); begin if (fOwnsObjects) and (Action = TCollectionNotification.cnRemoved) then begin if Assigned(Item) then Item.DisposeOf; //if PTypeInfo(typeInfo(T)).Kind = tkClass then //PObject(@Item).DisposeOf; end; end; function TxObjectList<T>.Where(const aWhereClause: string): ILinqQuery<T>; begin Result := TLinqQuery<T>.Create(Self.fList).Where(aWhereClause); end; function TxObjectList<T>.Where(const aWhereClause: string; aWhereValues: array of const): ILinqQuery<T>; begin Result := TLinqQuery<T>.Create(Self.fList).Where(aWhereClause,aWhereValues); end; function TxObjectList<T>.Where(aPredicate: TPredicate<T>): ILinqQuery<T>; begin Result := TLinqQuery<T>.Create(Self.fList).Where(aPredicate); end; end.
unit Thermostat.HeatingState; interface uses Thermostat.Classes; type THeatingState = class(TThermostatState) public procedure Init; override; procedure Finish; override; procedure Execute; override; end; implementation uses Thermostat.NotHeatingState; { THeatingState } procedure THeatingState.Execute; begin inherited; if Thermostat.SampleTemperature >= Thermostat.TargetTemperature then ChangeState(TNotHeatingState); end; procedure THeatingState.Finish; begin inherited; Thermostat.Heater := False; end; procedure THeatingState.Init; begin inherited; Thermostat.Heater := True; end; end.
unit kwProcessSubDirs; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwProcessSubDirs.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::FileProcessing::ProcessSubDirs // // ProcessSubDirs - перебирает директории в заданной директории и вызывает для каждого найденного // функцию. // *Формат:* // aProc aDirName ProcessSubDirs // * aProc - функция, которая вызывается для каждой директории. В стек при вызове помещается имя // директории. // * aDirName - путь, по которому ищутся директории. // *Пример:* // {code} // : PrintFileName // . // ; // // @ PrintFileName 'w:\archi\source\projects\Archi\TestSet\' ProcessSubDirs // {code} // В результате будет создан файл с имя_скрипта.prn с именами директорий с полными путями. // *Примечание:* Если ни одна директория не найдена, то функция не будет вызвана ни разу. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses tfwScriptingInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} TkwProcessSubDirs = {final} class(_tfwAutoregisteringWord_) {* ProcessSubDirs - перебирает директории в заданной директории и вызывает для каждого найденного функцию. *Формат:* aProc aDirName ProcessSubDirs * aProc - функция, которая вызывается для каждой директории. В стек при вызове помещается имя директории. * aDirName - путь, по которому ищутся директории. *Пример:* [code] : PrintFileName . ; @ PrintFileName 'w:\archi\source\projects\Archi\TestSet\' ProcessSubDirs [code] В результате будет создан файл с имя_скрипта.prn с именами директорий с полными путями. *Примечание:* Если ни одна директория не найдена, то функция не будет вызвана ни разу. } protected // realized methods procedure DoDoIt(const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwProcessSubDirs {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses SysUtils, l3FileUtils, tfwAutoregisteredDiction, tfwScriptEngine ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwProcessSubDirs; {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} // start class TkwProcessSubDirs procedure TkwProcessSubDirs.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_5091008A0389_var* var l_V : TtfwStackValue; l_Word : TtfwWord; l_DirName : AnsiString; l_SearchRec : TSearchRec; l_FindResult: Integer; //#UC END# *4DAEEDE10285_5091008A0389_var* begin //#UC START# *4DAEEDE10285_5091008A0389_impl* if aCtx.rEngine.IsTopString then begin l_DirName := aCtx.rEngine.PopDelphiString; if not DirectoryExists(l_DirName) then begin Assert(False, Format('Директория %s не существует', [l_DirName])); Exit; end; // if not DirectoryExists(l_DirName) then l_FindResult := FindFirst(ConcatDirName(l_DirName, '*.*'), faDirectory , l_SearchRec); l_V := aCtx.rEngine.Pop; l_Word := TtfwWord(l_V.AsObject); try while l_FindResult = 0 do begin if ((l_SearchRec.Attr and faDirectory) <> 0) and (l_SearchRec.Name <> '.') and (l_SearchRec.Name <> '..') then begin aCtx.rEngine.PushString(ConcatDirName(l_DirName, l_SearchRec.Name)); l_Word.DoIt(aCtx); end; // if (l_SearchRec.Attr and (faDirectory or faVolumeID or faSymLink)) = 0 then l_FindResult := FindNext(l_SearchRec); end; // while l_FindResult = 0 do finally FindClose(l_SearchRec); end; end // if aCtx.rEngine.IsTopString then else Assert(False, 'Не задана директория для поиска!'); //#UC END# *4DAEEDE10285_5091008A0389_impl* end;//TkwProcessSubDirs.DoDoIt class function TkwProcessSubDirs.GetWordNameForRegister: AnsiString; {-} begin Result := 'ProcessSubDirs'; end;//TkwProcessSubDirs.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} {$IfEnd} //not NoScripts end.
unit tmsUXlsSST; {$INCLUDE ..\FLXCOMPILER.INC} //This is a unit to optimize the SST for a big number of strings. //Optimizations: //We use records, no objects to store the strings (4 bytes of VMT per string and avoid calling create/destroy) //We don't use Widestrings or Strings to store them (8+6 bytes / string and avoid double allocation, one for the record and one for the string) //PENDING: Hash array to locate strings interface uses SysUtils, tmsXlsMessages, tmsUXlsBaseRecords, tmsUXlsOtherRecords, tmsUXlsStrings, Classes, tmsUFlxMessages, {$IFDEF FLX_GENERICS} Generics.Collections, {$ENDIF} tmsUOle2Impl; type TExtraData=Packed Record Refs: word; AbsStreamPos: LongWord; RecordStreamPos: Word; PosInTable:LongWord; end; PExtraData=^TExtraData; TiSSTEntry = integer; //offset to the array PiSSTEntry = PArrayOfByte; //Pointer to internal calcs. Never store it, because MemData.Buffer can be realocated TMemSST=record UsedSize: integer; Buffer: Array of Byte; end; {$IFDEF FLX_GENERICS} TSST = class(TList<TiSSTEntry>) private {$ELSE} TSST = class (TList) {$INCLUDE TiSSTHdr.inc} {$ENDIF} private MemSST: TMemSST; procedure QuickSort(L, R: Integer); function SSTRecordSize: int64; function ExtSSTRecordSize: int64; public constructor Create; function Find(const s:PiSSTEntry; var Index: integer): boolean; procedure Load(const aSSTRecord: TSSTRecord); procedure SaveToStream(const DataStream: TOle2File); procedure WriteExtSST(const DataStream: TOle2File); function AddString(const s:UTF16String; const RTFRuns: TRTFRunList):integer; procedure Sort; function TotalSize: int64; procedure FixRefs; function GetEntry(const aEntry: TiSSTEntry): PiSSTEntry; end; TLabelSSTRecord= class(TCellRecord) private pSSTEntry: TiSSTEntry; SST: TSST; function GetAsString: UTF16String; procedure SetAsString(const Value: UTF16String); function GetAsRTF: UTF16String; procedure SetAsRTF(const Value: UTF16String); function GetAsRichString: TRichString; procedure SetAsRichString(const Value: TRichString); protected function GetValue: Variant; override; procedure SetValue(const Value: Variant); override; function DoCopyTo: TBaseRecord; override; public constructor Create(const aId: word; const aData: PArrayOfByte; const aDataSize: integer);override; constructor CreateFromData(const aRow, aCol, aXF: word; const aSST: TSST); procedure AttachToSST(const aSST: TSST); procedure SaveToStream(const Workbook: TOle2File); override; destructor Destroy;override; property AsString: UTF16String read GetAsString write SetAsString; property AsRichString: TRichString read GetAsRichString write SetAsRichString; property AsRTF: UTF16String read GetAsRTF write SetAsRTF; end; TLabelRecord=class(TCellRecord) function GetValue: Variant; override; //We dont implement writing to a label. All writing should go to a LabelSST end; TRStringRecord=class(TCellRecord) private function GetAsRichString: TRichString; public function GetValue: Variant; override; property AsRichString: TRichString read GetAsRichString; //We dont implement writing to a label. All writing should go to a LabelSST end; implementation {$IFNDEF FLX_GENERICS} {$INCLUDE TiSSTImp.inc} {$ENDIF} const MemSSTDeltaSize=8096*1024; {4M} type TRecordBuff= array [0..MaxRecordDataSize+4] of byte; procedure CreateSSTEntryFromString(var MemSST: TMemSST; const s: UTF16String; const RTFRuns: TRTFRunList; var Entry: TiSSTEntry); var OptionFlags: byte; Wide: byte; Lb, OldSize, Posi, i: integer; pEntry: PArrayOfByte; begin if IsWide(s) then Wide := 1 else Wide:=0; OptionFlags := Wide; if Length(RTFRuns)>0 then OptionFlags:=OptionFlags or $8; { GetMem(Entry, SizeOf(TExtraData)+ //Extra data not to be saved SizeOf(Word) + // String Length SizeOf(byte) + // OptionsFlag Length(s)*(1+OptionFlags)); } OldSize:=MemSST.UsedSize; inc( MemSST.UsedSize, SizeOf(TExtraData)+ //Extra data not to be saved SizeOf(Word) + // String Length SizeOf(byte) + // OptionsFlag Length(s)*(1+Wide)); if Length(RTFRuns)>0 then inc( MemSST.UsedSize, Length(RTFRuns)*4+2 ); //RTF Info Lb:=Length(MemSST.Buffer); if MemSST.UsedSize>=Lb then SetLength(MemSST.Buffer, Lb+ MemSSTDeltaSize); //A string can't be longer than 8192 bytes; Entry:=OldSize; pEntry:=@MemSST.Buffer[Entry]; PExtraData(pEntry).Refs:=0; PExtraData(pEntry).AbsStreamPos:=0; PExtraData(pEntry).RecordStreamPos:=0; PExtraData(pEntry).PosInTable:=0; SetWord(pEntry, SizeOf(TExtraData), Length(s)); pEntry[2+SizeOf(TExtraData)]:=OptionFlags; Posi:=3+SizeOf(TExtraData); if Length(RTFRuns)>0 then begin SetWord(pEntry, Posi, Length(RTFRuns)); inc(Posi,2); end; if Wide = 1 then begin System.Move(s[1], pEntry^[Posi], Length(s)*2); inc(Posi, Length(s)*2); end else begin System.Move(WideStringToStringNoCodePage(s)[1], pEntry^[Posi], Length(s)); inc(Posi, Length(s)); end; for i:=0 to Length(RTFRuns)-1 do begin SetWord(pEntry, Posi, RTFRuns[i].FirstChar); SetWord(pEntry, Posi+2, RTFRuns[i].FontIndex); Inc(Posi, 4); end; end; procedure CreateSSTEntryFromRecord(var MemSST: TMemSST; var aSSTRecord: TBaseRecord; var Ofs: integer; var Entry: TiSSTEntry); var Xs: TExcelString; Lb, OldSize: integer; pEntry: PArrayOfByte; begin Xs:=TExcelString.Create(2, aSSTRecord, Ofs); //Ok, we use TExcelString... This could be done without creating an object, but I don't think there is a difference // and it's complicated, because it has to handle all continues and char-widechar issues try {GetMem(Entry, SizeOf(TExtraData)+Xs.TotalSize);} OldSize:=MemSST.UsedSize; inc( MemSST.UsedSize, SizeOf(TExtraData)+Xs.TotalSize); Lb:=Length(MemSST.Buffer); if MemSST.UsedSize>=Lb then SetLength(MemSST.Buffer, Lb+ MemSSTDeltaSize); //A string can't be longer than 8192 bytes; Entry:=OldSize; pEntry:=@MemSST.Buffer[OldSize]; PExtraData(pEntry).Refs:=0; PExtraData(pEntry).AbsStreamPos:=0; PExtraData(pEntry).RecordStreamPos:=0; PExtraData(pEntry).PosInTable:=0; Xs.CopyToPtr(pEntry, SizeOf(TExtraData)); finally FreeAndNil(Xs); end; end; function SSTLength(const S: PiSSTEntry): int64; var OptionFlags: byte; Ofs: integer; begin Ofs:=0; OptionFlags:=S[2+SizeOf(TExtraData)]; Result:=SizeOf(TExtraData)+ 2+ //Length SizeOf(OptionFlags); if OptionFlags and $1 = 0 then Result:=Result+GetWord(S, SizeOf(TExtraData)) else Result:= Result+GetWord(S, SizeOf(TExtraData))*2; //Rich text if OptionFlags and $8 = $8 {HasRichText} then begin Result:=Result + 2+ 4* GetWord(S,3+SizeOf(TExtraData)); Ofs:=2; end; //FarEast if OptionFlags and $4 = $4 {HasFarInfo} then Result:=Result+ 4 + GetLongWord(S, 3+SizeOf(TExtraData)+Ofs); end; {function SSTRealLength(const S: PiSSTEntry): int64; begin Result:=SSTLength(S)-SizeOf(TExtraData); end; } function CompareSSTEntry(const S1, S2: PiSSTEntry): integer; var i:integer; L1, L2: integer; begin Result:=0; L1:= SSTLength(S1); L2:= SSTLength(S2); if L1<L2 then Result:=-1 else if L1>L2 then Result:=1 else for i:=SizeOf(TExtraData) to L1-1 do begin if S1[i]=S2[i] then continue else if S1[i]<S2[i] then Result:=-1 else Result:=1; exit; end; end; function CompareSSTEntries(Item1, Item2: Pointer): Integer; begin CompareSSTEntries:= CompareSSTEntry(PiSSTEntry(Item1),PiSSTEntry(Item2)); end; procedure AddSSTRef(const Entry: PiSSTEntry); begin Inc(PExtraData(Entry).Refs); end; procedure DecSSTRef(const Entry: PiSSTEntry); begin Dec(PExtraData(Entry).Refs); end; function SSTRefs(const Entry: PiSSTEntry): word; begin Result:=PExtraData(Entry).Refs; end; procedure AddContinue (const DataStream: TOle2File; var Buffer: TRecordBuff; var BufferPos: integer; var BeginRecordPos: LongWord; var TotalSize: int64); begin if DataStream<>nil then begin SetWord(PArrayOfByte(@Buffer), 2, BufferPos - 4); //Adapt the record size before writing it. DataStream.WriteMem(Buffer, BufferPos); BeginRecordPos:=DataStream.Position; SetWord(PArrayOfByte(@Buffer), 0, xlr_CONTINUE); Buffer[4]:=0; Buffer[5]:=0; //Clear the OptionFlags. end; inc(TotalSize, BufferPos); BufferPos:= 4; end; function Min(const a, b: integer): integer; begin if a<b then Result:=a else Result:=b; end; procedure WriteArray(const DataToWrite: PArrayOfByte; const DataLength: integer; DataStream: TOle2File; var Buffer: TRecordBuff; var BufferPos: Integer; var BeginRecordPos: LongWord; var TotalSize: Int64); var Chars: Integer; BytesLeft: Integer; StPos: Integer; begin StPos := 0; while (StPos < DataLength) do begin BytesLeft := (Length(Buffer) - BufferPos) div 4 * 4; //A string can not be splitted between formatting runs. Chars := Min((DataLength - StPos), BytesLeft); System.Move(DataToWrite[StPos], Buffer[BufferPos], Chars); inc(BufferPos, Chars); inc(StPos, Chars); if (StPos < DataLength) then AddContinue(DataStream, Buffer, BufferPos, BeginRecordPos, TotalSize); end; end; procedure SaveSSTToStream(const Entry: PiSSTEntry; const DataStream: TOle2File; var BeginRecordPos: LongWord; var Buffer: TRecordBuff; var BufferPos: Integer; var TotalSize: Int64); var i: Integer; b: Byte; CanCompress: Boolean; CharsUncompressed: Integer; CharsCompressed: Integer; StPos: Integer; OpFlagsPos: Integer; BytesLeft: Integer; aLen: word; OptionFlags: byte; p: integer; FarEastLen: LongWord; RTFRuns: word; Data: PArrayOfByte; CharSize: integer; begin //First, see if we can write the header of this string on the current record, or if we have to create a new one BytesLeft := (Length(Buffer) - BufferPos); if (BytesLeft < 32) then //12 is really the required, but we play it safe. Anyway, starting a new continue does no harm. begin AddContinue(DataStream, Buffer, BufferPos, BeginRecordPos, TotalSize); BytesLeft := (Length(Buffer) - BufferPos); end; if (DataStream <> nil) then begin PExtraData(Entry).AbsStreamPos := (DataStream.Position + BufferPos); PExtraData(Entry).RecordStreamPos := PExtraData(Entry).AbsStreamPos - BeginRecordPos; end; Assert((BytesLeft >= 32)); aLen:=GetWord(Entry, SizeOf(TExtraData)); if (DataStream <> nil) then System.Move(aLen , Buffer[BufferPos], 2); inc(BufferPos,2); OpFlagsPos := BufferPos; OptionFlags:= Entry[2+SizeOf(TExtraData)]; Buffer[BufferPos] := OptionFlags; inc(BufferPos); p:=3; if OptionFlags and $8 = $8 then //HasRichText then begin RTFRuns:=GetWord(Entry,p+SizeOf(TExtraData)); if (DataStream <> nil) then begin System.Move(RTFRuns , Buffer[BufferPos], 2); end; inc(p,2); inc(BufferPos, 2); end; if OptionFlags and $4 = $4 then //HasFarInfo then begin FarEastLen:=GetLongWord(Entry,p+SizeOf(TExtraData)); if (DataStream <> nil) then begin System.Move(FarEastLen , Buffer[BufferPos], 4); end; inc(p,4); inc(BufferPos, 4); end; // Write the actual string. It might span multiple continues StPos := 0; Data:= PArrayOfByte(@Entry[p+SizeOf(TExtraData)]); CharSize:=(OptionFlags and 1)+1; while (StPos < aLen) do //If aLen==0, we won't write this string. begin BytesLeft := (Length(Buffer) - BufferPos); //Find if we can compress the unicode on this part. //If the number of chars we can write using compressed is bigger or equal than using uncompressed, we compress... CharsCompressed := Min((aLen - StPos), BytesLeft); CharsUncompressed := Min((aLen - StPos), (BytesLeft div 2)); if (CharSize <> 1) then //if charsize=1, string is already compressed. begin for i:= 0 to CharsCompressed-1 do begin if (Data[(StPos*CharSize + i*2+1)] <> 0) then begin CharsCompressed := i; break; end; end; end; CanCompress := (CharsCompressed >= CharsUncompressed); if CanCompress then begin b := $FE; Buffer[OpFlagsPos] := Buffer[OpFlagsPos] and b; if (DataStream <> nil) then begin for i := 0 to CharsCompressed-1 do begin Buffer[BufferPos] := Data[(StPos + i)*CharSize]; inc(BufferPos); end; end else inc(BufferPos, CharsCompressed); inc( StPos, CharsCompressed); if (StPos < aLen) then begin AddContinue(DataStream, Buffer, BufferPos, BeginRecordPos, TotalSize); OpFlagsPos := BufferPos; inc(BufferPos); end; end else begin b := 1; Buffer[OpFlagsPos] := Buffer[OpFlagsPos] or b; if (DataStream <> nil) then begin System.Move(Data[StPos*2], Buffer[BufferPos], 2*CharsUncompressed); end; inc (BufferPos, CharsUncompressed*2); inc (StPos, CharsUncompressed); if (StPos < aLen) then begin AddContinue(DataStream, Buffer, BufferPos, BeginRecordPos, TotalSize); OpFlagsPos := BufferPos; inc(BufferPos); end; end; end; inc(p, aLen*CharSize); if OptionFlags and $8 = $8 then //HasRichText then begin Data:= PArrayOfByte(@Entry[p+SizeOf(TExtraData)]); WriteArray(Data, RTFRuns*4, DataStream, Buffer, BufferPos, BeginRecordPos, TotalSize); p:=p+RTFRuns*4; end; if OptionFlags and $4 = $4 then //HasFarInfo then begin Data:= PArrayOfByte(@Entry[p+SizeOf(TExtraData)]); WriteArray(Data, FarEastLen, DataStream, Buffer, BufferPos, BeginRecordPos, TotalSize); end; end; function GetSSTValue(const Entry: PiSSTEntry; var RTFRunList: TRTFRunList): UTF16String; var OptionFlags: byte; Ini: integer; RTFRunCount: integer; i: integer; St: AnsiString; begin OptionFlags:=Entry[2+SizeOf(TExtraData)]; Ini:=SizeOf(TExtraData)+ 2+ //Length SizeOf(OptionFlags); //Rich text RTFRunCount:=0; if OptionFlags and $8 = $8 {HasRichText} then begin RTFRunCount:=GetWord(Entry, Ini); Inc(Ini, 2); end; //FarEast if OptionFlags and $4 = $4 {HasFarInfo} then Inc(Ini, 4); if OptionFlags and $1 = 0 then begin SetLength(St, GetWord(Entry, SizeOf(TExtraData))); Move(Entry[Ini], St[1], Length(St)); Inc(Ini, Length(St)); Result:=StringToWideStringNoCodePage(St); end else begin SetLength(Result, GetWord(Entry, SizeOf(TExtraData))); Move(Entry[Ini], Result[1], Length(Result)*2); Inc(Ini, Length(Result)*2); end; SetLength(RTFRunList, RTFRunCount); for i:=0 to RTFRunCount-1 do begin RTFRunList[i].FirstChar:=GetWord(Entry, Ini); RTFRunList[i].FontIndex:=GetWord(Entry, Ini+2); inc(Ini,4); end; end; //************************************************************** { TSST } function TSST.AddString(const s: UTF16String; const RTFRuns: TRTFRunList): integer; var es: TiSSTEntry; pEs: PiSSTEntry; LastMem: integer; begin LastMem:=MemSST.UsedSize; CreateSSTEntryFromString(MemSST, s, RTFRuns, es); try pEs:=@MemSST.Buffer[es]; if Find(pEs, Result) then begin AddSSTRef(@MemSST.Buffer[self[Result]]); MemSST.UsedSize:=LastMem; //No need to add space. end else begin Insert(Result, es); AddSSTRef(pEs); //es:=nil; //so we dont free it end; finally //No need to free. if es<>nil then Freemem(es); end; end; function TSST.Find(const S: PiSSTEntry; var Index: Integer): Boolean; var L, H, I, C: Integer; begin Result := False; L := 0; H := Count - 1; while L <= H do begin I := (L + H) shr 1; C := CompareSSTEntry(@MemSST.Buffer[self[I]],S); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; L := I; end; end; end; Index := L; end; procedure TSST.Load(const aSSTRecord: TSSTRecord); var i, Ofs:integer; Es: TiSSTEntry; TmpSSTRecord: TBaseRecord; begin Ofs:=8; TmpSSTRecord:= aSSTRecord; for i:=0 to aSSTRecord.Count-1 do begin CreateSSTEntryFromRecord(MemSST, TmpSSTRecord, Ofs, Es); try Add(Es); //Es:=nil; finally //No need to free. if es<>nil then Freemem(Es); end; //Finally end; //We can't sort now, this should be done after all the LABELSST records have been loaded end; procedure TSST.FixRefs; var i: integer; begin for i:=count-1 downto 0 do if SSTRefs(@MemSST.Buffer[self[i]])<=0 then Delete(i); end; procedure TSST.SaveToStream(const DataStream: TOle2File); var i:integer; TotalRefs, aCount: LongWord; BeginRecordPos: LongWord; Se: PiSSTEntry; Buffer: TRecordBuff; BufferPos: integer; TotalSize: int64; w:word; begin BeginRecordPos:=DataStream.Position; w:=xlr_SST; System.move(w, Buffer[0], 2); //Renum the items i:=0; TotalRefs:=0; while i< Count do begin Se:=@MemSST.Buffer[self[i]]; Assert(SSTRefs(Se)>0,'Refs should be >0'); PExtraData(Se).PosInTable:=i; TotalRefs:=TotalRefs+LongWord(SSTRefs(Se)); inc(i); end; System.move(TotalRefs, Buffer[4], 4); aCount:=Count; System.move(aCount, Buffer[8], 4); BufferPos:=4+8; TotalSize:=0; for i:= 0 to Count-1 do begin SaveSSTToStream(@MemSST.Buffer[Self[i]], DataStream, BeginRecordPos, Buffer, BufferPos, TotalSize); end; //Flush the buffer. SetWord(PArrayOfByte(@Buffer), 2, BufferPos - 4); //Adapt the record size before writing it. DataStream.WriteMem(Buffer, BufferPos); WriteExtSST(DataStream); end; procedure TSST.WriteExtSST(const DataStream: TOle2File); var n, nBuckets, Dummy: Word; i: integer; RecordHeader: TRecordHeader; begin // Calc number of strings per hash bucket n:=Count div 128+1; if n<8 then n:=8; if Count=0 then nBuckets:=0 else nBuckets:= (Count-1) div n + 1; RecordHeader.Id:= xlr_EXTSST; RecordHeader.Size:= 2+8*nBuckets; DataStream.WriteMem(RecordHeader, SizeOf(RecordHeader)); DataStream.WriteMem(n, SizeOf(n)); i:= 0; Dummy:=0; while i<Count do begin DataStream.WriteMem(PExtraData(@MemSST.Buffer[Self[i]]).AbsStreamPos, SizeOf(PExtraData(nil).AbsStreamPos)); DataStream.WriteMem(PExtraData(@MemSST.Buffer[Self[i]]).RecordStreamPos, SizeOf(PExtraData(nil).RecordStreamPos)); DataStream.WriteMem(Dummy, SizeOf(Dummy)); inc(i,n); end; end; procedure TSST.QuickSort(L, R: Integer); var I, J: Integer; P: Pointer; T: integer; begin repeat I := L; J := R; P := @MemSST.Buffer[self[(L + R) shr 1]]; repeat while CompareSSTEntries(@MemSST.Buffer[Self[I]], P) < 0 do Inc(I); while CompareSSTEntries(@MemSST.Buffer[Self[J]], P) > 0 do Dec(J); if I <= J then begin T := Self[I]; Self[I] := Self[J]; Self[J] := T; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(L, J); L := I; until I >= R; end; procedure TSST.Sort; begin if (Count > 0) then QuickSort(0, Count - 1); end; function TSST.ExtSSTRecordSize: int64; var n, nBuckets: word; begin n:=Count div 128+1; if n<8 then n:=8; if Count=0 then nBuckets:=0 else nBuckets:= (Count-1) div n + 1; Result:= 2+8*nBuckets+SizeOf(TRecordHeader); end; //Simulates a write to know how much it takes. function TSST.SSTRecordSize: int64; //Has to handle continue records var BeginRecordPos:LongWord; Buffer: TRecordBuff; BufferPos: integer; TotalSize: int64; i: integer; begin BeginRecordPos:=0; BufferPos:=4+8; TotalSize:=0; for i:=0 to Count-1 do begin SaveSSTToStream(@MemSST.Buffer[Self[i]], nil, BeginRecordPos, Buffer, BufferPos, TotalSize); end; Result:=TotalSize+BufferPos; end; function TSST.TotalSize: int64; begin Result:= SSTRecordSize + ExtSSTRecordSize; end; constructor TSST.Create; begin inherited; MemSST.UsedSize:=0; SetLength(MemSST.Buffer, MemSSTDeltaSize); end; function TSST.GetEntry(const aEntry: TiSSTEntry): PiSSTEntry; begin Result:=@MemSST.Buffer[aEntry]; end; { TLabelSSTRecord } constructor TLabelSSTRecord.Create(const aId: word; const aData: PArrayOfByte; const aDataSize: integer); begin inherited Create(aId, aData, aDataSize); end; procedure TLabelSSTRecord.AttachToSST(const aSST: TSST); var a:int64; begin SST:=aSST; a:=GetLongWord(Data,6); if a>= SST.Count then raise Exception.Create(ErrExcelInvalid); pSSTEntry:= SST[a]; AddSSTRef(SST.GetEntry(pSSTEntry)); end; destructor TLabelSSTRecord.Destroy; begin if (pSSTEntry>=0) and (SST <> nil) then DecSSTRef(SST.GetEntry(pSSTEntry)); inherited; end; procedure TLabelSSTRecord.SaveToStream(const Workbook: TOle2File); begin SetLongWord(Data, 6, PExtraData(SST.GetEntry(pSSTEntry)).PosInTable); inherited; end; function TLabelSSTRecord.DoCopyTo: TBaseRecord; begin Result:= inherited DoCopyTo; (Result as TLabelSSTRecord).SST:= SST; (Result as TLabelSSTRecord).pSSTEntry:= pSSTEntry; AddSSTRef(SST.GetEntry((Result as TLabelSSTRecord).pSSTEntry)); end; function TLabelSSTRecord.GetValue: Variant; begin Result:=GetAsString; end; procedure TLabelSSTRecord.SetValue(const Value: Variant); begin SetAsString(Value); end; function TLabelSSTRecord.GetAsString: UTF16String; var RTFRuns: TRTFRunList; begin Result:=GetSSTValue(SST.GetEntry(pSSTEntry), RTFRuns); end; procedure TLabelSSTRecord.SetAsString(const Value: UTF16String); var OldpSSTEntry: TiSSTEntry; begin OldpSSTEntry:=pSSTEntry; pSSTEntry:= SST[SST.AddString(Value, nil)]; if OldpSSTEntry>=0 then DecSSTRef(SST.GetEntry(OldpSSTEntry)); end; function TLabelSSTRecord.GetAsRichString: TRichString; begin Result.Value:=GetSSTValue(SST.GetEntry(pSSTEntry), Result.RTFRuns); end; procedure TLabelSSTRecord.SetAsRichString(const Value: TRichString); var OldpSSTEntry: TiSSTEntry; begin OldpSSTEntry:=pSSTEntry; pSSTEntry:= SST[SST.AddString(Value.Value, Value.RTFRuns)]; if OldpSSTEntry>=0 then DecSSTRef(SST.GetEntry(OldpSSTEntry)); end; constructor TLabelSSTRecord.CreateFromData(const aRow, aCol, aXF: word; const aSST: TSST); begin inherited CreateFromData(xlr_LABELSST, 10, aRow, aCol, aXF); SST:=aSST; pSSTEntry:=-1; end; function TLabelSSTRecord.GetAsRTF: UTF16String; begin //Todo: end; procedure TLabelSSTRecord.SetAsRTF(const Value: UTF16String); //var // OldpSSTEntry: TiSSTEntry; begin {TODO: OldpSSTEntry:=pSSTEntry; pSSTEntry:= SST[SST.AddString(Value)]; if OldpSSTEntry>=0 then DecSSTRef(SST.GetEntry(OldpSSTEntry)); } end; { TLabelRecord } function TLabelRecord.GetValue: Variant; var XS: TExcelString; MySelf: TBaseRecord; MyOfs: integer; begin MySelf:=Self; MyOfs:=6; XS:=TExcelString.Create(2, Myself, MyOfs); try Result:= XS.Value; finally FreeAndNil(XS); end; end; { TRStringRecord } function TRStringRecord.GetAsRichString: TRichString; var XS: TExcelString; MySelf: TBaseRecord; MyOfs: integer; d: array[0..1] of byte; i: integer; begin MySelf:=Self; MyOfs:=6; XS:=TExcelString.Create(2, Myself, MyOfs); try Result.Value:= XS.Value; finally FreeAndNil(XS); end; ReadMem(MySelf, MyOfs, 2, @d); SetLength(Result.RTFRuns, GetWord(@d, 0)); for i := 0 to Length(Result.RTFRuns) - 1 do begin ReadMem(MySelf, MyOfs, 2, @d); Result.RTFRuns[i].FirstChar := GetWord(@d,0); ReadMem(MySelf, MyOfs, 2, @d); Result.RTFRuns[i].FontIndex := GetWord(@d,0); end; end; function TRStringRecord.GetValue: Variant; var XS: TExcelString; MySelf: TBaseRecord; MyOfs: integer; begin MySelf:=Self; MyOfs:=6; XS:=TExcelString.Create(2, Myself, MyOfs); try Result:= XS.Value; finally FreeAndNil(XS); end; end; end.
unit fmuFullStatus; interface uses // VCL Windows, Forms, ComCtrls, StdCtrls, Controls, Classes, SysUtils, Messages, Buttons, Dialogs, // This untPages, untUtil, untDriver, untTypes, GlobalConst; type { TfmFullStatus } TfmFullStatus = class(TPage) Memo: TMemo; btnFullEcrStatus: TButton; btnSaveToFile: TBitBtn; dlgSave: TSaveDialog; btnInterrupt: TButton; procedure btnFullEcrStatusClick(Sender: TObject); procedure btnSaveToFileClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnInterruptClick(Sender: TObject); private FStop: Boolean; procedure AddTables; procedure AddSeparator; procedure AddDeviceFlags; procedure AddFullStatus; procedure AddShortStatus; procedure AddDeviceMetrics; procedure AddCashTotalizers; procedure AddWorkTotalizers; procedure AddLine(V1, V2: Variant); procedure Check2(AResultCode: Integer); procedure AddMemoLine(const S: string); procedure AddBool(const ValueName: string; Value: Boolean); procedure AddLineWidth(V1, V2: Variant; TextWidth: Integer); end; { EStopException } EStopException = class(Exception); implementation {$R *.DFM} { TfmFullStatus } const DescriptionWidth = 33; procedure TfmFullStatus.AddMemoLine(const S: string); begin Memo.Lines.Add(' ' + S); end; procedure TfmFullStatus.AddLineWidth(V1, V2: Variant; TextWidth: Integer); begin AddMemoLine(Format('%-*s: %s', [TextWidth, String(V1), String(V2)])); end; procedure TfmFullStatus.AddLine(V1, V2: Variant); begin AddLineWidth(V1, V2, 24); end; procedure TfmFullStatus.AddBool(const ValueName: string; Value: Boolean); const BoolToStr: array [Boolean] of string = ('[нет]', '[да]'); begin AddLineWidth(ValueName, BoolToStr[Value], DescriptionWidth); end; procedure TfmFullStatus.AddSeparator; begin AddMemoLine(StringOfChar('-', 52)); end; procedure TfmFullStatus.AddDeviceFlags; begin AddSeparator; AddLine('Флаги', Format('%.4xh, %d', [Driver.ECRFlags, Driver.ECRFlags])); AddSeparator; AddBool('Увеличенная точность количества', Driver.QuantityPointPosition); AddBool('Бумага на выходе из накопителя', Driver.PresenterOut); AddBool('Бумага на входе в накопитель', Driver.PresenterIn); AddBool('ЭКЛЗ почти заполнена', Driver.IsEKLZOverflow); AddBool('Денежный ящик открыт', Driver.IsDrawerOpen); AddBool('Крышка корпуса поднята', Driver.LidPositionSensor); AddBool('Рычаг термоголовки чека опущен', Driver.ReceiptRibbonLever); AddBool('Рычаг термоголовки журнала опущен', Driver.JournalRibbonLever); AddBool('Оптический датчик чека', Driver.ReceiptRibbonOpticalSensor); AddBool('Оптический датчик журнала', Driver.JournalRibbonOpticalSensor); AddBool('ЭКЛЗ есть', Driver.EKLZIsPresent); AddBool('2 знака после запятой в цене', Driver.PointPosition); AddBool('Нижний датчик ПД', Driver.SlipDocumentIsPresent); AddBool('Верхний датчик ПД', Driver.SlipDocumentIsMoving); AddBool('Рулон чековой ленты', Driver.ReceiptRibbonIsPresent); AddBool('Рулон контрольной ленты', Driver.JournalRibbonIsPresent); end; procedure TfmFullStatus.AddFullStatus; begin Check2(Driver.GetDeviceMetrics); Check2(Driver.GetECRStatus); Memo.Lines.Add(''); AddSeparator; Memo.Lines.Add(' Запрос состояния:'); AddSeparator; Memo.Lines.Add(' Режим: '); Memo.Lines.Add(' ' + Format('%d, %s', [Driver.ECRMode, Driver.ECRModeDescription])); // ПО принтера AddSeparator; AddLine('Версия ПО', Driver.ECRSoftVersion); AddLine('Сборка ПО', Driver.ECRBuild); AddLine('Дата ПО', Driver.ECRSoftDate); // ПО ФП AddSeparator; AddLine('Версия ПО ФП', Driver.FMSoftVersion); AddLine('Сборка ПО ФП', Driver.FMBuild); AddLine('Дата ПО ФП', Driver.FMSoftDate); // Режимы AddSeparator; AddLine('Подрежим ' + DeviceName, Format('%d, %s', [Driver.ECRAdvancedMode, Driver.ECRAdvancedModeDescription])); AddLine('Статус режима', Driver.ECRModeStatus); AddLine('Номер в зале', Driver.LogicalNumber); AddLine('Номер документа', Driver.OpendocumentNumber); AddLine('Порт ' + DeviceName, Driver.PortNumber); AddLine('Количество фискализаций', Driver.RegistrationNumber); AddLine('Осталось фискализаций', Driver.FreeRegistration); AddLine('Последняя закрытая смена', Driver.SessionNumber); AddLine('Свободных записей в ФП', Driver.FreeRecordInFM); AddLine('Дата', Driver.Date); AddLine('Время', Driver.Time); AddLine('Заводской номер', GetSerialNumber(Driver.SerialNumber)); AddLine('ИНН', GetINN(Driver.INN)); // Флаги устройства AddDeviceFlags; // Флаги ФП AddSeparator; AddLine('Флаги ФП', Format('%.2xh, %d', [Driver.FMFlags, Driver.FMFlags])); AddSeparator; AddBool('24 часа в ФП кончились', Driver.IsFM24HoursOver); AddBool('Смена в ФП открыта', Driver.IsFMSessionOpen); AddBool('Последняя запись в ФП повреждена', Driver.IsLastFMRecordCorrupted); AddBool('Батарея ФП заряжена более 80 %', Driver.IsBatteryLow); AddBool('Переполнение ФП', Driver.FMOverflow); AddBool('Лицензия введена', Driver.LicenseIsPresent); AddBool('ФП 2 есть', Driver.FM2IsPresent); AddBool('ФП 1 есть', Driver.FM1IsPresent); AddSeparator; // Прокручиваем Memo на начало Memo.SelStart := 0; Memo.SelLength := 0; end; procedure TfmFullStatus.AddShortStatus; begin Check2(Driver.GetDeviceMetrics); Check2(Driver.GetShortECRStatus); Memo.Lines.Add(''); AddSeparator; Memo.Lines.Add(' Краткий запрос состояния:'); AddSeparator; Memo.Lines.Add(' Режим:'); Memo.Lines.Add(Format(' %d, %s', [Driver.ECRMode, Driver.ECRModeDescription])); AddSeparator; AddLine('Подрежим ' + DeviceName, Format('%d, %s', [Driver.ECRAdvancedMode, Driver.ECRAdvancedModeDescription])); AddLine('Статус режима', Driver.ECRModeStatus); AddLine('Количество операций в чеке', Driver.QuantityOfOperations); AddLine('Напряжение батареи, В', Driver.BatteryVoltage); AddLine('Напряжение источника, В', Driver.PowerSourceVoltage); AddLine('Ошибка ФП', Driver.FMResultCode); AddLine('Ошибка ЭКЛЗ', Driver.EKLZResultCode); // Флаги устройства AddDeviceFlags; AddSeparator; // Прокручиваем Memo на начало Memo.SelStart := 0; Memo.SelLength := 0; end; procedure TfmFullStatus.AddDeviceMetrics; begin Check2(Driver.GetDeviceMetrics); Memo.Lines.Add(''); AddSeparator; Memo.Lines.Add(' Параметры устройства:'); AddSeparator; Memo.Lines.Add(' Кодовая страница : '+ IntToStr(Driver.UCodePage)); Memo.Lines.Add(' Описание устройства : '+ Driver.UDescription); Memo.Lines.Add(' Версия протокола : '+ IntToStr(Driver.UMajorProtocolVersion)); Memo.Lines.Add(' Подверсия протокола : '+ IntToStr(Driver.UMinorProtocolVersion)); Memo.Lines.Add(' Тип устройства : '+ IntToStr(Driver.UMajorType)); Memo.Lines.Add(' Подтип устройства : '+ IntToStr(Driver.UMinorType)); Memo.Lines.Add(' Модель устройства : '+ IntToStr(Driver.UModel)); end; procedure TfmFullStatus.btnFullEcrStatusClick(Sender: TObject); begin EnableButtons(False); try FStop := False; btnInterrupt.Enabled := True; Memo.Clear; Memo.Lines.Add(''); AddSeparator; Memo.Lines.Add(' Полное состояние'); AddSeparator; try AddFullStatus; AddShortStatus; AddDeviceMetrics; AddTables; AddCashTotalizers; AddWorkTotalizers; AddSeparator; // Прокручиваем Memo на начало Memo.SelStart := 0; Memo.SelLength := 0; except on E: EAbort do Memo.Lines.Add(Format('<Прервано в связи с ошибкой: %d (%s)>', [Driver.ResultCode, Driver.ResultCodeDescription])); on E: EStopException do Memo.Lines.Add(E.Message) end; finally EnableButtons(True); FStop := True; end; end; procedure TfmFullStatus.btnSaveToFileClick(Sender: TObject); begin if not dlgSave.Execute then Exit; Memo.Lines.SaveToFile(dlgSave.FileName); end; procedure TfmFullStatus.AddCashTotalizers; procedure AddCaption(S: string); begin Memo.Lines.Add(''); Memo.Lines.Add(S); Memo.Lines.Add(' ' + StringOfChar('-', 52)); end; procedure AddCashRegisters(S: string; L: Integer; H: Integer); var i: Integer; RegisterName: string; begin AddCaption(S); for i := L to H do begin Driver.RegisterNumber := i; Check2(Driver.GetCashReg); if i in [0..High(CashRegisterName)] then RegisterName := CashRegisterName[i] else RegisterName := ''; Memo.Lines.Add(Format(' %3d.%-44s : %s', [i+1, RegisterName, CurrToStr(Driver.ContentsOfCashRegister)])) end; end; begin Memo.Lines.Add(''); AddSeparator; Memo.Lines.Add(' ДЕНЕЖНЫЕ РЕГИСТРЫ:'); AddSeparator; AddCashRegisters(' Накопление:', $00, $57); AddCashRegisters(' Оборот по:', $58, $67); AddCashRegisters(' Накопления по:', $68, $77); AddCashRegisters(' Наличность:', $78, $78); AddCashRegisters(' Накопление:', $79, $D0); AddCashRegisters(' Оборот по:', $D1, $E0); AddCashRegisters(' Накопления по:', $E1, $F0); AddCashRegisters(' Накопление:', $F1, $F3); AddCashRegisters(' Необнуляемая сумма:', $F4, $F4); AddCashRegisters(' Сумма:', $F5, $F8); end; procedure TfmFullStatus.AddWorkTotalizers; procedure AddCaption(S: string); begin Memo.Lines.Add(''); Memo.Lines.Add(S); Memo.Lines.Add(' ' + StringOfChar('-', 52)); end; procedure AddOperationRegisters(S: string; L: Integer; H: Integer); var i: Integer; RegisterName: string; begin AddCaption(S); for i := L to H do begin Driver.RegisterNumber := i; Check2(Driver.GetOperationReg); if i in [0..High(OperationRegisterName)] then RegisterName := OperationRegisterName[i] else RegisterName := ''; Memo.Lines.Add(Format(' %3d.%-44s : %s', [i+1, RegisterName, CurrToStr(Driver.ContentsOfOperationRegister)])) end; end; begin Memo.Lines.Add(''); AddSeparator; Memo.Lines.Add(' ОПЕРАЦИОННЫЕ РЕГИСТРЫ:'); AddSeparator; AddOperationRegisters(' Количество:', $00, $93); AddOperationRegisters(' Номер:', $94, $97); AddOperationRegisters(' Сквозной номер', $98, $98); AddOperationRegisters(' Количество:', $99, $9A); AddOperationRegisters(' Номер:', $9B, $9C); AddOperationRegisters(' Количество:', $9D, $9D); AddOperationRegisters(' Номер:', $9E, $A5); AddOperationRegisters(' Количество:', $A6, $A8); AddOperationRegisters(' Количество отчетов по:', $A9, $B0); AddOperationRegisters(' Количество :', $B1, $B1); AddOperationRegisters(' Номер отчета по :', $B2, $B2); end; procedure TfmFullStatus.AddTables; function AddTable(ATableNumber: Integer): Integer; var Row: Integer; Field: Integer; RowN: Integer; FieldN: Integer; FieldName: string; begin Check2(0); Driver.TableNumber := ATableNumber; Result := Driver.GetTableStruct; if Result <> 0 then Exit; RowN := Driver.RowNumber; FieldN := Driver.FieldNumber; Memo.Lines.Add(''); AddSeparator; Memo.Lines.Add(Format(' ТАБЛИЦА %d. %s. Рядов:%d Полей:%d', [Driver.TableNumber, Driver.TableName, RowN, FieldN])); Memo.Lines.Add(' Ряд.Поле. Наименование:Значение'); AddSeparator; Driver.TableNumber := ATableNumber; Result := Driver.GetTableStruct; if (Result <> 0) then Exit; RowN := Driver.RowNumber; FieldN := Driver.FieldNumber; for Row := 1 to RowN do begin Driver.RowNumber := Row; for Field := 1 to FieldN do begin Check2(0); Driver.FieldNumber := Field; Result := Driver.GetFieldStruct; if Result <> 0 then Exit; FieldName := Driver.FieldName; Result := Driver.ReadTable; if Result <> 0 then Exit; Memo.Lines.Add(Format(' %.2d.%.2d. %s:%s', [Row, Field, FieldName, Driver.ValueOfFieldString])); Driver.FieldName; end; AddSeparator; end; end; var i: Integer; Res: Integer; begin Memo.Lines.Add(''); AddSeparator; Memo.Lines.Add(' ТАБЛИЦЫ:'); AddSeparator; i := 1; Res := 0; while True do begin Res := AddTable(i); if (Res <> 0) then Break; Inc(i); end; if Res = $5D then Res := 0; Check(Res); end; procedure TfmFullStatus.FormCreate(Sender: TObject); begin FStop := False; end; procedure TfmFullStatus.btnInterruptClick(Sender: TObject); begin FStop := True; end; procedure TfmFullStatus.Check2(AResultCode: Integer); begin Application.ProcessMessages; if FStop then raise EStopException.Create('<Прервано пользователем>'); Check(AResultCode); end; end.
unit uENetClass; { ENet UDP Class for FreePascal Copyright (c) 2013 Do-wan Kim Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - Add SendMsgEventPeer } {$mode objfpc}{$H+} interface uses Classes, SysUtils, enet_consts, enet_peer, enet_host, enet_packet, enet_socket, enet_protocol; type TENet_Event_Type = (ENetEventNone, ENetEventConnect, ENetEventDisConnect, ENetEventReceive); TENetPacketFlag = (ENetPacketReliable, ENetPacketUnsequenced, ENetPacketNoAllocate, ENetPacketUnReliableFragment); TENetPacketFlags = set of TENetPacketFlag; TENetEventProc = procedure (const Event:ENetEvent) of object; TENetEventRecv = procedure (const Event:ENetEvent; var BroadcastMsg : Boolean; var BroadcastChannel : Byte) of object; { TENetClass } TENetClass = class private FInit : Boolean; FHostname : string; FAddress : ENetAddress; FIsServer : Boolean; FMaxPeer : Cardinal; FMaxChannels : Byte; FBandwidthIncoming, FBandwidthOutgoing : Cardinal; FHost : pENetHost; FEvent : ENetEvent; FPeer : pENetPeer; FClientData : Cardinal; FConnectTimeout : Cardinal; FMessageTimeout : Cardinal; FEventNone : TENetEventProc; FEventConnect : TENetEventProc; FEventDisConnect : TENetEventProc; FEventReceive : TENetEventRecv; protected public constructor Create(Port : word; bServer : Boolean); destructor Destroy; override; function InitHost:Boolean; procedure DeInitHost; function Connect(const Host: string; Port: Word): Boolean; function DisConnect(bNow: Boolean): Boolean; function SendMsg(Channel: Byte; Data: Pointer; Length: Integer; flag: TENetPacketFlags; WaitResponse: Boolean = False): Boolean; function SendMsgEventPeer(Data: Pointer; Length: Integer; flag: TENetPacketFlags; WaitResponse: Boolean=False): Boolean; procedure FlushMsg; function BroadcastMsg(Channel: Byte; Data: Pointer; Length: Integer; flag: TENetPacketFlags; WaitResponse : Boolean = False):Boolean; function ProcessMsg:Boolean; virtual; procedure Ping; property Port : Word read FAddress.port write FAddress.port; property MaxClient : Cardinal read FMaxPeer write FMaxPeer; property MaxChannels : Byte read FMaxChannels write FMaxChannels; property BandwidthIncoming : Cardinal read FBandwidthIncoming write FBandwidthIncoming; property BandwidthOutgoing : Cardinal read FBandwidthOutgoing write FBandwidthOutgoing; property ClientData : Cardinal read FClientData; property ConnectTimeout : Cardinal read FConnectTimeout write FConnectTimeout; property MessageTimeout : Cardinal read FMessageTimeout write FMessageTimeout; property OnNone : TENetEventProc read FEventNone write FEventNone; property OnConnect : TENetEventProc read FEventConnect write FEventConnect; property OnDisconnect : TENetEventProc read FEventDisConnect write FEventDisConnect; property OnReceive : TENetEventRecv read FEventReceive write FEventReceive; end; implementation function GetPacketFlag(flag:TENetPacketFlags):Integer; begin Result:=0; if ENetPacketReliable in flag then Inc(Result,ENET_PACKET_FLAG_RELIABLE); if ENetPacketUnsequenced in flag then Inc(Result,ENET_PACKET_FLAG_UNSEQUENCED); if ENetPacketNoAllocate in flag then Inc(Result,ENET_PACKET_FLAG_NO_ALLOCATE); if ENetPacketUnReliableFragment in flag then Inc(Result,ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT); end; { TENetClass } constructor TENetClass.Create(Port: word; bServer: Boolean); begin FAddress.port:=Port; FMaxPeer:=100; FMaxChannels:=255; FBandwidthIncoming:=0; FBandwidthOutgoing:=0; FIsServer:=False; FConnectTimeout:=5000; FMessageTimeout:=100; FHost:=nil; FPeer:=nil; FEventNone:=nil; FEventConnect:=nil; FEventDisConnect:=nil; FEventReceive:=nil; FIsServer:=bServer; FInit := enet_initialize = 0; end; destructor TENetClass.Destroy; begin DisConnect(True); if FInit then enet_deinitialize; inherited Destroy; end; function TENetClass.InitHost: Boolean; begin DeInitHost; if FInit then if FIsServer then begin // for server FAddress.host:=ENET_HOST_ANY; FHost:=enet_host_create(@FAddress, FMaxPeer, FMaxChannels, FBandwidthIncoming, FBandwidthOutgoing ); end else begin // for client FMaxPeer:=1; FHost:=enet_host_create(nil, FMaxPeer, FMaxChannels, FBandwidthIncoming, FBandwidthOutgoing ); end; Result:= FHost<>nil; end; procedure TENetClass.DeInitHost; begin if FHost<>nil then enet_host_destroy(FHost); FHost:=nil; end; function TENetClass.Connect(const Host: string; Port: Word): Boolean; begin Result:=False; if not FIsServer then begin DisConnect(True); InitHost; enet_address_set_host(@FAddress,PAnsiChar(Host)); FAddress.port:=Port; FClientData:=Random(MaxInt); FPeer:=enet_host_connect(FHost,@FAddress,FMaxChannels,FClientData); Result:=FPeer<>nil; if Result then if (enet_host_service(FHost,@FEvent,FConnectTimeout)>0) and (FEvent.EventType=ENET_EVENT_TYPE_CONNECT) then begin Result:=True; if Assigned(FEventConnect) then FEventConnect(FEvent); end else begin enet_peer_reset(FPeer); FPeer:=nil; DeInitHost; end; end; end; function TENetClass.DisConnect(bNow:Boolean): Boolean; begin Result:=False; if (not FIsServer) and (FHost<>nil) then begin if FPeer<>nil then begin if bNow then enet_peer_disconnect_now(FPeer,FClientData) else enet_peer_disconnect(FPeer,FClientData); FPeer:=nil; end; Result:=True; end; DeInitHost; end; function TENetClass.SendMsg(Channel: Byte; Data: Pointer; Length: Integer; flag: TENetPacketFlags; WaitResponse: Boolean): Boolean; var FPacket : pENetPacket; PacketFlag : Cardinal; begin Result:=False; if FPeer<>nil then begin PacketFlag:=GetPacketFlag(flag); FPacket := enet_packet_create(Data, Length, PacketFlag); if enet_peer_send(FPeer,Channel,FPacket)=0 then if WaitResponse then Result:=ProcessMsg; end; end; function TENetClass.SendMsgEventPeer(Data: Pointer; Length: Integer; flag: TENetPacketFlags; WaitResponse: Boolean = False): Boolean; var FPacket : pENetPacket; PacketFlag : Cardinal; begin Result:=False; if FEvent.Peer<>nil then begin PacketFlag:=GetPacketFlag(flag); FPacket := enet_packet_create(Data, Length, PacketFlag); if enet_peer_send(FEvent.Peer,FEvent.channelID,FPacket)=0 then if WaitResponse then Result:=ProcessMsg; end; end; procedure TENetClass.FlushMsg; begin if FHost<>nil then enet_host_flush(FHost); end; function TENetClass.BroadcastMsg(Channel: Byte; Data: Pointer; Length: Integer; flag: TENetPacketFlags; WaitResponse: Boolean): Boolean; var FPacket : pENetPacket; PacketFlag : Cardinal; begin Result:=False; if FPeer<>nil then begin PacketFlag:=GetPacketFlag(flag); FPacket:= enet_packet_create(Data, Length, PacketFlag); enet_host_broadcast(FHost,Channel,FPacket); if WaitResponse then Result:=ProcessMsg; end; end; function TENetClass.ProcessMsg: Boolean; var broadcast : Boolean; bdChannel : Byte; packet : pENetPacket; pflag : Integer; begin Result := False; if FHost<>nil then if enet_host_service(FHost,@FEvent,FMessageTimeout)>0 then begin case FEvent.EventType of ENET_EVENT_TYPE_NONE : if Assigned(FEventNone) then FEventNone(FEvent); ENET_EVENT_TYPE_CONNECT : if Assigned(FEventConnect) then FEventConnect(FEvent); ENET_EVENT_TYPE_DISCONNECT : if Assigned(FEventDisConnect) then FEventDisConnect(FEvent); ENET_EVENT_TYPE_RECEIVE : begin try if FIsServer then begin broadcast:=True; pflag:=FEvent.packet^.flags; bdChannel:= FEvent.channelID; end; if Assigned(FEventReceive) then FEventReceive(FEvent,broadcast,bdChannel); if FIsServer and broadcast then begin packet := enet_packet_create(FEvent.packet^.data,FEvent.packet^.dataLength,pflag); enet_host_broadcast(FHost,bdChannel,packet); end; finally enet_packet_destroy(FEvent.packet); end; end; else ; end; Result := True; end; end; procedure TENetClass.Ping; begin if (not FIsServer) and (FPeer<>nil) then enet_peer_ping(FPeer); end; end.
Program Aufgabe4; {$codepage utf8} Var Eingabe: String; LangerName: String; Fehler: Boolean = False; Begin Write('Bitte gib die Kurzform des Wochentags ein: '); Read(Eingabe); Case Eingabe Of 'mo': LangerName := 'Montag'; 'di': LangerName := 'Dienstag'; 'mi': LangerName := 'Mittwoch'; 'do': LangerName := 'Donnerstag'; 'fr': LangerName := 'Freitag'; 'sa': LangerName := 'Samstag'; 'so': LangerName := 'Sonntag'; Else Fehler := True; End; If Fehler Then WriteLn('Es gab einen Fehler bei der Eingabe!') Else WriteLn('Der lange Name des Wochentags ist ', LangerName, '.'); End.
unit ConflictsMeta; {$mode objfpc}{$H+} interface uses Classes, SysUtils, sqldb, FileUtil, MetaData, bddatamodule, Dialogs; type TConflictPairs = array of TPoint; TConflict = class FName: string; FEqual, FUnequal: array of integer; constructor Create(AName: string; AEqual, AUnequal: array of integer); end; { TConflictsModule } TConflictsModule = class(TDataModule) ConflictsSQLQuery: TSQLQuery; public ConflictPairs: array of TConflictPairs; procedure AddConflict(AName: string; AEqual, AUnequal: array of integer); function MakeQuery(AID: integer): string; function GetConflictPairs(AID: integer): TConflictPairs; procedure Refresh_conflicts(); end; var ConflictsModule: TConflictsModule; Conflicts: array of TConflict; implementation constructor TConflict.Create(AName: string; AEqual, AUnequal: array of integer); var i: integer; begin FName := AName; SetLength(FEqual, Length(AEqual)); SetLength(FUnequal, Length(AUnequal)); for i := 0 to High(AEqual) do FEqual[i] := AEqual[i]; for i := 0 to High(AUnequal) do FUnequal[i] := AUnequal[i]; end; procedure TConflictsModule.AddConflict(AName: string; AEqual, AUnequal: array of integer); var i: integer; begin SetLength(Conflicts, Length(Conflicts) + 1); Conflicts[High(Conflicts)] := TConflict.Create(AName, AEqual, AUnequal); SetLength(ConflictPairs, Length(ConflictPairs) + 1); ConflictPairs[High(ConflictPairs)] := GetConflictPairs(High(Conflicts)); end; function TConflictsModule.MakeQuery(AID: integer): string; var i: integer; q, pairs: string; currConf: TConflict; begin currConf := Conflicts[AID]; q := 'SELECT A.*, B.* FROM Schedule_Items A INNER JOIN Schedule_Items B ON '; pairs := ''; for i := 0 to High(currConf.FEqual) do with Schedule_Table.FFields[currConf.FEqual[i]] do pairs += Format('AND A.%s = B.%s ', [FName, FName]); for i := 0 to High(currConf.FUnequal) do with Schedule_Table.FFields[currConf.FUnequal[i]] do pairs += Format('AND A.%s <> B.%s ', [FName, FName]); Delete(pairs, 1, 4); pairs += 'AND A.ID < B.ID'; q += pairs; Result := q; end; function TConflictsModule.GetConflictPairs(AID: integer): TConflictPairs; var tmpPairs: TConflictPairs; begin with ConflictsSQLQuery do begin Close; SQL.Clear; SQL.Text := MakeQuery(AID); Open; First; while not EOF do begin SetLength(tmpPairs, Length(tmpPairs) + 1); tmpPairs[High(tmpPairs)].x := Fields[0].AsInteger; tmpPairs[High(tmpPairs)].y := Fields[Length(Schedule_Table.FFields)].AsInteger; Next; end; end; Result := tmpPairs; end; procedure TConflictsModule.Refresh_conflicts; var i: integer; begin for i := 0 to High(Conflicts) do Conflicts[i].Destroy; SetLength(Conflicts,0); SetLength(ConflictPairs,0); AddConflict('Преподаватель в разных аудиториях', [2, 4, 3], [6]); AddConflict('Разные пары в одной аудитории', [4, 3, 6], [2]); AddConflict('Группа в разных аудиториях', [4, 3, 5], [6]); AddConflict('Группа на разных дициплинах', [4, 3, 5], [1]); AddConflict('Преподаватель на разных дисциплинах', [2, 4, 3], [1]); AddConflict('Дублирующися пары', [1, 2, 3, 4, 5, 6], []); end; {$R *.lfm}end.
{***********************************************************************} { TPLANNERCALENDAR component } { for Delphi & C++Builder } { } { written by : } { TMS Software } { copyright © 1999-2012 } { Email : info@tmssoftware.com } { Website : http://www.tmssoftware.com } {***********************************************************************} unit PlannerCalReg; interface {$I TMSDEFS.INC} uses PlannerCal, PlannerDatePicker, PlannerMaskDatePicker, Classes; procedure Register; implementation procedure Register; begin RegisterComponents('TMS Planner', [TPlannerCalendar, TPlannerCalendarGroup, TPlannerDatePicker, TPlannerMaskDatePicker]); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpFilterStream; {$I ..\..\Include\CryptoLib.inc} interface uses Classes, ClpStreamHelper, ClpDefiniteLengthInputStream; type TFilterStream = class(TStream) protected var Fs: TStream; function GetPosition: Int64; {$IFDEF FPC} override; {$ENDIF FPC} procedure SetPosition(const Value: Int64); {$IFDEF FPC} override; {$ENDIF FPC} function GetSize: Int64; override; public constructor Create(const s: TStream); property Size: Int64 read GetSize; property Position: Int64 read GetPosition write SetPosition; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; function Read(var Buffer; Count: LongInt): LongInt; override; function Write(const Buffer; Count: LongInt): LongInt; override; function ReadByte(): Int32; procedure WriteByte(Value: Byte); end; implementation uses // included here to avoid circular dependency :) ClpStreamSorter; { TFilterStream } constructor TFilterStream.Create(const s: TStream); begin inherited Create(); Fs := s; end; function TFilterStream.GetPosition: Int64; begin Result := Fs.Position; end; procedure TFilterStream.SetPosition(const Value: Int64); begin Fs.Position := Value; end; function TFilterStream.Write(const Buffer; Count: LongInt): LongInt; begin Result := Fs.Write(PByte(Buffer), Count); end; procedure TFilterStream.WriteByte(Value: Byte); begin Fs.WriteByte(Value); end; function TFilterStream.GetSize: Int64; begin Result := Fs.Size; end; function TFilterStream.Read(var Buffer; Count: LongInt): LongInt; begin Result := Fs.Read(PByte(Buffer), Count); end; function TFilterStream.ReadByte: Int32; begin Result := TStreamSorter.ReadByte(Fs); end; function TFilterStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin Result := Fs.Seek(Offset, Origin); end; end.
unit Editor; {$mode objfpc}{$H+} interface uses Classes, Windows, SysUtils, FileUtil, SynEdit, SynHighlighterAny, SynCompletion, Forms, Controls, ComCtrls, ExtCtrls, StdCtrls, Menus, Global, Dialogs, Types, LCLType, Graphics; type { TEditorFrame } TEditorFrame = class(TFrame) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; CheckBox1: TCheckBox; CheckBox2: TCheckBox; Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; MenuItem1: TMenuItem; MenuItem10: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; MenuItem8: TMenuItem; MenuItem9: TMenuItem; ReplaceDlgPanel: TPanel; ImageList1: TImageList; FindDlgPanel: TPanel; PopupMenu1: TPopupMenu; SaveDialog1: TSaveDialog; SynAnySyn1: TSynAnySyn; SynCompletion: TSynCompletion; SelfTab: TTabSheet; SelfStates: TStatusBar; CWUpdateTimer: TTimer; SynEdit: TSynEdit; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); constructor CreateEditor(TabSheet:TTabSheet; StatusBar:TStatusBar; OpenOp:TOpenOp; OpenParam:string); procedure CWUpdateTimerTimer(Sender: TObject); destructor Destroy; override; procedure FindDlg; procedure MenuItem10Click(Sender: TObject); procedure MenuItem1Click(Sender: TObject); procedure MenuItem2Click(Sender: TObject); procedure MenuItem4Click(Sender: TObject); procedure MenuItem5Click(Sender: TObject); procedure MenuItem7Click(Sender: TObject); procedure MenuItem8Click(Sender: TObject); procedure MenuItem9Click(Sender: TObject); procedure ReplaceDlg; procedure SynCompletionCodeCompletion(var Value: string; SourceValue: string; var SourceStart, SourceEnd: TPoint; KeyChar: TUTF8Char; Shift: TShiftState); function SynCompletionPaintItem(const AKey: string; ACanvas: TCanvas; X, Y: integer; Selected: boolean; Index: integer): boolean; procedure SynEditChange(Sender: TObject); procedure SynEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState ); procedure SynEditMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure UpdateState; function CW_MakeDescr(wrd, descr, infile:string):string; procedure CW_Add(s:string); procedure CW_Update; procedure CW_ParseFile(fp:string); private CW_ParsedFiles, CW_Lst:TStringList; CW_MaxWordLen, CW_MaxDescrLen, CW_LastMaxWordLen, CW_LastMaxDescrLen:word; public DefFile:string; Saved:boolean; end; implementation {$R *.lfm} constructor TEditorFrame.CreateEditor(TabSheet:TTabSheet; StatusBar:TStatusBar; OpenOp:TOpenOp; OpenParam:string); begin inherited Create(SelfTab); CW_ParsedFiles := TStringList.Create; CW_Lst := TStringList.Create; CW_MaxWordLen := 0; CW_MaxDescrLen := 0; CW_LastMaxWordLen := 0; CW_LastMaxDescrLen := 0; Self.Parent := SelfTab; SelfTab := TabSheet; SelfStates := StatusBar; Saved := False; case OpenOp of opopOpen: begin SynEdit.Lines.LoadFromFile(OpenParam); Saved := True; CW_ParseFile(OpenParam); end; end; DefFile := OpenParam; FindDlgPanel.Visible := False; ReplaceDlgPanel.Visible := False; SynEdit.SetFocus; end; procedure TEditorFrame.CWUpdateTimerTimer(Sender: TObject); begin if FileExists(DefFile) then begin CW_ParsedFiles.Clear; CW_Lst.Clear; CW_MaxWordLen := 0; CW_MaxDescrLen := 0; CW_ParseFile(DefFile); CW_Update; end; end; destructor TEditorFrame.Destroy; begin FreeAndNil(CW_ParsedFiles); FreeAndNil(CW_Lst); inherited; end; procedure TEditorFrame.Button2Click(Sender: TObject); begin FindDlgPanel.Visible := False; end; procedure TEditorFrame.Button3Click(Sender: TObject); begin if CheckBox2.Checked then SynEdit.Text := StringReplace(SynEdit.Text, Edit2.Text, Edit3.Text,[]) else SynEdit.Text := StringReplace(SynEdit.Text, Edit2.Text, Edit3.Text,[rfIgnoreCase]); end; procedure TEditorFrame.Button1Click(Sender: TObject); var p:cardinal; s:string; begin if Edit1.Text <> SynEdit.SelText then begin //find first if CheckBox1.Checked then p := Pos(Edit1.Text, SynEdit.Text) else p := Pos(LowerCase(Edit1.Text), LowerCase(SynEdit.Text)); if p<>0 then begin SynEdit.SelStart := p; SynEdit.SelEnd := p+Length(Edit1.Text); end else begin ShowMessage('No matches found.'); SynEdit.SelEnd := SynEdit.SelStart; end; end else begin //find next s := SynEdit.Text; Delete(s,1,SynEdit.SelEnd); if CheckBox1.Checked then p := Pos(Edit1.Text, s) else p := Pos(LowerCase(Edit1.Text), LowerCase(s)); if p<>0 then begin p := SynEdit.SelEnd+p; SynEdit.SelStart := p; SynEdit.SelEnd := p+Length(Edit1.Text); end else begin SynEdit.SelEnd := SynEdit.SelStart; Button1Click(Sender); end; end; end; procedure TEditorFrame.Button4Click(Sender: TObject); begin ReplaceDlgPanel.Visible := False; end; procedure TEditorFrame.Button5Click(Sender: TObject); begin if CheckBox2.Checked then SynEdit.Text := StringReplace(SynEdit.Text, Edit2.Text, Edit3.Text,[rfReplaceAll]) else SynEdit.Text := StringReplace(SynEdit.Text, Edit2.Text, Edit3.Text,[rfIgnoreCase,rfReplaceAll]); end; procedure TEditorFrame.FindDlg; begin ReplaceDlgPanel.Visible := False; FindDlgPanel.Visible := True; Edit1.SetFocus; end; procedure TEditorFrame.MenuItem10Click(Sender: TObject); begin SynEdit.SelectAll; end; procedure TEditorFrame.MenuItem1Click(Sender: TObject); begin SynEdit.Undo;; end; procedure TEditorFrame.MenuItem2Click(Sender: TObject); begin SynEdit.Redo; end; procedure TEditorFrame.MenuItem4Click(Sender: TObject); begin FindDlg; end; procedure TEditorFrame.MenuItem5Click(Sender: TObject); begin ReplaceDlg; end; procedure TEditorFrame.MenuItem7Click(Sender: TObject); begin SynEdit.CutToClipboard; end; procedure TEditorFrame.MenuItem8Click(Sender: TObject); begin SynEdit.CopyToClipboard; end; procedure TEditorFrame.MenuItem9Click(Sender: TObject); begin SynEdit.PasteFromClipboard; end; procedure TEditorFrame.ReplaceDlg; begin FindDlgPanel.Visible := False; ReplaceDlgPanel.Visible := True; Edit2.SetFocus; end; procedure TEditorFrame.SynCompletionCodeCompletion(var Value: string; SourceValue: string; var SourceStart, SourceEnd: TPoint; KeyChar: TUTF8Char; Shift: TShiftState); begin Delete(Value,Pos('`',Value),Length(Value)); end; function TEditorFrame.SynCompletionPaintItem(const AKey: string; ACanvas: TCanvas; X, Y: integer; Selected: boolean; Index: integer): boolean; var s,wrd,desc,infile:string; begin s := SynCompletion.ItemList[Index]; wrd := copy(s,1,pos('`',s)-1); delete(s,1,pos('`',s)); desc := copy(s,1,pos('`',s)-1); delete(s,1,pos('`',s)); infile := s; if Selected then begin ACanvas.Brush.Color := clHighlight; ACanvas.FillRect(X,Y,X+SynCompletion.Width,Y+ACanvas.TextHeight('|')); ACanvas.Font.Style := [fsBold]; ACanvas.Font.Color := clWhite; ACanvas.TextOut(X+2,Y,wrd); ACanvas.Font.Style := []; ACanvas.Font.Color := clSilver; ACanvas.TextOut(X+2+ACanvas.TextWidth('_')*(CW_LastMaxWordLen+8),Y,desc); ACanvas.Font.Style := []; ACanvas.Font.Color := clSilver; ACanvas.TextOut(X+2+ACanvas.TextWidth('_')*(CW_LastMaxWordLen+8) +ACanvas.TextWidth('_')*(CW_LastMaxDescrLen+8),Y,infile); end else begin ACanvas.Brush.Color := clWhite; ACanvas.FillRect(X,Y,X+SynCompletion.Width,Y+ACanvas.TextHeight('|')); ACanvas.Font.Style := [fsBold]; ACanvas.Font.Color := clBlack; ACanvas.TextOut(X+2,Y,wrd); ACanvas.Font.Style := []; ACanvas.Font.Color := clBlue; if copy(desc,1,4) = 'proc' then ACanvas.Font.Color := clMaroon; if (desc[1] = '[') and (desc[2] <> '@') then ACanvas.Font.Color := clOlive; ACanvas.TextOut(X+2+ACanvas.TextWidth('_')*(CW_LastMaxWordLen+8),Y,desc); ACanvas.Font.Style := []; ACanvas.Font.Color := clGreen; ACanvas.TextOut(X+2+ACanvas.TextWidth('_')*(CW_LastMaxWordLen+8) +ACanvas.TextWidth('_')*(CW_LastMaxDescrLen+8),Y,infile); end; Result := True; end; procedure TEditorFrame.SynEditChange(Sender: TObject); begin Saved := False; UpdateState; end; procedure TEditorFrame.SynEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if ssCtrl in Shift then case Key of VK_S: begin if FileExists(DefFile) then begin SynEdit.Lines.SaveToFile(DefFile); Saved := True; UpdateState; end else if SaveDialog1.Execute then begin DefFile := SaveDialog1.FileName; SelfTab.Caption := ExtractFileName(DefFile)+' [X]'; SynEdit.Lines.SaveToFile(DefFile); Saved := True; UpdateState; end; end; VK_F: FindDlg; VK_R: ReplaceDlg; end; end; procedure TEditorFrame.SynEditMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin UpdateState; end; procedure TEditorFrame.UpdateState; begin SelfStates.Panels[0].Text := 'Lines: '+IntToStr(SynEdit.Lines.Count); SelfStates.Panels[1].Text := 'CaretXY: '+IntToStr(SynEdit.CaretX)+'/'+ IntToStr(SynEdit.CaretY); if Saved then SelfStates.Panels[2].Text := 'Status: Saved' else SelfStates.Panels[2].Text := 'Status: Modified'; SelfStates.Panels[3].Text := 'File: "'+DefFile+'"'; end; function CheckName(n:string):boolean; var chars: set of char = ['a'..'z','0'..'9','_','.']; begin result := false; if not (n[1] in ['0'..'9']) then begin delete(n,1,1); while Length(n)>0 do begin if not (n[1] in chars) then exit; delete(n,1,1); end; result := true; end; end; function TrimCodeStr(s:string):string; var ConstStr: boolean; begin s := Trim(s); ConstStr := false; Result := ''; while Length(s)>0 do begin if s[1] = '"' then ConstStr := not ConstStr; if ConstStr then begin Result := Result+s[1]; Delete(s,1,1); end else begin if s[1] = ';' then break; Result := Result+s[1]; Delete(s,1,1); end; end; end; function Tk(s:string; w:word):string; begin result := ''; while (length(s)>0)and(w>0) do begin if s[1] = '"' then begin delete(s,1,1); result := copy(s,1,pos('"',s)-1); delete(s,1,pos('"',s)); s := trim(s); end else if Pos(' ',s)>0 then begin result := copy(s,1,pos(' ',s)-1); delete(s,1,pos(' ',s)); s := trim(s); end else begin result := s; s := ''; end; dec(w); end; end; function TEditorFrame.CW_MakeDescr(wrd, descr, infile:string):string; begin if CW_MaxWordLen < Length(wrd) then CW_MaxWordLen := Length(wrd); if CW_MaxDescrLen < Length(descr) then CW_MaxDescrLen := Length(descr); Result := wrd+'`'+descr+'`'+infile; end; procedure TEditorFrame.CW_Add(s:string); begin if CW_Lst.IndexOf(s) = -1 then begin CW_Lst.Add(s); end; end; procedure TEditorFrame.CW_Update; begin CW_LastMaxWordLen := CW_MaxWordLen; CW_LastMaxDescrLen := CW_MaxDescrLen; SynCompletion.ItemList.Text := CW_Lst.Text; end; procedure TEditorFrame.CW_ParseFile(fp:string); var s,fp2:string; f:textfile; begin AssignFile(f,fp); Reset(f); CW_ParsedFiles.Add(fp); while not Eof(f) do begin ReadLn(f,s); s := TrimCodeStr(s); if s <> '' then begin if Tk(s,1) = 'uses' then begin Delete(s,1,length('uses')); s := Trim(s); if s[1] = '<' then fp2 := ExtractFilePath(ParamStr(0))+'inc\' else if FileExists(fp) then fp2 := ExtractFilePath(fp); Delete(s,1,1); Delete(s,Length(s),1); fp2 := fp2 + s; if FileExists(fp2) and (CW_ParsedFiles.IndexOf(fp2) = -1) then CW_ParseFile(fp2); end; if Tk(s,1) = 'import' then begin CW_Add(CW_MakeDescr(Tk(s,2),'[@] "'+Tk(s,3)+'":"'+Tk(s,4)+'"', '"'+ExtractFileName(fp)+'"')); end; if Tk(s,1) = 'proc' then begin delete(s,1,length('proc')); s := Trim(s); CW_Add(CW_MakeDescr(copy(s,1,pos('(',s)-1),'proc '+s,'"'+ExtractFileName(fp)+'"')); end; if Tk(s,1) = 'word' then begin CW_Add(CW_MakeDescr(Tk(s,2),'[word] '+Tk(s,3),'"'+ExtractFileName(fp)+'"')); end; if Tk(s,1) = 'int' then begin CW_Add(CW_MakeDescr(Tk(s,2),'[int] '+Tk(s,3),'"'+ExtractFileName(fp)+'"')); end; if Tk(s,1) = 'real' then begin CW_Add(CW_MakeDescr(Tk(s,2),'[real] '+Tk(s,3),'"'+ExtractFileName(fp)+'"')); end; if Tk(s,1) = 'str' then begin CW_Add(CW_MakeDescr(Tk(s,2),'[str] "'+Tk(s,3)+'"','"'+ExtractFileName(fp)+'"')); end; {if s[Length(s)] = ':' then begin Delete(s,length(s),1); CW_Add(CW_MakeDescr(s,'[label] '+s+':','"'+ExtractFileName(fp)+'"')); end;} end; end; CloseFile(f); end; end.
unit Project.PessoaFisica; interface uses Project.Interfaces, Project.Endereco; type TPessoaFisica = class(TInterfacedObject, iPessoaFisica) private FCPF : String; FEndereco : iEndereco<iPessoaFisica>; public constructor Create; destructor Destroy; override; class function New : iPessoaFisica; function Endereco : iEndereco<iPessoaFisica>; function CPF ( aValue : String ) : iPessoaFisica; overload; function CPF : String; overload; end; implementation { TPessoaFisica } function TPessoaFisica.CPF(aValue: String): iPessoaFisica; begin Result := Self; FCPF := aValue; end; function TPessoaFisica.CPF: String; begin Result := FCPF; end; constructor TPessoaFisica.Create; begin FEndereco := TEndereco<iPessoaFisica>.New(Self); end; destructor TPessoaFisica.Destroy; begin inherited; end; function TPessoaFisica.Endereco: iEndereco<iPessoaFisica>; begin Result := FEndereco; end; class function TPessoaFisica.New: iPessoaFisica; begin Result := Self.Create; end; end.