text
stringlengths
14
6.51M
{*******************************************************} { } { Copyright(c) 2003-2021 Oamaru Group , Inc. } { } { Copyright and license exceptions noted in source } { } {*******************************************************} unit ElementApi.Node; interface uses System.SysUtils, System.Classes, System.JSON, System.Generics.Collections, ElementApi.Link; const API_NODE_PATH = 'api/cluster/nodes'; type TNodeDriveInfo = class protected FLinks: TLinks; FState: String; FUUID: String; FNodeUUID: String; procedure Init; function ToJson: String; procedure FromJson(AValue: String); public constructor Create; overload; virtual; constructor Create(AJSONString: String); overload; virtual; constructor Create(ANodeDriveInfo: TNodeDriveInfo); overload; virtual; destructor Destroy; override; function ToJsonObject: TJSONObject; procedure FromJsonObject(AJSONObject: TJSONObject); property Links: TLinks read FLinks; property State: String read FState write FState; property UUID: String read FUUID write FUUID; property NodeUUID: String read FNodeUUID write FNodeUUID; //Not part of JSON property AsJson: String read ToJson write FromJson; end; TMaintenceModeInfo = class protected FMaintenceModeState: String; FMaintenceModeVariant: String; procedure Init; function ToJson: String; procedure FromJson(AValue: String); public constructor Create; overload; virtual; constructor Create(AJSONString: String); overload; virtual; constructor Create(AMaintenceModeInfo: TMaintenceModeInfo); overload; virtual; function ToJsonObject: TJSONObject; procedure FromJsonObject(AJSONObject: TJSONObject); property MaintenceModeState: String read FMaintenceModeState write FMaintenceModeState; property MaintenceModeVariant: String read FMaintenceModeVariant write FMaintenceModeVariant; property AsJson: String read ToJson write FromJson; end; TNodeStatus = class protected FReachable: Boolean; FState: String; procedure Init; function ToJson: String; procedure FromJson(AValue: String); public constructor Create; overload; virtual; constructor Create(AJSONString: String); overload; virtual; constructor Create(ANodeStatus: TNodeStatus); overload; virtual; function ToJsonObject: TJSONObject; procedure FromJsonObject(AJSONObject: TJSONObject); property Reachable: Boolean read FReachable write FReachable; property State: String read FState write FState; property AsJson: String read ToJson write FromJson; end; TNodeDriveInfoList = class protected { Protected declarations } FList: TObjectList<TNodeDriveInfo>; function GetCount: Integer; function GetListItem(AIndex: Integer): TNodeDriveInfo; procedure SetListItem(AIndex: Integer; AValue: TNodeDriveInfo); function EncodeToJSONArrayString: String; procedure DecodeFromJSONArrayString(AValue: String); public { Pulblic declarations } constructor Create; overload; virtual; constructor Create(AJSONString: String); overload; virtual; constructor Create(ANodeDriveInfoList: TNodeDriveInfoList); overload; virtual; destructor Destroy; override; function ToJSONArray: TJSONArray; procedure FromJSONArray(AJsonArray: TJSONArray); procedure Add(ANodeDriveInfo: TNodeDriveInfo); procedure Delete(AIndex: Integer); procedure AppendFromList(AList: TNodeDriveInfoList); procedure Clear; property Count: Integer read GetCount; property Drives[AIndex: Integer]: TNodeDriveInfo read GetListitem write SetListItem; default; property AsJSONArray: String read EncodeToJSONArrayString write DecodeFromJSONArrayString; end; TNodeInfoDetail = class protected FClusterIP: String; FDrives: TNodeDriveInfoList; FMaintenceModeInfo: TMaintenceModeInfo; FNodeStatus: TNodeStatus; FManagementIP: String; FStorageIP: String; FRole: String; FVersion: String; procedure Init; function ToJson: String; procedure FromJson(AValue: String); public constructor Create; overload; virtual; constructor Create(AJSONString: String); overload; virtual; constructor Create(ANodeInfoDetail: TNodeInfoDetail); overload; virtual; destructor Destroy; override; function ToJsonObject: TJSONObject; procedure FromJsonObject(AJSONObject: TJSONObject); property ClusterIP: String read FClusterIP write FClusterIP; property Drives: TNodeDriveInfoList read FDrives; property MaintenceModeInfo: TMaintenceModeInfo read FMaintenceModeInfo; property Status: TNodeStatus read FNodeStatus; property ManagementIP: String read FManagementIP write FManagementIP; property Role: String read FRole write FRole; property StorageIP: String read FStorageIP write FStorageIP; property Version: String read FVersion write FVersion; property AsJson: String read ToJson write FromJson; end; TNodeInfo = class protected FLinks: TLinks; FNodeInfoDetail: TNodeInfoDetail; FNodeID: Integer; FName: String; FUUID: String; procedure Init; function ToJson: String; procedure FromJson(AValue: String); public constructor Create; overload; virtual; constructor Create(AJSONString: String); overload; virtual; constructor Create(ANodeInfo: TNodeInfo); overload; virtual; destructor Destroy; override; function ToJsonObject: TJSONObject; procedure FromJsonObject(AJSONObject: TJSONObject); property Links: TLinks read FLinks; property NodeInfoDetail: TNodeInfoDetail read FNodeInfoDetail; property NodeID: Integer read FNodeID write FNodeID; property Name: String read FName write FName; property UUID: String read FUUID write FUUID; property AsJson: String read ToJson write FromJson; end; TNodeInfoList = class protected { Protected declarations } FList: TObjectList<TNodeInfo>; function GetCount: Integer; function GetListItem(AIndex: Integer): TNodeInfo; procedure SetListItem(AIndex: Integer; AValue: TNodeInfo); function EncodeToJSONArrayString: String; procedure DecodeFromJSONArrayString(AValue: String); public { Pulblic declarations } constructor Create; overload; virtual; constructor Create(AJSONString: String); overload; virtual; constructor Create(ANodeInfoList: TNodeInfoList); overload; virtual; destructor Destroy; override; function ToJSONArray: TJSONArray; procedure FromJSONArray(AJsonArray: TJSONArray); procedure Add(ANodeInfo: TNodeInfo); procedure Delete(AIndex: Integer); procedure Clear; property Count: Integer read GetCount; property Nodes[AIndex: Integer]: TNodeInfo read GetListitem write SetListItem; default; property AsJSONArray: String read EncodeToJSONArrayString write DecodeFromJSONArrayString; end; implementation {$REGION 'TNodeDriveInfo'} constructor TNodeDriveInfo.Create; begin inherited Create; FLinks := TLinks.Create; Init; end; constructor TNodeDriveInfo.Create(AJSONString: String); begin inherited Create; FLinks := TLinks.Create; FromJson(AJSONString); end; constructor TNodeDriveInfo.Create(ANodeDriveInfo: TNodeDriveInfo); begin inherited Create; FLinks := TLinks.Create(ANodeDriveInfo.Links); FState := ANodeDriveInfo.State; FUUID := ANodeDriveInfo.UUID; FNodeUUID := ANodeDriveInfo.NodeUUID; end; destructor TNodeDriveInfo.Destroy; begin FLinks.Free; inherited Create; end; procedure TNodeDriveInfo.Init; begin FLinks.Clear; FState := String.Empty; FUUID := String.Empty; end; function TNodeDriveInfo.ToJson: String; begin var LObj := Self.ToJSONObject; try Result := LObj.ToJSON; finally LObj.Free; end; end; procedure TNodeDriveInfo.FromJson(AValue: String); begin var LObj := TJSONObject.ParseJSONValue(AValue) as TJSONObject; try FromJSONObject(LObj) finally LObj.Free; end; end; function TNodeDriveInfo.ToJsonObject: TJSONObject; begin Result := TJSONObject.Create; Result.AddPair('_links', FLinks.ToJsonObject); Result.AddPair('state', FState); Result.AddPair('uuid', FUUID); end; procedure TNodeDriveInfo.FromJsonObject(AJSONObject: TJSONObject); begin Init; if nil <> AJSONObject.Values['_links'] then FLinks.FromJsonObject(AJSONObject.Values['_links'] as TJSONObject); if nil <> AJsonObject.Values['state'] then FState := AJsonObject.Values['state'].Value; if nil <> AJsonObject.Values['uuid'] then FUUID := AJsonObject.Values['uuid'].Value; end; {$ENDREGION} {$REGION 'TNodeDriveInfoList'} constructor TNodeDriveInfoList.Create; begin inherited Create; FList := TObjectList<TNodeDriveInfo>.Create(TRUE); end; constructor TNodeDriveInfoList.Create(AJSONString: String); begin inherited Create; FList := TObjectList<TNodeDriveInfo>.Create(TRUE); DecodeFromJSONArrayString(AJSONString); end; constructor TNodeDriveInfoList.Create(ANodeDriveInfoList: TNodeDriveInfoList); begin inherited Create; FList := TObjectList<TNodeDriveInfo>.Create(TRUE); for var i := 0 to (ANodeDriveInfoList.Count - 1) do FList.Add(TNodeDriveInfo.Create(ANodeDriveInfoList[i])); end; destructor TNodeDriveInfoList.Destroy; begin FList.Free; inherited Destroy; end; function TNodeDriveInfoList.GetCount: Integer; begin Result := FList.Count; end; function TNodeDriveInfoList.GetListItem(AIndex: Integer): TNodeDriveInfo; begin Result := FList[AIndex]; end; procedure TNodeDriveInfoList.SetListItem(AIndex: Integer; AValue: TNodeDriveInfo); begin FList[AIndex] := AValue; end; function TNodeDriveInfoList.EncodeToJSONArrayString: String; begin var LArray := Self.ToJSONArray; try Result := LArray.ToJSON; finally LArray.Free; end; end; procedure TNodeDriveInfoList.DecodeFromJSONArrayString(AValue: String); begin if String.IsNullOrWhitespace(AValue) then EXIT; var LArray := TJSONObject.ParseJSONValue(AValue) as TJSONArray; try Self.FromJSONArray(LArray) finally LArray.Free; end; end; function TNodeDriveInfoList.ToJSONArray: TJSONArray; begin Result := TJSONArray.Create; for var i := 0 to (FList.Count - 1) do Result.Add(FList[i].ToJSONObject); end; procedure TNodeDriveInfoList.FromJSONArray(AJsonArray: TJSONArray); begin FList.Clear; for var LArrayValue in AJsonArray do FList.Add(TNodeDriveInfo.Create((LArrayValue As TJSONObject).ToJSON)); end; procedure TNodeDriveInfoList.Add(ANodeDriveInfo: TNodeDriveInfo); begin FList.Add(ANodeDriveInfo); end; procedure TNodeDriveInfoList.Delete(AIndex: Integer); begin FList.Delete(AIndex); end; procedure TNodeDriveInfoList.AppendFromList(AList: TNodeDriveInfoList); begin for var i := 0 to (AList.Count - 1) do FList.Add(TNodeDriveInfo.Create(AList[i])); end; procedure TNodeDriveInfoList.Clear; begin FList.Clear; end; {$ENDREGION} {$REGION 'TMaintenceModeInfo'} constructor TMaintenceModeInfo.Create; begin inherited Create; Init; end; constructor TMaintenceModeInfo.Create(AJSONString: String); begin inherited Create; FromJson(AJSONString); end; constructor TMaintenceModeInfo.Create(AMaintenceModeInfo: TMaintenceModeInfo); begin inherited Create; FMaintenceModeState := AMaintenceModeInfo.MaintenceModeState; FMaintenceModeVariant := AMaintenceModeInfo.FMaintenceModeVariant; end; procedure TMaintenceModeInfo.Init; begin FMaintenceModeState := String.Empty; FMaintenceModeVariant := String.Empty; end; function TMaintenceModeInfo.ToJson: String; begin var LObj := Self.ToJSONObject; try Result := LObj.ToJSON; finally LObj.Free; end; end; procedure TMaintenceModeInfo.FromJson(AValue: String); begin var LObj := TJSONObject.ParseJSONValue(AValue) as TJSONObject; try FromJSONObject(LObj) finally LObj.Free; end; end; function TMaintenceModeInfo.ToJsonObject: TJSONObject; begin Result := TJSONObject.Create; Result.AddPair('state', FMaintenceModeState); Result.AddPair('variant', FMaintenceModeVariant); end; procedure TMaintenceModeInfo.FromJsonObject(AJSONObject: TJSONObject); begin if (nil <> AJSONObject.Values['state']) then FMaintenceModeState := AJSONObject.Values['state'].Value; if (nil <> AJSONObject.Values['variant']) then FMaintenceModeVariant := AJSONObject.Values['variant'].Value; end; {$ENDREGION} {$REGION 'TNodeStatus'} constructor TNodeStatus.Create; begin inherited Create; Init; end; constructor TNodeStatus.Create(AJSONString: String); begin inherited Create; FromJson(AJSONString); end; constructor TNodeStatus.Create(ANodeStatus: TNodeStatus); begin inherited Create; FReachable := ANodeStatus.Reachable; FState := ANodeStatus.State; end; procedure TNodeStatus.Init; begin FReachable := FALSE; FState := String.Empty; end; function TNodeStatus.ToJson: String; begin var LObj := Self.ToJSONObject; try Result := LObj.ToJSON; finally LObj.Free; end; end; procedure TNodeStatus.FromJson(AValue: String); begin var LObj := TJSONObject.ParseJSONValue(AValue) as TJSONObject; try FromJSONObject(LObj) finally LObj.Free; end; end; function TNodeStatus.ToJsonObject: TJSONObject; begin Result := TJSONObject.Create; Result.AddPair('reachable', TJsonBool.Create(FReachable)); Result.AddPair('state', FState); end; procedure TNodeStatus.FromJsonObject(AJSONObject: TJSONObject); begin Init; if (nil <> AJSONObject.Values['state']) then FState := AJSONObject.Values['state'].Value; if (nil <> AJSONObject.Values['reachable']) then FReachable := ('TRUE' = AJSONObject.Values['reachable'].Value.ToUpper); end; {$ENDREGION} {$REGION 'TNodeInfoDetail'} constructor TNodeInfoDetail.Create; begin inherited Create; FDrives := TNodeDriveInfoList.Create; FMaintenceModeInfo := TMaintenceModeInfo.Create; FNodeStatus := TNodeStatus.Create; Init; end; constructor TNodeInfoDetail.Create(AJSONString: String); begin inherited Create; FDrives := TNodeDriveInfoList.Create; FMaintenceModeInfo := TMaintenceModeInfo.Create; FNodeStatus := TNodeStatus.Create; FromJson(AJSONString); end; constructor TNodeInfoDetail.Create(ANodeInfoDetail: TNodeInfoDetail); begin inherited Create; FDrives := TNodeDriveInfoList.Create(ANodeInfoDetail.Drives) ; FMaintenceModeInfo := TMaintenceModeInfo.Create(ANodeInfoDetail.MaintenceModeInfo); FNodeStatus := TNodeStatus.Create(ANodeInfoDetail.Status); end; destructor TNodeInfoDetail.Destroy; begin FNodeStatus.Free; FMaintenceModeInfo.Free; FDrives.Free; inherited Destroy; end; procedure TNodeInfoDetail.Init; begin FClusterIP := String.Empty; FDrives.Clear; FMaintenceModeInfo.MaintenceModeState := String.Empty; FMaintenceModeInfo.MaintenceModeVariant := String.Empty; FManagementIP := String.Empty; FStorageIP := String.Empty; FRole := String.Empty; FVersion := String.Empty; FNodeStatus.State := String.Empty; FNodeStatus.Reachable := FALSE; end; function TNodeInfoDetail.ToJson: String; begin var LObj := Self.ToJSONObject; try Result := LObj.ToJSON; finally LObj.Free; end; end; procedure TNodeInfoDetail.FromJson(AValue: String); begin var LObj := TJSONObject.ParseJSONValue(AValue) as TJSONObject; try FromJSONObject(LObj) finally LObj.Free; end; end; function TNodeInfoDetail.ToJsonObject: TJSONObject; begin Result := TJSONObject.Create; var LIPObj := TJSONObject.Create; LIPObj.AddPair('address', FClusterIP); Result.AddPair('clusterIPInterface', LIPObj); Result.AddPair('drives', FDrives.ToJSONArray); Result.AddPair('maintenance_mode', FMaintenceModeInfo.ToJsonObject); LIPObj := TJSONObject.Create; LIPObj.AddPair('address', FManagementIP); Result.AddPair('managementIPInterface', LIPObj); Result.AddPair('role', FRole); Result.AddPair('status', FNodeStatus.ToJsonObject); LIPObj := TJSONObject.Create; LIPObj.AddPair('address', FStorageIP); Result.AddPair('storageIPInterface', LIPObj); Result.AddPair('version', FVersion); end; procedure TNodeInfoDetail.FromJsonObject(AJSONObject: TJSONObject); begin Init; if (nil <> AJSONObject.Values['clusterIPInterface']) and (nil <> (AJSONObject.Values['clusterIPInterface'] as TJSONObject).Values['address']) then FClusterIP := (AJSONObject.Values['clusterIPInterface'] as TJSONObject).Values['address'].Value; if nil <> AJSONObject.Values['drives'] then FDrives.FromJSONArray(AJSONObject.Values['drives'] as TJSONArray); if (nil <> AJSONObject.Values['maintenance_mode']) then FMaintenceModeInfo.FromJsonObject(AJSONObject.Values['maintenance_mode'] as TJSONObject); if (nil <> AJSONObject.Values['managementIPInterface']) and (nil <> (AJSONObject.Values['managementIPInterface'] as TJSONObject).Values['address']) then FManagementIP := (AJSONObject.Values['managementIPInterface'] as TJSONObject).Values['address'].Value; if nil <> AJSONObject.Values['role'] then FRole := AJSONObject.Values['role'].Value; if (nil <> AJSONObject.Values['status']) then FNodeStatus.FromJsonObject(AJSONObject.Values['status'] as TJSONObject); if (nil <> AJSONObject.Values['storageIPInterface']) and (nil <> (AJSONObject.Values['storageIPInterface'] as TJSONObject).Values['address']) then FStorageIP := (AJSONObject.Values['storageIPInterface'] as TJSONObject).Values['address'].Value; if nil <> AJSONObject.Values['version'] then FVersion := AJSONObject.Values['version'].Value; end; {$ENDREGION} {$REGION 'TNodeInfo'} constructor TNodeInfo.Create; begin inherited Create; FLinks := TLinks.Create; FNodeInfoDetail := TNodeInfoDetail.Create; end; constructor TNodeInfo.Create(AJSONString: String); begin inherited Create; FLinks := TLinks.Create; FNodeInfoDetail := TNodeInfoDetail.Create; FromJson(AJSONString); end; constructor TNodeInfo.Create(ANodeInfo: TNodeInfo); begin inherited Create; FLinks := TLinks.Create(ANodeInfo.Links); FNodeInfoDetail := TNodeInfoDetail.Create(ANodeInfo.NodeInfoDetail); end; destructor TNodeInfo.Destroy; begin if nil <> FNodeInfoDetail then FNodeInfoDetail.Free; if nil <> FLinks then FLinks.Free; inherited Destroy; end; procedure TNodeInfo.Init; begin FLinks.Clear; FNodeID := 0; FName := String.Empty; FUUID := String.Empty; end; function TNodeInfo.ToJson: String; begin var LObj := Self.ToJSONObject; try Result := LObj.ToJSON; finally LObj.Free; end; end; procedure TNodeInfo.FromJson(AValue: String); begin var LObj := TJSONObject.ParseJSONValue(AValue) as TJSONObject; try FromJSONObject(LObj) finally LObj.Free; end; end; function TNodeInfo.ToJsonObject: TJSONObject; begin Result := TJSONObject.Create; Result.AddPair('_links', FLinks.ToJsonObject); Result.AddPair('detail', FNodeInfoDetail.ToJsonObject); Result.AddPair('id', TJsonNumber.Create(FNodeID)); Result.AddPair('name', FName); Result.AddPair('uuid', FUUID); end; procedure TNodeInfo.FromJsonObject(AJSONObject: TJSONObject); begin Init; if nil <> AJSONObject.Values['_links'] then FLinks.FromJsonObject(AJSONObject.Values['_links'] as TJSONObject); if nil <> AJSONObject.Values['detail'] then FNodeInfoDetail.FromJsonObject(AJSONObject.Values['detail'] as TJSONObject); if nil <> AJsonObject.Values['id'] then FNodeID := StrToIntDef(AJsonObject.Values['id'].Value, -1); if nil <> AJsonObject.Values['name'] then FName := AJsonObject.Values['name'].Value; if nil <> AJsonObject.Values['uuid'] then FUUID := AJsonObject.Values['uuid'].Value; for var i := 0 to (FNodeInfoDetail.Drives.Count - 1) do FNodeInfoDetail.Drives[i].NodeUUID := FUUID; end; {$ENDREGION} {$REGION 'TNodeInfoList'} constructor TNodeInfoList.Create; begin inherited Create; FList := TObjectList<TNodeInfo>.Create(TRUE); end; constructor TNodeInfoList.Create(AJSONString: String); begin inherited Create; FList := TObjectList<TNodeInfo>.Create(TRUE); DecodeFromJSONArrayString(AJSONString); end; constructor TNodeInfoList.Create(ANodeInfoList: TNodeInfoList); begin FList := TObjectList<TNodeInfo>.Create(TRUE); for var i := 0 to (ANodeInfoList.Count - 1) do FList.Add(TNodeInfo.Create(ANodeInfoList[i])); end; destructor TNodeInfoList.Destroy; begin FList.Free; inherited Destroy; end; function TNodeInfoList.GetCount: Integer; begin Result := FList.Count; end; function TNodeInfoList.GetListItem(AIndex: Integer): TNodeInfo; begin Result := FList[AIndex]; end; procedure TNodeInfoList.SetListItem(AIndex: Integer; AValue: TNodeInfo); begin FList[AIndex] := AValue; end; function TNodeInfoList.EncodeToJSONArrayString: String; begin var LArray := Self.ToJSONArray; try Result := LArray.ToJSON; finally LArray.Free; end; end; procedure TNodeInfoList.DecodeFromJSONArrayString(AValue: String); begin if String.IsNullOrWhitespace(AValue) then EXIT; var LArray := TJSONObject.ParseJSONValue(AValue) as TJSONArray; try Self.FromJSONArray(LArray) finally LArray.Free; end; end; function TNodeInfoList.ToJSONArray: TJSONArray; begin Result := TJSONArray.Create; for var i := 0 to (FList.Count - 1) do Result.Add(FList[i].ToJSONObject); end; procedure TNodeInfoList.FromJSONArray(AJsonArray: TJSONArray); begin FList.Clear; for var LArrayValue in AJsonArray do FList.Add(TNodeInfo.Create((LArrayValue As TJSONObject).ToJSON)); end; procedure TNodeInfoList.Add(ANodeInfo: TNodeInfo); begin FList.Add(ANodeInfo); end; procedure TNodeInfoList.Delete(AIndex: Integer); begin FList.Delete(AIndex); end; procedure TNodeInfoList.Clear; begin FList.Clear; end; {$ENDREGION} end.
unit uMQTTInterface; interface uses System.Classes, System.StrUtils, System.Math, winapi.Windows, Winapi.Messages, Vcl.StdCtrls, Vcl.WinXCtrls, Vcl.Menus, Vcl.Graphics, uMQTT; type IMQTTClientCustom = interface ['{81A6799E-6BB0-4D6B-ACE6-DB9DCB88F1DD}'] function Enabled : boolean; function Online : boolean; function NextMessageID : Word; procedure Subscribe (aTopic : UTF8String; aQos : TMQTTQOSType); overload; procedure Subscribe (Topics : TStringList); overload; procedure Unsubscribe (aTopic : UTF8String); overload; procedure Unsubscribe (Topics : TStringList); overload; procedure Ping; procedure Publish (aTopic : UTF8String; aMessage : AnsiString; aQos : TMQTTQOSType; aRetain : Boolean = false); procedure SetWill (aTopic, aMessage : UTF8String; aQos : TMQTTQOSType; aRetain : Boolean = false); procedure Mon (aStr : string); procedure Activate (Enable : Boolean); end; implementation end.
unit ListEx; interface uses Windows, SysUtils, SortList, Classes; type TLockSortList = class (TSortList) private m_Lock: TRTLCriticalSection; public constructor Create();override; destructor Destroy();override; procedure Lock(); procedure Unlock(); end; TDoubleList = class(TLockSortList) private m_AppendList: TSortList; function GetAppendCount: Integer; public constructor Create();override; destructor Destroy();override; procedure Append(P: Pointer); procedure Flush(); property AppendCount: Integer read GetAppendCount; property AppendList: TSortList read m_AppendList; end; TLockStringList = class(TStringList) private m_Lock: TRTLCriticalSection; public constructor Create();virtual; destructor Destroy();override; procedure Lock(); procedure Unlock(); end; TDoubleStringList = class(TLockStringList) m_AppendStrings: TStringList; function GetAppendCount: Integer; private public constructor Create();override; destructor Destroy();override; procedure Append(S: string); procedure AppendObject(s: string; AObject: TObject); procedure Flush(); property AppendCount: Integer read GetAppendCount; property AppendList: TStringList read m_AppendStrings; end; implementation { TDoubleList } procedure TDoubleList.Append(P: Pointer); begin EnterCriticalSection( m_Lock ); try m_AppendList.Add(P); finally LeaveCriticalSection( m_Lock ); end; end; constructor TDoubleList.Create; begin inherited Create; m_AppendList := TSortList.Create; end; destructor TDoubleList.Destroy; begin m_AppendList.Free; inherited; end; procedure TDoubleList.Flush; begin EnterCriticalSection( m_Lock ); try AddList( m_AppendList ); m_AppendList.Trunc(0); finally LeaveCriticalSection( m_Lock ); end; end; function TDoubleList.GetAppendCount: Integer; begin result := m_AppendList.Count; end; { TLockSortList } constructor TLockSortList.Create; begin inherited Create(); InitializeCriticalSection( m_Lock ); end; destructor TLockSortList.Destroy; begin DeleteCriticalSection( m_Lock ); inherited; end; procedure TLockSortList.Lock; begin EnterCriticalSection( m_Lock ); end; procedure TLockSortList.Unlock; begin LeaveCriticalSection( m_Lock ); end; { TLockStringList } constructor TLockStringList.Create; begin inherited Create; InitializeCriticalSection( m_Lock ); end; destructor TLockStringList.Destroy; begin DeleteCriticalSection( m_Lock ); inherited; end; procedure TLockStringList.Lock; begin EnterCriticalSection( m_Lock ); end; procedure TLockStringList.Unlock; begin LeaveCriticalSection( m_Lock ); end; { TDoubleStringList } procedure TDoubleStringList.Append(S: string); begin EnterCriticalSection( m_Lock ); try m_AppendStrings.Add( S ); finally LeaveCriticalSection( m_Lock ); end; end; procedure TDoubleStringList.AppendObject(s: string; AObject: TObject); begin EnterCriticalSection( m_Lock ); try m_AppendStrings.AddObject( S, AObject ); finally LeaveCriticalSection( m_Lock ); end; end; constructor TDoubleStringList.Create; begin inherited Create; m_AppendStrings := TStringList.Create; end; destructor TDoubleStringList.Destroy; begin m_AppendStrings.Free; inherited; end; procedure TDoubleStringList.Flush; begin EnterCriticalSection( m_Lock ); try AddStrings( m_AppendStrings ); m_AppendStrings.Clear(); finally LeaveCriticalSection( m_Lock ); end; end; function TDoubleStringList.GetAppendCount: Integer; begin Result := m_AppendStrings.Count; end; end.
unit UFLConfDesenvolvimentoDeClientes; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFBasicoLista, cxStyles, DB, ADODB, Menus, ImgList, cxPropertiesStore, ActnList, ComCtrls, ToolWin, cxControls, cxGrid, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridCustomView, cxClasses, cxGridLevel, uConfDesenvolvimentoDeClientes, UFDConfDesenvolvimentoDeClientes; type TFLDesenvolvimentoDeClientes = class(TFBasicoLista) ADODataSetcodigo: TIntegerField; ADODataSetcodRepresentanteInicial: TStringField; ADODataSetdataFinalCompra: TDateTimeField; ADODataSetdataInicialCompra: TDateTimeField; ADODataSetdataLimiteInicialCompra: TDateTimeField; ADODataSetmesCorrente: TIntegerField; ADODataSetanoCorrente: TIntegerField; ADODataSetNomeRepresentanteInicial: TStringField; ADODataSetNomeRepresentanteFinal: TStringField; ADODataSetcodRepresentanteFinal: TStringField; cxGridLevel1: TcxGridLevel; grid: TcxGridDBTableView; gridcodigo: TcxGridDBColumn; gridcodRepresentanteInicial: TcxGridDBColumn; griddataFinalCompra: TcxGridDBColumn; griddataInicialCompra: TcxGridDBColumn; griddataLimiteInicialCompra: TcxGridDBColumn; gridmesCorrente: TcxGridDBColumn; gridanoCorrente: TcxGridDBColumn; gridNomeRepresentanteInicial: TcxGridDBColumn; gridNomeRepresentanteFinal: TcxGridDBColumn; gridcodRepresentanteFinal: TcxGridDBColumn; ActionIncluir: TAction; ActionExcluir: TAction; ActionDetalhes: TAction; ActionImprimir: TAction; Cadastro1: TMenuItem; Incluir1: TMenuItem; Excluir1: TMenuItem; Detalhes1: TMenuItem; ToolButton1: TToolButton; ActionImprimirPorCliente: TAction; ToolButton2: TToolButton; procedure bt_ExcelClick(Sender: TObject); procedure bt_CalcClick(Sender: TObject); procedure ActionIncluirExecute(Sender: TObject); procedure ActionDetalhesExecute(Sender: TObject); procedure ActionExcluirExecute(Sender: TObject); procedure ActionImprimirExecute(Sender: TObject); procedure ActionImprimirPorClienteExecute(Sender: TObject); private conf : TConfDesenvolvimentoDeClientes; procedure populaConfiguracao; { Private declarations } public constructor create(AOwner: TComponent); { Public declarations } end; implementation uses UExportacao, Funcoes, uEntid, UMBancoDeDados, UFBasicoDetalhes, UMMensagem, URDesenvolvimentoDeClientes; {$R *.dfm} procedure TFLDesenvolvimentoDeClientes.ActionDetalhesExecute(Sender: TObject); var form : TFDDesenvolvimentoDeClientes; begin inherited; if ADODataSetCodigo.AsInteger > 0 then begin populaConfiguracao; form := TFDDesenvolvimentoDeClientes.create(Application, ADODataSet, ADODataSetCodigo.Value, taNormalBD, conf); form.showModal; form.Free; end else MensagemWarning('Selecione um registro!'); end; procedure TFLDesenvolvimentoDeClientes.ActionExcluirExecute(Sender: TObject); begin inherited; if ADODataSetcodigo.AsString <> '' then if MensagemQuestion('Deseja excluir o registro ' + ADODataSetcodigo.AsString + '?') then begin excluirRegistro('ConfDesenvolvimentoDeClientes', 'codigo', ADODataSetcodigo.AsString, False); ADODataSet.Requery([]); end; end; procedure TFLDesenvolvimentoDeClientes.ActionImprimirExecute(Sender: TObject); var relatorio : TFRDesenvolvimentoDeClientes; begin inherited; if ADODataSetcodigo.AsInteger > 0 then begin Application.CreateForm(TFRDesenvolvimentoDeClientes, relatorio); relatorio.passaParametros(ADODataSetcodRepresentanteInicial.AsString, ADODataSetcodRepresentanteFinal.AsString, ADODataSetmesCorrente.AsInteger, ADODataSetanoCorrente.AsInteger, ADODataSetdataInicialCompra.AsDateTime, ADODataSetdataFinalCompra.AsDateTime, ADODataSetdataLimiteInicialCompra.AsDateTime, tiIev); relatorio.executaRelatorio; end; end; procedure TFLDesenvolvimentoDeClientes.ActionImprimirPorClienteExecute(Sender: TObject); var relatorio : TFRDesenvolvimentoDeClientes; begin inherited; if ADODataSetcodigo.AsInteger > 0 then begin Application.CreateForm(TFRDesenvolvimentoDeClientes, relatorio); relatorio.passaParametros(ADODataSetcodRepresentanteInicial.AsString, ADODataSetcodRepresentanteFinal.AsString, ADODataSetmesCorrente.AsInteger, ADODataSetanoCorrente.AsInteger, ADODataSetdataInicialCompra.AsDateTime, ADODataSetdataFinalCompra.AsDateTime, ADODataSetdataLimiteInicialCompra.AsDateTime, tiCliente); relatorio.executaRelatorio; end; end; procedure TFLDesenvolvimentoDeClientes.ActionIncluirExecute(Sender: TObject); var form : TFDDesenvolvimentoDeClientes; begin inherited; form := TFDDesenvolvimentoDeClientes.create(Application, ADODataSet, ADODataSetCodigo.Value, taIncluirBD, nil); form.showModal; form.Free; end; procedure TFLDesenvolvimentoDeClientes.bt_CalcClick(Sender: TObject); var exportacao: TExportacao; begin exportacao := TExportacao.Create; exportacao.exportarParaCalc(grid, ADODataSet, Caption); exportacao.Free; end; procedure TFLDesenvolvimentoDeClientes.bt_ExcelClick(Sender: TObject); var exportacao: TExportacao; begin exportacao := TExportacao.Create; exportacao.exportarParaExcel(grid, ADODataSet, Caption); exportacao.Free; end; constructor TFLDesenvolvimentoDeClientes.create(AOwner: TComponent); var funcoes : TFuncoes; begin inherited create(AOwner); funcoes := TFuncoes.Create; grid := funcoes.configuraPropriedadesDaGrid(grid); funcoes.Free; CarregarConfiguracoesDoUsuario; end; procedure TFLDesenvolvimentoDeClientes.populaConfiguracao; var reprInicial : TEntid; reprFinal : TEntid; begin if ADODataSetCodigo.AsString <> '' then begin reprInicial := nil; reprFinal := nil; conf := TConfDesenvolvimentoDeClientes.Create; conf.codigo := ADODataSetCodigo.AsInteger; conf.dataInicialCompra := ADODataSetdataInicialCompra.Value; conf.dataFinalCompra := ADODataSetdataFinalCompra.Value; conf.dataLimiteInicialCompra := ADODataSetdataLimiteInicialCompra.Value; conf.mesCorrente := ADODataSetmesCorrente.Value; conf.anoCorrente := ADODataSetanoCorrente.Value; if ADODataSetcodRepresentanteInicial.AsString <> '' then begin reprInicial := TEntid.Create; reprInicial.codEntidade := ADODataSetcodRepresentanteInicial.AsString; reprInicial.nome := ADODataSetNomeRepresentanteInicial.AsString; end; if ADODataSetcodRepresentanteFinal.AsString <> '' then begin reprFinal := TEntid.Create; reprFinal.codEntidade := ADODataSetcodRepresentanteFinal.AsString; reprFinal.nome := ADODataSetNomeRepresentanteFinal.AsString; end; conf.representanteInicial := reprInicial; conf.representanteFinal := reprFinal; end; end; end.
Program Subtraction; { Variables declaration } Var x, y, result :integer; Begin { Get the values by user } writeln('Set the variable X:'); read(x); writeln('Set the variable Y:'); read(y); { Calculates the sum between two numbers } result := x - y; writeln('The subtraction between ', x, ' and ', y, ' is ', result); End.
unit uTabelaPrecoItens; interface uses ZConnection, ZDataset, SysUtils, uConstantes, Classes, uProcedimentosBanco, uExceptions, Variants, Forms, Dialogs, Windows, uTabelaPreco, uProduto; type TTabelaPrecoItens = class public oTabelaPreco: TTabelaPreco; oProduto: TProduto; constructor Create(pzcoConnection: TZConnection); destructor Destroy; override; procedure CadastraTabelaPrecoItens; procedure AlteraTabelaPrecoItens; procedure DeletaTabelaPrecoItens; function bPesquisaTabelaPrecoItens(piTabela, piProduto: Integer): Boolean; function bPesquisaTabelaPrecoItensCodigo(piCodigo: Integer): Boolean; function iRetornaUltimoCodigo: Integer; function iGetCodigo: Integer; function nGetPreco: Real; function sGetStatus: string; procedure SetCodigo(piCodigo: Integer); procedure SetStatus(psStatus: string); procedure SetPreco(pnPreco: Real); private iCodigo: Integer; nPreco: Real; sStatus: string; zcoConnection: TZConnection; function iCamposConsistentes: Integer; end; implementation { TTabelaPrecoItens } procedure TTabelaPrecoItens.AlteraTabelaPrecoItens; var ZQryTabelaPrecoItens: TZQuery; begin if iCamposConsistentes = 0 then begin ZQryTabelaPrecoItens := TZQuery.Create(nil); with ZQryTabelaPrecoItens do begin Connection := zcoConnection; SQL.Clear; SQL.Add('UPDATE tbTabelaPrecoItens SET npreco = :npreco, sstatus = :sstatus'); SQL.Add('WHERE icodigo = :icodigo'); ParamByName('npreco').AsFloat := nPreco; ParamByName('icodigo').AsInteger := iCodigo; ParamByName('sstatus').AsString := sStatus; ExecSQL; end; FreeAndNil(ZQryTabelaPrecoItens); end; end; function TTabelaPrecoItens.bPesquisaTabelaPrecoItens(piTabela, piProduto: Integer): Boolean; var ZQryTabelaPrecoItens: TZQuery; begin ZQryTabelaPrecoItens := TZQuery.Create(nil); Result := False; with ZQryTabelaPrecoItens do begin Connection := zcoConnection; SQL.Clear; SQL.Add('SELECT * FROM tbTabelaPrecoItens WHERE itabela = :itabela and iproduto = :iproduto'); ParamByName('itabela').AsInteger := piTabela; ParamByName('iproduto').AsInteger := piProduto; Open; if not IsEmpty then begin Result := True; SetCodigo(FieldByName('icodigo').AsInteger); oTabelaPreco.bPesquisaTabelaPreco(FieldByName('itabela').AsInteger); oProduto.bPesquisaProduto(FieldByName('iproduto').AsInteger); SetPreco(FieldByName('npreco').AsFloat); SetStatus(FieldByName('sstatus').AsString); if sGetStatus = 'I' then if Application.MessageBox('Esta composição de preços está Inativa! Deseja Reativar?', 'Reativar composição de preços', MB_YESNO) = IDYES then begin SetStatus('A'); AlteraTabelaPrecoItens; SetStatus('A'); end; end else begin SetCodigo(0); SetPreco(0); oTabelaPreco.SetCodigo(0); oProduto.SetCodigo(0); oTabelaPreco.bPesquisaTabelaPreco(0); end; end; FreeAndNil(ZQryTabelaPrecoItens); end; function TTabelaPrecoItens.bPesquisaTabelaPrecoItensCodigo(piCodigo: Integer): Boolean; var ZQryTabelaPrecoItens: TZQuery; begin ZQryTabelaPrecoItens := TZQuery.Create(nil); Result := False; with ZQryTabelaPrecoItens do begin Connection := zcoConnection; SQL.Clear; SQL.Add('SELECT * FROM tbTabelaPrecoItens WHERE icodigo = :icodigo'); ParamByName('icodigo').AsInteger := piCodigo; Open; if not IsEmpty then begin Result := True; SetCodigo(FieldByName('icodigo').AsInteger); oTabelaPreco.bPesquisaTabelaPreco(FieldByName('itabela').AsInteger); oProduto.bPesquisaProduto(FieldByName('iproduto').AsInteger); SetPreco(FieldByName('npreco').AsFloat); SetStatus(FieldByName('sstatus').AsString); if sGetStatus = 'I' then if Application.MessageBox('Esta composição de preços está Inativa! Deseja Reativar?', 'Reativar composição de preços', MB_YESNO) = IDYES then begin SetStatus('A'); AlteraTabelaPrecoItens; SetStatus('A'); end; end else begin SetCodigo(0); SetPreco(0); oTabelaPreco.SetCodigo(0); oProduto.SetCodigo(0); end; end; FreeAndNil(ZQryTabelaPrecoItens); end; procedure TTabelaPrecoItens.CadastraTabelaPrecoItens; var ZQryTabelaPrecoItens: TZQuery; begin if iCamposConsistentes = 0 then begin ZQryTabelaPrecoItens := TZQuery.Create(nil); with ZQryTabelaPrecoItens do begin Connection := zcoConnection; SQL.Clear; SQL.Add('INSERT INTO tbTabelaPrecoItens(icodigo, itabela, iproduto, npreco)'); SQL.Add('VALUES(:icodigo, :itabela, :iproduto, :npreco)'); ParamByName('icodigo').AsInteger := iGetCodigo; ParamByName('itabela').AsInteger := oTabelaPreco.iGetCodigo; ParamByName('iproduto').AsInteger := oProduto.GetiCodigo; ParamByName('npreco').AsFloat := nGetPreco; try ExecSQL; except on E: Exception do begin TrataErro(E.Message); Application.MessageBox(Pchar(E.Message), 'Erro', MB_OK); end; end; end; FreeAndNil(ZQryTabelaPrecoItens); end; end; constructor TTabelaPrecoItens.Create(pzcoConnection: TZConnection); begin inherited Create; zcoConnection := pzcoConnection; oTabelaPreco := TTabelaPreco.Create(pzcoConnection); oProduto := TProduto.Create(pzcoConnection); end; procedure TTabelaPrecoItens.DeletaTabelaPrecoItens; var ZQryTabelaPrecoItens: TZQuery; begin ZQryTabelaPrecoItens := TZQuery.Create(nil); with ZQryTabelaPrecoItens do begin Connection := zcoConnection; SQL.Clear; SQL.Add('UPDATE tbTabelaPrecoItens SET sstatus = ' + QuotedStr('I') + ' '); SQL.Add('WHERE icodigo = :icodigo'); ParamByName('icodigo').AsInteger := iGetCodigo; ExecSQL; end; FreeAndNil(ZQryTabelaPrecoItens); end; destructor TTabelaPrecoItens.Destroy; begin FreeAndNil(oTabelaPreco); FreeAndNil(oProduto); inherited; end; function TTabelaPrecoItens.iCamposConsistentes: Integer; var iCont: SmallInt; slCampos: TStringList; begin Result := 0; slCampos := TStringList.Create; slCampos.CommaText := sCamposObrigatorios('tbtabelaprecoitens', zcoConnection); for iCont := 0 to slCampos.Count - 1 do begin if AnsiLowerCase(slCampos.Strings[iCont]) = 'npreco' then begin if (nGetPreco = 0) then begin Result := c_CampoVazio; eCampoNaoPreenchido.Create(StringReplace(asMensagemErro[c_CampoVazio], '%', 'Preço', [rfReplaceAll])); end; end; if AnsiLowerCase(slCampos.Strings[iCont]) = 'icodigo' then begin if (IntToStr(iGetCodigo) = '') or (iGetCodigo <= 0) then begin Result := c_CampoVazio; eCampoNaoPreenchido.Create(StringReplace(asMensagemErro[c_CampoVazio], '%', 'Código', [rfReplaceAll])); end; end; if AnsiLowerCase(slCampos.Strings[iCont]) = 'itabela' then begin if (IntToStr(oTabelaPreco.iGetCodigo) = '') or (oTabelaPreco.iGetCodigo <= 0) then begin Result := c_CampoVazio; eCampoNaoPreenchido.Create(StringReplace(asMensagemErro[c_CampoVazio], '%', 'Tabela', [rfReplaceAll])); end; end; if AnsiLowerCase(slCampos.Strings[iCont]) = 'iproduto' then begin if (IntToStr(oProduto.GetiCodigo) = '') or (oProduto.GetiCodigo <= 0) then begin Result := c_CampoVazio; eCampoNaoPreenchido.Create(StringReplace(asMensagemErro[c_CampoVazio], '%', 'Produto', [rfReplaceAll])); end; end; end; end; function TTabelaPrecoItens.iGetCodigo: Integer; begin Result := iCodigo; end; function TTabelaPrecoItens.iRetornaUltimoCodigo: Integer; var ZQryTabelaPrecoItens: TZQuery; begin ZQryTabelaPrecoItens := TZQuery.Create(nil); with ZQryTabelaPrecoItens do begin Connection := zcoConnection; SQL.Clear; SQL.Add('SELECT COALESCE(MAX(icodigo),0) AS ULTIMO FROM tbTabelaPrecoItens'); Open; Result := FieldByName('ULTIMO').AsInteger; end; FreeAndNil(ZQryTabelaPrecoItens); end; function TTabelaPrecoItens.nGetPreco: Real; begin Result := nPreco; end; procedure TTabelaPrecoItens.SetCodigo(piCodigo: Integer); begin iCodigo := piCodigo; end; procedure TTabelaPrecoItens.SetPreco(pnPreco: Real); begin nPreco := pnPreco; end; procedure TTabelaPrecoItens.SetStatus(psStatus: string); begin sStatus := psStatus; end; function TTabelaPrecoItens.sGetStatus: string; begin Result := sStatus; end; end.
unit DataSet.Model; interface uses System.SysUtils, System.Classes, Data.DB, Datasnap.DBClient, Spring, Spring.Collections, DataSet.Interfaces, MVVM.Interfaces, MVVM.Bindings; type TDataSet_Model = class(TDataModule, IDataSetFile_Model, IModel, INotifyChangedProperty) cdsSource: TClientDataSet; procedure DataModuleDestroy(Sender: TObject); procedure DataModuleCreate(Sender: TObject); private { Private declarations } FManager: IStrategyEventedObject; FFileName: String; protected function GetManager: IStrategyEventedObject; procedure SetManager(AManager: IStrategyEventedObject); function GetOnPropertyChangedEvent: IChangedPropertyEvent; function GetFileName: String; procedure SetFileName(const AFileName: String); function GetIsPathOK: Boolean; function GetDataSet: TDataSet; procedure Notify(const APropertyName: string = ''); public { Public declarations } constructor Create; overload; function GetAsObject: TObject; procedure Open; property DataSet: TDataSet read GetDataSet; property IsPathOk: Boolean read GetIsPathOK; property FileName: String read GetFileName write SetFileName; property Manager: IStrategyEventedObject read GetManager write SetManager; property OnPropertyChangedEvent: IChangedPropertyEvent read GetOnPropertyChangedEvent; end; var DataSet_Model: TDataSet_Model; implementation uses System.IOUtils; {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} procedure TDataSet_Model.DataModuleDestroy(Sender: TObject); begin FManager := nil; inherited; end; constructor TDataSet_Model.Create; begin inherited Create(nil); end; procedure TDataSet_Model.DataModuleCreate(Sender: TObject); begin inherited; end; { TdmDataSet } function TDataSet_Model.GetAsObject: TObject; begin Result := Self end; function TDataSet_Model.GetDataSet: TDataSet; begin Result := cdsSource; end; function TDataSet_Model.GetFileName: String; begin Result := FFileName end; function TDataSet_Model.GetIsPathOK: Boolean; begin Result := TFile.Exists(FFileName); end; function TDataSet_Model.GetManager: IStrategyEventedObject; begin if (FManager = nil) then FManager := TStrategyEventedObject.Create(Self); Result := FManager; end; function TDataSet_Model.GetOnPropertyChangedEvent: IChangedPropertyEvent; begin Result := Manager.OnPropertyChangedEvent; end; procedure TDataSet_Model.Notify(const APropertyName: string); begin Manager.NotifyPropertyChanged(Self, APropertyName); end; procedure TDataSet_Model.Open; begin if IsPathOk then begin cdsSource.LoadFromFile(FFileName); cdsSource.Active := True; end else raise Exception.Create('El fichero no existe'); end; procedure TDataSet_Model.SetFileName(const AFileName: String); begin if FFileName <> AFileName then begin FFileName := AFileName; Notify('FileName'); Notify('IsPathOK'); end; end; procedure TDataSet_Model.SetManager(AManager: IStrategyEventedObject); begin FManager := AManager; end; end.
unit TripackPascalDriver; interface uses FastGeo, TripackTypes; procedure TripackDemoPascal; procedure ModifiedTripackDemoPascal; procedure TRMTST (var N: longint; var X,Y: TNmaxSingleArray; var LIST,LPTR: TN6IntArray; var LEND: TNmaxIntArray; var LNEW: longint; var TOL: TFloat; var LUN:longint; var ARMAX: TFloat; var IER:longint); implementation uses {$IFDEF UseTripackMessages} TripackMessages, {$ENDIF} Math, TripackProcedures; procedure TripackDemoPascal; // subroutine TripackDemo // dll_export TripackDemo // dll_import Tripack205, Tripack210, Tripack212, Tripack214, // 1 Tripack220, Tripack230, Tripack240, Tripack250, Tripack260, // 2 Tripack270, Tripack400, Tripack410, Tripack420, Tripack430, // 3 Tripack440, Tripack450, Tripack460, Tripack470 //C //C //C TRITEST: Portable Test Driver for TRIPACK //C 07/02/98 //C //C //C This driver tests software package TRIPACK for construc- //C ting a constrained Delaunay triangulation of a set of //C points in the plane. All modules other than TRMSHR are //C tested unless an error is encountered, in which case the //C program terminates immediately. //C //C By default, tests are performed on a simple data set //C consisting of 12 nodes whose convex hull covers the unit //C square. The data set includes a single constraint region //C consisting of four nodes forming a smaller square at the //C center of the unit square. However, by enabling the READ //C statements below (C# in the first two columns), testing //C may be performed on an arbitrary set of up to NMAX nodes //C with up to NCMAX constraint curves. (Refer to the //C PARAMETER statements below.) A data set consists of the //C following sequence of records: //C //C N = Number of nodes (format I4) -- 3 to NMAX. //C NCC = Number of constraint curves (format I4) -- 0 to //C NCMAX. //C (LCC(I), I = 1,NCC) = Indexes of the first node in each //C constraint curve (format I4). 1 .LE. LCC(1) //C and, for I .GT. 1, LCC(I-1) + 3 .LE. LCC(I) //C .LE. N-2. (Each constraint curve has at least //C three nodes.) //C (X(I),Y(I), I = 1,N) = Nodal coordinates with non- //C constraint nodes followed by the NCC //C sequences of constraint nodes (format //C 2F13.8). //C //C The I/O units may be changed by altering LIN (input) and //C LOUT (output) in the DATA statement below. //C //C This driver must be linked to TRIPACK. //C var TITLE: string; IER, IO1, IO2, K, KSUM, LIN, LNEW, LOUT, LPLT, LW, {LWK,} N, N0, {N6,} NA, NB, NCC, {NCMAX, NMAX,} NN, NROW, NT {, NTMX}, K_Temp: longint; NUMBR, PRNTX: longbool; A, ARMAX, DSQ, PLTSIZ, TOL, WX1, WX2, WY1, WY2: TFloat; IFORTRAN: longint; LCC: TNcmaxIntarray; LCT: TNcmaxIntarray; LEND: TNmaxIntArray; LIST: TN6IntArray; LPTR: TN6IntArray; LTRI: TNtmx_LwkIntArray; NODES: TLwkIntArray; DS: TNmaxSingleArray; X: TNmaxSingleArray; Y: TNmaxSingleArray; I: Integer; IST_Temp: Integer; // CHARACTER*80 TITLE // INTEGER IER, IO1, IO2, K, KSUM, LIN, LNEW, LOUT, LPLT, // . LW, LWK, N, N0, N6, NA, NB, NCC, NCMAX, NMAX, // . NN, NROW, NT, NTMX // INTEGER NEARND // LOGICAL NUMBR, PRNTX // REAL A, ARMAX, DSQ, PLTSIZ, TOL, WX1, WX2, WY1, WY2 // REAL AREAP // INTEGER IFORTRAN //C // PARAMETER (NMAX=100, NCMAX=5, NTMX=2*NMAX, N6=6*NMAX, // . LWK=2*NMAX, NROW=9) //C //C Array storage: //C // INTEGER LCC(NCMAX), LCT(NCMAX), LEND(NMAX), LIST(N6), // . LPTR(N6), LTRI(NROW,NTMX), NODES(LWK) // REAL DS(NMAX), X(NMAX), Y(NMAX) //C //C Tolerance for TRMTST and NEARND: upper bound on squared //C distances. //C begin SetLength(LCC, NCMAX); SetLength(LCT, NCMAX); SetLength(LEND,NMAX); SetLength(LIST,N6); SetLength(LPTR,N6); SetLength(NODES,LWK); SetLength(LTRI,NTMX,TripackTypes.NROW); SetLength(DS,NMAX); SetLength(X,NMAX); SetLength(Y,NMAX); {$IFDEF UseTripackMessages} IFORTRAN :=2; {$ENDIF} NROW:=9; Tol := 1e-2; // DATA TOL/1.E-2/ //C //C Plot size for the triangulation plot. //C PLTSIZ := 7.5; // DATA PLTSIZ/7.5/ //C //C Default data set: //C N:= 12; NCC := 1; LCC[0] := 9; X[0] := 0; X[1] := 1; X[2] := 0.5; X[3] := 0.15; X[4] := 0.85; X[5] := 0.5; X[6] := 0; X[7] := 1; X[8] := 0.35; X[9] := 0.65; X[10] := 0.65; X[11] := 0.35; Y[0] := 0; Y[1] := 0; Y[2] := 0.15; Y[3] := 0.5; Y[4] := 0.5; Y[5] := 0.85; Y[6] := 1; Y[7] := 1; Y[8] := 0.35; Y[9] := 0.35; Y[10] := 0.65; Y[11] := 0.65; // DATA N/12/, NCC/1/, LCC(1)/9/ // DATA X(1), X(2), X(3), X(4), X(5), X(6), X(7) // . / 0., 1., .5, .15, .85, .5, 0./, // . X(8), X(9), X(10), X(11), X(12) // . / 1., .35, .65, .65, .35/, // . Y(1), Y(2), Y(3), Y(4), Y(5), Y(6), Y(7) // . / 0., 0., .15, .5, .5, .85, 1./, // . Y(8), Y(9), Y(10), Y(11), Y(12) // . / 1., .35, .35, .65, .65/ //C //C Logical unit numbers for I/O: //C LIN := 1; LOUT := 2; LPLT := 3; // DATA LIN/1/, LOUT/2/, LPLT/3/ // IFORTRAN = 1 // OPEN (LOUT,FILE='RES') // OPEN (LPLT,FILE='RES.eps') //C //C Store a plot title. It must be enclosed in parentheses. //C TITLE := '(Triangulation created by TRITEST)'; // TITLE = '(Triangulation created by TRITEST)' //C //C *** Read triangulation parameters -- N, NCC, LCC, X, Y. //C //C# OPEN (LIN,FILE='tritest.dat',STATUS='OLD') //C# READ (LIN,100,ERR=30) N, NCC IF (N < 3) OR (N > NMAX) OR (NCC < 0) OR (NCC > NCMAX) then begin {$IFDEF UseTripackMessages} Tripack205(IFORTRAN, N, NCC); {$ENDIF} Exit; end; //C# IF (NCC .GT. 0) READ (LIN,100,ERR=30) //C# . (LCC(K), K = 1,NCC) //C# READ (LIN,110,ERR=30) (X(K),Y(K), K = 1,N) //C#100 FORMAT (I4) //C#110 FORMAT (2F13.8) //C //C Print a heading. //C //! WRITE (LOUT,400) N // call Tripack400(IFORTRAN, N) {$IFDEF UseTripackMessages} Tripack400(IFORTRAN, N); {$ENDIF} //C //C *** Create the Delaunay triangulation (TRMESH), and test //C for errors (refer to TRMTST below). NODES and DS are //C used as work space. //C for I := 0 to Length(List) - 1 do begin List[I] := 0; end; for I := 0 to Length(LPTR) - 1 do begin LPTR[I] := 0; end; for I := 0 to Length(LEND) - 1 do begin LEND[I] := 0; end; LNEW := 0; IER := 0; TRMESH (N,X,Y, LIST,LPTR,LEND,LNEW,NODES, NODES,DS,IER,N); // CALL TRMESH (N,X,Y, LIST,LPTR,LEND,LNEW,NODES, // . NODES(N+1),DS,IER) IF (IER = -2) THEN begin {$IFDEF UseTripackMessages} Tripack210(IFORTRAN); {$ENDIF} Exit; end ELSE IF (IER = -4) THEN begin {$IFDEF UseTripackMessages} Tripack212(IFORTRAN); {$ENDIF} Exit; end ELSE IF (IER > 0) THEN begin {$IFDEF UseTripackMessages} Tripack214(IFORTRAN); {$ENDIF} Exit; end; // IF (IER .EQ. -2) THEN //! WRITE (LOUT,210) // CALL Tripack210(IFORTRAN) // return // ELSEIF (IER .EQ. -4) THEN // CALL Tripack212(IFORTRAN) //! WRITE (LOUT,212) // return // ELSEIF (IER .GT. 0) THEN // CALL Tripack214(IFORTRAN) //! WRITE (LOUT,214) // return // ENDIF TRMTST(N,X,Y,LIST,LPTR,LEND,LNEW,TOL,LOUT, ARMAX,IER); // CALL TRMTST (N,X,Y,LIST,LPTR,LEND,LNEW,TOL, // . LOUT, ARMAX,IER) {$IFDEF UseTripackMessages} Tripack410(IFORTRAN, ARMAX); {$ENDIF} // CALL Tripack410(IFORTRAN, ARMAX) //! WRITE (LOUT,410) ARMAX IF (IER > 0) then Exit; // IF (IER .GT. 0) return //C //C *** Add the constraint curves (ADDCST). Note that edges //C and triangles are not removed from constraint regions. //C ADDCST forces the inclusion of triangulation edges //C connecting the sequences of constraint nodes. If it //C is necessary to alter the triangulation, the empty //C circumcircle property is no longer satisfied. //C LW := LWK; ADDCST (NCC,LCC,N,X,Y, LW,NODES,LIST,LPTR, LEND, IER); // LW = LWK // CALL ADDCST (NCC,LCC,N,X,Y, LW,NODES,LIST,LPTR, // . LEND, IER) IF (IER <> 0) THEN begin {$IFDEF UseTripackMessages} Tripack220(IFORTRAN, IER); {$ENDIF} Exit; END; // IF (IER .NE. 0) THEN // CALL Tripack220(IFORTRAN, IER) //! WRITE (LOUT,220) IER // return // ENDIF //! IF (LW .EQ. 0) WRITE (LOUT,430) {$IFDEF UseTripackMessages} IF (LW = 0) then Tripack430(IFORTRAN); {$ENDIF} // IF (LW .EQ. 0) CALL Tripack430(IFORTRAN) //C //C *** Test TRPRNT, TRLIST, and TRLPRT, and TRPLOT. //C PRNTX := TRUE; TRPRNT (NCC,LCC,N,X,Y,LIST,LPTR,LEND,LOUT,PRNTX); // PRNTX = .TRUE. // CALL TRPRNT (NCC,LCC,N,X,Y,LIST,LPTR,LEND,LOUT,PRNTX) TRLIST (NCC,LCC,N,LIST,LPTR,LEND,NROW, NT,LTRI, LCT,IER); // CALL TRLIST (NCC,LCC,N,LIST,LPTR,LEND,NROW, NT,LTRI, // . LCT,IER) TRLPRT (NCC,LCT,N,X,Y,NROW,NT,LTRI,LOUT,PRNTX); // CALL TRLPRT (NCC,LCT,N,X,Y,NROW,NT,LTRI,LOUT,PRNTX) //C //C Set the plot window [WX1,WX2] X [WY1,WY2] to the //C smallest rectangle that contains the nodes. //C NUMBR = TRUE iff nodal indexes are to be displayed. //C WX1 := X[0]; WX2 := WX1; WY1 := Y[0]; WY2 := WY1; // WX1 = X(1) // WX2 = WX1 // WY1 = Y(1) // WY2 = WY1 for K := 1 to N - 1 do begin IF (X[K] < WX1) then WX1 := X[K]; IF (X[K] > WX2) then WX2 := X[K]; IF (Y[K] < WY1) then WY1 := Y[K]; IF (Y[K] > WY2) then WY2 := Y[K]; end; // DO 1 K = 2,N // IF (X(K) .LT. WX1) WX1 = X(K) // IF (X(K) .GT. WX2) WX2 = X(K) // IF (Y(K) .LT. WY1) WY1 = Y(K) // IF (Y(K) .GT. WY2) WY2 = Y(K) // 1 CONTINUE NUMBR := N <= 200; TRPLOT (LPLT,PLTSIZ,WX1,WX2,WY1,WY2,NCC,LCC,N, X,Y,LIST,LPTR,LEND,NUMBR, IER); // NUMBR = N .LE. 200 // CALL TRPLOT (LPLT,PLTSIZ,WX1,WX2,WY1,WY2,NCC,LCC,N, // . X,Y,LIST,LPTR,LEND,TITLE,NUMBR, IER) {$IFDEF UseTripackMessages} IF (IER = 0) THEN begin Tripack470(IFORTRAN); end ELSE begin Tripack270(IFORTRAN, IER); end; {$ENDIF} // IF (IER .EQ. 0) THEN // CALL Tripack470(IFORTRAN) // ! WRITE (LOUT,470) // ELSE // CALL Tripack270(IFORTRAN, IER) //! WRITE (LOUT,270) IER // ENDIF //C //C *** Test BNODES and AREAP. //C BNODES (N,LIST,LPTR,LEND, NODES,NB,NA,NT); // CALL BNODES (N,LIST,LPTR,LEND, NODES,NB,NA,NT) {$IFDEF UseTripackMessages} A := AREAP(X,Y,NB,NODES); // A = AREAP(X,Y,NB,NODES) Tripack420(IFORTRAN, NB, NA, NT, A); {$ENDIF} // CALL Tripack420(IFORTRAN, NB, NA, NT, A) //! WRITE (LOUT,420) NB, NA, NT, A //C //C *** Test GETNP by ordering the nodes on distance from N0 //C and verifying the ordering. //C N0 := N div 2; NODES[0] := N0; DS[0] := 0.0; KSUM := N0; for K := 2 to N do begin K_Temp := K; GETNP (NCC,LCC,N,X,Y,LIST,LPTR,LEND, K_Temp, NODES,DS, IER); IF (IER <> 0) OR (DS[K-1] < DS[K-2]) THEN begin {$IFDEF UseTripackMessages} Tripack230(IFORTRAN); {$ENDIF} Exit; END; KSUM := KSUM + NODES[K-1]; end; // N0 = N/2 // NODES(1) = N0 // DS(1) = 0. // KSUM = N0 // DO 2 K = 2,N // CALL GETNP (NCC,LCC,N,X,Y,LIST,LPTR,LEND, // . K, NODES,DS, IER) // IF (IER .NE. 0 .OR. DS(K) .LT. DS(K-1)) THEN // CALL Tripack230(IFORTRAN) //! WRITE (LOUT,230) // return // ENDIF // KSUM = KSUM + NODES(K) // 2 CONTINUE //C //C Test for all nodal indexes included in NODES. //C IF (KSUM <> (N*(N+1)) div 2) THEN begin {$IFDEF UseTripackMessages} Tripack230(IFORTRAN); {$ENDIF} Exit; END; // IF (KSUM .NE. (N*(N+1))/2) THEN // CALL Tripack230(IFORTRAN) //! WRITE (LOUT,230) // return // ENDIF //C //C *** Test NEARND by verifying that the nearest node to K is //C node K for K = 1 to N. //C for K := 1 to N do begin IST_Temp := 1; N0 := NEARND (X[K-1],Y[K-1],IST_Temp,N,X,Y,LIST,LPTR,LEND, DSQ); IF (N0 <> K) OR (DSQ > TOL) THEN begin {$IFDEF UseTripackMessages} Tripack240(IFORTRAN); {$ENDIF} Exit; END; end; // DO 3 K = 1,N // N0 = NEARND (X(K),Y(K),1,N,X,Y,LIST,LPTR,LEND, DSQ) // IF (N0 .NE. K .OR. DSQ .GT. TOL) THEN // CALL Tripack240(IFORTRAN) //!! WRITE (LOUT,240) // return // ENDIF // 3 CONTINUE //C //C *** Test DELARC by removing a boundary arc if possible. //C The first two nodes define a boundary arc //C in the default data set. //C IO1 := 1; IO2 := 2; DELARC (N,IO1,IO2, LIST,LPTR,LEND,LNEW, IER); IF (IER = 1) OR (IER = 4) THEN begin {$IFDEF UseTripackMessages} Tripack250(IFORTRAN, IER); {$ENDIF} Exit; END; {$IFDEF UseTripackMessages} IF (IER <> 0) then Tripack440(IFORTRAN); {$ENDIF} // IO1 = 1 // IO2 = 2 // CALL DELARC (N,IO1,IO2, LIST,LPTR,LEND,LNEW, IER) // IF (IER .EQ. 1 .OR. IER .EQ. 4) THEN // CALL Tripack250(IFORTRAN, IER) //! WRITE (LOUT,250) IER // return // ENDIF //! IF (IER .NE. 0) WRITE (LOUT,440) // IF (IER .NE. 0) CALL Tripack440(IFORTRAN) //CC //C Recreate the triangulation without constraints. //C TRMESH (N,X,Y, LIST,LPTR,LEND,LNEW,NODES, NODES,DS,IER,N); NCC := 0; // CALL TRMESH (N,X,Y, LIST,LPTR,LEND,LNEW,NODES, // . NODES(N+1),DS,IER) // NCC = 0 //C //C *** Test DELNOD by removing nodes 4 to N (in reverse //C order). //C IF (N <= 3) THEN begin {$IFDEF UseTripackMessages} Tripack450(IFORTRAN); {$ENDIF} end ELSE begin NN := N; repeat LW := LWK div 2; DELNOD (NN,NCC, LCC,NN,X,Y,LIST,LPTR,LEND, LNEW,LW,NODES, IER); IF (IER <> 0) THEN begin {$IFDEF UseTripackMessages} Tripack260(IFORTRAN, IER); {$ENDIF} Exit; END; until NN <= 3; END; // IF (N .LE. 3) THEN // CALL Tripack450(IFORTRAN) //! WRITE (LOUT,450) // ELSE // NN = N // 4 LW = LWK/2 // CALL DELNOD (NN,NCC, LCC,NN,X,Y,LIST,LPTR,LEND, // . LNEW,LW,NODES, IER) // IF (IER .NE. 0) THEN // CALL Tripack260(IFORTRAN, IER) //! WRITE (LOUT,260) IER // return // ENDIF // IF (NN .GT. 3) GO TO 4 // ENDIF //C //C Successful test. {$IFDEF UseTripackMessages} Tripack460(IFORTRAN); {$ENDIF} // CALL Tripack460(IFORTRAN) //! WRITE (LOUT,460) // return //C //C Error reading the data set. //C //C# 30 WRITE (*,200) //! STOP //C //C Invalid value of N or NCC. //C //! 31 WRITE (*,205) N, NCC // 31 CALL Tripack205(IFORTRAN, N, NCC) // return //C //C Error message formats: //C //C#200 FORMAT (//5X,'*** Input data set invalid ***'/) //! 205 FORMAT (//5X,'*** N or NCC is outside its valid ', //! . 'range: N =',I5,', NCC = ',I4,' ***'/) //! 210 FORMAT (//5X,'*** Error in TRMESH: the first three ', //! . 'nodes are collinear ***'/) //! 212 FORMAT (//5X,'*** Error in TRMESH: invalid ', //! . 'triangulation ***'/) //! 214 FORMAT (//5X,'*** Error in TRMESH: duplicate nodes ', //! . 'encountered ***'/) //! 220 FORMAT (//5X,'*** Error in ADDCST: IER = ',I1, //! . ' ***'/) //! 230 FORMAT (//5X,'*** Error in GETNP ***'/) //! 240 FORMAT (//5X,'*** Error in NEARND ***'/) //! 250 FORMAT (//5X,'*** Error in DELARC: IER = ',I1, //! . ' ***'/) //! 260 FORMAT (//5X,'*** Error in DELNOD: IER = ',I1, //! . ' ***'/) //! 270 FORMAT (//5X,'*** Error in TRPLOT: IER = ',I1, //! . ' ***'/) //C //C Informative message formats: //C //! 400 FORMAT (///1X,21X,'TRIPACK Test: N =',I5///) //! 410 FORMAT (5X,'Maximum triangle aspect ratio = ',E10.3//) //! 420 FORMAT (/5X,'Output from BNODES and AREAP'// //! . 5X,'BNODES: ',I4,' boundary nodes, ',I5, //! . ' edges, ',I5,' triangles'/5X, //! . 'AREAP: area of convex hull = ',E15.8//) //! 430 FORMAT (5X,'Subroutine EDGE not tested:'/ //! . 5X,' No edges were swapped by ADDCST'//) //! 440 FORMAT (5X,'Subroutine DELARC not tested:'/ //! . 5X,' Nodes 1 and 2 do not form a ', //! . 'removable boundary edge.'//) //! 450 FORMAT (5X,'Subroutine DELNOD not tested:'/ //! . 5X,' N cannot be reduced below 3'//) //! 460 FORMAT (5X,'No triangulation errors encountered.'/) //! 470 FORMAT (/5X,'A triangulation plot file was ', //! . 'successfully created.'/) // END end; procedure ModifiedTripackDemoPascal; // subroutine TripackDemo // dll_export TripackDemo // dll_import Tripack205, Tripack210, Tripack212, Tripack214, // 1 Tripack220, Tripack230, Tripack240, Tripack250, Tripack260, // 2 Tripack270, Tripack400, Tripack410, Tripack420, Tripack430, // 3 Tripack440, Tripack450, Tripack460, Tripack470 //C //C //C TRITEST: Portable Test Driver for TRIPACK //C 07/02/98 //C //C //C This driver tests software package TRIPACK for construc- //C ting a constrained Delaunay triangulation of a set of //C points in the plane. All modules other than TRMSHR are //C tested unless an error is encountered, in which case the //C program terminates immediately. //C //C By default, tests are performed on a simple data set //C consisting of 12 nodes whose convex hull covers the unit //C square. The data set includes a single constraint region //C consisting of four nodes forming a smaller square at the //C center of the unit square. However, by enabling the READ //C statements below (C# in the first two columns), testing //C may be performed on an arbitrary set of up to NMAX nodes //C with up to NCMAX constraint curves. (Refer to the //C PARAMETER statements below.) A data set consists of the //C following sequence of records: //C //C N = Number of nodes (format I4) -- 3 to NMAX. //C NCC = Number of constraint curves (format I4) -- 0 to //C NCMAX. //C (LCC(I), I = 1,NCC) = Indexes of the first node in each //C constraint curve (format I4). 1 .LE. LCC(1) //C and, for I .GT. 1, LCC(I-1) + 3 .LE. LCC(I) //C .LE. N-2. (Each constraint curve has at least //C three nodes.) //C (X(I),Y(I), I = 1,N) = Nodal coordinates with non- //C constraint nodes followed by the NCC //C sequences of constraint nodes (format //C 2F13.8). //C //C The I/O units may be changed by altering LIN (input) and //C LOUT (output) in the DATA statement below. //C //C This driver must be linked to TRIPACK. //C var TITLE: string; IER, IO1, IO2, K, KSUM, LIN, LNEW, LOUT, LPLT, LW, {LWK,} N, N0, {N6,} NA, NB, NCC, {NCMAX, NMAX,} NN, NROW, NT {, NTMX}, K_Temp: longint; NUMBR, PRNTX: longbool; A, ARMAX, DSQ, PLTSIZ, TOL, WX1, WX2, WY1, WY2: TFloat; IFORTRAN: longint; LCC: TNcmaxIntarray; LCT: TNcmaxIntarray; LEND: TNmaxIntArray; LIST: TN6IntArray; LPTR: TN6IntArray; LTRI: TNtmx_LwkIntArray; NODES: TLwkIntArray; DS: TNmaxSingleArray; X: TNmaxSingleArray; Y: TNmaxSingleArray; I: Integer; IST_Temp: Integer; // CHARACTER*80 TITLE // INTEGER IER, IO1, IO2, K, KSUM, LIN, LNEW, LOUT, LPLT, // . LW, LWK, N, N0, N6, NA, NB, NCC, NCMAX, NMAX, // . NN, NROW, NT, NTMX // INTEGER NEARND // LOGICAL NUMBR, PRNTX // REAL A, ARMAX, DSQ, PLTSIZ, TOL, WX1, WX2, WY1, WY2 // REAL AREAP // INTEGER IFORTRAN //C // PARAMETER (NMAX=100, NCMAX=5, NTMX=2*NMAX, N6=6*NMAX, // . LWK=2*NMAX, NROW=9) //C //C Array storage: //C // INTEGER LCC(NCMAX), LCT(NCMAX), LEND(NMAX), LIST(N6), // . LPTR(N6), LTRI(NROW,NTMX), NODES(LWK) // REAL DS(NMAX), X(NMAX), Y(NMAX) //C //C Tolerance for TRMTST and NEARND: upper bound on squared //C distances. //C begin SetLength(LCC, NCMAX); SetLength(LCT, NCMAX); SetLength(LEND,NMAX); SetLength(LIST,N6); SetLength(LPTR,N6); SetLength(NODES,LWK); SetLength(LTRI,NTMX,TripackTypes.NROW); SetLength(DS,NMAX); SetLength(X,NMAX); SetLength(Y,NMAX); {$IFDEF UseTripackMessages} IFORTRAN :=2; {$ENDIF} NROW:=9; Tol := 1e-2; // DATA TOL/1.E-2/ //C //C Plot size for the triangulation plot. //C PLTSIZ := 7.5; // DATA PLTSIZ/7.5/ //C //C Default data set: //C N:= 12; NCC := 1; LCC[0] := 9; X[0] := 0; X[1] := 1; X[2] := 0.5; X[3] := 0.15; X[4] := 0.85; X[5] := 0.5; X[6] := 0; X[7] := 1; X[8] := 0.05; X[9] := 0.65; X[10] := 0.65; X[11] := 0.35; Y[0] := 0; Y[1] := 0; Y[2] := 0.15; Y[3] := 0.5; Y[4] := 0.5; Y[5] := 0.85; Y[6] := 1; Y[7] := 1; Y[8] := 0.05; Y[9] := 0.35; Y[10] := 0.65; Y[11] := 0.65; // DATA N/12/, NCC/1/, LCC(1)/9/ // DATA X(1), X(2), X(3), X(4), X(5), X(6), X(7) // . / 0., 1., .5, .15, .85, .5, 0./, // . X(8), X(9), X(10), X(11), X(12) // . / 1., .35, .65, .65, .35/, // . Y(1), Y(2), Y(3), Y(4), Y(5), Y(6), Y(7) // . / 0., 0., .15, .5, .5, .85, 1./, // . Y(8), Y(9), Y(10), Y(11), Y(12) // . / 1., .35, .35, .65, .65/ //C //C Logical unit numbers for I/O: //C LIN := 1; LOUT := 2; LPLT := 3; // DATA LIN/1/, LOUT/2/, LPLT/3/ // IFORTRAN = 1 // OPEN (LOUT,FILE='RES') // OPEN (LPLT,FILE='RES.eps') //C //C Store a plot title. It must be enclosed in parentheses. //C TITLE := '(Triangulation created by TRITEST)'; // TITLE = '(Triangulation created by TRITEST)' //C //C *** Read triangulation parameters -- N, NCC, LCC, X, Y. //C //C# OPEN (LIN,FILE='tritest.dat',STATUS='OLD') //C# READ (LIN,100,ERR=30) N, NCC IF (N < 3) OR (N > NMAX) OR (NCC < 0) OR (NCC > NCMAX) then begin {$IFDEF UseTripackMessages} Tripack205(IFORTRAN, N, NCC); {$ENDIF} Exit; end; //C# IF (NCC .GT. 0) READ (LIN,100,ERR=30) //C# . (LCC(K), K = 1,NCC) //C# READ (LIN,110,ERR=30) (X(K),Y(K), K = 1,N) //C#100 FORMAT (I4) //C#110 FORMAT (2F13.8) //C //C Print a heading. //C //! WRITE (LOUT,400) N // call Tripack400(IFORTRAN, N) {$IFDEF UseTripackMessages} Tripack400(IFORTRAN, N); {$ENDIF} //C //C *** Create the Delaunay triangulation (TRMESH), and test //C for errors (refer to TRMTST below). NODES and DS are //C used as work space. //C for I := 0 to Length(List) - 1 do begin List[I] := 0; end; for I := 0 to Length(LPTR) - 1 do begin LPTR[I] := 0; end; for I := 0 to Length(LEND) - 1 do begin LEND[I] := 0; end; LNEW := 0; IER := 0; TRMESH (N,X,Y, LIST,LPTR,LEND,LNEW,NODES, NODES,DS,IER,N); // CALL TRMESH (N,X,Y, LIST,LPTR,LEND,LNEW,NODES, // . NODES(N+1),DS,IER) IF (IER = -2) THEN begin {$IFDEF UseTripackMessages} Tripack210(IFORTRAN); {$ENDIF} Exit; end ELSE IF (IER = -4) THEN begin {$IFDEF UseTripackMessages} Tripack212(IFORTRAN); {$ENDIF} Exit; end ELSE IF (IER > 0) THEN begin {$IFDEF UseTripackMessages} Tripack214(IFORTRAN); {$ENDIF} Exit; end; // IF (IER .EQ. -2) THEN //! WRITE (LOUT,210) // CALL Tripack210(IFORTRAN) // return // ELSEIF (IER .EQ. -4) THEN // CALL Tripack212(IFORTRAN) //! WRITE (LOUT,212) // return // ELSEIF (IER .GT. 0) THEN // CALL Tripack214(IFORTRAN) //! WRITE (LOUT,214) // return // ENDIF TRMTST(N,X,Y,LIST,LPTR,LEND,LNEW,TOL,LOUT, ARMAX,IER); // CALL TRMTST (N,X,Y,LIST,LPTR,LEND,LNEW,TOL, // . LOUT, ARMAX,IER) PRNTX := TRUE; TRPRNT (NCC,LCC,N,X,Y,LIST,LPTR,LEND,LOUT,PRNTX); // PRNTX = .TRUE. // CALL TRPRNT (NCC,LCC,N,X,Y,LIST,LPTR,LEND,LOUT,PRNTX) TRLIST (NCC,LCC,N,LIST,LPTR,LEND,NROW, NT,LTRI, LCT,IER); // CALL TRLIST (NCC,LCC,N,LIST,LPTR,LEND,NROW, NT,LTRI, // . LCT,IER) TRLPRT (NCC,LCT,N,X,Y,NROW,NT,LTRI,LOUT,PRNTX); {$IFDEF UseTripackMessages} Tripack410(IFORTRAN, ARMAX); {$ENDIF} // CALL Tripack410(IFORTRAN, ARMAX) //! WRITE (LOUT,410) ARMAX IF (IER > 0) then Exit; // IF (IER .GT. 0) return //C //C *** Add the constraint curves (ADDCST). Note that edges //C and triangles are not removed from constraint regions. //C ADDCST forces the inclusion of triangulation edges //C connecting the sequences of constraint nodes. If it //C is necessary to alter the triangulation, the empty //C circumcircle property is no longer satisfied. //C LW := LWK; ADDCST (NCC,LCC,N,X,Y, LW,NODES,LIST,LPTR, LEND, IER); // LW = LWK // CALL ADDCST (NCC,LCC,N,X,Y, LW,NODES,LIST,LPTR, // . LEND, IER) IF (IER <> 0) THEN begin {$IFDEF UseTripackMessages} Tripack220(IFORTRAN, IER); {$ENDIF} Exit; END; // IF (IER .NE. 0) THEN // CALL Tripack220(IFORTRAN, IER) //! WRITE (LOUT,220) IER // return // ENDIF //! IF (LW .EQ. 0) WRITE (LOUT,430) {$IFDEF UseTripackMessages} IF (LW = 0) then Tripack430(IFORTRAN); {$ENDIF} // IF (LW .EQ. 0) CALL Tripack430(IFORTRAN) //C //C *** Test TRPRNT, TRLIST, and TRLPRT, and TRPLOT. //C PRNTX := TRUE; TRPRNT (NCC,LCC,N,X,Y,LIST,LPTR,LEND,LOUT,PRNTX); // PRNTX = .TRUE. // CALL TRPRNT (NCC,LCC,N,X,Y,LIST,LPTR,LEND,LOUT,PRNTX) TRLIST (NCC,LCC,N,LIST,LPTR,LEND,NROW, NT,LTRI, LCT,IER); // CALL TRLIST (NCC,LCC,N,LIST,LPTR,LEND,NROW, NT,LTRI, // . LCT,IER) TRLPRT (NCC,LCT,N,X,Y,NROW,NT,LTRI,LOUT,PRNTX); // CALL TRLPRT (NCC,LCT,N,X,Y,NROW,NT,LTRI,LOUT,PRNTX) //C //C Set the plot window [WX1,WX2] X [WY1,WY2] to the //C smallest rectangle that contains the nodes. //C NUMBR = TRUE iff nodal indexes are to be displayed. //C WX1 := X[0]; WX2 := WX1; WY1 := Y[0]; WY2 := WY1; // WX1 = X(1) // WX2 = WX1 // WY1 = Y(1) // WY2 = WY1 for K := 1 to N - 1 do begin IF (X[K] < WX1) then WX1 := X[K]; IF (X[K] > WX2) then WX2 := X[K]; IF (Y[K] < WY1) then WY1 := Y[K]; IF (Y[K] > WY2) then WY2 := Y[K]; end; // DO 1 K = 2,N // IF (X(K) .LT. WX1) WX1 = X(K) // IF (X(K) .GT. WX2) WX2 = X(K) // IF (Y(K) .LT. WY1) WY1 = Y(K) // IF (Y(K) .GT. WY2) WY2 = Y(K) // 1 CONTINUE NUMBR := N <= 200; TRPLOT (LPLT,PLTSIZ,WX1,WX2,WY1,WY2,NCC,LCC,N, X,Y,LIST,LPTR,LEND,NUMBR, IER); // NUMBR = N .LE. 200 // CALL TRPLOT (LPLT,PLTSIZ,WX1,WX2,WY1,WY2,NCC,LCC,N, // . X,Y,LIST,LPTR,LEND,TITLE,NUMBR, IER) {$IFDEF UseTripackMessages} IF (IER = 0) THEN begin Tripack470(IFORTRAN); end ELSE begin Tripack270(IFORTRAN, IER); end; {$ENDIF} // IF (IER .EQ. 0) THEN // CALL Tripack470(IFORTRAN) // ! WRITE (LOUT,470) // ELSE // CALL Tripack270(IFORTRAN, IER) //! WRITE (LOUT,270) IER // ENDIF //C //C *** Test BNODES and AREAP. //C BNODES (N,LIST,LPTR,LEND, NODES,NB,NA,NT); // CALL BNODES (N,LIST,LPTR,LEND, NODES,NB,NA,NT) {$IFDEF UseTripackMessages} A := AREAP(X,Y,NB,NODES); // A = AREAP(X,Y,NB,NODES) Tripack420(IFORTRAN, NB, NA, NT, A); {$ENDIF} // CALL Tripack420(IFORTRAN, NB, NA, NT, A) //! WRITE (LOUT,420) NB, NA, NT, A //C //C *** Test GETNP by ordering the nodes on distance from N0 //C and verifying the ordering. //C N0 := N div 2; NODES[0] := N0; DS[0] := 0.0; KSUM := N0; for K := 2 to N do begin K_Temp := K; GETNP (NCC,LCC,N,X,Y,LIST,LPTR,LEND, K_Temp, NODES,DS, IER); IF (IER <> 0) OR (DS[K-1] < DS[K-2]) THEN begin {$IFDEF UseTripackMessages} Tripack230(IFORTRAN); {$ENDIF} Exit; END; KSUM := KSUM + NODES[K-1]; end; // N0 = N/2 // NODES(1) = N0 // DS(1) = 0. // KSUM = N0 // DO 2 K = 2,N // CALL GETNP (NCC,LCC,N,X,Y,LIST,LPTR,LEND, // . K, NODES,DS, IER) // IF (IER .NE. 0 .OR. DS(K) .LT. DS(K-1)) THEN // CALL Tripack230(IFORTRAN) //! WRITE (LOUT,230) // return // ENDIF // KSUM = KSUM + NODES(K) // 2 CONTINUE //C //C Test for all nodal indexes included in NODES. //C IF (KSUM <> (N*(N+1)) div 2) THEN begin {$IFDEF UseTripackMessages} Tripack230(IFORTRAN); {$ENDIF} Exit; END; // IF (KSUM .NE. (N*(N+1))/2) THEN // CALL Tripack230(IFORTRAN) //! WRITE (LOUT,230) // return // ENDIF //C //C *** Test NEARND by verifying that the nearest node to K is //C node K for K = 1 to N. //C for K := 1 to N do begin IST_Temp := 1; N0 := NEARND (X[K-1],Y[K-1],IST_Temp,N,X,Y,LIST,LPTR,LEND, DSQ); IF (N0 <> K) OR (DSQ > TOL) THEN begin {$IFDEF UseTripackMessages} Tripack240(IFORTRAN); {$ENDIF} Exit; END; end; // DO 3 K = 1,N // N0 = NEARND (X(K),Y(K),1,N,X,Y,LIST,LPTR,LEND, DSQ) // IF (N0 .NE. K .OR. DSQ .GT. TOL) THEN // CALL Tripack240(IFORTRAN) //!! WRITE (LOUT,240) // return // ENDIF // 3 CONTINUE //C //C *** Test DELARC by removing a boundary arc if possible. //C The first two nodes define a boundary arc //C in the default data set. //C IO1 := 1; IO2 := 2; DELARC (N,IO1,IO2, LIST,LPTR,LEND,LNEW, IER); IF (IER = 1) OR (IER = 4) THEN begin {$IFDEF UseTripackMessages} Tripack250(IFORTRAN, IER); {$ENDIF} Exit; END; {$IFDEF UseTripackMessages} IF (IER <> 0) then Tripack440(IFORTRAN); {$ENDIF} // IO1 = 1 // IO2 = 2 // CALL DELARC (N,IO1,IO2, LIST,LPTR,LEND,LNEW, IER) // IF (IER .EQ. 1 .OR. IER .EQ. 4) THEN // CALL Tripack250(IFORTRAN, IER) //! WRITE (LOUT,250) IER // return // ENDIF //! IF (IER .NE. 0) WRITE (LOUT,440) // IF (IER .NE. 0) CALL Tripack440(IFORTRAN) //CC //C Recreate the triangulation without constraints. //C TRMESH (N,X,Y, LIST,LPTR,LEND,LNEW,NODES, NODES,DS,IER,N); NCC := 0; // CALL TRMESH (N,X,Y, LIST,LPTR,LEND,LNEW,NODES, // . NODES(N+1),DS,IER) // NCC = 0 //C //C *** Test DELNOD by removing nodes 4 to N (in reverse //C order). //C IF (N <= 3) THEN begin {$IFDEF UseTripackMessages} Tripack450(IFORTRAN); {$ENDIF} end ELSE begin NN := N; repeat LW := LWK div 2; DELNOD (NN,NCC, LCC,NN,X,Y,LIST,LPTR,LEND, LNEW,LW,NODES, IER); IF (IER <> 0) THEN begin {$IFDEF UseTripackMessages} Tripack260(IFORTRAN, IER); {$ENDIF} Exit; END; until NN <= 3; END; // IF (N .LE. 3) THEN // CALL Tripack450(IFORTRAN) //! WRITE (LOUT,450) // ELSE // NN = N // 4 LW = LWK/2 // CALL DELNOD (NN,NCC, LCC,NN,X,Y,LIST,LPTR,LEND, // . LNEW,LW,NODES, IER) // IF (IER .NE. 0) THEN // CALL Tripack260(IFORTRAN, IER) //! WRITE (LOUT,260) IER // return // ENDIF // IF (NN .GT. 3) GO TO 4 // ENDIF //C //C Successful test. {$IFDEF UseTripackMessages} Tripack460(IFORTRAN); {$ENDIF} // CALL Tripack460(IFORTRAN) //! WRITE (LOUT,460) // return //C //C Error reading the data set. //C //C# 30 WRITE (*,200) //! STOP //C //C Invalid value of N or NCC. //C //! 31 WRITE (*,205) N, NCC // 31 CALL Tripack205(IFORTRAN, N, NCC) // return //C //C Error message formats: //C //C#200 FORMAT (//5X,'*** Input data set invalid ***'/) //! 205 FORMAT (//5X,'*** N or NCC is outside its valid ', //! . 'range: N =',I5,', NCC = ',I4,' ***'/) //! 210 FORMAT (//5X,'*** Error in TRMESH: the first three ', //! . 'nodes are collinear ***'/) //! 212 FORMAT (//5X,'*** Error in TRMESH: invalid ', //! . 'triangulation ***'/) //! 214 FORMAT (//5X,'*** Error in TRMESH: duplicate nodes ', //! . 'encountered ***'/) //! 220 FORMAT (//5X,'*** Error in ADDCST: IER = ',I1, //! . ' ***'/) //! 230 FORMAT (//5X,'*** Error in GETNP ***'/) //! 240 FORMAT (//5X,'*** Error in NEARND ***'/) //! 250 FORMAT (//5X,'*** Error in DELARC: IER = ',I1, //! . ' ***'/) //! 260 FORMAT (//5X,'*** Error in DELNOD: IER = ',I1, //! . ' ***'/) //! 270 FORMAT (//5X,'*** Error in TRPLOT: IER = ',I1, //! . ' ***'/) //C //C Informative message formats: //C //! 400 FORMAT (///1X,21X,'TRIPACK Test: N =',I5///) //! 410 FORMAT (5X,'Maximum triangle aspect ratio = ',E10.3//) //! 420 FORMAT (/5X,'Output from BNODES and AREAP'// //! . 5X,'BNODES: ',I4,' boundary nodes, ',I5, //! . ' edges, ',I5,' triangles'/5X, //! . 'AREAP: area of convex hull = ',E15.8//) //! 430 FORMAT (5X,'Subroutine EDGE not tested:'/ //! . 5X,' No edges were swapped by ADDCST'//) //! 440 FORMAT (5X,'Subroutine DELARC not tested:'/ //! . 5X,' Nodes 1 and 2 do not form a ', //! . 'removable boundary edge.'//) //! 450 FORMAT (5X,'Subroutine DELNOD not tested:'/ //! . 5X,' N cannot be reduced below 3'//) //! 460 FORMAT (5X,'No triangulation errors encountered.'/) //! 470 FORMAT (/5X,'A triangulation plot file was ', //! . 'successfully created.'/) // END end; procedure TRMTST (var N: longint; var X,Y: TNmaxSingleArray; var LIST,LPTR: TN6IntArray; var LEND: TNmaxIntArray; var LNEW: longint; var TOL: TFloat; var LUN:longint; var ARMAX: TFloat; var IER:longint); // SUBROUTINE TRMTST (N,X,Y,LIST,LPTR,LEND,LNEW,TOL, // . LUN, ARMAX,IER,IFORTRAN) // dll_import Trmtst100, Trmtst110, Trmtst120, Trmtst130, Trmtst140, // 1 Trmtst150 // INTEGER N, LIST(*), LPTR(*), LEND(N), LNEW, LUN, IER // REAL X(N), Y(N), TOL, ARMAX //C //C*********************************************************** //C //C From TRPTEST //C Robert J. Renka //C Dept. of Computer Science //C Univ. of North Texas //C (817) 565-2767 //C 09/01/91 //C //C This subroutine tests the validity of the data structure //C representing a Delaunay triangulation created by subrou- //C tine TRMESH. The following properties are tested: //C //C 1) Each interior node has at least three neighbors, and //C each boundary node has at least two neighbors. //C //C 2) abs(LIST(LP)) is a valid nodal index in the range //C 1 to N and LIST(LP) > 0 unless LP = LEND(K) for some //C nodal index K. //C //C 3) Each pointer LEND(K) for K = 1 to N and LPTR(LP) for //C LP = 1 to LNEW-1 is a valid LIST index in the range //C 1 to LNEW-1. //C //C 4) N .GE. NB .GE. 3, NT = 2*N-NB-2, and NA = 3*N-NB-3 = //C (LNEW-1)/2, where NB, NT, and NA are the numbers of //C boundary nodes, triangles, and arcs, respectively. //C //C 5) Each circumcircle defined by the vertices of a tri- //C angle contains no nodes in its interior. This prop- //C erty distinguishes a Delaunay triangulation from an //C arbitrary triangulation of the nodes. //C //C Note that no test is made for the property that a triangu- //C lation covers the convex hull of the nodes. //C //C On input: //C //C N = Number of nodes. N .GE. 3. //C //C X,Y = Arrays of length N containing the nodal //C coordinates. //C //C LIST,LPTR,LEND = Data structure containing the tri- //C angulation. Refer to subroutine //C TRMESH. //C //C TOL = Nonnegative tolerance to allow for floating- //C point errors in the circumcircle test. An //C error situation is defined as (R**2 - D**2)/ //C R**2 > TOL, where R is the radius of a circum- //C circle and D is the distance from the //C circumcenter to the nearest node. A reason- //C able value for TOL is 10*EPS, where EPS is the //C machine precision. The test is effectively //C bypassed by making TOL large. If TOL < 0, the //C tolerance is taken to be 0. //C //C LUN = Logical unit number for printing error mes- //C sages. If LUN < 0 or LUN > 99, no messages //C are printed. //C //C Input parameters are not altered by this routine. //C //C On output: //C //C ARMAX = Maximum aspect ratio (radius of inscribed //C circle divided by circumradius) of a trian- //C gle in the triangulation unless IER > 0. //C //C IER = Error indicator: //C IER = -1 if one or more null triangles (area = //C 0) are present but no (other) errors //C were encountered. A null triangle is //C an error only if it occurs in the //C the interior. //C IER = 0 if no errors or null triangles were //C encountered. //C IER = 1 if a node has too few neighbors. //C IER = 2 if a LIST entry is outside its valid //C range. //C IER = 3 if a LPTR or LEND entry is outside its //C valid range. //C IER = 4 if the triangulation parameters (N, //C NB, NT, NA, and LNEW) are inconsistent //C (or N < 3 or LNEW is invalid). //C IER = 5 if a triangle contains a node interior //C to its circumcircle. //C //C Module required by TRMTST: CIRCUM //C //C Intrinsic function called by TRMTST: MAX, ABS //C //C*********************************************************** //C var K, LP, LPL, LPMAX, LPN, N1, N2, N3, NA, NB, NFAIL, NN, NNB, NT, NULL: longint; RATIO, RITE: longbool; AR, CR, CX, CY, RS, RTOL, SA: TFloat; IFORTRAN: longint; N1_Temp: Integer; // INTEGER K, LP, LPL, LPMAX, LPN, N1, N2, N3, NA, NB, // . NFAIL, NN, NNB, NT, NULL // LOGICAL RATIO, RITE // REAL AR, CR, CX, CY, RS, RTOL, SA // integer IFORTRAN begin //C //C Store local variables, test for errors in input, and //C initialize counts. //C IFORTRAN := 2; NN := N; LPMAX := LNEW - 1; RTOL := TOL; IF (RTOL < 0.0) then RTOL := 0.0; RATIO := TRUE; ARMAX := 0.0; RITE := (LUN >= 0) AND (LUN <= 99); IF (NN < 3) then begin //C Inconsistent triangulation parameters encountered. //C IER := 4; {$IFDEF UseTripackMessages} IF (RITE) then Trmtst140(IFORTRAN, N, LNEW, NB, NT, NA); {$ENDIF} Exit; end; NB := 0; NT := 0; NULL := 0; NFAIL := 0; // NN = N // LPMAX = LNEW - 1 // RTOL = TOL // IF (RTOL .LT. 0.) RTOL = 0. // RATIO = .TRUE. // ARMAX = 0. // RITE = LUN .GE. 0 .AND. LUN .LE. 99 // IF (NN .LT. 3) GO TO 14 // NB = 0 // NT = 0 // NULL = 0 // NFAIL = 0 //C //C Loop on triangles (N1,N2,N3) such that N2 and N3 index //C adjacent neighbors of N1 and are both larger than N1 //C (each triangle is associated with its smallest index). //C NNB is the neighbor count for N1. //C for N1 := 1 to NN do begin NNB := 0; LPL := LEND[N1-1]; IF (LPL < 1) OR (LPL > LPMAX) THEN begin LP := LPL; //C LIST pointer LP is outside its valid range. //C IER := 3; {$IFDEF UseTripackMessages} N1_Temp := N1; IF (RITE) then Trmtst130(IFORTRAN, LP, LNEW, N1_Temp); {$ENDIF} Exit; end; LP := LPL; // DO 5 N1 = 1,NN // NNB = 0 // LPL = LEND(N1) // IF (LPL .LT. 1 .OR. LPL .GT. LPMAX) THEN // LP = LPL // GO TO 13 // ENDIF // LP = LPL //C //C Loop on neighbors of N1. //C repeat LP := LPTR[LP-1]; NNB := NNB + 1; IF (LP < 1) OR (LP > LPMAX) then begin //C LIST pointer LP is outside its valid range. //C IER := 3; {$IFDEF UseTripackMessages} N1_Temp := N1; IF (RITE) then Trmtst130(IFORTRAN, LP, LNEW, N1_Temp); {$ENDIF} Exit; end; // 1 LP = LPTR(LP) // NNB = NNB + 1 // IF (LP .LT. 1 .OR. LP .GT. LPMAX) GO TO 13 N2 := LIST[LP-1]; IF (N2 < 0) THEN begin IF (LP <> LPL) then begin //C N2 = LIST(LP) is outside its valid range. //C IER := 2; {$IFDEF UseTripackMessages} N1_Temp := N1; IF (RITE) then Trmtst120(IFORTRAN, N2, LP, N1_Temp); {$ENDIF} Exit; end; IF (N2 = 0) OR (-N2 > NN) then begin //C N2 = LIST(LP) is outside its valid range. //C IER := 2; {$IFDEF UseTripackMessages} N1_Temp := N1; IF (RITE) then Trmtst120(IFORTRAN, N2, LP, N1_Temp); {$ENDIF} Exit; end; NB := NB + 1; END else begin // N2 = LIST(LP) // IF (N2 .LT. 0) THEN // IF (LP .NE. LPL) GO TO 12 // IF (N2 .EQ. 0 .OR. -N2 .GT. NN) GO TO 12 // NB = NB + 1 // GO TO 4 // ENDIF IF (N2 < 1) OR (N2 > NN) then begin //C N2 = LIST(LP) is outside its valid range. //C IER := 2; {$IFDEF UseTripackMessages} N1_Temp := N1; IF (RITE) then Trmtst120(IFORTRAN, N2, LP, N1_Temp); {$ENDIF} Exit; end; LPN := LPTR[LP-1]; N3 := ABS(LIST[LPN-1]); IF (N2 >= N1) AND (N3 >= N1) then begin NT := NT + 1; // IF (N2 .LT. 1 .OR. N2 .GT. NN) GO TO 12 // LPN = LPTR(LP) // N3 = ABS(LIST(LPN)) // IF (N2 .LT. N1 .OR. N3 .LT. N1) GO TO 4 // NT = NT + 1 //C //C Compute the coordinates of the circumcenter of //C (N1,N2,N3). //C CIRCUM (X[N1-1],Y[N1-1],X[N2-1],Y[N2-1],X[N3-1],Y[N3-1], RATIO, CX,CY,CR,SA,AR); IF (SA = 0.0) THEN begin NULL := NULL + 1; END else begin ARMAX := MAX(ARMAX,AR); // CALL CIRCUM (X(N1),Y(N1),X(N2),Y(N2),X(N3),Y(N3), // . RATIO, CX,CY,CR,SA,AR) // IF (SA .EQ. 0.) THEN // NULL = NULL + 1 // GO TO 4 // ENDIF // ARMAX = MAX(ARMAX,AR) //C //C Test for nodes within the circumcircle. //C RS := CR*CR*(1.0-RTOL); for K := 1 to NN do begin IF (K = N1) OR (K = N2) OR (K = N3) then begin continue; end; IF (Sqr(CX-X[K-1]) + Sqr(CY-Y[K-1]) < RS) then begin //C Node K is interior to the circumcircle of (N1,N2,N3). NFAIL := NFAIL + 1; break; end; end; // RS = CR*CR*(1.-RTOL) // DO 2 K = 1,NN // IF (K .EQ. N1 .OR. K .EQ. N2 .OR. // . K .EQ. N3) GO TO 2 // IF ((CX-X(K))**2 + (CY-Y(K))**2 .LT. RS) GO TO 3 // 2 CONTINUE // GO TO 4 //C //C Node K is interior to the circumcircle of (N1,N2,N3). //C // 3 NFAIL = NFAIL + 1 //C //C Bottom of loop on neighbors. //C // 4 IF (LP .NE. LPL) GO TO 1 end; end; end; until LP = LPL; IF (NNB < 2) OR ((NNB = 2) AND (LIST[LPL-1] > 0)) then begin //C Node N1 has fewer than three neighbors. //C IER := 1; N1_Temp := N1; {$IFDEF UseTripackMessages} IF (RITE) then Trmtst110(IFORTRAN, N1_Temp, NNB); {$ENDIF} Exit end; // IF (NNB .LT. 2 .OR. (NNB .EQ. 2 .AND. // . LIST(LPL) .GT. 0)) GO TO 11 // 5 CONTINUE end; //C //C Test parameters for consistency and check for NFAIL = 0. //C NA := LPMAX div 2; IF (NB < 3) OR (NT <> 2*NN-NB-2) OR (NA <> 3*NN-NB-3) then begin //C Inconsistent triangulation parameters encountered. //C IER := 4; {$IFDEF UseTripackMessages} IF (RITE) then Trmtst140(IFORTRAN, N, LNEW, NB, NT, NA); {$ENDIF} Exit end; IF (NFAIL <> 0) then begin //C Circumcircle test failure. //C IER := 5; {$IFDEF UseTripackMessages} IF (RITE) then Trmtst150(IFORTRAN, NFAIL); {$ENDIF} Exit; end; // NA = LPMAX/2 // IF (NB .LT. 3 .OR. NT .NE. 2*NN-NB-2 .OR. // . NA .NE. 3*NN-NB-3) GO TO 14 // IF (NFAIL .NE. 0) GO TO 15 //C //C No errors were encountered. //C IER := 0; IF (NULL = 0) then begin Exit; end; IER := -1; {$IFDEF UseTripackMessages} IF (RITE) then Trmtst100(IFORTRAN, NULL); {$ENDIF} // IER = 0 // IF (NULL .EQ. 0) RETURN // IER = -1 //! IF (RITE) WRITE (LUN,100) NULL // IF (RITE) call Trmtst100(IFORTRAN, NULL) //! 100 FORMAT (//5X,'*** TRMTST -- ',I5,' NULL TRIANGLES ', //! . 'ARE PRESENT'/19X,'(NULL TRIANGLES ', //! . 'ON THE BOUNDARY ARE UNAVOIDABLE) ***'//) // RETURN //C //C Node N1 has fewer than three neighbors. //C // 11 IER = 1 //! IF (RITE) WRITE (LUN,110) N1, NNB // IF (RITE) CALL Trmtst110(IFORTRAN, N1, NNB) //! 110 FORMAT (//5X,'*** TRMTST -- NODE ',I5, //! . ' HAS ONLY ',I5,' NEIGHBORS ***'/) // RETURN //C //C N2 = LIST(LP) is outside its valid range. //C // 12 IER = 2 // ! IF (RITE) WRITE (LUN,120) N2, LP, N1 // IF (RITE) CALL Trmtst120(IFORTRAN, N2, LP, N1) //! 120 FORMAT (//5X,'*** TRMTST -- LIST(LP) =',I5, //! . ', FOR LP =',I5,','/19X, //! .'IS NOT A VALID NEIGHBOR OF ',I5,' ***'/) // RETURN //C //C LIST pointer LP is outside its valid range. //C // 13 IER = 3 //! IF (RITE) WRITE (LUN,130) LP, LNEW, N1 // IF (RITE) CALL Trmtst130(IFORTRAN, LP, LNEW, N1) //! 130 FORMAT (//5X,'*** TRMTST -- LP =',I5,' IS NOT IN THE', //! . ' RANGE 1 TO LNEW-1 FOR LNEW = ',I5/ //! . 19X,'LP POINTS TO A NEIGHBOR OF ',I5, //! . ' ***'/) // RETURN //C //C Inconsistent triangulation parameters encountered. //C // 14 IER = 4 //! IF (RITE) WRITE (LUN,140) N, LNEW, NB, NT, NA // IF (RITE) CALL Trmtst140(IFORTRAN, N, LNEW, NB, NT, NA) //! 140 FORMAT (//5X,'*** TRMTST -- INCONSISTENT PARAMETERS', //! . ' ***'/19X,'N = ',I5,' NODES',12X,'LNEW =',I5/ //! . 19X,'NB = ',I5,' BOUNDARY NODES'/ //! . 19X,'NT = ',I5,' TRIANGLES'/ //! . 19X,'NA = ',I5,' ARCS'/) // RETURN //C //C Circumcircle test failure. //C // 15 IER = 5 //! IF (RITE) WRITE (LUN,150) NFAIL // IF (RITE) CALL Trmtst140(IFORTRAN, NFAIL) //! 150 FORMAT (//5X,'*** TRMTST -- ',I5,' CIRCUMCIRCLES ', //! . 'CONTAIN NODES IN THEIR INTERIORS ***'/) // RETURN // END end; end.
UNIT PoTweak; { DESCRIPTION: Fixing Erm PO command to support maps of any size AUTHOR: Alexander Shostak (aka Berserker aka EtherniDee aka BerSoft) } (***) INTERFACE (***) USES Core, GameExt, Heroes, Stores; CONST FILE_SECTION_NAME = 'EraPO'; TYPE PSquare = ^TSquare; TSquare = INTEGER; PSquare2 = ^TSquare2; TSquare2 = PACKED ARRAY [0..15] OF BYTE; CONST ErmSquare: ^PSquare = Ptr($27C9678); ErmSquare2: ^PSquare2 = Ptr($9A48A0); VAR Squares: ARRAY OF BYTE; Squares2: ARRAY OF BYTE; MapSize: INTEGER; BasicPoSize: INTEGER; SquaresSize: INTEGER; Squares2Size: INTEGER; SecondDimSize: INTEGER; SecondDimSize2: INTEGER; (***) IMPLEMENTATION (***) PROCEDURE PatchSquaresRefs; BEGIN MapSize := Heroes.GetMapSize; BasicPoSize := MapSize * MapSize * 2; SquaresSize := BasicPoSize * SIZEOF(TSquare); Squares2Size := BasicPoSize * SIZEOF(TSquare2); IF SquaresSize > LENGTH(Squares) THEN BEGIN SetLength(Squares, SquaresSize); END; // .IF IF Squares2Size > LENGTH(Squares2) THEN BEGIN SetLength(Squares2, Squares2Size); END; // .IF SecondDimSize := MapSize * 2 * SIZEOF(TSquare); SecondDimSize2 := MapSize * 2 * SIZEOF(TSquare2); // Patch Squares PPOINTER($73644C)^ := @Squares[0]; PPOINTER($73BB32)^ := @Squares[0]; PPOINTER($73BE35)^ := @Squares[0]; PPOINTER($75118F)^ := @Squares[0]; PPOINTER($751975)^ := @Squares[0]; PPOINTER($752B68)^ := @Squares[0]; PPOINTER($752B87)^ := @Squares[0]; PPOINTER($752BA0)^ := @Squares[0]; PPOINTER($752BBF)^ := @Squares[0]; PPOINTER($752BD8)^ := @Squares[0]; PPOINTER($752BF6)^ := @Squares[0]; PPOINTER($752C0F)^ := @Squares[0]; PPOINTER($752C2E)^ := @Squares[0]; PPOINTER($752C47)^ := @Squares[0]; PPOINTER($752C66)^ := @Squares[0]; // Patch Squares2 PPOINTER($73BB51)^ := @Squares2[0]; PPOINTER($751582)^ := @Squares2[0]; PPOINTER($752472)^ := @Squares2[0]; PPOINTER($752FA4)^ := @Squares2[0]; // Patch calculating Squares addresses PINTEGER($736442)^ := SecondDimSize; PINTEGER($73BB28)^ := SecondDimSize; PINTEGER($73BE2B)^ := SecondDimSize; PINTEGER($752B5E)^ := SecondDimSize; PINTEGER($752B7D)^ := SecondDimSize; PINTEGER($752B96)^ := SecondDimSize; PINTEGER($752BB5)^ := SecondDimSize; PINTEGER($752BCE)^ := SecondDimSize; PINTEGER($752BEC)^ := SecondDimSize; PINTEGER($752C05)^ := SecondDimSize; PINTEGER($752C24)^ := SecondDimSize; PINTEGER($752C3D)^ := SecondDimSize; PINTEGER($752C5C)^ := SecondDimSize; // Patch calculating Squares2 addresses PINTEGER($73BB44)^ := SecondDimSize2; PINTEGER($752FBD)^ := Squares2Size; // Fix cycles PINTEGER($752B14)^ := MapSize; PINTEGER($752B33)^ := MapSize; END; // .PROCEDURE PatchSquaresRefs PROCEDURE OnSavegameWrite (Event: GameExt.PEvent); STDCALL; BEGIN Stores.WriteSavegameSection(SquaresSize, @Squares[0], FILE_SECTION_NAME); Stores.WriteSavegameSection(Squares2Size, @Squares2[0], FILE_SECTION_NAME); END; // .PROCEDURE OnSavegameWrite PROCEDURE OnSavegameRead (Event: GameExt.PEvent); STDCALL; BEGIN Stores.ReadSavegameSection(SquaresSize, @Squares[0], FILE_SECTION_NAME); Stores.ReadSavegameSection(Squares2Size, @Squares2[0], FILE_SECTION_NAME); END; // .PROCEDURE OnSavegameRead FUNCTION Hook_ResetErm (Context: Core.PHookHandlerArgs): LONGBOOL; STDCALL; BEGIN PatchSquaresRefs; RESULT := Core.EXEC_DEF_CODE; END; // .FUNCTION Hook_ResetErm PROCEDURE OnAfterWoG (Event: GameExt.PEvent); STDCALL; BEGIN // Disable Squares Save/Load PINTEGER($751189)^ := INTEGER($909023EB); PBYTE($75118D)^ := BYTE($90); PINTEGER($75196F)^ := INTEGER($909023EB); PBYTE($751973)^ := BYTE($90); // Disable Squares2 Save/Load PINTEGER($75157C)^ := INTEGER($909020EB); PBYTE($751580)^ := BYTE($90); PINTEGER($75246C)^ := INTEGER($909023EB); PBYTE($752470)^ := BYTE($90); END; // .PROCEDURE OnAfterWoG BEGIN GameExt.RegisterHandler(OnAfterWoG, 'OnAfterWoG'); GameExt.RegisterHandler(OnSavegameWrite, 'OnSavegameWrite'); GameExt.RegisterHandler(OnSavegameRead, 'OnSavegameRead'); Core.Hook(@Hook_ResetErm, Core.HOOKTYPE_BRIDGE, 5, Ptr($7525A4)); END.
unit ficha.Configuracoes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxCheckBox, Vcl.ExtCtrls, System.Actions, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, dxBar, cxBarEditItem, cxClasses, ORM.DTOBase, ORM.FichaBase, DTO.Configuracoes, controller.Configuracoes, ORM.controllerBase, frame.Configuracoes, WLick.ClassHelper, Generics.collections, WLick.Sessao, enum.Configuracoes, assembler.Configuracoes, IniFiles, VFrames, viewMessageForm, WLick.Miscelania; type TFichaConfiguracoes = class(TORMFichaBase) private FListaConfiguracoes: TObjectList<TDTOConfiguracoes>; function MyController: TControllerConfiguracoes; function MyFrame: TframeConfiguracoes; function MyDTO: TDTOConfiguracoes; procedure LoadAllConfiguracoes(); procedure LoadCamerasDevices(); procedure SetEvents; override; procedure btnCarregarEvent(Sender: TObject); procedure btnLimparEvent(Sender: TObject); protected function GetCaption: String; override; function GetFrame: TFrame; override; procedure SetOnChange(); override; function ClassController: TORMControllerBaseClass; override; function ClassDTO: TORMDTOBaseClass; override; procedure CreateAllObjects(); override; procedure DestroyAllObjects(); override; procedure ViewToDTO(); override; procedure DTOToView(); override; procedure InternalDTOToView(vDTO: TDTOConfiguracoes); procedure InternalViewToDTO(vConfig: TNomeConfiguracoes); public end; implementation { TFichaConfiguracoes } function TFichaConfiguracoes.GetCaption: String; begin Result := 'Configurações'; end; function TFichaConfiguracoes.MyController: TControllerConfiguracoes; begin Result := (Self.FController as TControllerConfiguracoes); end; function TFichaConfiguracoes.MyDTO: TDTOConfiguracoes; begin Result := (Self.FDTO as TDTOConfiguracoes); end; function TFichaConfiguracoes.MyFrame: TframeConfiguracoes; begin Result := (Self.FFrame as TframeConfiguracoes); end; function TFichaConfiguracoes.GetFrame: TFrame; begin if not Assigned(FFrame) then FFrame := TframeConfiguracoes.Create(Self); Result := FFrame; end; procedure TFichaConfiguracoes.InternalDTOToView(vDTO: TDTOConfiguracoes); var vConfig: TNomeConfiguracoes; vValorBinario, vValor: String; begin vValor := vDTO.Valor; vValorBinario := vDTO.ValorBinario; vConfig := LocateConfiguracaoByNome(vDTO.Configuracao); case vConfig of tncNaoEncontrado: ; tncCotacaoMinuto: MyFrame.edtValorPorMinuto.Value := vValor.ToCurrency; tncTempoTolerancia: MyFrame.edtTolerancia.Time := vValor.ToTime; tncLogotipo: begin if vValorBinario <> EmptyStr then MyFrame.ImgFoto.Picture := TMisc.StringToPicture( vValorBinario ); end; end; end; procedure TFichaConfiguracoes.InternalViewToDTO(vConfig: TNomeConfiguracoes); var vDTO: TDTOConfiguracoes; vDTOPersist: TDTOConfiguracoes; vValorBinario, vValor: String; begin vDTOPersist := nil; for vDTO in FListaConfiguracoes do begin if vDTO.Configuracao = NomeConfiguracoes[vConfig] then begin with TAssemblerConfiguracoes.GetAssembler(vDTO.AssemblerClass) do try vDTOPersist := TDTOConfiguracoes(GetClone(vDTO)); Break finally Free; end; end; end; if not Assigned(vDTOPersist) then begin vDTOPersist := TDTOConfiguracoes.Create; vDTOPersist.Configuracao := NomeConfiguracoes[vConfig]; end; vValor := EmptyStr; vValorBinario := EmptyStr; case vConfig of tncNaoEncontrado: ; tncCotacaoMinuto: vValor := MyFrame.edtValorPorMinuto.Value.ToString; tncTempoTolerancia: vValor := MyFrame.edtTolerancia.Time.ToString; tncLogotipo: vValorBinario := TMisc.PictureToString( MyFrame.ImgFoto.Picture ); end; vDTOPersist.Valor := vValor; vDTOPersist.ValorBinario := vValorBinario; if vDTOPersist.ID.IsNull then MyController.Insert(vDTOPersist) else MyController.Update(vDTOPersist); end; procedure TFichaConfiguracoes.LoadAllConfiguracoes; begin MyController.GetAllConfiguracoes(FListaConfiguracoes); end; procedure TFichaConfiguracoes.LoadCamerasDevices; var vDeviceList: TStringList; vVideoImage: TVideoImage; begin vVideoImage := TVideoImage.Create; try vDeviceList := TStringList.Create; try vVideoImage.GetListOfDevices(vDeviceList); MyFrame.grpCameraDefault.Properties.Items := vDeviceList; finally vDeviceList.Free; end; finally vVideoImage.Free; end; end; procedure TFichaConfiguracoes.SetEvents; begin inherited; with MyFrame do begin btnLoad.OnClick := btnCarregarEvent; btnClear.OnClick := btnLimparEvent; end; end; procedure TFichaConfiguracoes.SetOnChange; begin inherited; with MyFrame do begin edtValorPorMinuto.Properties.OnChange := OnChangeMethod; edtTolerancia.Properties.OnChange := OnChangeMethod; ImgFoto.Properties.OnChange := OnChangeMethod; grpCameraDefault.Properties.OnChange := OnChangeMethod; MyFrame.edtLogin.Properties.OnChange := OnChangeMethod; MyFrame.edtSenha.Properties.OnChange := OnChangeMethod; end; end; procedure TFichaConfiguracoes.btnCarregarEvent(Sender: TObject); var vDlgImage: TOpenDialog; begin vDlgImage := TOpenDialog.Create(nil); try vDlgImage.Filter := 'All(*.JPG;*.JPEG)|*.JPG;*.JPEG'; if vDlgImage.Execute() then begin MyFrame.ImgFoto.Picture.LoadFromFile(vDlgImage.FileName); end; finally vDlgImage.Free; end; end; procedure TFichaConfiguracoes.btnLimparEvent(Sender: TObject); begin if TviewMessage.Send_Question('Deseja realmente remover esta imagem?') then MyFrame.ImgFoto.Clear; end; function TFichaConfiguracoes.ClassController: TORMControllerBaseClass; begin Result := TControllerConfiguracoes; end; function TFichaConfiguracoes.ClassDTO: TORMDTOBaseClass; begin Result := TDTOConfiguracoes; end; procedure TFichaConfiguracoes.CreateAllObjects; begin inherited CreateAllObjects(); Self.FListaConfiguracoes := TObjectList<TDTOConfiguracoes>.Create(); end; procedure TFichaConfiguracoes.DestroyAllObjects; begin Self.FListaConfiguracoes.Free; inherited DestroyAllObjects(); end; procedure TFichaConfiguracoes.DTOToView; var vDTO: TDTOConfiguracoes; ArquivoINI: TIniFile; const cTagName = 'Configuracao'; cTagNameSessao = 'Sessao'; begin inherited; LoadAllConfiguracoes; LoadCamerasDevices; for vDTO in FListaConfiguracoes do begin InternalDTOToView(vDTO); end; ArquivoINI := TIniFile.Create( ExtractFilePath(Application.ExeName) + '\conexao.ini' ); try MyFrame.grpCameraDefault.ItemIndex := MyFrame.grpCameraDefault.Properties.Items.IndexOf(ArquivoINI.ReadString(cTagName, 'CameraDefault','')); {Senha padrão} MyFrame.edtLogin.Text := ArquivoINI.ReadString(cTagNameSessao, 'usuario',''); MyFrame.edtSenha.Text := TMisc.Decrypt(ArquivoINI.ReadString(cTagNameSessao, 'senha','')); finally ArquivoINI.Free; end; MyFrame.pgConfiguracao.ActivePageIndex := 0; end; procedure TFichaConfiguracoes.ViewToDTO; var vConfig: TNomeConfiguracoes; ArquivoINI: TIniFile; const cTagName = 'Configuracao'; cTagNameSessao = 'Sessao'; begin inherited; for vConfig := Low(NomeConfiguracoes) to High(NomeConfiguracoes) do begin if not (vConfig in [tncNaoEncontrado, tncVersaoBD, tncDataOperacao]) then InternalViewToDTO(vConfig); end; ArquivoINI := TIniFile.Create( ExtractFilePath(Application.ExeName) + '\conexao.ini' ); try ArquivoINI.WriteString(cTagName, 'CameraDefault',MyFrame.grpCameraDefault.Text); {Senha padrão} ArquivoINI.WriteString(cTagNameSessao, 'usuario',MyFrame.edtLogin.Text); ArquivoINI.WriteString(cTagNameSessao, 'senha', TMisc.Encrypt(MyFrame.edtSenha.Text)); finally ArquivoINI.Free; end; end; end.
unit MVVM.Core; interface uses System.SysUtils, Spring, Spring.Container, MVVM.Bindings, MVVM.Interfaces, MVVM.Types; type MVVMCore = record private class var FPlatformServicesClass: TPlatformServicesClass; FContainer: TContainer; FDefaultBindingStrategyName: String; FSynchronizer: IReadWriteSync; class constructor CreateC; class destructor DestroyC; class function GetDefaultBindingStrategyName: String; static; class procedure SetDefaultBindingStrategyName(const AStrategyName: String); static; public class procedure RegisterPlatformServices(AServicioClass: TPlatformServicesClass); static; class function PlatformServices: IPlatformServices; static; class function Container: TContainer; static; class function EnableBinding(AObject: TObject): Boolean; static; class function DisableBinding(AObject: TObject): Boolean; static; class procedure InitializationDone; static; class procedure DelegateExecution(AProc: TProc; AExecutionMode: EDelegatedExecutionMode); overload; static; class procedure DelegateExecution<T>(AData: T; AProc: TProc<T>; AExecutionMode: EDelegatedExecutionMode); overload; static; class function DefaultBindingStrategy: IBindingStrategy; static; class property DefaultBindingStrategyName: String read GetDefaultBindingStrategyName write SetDefaultBindingStrategyName; end; implementation uses System.Classes, System.Threading, MVVM.Utils; { MVVM } class function MVVMCore.Container: TContainer; begin Result := FContainer; end; class constructor MVVMCore.CreateC; begin FContainer := TContainer.Create; FSynchronizer := TMREWSync.Create; end; class function MVVMCore.GetDefaultBindingStrategyName: String; begin FSynchronizer.BeginRead; try Result := FDefaultBindingStrategyName; finally FSynchronizer.EndRead; end; end; class function MVVMCore.DefaultBindingStrategy: IBindingStrategy; begin Result := TBindingManager.GetDefaultRegisteredBindingStrategy end; class procedure MVVMCore.DelegateExecution(AProc: TProc; AExecutionMode: EDelegatedExecutionMode); begin case AExecutionMode of medQueue: begin TThread.Queue(TThread.CurrentThread, procedure begin AProc; end); end; medSynchronize: begin TThread.Synchronize(TThread.CurrentThread, procedure begin AProc end); end; medNewTask: begin TTask.Create( procedure begin AProc end).Start; end; medNormal: begin AProc; end; end; end; class procedure MVVMCore.DelegateExecution<T>(AData: T; AProc: TProc<T>; AExecutionMode: EDelegatedExecutionMode); begin case AExecutionMode of medQueue: begin TThread.Queue(TThread.CurrentThread, procedure begin AProc(AData); end); end; medSynchronize: begin TThread.Synchronize(TThread.CurrentThread, procedure begin AProc(AData) end); end; medNewTask: begin TTask.Create( procedure begin AProc(AData) end).Start; end; medNormal: begin AProc(AData); end; end; end; class destructor MVVMCore.DestroyC; begin FContainer.Free; end; class function MVVMCore.DisableBinding(AObject: TObject): Boolean; var [weak] LBinding: IBindable; begin if Supports(AObject, IBindable, LBinding) then LBinding.Binding.Enabled := False; end; class function MVVMCore.EnableBinding(AObject: TObject): Boolean; var [weak] LBinding: IBindable; begin if Supports(AObject, IBindable, LBinding) then LBinding.Binding.Enabled := True; end; class procedure MVVMCore.InitializationDone; begin FContainer.Build; end; class procedure MVVMCore.RegisterPlatformServices(AServicioClass: TPlatformServicesClass); begin FPlatformServicesClass := AServicioClass; end; class procedure MVVMCore.SetDefaultBindingStrategyName(const AStrategyName: String); begin FSynchronizer.BeginWrite; try FDefaultBindingStrategyName := AStrategyName; finally FSynchronizer.EndWrite; end; end; class function MVVMCore.PlatformServices: IPlatformServices; begin Spring.Guard.CheckNotNull(FPlatformServicesClass, 'No hay registrado ningun servicio para la plataforma'); Result := FPlatformServicesClass.Create; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ImgList, ExtCtrls, Cosmos.Framework.Interfaces.Root, Cosmos.Framework.Interfaces.Utils, Cosmos.Framework.Interfaces.Dialogs, ComCtrls, Buttons, ActnList, cosmos.core.winshell, cosmos.core.ConstantesMsg, System.Actions; type TFrmWindowsList = class(TForm, ICosmosDialogWinManager) ImgList18: TImageList; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; LsvWindows: TListView; ImgList32: TImageList; SbnReportStyle: TSpeedButton; SbnIconsStyle: TSpeedButton; ActionList1: TActionList; ActActivate: TAction; ActCloseWin: TAction; procedure FormShow(Sender: TObject); procedure LsvWindowsDblClick(Sender: TObject); procedure ActActivateUpdate(Sender: TObject); procedure ActCloseWinExecute(Sender: TObject); procedure ActActivateExecute(Sender: TObject); procedure SbnIconsStyleClick(Sender: TObject); procedure SbnReportStyleClick(Sender: TObject); procedure Button3Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure LoadWindowsList; protected function SelectForm: TForm; public { Public declarations } end; var FrmWindowsList: TFrmWindowsList; implementation {$R *.dfm} procedure TFrmWindowsList.ActActivateExecute(Sender: TObject); begin if LsvWindows.Selected <> nil then ModalResult := mrOk; end; procedure TFrmWindowsList.ActActivateUpdate(Sender: TObject); begin TAction(Sender).Enabled := LsvWindows.Selected <> nil; end; procedure TFrmWindowsList.ActCloseWinExecute(Sender: TObject); var IWinManager: ICosmosWindowsManager; begin if LsvWindows.Selected <> nil then begin IWinManager := Application.MainForm as ICosmosWindowsManager; if IWinManager.CloseRegisteredWindow(LsvWindows.Selected.Caption) then begin LsvWindows.Selected.Delete; LsvWindows.Arrange(arDefault); end; end; end; procedure TFrmWindowsList.Button3Click(Sender: TObject); begin if Self.HelpContext <> 0 then Application.HelpSystem.ShowContextHelp(Self.HelpContext, Application.CurrentHelpFile); end; procedure TFrmWindowsList.FormCreate(Sender: TObject); begin //XMLFileStorage.FileName := TShellFolders.GetMyAppDataFolder + sCommonUserData + 'screens.xml'; LoadWindowsList; end; procedure TFrmWindowsList.FormShow(Sender: TObject); begin SbnIconsStyle.Down := LsvWindows.ViewStyle = vsIcon; SbnReportStyle.Down := LsvWindows.ViewStyle = vsReport; end; procedure TFrmWindowsList.LoadWindowsList; var I: integer; Form: TCustomForm; IWinManager: ICosmosWindowsManager; Icon: TIcon; Item: TListItem; IDockedForm: ICosmosDockedForm; begin IWinManager := Application.MainForm as ICosmosWindowsManager; for I := 0 to Pred(IWinManager.FormCount) do begin Form := IWinManager.FindFormByID(I); if Form <> nil then begin Item := LsvWindows.Items.Add; Item.Caption := Form.Caption; if Supports(Form, ICosmosDockedForm) then begin IDockedForm := Form as ICosmosDockedForm; Item.SubItems.Add(IDockedForm.FormDescription); end; Icon := IWinManager.ExtractFormIcon(Form); if Icon <> nil then begin Item.ImageIndex := ImgList18.AddIcon(Icon); ImgList32.AddIcon(Icon); end else Item.ImageIndex := 0; end; end; end; procedure TFrmWindowsList.LsvWindowsDblClick(Sender: TObject); begin if LsvWindows.Selected <> nil then ActActivate.Execute; end; function TFrmWindowsList.SelectForm: TForm; var IWinManager: ICosmosWindowsManager; begin if ShowModal = mrOk then begin IWinManager := Application.MainForm as ICosmosWindowsManager; Result := TForm(IWinManager.FindFormByCaption(LsvWindows.Selected.Caption)); end else Result := nil; end; procedure TFrmWindowsList.SbnReportStyleClick(Sender: TObject); begin LsvWindows.ViewStyle := vsReport; end; procedure TFrmWindowsList.SbnIconsStyleClick(Sender: TObject); begin LsvWindows.ViewStyle := vsIcon; end; initialization RegisterClass(TFrmWindowsList); finalization UnRegisterClass(TFrmWindowsList); end.
unit datamatrix; (* @type: unit @author: bocianu <bocianu@gmail.com> @name: Datamatrix library @description: <https://github.com/pfusik/datamatrix6502> adapted into MadPascal by bocianu '2017 *) interface procedure CalculateMatrix:assembler; procedure SetMessage(msg:string; dmData:word); implementation const DataMatrix_EOF = 255; procedure CalculateMatrix:assembler; (* @description: *) asm { txa:pha ; need to store register X in Mad pascal ; datamatrix.asx - Data Matrix barcode encoder in 6502 assembly language ; "THE BEER-WARE LICENSE" (Revision 42): ; Piotr Fusik <fox@scene.pl> wrote this file. ; As long as you retain this notice you can do whatever you want with this stuff. ; If we meet some day, and you think this stuff is worth it, you can buy me a beer in return. ; Compile with xasm (http://xasm.atari.org/), for example: ; xasm datamatrix.asx /l /d:DataMatrix_code=$b600 /d:DataMatrix_data=$b900 /d:DataMatrix_SIZE=20 ; DataMatrix_code - self-modifying code ; DataMatrix_data - uninitialized data ; DataMatrix_SIZE - 10, 12, 14, 16, 18, 20, 22, 24, 26, 32, 36, 40, 44 or 48 DataMatrix_data = DM_DATA; DataMatrix_SIZE = DM_SIZE; DataMatrix_message equ DataMatrix_data ; DataMatrix_DATA_CODEWORDS DataMatrix_symbol = DataMatrix_data+$100; ; private: ift DataMatrix_SIZE<=26 DataMatrix_MATRIX_SIZE equ DataMatrix_SIZE-2 els DataMatrix_MATRIX_SIZE equ DataMatrix_SIZE-4 eif DataMatrix_dataCodewords equ DataMatrix_message ; DataMatrix_DATA_CODEWORDS DataMatrix_errorCodewords equ DataMatrix_dataCodewords+DataMatrix_DATA_CODEWORDS ; DataMatrix_ERROR_CODEWORDS DataMatrix_exp equ DataMatrix_data+$100 ; $100 DataMatrix_log equ Datamatrix_data+$200 ; $100 ;org DataMatrix_code ldx #-1 DataMatrix_encodeMessage_1 inx inc DataMatrix_message,x bne DataMatrix_encodeMessage_1 lda #129 DataMatrix_padMessage_1 sta DataMatrix_message,x+ lda DataMatrix_padding,x bne DataMatrix_padMessage_1 tax ; #0 lda #1 DataMatrix_initExpLog_1 sta DataMatrix_exp,x tay txa sta DataMatrix_log,y tya asl @ scc:eor <301 inx bne DataMatrix_initExpLog_1 ldy #DataMatrix_ERROR_CODEWORDS-1 txa ; #0 sta:rpl DataMatrix_errorCodewords,y- ; ldx #0 DataMatrix_reedSolomon_1 txa:pha ldy #0 lda DataMatrix_dataCodewords,x eor DataMatrix_errorCodewords DataMatrix_reedSolomon_2 pha beq DataMatrix_reedSolomon_3 tax lda DataMatrix_log,x add DataMatrix_poly,y adc #0 tax lda DataMatrix_exp,x DataMatrix_reedSolomon_3 cpy #DataMatrix_ERROR_CODEWORDS-1 scs:eor DataMatrix_errorCodewords+1,y sta DataMatrix_errorCodewords,y+ pla bcc DataMatrix_reedSolomon_2 pla:tax inx cpx #DataMatrix_DATA_CODEWORDS bcc DataMatrix_reedSolomon_1 ldy #DataMatrix_SIZE-3 mwa #DataMatrix_symbol DataMatrix_clear_store+1 DataMatrix_clear_line lda #DataMatrix_SIZE add:sta DataMatrix_clear_store+1 scc:inc DataMatrix_clear_store+2 ldx #DataMatrix_SIZE-1 DataMatrix_clear_dashed tya and #1 DataMatrix_clear_store sta $ffff,x lda #2 dex bmi DataMatrix_clear_next ift DataMatrix_SIZE>26 beq DataMatrix_clear_solid cpx #DataMatrix_SIZE/2-1 beq DataMatrix_clear_dashed cpx #DataMatrix_SIZE/2 eif bne DataMatrix_clear_store DataMatrix_clear_solid lsr @ bpl DataMatrix_clear_store ; jmp DataMatrix_clear_next dey bpl DataMatrix_clear_line ldx #DataMatrix_SIZE-1 DataMatrix_horizontal_1 txa and:eor #1 sta DataMatrix_symbol,x :DataMatrix_SIZE>26 sta DataMatrix_symbol+DataMatrix_SIZE/2*DataMatrix_SIZE,x mva #1 DataMatrix_symbol+[DataMatrix_SIZE-1]*DataMatrix_SIZE,x :DataMatrix_SIZE>26 sta DataMatrix_symbol+[DataMatrix_SIZE/2-1]*DataMatrix_SIZE,x dex bpl DataMatrix_horizontal_1 mwa #DataMatrix_dataCodewords DataMatrix_fillSource ldx #0 ldy #4 DataMatrix_fill_1 ; Check corner cases ift [DataMatrix_MATRIX_SIZE&4]!=0 txa bne DataMatrix_noCorner cpy #DataMatrix_MATRIX_SIZE-[DataMatrix_MATRIX_SIZE&2] bne DataMatrix_noCorner ; corner1/2 lda #15 jsr DataMatrix_setCorner DataMatrix_noCorner eif ; Sweep upward-right DataMatrix_fill_up cpy #DataMatrix_MATRIX_SIZE jsr DataMatrix_setUtah DataMatrix_no_up :2 inx :2 dey bmi DataMatrix_fill_top cpx #DataMatrix_MATRIX_SIZE bcc DataMatrix_fill_up DataMatrix_fill_top :3 inx iny ; Sweep downward-left DataMatrix_fill_down tya bmi DataMatrix_no_down cpx #DataMatrix_MATRIX_SIZE jsr DataMatrix_setUtah DataMatrix_no_down :2 iny :2 dex bmi DataMatrix_fill_left cpy #DataMatrix_MATRIX_SIZE bcc DataMatrix_fill_down DataMatrix_fill_left inx :3 iny cpx #DataMatrix_MATRIX_SIZE bcc DataMatrix_fill_1 cpy #DataMatrix_MATRIX_SIZE bcc DataMatrix_fill_1 ift [DataMatrix_SIZE&2]==0 ; Fixed pattern in the bottom-right corner. lda #1 sta DataMatrix_symbol+[DataMatrix_SIZE-3]*DataMatrix_SIZE+DataMatrix_SIZE-3 sta DataMatrix_symbol+[DataMatrix_SIZE-2]*DataMatrix_SIZE+DataMatrix_SIZE-2 lsr @ sta DataMatrix_symbol+[DataMatrix_SIZE-3]*DataMatrix_SIZE+DataMatrix_SIZE-2 sta DataMatrix_symbol+[DataMatrix_SIZE-2]*DataMatrix_SIZE+DataMatrix_SIZE-3 eif pla:tax ; need to restore register X in Mad pascal rts DataMatrix_setUtah bcs DataMatrix_setUtah_no lda DataMatrix_matrixLo,y ift DataMatrix_SIZE>26 cpx #DataMatrix_MATRIX_SIZE/2 scc:adc #1 eif sta DataMatrix_setUtah_load+1 lda DataMatrix_matrixHi,y ift DataMatrix_SIZE>26 adc #0 eif sta DataMatrix_setUtah_load+2 DataMatrix_setUtah_load lda $ffff,x lsr @ beq DataMatrix_setUtah_no lda #7 DataMatrix_setCorner stx DataMatrix_column sty DataMatrix_row tay DataMatrix_setShape_1 tya:pha lda #0 DataMatrix_column equ *-1 add DataMatrix_shapeX,y tax lda #0 DataMatrix_row equ *-1 add DataMatrix_shapeY,y tay bpl DataMatrix_setModuleWrapped_yOk add #DataMatrix_MATRIX_SIZE tay ift [DataMatrix_MATRIX_SIZE&7]!=0 txa add #4-[[DataMatrix_MATRIX_SIZE+4]&7] tax eif DataMatrix_setModuleWrapped_yOk txa bpl DataMatrix_setModuleWrapped_xOk add #DataMatrix_MATRIX_SIZE tax ift [DataMatrix_MATRIX_SIZE&7]!=0 tya add #4-[[DataMatrix_MATRIX_SIZE+4]&7] tay eif DataMatrix_setModuleWrapped_xOk ift DataMatrix_SIZE>26 cpx #DataMatrix_MATRIX_SIZE/2 bcc DataMatrix_setModuleWrapped_leftRegion inx:inx DataMatrix_setModuleWrapped_leftRegion eif mva DataMatrix_matrixLo,y DataMatrix_setModule_store+1 mva DataMatrix_matrixHi,y DataMatrix_setModule_store+2 asl DataMatrix_dataCodewords DataMatrix_fillSource equ *-2 lda #0 rol @ DataMatrix_setModule_store sta $ffff,x pla:tay dey and #7 bne DataMatrix_setShape_1 inw DataMatrix_fillSource ldx DataMatrix_column ldy DataMatrix_row DataMatrix_setUtah_no rts ift DataMatrix_SIZE==10 DataMatrix_DATA_CODEWORDS equ 3 DataMatrix_ERROR_CODEWORDS equ 5 DataMatrix_poly dta $eb,$cf,$d2,$f4,$0f eli DataMatrix_SIZE==12 DataMatrix_DATA_CODEWORDS equ 5 DataMatrix_ERROR_CODEWORDS equ 7 DataMatrix_poly dta $b1,$1e,$d6,$da,$2a,$c5,$1c eli DataMatrix_SIZE==14 DataMatrix_DATA_CODEWORDS equ 8 DataMatrix_ERROR_CODEWORDS equ 10 DataMatrix_poly dta $c7,$32,$96,$78,$ed,$83,$ac,$53,$f3,$37 eli DataMatrix_SIZE==16 DataMatrix_DATA_CODEWORDS equ 12 DataMatrix_ERROR_CODEWORDS equ 12 DataMatrix_poly dta $a8,$8e,$23,$ad,$5e,$b9,$6b,$c7,$4a,$c2,$e9,$4e eli DataMatrix_SIZE==18 DataMatrix_DATA_CODEWORDS equ 18 DataMatrix_ERROR_CODEWORDS equ 14 DataMatrix_poly dta $53,$ab,$21,$27,$08,$0c,$f8,$1b,$26,$54,$5d,$f6,$ad,$69 eli DataMatrix_SIZE==20 DataMatrix_DATA_CODEWORDS equ 22 DataMatrix_ERROR_CODEWORDS equ 18 DataMatrix_poly dta $a4,$09,$f4,$45,$b1,$a3,$a1,$e7,$5e,$fa,$c7,$dc,$fd,$a4,$67,$8e,$3d,$ab eli DataMatrix_SIZE==22 DataMatrix_DATA_CODEWORDS equ 30 DataMatrix_ERROR_CODEWORDS equ 20 DataMatrix_poly dta $7f,$21,$92,$17,$4f,$19,$c1,$7a,$d1,$e9,$e6,$a4,$01,$6d,$b8,$95,$26,$c9,$3d,$d2 eli DataMatrix_SIZE==24 DataMatrix_DATA_CODEWORDS equ 36 DataMatrix_ERROR_CODEWORDS equ 24 DataMatrix_poly dta $41,$8d,$f5,$1f,$b7,$f2,$ec,$b1,$7f,$e1,$6a,$16,$83,$14,$ca,$16,$6a,$89,$67,$e7,$d7,$88,$55,$2d eli DataMatrix_SIZE==26 DataMatrix_DATA_CODEWORDS equ 44 DataMatrix_ERROR_CODEWORDS equ 28 DataMatrix_poly dta $96,$20,$6d,$95,$ef,$d5,$c6,$30,$5e,$32,$0c,$c3,$a7,$82,$c4,$fd,$63,$a6,$ef,$de,$92,$be,$f5,$b8,$ad,$7d,$11,$97 eli DataMatrix_SIZE==32 DataMatrix_DATA_CODEWORDS equ 62 DataMatrix_ERROR_CODEWORDS equ 36 DataMatrix_poly dta $39,$56,$bb,$45,$8c,$99,$1f,$42,$87,$43,$f8,$54,$5a,$51,$db,$c5,$02,$01,$27,$10,$4b,$e5,$14,$33,$fc,$6c,$d5,$b5,$b7,$57,$6f,$4d,$e8,$a8,$b0,$9c eli DataMatrix_SIZE==36 DataMatrix_DATA_CODEWORDS equ 86 DataMatrix_ERROR_CODEWORDS equ 42 DataMatrix_poly dta $e1,$26,$e1,$94,$c0,$fe,$8d,$0b,$52,$ed,$51,$18,$0d,$7a,$ff,$6a,$a7,$0d,$cf,$a0,$58,$cb,$26,$8e,$54,$42,$03,$a8,$66,$9c,$01,$c8,$58,$3c,$e9,$86,$73,$72,$ea,$5a,$41,$8a eli DataMatrix_SIZE==40 DataMatrix_DATA_CODEWORDS equ 114 DataMatrix_ERROR_CODEWORDS equ 48 DataMatrix_poly dta $72,$45,$7a,$1e,$5e,$0b,$42,$e6,$84,$49,$91,$89,$87,$4f,$d6,$21,$0c,$dc,$8e,$d5,$88,$7c,$d7,$a6,$09,$de,$1c,$9a,$84,$04,$64,$aa,$91,$3b,$a4,$d7,$11,$f9,$66,$f9,$86,$80,$05,$f5,$83,$7f,$dd,$9c eli DataMatrix_SIZE==44 DataMatrix_DATA_CODEWORDS equ 144 DataMatrix_ERROR_CODEWORDS equ 56 DataMatrix_poly dta $1d,$b3,$63,$95,$9f,$48,$7d,$16,$37,$3c,$d9,$b0,$9c,$5a,$2b,$50,$fb,$eb,$80,$a9,$fe,$86,$f9,$2a,$79,$76,$48,$80,$81,$e8,$25,$0f,$18,$dd,$8f,$73,$83,$28,$71,$fe,$13,$7b,$f6,$44,$a6,$42,$76,$8e,$2f,$33,$c3,$f2,$f9,$83,$26,$42 eli DataMatrix_SIZE==48 DataMatrix_DATA_CODEWORDS equ 174 DataMatrix_ERROR_CODEWORDS equ 68 DataMatrix_poly dta $21,$4f,$be,$f5,$5b,$dd,$e9,$19,$18,$06,$90,$97,$79,$ba,$8c,$7f,$2d,$99,$fa,$b7,$46,$83,$c6,$11,$59,$f5,$79,$33,$8c,$fc,$cb,$52,$53,$e9,$98,$dc,$9b,$12,$e6,$d2,$5e,$20,$c8,$c5,$c0,$c2,$ca,$81,$0a,$ed,$c6,$5e,$b0,$24,$28,$8b,$c9,$84,$db,$22,$38,$71,$34,$14,$22,$f7,$0f,$33 els ert 1 ; unsupported DataMatrix_SIZE eif DataMatrix_padding :DataMatrix_DATA_CODEWORDS dta [129+[1+#]*149%253]%254+1 ; NOTE: the following two zero bytes terminate DataMatrix_padding: DataMatrix_shapeY dta 0,0,0,-1,-1,-1,-2,-2 ift DataMatrix_SIZE==14||DataMatrix_SIZE==22||DataMatrix_SIZE==32||DataMatrix_SIZE==40||DataMatrix_SIZE==48 ; corner1 dta 3-DataMatrix_MATRIX_SIZE,2-DataMatrix_MATRIX_SIZE,1-DataMatrix_MATRIX_SIZE,-DataMatrix_MATRIX_SIZE,-DataMatrix_MATRIX_SIZE,-1,-1,-1 eli DataMatrix_SIZE==16||DataMatrix_SIZE==24 ; corner2 dta 3-DataMatrix_MATRIX_SIZE,2-DataMatrix_MATRIX_SIZE,2-DataMatrix_MATRIX_SIZE,2-DataMatrix_MATRIX_SIZE,2-DataMatrix_MATRIX_SIZE,1,0,-1 eif DataMatrix_shapeX dta 0,-1,-2,0,-1,-2,-1,-2 ift DataMatrix_SIZE==14||DataMatrix_SIZE==22||DataMatrix_SIZE==32||DataMatrix_SIZE==40||DataMatrix_SIZE==48 ; corner1 dta DataMatrix_MATRIX_SIZE-1,DataMatrix_MATRIX_SIZE-1,DataMatrix_MATRIX_SIZE-1,DataMatrix_MATRIX_SIZE-1,DataMatrix_MATRIX_SIZE-2,2,1,0 eli DataMatrix_SIZE==16||DataMatrix_SIZE==24 ; corner2 dta DataMatrix_MATRIX_SIZE-1,DataMatrix_MATRIX_SIZE-1,DataMatrix_MATRIX_SIZE-2,DataMatrix_MATRIX_SIZE-3,DataMatrix_MATRIX_SIZE-4,0,0,0 eif ift DataMatrix_SIZE<=26 DataMatrix_matrixLo :DataMatrix_MATRIX_SIZE dta l(DataMatrix_symbol+[1+#]*DataMatrix_SIZE+1) DataMatrix_matrixHi :DataMatrix_MATRIX_SIZE dta h(DataMatrix_symbol+[1+#]*DataMatrix_SIZE+1) els DataMatrix_matrixLo :DataMatrix_MATRIX_SIZE/2 dta l(DataMatrix_symbol+[1+#]*DataMatrix_SIZE+1) :DataMatrix_MATRIX_SIZE/2 dta l(DataMatrix_symbol+[1+DataMatrix_SIZE/2+#]*DataMatrix_SIZE+1) DataMatrix_matrixHi :DataMatrix_MATRIX_SIZE/2 dta h(DataMatrix_symbol+[1+#]*DataMatrix_SIZE+1) :DataMatrix_MATRIX_SIZE/2 dta h(DataMatrix_symbol+[1+DataMatrix_SIZE/2+#]*DataMatrix_SIZE+1) eif }; end; procedure SetMessage(msg:string; dmData:word); (* @description: *) var len: byte; begin len := byte(msg[0]); Move(@msg[1], pointer(dmData), len); Poke(dmData+len, DataMatrix_EOF); end; end.
unit A111THread; interface uses SysUtils, Classes, Windows, Dialogs, WinSock, SerialLink; type TDWORD = packed record case Integer of 0: (dw: Cardinal); 1: (w:array[0..1]of Word); 2: (b:array[0..3]of Byte); end; type TA111 =record cmd:Byte; reg:array[0..127]of TDWORD; end; { 0x02 mode_selection, (r/w) 0x03 main_control, (w) 0x05 streaming_control, (r/w) 0x06 status (r) 0x07 baudrate, (r/w) 0x0a module_power_mode, (r/w) 0x10 product_id, (r) 0x11 version, (r) 0x12 max_uart_baudrate, (r) 0xE9 output_buffer_length, (r) 0x20 range_start, (r/w) 0x21 range_length, (r/w) 0x22 repetition_mode (r/w) 0x23 update_rate, (r/w) 0x24 gain 0x25 sensor_power_mode, (r/w) 0x26 tx_disable, (r/w) } type TTHA111 = class(TThread) private { Private declarations } FActiv: boolean; bufferWrite,bufferRead: Cardinal; public cmdMessage,streamMessage : integer; streamError,reconnect : boolean; byteToSend: Cardinal; regchange:Byte; buffSize:DWORD; answReady: boolean; FLink: TSerialLink; A111:TA111; A111ZBuff:array[0..15] of byte; A111InBuff:TByteArray; property Activ: boolean read FActiv; procedure execCmd(cmd: integer;pd:TByteArray); protected procedure Execute; override; end; implementation uses A111Form; procedure TTHA111.execCmd(cmd: integer;pd:TByteArray); var dw:TDWord; begin case cmd of $F5: begin regchange:=pd[0]; A111.reg[regchange].b[0]:=pd[1]; A111.reg[regchange].b[1]:=pd[2]; A111.reg[regchange].b[2]:=pd[3]; A111.reg[regchange].b[3]:=pd[4]; end; $F7: begin regchange:=pd[0]; Move(A111InBuff,A111_Form.A111AnswBuff,buffSize) end; $F6: begin regchange:=pd[0]; A111.reg[regchange].b[0]:=pd[1]; A111.reg[regchange].b[1]:=pd[2]; A111.reg[regchange].b[2]:=pd[3]; A111.reg[regchange].b[3]:=pd[4]; end; end; end; procedure TTHA111.Execute; var n,cmd:Integer; len:TWords; pd:PByteArray; begin cmdMessage:=cmd_message; streamMessage:=stream_message; reconnect:=False; answReady:=False; try FLink:=TSerialLink.Create(nil); FLink.Port:= A111_Form.CommunicPortName; FLink.Speed:= A111_Form.CommunicPortSpeed; FLink.Open; finally if not FLink.Active then ShowMessage('Нет связи с радаром'); end; FActiv:=true; while not terminated do begin if reconnect then begin try FLink.Speed:=A111_Form.CommunicPortSpeed; // FLink.Close; // FLink.Open; finally if not FLink.Active then ShowMessage('Нет связи с радаром'); end; Delay(100); reconnect:=False; end; if byteToSend<>0 then begin FLink.SendBuffer(A111_Form.A111SendBuff,byteToSend); byteToSend:=0; end; if FLink.GetBytesReceived then begin n:=FLink.BytesReceived; if n>0 then begin FLink.ReceiveBuffer(A111ZBuff,4); if A111ZBuff[0]=$CC then begin len.lo:=A111ZBuff[1]; len.hi:=A111ZBuff[2]; cmd:=A111ZBuff[3]; end; if cmd=$FE then begin FLink.ReceiveBuffer(A111InBuff,len.Words+1); Move(A111InBuff,A111_Form.A111SteamBuff,len.Words); postmessage(A111_Form.Handle,streamMessage,0,0); end else begin FLink.ReceiveBuffer(A111InBuff,len.Words+1); buffSize:=len.Words; execCmd(cmd,A111InBuff); answReady:=true; end; end; end; end; FLink.Destroy; FActiv:=false; end; end.
FUNCTION CompareNumbers (number1, number2: Integer):Boolean; BEGIN CompareNumbers:= (number1 = number2); END; FUNCTION CountReps (list: TypeList; number: Integer): Integer; VAR auxList: TypeList; {Como la lista se pasa por valor, se puede omitir la lista auxiliar y reocrrer la lista directamente con el puntero lista} counter: Integer; BEGIN auxList:= list; {auxList es el puntero auxiliar de list} counter:= 0; {contador empieza siendo 0} WHILE (auxList <> NIL) DO {Mientras no se llegue al final de la lista} BEGIN IF (CompareNumbers(number, auxList^.info)) THEN {Si el número que hay en el nodo es el mismo que number} BEGIN counter:= counter + 1; {En el caso que sean los mismos, se aumenta en uno el contador} END; auxList:= auxList^.next; {Sea o no el dato igual, se va recorriendo la posición} END; CountReps:= counter; {Se asigna el valor del contador a la función} END;
object AdjustSongTempoDlg: TAdjustSongTempoDlg Left = 0 Top = 0 BorderIcons = [biSystemMenu] BorderStyle = bsDialog Caption = 'Adjust Song Tempo' ClientHeight = 149 ClientWidth = 311 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poMainFormCenter OnShow = FormShow DesignSize = ( 311 149) PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 12 Top = 14 Width = 140 Height = 13 Alignment = taRightJustify Caption = 'Adjust all pattern &tempos by:' end object lblRangeErrorMsg: TLabel Left = 12 Top = 47 Width = 273 Height = 66 Anchors = [akLeft, akTop, akRight] AutoSize = False Caption = 'Adjusting the song tempo by this much will cause one or more pat' + 'terns to exceed the supported range. These patterns will have th' + 'eir tempos adjusted to the limit of the supported range only.' WordWrap = True end object cmdOK: TButton Left = 147 Top = 116 Width = 75 Height = 25 Anchors = [akRight, akBottom] Caption = 'OK' Default = True TabOrder = 0 OnClick = cmdOKClick ExplicitTop = 163 end object cmdCancel: TButton Left = 228 Top = 116 Width = 75 Height = 25 Anchors = [akRight, akBottom] Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 1 ExplicitTop = 163 end object cboAdjust: TComboBox Left = 158 Top = 11 Width = 99 Height = 21 Style = csDropDownList ItemHeight = 13 TabOrder = 2 OnClick = cboAdjustClick Items.Strings = ( '-10' '-9' '-8' '-7' '-6' '-5' '-4' '-3' '-2' '-1' 'None' '+1' '+2' '+3' '+4' '+5' '+6' '+7' '+8' '+9' '+10') end end
unit SaveThread; interface uses Windows, Classes; type TSaveThread = class(TThread) private { Private declarations } protected procedure Execute; override; procedure Save; end; implementation uses UnitMain; procedure TSaveThread.Save; begin SaveAll ; end; procedure TSaveThread.Execute; begin while not Terminated do begin Sleep(SaveTime*1000*60); Synchronize(Save); end; end; end.
//Convert From mongo-c-driver v1.3.5 //Hezihang@ cnblogs.com unit DriverBson; interface type { A value of TBsonType indicates the type of the data associated with a field within a BSON document. } TBsonType = (bsonEOO = 0, bsonDOUBLE = 1, bsonSTRING = 2, bsonOBJECT = 3, bsonARRAY = 4, bsonBINDATA = 5, bsonUNDEFINED = 6, bsonOID = 7, bsonBOOL = 8, bsonDATE = 9, bsonNULL = 10, bsonREGEX = 11, bsonDBREF = 12, (* Deprecated. *) bsonCODE = 13, bsonSYMBOL = 14, bsonCODEWSCOPE = 15, bsonINT = 16, bsonTIMESTAMP = 17, bsonLONG = 18, bsonMAXKEY = $7F, bsonMINKEY = $FF); TBsonSubType = (BSON_SUBTYPE_BINARY = $00, BSON_SUBTYPE_FUNCTION = $01, BSON_SUBTYPE_BINARY_DEPRECATED = $02, BSON_SUBTYPE_UUID_DEPRECATED = $03, BSON_SUBTYPE_UUID = $04, BSON_SUBTYPE_MD5 = $05, BSON_SUBTYPE_USER = $80); TBsonValidateFlags = ( // bson_validate_flags_t BSON_VALIDATE_NONE = 0, BSON_VALIDATE_UTF8 = (1 shl 0), BSON_VALIDATE_DOLLAR_KEYS = (1 shl 1), BSON_VALIDATE_DOT_KEYS = (1 shl 2), BSON_VALIDATE_UTF8_ALLOW_NULL = (1 shl 3)); TBsonContextFlags = ( // bson_context_flags_t BSON_CONTEXT_NONE = 0, BSON_CONTEXT_THREAD_SAFE = (1 shl 0), BSON_CONTEXT_DISABLE_HOST_CACHE = (1 shl 1), BSON_CONTEXT_DISABLE_PID_CACHE = (1 shl 2) {$IFDEF LINUX} , BSON_CONTEXT_USE_TASK_ID = (1 shl 3) {$ENDIF} ); TBsonOid = array [0 .. 11] of Byte; PBsonOid = ^TBsonOid; PBson = Pointer; TBsonArray = array [0 .. 0] of PBson; PBsonArray = ^TBsonArray; ssize_t = NativeInt; size_t = NativeInt; TBsonError = record domain: UInt32; code: UInt32; message: array [0 .. 503] of AnsiChar; end; PBsonError = ^TBsonError; TBsonReallocFunc = procedure(mem: Pointer; num_bytes: size_t; ctx: Pointer); cdecl; time_t = UInt32; timeval = record tv_sec: UInt32; tv_usec: UInt32; end; ptimeval = ^timeval; t_timestamp = record timestamp, increment: UInt32; end; t_utf8 = record len: UInt32; str: PAnsiChar; end; t_doc = record data_len: UInt32; data: Pointer; end; t_binary = record data_len: UInt32; data: Pointer; subtype: TBsonSubType; end; t_regex = record regex: PAnsiChar; options: PAnsiChar; end; t_dbPointer = record collection: PAnsiChar; collection_len: UInt32; oid: TBsonOid; end; t_code = record code_len: UInt32; code: PAnsiChar; end; t_codewscope = record code_len: UInt32; code: PAnsiChar; scope_len: UInt32; scope_data: Pointer; end; t_symbol = record len: UInt32; symbol: PAnsiChar; end; {$ALIGN 8} TBsonValue = record case value_type: TBsonType of bsonEOO: (); bsonDOUBLE: (v_double: Double); bsonOBJECT: (v_int64: Int64); bsonARRAY: (v_int32: Int32); bsonUNDEFINED: (v_int8: Byte); bsonDATE: (v_datetime: Int64); bsonOID: (v_oid: TBsonOid); bsonBOOL: (v_bool: Boolean); bsonTIMESTAMP: (v_timestamp: t_timestamp); bsonSTRING: (v_utf8: t_utf8); bsonNULL: (v_doc: t_doc); bsonBINDATA: (v_binary: t_binary); bsonREGEX: (v_regex: t_regex); bsonLONG: (v_dbPointer: t_dbPointer); bsonCODE: (v_code: t_code); bsonCODEWSCOPE: (v_codewscope: t_codewscope); bsonSYMBOL: (v_symbol: t_symbol); end; {$A-} {$A+} PBsonIterator = ^TBsonIterator; {$IFDEF CPU32BITS} {$ALIGN 4} {$ENDIF} {$IFDEF CPU64BITS} {$ALIGN 8} {$ENDIF} TBsonIterator = record raw: Pointer; // The raw buffer being iterated. len: UInt32; // The length of raw. off: UInt32; // The offset within the buffer. _type: UInt32; // The offset of the type byte. key: UInt32; // The offset of the key byte. d1: UInt32; // The offset of the first data byte. d2: UInt32; // The offset of the second data byte. d3: UInt32; // The offset of the third data byte. d4: UInt32; // The offset of the fourth data byte. next_off: UInt32; // The offset of the next field. err_off: UInt32; // The offset of the error. value: TBsonValue; // Internal value for various state. end; {$A-} {$A+} PBsonValue = ^TBsonValue; PBsonContext = Pointer; //function bson_iter_create: PBsonIterator; //procedure bson_iter_dispose(iter: PBsonIterator); function bson_get_major_version: Integer; cdecl; function bson_get_minor_version: Integer; cdecl; function bson_get_micro_version: Integer; cdecl; function bson_get_version: PInteger; cdecl; function bson_check_version(required_major, required_minor, required_micro: Integer): Boolean; cdecl; function bson_get_monotonic_time: Int64; cdecl; function bson_gettimeofday(tv: ptimeval): Integer; cdecl; function bson_context_new(flags: TBsonValidateFlags): PBsonContext; cdecl; procedure bson_context_destroy(context: PBsonContext); cdecl; function bson_context_get_default(): PBsonContext; cdecl; function bson_new: PBson; cdecl; function bson_new_from_json(data: Pointer; len: size_t; var error: TBsonError): PBson; cdecl; function bson_init_from_json(Bson: PBson; data: Pointer; len: size_t; var error: TBsonError): Boolean; cdecl; function bson_init_static(b: PBson; data: Pointer; len: size_t): Boolean; cdecl; procedure bson_init(b: PBson); cdecl; function bson_new_from_data(data: Pointer; len: size_t): PBson; cdecl; function bson_new_from_buffer(var buf: Pointer; var buf_len: size_t; realloc_func: TBsonReallocFunc; realloc_func_ctx: Pointer): PBson; cdecl; function bson_sized_new(size: size_t): PBson; cdecl; function bson_copy(const Bson: PBson): PBson; cdecl; procedure bson_copy_to(const src: PBson; dst: PBson); cdecl; procedure bson_copy_to_excluding(const src: PBson; dst: PBson; const first_exclude: PAnsiChar); cdecl; varargs; procedure bson_copy_to_excluding_noinit(const src: PBson; dst: PBson; const first_exclude: PAnsiChar); cdecl; varargs; procedure bson_destroy(Bson: PBson); cdecl; function bson_destroy_with_steal(Bson: PBson; steal: Boolean; var length: UInt32): Pointer; cdecl; function bson_get_data(Bson: PBson): Pointer; cdecl; function bson_count_keys(Bson: PBson): UInt32; cdecl; function bson_has_field(const Bson: PBson; const key: PAnsiChar): Boolean; cdecl; function bson_compare(const Bson: PBson; const other: PBson): Integer; cdecl; function bson_equal(const Bson: PBson; const other: PBson): Integer; cdecl; function bson_validate(const Bson: PBson; flags: TBsonValidateFlags; var offset: size_t): Boolean; cdecl; function bson_as_json(const Bson: PBson; var length: size_t): PAnsiChar; cdecl; function bson_array_as_json(const Bson: PBson; var length: size_t): PAnsiChar; cdecl; function bson_append_value(Bson: PBson; const key: PAnsiChar; key_length: Integer; const value: PBsonValue): Boolean; cdecl; function bson_append_array(Bson: PBson; const key: PAnsiChar; key_length: Integer; const array_: PBson): Boolean; cdecl; function bson_append_binary(Bson: PBson; const key: PAnsiChar; key_length: Integer; subtype: TBsonSubType; const binary: Pointer; length: UInt32) : Boolean; cdecl; function bson_append_bool(Bson: PBson; const key: PAnsiChar; key_length: Integer; value: Boolean): Boolean; cdecl; function bson_append_code(Bson: PBson; const key: PAnsiChar; key_length: Integer; const javascript: PAnsiChar): Boolean; cdecl; function bson_append_code_with_scope(Bson: PBson; const key: PAnsiChar; key_length: Integer; const javascript: PAnsiChar; const scope: PBson): Boolean; cdecl; function bson_append_dbPointer(Bson: PBson; const key: PAnsiChar; key_length: Integer; const collection: PAnsiChar; const oid: PBsonOid): Boolean; cdecl; function bson_append_double(Bson: PBson; const key: PAnsiChar; key_length: Integer; value: Double): Boolean; cdecl; function bson_append_document(Bson: PBson; const key: PAnsiChar; key_length: Integer; const value: PBson): Boolean; cdecl; function bson_append_document_begin(Bson: PBson; const key: PAnsiChar; key_length: Integer; child: PBson): Boolean; cdecl; function bson_append_document_end(Bson, child: PBson): Boolean; cdecl; function bson_append_array_begin(Bson: PBson; const key: PAnsiChar; key_length: Integer; child: PBson): Boolean; cdecl; function bson_append_array_end(Bson, child: PBson): Boolean; cdecl; function bson_append_int32(Bson: PBson; const key: PAnsiChar; key_length: Integer; value: Int32): Boolean; cdecl; function bson_append_int64(Bson: PBson; const key: PAnsiChar; key_length: Integer; value: Int64): Boolean; cdecl; function bson_append_iter(Bson: PBson; const key: PAnsiChar; key_length: Integer; const iter: PBsonIterator): Boolean; cdecl; function bson_append_minkey(Bson: PBson; const key: PAnsiChar; key_length: Integer): Boolean; cdecl; function bson_append_maxkey(Bson: PBson; const key: PAnsiChar; key_length: Integer): Boolean; cdecl; function bson_append_null(Bson: PBson; const key: PAnsiChar; key_length: Integer): Boolean; cdecl; function bson_append_oid(Bson: PBson; const key: PAnsiChar; key_length: Integer; const oid: PBsonOid): Boolean; cdecl; function bson_append_regex(Bson: PBson; const key: PAnsiChar; key_length: Integer; const regex, options: PAnsiChar): Boolean; cdecl; function bson_append_utf8(Bson: PBson; const key: PAnsiChar; key_length: Integer; const value: PAnsiChar; length: Integer): Boolean; cdecl; function bson_append_symbol(Bson: PBson; const key: PAnsiChar; key_length: Integer; const value: PAnsiChar; length: Integer): Boolean; cdecl; function bson_append_time_t(Bson: PBson; const key: PAnsiChar; key_length: Integer; value: time_t; length: Integer): Boolean; cdecl; function bson_append_timeval(Bson: PBson; const key: PAnsiChar; key_length: Integer; value: timeval; length: Integer): Boolean; cdecl; function bson_append_date_time(Bson: PBson; const key: PAnsiChar; key_length: Integer; value: Int64): Boolean; cdecl; function bson_append_now_utc(Bson: PBson; const key: PAnsiChar; key_length: Integer): Boolean; cdecl; function bson_append_timestamp(Bson: PBson; const key: PAnsiChar; key_length: Integer; timestamp, increment: UInt32): Boolean; cdecl; function bson_append_undefined(Bson: PBson; const key: PAnsiChar; key_length: Integer): Boolean; cdecl; function bson_concat(dst: PBson; const src: PBson): Boolean; cdecl; procedure bson_iter_array(iter: PBsonIterator; var arraylen: UInt32; var arr: Pointer); cdecl; function bson_iter_as_bool(iter: PBsonIterator): Boolean; cdecl; function bson_iter_as_int64(iter: PBsonIterator): Int64; cdecl; procedure bson_iter_binary(iter: PBsonIterator; var subtype: TBsonSubType; var binary_len: UInt32; var binary: PByte); cdecl; function bson_iter_bool(iter: PBsonIterator): Boolean; cdecl; function bson_iter_code(iter: PBsonIterator; var len: UInt32): PAnsiChar; cdecl; function bson_iter_codewscope(iter: PBsonIterator; var length, scope_len: UInt32; var scope: Pointer): PAnsiChar; cdecl; function bson_iter_date_time(iter: PBsonIterator): Int64; cdecl; procedure bson_iter_dbPointer(iter: PBsonIterator; var collection_len: UInt32; var collection: PAnsiChar; var oid: PBsonOid); cdecl; procedure bson_iter_document(iter: PBsonIterator; var document_len: UInt32; var document: Pointer); cdecl; function bson_iter_double(iter: PBsonIterator): Double; cdecl; function bson_iter_dup_utf8(iter: PBsonIterator; var length: UInt32): PAnsiChar; cdecl; function bson_iter_find(iter: PBsonIterator; key: PAnsiChar): Boolean; cdecl; function bson_iter_find_case(iter: PBsonIterator; key: PAnsiChar): Boolean; cdecl; function bson_iter_find_descendant(iter: PBsonIterator; dotkey: PAnsiChar; descendant: PBsonIterator): Boolean; cdecl; procedure bson_iter_init(var iter: PBsonIterator; Bson: PBson); cdecl; function bson_iter_init_find(var iter: PBsonIterator; Bson: PBson; key: PAnsiChar): Boolean; cdecl; function bson_iter_init_find_case(var iter: PBsonIterator; Bson: PBson; key: PAnsiChar): Boolean; cdecl; function bson_iter_int32(iter: PBsonIterator): Int32; cdecl; function bson_iter_int64(iter: PBsonIterator): Int64; cdecl; function bson_iter_key(iter: PBsonIterator): PAnsiChar; cdecl; function bson_iter_next(iter: PBsonIterator): Boolean; cdecl; function bson_iter_oid(iter: PBsonIterator): PBsonOid; cdecl; procedure bson_iter_overwrite_bool(iter: PBsonIterator; value: Boolean); cdecl; procedure bson_iter_overwrite_double(iter: PBsonIterator; value: Double); cdecl; procedure bson_iter_overwrite_int32(iter: PBsonIterator; value: Int32); cdecl; procedure bson_iter_overwrite_int64(iter: PBsonIterator; value: Int64); cdecl; function bson_iter_recurse(iter: PBsonIterator; child: Pointer): Boolean; cdecl; function bson_iter_regex(iter: PBsonIterator; options: PPAnsiChar): PAnsiChar; cdecl; function bson_iter_symbol(iter: PBsonIterator; var length: UInt32): PAnsiChar; cdecl; function bson_iter_time_t(iter: PBsonIterator): Int64; cdecl; procedure bson_iter_timestamp(iter: PBsonIterator; var timestamp, increment: UInt32); cdecl; procedure bson_iter_timeval(iter: PBsonIterator; var tv: timeval); cdecl; function bson_iter_type(iter: PBsonIterator): TBsonType; cdecl; function bson_iter_utf8(iter: PBsonIterator; var length: UInt32): PAnsiChar; cdecl; function bson_iter_value(iter: PBsonIterator): PBsonValue; cdecl; function bson_iter_visit_all(iter: PBsonIterator; visitor: Pointer; data: Pointer): Boolean; cdecl; type pbson_json_reader_t = Pointer; TBsonJsonErrorCode = // bson_json_error_code_t (BSON_JSON_ERROR_READ_CORRUPT_JS = 1, BSON_JSON_ERROR_READ_INVALID_PARAM, BSON_JSON_ERROR_READ_CB_FAILURE); bson_json_reader_cb = function(handle: Pointer; buf: Pointer; count: size_t): ssize_t; cdecl; bson_json_destroy_cb = procedure(handle: Pointer); cdecl; function bson_json_reader_new(data: Pointer; cb: bson_json_reader_cb; dcb: bson_json_destroy_cb; allow_multiple: Boolean; buf_size: size_t) : pbson_json_reader_t; cdecl; function bson_json_reader_new_from_fd(fd: Integer; close_on_destroy: Boolean): pbson_json_reader_t; cdecl; function bson_json_reader_new_from_file(const filename: PAnsiChar; var error: TBsonError): pbson_json_reader_t; cdecl; procedure bson_json_reader_destroy(reader: pbson_json_reader_t); cdecl; function bson_json_reader_read(reader: pbson_json_reader_t; Bson: PBson; var error: TBsonError): Integer; cdecl; function bson_json_data_reader_new(allow_multiple: Boolean; size: size_t): pbson_json_reader_t; cdecl; procedure bson_json_data_reader_ingest(reader: pbson_json_reader_t; const data: Pointer; len: size_t); cdecl; function bson_oid_compare(const oid1: PBsonOid; const oid2: PBsonOid): Integer; cdecl; procedure bson_oid_copy(const src: PBsonOid; dst: PBsonOid); cdecl; function bson_oid_equal(const oid1: PBsonOid; const oid2: PBsonOid): Boolean; cdecl; function bson_oid_is_valid(const str: PAnsiChar; length: size_t): Boolean; cdecl; function bson_oid_get_time_t(const oid: PBsonOid): time_t; cdecl; function bson_oid_hash(const oid: PBsonOid): UInt32; cdecl; procedure bson_oid_init(oid: PBsonOid; context: PBsonContext); cdecl; procedure bson_oid_init_from_data(oid: PBsonOid; const data: Pointer); cdecl; procedure bson_oid_init_from_string(oid: PBsonOid; const str: PAnsiChar); cdecl; procedure bson_oid_init_sequence(oid: PBsonOid; context: PBsonContext); cdecl; type TOidString = packed array [0 .. 24] of AnsiChar; procedure bson_oid_to_string(const oid: PBsonOid; var str: TOidString); cdecl; type bson_reader_read_func_t = function(handle: Pointer; buf: Pointer; count: size_t): ssize_t; cdecl; bson_reader_destroy_func_t = procedure(handle: Pointer); cdecl; pbson_reader_t = Pointer; off_t = NativeInt; function bson_reader_new_from_handle(handle: Pointer; rf: bson_reader_read_func_t; df: bson_reader_destroy_func_t): pbson_reader_t; cdecl; function bson_reader_new_from_fd(fd: Integer; close_on_destroy: Boolean): pbson_reader_t; cdecl; function bson_reader_new_from_file(const path: PAnsiChar; var error: TBsonError): pbson_reader_t; cdecl; function bson_reader_new_from_data(const data: Pointer; length: size_t): pbson_reader_t; cdecl; procedure bson_reader_destroy(reader: pbson_reader_t); cdecl; procedure bson_reader_set_read_func(reader: pbson_reader_t; func: bson_reader_read_func_t); cdecl; procedure bson_reader_set_destroy_func(reader: pbson_reader_t; func: bson_reader_destroy_func_t); cdecl; function bson_reader_read(reader: pbson_reader_t; var reached_eof: Boolean): PBson; cdecl; function bson_reader_tell(reader: pbson_reader_t): off_t; cdecl; type TBsonString = record str: PAnsiChar; len, alloc: UInt32; end; PBsonString = ^TBsonString; bson_unichar_t = WideChar; function bson_string_new(const str: PAnsiChar): PBsonString; cdecl; function bson_string_free(str: PBsonString; free_segment: Boolean): PAnsiChar; cdecl; procedure bson_string_append(str: PBsonString; const str2: PAnsiChar); cdecl; procedure bson_string_append_c(str: PBsonString; str2: AnsiChar); cdecl; procedure bson_string_append_unichar(str: PBsonString; unichar: bson_unichar_t); cdecl; procedure bson_string_append_printf(str: PBsonString; const format: PAnsiChar); cdecl; varargs; procedure bson_string_truncate(str: PBsonString; len: UInt32); cdecl; function bson_strdup(const str: PAnsiChar): PAnsiChar; cdecl; function bson_strdup_printf(const format: PAnsiChar): PAnsiChar; cdecl; varargs; function bson_strdupv_printf(const format: PAnsiChar): PAnsiChar; cdecl; varargs; function bson_strndup(const str: PAnsiChar; n_bytes: size_t): PAnsiChar; cdecl; procedure bson_strncpy(dst: PAnsiChar; const src: PAnsiChar; size: size_t); cdecl; function bson_vsnprintf(str: PAnsiChar; size: size_t; const format: PAnsiChar): Integer; cdecl; function bson_snprintf(str: PAnsiChar; size: size_t; const format: PAnsiChar): Integer; cdecl; procedure bson_strfreev(var strv: PAnsiChar); cdecl; function bson_strnlen(const s: PAnsiChar; maxlen: size_t): size_t; cdecl; function bson_ascii_strtoll(const str: PAnsiChar; var endptr: PAnsiChar; base: Integer): Int64; cdecl; type pbson_writer_t = Pointer; bson_realloc_func = function(mem: Pointer; num_bytes: size_t; ctx: Pointer): Pointer; cdecl; function bson_writer_new(var buf: Pointer; var buflen: size_t; offset: size_t; realloc_func: bson_realloc_func; realloc_func_ctx: Pointer) : pbson_writer_t; cdecl; procedure bson_writer_destroy(writer: pbson_writer_t); cdecl; function bson_writer_get_length(writer: pbson_writer_t): size_t; cdecl; function bson_writer_begin(writer: pbson_writer_t; var Bson: PBson): Boolean; cdecl; procedure bson_writer_end(writer: pbson_writer_t); cdecl; procedure bson_writer_rollback(writer: pbson_writer_t); cdecl; function bson_utf8_validate(const utf8: PAnsiChar; utf8_len: size_t; allow_null: Boolean): Boolean; cdecl; function bson_utf8_escape_for_json(const utf8: PAnsiChar; utf8_len: ssize_t): PAnsiChar; cdecl; function bson_utf8_get_char(const utf8: PAnsiChar): PWideChar; cdecl; function bson_utf8_next_char(const utf8: PAnsiChar): PAnsiChar; cdecl; type unichar_out = packed array [0 .. 5] of AnsiChar; procedure bson_utf8_from_unichar(unichar: WideChar; var utf8: unichar_out; var len: UInt32); cdecl; procedure bson_value_copy(const src: PBsonValue; dst: PBsonValue); cdecl; procedure bson_value_destroy(value: PBsonValue); cdecl; function bson_uint32_to_string(value: UInt32; const strptr: PPAnsiChar; str: PAnsiChar; size: size_t): size_t; cdecl; const BSON_ERROR_JSON = 1; BSON_ERROR_READER = 2; BSON_ERROR_BUFFER_SIZE = 64; procedure bson_set_error(var error: TBsonError; domain, code: UInt32; const format: PAnsiChar); cdecl; varargs; function bson_strerror_r(err_code: Integer; buf: PAnsiChar; buflen: size_t): PAnsiChar; cdecl; procedure bson_reinit(b: PBson); cdecl; type bson_mem_vtable_t = record malloc: function(num_bytes: size_t): Pointer; cdecl; calloc: function(n_members: size_t; num_bytes: size_t): Pointer; cdecl; realloc: function(mem: Pointer; num_bytes: size_t): Pointer; cdecl; free: procedure(mem: Pointer); cdecl; padding: array [0 .. 3] of Pointer; end; pbson_mem_vtable_t = ^bson_mem_vtable_t; procedure bson_mem_set_vtable(const vtable: pbson_mem_vtable_t); cdecl; procedure bson_mem_restore_vtable(); cdecl; function bson_malloc(num_bytes: size_t): Pointer; cdecl; function bson_malloc0(num_bytes: size_t): Pointer; cdecl; function bson_realloc(mem: Pointer; num_bytes: size_t): Pointer; cdecl; function bson_realloc_ctx(mem: Pointer; num_bytes: size_t; ctx: Pointer): Pointer; cdecl; procedure bson_free(mem: Pointer); cdecl; procedure bson_zero_free(mem: Pointer; size: size_t); cdecl; type bson_md5_t = record count: array [0 .. 1] of UInt32; // message length in bits, lsw first abcd: array [0 .. 3] of UInt32; // digest buffer buf: array [0 .. 63] of Byte; // accumulate block end; PBsonMD5 = ^bson_md5_t; md5_digest_t = array [0 .. 15] of Byte; procedure bson_md5_init(pms: PBsonMD5); cdecl; procedure bson_md5_append(pms: PBsonMD5; const data: Pointer; nbytes: UInt32); cdecl; procedure bson_md5_finish(pms: PBsonMD5; digest: md5_digest_t); cdecl; type pbcon_append_ctx_t = Pointer; pbcon_extract_ctx_t = Pointer; procedure bcon_append(Bson: PBson); cdecl; procedure bcon_append_ctx(Bson: PBson; ctx: pbcon_append_ctx_t); cdecl; varargs; procedure bcon_append_ctx_va(Bson: PBson; ctx: pbcon_append_ctx_t; va: Pointer); cdecl; procedure bcon_append_ctx_init(ctx: pbcon_append_ctx_t); cdecl; procedure bcon_extract_ctx_init(ctx: pbcon_extract_ctx_t); cdecl; procedure bcon_extract_ctx(Bson: PBson; ctx: pbcon_extract_ctx_t); cdecl; varargs; function bcon_extract_ctx_va(Bson: PBson; ctx: pbcon_extract_ctx_t; ap: Pointer): Boolean; cdecl; function bcon_extract(Bson: PBson): Boolean; cdecl; varargs; function bcon_extract_va(Bson: PBson; ctx: pbcon_extract_ctx_t): Boolean; cdecl; varargs; function bcon_new(unused: Pointer): PBson; cdecl; varargs; function bson_bcon_magic: PAnsiChar; cdecl; function bson_bcone_magic: PAnsiChar cdecl; implementation const bsondll = 'libbson-1.0-0.dll'; //function bson_iter_create: PBsonIterator; //begin // GetMem(Result, SizeOf(TBsonIterator)); //end; // //procedure bson_iter_dispose(iter: PBsonIterator); //begin // FreeMem(iter); //end; function bson_get_major_version: Integer; cdecl; external bsondll; function bson_get_minor_version: Integer; cdecl; external bsondll; function bson_get_micro_version: Integer; cdecl; external bsondll; function bson_get_version: PInteger; cdecl; external bsondll; function bson_check_version; cdecl; external bsondll; function bson_get_monotonic_time: Int64; cdecl; external bsondll; function bson_gettimeofday; cdecl; external bsondll; function bson_context_new; cdecl; external bsondll; procedure bson_context_destroy; cdecl; external bsondll; function bson_context_get_default; cdecl; external bsondll; function bson_new: PBson; cdecl; external bsondll; function bson_new_from_json; cdecl; external bsondll; function bson_init_from_json; cdecl; external bsondll; function bson_init_static; cdecl; external bsondll; procedure bson_init; cdecl; external bsondll; function bson_new_from_data; cdecl; external bsondll; function bson_new_from_buffer; cdecl; external bsondll; function bson_sized_new; cdecl; external bsondll; function bson_copy; cdecl; external bsondll; procedure bson_copy_to; cdecl; external bsondll; procedure bson_copy_to_excluding; cdecl; varargs; external bsondll; procedure bson_copy_to_excluding_noinit; cdecl; varargs; external bsondll; procedure bson_destroy; cdecl; external bsondll; function bson_destroy_with_steal; cdecl; external bsondll; function bson_get_data; cdecl; external bsondll; function bson_count_keys; cdecl; external bsondll; function bson_has_field; cdecl; external bsondll; function bson_compare; cdecl; external bsondll; function bson_equal; cdecl; external bsondll; function bson_validate; cdecl; external bsondll; function bson_as_json; cdecl; external bsondll; function bson_array_as_json; cdecl; external bsondll; function bson_append_value; cdecl; external bsondll; function bson_append_array; cdecl; external bsondll; function bson_append_binary; cdecl; external bsondll; function bson_append_bool; cdecl; external bsondll; function bson_append_code; cdecl; external bsondll; function bson_append_code_with_scope; cdecl; external bsondll; function bson_append_dbPointer; cdecl; external bsondll; function bson_append_double; cdecl; external bsondll; function bson_append_document; cdecl; external bsondll; function bson_append_document_begin; cdecl; external bsondll; function bson_append_document_end; cdecl; external bsondll; function bson_append_array_begin; cdecl; external bsondll; function bson_append_array_end; cdecl; external bsondll; function bson_append_int32; cdecl; external bsondll; function bson_append_int64; cdecl; external bsondll; function bson_append_iter; cdecl; external bsondll; function bson_append_minkey; cdecl; external bsondll; function bson_append_maxkey; cdecl; external bsondll; function bson_append_null; cdecl; external bsondll; function bson_append_oid; cdecl; external bsondll; function bson_append_regex; cdecl; external bsondll; function bson_append_utf8; cdecl; external bsondll; function bson_append_symbol; cdecl; external bsondll; function bson_append_time_t; cdecl; external bsondll; function bson_append_timeval; cdecl; external bsondll; function bson_append_date_time; cdecl; external bsondll; function bson_append_now_utc; cdecl; external bsondll; function bson_append_timestamp; cdecl; external bsondll; function bson_append_undefined; cdecl; external bsondll; function bson_concat; cdecl; external bsondll; procedure bson_iter_array; cdecl; external bsondll; function bson_iter_as_bool; cdecl; external bsondll; function bson_iter_as_int64; cdecl; external bsondll; procedure bson_iter_binary; cdecl; external bsondll; function bson_iter_bool; cdecl; external bsondll; function bson_iter_code; cdecl; external bsondll; function bson_iter_codewscope; cdecl; external bsondll; function bson_iter_date_time; cdecl; external bsondll; procedure bson_iter_dbPointer; cdecl; external bsondll; procedure bson_iter_document; cdecl; external bsondll; function bson_iter_double; cdecl; external bsondll; function bson_iter_dup_utf8; cdecl; external bsondll; function bson_iter_find; cdecl; external bsondll; function bson_iter_find_case; cdecl; external bsondll; function bson_iter_find_descendant; cdecl; external bsondll; procedure bson_iter_init; cdecl; external bsondll; function bson_iter_init_find; cdecl; external bsondll; function bson_iter_init_find_case; cdecl; external bsondll; function bson_iter_int32; cdecl; external bsondll; function bson_iter_int64; cdecl; external bsondll; function bson_iter_key; cdecl; external bsondll; function bson_iter_next; cdecl; external bsondll; function bson_iter_oid; cdecl; external bsondll; procedure bson_iter_overwrite_bool; cdecl; external bsondll; procedure bson_iter_overwrite_double; cdecl; external bsondll; procedure bson_iter_overwrite_int32; cdecl; external bsondll; procedure bson_iter_overwrite_int64; cdecl; external bsondll; function bson_iter_recurse; cdecl; external bsondll; function bson_iter_regex; cdecl; external bsondll; function bson_iter_symbol; cdecl; external bsondll; function bson_iter_time_t; cdecl; external bsondll; procedure bson_iter_timestamp; cdecl; external bsondll; procedure bson_iter_timeval; cdecl; external bsondll; function bson_iter_type; cdecl; external bsondll; function bson_iter_utf8; cdecl; external bsondll; function bson_iter_value; cdecl; external bsondll; function bson_iter_visit_all; cdecl; external bsondll; function bson_json_reader_new; cdecl; external bsondll; function bson_json_reader_new_from_fd; cdecl; external bsondll; function bson_json_reader_new_from_file; cdecl; external bsondll; procedure bson_json_reader_destroy; cdecl; external bsondll; function bson_json_reader_read; cdecl; external bsondll; function bson_json_data_reader_new; cdecl; external bsondll; procedure bson_json_data_reader_ingest; cdecl; external bsondll; function bson_oid_compare; cdecl; external bsondll; procedure bson_oid_copy; cdecl; external bsondll; function bson_oid_equal; cdecl; external bsondll; function bson_oid_is_valid; cdecl; external bsondll; function bson_oid_get_time_t; cdecl; external bsondll; function bson_oid_hash; cdecl; external bsondll; procedure bson_oid_init; cdecl; external bsondll; procedure bson_oid_init_from_data; cdecl; external bsondll; procedure bson_oid_init_from_string; cdecl; external bsondll; procedure bson_oid_init_sequence; cdecl; external bsondll; procedure bson_oid_to_string; cdecl; external bsondll; function bson_reader_new_from_handle; cdecl; external bsondll; function bson_reader_new_from_fd; cdecl; external bsondll; function bson_reader_new_from_file; cdecl; external bsondll; function bson_reader_new_from_data; cdecl; external bsondll; procedure bson_reader_destroy; cdecl; external bsondll; procedure bson_reader_set_read_func; cdecl; external bsondll; procedure bson_reader_set_destroy_func; cdecl; external bsondll; function bson_reader_read; cdecl; external bsondll; function bson_reader_tell; cdecl; external bsondll; function bson_string_new; cdecl; external bsondll; function bson_string_free; cdecl; external bsondll; procedure bson_string_append; cdecl; external bsondll; procedure bson_string_append_c; cdecl; external bsondll; procedure bson_string_append_unichar; cdecl; external bsondll; procedure bson_string_append_printf; cdecl; varargs; external bsondll; procedure bson_string_truncate; cdecl; external bsondll; function bson_strdup; cdecl; external bsondll; function bson_strdup_printf; cdecl; varargs; external bsondll; function bson_strdupv_printf; cdecl; varargs; external bsondll; function bson_strndup; cdecl; external bsondll; procedure bson_strncpy; cdecl; external bsondll; function bson_vsnprintf; cdecl; external bsondll; function bson_snprintf; cdecl; external bsondll; procedure bson_strfreev; cdecl; external bsondll; function bson_strnlen; cdecl; external bsondll; function bson_ascii_strtoll; cdecl; external bsondll; function bson_writer_new; cdecl; external bsondll; procedure bson_writer_destroy; cdecl; external bsondll; function bson_writer_get_length; cdecl; external bsondll; function bson_writer_begin; cdecl; external bsondll; procedure bson_writer_end; cdecl; external bsondll; procedure bson_writer_rollback; cdecl; external bsondll; function bson_utf8_validate; cdecl; external bsondll; function bson_utf8_escape_for_json; cdecl; external bsondll; function bson_utf8_get_char; cdecl; external bsondll; function bson_utf8_next_char; cdecl; external bsondll; procedure bson_utf8_from_unichar; cdecl; external bsondll; procedure bson_value_copy; cdecl; external bsondll; procedure bson_value_destroy; cdecl; external bsondll; function bson_uint32_to_string; cdecl; external bsondll; procedure bson_set_error; cdecl; varargs; external bsondll; function bson_strerror_r; cdecl; external bsondll; procedure bson_mem_set_vtable; cdecl; external bsondll; procedure bson_mem_restore_vtable; cdecl; external bsondll; function bson_malloc; cdecl; external bsondll; function bson_malloc0; cdecl; external bsondll; function bson_realloc; cdecl; external bsondll; function bson_realloc_ctx; cdecl; external bsondll; procedure bson_free; cdecl; external bsondll; procedure bson_zero_free; cdecl; external bsondll; procedure bson_md5_init; cdecl; external bsondll; procedure bson_md5_append; cdecl; external bsondll; procedure bson_md5_finish; cdecl; external bsondll; procedure bson_reinit; cdecl; external bsondll; procedure bcon_append; cdecl; external bsondll; procedure bcon_append_ctx; cdecl; varargs; external bsondll; procedure bcon_append_ctx_va; cdecl; external bsondll; procedure bcon_append_ctx_init; cdecl; external bsondll; procedure bcon_extract_ctx_init; cdecl; external bsondll; procedure bcon_extract_ctx; cdecl; varargs; external bsondll; function bcon_extract_ctx_va; cdecl; external bsondll; function bcon_extract; cdecl; varargs; external bsondll; function bcon_extract_va; cdecl; varargs; external bsondll; function bcon_new; cdecl; varargs; external bsondll; function bson_bcon_magic: PAnsiChar; cdecl; external bsondll; function bson_bcone_magic: PAnsiChar cdecl; external bsondll; end.
unit cosmos.common.view.updaterconf; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, GroupHeader, Vcl.ImgList, cosmos.system.messages, Vcl.Buttons, cosmos.framework.forms.pages, Cosmos.Framework.Interfaces.Dialogs, cosmos.system.formsconst, Xml.XMLDoc, Xml.XMLIntf, Vcl.ActnList, System.Actions, cosmos.classes.security; type TFrmUpdaterOptions = class(TFrmCosmosPages) GrpUpdates: TMSGroupHeader; ChkAutoUpdate: TCheckBox; MSGroupHeader3: TMSGroupHeader; RdbHTTP: TRadioButton; RdbFTP: TRadioButton; RdbNetwork: TRadioButton; ImgSource: TImage; ImageSources: TImageList; Bevel1: TBevel; Button1: TButton; Button2: TButton; Button3: TButton; Bevel2: TBevel; Panel1: TPanel; Label2: TLabel; RdbConfirmAllFiles: TRadioButton; RdbConfirmPackage: TRadioButton; RdbConfirmNone: TRadioButton; ActionList1: TActionList; ActHttpOptions: TAction; ActFtpOptions: TAction; ActNetworkOptions: TAction; EdtUpdatesSource: TEdit; LblUpdatesSource: TLabel; Image1: TImage; Label1: TLabel; ImageList1: TImageList; procedure ChkAutoUpdateClick(Sender: TObject); procedure RdbHTTPClick(Sender: TObject); procedure ActFtpOptionsExecute(Sender: TObject); procedure ActNetworkOptionsExecute(Sender: TObject); procedure ActHttpOptionsExecute(Sender: TObject); procedure EdtUpdatesSourceChange(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FChanged: boolean; function LoadBitmap: TBitmap; protected function GetChanged: boolean; override; function GetEnabled: boolean; override; function GetPageInfo: TPageInfo; override; function SaveOptions: boolean; override; procedure LoadOptions; override; function ValidateFields: boolean; override; property Changed: boolean read GetChanged; property Enabled: boolean read GetEnabled; property PageInfo: TPageInfo read GetPageInfo; public { Public declarations } end; var FrmUpdaterOptions: TFrmUpdaterOptions; implementation {$R *.dfm} uses cosmos.common.view.updaterFTPconf, cosmos.common.view.updaterothersconf; procedure TFrmUpdaterOptions.ActFtpOptionsExecute(Sender: TObject); begin FrmFTPOptions := TFrmFTPOptions.Create(self); try FrmFTPOptions.ShowConfigurations; finally if Assigned(FrmFTPOptions) then FreeAndNil(FrmFTPOptions); end; end; procedure TFrmUpdaterOptions.ActHttpOptionsExecute(Sender: TObject); begin Exit; end; procedure TFrmUpdaterOptions.ActNetworkOptionsExecute(Sender: TObject); begin Exit; end; procedure TFrmUpdaterOptions.ChkAutoUpdateClick(Sender: TObject); begin LblUpdatesSource.Enabled := TCheckBox(sender).Checked; EdtUpdatesSource.Enabled := LblUpdatesSource.Enabled; end; procedure TFrmUpdaterOptions.EdtUpdatesSourceChange(Sender: TObject); begin FChanged := True; end; procedure TFrmUpdaterOptions.FormCreate(Sender: TObject); begin inherited; if (IRemoteCon <> nil) and (IRemoteCon.CurrentConnectionInfo <> nil) then begin if not (cfConfPageUpdater in IRemoteCon.CurrentConnectionInfo.AuthorizedFeatures) then self.DisableControls; end else self.DisableControls; end; function TFrmUpdaterOptions.GetChanged: boolean; begin Result := FChanged; end; function TFrmUpdaterOptions.GetEnabled: boolean; begin Result := True; end; function TFrmUpdaterOptions.GetPageInfo: TPageInfo; begin Result.CodePage := 'Cosmos.Updater'; Result.PageTitle := Caption; Result.PageDesc := TConfigurationPagesDesc.ConfGerais; Result.PageTreeRoot := TCosmosTitles.ConfGerais; Result.PageTreeItem := TCosmosTitles.ConfAtualizacoes; Result.PageIndex := 1; Result.PageImage := LoadBitmap; Result.HelpFile := Application.CurrentHelpFile; Result.HelpContext := self.HelpContext; end; function TFrmUpdaterOptions.LoadBitmap: TBitmap; begin Result := TBitMap.Create; ImageList1.GetBitmap(0, Result); end; procedure TFrmUpdaterOptions.LoadOptions; var AXMLDoc: TXMLDocument; ANode: IXMLNode; begin //Lê as opções de configuração salvas. AXMLDoc := self.CreateXMLDocument(ICosmosApp.IApplicationPaths.GetCommonConfigurationsFile); try ANode := AXMLDoc.DocumentElement; ANode := ANode.ChildNodes.FindNode('UpdatesInfo'); ANode := ANode.ChildNodes.FindNode('Info'); if ANode <> nil then begin ChkAutoUpdate.Checked := ANode.Attributes['AutoUpdate']; EdtUpdatesSource.Text := ANode.Attributes['UpdatesSourceFile']; //Lê o protocolo de atualização a ser usado case ANode.Attributes['Protocol'] of 0: RdbHTTP.Checked := True; 1: RdbFTP.Checked := True; 2: RdbNetwork.Checked := True else RdbHTTP.Checked := True; end; //Lê a ação padrão a ser usada ao receber uma atualização. case ANode.Attributes['OnNewUpdate'] of 0: RdbConfirmAllFiles.Checked := True; 1: RdbConfirmPackage.Checked := True; 2: RdbConfirmNone.Checked := True; end; FChanged := False; //default if Assigned(AXMLDoc) then FreeAndNil(AXMLDoc); end; except on E: Exception do begin ICosmosApp.DlgMessage.ErrorMessage(TCosmosTitles.SystemFailure, TCosmosErrorMsg.LoadConfigurations); ICosmosApp.MainLog.RegisterError(E.Message); if Assigned(AXMLDoc) then FreeAndNil(AXMLDoc); end; end; end; procedure TFrmUpdaterOptions.RdbHTTPClick(Sender: TObject); begin ImageSources.GetIcon(TRadioButton(Sender).Tag, ImgSource.Picture.Icon); ImgSource.Update; FChanged := True; end; function TFrmUpdaterOptions.SaveOptions: boolean; var AXMLDoc: TXMLDocument; ANode: IXMLNode; begin {Salva as opções de configuração. Somente salva se houver um usuário autenticado e se o mesmo for administrador do Cosmos.} Result := ValidateFields; if not Result then begin ICosmosApp.DlgMessage.WarningMessage(TCosmosTitles.Atenttion, TCosmosWarningMsg.IncompletedFields); Exit; end; AXMLDoc := self.CreateXMLDocument(ICosmosApp.IApplicationPaths.GetCommonConfigurationsFile); try ANode := AXMLDoc.DocumentElement; ANode := ANode.ChildNodes.FindNode('UpdatesInfo'); ANode := ANode.ChildNodes.FindNode('Info'); if ANode <> nil then begin //Salva se a atualização será automática e outras informações correlatas. ANode.Attributes['AutoUpdate'] := ChkAutoUpdate.Checked; ANode.Attributes['UpdatesSourceFile'] := EdtUpdatesSource.Text; //Salva agora o protocolo de atualização a ser usado if RdbHTTP.Checked then ANode.Attributes['Protocol'] := 0 else if RdbFTP.Checked then ANode.Attributes['Protocol'] := 1 else ANode.Attributes['Protocol'] := 2; //Salva agora a ação padrão a ser usada ao receber uma atualização if RdbConfirmAllFiles.Checked then ANode.Attributes['OnNewUpdate'] := 0 else if RdbConfirmPackage.Checked then ANode.Attributes['OnNewUpdate'] := 1 else ANode.Attributes['OnNewUpdate'] := 2; AXMLDoc.SaveToFile(AXMLDoc.FileName); Result := True; end; finally if Assigned(AXMLDoc) then FreeAndNil(AXMLDoc); end; end; function TFrmUpdaterOptions.ValidateFields: boolean; begin if ChkAutoUpdate.Checked then begin Result := HasValue(EdtUpdatesSource); end else Result := True; end; initialization RegisterClass(TFrmUpdaterOptions); finalization UnRegisterClass(TFrmUpdaterOptions); end.
(** This module contains a wizard interface for creating an options page frame within the IDEs main option dialogue. @Author David Hoyle @Version 1.0 @Date 18 Dec 2016 **) Unit DGHIDEAutoSaveIDEOptionsInterface; Interface Uses ToolsAPI, Forms, DGHIDEAutoSaveOptionsFrame; {$INCLUDE CompilerDefinitions.inc} {$IFDEF DXE00} Type (** A class to create an options frame page for the IDEs options dialogue. **) TDGHIDEAutoSaveOptionsInterface = Class(TInterfacedObject, INTAAddInOptions) Strict Private FFrame: TfmIDEAutoSaveOptions; Strict Protected Public Procedure DialogClosed(Accepted: Boolean); Procedure FrameCreated(AFrame: TCustomFrame); Function GetArea: String; Function GetCaption: String; Function GetFrameClass: TCustomFrameClass; Function GetHelpContext: Integer; Function IncludeInIDEInsight: Boolean; Function ValidateContents: Boolean; End; {$ENDIF} Implementation {TDGHAutoSaveOptions} Uses DGHIDEAutoSaveSettings; {$IFDEF DXE00} (** This method is call when the IDEs Options dialogue is closed. Accepted = True if the dialogue is confirmed and settings should be saved or Accepted = False if the dialogue if dismissed and setting changes should not be saved. @precon None. @postcon If the dialogue is accepted then the options frame settings are retreived and saved back to the applications options class. @param Accepted as a Boolean **) Procedure TDGHIDEAutoSaveOptionsInterface.DialogClosed(Accepted: Boolean); Var iInterval: Integer; boolPrompt, boolEnabled: Boolean; Begin If Accepted Then Begin FFrame.FinaliseFrame(iInterval, boolPrompt, boolEnabled); AppOptions.Interval := iInterval; AppOptions.Prompt := boolPrompt; AppOptions.Enabled := boolEnabled; End; End; (** This method is called when IDE creates the Options dialogue and creates your options frame for you and should be used to initialise the frame information. @precon None. @postcon Checks the frame is the corrct frames and is so initialises the frame through its InitialiseFrame method. @param AFrame as a TCustomFrame **) Procedure TDGHIDEAutoSaveOptionsInterface.FrameCreated(AFrame: TCustomFrame); Begin If AFrame Is TfmIDEAutoSaveOptions Then Begin FFrame := AFrame As TfmIDEAutoSaveOptions; FFrame.InitialiseFrame(AppOptions.Interval, AppOptions.Prompt, AppOptions.Enabled); End; End; (** This is called by the IDE to get the primary area in the options tree where your options frame is to be displayed. Recommended to return a null string to have your options displayed under a third party node. @precon None. @postcon Returns a null string to place the options under the Third Parrty node. @return a String **) Function TDGHIDEAutoSaveOptionsInterface.GetArea: String; Begin Result := ''; End; (** This method is caled by the IDE to get the sub node tre items where the page is to be displayed. The period acts as a separator for another level of node in the tree. @precon None. @postcon Returns the name of the expert then the page name separated by a period. @return a String **) Function TDGHIDEAutoSaveOptionsInterface.GetCaption: String; Begin Result := 'IDE Auto Save.Options'; End; (** This method should return a class reference to your frame for so that the IDe can create an instance of your frame for you. @precon None. @postcon Returns a class reference to the options frame form. @return a TCustomFrameClass **) Function TDGHIDEAutoSaveOptionsInterface.GetFrameClass: TCustomFrameClass; Begin Result := TfmIDEAutoSaveOptions; End; (** This method returns the help context reference for the optins page. @precon None. @postcon Returns 0 for no context. @return an Integer **) Function TDGHIDEAutoSaveOptionsInterface.GetHelpContext: Integer; Begin Result := 0; End; (** This method determines whether your options frame page appears in the IDE Insight search. Its recommended you return true. @precon None. @postcon Returns true to include in IDE Insight. @return a Boolean **) Function TDGHIDEAutoSaveOptionsInterface.IncludeInIDEInsight: Boolean; Begin Result := True; End; (** This method should be used to valdate you options frame. You should display an error message if there is something wrong and return false else if all is okay return true. @precon None. @postcon Checks the interval is a valid integer greater than zero. @return a Boolean **) Function TDGHIDEAutoSaveOptionsInterface.ValidateContents: Boolean; Var iInterval: Integer; iErrorCode: Integer; Begin Val(FFrame.edtAutosaveInterval.Text, iInterval, iErrorCode); Result := (iErrorCode = 0) And (iInterval > 0); End; {$ENDIF} End.
unit TBGFirebaseConnection.Interfaces; interface uses System.JSON, Data.DB, System.Classes; type iFirebaseConnect = interface; iFirebasePut = interface; iFirebaseGet = interface; iFirebasePatch = interface; iFirebaseDelete = interface; iFirebaseCloudMessage = interface; iFirebaseCloudMessageRegistration = interface; iFirebaseConnection = interface ['{D24B1AB1-2AA9-46E3-8DB8-5CB550A2BD17}'] function Connect : iFirebaseConnect; function Put : iFirebasePut; function Get : iFirebaseGet; function Patch : iFirebasePatch; function Delete : iFirebaseDelete; function CloudMessage : iFirebaseCloudMessage; procedure &Exec; end; iFirebaseConnect = interface ['{CAABD8E2-3530-4D50-9EBB-225B45E6A686}'] function BaseURL (Value : String) : iFirebaseConnect; overload; function Auth (Value : String) : iFirebaseConnect; overload; function uId (Value : String) : iFirebaseConnect; overload; function BaseURL : String; overload; function Auth : String; overload; function uId : String; overload; function &End : iFirebaseConnection; end; iFirebasePut = interface ['{15826039-2077-4FA3-A952-5F6EE716664E}'] function Resource ( Value : String) : iFirebasePut; overload; function Resource : String; overload; function Json ( Value : String) : iFirebasePut; overload; function Json ( Value : TJsonObject) : iFirebasePut; overload; function Json ( Value : TJsonArray ) : iFirebasePut; overload; function Json : String; overload; function &End : iFirebaseConnection; end; iFirebasePatch = interface ['{15826039-2077-4FA3-A952-5F6EE716664E}'] function Resource ( Value : String) : iFirebasePatch; overload; function Resource : String; overload; function Json ( Value : String) : iFirebasePatch; overload; function Json ( Value : TJsonObject) : iFirebasePatch; overload; function Json : String; overload; function &End : iFirebaseConnection; end; iFirebaseDelete = interface ['{15826039-2077-4FA3-A952-5F6EE716664E}'] function Resource ( Value : String) : iFirebaseDelete; overload; function Resource : String; overload; function Json ( Value : String) : iFirebaseDelete; overload; function Json ( Value : TJsonObject) : iFirebaseDelete; overload; function Json : String; overload; function &End : iFirebaseConnection; end; iFirebaseGet = interface ['{42656C46-ADD4-4F7D-AA15-DB4E9437CF55}'] function DataSet ( Value : TDataSet ) : iFirebaseGet; overload; function DataSet : TDataSet; overload; function ResponseContent(var aResponse : String ) : iFirebaseGet; overload; function ResponseContent(var aJsonArray : TJsonArray) : iFirebaseGet; overload; function ResponseContent(var aJsonObject : TJsonObject) : iFirebaseGet; overload; function Resource (Value : String) : iFirebaseGet; overload; function Resource : String; overload; function &End : iFirebaseConnection; end; iFirebaseCloudMessage = interface ['{4B4EBB38-10D2-4CAA-812C-3A0A900DFFA5}'] function BaseURL( aBaseURL : String ) : iFirebaseCloudMessage; function Auth ( aAuth : String ) : iFirebaseCloudMessage; function UID ( aUID : String ) : iFirebaseCloudMessage; function RemetenteCode(aCode : String) : iFirebaseCloudMessage; function APIKey(aApi : String) : iFirebaseCloudMessage; function AddDeviceAPI(aDeviceToken : String) : iFirebaseCloudMessage; function AddDeviceList(aDeviceList : TStringList) : iFirebaseCloudMessage; function SendMessage(aMessage : String) : iFirebaseCloudMessage; function Send : iFirebaseCloudMessage; function RegisterPush : iFirebaseCloudMessageRegistration; end; iFirebaseCloudMessageRegistration = interface ['{CCBA59F7-2B91-4F92-8323-4C7610B6C873}'] function RegisterPushService : iFirebaseCloudMessageRegistration; function BaseURL(aURL : String) : iFirebaseCloudMessageRegistration; function Auth(aAuth : String) : iFirebaseCloudMessageRegistration; function uID(aUID : String) : iFirebaseCloudMessageRegistration; function Resource(aResource : String) : iFirebaseCloudMessageRegistration; function RemetenteCode(aCode : String) : iFirebaseCloudMessageRegistration; end; implementation end.
unit StringBuffer; interface uses SysUtils; type EBufferDepleted = class(Exception); EBufferUnderflow = class(Exception); EBufferPosError = class(Exception); TSchStringBuffer = class(TObject) private fStringBuffer: String; function GetStringBuffer: String; virtual; procedure SetStringBuffer(const Value: String); virtual; public constructor Create(ABuffer: String); overload; constructor Create(); overload; destructor Destroy(); override; property StringBuffer: String Read GetStringBuffer Write SetStringBuffer; end; TSchReadStringBuffer = class(TSchStringBuffer) private fPosition: Integer; fBuffLength: Integer; procedure SetStringBuffer(const Value: String); override; public function ReadByte(): Byte; function ReadChar(): Char; function ReadWord(): Word; function ReadInteger(): Cardinal; function ReadString(): String; function ReadInt8(): Byte; function ReadInt16(): Word; function ReadInt32(): Cardinal; function ReadInt64(): Int64; function ReadFloat(): Single; function ReadBuffer(Size: Integer): String; property Size: Integer Read fBuffLength; end; TSchReadWriteStringBuffer = class(TSchReadStringBuffer) public procedure WriteByte(AByte: Byte); procedure WriteChar(AChar: Char); procedure WriteWord(AWord: Word); procedure WriteInteger(AInt: Cardinal); procedure WriteString(AStr: String); procedure WriteInt8(AByte: Byte); procedure WriteInt16(AWord: Word); procedure WriteInt32(AInt: Cardinal); procedure WriteFloat(AFt: Single); procedure WriteInt64(AWInt: Int64); end; TSchInOutStringBuffer = class(TSchReadWriteStringBuffer) private fSavedPosition: Integer; procedure SetStringBuffer(const Value: String); override; public procedure AddChunk(AChunk: String); procedure SavePosition(); procedure RestorePosition(); procedure ClearUsedChunk(); end; implementation { TSchStringBuffer } constructor TSchStringBuffer.Create(ABuffer: String); begin SetStringBuffer(ABuffer); end; constructor TSchStringBuffer.Create; begin Create(''); end; destructor TSchStringBuffer.Destroy; begin fStringBuffer := ''; inherited; end; function TSchStringBuffer.GetStringBuffer: String; begin Result := fStringBuffer; end; procedure TSchStringBuffer.SetStringBuffer(const Value: String); begin fStringBuffer := Value; end; { TSchReadStringBuffer } function TSchReadStringBuffer.ReadBuffer(Size: Integer): String; var iI: Integer; begin Result := ''; for iI := 1 to Size do Result := Result + ReadChar(); end; function TSchReadStringBuffer.ReadByte: Byte; begin if fPosition > fBuffLength then begin raise EBufferDepleted.Create('String Buffer Depleted!'); exit; end; Result := Byte(fStringBuffer[fPosition]); Inc(fPosition); end; function TSchReadStringBuffer.ReadChar: Char; begin Result := Char(ReadByte()); end; function TSchReadStringBuffer.ReadFloat: Single; var Floaty: Single; _a: array[0..3] of Byte absolute Floaty; begin _a[0] := ReadByte(); _a[1] := ReadByte(); _a[2] := ReadByte(); _a[3] := ReadByte(); Result := Floaty; end; function TSchReadStringBuffer.ReadInt16: Word; begin Result := ReadWord(); end; function TSchReadStringBuffer.ReadInt32: Cardinal; begin Result := ReadInteger(); end; function TSchReadStringBuffer.ReadInt64: Int64; var _Int64: Int64; _a: array[0..7] of Byte absolute _Int64; begin _a[0] := ReadByte(); _a[1] := ReadByte(); _a[2] := ReadByte(); _a[3] := ReadByte(); _a[4] := ReadByte(); _a[5] := ReadByte(); _a[6] := ReadByte(); _a[7] := ReadByte(); Result := _Int64; end; function TSchReadStringBuffer.ReadInt8: Byte; begin Result := ReadByte(); end; function TSchReadStringBuffer.ReadInteger: Cardinal; var Int32: Cardinal; _a: array[0..3] of Byte absolute Int32; begin _a[0] := ReadByte(); _a[1] := ReadByte(); _a[2] := ReadByte(); _a[3] := ReadByte(); Result := Int32; end; function TSchReadStringBuffer.ReadString: String; var Ch: Char; begin Result := ''; while True do begin Ch := ReadChar(); if Ch = #0 then break; Result := Result + Ch; end; end; function TSchReadStringBuffer.ReadWord: Word; var Int16: Integer; _a: array[0..1] of Byte absolute Int16; begin _a[0] := ReadByte(); _a[1] := ReadByte(); Result := Int16; end; procedure TSchReadStringBuffer.SetStringBuffer(const Value: String); begin fPosition := 1; fBuffLength := Length(Value); inherited; end; { TSchReadWriteStringBuffer } procedure TSchReadWriteStringBuffer.WriteByte(AByte: Byte); begin Insert(Char(AByte), fStringBuffer, fPosition); Inc(fPosition); Inc(fBuffLength); end; procedure TSchReadWriteStringBuffer.WriteChar(AChar: Char); begin WriteByte(Byte(AChar)); end; procedure TSchReadWriteStringBuffer.WriteFloat(AFt: Single); var _a: array[0..3] of Byte absolute AFt; begin WriteByte(_a[0]); WriteByte(_a[1]); WriteByte(_a[2]); WriteByte(_a[3]); end; procedure TSchReadWriteStringBuffer.WriteInt16(AWord: Word); begin WriteWord(AWord); end; procedure TSchReadWriteStringBuffer.WriteInt32(AInt: Cardinal); begin WriteInteger(AInt); end; procedure TSchReadWriteStringBuffer.WriteInt64(AWInt: Int64); var _a: array[0..7] of Byte absolute AWInt; begin WriteByte(_a[0]); WriteByte(_a[1]); WriteByte(_a[2]); WriteByte(_a[3]); WriteByte(_a[4]); WriteByte(_a[5]); WriteByte(_a[6]); WriteByte(_a[7]); end; procedure TSchReadWriteStringBuffer.WriteInt8(AByte: Byte); begin WriteByte(AByte); end; procedure TSchReadWriteStringBuffer.WriteInteger(AInt: Cardinal); var _a: array[0..3] of Byte absolute AInt; begin WriteByte(_a[0]); WriteByte(_a[1]); WriteByte(_a[2]); WriteByte(_a[3]); end; procedure TSchReadWriteStringBuffer.WriteString(AStr: String); var iI: Integer; begin if Length(AStr) > 0 then for iI := 1 to Length(AStr) do WriteChar(AStr[iI]); WriteChar(#0); // Null Terminator; end; procedure TSchReadWriteStringBuffer.WriteWord(AWord: Word); var _a: array[0..1] of Byte absolute AWord; begin WriteByte(_a[0]); WriteByte(_a[1]); end; { TSchInOutStringBuffer } procedure TSchInOutStringBuffer.AddChunk(AChunk: String); begin fStringBuffer := fStringBuffer + AChunk; Inc(fBuffLength, Length(AChunk)); end; procedure TSchInOutStringBuffer.ClearUsedChunk; begin if fSavedPosition > 0 then fSavedPosition := fSavedPosition - fPosition; Delete(fStringBuffer, 1, fPosition - 1); fBuffLength := fBuffLength - fPosition + 1; fPosition := 1; end; procedure TSchInOutStringBuffer.RestorePosition; begin if fSavedPosition = 0 then begin raise EBufferPosError.Create( 'Unable to restore old position. Position hasn''t been saved priorly.'); exit; end; if fSavedPosition > fBuffLength then begin raise EBufferUnderflow.Create('Unable to restore old position. The buffer is smaller.'); exit; end; fPosition := fSavedPosition; fSavedPosition := 0; end; procedure TSchInOutStringBuffer.SavePosition; begin fSavedPosition := fPosition; end; procedure TSchInOutStringBuffer.SetStringBuffer(const Value: String); begin fSavedPosition := 0; inherited; end; end.
unit TimeMaskFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, InputFrame, StdCtrls, Mask; type Tframe_TimeMask = class(Tframe_Input) MaskEdit: TMaskEdit; procedure MaskEditChange(Sender: TObject); private function GetFieldValue: variant; override; procedure SetFieldValue(Value: variant); override; public procedure MySetFocus; override; end; implementation {$R *.dfm} { Tframe_TimeMask } function Tframe_TimeMask.GetFieldValue: variant; begin Result := StrToTime( MaskEdit.Text ); end; procedure Tframe_TimeMask.SetFieldValue(Value: variant); var _OnChange: TNotifyEvent; begin _OnChange := MaskEdit.OnChange; try MaskEdit.OnChange := nil; MaskEdit.Text := FormatDateTime('hh:mm', Value); finally MaskEdit.OnChange := _OnChange; end; end; procedure Tframe_TimeMask.MaskEditChange(Sender: TObject); begin if Assigned( F_OnControlChange ) then F_OnControlChange( Sender ); OnInputChange( Sender ); end; procedure Tframe_TimeMask.MySetFocus; begin MaskEdit.SetFocus; end; end.
unit NtUtils.AntiHooking; { This module introduces user-mode unhooking of ntdll functions via IAT modification. It works for native 32 and 64 bits, as well as under WoW64. Note that not all functions support unhooking, but syscall stubs always do. } interface uses NtUtils, NtUtils.Ldr; type TUnhookableImport = record FunctionName: AnsiString; IATEntry: PPointer; TargetRVA: Cardinal; // inside ntdll end; // Find all imports of a module that can be unhooked via IAT modification function RtlxFindUnhookableImport( const Module: TModuleEntry; out Entries: TArray<TUnhookableImport> ): TNtxStatus; // Unhook the specified functions function RtlxEnforceAntiHooking( const Imports: TArray<TUnhookableImport>; Enable: Boolean = True ): TNtxStatus; // Unhook functions imported using Delphi's "external" keyword // Example usage: RtlxEnforceExternalImportAntiHooking([@NtCreateUserProcess]); function RtlxEnforceExternalImportAntiHooking( const ExtenalImports: TArray<Pointer>; Enable: Boolean = True ): TNtxStatus; // Unhook specific functions for a single module function RtlxEnforceModuleAntiHooking( const Module: TModuleEntry; const Functions: TArray<AnsiString>; Enable: Boolean = True ): TNtxStatus; // Unhook specific functions for all currently loaded modules function RtlxEnforceGlobalAntiHooking( const Functions: TArray<AnsiString>; Enable: Boolean = True ): TNtxStatus; // Apply a custom IAT hook to a specific module function RtlxInstallIATHook( out Reverter: IAutoReleasable; const ModuleName: String; const ImportModuleName: AnsiString; const ImportFunction: AnsiString; [in] Hook: Pointer; [out, opt] OriginalTarget: PPointer = nil ): TNtxStatus; implementation uses Ntapi.ntdef, Ntapi.ntldr, Ntapi.ntmmapi, Ntapi.ntpebteb, Ntapi.ntstatus, DelphiUtils.ExternalImport, NtUtils.Sections, NtUtils.ImageHlp, NtUtils.SysUtils, NtUtils.Memory, NtUtils.Processes, DelphiUtils.Arrays, DelphiApi.Reflection; {$BOOLEVAL OFF} {$IFOPT R+}{$DEFINE R+}{$ENDIF} {$IFOPT Q+}{$DEFINE Q+}{$ENDIF} var AlternateNtdllInitialized: Boolean; AlternateNtdll: IMemory; AlternateTargets: TArray<TExportEntry>; // Note: we suppress range checking in these functions because hooked modules // might have atypical layout (such as an import table outside of the image) function RtlxInitializeAlternateNtdll: TNtxStatus; begin if AlternateNtdllInitialized then begin Result.Status := STATUS_SUCCESS; Exit; end; // Map a second instance of ntdll from KnownDlls Result := RtlxMapKnownDll(AlternateNtdll, ntdll, RtlIsWoW64); if not Result.IsSuccess then Exit; // Parse its export and save all functions as available for redirection Result := RtlxEnumerateExportImage(AlternateTargets, AlternateNtdll.Region, True, False); if not Result.IsSuccess then begin AlternateNtdll := nil; Exit; end; AlternateNtdll.AutoRelease := False; AlternateNtdllInitialized := True; end; function UnhookableImportCapturer( [in] IAT: Pointer ): TConvertRoutineEx<TImportEntry, TUnhookableImport>; begin Result := function ( const Index: Integer; const Import: TImportEntry; out UnhookableImport: TUnhookableImport ): Boolean var i: Integer; begin // Find the export that corresponds to the function. Use fast binary search // when importing by name (which are sorted by default) or slow linear // search when importing by ordinal. if Import.ImportByName then i := TArray.BinarySearchEx<TExportEntry>(AlternateTargets, function (const Target: TExportEntry): Integer begin Result := RtlxCompareAnsiStrings(Target.Name, Import.Name, True) end ) else i := TArray.IndexOfMatch<TExportEntry>(AlternateTargets, function (const Target: TExportEntry): Boolean begin Result := (Target.Ordinal = Import.Ordinal); end ); if i < 0 then Exit(False); // Save the name, IAT entry address, and ntdll function RVA UnhookableImport.FunctionName := Import.Name; UnhookableImport.IATEntry := PPointer(PByte(IAT) + Cardinal(Index) * SizeOf(Pointer)); UnhookableImport.TargetRVA := AlternateTargets[i].VirtualAddress; Result := True; end; end; function UnhookableImportFinder( [in] Base: Pointer ): TMapRoutine<TImportDllEntry, TArray<TUnhookableImport>>; begin // Find and capture all functions that are imported from ntdll Result := function (const Dll: TImportDllEntry): TArray<TUnhookableImport> begin if RtlxEqualAnsiStrings(Dll.DllName, ntdll) then Result := TArray.ConvertEx<TImportEntry, TUnhookableImport>(Dll.Functions, UnhookableImportCapturer(PByte(Base) + Dll.IAT)) else Result := nil; end end; function RtlxFindUnhookableImport; var AllImport: TArray<TImportDllEntry>; begin Result := RtlxInitializeAlternateNtdll; if not Result.IsSuccess then Exit; // Determine which functions a module imports Result := RtlxEnumerateImportImage(AllImport, Module.Region, True, [itNormal, itDelayed], False); if not Result.IsSuccess then Exit; // Intersect them with what we can unhook Entries := TArray.FlattenEx<TImportDllEntry, TUnhookableImport>(AllImport, UnhookableImportFinder(Module.DllBase)); end; function RtlxEnforceAntiHooking; var ImportGroups: TArray<TArrayGroup<Pointer, TUnhookableImport>>; ProtectionReverter: IAutoReleasable; TargetModule: Pointer; i, j: Integer; begin Result := RtlxInitializeAlternateNtdll; if not Result.IsSuccess then Exit; // Choose where to redirect the functions if Enable then TargetModule := AlternateNtdll.Data else TargetModule := hNtdll.DllBase; // Combine entries that reside on the same page so we can change memory // protection more efficiently ImportGroups := TArray.GroupBy<TUnhookableImport, Pointer>(Imports, function (const Element: TUnhookableImport): Pointer begin Result := Pointer(UIntPtr(Element.IATEntry) and not (PAGE_SIZE - 1)); end ); for i := 0 to High(ImportGroups) do begin // Make sure the pages with IAT entries are writable Result := NtxProtectMemoryAuto(NtxCurrentProcess, ImportGroups[i].Key, PAGE_SIZE, PAGE_READWRITE, ProtectionReverter); if not Result.IsSuccess then Exit; // Redirect the import for j := 0 to High(ImportGroups[i].Values) do ImportGroups[i].Values[j].IATEntry^ := PByte(TargetModule) + ImportGroups[i].Values[j].TargetRVA; end; end; function RtlxEnforceExternalImportAntiHooking; var CurrentModule: TModuleEntry; UnhookableImport: TArray<TUnhookableImport>; IATEntries: TArray<PPointer>; i: Integer; begin Result := LdrxFindModule(CurrentModule, ContainingAddress(@ImageBase)); if not Result.IsSuccess then Exit; // Find all imports from the current module that we can unhook Result := RtlxFindUnhookableImport(CurrentModule, UnhookableImport); if not Result.IsSuccess then Exit; // Determine IAT entry locations of the specified imports SetLength(IATEntries, Length(ExtenalImports)); for i := 0 to High(IATEntries) do IATEntries[i] := ExternalImportTarget(ExtenalImports[i]); // Leave only the function we were asked to unhook TArray.FilterInline<TUnhookableImport>(UnhookableImport, function (const Import: TUnhookableImport): Boolean begin Result := TArray.Contains<PPointer>(IATEntries, Import.IATEntry); end ); if Length(UnhookableImport) <> Length(ExtenalImports) then begin // Should not happen as long as the specified functions are imported via the // "extern" keyword. Result.Location := 'RtlxEnforceExternalImportAntiHooking'; Result.Status := STATUS_ENTRYPOINT_NOT_FOUND; Exit; end; // Adjust IAT targets Result := RtlxEnforceAntiHooking(UnhookableImport, Enable); end; function RtlxEnforceModuleAntiHooking; var UnhookableImport: TArray<TUnhookableImport>; begin // Find what we can unhook Result := RtlxFindUnhookableImport(Module, UnhookableImport); if not Result.IsSuccess then Exit; // Include only the specified names TArray.FilterInline<TUnhookableImport>(UnhookableImport, function (const Import: TUnhookableImport): Boolean begin Result := TArray.Contains<AnsiString>(Functions, Import.FunctionName); end ); // Adjust IAT targets if Length(UnhookableImport) > 0 then Result := RtlxEnforceAntiHooking(UnhookableImport, Enable) else begin Result.Location := 'RtlxEnforceModuleAntiHookingByName'; Result.Status := STATUS_ALREADY_COMPLETE; end; end; function RtlxEnforceGlobalAntiHooking; var Module: TModuleEntry; begin for Module in LdrxEnumerateModules do begin Result := RtlxEnforceModuleAntiHooking(Module, Functions, Enable); if not Result.IsSuccess then Exit; end; end; function RtlxApplyPatch( [in, out, WritesTo] Address: PPointer; [in] Value: Pointer; [out, opt] OldValue: PPointer = nil ): TNtxStatus; var ProtectionReverter: IAutoReleasable; Old: Pointer; begin // Make address writable Result := NtxProtectMemoryAuto(NtxCurrentProcess, Address, SizeOf(Pointer), PAGE_READWRITE, ProtectionReverter); if not Result.IsSuccess then Exit; try Old := AtomicExchange(Address^, Value); if Assigned(OldValue) then OldValue^ := Old; except Result.Location := 'RtlxApplyIATPatch'; Result.Status := STATUS_ACCESS_VIOLATION; end; end; function RtlxInstallIATHook; var Module: TModuleEntry; ModuleRef: IAutoPointer; Imports: TArray<TImportDllEntry>; Address: PPointer; OldTarget: Pointer; i, j: Integer; begin Result := LdrxLoadDllAuto(ModuleName, ModuleRef); if not Result.IsSuccess then Exit; Result := LdrxFindModule(Module, ContainingAddress(ModuleRef.Data)); if not Result.IsSuccess then Exit; Result := RtlxEnumerateImportImage(Imports, Module.Region, True, [itNormal, itDelayed], False); if not Result.IsSuccess then Exit; for i := 0 to High(Imports) do if RtlxEqualAnsiStrings(Imports[i].DllName, ImportModuleName) then begin for j := 0 to High(Imports[i].Functions) do if Imports[i].Functions[j].ImportByName and (Imports[i].Functions[j].Name = ImportFunction) then begin Pointer(Address) := PByte(Module.DllBase) + Imports[i].IAT + SizeOf(Pointer) * j; // Patch the IAT entry Result := RtlxApplyPatch(Address, Hook, @OldTarget); if not Result.IsSuccess then Exit; Reverter := Auto.Delay( procedure begin // Restore the original target RtlxApplyPatch(Address, OldTarget); // Capture the module lifetime and release after unpatching ModuleRef := nil; end ); if Assigned(OriginalTarget) then OriginalTarget^ := OldTarget; Exit; end; Break; end; Result.Location := 'RtlxSetHook'; Result.Status := STATUS_ENTRYPOINT_NOT_FOUND; end; end.
unit PipeClient; interface uses Windows, SysUtils, Classes; type TNamedPipeClientOnError = procedure (Sender: TObject; var ErrorCode: Integer) of object; TNamedPipeClient = class (TComponent) private FHandle : THandle; FPipeName : string; FActive : Boolean; FTimeOut : DWord; FOnOpen : TNotifyEvent; FOnClose : TNotifyEvent; FOnError : TNamedPipeClientOnError; procedure SetActive(const Value: Boolean); procedure SetPipeName(const Value: string); procedure PipeError(nErr: Integer); procedure SetTimeOut(const Value: DWord); protected public constructor Create(AOwner: TComponent);override; destructor Destroy();override; procedure Open(); procedure Close(); function ReadBuf(var Buf; const BufSize: Integer): Integer; function TryReadBuf(var Buf; const BufSize: Integer): Integer; function WriteBuf(const Buf; const BufSize: Integer): Integer; function GetAvaliableReadSize: Integer; property Handle: THandle read FHandle; published property PipeName: string read FPipeName write SetPipeName; property Active: Boolean read FActive write SetActive; property TimeOut: DWord read FTimeOut write SetTimeOut; property OnOpen : TNotifyEvent read FOnOpen write FOnOpen; property OnClose : TNotifyEvent read FOnClose write FOnClose; property OnError : TNamedPipeClientOnError read FOnError write FOnError; end; implementation { TNamedPipeClient } procedure TNamedPipeClient.Close; begin if FActive then begin FActive := False; if @FOnClose <> nil then FOnClose( Self ); CloseHandle( FHandle ); FHandle := INVALID_HANDLE_VALUE; end; end; constructor TNamedPipeClient.Create(AOwner: TComponent); begin inherited; FHandle := INVALID_HANDLE_VALUE; FPipeName := '\\.\pipe\default'; FTimeOut := NMPWAIT_WAIT_FOREVER; end; destructor TNamedPipeClient.Destroy; begin Close(); inherited; end; function TNamedPipeClient.GetAvaliableReadSize: Integer; begin if not FActive then Result := 0 else Result := GetFileSize( FHandle, nil ); end; procedure TNamedPipeClient.Open; var nErr: Integer; begin if FActive then Exit; while True do begin FHandle := CreateFile( PChar(FPipeName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0 ); if FHandle <> INVALID_HANDLE_VALUE then begin FActive := True; if @FOnOpen <> nil then FOnOpen( Self ); break; end; nErr := GetLastError(); if nErr <> ERROR_PIPE_BUSY then begin PipeError( nErr ); break; end; if not WaitNamedPipe( PChar(FPipeName), FTimeOut ) then begin PipeError( GetLastError() ); break; end; end; end; procedure TNamedPipeClient.PipeError(nErr: Integer); var S: string; begin if @FOnError <> nil then FOnError( Self, nErr ); case nErr of ERROR_SUCCESS: Exit; ERROR_FILE_NOT_FOUND: S := '管道“' + FPipeName + '”不存在。'; else S := '命名管道错误:' + IntToStr(nErr); end; Raise Exception.Create( S ) end; function TNamedPipeClient.ReadBuf(var Buf; const BufSize: Integer): Integer; var BytesReaded: DWord; nErr: Integer; begin Result := -1; if not ReadFile( FHandle, Buf, BufSize, BytesReaded, nil ) then begin nErr := GetLastError(); case nErr of ERROR_NO_DATA: Result := 0; else PipeError( nErr ); end; end else Result := BytesReaded; end; procedure TNamedPipeClient.SetActive(const Value: Boolean); begin if FActive <> Value then begin if Value then Open() else Close(); end; end; procedure TNamedPipeClient.SetPipeName(const Value: string); begin if FActive then Raise Exception.Create( '命名管道已被创建' ); FPipeName := Value; end; procedure TNamedPipeClient.SetTimeOut(const Value: DWord); begin if FActive then Raise Exception.Create( '不能在命名管道建立后修改超时时间' ); FTimeOut := Value; end; function TNamedPipeClient.TryReadBuf(var Buf; const BufSize: Integer): Integer; begin if GetFileSize( FHandle, nil ) > 0 then begin Result := ReadBuf( BUf, BufSize ); end else Result := 0; end; function TNamedPipeClient.WriteBuf(const Buf; const BufSize: Integer): Integer; var BytesWriten: DWord; nErr: Integer; begin Result := -1; if not WriteFile( FHandle, Buf, BufSize, BytesWriten, nil ) then begin nErr := GetLastError(); PipeError( nErr ); end else Result := BytesWriten; end; end.
unit Main; interface //#################################################################### ■ uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Math.Vectors, FMX.Types3D, FMX.Viewport3D, FMX.Controls3D, FMX.Objects3D, FMX.MaterialSources, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.TabControl, LUX, LUX.FMX, LIB.Asset; type TForm1 = class(TForm) TabControl1: TTabControl; TabItemV: TTabItem; Viewport3D1: TViewport3D; Dummy1: TDummy; Dummy2: TDummy; Camera1: TCamera; Light1: TLight; Grid3D1: TGrid3D; Sphere1: TSphere; TextureMaterialSource1: TTextureMaterialSource; TabItemS: TTabItem; TabControlS: TTabControl; TabItemSV: TTabItem; TabControlSV: TTabControl; TabItemSVC: TTabItem; MemoSVC: TMemo; TabItemSVE: TTabItem; MemoSVE: TMemo; TabItemSP: TTabItem; TabControlSP: TTabControl; TabItemSPC: TTabItem; MemoSPC: TMemo; TabItemSPE: TTabItem; MemoSPE: TMemo; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure Viewport3D1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure Viewport3D1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); procedure Viewport3D1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure Timer1Timer(Sender: TObject); private { private 宣言 } _MouseS :TShiftState; _MouseP :TPointF; public { public 宣言 } _MyAsset :TMyAsset; _Tensors :TTensorShape; end; var Form1: TForm1; implementation //############################################################### ■ {$R *.fmx} //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& procedure TForm1.FormCreate(Sender: TObject); var T :String; begin _MouseS := []; TextureMaterialSource1.Texture.LoadFromFile( '..\..\_DATA\EnviImage.png' ); _MyAsset := TMyAsset.Create( Self ); MemoSVC.Lines.LoadFromFile( '..\..\_DATA\ShaderV.hlsl' ); MemoSPC.Lines.LoadFromFile( '..\..\_DATA\ShaderP.hlsl' ); with _MyAsset do begin Parent := Viewport3D1; with Material do begin EmisLight := TAlphaColorF.Create( 0, 0, 0 ); AmbiLight := TAlphaColorF.Create( 0.1, 0.1, 0.1 ); DiffRatio := TAlphaColorF.Create( 1, 1, 1 ); SpecRatio := TAlphaColorF.Create( 1, 1, 1 ); SpecShiny := 30; TranRatio := TAlphaColorF.Create( 1, 1, 1 ); RefrIndex := TAlphaColorF.Create( 2.4, 2.3, 2.2 ); DiffImage.LoadFromFile( '..\..\_DATA\DiffImage.png' ); NormImage.LoadFromFile( '..\..\_DATA\NormImage.png' ); EnviImage.LoadFromFile( '..\..\_DATA\EnviImage.png' ); with ShaderV do begin Source.Text := MemoSVC.Text; for T in Errors.Keys do begin with MemoSVE.Lines do begin Add( '▼ ' + T ); Add( Errors[ T ] ); end; end; end; with ShaderP do begin Source.Text := MemoSPC.Text; for T in Errors.Keys do begin with MemoSPE.Lines do begin Add( '▼ ' + T ); Add( Errors[ T ] ); end; end; end; end; end; _Tensors := TTensorShape.Create( Self ); with _Tensors do begin Parent := _MyAsset; MeshData := _MyAsset.Geometry; Visible := False; {テンソルを非表示} end; end; //////////////////////////////////////////////////////////////////////////////// procedure TForm1.Viewport3D1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin _MouseS := Shift; _MouseP := TPointF.Create( X, Y ); end; procedure TForm1.Viewport3D1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); var P :TPointF; begin if ssLeft in _MouseS then begin P := TPointF.Create( X, Y ); with Dummy1.RotationAngle do Y := Y + ( P.X - _MouseP.X ) / 2; with Dummy2.RotationAngle do X := X - ( P.Y - _MouseP.Y ) / 2; _MouseP := P; end; end; procedure TForm1.Viewport3D1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin Viewport3D1MouseMove( Sender, Shift, X, Y ); _MouseS := []; end; //////////////////////////////////////////////////////////////////////////////// procedure TForm1.Timer1Timer(Sender: TObject); begin with _MyAsset.RotationAngle do Y := Y + 0.5; end; end. //######################################################################### ■
// CSV Import stuff // // Started: December 20th 2007 // Last Modified: May 11th 2019 // // 287 unit X.Form.CSVProcess; interface uses System.UITypes, Windows, Messages, System.SysUtils, System.Variants, Classes, Graphics, Controls, Forms, ExtCtrls, StdCtrls, Buttons, X.Help, X.Utility, X.CCSVDataFormat, X.LanguageHandler, X.SystemGlobal; type TfrmCSVProcess = class(TForm) bImport: TBitBtn; bCancel: TBitBtn; Bevel1: TBevel; bHelp: TBitBtn; cbIFR: TCheckBox; GroupBox1: TGroupBox; lContents1: TLabel; lContents2: TLabel; lContents3: TLabel; lContents4: TLabel; lContents5: TLabel; lContents6: TLabel; lContents7: TLabel; cbType1: TComboBox; cbType2: TComboBox; cbType3: TComboBox; cbType4: TComboBox; cbType5: TComboBox; cbType6: TComboBox; cbType7: TComboBox; GroupBox2: TGroupBox; lFilename: TLabel; Label3: TLabel; cbType8: TComboBox; lContents8: TLabel; cbType9: TComboBox; lContents9: TLabel; cbType15: TComboBox; cbType13: TComboBox; cbType12: TComboBox; cbType11: TComboBox; cbType14: TComboBox; cbType10: TComboBox; lContents15: TLabel; lContents14: TLabel; lContents13: TLabel; lContents12: TLabel; lContents11: TLabel; lContents10: TLabel; BitBtn1: TBitBtn; Label1: TLabel; Label2: TLabel; cbType19: TComboBox; lContents19: TLabel; lContents18: TLabel; lContents17: TLabel; lContents16: TLabel; cbType16: TComboBox; cbType17: TComboBox; cbType18: TComboBox; cbType20: TComboBox; lContents20: TLabel; procedure ProcessFile(const fn : string); procedure bHelpClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure cbType1Change(Sender: TObject); procedure FormCreate(Sender: TObject); private FFieldCount : integer; function GetFieldCount(aRow : string): integer; public { Public declarations } end; var frmCSVProcess: TfrmCSVProcess; function GetCSVDataFormat(const filename : string): TCSVDataFormat; implementation {$R *.dfm} uses X.Global, X.Constants, X.Dialogs.Dialog; var LabelList : array[0..MaxCSVFields] of TLabel; ComboList : array[0..MaxCSVFields] of TComboBox; function GetCSVDataFormat(const filename : string): TCSVDataFormat; var t : integer; begin with TfrmCSVProcess.Create(Application) do try LabelList[0] := lContents1; LabelList[1] := lContents2; LabelList[2] := lContents3; LabelList[3] := lContents4; LabelList[4] := lContents5; LabelList[5] := lContents6; LabelList[6] := lContents7; LabelList[7] := lContents8; LabelList[8] := lContents9; LabelList[9] := lContents10; LabelList[10] := lContents11; LabelList[11] := lContents12; LabelList[12] := lContents13; LabelList[13] := lContents14; LabelList[14] := lContents15; LabelList[15] := lContents16; LabelList[16] := lContents17; LabelList[17] := lContents18; LabelList[18] := lContents19; LabelList[19] := lContents20; ComboList[0] := cbType1; ComboList[1] := cbType2; ComboList[2] := cbType3; ComboList[3] := cbType4; ComboList[4] := cbType5; ComboList[5] := cbType6; ComboList[6] := cbType7; ComboList[7] := cbType8; ComboList[8] := cbType9; ComboList[9] := cbType10; ComboList[10] := cbType11; ComboList[11] := cbType12; ComboList[12] := cbType13; ComboList[13] := cbType14; ComboList[14] := cbType15; ComboList[15] := cbType16; ComboList[16] := cbType17; ComboList[17] := cbType18; ComboList[18] := cbType19; ComboList[19] := cbType20; lFilename.Caption := filename; lFilename.Hint := filename; ShowModal; if ModalResult = mrOK then begin for t := 0 to MaxCSVFields do Result.Fields[t] := ComboList[t].ItemIndex; Result.IgnoreFirstRecord := cbIFR.Checked; end else begin for t := 0 to MaxCSVFields do Result.Fields[t] := -1; end; finally free; end; end; procedure TfrmCSVProcess.FormCreate(Sender: TObject); begin Caption := XText[rsImportCSVData]; end; procedure TfrmCSVProcess.FormShow(Sender: TObject); var x, t : integer; begin Label1.Caption := XText[rsFieldDataType]; Label2.Caption := XText[rsContentsFirstRecord]; Label3.Caption := XText[rsFilename]; for x := 0 to MaxCSVFields do begin ComboList[x].Items.Add(XText[rsIgnore]); ComboList[x].Items.Add(XText[rsFullFilePath]); ComboList[x].Items.Add(XText[rsFileSizeBytes]); ComboList[x].Items.Add(XText[rsFileSizeOnDisk]); ComboList[x].Items.Add(XText[rsCreatedDateDDMMYYYY]); ComboList[x].Items.Add(XText[rsCreatedDateMMDDYYYY]); ComboList[x].Items.Add(XText[rsModifiedDateDDMMYYYY]); ComboList[x].Items.Add(XText[rsModifiedDateMMDDYYYY]); ComboList[x].Items.Add(XText[rsAccessedDateDDMMYYYY]); ComboList[x].Items.Add(XText[rsAccessedDateMMDDYYYY]); ComboList[x].Items.Add(XText[rsFilePath]); ComboList[x].Items.Add(XText[rsFileName]); ComboList[x].Items.Add(XText[rsOwner]); ComboList[x].Items.Add(XText[rsCategory]); ComboList[x].Items.Add(XText[rsReadOnly]); ComboList[x].Items.Add(XText[rsHidden]); ComboList[x].Items.Add(XText[rsSystem]); ComboList[x].Items.Add(XText[rsArchive]); ComboList[x].Items.Add(XText[rsTemporary]); ComboList[x].Items.Add(XText[rsFileAttributes]); ComboList[x].Items.Add(XText[rsCreated] + ' ' + XText[rsTime] + ' (HHMM)'); ComboList[x].Items.Add(XText[rsAccessed] + ' ' + XText[rsTime] + ' (HHMM)'); ComboList[x].Items.Add(XText[rsModified] + ' ' + XText[rsTime] + ' (HHMM)'); end; cbIFR.Caption := XText[rsIgnoreFirstRecord]; bHelp.Caption := XText[rsHelp]; bImport.Caption := XText[rsImport]; bCancel.Caption := XText[rsCancel]; for t := 0 to MaxCSVFields do begin LabelList[t].Caption := ''; LabelList[t].Visible := False; ComboList[t].ItemIndex := 0; end; ProcessFile(lFilename.Caption); end; procedure TfrmCSVProcess.ProcessFile(const fn : string); var tf : TextFile; s,r : string; t,i : integer; inquotes, processthisfield : boolean; begin AssignFile(tf, fn); {$I-} Reset(tf); if IOResult <> 0 then begin ShowXDialog(XText[rsWarning], XText[rsErrorOpening] + ' "' + fn + '".', XDialogTypeWarning); end else begin repeat Readln(tf, s); until (Pos(',', s) <> 0) or (eof(tf)); CloseFile(tf); end; {$I+} if Pos(',', s) <> 0 then begin FFieldCount := GetFieldCount(s); r := ''; i := 0; inquotes := False; processthisfield := False; for t := 1 to length(s) do begin case s[t] of '"' : begin if inquotes then begin case s[t + 1] of ',' : inquotes := False; else r := r + s[t]; end; end else inquotes := not(inquotes); end; ',' : begin if not(inquotes) then processthisfield := True; end; else r := r + s[t]; end; if processthisfield then begin if i <= MaxCSVFields then begin LabelList[i].Caption := r; LabelList[i].Visible := True; ComboList[i].Visible := True; end; processthisfield := False; r := ''; inc(i); end; end; if i <= MaxCSVFields then begin LabelList[i].Caption := r; LabelList[i].Visible := True; ComboList[i].Visible := True; end; end else ShowXDialog(XText[rsWarning], XText[rsBadCSVFile], XDialogTypeWarning); end; procedure TfrmCSVProcess.bHelpClick(Sender: TObject); begin THelp.OpenHelpPage('w21.htm'); end; procedure TfrmCSVProcess.BitBtn1Click(Sender: TObject); begin cbType1.ItemIndex := CFieldFileName; cbType2.ItemIndex := CFieldFullFilePath; cbType3.ItemIndex := CFieldIgnore; cbType4.ItemIndex := CFieldFileSizeBytes; cbType5.ItemIndex := CFieldFileSizeOnDIsk; cbType6.ItemIndex := CFieldCreatedDDMMYYYY; cbType7.ItemIndex := CFieldModifiedDDMMYYYY; cbType8.ItemIndex := CFieldAccessedDDMMYYYY; cbType9.ItemIndex := CFieldCreatedTimeHHMMSS; cbType10.ItemIndex := CFieldModifiedTimeHHMMSS; cbType11.ItemIndex := CFieldAccessedTimeHHMMSS; cbType12.ItemIndex := CFieldIgnore; cbType13.ItemIndex := CFieldCategory; cbType14.ItemIndex := CFieldOwner; cbType15.ItemIndex := CFieldReadOnly; cbType16.ItemIndex := CFieldHidden; cbType17.ItemIndex := CFieldSystem; cbType18.ItemIndex := CFieldArchive; cbType19.ItemIndex := CFieldTemp; if FFieldCount = 20 then begin cbType20.ItemIndex := CFieldAttributes; end else begin cbType20.ItemIndex := CFieldIgnore; end; cbType1Change(cbType2); cbType1Change(cbType3); cbType1Change(cbType9); end; procedure TfrmCSVProcess.cbType1Change(Sender: TObject); function IsNumber(s : string): boolean; var t : integer; begin Result := True; for t := 1to length(s) do if (ord(s[t]) < 48) or (ord(s[t]) > 57) then Result := False; end; begin case TComboBox(Sender).ItemIndex of 2 : if not(IsNumber(LabelList[TComboBox(Sender).ItemIndex].Caption)) then cbIFR.Checked := True; 3 : if not(IsNumber(LabelList[TComboBox(Sender).ItemIndex].Caption)) then cbIFR.Checked := True; 13 : if not(IsNumber(LabelList[TComboBox(Sender).ItemIndex].Caption)) then cbIFR.Checked := True; end; end; function TfrmCSVProcess.GetFieldCount(aRow : string): integer; var t : integer; count : integer; inString : boolean; begin count := 1; inString := False; for t := 1 to length(aRow) do begin if aRow[t] = '"' then begin if inString then inString := False else inString := True; end else if aRow[t] = ',' then begin if not(inString) then inc(count); end; end; Result := count; end; end.
unit TradesClass; interface uses IdHashMessageDigest, Classes, Generics.Collections; type TBaseTrade = class private FParam : TStringlist; Fapp_secret: string; procedure SetSign(); function GetMD5(Str: string): string; procedure Setapp_secret(const Value: string); function getURL: string; procedure SetNick(const Value: string); procedure SetMethod(const Value: string); procedure SetApp_key(const Value: string); procedure SetFields(const Value: string); procedure SetSession(const Value: string); protected procedure AddParam(Name, Value : string); public constructor Create(); virtual; destructor Destroy(); override; property app_secret : string read Fapp_secret write Setapp_secret; property URL : string read getURL; property Nick : string write SetNick; property Method : string write SetMethod; property App_key : string write SetApp_key; property Session : string write SetSession; end; /// <summary> /// 获取单个用户信息 /// </summary> TUser = Class(TBaseTrade) private property Method : string write SetMethod; public constructor Create(); override; End; /// <summary> /// 获取店铺信息 /// </summary> TShop = Class(TBaseTrade) private property Method : string write SetMethod; public constructor Create(); override; End; /// <summary> /// 交易订单帐务查询 /// </summary> TAmount = Class(TBaseTrade) private procedure Settid(const Value: string); property Method : string write SetMethod; public constructor Create(); override; property tid : string write Settid; End; /// <summary> /// 获取产品列表 /// </summary> TProductcats = Class(TBaseTrade) private procedure SetPage_no(const Value: string); property Method : string write SetMethod; public constructor Create(); override; property Page_no : string write SetPage_no; End; /// <summary> /// 获取单个产品 /// </summary> TProductcat = Class(TBaseTrade) private procedure Setproduct_id(const Value: string); published public constructor Create(); override; property product_id : string write Setproduct_id; End; /// <summary> /// 淘宝系统时间 /// </summary> TServerTime = Class(TBaseTrade) public constructor Create(); override; end; /// <summary> /// 物流查询 /// </summary> TAreasGet = Class(TBaseTrade) public constructor Create(); override; end; implementation uses SysUtils, HTTPApp; { TBaseTrade } procedure TBaseTrade.AddParam(Name, Value: string); begin if FParam.IndexOfName(LowerCase(Name))<0 then FParam.Add(LowerCase(Name) +'=' + Value) else FParam.Values[LowerCase(Name)] := Value; end; constructor TBaseTrade.Create; begin FParam := TStringList.Create; AddParam('Timestamp', FormatDateTime('yyyy-mm-dd hh:nn:ss', now)); AddParam('v','2.0'); AddParam('format','xml'); AddParam('sign_method','md5'); end; destructor TBaseTrade.Destroy; begin FParam.Free; inherited; end; function TBaseTrade.GetMD5(Str: string): string; var md5: TIdHashMessageDigest5; begin md5 := TIdHashMessageDigest5.Create; try Result := LowerCase(md5.HashStringAsHex(Str, TEncoding.UTF8)); // 设置编码汉字才能正确 finally FreeAndNil(md5); end; end; function TBaseTrade.getURL: string; var I: Integer; begin SetSign(); Result := ''; for I := 0 to FParam.Count - 1 do Result := Result + '&' + FParam.Names[i] + '=' + HTTPEncode(UTF8Encode(FParam.ValueFromIndex[i])); Result := 'http://gw.api.taobao.com/router/rest?' + copy(Result , 2, length(Result)-1); end; procedure TBaseTrade.SetApp_key(const Value: string); begin AddParam('app_key', Value); end; procedure TBaseTrade.Setapp_secret(const Value: string); begin Fapp_secret := Value; end; procedure TBaseTrade.SetFields(const Value: string); begin AddParam('fields', Value); end; procedure TBaseTrade.SetMethod(const Value: string); begin AddParam('method', Value); end; procedure TBaseTrade.SetNick(const Value: string); begin AddParam('nick', Value); end; procedure TBaseTrade.SetSession(const Value: string); begin AddParam('session', Value); end; procedure TBaseTrade.SetSign; var i: Integer; SignStr : string; begin FParam.Sort; SignStr := ''; for i :=0 to FParam.Count -1 do SignStr := SignStr + FParam.Names[i] + FParam.ValueFromIndex[i]; SignStr := Fapp_secret + SignStr + Fapp_secret; SignStr := UpperCase(GetMD5(SignStr)); AddParam('sign', SignStr); end; { TAmount } constructor TAmount.Create; begin inherited; AddParam('fields', 'tid,oid,alipay_no,total_fee,post_fee'); AddParam('method', 'taobao.trade.amount.get'); end; procedure TAmount.Settid(const Value: string); begin AddParam('tid', Value); end; { TProductcats } constructor TProductcats.Create; begin inherited; AddParam('method', 'taobao.products.get'); AddParam('fields', 'product_id,tsc,name'); end; procedure TProductcats.SetPage_no(const Value: string); begin AddParam('page_no', Value); end; { TUser } constructor TUser.Create; begin inherited; AddParam('method', 'taobao.user.get'); AddParam('fields', 'user_id,nick,seller_credit,buyer_credit'); end; { TProductcat } constructor TProductcat.Create; begin inherited; AddParam('method', 'taobao.product.get'); AddParam('fields', 'name,product_id'); end; procedure TProductcat.Setproduct_id(const Value: string); begin AddParam('product_id', Value); end; { TServerTime } constructor TServerTime.Create; begin inherited; AddParam('method', 'taobao.time.get'); end; { TShop } constructor TShop.Create; begin inherited; AddParam('method', 'taobao.shop.get'); AddParam('fields', 'sid,cid,title,nick,desc,bulletin,pic_path,created,modified'); end; { TAreasGet } constructor TAreasGet.Create; begin inherited; AddParam('method', 'taobao.areas.get'); AddParam('fields', 'id,type,name'); end; end.
unit Lua.GlobalVariable; interface uses LuaLib, Lua.Types; type TLuaGlobalVariable = class(TInterfacedObject, ILuaExtension) protected FName: string; FType: ( TypeNil, TypeBoolean, TypeInteger, TypeDouble, TypeString, TypeData ); FBoolean: Boolean; FInteger: Integer; FDouble: Double; FString: RawByteString; FData: Pointer; FDataSize: Integer; protected // ILuaExtension function ShouldBeSaved: LongBool; stdcall; procedure Register(const AHandle: TLuaState); stdcall; public constructor Create(const AName: string); overload; virtual; constructor Create(const AName: string; const Value: Boolean); overload; virtual; constructor Create(const AName: string; const Value: Integer); overload; virtual; constructor Create(const AName: string; const Value: Double); overload; virtual; constructor Create(const AName: string; const Value: RawByteString); overload; virtual; constructor Create(const AName: string; const Data: Pointer; const DataSize: Integer); overload; virtual; end; implementation { TLuaGlobalVariable } constructor TLuaGlobalVariable.Create(const AName: string; const Value: Integer); begin FName := AName; FType := TypeInteger; FInteger := Value; end; constructor TLuaGlobalVariable.Create(const AName: string; const Value: Boolean); begin FName := AName; FType := TypeBoolean; FBoolean := Value; end; constructor TLuaGlobalVariable.Create(const AName: string; const Value: Double); begin FName := AName; FType := TypeDouble; FDouble := Value; end; constructor TLuaGlobalVariable.Create(const AName: string; const Data: Pointer; const DataSize: Integer); begin FName := AName; FType := TypeData; FData := Data; FDataSize := DataSize; if FDataSize < 0 then FDataSize := 0; end; constructor TLuaGlobalVariable.Create(const AName: string); begin FName := AName; FType := TypeNil; end; constructor TLuaGlobalVariable.Create(const AName: string; const Value: RawByteString); begin FName := AName; FType := TypeString; FString := Value; end; procedure TLuaGlobalVariable.Register(const AHandle: TLuaState); begin if Assigned(AHandle) and (FName <> '') then begin case FType of TypeNil: lua_pushnil(AHandle); TypeBoolean: lua_pushboolean(AHandle, FBoolean); TypeInteger: lua_pushinteger(AHandle, FInteger); TypeDouble: lua_pushnumber(AHandle, FDouble); TypeString: lua_pushlstring(AHandle, PAnsiChar(FString), Length(FString)); TypeData: begin if Assigned(FData) then lua_pushlstring(AHandle, PAnsiChar(FData), FDataSize) else lua_pushnil(AHandle); end; end; lua_setglobal(AHandle, PAnsiChar(AnsiString(FName))); end; end; function TLuaGlobalVariable.ShouldBeSaved: LongBool; begin Result := false; end; end.
unit UFL_PC_ReceitaBrutaMensal; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFBasicoLista, cxStyles, DB, ADODB, Menus, ImgList, cxPropertiesStore, ActnList, ComCtrls, ToolWin, cxControls, cxGrid, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridCustomView, cxClasses, cxGridLevel, Funcoes; type TFLReceitaBrutaMensal = class(TFBasicoLista) ADODataSetcodigo: TAutoIncField; ADODataSetRBNaoCumulativaTributada: TFloatField; ADODataSetRBNaoCumulativaNaoTributada: TFloatField; ADODataSetRBNaoCumulativaExportacao: TFloatField; ADODataSetRBCumulativa: TFloatField; ADODataSetRBTotal: TFloatField; ADODataSetcodigoParametroContribuicaoSocial: TIntegerField; cxGridLevel1: TcxGridLevel; cxGridDBTableView1: TcxGridDBTableView; cxGridDBTableView1codigo: TcxGridDBColumn; cxGridDBTableView1RBNaoCumulativaTributada: TcxGridDBColumn; cxGridDBTableView1RBNaoCumulativaNaoTributada: TcxGridDBColumn; cxGridDBTableView1RBNaoCumulativaExportacao: TcxGridDBColumn; cxGridDBTableView1RBCumulativa: TcxGridDBColumn; cxGridDBTableView1RBTotal: TcxGridDBColumn; private codigoRegimeApuracao : Integer; procedure configuraGrid; { Private declarations } public constructor create(AOwner: TComponent; codigoRegimeApuracao: Integer); { Public declarations } end; implementation {$R *.dfm} { TFLReceitaBrutaMensal } procedure TFLReceitaBrutaMensal.configuraGrid; var funcoes : TFuncoes; begin funcoes := TFuncoes.Create; cxGridDBTableView1 := funcoes.configuraPropriedadesDaGrid(cxGridDBTableView1); funcoes.Free; end; constructor TFLReceitaBrutaMensal.create(AOwner: TComponent; codigoRegimeApuracao: Integer); begin Self.codigoRegimeApuracao := codigoRegimeApuracao; inherited create(AOwner, ' WHERE codigoParametroContribuicaoSocial = ' + IntToStr(Self.codigoRegimeApuracao)); configuraGrid; end; end.
Program Rectangle; { Variables declaration } Var base, height :real; { Functions } Function fncArea(base, height :real) :real; Begin fncArea := base * height; End; Begin { Get the rectangle base and height by user } writeln('Enter the rectangle base:'); readln(base); writeln('Enter the rectangle height:'); readln(height); { Show the rectangle area to user } writeln('The rectangle area is ', fncArea(base, height):4:2); End.
unit cosmos.secretarias.view.FormEditarParticipantesTiposAti; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FrameDeleteButtons, cosmos.frames.fkSearch, cosmos.frames.gridsearch, StdCtrls, Mask, DBCtrls, ExtCtrls, GroupHeader, DB, DBClient, cosmos.classes.ServerInterface, Cosmos.Framework.Interfaces.DataAcess, cosmos.framework.interfaces.root, cosmos.system.messages, Datasnap.DSConnect, cosmos.classes.security; type TFrmEditarParticipantesTiposAti = class(TForm) MSGroupHeader1: TMSGroupHeader; Label2: TLabel; Label3: TLabel; DBEdit1: TDBEdit; DBEdit2: TDBEdit; MSGroupHeader2: TMSGroupHeader; FmeGridSearch1: TFmeGridSearch; FmeFKDiscipulados: TFmeFKSearch; FmeDBDelButtons1: TFmeDBDelButtons; CdsTiposAtividades: TClientDataSet; CdsParticipantes: TClientDataSet; DsrTiposAtividades: TDataSource; procedure CdsParticipantesAfterInsert(DataSet: TDataSet); procedure CdsParticipantesBeforePost(DataSet: TDataSet); procedure CdsParticipantesBeforeDelete(DataSet: TDataSet); procedure CdsParticipantesAfterPost(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CdsParticipantesReconcileError(DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); procedure CdsParticipantesAfterOpen(DataSet: TDataSet); private { Private declarations } FICosmosApp: ICosmosApplication; FRemoteConnection: TDSProviderConnection; public { Public declarations } procedure EditarParticipantes(const codtipati: integer); property ICosmosApp: ICosmosApplication read FICosmosApp; end; var FrmEditarParticipantesTiposAti: TFrmEditarParticipantesTiposAti; implementation {$R *.dfm} procedure TFrmEditarParticipantesTiposAti.CdsParticipantesAfterInsert( DataSet: TDataSet); begin Dataset.Fields.FieldByName('codtipati').Value := CdsParticipantes.Params.Items[0].Value; end; procedure TFrmEditarParticipantesTiposAti.CdsParticipantesAfterOpen( DataSet: TDataSet); begin TClientDataset(Dataset).ReadOnly := ICosmosApp.IRemoteCon.CurrentConnectionMode = cmRead; end; procedure TFrmEditarParticipantesTiposAti.CdsParticipantesAfterPost( DataSet: TDataSet); begin if TClientDataset(Dataset).ChangeCount > 0 then TClientDataset(Dataset).ApplyUpdates(0); end; procedure TFrmEditarParticipantesTiposAti.CdsParticipantesBeforeDelete( DataSet: TDataSet); begin if ICosmosApp.DlgMessage.ConfirmationMessage(TCosmosTitles.AgendaAtividades, TCosmosConfMsg.DelParticipante) = mrNo then Abort; end; procedure TFrmEditarParticipantesTiposAti.CdsParticipantesBeforePost( DataSet: TDataSet); var SequenceName: string; begin if Dataset.State = dsInsert then begin SequenceName := TClientDataset(DataSet).GetOptionalParam('SequenceName'); Dataset.Fields.Fields[0].Value := ICosmosApp.IRemoteCon.GetSequenceValue(SequenceName); if Dataset.Fields.Fields[0].Value = unassigned then Dataset.Cancel; end; end; procedure TFrmEditarParticipantesTiposAti.CdsParticipantesReconcileError( DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); begin Action := ICosmosApp.IRemoteCon.ReconcileError(E, UpdateKind); end; procedure TFrmEditarParticipantesTiposAti.EditarParticipantes( const codtipati: integer); begin CdsTiposAtividades.Params.Items[0].Value := codtipati; CdsTiposAtividades.Open; CdsParticipantes.Params.Items[0].Value := codtipati; CdsParticipantes.Open; ShowModal; end; procedure TFrmEditarParticipantesTiposAti.FormClose(Sender: TObject; var Action: TCloseAction); begin if CdsTiposAtividades.Active then CdsTiposAtividades.Close; CdsTiposAtividades.RemoteServer := nil; if CdsParticipantes.Active then CdsParticipantes.Close; CdsParticipantes.RemoteServer := nil; if Assigned(FRemoteConnection) then ICosmosApp.IRemoteCon.DropConnection(FRemoteConnection); end; procedure TFrmEditarParticipantesTiposAti.FormCreate(Sender: TObject); begin FICosmosApp := Application.MainForm as ICosmosApplication; FRemoteConnection := ICosmosApp.IRemoteCon.CreateConnection(scAtividades); CdsTiposAtividades.RemoteServer := FRemoteConnection; CdsParticipantes.RemoteServer := FRemoteConnection; FmeFKDiscipulados.Configure('coddis', csDiscipulados); end; end.
(*Considere a soma S dos termo da série infinita apresentada abaixo, a qual é responsável pelo cálculo do valor do co-seno de 1 (um) radiano: S = 1 - 1/2! + 1/4! - 1/6! + 1/8! - 1/10! + 1/12! - ... Fazer um programa em linguagem Pascal que seja capaz de calcular o valor aproximado da soma (S) dos termos da série até o momento em que a diferença das normas (módulo) de 2 termos consecutivos for menor que 0,000001 (i.e., norma da diferença das normas de dois termos consecutivos).*) program cosseno; function fatorial (n : integer) : extended; var fat, i : integer; begin fat := 1; for i := 1 to n do fat := fat * i; fatorial := 1 / fat; end; var fato, anterior, soma: extended; num, i, contador, repetir : integer; begin contador := 0; soma := 1; num := 2; fato := 1; anterior := 0.25; repetir := 1; while (repetir = 1) do begin fato := fatorial(num); writeln; writeln('Fatorial de 1/',num,' : ',fato:0:15); writeln ('Diferenca : ',fato - anterior:0:6); writeln ('Contador : ',contador); writeln; if abs(fato - anterior) > 0.000001 then begin if odd(contador) then soma := soma + fato else soma := soma - fato; end else break; anterior := fato; contador := contador + 1; num := num + 2; end; // end while writeln(soma:0:15); end. // end
unit MiscTests4; interface uses {$IF (CompilerVersion >= 23)} // Delphi XE2 or newer System.Classes, {$ELSE} Classes, {$ENDIF} TestFramework, Windows, ZMStructs, Controls, ZipMstr, Dialogs, SysUtils, Graphics, ZMXcpt, ZMTest; type // Test methods for class TZipMaster_A TTestZipComment = class(TValidatedTestCase1) private FTestStream: TStream; public procedure SetUp; override; procedure TearDown; override; published procedure ReadComment; procedure SetComment; procedure SetCommentDelayed; procedure SetCommentStream; procedure SetComment_Multi; procedure SetNameCommentDelayed; end; type TTestToSFX = class(TZMTestCase) public procedure SetUp; override; procedure TearDown; override; published procedure SingleToExistingSFX; procedure SingleToSFX; end; type TTestToZip = class(TZMTestCase) public procedure SetUp; override; procedure TearDown; override; published procedure SFXToExistingBadSingle; procedure SFXToExistingSingle; procedure SFXToSingle; end; type TTestReadSpan = class(TZMTestCase) public procedure SetUp; override; procedure TearDown; override; published procedure ToExistingBadSingle; procedure ToExistingSingle; procedure ToSingle; end; implementation uses ZMUtils, ZMMsg, ZMEngine, ZMTestUtils, ZMTimeUtils; procedure TTestZipComment.ReadComment; var ReturnValue: Integer; begin Dest := 'zldzip.zip'; SetZipFile(FZip, dest, 'Tst_Cmnt.zip'); FZip.ZipFileName := dest; ReturnValue := FZip.ErrCode; CheckEquals(0, ReturnValue, 'error loading zip'); CheckEquals('zip with comment', String(FZip.ZipComment), 'bad comment'); Validate1(ReturnValue, GetName); end; procedure TTestZipComment.SetComment; var ReturnValue: Integer; begin Dest := 'zldzip.zip'; SetZipFile(FZip, dest, 'Tst_Cpy_1.zip'); FZip.ZipFileName := dest; ReturnValue := FZip.ErrCode; CheckEquals(0, ReturnValue, 'error loading zip'); FZip.ZipComment := 'test comment'; Validate1(ReturnValue, GetName); end; procedure TTestZipComment.SetCommentDelayed; var ReturnValue: Integer; begin Dest := 'zldzip.zip'; SetZipFile(FZip, dest, 'Tst_Cpy_1.zip'); FZip.ZipFileName := dest; ReturnValue := FZip.ErrCode; CheckEquals(0, ReturnValue, 'error loading zip'); FZip.Active := False; FZip.ZipComment := 'test comment'; FZip.Active := True; ReturnValue := FZip.ErrCode; Validate1(ReturnValue, GetName); end; procedure TTestZipComment.SetCommentStream; var ReturnValue: Integer; dst: string; begin Dest := 'zldzip.zip'; dst := PrepareDestFile(FZip, dest, 'Tst_Cpy_1.zip'); FTestStream := TFileStream.Create(dst, fmOpenReadWrite); FZip.ExtStream := FTestStream; ReturnValue := FZip.ErrCode; CheckEquals(0, ReturnValue, 'error loading zip from stream'); FZip.ZipComment := 'test comment'; Validate1(ReturnValue, GetName); end; procedure TTestZipComment.SetComment_Multi; var ReturnValue: Integer; begin Dest := 'Split1001.zip'; FZip.CopyFiles('split1001.zip| split1002.zip | split1003.zip|split1004.zip|' + 'split1005.zip|split1006.zip|split1007.zip|split1008.zip'); FZip.ZipFileName := dest; FZip.MaxVolumeSizeKb := 100; ReturnValue := FZip.ErrCode; CheckEquals(0, ReturnValue, 'error loading zip'); FZip.ZipComment := 'test comment'; CheckEquals(0, FZip.ErrCode, FZip.ErrMessage); // Validate1(ReturnValue, GetName); FZip.Clear; FZip.ZipFileName := dest; CheckEquals(0, ReturnValue, 'error loading zip: '+ FZip.ErrMessage); CheckEquals('test comment', String(FZip.ZipComment), 'zip comment wrong'); end; procedure TTestZipComment.SetNameCommentDelayed; var ReturnValue: Integer; begin Dest := 'zldzip.zip'; SetZipFile(FZip, dest, 'Tst_Cpy_1.zip'); FZip.Active := False; FZip.ZipFileName := dest; FZip.ZipComment := 'test comment'; FZip.Active := True; ReturnValue := FZip.ErrCode; Validate1(ReturnValue, GetName); end; procedure TTestZipComment.SetUp; begin inherited; SetupFZip; FTestStream := nil; end; procedure TTestZipComment.TearDown; begin FZip.Free; FZip := nil; if FTestStream <> nil then FTestStream.Free; inherited; end; procedure TTestToSFX.SetUp; begin inherited; KillFiles(TestDir); ForceDirectories(TestDir + 'Tmp\'); FZip.UseDirOnlyEntries := True; end; procedure TTestToSFX.SingleToExistingSFX; var BeforeMD5: string; dst: string; begin Dest := 'AZip.zip'; dst := Dest; SetZipFile(FZip, dest, 'AZip.zip'); FZip.CopyFiles('AZip.exe=Tst_SFX.exe'); FZip.CopyFiles('AZip.exe'); BeforeMD5 := FileMD5(Dest); FZip.ZipFileName := dest; FZip.WriteOptions := [{zwoDiskSpan,} zwoZipTime]; // FZip.MaxVolumeSizeKb := 1000; {ReturnValue :=} FZip.ConvertToSFX;//(TestDir + 'AZip.exe'); CheckEquals(0, FZip.ErrCode, 'Error converting to SFX: ' + FZip.ErrMessage); FZip.ZipFileName := ChangeFileExt(Dest, '.exe'); CheckEntryExists('Special\Data.txt'); CheckEquals(3, FZip.Count, 'Not correct resulting to SFX'); CheckEqualsString(BeforeMD5, FileMD5(Dest), 'Original file changed'); end; procedure TTestToSFX.SingleToSFX; var dst: string; begin Dest := 'AZip.zip'; dst := Dest; SetZipFile(FZip, dest, 'AZip.zip'); FZip.ZipFileName := dest; FZip.WriteOptions := [{zwoDiskSpan,} zwoZipTime]; FZip.MaxVolumeSizeKb := 1000; {ReturnValue :=} FZip.ConvertToSFX;//(TestDir + 'AZip.exe'); CheckEquals(0, FZip.ErrCode, 'Error converting to SFX: ' + FZip.ErrMessage); end; procedure TTestToSFX.TearDown; begin FZip.Free; FZip := nil; inherited; end; procedure TTestToZip.SetUp; begin inherited; KillFiles(TestDir); ForceDirectories(TestDir + 'Tmp\'); FZip.UseDirOnlyEntries := True; end; procedure TTestToZip.SFXToExistingBadSingle; var BeforeMD5: string; dst: string; begin Dest := 'AZip.exe'; dst := Dest; SetZipFile(FZip, dest, 'AZip.exe'); FZip.CopyFiles('AZip.zip=Busy.txt', True); BeforeMD5 := FileMD5(Dest); FZip.ZipFileName := dest; FZip.WriteOptions := [{zwoDiskSpan,} zwoZipTime]; // FZip.MaxVolumeSizeKb := 1000; {ReturnValue :=} FZip.ConvertToZip;//(TestDir + 'AZip.exe'); CheckEquals(0, FZip.ErrCode, 'Error converting to Zip: ' + FZip.ErrMessage); FZip.ZipFileName := ChangeFileExt(Dest, '.zip'); CheckEntryExists('Special\Data.txt'); CheckEquals(3, FZip.Count, 'Not correct resulting zip'); CheckEqualsString(BeforeMD5, FileMD5(Dest), 'Original file changed'); end; procedure TTestToZip.SFXToExistingSingle; var BeforeMD5: string; dst: string; begin Dest := 'AZip.exe'; dst := Dest; SetZipFile(FZip, dest, 'AZip.exe'); FZip.CopyFiles('AZip.zip=Help.zip'); BeforeMD5 := FileMD5(Dest); FZip.ZipFileName := dest; FZip.WriteOptions := [{zwoDiskSpan,} zwoZipTime]; // FZip.MaxVolumeSizeKb := 1000; {ReturnValue :=} FZip.ConvertToZip;//(TestDir + 'AZip.exe'); CheckEquals(0, FZip.ErrCode, 'Error converting to Zip: ' + FZip.ErrMessage); FZip.ZipFileName := ChangeFileExt(Dest, '.zip'); CheckEntryExists('Special\Data.txt'); CheckEquals(3, FZip.Count, 'Not correct resulting zip'); CheckEqualsString(BeforeMD5, FileMD5(Dest), 'Original file changed'); end; procedure TTestToZip.SFXToSingle; var dst: string; begin Dest := 'AZip.zip'; dst := Dest; SetZipFile(FZip, dest, 'AZip.zip'); FZip.ZipFileName := dest; FZip.WriteOptions := [{zwoDiskSpan,} zwoZipTime]; FZip.MaxVolumeSizeKb := 1000; {ReturnValue :=} FZip.ConvertToSFX;//(TestDir + 'AZip.exe'); CheckEquals(0, FZip.ErrCode, 'Error converting to SFX: ' + FZip.ErrMessage); end; procedure TTestToZip.TearDown; begin FZip.Free; FZip := nil; inherited; end; procedure TTestReadSpan.SetUp; begin inherited; KillFiles(TestDir); ForceDirectories(TestDir + 'Tmp\'); FZip.UseDirOnlyEntries := True; end; procedure TTestReadSpan.TearDown; begin FZip.Free; FZip := nil; inherited; end; procedure TTestReadSpan.ToExistingBadSingle; var BeforeMD5: string; // dst: string; Idx: Integer; Outname: string; ReturnValue: Integer; begin Dest := 'Split1001.zip'; FZip.CopyFiles('split1001.zip| split1002.zip | split1003.zip|split1004.zip|' + 'split1005.zip|split1006.zip|split1007.zip|split1008.zip'); FZip.CopyFiles('Joined.zip=Busy.txt', True); Outname := TestDir + 'Joined.zip'; BeforeMD5 := FileMD5(OutName); {ReturnValue :=} FZip.ReadSpan(TestDir + 'Split1.zip', Outname); // {ReturnValue :=} FZip.ReadSpan(TestDir + 'Split1008.zip', Outname); CheckEquals(0, FZip.ErrCode, 'Error joining split zip: ' + FZip.ErrMessage); Check(FileExists(TestDir + 'Joined.zip'), 'Could not find: joined.zip'); FZip.ZipFileName := TestDir + 'Joined.zip'; ReturnValue := FZip.ErrCode; CheckEquals(0, ReturnValue, 'error loading Joined.zip'); CheckEquals(1, FZip.Count, 'wrong number of files'); Idx := -1; CheckEntryExists(Idx, 'TestFiles\ZMTestFiles\big.txt'); CheckNotEqualsString(BeforeMD5, FileMD5(Outname), 'Original file not changed'); end; procedure TTestReadSpan.ToExistingSingle; var BeforeMD5: string; // dst: string; Idx: Integer; Outname: string; ReturnValue: Integer; begin Dest := 'Split1001.zip'; FZip.CopyFiles('split1001.zip| split1002.zip | split1003.zip|split1004.zip|' + 'split1005.zip|split1006.zip|split1007.zip|split1008.zip'); FZip.CopyFiles('Joined.zip=Help.zip'); Outname := TestDir + 'Joined.zip'; BeforeMD5 := FileMD5(OutName); {ReturnValue :=} FZip.ReadSpan(TestDir + 'Split1.zip', Outname); // {ReturnValue :=} FZip.ReadSpan(TestDir + 'Split1008.zip', Outname); CheckEquals(0, FZip.ErrCode, 'Error joining split zip: ' + FZip.ErrMessage); Check(FileExists(TestDir + 'Joined.zip'), 'Could not find: joined.zip'); FZip.ZipFileName := TestDir + 'Joined.zip'; ReturnValue := FZip.ErrCode; CheckEquals(0, ReturnValue, 'error loading Joined.zip'); CheckEquals(1, FZip.Count, 'wrong number of files'); Idx := -1; CheckEntryExists(Idx, 'TestFiles\ZMTestFiles\big.txt'); CheckNotEqualsString(BeforeMD5, FileMD5(Outname), 'Original file not changed'); end; procedure TTestReadSpan.ToSingle; var // dst: string; Idx: Integer; Outname: string; ReturnValue: Integer; begin Dest := 'Split1001.zip'; FZip.CopyFiles('split1001.zip| split1002.zip | split1003.zip|split1004.zip|' + 'split1005.zip|split1006.zip|split1007.zip|split1008.zip'); // FZip.ZipFileName := dest; // FZip.MaxVolumeSizeKb := 100; // ReturnValue := FZip.ErrCode; // CheckEquals(0, ReturnValue, 'error loading zip'); // FZip.WriteOptions := [{zwoDiskSpan,} zwoZipTime]; // FZip.MaxVolumeSizeKb := 1000; Outname := TestDir + 'Joined.zip'; {ReturnValue :=} FZip.ReadSpan(TestDir + 'Split1.zip', Outname); // {ReturnValue :=} FZip.ReadSpan(TestDir + 'Split1008.zip', Outname); CheckEquals(0, FZip.ErrCode, 'Error joining split zip: ' + FZip.ErrMessage); Check(FileExists(TestDir + 'Joined.zip'), 'Could not find: joined.zip'); FZip.ZipFileName := TestDir + 'Joined.zip'; ReturnValue := FZip.ErrCode; CheckEquals(0, ReturnValue, 'error loading Joined.zip'); CheckEquals(1, FZip.Count, 'wrong number of files'); Idx := -1; CheckEntryExists(Idx, 'TestFiles\ZMTestFiles\big.txt'); end; initialization RegisterTests('Misc Tests\Group 4', [ TTestZipComment.Suite, TTestToZip.Suite, TTestToSFX.Suite, TTestReadSpan.Suite ]); end.
{13. En astrofísica, una galaxia se identifica por su nombre, su tipo (1. elíptica; 2. espiral; 3. lenticular; 4. irregular), su masa (medida en kg) y la distancia en pársecs (pc) medida desde la Tierra. La Unión Astronómica Internacional cuenta con datos correspondientes a las 53 galaxias que componen el Grupo Local. Realizar un programa que lea y almacene estos datos y, una vez finalizada la carga, informe: a) la cantidad de galaxias de cada tipo. b) la masa total acumulada de las 3 galaxias principales (la Vía Láctea, Andrómeda y Triángulo) y el porcentaje que esto representa respecto a la masa de todas las galaxias. c) la cantidad de galaxias no irregulares que se encuentran a menos de 1000 pc. d) el nombre de las dos galaxias con mayor masa y el de las dos galaxias con menor masa. } const dimF = 53; type cadena10 = string[10]; rango_tipo = 1..4; galaxia = record nombre:cadena10; tipo:rango_tipo; masa:integer; distancia:integer; end; vector_galaxias = array [1..dimF] of galaxia; vector_contador = array [rango_tipo] of integer; //_____________________________________________________ procedure LeerGalaxia(var g:galaxia); begin write('Nombre: '); ReadLn(g.nombre); write('Tipo: '); ReadLn(g.tipo); write('Masa: '); ReadLn(g.masa); write('Distancia: '); ReadLn(g.distancia); end; //_____________________________________________________ procedure cargarGalaxias(var vg:vector_galaxias); var i:Integer; begin for i:=1 to dimF do begin LeerGalaxia(vg[i]); end; end; //_____________________________________________________ procedure DosMayores(nombre:cadena10;Masa:Integer;mayorMasa1:integer;nombreMayor1:cadena10;var mayorMasa2:integer;var nombreMayor2:cadena10); begin if (Masa > mayorMasa1) then begin mayorMasa2:=mayorMasa1; nombreMayor2:=nombreMayor1; mayorMasa1:=Masa; nombreMayor1:=nombre; end else begin if (Masa>mayorMasa2) then begin mayorMasa2:=Masa; nombreMayor2:=nombre; end; end; end; //_____________________________________________________ procedure DosMayores(nombre:cadena10;Masa:Integer;mayorMasa1:integer;nombreMayor1:cadena10;var mayorMasa2:integer;var nombreMayor2:cadena10); begin if (Masa < mayorMasa1) then begin mayorMasa2:=mayorMasa1; nombreMayor2:=nombreMayor1; mayorMasa1:=Masa; nombreMayor1:=nombre; end else begin if (Masa < mayorMasa2) then begin mayorMasa2:=Masa; nombreMayor2:=nombre; end; end; end; //_____________________________________________________ procedure Informar(vg:vector_galaxias); var i:integer; vc:vector_contador; masaTotal:integer; galaxiasNoIrregulares:integer; mayorMasa1:integer; nombreMayor1:cadena10; mayorMasa2:integer; nombreMayor2:cadena10; menorMasa1:integer; nombreMenor1:cadena10; menorMasa2:integer; nombreMenor2:cadena10; begin galaxiasNoIrregulares:=0; vc[1]:=0; vc[2]:=0; vc[3]:=0; vc[4]:=0; masaTotal:=0; mayorMasa1:=-1; nombreMayor1:=''; mayorMasa2:=-1; nombreMayor2:=''; mayorMenor1:=999; nombreMenor1:=''; menorMasa2:=999; nombreMenor2:=''; for i:=1 to dimF do begin vc[vg[i].tipo]:=vc[vg[i].tipo]+1; if ((vg[i].nombre ='la Via Lactea') or (vg[i].nombre ='Andromeda') or (vg[i].nombre ='Triangulo')) then begin masaTotal:=masaTotal+vg[i].masa; end; if (vg[i].distancia < 1000) then begin galaxiasNoIrregulares:=galaxiasNoIrregulares+1; end; DosMayores(vg[i].nombre,vg[i].masa,mayorMasa1,nombreMayor1,mayorMasa2,nombreMayor2); DosMenores(vg[i].nombre,vg[i].masa,mayorMenor1,nombreMenor1,mayorMenor2,nombreMenor2); end; WriteLn('Cantidad de galaxias de cada tipo'); WriteLn(vc[1]); WriteLn(vc[2]); WriteLn(vc[3]); WriteLn(vc[4]); WriteLn('La masa total acumulada es: ',masaTotal); end; //_____________________________________________________ var vg:vector_galaxias; begin cargarGalaxias(vg); Informar(vg); end.
{==============================================================================| | Project: MontDigital RMI | |==============================================================================| | Content: Process unit | |==============================================================================| | Copyright (c) 2013-2014 MontDigital Software. All rights reserved. | | Author: Montredo. Contacts: <montredo@mail.ru> | |==============================================================================} unit uProcess; {$MODE OBJFPC}{$H+} interface type { TProcess } TProcess = record FTime: string; FEvent: string; FImageIndex: ShortInt; end; var Process: array of TProcess; function GetProcess(AEvent: string): Integer; procedure SetProcess(AIndex: Integer; AImageIndex: ShortInt); procedure AddProcess(ATime, AEvent: string; AImageIndex: ShortInt); procedure ViewProcess; procedure SearchProcess(AValue: string); procedure CleanProcessList; implementation uses Classes, SysUtils, SyncObjs, uMain; var CS: TCriticalSection; function GetProcess(AEvent: string): Integer; var I: Integer; begin Result := -1; CS.Enter; for I := Low(Process) to High(Process) do begin with Process[I] do begin if Pos(AEvent, FEvent) > 0 then begin Result := I; Break; end; end; end; CS.Leave; end; procedure SetProcess(AIndex: Integer; AImageIndex: ShortInt); begin CS.Enter; with Process[AIndex] do begin FImageIndex := AImageIndex; end; CS.Leave; end; procedure AddProcess(ATime, AEvent: string; AImageIndex: ShortInt); var Count: Integer; begin CS.Enter; Count := Length(Process); SetLength(Process, Count + 1); with Process[Count] do begin FTime := ATime; FEvent := AEvent; FImageIndex := AImageIndex; end; CS.Leave; end; procedure ViewProcess; var I: Integer; begin MainForm.EventView.Items.BeginUpdate; CS.Enter; for I := Low(Process) to High(Process) do begin with Process[I] do begin with MainForm.EventView.Items.Add do begin Caption := FTime; SubItems.Add(FEvent); ImageIndex := FImageIndex; end; end; end; CS.Leave; MainForm.EventView.Items.EndUpdate; end; procedure SearchProcess(AValue: string); var I: Integer; begin MainForm.EventView.Items.BeginUpdate; CS.Enter; for I := Low(Process) to High(Process) do begin with Process[I] do begin if (Pos(AValue, FTime) > 0) or (Pos(AValue, FEvent) > 0) then begin with MainForm.EventView.Items.Add do begin Caption := FTime; SubItems.Add(FEvent); ImageIndex := FImageIndex; end; end; end; end; CS.Leave; MainForm.EventView.Items.EndUpdate; end; procedure CleanProcessList; begin CS.Enter; SetLength(Process, 0); CS.Leave; end; initialization CS := TCriticalSection.Create; SetLength(Process, 0); finalization CS.Free; SetLength(Process, 0); end.
unit cosmos.secretarias.view.FormFuncoesCadastrados; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FrameDeleteButtons, cosmos.frames.fkSearch, StdCtrls, ExtCtrls, GroupHeader, cosmos.frames.gridsearch, cosmos.classes.ServerInterface, DB, DBClient, cosmos.framework.interfaces.root, Cosmos.Framework.Interfaces.Dialogs, cosmos.frames.usuariocad, cosmos.system.messages, cosmos.classes.security, Cosmos.Framework.Interfaces.DataAcess, Datasnap.DSConnect; type TFrmFuncoesCadastrados = class(TForm) FmeGridSearch1: TFmeGridSearch; CdsFuncoesCadastrado: TClientDataSet; FmeDBDelButtons1: TFmeDBDelButtons; MSGroupHeader3: TMSGroupHeader; FmeUsuarioCadastrador1: TFmeUsuarioCadastrador; FmeFkFuncoes: TFmeFKSearch; Label2: TLabel; MSGroupHeader1: TMSGroupHeader; EdtCadastrado: TEdit; procedure CdsFuncoesCadastradoBeforeDelete(DataSet: TDataSet); procedure CdsFuncoesCadastradoBeforePost(DataSet: TDataSet); procedure CdsFuncoesCadastradoAfterInsert(DataSet: TDataSet); procedure CdsFuncoesCadastradoAfterPost(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CdsFuncoesCadastradoReconcileError(DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); private { Private declarations } FICosmosApp: ICosmosApplication; FRemoteConnection: TDSProviderConnection; protected public { Public declarations } procedure CadastrarFuncoes(const codcad: integer; nomcad: string); property ICosmosApp: ICosmosApplication read FICosmosApp; end; var FrmFuncoesCadastrados: TFrmFuncoesCadastrados; implementation {$R *.dfm} procedure TFrmFuncoesCadastrados.CdsFuncoesCadastradoAfterInsert( DataSet: TDataSet); begin Dataset.Fields.FieldByName('codcad').AsInteger := CdsFuncoesCadastrado.Params.Items[0].AsInteger; end; procedure TFrmFuncoesCadastrados.CdsFuncoesCadastradoAfterPost( DataSet: TDataSet); begin if CdsFuncoesCadastrado.ChangeCount > 0 then CdsFuncoesCadastrado.ApplyUpdates(0); end; procedure TFrmFuncoesCadastrados.CdsFuncoesCadastradoBeforeDelete( DataSet: TDataSet); begin if ICosmosApp.DlgMessage.ConfirmationMessage(TCosmosTitles.Funcoes, TCosmosConfMsg.DeleteFuncao) = mrNo then Abort; end; procedure TFrmFuncoesCadastrados.CdsFuncoesCadastradoBeforePost( DataSet: TDataSet); var SequenceName: string; begin inherited; DataSet.Fields.FieldByName('USURES').Value := UpperCase(ICosmosApp.IRemoteCon.ConnectedUser);; DataSet.Fields.FieldByName('DATCAD').Value := ICosmosApp.IRemoteCon.ServerDateTime; if Dataset.State = dsInsert then begin SequenceName := TClientDataset(DataSet).GetOptionalParam('SequenceName'); Dataset.Fields.Fields[0].AsInteger := ICosmosApp.IRemoteCon.GetSequenceValue(SequenceName); end; end; procedure TFrmFuncoesCadastrados.CdsFuncoesCadastradoReconcileError( DataSet: TCustomClientDataSet; E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction); begin Action := ICosmosApp.IRemoteCon.ReconcileError(E, UpdateKind); end; procedure TFrmFuncoesCadastrados.FormClose(Sender: TObject; var Action: TCloseAction); begin if CdsFuncoesCadastrado.Active then CdsFuncoesCadastrado.Close; CdsFuncoesCadastrado.RemoteServer := nil; if Assigned(FRemoteConnection) then ICosmosApp.IRemoteCon.DropConnection(FRemoteConnection); if ICosmosApp <> nil then FICosmosApp := nil; end; procedure TFrmFuncoesCadastrados.FormCreate(Sender: TObject); begin FICosmosApp := Application.MainForm as ICosmosApplication; FRemoteConnection := ICosmosApp.IRemoteCon.CreateConnection(scCommon); CdsFuncoesCadastrado.RemoteServer := FRemoteConnection; FmeFkFuncoes.Configure('codfun',csFuncoes); FmeGridSearch1.SearchFields := 'desfun'; CdsFuncoesCadastrado.ReadOnly := (Assigned(ICosmosApp.IRemoteCon)) and (ICosmosApp.IRemoteCon.CurrentConnectionMode <> cmWrite); end; procedure TFrmFuncoesCadastrados.CadastrarFuncoes(const codcad: integer; nomcad: string); begin CdsFuncoesCadastrado.Params.Items[0].AsInteger := codcad; CdsFuncoesCadastrado.Open; EdtCadastrado.Text := nomcad; ShowModal; end; end.
unit BCEditor.Editor.Utils; interface uses System.Classes, System.SysUtils, BCEditor.Types; function GetTextPosition(const AChar, ALine: Integer): TBCEditorTextPosition; function IsUTF8Buffer(const ABuffer: TBytes; out AWithBOM: Boolean): Boolean; function GetClipboardText: string; procedure SetClipboardText(const AText: string); implementation uses System.Math, BCEditor.Consts, Winapi.Windows, vcl.ClipBrd; function GetTextPosition(const AChar, ALine: Integer): TBCEditorTextPosition; begin with Result do begin Char := AChar; Line := ALine; end; end; // checks for a BOM in UTF-8 format or searches the Buffer for typical UTF-8 octet sequences function IsUTF8Buffer(const ABuffer: TBytes; out AWithBOM: Boolean): Boolean; const MinimumCountOfUTF8Strings = 1; var i, LBufferSize, LFoundUTF8Strings: Integer; { 3 trailing bytes are the maximum in valid UTF-8 streams, so a count of 4 trailing bytes is enough to detect invalid UTF-8 streams } function CountOfTrailingBytes: Integer; begin Result := 0; Inc(i); while (i < LBufferSize) and (Result < 4) do begin if ABuffer[i] in [$80 .. $BF] then Inc(Result) else Break; Inc(i); end; end; begin { if Stream is nil, let Delphi raise the exception, by accessing Stream, to signal an invalid result } // start analysis at actual Stream.Position LBufferSize := Length(ABuffer); // if no special characteristics are found it is not UTF-8 Result := False; AWithBOM := False; if LBufferSize > 0 then begin { first search for BOM } if (LBufferSize >= Length(BCEDITOR_UTF8BOM)) and CompareMem(@ABuffer[0], @BCEDITOR_UTF8BOM[0], Length(BCEDITOR_UTF8BOM)) then begin AWithBOM := True; Result := True; Exit; end; { If no BOM was found, check for leading/trailing byte sequences, which are uncommon in usual non UTF-8 encoded text. NOTE: There is no 100% save way to detect UTF-8 streams. The bigger MinimumCountOfUTF8Strings, the lower is the probability of a false positive. On the other hand, a big MinimumCountOfUTF8Strings makes it unlikely to detect files with only little usage of non US-ASCII chars, like usual in European languages. } LFoundUTF8Strings := 0; i := 0; while i < LBufferSize do begin case ABuffer[i] of $00 .. $7F: // skip US-ASCII characters as they could belong to various charsets ; $C2 .. $DF: if CountOfTrailingBytes = 1 then Inc(LFoundUTF8Strings) else Break; $E0: begin Inc(i); if (i < LBufferSize) and (ABuffer[i] in [$A0 .. $BF]) and (CountOfTrailingBytes = 1) then Inc(LFoundUTF8Strings) else Break; end; $E1 .. $EC, $EE .. $EF: if CountOfTrailingBytes = 2 then Inc(LFoundUTF8Strings) else Break; $ED: begin Inc(i); if (i < LBufferSize) and (ABuffer[i] in [$80 .. $9F]) and (CountOfTrailingBytes = 1) then Inc(LFoundUTF8Strings) else Break; end; $F0: begin Inc(i); if (i < LBufferSize) and (ABuffer[i] in [$90 .. $BF]) and (CountOfTrailingBytes = 2) then Inc(LFoundUTF8Strings) else Break; end; $F1 .. $F3: if CountOfTrailingBytes = 3 then Inc(LFoundUTF8Strings) else Break; $F4: begin Inc(i); if (i < LBufferSize) and (ABuffer[i] in [$80 .. $8F]) and (CountOfTrailingBytes = 2) then Inc(LFoundUTF8Strings) else Break; end; $C0, $C1, $F5 .. $FF: // invalid UTF-8 bytes Break; $80 .. $BF: // trailing bytes are consumed when handling leading bytes, // any occurence of "orphaned" trailing bytes is invalid UTF-8 Break; end; if LFoundUTF8Strings = MinimumCountOfUTF8Strings then begin Result := True; Break; end; Inc(i); end; end; end; function OpenClipboard: Boolean; var LRetryCount: Integer; LDelayStepMs: Integer; begin LDelayStepMs := BCEDITOR_CLIPBOARD_DELAY_STEP_MS; Result := False; for LRetryCount := 1 to BCEDITOR_CLIPBOARD_MAX_RETRIES do try Clipboard.Open; Exit(True); except on Exception do if LRetryCount = BCEDITOR_CLIPBOARD_MAX_RETRIES then raise else begin Sleep(LDelayStepMs); Inc(LDelayStepMs, BCEDITOR_CLIPBOARD_DELAY_STEP_MS); end; end; end; function GetClipboardText: string; var LGlobalMem: HGlobal; LLocaleID: LCID; LBytePointer: PByte; function AnsiStringToString(const AValue: AnsiString; ACodePage: Word): string; var LInputLength, LOutputLength: Integer; begin LInputLength := Length(AValue); LOutputLength := MultiByteToWideChar(ACodePage, 0, PAnsiChar(AValue), LInputLength, nil, 0); SetLength(Result, LOutputLength); MultiByteToWideChar(ACodePage, 0, PAnsiChar(AValue), LInputLength, PChar(Result), LOutputLength); end; function CodePageFromLocale(ALanguage: LCID): Integer; var LBuffer: array [0 .. 6] of Char; begin GetLocaleInfo(ALanguage, LOCALE_IDEFAULTANSICODEPAGE, LBuffer, 6); Result := StrToIntDef(LBuffer, GetACP); end; begin Result := ''; if not OpenClipboard then Exit; try if Clipboard.HasFormat(CF_UNICODETEXT) then begin LGlobalMem := Clipboard.GetAsHandle(CF_UNICODETEXT); if LGlobalMem <> 0 then try Result := PChar(GlobalLock(LGlobalMem)); finally GlobalUnlock(LGlobalMem); end; end else begin LLocaleID := 0; LGlobalMem := Clipboard.GetAsHandle(CF_LOCALE); if LGlobalMem <> 0 then try LLocaleID := PInteger(GlobalLock(LGlobalMem))^; finally GlobalUnlock(LGlobalMem); end; LGlobalMem := Clipboard.GetAsHandle(CF_TEXT); if LGlobalMem <> 0 then try LBytePointer := GlobalLock(LGlobalMem); Result := AnsiStringToString(PAnsiChar(LBytePointer), CodePageFromLocale(LLocaleID)); finally GlobalUnlock(LGlobalMem); end; end; finally Clipboard.Close; end; end; procedure SetClipboardText(const AText: string); var LGlobalMem: HGlobal; LPGlobalLock: PByte; LLength: Integer; begin if AText = '' then Exit; LLength := Length(AText); if not OpenClipboard then Exit; try Clipboard.Clear; { Set ANSI text only on Win9X, WinNT automatically creates ANSI from Unicode } if Win32Platform <> VER_PLATFORM_WIN32_NT then begin LGlobalMem := GlobalAlloc(GMEM_MOVEABLE or GMEM_DDESHARE, LLength + 1); if LGlobalMem <> 0 then begin LPGlobalLock := GlobalLock(LGlobalMem); try if Assigned(LPGlobalLock) then begin Move(PAnsiChar(AnsiString(AText))^, LPGlobalLock^, LLength + 1); Clipboard.SetAsHandle(CF_TEXT, LGlobalMem); end; finally GlobalUnlock(LGlobalMem); end; end; end; { Set unicode text, this also works on Win9X, even if the clipboard-viewer can't show it, Word 2000+ can paste it including the unicode only characters } LGlobalMem := GlobalAlloc(GMEM_MOVEABLE or GMEM_DDESHARE, (LLength + 1) * SizeOf(Char)); if LGlobalMem <> 0 then begin LPGlobalLock := GlobalLock(LGlobalMem); try if Assigned(LPGlobalLock) then begin Move(PChar(AText)^, LPGlobalLock^, (LLength + 1) * SizeOf(Char)); Clipboard.SetAsHandle(CF_UNICODETEXT, LGlobalMem); end; finally GlobalUnlock(LGlobalMem); end; end; finally Clipboard.Close; end; end; end.
Unit Timers; (* Обертка для класса System.Timers.Timer (c) Брагилевский В.Н. 2007 Сохранен интерфейс класса Timer из PascalABC за исключением функции Handle. *) interface uses System; type /// Класс таймера Timer = class private _timer: System.Timers.Timer; _procedure: procedure; procedure SetEnabled(_enabled: boolean); function GetEnabled: boolean; procedure SetInterval(_interval: integer); function GetInterval: integer; procedure OnTimer(sender: object; e: System.Timers.ElapsedEventArgs); public /// Создает таймер с интервалом срабатывания ms миллисекунд и обработчиком TimerProc constructor Create(ms: integer; TimerProc: procedure); /// Запускает таймер procedure Start; /// Останавливает таймер procedure Stop; /// Запущен ли таймер property Enabled: boolean read GetEnabled write SetEnabled; /// Интервал срабатывания таймера property Interval: integer read GetInterval write SetInterval; end; implementation procedure Timer.OnTimer(sender: object; e: System.Timers.ElapsedEventArgs); begin _procedure; end; constructor Timer.Create(ms: integer; TimerProc: procedure); begin _timer := new System.Timers.Timer(ms); _procedure := TimerProc; _timer.Elapsed += OnTimer; end; procedure Timer.Start; begin Enabled := True; end; procedure Timer.Stop; begin Enabled := False; end; procedure Timer.SetEnabled(_enabled: boolean); begin _timer.Enabled := _enabled; end; function Timer.GetEnabled: boolean; begin Result := _timer.Enabled; end; procedure Timer.SetInterval(_interval: integer); begin _timer.Interval := _interval; end; function Timer.GetInterval: integer; begin Result := Round(_timer.Interval); end; end.
// 003 u_c_base_socket_4 // 20 may 2005 // -- (C) Felix John COLIBRI 2004 // -- documentation: http://www.felix-colibri.com // -- common to client and server (*$r+*) unit u_c_base_socket_4; interface uses Windows, Messages, WinSock , SysUtils // exception , u_c_basic_object ; type t_socket_error= (e_no_socket_error , e_wsa_startup_error , e_create_socket_error , e_wsa_select_error , e_connect_error , e_wsa_lookup_host_error , e_lookup_result_error, e_notification_error , e_receive_data_error, e_send_data_error , e_wsa_cancel_lookup_error, e_close_socket_error , e_win_proc_exception); c_socket_exception= Class(Exception) constructor create_socket_exception(p_socket_handle: Integer; p_text: String; p_socket_error: Integer); end; // -- the socket messages t_wm_async_select= record Msg: Cardinal; m_socket_handle: TSocket; // -- lParam.Lo m_select_event: Word; // -- lParam.Hi m_select_error: Word; Result: Longint; end; c_base_socket= Class; // -- triggered when received data t_po_base_socket_event= Procedure(p_c_base_socket: c_base_socket) of Object; t_po_traffic_event= Procedure(p_traffic: String) of Object; c_base_socket= class(c_basic_object) m_trace_socket: Boolean; // -- WsaData "mailbox variable" to display the data m_wsa_data: twsaData; // -- "mailbox variables" m_remote_ip: String; m_remote_port: Integer; m_local_ip: String; m_local_port: Integer; m_base_socket_handle: tSocket; m_window_handle: hWnd; // -- if handle is used as a key, must save the m_save_socket_handle: tSocket; // -- called Listen or Connect m_is_open: Boolean; m_socket_error: t_socket_error; m_socket_error_text: String; m_wsa_error_code: Integer; m_wsa_socket_error_message: String; // -- notify the user about an exception m_on_after_socket_error: t_po_base_socket_event; // -- somebody called "do_close_socket" (also called by server closed, and Free) // m_on_before_do_close_socket, m_on_after_do_close_socket: t_po_base_socket_event; m_on_display_traffic: t_po_traffic_event; Constructor create_base_socket(p_name: String); function f_display_base_socket: String; function f_name_and_handle(p_handle: Integer): String; procedure trace_socket(p_text: String); procedure raise_exception(p_socket_error: t_socket_error; p_wsa_error_code: Integer; p_error_text: String); procedure wsa_startup; procedure display_wsa_data; procedure allocate_window; procedure create_win_socket; procedure WndProc(var Message: TMessage); function f_format_traffic(p_direction: Char; p_traffic: String): String; function f_do_send_string(p_string: String): Integer; Virtual; function f_do_send_buffer(p_pt_buffer: Pointer; p_send_count: Integer): Integer; Virtual; function f_do_read_data(p_pt: Pointer; p_get_max: Integer): Integer; procedure do_close_win_socket; Virtual; Destructor Destroy; Override; end; // c_base_socket implementation uses // SysUtils Forms // Application , u_characters , u_c_display, u_display_hex_2, u_strings , u_winsock ; constructor c_socket_exception.create_socket_exception(p_socket_handle: Integer; p_text: String; p_socket_error: Integer); begin InHerited Create('Handle '+ IntToStr(p_socket_handle) + ' err= '+ p_text+ ' sock_err '+ IntToStr(p_socket_error)); end; // create_socket_exception // -- c_base_socket Constructor c_base_socket.create_base_socket(p_name: String); begin Inherited create_basic_object(p_name); m_base_socket_handle:= INVALID_SOCKET; end; // create_base_socket function c_base_socket.f_name_and_handle(p_handle: Integer): String; begin Result:= m_name+ '_'+ f_socket_handle_string(p_handle); end; // f_name_and_handle function c_base_socket.f_display_base_socket: String; // -- debug begin Result:= f_name_and_handle(m_base_socket_handle) + ' $'+ f_integer_to_hex(Integer(Self)); end; // f_display_base_socket procedure c_base_socket.trace_socket(p_text: String); begin if m_trace_socket then display(p_text); end; // trace_socket procedure c_base_socket.raise_exception(p_socket_error: t_socket_error; p_wsa_error_code: Integer; p_error_text: String); begin if assigned(m_on_after_socket_error) then begin m_socket_error:= p_socket_error; m_wsa_error_code:= p_wsa_error_code; m_socket_error_text:= p_error_text; m_wsa_socket_error_message:= f_socket_error_message(m_wsa_error_code); m_on_after_socket_error(Self); end else Raise c_socket_exception.create_socket_exception(m_base_socket_handle, p_error_text, p_wsa_error_code); end; // raise_exception // -- the usual wsa calls procedure c_base_socket.wsa_startup; var l_version: Word; l_result: Integer; begin trace_socket(''); trace_socket('> wsa_startup'); // -- l_version:= $0202; l_version:= $0101; trace_socket(':wsaStartup()'); l_result:= wsaStartup(l_version, m_wsa_data); if l_result<> 0 then raise_exception(e_wsa_startup_error, WSAGetLastError, 'WsaStartup'); trace_socket('< wsa_startup'); end; // wsa_startup procedure c_base_socket.display_wsa_data; begin with m_wsa_data do begin display('wVersion '+ IntToHex(wVersion, 4)); display('wHighVersion '+ IntToHex(wHighVersion, 4)); display('szDescription '+ string(szDescription)); display('szSystemStatus '+ string(szSystemStatus)); display('iMaxSockets '+ IntToStr(iMaxSockets)); display('iMaxUdpDg '+ IntToStr(iMaxUdpDg)); if lpVendorInfo= nil then display('lpVendorInfo NIL'); end; end; // display_wsa_data procedure c_base_socket.create_win_socket; begin trace_socket(''); trace_socket('> create_win_socket'); // -- allocate the Socket record, and get back its handle trace_socket(':Socket(pf_Inet, Sock_Stream)'); m_base_socket_handle:= Socket(PF_INET, SOCK_STREAM, IPPROTO_IP); if m_base_socket_handle= INVALID_SOCKET then raise_exception(e_create_socket_error, WSAGetLastError, 'Socket()'); // -- local addr can be undefined because did not Connect yet trace_socket('< create_win_socket '+ f_name_and_handle(m_base_socket_handle)); end; // create_win_socket procedure c_base_socket.allocate_window; begin if m_window_handle= 0 then begin m_window_handle:= AllocateHwnd(WndProc); trace_socket('allocate_window '+ IntToStr(m_window_handle)); end; end; // allocate_window procedure c_base_socket.WndProc(var Message: TMessage); begin try Dispatch(Message); except on e: exception do begin display('*** c_base_socket.WndProc_exception '+ e.Message); raise_exception(e_win_proc_exception, 0, 'c_base_socket.WndProc_exception '+ e.Message); end; end; // try except end; // WndProc // -- received some data function c_base_socket.f_format_traffic(p_direction: Char; p_traffic: String): String; var l_prefix: String; l_index: Integer; begin l_prefix:= Format('%5d ', [m_base_socket_handle])+ p_direction+ ' '; Result:= l_prefix; l_index:= 1; while l_index<= Length(p_traffic) do begin if p_traffic[l_index]= k_return then begin Result:= Result+ k_new_line; Inc(l_index, 1); if l_index+ 1< Length(p_traffic) then Result:= Result+ l_prefix; end else Result:= Result+ p_traffic[l_index]; Inc(l_index); end; // while l_index end; // f_format_traffic function c_base_socket.f_do_read_data(p_pt: Pointer; p_get_max: Integer): Integer; // -- get the data from the client socket var l_display_traffic: String; begin trace_socket(''); trace_socket('> f_do_read_data '+ f_name_and_handle(m_base_socket_handle)); trace_socket(':Recv('+ f_socket_handle_string(m_base_socket_handle)+ ', pt^, ' + IntToStr(p_get_max)+ ', 0)'); Result:= Recv(m_base_socket_handle, p_pt^, p_get_max, 0); if (Result> 0) and Assigned(m_on_display_traffic) then begin SetLength(l_display_traffic, Result); Move(p_pt^, l_display_traffic[1], Result); m_on_display_traffic(f_format_traffic('<', l_display_traffic)); end; if Result< 0 then raise_exception(e_receive_data_error, WSAGetLastError, 'f_receive_data - Recv'); trace_socket('< f_do_read_data. Received ='+ IntToStr(Result)); end; // f_do_read_data // -- user sends data function c_base_socket.f_do_send_buffer(p_pt_buffer: Pointer; p_send_count: Integer): Integer; var l_display_traffic: String; begin trace_socket(''); trace_socket('> f_do_send_buffer '+ f_name_and_handle(m_base_socket_handle)); trace_socket(':Send('+ f_socket_handle_string(m_base_socket_handle)+ ', pt^, ' + IntToStr(p_send_count)+ ', 0)'); Result:= Send(m_base_socket_handle, p_pt_buffer^, p_send_count, 0); if Result< 0 then raise_exception(e_send_data_error, WSAGetLastError, 'send_buffer Send') else begin SetLength(l_display_traffic, Result); Move(p_pt_buffer^, l_display_traffic[1], Result); m_on_display_traffic(f_format_traffic('>', l_display_traffic)); end; trace_socket('< f_do_send_buffer. Sent='+ IntToStr(Result)); end; // send_buffer function c_base_socket.f_do_send_string(p_string: String): Integer; begin trace_socket(''); trace_socket('> f_send_string '+ f_name_and_handle(m_base_socket_handle)); trace_socket(':Send('+ f_socket_handle_string(m_base_socket_handle)+ ', ' + f_display_string(p_string)+ ', '+ IntToStr(Length(p_string))+ ', 0)'); Result:= Send(m_base_socket_handle, p_string[1], Length(p_string), 0); if Result< 0 then raise_exception(e_send_data_error, WSAGetLastError, 'send_string Send') else if Assigned(m_on_display_traffic) then m_on_display_traffic(f_format_traffic('>', p_string)); trace_socket('< f_do_send_string. Sent = '+ IntToStr(Result)); end; // f_do_send_string procedure c_base_socket.do_close_win_socket; var l_result: Integer; l_trace_socket: boolean; begin trace_socket(''); trace_socket('> do_close_win_socket '+ f_name_and_handle(m_base_socket_handle)); m_save_socket_handle:= m_base_socket_handle; l_trace_socket:= m_trace_socket; if m_base_socket_handle= INVALID_SOCKET then trace_socket('INVALID_SOCKET (already_closed ?)') else begin trace_socket(':CloseSocket('+ f_socket_handle_string(m_base_socket_handle)+ ')'); l_result:= CloseSocket(m_base_socket_handle); if l_result<> 0 then raise_exception(e_close_socket_error, WSAGetLastError, 'CloseSocket') else begin m_base_socket_handle:= INVALID_SOCKET; m_is_open:= False; end; end; if Assigned(m_on_after_do_close_socket) then m_on_after_do_close_socket(Self); if l_trace_socket then display('< do_close_win_socket'); end; // do_close_win_socket Destructor c_base_socket.Destroy; begin trace_socket('> c_base_socket.Destroy'); if m_is_open and (m_base_socket_handle<> INVALID_SOCKET) then do_close_win_socket; Inherited; trace_socket('< c_base_socket.Destroy'); end; // Destroy begin // u_c_base_socket end. // u_c_base_socket
unit uPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, System.ImageList, Vcl.ImgList, System.Actions, Vcl.ActnList, Vcl.ExtCtrls, Vcl.DBCtrls, Vcl.ComCtrls, Vcl.ToolWin, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, uProduto; type TPrincipal = class(TForm) ToolBar1: TToolBar; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ActionList1: TActionList; Incluir: TAction; Alterar: TAction; Excluir: TAction; ImageList1: TImageList; DBGrid1: TDBGrid; DataSource1: TDataSource; edtPesquisa: TEdit; procedure IncluirExecute(Sender: TObject); procedure AlterarExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ExcluirExecute(Sender: TObject); procedure edtPesquisaChange(Sender: TObject); private Produto: TProduto; procedure AtualizarCadastro; { Private declarations } public { Public declarations } end; var Principal: TPrincipal; implementation {$R *.dfm} uses uIncProduto; procedure TPrincipal.AlterarExecute(Sender: TObject); begin if DBGrid1.DataSource.DataSet.RecordCount = 0 then Exit; if IncProduto = nil then Application.CreateForm(TIncProduto, IncProduto); IncProduto.vID:= DBGrid1.DataSource.DataSet.FieldByName('ID').AsInteger; // Edição Try IncProduto.ShowModal; Finally FreeAndNil(IncProduto); End; AtualizarCadastro; end; procedure TPrincipal.FormCreate(Sender: TObject); begin AtualizarCadastro; end; procedure TPrincipal.IncluirExecute(Sender: TObject); begin if IncProduto = nil then Application.CreateForm(TIncProduto, IncProduto); IncProduto.vID:= 0; // Inclusão IncProduto.edtValor.Text:= '0,00'; Try IncProduto.ShowModal; Finally FreeAndNil(IncProduto); End; AtualizarCadastro; end; procedure TPrincipal.AtualizarCadastro; begin Try Produto:= TProduto.Create; DataSource1.DataSet:= Produto.ConsultarProduto(edtPesquisa.Text); TFloatField(DataSource1.DataSet.FieldByName('VALOR')).DisplayFormat:= '#,##0.00'; Finally FreeAndNil(Produto); End; end; procedure TPrincipal.edtPesquisaChange(Sender: TObject); begin AtualizarCadastro; end; procedure TPrincipal.ExcluirExecute(Sender: TObject); begin if DBGrid1.DataSource.DataSet.RecordCount = 0 then Exit; if MessageDlg('Deseja realmente excluir o produto selecionado?', mtConfirmation, [mbYes, mbNo], 0) <> mrYes then Exit; Try Produto:= TProduto.Create; Produto.ID:= DBGrid1.DataSource.DataSet.FieldByName('ID').AsInteger; Produto.ExcluirProduto; Finally FreeAndNil(Produto); End; AtualizarCadastro; end; end.
(* * Delphi Multi-tab Chromium Browser Frame * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : BccSafe <bccsafe5988@gmail.com> * QQ : 1262807955 * Web site : http://www.bccsafe.com * Repository : https://github.com/bccsafe/DcefBrowser * * The code of DcefBrowser is based on DCEF3 by: Henri Gourvest <hgourvest@gmail.com> * code: https://github.com/hgourvest/dcef3 * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit DcefB.Handler.Geolocation; interface uses Windows, Classes, DcefB.Cef3.Interfaces, DcefB.Cef3.Classes, DcefB.Cef3.Types, DcefB.Events, DcefB.res, DcefB.Utils, DcefB.BaseObject; type TDcefBGeolocationHandler = class(TCefGeolocationHandlerOwn) private FEvents: IDcefBrowser; protected function OnRequestGeolocationPermission(const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback): Boolean; override; procedure OnCancelGeolocationPermission(const browser: ICefBrowser; requestId: Integer); override; public constructor Create(aDcefBrowser: IDcefBrowser); reintroduce; destructor Destroy; override; end; implementation { TCustomGeolocationHandler } constructor TDcefBGeolocationHandler.Create(aDcefBrowser: IDcefBrowser); begin inherited Create; FEvents := aDcefBrowser; end; destructor TDcefBGeolocationHandler.Destroy; begin FEvents := nil; inherited; end; procedure TDcefBGeolocationHandler.OnCancelGeolocationPermission (const browser: ICefBrowser; requestId: Integer); { var PArgs: PCancelGeolocationPermissionArgs; } begin inherited; { New(PArgs); PArgs.requestingUrl := @requestingUrl; PArgs.requestId := requestId; TDcefBUtils.SendMsg(browser, WM_CancelGeolocationPermission, LParam(PArgs)); Dispose(PArgs); } FEvents.doOnCancelGeolocationPermission(browser, requestId); end; function TDcefBGeolocationHandler.OnRequestGeolocationPermission (const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback): Boolean; { var PArgs: PRequestGeolocationPermissionArgs; } begin { New(PArgs); PArgs.requestingUrl := @requestingUrl; PArgs.requestId := requestId; PArgs.callback := @callback; PArgs.Result := False; if TDcefBUtils.SendMsg(browser, WM_RequestGeolocationPermission, LParam(PArgs)) then Result := PArgs.Result else Result := False; Dispose(PArgs); } Result := False; FEvents.doOnRequestGeolocationPermission(browser, requestingUrl, requestId, callback, Result); end; end.
{ fpDebug - A debugger for the Free Pascal Compiler. Copyright (c) 2012 by Graeme Geldenhuys. See the file LICENSE.txt, included in this distribution, for details about redistributing fpDebug. Description: . } unit machoDbgSource; {$mode objfpc}{$H+} interface uses Classes, SysUtils, macho, machofile, dbgInfoTypes, stabs; type { TDbgMachoDataSource } TDbgMachoDataSource = class(TDbgDataSource) private fSource : TStream; fOwnSource : Boolean; fFile : TMachoFile; isStabs : Boolean; StabsCmd : symtab_command; fileRead : Boolean; protected procedure ReadFile; function GetStabSectionInfo(StabStr: Boolean; var SectionOffset, SectionSize: Int64): Boolean; function GetSectionIndex(const SectionName: AnsiString): Integer; public class function isValid(ASource: TStream): Boolean; override; class function UserName: AnsiString; override; public constructor Create(ASource: TStream; OwnSource: Boolean); override; destructor Destroy; override; { function SectionsCount: Integer; function GetSection(index: Integer; var Name: AnsiString; var Size: Int64): Boolean; function GetSectionData(index: Integer; outStream: TStream): Boolean;} function GetSectionInfo(const SectionName: AnsiString; var Size: int64): Boolean; override; function GetSectionData(const SectionName: AnsiString; Offset, Size: Int64; var Buf: array of byte): Int64; override; end; implementation const //StabSectoinName _stab = '.stab'; _stabstr = '.stabstr'; function isValidMachoStream(stream: TStream): Boolean; var header : mach_header; begin try Result := Assigned(stream); if not Result then Exit; Result := stream.Read(header, sizeof(header)) = sizeof(header); if not Result then Exit; Result := (header.magic = MH_CIGAM) or (header.magic = MH_MAGIC); except Result := false; end; end; function FixMachoName(const macsectionname: String): String; begin if Copy(macsectionName, 1, 2) = '__' then Result:= '.'+Copy(macsectionName, 3, length(macsectionName)-2) else Result := macsectionname; end; { TDbgMachoDataSource } class function TDbgMachoDataSource.isValid(ASource: TStream): Boolean; begin Result := isValidMachoStream(ASource); end; class function TDbgMachoDataSource.UserName: AnsiString; begin Result:='mach-o file'; end; procedure TDbgMachoDataSource.ReadFile; var i : Integer; begin if Assigned(fFile) then fFile.Free; fFile:=TMachOFile.Create; fFile.LoadFromStream(fSource); for i := 0 to fFile.header.ncmds - 1 do begin isStabs := fFile.commands[i]^.cmd = LC_SYMTAB; if isStabs then begin StabsCmd := psymtab_command(fFile.commands[i])^; Break; end; end; fileRead := true; end; function TDbgMachoDataSource.GetStabSectionInfo(StabStr: Boolean; var SectionOffset, SectionSize: Int64): Boolean; begin Result := isStabs; if not Result then Exit; if StabStr then begin SectionOffset := StabsCmd.stroff; SectionSize := StabsCmd.strsize; end else begin SectionOffset := StabsCmd.symoff; SectionSize := Int64(StabsCmd.nsyms * sizeof(TStabSym)); end; end; function TDbgMachoDataSource.GetSectionIndex(const SectionName: AnsiString): Integer; var i : Integer; Name : AnsiString; begin //todo: hash-table for i := 0 to fFile.Sections.Count - 1 do begin with TMachoSection(fFile.sections[i]) do if is32 then Name := FixMachoName(sec32.sectname) else Name := FixMachoName(sec64.sectname); if Name = SectionName then begin Result := i; Exit; end; end; Result := -1; end; constructor TDbgMachoDataSource.Create(ASource: TStream; OwnSource: Boolean); begin fSource := ASource; fOwnSource := OwnSource; inherited Create(ASource, OwnSource); end; destructor TDbgMachoDataSource.Destroy; begin if Assigned(fFile) then fFile.Free; if fOwnSource then fSource.Free; inherited Destroy; end; {function TDbgMachoDataSource.SectionsCount: Integer; begin if not Assigned(fFile) then ReadFile; Result := fFile.Sections.Count; if isStabs then inc(Result, 2); end; function TDbgMachoDataSource.GetSection(Index: Integer; var Name: AnsiString; var Size: Int64): Boolean; var cnt : Integer; sstr : Boolean; const StabSectionName : array [Boolean] of AnsiString = (_stab, _stabstr); begin if not Assigned(fFile) then ReadFile; cnt := fFile.Sections.Count; if isStabs then inc(cnt, 2); Result := (Index >= 0) and (Index < cnt); if not Result then Exit; if Index < fFile.Sections.Count then begin with TMachoSection(fFile.sections[index]) do if is32 then begin Name := FixMachoName(sec32.sectname); Size := sec32.size; end else begin Name := FixMachoName(sec64.sectname); Size := sec64.size; end; end else begin sstr := Index = cnt - 1; Name := StabSectionName[sstr]; Result := GetStabSectionInfo(sstr, Size); end; end; function TDbgMachoDataSource.GetSectionData(index: Integer; outStream: TStream): Boolean; var ofs : Int64; sz : Int64; begin //todo: method will be removed if not Assigned(outStream) then begin Result := false; Exit; end; if not Assigned(fFile) then ReadFile; Result := (Index >= 0) and (Index < fFile.Sections.Count); if not Result then Exit; with TMachOsection(fFile.sections[index]) do begin if is32 then begin ofs := sec32.offset; sz := sec32.size; end else begin ofs := sec64.offset; sz := sec64.size; end; end; if ofs > 0 then begin fSource.Position:=ofs; outStream.CopyFrom(fSource, sz); end; end;} function TDbgMachoDataSource.GetSectionInfo(const SectionName: AnsiString; var Size: int64): Boolean; var idx : integer; stabstr : Boolean; dummy : int64; begin if not fileRead then ReadFile; stabstr := (SectionName = _stabstr); if stabstr or (SectionName = _stab) then Result := GetStabSectionInfo(stabstr, dummy, Size) else begin idx := GetSectionIndex(SectionName); Result := idx >= 0; if not Result then Exit; with TMachOsection(fFile.sections[idx]) do if is32 then Size := sec32.size else Size := sec64.size; end; end; function TDbgMachoDataSource.GetSectionData(const SectionName: AnsiString; Offset, Size: Int64; var Buf: array of byte): Int64; var idx : Integer; sofs : int64; ssize : int64; stabstr : Boolean; sz : Int64; s : TMachOsection; begin if not fileRead then ReadFile; Result := 0; stabstr := SectionName = _stabstr; if stabstr or (SectionName = _stab) then begin if not GetStabSectionInfo(stabstr, sofs, ssize) then Exit; end else begin idx := GetSectionIndex(SectionName); s := TMachOsection(fFile.sections[idx]); if s.is32 then begin ssize := s.sec32.size; sofs := s.sec32.offset; end else begin sofs := s.sec64.offset; ssize := s.sec64.size; end; end; sz := ssize - Offset; if sz < 0 then Exit; fSource.Position := sofs + Offset; Result := fSource.Read(Buf[0], sz); end; initialization RegisterDataSource ( TDbgMachoDataSource ); end.
{ 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; version 2 of the License. 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. } // Copyright (c) 2010 2011 2012 - J. Aldo G. de Freitas Junior {$mode objfpc} {$H+}{$M+} Unit SyncQueue; Interface Uses Classes, SysUtils, SyncObjs, ActorMessages, ContNrs, DateUtils; Type // Synchronized Queue TCustomSynchronizedQueue = Class Private fQueue : TObjectQueue; fSynchronizer : TMultiReadExclusiveWriteSynchronizer; fSignal : TEventObject; fActive : Boolean; Public Function WaitFor(Const aTimeout : Cardinal): TWaitResult; Function Count : Integer; Function AtLeast(Const aCount : Integer): Boolean; Procedure Push(Const aObject : TCustomActorMessage); Function Pop : TCustomActorMessage; Function Top : TCustomActorMessage; Procedure Recycle; Procedure Drop; Function WaitForMessage(Const aTimeout : Integer): Boolean; Function WaitForTransaction(Const aTransactionID : Int64; Const aTimeout : Integer): Boolean; Constructor Create; Destructor Destroy; Override; End; Implementation // TCustomSynchronizedQueue Function TCustomSynchronizedQueue.WaitFor(Const aTimeout : Cardinal): TWaitResult; Begin Result := fSignal.WaitFor(aTimeout); End; Function TCustomSynchronizedQueue.Count : Integer; Begin Try fSynchronizer.BeginRead; Result := fQueue.Count; Finally fSynchronizer.EndRead; End; End; Function TCustomSynchronizedQueue.AtLeast(Const aCount : Integer): Boolean; Begin Try fSynchronizer.BeginRead; Result := fQueue.AtLeast(aCount); Finally fSynchronizer.EndRead; End; End; Procedure TCustomSynchronizedQueue.Push(Const aObject : TCustomActorMessage); Begin Try fSynchronizer.BeginWrite; fQueue.Push(aObject); fSignal.SetEvent; Finally fSynchronizer.EndWrite; End; End; Function TCustomSynchronizedQueue.Pop: TCustomActorMessage; Begin Try fSynchronizer.BeginWrite; Result := (fQueue.Pop As TCustomActorMessage) Finally fSynchronizer.EndWrite; End; End; Function TCustomSynchronizedQueue.Top : TCustomActorMessage; Begin Try fSynchronizer.BeginRead; Result := (fQueue.Peek As TCustomActorMessage); Finally fSynchronizer.EndRead; End; End; Procedure TCustomSynchronizedQueue.Recycle; Begin Try fSynchronizer.BeginWrite; If fQueue.AtLeast(1) Then fQueue.Push(fQueue.Pop); Finally fSynchronizer.EndWrite; End; End; Procedure TCustomSynchronizedQueue.Drop; Begin Try fSynchronizer.BeginWrite; If Assigned(fQueue.Peek) Then (fQueue.Pop As TCustomActorMessage).Free; Finally fSynchronizer.EndWrite; End; End; Function TCustomSynchronizedQueue.WaitForMessage(Const aTimeout : Integer): Boolean; Var lStart : TDateTime; lTimeout : Integer; Procedure CalcTimeout; Begin lTimeout := MilliSecondsBetween(Now, lStart); End; Function NotTimeout: Boolean; Begin Result := (lTimeout <= aTimeout); End; Function SmallerTimeout: Integer; Begin Result := aTimeout Div 10; If Result < 1 Then Result := 1; End; Begin lStart := Now; CalcTimeout; While Not(AtLeast(1)) And NotTimeout Do Begin WaitFor(SmallerTimeout); CalcTimeout; End; Result := AtLeast(1); End; Function TCustomSynchronizedQueue.WaitForTransaction(Const aTransactionID : Int64; Const aTimeout : Integer): Boolean; Var lStart : TDateTime; lTimeout : Integer; Procedure CalcTimeout; Begin lTimeout := MilliSecondsBetween(Now, lStart); End; Function NotTimeout: Boolean; Begin // Debug WriteLn('lTimeout : ', lTimeout, ' aTimeout : ', aTimeout); Result := lTimeout <= aTimeout; End; Function NotMatch: Boolean; Begin If AtLeast(1) Then Result := Top.TransactionID <> aTransactionID Else Result := True; End; Function SmallerTimeout: Integer; Begin Result := aTimeout Div 10; If Result < 1 Then Result := 1; // Debug WriteLn('Waiting for ', Result, ' milliseconds...'); End; Begin // Debug WriteLn('TCustomSynchronizedQueue : Waiting for transaction'); lStart := Now; CalcTimeout; While NotMatch And NotTimeout Do Begin // Debug WriteLn('TCustomSynchronizedQueue : NotMatch ', NotMatch, ' NotTimeout ', NotTimeout); If AtLeast(1) Then // Debug WriteLn('TCustomSynchronizedQueue : ', Top.Source, '->', Top.Destination, ': ', Top.ClassName, ':', Top.TransactionID); Recycle; WaitFor(SmallerTimeout); CalcTimeout; End; Result := Not NotMatch; // Debug WriteLn('TCustomSynchronizedQueue : Found ? ', Result); End; Constructor TCustomSynchronizedQueue.Create; Begin Inherited Create; fQueue := TObjectQueue.Create; fSynchronizer := TMultiReadExclusiveWriteSynchronizer.Create; fSignal := TEventObject.Create(Nil, False, False, ''); fActive := True; End; Destructor TCustomSynchronizedQueue.Destroy; Begin Try While fQueue.AtLeast(1) Do fQueue.Pop.Free; Finally FreeAndNil(fQueue); FreeAndNil(fSynchronizer); FreeAndNil(fSignal); End; Inherited Destroy; End; End.
/// Sergii Sidorov 2013 @ Home/test /// /// Created: 26.02.2013 /// /// /// /// Description: Simple text file search engine. /// /// File scanning put into a TThread and /// whenver it search in new file,find text in file or finished work /// it send messages to the parent form, /// which then updates the memo with new results/changing status label/finish status /// (Parent form contains message handlers to work with it, see SearchStringMain.pas) /// unit SearchStringThread; interface uses Winapi.Messages, Winapi.Windows, Vcl.Forms, System.SysUtils, System.Variants, Vcl.FileCtrl, System.Classes, Math; const WM_FILE_SEARCH_STRING_FINISHED = WM_USER + 1; const WM_NEW_RESULT_ADD = WM_USER + 2; const WM_CURRENT_FILE_PATH_SHOW = WM_USER + 3; const FILE_SEARCH_BUFFER_SIZE = 1000000; function IsStringFindInFile(const FileNameStr, SearchStr : String) : Boolean; type TFileSearchStringThread = class (TThread) private DirPathStr : String; CurentFilePath : String; SearchTextStr : String; FResultFileName : String; ExtStr : String; MotherForm : TForm; MutexPause : THandle; IsSrchInSubDir : Boolean; procedure RecursiveDirectoryStrSearchProcesing(const DirPath: String); protected procedure Execute; override; public constructor Create (const Path, SearchStr, FileExtensions : String; const TheForm: TForm; const IsSrchInSubFolders : Boolean); property FileName : String read FResultFileName; property CurentPath : String read CurentFilePath; end; implementation constructor TFileSearchStringThread.Create (const Path, SearchStr, FileExtensions : String; const TheForm: TForm; const IsSrchInSubFolders : Boolean); begin inherited Create (True); DirPathStr := Path; SearchTextStr := SearchStr; MotherForm := TheForm; ExtStr := FileExtensions; IsSrchInSubDir := IsSrchInSubFolders; end; procedure TFileSearchStringThread.Execute; begin RecursiveDirectoryStrSearchProcesing(DirPathStr); SendMessage (MotherForm.Handle, WM_FILE_SEARCH_STRING_FINISHED, 0, 0); end; procedure TFileSearchStringThread.RecursiveDirectoryStrSearchProcesing(const DirPath: String);//(const aPath, aTmpl : String); const FILE_ATTRIBUTES = faAnyFile - faDirectory; const DIR_ATTRIBUTES = faDirectory; const FILE_SEARCH_MASK = '*.*'; var CurrentPath : String; FileSearchrRec : TSearchRec; begin CurrentPath := IncludeTrailingBackslash(DirPath); if FindFirst(CurrentPath + FILE_SEARCH_MASK, FILE_ATTRIBUTES, FileSearchrRec) = 0 then try repeat if self.Terminated = true then Exit; CurentFilePath := CurrentPath + FileSearchrRec.Name; SendMessage (MotherForm.Handle, WM_CURRENT_FILE_PATH_SHOW, 0, 0); if (ExtStr = '*.*') then begin if IsStringFindInFile(CurentFilePath, SearchTextStr) then begin FResultFileName := CurentFilePath; SendMessage (MotherForm.Handle, WM_NEW_RESULT_ADD, 0, 0); end; end else begin if AnsiPos(ExtractFileExt(FileSearchrRec.Name), ExtStr) > 0 then if IsStringFindInFile(CurentFilePath, SearchTextStr) then begin FResultFileName := CurentFilePath; SendMessage (MotherForm.Handle, WM_NEW_RESULT_ADD, 0, 0); end; end; until FindNext(FileSearchrRec) <> 0; finally FindClose(FileSearchrRec); end; if IsSrchInSubDir then if FindFirst(CurrentPath + FILE_SEARCH_MASK, DIR_ATTRIBUTES, FileSearchrRec) = 0 then try repeat if self.Terminated = true then Exit; CurentFilePath := CurrentPath + FileSearchrRec.Name; if ((FileSearchrRec.Attr and faDirectory) <> 0) and (FileSearchrRec.Name <> '.') and (FileSearchrRec.Name <> '..') then RecursiveDirectoryStrSearchProcesing(CurentFilePath); until FindNext(FileSearchrRec) <> 0; finally FindClose(FileSearchrRec); end; end; { Realization is not good: - ansiPos() - slow; - not using buffering - in case of litle memories will crash; - repeat 4 times for encoding foolproof; In order to load a Unicode text file we need to know its encoding. If the file has a Byte Order Mark (BOM), then we can simply use LoadFromFile(FileNameStr) If the file does not have a BOM then we need to explicitly specify the encoding, e.g. // StrList.LoadFromFile(FileNameStr, TEncoding.UTF8); //UTF-8 // StrList.LoadFromFile(FileNameStr, TEncoding.Unicode); //UTF-16 LE or UCS-2 LE // StrList.LoadFromFile(FileNameStr, TEncoding.BigEndianUnicode); //UTF-16 BE or UCS-2 BE } function IsStringFindInFile(const FileNameStr, SearchStr : String) : Boolean; var StrList : TStringList; i: Integer; begin Result := False; StrList := TStringList.Create; try StrList.LoadFromFile(FileNameStr); for i := StrList.Count-1 downto 0 do if ansiPos(SearchStr, StrList[i])<>0 then Result := True; //In case file doesn't have BOM for foolproof StrList.LoadFromFile(FileNameStr, TEncoding.UTF8); for i := StrList.Count-1 downto 0 do if ansiPos(SearchStr, StrList[i])<>0 then Result := True; StrList.LoadFromFile(FileNameStr, TEncoding.Unicode); for i := StrList.Count-1 downto 0 do if ansiPos(SearchStr, StrList[i])<>0 then Result := True; StrList.LoadFromFile(FileNameStr, TEncoding.BigEndianUnicode); for i := StrList.Count-1 downto 0 do if ansiPos(SearchStr, StrList[i])<>0 then Result := True; finally StrList.Free; end; end; end.
unit desktop.views.messagebox; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Effects, FMX.Objects, FMX.Layouts; type TMessageBox = class(TForm) Layout1: TLayout; Rectangle1: TRectangle; Rectangle2: TRectangle; ShadowEffect1: TShadowEffect; Layout2: TLayout; Button1: TButton; lblTitulo: TLabel; Layout3: TLayout; Layout4: TLayout; lblMensagem: TLabel; ButtonSim: TButton; ButtonNao: TButton; ButtonOk: TButton; procedure ButtonSimClick(Sender: TObject); procedure ButtonNaoClick(Sender: TObject); procedure ButtonOkClick(Sender: TObject); private FProcSim : TProc; FProcNao : TProc; FProcOK : TProc; FRender: TFMXObject; public procedure MensagemSimNao(aTitulo, aMensagem : string; aProcSim, aProcNao : TProc); overload; procedure MensagemSimNao(aTitulo, aMensagem : string; aProcSim : TProc); overload; procedure MensagemOk(aTitulo, aMensagem : string; aProcOk : TProc); property Render: TFMXObject read FRender write FRender; end; var MessageBox: TMessageBox; implementation {$R *.fmx} procedure TMessageBox.ButtonNaoClick(Sender: TObject); begin Layout1.Parent := nil; FProcNao; end; procedure TMessageBox.ButtonOkClick(Sender: TObject); begin Layout1.Parent := nil; FProcOk; end; procedure TMessageBox.ButtonSimClick(Sender: TObject); begin Layout1.Parent := nil; FProcSim; end; procedure TMessageBox.MensagemOk(aTitulo, aMensagem: string; aProcOk: TProc); begin ButtonOk.Visible := True; ButtonSim.Visible := False; ButtonNao.Visible := False; lblTitulo.Text := aTitulo; lblMensagem.Text := aMensagem; FProcOK := aProcOK; Layout1.Align := TAlignLayout.Contents; Layout1.Parent := FRender; end; procedure TMessageBox.MensagemSimNao(aTitulo, aMensagem: string; aProcSim: TProc); begin MensagemSimNao(aTitulo, aMensagem, aProcSim, procedure begin end); end; procedure TMessageBox.MensagemSimNao(aTitulo, aMensagem: string; aProcSim, aProcNao: TProc); begin ButtonOk.Visible := False; ButtonSim.Visible := True; ButtonNao.Visible := True; lblTitulo.Text := aTitulo; lblMensagem.Text := aMensagem; FProcSim := aProcSim; FProcNao := aProcNao; Layout1.Align := TAlignLayout.Contents; Layout1.Parent := FRender; end; end.
type Recurrent<T> = class first: T; next: Func<T,T>; count: integer; constructor (f: T; n: Func<T,T>; c: integer); begin first := f; next := n; count := c; end; function f(): IEnumerable<T>; begin result := Range(1, count).Select(x -> begin result := first; first := next(first); end) end; end; begin var a := new Recurrent<integer>(1, x -> x * 2, 10); writeln(a.f()); end.
unit Ntapi.UserEnv; { This file defines functions for working with user and AppContainer profiles. } interface {$WARN SYMBOL_PLATFORM OFF} {$MINENUMSIZE 4} uses Ntapi.WinNt, Ntapi.ntseapi, Ntapi.ntregapi, Ntapi.Versions, DelphiApi.Reflection, DelphiApi.DelayLoad; const userenv = 'userenv.dll'; var delayed_userenv: TDelayedLoadDll = (DllName: userenv); const // SDK::UserEnv.h - profile flags PT_TEMPORARY = $00000001; PT_ROAMING = $00000002; PT_MANDATORY = $00000004; PT_ROAMING_PREEXISTING = $00000008; // For annotations TOKEN_LOAD_PROFILE = TOKEN_QUERY or TOKEN_IMPERSONATE or TOKEN_DUPLICATE; type [FlagName(PT_TEMPORARY, 'Temporary')] [FlagName(PT_ROAMING, 'Roaming')] [FlagName(PT_MANDATORY, 'Mandatory')] [FlagName(PT_ROAMING_PREEXISTING, 'Roaming Pre-existing')] TProfileType = type Cardinal; // SDK::ProfInfo.h [SDKName('PROFILEINFOW')] TProfileInfoW = record [Bytes, Unlisted] Size: Cardinal; Flags: TProfileType; UserName: PWideChar; ProfilePath: PWideChar; DefaultPath: PWideChar; ServerName: PWideChar; PolicyPath: PWideChar; hProfile: THandle; end; PProfileInfoW = ^TProfileInfoW; // SDK::UserEnv.h [SetsLastError] [Result: ReleaseWith('UnloadUserProfile')] [RequiredPrivilege(SE_BACKUP_PRIVILEGE, rpAlways)] [RequiredPrivilege(SE_RESTORE_PRIVILEGE, rpAlways)] function LoadUserProfileW( [in, Access(TOKEN_LOAD_PROFILE)] hToken: THandle; [in, out] var ProfileInfo: TProfileInfoW ): LongBool; stdcall; external userenv delayed; var delayed_LoadUserProfileW: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'LoadUserProfileW'; ); // SDK::UserEnv.h [SetsLastError] [RequiredPrivilege(SE_BACKUP_PRIVILEGE, rpAlways)] [RequiredPrivilege(SE_RESTORE_PRIVILEGE, rpAlways)] function UnloadUserProfile( [in, Access(TOKEN_LOAD_PROFILE)] hToken: THandle; [in] hProfile: THandle ): LongBool; stdcall; external userenv delayed; var delayed_UnloadUserProfile: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'UnloadUserProfile'; ); // SDK::UserEnv.h [SetsLastError] function GetProfilesDirectoryW( [out, WritesTo] ProfileDir: PWideChar; [in, out, NumberOfElements] var Size: Cardinal ): LongBool; stdcall; external userenv delayed; var delayed_GetProfilesDirectoryW: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'GetProfilesDirectoryW'; ); // SDK::UserEnv.h [SetsLastError] function GetProfileType( [out] out Flags: TProfileType ): LongBool; stdcall; external userenv delayed; var delayed_GetProfileType: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'GetProfileType'; ); // SDK::UserEnv.h [SetsLastError] function CreateEnvironmentBlock( [out, ReleaseWith('RtlDestroyEnvironment')] out Environment: PEnvironment; [in, opt] hToken: THandle; [in] bInherit: LongBool ): LongBool; stdcall; external userenv delayed; var delayed_CreateEnvironmentBlock: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'CreateEnvironmentBlock'; ); // SDK::UserEnv.h [MinOSVersion(OsWin8)] [Result: ReleaseWith('DeleteAppContainerProfile')] function CreateAppContainerProfile( [in] AppContainerName: PWideChar; [in] DisplayName: PWideChar; [in] Description: PWideChar; [in, opt, ReadsFrom] const Capabilities: TArray<TSidAndAttributes>; [in, opt, NumberOfElements] CapabilityCount: Integer; [out, ReleaseWith('RtlFreeSid')] out SidAppContainerSid: PSid ): HResult; stdcall; external userenv delayed; var delayed_CreateAppContainerProfile: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'CreateAppContainerProfile'; ); // SDK::UserEnv.h [MinOSVersion(OsWin8)] function DeleteAppContainerProfile( [in] AppContainerName: PWideChar ): HResult; stdcall; external userenv delayed; var delayed_DeleteAppContainerProfile: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'DeleteAppContainerProfile'; ); // SDK::UserEnv.h [MinOSVersion(OsWin8)] function GetAppContainerRegistryLocation( [in] DesiredAccess: TRegKeyAccessMask; [out, ReleaseWith('NtClose')] out hAppContainerKey: THandle ): HResult; stdcall; external userenv delayed; var delayed_GetAppContainerRegistryLocation: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'GetAppContainerRegistryLocation'; ); // SDK::UserEnv.h [MinOSVersion(OsWin8)] function GetAppContainerFolderPath( [in] AppContainerSid: PWideChar; [out, ReleaseWith('CoTaskMemFree')] out Path: PWideChar ): HResult; stdcall; external userenv delayed; var delayed_GetAppContainerFolderPath: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'GetAppContainerFolderPath'; ); // MSDN [MinOSVersion(OsWin8)] function AppContainerDeriveSidFromMoniker( [in] Moniker: PWideChar; [out, ReleaseWith('RtlFreeSid')] out AppContainerSid: PSid ): HResult; stdcall; external kernelbase delayed; var delayed_AppContainerDeriveSidFromMoniker: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'AppContainerDeriveSidFromMoniker'; ); // rev [MinOSVersion(OsWin8)] function AppContainerFreeMemory( [in] Memory: Pointer ): Boolean; stdcall; external kernelbase delayed; var delayed_AppContainerFreeMemory: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'AppContainerFreeMemory'; ); // rev [MinOSVersion(OsWin8)] function AppContainerLookupMoniker( [in] Sid: PSid; [out, ReleaseWith('AppContainerFreeMemory')] out Moniker: PWideChar ): HResult; stdcall; external kernelbase delayed; var delayed_AppContainerLookupMoniker: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'AppContainerLookupMoniker'; ); // SDK::UserEnv.h [MinOSVersion(OsWin81)] function DeriveRestrictedAppContainerSidFromAppContainerSidAndRestrictedName( [in] AppContainerSid: PSid; [in] RestrictedAppContainerName: PWideChar; [out, ReleaseWith('RtlFreeSid')] out RestrictedAppContainerSid: PSid ): HResult; stdcall; external userenv delayed; var delayed_DeriveRestrictedAppContainerSidFromAppContainerSidAndRestrictedName: TDelayedLoadFunction = ( DllName: userenv; FunctionName: 'DeriveRestrictedAppContainerSidFromAppContainerSidAndRestrictedName'; ); implementation {$BOOLEVAL OFF} {$IFOPT R+}{$DEFINE R+}{$ENDIF} {$IFOPT Q+}{$DEFINE Q+}{$ENDIF} end.
unit AndroidTTS; interface uses System.SysUtils, System.Classes, AndroidAPI.JNIBridge, androidapi.JNI.TTS, FMX.Forms; type TAndroidTTS = class(TComponent) private ftts: JTextToSpeech; finit: Boolean; type TttsOnInitListener = class(TJavaLocal, JTextToSpeech_OnInitListener) private [weak] FParent : TAndroidTTS; public constructor Create(AParent : TAndroidTTS); procedure onInit(status: Integer); cdecl; end; private fttsListener : TttsOnInitListener; public procedure Init; constructor Create(AOwner: TComponent); override; procedure Speak(say: String); end; implementation uses FMX.Helpers.Android , FMX.Platform.Android , Androidapi.JNI.Os , Androidapi.JNI.GraphicsContentViewText , Androidapi.JNI.JavaTypes , Androidapi.Helpers , Androidapi.JNI.App ; { TAndroidTTS } constructor TAndroidTTS.Create(AOwner: TComponent); begin inherited; finit := False; Init; end; procedure TAndroidTTS.Init; begin Ftts := TJTextToSpeech.JavaClass.init(SharedActivityContext, fttsListener); end; procedure TAndroidTTS.Speak(say: String); begin ftts.speak(StringToJString(say), TJTextToSpeech.JavaClass.QUEUE_FLUSH, nil) end; { TAndroidTTS.TttsOnInitListener } constructor TAndroidTTS.TttsOnInitListener.Create(AParent: TAndroidTTS); begin Inherited Create; FParent := AParent; end; procedure TAndroidTTS.TttsOnInitListener.onInit(status: Integer); var Result : Integer; begin if (status = TJTextToSpeech.JavaClass.SUCCESS) then begin result := FParent.ftts.setLanguage(TJLocale.JavaClass.US); if (result = TJTextToSpeech.JavaClass.LANG_MISSING_DATA) or (result = TJTextToSpeech.JavaClass.LANG_NOT_SUPPORTED) then raise Exception.Create('This Language is not supported') else begin FParent.finit := true; end; end else raise Exception.Create('Initilization Failed!'); end; end.
{: @abstract(Implementação da base de um driver de protocolo.) @author(Fabio Luis Girardi papelhigienico@gmail.com) } unit ProtocolDriver; {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses SysUtils, Classes, CommPort, CommTypes, ProtocolTypes, protscanupdate, protscan, CrossEvent, Tag, syncobjs {$IFNDEF FPC}, Windows{$ENDIF}; type {: @abstract(Classe base para drivers de protocolo.) @author(Fabio Luis Girardi papelhigienico@gmail.com) Para você criar um novo driver, basta sobrescrever alguns métodos e funções, de acordo com as necessidades de seu driver de protocolo. São eles: @code(procedure DoAddTag(TagObj:TTag);) Sobrescreva esse procedimento para adicionar tags ao scan do driver. Faça as devidas verificações do tag nesse método e caso ele não seja um tag válido gere uma excessão para abortar a adição do tag no driver. Não esqueça de chamar o método herdado com @code(inherited DoAddTag(TagObj:TTag)) para adicionar o tag na classe base (@name). @code(procedure DoDelTag(TagObj:TTag);) Procedimento por remover tags do scan do driver. Não esqueça de chamar o método herdado com @code(inherited DoDelTag(TagObj:TTag)) para remover o tag da classe base (@name). @code(procedure DoTagChange(TagObj:TTag; Change:TChangeType; oldValue, newValue:Integer);) Procedimento usado para atualizar as informações do tag no driver. Caso alguma alteração torne o tag inconsistente para o seu driver, gere um excessão para abortar a mudança. @code(procedure DoScanRead(Sender:TObject; var NeedSleep:Integer);) Prodimento chamado para verificar se há algum tag necessitando ser lido. @code(procedure DoGetValue(TagObj:TTagRec; var values:TScanReadRec);) Procedimento chamado pelo driver para retornar os valores lidos que estão em algum gerenciador de memória para os tags. @code(function DoWrite(const tagrec:TTagRec; const Values:TArrayOfDouble; Sync:Boolean):TProtocolIOResult;) Executa as escritas de valores sincronas e assincronas dos tags. É este método que escreve os valores do tag no seu equipamento. @code(function DoRead (const tagrec:TTagRec; var Values:TArrayOfDouble; Sync:Boolean):TProtocolIOResult;) Executa as leituras sincronas e assincronas dos tags. É o método que vai buscar os valores no seu equipamento. @code(function SizeOfTag(Tag:TTag; isWrite:Boolean; var ProtocolTagType:TProtocolTagType):BYTE; ) Função responsável por informar o tamanho das palavras de dados em bits que o tag está referenciando. Sobrescrevendo esses métodos e rotinas, seu driver estará pronto. @bold(Veja a documentação detalhada de cada método para enteder como cada um funciona.) } TProtocolDriver = class(TComponent, IPortDriverEventNotification) private //Array de tags associados ao driver. PTags:array of TTag; //thread de execução do scan dos tags PScanReadThread:TScanThread; //Thread de execução de escritas PScanWriteThread:TScanThread; //thread de atualização dos pedidos dos tags PScanUpdateThread:TScanUpdate; //excessao caso o index to tag esteja fora dos limites procedure DoExceptionIndexOut(index:integer); //metodos para manipulação da lista de tags function GetTagCount:Integer; function GetTag(index:integer):TTag; function GetTagName(index:integer):String; function GetTagByName(Nome:String):TTag; //metodos chamados pelas threads procedure SafeScanRead(Sender:TObject; var NeedSleep:Integer); function SafeScanWrite(const TagRec:TTagRec; const values:TArrayOfDouble):TProtocolIOResult; procedure SafeGetValue(const TagRec:TTagRec; var values:TScanReadRec); function GetMultipleValues(var MultiValues:TArrayOfScanUpdateRec):Integer; procedure DoPortOpened(Sender: TObject); procedure DoPortClosed(Sender: TObject); procedure DoPortDisconnected(Sender: TObject); procedure DoPortRemoved(Sender:TObject); protected {: Flag que informa ao driver se ao menos uma variavel deve ser lida a cada ciclo de scan do driver. } PReadSomethingAlways:Boolean; //: Indica se o driver está pronto. FProtocolReady:Boolean; //: Armazena a ID (número único) do driver. PDriverID:Cardinal; //: Armazena o driver de porta associado a esse driver de protocolo. PCommPort:TCommPortDriver; //: Armazena o ID (número único) esses pedidos. FScanReadID, FScanWriteID, FReadID, FWriteID:Cardinal; //: Armazena a evento usado para parar as threads do driver de protocolo. FCritical:TCriticalSection; //: Forca a suspensão das threads. FPause:TCrossEvent; //: Armazena a seção crítica que protege areas comuns a muitas threads. PCallersCS:TCriticalSection; //: Array de ações pendentes. FPendingActions:TArrayOfObject; //: function GetPortOpenedEvent:TNotifyEvent; function GetPortClosedEvent:TNotifyEvent; function GetPortDisconnectedEvent:TNotifyEvent; function NotifyThisEvents:TNotifyThisEvents; virtual; procedure PortOpened(Sender: TObject); virtual; procedure PortClosed(Sender: TObject); virtual; procedure PortDisconnected(Sender: TObject); virtual; //: Configura a porta de comunicação que será usada pelo driver. procedure SetCommPort(CommPort:TCommPortDriver); {: Copia uma estrutura TIOPacket para outra. @param(Source TIOPacket. Estrutura de origem dos dados.) @param(Dest TIOPacket. Estrutura para onde os dados serão copiados.) } procedure CopyIOPacket(const Source:TIOPacket; var Dest:TIOPacket); {: Callback @bold(assincrono) que o driver de porta (TCommPortDriver) irá chamar para retornar os resultados de I/O. @param(Result TIOPacket. Estrutura com os dados de retorno da solicitação de I/O. @bold(É automaticamente destruida após retornar desse método.) } procedure CommPortCallBack(var Result:TIOPacket); virtual; {: Método chamado pelo driver de protocolo para adicionar um tag ao scan driver. @param(TagObj TTag. Tag a adicionar como dependente do driver.) @seealso(AddTag) } procedure DoAddTag(TagObj:TTag; TagValid:Boolean); virtual; {: Método chamado pelo driver de protocolo para remover um tag do scan do driver. @param(TagObj TTag. Tag dependente para remover do driver.) @seealso(RemoveTag) } procedure DoDelTag(TagObj:TTag); virtual; {: Método chamado pelas threads do driver de protocolo para realizar leitura dos tags a ele associado. @param(Sender TObject. Thread que está solicitando a varredura de atualização.) @param(NeedSleep Integer. Caso o procedimento não encontrou nada que precise ser lido, escreva nesse valor um valor negativo a forçar o scheduler do seu sistema operacional a executar outra thread ou um valor positivo para fazer a thread de scan dormir. O tempo que ela ficará dormindo é o valor que você escreve nessa variável. Caso o seu driver encontrou algum tag necessitando de atualização, retorne 0 (Zero).) } procedure DoScanRead(Sender:TObject; var NeedSleep:Integer); virtual; abstract; {: Método chamado pelas threads do driver de protocolo para atualizar os valores dos tags. @param(TagRec TTagRec. Estrutura com informações do tag.) @param(values TScanReadRec. Armazena os valores que serão enviados ao tag.) } procedure DoGetValue(TagRec:TTagRec; var values:TScanReadRec); virtual; abstract; {: Função chamada para escrever o valor de um tag (simples ou bloco) no equipamento. @param(tagrec TTagRec. Estrutura com informações do tag.) @param(Values TArrayOfDouble. Valores a serem escritos no equipamento.) @param(Sync Boolean. Flag que indica se a escrita deve ser sincrona ou assincrona.) @returns(TProtocolIOResult). } function DoWrite(const tagrec:TTagRec; const Values:TArrayOfDouble; Sync:Boolean):TProtocolIOResult; virtual; abstract; {: Função chamada para ler valores do equipamento. @param(tagrec TTagRec. Estrutura com informações do tag.) @param(Values TArrayOfDouble. Array que irá armazenar os valores lidos do equipamento.) @param(Sync Boolean. Flag que indica se a leitura deve ser sincrona ou assincrona.) @returns(TProtocolIOResult). } function DoRead (const tagrec:TTagRec; out Values:TArrayOfDouble; Sync:Boolean):TProtocolIOResult; virtual; abstract; //: Informa ao driver se ele deve ler algum tag a todo scan. property ReadSomethingAlways:Boolean read PReadSomethingAlways write PReadSomethingAlways default true; public //: @exclude constructor Create(AOwner:TComponent); override; //: @exclude procedure AfterConstruction; override; //: @exclude destructor Destroy; override; {: Adiciona um tag ao scan do driver. @param(Tag TTag. Tag a adicionar no scan do driver.) @raises(Exception caso alguma configuração esteja errada.) } procedure AddTag(TagObj:TTag); //: Chama o editor de tags do driver. procedure OpenTagEditor(OwnerOfNewTags:TComponent; InsertHook:TAddTagInEditorHook; CreateProc:TCreateTagProc); virtual; {: Remove um tag do scan do driver. @param(Tag TTag. Tag a remover do scan do driver.) } procedure RemoveTag(TagObj:TTag); {: Função que informa se o Tag está associado ao driver. @param(TagObj TTag. Tag que deseja saber se está associado ao driver.) @returns(@true caso o tag esteja associado ao driver.) } function IsMyTag(TagObj:TTag):Boolean; {: Função que retorna o tamanho em bits do registrador mapeado pelo tag. @param(Tag TTag. Tag que se deseja saber o tamanho do registrador.) @param(isWrite Boolean. Caso @true, informa o tamanho em bits usando as funções de escrita.) @returns(Tamanho em bits do registrador associado ou 0 (zero) caso falhe. } function SizeOfTag(Tag:TTag; isWrite:Boolean; var ProtocolTagType:TProtocolTagType):BYTE; virtual; abstract; {: Solicita a leitura por scan (assincrona) de um tag. @param(tagrec TTagRec. Estrutura com as informações do tag que se deseja ler.) @returns(Cardinal. Número único do pedido de leitura por scan.) } function ScanRead(const tagrec:TTagRec):Cardinal; {: Solicita a escrita por scan (assincrona) de um tag. @param(tagrec TTagRec. Estrutura com as informações do tag que se deseja escrever.) @param(Values TArrayOfDouble Conjunto de valores a escrever.) @returns(Cardinal. Número único do pedido de escrita por scan.) } function ScanWrite(const tagrec:TTagRec; const Values:TArrayOfDouble):Cardinal; {: Solicita a leitura (sincrona) de um tag. @param(tagrec TTagRec. Estrutura com as informações do tag que se deseja ler.) } procedure Read(const tagrec:TTagRec); {: Solicita uma escrita (sincrona) de um tag. @param(tagrec TTagRec. Estrutura com as informações do tag que se deseja escrever.) @param(Values TArrayOfDouble Conjunto de valores a escrever.) } procedure Write(const tagrec:TTagRec; const Values:TArrayOfDouble); //: Conta os tags dependentes desse driver de protocolo. property TagCount:Integer read GetTagCount; //: Lista cada tag dependente desse driver. property Tag[index:integer]:TTag read GetTag; //: Lista o nome de cada tag dependente desse driver. property TagName[index:integer]:String read GetTagName; //: Lista cada tag dependente desse driver usando o nome do tag como indice. property TagByName[Nome:String]:TTag read GetTagByName; published {: Driver de porta que será usado para realizar as operações de comunicação do protoloco. @seealso(TCommPortDriver) } property CommunicationPort:TCommPortDriver read PCommPort write SetCommPort nodefault; //: Identificação (número único) do driver. property DriverID:Cardinal read PDriverID; end; var {: Contador de drivers criados, usado para gerar nomes únicos dos eventos seções críticas e semaforos em ambiente Windows. @bold(Não altere o valor dessa variável.) } DriverCount:Cardinal; implementation uses PLCTag, hsstrings, Dialogs, math; //////////////////////////////////////////////////////////////////////////////// // inicio da implementação de TProtocolDriver //////////////////////////////////////////////////////////////////////////////// constructor TProtocolDriver.Create(AOwner:TComponent); begin inherited Create(AOwner); PDriverID := DriverCount; Inc(DriverCount); FProtocolReady:=true; FCritical := TCriticalSection.Create; FPause := TCrossEvent.Create(nil,true,true,''); PCallersCS := TCriticalSection.Create; PScanUpdateThread := TScanUpdate.Create(true, Self); PScanUpdateThread.Priority:=tpHighest; PScanUpdateThread.OnGetValue := SafeGetValue; PScanUpdateThread.OnScanTags := GetMultipleValues; PScanReadThread := TScanThread.Create(true, PScanUpdateThread); PScanReadThread.Priority:=tpTimeCritical; PScanReadThread.OnDoScanRead := SafeScanRead; PScanReadThread.OnDoScanWrite := nil; PScanWriteThread := TScanThread.Create(true, PScanUpdateThread); PScanWriteThread.Priority:=tpTimeCritical; PScanWriteThread.OnDoScanRead := nil; PScanWriteThread.OnDoScanWrite := SafeScanWrite; end; procedure TProtocolDriver.AfterConstruction; begin Inherited AfterConstruction; PScanUpdateThread.Resume; PScanReadThread.Resume; PScanReadThread.WaitInit; PScanWriteThread.Resume; PScanWriteThread.WaitInit; end; destructor TProtocolDriver.Destroy; var c:Integer; begin PScanReadThread.Destroy; PScanWriteThread.Destroy; PScanUpdateThread.Terminate; PScanUpdateThread.WaitFor; for c:=0 to High(PTags) do TPLCTag(PTags[c]).RemoveDriver; SetCommPort(nil); FCritical.Destroy; FPause.Destroy; SetLength(PTags,0); SetLength(FPendingActions,0); PCallersCS.Destroy; inherited Destroy; end; procedure TProtocolDriver.OpenTagEditor(OwnerOfNewTags:TComponent; InsertHook:TAddTagInEditorHook; CreateProc:TCreateTagProc); begin MessageDlg(SWithoutTagBuilder, mtError,[mbOK],0); end; procedure TProtocolDriver.SetCommPort(CommPort:TCommPortDriver); begin try FPause.ResetEvent; FCritical.Enter; //se for a mesma porta cai fora... if CommPort=PCommPort then exit; if PCommPort<>nil then begin if PCommPort.LockedBy=PDriverID then PCommPort.Unlock(PDriverID); PCommPort.DelProtocol(Self); end; if CommPort<>nil then begin CommPort.AddProtocol(Self); end; PCommPort := CommPort; finally FCritical.Leave; FPause.SetEvent; end; end; procedure TProtocolDriver.DoAddTag(TagObj:TTag; TagValid:Boolean); var c:integer; begin for c:=0 to High(PTags) do if PTags[c]=TagObj then raise Exception.Create(STagAlreadyRegiteredWithThisDriver); c:=Length(Ptags); SetLength(PTags,c+1); PTags[c] := TagObj; (TagObj as IScanableTagInterface).SetTagValidity(TagValid); end; procedure TProtocolDriver.DoDelTag(TagObj:TTag); var c:Integer; h:integer; found:boolean; begin if Length(PTags)<=0 then exit; h:=High(PTags); found := false; for c:=0 to h do if PTags[c]=TagObj then begin found := true; break; end; if found then begin (PTags[c] as IScanableTagInterface).SetTagValidity(false); PTags[c] := PTags[h]; SetLength(PTags,h); end; end; procedure TProtocolDriver.AddTag(TagObj:TTag); begin if not Supports(TagObj, IScanableTagInterface) then raise Exception.Create(SScanableNotSupported); try FPause.ResetEvent; FCritical.Enter; DoAddTag(TagObj,false); finally FCritical.Leave; FPause.SetEvent; end; end; procedure TProtocolDriver.RemoveTag(TagObj:TTag); begin try FPause.ResetEvent; FCritical.Enter; DoDelTag(TagObj); finally FCritical.Leave; FPause.SetEvent; end; end; procedure TProtocolDriver.DoExceptionIndexOut(index:integer); begin if (index>high(PTags)) then raise Exception.Create(SoutOfBounds); end; function TProtocolDriver.GetTagCount; begin //FCritical.Enter; try Result := Length(PTags); finally //FCritical.Leave; end; end; function TProtocolDriver.GetTag(index:integer):TTag; begin //FCritical.Enter; try DoExceptionIndexOut(index); result:=PTags[index]; finally //FCritical.Leave; end; end; function TProtocolDriver.GetTagName(index:integer):String; begin Result:=''; //FCritical.Enter; try DoExceptionIndexOut(index); result:=PTags[index].Name; finally //FCritical.Leave; end; end; function TProtocolDriver.GetTagByName(Nome:String):TTag; var c:Integer; begin Result := nil; //FCritical.Enter; try for c:=0 to High(PTags) do if PTags[c].Name = Nome then begin Result := PTags[c]; break; end; finally //FCritical.Leave; end; end; function TProtocolDriver.IsMyTag(TagObj:TTag):Boolean; var c:integer; begin Result := false; FCritical.Enter; try for c:=0 to High(PTags) do if TagObj=PTags[c] then begin Result := true; break; end; finally FCritical.Leave; end; end; function TProtocolDriver.ScanRead(const tagrec:TTagRec):Cardinal; begin try PCallersCS.Enter; //verifica se esta em edição, caso positivo evita o comando. if (csReading in ComponentState) or (csDestroying in ComponentState) then begin Result := 0; exit; end; //incrementa o contador de scanReads //zera o contador para evitar overflow; if FScanReadID=$FFFFFFFF then FScanReadID := 0 else inc(FScanReadID); //posta uma mensagem de Leitura por Scan if (PScanUpdateThread<>nil) then PScanUpdateThread.ScanRead(tagrec); Result := FScanReadID; finally PCallersCS.Leave; end; end; function TProtocolDriver.ScanWrite(const tagrec:TTagRec; const Values:TArrayOfDouble):Cardinal; var pkg:PScanWriteRec; begin try PCallersCS.Enter; //verifica se esta em edição, caso positivo evita o comando. if (csReading in ComponentState) or (csDestroying in ComponentState) then begin Result := 0; exit; end; //incrementa o contador de ScanWrites //zera o contador para evitar overflow; if FScanWriteID=$FFFFFFFF then FScanWriteID := 0 else inc(FScanWriteID); //cria um pacote de escrita por scan New(pkg); pkg^.SWID:=FScanReadID; //copia o TagRec Move(tagrec, pkg^.Tag, sizeof(TTagRec)); //copia os valores pkg^.ValuesToWrite := Values; pkg^.WriteResult:=ioNone; pkg^.ValueTimeStamp:=Now; //posta uma mensagem de Escrita por Scan if (PScanWriteThread<>nil) then begin PScanWriteThread.ScanWrite(pkg); {$IFDEF FPC} ThreadSwitch; {$ELSE} SwitchToThread; {$ENDIF} end; Result := FScanWriteID; finally PCallersCS.Leave; end; end; procedure TProtocolDriver.Read(const tagrec:TTagRec); var res:TProtocolIOResult; Values:TArrayOfDouble; begin try FPause.ResetEvent; FCritical.Enter; res := DoRead(tagrec,Values,true); if assigned(tagrec.CallBack) then tagrec.CallBack(Values,Now,tcRead,res,tagrec.RealOffset); finally FCritical.Leave; FPause.SetEvent; SetLength(Values,0); end; end; procedure TProtocolDriver.Write(const tagrec:TTagRec; const Values:TArrayOfDouble); var res:TProtocolIOResult; begin try FPause.ResetEvent; FCritical.Enter; res := DoWrite(tagrec,Values,true); if assigned(tagrec.CallBack) then tagrec.CallBack(Values,Now,tcWrite,res,tagrec.RealOffset); finally FCritical.Leave; FPause.SetEvent; end; end; procedure TProtocolDriver.CommPortCallBack(var Result:TIOPacket); begin if Result.Res2<>nil then CopyIOPacket(Result,PIOPacket(Result.Res2)^); if Result.res1 is TCrossEvent then TCrossEvent(Result.res1).SetEvent; end; procedure TProtocolDriver.CopyIOPacket(const Source:TIOPacket; var Dest:TIOPacket); begin Dest.PacketID := Source.PacketID; Dest.WriteIOResult := Source.WriteIOResult; Dest.ToWrite := Source.ToWrite; Dest.Wrote := Source.Wrote; Dest.WriteRetries := Source.WriteRetries; Dest.DelayBetweenCommand := Source.DelayBetweenCommand; Dest.ReadIOResult := Source.ReadIOResult; Dest.ToRead := Source.ToRead; Dest.Received := Source.Received; Dest.ReadRetries := Source.ReadRetries; SetLength(Dest.BufferToRead, 0); SetLength(Dest.BufferToWrite, 0); Dest.BufferToRead := Source.BufferToRead; Dest.BufferToWrite:= Source.BufferToWrite; Dest.Res1 := Source.Res1; Dest.Res2 := Source.Res2; end; procedure TProtocolDriver.SafeScanRead(Sender:TObject; var NeedSleep:Integer); begin try FPause.WaitFor($FFFFFFFF); FCritical.Enter; DoScanRead(Sender, NeedSleep); finally FCritical.Leave; end; end; function TProtocolDriver.SafeScanWrite(const TagRec:TTagRec; const values:TArrayOfDouble):TProtocolIOResult; begin try FPause.ResetEvent; FCritical.Enter; Result := DoWrite(TagRec,values,false) finally FCritical.Leave; FPause.SetEvent; end; end; procedure TProtocolDriver.SafeGetValue(const TagRec:TTagRec; var values:TScanReadRec); begin try FPause.ResetEvent; FCritical.Enter; DoGetValue(TagRec,values); finally FCritical.Leave; FPause.SetEvent; end; end; function TProtocolDriver.GetMultipleValues(var MultiValues:TArrayOfScanUpdateRec):Integer; var t, valueSet:Integer; first:Boolean; tagiface:IScanableTagInterface; tr:TTagRec; remainingMs:Int64; ScanReadRec:TScanReadRec; doneOne:Boolean; begin doneOne:=false; try Result:=0; valueSet:=-1; FPause.ResetEvent; FCritical.Enter; if (PCommPort=nil) or (not PCommPort.ReallyActive) then begin Result:=50; //forca espera de 50ms exit; end; for t:=0 to TagCount-1 do begin if Supports(Tag[t], IScanableTagInterface) then begin tagiface:=Tag[t] as IScanableTagInterface; if tagiface.IsValidTag then begin if PReadSomethingAlways then remainingMs:=tagiface.RemainingMiliseconds else remainingMs:=tagiface.RemainingMilisecondsForNextScan; //se o tempo restante é maior que zero if remainingMs>0 then begin if first then begin Result:=remainingMs; first:=false; end else Result := Min(remainingMs, Result); end else begin doneOne:=true; inc(valueSet); SetLength(MultiValues,valueSet+1); tagiface.BuildTagRec(tr,0,0); SetLength(ScanReadRec.Values, tr.Size); DoGetValue(tr, ScanReadRec); MultiValues[valueSet].LastResult:=ScanReadRec.LastQueryResult; MultiValues[valueSet].CallBack :=tr.CallBack; MultiValues[valueSet].Values :=ScanReadRec.Values; MultiValues[valueSet].ValueTimeStamp:=ScanReadRec.ValuesTimestamp; end; end; end; end; finally FCritical.Leave; if doneOne then Result:=0; FPause.SetEvent; end; end; function TProtocolDriver.GetPortOpenedEvent:TNotifyEvent; begin Result := DoPortOpened; end; function TProtocolDriver.GetPortClosedEvent:TNotifyEvent; begin Result := DoPortClosed; end; function TProtocolDriver.GetPortDisconnectedEvent:TNotifyEvent; begin Result := DoPortDisconnected; end; function TProtocolDriver.NotifyThisEvents:TNotifyThisEvents; begin Result:=[]; end; procedure TProtocolDriver.DoPortOpened(Sender: TObject); begin try FPause.ResetEvent; FCritical.Enter; PortOpened(Sender); finally FCritical.Leave; FPause.SetEvent; end; end; procedure TProtocolDriver.DoPortClosed(Sender: TObject); begin try FPause.ResetEvent; FCritical.Enter; PortClosed(Sender); finally FCritical.Leave; FPause.SetEvent; end; end; procedure TProtocolDriver.DoPortDisconnected(Sender: TObject); begin try FPause.ResetEvent; FCritical.Enter; PortDisconnected(Sender); finally FCritical.Leave; FPause.SetEvent; end; end; procedure TProtocolDriver.DoPortRemoved(Sender:TObject); begin if CommunicationPort=Sender then CommunicationPort:=nil; end; procedure TProtocolDriver.PortOpened(Sender: TObject); begin end; procedure TProtocolDriver.PortClosed(Sender: TObject); begin end; procedure TProtocolDriver.PortDisconnected(Sender: TObject); begin end; initialization DriverCount:=1; end.
unit UI.Base.Controlador.ConsultaDesktop; interface uses UI.Base.ConsultaPadrao, Framework.Interfaces.CRUD, Lib.Biblioteca, Framework.Controlador.ConsultaBase, Vcl.Forms, Lib.ResultFilter; type TControladorConsultaDesktop<T: Class> = class(TFrmConsultaPadrao) private FormularioCadastro: TFormClass; FResultFilter: TResultFilter; procedure SetResultFilter(const Value: TResultFilter); public property ResultFilter: TResultFilter read FResultFilter write SetResultFilter; procedure Inicializar(formCadastro: TFormClass); procedure Finalizar; procedure ExecutarInserirClick(sender: TObject); virtual; procedure ExecutarAlterarClick(sender: TObject); virtual; procedure ExecutarExcluirClick(sender: TObject); virtual; procedure ExecutarVisualizarClick(sender: TObject); virtual; procedure ExecutarPesquisarClick(sender: TObject); virtual; end; implementation uses System.SysUtils; { TControladorConsultaDesktop<T> } procedure TControladorConsultaDesktop<T>.ExecutarAlterarClick(sender: TObject); begin TControladorConsultaBase<T>.ExecutarAlterar(grDados,FormularioCadastro, ResultFilter); end; procedure TControladorConsultaDesktop<T>.ExecutarExcluirClick(sender: TObject); begin TControladorConsultaBase<T>.ExecutarExcluir(grDados,ResultFilter); end; procedure TControladorConsultaDesktop<T>.ExecutarInserirClick(sender: TObject); begin TControladorConsultaBase<T>.ExecutarInserir(grDados,FormularioCadastro,lblTotalDeRegistros); end; procedure TControladorConsultaDesktop<T>.ExecutarPesquisarClick(sender: TObject); begin TControladorConsultaBase<T>.ExecutaPesquisar(grDados,lblTotalDeRegistros, fResultFilter); end; procedure TControladorConsultaDesktop<T>.ExecutarVisualizarClick(sender: TObject); begin TControladorConsultaBase<T>.ExecutarVisualizar(grDados,FormularioCadastro); end; procedure TControladorConsultaDesktop<T>.Finalizar; begin if FResultFilter <> nil then FreeAndNil(FResultFilter); end; procedure TControladorConsultaDesktop<T>.Inicializar(formCadastro: TFormClass); begin FormularioCadastro := formCadastro; btnInserir.OnClick := ExecutarInserirClick; btnAlterar.OnClick := ExecutarAlterarClick; btnExcluir.OnClick := ExecutarExcluirClick; btnVisualizar.OnClick := ExecutarVisualizarClick; btnPesquisar.OnClick := ExecutarPesquisarClick; end; procedure TControladorConsultaDesktop<T>.SetResultFilter(const Value: TResultFilter); begin FResultFilter := Value; end; end.
unit Fraction; {Canboc Software Studio} interface type TFract=object numerator:integer; denominator:integer; {Procedures&Functions} procedure SetValue(const num,den:integer); procedure Reduce; end; function RealtoFract(decimal: double): TFract; implementation uses math; {Procedures&Functions of Object:TFract } procedure TFract.SetValue(const num,den:integer); begin numerator:=num; denominator:=den; end; procedure TFract.Reduce; var i,j,k:integer; begin i:=numerator; j:=denominator; repeat k:=i mod j; i:=j; j:=k; until k=0; numerator:=numerator div i; denominator:=denominator div i; end; {END} function RealtoFract(decimal: double): TFract; var intNumerator, intDenominator, intNegative: integer; dblFraction, dblDecimal, dblAccuracy, dblinteger: Double; ans:TFract; begin dblDecimal := decimal; if trunc(decimal) = decimal then ans.SetValue(trunc(decimal),1) else begin if abs(decimal) > 1 then begin dblinteger := trunc(decimal); dblDecimal := abs(frac(decimal)); end else dblDecimal := decimal; dblAccuracy := 0.00001; intNumerator := 0; intDenominator := 1; intNegative := 1; if dblDecimal < 0 then intNegative := -1; dblFraction := 0; while Abs(dblFraction - dblDecimal) > dblAccuracy do begin if Abs(dblFraction) > Abs(dblDecimal) then intDenominator := intDenominator + 1 else intNumerator := intNumerator + intNegative; dblFraction := intNumerator / intDenominator; end; RealtoFract.SetValue(intNumerator,intDenominator); end; end; function FMulti(const a,b:TFract):TFract; var ans:TFract; begin ans.SetValue(a.numerator*b.numerator,a.denominator*b.denominator); end; function FDiv(const a,b:TFract):TFract; var ans:TFract; begin ans.SetValue(a.numerator*b.denominator,a.denominator*b.numerator); end; function FPlus(const a,b:TFract):TFract; var ans:TFract; begin end; function FMinus(const a,b:TFract):TFract; var ans:TFract; begin end; end.
{*******************************************************} { } { Chesslink by } { Perpetual Chess LLC } { Copyright (c) 1995-2013 } { } {*******************************************************} unit CLMembershipType; interface uses SysUtils, contnrs, classes; type TCLMembershipType = class id: integer; name: string; end; TCLMembershipTypes = class(TObjectList) private function GetMembershipType(Index: integer): TCLMembershipType; public procedure CMD_MembershipTypeBegin(CMD: TStrings); procedure CMD_MembershipType(CMD: TStrings); function GetName(p_ID: integer): string; property MembershipType[Index: integer]: TCLMembershipType read GetMembershipType; default; end; var fCLMembershipTypes: TCLMembershipTypes; implementation //====================================================================================== { TCLMembershipTypes } procedure TCLMembershipTypes.CMD_MembershipType(CMD: TStrings); var mt: TCLMembershipType; begin if CMD.Count < 3 then exit; mt := TCLMembershipType.Create; mt.id := StrToInt(CMD[1]); mt.name := CMD[2]; Add(mt); end; //====================================================================================== procedure TCLMembershipTypes.CMD_MembershipTypeBegin(CMD: TStrings); begin Clear; end; //====================================================================================== function TCLMembershipTypes.GetMembershipType(Index: integer): TCLMembershipType; begin result := TCLMembershipType(Items[Index]); end; //====================================================================================== function TCLMembershipTypes.GetName(p_ID: integer): string; var i: integer; begin result := ''; for i := 0 to Count - 1 do if Self[i].id = p_ID then begin result := Self[i].name; exit; end; end; //====================================================================================== end.
UNIT STG_GAME; INTERFACE USES CRT,GRAPH,DOS,MOUSE; CONST HOCH=#72; RUNTER=#80; LINKS=#75; RECHTS=#77; ENTER=#13; ESC=#27; AN=TRUE; AUS=FALSE; CenterX=320; CenterY=240; PROCEDURE cursor(an_aus:boolean); {Cursor an aus schalten im Textmodus} PROCEDURE DEL_TASTATUR; {Löschte den Tastaturspeicehr} PROCEDURE WAIT(TASTE:CHAR); {Wartet auf eine bestimmte Taste} PROCEDURE LOAD_STG_GRAFIK(x,y:integer;datei_name:string); {STG GRAFIK LADEN} FUNCTION ToStr(Zahl: Longint): String; {Zahl in String umwandeln} FUNCTION INKEY:char; {Zeichen ohne Warten einlesen} PROCEDURE MOUSECHANGE; {Wartet auf das Bewegen der Maus} FUNCTION MOUSEOVER(x1,y1,x2,y2:word):boolean; {šberprft ob die Maus sich in einem bestimmten Rechteck(x1,y1,x2,y2) befindet} PROCEDURE BOX(zeile1,zeile2:string); {zeichnet eine MEssageBox} PROCEDURE WINDOWBOX(x,y,x1,y1:word;zeile_oben:string); {groáes fenster mit šberschrift } FUNCTION TIME:longint; {Zeit in Sekunden} PROCEDURE INPUT(VAR text:string); {readln Ersatz fr GrafikModus (mit Outtext)} IMPLEMENTATION PROCEDURE cursor(an_aus:boolean);{Quelle www.webplain.de} VAR regs:registers; BEGIN IF an_aus THEN BEGIN regs.ax := $0100; regs.cx := $0607; intr($10, regs); END ELSE BEGIN regs.ax := $0100; regs.cx := $2607; intr($10, regs); END; END; PROCEDURE DEL_TASTATUR;{Quelle www.webplain.de} BEGIN inline($FA); memw[$40 : $1A] := memw[$40 : $1C]; inline($FB); END; PROCEDURE WAIT (TASTE:CHAR); VAR EINGABE:CHAR; BEGIN REPEAT EINGABE:=READKEY; UNTIL EINGABE=TASTE; END; PROCEDURE LOAD_STG_GRAFIK(x,y:integer;datei_name:string); VAR Datei:Text; zeile:string; zeilen_nr:byte; i:integer; farbe,zeichen,fehler:integer; BEGIN Assign(Datei, datei_name); ReSET(Datei); zeilen_nr:=1; WHILE NOT(EOF(Datei)) DO BEGIN READLN(DATEI,zeile); FOR i:=1 TO LENGTH(zeile) DO BEGIN VAL(copy(zeile,i,1),zeichen,fehler); CASE zeichen OF 0: farbe:=0; {.. Schwarz ..} 1: farbe:=14; {.. Gelb ..} 2: farbe:=9; {.. hellblau ..} 3: farbe:=6 ; {.. braun ..} 4: farbe:=2 ; {.. grn ..} 5: farbe:=1 ; {.. blau ..} 6: farbe:=7; {.. hellgrau ..} 7: farbe:=8; {..dunkelgrau..} 8: farbe:=15; {.. weiß ..} 9: farbe:=4 {.. rot ..} END; PUTPIXEL(x+i,y+zeilen_nr,farbe); END; zeilen_nr:=zeilen_nr+1; END; Close(Datei); END; FUNCTION ToStr(Zahl: Longint): String; {Zahl in String umwandeln } VAR s: string[11]; BEGIN Str(Zahl, S); ToStr := S; END; FUNCTION INKEY; BEGIN IF KEYPRESSED THEN inkey:=readkey ELSE inkey:=' '; END; PROCEDURE MOUSECHANGE; VAR taste,x,y:word; taste1,x1,y1:word; CHANGE:boolean; BEGIN REPEAT MouseEVENT(taste,x,y); delay(5); MouseEVENT(taste1,x1,y1); CHANGE:=(X<>X1) AND (y<>y1) OR (TASTE<>TASTE1); UNTIL (CHANGE) OR (INKEY=ESC); END; FUNCTION MOUSEOVER(x1,y1,x2,y2:word):boolean; VAR x,y:word; BEGIN MOUSEGETPOS(x,y); MOUSEOVER:= (x>x1) AND (x<x2) AND (y>y1) AND (y<y2) END; PROCEDURE BOX; VAR Text_Settings: TextSettingsType; Fill_settings: FillSettingsType; alte_farbe:word; BEGIN GETFILLSETTINGS(FILL_SETTINGS); alte_farbe:=GETCOLOR; GETTEXTSETTINGS(Text_Settings); SETFILLSTYLE(1,1); SETTEXTSTYLE(DefaultFont,HORIZDIR,1); SETFILLSTYLE(1,15); BAR(198,198,422,252); SETFILLSTYLE(1,1); BAR(200,200,420,250); SETCOLOR(15); OUTTEXTXY(210,210,zeile1); OUTTEXTXY(210,230,zeile2); {Alten Zustand wiederherstellen} WITH TEXT_SETTINGS DO BEGIN SetTextJustify(Horiz, Vert); SetTextStyle(Font, Direction, CharSize); END; WITH Fill_SETTINGS DO SetFillStyle(Pattern, Color); SETCOLOR(alte_farbe); END; PROCEDURE WINDOWBOX; VAR Text_Settings: TextSettingsType; Fill_settings: FillSettingsType; alte_farbe:word; BEGIN GETFILLSETTINGS(FILL_SETTINGS); alte_farbe:=GETCOLOR; GETTEXTSETTINGS(Text_Settings); SETFILLSTYLE(1,1); SETTEXTSTYLE(DefaultFont,HORIZDIR,1); SETFILLSTYLE(1,15); BAR(x,y,x1,y1); SETFILLSTYLE(1,1); BAR(x+2,y+2,x1-2,y1-1); SETCOLOR(15); OUTTEXTXY(x+5,y+5,zeile_oben); {Alten Zustand wiederherstellen} WITH TEXT_SETTINGS DO BEGIN SetTextJustify(Horiz, Vert); SetTextStyle(Font, Direction, CharSize); END; WITH Fill_SETTINGS DO SetFillStyle(Pattern, Color); SETCOLOR(alte_farbe); END; FUNCTION TIME:longint; VAR std,min,sec,hsec:word; BEGIN GETTIME(std,min,sec,hsec); TIME:=std*60*60+min*60+sec; END; PROCEDURE INPUT(VAR text:string); VAR taste:char; BEGIN text:=''; WHILE NOT(TASTE=ENTER) DO BEGIN taste:=readkey; IF NOT(TASTE=ENTER) THEN BEGIN text:=text+taste; OUTTEXT(taste); END; END; END; BEGIN END.
unit UCyphers; interface uses System.SysUtils, IdCoderMIME, IdCoderQuotedPrintable, LbCipher, LbClass; const C1 = 4512; C2 = 5627; type TCyphers = class private public class function SimpleEncrypt(Text: string; var code: integer): string; class function SimpleDecrypt(Text: string; var code: integer): string; class function HexEncrypt(InString: string; var Key: word): string; class function HexDecrypt(InString: string; var Key: word): string; class function BlowfishEncrypt128(const InString, Pass : string): string; class function BlowfishDecrypt128(const InString, Pass : string): string; class function DesEncrypt64(const InString, Pass: string): string; class function DesDecrypt64(const InString, Pass: string): string; class function TripleDesEncrypt128(const InString, Pass: string): string; class function TripleDESDecrypt128(const InString, Pass: string): string; class function RDLEncrypt256(const InString, Pass: string): string; class function RDLDecrypt256(const InString, Pass: string): string; class function RDLEncrypt192(const InString, Pass: string): string; class function RDLDecrypt192(const InString, Pass: string): string; class function RDLEncrypt128(const InString, Pass: string): string; class function RDLDecrypt128(const InString, Pass: string): string; class procedure RDLEncryptFile256(const InputFile, OutputFile: string); class procedure RDLDecryptFile256(const InputFile, OutputFile: string); class procedure TripleDESEncryptFile128(const InFile, OutFile : string); class procedure TripleDESDecryptFile128(const InFile, OutFile : string); class function Base64Encrypt(const InString : string): string; class function Base64Decrypt(const InString : string): string; class function QuotedPrintableEncrypt(const InString : string): string; class function QuotedPrintableDecrypt(const InString : string): string; end; implementation { TCyphers } class function TCyphers.Base64Encrypt(const InString: string): string; var IdEncBase64: TIdEncoderMIME; begin IdEncBase64 := TIdEncoderMIME.Create(nil); try Result := IdEncBase64.EncodeString(InString); finally IdEncBase64.Free; end; end; class function TCyphers.Base64Decrypt(const InString: string): string; var IdDecBase64: TIdDecoderMIME; begin IdDecBase64 := TIdDecoderMIME.Create(nil); try Result := IdDecBase64.DecodeString(InString) finally IdDecBase64.Free; end; end; class function TCyphers.QuotedPrintableDecrypt(const InString: string): string; var IdEncQuotePrintable: TIdEncoderQuotedPrintable; begin IdEncQuotePrintable := TIdEncoderQuotedPrintable.Create(nil); try Result := IdEncQuotePrintable.EncodeString(InString); finally IdEncQuotePrintable.Free; end; end; class function TCyphers.QuotedPrintableEncrypt(const InString: string): string; var IdDecQuotedPrintable: TIdDecoderQuotedPrintable; begin IdDecQuotedPrintable := TIdDecoderQuotedPrintable.Create(nil); try Result := IdDecQuotedPrintable.DecodeString(InString) finally IdDecQuotedPrintable.Free; end; end; class function TCyphers.BlowfishDecrypt128(const InString, Pass: string): string; var IdBlowfish: TLbBlowfish; begin IdBlowfish := TLbBlowfish.Create(nil); try IdBlowfish.CipherMode := cmCBC; IdBlowfish.GenerateKey(Pass); Result := IdBlowfish.DecryptString(InString); finally IdBlowfish.Free; end; end; class function TCyphers.BlowfishEncrypt128(const InString, Pass: string): string; var IdBlowfish: TLbBlowfish; begin IdBlowfish := TLbBlowfish.Create(nil); try IdBlowfish.CipherMode := cmCBC; IdBlowfish.GenerateKey(Pass); Result := IdBlowfish.EncryptString(InString); finally IdBlowfish.Free; end; end; class function TCyphers.DesDecrypt64(const InString, Pass: string): string; var LbDES: TLbDES; begin LbDes := TLBDES.Create(nil); try LbDES.GenerateKey(Pass); Result := LbDES.DecryptString(InString) finally LbDES.Free; end; end; class function TCyphers.DesEncrypt64(const InString, Pass: string): string; var LbDES: TLbDES; begin LbDes := TLBDES.Create(nil); try LbDES.GenerateKey(Pass); Result := LbDES.EncryptString(InString) finally LbDES.Free; end; end; class function TCyphers.HexDecrypt(InString: string; var Key: word): string; var I: byte; x: char; begin //Descriptografia hexadecimal de 128 bits Result := ''; i := 1; while (i < length(InString)) do begin x := char(StrToInt('$' + copy(InString,i,2))); Result := result + IntToStr((byte(x) xor (key shr 8))); Key := (byte(x) + key) * C1 + C2; Inc(i,2); end; end; class function TCyphers.HexEncrypt(InString: string; var Key: word): string; var I: byte; begin //Criptografia hexadecimal de 128 bits Result := ''; for i := 1 to Length(InString) do begin Result := Result + IntToHex(byte(char(byte(InString[i]) xor (key shr 8))),2); Key := (byte(char(byte(InString[i]) xor (key shr 8))) + Key) * C1 + C2; end; end; class function TCyphers.RDLDecrypt128(const InString, Pass: string): string; var LbRijndael: TLbRijndael; begin LbRijndael := TLbRijndael.Create(nil); try LbRijndael.KeySize := ks128; LbRijndael.CipherMode := cmECB; LbRijndael.GenerateKey(Pass); Result := LbRijndael.DecryptString(InString); finally LbRijndael.Free; end; end; class function TCyphers.RDLDecrypt192(const InString, Pass: string): string; var LbRijndael: TLbRijndael; begin LbRijndael := TLbRijndael.Create(nil); try LbRijndael.KeySize := ks192; LbRijndael.CipherMode := cmECB; LbRijndael.GenerateKey(Pass); Result := LbRijndael.DecryptString(InString); finally LbRijndael.Free; end; end; class function TCyphers.RDLDecrypt256(const InString, Pass: string): string; var LbRijndael: TLbRijndael; begin LbRijndael := TLbRijndael.Create(nil); try LbRijndael.KeySize := ks256; LbRijndael.CipherMode := cmECB; LbRijndael.GenerateKey(Pass); Result := LbRijndael.DecryptString(InString); finally LbRijndael.Free; end; end; class procedure TCyphers.RDLDecryptFile256(const InputFile, OutputFile: string); var LbRijndael: TLbRijndael; begin LbRijndael := TLbRijndael.Create(nil); try LbRijndael.KeySize := ks256; LbRijndael.CipherMode := cmECB; LbRijndael.DecryptFile(InputFile, OutputFile); finally LbRijndael.Free; end end; class function TCyphers.RDLEncrypt128(const InString, Pass: string): string; var LbRijndael: TLbRijndael; begin LbRijndael := TLbRijndael.Create(nil); try LbRijndael.KeySize := ks128; LbRijndael.CipherMode := cmECB; LbRijndael.GenerateKey(Pass); Result := LbRijndael.EncryptString(InString); finally LbRijndael.Free; end; end; class function TCyphers.RDLEncrypt192(const InString, Pass: string): string; var LbRijndael: TLbRijndael; begin LbRijndael := TLbRijndael.Create(nil); try LbRijndael.KeySize := ks192; LbRijndael.CipherMode := cmECB; LbRijndael.GenerateKey(Pass); Result := LbRijndael.EncryptString(InString); finally LbRijndael.Free; end; end; class function TCyphers.RDLEncrypt256(const InString, Pass: string): string; var LbRijndael: TLbRijndael; begin LbRijndael := TLbRijndael.Create(nil); try LbRijndael.KeySize := ks256; LbRijndael.CipherMode := cmECB; LbRijndael.GenerateKey(Pass); Result := LbRijndael.EncryptString(InString); finally LbRijndael.Free; end; end; class procedure TCyphers.RDLEncryptFile256(const InputFile, OutputFile: string); var LbRijndael: TLbRijndael; begin LbRijndael := TLbRijndael.Create(nil); try LbRijndael.KeySize := ks256; LbRijndael.CipherMode := cmECB; LbRijndael.EncryptFile(InputFile, OutputFile); finally LbRijndael.Free; end; end; class function TCyphers.SimpleDecrypt(Text: string; var code: integer): string; { Implementa uma descriptografia simples. Esta função permite alterar o algoritmo de encriptação a partir do valor passado em code. } var ResultStr: string; Temp: char; I, DecryptIndex: integer; begin ResultStr := ''; Temp := ' '; for I := 1