text stringlengths 14 6.51M |
|---|
unit uthImageMove;
interface
uses
Classes,ExtCtrls,forms;
type
TFlowMove = (fmToRight,fmToLeft);
TTHImageMove = class(TThread)
private
FFlowMove: TFlowMove;
FImage: TImage;
FMaxLeft: integer;
FMinLeft: integer;
FisRun: Boolean;
procedure startMove;
{ Private declarations }
protected
procedure Execute; override;
public
constructor Create;
property Image: TImage read FImage write FImage;
property FlowMove: TFlowMove read FFlowMove write FFlowMove;
property MaxLeft: integer read FMaxLeft write FMaxLeft;
property MinLeft: integer read FMinLeft write FMinLeft;
property isRun: Boolean read FisRun write FisRun;
procedure Stop;
end;
implementation
{ TTHImageMove }
constructor TTHImageMove.Create;
begin
inherited Create(True);
FreeOnTerminate := True;
FFlowMove := fmToRight;
FMaxLeft := -1;
FMinLeft := -1;
FisRun := False;
end;
procedure TTHImageMove.Execute;
begin
while (True) do
begin
FisRun := True;
Synchronize(startMove);
sleep(100);
Application.ProcessMessages;
if Terminated then
begin
FisRun := False;
Break;
end;
end;
end;
procedure TTHImageMove.startMove;
begin
case FFlowMove of
fmToRight:
begin
if FMaxLeft > -1 then
begin
if Image.Left >= FMaxLeft then
exit;
end;
Image.Left := Image.Left + 1;
end;
fmToLeft:
begin
if FMinLeft > -1 then
begin
if Image.Left <= FMinLeft then
exit;
end;
Image.Left := Image.Left - 1;
end;
end;
end;
procedure TTHImageMove.Stop;
begin
Terminate;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXTransportFilter;
interface
uses
Data.DBXCommon,
Data.DBXJSON,
Data.DBXTransport,
System.SysUtils;
type
/// <summary> Implements TCP communication where use can insert filters to process (compress, encrypt) the byte flow
///
/// </summary>
TDBXFilterSocketChannel = class(TDbxChannel)
public
function HasLeftover: Boolean; virtual;
/// <summary> Constructor with socket id
///
/// </summary>
constructor Create; overload;
/// <summary> Constructor when id and filter list are known
///
/// </summary>
/// <param name="list">- filter list</param>
constructor Create(const List: TTransportFilterCollection); overload;
/// <summary> Releases filter list objects, if owned
/// </summary>
destructor Destroy; override;
/// <summary> Returns true if filters are defined
///
/// </summary>
/// <returns>true if filters are present</returns>
function HasFilters: Boolean; virtual;
/// <summary> Reads byte[], implements handshake protocol
/// </summary>
function Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
/// <summary> Write data, implements handshake protocol
/// </summary>
function Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
procedure Close; override;
procedure Open; override;
protected
function GetFlag: Integer; virtual;
/// <summary> Sets the delegate channel value
///
/// </summary>
/// <param name="channel">DbxChannel instance, never null</param>
procedure SetChannel(const Channel: TDbxChannel); virtual;
/// <summary> Filter list setter
///
/// </summary>
/// <param name="filters">filter list, never null</param>
procedure SetFilterList(const Filters: TTransportFilterCollection); virtual;
function GetChannelInfo: TDBXChannelInfo; override;
function GetDBXProperties: TDBXProperties; override;
procedure SetDBXProperties(const Properties: TDBXProperties); override;
///<summary>Specifies if there is an open connection or not.</summary>
///<returns>False if connection is active, True if connection is not active.</returns>
function IsConnectionLost: Boolean; override;
private
function ConsumeLeftover(const Data: TBytes; const Offset: Integer; const Len: Integer): Integer;
procedure SetLeftover(const Data: TBytes; const Offset: Integer);
/// <summary> Returns the JSONObject representing the filter parameters
///
/// </summary>
/// <param name="onlyPublicKeyCryptographs">boolean - true if the list should consists
/// of public key cryptograph filters</param>
/// <returns>JSONObject, never null</returns>
function FilterParameters(const OnlyPublicKeyCryptographs: Boolean): TJSONObject;
/// <summary> Restores the client (usually) filter list from the server byte array.
/// </summary>
/// <remarks>
/// Performs merge is the list exists
///
/// </remarks>
/// <param name="data">server byte array</param>
/// <param name="pos">position to start parsing</param>
/// <returns>true if the filter list was properly restored</returns>
function RestoreFilterList(const Data: TBytes; const Pos: Integer): Boolean;
/// <summary> Fills the buffer with expected number of bytes
///
/// </summary>
/// <param name="buffer">data to be filled</param>
/// <param name="offset">from position</param>
/// <param name="count">expected number of bytes</param>
/// <returns>false if the operation cannot be completed - no more data are available</returns>
function FillBuffer(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Boolean;
/// <summary> Creates the JSON message associated with the filter id and parameters
///
/// The regular filters are to be encrypted by the public key cryptographs if
/// present.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="onlyPublickKeyCryptographs">: boolean - true if only the public key
/// cryptograph filters are to be sent</param>
function SendFilterParameters(const OnlyPublickKeyCryptographs: Boolean): Integer;
/// <summary> Reads and set the confederate filter parameters
///
/// </summary>
/// <param name="publicKeyEncrypted">: true if the filter parameters were encrypted</param>
function ReceiveAndSetConfederateFilterParameters(const PublicKeyEncrypted: Boolean): Integer;
/// <summary> Returns filtered data
///
/// </summary>
/// <param name="data">: byte[] raw data</param>
/// <param name="count">: size of raw data</param>
/// <param name="onlyPublikKeyCryptographs">: boolean - true if only the public key
/// cryptographs filters are to be used</param>
/// <returns>: byte[] processed data to be written</returns>
function FilterDataRead(const Data: TBytes; const Count: Integer; const OnlyPublikKeyCryptographs: Boolean): TBytes;
/// <summary> Filters clear data
///
/// </summary>
/// <param name="data">: byte[] byte array of raw data</param>
/// <param name="count">: number of bytes to processed</param>
/// <param name="onlyPublikKeyCryptographs">: boolean - true if only the public key
/// cryptographs filters are to be used for filtering</param>
/// <returns>: byte array of processed data</returns>
function FilterDataWrite(const Data: TBytes; const Count: Integer; const OnlyPublikKeyCryptographs: Boolean): TBytes;
public
/// <summary>Used internally to indicate that no decision on the filter status
/// of the byte stream has been made yet.</summary>
class var Pendant: Integer;
class var Filtered: Integer;
class var Regular: Integer;
private
/// <summary> Filter list, from DSServerTransport
/// </summary>
FFilterList: TTransportFilterCollection;
/// <summary> True if filter list is owned by the instance.
/// </summary>
/// <remarks>
///
/// This is true usually for client instances where filters are created by handshake protocol.
/// </remarks>
FOwnFilterList: Boolean;
/// <summary> data buffer used by the handshake protocol
/// </summary>
FHeaderData: TBytes;
/// <summary>DbxChannel delegate instance.</summary>
/// <remarks>It should be instantiated before any other DbxChannel API is called.
/// The instance assumes ownership, so it will be freed on destroy.
/// </remarks>
FDelegate: TDbxChannel;
/// <summary> Status flag:
/// PENDANT: no decision; REGULAR: "as is" byte stream; FILTERED: filtered byte stream
/// </summary>
FFilterFlag: Integer;
FLeftover: TBytes;
FLeftoverPos: Integer;
public
property Flag: Integer read GetFlag;
/// <summary> Sets the delegate channel value
///
/// </summary>
property Channel: TDbxChannel read FDelegate write SetChannel;
/// <summary> Filter list setter
///
/// </summary>
property FilterList: TTransportFilterCollection write SetFilterList;
end;
implementation
uses
Data.DBXPlatform,
Data.DBXClientResStrs
;
function TDBXFilterSocketChannel.GetFlag: Integer;
begin
Result := FFilterFlag;
end;
function TDBXFilterSocketChannel.HasLeftover: Boolean;
begin
Result := FLeftover <> nil;
end;
function TDBXFilterSocketChannel.IsConnectionLost: Boolean;
begin
Result := Assigned(FDelegate) and FDelegate.ConnectionLost;
end;
function TDBXFilterSocketChannel.ConsumeLeftover(const Data: TBytes; const Offset: Integer; const Len: Integer): Integer;
var
Size: Integer;
begin
Size := Length(FLeftover) - FLeftoverPos;
if Size > Len then
Size := Len;
TDBXPlatform.CopyByteArray(FLeftover, FLeftoverPos, Data, Offset, Size);
FLeftoverPos := FLeftoverPos + Size;
if FLeftoverPos >= Length(FLeftover) then
begin
FLeftoverPos := 0;
FLeftover := nil;
end;
Result := Size;
end;
procedure TDBXFilterSocketChannel.SetLeftover(const Data: TBytes; const Offset: Integer);
begin
FLeftover := Data;
FLeftoverPos := Offset;
end;
function TDBXFilterSocketChannel.FilterParameters(const OnlyPublicKeyCryptographs: Boolean): TJSONObject;
var
JsonObj: TJSONObject;
I: Integer;
Filter: TTransportFilter;
Pair: TJSONPair;
FilterName: TJSONString;
Params: TJSONObject;
ParamNames: TDBXStringArray;
J: Integer;
Val: UnicodeString;
begin
JsonObj := TJSONObject.Create;
if (FFilterList <> nil) and (FFilterList.Count > 0) then
for i := 0 to FFilterList.Count - 1 do
begin
Filter := TTransportFilter(FFilterList.GetFilter(I));
if Filter.PublicKeyCryptograph = OnlyPublicKeyCryptographs then
begin
Pair := TJSONPair.Create;
JsonObj.AddPair(Pair);
FilterName := TJSONString.Create(Filter.Id);
Pair.JsonString := FilterName;
Params := TJSONObject.Create;
Pair.JsonValue := Params;
ParamNames := Filter.Parameters;
if (ParamNames <> nil) and (Length(ParamNames) > 0) then
for j := 0 to Length(ParamNames) - 1 do
begin
Pair := TJSONPair.Create;
Pair.JsonString := TJSONString.Create(ParamNames[J]);
Val := Filter.GetParameterValue(ParamNames[J]);
if not StringIsNil(Val) then
Pair.JsonValue := TJSONString.Create(Val)
else
Pair.JsonValue := TJSONNull.Create;
Params.AddPair(Pair);
end;
end;
end;
Result := JsonObj;
end;
function TDBXFilterSocketChannel.RestoreFilterList(const Data: TBytes; const Pos: Integer): Boolean;
var
FilterCreated: Boolean;
Obj: TJSONObject;
I: Integer;
Pair: TJSONPair;
FilterName: UnicodeString;
Filter: TTransportFilter;
Params: TJSONObject;
J: Integer;
ParamName: UnicodeString;
Value: TJSONValue;
ParamValue: UnicodeString;
begin
FilterCreated := False;
if FFilterList = nil then
begin
FFilterList := TTransportFilterCollection.Create;
FOwnFilterList := True;
end;
Obj := TJSONObject.Create;
if Obj.Parse(Data, Pos) <= 0 then
begin
Obj.Free;
Exit(False);
end;
for i := Obj.Size - 1 downto 0 do
begin
Pair := Obj.Get(I);
FilterName := Pair.JsonString.Value;
Filter := TTransportFilter(FFilterList.GetFilter(FilterName));
if Filter = nil then
begin
Filter := TTransportFilterFactory.CreateFilter(FilterName);
if Filter = nil then
begin
Obj.Free;
raise TDBXError.Create(0, Format(SFilterNotRegistered, [FilterName]));
end;
FilterCreated := True;
end;
Filter.ServerInstance := False;
Filter.FilterCollection := FFilterList;
Filter.StartHandshake;
Params := TJSONObject(Pair.JsonValue);
for j := 0 to Params.Size - 1 do
begin
Pair := Params.Get(J);
ParamName := Pair.JsonString.Value;
Value := Pair.JsonValue;
if Value.Null then
ParamValue := NullString
else
ParamValue := (TJSONString(Value)).Value;
if not Filter.SetConfederateParameter(ParamName, ParamValue) then
begin
Obj.Free;
raise TDBXError.Create(0, Format(SInvalidFilterParameter, [Filter.Id,ParamName,ParamValue]));
end;
end;
if FilterCreated then
FFilterList.AddFilter(Filter);
end;
Obj.Free;
Result := True;
end;
constructor TDBXFilterSocketChannel.Create;
begin
Pendant := 0;
Filtered := 1;
Regular := -1;
inherited Create;
SetLength(FHeaderData,TTransportFilterTools.HeaderLen);
FFilterFlag := Pendant;
FOwnFilterList := False;
end;
constructor TDBXFilterSocketChannel.Create(const List: TTransportFilterCollection);
begin
Pendant := 0;
Filtered := 1;
Regular := -1;
Create;
FilterList := List;
end;
procedure TDBXFilterSocketChannel.SetChannel(const Channel: TDbxChannel);
begin
FDelegate := Channel;
end;
destructor TDBXFilterSocketChannel.Destroy;
var
I: Integer;
begin
if FOwnFilterList then
begin
if FFilterList <> nil then
begin
for i := FFilterList.Count - 1 downto 0 do
FFilterList.GetItem(I).Free;
FreeAndNil(FFilterList);
end;
end;
if FDelegate <> nil then
begin
FDelegate.Free;
FDelegate := nil;
end;
inherited Destroy;
end;
procedure TDBXFilterSocketChannel.SetFilterList(const Filters: TTransportFilterCollection);
var
Filter: TTransportFilter;
SourceFilter: TTransportFilter;
UserParametersName: TDBXStringArray;
I: Integer;
J: Integer;
begin
if FOwnFilterList and (FFilterList <> nil) then
FFilterList.Free;
FFilterList := TTransportFilterCollection.Create;
FOwnFilterList := True;
for i := 0 to Filters.Count - 1 do
begin
SourceFilter := Filters.GetFilter(I);
Filter := TTransportFilterFactory.CreateFilter(SourceFilter.Id);
UserParametersName := SourceFilter.UserParameters;
for j := 0 to Length(UserParametersName) - 1 do
Filter.SetParameterValue(UserParametersName[J], SourceFilter.GetParameterValue(UserParametersName[J]));
FFilterList.AddFilter(Filter);
end;
end;
function TDBXFilterSocketChannel.HasFilters: Boolean;
begin
Result := (FFilterList <> nil) and (FFilterList.Count <> 0);
end;
function TDBXFilterSocketChannel.FillBuffer(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Boolean;
var
Len: Integer;
Size: Integer;
begin
Len := 0;
while Len < Count do
begin
Size := FDelegate.Read(Buffer, Offset + Len, Count - Len);
if Size = -1 then
Exit(False);
Len := Len + Size;
end;
Assert(Len=Count);
Result := True;
end;
function TDBXFilterSocketChannel.Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer;
var
PkcFiltersPresent: Boolean;
ReadCount: Integer;
ConsistentSize: Integer;
FilteredBuffer: TBytes;
FilteredData: TBytes;
begin
if FFilterFlag = Pendant then
begin
if not FillBuffer(FHeaderData, 0, TTransportFilterTools.HeaderLen) then
Exit(-1);
if TTransportFilterTools.IsFilterQuery(FHeaderData) then
begin
if HasFilters then
begin
FFilterFlag := Filtered;
FFilterList.StartHandshake;
PkcFiltersPresent := TTransportFilterTools.HasPublicKeyCryptography(FFilterList);
if PkcFiltersPresent then
begin
if SendFilterParameters(True) < 0 then
Exit(-1);
if not FillBuffer(FHeaderData, 0, TTransportFilterTools.HeaderLen) then
Exit(-1);
if ReceiveAndSetConfederateFilterParameters(False) < 0 then
Exit(-1);
end;
if SendFilterParameters(False) < 0 then
Exit(-1);
if not FillBuffer(FHeaderData, 0, TTransportFilterTools.HeaderLen) then
Exit(-1);
if ReceiveAndSetConfederateFilterParameters(PkcFiltersPresent) < 0 then
Exit(-1);
if not FFilterList.HandshakeComplete then
Exit(-1);
end
else
begin
FFilterFlag := Regular;
if FDelegate.Write(TTransportFilterTools.NoFilter(FHeaderData), 0, TTransportFilterTools.HeaderLen) < 0 then
Exit(-1);
Exit(FDelegate.Read(Buffer, Offset, Count));
end;
end
else
begin
if HasFilters then
Exit(-1);
FFilterFlag := Regular;
TDBXPlatform.CopyByteArray(FHeaderData, 0, Buffer, Offset, TTransportFilterTools.HeaderLen);
ReadCount := FDelegate.Read(Buffer, Offset + TTransportFilterTools.HeaderLen, Count - TTransportFilterTools.HeaderLen);
if ReadCount < 0 then
Exit(-1);
Exit(TTransportFilterTools.HeaderLen + ReadCount);
end;
end;
if FFilterFlag = Filtered then
begin
if HasLeftover then
Exit(ConsumeLeftover(Buffer, Offset, Count));
// get the filtered data byte length
if not FillBuffer(FHeaderData, 0, TTransportFilterTools.HeaderLen) then
Exit(-1);
ConsistentSize := TTransportFilterTools.DecodeDataLen(FHeaderData);
if ConsistentSize < 0 then
Exit(-1);
// read the filtered data
SetLength(FilteredBuffer,ConsistentSize);
if not FillBuffer(FilteredBuffer, 0, ConsistentSize) then
Exit(-1);
// filter the data
Assert(Length(FilteredBuffer) = ConsistentSize);
FilteredData := FilterDataRead(FilteredBuffer, ConsistentSize, False);
// cache the un-filtered data
SetLeftover(FilteredData, 0);
// consume what you can
Exit(ConsumeLeftover(Buffer, Offset, Count));
end;
Result := FDelegate.Read(Buffer, Offset, Count);
end;
function TDBXFilterSocketChannel.SendFilterParameters(const OnlyPublickKeyCryptographs: Boolean): Integer;
var
JsonLen: TBytes;
JsonFilters: TJSONObject;
ByteSize: Integer;
JsonBytes: TBytes;
begin
SetLength(JsonLen,5);
try
JsonFilters := FilterParameters(OnlyPublickKeyCryptographs);
ByteSize := JsonFilters.EstimatedByteSize;
SetLength(JsonBytes,ByteSize);
ByteSize := JsonFilters.ToBytes(JsonBytes, 0);
FreeAndNil(JsonFilters);
if not OnlyPublickKeyCryptographs then
begin
JsonBytes := FilterDataWrite(JsonBytes, ByteSize, True);
ByteSize := Length(JsonBytes);
TTransportFilterTools.EncodeDataLength(JsonLen, ByteSize);
end
else
TTransportFilterTools.EncodePublicKeyLength(JsonLen, ByteSize);
if FDelegate.Write(JsonLen, 0, 5) < 0 then
Exit(-1);
Exit(FDelegate.Write(JsonBytes, 0, ByteSize));
except
on Err: TDBXError do
begin
end;
end;
Result := -1;
end;
function TDBXFilterSocketChannel.Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer;
var
FilteredData: TBytes;
i: Integer;
Filter: TTransportFilter;
HasPublicKeyFilter: Boolean;
begin
if Count = 0 then
Exit(0);
if FFilterFlag = Pendant then
begin
if FDelegate.Write(TTransportFilterTools.FilterQuery(FHeaderData), 0, TTransportFilterTools.HeaderLen) < 0 then
Exit(-1);
if FillBuffer(FHeaderData, 0, TTransportFilterTools.HeaderLen) then
begin
HasPublicKeyFilter := (not TTransportFilterTools.HasNoFilter(FHeaderData)) and
TTransportFilterTools.HasPublicKey(FHeaderData);
if not HasPublicKeyFilter then
begin
if FFilterList <> nil then
begin
//throw an exception if there is a public key encryption filter (such as RSA)
//on the client but not the server.
for i := FFilterList.Count - 1 downto 0 do
begin
Filter := TTransportFilter(FFilterList.GetFilter(I));
if Filter.PublicKeyCryptograph = true then
raise TDBXError.Create(0, Format(SNoMatchingFilter, [Filter.Id]));
end;
end;
end;
if TTransportFilterTools.HasNoFilter(FHeaderData) then
FFilterFlag := Regular
else
begin
FFilterFlag := Filtered;
if HasPublicKeyFilter then
begin
if ReceiveAndSetConfederateFilterParameters(False) < 0 then
Exit(-1);
if SendFilterParameters(True) < 0 then
Exit(-1);
if not FillBuffer(FHeaderData, 0, TTransportFilterTools.HeaderLen) or (ReceiveAndSetConfederateFilterParameters(True) < 0) then
Exit(-1);
end
else
begin
if ReceiveAndSetConfederateFilterParameters(False) < 0 then
Exit(-1);
end;
if SendFilterParameters(False) < 0 then
Exit(-1);
if not FFilterList.HandshakeComplete then
Exit(-1);
end;
end
else
Exit(-1);
end;
if FFilterFlag = Filtered then
begin
Assert(Offset = 0);
FilteredData := FilterDataWrite(Buffer, Count, False);
TTransportFilterTools.EncodeDataLength(FHeaderData, Length(FilteredData));
if FDelegate.Write(FHeaderData, 0, TTransportFilterTools.HeaderLen) = -1 then
Exit(-1);
Exit(FDelegate.Write(FilteredData, 0, Length(FilteredData)));
end;
Result := FDelegate.Write(Buffer, Offset, Count);
end;
function TDBXFilterSocketChannel.ReceiveAndSetConfederateFilterParameters(const PublicKeyEncrypted: Boolean): Integer;
var
FilterByteLen: Integer;
FilterBytes: TBytes;
begin
FilterByteLen := TTransportFilterTools.DecodeDataLen(FHeaderData);
if FilterByteLen < 0 then
Exit(-1);
SetLength(FilterBytes,FilterByteLen);
if not FillBuffer(FilterBytes, 0, FilterByteLen) then
Exit(-1);
if PublicKeyEncrypted then
FilterBytes := FilterDataRead(FilterBytes, FilterByteLen, True);
if not RestoreFilterList(FilterBytes, 0) then
Exit(-1);
Result := 0;
end;
function TDBXFilterSocketChannel.FilterDataRead(const Data: TBytes; const Count: Integer; const OnlyPublikKeyCryptographs: Boolean): TBytes;
var
ProcessedData: TBytes;
Filter: TTransportFilter;
I: Integer;
begin
SetLength(ProcessedData,Count);
TDBXPlatform.CopyByteArray(Data, 0, ProcessedData, 0, Count);
for i := 0 to FFilterList.Count - 1 do
begin
Filter := FFilterList.GetFilter(I);
if Filter.PublicKeyCryptograph = OnlyPublikKeyCryptographs then
ProcessedData := Filter.ProcessOutput(ProcessedData);
end;
Result := ProcessedData;
end;
function TDBXFilterSocketChannel.FilterDataWrite(const Data: TBytes; const Count: Integer; const OnlyPublikKeyCryptographs: Boolean): TBytes;
var
ProcessedData: TBytes;
Filter: TTransportFilter;
I: Integer;
begin
SetLength(ProcessedData,Count);
TDBXPlatform.CopyByteArray(Data, 0, ProcessedData, 0, Count);
for i := 0 to FFilterList.Count - 1 do
begin
Filter := TTransportFilter(FFilterList.GetFilter(I));
if Filter.PublicKeyCryptograph = OnlyPublikKeyCryptographs then
ProcessedData := Filter.ProcessInput(ProcessedData);
end;
Result := ProcessedData;
end;
procedure TDBXFilterSocketChannel.Close;
begin
FDelegate.Close;
end;
function TDBXFilterSocketChannel.GetChannelInfo: TDBXChannelInfo;
begin
Result := FDelegate.ChannelInfo;
end;
procedure TDBXFilterSocketChannel.Open;
begin
FDelegate.Open;
end;
function TDBXFilterSocketChannel.GetDBXProperties: TDBXProperties;
begin
Result := FDelegate.DBXProperties;
end;
procedure TDBXFilterSocketChannel.SetDBXProperties(const Properties: TDBXProperties);
var
JsonFilters: UnicodeString;
begin
FDelegate.DBXProperties := Properties;
JsonFilters := Properties[TDBXPropertyNames.Filters];
if Length(JsonFilters) > 0 then
begin
FFilterList := TTransportFilterCollection.FromJSON(JsonFilters);
FOwnFilterList := True;
end;
end;
end.
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.Animations;
interface
uses
System.Types, System.Classes, FMX.Ani, FMX.Types, FMX.Types3D, FMX.Styles.Objects, FMX.Forms,
FGX.Consts;
type
{ TfgCustomPropertyAnimation }
TfgCustomPropertyAnimation<T: TPersistent, constructor> = class(TCustomPropertyAnimation)
public const
DefaultDuration = 0.2;
DefaultAnimationType = TAnimationType.In;
DefaultAutoReverse = False;
DefaultEnabled = False;
DefaultInterpolation = TInterpolationType.Linear;
DefaultInverse = False;
DefaultLoop = False;
DefaultStartFromCurrent = False;
private
FStartFromCurrent: Boolean;
FStartValue: T;
FStopValue: T;
FCurrentValue: T;
protected
{ Bug of Compiler with generics. Compiler cannot mark this property as published and show it in IDE.
So i put them in protected and public in each successor declare property }
procedure SetStartValue(const Value: T);
procedure SetStopValue(const Value: T);
function GetStartValue: T;
function GetStopValue: T;
protected
procedure FirstFrame; override;
procedure ProcessAnimation; override;
procedure DefineCurrentValue(const ANormalizedTime: Single); virtual; abstract;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property CurrentValue: T read FCurrentValue;
property StartFromCurrent: Boolean read FStartFromCurrent write FStartFromCurrent default False;
property StartValue: T read GetStartValue write SetStartValue;
property StopValue: T read GetStopValue write SetStopValue;
end;
{ TfgPositionAnimation }
TfgCustomPositionAnimation = class(TfgCustomPropertyAnimation<TPosition>)
protected
procedure DefineCurrentValue(const ANormalizedTime: Single); override;
public
constructor Create(AOwner: TComponent); override;
property StartValue: TPosition read GetStartValue write SetStartValue;
property StopValue: TPosition read GetStopValue write SetStopValue;
end;
[ComponentPlatformsAttribute(fgAllPlatform)]
TfgPositionAnimation = class(TfgCustomPositionAnimation)
published
property AnimationType default TfgCustomPositionAnimation.DefaultAnimationType;
property AutoReverse default TfgCustomPositionAnimation.DefaultAutoReverse;
property Enabled default TfgCustomPositionAnimation.DefaultEnabled;
property Delay;
property Duration nodefault;
property Interpolation default TfgCustomPositionAnimation.DefaultInterpolation;
property Inverse default TfgCustomPositionAnimation.DefaultInverse;
property Loop default TfgCustomPositionAnimation.DefaultLoop;
property PropertyName;
property StartValue stored True nodefault;
property StartFromCurrent default TfgCustomPositionAnimation.DefaultStartFromCurrent;
property StopValue stored True nodefault;
property Trigger;
property TriggerInverse;
property OnProcess;
property OnFinish;
end;
{ TfgPosition3DAnimation }
TfgCustomPosition3DAnimation = class(TfgCustomPropertyAnimation<TPosition3D>)
protected
procedure DefineCurrentValue(const ANormalizedTime: Single); override;
public
constructor Create(AOwner: TComponent); override;
property StartValue: TPosition3D read GetStartValue write SetStartValue;
property StopValue: TPosition3D read GetStopValue write SetStopValue;
end;
[ComponentPlatformsAttribute(fgAllPlatform)]
TfgPosition3DAnimation = class(TfgCustomPosition3DAnimation)
published
property AnimationType default TfgCustomPosition3DAnimation.DefaultAnimationType;
property AutoReverse default TfgCustomPosition3DAnimation.DefaultAutoReverse;
property Enabled default TfgCustomPosition3DAnimation.DefaultEnabled;
property Delay;
property Duration nodefault;
property Interpolation default TfgCustomPosition3DAnimation.DefaultInterpolation;
property Inverse default TfgCustomPosition3DAnimation.DefaultInverse;
property Loop default TfgCustomPosition3DAnimation.DefaultLoop;
property PropertyName;
property StartValue stored True nodefault;
property StartFromCurrent default TfgCustomPosition3DAnimation.DefaultStartFromCurrent;
property StopValue stored True nodefault;
property Trigger;
property TriggerInverse;
property OnProcess;
property OnFinish;
end;
{ TfgCustomBitmapLinkAnimation }
TfgBitmapLinkAnimationOption = (AnimateSourceRect, AnimateCapInsets);
TfgBitmapLinkAnimationOptions = set of TfgBitmapLinkAnimationOption;
TfgCustomBitmapLinkAnimation = class(TfgCustomPropertyAnimation<TBitmapLinks>)
public const
DefaultOptions = [TfgBitmapLinkAnimationOption.AnimateSourceRect, TfgBitmapLinkAnimationOption.AnimateCapInsets];
private
FOptions: TfgBitmapLinkAnimationOptions;
FStopValue: TBitmapLinks;
FStartValue: TBitmapLinks;
procedure SetStartValue(const Value: TBitmapLinks);
procedure SetStopValue(const Value: TBitmapLinks);
protected
procedure DefineCurrentValue(const ANormalizedTime: Single); override;
procedure ProcessAnimation; override;
function GetSceneScale: Single;
public
constructor Create(AOwner: TComponent); override;
property Options: TfgBitmapLinkAnimationOptions read FOptions write FOptions default DefaultOptions;
property StartValue: TBitmapLinks read GetStartValue write SetStartValue;
property StopValue: TBitmapLinks read GetStopValue write SetStopValue;
end;
[ComponentPlatformsAttribute(fgAllPlatform)]
TfgBitmapLinkAnimation = class(TfgCustomBitmapLinkAnimation)
published
property AnimationType default TfgCustomBitmapLinkAnimation.DefaultAnimationType;
property AutoReverse default TfgCustomBitmapLinkAnimation.DefaultAutoReverse;
property Enabled default TfgCustomBitmapLinkAnimation.DefaultEnabled;
property Delay;
property Duration nodefault;
property Interpolation default TfgCustomBitmapLinkAnimation.DefaultInterpolation;
property Inverse default TfgCustomBitmapLinkAnimation.DefaultInverse;
property Loop default TfgCustomBitmapLinkAnimation.DefaultLoop;
property Options;
property PropertyName;
property StartValue stored True nodefault;
property StartFromCurrent default TfgCustomBitmapLinkAnimation.DefaultStartFromCurrent;
property StopValue stored True nodefault;
property Trigger;
property TriggerInverse;
property OnProcess;
property OnFinish;
end;
function fgInterpolateRectF(const AStart: TRectF; const AStop: TRectF; const ANormalizedTime: Single): TRectF; inline;
implementation
uses
System.SysUtils, System.Math.Vectors, FGX.Asserts, FMX.Utils, FMX.Controls;
function fgInterpolateRectF(const AStart, AStop: TRectF; const ANormalizedTime: Single): TRectF;
begin
Result.Left := InterpolateSingle(AStart.Left, AStop.Left, ANormalizedTime);
Result.Top := InterpolateSingle(AStart.Top, AStop.Top, ANormalizedTime);
Result.Right := InterpolateSingle(AStart.Right, AStop.Right, ANormalizedTime);
Result.Bottom := InterpolateSingle(AStart.Bottom, AStop.Bottom, ANormalizedTime);
end;
{ TfgCustomPropertyAnimation<T> }
constructor TfgCustomPropertyAnimation<T>.Create(AOwner: TComponent);
begin
inherited;
FStartValue := T.Create;
FStopValue := T.Create;
FCurrentValue := T.Create;
AnimationType := DefaultAnimationType;
AutoReverse := DefaultAutoReverse;
Duration := DefaultDuration;
Enabled := DefaultEnabled;
Interpolation := DefaultInterpolation;
Inverse := DefaultInverse;
Loop := DefaultLoop;
StartFromCurrent := DefaultStartFromCurrent;
end;
destructor TfgCustomPropertyAnimation<T>.Destroy;
begin
FreeAndNil(FStartValue);
FreeAndNil(FStopValue);
FreeAndNil(FCurrentValue);
inherited Destroy;
end;
procedure TfgCustomPropertyAnimation<T>.FirstFrame;
begin
AssertIsNotNil(FCurrentValue);
if StartFromCurrent and (FRttiProperty <> nil) and FRttiProperty.PropertyType.IsInstance then
T(FRttiProperty.GetValue(FInstance).AsObject).Assign(FCurrentValue);
end;
function TfgCustomPropertyAnimation<T>.GetStartValue: T;
begin
Result := FStartValue;
end;
function TfgCustomPropertyAnimation<T>.GetStopValue: T;
begin
Result := FStopValue;
end;
procedure TfgCustomPropertyAnimation<T>.ProcessAnimation;
begin
AssertIsNotNil(FStartValue);
AssertIsNotNil(FStopValue);
AssertIsNotNil(FCurrentValue);
inherited;
if (FInstance <> nil) and (FRttiProperty <> nil) then
begin
DefineCurrentValue(NormalizedTime);
if FRttiProperty.PropertyType.IsInstance then
T(FRttiProperty.GetValue(FInstance).AsObject).Assign(FCurrentValue);
end;
end;
procedure TfgCustomPropertyAnimation<T>.SetStartValue(const Value: T);
begin
AssertIsNotNil(FStartValue);
AssertIsNotNil(Value);
FStartValue.Assign(Value);
end;
procedure TfgCustomPropertyAnimation<T>.SetStopValue(const Value: T);
begin
AssertIsNotNil(FStopValue);
AssertIsNotNil(Value);
FStopValue.Assign(Value);
end;
{ TfgCustomPositionAnimation }
constructor TfgCustomPositionAnimation.Create(AOwner: TComponent);
begin
inherited;
StartValue.DefaultValue := TPointF.Zero;
StopValue.DefaultValue := TPointF.Zero;
end;
procedure TfgCustomPositionAnimation.DefineCurrentValue(const ANormalizedTime: Single);
begin
FCurrentValue.X := InterpolateSingle(StartValue.X, StopValue.X, ANormalizedTime);
FCurrentValue.Y := InterpolateSingle(StartValue.Y, StopValue.Y, ANormalizedTime);
end;
{ TfgCustomPosition3DAnimation }
constructor TfgCustomPosition3DAnimation.Create(AOwner: TComponent);
begin
inherited;
FStartValue.DefaultValue := TPoint3D.Zero;
FStopValue.DefaultValue := TPoint3D.Zero;
FCurrentValue.DefaultValue := TPoint3D.Zero;
end;
procedure TfgCustomPosition3DAnimation.DefineCurrentValue(const ANormalizedTime: Single);
begin
FCurrentValue.X := InterpolateSingle(StartValue.X, StopValue.X, ANormalizedTime);
FCurrentValue.Y := InterpolateSingle(StartValue.Y, StopValue.Y, ANormalizedTime);
FCurrentValue.Z := InterpolateSingle(StartValue.Z, StopValue.Z, ANormalizedTime);
end;
{ TfgCustomBitmapLinkAnimation }
constructor TfgCustomBitmapLinkAnimation.Create(AOwner: TComponent);
begin
inherited;
FOptions := DefaultOptions;
end;
procedure TfgCustomBitmapLinkAnimation.DefineCurrentValue(const ANormalizedTime: Single);
var
SceneScale: Single;
LinkStart: TBitmapLink;
LinkStop: TBitmapLink;
Link: TBitmapLink;
begin
SceneScale := GetSceneScale;
LinkStart := StartValue.LinkByScale(SceneScale, True);
LinkStop := StopValue.LinkByScale(SceneScale, True);
AssertIsNotNil(LinkStart, Format('For current scene scale |%f|, Animator doesn''t have specified Start link', [SceneScale]));
AssertIsNotNil(LinkStop, Format('For current scene scale |%f|, Animator doesn''t have specified Stop link', [SceneScale]));
Link := CurrentValue.LinkByScale(SceneScale, True);
if Link = nil then
begin
Link := TBitmapLink(CurrentValue.Add);
Link.Scale := SceneScale;
end;
if TfgBitmapLinkAnimationOption.AnimateSourceRect in Options then
Link.SourceRect.Rect := fgInterpolateRectF(LinkStart.SourceRect.Rect, LinkStop.SourceRect.Rect, NormalizedTime);
if TfgBitmapLinkAnimationOption.AnimateCapInsets in Options then
Link.CapInsets.Rect := fgInterpolateRectF(LinkStart.CapInsets.Rect, LinkStop.CapInsets.Rect, NormalizedTime);
end;
function TfgCustomBitmapLinkAnimation.GetSceneScale: Single;
var
ScreenScale: Single;
ParentControl: TControl;
begin
if Parent is TControl then
begin
ParentControl := TControl(Parent);
if ParentControl.Scene <> nil then
ScreenScale := ParentControl.Scene.GetSceneScale
else
ScreenScale := ParentControl.Canvas.Scale;
end
else
ScreenScale := 1;
Result := ScreenScale;
end;
procedure TfgCustomBitmapLinkAnimation.ProcessAnimation;
begin
AssertEqual(StartValue.Count, StopValue.Count, 'Count of links in StartValue and StopValue must be identical');
inherited;
// Workaround: TStyleObject doesn't repaint itself, when we change BitmapLinks. So we force painting in this case
if Parent is TStyleObject then
TStyleObject(Parent).Repaint;
end;
procedure TfgCustomBitmapLinkAnimation.SetStartValue(const Value: TBitmapLinks);
begin
FStartValue := Value;
end;
procedure TfgCustomBitmapLinkAnimation.SetStopValue(const Value: TBitmapLinks);
begin
FStopValue := Value;
end;
initialization
RegisterFmxClasses([TfgPositionAnimation, TfgPosition3DAnimation, TfgBitmapLinkAnimation]);
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC SQL Time Interval data type }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Stan.SQLTimeInt;
interface
uses
System.Variants;
type
TFDSQLTimeIntervalKind = (itUnknown, itYear, itMonth, itDay, itHour, itMinute,
itSecond, itYear2Month, itDay2Hour, itDay2Minute, itDay2Second, itHour2Minute,
itHour2Second, itMinute2Second);
TFDSQLTimeInterval = packed record
Sign: Shortint;
case Kind: TFDSQLTimeIntervalKind of
itYear, itMonth, itYear2Month: (
Years: Cardinal;
Months: Cardinal
);
itDay, itHour, itMinute, itSecond, itDay2Hour, itDay2Minute,
itDay2Second, itHour2Minute, itHour2Second, itMinute2Second: (
Days: Cardinal;
Hours: Cardinal;
Minutes: Cardinal;
Seconds: Cardinal;
Fractions: Cardinal
);
end;
PFDSQLTimeInterval = ^TFDSQLTimeInterval;
function FDVarSQLTimeIntervalCreate: Variant; overload;
function FDVarSQLTimeIntervalCreate(const AValue: string): Variant; overload;
function FDVarSQLTimeIntervalCreate(const AValue: TFDSQLTimeInterval): Variant; overload;
function FDVarSQLTimeInterval: TVarType;
function FDVarIsSQLTimeInterval(const AValue: Variant): Boolean; overload;
function FDVar2SQLTimeInterval(const AValue: Variant): TFDSQLTimeInterval;
function FDStr2SQLTimeInterval(const AValue: String): TFDSQLTimeInterval;
function FDSQLTimeInterval2Str(const AValue: TFDSQLTimeInterval): String;
function FDSQLTimeIntervalCompare(const AValue1, AValue2: TFDSQLTimeInterval): Integer;
function FDSQLTimeIntervalCast(const AValue: TFDSQLTimeInterval;
AKind: TFDSQLTimeIntervalKind): TFDSQLTimeInterval;
const
C_NullSQLTimeInterval: TFDSQLTimeInterval = (Sign: 0; Kind: itUnknown; Days: 0;
Hours: 0; Minutes: 0; Seconds: 0; Fractions: 0);
implementation
uses
System.SysUtils, System.Classes, System.TypInfo, System.SysConst, Data.SQLTimSt,
FireDAC.Stan.Intf, FireDAC.Stan.Util;
{ ----------------------------------------------------------------------------- }
{ TFDSQLTimeIntervalVariantType }
{ ----------------------------------------------------------------------------- }
type
TFDSQLTimeIntervalData = class(TPersistent)
private
FInterval: TFDSQLTimeInterval;
procedure CheckIntervalsCompatibility(const AInt1, AInt2: TFDSQLTimeInterval);
procedure NotInitError;
function GetIsBlankBase(const AInterval: TFDSQLTimeInterval): Boolean;
function GetIsBlank: Boolean;
function GetIsNegative: Boolean;
procedure DoIncrementBase(const AInterval: TFDSQLTimeInterval; ASign: Integer); overload;
procedure DoIncrementBase(const AValue: Integer; ASign: Integer); overload;
procedure DoAddToBase(var ADateTime: TSQLTimeStamp; ASign: Integer);
function GetAsString: string;
procedure SetAsString(const AValue: string);
public
// the many ways to create
constructor Create(const AText: string); overload;
constructor Create(const ASQLTimeInterval: TFDSQLTimeInterval); overload;
constructor Create(const ASource: TFDSQLTimeIntervalData); overload;
// access to the private bits
property Interval: TFDSQLTimeInterval read FInterval write FInterval;
property IsBlank: Boolean read GetIsBlank;
property IsNegative: Boolean read GetIsNegative;
// non-destructive operations
function Compare(const AValue: TFDSQLTimeInterval): TVarCompareResult;
procedure DoAddTo(var ADateTime: TSQLTimeStamp);
procedure DoSubFrom(var ADateTime: TSQLTimeStamp);
// destructive operations
procedure DoSubstract(const ADateTime1, ADateTime2: TSQLTimeStamp); overload;
procedure DoInc(const AInterval: TFDSQLTimeInterval); overload;
procedure DoInc(const AValue: Integer); overload;
procedure DoDec(const AInterval: TFDSQLTimeInterval); overload;
procedure DoDec(const AValue: Integer); overload;
procedure CastToKind(AKind: TFDSQLTimeIntervalKind);
procedure DoMultiply(AValue: Integer);
procedure DoDivide(AValue: Integer);
procedure DoNegate;
published
// conversion
property AsString: string read GetAsString write SetAsString;
property Sign: Shortint read FInterval.Sign write FInterval.Sign;
property Kind: TFDSQLTimeIntervalKind read FInterval.Kind write FInterval.Kind;
property Years: Cardinal read FInterval.Years write FInterval.Years;
property Month: Cardinal read FInterval.Months write FInterval.Months;
property Days: Cardinal read FInterval.Days write FInterval.Days;
property Hour: Cardinal read FInterval.Hours write FInterval.Hours;
property Minute: Cardinal read FInterval.Minutes write FInterval.Minutes;
property Second: Cardinal read FInterval.Seconds write FInterval.Seconds;
property Fractions: Cardinal read FInterval.Fractions write FInterval.Fractions;
end;
TFDSQLTimeIntervalVariantType = class(TPublishableVariantType)
protected
function GetInstance(const V: TVarData): TObject; override;
public
procedure Clear(var V: TVarData); override;
procedure Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); override;
procedure Cast(var Dest: TVarData; const Source: TVarData); override;
procedure CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType); override;
function RightPromotion(const V: TVarData; const Operator: TVarOp; out RequiredVarType: TVarType): Boolean; override;
procedure BinaryOp(var Left: TVarData; const Right: TVarData; const Operator: TVarOp); override;
procedure UnaryOp(var Right: TVarData; const Operator: TVarOp); override;
procedure Compare(const Left, Right: TVarData; var Relationship: TVarCompareResult); override;
end;
PFDSQLTimeIntervalVarData = ^TFDSQLTimeIntervalVarData;
TFDSQLTimeIntervalVarData = packed record
VType: TVarType;
Reserved1, Reserved2, Reserved3: Word;
VInterval: TFDSQLTimeIntervalData;
Reserved4: Cardinal;
end;
var
GSQLTimeIntervalVariantType: TFDSQLTimeIntervalVariantType = nil;
{-------------------------------------------------------------------------------}
{ TFDSQLTimeIntervalData }
{-------------------------------------------------------------------------------}
constructor TFDSQLTimeIntervalData.Create(const AText: string);
begin
inherited Create;
SetAsString(AText);
end;
{-------------------------------------------------------------------------------}
constructor TFDSQLTimeIntervalData.Create(const ASQLTimeInterval: TFDSQLTimeInterval);
begin
inherited Create;
FInterval := ASQLTimeInterval;
end;
{-------------------------------------------------------------------------------}
constructor TFDSQLTimeIntervalData.Create(const ASource: TFDSQLTimeIntervalData);
begin
Create(ASource.FInterval);
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.CheckIntervalsCompatibility(
const AInt1, AInt2: TFDSQLTimeInterval);
begin
if not (
(AInt1.Kind in [itYear, itMonth, itYear2Month]) and
(AInt2.Kind in [itYear, itMonth, itYear2Month]) or
(AInt1.Kind in [itDay, itHour, itMinute, itSecond, itDay2Hour, itDay2Minute,
itDay2Second, itHour2Minute, itHour2Second, itMinute2Second]) and
(AInt2.Kind in [itDay, itHour, itMinute, itSecond, itDay2Hour, itDay2Minute,
itDay2Second, itHour2Minute, itHour2Second, itMinute2Second])) then
raise EVariantError.Create('Cannot substruct intervals of incompatible kinds');
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.NotInitError;
begin
raise EVariantError.Create('Cannot perform operation on non initialized interval value');
end;
{-------------------------------------------------------------------------------}
function TFDSQLTimeIntervalData.GetIsBlankBase(const AInterval: TFDSQLTimeInterval): Boolean;
begin
Result := (AInterval.Sign = 0) and (AInterval.Kind = itUnknown) or
(AInterval.Days = 0) and (AInterval.Hours = 0) and (AInterval.Minutes = 0) and
(AInterval.Seconds = 0) and (AInterval.Fractions = 0);
end;
{-------------------------------------------------------------------------------}
function TFDSQLTimeIntervalData.GetIsBlank: Boolean;
begin
Result := GetIsBlankBase(FInterval);
end;
{-------------------------------------------------------------------------------}
function TFDSQLTimeIntervalData.GetIsNegative: Boolean;
begin
Result := FInterval.Sign < 0;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoSubstract(const ADateTime1, ADateTime2: TSQLTimeStamp);
var
dVal: Double;
lNeg: Boolean;
wHour, wMin, wSec, wMSec: Word;
begin
dVal := SQLTimeStampToDateTime(ADateTime1) - SQLTimeStampToDateTime(ADateTime2);
if dVal < 0 then begin
lNeg := True;
dVal := Abs(dVal);
end
else
lNeg := False;
if lNeg then
FInterval.Sign := -1
else
FInterval.Sign := 1;
FInterval.Kind := itDay2Second;
FInterval.Days := Trunc(dVal);
DecodeTime(Frac(dVal), wHour, wMin, wSec, wMSec);
FInterval.Hours := wHour;
FInterval.Minutes := wMin;
FInterval.Seconds := wSec;
FInterval.Fractions := wMSec;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoAddToBase(var ADateTime: TSQLTimeStamp;
ASign: Integer);
var
iSign, iVal: Integer;
d: TDateTime;
begin
if IsBlank then
Exit;
if (ASign < 0) xor (FInterval.Sign < 0) then
iSign := -1
else
iSign := 1;
case Kind of
itYear,
itMonth,
itYear2Month:
begin
ADateTime.Year := ADateTime.Year + iSign * Integer(FInterval.Years);
iVal := Integer(ADateTime.Month) + iSign * Integer(FInterval.Months);
ADateTime.Year := ADateTime.Year + iVal div 12;
iVal := iVal mod 12;
if iVal < 0 then begin
Dec(ADateTime.Year);
ADateTime.Month := Word(12 + iVal);
end
else
ADateTime.Month := Word(iVal);
end;
itDay,
itHour,
itMinute,
itSecond,
itDay2Hour,
itDay2Minute,
itDay2Second,
itHour2Minute,
itHour2Second,
itMinute2Second:
begin
d := SQLTimeStampToDateTime(ADateTime);
d := d + iSign * Integer(FInterval.Days);
d := d + iSign * MSecsPerDay / (((FInterval.Hours * 60 + FInterval.Minutes) * 60 + FInterval.Seconds) * 1000 + FInterval.Fractions);
ADateTime := DateTimeToSQLTimeStamp(d);
end;
else
NotInitError;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoAddTo(var ADateTime: TSQLTimeStamp);
begin
DoAddToBase(ADateTime, 1);
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoSubFrom(var ADateTime: TSQLTimeStamp);
begin
DoAddToBase(ADateTime, -1);
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoIncrementBase(const AInterval: TFDSQLTimeInterval;
ASign: Integer);
var
iMonths: Int64;
iFractions: Int64;
iSignMy, iSignArg: Integer;
begin
if GetIsBlankBase(AInterval) then
Exit;
if (ASign < 0) xor (AInterval.Sign < 0) then
iSignArg := -1
else
iSignArg := 1;
if IsBlank then begin
FInterval := AInterval;
FInterval.Sign := iSignArg;
Exit;
end;
CheckIntervalsCompatibility(FInterval, AInterval);
iMonths := 0;
iFractions := 0;
if FInterval.Sign < 0 then
iSignMy := -1
else
iSignMy := 1;
case Kind of
itYear,
itMonth,
itYear2Month:
begin
iMonths :=
iSignMy * (Int64(FInterval.Years) * 12 + Int64(FInterval.Months)) +
iSignArg * (Int64(AInterval.Years) * 12 + Int64(AInterval.Months));
if iMonths < 0 then begin
iMonths := Abs(iMonths);
iSignMy := -1;
end
else
iSignMy := 1;
end;
itDay,
itHour,
itMinute,
itSecond,
itDay2Hour,
itDay2Minute,
itDay2Second,
itHour2Minute,
itHour2Second,
itMinute2Second:
begin
iFractions :=
iSignMy * ((((Int64(FInterval.Days) * 24 + Int64(FInterval.Hours)) * 60 + Int64(FInterval.Minutes)) * 60 +
Int64(FInterval.Seconds)) * 1000 + Int64(FInterval.Fractions)) +
iSignArg * ((((Int64(AInterval.Days) * 24 + Int64(AInterval.Hours)) * 60 + Int64(AInterval.Minutes)) * 60 +
Int64(AInterval.Seconds)) * 1000 + Int64(AInterval.Fractions));
if iFractions < 0 then begin
iFractions := Abs(iFractions);
iSignMy := -1;
end
else
iSignMy := 1;
end;
else
NotInitError;
end;
FInterval.Sign := iSignMy;
FInterval.Days := 0;
FInterval.Hours := 0;
FInterval.Minutes := 0;
FInterval.Seconds := 0;
FInterval.Fractions := 0;
case FInterval.Kind of
itYear:
FInterval.Years := iMonths div 12;
itMonth:
FInterval.Months := iMonths;
itYear2Month:
begin
FInterval.Years := iMonths div 12;
FInterval.Months := iMonths mod 12;
end;
itDay:
FInterval.Days := iFractions div (1000 * SecsPerDay);
itHour:
FInterval.Hours := iFractions div (1000 * SecsPerHour);
itMinute:
FInterval.Hours := iFractions div (1000 * SecsPerMin);
itSecond:
FInterval.Hours := iFractions div 1000;
itDay2Hour:
begin
FInterval.Days := iFractions div (1000 * SecsPerDay);
iFractions := iFractions - Int64(FInterval.Days) * 1000 * SecsPerDay;
FInterval.Hours := iFractions div (1000 * SecsPerHour);
end;
itDay2Minute:
begin
FInterval.Days := iFractions div (1000 * SecsPerDay);
iFractions := iFractions - Int64(FInterval.Days) * 1000 * SecsPerDay;
FInterval.Hours := iFractions div (1000 * SecsPerHour);
iFractions := iFractions - Int64(FInterval.Hours) * 1000 * SecsPerHour;
FInterval.Minutes := iFractions div (1000 * SecsPerMin);
end;
itDay2Second:
begin
FInterval.Days := iFractions div (1000 * SecsPerDay);
iFractions := iFractions - Int64(FInterval.Days) * 1000 * SecsPerDay;
FInterval.Hours := iFractions div (1000 * SecsPerHour);
iFractions := iFractions - Int64(FInterval.Hours) * 1000 * SecsPerHour;
FInterval.Minutes := iFractions div (1000 * SecsPerMin);
iFractions := iFractions - Int64(FInterval.Minutes) * 1000 * SecsPerMin;
FInterval.Seconds := iFractions div 1000;
FInterval.Fractions := iFractions - Int64(FInterval.Seconds) * 1000;
end;
itHour2Minute:
begin
FInterval.Hours := iFractions div (1000 * SecsPerHour);
iFractions := iFractions - Int64(FInterval.Hours) * 1000 * SecsPerHour;
FInterval.Minutes := iFractions div (1000 * SecsPerMin);
end;
itHour2Second:
begin
FInterval.Hours := iFractions div (1000 * SecsPerHour);
iFractions := iFractions - Int64(FInterval.Hours) * 1000 * SecsPerHour;
FInterval.Minutes := iFractions div (1000 * SecsPerMin);
iFractions := iFractions - Int64(FInterval.Minutes) * 1000 * SecsPerMin;
FInterval.Seconds := iFractions div 1000;
FInterval.Fractions := iFractions - Int64(FInterval.Seconds) * 1000;
end;
itMinute2Second:
begin
FInterval.Minutes := iFractions div (1000 * SecsPerMin);
iFractions := iFractions - Int64(FInterval.Minutes) * 1000 * SecsPerMin;
FInterval.Seconds := iFractions div 1000;
FInterval.Fractions := iFractions - Int64(FInterval.Seconds) * 1000;
end;
else
NotInitError;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoInc(const AInterval: TFDSQLTimeInterval);
begin
DoIncrementBase(AInterval, 1);
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoDec(const AInterval: TFDSQLTimeInterval);
begin
DoIncrementBase(AInterval, -1);
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoIncrementBase(const AValue: Integer; ASign: Integer);
var
rInt: TFDSQLTimeInterval;
begin
FillChar(rInt, SizeOf(rInt), 0);
rInt.Sign := 1;
rInt.Kind := FInterval.Kind;
case FInterval.Kind of
itYear:
rInt.Years := AValue;
itMonth,
itYear2Month:
rInt.Months := AValue;
itDay:
rInt.Days := AValue;
itHour,
itDay2Hour:
rInt.Hours := AValue;
itMinute,
itDay2Minute,
itHour2Minute:
rInt.Minutes := AValue;
itSecond,
itDay2Second,
itHour2Second,
itMinute2Second:
rInt.Seconds := AValue;
else
NotInitError;
end;
DoIncrementBase(rInt, ASign);
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoInc(const AValue: Integer);
begin
DoIncrementBase(AValue, 1);
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoDec(const AValue: Integer);
begin
DoIncrementBase(AValue, -1);
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoDivide(AValue: Integer);
begin
if AValue < 0 then begin
AValue := Abs(AValue);
DoNegate;
end;
case FInterval.Kind of
itYear,
itMonth,
itYear2Month:
begin
FInterval.Years := FInterval.Years div Cardinal(AValue);
FInterval.Months := FInterval.Months div Cardinal(AValue);
end;
itDay,
itHour,
itMinute,
itSecond,
itDay2Hour,
itDay2Minute,
itDay2Second,
itHour2Minute,
itHour2Second,
itMinute2Second:
begin
FInterval.Days := FInterval.Days div Cardinal(AValue);
FInterval.Hours := FInterval.Hours div Cardinal(AValue);
FInterval.Minutes := FInterval.Minutes div Cardinal(AValue);
FInterval.Seconds := FInterval.Seconds div Cardinal(AValue);
FInterval.Fractions := FInterval.Fractions div Cardinal(AValue);
end;
else
NotInitError;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoMultiply(AValue: Integer);
begin
if AValue < 0 then begin
AValue := Abs(AValue);
DoNegate;
end;
case FInterval.Kind of
itYear,
itMonth,
itYear2Month:
begin
FInterval.Years := FInterval.Years * Cardinal(AValue);
FInterval.Months := FInterval.Months * Cardinal(AValue);
end;
itDay,
itHour,
itMinute,
itSecond,
itDay2Hour,
itDay2Minute,
itDay2Second,
itHour2Minute,
itHour2Second,
itMinute2Second:
begin
FInterval.Days := FInterval.Days * Cardinal(AValue);
FInterval.Hours := FInterval.Hours * Cardinal(AValue);
FInterval.Minutes := FInterval.Minutes * Cardinal(AValue);
FInterval.Seconds := FInterval.Seconds * Cardinal(AValue);
FInterval.Fractions := FInterval.Fractions * Cardinal(AValue);
end;
else
NotInitError;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.DoNegate;
begin
if FInterval.Sign < 0 then
FInterval.Sign := 1
else
FInterval.Sign := -1;
end;
{-------------------------------------------------------------------------------}
function TFDSQLTimeIntervalData.Compare(const AValue: TFDSQLTimeInterval): TVarCompareResult;
var
oData: TFDSQLTimeIntervalData;
begin
oData := TFDSQLTimeIntervalData.Create(FInterval);
try
oData.DoDec(AValue);
if oData.IsBlank then
Result := crEqual
else if oData.IsNegative then
Result := crLessThan
else
Result := crGreaterThan;
finally
FDFree(oData);
end;
end;
{-------------------------------------------------------------------------------}
function TFDSQLTimeIntervalData.GetAsString: string;
begin
if IsBlank then
Result := ''
else begin
case FInterval.Kind of
itYear,
itMonth,
itYear2Month:
Result := Format('%u-%.2u', [FInterval.Years, FInterval.Months]);
itDay:
Result := Format('%u', [FInterval.Days]);
itDay2Hour,
itDay2Minute,
itDay2Second:
begin
Result := Format('%u %.2u:%.2u:%.2u', [FInterval.Days, FInterval.Hours,
FInterval.Minutes, FInterval.Seconds]);
if FInterval.Fractions <> 0 then
Result := Result + Format('.%.3u', [FInterval.Fractions]);
end;
itHour,
itMinute,
itSecond,
itHour2Minute,
itHour2Second,
itMinute2Second:
begin
Result := Format('%u:%.2u:%.2u', [FInterval.Hours, FInterval.Minutes,
FInterval.Seconds]);
if FInterval.Fractions <> 0 then
Result := Result + Format('.%.3u', [FInterval.Fractions]);
end;
else
NotInitError;
end;
if FInterval.Sign < 0 then
Result := '-' + Result;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.SetAsString(const AValue: string);
var
pCh, pSep: PChar;
iSign: Integer;
procedure NextGroup;
begin
while pCh^ = ' ' do
Inc(pCh);
if pCh^ = '-' then begin
iSign := -1;
Inc(pCh);
end
else if pCh^ = '+' then
Inc(pCh);
end;
function NextItem(out APart: Cardinal; ADelim: Char; ARequired: Boolean): Boolean;
begin
if pCh^ = #0 then begin
Result := False;
Exit;
end;
pSep := StrScan(pCh, ADelim);
Result := pSep <> nil;
if not Result then
if ARequired then
Exit
else
pSep := PChar(AValue) + Length(AValue);
FDStr2Int(pCh, pSep - pCh, @APart, SizeOf(APart), True);
if pSep^ = #0 then
pCh := pSep
else
pCh := pSep + 1;
end;
procedure Error;
begin
raise EVariantError.CreateFmt('[%s] is not a valid interval', [AValue]);
end;
begin
FillChar(FInterval, SizeOf(FInterval), 0);
if AValue = '' then
Exit;
pCh := PChar(AValue);
iSign := 1;
NextGroup;
if NextItem(FInterval.Years, '-', True) then begin
NextItem(FInterval.Months, ' ', False);
FInterval.Kind := itYear2Month;
end
else begin
NextGroup;
if NextItem(FInterval.Days, ' ', True) then
FInterval.Kind := itDay;
NextGroup;
if NextItem(FInterval.Hours, ':', True) then begin
NextItem(FInterval.Minutes, ':', False);
NextItem(FInterval.Seconds, '.', False);
NextItem(FInterval.Fractions, #0, False);
if FInterval.Kind = itDay then
FInterval.Kind := itDay2Second
else
FInterval.Kind := itHour2Second;
end;
end;
if (pCh^ <> #0) or (FInterval.Kind = itUnknown) then
Error;
FInterval.Sign := iSign;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalData.CastToKind(AKind: TFDSQLTimeIntervalKind);
var
oData: TFDSQLTimeIntervalData;
begin
oData := TFDSQLTimeIntervalData.Create(C_NullSQLTimeInterval);
try
oData.Kind := AKind;
oData.DoInc(Interval);
Interval := oData.Interval;
finally
FDFree(oData);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDSQLTimeIntervalVariantType }
{-------------------------------------------------------------------------------}
function TFDSQLTimeIntervalVariantType.GetInstance(const V: TVarData): TObject;
begin
Result := PFDSQLTimeIntervalVarData(@V)^.VInterval;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalVariantType.Clear(var V: TVarData);
begin
V.VType := varEmpty;
FDFreeAndNil(PFDSQLTimeIntervalVarData(@V)^.VInterval);
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalVariantType.Cast(var Dest: TVarData; const Source: TVarData);
var
LSource: TVarData;
begin
VarDataInit(LSource);
try
VarDataCopyNoInd(LSource, Source);
if VarDataIsStr(LSource) then
PFDSQLTimeIntervalVarData(@Dest)^.VInterval := TFDSQLTimeIntervalData.Create(VarDataToStr(LSource))
else
RaiseCastError;
Dest.VType := VarType;
finally
VarDataClear(LSource);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalVariantType.CastTo(var Dest: TVarData;
const Source: TVarData; const AVarType: TVarType);
begin
if Source.VType = VarType then
case AVarType of
{$IFNDEF NEXTGEN}
varOleStr:
VarDataFromOleStr(Dest, PFDSQLTimeIntervalVarData(@Source)^.VInterval.AsString);
{$ELSE}
varOleStr,
{$ENDIF}
varUString:
VarDataFromStr(Dest, PFDSQLTimeIntervalVarData(@Source)^.VInterval.AsString);
varString:
VarDataFromLStr(Dest, PFDSQLTimeIntervalVarData(@Source)^.VInterval.AsString);
else
RaiseCastError;
end
else
inherited;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalVariantType.Copy(var Dest: TVarData;
const Source: TVarData; const Indirect: Boolean);
begin
if Indirect and VarDataIsByRef(Source) then
VarDataCopyNoInd(Dest, Source)
else begin
PFDSQLTimeIntervalVarData(@Dest)^.VType := VarType;
PFDSQLTimeIntervalVarData(@Dest)^.VInterval :=
TFDSQLTimeIntervalData.Create(PFDSQLTimeIntervalVarData(@Source)^.VInterval);
end;
end;
{-------------------------------------------------------------------------------}
function TFDSQLTimeIntervalVariantType.RightPromotion(const V: TVarData;
const Operator: TVarOp; out RequiredVarType: TVarType): Boolean;
begin
RequiredVarType := VarType;
Result := True;
case Operator of
opAdd:
if VarIsSQLTimeStamp(Variant(V)) then
RequiredVarType := VarSQLTimeStamp;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalVariantType.BinaryOp(var Left: TVarData;
const Right: TVarData; const Operator: TVarOp);
var
rTS: TSQLTimeStamp;
begin
case Operator of
opAdd:
if VarIsSQLTimeStamp(Variant(Right)) then begin
rTS := VarToSQLTimeStamp(Variant(Right));
PFDSQLTimeIntervalVarData(@Left)^.VInterval.DoAddTo(rTS);
Variant(Left) := VarSQLTimeStampCreate(rTS);
end
else
if FDVarIsSQLTimeInterval(Variant(Right)) then
PFDSQLTimeIntervalVarData(@Left)^.VInterval.DoInc(
PFDSQLTimeIntervalVarData(@Right)^.VInterval.Interval)
else if VarDataIsNumeric(Right) then
PFDSQLTimeIntervalVarData(@Left)^.VInterval.DoInc(Integer(Variant(Right)))
else
RaiseInvalidOp;
opSubtract:
if VarIsSQLTimeStamp(Variant(Right)) then begin
rTS := VarToSQLTimeStamp(Variant(Right));
PFDSQLTimeIntervalVarData(@Left)^.VInterval.DoSubFrom(rTS);
Variant(Left) := VarSQLTimeStampCreate(rTS);
end
else
if FDVarIsSQLTimeInterval(Variant(Right)) then
PFDSQLTimeIntervalVarData(@Left)^.VInterval.DoDec(
PFDSQLTimeIntervalVarData(@Right)^.VInterval.Interval)
else if VarDataIsNumeric(Right) then
PFDSQLTimeIntervalVarData(@Left)^.VInterval.DoDec(Integer(Variant(Right)))
else
RaiseInvalidOp;
opMultiply:
if VarDataIsNumeric(Right) then
PFDSQLTimeIntervalVarData(@Left)^.VInterval.DoMultiply(Integer(Variant(Right)))
else
RaiseInvalidOp;
opDivide:
if VarDataIsNumeric(Right) then
PFDSQLTimeIntervalVarData(@Left)^.VInterval.DoDivide(Integer(Variant(Right)))
else
RaiseInvalidOp;
else
RaiseInvalidOp;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalVariantType.UnaryOp(var Right: TVarData;
const Operator: TVarOp);
begin
case Operator of
opNegate:
if FDVarIsSQLTimeInterval(Variant(Right)) then
PFDSQLTimeIntervalVarData(@Right)^.VInterval.DoNegate
else
RaiseInvalidOp;
else
RaiseInvalidOp;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLTimeIntervalVariantType.Compare(const Left, Right: TVarData;
var Relationship: TVarCompareResult);
begin
Relationship := PFDSQLTimeIntervalVarData(@Left)^.VInterval.Compare(
PFDSQLTimeIntervalVarData(@Right)^.VInterval.Interval);
end;
{-------------------------------------------------------------------------------}
{ Utilities }
{-------------------------------------------------------------------------------}
function FDVarSQLTimeIntervalCreate: Variant;
begin
Result := FDVarSQLTimeIntervalCreate('');
end;
{-------------------------------------------------------------------------------}
function FDVarSQLTimeIntervalCreate(const AValue: string): Variant;
begin
VarClear(Result);
TVarData(Result).VType := GSQLTimeIntervalVariantType.VarType;
TFDSQLTimeIntervalData(TVarData(Result).VPointer) := TFDSQLTimeIntervalData.Create(AValue);
end;
{-------------------------------------------------------------------------------}
function FDVarSQLTimeIntervalCreate(const AValue: TFDSQLTimeInterval): Variant;
begin
VarClear(Result);
TVarData(Result).VType := GSQLTimeIntervalVariantType.VarType;
TFDSQLTimeIntervalData(TVarData(Result).VPointer) := TFDSQLTimeIntervalData.Create(AValue);
end;
{-------------------------------------------------------------------------------}
function FDVarSQLTimeInterval: TVarType;
begin
Result := GSQLTimeIntervalVariantType.VarType;
end;
{-------------------------------------------------------------------------------}
function FDVarIsSQLTimeInterval(const AValue: Variant): Boolean; overload;
begin
Result := TVarData(AValue).VType = GSQLTimeIntervalVariantType.VarType;
end;
{-------------------------------------------------------------------------------}
function FDVar2SQLTimeInterval(const AValue: Variant): TFDSQLTimeInterval;
var
oData: TFDSQLTimeIntervalData;
begin
case TVarData(AValue).VType of
varNull,
varEmpty:
Result := C_NullSQLTimeInterval;
varUString,
varString,
varOleStr:
begin
oData := TFDSQLTimeIntervalData.Create(String(AValue));
try
Result := oData.Interval;
finally
FDFree(oData);
end;
end;
else
if TVarData(AValue).VType = GSQLTimeIntervalVariantType.VarType then
Result := TFDSQLTimeIntervalData(TVarData(AValue).VPointer).Interval
else
raise EVariantError.Create(SInvalidVarCast);
end;
end;
{-------------------------------------------------------------------------------}
function FDStr2SQLTimeInterval(const AValue: String): TFDSQLTimeInterval;
var
oData: TFDSQLTimeIntervalData;
begin
oData := TFDSQLTimeIntervalData.Create(AValue);
try
Result := oData.Interval;
finally
FDFree(oData);
end;
end;
{-------------------------------------------------------------------------------}
function FDSQLTimeInterval2Str(const AValue: TFDSQLTimeInterval): String;
var
oData: TFDSQLTimeIntervalData;
begin
oData := TFDSQLTimeIntervalData.Create(AValue);
try
Result := oData.AsString;
finally
FDFree(oData);
end;
end;
{-------------------------------------------------------------------------------}
function FDSQLTimeIntervalCompare(const AValue1, AValue2: TFDSQLTimeInterval): Integer;
var
oData: TFDSQLTimeIntervalData;
begin
oData := TFDSQLTimeIntervalData.Create(AValue1);
try
case oData.Compare(AValue2) of
crLessThan: Result := -1;
crGreaterThan: Result := 1;
else Result := 0;
end;
finally
FDFree(oData);
end;
end;
{-------------------------------------------------------------------------------}
function FDSQLTimeIntervalCast(const AValue: TFDSQLTimeInterval;
AKind: TFDSQLTimeIntervalKind): TFDSQLTimeInterval;
var
oData: TFDSQLTimeIntervalData;
begin
oData := TFDSQLTimeIntervalData.Create(AValue);
try
oData.CastToKind(AKind);
Result := oData.Interval;
finally
FDFree(oData);
end;
end;
{-------------------------------------------------------------------------------}
initialization
GSQLTimeIntervalVariantType := TFDSQLTimeIntervalVariantType.Create;
finalization
FDFreeAndNil(GSQLTimeIntervalVariantType);
end.
|
unit ApacheAdapter;
{
*******************************************************************************************************************
ApaacheApapter: Decodes Apache Module reqeuest and response, triggers ApacheModule component
Author: Motaz Abdel Azeem
Forked from: http://wiki.freepascal.org/FPC_and_Apache_Modules
email: motaz@code.sd
Home page: http://code.sd
License: LGPL
Last modified: 27.July.2012
*******************************************************************************************************************
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, httpd, apr, SpiderApache, SpiderUtils, syncobjs;
function ProcessHandler(r: Prequest_rec; WebModule: TDataModuleClass; ModuleName,
HandlerName: string; ThreadPool: Boolean = True): Integer;
implementation
type
{ TMyWeb }
TMyWeb = class
public
IsFinished: Boolean;
HasError: Boolean;
Web: TDataModule;
constructor Create;
destructor Destroy; override;
end;
var
myWebPool: array of TMyWeb;
MyCS: TCriticalSection;
SecCS: TCriticalSection;
LastRequest: TDateTime;
(* GetDataModuleFromPool: Thread Pooling implementation *)
function GetDataModuleFromPool(WebModule: TDataModuleClass): TMyWeb;
var
i: Integer;
aWeb: TMyWeb;
Found: Boolean;
FirstEmpty: Integer;
AllFinished: Boolean;
begin
Result:= nil;
MyCS.Enter; // Enter critical section
Found:= False;
FirstEmpty:= -1;
try
// Remove all web modules in idle time to reduce memory leak
AllFinished:= True;
if (LastRequest + EncodeTime(0, 1, 0, 0) < Now) and (Length(myWebPool) > 0) then
begin
for i:= 0 to High(myWebPool) do
if (Assigned(myWebPool[i])) and (myWebPool[i].IsFinished) or (myWebPool[i].HasError) then
begin
myWebPool[i].Web.Free;
myWebPool[i].Free;
myWebPool[i]:= nil;;
end
else
if (AllFinished) and (Assigned(myWebPool[i])) then
AllFinished:= False;
if (Length(myWebPool) > 0) and AllFinished then
SetLength(myWebPool, 0);
end;
LastRequest:= Now;
// Search for new/reusable Web module
for i:= 0 to High(myWebPool) do
begin
// Remove buggy modules
if Assigned(myWebPool[i]) and (myWebPool[i].HasError) then
begin
myWebPool[i].Web.Free;
myWebPool[i].Free;
myWebPool[i]:= nil;
end;
// Get first empty slot index
if (FirstEmpty = -1) and not Assigned(myWebPool[i]) then
FirstEmpty:= i;
// Get usable web module
if Assigned(myWebPool[i]) and (myWebPool[i].IsFinished) and (not myWebPool[i].HasError) then
begin
Result:= myWebPool[i];
Found:= True;
Break;
end;
end;
// No available web module, create new one, add it to the pool
if not Found then
begin
Result:= TMyWeb.Create;
Result.IsFinished:= False;
Result.Web:= WebModule.Create(nil);
if FirstEmpty = -1 then
begin
SetLength(myWebPool, Length(myWebPool) + 1);
FirstEmpty:= High(myWebPool);
end;
myWebPool[FirstEmpty]:= Result;
end;
finally
MyCS.Leave;
end;
end;
function ProcessHandler(r: Prequest_rec; WebModule: TDataModuleClass; ModuleName,
HandlerName: string; ThreadPool: Boolean = True): Integer;
var
RequestedHandler: string;
Buf: array [0 .. 20024] of Char;
NumRead: Integer;
Line: string;
Head: Papr_array_header_t;
Access: Phtaccess_result;
aWeb: TMyWeb;
i: Integer;
SpiderApacheObj: TSpiderApache;
aResponse: TSpiderResponse;
ContentType: string;
j: Integer;
PostedData: string;
DataLen: Integer;
WebFound: Boolean;
FoundIndex: Integer;
CGICom: TSpiderCGI;
begin
RequestedHandler := r^.handler;
aWeb:= nil;
aResponse:= nil;
{ We decline to handle a request if configured handler is not the value of r^.handler }
if not SameText(RequestedHandler, HANDLERNAME) then
begin
Result := DECLINED;
Exit;
end;
ap_set_content_type(r, 'text/html');
{ If the request is for a header only, and not a request for
the whole content, then return OK now. We don't have to do
anything else. }
if (r^.header_only <> 0) then
begin
Result := OK;
Exit;
end;
try
Line:= '';
// read posted data
PostedData:= '';
if (r^.method = 'POST') then
begin
ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK);
repeat
NumRead:= ap_get_client_block(r, Buf, SizeOf(Buf));
SetLength(Line, NumRead);
Move(Buf, Pointer(Line)^, NumRead);
PostedData:= PostedData + Line;
until NumRead = 0;
end;
if ThreadPool then
begin
repeat
aWeb:= GetDataModuleFromPool(WebModule);
Sleep(2);
until aWeb <> nil;
end
else
begin
aWeb:= TMyWeb.Create;
aweb.Web:= WebModule.Create(nil);
end;
// Search for SpiderApache component in Web Data Module
with aWeb.web do
for i:= 0 to ComponentCount - 1 do
if Components[i] is TSpiderApache then
begin
aResponse:= nil;
SpiderApacheObj:= Components[i] as TSpiderApache;
ContentType:= apr_table_get(r^.headers_in, 'CONTENT-TYPE');
if Trim(ContentType) = '' then
ContentType:= r^.content_type;
// Intialize SpiderApache:
SpiderApacheObj.Init(r^.path_info, ContentType, r^.method, r^.args, apr_table_get(r^.headers_in, 'COOKIE'),
apr_table_get(r^.headers_in, 'User-Agent'), Posteddata, apr_table_get(r^.headers_in, 'Content-Length'),
apr_table_get(r^.headers_in, 'REFERER'), r^.connection^.remote_ip, r^.uri, ap_get_server_version, r^.hostname);
// Execute web application
aResponse:= SpiderApacheObj.Execute;
// Send response to the browser
if Assigned(aResponse) then
begin
// Content type
ap_set_content_type(r, PChar(aResponse.ContentType));
// Custome header
with aResponse.CustomHeader do
for j:= 0 to Count - 1 do
apr_table_set(r^.headers_out, PChar(Copy(Strings[j], 1, Pos(':', Strings[j]) - 1)),
PChar(Copy(Strings[j], Pos(':', Strings[j]) + 1, Length(Strings[j])) ));
// Response contents
DataLen:= Length(aResponse.Content.Text);
ap_rwrite(Pointer(aResponse.Content.Text), DataLen, r);
// Set cookies:
with aResponse.CookieList do
for j:= 0 to Count - 1 do
apr_table_set(r^.headers_out, 'Set-Cookie', PChar(Copy(Strings[j],
Pos(':', Strings[j]) + 1, Length(Strings[j]))));
aResponse.CookieList.Clear;
aResponse.CustomHeader.Clear;
aResponse.Content.Clear;
end;
Break;
end;
except
on e: exception do
begin
// Remove from pool
if ThreadPool and Assigned(aWeb) then
begin
if Assigned(aResponse) then
begin
aResponse.CookieList.Clear;
aResponse.CustomHeader.Clear;
aResponse.Content.Clear;
end;
SecCS.Enter;
try
aWeb.HasError:= True;
finally
SecCS.Leave;
end;
end;
ap_rputs(PChar('<br/> Error in WebModule : <font color=red>' + e.Message + '</font>'), r);
ap_log_error(PChar(MODULENAME), 54, APLOG_NOERRNO or APLOG_NOTICE,1,
r^.server, PChar(ModuleName + ': %s'), [PChar(e.Message)]);
Result:= 1;
end;
end;
if Assigned(aWeb) then
if ThreadPool then
begin
SecCS.Enter;
try
aWeb.IsFinished:= True
finally
SecCS.Leave;
end;
end
else
begin
aWeb.Web.Free;
aWeb.Free;
end;
Result:= Ok;
end;
{ TMyWeb }
constructor TMyWeb.Create;
begin
inherited Create;
IsFinished:= False;
HasError:= False;
Web:= nil;
end;
destructor TMyWeb.Destroy;
begin
inherited Destroy;
end;
initialization
MyCS:= TCriticalSection.Create;
SecCS:= TCriticalSection.Create;
end.
|
unit ncCredTempo;
{
ResourceString: Dario 12/03/13
}
interface
uses
SysUtils,
DB,
MD5,
Classes,
Windows,
ClasseCS,
ncEspecie,
ncClassesBase;
type
TncCredTempo = class
private
function GetString: String;
procedure SetString(const Value: String);
public
teID : Integer;
teDataHora : TDateTime;
teFunc : String;
teTipo : Byte;
teMinutos : Double;
teIDPacPass : Integer;
teTotal : Currency;
teDesconto : Currency;
tePago : Currency;
teCliente : Integer;
teMaq : Word;
teSessao : Integer;
tePassaporte: Integer;
teCancelado : Boolean;
teTran : Integer;
teCaixa : Integer;
teSenha : String;
teNome : String;
teTipoAcesso: Integer;
teObs : String;
teCredValor : Boolean;
teFidResgate : Boolean;
teFidPontos : Double;
tePagEsp : TncPagEspecies;
_Recibo : Boolean;
_Operacao : Byte;
constructor Create;
destructor Destroy; override;
procedure Limpa;
procedure AssignFrom(T: TncCredTempo);
function Igual(T: TncCredTempo): Boolean;
function MudouTempo(B: TncCredTempo): Boolean;
function Debito: Currency;
procedure SaveToDataset(D: TDataset);
procedure SaveToITranDataset(D: TDataset);
procedure SaveToTran(D: TDataset);
procedure SaveToStream(S: TStream);
procedure LoadFromDataset(D: TDataset);
procedure LoadFromStream(S: TStream);
property AsString: String
read GetString write SetString;
end;
TncCredTempos = class
private
FItens : TList;
function GetItem(I: Integer): TncCredTempo;
function GetString: String;
procedure SetString(Value: String);
public
constructor Create;
destructor Destroy; override;
procedure AjustaOperacao(B: TncCredTempos);
procedure Remove(CT: TncCredTempo);
procedure Limpa;
function Count: Integer;
function NewItem: TncCredTempo;
function TotCredTempoValido: TncTempo;
function GetItemByID(aID: Integer): TncCredTempo;
function GetItemByTran(aTran: Integer): TncCredTempo;
property Itens[I: Integer]: TncCredTempo
read GetItem; Default;
property AsString: String
read GetString write SetString;
end;
implementation
{ TncCredTempo }
procedure TncCredTempo.AssignFrom(T: TncCredTempo);
begin
teID := T.teID;
teDataHora := T.teDataHora;
teFunc := T.teFunc;
teTipo := T.teTipo;
teMinutos := T.teMinutos;
teIDPacPass := T.teIDPacPass;
teTotal := T.teTotal;
teDesconto := T.teDesconto;
tePago := T.tePago;
teCliente := T.teCliente;
teMaq := T.teMaq;
teSessao := T.teSessao;
tePassaporte := T.tePassaporte;
teCancelado := T.teCancelado;
teTran := T.teTran ;
teCaixa := T.teCaixa;
teSenha := T.teSenha;
teNome := T.teNome;
teTipoAcesso := T.teTipoAcesso;
teObs := T.teObs;
teCredValor := T.teCredValor;
teFidResgate := T.teFidResgate;
teFidPontos := T.teFidPontos;
tePagEsp.Assign(T.tePagEsp);
_Recibo := T._Recibo;
_Operacao := T._Operacao;
end;
constructor TncCredTempo.Create;
begin
tePagEsp := TncPagEspecies.Create;
Limpa;
end;
function TncCredTempo.Debito: Currency;
begin
if (not teCancelado) and (teSessao=0) then
Result := teTotal - teDesconto - tePago else
Result := 0;
end;
destructor TncCredTempo.Destroy;
begin
tePagEsp.Free;
inherited;
end;
function TncCredTempo.GetString: String;
begin
Result :=
IntToStr(teID) + sFldDelim(classid_TncCredTempo) +
GetDTStr(teDataHora) + sFldDelim(classid_TncCredTempo) +
teFunc + sFldDelim(classid_TncCredTempo) +
IntToStr(teTipo) + sFldDelim(classid_TncCredTempo) +
FloatParaStr(teMinutos) + sFldDelim(classid_TncCredTempo) +
IntToStr(teIDPacPass) + sFldDelim(classid_TncCredTempo) +
FloatParaStr(teTotal) + sFldDelim(classid_TncCredTempo) +
FloatParaStr(teDesconto) + sFldDelim(classid_TncCredTempo) +
FloatParaStr(tePago) + sFldDelim(classid_TncCredTempo) +
IntToStr(teCliente) + sFldDelim(classid_TncCredTempo) +
IntToStr(teMaq) + sFldDelim(classid_TncCredTempo) +
IntToStr(teSessao) + sFldDelim(classid_TncCredTempo) +
IntToStr(tePassaporte) + sFldDelim(classid_TncCredTempo) +
BoolStr[teCancelado] + sFldDelim(classid_TncCredTempo) +
IntToStr(teTran) + sFldDelim(classid_TncCredTempo) +
IntToStr(teCaixa) + sFldDelim(classid_TncCredTempo) +
teSenha + sFldDelim(classid_TncCredTempo) +
teNome + sFldDelim(classid_TncCredTempo) +
IntToStr(teTipoAcesso) + sFldDelim(classid_TncCredTempo) +
teObs + sFldDelim(classid_TncCredTempo) +
BoolStr[teCredValor] + sFldDelim(classid_TncCredTempo) +
BoolStr[teFidResgate] + sFldDelim(classid_TncCredTempo) +
FloatParaStr(teFidPontos) + sFldDelim(classid_TncCredTempo) +
tePagEsp.AsString + sFldDelim(classid_TncCredTempo) +
BoolStr[_Recibo] + sFldDelim(classid_TncCredTempo) +
IntToStr(_Operacao) + sFldDelim(classid_TncCredTempo);
end;
function TncCredTempo.Igual(T: TncCredTempo): Boolean;
begin
Result := False;
if teID <> T.teID then Exit;
if teDataHora <> T.teDataHora then Exit;
if teFunc <> T.teFunc then Exit;
if teTipo <> T.teTipo then Exit;
if teMinutos <> T.teMinutos then Exit;
if teIDPacPass <> T.teIDPacPass then Exit;
if teTotal <> T.teTotal then Exit;
if teDesconto <> T.teDesconto then Exit;
if tePago <> T.tePago then Exit;
if teCliente <> T.teCliente then Exit;
if teMaq <> T.teMaq then Exit;
if teSessao <> T.teSessao then Exit;
if tePassaporte <> T.tePassaporte then Exit;
if teCancelado <> T.teCancelado then Exit;
if teTran <> T.teTran then Exit;
if teCaixa <> T.teCaixa then Exit;
if teSenha <> T.teSenha then Exit;
if teNome <> T.teNome then Exit;
if teTipoAcesso <> T.teTipoAcesso then Exit;
if teObs <> T.teObs then Exit;
if teCredValor <> T.teCredValor then Exit;
if teFidResgate <> T.teFidResgate then Exit;
if teFidPontos <> T.teFidPontos then Exit;
if tePagEsp.AsString <> T.tePagEsp.AsString then Exit;
if _Operacao <> T._Operacao then Exit;
Result := True;
end;
procedure TncCredTempo.Limpa;
begin
teID := -1;
teDataHora := 0;
teFunc := '';
teTipo := tctPrevisao;
teMinutos := 0;
teIDPacPass := 0;
teTotal := 0;
teDesconto := 0;
tePago := 0;
teCliente := 0;
teMaq := 0;
teSessao := 0;
tePassaporte := 0;
teCancelado := False;
teTran := -1;
teCaixa := 0;
teSenha := '';
teNome := '';
teTipoAcesso := -1;
teObs := '';
teCredValor := False;
teFidResgate := False;
teFidPontos := 0;
tePagEsp.Clear;
_Operacao := osNenhuma;
_Recibo := False;
end;
procedure TncCredTempo.LoadFromDataset(D: TDataset);
begin
teID := D.FieldByName('ID').AsInteger; // do not localize
teDataHora := D.FieldByName('DataHora').AsDateTime; // do not localize
teFunc := D.FieldByName('Func').AsString; // do not localize
teTipo := D.FieldByName('Tipo').AsInteger; // do not localize
teMinutos := D.FieldByName('Minutos').AsFloat; // do not localize
teIDPacPass := D.FieldByName('IDPacPass').AsInteger; // do not localize
teTotal := D.FieldByName('Total').AsCurrency; // do not localize
teDesconto := D.FieldByName('Desconto').AsCurrency; // do not localize
tePago := D.FieldByName('Pago').AsCurrency; // do not localize
teCliente := D.FieldByName('Cliente').AsInteger; // do not localize
teMaq := D.FieldByName('Maq').AsInteger; // do not localize
teSessao := D.FieldByName('Sessao').AsInteger; // do not localize
tePassaporte := D.FieldByName('Passaporte').AsInteger; // do not localize
teCancelado := D.FieldByName('Cancelado').AsBoolean; // do not localize
teTran := D.FieldByName('Tran').AsInteger; // do not localize
teCaixa := D.FieldByName('Caixa').AsInteger; // do not localize
teSenha := D.FieldByName('Senha').AsString; // do not localize
teNome := D.FieldByName('Nome').AsString; // do not localize
teTipoAcesso := D.FieldByName('TipoAcesso').AsInteger; // do not localize
teObs := D.FieldByName('Obs').AsString; // do not localize
teCredValor := D.FieldByName('CredValor').AsBoolean; // do not localize
teFidResgate := D.FieldByName('FidResgate').AsBoolean; // do not localize
teFidPontos := D.FieldByName('FidPontos').AsFloat; // do not localize
_Recibo := False;
_Operacao := osNenhuma;
end;
procedure TncCredTempo.LoadFromStream(S: TStream);
var
Str: String;
I: Integer;
begin
S.Read(I, SizeOf(I));
if I>0 then begin
SetLength(Str, I);
S.Read(Str[1], I);
AsString := Str;
end else
Limpa;
end;
function TncCredTempo.MudouTempo(B: TncCredTempo): Boolean;
begin
Result :=
(B.teTipo <> teTipo) or
(B.teMinutos <> teMinutos) or
(B.teCliente <> teCliente) or
((B.teTipo = tctPassaporte) or
(B.teIDPacPass <> teIDPacPass));
end;
procedure TncCredTempo.SaveToDataset(D: TDataset);
begin
D.FieldByName('DataHora').AsDateTime := teDataHora; // do not localize
D.FieldByName('Func').AsString := teFunc; // do not localize
D.FieldByName('Tipo').AsInteger := teTipo; // do not localize
D.FieldByName('Minutos').AsFloat := teMinutos; // do not localize
D.FieldByName('IDPacPass').AsInteger := teIDPacPass; // do not localize
D.FieldByName('Total').AsCurrency := teTotal; // do not localize
D.FieldByName('Desconto').AsCurrency := teDesconto; // do not localize
D.FieldByName('Pago').AsCurrency := tePago; // do not localize
D.FieldByName('Cliente').AsInteger := teCliente; // do not localize
D.FieldByName('Maq').AsInteger := teMaq; // do not localize
D.FieldByName('Sessao').AsInteger := teSessao; // do not localize
D.FieldByName('Passaporte').AsInteger := tePassaporte; // do not localize
D.FieldByName('Cancelado').AsBoolean := teCancelado; // do not localize
D.FieldByName('Tran').AsInteger := teTran; // do not localize
D.FieldByName('Caixa').AsInteger := teCaixa; // do not localize
D.FieldByName('Senha').AsString := teSenha; // do not localize
D.FieldByName('Nome').AsString := teNome; // do not localize
D.FieldByName('TipoAcesso').AsInteger := teTipoAcesso; // do not localize
D.FieldByname('Obs').AsString := teObs; // do not localize
D.FieldByName('CredValor').AsBoolean := teCredValor; // do not localize
D.FieldByName('FidResgate').AsBoolean := teFidResgate; // do not localize
D.FieldByName('FidPontos').AsFloat := teFidPontos; // do not localize
end;
procedure TncCredTempo.SaveToITranDataset(D: TDataset);
begin
D.FieldByName('Tran').AsInteger := teTran; // do not localize
D.FieldByName('Caixa').AsInteger := teCaixa; // do not localize
D.FieldByName('DataHora').AsDateTime := teDataHora; // do not localize
D.FieldByName('Caixa').AsInteger := teCaixa; // do not localize
D.FieldByName('TipoItem').AsInteger := itTempo; // do not localize
D.FieldByName('TipoTran').AsInteger := trCredTempo; // do not localize
D.FieldByName('ItemID').AsInteger := teID; // do not localize
D.FieldByname('ItemPos').AsInteger := 1; // do not localize
D.FieldByName('Total').AsCurrency := teTotal; // do not localize
D.FieldByName('Desconto').AsCurrency := teDesconto; // do not localize
D.FieldByName('Pago').AsCurrency := tePago; // do not localize
D.FieldByName('Cancelado').AsBoolean := teCancelado; // do not localize
D.FieldByName('Sessao').AsInteger := teSessao; // do not localize
if teFidResgate then begin
D.FieldByName('FidFator').AsInteger := -1; // do not localize
D.FieldByName('FidPontos').AsFloat := teFidPontos; // do not localize
end else begin
D.FieldByName('FidFator').Clear; // do not localize
D.FieldByName('FidPontos').Clear; // do not localize
end;
end;
procedure TncCredTempo.SaveToStream(S: TStream);
var
Str: String;
I: Integer;
begin
Str := AsString;
I := Length(Str);
S.Write(I, SizeOf(I));
if I>0 then
S.Write(Str[1], I);
end;
procedure TncCredTempo.SaveToTran(D: TDataset);
begin
D.FieldByName('Caixa').AsInteger := teCaixa; // do not localize
D.FieldByName('DataHora').AsDateTime := teDataHora; // do not localize
D.FieldByName('Caixa').AsInteger := teCaixa; // do not localize
D.FieldByName('Total').AsCurrency := teTotal; // do not localize
D.FieldByName('Desconto').AsCurrency := teDesconto; // do not localize
D.FieldByName('Pago').AsCurrency := tePago; // do not localize
D.FieldByName('Cancelado').AsBoolean := teCancelado; // do not localize
D.FieldByName('Sessao').AsInteger := teSessao; // do not localize
D.FieldByName('Cliente').AsInteger := teCliente; // do not localize
D.FieldByName('Func').AsString := teFunc; // do not localize
D.FieldByName('Maq').AsInteger := teMaq; // do not localize
D.FieldByName('Tipo').AsInteger := trCredTempo; // do not localize
D.FieldByName('Obs').AsString := teObs; // do not localize
D.FieldByName('FidResgate').AsBoolean := teFidResgate; // do not localize
end;
procedure TncCredTempo.SetString(const Value: String);
var S: String;
function pCampo: String;
begin
Result := GetNextStrDelim(S, classid_TncCredTempo);
end;
begin
Limpa;
S := Value;
teID := StrToIntDef(pCampo, -1);
teDataHora := DTFromStr(pCampo);
teFunc := pCampo;
teTipo := StrToIntDef(pCampo, 0);
teMinutos := StrParaFloat(pCampo);
teIDPacPass := StrToIntDef(pCampo, 0);
teTotal := StrParaFloat(pCampo);
teDesconto := StrParaFloat(pCampo);
tePago := StrParaFloat(pCampo);
teCliente := StrToIntDef(pCampo, 0);
teMaq := StrToIntDef(pCampo, 0);
teSessao := StrToIntDef(pCampo, 0);
tePassaporte := StrToIntDef(pCampo, 0);
teCancelado := (BoolStr[True]=pCampo);
teTran := StrToIntDef(pCampo, -1);
teCaixa := StrToIntDef(pCampo, 0);
teSenha := pCampo;
teNome := pCampo;
teTipoAcesso := StrToIntDef(pCampo, -1);
teObs := pCampo;
teCredValor := (BoolStr[True]=pCampo);
teFidResgate := (BoolStr[True]=pCampo);
teFidPontos := StrParaFloat(pCampo);
tePagEsp.AsString := pCampo;
_Recibo := (BoolStr[True]=pCampo);
_Operacao := StrToIntDef(pCampo, osNenhuma);
end;
{ TncCredTempos }
procedure TncCredTempos.AjustaOperacao(B: TncCredTempos);
var
I : Integer;
T : TncCredTempo;
begin
for I := 0 to Count - 1 do with Itens[I] do
if (teID<>-1) and (B.GetItemByID(teID)=nil) then
_Operacao := osExcluir;
for I := 0 to B.Count - 1 do
if (B[I].teID=-1) then begin
if (B[I]._Operacao<>osCancelar) then begin
B[I]._Operacao := osIncluir;
NewItem.AssignFrom(B[I]);
end;
end
else begin
T := GetItemByID(B[I].teID);
if T<>nil then begin
if B[I]._Operacao=osCancelar then
T._Operacao := osCancelar
else begin
T.AssignFrom(B[I]);
T._Operacao := osAlterar;
end;
end;
end;
for I := Count-1 downto 0 do
if Itens[I]._Operacao=osNenhuma then begin
Itens[I].Free;
FItens.Delete(I);
end;
end;
function TncCredTempos.Count: Integer;
begin
Result := FItens.Count;
end;
constructor TncCredTempos.Create;
begin
FItens := TList.Create;
end;
destructor TncCredTempos.Destroy;
begin
Limpa;
FItens.Free;
inherited;
end;
function TncCredTempos.GetItem(I: Integer): TncCredTempo;
begin
Result := TncCredTempo(FItens[I]);
end;
function TncCredTempos.GetItemByID(aID: Integer): TncCredTempo;
var I : Integer;
begin
for I := 0 to FItens.Count - 1 do with Itens[I] do
if teID=aID then begin
Result := Itens[I];
Exit;
end;
Result := nil;
end;
function TncCredTempos.GetItemByTran(aTran: Integer): TncCredTempo;
var I : Integer;
begin
for I := 0 to FItens.Count - 1 do with Itens[I] do
if teTran=aTran then begin
Result := Itens[I];
Exit;
end;
Result := nil;
end;
function TncCredTempos.GetString: String;
var I : Integer;
begin
Result := '';
for I := 0 to Count - 1 do
Result := Result + Itens[I].AsString + sListaDelim(classid_TncCredTempos);
end;
procedure TncCredTempos.Limpa;
begin
while Count>0 do begin
Itens[0].Free;
FItens.Delete(0);
end;
end;
function TncCredTempos.NewItem: TncCredTempo;
begin
Result := TncCredTempo.Create;
FItens.Add(Result);
end;
procedure TncCredTempos.Remove(CT: TncCredTempo);
begin
FItens.Remove(CT);
end;
procedure TncCredTempos.SetString(Value: String);
var S: String;
begin
Limpa;
while GetNextListItem(Value, S, classid_TncCredTempos) do
NewItem.AsString := S;
end;
function TncCredTempos.TotCredTempoValido: TncTempo;
var I : Integer;
begin
Result.MInutos := 0;
for I := 0 to Count-1 do with Itens[I] do
if (not teCancelado) and (teTipo in [tctAvulso, tctPacote]) then
Result.Minutos := Result.Minutos + teMinutos;
end;
end.
|
{
IPINFO v0.1
Implements some classes to obtain informations
about the network configuration and network adapters.
Based on the work of http://www.whirlwater.com/
This materia is provied "as is"
without any warranty of any kind.
By Leonardo Perria - 2003
leoperria@tiscali.it
Very poor implementation at the moment....be patient.
}
unit IPInfo;
interface
uses
Windows, Messages, SysUtils, Classes,
Contnrs, IPHelperDef;
procedure GetNetworkParameters(Dest:TStrings); // TODO: Da eliminare e integrare in TIPInfo
type
TIP = record
n1, n2, n3, n4 : byte;
end;
TInfoIPAddress=class
private
FAddress:string;
FNetmask:string;
public
constructor Create(Addr : PIPAddrString);
destructor Destroy; override;
property Address:string read FAddress;
property Netmask:string read FNetmask;
function asString() : string;
end;
TAdapter=class
private
FComboIndex: integer;
FName: string;
FDescription: string;
FHWAddressLength : Integer;
FHWAddress: string;
FAIndex: integer;
FAType: integer; // see IPIfCons.H
FDHCPEnabled: boolean;
FCurrentIPAddress : TInfoIPAddress;
FIPAddressList: TObjectList;
FGatewayList : TObjectList;
FDHCPServer : TInfoIPAddress;
FHaveWINS : boolean;
FPrimaryWINSServer : TInfoIPAddress;
FSecondaryWINSServer : TInfoIPAddress;
// LeaseObtained : Integer;
// LeaseExpires : Integer;
function GetIPAddress(index : integer) : TInfoIPAddress;
function GetMaxIPAddresses() : integer;
function GetGateway(index : integer) : TInfoIPAddress;
function GetMaxGateways() : integer;
public
constructor Create(adapterInfo:PIPAdapterInfo);
destructor Destroy; override;
property Name: string read FName;
property Description : string read FDescription;
property ComboIndex : integer read FComboIndex;
property HWAddressLength : Integer read FHWAddressLength;
property HWAddress: string read FHWAddress;
property AIndex: integer read FAIndex;
property AType: integer read FAType;
property DHCPEnabled: boolean read FDHCPEnabled;
property CurrentIPAddress : TInfoIPAddress read FCurrentIPAddress;
property IPAddresses[index : integer] : TInfoIPAddress read GetIPAddress;
property MaxIPAddresses : integer read GetMaxIPAddresses;
property Gateways[index : integer] : TInfoIPAddress read GetGateway;
property MaxGateways : integer read GetMaxGateways;
property DHCPServer : TInfoIPAddress read FDHCPServer;
property HaveWINS : boolean read FHaveWINS;
property PrimaryWINSServer : TInfoIPAddress read FPrimaryWINSServer;
property SecondaryWINSServer : TInfoIPAddress read FSecondaryWINSServer;
end;
TIPInfo=class(TObject)
private
FAdapters: TObjectList;
function getMaxAdapters(): integer;
function GetAdapter(index:integer) : TAdapter;
public
Constructor Create;
Destructor Destroy;override;
property Adapters[index: Integer]: TAdapter read GetAdapter;
property MaxAdapters:integer read getMaxAdapters;
end;
function IsNumeric(const AString: string): Boolean;
function StrToIp(addr:string):TIP;
function checkIP(var addr:string):boolean;
function StripIP(addr:string):string;
function IPinNetwork(ip,nw:string):boolean;
implementation
{$HINTS OFF}
function IsNumeric(const AString: string): Boolean;
var
LCode: Integer;
LVoid: Integer;
begin
Val(AString, LVoid, LCode);
Result := LCode = 0;
end;
{$HINTS ON}
function checkIP(var addr:string):boolean;
var
n, raddr : string;
begin
result := false;
if pos('.', addr)>0 then begin
n := copy(addr, 1, pos('.', addr)-1);
if isNumeric(n) and (strToint(n)>=0) and (strToint(n)<256) then begin
raddr := n + '.';
end else
raddr := '0.';
addr := copy(addr, pos('.', addr)+1, 15);
if pos('.', addr)>0 then begin
n := copy(addr, 1, pos('.', addr)-1);
if isNumeric(n) and (strToint(n)>=0) and (strToint(n)<256) then begin
raddr := raddr + n + '.';
end else
raddr := raddr + '0.';
addr := copy(addr, pos('.', addr)+1, 15);
if pos('.', addr)>0 then begin
n := copy(addr, 1, pos('.', addr)-1);
if isNumeric(n) and (strToint(n)>=0) and (strToint(n)<256) then begin
raddr := raddr + n + '.';
end else
raddr := raddr + '0.';
n := copy(addr, pos('.', addr)+1, 15);
if isNumeric(n) and (strToint(n)>=0) and (strToint(n)<256) then begin
raddr := raddr + n ;
result := true;
end else
raddr := raddr + '0';
end else
raddr := raddr + '0.0';
end else
raddr := raddr + '0.0.0';
end else
raddr := '0.0.0.0';
addr := raddr;
end;
function StripIP(addr:string):string;
begin
if pos(':', addr)>0 then
addr := copy(addr, 1, pos(':', addr)-1);
result := addr;
checkIP(result);
end;
function StrToIp(addr:string):TIP;
var
n : string;
begin
if pos('.', addr)>0 then begin
n := copy(addr, 1, pos('.', addr)-1);
if isNumeric(n) and (strToint(n)>=0) and (strToint(n)<256) then begin
result.n1 := strtoint(n);
end else
result.n1 := 0;
addr := copy(addr, pos('.', addr)+1, 15);
if pos('.', addr)>0 then begin
n := copy(addr, 1, pos('.', addr)-1);
if isNumeric(n) and (strToint(n)>=0) and (strToint(n)<256) then begin
result.n2 := strtoint(n);
end else
result.n2 := 0;
addr := copy(addr, pos('.', addr)+1, 15);
if pos('.', addr)>0 then begin
n := copy(addr, 1, pos('.', addr)-1);
if isNumeric(n) and (strToint(n)>=0) and (strToint(n)<256) then begin
result.n3 := strtoint(n);
end else
result.n3 := 0;
n := copy(addr, pos('.', addr)+1, 15);
if isNumeric(n) and (strToint(n)>=0) and (strToint(n)<256) then begin
result.n4 := strtoint(n);
end else
result.n4 := 0;
end;
end;
end;
end;
function IPinNetwork(ip, nw:string):boolean;
var
nip, nnw : TIp;
begin
result := false;
if (checkIP(ip)) and (checkIP(nw)) then begin
nip := StrToIp(ip);
nnw := StrToIp(nw);
result := ((nnw.n1=0 ) or (nnw.n1=nip.n1) ) and
((nnw.n2=0 ) or (nnw.n2=nip.n2) ) and
((nnw.n3=0 ) or (nnw.n3=nip.n3) ) and
((nnw.n4=0 ) or (nnw.n4=nip.n4) );
end;
end;
constructor TInfoIPAddress.Create(Addr : PIPAddrString);
begin
if Addr<>nil then begin
FAddress:=Addr^.IPAddress;
FNetmask:=Addr^.IPMask;
end
else begin
FAddress:='';
FNetmask:='';
end;
end;
function TInfoIPAddress.asString() : string;
begin
if (FAddress='') and (FNetmask='') then
Result:=''
else
Result:=FAddress+'/'+FNetmask;
end;
destructor TInfoIPAddress.Destroy;
begin
inherited;
end;
constructor TAdapter.Create(adapterInfo:PIPAdapterInfo);
Function MACToStr(ByteArr : PByte; Len : Integer) : String;
Begin
Result := '';
While (Len > 0) do Begin
Result := Result+IntToHex(ByteArr^,2)+':';
ByteArr := Pointer(Integer(ByteArr)+SizeOf(Byte));
Dec(Len);
End;
SetLength(Result,Length(Result)-1); { remove last dash }
End;
procedure PopulateAddressList(Addr : PIPAddrString; List: TObjectList);
begin
List.Clear;
While (Addr <> nil) do Begin
List.Add(TInfoIPAddress.Create(Addr));
Addr := Addr^.Next;
End;
end;
{ TODO: Implementare i LeaseTime
Function TimeTToDateTimeStr(TimeT : Integer) : String;
Const UnixDateDelta = 25569;
Var
DT : TDateTime;
TZ : TTimeZoneInformation;
Res : DWord;
Begin
If (TimeT = 0) Then Result := ''
Else Begin
DT := UnixDateDelta+(TimeT / (24*60*60));
Res := GetTimeZoneInformation(TZ);
If (Res = TIME_ZONE_ID_INVALID) Then RaiseLastOSError;
If (Res = TIME_ZONE_ID_STANDARD) Then Begin
DT := DT-((TZ.Bias+TZ.StandardBias) / (24*60));
Result := DateTimeToStr(DT)+' '+WideCharToString(TZ.StandardName);
End
Else Begin
DT := DT-((TZ.Bias+TZ.DaylightBias) / (24*60));
Result := DateTimeToStr(DT)+' '+WideCharToString(TZ.DaylightName);
End;
End;
End;
}
begin
FIPAddressList:=TObjectList.Create(True);
FGatewayList:=TObjectList.Create(True);
FName:=adapterInfo^.AdapterName;
FDescription:=adapterInfo^.Description;
FHWAddressLength:=adapterInfo^.AddressLength;
FHWAddress:=MACToStr(@adapterInfo^.Address,adapterInfo^.AddressLength);
FAIndex:=adapterInfo^.Index;
FAType:=adapterInfo^._Type;
if adapterInfo^.DHCPEnabled<>0 then FDHCPEnabled:=True else FDHCPEnabled:=False;
FCurrentIPAddress:=TInfoIPAddress.Create(adapterInfo.CurrentIPAddress);
PopulateAddressList(@adapterInfo^.IPAddressList,FIPAddressList);
PopulateAddressList(@adapterInfo^.GatewayList,FGatewayList);
FDHCPServer :=TInfoIPAddress.Create(@adapterInfo.DHCPServer);
if adapterInfo^.HaveWINS then FHaveWINS:=True else FHaveWINS:=False;
FPrimaryWINSServer:=TInfoIPAddress.Create(@adapterInfo.PrimaryWINSServer);
FSecondaryWINSServer:=TInfoIPAddress.Create(@adapterInfo.SecondaryWINSServer);
end;
function TAdapter.GetIPAddress(index : integer) : TInfoIPAddress;
begin
Result:=FIPAddressList.Items[index] as TInfoIPAddress;
end;
function TAdapter.GetMaxIPAddresses() : integer;
begin
Result:=FIPAddressList.Count;
end;
function TAdapter.GetGateway(index : integer) : TInfoIPAddress;
begin
Result:=FGatewayList.Items[index] as TInfoIPAddress;
end;
function TAdapter.GetMaxGateways() : integer;
begin
Result:=FGatewayList.Count;
end;
destructor TAdapter.Destroy;
begin
FCurrentIPAddress.Free;
FIPAddressList.Free;
FGatewayList.Free;
FDHCPServer.Free;
FPrimaryWINSServer.Free;
FSecondaryWINSServer.Free;
end;
constructor TIPInfo.Create;
Var
AI,Work : PIPAdapterInfo;
Size : Integer;
Res : Integer;
//I : Integer;
adapter : TAdapter;
begin
// Lista di adattatori
FAdapters:=TObjectList.Create(True);
Size := 5120;
GetMem(AI,Size);
Res := GetAdaptersInfo(AI,Size);
If (Res <> ERROR_SUCCESS) Then Begin
SetLastError(Res);
RaiseLastOSError;
End;
Work := AI;
Repeat
adapter:=TAdapter.Create(Work);
FAdapters.Add(adapter);
Work := Work^.Next;
Until (Work = nil);
FreeMem(AI);
inherited;
end;
destructor TIPInfo.Destroy;
begin
FAdapters.Free;
FAdapters := nil;
inherited;
end;
function TIPInfo.GetAdapter(index:integer) : TAdapter;
begin
Result:=FAdapters.Items[index] as TAdapter;
end;
function TIPInfo.getMaxAdapters(): integer;
begin
Result:=FAdapters.Count;
end;
procedure GetNetworkParameters(Dest:TStrings);
Var
FI : PFixedInfo;
Size : Integer;
Res : Integer;
I : Integer;
DNS : PIPAddrString;
begin
Size := 1024;
GetMem(FI,Size);
Res := GetNetworkParams(FI,Size);
If (Res <> ERROR_SUCCESS) Then Begin
SetLastError(Res);
RaiseLastOSError;
End;
With Dest do Begin
Clear;
Add('Host name: '+FI^.HostName);
Add('Domain name: '+FI^.DomainName);
If (FI^.CurrentDNSServer <> nil) Then
Add('Current DNS Server: '+FI^.CurrentDNSServer^.IPAddress)
Else Add('Current DNS Server: (none)');
I := 1;
DNS := @FI^.DNSServerList;
Repeat
Add('DNS '+IntToStr(I)+': '+DNS^.IPAddress);
Inc(I);
DNS := DNS^.Next;
Until (DNS = nil);
Add('Scope ID: '+FI^.ScopeId);
Add('Routing: '+IntToStr(FI^.EnableRouting));
Add('Proxy: '+IntToStr(FI^.EnableProxy));
Add('DNS: '+IntToStr(FI^.EnableDNS));
End;
FreeMem(FI);
end;
end.
|
unit RemoveSpaceAtLineEnd;
{ AFS 10 May 2003
remove trainling spaces on lines
makes test fail, false delta }
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is RemoveSpaceAtLineEnd, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses SwitchableVisitor;
type
TRemoveSpaceAtLineEnd = class(TSwitchableVisitor)
private
protected
function EnabledVisitSourceToken(const pcNode: TObject): Boolean; override;
public
constructor Create; override;
function IsIncludedInSettings: boolean; override;
end;
implementation
uses JcfSettings, FormatFlags, SourceToken, Tokens, TokenUtils;
constructor TRemoveSpaceAtLineEnd.Create;
begin
inherited;
FormatFlags := FormatFlags + [eRemoveSpace];
end;
function TRemoveSpaceAtLineEnd.EnabledVisitSourceToken(const pcNode: TObject): Boolean;
var
lcSourceToken, lcNext: TSourceToken;
begin
Result := False;
lcSourceToken := TSourceToken(pcNode);
{ is this white space? }
if lcSourceToken.TokenType = ttWhiteSpace then
begin
{ is a return next ? }
lcNext := lcSourceToken.NextTokenWithExclusions([ttWhiteSpace]);
if (lcNext <> nil) and (lcNext.TokenType = ttReturn) then
begin
BlankToken(lcSourceToken);
end;
end;
end;
function TRemoveSpaceAtLineEnd.IsIncludedInSettings: boolean;
begin
Result := JcfFormatSettings.Spaces.FixSpacing;
end;
end.
|
Unit UnAtualizacao;
interface
Uses Classes, DbTables,SysUtils, APrincipal, Windows, Forms, UnVersoes,
SQLExpr,IniFiles, UnProgramador1, Tabela ;
Const
CT_VersaoBanco = 2122;
CT_VersaoInvalida = 'SISTEMA DESATUALIZADO!!! Este sistema já possui novas versões, essa versão pode não funcionar corretamente, para o bom funcionamento do mesmo é necessário fazer a atualização...' ;
CT_SenhaAtual = '9774';
{CFG_FISCAL
C_OPT_SIM
CadFormasPagamento
C_FLA_BCP
C_FLA_BCR
CFG_FISCAL
I_CLI_DEV
C_EST_ICM
CFG_GERAL
C_COT_TPR
CFG_FINANCEIRO
C_CON_CAI
AMOSTRA
DESDEPARTAMENTO
INDCOPIA
}
Type
TAtualiza = Class
Private
Aux : TSQLQuery;
Tabela,
Cadastro : TSQL;
VprBaseDados : TSQLConnection;
FunProgramador1 : TRBFunProgramador1;
function RCodClienteDisponivel : Integer;
procedure AtualizaSenha( Senha : string );
procedure AlteraVersoesSistemas(VpaNomCampo, VpaDesVersao : String);
procedure VerificaVersaoSistema;
procedure CadastraTransportadorasComoClientes;
public
constructor criar( aowner : TComponent; VpaBaseDados : TSQLConnection );
destructor destroy;override;
procedure AtualizaTabela(VpaNumAtualizacao : Integer);
function AtualizaTabela1(VpaNumAtualizacao : Integer): String;
function AtualizaTabela2(VpaNumAtualizacao : Integer): String;
function AtualizaTabela3(VpaNumAtualizacao : Integer): String;
function AtualizaTabela4(VpaNumAtualizacao : Integer): String;
function AtualizaTabela5(VpaNumAtualizacao : Integer): String;
procedure AtualizaBanco;
procedure AtualizaNumeroVersaoSistema;
end;
implementation
Uses FunSql, ConstMsg, FunNumeros,Registry, Constantes, FunString, funvalida, FunArquivos;
{*************************** cria a classe ************************************}
constructor TAtualiza.criar( aowner : TComponent; VpaBaseDados : TSQLConnection );
begin
inherited Create;
VprBaseDados := VpaBasedados;
Aux := TSQLQuery.Create(aowner);
Aux.SQLConnection := VpaBaseDados;
Tabela := TSql.create(nil);
Tabela.ASQLConnection := VpaBaseDados;
Cadastro := TSql.create(nil);
Cadastro.ASQLConnection := VpaBaseDados;
FunProgramador1 := TRBFunProgramador1.cria(VpaBaseDados);
end;
destructor TAtualiza.destroy;
begin
FunProgramador1.Free;
Aux.Free;
inherited;
end;
{******************************************************************************}
function TAtualiza.RCodClienteDisponivel: Integer;
begin
AdicionaSQLAbreTabela(Aux,'Select max(I_COD_CLI) ULTIMO from CADCLIENTES');
result := Aux.FieldByName('ULTIMO').AsInteger + 1;
aux.Close;
end;
{*************** atualiza senha na base de dados ***************************** }
procedure TAtualiza.AtualizaSenha( Senha : string );
var
ini : TRegIniFile;
senhaInicial : string;
begin
try
// atualiza regedit
Ini := TRegIniFile.Create('Software\Systec\Sistema');
senhaInicial := Ini.ReadString('SENHAS','BANCODADOS', ''); // guarda senha do banco
Ini.WriteString('SENHAS','BANCODADOS', Criptografa(senha)); // carrega senha do banco
// atualiza base de dados
LimpaSQLTabela(aux);
AdicionaSQLTabela(Aux, 'grant connect, to DBA identified by ''' + senha + '''');
Aux.ExecSQL;
ini.free;
except
Ini.WriteString('SENHAS','BANCODADOS', senhaInicial);
ini.free;
end;
end;
{*********************** atualiza o banco de dados ****************************}
procedure TAtualiza.AtualizaBanco;
begin
AdicionaSQLAbreTabela(Aux,'Select I_Ult_Alt from Cfg_Geral ');
if Aux.FieldByName('I_Ult_Alt').AsInteger < CT_VersaoBanco Then
AtualizaTabela(Aux.FieldByName('I_Ult_Alt').AsInteger);
Aux.Close;
FunProgramador1.AtualizaBanco;
VerificaVersaoSistema
end;
{******************************************************************************}
procedure TAtualiza.AtualizaNumeroVersaoSistema;
var
VpfRegistry : TIniFile;
begin
VpfRegistry := TIniFile.Create(RetornaDiretorioCorrente+'\'+ varia.ParametroBase+ '.ini');
if UpperCase(CampoPermissaoModulo) = 'C_MOD_PON' then
VpfRegistry.WriteString('VERSAO','PONTOLOJA',VersaoPontoLoja)
else
if UpperCase(CampoPermissaoModulo) = 'C_CON_SIS' then
VpfRegistry.WriteString('VERSAO','CONFIGURACAOSISTEMA',VersaoConfiguracaoSistema)
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_FIN' then
VpfRegistry.WriteString('VERSAO','FINANCEIRO',VersaoFinanceiro)
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_FAT' then
VpfRegistry.WriteString('VERSAO','FATURAMENTO',VersaoFaturamento)
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_EST' then
VpfRegistry.WriteString('VERSAO','ESTOQUE',VersaoEstoque)
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_CHA' then
VpfRegistry.WriteString('VERSAO','CHAMADO',VersaoChamadoTecnico)
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_AGE' then
VpfRegistry.WriteString('VERSAO','AGENDA',VersaoAgenda)
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_CRM' then
VpfRegistry.WriteString('VERSAO','CRM',VersaoCRM)
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_CAI' then
VpfRegistry.WriteString('VERSAO','CAIXA',VersaoCaixa)
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_PDV' then
VpfRegistry.WriteString('VERSAO','PDV',VersaoPDV);
VpfRegistry.Free;
end;
{****************** verifica a versao do sistema ******************************}
procedure TAtualiza.VerificaVersaoSistema;
var
VpfVersaoSistema : String;
begin
if CampoPermissaoModulo <> 'SISCORP' then
Begin
AdicionaSQLAbreTabela(Aux,'Select '+SQlTextoIsNull(CampoPermissaoModulo,'0')+ CampoPermissaoModulo +
' from cfg_geral ');
if UpperCase(CampoPermissaoModulo) = 'C_MOD_EST' THEN
VpfVersaoSistema := VersaoEstoque
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_FAT' THEN
VpfVersaoSistema := VersaoFaturamento
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_PON' THEN
VpfVersaoSistema := VersaoPontoLoja
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_CHA' THEN
VpfVersaoSistema := VersaoChamadoTecnico
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_FIN' THEN
VpfVersaoSistema := VersaoFinanceiro
else
if UpperCase(CampoPermissaoModulo) = 'C_CON_SIS' THEN
VpfVersaoSistema := VersaoConfiguracaoSistema
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_AGE' THEN
VpfVersaoSistema := VersaoAgenda
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_CRM' THEN
VpfVersaoSistema := VersaoCRM
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_CAI' THEN
VpfVersaoSistema := VersaoCaixa
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_SIP' THEN
VpfVersaoSistema := VersaoSistemaPedido
else
if UpperCase(CampoPermissaoModulo) = 'C_MOD_PDV' THEN
VpfVersaoSistema := VersaoPDV;
if trim(SubstituiStr(VpfVersaoSistema,'.',',')) <> trim(Aux.FieldByName(CampoPermissaoModulo).AsString) then
begin
if ArredondaDecimais(StrToFloat(SubstituiStr(VpfVersaoSistema,'.',',')),3) > ArredondaDecimais(StrToFloat(SubstituiStr(Aux.FieldByName(CampoPermissaoModulo).AsString,'.',',')),3) then
if StrToFloat(SubstituiStr(VpfVersaoSistema,'.',',')) > StrToFloat(SubstituiStr(Aux.FieldByName(CampoPermissaoModulo).AsString,'.',',')) then
AlteraVersoesSistemas(CampoPermissaoModulo,VpfVersaoSistema);
end;
if UpperCase(Application.Title) <> 'SISCORP' then
AtualizaNumeroVersaoSistema;
Aux.close;
End;
end;
{********************* altera as versoes do sistema ***************************}
procedure TAtualiza.AlteraVersoesSistemas(VpaNomCampo, VpaDesVersao : String);
begin
ExecutaComandoSql(Aux,'Update Cfg_Geral ' +
'set '+VpaNomCampo+ ' = '''+VpaDesVersao + '''');
end;
{******************************************************************************}
procedure TAtualiza.CadastraTransportadorasComoClientes;
begin
AdicionaSQLAbreTabela(Tabela,'Select * from CADTRANSPORTADORAS ' +
// ' WHERE I_COD_TRA = 2965 '+
' ORDER BY I_COD_TRA');
while not Tabela.Eof do
begin
AdicionaSQLAbreTabela(Cadastro,'Select * from CADCLIENTES ' +
' Where I_TRA_ANT ='+Tabela.FieldByName('I_COD_TRA').AsString);
if Cadastro.Eof then
begin
Cadastro.Insert;
Cadastro.FieldByName('I_COD_CLI').AsInteger := RCodClienteDisponivel;
end
else
Cadastro.Edit;
Cadastro.FieldByName('I_TRA_ANT').AsInteger := Tabela.FieldByName('I_COD_TRA').AsInteger;
Cadastro.FieldByName('C_NOM_CLI').AsString := Tabela.FieldByName('C_NOM_TRA').AsString;
Cadastro.FieldByName('C_NOM_FAN').AsString := Tabela.FieldByName('C_NOM_TRA').AsString;
Cadastro.FieldByName('C_END_CLI').AsString := Tabela.FieldByName('C_END_TRA').AsString;
Cadastro.FieldByName('C_BAI_CLI').AsString := Tabela.FieldByName('C_BAI_TRA').AsString;
Cadastro.FieldByName('I_NUM_END').AsInteger := Tabela.FieldByName('I_NUM_TRA').AsInteger;
Cadastro.FieldByName('C_CEP_CLI').AsString := Tabela.FieldByName('C_CEP_TRA').AsString;
Cadastro.FieldByName('C_CID_CLI').AsString := Tabela.FieldByName('C_CID_TRA').AsString;
Cadastro.FieldByName('C_EST_CLI').AsString := Tabela.FieldByName('C_EST_TRA').AsString;
Cadastro.FieldByName('C_CID_CLI').AsString := Tabela.FieldByName('C_CID_TRA').AsString;
Cadastro.FieldByName('C_FO1_CLI').AsString := '('+DeleteAteChar(Tabela.FieldByName('C_FON_TRA').AsString,'*');
Cadastro.FieldByName('C_FON_FAX').AsString := '('+DeleteAteChar(Tabela.FieldByName('C_FAX_TRA').AsString,'*');
Cadastro.FieldByName('C_CON_CLI').AsString := Tabela.FieldByName('C_NOM_GER').AsString;
Cadastro.FieldByName('C_CGC_CLI').AsString := Tabela.FieldByName('C_CGC_TRA').AsString;
Cadastro.FieldByName('C_INS_CLI').AsString := Tabela.FieldByName('C_INS_TRA').AsString;
Cadastro.FieldByName('C_TIP_PES').AsString := 'J';
Cadastro.FieldByName('D_DAT_CAD').AsDateTime := Tabela.FieldByName('D_DAT_MOV').AsDateTime;
Cadastro.FieldByName('C_END_ELE').AsString := Tabela.FieldByName('C_END_ELE').AsString;
Cadastro.FieldByName('C_WWW_CLI').AsString := Tabela.FieldByName('C_WWW_TRA').AsString;
Cadastro.FieldByName('C_COM_END').AsString := Tabela.FieldByName('C_COM_END').AsString;
Cadastro.FieldByName('C_OBS_CLI').AsString := Tabela.FieldByName('L_OBS_TRA').AsString;
Cadastro.FieldByName('C_IND_ATI').AsString := Tabela.FieldByName('C_IND_ATI').AsString;
Cadastro.FieldByName('I_COD_IBG').AsInteger := Tabela.FieldByName('I_COD_IBG').AsInteger;
Cadastro.FieldByName('C_ACE_SPA').AsString := 'S';
Cadastro.FieldByName('C_ACE_TEL').AsString := 'S';
Cadastro.FieldByName('C_EMA_INV').AsString := 'N';
Cadastro.FieldByName('C_EXP_EFI').AsString := 'N';
Cadastro.FieldByName('C_IND_CRA').AsString := 'N';
Cadastro.FieldByName('C_IND_CON').AsString := 'N';
Cadastro.FieldByName('C_IND_SER').AsString := 'N';
Cadastro.FieldByName('C_IND_PRO').AsString := 'N';
Cadastro.FieldByName('C_IND_BLO').AsString := 'N';
Cadastro.FieldByName('C_FIN_CON').AsString := 'S';
Cadastro.FieldByName('C_COB_FRM').AsString := 'S';
Cadastro.FieldByName('C_IND_AGR').AsString := 'N';
Cadastro.FieldByName('C_IND_CLI').AsString := 'N';
Cadastro.FieldByName('C_IND_PRC').AsString := 'N';
Cadastro.FieldByName('C_IND_FOR').AsString := 'N';
Cadastro.FieldByName('C_IND_HOT').AsString := 'N';
Cadastro.FieldByName('C_IND_TRA').AsString := 'S';
Cadastro.FieldByName('C_IND_CBA').AsString := 'S';
Cadastro.FieldByName('C_IND_BUM').AsString := 'N';
Cadastro.FieldByName('C_IND_VIS').AsString := 'N';
Cadastro.FieldByName('C_OPT_SIM').AsString := 'N';
Cadastro.FieldByName('C_FLA_EXP').AsString := 'S';
Cadastro.FieldByName('C_OPT_SIM').AsString := 'N';
Cadastro.FieldByName('C_DES_ICM').AsString := 'S';
Cadastro.FieldByName('C_DES_ISS').AsString := 'N';
Cadastro.FieldByName('C_FLA_EXP').AsString := 'S';
Cadastro.FieldByName('I_COD_SIT').AsInteger := 1101;
Cadastro.post;
Tabela.Next;
end;
Tabela.Close;
end;
{**************************** atualiza a tabela *******************************}
procedure TAtualiza.AtualizaTabela(VpaNumAtualizacao : Integer);
var
VpfSemErros : Boolean;
VpfErro : String;
begin
VpfSemErros := true;
// FAbertura.painelTempo1.Execute('Atualizando o Banco de Dados. Aguarde...');
repeat
Try
if VpaNumAtualizacao < 300 Then
begin
VpfErro := '300';
ExecutaComandoSql(Aux,'ALTER TABLE CADVENDEDORES' +
' add C_DES_EMA CHAR(50) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 300');
end;
if VpaNumAtualizacao < 301 Then
begin
VpfErro := '301';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS' +
' ADD N_VLR_DES NUMERIC(12,3) NULL, '+
' ADD N_PER_DES NUMERIC(12,3) NULL, '+
' ADD N_PER_COM NUMERIC(5,2) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 301');
end;
if VpaNumAtualizacao < 302 Then
begin
VpfErro := '302';
ExecutaComandoSql(Aux,'DROP INDEX MOVNOTASFISCAIS_PK');
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS drop PRIMARY KEY');
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS '+
' ADD PRIMARY KEY(I_EMP_FIL,I_SEQ_NOT,I_SEQ_MOV)');
ExecutaComandoSql(Aux,'CREATE UNIQUE INDEX MOVNOTASFISCAIS_PK ON MOVNOTASFISCAIS(I_EMP_FIL,I_SEQ_NOT,I_SEQ_MOV)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 302');
end;
if VpaNumAtualizacao < 303 Then
begin
VpfErro := '303';
ExecutaComandoSql(Aux,'create index CadNotaFiscais_CP1 on CADNOTAFISCAIS(C_Ser_Not,I_NRO_NOT)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 303');
end;
if VpaNumAtualizacao < 1429 Then
begin
VpfErro := '1429';
ExecutaComandoSql(Aux,'alter table RETORNOITEM ADD NOMOCORRENCIA VARCHAR2(30) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1429');
end;
if VpaNumAtualizacao < 1430 Then
begin
VpfErro := '1430';
ExecutaComandoSql(Aux,'alter table REMESSAITEM ADD NOMMOTIVO VARCHAR2(30) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1430');
end;
if VpaNumAtualizacao < 1431 Then
begin
VpfErro := '1431';
ExecutaComandoSql(Aux,'DROP INDEX MOVCOMISSOES_CP4');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1431');
end;
if VpaNumAtualizacao < 1432 Then
begin
VpfErro := '1432';
ExecutaComandoSql(Aux,'CREATE INDEX MOVCOMISSOES_CP3 ON MOVCOMISSOES(D_DAT_VAL,D_DAT_PAG)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1432');
end;
if VpaNumAtualizacao < 1433 Then
begin
VpfErro := '1433';
TRY
ExecutaComandoSql(Aux,'DROP INDEX MOVCOMISSOES_CP2');
FINALLY
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1433');
END;
end;
if VpaNumAtualizacao < 1434 Then
begin
VpfErro := '1434';
ExecutaComandoSql(Aux,'CREATE INDEX MOVCOMISSOES_CP2 ON MOVCOMISSOES(D_DAT_VEN,D_DAT_PAG)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1434');
end;
if VpaNumAtualizacao < 1435 Then
begin
VpfErro := '1435';
try
ExecutaComandoSql(Aux,'DROP INDEX MOVCONTASRECEBERCP5');
finally
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1435');
end;
end;
if VpaNumAtualizacao < 1436 Then
begin
VpfErro := '1436';
ExecutaComandoSql(Aux,'create index remessacorpo_cp1 on REMESSACORPO(DATBLOQUEIO,NUMCONTA,CODFILIAL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1436');
end;
if VpaNumAtualizacao < 1437 Then
begin
VpfErro := '1437';
ExecutaComandoSql(Aux,'CREATE INDEX CADCODIGO_CP1 ON CADCODIGO(I_EMP_FIL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1437');
end;
if VpaNumAtualizacao < 1438 Then
begin
VpfErro := '1438';
ExecutaComandoSql(Aux,'alter table CONTRATOCORPO ADD (CODPREPOSTO NUMBER(10,0) NULL,'+
' PERCOMISSAO NUMBER(6,3) NULL, '+
' PERCOMISSAOPREPOSTO NUMBER(6,3) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1438');
end;
if VpaNumAtualizacao < 1439 Then
begin
VpfErro := '1439';
ExecutaComandoSql(Aux,'CREATE INDEX CONTRATOCORPO_FK4 on CONTRATOCORPO(CODPREPOSTO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1439');
end;
if VpaNumAtualizacao < 1440 Then
begin
VpfErro := '1440';
ExecutaComandoSql(Aux,'ALTER TABLE CONTRATOCORPO ADD DESEMAIL VARCHAR2(60) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1440');
end;
if VpaNumAtualizacao < 1441 Then
begin
VpfErro := '1441';
ExecutaComandoSql(Aux,'CREATE TABLE FIGURAGRF( '+
' CODFIGURAGRF NUMBER(10,0) NOT NULL, '+
' NOMFIGURAGRF VARCHAR2(50) NULL,'+
' DESFIGURAGRF VARCHAR2(2000)NULL,'+
' PRIMARY KEY(CODFIGURAGRF))' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1441');
end;
if VpaNumAtualizacao < 1442 Then
begin
VpfErro := '1442';
ExecutaComandoSql(Aux,'CREATE TABLE COMPOSICAO( '+
' CODCOMPOSICAO NUMBER(10,0) NOT NULL, '+
' NOMCOMPOSICAO VARCHAR2(50) NULL,'+
' PRIMARY KEY(CODCOMPOSICAO))' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1442');
end;
if VpaNumAtualizacao < 1443 Then
begin
VpfErro := '1443';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD C_REF_CLI CHAR(1) NULL' );
ExecutaComandoSql(Aux,'Update CFG_PRODUTO set C_REF_CLI = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1443');
end;
if VpaNumAtualizacao < 1444 Then
begin
VpfErro := '1444';
ExecutaComandoSql(Aux,'ALTER TABLE CADUSUARIOS ADD C_CON_CAI VARCHAR2(13) NULL' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1444');
end;
if VpaNumAtualizacao < 1445 Then
begin
VpfErro := '1445';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD C_CNF_ESC CHAR(1) NULL' );
ExecutaComandoSql(Aux,'Update CFG_FISCAL set C_CNF_ESC = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1445');
end;
if VpaNumAtualizacao < 1446 Then
begin
VpfErro := '1446';
ExecutaComandoSql(Aux,'alter table CADFILIAIS ADD (C_UFD_NFE CHAR(2) NULL,'+
' C_AMH_NFE CHAR(1) NULL, '+ //AMBIENTE DE HOMOLOGACAO
' C_MOM_NFE CHAR(1) NULL)'); // MOSTRAR MENSAGEM
ExecutaComandoSql(Aux,'UPDATE CADFILIAIS SET C_AMH_NFE = ''T'','+
' C_MOM_NFE = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1446');
end;
if VpaNumAtualizacao < 1447 Then
begin
VpfErro := '1447';
ExecutaComandoSql(Aux,'alter table CADGRUPOS ADD (C_POL_PSP CHAR(1) NULL,'+
' C_POL_PCP CHAR(1) NULL) ');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_POL_PSP = ''T'','+
' C_POL_PCP = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1447');
end;
if VpaNumAtualizacao < 1448 Then
begin
VpfErro := '1448';
ExecutaComandoSql(Aux,'alter table CADGRUPOS ADD C_POL_ECP CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_POL_ECP = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1448');
end;
if VpaNumAtualizacao < 1449 Then
begin
VpfErro := '1449';
ExecutaComandoSql(Aux,'alter table CADFILIAIS ADD (C_DAN_NFE CHAR(1) NULL,'+
' C_CER_NFE VARCHAR2(50))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1449');
end;
if VpaNumAtualizacao < 1450 Then
begin
VpfErro := '1450';
ExecutaComandoSql(Aux,'alter table CADFILIAIS ADD C_IND_NFE CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADFILIAIS SET C_IND_NFE = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1450');
end;
if VpaNumAtualizacao < 1451 Then
begin
VpfErro := '1451';
ExecutaComandoSql(Aux,'alter table CADGRUPOS ADD C_FAT_CNO CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_FAT_CNO = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1451');
end;
if VpaNumAtualizacao < 1452 Then
begin
VpfErro := '1452';
ExecutaComandoSql(Aux,'alter table movorcamentos add I_SEQ_ORD NUMBER(10,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1452');
end;
if VpaNumAtualizacao < 1453 Then
begin
VpfErro := '1453';
ExecutaComandoSql(Aux,'create table COMPOSICAOFIGURAGRF ('+
' CODCOMPOSICAO NUMBER(10,0) NOT NULL,'+
' CODFIGURAGRF NUMBER(10,0) NOT NULL,'+
' PRIMARY KEY(CODCOMPOSICAO,CODFIGURAGRF))');
ExecutaComandoSql(Aux,'CREATE INDEX COMPOSICAOFIGURAGRF_FK1 ON COMPOSICAOFIGURAGRF(CODCOMPOSICAO)');
ExecutaComandoSql(Aux,'CREATE INDEX COMPOSICAOFIGURAGRF_FK2 ON COMPOSICAOFIGURAGRF(CODFIGURAGRF)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1453');
end;
if VpaNumAtualizacao < 1454 Then
begin
VpfErro := '1454';
ExecutaComandoSql(Aux,'alter table CADPRODUTOS ADD I_COD_COM NUMBER(10,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1454');
end;
if VpaNumAtualizacao < 1455 Then
begin
VpfErro := '1455';
ExecutaComandoSql(Aux,'alter table CFG_PRODUTO ADD C_ORP_ACE CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_PRODUTO SET C_ORP_ACE = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1455');
end;
if VpaNumAtualizacao < 1456 Then
begin
VpfErro := '1456';
ExecutaComandoSql(Aux,'alter table CADPRODUTOS ADD I_NUM_LOT NUMBER(10,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1456');
end;
if VpaNumAtualizacao < 1457 Then
begin
VpfErro := '1457';
ExecutaComandoSql(Aux,'alter table CFG_PRODUTO ADD I_REG_LOT NUMBER(5,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1457');
end;
if VpaNumAtualizacao < 1458 Then
begin
VpfErro := '1458';
ExecutaComandoSql(Aux,'alter table CFG_PRODUTO ADD C_EST_SER CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_PRODUTO set C_EST_SER = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1458');
end;
if VpaNumAtualizacao < 1459 Then
begin
VpfErro := '1459';
ExecutaComandoSql(Aux,'alter table CADFILIAIS ADD I_COD_FIS NUMBER(10,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1459');
end;
if VpaNumAtualizacao < 1460 Then
begin
VpfErro := '1460';
ExecutaComandoSql(Aux,'alter table CADCLIENTES ADD I_COD_IBG NUMBER(10,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1460');
end;
if VpaNumAtualizacao < 1461 Then
begin
VpfErro := '1461';
ExecutaComandoSql(Aux,'alter table CADFILIAIS ADD C_COD_CNA VARCHAR2(15)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1461');
end;
if VpaNumAtualizacao < 1462 Then
begin
VpfErro := '1462';
ExecutaComandoSql(Aux,'alter table CADNOTAFISCAIS ADD( C_CHA_NFE VARCHAR2(50)NULL, '+
' C_REC_NFE VARCHAR2(15) NULL, '+
' C_PRO_NFE VARCHAR2(20) NULL,'+
' C_STA_NFE VARCHAR2(3) NULL,'+
' C_MOT_NFE VARCHAR2(40) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1462');
end;
if VpaNumAtualizacao < 1463 Then
begin
VpfErro := '1463';
ExecutaComandoSql(Aux,'alter table CADPRODUTOS ADD C_IND_MON CHAR(1)NULL ');
ExecutaComandoSql(Aux,'UPDATE CADPRODUTOS SET C_IND_MON = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1463');
end;
if VpaNumAtualizacao < 1464 Then
begin
VpfErro := '1464';
ExecutaComandoSql(Aux,'alter table MOVESTOQUEPRODUTOS ADD(N_QTD_INI NUMBER(17,4)NULL, '+
' N_QTD_FIN NUMBER(17,4) NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1464');
end;
if VpaNumAtualizacao < 1465 Then
begin
VpfErro := '1465';
ExecutaComandoSql(Aux,'alter table CADGRUPOS ADD(C_COD_CLA VARCHAR2(15)NULL, '+
' I_COD_FIL NUMBER(10) NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1465');
end;
if VpaNumAtualizacao < 1466 Then
begin
VpfErro := '1466';
ExecutaComandoSql(Aux,'INSERT INTO CADSERIENOTAS(C_SER_NOT) VALUES(''900'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1466');
end;
if VpaNumAtualizacao < 1467 Then
begin
VpfErro := '1467';
ExecutaComandoSql(Aux,'ALTER TABLE CAD_PAISES ADD(COD_IBGE NUMBER(4) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1467');
end;
if VpaNumAtualizacao < 1468 Then
begin
VpfErro := '1468';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD(I_COD_PAI NUMBER(4) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1468');
end;
if VpaNumAtualizacao < 1469 Then
begin
VpfErro := '1469';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD C_INS_MUN VARCHAR2(30) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1469');
end;
if VpaNumAtualizacao < 1470 Then
begin
VpfErro := '1470';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD I_ORI_PRO NUMBER(1,0) NULL');
ExecutaComandoSql(Aux,'UPDATE CADPRODUTOS SET I_ORI_PRO = 0 ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1470');
end;
if VpaNumAtualizacao < 1471 Then
begin
VpfErro := '1471';
ExecutaComandoSql(Aux,'ALTER TABLE CADSERVICO ADD I_COD_FIS NUMBER(6,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1471');
end;
if VpaNumAtualizacao < 1472 Then
begin
VpfErro := '1472';
ExecutaComandoSql(Aux,'CREATE INDEX MOVCONTASARECEBER_CP6 ON MOVCONTASARECEBER(C_NOS_NUM)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1472');
end;
if VpaNumAtualizacao < 1473 Then
begin
VpfErro := '1473';
ExecutaComandoSql(Aux,'CREATE INDEX FRACAOOP_CP1 ON FRACAOOP(INDPLANOCORTE)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1473');
end;
if VpaNumAtualizacao < 1474 Then
begin
VpfErro := '1474';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD(I_TIP_BAR NUMBER(1,0),'+
' N_PRE_EAN NUMBER(15,0)NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1474');
end;
if VpaNumAtualizacao < 1475 Then
begin
VpfErro := '1475';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD(I_ULT_EAN NUMBER(20,0)NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1475');
end;
if VpaNumAtualizacao < 1476 Then
begin
VpfErro := '1476';
ExecutaComandoSql(Aux,'CREATE TABLE CONDICAOPAGAMENTOGRUPOUSUARIO('+
' CODGRUPOUSUARIO NUMBER(10,0) NOT NULL, '+
' CODCONDICAOPAGAMENTO NUMBER(10,0) NOT NULL, ' +
' PRIMARY KEY(CODGRUPOUSUARIO,CODCONDICAOPAGAMENTO))');
ExecutaComandoSql(Aux,'CREATE INDEX CONDICAOPGTOGRUPOUSUARIO_FK1 ON CONDICAOPAGAMENTOGRUPOUSUARIO(CODGRUPOUSUARIO)');
ExecutaComandoSql(Aux,'CREATE INDEX CONDICAOPGTOGRUPOUSUARIO_FK2 ON CONDICAOPAGAMENTOGRUPOUSUARIO(CODCONDICAOPAGAMENTO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1476');
end;
if VpaNumAtualizacao < 1477 Then
begin
VpfErro := '1477';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_GER_COP CHAR(1)NULL');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS set C_GER_COP = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1477');
end;
if VpaNumAtualizacao < 1478 Then
begin
VpfErro := '1478';
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOCOMPRAFORNECEDORCORPO '+
' ADD (DESEMAIL VARCHAR2(100) NULL, '+
' NOMCONTATO VARCHAR2(50) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1478');
end;
if VpaNumAtualizacao < 1479 Then
begin
VpfErro := '1479';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_ORP_CMM CHAR(1) NULL ');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_ORP_CMM = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1479');
end;
if VpaNumAtualizacao < 1480 Then
begin
VpfErro := '1480';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD (C_PRC_NFE VARCHAR2(20) NULL, '+
' C_MOC_NFE VARCHAR2(255) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1480');
end;
if VpaNumAtualizacao < 1481 Then
begin
VpfErro := '1481';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD (C_SER_SER VARCHAR2(15) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1481');
end;
if VpaNumAtualizacao < 1482 Then
begin
VpfErro := '1482';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD (C_NOT_CON CHAR(1) NULL)');
ExecutaComandoSql(Aux,'Update CADFILIAIS set C_NOT_CON = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1482');
end;
if VpaNumAtualizacao < 1483 Then
begin
VpfErro := '1483';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD (C_EST_CAC CHAR(1) NULL)');
ExecutaComandoSql(Aux,'Update CADGRUPOS set C_EST_CAC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1483');
end;
if VpaNumAtualizacao < 1484 Then
begin
VpfErro := '1484';
ExecutaComandoSql(Aux,'ALTER TABLE RETORNOITEM MODIFY NOMSACADO VARCHAR2(40)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1484');
end;
if VpaNumAtualizacao < 1485 Then
begin
VpfErro := '1485';
ExecutaComandoSql(Aux,'ALTER TABLE CAD_PLANO_CONTA ADD N_VLR_PRE NUMBER(17,2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1485');
end;
if VpaNumAtualizacao < 1486 Then
begin
VpfErro := '1486';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD I_MOD_EPE NUMBER(2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1486');
end;
if VpaNumAtualizacao < 1487 Then
begin
VpfErro := '1487';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD C_EAN_ACE CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_PRODUTO SET C_EAN_ACE = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1487');
end;
if VpaNumAtualizacao < 1488 Then
begin
VpfErro := '1488';
ExecutaComandoSql(Aux,'ALTER TABLE EMBALAGEM ADD QTD_EMBALAGEM NUMBER(15,3)NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1488');
end;
if VpaNumAtualizacao < 1489 Then
begin
VpfErro := '1489';
ExecutaComandoSql(Aux,'ALTER TABLE FRACAOOPCONSUMO ADD QTDARESERVAR NUMBER(15,4)NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1489');
end;
if VpaNumAtualizacao < 1490 Then
begin
VpfErro := '1490';
ExecutaComandoSql(Aux,'ALTER TABLE MOVQDADEPRODUTO ADD N_QTD_ARE NUMBER(15,4)NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1490');
end;
if VpaNumAtualizacao < 1491 Then
begin
VpfErro := '1491';
ExecutaComandoSql(Aux,'ALTER TABLE IMPRESSAOCONSUMOFRACAO ADD(QTDRESERVADA NUMBER(15,4)NULL, '+
' QTDARESERVAR NUMBER(15,4) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1491');
end;
if VpaNumAtualizacao < 1492 Then
begin
VpfErro := '1492';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD C_EMA_NFE VARCHAR2(75) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1492');
end;
if VpaNumAtualizacao < 1493 Then
begin
VpfErro := '1493';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD C_NOT_IEC CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_FISCAL set C_NOT_IEC =''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1493');
end;
if VpaNumAtualizacao < 1494 Then
begin
VpfErro := '1494';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD C_COM_ROM CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_FISCAL set C_COM_ROM =''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1494');
end;
if VpaNumAtualizacao < 1495 Then
begin
VpfErro := '1495';
ExecutaComandoSql(Aux,'CREATE TABLE PRODUTORESERVADOEMEXCESSO ('+
' SEQRESERVA NUMBER(10) NOT NULL, '+
' DATRESERVA DATE, ' +
' SEQPRODUTO NUMBER(10) NOT NULL, '+
' QTDESTOQUEPRODUTO NUMBER(15,4) NULL, '+
' QTDRESERVADO NUMBER(15,4) NULL, '+
' QTDEXCESSO NUMBER(15,4) NULL, '+
' CODFILIAL NUMBER(10) NULL, ' +
' SEQORDEMPRODUCAO NUMBER(10) NULL, '+
' CODUSUARIO NUMBER(10) NULL, '+
' DESUM CHAR(2) NULL, '+
' PRIMARY KEY(SEQRESERVA))');
ExecutaComandoSql(Aux,'CREATE INDEX PRODUTORESERVADOEXCE_FK1 ON PRODUTORESERVADOEMEXCESSO(SEQPRODUTO)' );
ExecutaComandoSql(Aux,'CREATE INDEX PRODUTORESERVADOEXCE_FK2 ON PRODUTORESERVADOEMEXCESSO(CODFILIAL,SEQORDEMPRODUCAO)' );
ExecutaComandoSql(Aux,'CREATE INDEX PRODUTORESERVADOEXCE_FK3 ON PRODUTORESERVADOEMEXCESSO(CODUSUARIO)' );
ExecutaComandoSql(Aux,'CREATE INDEX PRODUTORESERVADOEXCE_CP1 ON PRODUTORESERVADOEMEXCESSO(DATRESERVA)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1495');
end;
if VpaNumAtualizacao < 1496 Then
begin
VpfErro := '1496';
ExecutaComandoSql(Aux,'CREATE TABLE RESERVAPRODUTO( '+
' SEQRESERVA NUMBER(10) NOT NULL, '+
' SEQPRODUTO NUMBER(10) NOT NULL, '+
' TIPMOVIMENTO CHAR(1) NULL, '+
' DATRESERVA DATE NULL, '+
' QTDRESERVADA NUMBER(15,3) NULL, '+
' CODUSUARIO NUMBER(10) NULL, '+
' QTDINICIAL NUMBER(15,3) NULL,'+
' QTDFINAL NUMBER(15,3) NULL, '+
' CODFILIAL NUMBER(10) NULL, '+
' SEQORDEMPRODUCAO NUMBER(10) NULL, '+
' DESUM CHAR(2) NULL, '+
' PRIMARY KEY(SEQRESERVA))');
ExecutaComandoSql(Aux,'CREATE INDEX RESERVAPRODUTO_FK1 ON RESERVAPRODUTO(SEQPRODUTO)');
ExecutaComandoSql(Aux,'CREATE INDEX RESERVAPRODUTO_FK2 ON RESERVAPRODUTO(CODFILIAL,SEQORDEMPRODUCAO)');
ExecutaComandoSql(Aux,'CREATE INDEX RESERVAPRODUTO_FK3 ON RESERVAPRODUTO(CODUSUARIO)');
ExecutaComandoSql(Aux,'CREATE INDEX RESERVAPRODUTO_CP1 ON RESERVAPRODUTO(DATRESERVA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1496');
end;
if VpaNumAtualizacao < 1497 Then
begin
VpfErro := '1497';
ExecutaComandoSql(Aux,'CREATE TABLE PROJETO( '+
' CODPROJETO NUMBER(10) NOT NULL, '+
' NOMPROJETO VARCHAR2(50) NULL, '+
' PRIMARY KEY(CODPROJETO))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1497');
end;
if VpaNumAtualizacao < 1498 Then
begin
VpfErro := '1498';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO ADD C_CON_PRO CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FINANCEIRO SET C_CON_PRO = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1498');
end;
if VpaNumAtualizacao < 1499 Then
begin
VpfErro := '1499';
ExecutaComandoSql(Aux,'CREATE TABLE CONTAAPAGARPROJETO( '+
' CODFILIAL NUMBER(10) NOT NULL, '+
' LANPAGAR NUMBER(10) NOT NULL, '+
' CODPROJETO NUMBER(10) NOT NULL, '+
' SEQDESPESA NUMBER(10) NOT NULL,' +
' VALDESPESA NUMBER(15,3) NULL, '+
' PERDESPESA NUMBER(15,3) NULL,'+
' PRIMARY KEY(CODFILIAL,LANPAGAR,CODPROJETO,SEQDESPESA))');
ExecutaComandoSql(Aux,'CREATE INDEX CONTAAPAGARPROJETO_FK1 ON CONTAAPAGARPROJETO(CODFILIAL,LANPAGAR)');
ExecutaComandoSql(Aux,'CREATE INDEX CONTAAPAGARPROJETO_FK2 ON CONTAAPAGARPROJETO(CODPROJETO)');
ExecutaComandoSql(Aux,'ALTER TABLE CONTAAPAGARPROJETO add CONSTRAINT CONTAAPAGARPRO_CP '+
' FOREIGN KEY (CODFILIAL,LANPAGAR) '+
' REFERENCES CADCONTASAPAGAR (I_EMP_FIL,I_LAN_APG) ');
ExecutaComandoSql(Aux,'ALTER TABLE CONTAAPAGARPROJETO add CONSTRAINT CONTAAPAGAR_PROJETO '+
' FOREIGN KEY (CODPROJETO) '+
' REFERENCES PROJETO (CODPROJETO) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1499');
end;
if VpaNumAtualizacao < 1500 Then
begin
VpfErro := '1500';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_COT_PPP CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_PPP = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1500');
end;
if VpaNumAtualizacao < 1501 Then
begin
VpfErro := '1501';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_COT_QME NUMBER(10) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET I_COT_QME = 6');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1501');
end;
if VpaNumAtualizacao < 1502 Then
begin
VpfErro := '1502';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMPRODUCAOCORPO ADD CODPRJ NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1502');
end;
if VpaNumAtualizacao < 1503 Then
begin
VpfErro := '1503';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD N_CAP_LIQ NUMBER(10,2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1503');
end;
if VpaNumAtualizacao < 1504 Then
begin
VpfErro := '1504';
ExecutaComandoSql(Aux,'CREATE TABLE MOTIVOPARADA( '+
' CODMOTIVOPARADA NUMBER(10) NOT NULL, '+
' NOMMOTIVOPARADA VARCHAR2(50) NULL,'+
' PRIMARY KEY(CODMOTIVOPARADA))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1504');
end;
if VpaNumAtualizacao < 1505 Then
begin
VpfErro := '1505';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_EST_RES CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EST_RES = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1505');
end;
if VpaNumAtualizacao < 1506 Then
begin
VpfErro := '1506';
ExecutaComandoSql(Aux,'ALTER TABLE CADEMPRESAS ADD C_COT_ICS CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADEMPRESAS SET C_COT_ICS = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1506');
end;
if VpaNumAtualizacao < 1507 Then
begin
VpfErro := '1507';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLASSIFICACAO ADD C_IMP_ETI CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADCLASSIFICACAO SET C_IMP_ETI = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1507');
end;
if VpaNumAtualizacao < 1508 Then
begin
VpfErro := '1508';
ExecutaComandoSql(Aux,'ALTER TABLE MOVTABELAPRECO ADD I_COD_COR NUMBER(10) NULL');
ExecutaComandoSql(Aux,'UPDATE MOVTABELAPRECO SET I_COD_COR = 0');
ExecutaComandoSql(Aux,'ALTER TABLE MOVTABELAPRECO MODIFY I_COD_COR NUMBER(10) NOT NULL');
ExecutaComandoSql(Aux,'ALTER TABLE MOVTABELAPRECO drop PRIMARY KEY');
ExecutaComandoSql(Aux,'ALTER TABLE MOVTABELAPRECO '+
' ADD PRIMARY KEY(I_COD_EMP,I_COD_TAB,I_SEQ_PRO,I_COD_CLI,I_COD_TAM,I_COD_COR)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1508');
end;
if VpaNumAtualizacao < 1509 Then
begin
VpfErro := '1509';
ExecutaComandoSql(Aux,'create table DEPARTAMENTOAMOSTRA('+
' CODDEPARTAMENTOAMOSTRA NUMBER(10,0) NOT NULL,'+
' NOMDEPARTAMENTOAMOSTRA VARCHAR2(50)NULL,' +
' PRIMARY KEY(CODDEPARTAMENTOAMOSTRA))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1509');
end;
if VpaNumAtualizacao < 1510 Then
begin
VpfErro := '1510';
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRA ADD CODDEPARTAMENTOAMOSTRA NUMBER(10,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1510');
end;
if VpaNumAtualizacao < 1511 Then
begin
VpfErro := '1511';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(I_COD_DEA NUMBER(10,0) NULL , '+
' I_DIA_AMO NUMBER(3) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1511');
end;
if VpaNumAtualizacao < 1512 Then
begin
VpfErro := '1512';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_NOF_ICO CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_NOF_ICO = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1512');
end;
if VpaNumAtualizacao < 1513 Then
begin
VpfErro := '1513';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASARECEBER ADD C_IND_DEV CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADCONTASARECEBER SET C_IND_DEV = ''N''');
ExecutaComandoSql(Aux,'CREATE INDEX CADCONTASARECEBER_CP3 ON CADCONTASARECEBER(C_IND_DEV)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1513');
end;
if VpaNumAtualizacao < 1514 Then
begin
VpfErro := '1514';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD I_EST_REI NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1514');
end;
if VpaNumAtualizacao < 1515 Then
begin
VpfErro := '1515';
ExecutaComandoSql(Aux,'ALTER TABLE FRACAOOPCONSUMO ADD(INDEXCLUIR CHAR(1) NULL, '+
' ALTMOLDE NUMBER(9,4) NULL, ' +
' LARMOLDE NUMBER(9,4) NULL)');
ExecutaComandoSql(Aux,'UPDATE FRACAOOPCONSUMO SET INDEXCLUIR = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1515');
end;
if VpaNumAtualizacao < 1516 Then
begin
VpfErro := '1516';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD C_IND_VIS CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADCLIENTES SET C_IND_VIS = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1516');
end;
if VpaNumAtualizacao < 1517 Then
begin
VpfErro := '1517';
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRACONSUMO ADD DESLEGENDA CHAR(4)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1517');
end;
if VpaNumAtualizacao < 1518 Then
begin
VpfErro := '1518';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASAPAGAR add CONSTRAINT CADCONTASPAGAR_PLAC '+
' FOREIGN KEY (I_COD_EMP, C_CLA_PLA) '+
' REFERENCES CAD_PLANO_CONTA(I_COD_EMP,C_CLA_PLA) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1518');
end;
if VpaNumAtualizacao < 1519 Then
begin
VpfErro := '1519';
ExecutaComandoSql(Aux,'CREATE TABLE TIPOMATERIAPRIMA ('+
' CODTIPOMATERIAPRIMA NUMBER(10) NULL, '+
' NOMTIPOMATERIAPRIMA VARCHAR2(50) NULL, '+
' PRIMARY KEY(CODTIPOMATERIAPRIMA))' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1519');
end;
if VpaNumAtualizacao < 1520 Then
begin
VpfErro := '1520';
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRACONSUMO '+
' ADD(CODTIPOMATERIAPRIMA NUMBER(10) NULL,'+
' NUMSEQUENCIA NUMBER(10) NULL,' +
' SEQENTRETELA NUMBER(10) NULL,' +
' QTDENTRETELA NUMBER(10) NULL,' +
' SEQTERMOCOLANTE NUMBER(10)NULL,' +
' QTDTERMOCOLANTE NUMBER(10)NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1520');
end;
if VpaNumAtualizacao < 1521 Then
begin
VpfErro := '1521';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD( '+
' C_PER_SPE CHAR(1) NULL, '+
' I_ATI_SPE NUMBER(2) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1521');
end;
if VpaNumAtualizacao < 1522 Then
begin
VpfErro := '1522';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD( '+
' I_CON_SPE NUMBER(10) NULL, '+
' C_NCO_SPE VARCHAR2(50) NULL,'+
' C_CPC_SPE VARCHAR2(14) NULL,' +
' C_CRC_SPE VARCHAR2(15) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1522');
end;
if VpaNumAtualizacao < 1523 Then
begin
VpfErro := '1523';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD I_DES_PRO NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1523');
end;
if VpaNumAtualizacao < 1524 Then
begin
VpfErro := '1524';
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRA ADD(CODEMPRESA NUMBER(10) NULL, '+
' DESTIPOCLASSIFICACAO CHAR(1)NULL)');
ExecutaComandoSql(Aux,'UPDATE AMOSTRA SET CODEMPRESA = 1, ' +
' DESTIPOCLASSIFICACAO = ''P''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1524');
end;
if VpaNumAtualizacao < 1525 Then
begin
VpfErro := '1525';
ExecutaComandoSql(Aux,'ALTER TABLE FRACAOOP ADD INDPOSSUIEMESTOQUE CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update FRACAOOP SET INDPOSSUIEMESTOQUE = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1525');
end;
if VpaNumAtualizacao < 1526 Then
begin
VpfErro := '1526';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_OBS_BOL VARCHAR2(600) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL SET C_OBS_BOL = ''****O DEPOSITO BANCARIO NAO QUITA ESTE BOLETO****''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1526');
end;
if VpaNumAtualizacao < 1527 Then
begin
VpfErro := '1527';
ExecutaComandoSql(Aux,'ALTER TABLE CADEMPRESAS ADD C_IND_FCA CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADEMPRESAS SET C_IND_FCA = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1527');
end;
if VpaNumAtualizacao < 1528 Then
begin
VpfErro := '1528';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD I_ORC_LOC NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1528');
end;
if VpaNumAtualizacao < 1529 Then
begin
VpfErro := '1529';
ExecutaComandoSql(Aux,'ALTER TABLE FACA ADD (ALTPROVA NUMBER(9,3)NULL, '+
' LARPROVA NUMBER(9,3) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1529');
end;
if VpaNumAtualizacao < 1530 Then
begin
VpfErro := '1530';
ExecutaComandoSql(Aux,'alter TABLE CFG_GERAL ADD C_AMO_CAC CHAR(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set C_AMO_CAC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1530');
end;
if VpaNumAtualizacao < 1531 Then
begin
VpfErro := '1531';
ExecutaComandoSql(Aux,'alter TABLE CFG_GERAL ADD C_DIR_FAM VARCHAR2(200) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1531');
end;
if VpaNumAtualizacao < 1532 Then
begin
VpfErro := '1532';
ExecutaComandoSql(Aux,'create table COEFICIENTECUSTO('+
' CODCOEFICIENTE NUMBER(10) NOT NULL,' +
' NOMCOEFICIENTE VARCHAR2(50) NOT NULL,' +
' PERICMS NUMBER(9,3) NULL, ' +
' PERPISCOFINS NUMBER(9,3) NULL,' +
' PERCOMISSAO NUMBER(9,3) NULL,' +
' PERFRETE NUMBER(9,3) NULL,' +
' PERADMINISTRATIVO NUMBER(9,3) NULL,' +
' PERPROPAGANDA NUMBER(9,3) NULL,' +
' PERVENDAPRAZO NUMBER(9,3) NULL,' +
' PERLUCRO NUMBER(9,3) NULL,' +
' PRIMARY KEY(CODCOEFICIENTE))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1532');
end;
if VpaNumAtualizacao < 1533 Then
begin
VpfErro := '1533';
ExecutaComandoSql(Aux,'ALTER TABLE CADTRANSPORTADORAS ADD(I_COD_PAI NUMBER(10) NULL, '+
' I_COD_IBG NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1533');
end;
if VpaNumAtualizacao < 1534 Then
begin
VpfErro := '1534';
ExecutaComandoSql(Aux,'ALTER TABLE CADTRANSPORTADORAS ADD C_IND_PRO CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADTRANSPORTADORAS SET C_IND_PRO = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1534');
end;
if VpaNumAtualizacao < 1535 Then
begin
VpfErro := '1535';
ExecutaComandoSql(Aux,'create table TIPODOCUMENTOFISCAL ('+
' CODTIPODOCUMENTOFISCAL CHAR(2) NOT NULL, '+
' NOMTIPODOCUMENTOFISCAL VARCHAR2(70) NULL, '+
' PRIMARY KEY(CODTIPODOCUMENTOFISCAL))');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''01'',''NOTA FISCAL MODELO 1/1A'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''1B'',''NOTA FISCAL AVULSA'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''02'',''NOTA FISCAL DE VENDA AO CONSUMIDOR'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''2D'',''CUPOM FISCAL'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''04'',''NOTA FISCAL DE PRODUTOR'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''06'',''CONTA DE ENERGIA ELETRICA'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''07'',''NOTA FISCAL DE SERVICO DE TRANSPORTE'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''08'',''CONHECIMENTO DE TRANSPORTE RODOVIARIO DE CARGAS'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''8B'',''CONHECIMENTO DE TRANSPORTE AVULSO'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''09'',''CONHECIMENTO DE TRANSPORTE AQUAVIARIO DE CARGAS'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''10'',''CONHECIMENTO DE AEREO'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''11'',''CONHECIMENTO DE TRANSPORTE FERROVIARIO DE CARGAS'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''13'',''BILHETE DE PASSAGEM RODOVIARIO'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''14'',''BILHETE DE PASSAGEM AQUAVIARIO'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''15'',''BILHETE DE PASSAGEM E NOTA DE BAGAGEM'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''16'',''BILHETE DE PASSAGEM FERROVIARIO'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''18'',''RESUMO DE MOVIMENTO DIARIO'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''21'',''NOTA FISCAL DE SERVICO DE COMUNICACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''22'',''NOTA FISCAL DE SERVICO DE TELECOMUNICACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''26'',''CONHECIMENTO DE TRANSPORTE MULTIMODAL DE CARGAS'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''27'',''NOTA FISCAL DE TRANSPORTE FERROVIARIO DE CARGA'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''28'',''NOTA FISCAL/CONTA DE FORNECIMENTO DE GAS CANALIZADO'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''29'',''NOTA FISCAL/CONTA DE FORNECIMENTO DE AGUA CANALIZADA'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''55'',''NOTA FISCAL ELETRONICA (NF-E)'')');
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL VALUES(''57'',''CONHECIMENTO DE TRANSPORTE ELETRONICO (CT-E)'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1535');
end;
if VpaNumAtualizacao < 1536 Then
begin
VpfErro := '1536';
ExecutaComandoSql(Aux,'ALTER TABLE FRACAOOP ADD DATCORTE DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1536');
end;
if VpaNumAtualizacao < 1537 Then
begin
VpfErro := '1537';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD C_IND_SPE CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADFILIAIS SET C_IND_SPE = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1537');
end;
if VpaNumAtualizacao < 1538 Then
begin
VpfErro := '1538';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD (N_PER_COF NUMBER(6,3) NULL,'+
' N_PER_PIS NUMBER(6,3) NULL,'+
' C_CST_IPI CHAR(2) NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1538');
end;
if VpaNumAtualizacao < 1539 Then
begin
VpfErro := '1539';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL DROP (N_PER_COF, N_PER_PIS)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1539');
end;
if VpaNumAtualizacao < 1540 Then
begin
VpfErro := '1540';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD(C_CAL_PIS CHAR(1) NULL,'+
' C_CAL_COF CHAR(1) NULL)');
ExecutaComandoSql(Aux,'Update MOVNATUREZA SET C_CAL_PIS = ''N'','+
' C_CAL_COF = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1540');
end;
if VpaNumAtualizacao < 1541 Then
begin
VpfErro := '1541';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR DROP (I_PRA_DIA, I_QTD_PAR)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1541');
end;
if VpaNumAtualizacao < 1542 Then
begin
VpfErro := '1542';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR ADD I_COD_PAG NUMBER(10,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1542');
end;
if VpaNumAtualizacao < 1543 Then
begin
VpfErro := '1543';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASAPAGAR ADD I_COD_PAG NUMBER(10,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1543');
end;
if VpaNumAtualizacao < 1544 Then
begin
VpfErro := '1544';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR ADD C_MOD_DOC CHAR(2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1544');
end;
if VpaNumAtualizacao < 1545 Then
begin
VpfErro := '1545';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_SOW_IMC CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_SOW_IMC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1545');
end;
if VpaNumAtualizacao < 1546 Then
begin
VpfErro := '1546';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_COE_PAD NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1546');
end;
if VpaNumAtualizacao < 1547 Then
begin
VpfErro := '1547';
ExecutaComandoSql(Aux,'CREATE TABLE REPRESENTADA ('+
' CODREPRESENTADA NUMBER(10,0) NOT NULL, '+
' NOMREPRESENTADA VARCHAR2(50) NULL, '+
' NOMFANTASIA VARCHAR2(50) NULL,'+
' DESENDERECO VARCHAR2(50) NULL,'+
' DESBAIRRO VARCHAR2(30) NULL,'+
' DESCEP VARCHAR2(9) NULL,'+
' DESCOMPLEMENTO VARCHAR2(50) NULL,'+
' NUMENDERECO NUMBER(10) NULL,'+
' DESCIDADE VARCHAR2(40) NULL,'+
' DESUF CHAR(2) NULL, '+
' DESFONE VARCHAR2(20) NULL,'+
' DESFAX VARCHAR2(20) NULL,'+
' DESCNPJ VARCHAR2(18) NULL,'+
' DESINSCRICAOESTADUAL VARCHAR2(20),'+
' DESEMAIL VARCHAR2(100) NULL,'+
' PRIMARY KEY(CODREPRESENTADA))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1547');
end;
if VpaNumAtualizacao < 1548 Then
begin
VpfErro := '1548';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO ADD C_DEB_CRE CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FINANCEIRO SET C_DEB_CRE = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1548');
end;
if VpaNumAtualizacao < 1549 Then
begin
VpfErro := '1549';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(I_LAR_BAL NUMBER(10) NULL, '+
' I_ALT_BAL NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1549');
end;
if VpaNumAtualizacao < 1550 Then
begin
VpfErro := '1550';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMCORTEITEM ADD(LARENFESTO NUMBER(10) NULL, '+
' ALTENFESTO NUMBER(10) NULL, '+
' QTDENFESTO NUMBER(10,2) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1550');
end;
if VpaNumAtualizacao < 1551 Then
begin
VpfErro := '1551';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMCORTEITEM ADD(POSFACA NUMBER(1) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1551');
end;
if VpaNumAtualizacao < 1552 Then
begin
VpfErro := '1552';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD(C_AGR_BAL CHAR(1) NULL)');
ExecutaComandoSql(Aux,'Update CADPRODUTOS set C_AGR_BAL = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1552');
end;
if VpaNumAtualizacao < 1553 Then
begin
VpfErro := '1553';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(I_LAR_PRE NUMBER(10) NULL, '+
' I_ALT_PRE NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1553');
end;
if VpaNumAtualizacao < 1554 Then
begin
VpfErro := '1554';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD(C_IND_CAT CHAR(1) NULL)');
ExecutaComandoSql(Aux,'Update CFG_PRODUTO set C_IND_CAT = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1554');
end;
if VpaNumAtualizacao < 1555 Then
begin
VpfErro := '1555';
ExecutaComandoSql(Aux,'ALTER TABLE COMBINACAO ADD (SEQPRODUTOFIOTRAMA NUMBER(10) NULL,'+
' SEQPRODUTOFIOAJUDA NUMBER(10) NULL,'+
' CODCORFIOTRAMA NUMBER(10) NULL,'+
' CODCORFIOAJUDA NUMBER(10) NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1555');
end;
if VpaNumAtualizacao < 1556 Then
begin
VpfErro := '1556';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_CHA_SEC CHAR(1)NULL)' );
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CHA_SEC = ''F''' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1556');
end;
if VpaNumAtualizacao < 1557 Then
begin
VpfErro := '1557';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD(C_EST_CPR CHAR(1)NULL)' );
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EST_CPR = ''T''' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1557');
end;
if VpaNumAtualizacao < 1558 Then
begin
VpfErro := '1558';
ExecutaComandoSql(Aux,'ALTER TABLE MOVCONTASARECEBER ADD(C_DUP_IMP CHAR(1)NULL)' );
ExecutaComandoSql(Aux,'UPDATE MOVCONTASARECEBER SET C_DUP_IMP = ''S''' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1558');
end;
if VpaNumAtualizacao < 1559 Then
begin
VpfErro := '1559';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_COT_APG CHAR(1)NULL)' );
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_APG = ''F''' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1559');
end;
if VpaNumAtualizacao < 1560 Then
begin
VpfErro := '1560';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS ADD(N_ALT_PRO NUMBER(10,3)NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1560');
end;
if VpaNumAtualizacao < 1561 Then
begin
VpfErro := '1561';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS ADD(N_ALT_PRO NUMBER(10,3)NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1561');
end;
if VpaNumAtualizacao < 1562 Then
begin
VpfErro := '1562';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS ADD(I_COD_CFO NUMBER(10)NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1562');
end;
if VpaNumAtualizacao < 1563 Then
begin
VpfErro := '1563';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD(C_OPT_SIM CHAR(1)NULL)' );
ExecutaComandoSql(Aux,'Update CADCLIENTES set C_OPT_SIM = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1563');
end;
if VpaNumAtualizacao < 1564 Then
begin
VpfErro := '1564';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_GER_ALC CHAR(1) NULL' );
ExecutaComandoSql(Aux,'Update CADGRUPOS set C_GER_ALC = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1564');
end;
if VpaNumAtualizacao < 1565 Then
begin
VpfErro := '1565';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_MES_SCS NUMBER(10,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1565');
end;
if VpaNumAtualizacao < 1566 Then
begin
VpfErro := '1566';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD I_ORC_SLO NUMBER(10,0) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1566');
end;
if VpaNumAtualizacao < 1567 Then
begin
VpfErro := '1567';
ExecutaComandoSql(Aux,'CREATE TABLE AMOSTRAPRECOCLIENTE ('+
' CODAMOSTRA NUMBER(10,0) NOT NULL, '+
' CODCORAMOSTRA NUMBER(10,0) NOT NULL, '+
' CODCLIENTE NUMBER(10,0) NOT NULL, '+
' CODCOEFICIENTE NUMBER(10,0) NOT NULL, '+
' SEQPRECO NUMBER(10,0) NOT NULL, '+
' QTDAMOSTRA NUMBER(15,3) NULL,'+
' VALVENDA NUMBER(15,3) NULL,'+
' PERLUCRO NUMBER(5,2) NULL,'+
' PERCOMISSAO NUMBER(5,2) NULL,'+
' PRIMARY KEY(CODAMOSTRA,CODCORAMOSTRA,CODCLIENTE,CODCOEFICIENTE,SEQPRECO))');
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRAPRECOCLIENTE add CONSTRAINT AMOSTRAPRECOCLIENTE '+
' FOREIGN KEY (CODAMOSTRA) '+
' REFERENCES AMOSTRA (CODAMOSTRA) ');
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRAPRECOCLIENTE add CONSTRAINT AMOSTRAPRECOCLIENTECLI '+
' FOREIGN KEY (CODCLIENTE) '+
' REFERENCES CADCLIENTES (I_COD_CLI) ');
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRAPRECOCLIENTE add CONSTRAINT AMOSTRAPRECOCLIENTECOE '+
' FOREIGN KEY (CODCOEFICIENTE) '+
' REFERENCES COEFICIENTECUSTO (CODCOEFICIENTE) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1567');
end;
if VpaNumAtualizacao < 1568 Then
begin
VpfErro := '1568';
ExecutaComandoSql(Aux,'ALTER TABLE MOVCOMISSOES ADD D_PAG_REC DATE NULL ');
ExecutaComandoSql(Aux,'Update MOVCOMISSOES COM '+
' SET D_PAG_REC = (SELECT D_DAT_PAG FROM MOVCONTASARECEBER MOV '+
' WHERE MOV.I_EMP_FIL = COM.I_EMP_FIL '+
' AND MOV.I_LAN_REC = COM.I_LAN_REC '+
' AND MOV.I_NRO_PAR = COM.I_NRO_PAR )'+
' WHERE D_DAT_VAL IS NOT NULL' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1568');
end;
if VpaNumAtualizacao < 1569 Then
begin
VpfErro := '1569';
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRACONSUMO ADD QTDPONTOSBORDADO NUMBER(10,0) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1569');
end;
if VpaNumAtualizacao < 1570 Then
begin
VpfErro := '1570';
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRA ADD (QTDTOTALPONTOSBORDADO NUMBER(10,0) NULL, '+
' QTDCORTES NUMBER(10,0) NULL ,' +
' QTDTROCALINHA NUMBER(10,0) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1570');
end;
if VpaNumAtualizacao < 1571 Then
begin
VpfErro := '1571';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLASSIFICACAO ADD N_PER_PER NUMBER(5,2)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1571');
end;
if VpaNumAtualizacao < 1572 Then
begin
VpfErro := '1572';
ExecutaComandoSql(Aux,'DROP TABLE AMOSTRASERVICO ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1572');
end;
if VpaNumAtualizacao < 1573 Then
begin
VpfErro := '1573';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD (C_ENV_NFE CHAR(1) NULL)');
ExecutaComandoSql(Aux,'Update CADNOTAFISCAIS set C_ENV_NFE = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1573');
end;
if VpaNumAtualizacao < 1574 Then
begin
VpfErro := '1574';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_EST_INV CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CADGRUPOS set C_EST_INV = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1574');
end;
if VpaNumAtualizacao < 1575 Then
begin
VpfErro := '1575';
ExecutaComandoSql(Aux,'ALTER TABLE CADEMPRESAS ADD C_IND_REC CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CADEMPRESAS set C_IND_REC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1575');
end;
if VpaNumAtualizacao < 1576 Then
begin
VpfErro := '1576';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ADD I_COD_REP NUMBER(10) NULL');
ExecutaComandoSql(Aux,'CREATE INDEX CADORCAMENTOS_REP ON CADORCAMENTOS(I_COD_REP)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1576');
end;
if VpaNumAtualizacao < 1577 Then
begin
VpfErro := '1577';
ExecutaComandoSql(Aux,'ALTER TABLE OPITEMCADARCO ADD DESTAB VARCHAR2(150) NULL');
ExecutaComandoSql(Aux,'UPDATE OPITEMCADARCO SET DESTAB = NUMTAB');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1577');
end;
if VpaNumAtualizacao < 1578 Then
begin
VpfErro := '1578';
ExecutaComandoSql(Aux,'CREATE TABLE AMOSTRACOR ('+
' CODAMOSTRA NUMBER(10) NOT NULL,' +
' CODCOR NUMBER(10) NOT NULL, ' +
' DESIMAGEM VARCHAR2(200) NULL, ' +
' PRIMARY KEY(CODAMOSTRA,CODCOR))');
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRACOR add CONSTRAINT AMOSTRACORAMO '+
' FOREIGN KEY (CODAMOSTRA) '+
' REFERENCES AMOSTRA (CODAMOSTRA) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1578');
end;
if VpaNumAtualizacao < 1579 Then
begin
VpfErro := '1579';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_AMO_FTC CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_AMO_FTC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1579');
end;
if VpaNumAtualizacao < 1580 Then
begin
VpfErro := '1580';
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRA ADD DATFICHAAMOSTRA DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1580');
end;
if VpaNumAtualizacao < 1581 Then
begin
VpfErro := '1581';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD(C_EST_FAP CHAR(1), '+
' C_EST_MAP CHAR(1) NULL, '+
' C_EST_MCP CHAR(1) NULL)');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EST_FAP =''F'' ,'+
' C_EST_MAP = ''F'','+
' C_EST_MCP = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1581');
end;
if VpaNumAtualizacao < 1582 Then
begin
VpfErro := '1582';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD(C_CRM_CAM CHAR(1))');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_CRM_CAM =''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1582');
end;
if VpaNumAtualizacao < 1583 Then
begin
VpfErro := '1583';
ExecutaComandoSql(Aux,'ALTER TABLE SOLICITACAOCOMPRAITEM ADD(QTDCHAPA NUMBER(10,2) NULL,' +
' LARCHAPA NUMBER(8,2) NULL, ' +
' COMCHAPA NUMBER(8,2) NULL) ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1583');
end;
if VpaNumAtualizacao < 1584 Then
begin
VpfErro := '1584';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD C_EST_CHA CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_PRODUTO SET C_EST_CHA = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1584');
end;
if VpaNumAtualizacao < 1585 Then
begin
VpfErro := '1585';
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOCOMPRAITEM ADD(QTDCHAPA NUMBER(10,2) NULL,' +
' LARCHAPA NUMBER(8,2) NULL, ' +
' COMCHAPA NUMBER(8,2) NULL) ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1585');
end;
if VpaNumAtualizacao < 1586 Then
begin
VpfErro := '1586';
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOCOMPRAFORNECEDORITEM ADD(QTDCHAPA NUMBER(10,2) NULL,' +
' LARCHAPA NUMBER(8,2) NULL, ' +
' COMCHAPA NUMBER(8,2) NULL) ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1586');
end;
if VpaNumAtualizacao < 1587 Then
begin
VpfErro := '1587';
ExecutaComandoSql(Aux,'ALTER TABLE CADVENDEDORES ADD C_PAS_FTP VARCHAR2(150) NULL' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1587');
end;
if VpaNumAtualizacao < 1588 Then
begin
VpfErro := '1588';
ExecutaComandoSql(Aux,'ALTER TABLE PEDIDOCOMPRAITEM ADD(QTDCHAPA NUMBER(10,2) NULL,' +
' LARCHAPA NUMBER(8,2) NULL, ' +
' COMCHAPA NUMBER(8,2) NULL) ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1588');
end;
if VpaNumAtualizacao < 1589 Then
begin
VpfErro := '1589';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAISFOR ADD(N_QTD_CHA NUMBER(10,2) NULL,' +
' N_LAR_CHA NUMBER(8,2) NULL, ' +
' N_COM_CHA NUMBER(8,2) NULL) ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1589');
end;
if VpaNumAtualizacao < 1590 Then
begin
VpfErro := '1590';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD(N_DEN_VOL NUMBER(15,4) NULL,' +
' N_ESP_ACO NUMBER(8,4) NULL) ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1590');
end;
if VpaNumAtualizacao < 1591 Then
begin
VpfErro := '1591';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_COT_BPN CHAR(1) NULL)' );
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_BPN = ''F''' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1591');
end;
if VpaNumAtualizacao < 1592 Then
begin
VpfErro := '1592';
ExecutaComandoSql(Aux,'ALTER TABLE CADUSUARIOS ADD(C_DES_EMA VARCHAR2(120) NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1592');
end;
if VpaNumAtualizacao < 1593 Then
begin
VpfErro := '1593';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_COT_REU CHAR(1) NULL)' );
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_REU = ''F''' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1593');
end;
VpfErro := AtualizaTabela1(VpaNumAtualizacao);
if VpfErro = '' then
begin
VpfErro := AtualizaTabela2(VpaNumAtualizacao);
if VpfErro = '' then
begin
VpfErro := AtualizaTabela3(VpaNumAtualizacao);
if VpfErro = '' then
begin
VpfErro := AtualizaTabela4(VpaNumAtualizacao);
if VpfErro = '' then
begin
VpfErro := AtualizaTabela5(VpaNumAtualizacao);
end;
end;
end;
end;
VpfSemErros := true;
except
on E : Exception do
begin
Aux.sql.SaveToFile('comando.sql');
Aux.Sql.text := E.message;
Aux.Sql.SavetoFile('ErroInicio.txt');
if Confirmacao(VpfErro + ' - Existe uma alteração para ser feita no banco de dados mas existem usuários'+
' utilizando o sistema, ou algum outro sistema sendo utilizado no seu computador, é necessário'+
' que todos os usuários saiam do sistema, para'+
' poder continuar. Deseja continuar agora?') then
Begin
VpfSemErros := false;
AdicionaSQLAbreTabela(Aux,'Select I_Ult_Alt from CFG_GERAL ');
VpaNumAtualizacao := Aux.FieldByName('I_Ult_Alt').AsInteger;
end
else
exit;
end;
end;
until VpfSemErros;
// FAbertura.painelTempo1.Fecha;
end;
{******************************************************************************}
function TAtualiza.AtualizaTabela1(VpaNumAtualizacao : Integer): String;
begin
result := '';
if VpaNumAtualizacao < 1594 Then
begin
result := '1594';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_COT_CAA CHAR(1) NULL)' );
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_CAA = ''F''' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1594');
end;
if VpaNumAtualizacao < 1595 Then
begin
result := '1595';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS ADD(D_APR_AMO DATE NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1595');
end;
if VpaNumAtualizacao < 1596 Then
begin
result := '1596';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD(I_QTD_PAR NUMBER(10) NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1596');
end;
if VpaNumAtualizacao < 1597 Then
begin
result := '1597';
ExecutaComandoSql(Aux,'ALTER TABLE ETIQUETAPRODUTO ADD(NOMCOR VARCHAR2(60) NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1597');
end;
if VpaNumAtualizacao < 1598 Then
begin
result := '1598';
ExecutaComandoSql(Aux,'ALTER TABLE ETIQUETAPRODUTO ADD(NOMCLIENTE VARCHAR2(60) NULL, ' +
' DESORDEMCOMPRA VARCHAR2(40) NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1598');
end;
if VpaNumAtualizacao < 1599 Then
begin
result := '1599';
ExecutaComandoSql(Aux,'ALTER TABLE ETIQUETAPRODUTO ADD(NOMCOR2 VARCHAR2(60) NULL, ' +
' QTDCOR2 NUMBER(15,3) NULL, ' +
' NOMCOR3 VARCHAR2(60) NULL, ' +
' QTDCOR3 NUMBER(15,3) NULL, ' +
' NOMCOR4 VARCHAR2(60) NULL, ' +
' QTDCOR4 NUMBER(15,3) NULL, ' +
' NOMCOR5 VARCHAR2(60) NULL, ' +
' QTDCOR5 NUMBER(15,3) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1599');
end;
if VpaNumAtualizacao < 1600 Then
begin
result := '1600';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_TIP_BAD CHAR(2) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set C_TIP_BAD = ''MA''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1600');
end;
if VpaNumAtualizacao < 1601 Then
begin
result := '1601';
ExecutaComandoSql(Aux,'CREATE TABLE CODIGOCLIENTE(CODCLIENTE NUMBER(10) NOT NULL, ' +
' PRIMARY KEY(CODCLIENTE))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1601');
end;
if VpaNumAtualizacao < 1602 Then
begin
result := '1602';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(I_QTD_CCL NUMBER(10) NULL , '+
' I_ULT_CCG NUMBER(10) NULL ) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1602');
end;
if VpaNumAtualizacao < 1603 Then
begin
result := '1603';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD(C_FLA_EXP CHAR(1) NULL)' );
ExecutaComandoSql(Aux,'UPDATE CADCLIENTES SET C_FLA_EXP = ''S''' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1603');
end;
if VpaNumAtualizacao < 1604 Then
begin
result := '1604';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_MOD_SIP VARCHAR2(10) NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set C_MOD_SIP = ''0.001''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1604');
end;
if VpaNumAtualizacao < 1605 Then
begin
result := '1605';
ExecutaComandoSql(Aux,'ALTER TABLE CADUSUARIOS ADD C_MOD_SIP CHAR(1) NULL' );
ExecutaComandoSql(Aux,'Update CADUSUARIOS SET C_MOD_SIP = ''S''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1605');
end;
if VpaNumAtualizacao < 1606 Then
begin
result := '1606';
ExecutaComandoSql(Aux,'CREATE TABLE TABELAIMPORTACAO ( ' +
' CODTABELA NUMBER(10,0) NOT NULL, ' +
' SEQIMPORTACAO NUMBER(10,0) NULL, ' +
' NOMTABELA VARCHAR2(50) NULL, '+
' DESTABELA VARCHAR2(100) NULL, ' +
' DATIMPORTACAO DATE NULL,' +
' DESFILTROVENDEDOR VARCHAR2(50) NULL, ' +
' PRIMARY KEY(CODTABELA))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1606');
end;
if VpaNumAtualizacao < 1607 Then
begin
result := '1607';
ExecutaComandoSql(Aux,'CREATE TABLE ESTOQUECHAPA ( ' +
' SEQCHAPA NUMBER(10,0) NOT NULL, ' +
' CODFILIAL NUMBER(10,0) NOT NULL,' +
' SEQPRODUTO NUMBER(10,0) NOT NULL, ' +
' CODCOR NUMBER(10,0) NOT NULL, ' +
' CODTAMANHO NUMBER(10) NOT NULL, ' +
' LARCHAPA NUMBER(8,2) NULL, '+
' COMCHAPA NUMBER(8,2) NULL, '+
' PERCHAPA NUMBER(5,2) NULL,'+
' PESCHAPA NUMBER(15,3) NULL, ' +
' SEQNOTAFORNECEDOR NUMBER(10,0) ,'+
' PRIMARY KEY(SEQCHAPA))');
ExecutaComandoSql(Aux,'CREATE INDEX ESTOQUECHAPA_FK1 ON ESTOQUECHAPA(CODFILIAL,SEQPRODUTO,CODCOR,CODTAMANHO)');
ExecutaComandoSql(Aux,'CREATE INDEX ESTOQUECHAPA_FK2 ON ESTOQUECHAPA(CODFILIAL,SEQNOTAFORNECEDOR)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1607');
end;
if VpaNumAtualizacao < 1608 Then
begin
result := '1608';
ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTA ADD VALFRETE NUMBER(15,3)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1608');
end;
if VpaNumAtualizacao < 1609 Then
begin
result := '1609';
ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTA ADD DATPREVISAOVISITATEC DATE');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1609');
end;
if VpaNumAtualizacao < 1610 Then
begin
result := '1610';
ExecutaComandoSql(Aux,'ALTER TABLE TABELAIMPORTACAO ADD(DESCAMPODATA VARCHAR2(40),'+
' DATULTIMAALTERACAOMATRIZ DATE NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1610');
end;
if VpaNumAtualizacao < 1611 Then
begin
result := '1611';
ExecutaComandoSql(Aux,'ALTER TABLE CONTRATOITEM ADD VALCUSTOPRODUTO NUMBER(15,3)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1611');
end;
if VpaNumAtualizacao < 1612 Then
begin
result := '1612';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_COT_AAA CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_AAA = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1612');
end;
if VpaNumAtualizacao < 1613 Then
begin
result := '1613';
ExecutaComandoSql(Aux,'ALTER TABLE FRACAOOPCONSUMO ADD VALCUSTOTOTAL NUMBER(15,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1613');
end;
if VpaNumAtualizacao < 1614 Then
begin
result := '1614';
ExecutaComandoSql(Aux,'ALTER TABLE FRACAOOPCONSUMO ADD PESPRODUTO NUMBER(15,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1614');
end;
if VpaNumAtualizacao < 1615 then
begin
result := '1615';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS ADD N_QTD_CAN NUMBER(15,3)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1615');
end;
if VpaNumAtualizacao < 1616 then
begin
result := '1616';
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRA ADD INDAMOSTRAREALIZADA CHAR(1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1616');
end;
if VpaNumAtualizacao < 1617 then
begin
result := '1617';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD CODDEPARTAMENTOFICHATECNICA NUMBER(10)');
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_CRM_FIT CHAR(1)');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CRM_FIT = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1617');
end;
if VpaNumAtualizacao < 1618 then
begin
result := '1618';
ExecutaComandoSql(Aux,'ALTER TABLE CADVENDEDORES ADD I_TIP_VAL NUMBER(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADVENDEDORES SET I_TIP_VAL = 0');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1618');
end;
if VpaNumAtualizacao < 1619 then
begin
result := '1619';
ExecutaComandoSql(Aux,'ALTER TABLE MOVCOMISSOES ADD C_LIB_AUT CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE MOVCOMISSOES SET C_LIB_AUT = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1619');
end;
if VpaNumAtualizacao < 1620 then
begin
result := '1620';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL DROP COLUMN CODDEPARTAMENTOFICHATECNICA ');
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_CRM_FIT NUMBER(10)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1620');
end;
if VpaNumAtualizacao < 1621 then
begin
result := '1621';
ExecutaComandoSql(Aux,'ALTER TABLE PLANOCORTECORPO ADD(SEQCHAPA NUMBER(10,0)NULL, '+
' PERCHAPA NUMBER(15,3) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1621');
end;
if VpaNumAtualizacao < 1622 then
begin
result := '1622';
ExecutaComandoSql(Aux,'CREATE TABLE ESTAGIOPRODUCAOGRUPOUSUARIO ( '+
'CODGRUPOUSUARIO NUMBER(10), '+
'CODEST NUMBER(10) REFERENCES ESTAGIOPRODUCAO(CODEST),'+
'PRIMARY KEY(CODGRUPOUSUARIO, CODEST))');
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_EST_AUT CHAR(1)');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EST_AUT = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1622');
end;
if VpaNumAtualizacao < 1623 then
begin
result := '1623';
ExecutaComandoSql(Aux,'CREATE TABLE TABELAIMPORTACAOFILTRO( '+
' CODTABELA NUMBER(10) NOT NULL REFERENCES TABELAIMPORTACAO(CODTABELA),' +
' SEQFILTRO NUMBER(10) NOT NULL, ' +
' NOMCAMPO VARCHAR2(50) NULL, ' +
' TIPCAMPO NUMBER(1) NULL, '+
' PRIMARY KEY(CODTABELA,SEQFILTRO))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1623');
end;
if VpaNumAtualizacao < 1624 then
begin
result := '1624';
ExecutaComandoSql(Aux,'CREATE TABLE TABELAIMPORTACAOIGNORARCAMPO( '+
' CODTABELA NUMBER(10) NOT NULL REFERENCES TABELAIMPORTACAO(CODTABELA),' +
' SEQIGNORAR NUMBER(10) NOT NULL, ' +
' NOMCAMPO VARCHAR2(50) NULL, ' +
' TIPCAMPO NUMBER(1) NULL, '+
' PRIMARY KEY(CODTABELA,SEQIGNORAR))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1624');
end;
if VpaNumAtualizacao < 1625 Then
begin
result := '1625';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_MOD_PDV VARCHAR2(10) NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set C_MOD_PDV = ''0.001''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1625');
end;
if VpaNumAtualizacao < 1626 Then
begin
result := '1626';
ExecutaComandoSql(Aux,'ALTER TABLE CADUSUARIOS ADD C_MOD_PDV CHAR(1) NULL' );
ExecutaComandoSql(Aux,'Update CADUSUARIOS SET C_MOD_PDV = ''S''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1626');
end;
if VpaNumAtualizacao < 1627 Then
begin
result := '1627';
ExecutaComandoSql(Aux,'ALTER TABLE ETIQUETAPRODUTO ADD DESMM VARCHAR2(15) NULL' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1627');
end;
if VpaNumAtualizacao < 1628 Then
begin
result := '1628';
ExecutaComandoSql(Aux,'ALTER TABLE ETIQUETAPRODUTO ADD(DESREFERENCIACLIENTE VARCHAR2(25) NULL, ' +
' DESCOMPOSICAO VARCHAR2(25) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1628');
end;
if VpaNumAtualizacao < 1629 Then
begin
result := '1629';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS MODIFY C_SER_NOT VARCHAR2(35) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1629');
end;
if VpaNumAtualizacao < 1630 Then
begin
result := '1630';
ExecutaComandoSql(Aux,'ALTER TABLE CADSERIENOTAS MODIFY C_SER_NOT VARCHAR2(35) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1630');
end;
if VpaNumAtualizacao < 1631 Then
begin
result := '1631';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD C_VAP_OPC CHAR(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_PRODUTO set C_VAP_OPC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1631');
end;
if VpaNumAtualizacao < 1632 then
begin
result := '1632';
ExecutaComandoSql(Aux,'CREATE TABLE EMAILMEDIDORCORPO (' +
' SEQEMAIL NUMBER(10,0) NOT NULL,' +
' DATENVIO TIMESTAMP(6) NOT NULL,' +
' CODUSUARIO NUMBER(10,0) NOT NULL,' +
' PRIMARY KEY(SEQEMAIL) )');
ExecutaComandoSql(Aux,'CREATE INDEX EMAILMEDIDORCORPO_DATENVIO ON EMAILMEDIDORCORPO(DATENVIO)');
ExecutaComandoSql(Aux,'CREATE TABLE EMAILMEDIDORITEM (' +
' SEQEMAIL NUMBER(10,0) NOT NULL REFERENCES EMAILMEDIDORCORPO(SEQEMAIL),' +
' CODFILIAL NUMBER(10,0) NOT NULL,' +
' SEQCONTRATO NUMBER(10,0) NOT NULL,' +
' INDENVIADO CHAR(1) DEFAULT ''N'',' +
' DESSTATUS VARCHAR2(300), ' +
' PRIMARY KEY(SEQEMAIL,CODFILIAL,SEQCONTRATO) )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1632');
end;
if VpaNumAtualizacao < 1633 Then
begin
result := '1633';
ExecutaComandoSql(Aux,'CREATE TABLE RETORNOFRACAOOPFACTERCEIRO ('+
' CODFACCIONISTA NUMBER(10,0) NOT NULL, ' +
' SEQITEM NUMBER(10,0) NOT NULL, ' +
' SEQRETORNO NUMBER(10,0) NOT NULL, ' +
' SEQTERCEIRO NUMBER(10,0) NOT NULL, ' +
' NOMTERCEIRO VARCHAR2(50) NULL, ' +
' QTDREVISADO NUMBER(10,0) NULL, ' +
' QTDDEFEITO NUMBER(10,0) NULL, ' +
' PRIMARY KEY(CODFACCIONISTA,SEQITEM, SEQRETORNO,SEQTERCEIRO)) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1633');
end;
if VpaNumAtualizacao < 1634 Then
begin
result := '1634';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_EST_CEC CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EST_CEC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1634');
end;
if VpaNumAtualizacao < 1635 Then
begin
result := '1635';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_CRM_TMA NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1635');
end;
if VpaNumAtualizacao < 1636 Then
begin
result := '1636';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (N_CUS_RMA NUMBER(10,2) NULL, ' +
' N_CUS_TAP NUMBER(10,5) NULL, ' +
' N_CUS_INT NUMBER(10,3) NULL, ' +
' N_CUS_QTC NUMBER(10) NULL, ' +
' N_CUS_OPM NUMBER(10) NULL, ' +
' N_CUS_VMD NUMBER(10,5) NULL, ' +
' N_CUS_VMI NUMBER(10,5) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1636');
end;
if VpaNumAtualizacao < 1638 then
begin
result := '1638';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_ORP_OBS CHAR(1) NULL');
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_ORP_TER CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_ORP_TER=''F'',C_ORP_OBS=''F'' ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1638');
end;
if VpaNumAtualizacao < 1639 then
begin
result := '1639';
ExecutaComandoSql(Aux,'ALTER TABLE SETOR ADD DESMODELORELATORIO VARCHAR2(50) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1639');
end;
if VpaNumAtualizacao < 1640 then
begin
result := '1640';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD C_ALT_PLC CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_FISCAL set C_ALT_PLC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1640');
end;
if VpaNumAtualizacao < 1641 then
begin
result := '1641';
ExecutaComandoSql(Aux,'ALTER TABLE CADEMPRESAS ADD C_IND_DET CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CADEMPRESAS SET C_IND_DET = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1641');
end;
if VpaNumAtualizacao < 1642 then
begin
result := '1642';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(1,100,''CFG_GERAL'',''CONFIGURACOES DO SISTEMA'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOIGNORARCAMPO(CODTABELA, SEQIGNORAR,NOMCAMPO) ' +
' VALUES(1,1,''C_TIP_BAD'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1642');
end;
if VpaNumAtualizacao < 1643 then
begin
result := '1643';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD D_ULT_ALT DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1643');
end;
if VpaNumAtualizacao < 1644 then
begin
result := '1644';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(2,200,''CFG_ECF'',''CONFIGURACOES DO ECF'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1644');
end;
if VpaNumAtualizacao < 1645 then
begin
result := '1645';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_ECF ADD D_ULT_ALT DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1645');
end;
if VpaNumAtualizacao < 1646 then
begin
result := '1646';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(3,300,''CFG_FISCAL'',''CONFIGURACOES FISCAIS'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1646');
end;
if VpaNumAtualizacao < 1647 then
begin
result := '1647';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD D_ULT_ALT DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1647');
end;
if VpaNumAtualizacao < 1648 then
begin
result := '1648';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(4,400,''CFG_PRODUTO'',''CONFIGURACOES PRODUTO'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1648');
end;
if VpaNumAtualizacao < 1649 then
begin
result := '1649';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD D_ULT_ALT DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1649');
end;
if VpaNumAtualizacao < 1650 then
begin
result := '1650';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(5,500,''CADEMPRESAS'',''CONFIGURACOES DA EMPRESA'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(5,1,''I_COD_EMP'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1650');
end;
if VpaNumAtualizacao < 1651 then
begin
result := '1651';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(6,600,''CADFILIAIS'',''CONFIGURACOES DA FILIAL'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(6,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1651');
end;
if VpaNumAtualizacao < 1652 then
begin
result := '1652';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(7,700,''CAD_PAISES'',''PAISES'',''DAT_ULTIMA_ALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(7,1,''COD_PAIS'',3)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1652');
end;
if VpaNumAtualizacao < 1653 then
begin
result := '1653';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(8,800,''CAD_ESTADOS'',''UNIDADES FEDERADAS'',''DAT_ULTIMA_ALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(8,1,''COD_PAIS'',3)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(8,2,''COD_ESTADO'',3)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1653');
end;
if VpaNumAtualizacao < 1654 then
begin
result := '1654';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(9,900,''CAD_CIDADES'',''CIDADES'',''DAT_ULTIMA_ALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(9,1,''COD_CIDADE'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1654');
end;
if VpaNumAtualizacao < 1655 then
begin
result := '1655';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(10,1000,''CADREGIAOVENDA'',''REGIOES DE VENDAS'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(10,1,''I_COD_REG'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1655');
end;
if VpaNumAtualizacao < 1656 then
begin
result := '1656';
ExecutaComandoSql(Aux,'ALTER TABLE DESENVOLVEDOR ADD DATULTIMAALTERACAO DATE NULL ');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(11,1100,''DESENVOLVEDOR'',''DESENVOLVEDORES'',''DATULTIMAALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(11,1,''CODDESENVOLVEDOR'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1656');
end;
if VpaNumAtualizacao < 1657 then
begin
result := '1657';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(12,1200,''CADSITUACOESCLIENTES'',''SITUACOES CLIENTES'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(12,1,''I_COD_SIT'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1657');
end;
if VpaNumAtualizacao < 1658 then
begin
result := '1658';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(13,1300,''CADPROFISSOES'',''PROFISSOES CLIENTES'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(13,1,''I_COD_PRF'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1658');
end;
if VpaNumAtualizacao < 1659 then
begin
result := '1659';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_EST_FII NUMBER(10) NULL');
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_CRM_FII CHAR(1) NULL' );
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_EST_AGU NUMBER(10) NULL');
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_CRM_COT CHAR(1) NULL' );
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_CRM_OBS CHAR(1) NULL' );
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CRM_COT = ''F''' );
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CRM_FII = ''F''' );
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CRM_OBS = ''F''' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1659');
end;
if VpaNumAtualizacao < 1660 then
begin
result := '1660';
ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTA ADD DESOBSERVACAOCOMERCIAL VARCHAR2(300) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1660');
end;
if VpaNumAtualizacao < 1661 then
begin
result := '1661';
ExecutaComandoSql(Aux,'ALTER TABLE ordemproducaocorpo ADD DESCOR VARCHAR2(50) NULL');
ExecutaComandoSql(Aux,'ALTER TABLE ordemproducaocorpo ADD CODTRA NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1661');
end;
if VpaNumAtualizacao < 1662 then
begin
result := '1662';
ExecutaComandoSql(Aux,'CREATE TABLE PRODUTOINSTALACAOTEAR( ' +
' SEQPRODUTO NUMBER(10,0) NOT NULL, ' +
' SEQINSTALACAO NUMBER(10,0) NOT NULL, ' +
' CODCOR NUMBER(10,0) NULL, ' +
' QTDFIOLICO NUMBER(5) NULL, ' +
' DESFUNCAOFIO CHAR(1) NULL, ' +
' NUMLINHA NUMBER(3) NULL, ' +
' NUMCOLUNA NUMBER(3) NULL, ' +
' PRIMARY KEY(SEQPRODUTO,SEQINSTALACAO))');
ExecutaComandoSql(Aux,'CREATE INDEX PRODUTOINSTALACAOTEAR_FK1 ON PRODUTOINSTALACAOTEAR(SEQPRODUTO)');
ExecutaComandoSql(Aux,'CREATE INDEX PRODUTOINSTALACAOTEAR_FK2 ON PRODUTOINSTALACAOTEAR(CODCOR)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1662');
end;
if VpaNumAtualizacao < 1663 then
begin
result := '1663';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(14,1400,''CADUSUARIOS'',''CADASTRO DE USUARIOS'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(14,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(14,2,''I_COD_USU'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1663');
end;
if VpaNumAtualizacao < 1664 then
begin
result := '1664';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(15,1350,''CADGRUPOS'',''CADASTRO DE GRUPOS DE USUARIOS'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(15,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(15,2,''I_COD_GRU'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1664');
end;
if VpaNumAtualizacao < 1665 then
begin
result := '1665';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(16,1500,''CADCONDICOESPAGTO'',''CADASTRO DE CONDICOES DE PAGAMENTO'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(16,1,''I_COD_PAG'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1665');
end;
if VpaNumAtualizacao < 1666 then
begin
result := '1666';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(17,1600,''CADFORMASPAGAMENTO'',''CADASTRO DE FORMAS DE PAGAMENTO'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(17,1,''I_COD_FRM'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1666');
end;
if VpaNumAtualizacao < 1667 then
begin
result := '1667';
ExecutaComandoSql(Aux,'ALTER TABLE TECNICO ADD DATULTIMAALTERACAO DATE');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(18,1700,''TECNICO'',''CADASTRO DE TECNICOS'',''DATULTIMAALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(18,1,''CODTECNICO'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1667');
end;
if VpaNumAtualizacao < 1668 then
begin
result := '1668';
ExecutaComandoSql(Aux,'ALTER TABLE RAMO_ATIVIDADE ADD DAT_ULTIMA_ALTERACAO DATE');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(19,1800,''RAMO_ATIVIDADE'',''CADASTRO DE RAMOS DE ATIVIDADES'',''DAT_ULTIMA_ALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(19,1,''COD_RAMO_ATIVIDADE'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1668');
end;
if VpaNumAtualizacao < 1669 then
begin
result := '1669';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(20,1900,''CADTRANSPORTADORAS'',''CADASTRO DE TRANSPORTADORAS'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(20,1,''I_COD_TRA'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1670');
end;
if VpaNumAtualizacao < 1670 then
begin
result := '1670';
ExecutaComandoSql(Aux,'ALTER TABLE CONCORRENTE ADD DATULTIMAALTERACAO DATE');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(21,2000,''CONCORRENTE'',''CADASTRO DE CONCORRENTES '',''DATULTIMAALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(21,1,''CODCONCORRENTE'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1670');
end;
if VpaNumAtualizacao < 1671 then
begin
result := '1671';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(22,2100,''CADTABELAPRECO'',''CADASTRO DE TABELA DE PRECOS'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(22,1,''I_COD_EMP'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(22,2,''I_COD_TAB'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1671');
end;
if VpaNumAtualizacao < 1672 then
begin
result := '1672';
ExecutaComandoSql(Aux,'ALTER TABLE CADTIPOORCAMENTO ADD D_ULT_ALT DATE');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(23,2200,''CADTIPOORCAMENTO'',''CADASTRO DE TIPOS DE COTACOES '',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(23,1,''I_COD_TIP'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1672');
end;
if VpaNumAtualizacao < 1673 then
begin
result := '1673';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(24,2300,''CADBANCOS'',''CADASTRO DE BANCOS '',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(24,1,''I_COD_BAN'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1673');
end;
if VpaNumAtualizacao < 1674 then
begin
result := '1674';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(25,2400,''CADCONTAS'',''CADASTRO DE CONTA CORRENTE '',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(25,1,''C_NRO_CON'',3)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1674');
end;
if VpaNumAtualizacao < 1675 then
begin
result := '1675';
ExecutaComandoSql(Aux,'ALTER TABLE MEIODIVULGACAO ADD DATULTIMAALTERACAO DATE');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(26,2500,''MEIODIVULGACAO'',''CADASTRO DE MEIOS DE DIVULGACAO '',''DATULTIMAALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(26,1,''CODMEIODIVULGACAO'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1675');
end;
if VpaNumAtualizacao < 1676 then
begin
result := '1676';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD (I_QTD_QUA NUMBER(10) NULL, '+
' I_QTD_COL NUMBER(10) NULL,' +
' I_QTD_LIN NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'ALTER TABLE PRODUTOINSTALACAOTEAR ADD SEQMATERIAPRIMA NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1676');
end;
if VpaNumAtualizacao < 1677 then
begin
result := '1677';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(27,2600,''CAD_PLANO_CONTA'',''CADASTRO DE PLANOS DE CONTA'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(27,1,''C_CLA_PLA'',3)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(27,2,''I_COD_EMP'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1677');
end;
if VpaNumAtualizacao < 1678 then
begin
result := '1678';
ExecutaComandoSql(Aux,'ALTER TABLE MARCA ADD DATULTIMAALTERACAO DATE');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(28,2700,''MARCA'',''CADASTRO DE MARCA '',''DATULTIMAALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(28,1,''CODMARCA'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1678');
end;
if VpaNumAtualizacao < 1679 then
begin
result := '1679';
ExecutaComandoSql(Aux,'ALTER TABLE FAIXAETARIA ADD DATULTIMAALTERACAO DATE');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(29,2800,''FAIXAETARIA'',''CADASTRO DE FAIXA ETARIA'',''DATULTIMAALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(29,1,''CODFAIXAETARIA'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1679');
end;
if VpaNumAtualizacao < 1680 then
begin
result := '1680';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_ABE_CAB VARCHAR2(20)');
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_CON_ELE VARCHAR2(20)');
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_TEN_ALI VARCHAR2(20)');
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_COM_RED VARCHAR2(20)');
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_GRA_PRO VARCHAR2(20)');
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_SEN_FER VARCHAR2(20)');
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_SEN_NFE VARCHAR2(20)');
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_ACO_INO VARCHAR2(20)');
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD L_DES_FUN VARCHAR2(300)');
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD L_INF_DIS VARCHAR2(300)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1680');
end;
if VpaNumAtualizacao < 1681 then
begin
result := '1681';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD (C_EST_AVN CHAR(1) NULL, '+
' C_EST_SCC CHAR(1) NULL )' );
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EST_AVN = ''T'','+
' C_EST_SCC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1681');
end;
if VpaNumAtualizacao < 1682 then
begin
result := '1682';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLASSIFICACAO ADD (C_IND_INS CHAR(1) NULL )' );
ExecutaComandoSql(Aux,'UPDATE CADCLASSIFICACAO SET C_IND_INS = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1682');
end;
if VpaNumAtualizacao < 1683 then
begin
result := '1683';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD (C_EST_CSC CHAR(1) NULL, '+
' C_EST_CPC CHAR(1) NULL )' );
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EST_CSC = ''T'','+
' C_EST_CPC = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1683');
end;
if VpaNumAtualizacao < 1684 then
begin
result := '1684';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_ULT_PR1 NUMBER(10) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1684');
end;
if VpaNumAtualizacao < 1685 then
begin
result := '1685';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_SIP_VEN NUMBER(10) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1685');
end;
if VpaNumAtualizacao < 1686 then
begin
result := '1686';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOIGNORARCAMPO(CODTABELA, SEQIGNORAR,NOMCAMPO) ' +
' VALUES(1,2,''I_SIP_VEN'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1686');
end;
if VpaNumAtualizacao < 1687 then
begin
result := '1687';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,DESFILTROVENDEDOR) ' +
' VALUES(30,2900,''CADVENDEDORES'',''CADASTRO DE VENDEDORES'',''D_ULT_ALT'',''I_COD_VEN'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(30,1,''I_COD_VEN'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1687');
end;
if VpaNumAtualizacao < 1688 then
begin
result := '1688';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,DESFILTROVENDEDOR) ' +
' VALUES(31,3100,''CADCLIENTES'',''CADASTRO DE CLIENTES'',''D_ULT_ALT'',''I_COD_VEN'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(31,1,''I_COD_CLI'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1688');
end;
if VpaNumAtualizacao < 1689 then
begin
result := '1689';
ExecutaComandoSql(Aux,'CREATE INDEX CADCLIENTES_CP11 ON CADCLIENTES(C_FLA_EXP)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1689');
end;
if VpaNumAtualizacao < 1690 then
begin
result := '1690';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD(C_VER_PED VARCHAR2(15) NULL, ' +
' C_COM_PED VARCHAR2(50) NULL, ' +
' D_DAT_EXP DATE NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1690');
end;
if VpaNumAtualizacao < 1691 Then
begin
result := '1691';
ExecutaComandoSql(Aux,'CREATE TABLE NUMEROPEDIDO( '+
' CODFILIAL NUMBER(10) NOT NULL, ' +
' NUMPEDIDO NUMBER(10) NOT NULL, '+
' PRIMARY KEY(CODFILIAL,NUMPEDIDO))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1691');
end;
if VpaNumAtualizacao < 1691 Then
begin
result := '1691';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_QTD_NPE NUMBER(10)');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET I_QTD_NPE = 5000');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1691');
end;
if VpaNumAtualizacao < 1692 Then
begin
result := '1692';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD I_ULT_PED NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1692');
end;
if VpaNumAtualizacao < 1693 Then
begin
result := '1693';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ADD C_FLA_EXP CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CADORCAMENTOS set C_FLA_EXP = ''S''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1693');
end;
if VpaNumAtualizacao < 1694 then
begin
result := '1694';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(32,1550,''MOVCONDICAOPAGTO'',''PARCELAS DA CONDICAO DE PAGAMENTO'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(32,1,''I_COD_PAG'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(32,2,''I_NRO_PAR'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1694');
end;
if VpaNumAtualizacao < 1695 then
begin
result := '1695';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOIGNORARCAMPO(CODTABELA, SEQIGNORAR,NOMCAMPO) ' +
' VALUES(1,3,''C_DIR_REL'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOIGNORARCAMPO(CODTABELA, SEQIGNORAR,NOMCAMPO) ' +
' VALUES(1,4,''C_DIR_VER'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1695');
end;
if VpaNumAtualizacao < 1696 then
begin
result := '1696';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ADD(C_VER_PED VARCHAR2(15) NULL, ' +
' C_COM_PED VARCHAR2(50) NULL, ' +
' D_DAT_EXP DATE NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1696');
end;
if VpaNumAtualizacao < 1697 then
begin
result := '1697';
ExecutaComandoSql(Aux,'ALTER TABLE PRODUTOIMPRESSORA ADD DATULTIMAALTERACAO DATE');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1697');
end;
if VpaNumAtualizacao < 1698 then
begin
result := '1698';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' +
' VALUES(49,4700,''PRODUTOIMPRESSORA'',''IMPRESSORAS DO PRODUTO'',''DATULTIMAALTERACAO'', ''S'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(49,1,''SEQPRODUTO'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(49,2,''SEQIMPRESSORA'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1698');
end;
if VpaNumAtualizacao < 1699 then
begin
result := '1699';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' +
' VALUES(50,4800,''MOVKIT'',''CONSUMO DO PRODUTO'',''D_ULT_ALT'', ''S'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(50,1,''I_PRO_KIT'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(50,2,''I_SEQ_MOV'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(50,3,''I_COR_KIT'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1699');
end;
if VpaNumAtualizacao < 1700 then
begin
result := '1700';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' +
' VALUES(51,4900,''MOVTABELAPRECO'',''TABELA DE PRECO'',''D_ULT_ALT'', ''S'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(51,1,''I_COD_EMP'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(51,2,''I_COD_TAB'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(51,3,''I_SEQ_PRO'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(51,4,''I_COD_CLI'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(51,5,''I_COD_TAM'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(51,6,''I_COD_COR'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1700');
end;
if VpaNumAtualizacao < 1701 then
begin
result := '1701';
ExecutaComandoSql(Aux,'UPDATE MOVTABELAPRECO SET D_ULT_ALT = TO_DATE(''1/1/2000'',''DD/MM/YYYY'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1701');
end;
if VpaNumAtualizacao < 1702 then
begin
result := '1702';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR) ' +
' VALUES(52,5000,''MOVQDADEPRODUTO'',''ESTOQUE PRODUTOS'',''D_ULT_ALT'', ''S'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(52,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(52,2,''I_SEQ_PRO'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(52,3,''I_COD_TAM'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(52,4,''I_COD_COR'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1702');
end;
if VpaNumAtualizacao < 1703 then
begin
result := '1703';
ExecutaComandoSql(Aux,'UPDATE MOVQDADEPRODUTO SET D_ULT_ALT = TO_DATE(''1/1/2000'',''DD/MM/YYYY'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1703');
end;
if VpaNumAtualizacao < 1704 then
begin
result := '1704';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR,DESFILTROVENDEDOR) ' +
' VALUES(53,5100,''CADORCAMENTOS'',''COTACOES'',''D_ULT_ALT'', ''S'',''I_COD_VEN'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(53,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(53,2,''I_LAN_ORC'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1704');
end;
if VpaNumAtualizacao < 1705 then
begin
result := '1705';
ExecutaComandoSql(Aux,'CREATE TABLE TABELAIMPORTACAOCAMPOPAIFILHO ( ' +
' CODTABELA NUMBER(10) NOT NULL REFERENCES TABELAIMPORTACAO(CODTABELA), '+
' SEQCAMPO NUMBER(10) NOT NULL, ' +
' NOMCAMPO VARCHAR2(50) NULL, ' +
' NOMCAMPOPAI VARCHAR2(50) NULL, ' +
' PRIMARY KEY(CODTABELA,SEQCAMPO))');
ExecutaComandoSql(Aux,'CREATE INDEX TABELAIMPORTCAMPOPAIFILHO_FK ON TABELAIMPORTACAOCAMPOPAIFILHO(CODTABELA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1705');
end;
if VpaNumAtualizacao < 1706 then
begin
result := '1706';
ExecutaComandoSql(Aux,'ALTER TABLE TABELAIMPORTACAO ADD NOMTABELAPAI VARCHAR2(50) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1706');
end;
if VpaNumAtualizacao < 1707 then
begin
result := '1707';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA,INDIMPORTAR,DESFILTROVENDEDOR, NOMTABELAPAI) ' +
' VALUES(54,5400,''MOVORCAMENTOS'',''PRODUTOS DAS COTACOES'',''D_ULT_ALT'', ''S'',''I_COD_VEN'',''CADORCAMENTOS'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(54,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(54,2,''I_LAN_ORC'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA,SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(54,3,''I_SEQ_MOV'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOCAMPOPAIFILHO(CODTABELA,SEQCAMPO,NOMCAMPO,NOMCAMPOPAI) ' +
' VALUES(54,1,''I_EMP_FIL'',''I_EMP_FIL'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOCAMPOPAIFILHO(CODTABELA,SEQCAMPO,NOMCAMPO,NOMCAMPOPAI) ' +
' VALUES(54,2,''I_LAN_ORC'',''I_LAN_ORC'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1707');
end;
if VpaNumAtualizacao < 1708 then
begin
result := '1708';
ExecutaComandoSql(Aux,'UPDATE CAD_CIDADES SET DAT_ULTIMA_ALTERACAO = TO_DATE(''1/1/2000'',''DD/MM/YYYY'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1708');
end;
if VpaNumAtualizacao < 1709 then
begin
result := '1709';
ExecutaComandoSql(Aux,'UPDATE TABELAIMPORTACAO SET DATULTIMAALTERACAOMATRIZ = TO_DATE(''1/1/2000'',''DD/MM/YYYY'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1709');
end;
if VpaNumAtualizacao < 1710 then
begin
result := '1710';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASAPAGAR ADD C_IND_PRE CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADCONTASAPAGAR SET C_IND_PRE = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1710');
end;
if VpaNumAtualizacao < 1711 then
begin
result := '1711';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_COT_CPV CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_CPV = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1711');
end;
if VpaNumAtualizacao < 1712 then
begin
result := '1712';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (C_SIP_ITV CHAR(1) NULL, '+
' C_SIP_OBR VARCHAR2(10) NULL)');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_SIP_ITV = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set C_MOD_SIP = ''0.001''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set C_SIP_OBR = ''0.006''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1712');
end;
if VpaNumAtualizacao < 1713 then
begin
result := '1713';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOIGNORARCAMPO(CODTABELA, SEQIGNORAR,NOMCAMPO) ' +
' VALUES(1,5,''C_SIP_ITV'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1713');
end;
if VpaNumAtualizacao < 1714 then
begin
result := '1714';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD (D_ULT_IMP DATE NULL) ');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOIGNORARCAMPO(CODTABELA, SEQIGNORAR,NOMCAMPO) ' +
' VALUES(1,6,''D_ULT_IMP'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1714');
end;
if VpaNumAtualizacao < 1715 then
begin
result := '1715';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD (C_GER_APP CHAR(1) NULL) ');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_GER_APP = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1715');
end;
if VpaNumAtualizacao < 1716 then
begin
result := '1716';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD (N_PAR_MIN NUMBER(15,3) NULL, '+
' C_PAR_MIN CHAR(1) NULL )');
ExecutaComandoSql(Aux,'Update CADGRUPOS set C_PAR_MIN = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1716');
end;
if VpaNumAtualizacao < 1717 then
begin
result := '1717';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD (I_CFO_PRO NUMBER(6) NULL, '+
' I_CFO_SER NUMBER(6) NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1717');
end;
if VpaNumAtualizacao < 1718 then
begin
result := '1718';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD (C_EMA_NFE VARCHAR2(100) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1718');
end;
if VpaNumAtualizacao < 1719 then
begin
result := '1719';
ExecutaComandoSql(Aux,'ALTER TABLE PEDIDOCOMPRACORPO ADD TIPPEDIDO CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE PEDIDOCOMPRACORPO SET TIPPEDIDO = ''P''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1719');
end;
if VpaNumAtualizacao < 1720 then
begin
result := '1720';
ExecutaComandoSql(Aux,'CREATE TABLE AMOSTRAITEMESPECIAL (' +
' CODAMOSTRA NUMBER(10) NULL REFERENCES AMOSTRA(CODAMOSTRA), ' +
' SEQITEM NUMBER(10) NULL, ' +
' SEQPRODUTO NUMBER(10) NULL, ' +
' VALITEM NUMBER(15,3) NULL, ' +
' DESOBSERVACAO VARCHAR2(200) NULL, ' +
' PRIMARY KEY(CODAMOSTRA, SEQITEM)) ');
ExecutaComandoSql(Aux,'CREATE INDEX AMOSTRAITEMESPECIAL_FK1 ON AMOSTRAITEMESPECIAL(CODAMOSTRA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1720');
end;
if VpaNumAtualizacao < 1721 then
begin
result := '1721';
ExecutaComandoSql(Aux,'DROP TABLE AMOSTRASERVICOFIXO');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1721');
end;
end;
{******************************************************************************}
function TAtualiza.AtualizaTabela2(VpaNumAtualizacao: Integer): String;
begin
RESULT := '';
if VpaNumAtualizacao < 1722 then
begin
result := '1722';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_SUB_TRI CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CADPRODUTOS SET C_SUB_TRI = ''N''');
ExecutaComandoSql(Aux,'Update CADPRODUTOS SET C_SUB_TRI = ''S'''+
' Where N_RED_ICM < 0 ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1722');
end;
if VpaNumAtualizacao < 1723 then
begin
result := '1723';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD C_TIP_EMI CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update MOVNATUREZA SET C_TIP_EMI = ''P'''+
' Where C_ENT_SAI = ''S''');
ExecutaComandoSql(Aux,'Update MOVNATUREZA SET C_TIP_EMI = ''F'''+
' Where C_ENT_SAI = ''E''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1723');
end;
if VpaNumAtualizacao < 1724 then
begin
result := '1724';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_EST_ESR CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CADGRUPOS SET C_EST_ESR = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1724');
end;
if VpaNumAtualizacao < 1725 then
begin
result := '1725';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_DES_BCI CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CADPRODUTOS SET C_DES_BCI = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1725');
end;
if VpaNumAtualizacao < 1726 then
begin
result := '1726';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD I_MET_CUS NUMBER(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_PRODUTO SET I_MET_CUS = 0');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1726');
end;
if VpaNumAtualizacao < 1727 then
begin
result := '1727';
ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTAPRODUTO MODIFY NOMPRODUTO VARCHAR2(80)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1727');
end;
if VpaNumAtualizacao < 1728 then
begin
result := '1728';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD C_COT_TRA VARCHAR2(30) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1728');
end;
if VpaNumAtualizacao < 1729 then
begin
result := '1729';
ExecutaComandoSql(Aux,'ALTER TABLE CADICMSESTADOS ADD N_RED_ICM NUMBER(6,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1729');
end;
if VpaNumAtualizacao < 1730 then
begin
result := '1730';
ExecutaComandoSql(Aux,'CREATE TABLE AMOSTRALOG ( ' +
' CODAMOSTRA NUMBER(10) NOT NULL REFERENCES AMOSTRA(CODAMOSTRA), ' +
' SEQLOG NUMBER(10) NOT NULL,' +
' CODUSUARIO NUMBER(10) NOT NULL, ' +
' DATLOG DATE NOT NULL, ' +
' DESLOCALARQUIVO VARCHAR2(200) NULL, ' +
' PRIMARY KEY(CODAMOSTRA,SEQLOG))');
ExecutaComandoSql(Aux,'CREATE INDEX AMOSTRALOG_FK1 ON AMOSTRALOG(CODAMOSTRA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1730');
end;
if VpaNumAtualizacao < 1731 then
begin
result := '1731';
ExecutaComandoSql(Aux,'CREATE TABLE AMOSTRACONSUMOLOG ( ' +
' CODAMOSTRA NUMBER(10) NOT NULL REFERENCES AMOSTRA(CODAMOSTRA), ' +
' CODCOR NUMBER(10) NOT NULL, ' +
' SEQLOG NUMBER(10) NOT NULL,' +
' CODUSUARIO NUMBER(10) NOT NULL, ' +
' DATLOG DATE NOT NULL, ' +
' DESLOCALARQUIVO VARCHAR2(200) NULL, ' +
' PRIMARY KEY(CODAMOSTRA,CODCOR,SEQLOG))');
ExecutaComandoSql(Aux,'CREATE INDEX AMOSTRACONSUMOLOG_FK1 ON AMOSTRACONSUMOLOG(CODAMOSTRA,CODCOR)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1731');
end;
if VpaNumAtualizacao < 1732 then
begin
result := '1732';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS ADD N_RED_BAS NUMBER(6,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1732');
end;
if VpaNumAtualizacao < 1733 then
begin
result := '1733';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA MODIFY C_COD_NAT VARCHAR2(20)');
ExecutaComandoSql(Aux,'ALTER TABLE CADNATUREZA MODIFY C_COD_NAT VARCHAR2(20)');
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS MODIFY C_COD_NAT VARCHAR2(20)');
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR MODIFY C_COD_NAT VARCHAR2(20)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1732');
end;
if VpaNumAtualizacao < 1734 then
begin
result := '1734';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD (I_CFO_SUB NUMBER(6) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1734');
end;
if VpaNumAtualizacao < 1735 then
begin
result := '1735';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD (C_NAT_STD VARCHAR2(15) NULL, ' +
' C_NAT_STF VARCHAR2(15) NULL, ' +
' C_NAT_SPD VARCHAR2(15) NULL, ' +
' C_NAT_SPF VARCHAR2(15) NULL, ' +
' C_NAT_SSD VARCHAR2(15) NULL, ' +
' C_NAT_SSF VARCHAR2(15) NULL, ' +
' C_NST_SPD VARCHAR2(20) NULL, ' +
' C_NST_SPF VARCHAR2(20) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1735');
end;
if VpaNumAtualizacao < 1736 then
begin
result := '1736';
ExecutaComandoSql(Aux,'ALTER TABLE CADICMSESTADOS ADD C_SUB_TRI CHAR(1)');
ExecutaComandoSql(Aux,'UPDATE CADICMSESTADOS SET C_SUB_TRI = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1736');
end;
if VpaNumAtualizacao < 1737 then
begin
result := '1737';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD N_PER_SUT NUMBER(6,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1737');
end;
if VpaNumAtualizacao < 1738 then
begin
result := '1738';
ExecutaComandoSql(Aux,'CREATE TABLE PEDIDOCOMPRAITEMCONSUMOFRACAO ( ' +
' CODFILIAL NUMBER(10,0) NOT NULL, ' +
' SEQPEDIDO NUMBER(10,0) NOT NULL, ' +
' SEQITEM NUMBER(10,0) NOT NULL, ' +
' CODFILIALFRACAO NUMBER(10,0) NOT NULL, ' +
' SEQORDEM NUMBER(10,0) NOT NULL, ' +
' SEQFRACAO NUMBER(10,0) NOT NULL, ' +
' SEQCONSUMO NUMBER(10,0) NOT NULL, ' +
' PRIMARY KEY(CODFILIAL, SEQPEDIDO, SEQITEM, CODFILIALFRACAO, SEQORDEM,SEQFRACAO, SEQCONSUMO))');
ExecutaComandoSql(Aux,'ALTER TABLE PEDIDOCOMPRAITEMCONSUMOFRACAO add CONSTRAINT PEDIDOCOMPRAITEM_CONSUMOFRA '+
' FOREIGN KEY (CODFILIAL,SEQPEDIDO,SEQITEM) '+
' REFERENCES PEDIDOCOMPRAITEM (CODFILIAL,SEQPEDIDO,SEQITEM) ');
ExecutaComandoSql(Aux,'ALTER TABLE PEDIDOCOMPRAITEMCONSUMOFRACAO add CONSTRAINT CONSUMOFRACAO_PEDIDOITEM '+
' FOREIGN KEY (CODFILIALFRACAO,SEQORDEM,SEQFRACAO,SEQCONSUMO) '+
' REFERENCES FRACAOOPCONSUMO (CODFILIAL,SEQORDEM,SEQFRACAO,SEQCONSUMO) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1738');
end;
if VpaNumAtualizacao < 1739 then
begin
result := '1739';
ExecutaComandoSql(Aux,'ALTER TABLE COR ADD DATULTIMAALTERACAO DATE NULL ');
ExecutaComandoSql(Aux,'Update COR set DATULTIMAALTERACAO = SYSDATE ');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(55,4050,''COR'',''CORES'',''DATULTIMAALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(55,1,''COD_COR'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1739');
end;
if VpaNumAtualizacao < 1740 then
begin
result := '1740';
ExecutaComandoSql(Aux,'Update CFG_GERAL set C_SIP_OBR = ''0.010''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1740');
end;
if VpaNumAtualizacao < 1741 then
begin
result := '1741';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOIGNORARCAMPO(CODTABELA, SEQIGNORAR,NOMCAMPO) ' +
' VALUES(1,7,''I_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOIGNORARCAMPO(CODTABELA, SEQIGNORAR,NOMCAMPO) ' +
' VALUES(1,8,''I_ULT_PR1'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1741');
end;
if VpaNumAtualizacao < 1742 then
begin
result := '1742';
ExecutaComandoSql(Aux,'Update CFG_GERAL set C_SIP_OBR = ''0.011''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1742');
end;
if VpaNumAtualizacao < 1743 then
begin
result := '1743';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD (I_CFO_STR NUMBER(6) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1743');
end;
if VpaNumAtualizacao < 1744 then
begin
result := '1744';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTAORCAMENTO ADD (I_FIL_ORC NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update MOVNOTAORCAMENTO SET I_FIL_ORC = I_EMP_FIL');
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTAORCAMENTO drop PRIMARY KEY');
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTAORCAMENTO '+
' ADD PRIMARY KEY(I_EMP_FIL,I_SEQ_NOT,I_LAN_ORC,I_FIL_ORC)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1744');
end;
if VpaNumAtualizacao < 1745 then
begin
result := '1745';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD( I_COT_LCP NUMBER(4) NULL, ' +
' I_COT_LCC NUMBER(4) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_COT_LCP = 450, I_COT_LCC = 200');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1745');
end;
if VpaNumAtualizacao < 1746 then
begin
result := '1746';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS MODIFY C_NOM_PRO VARCHAR2(100)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1746');
end;
if VpaNumAtualizacao < 1747 then
begin
result := '1747';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD C_SAL_NMC CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_PRODUTO set C_SAL_NMC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1747');
end;
if VpaNumAtualizacao < 1748 then
begin
result := '1748';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD (C_NAT_RED VARCHAR2(15) NULL, ' +
' C_NAT_REF VARCHAR2(15) NULL, ' +
' C_NAT_RID VARCHAR2(15) NULL, ' +
' C_NAT_RIF VARCHAR2(15) NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1748');
end;
if VpaNumAtualizacao < 1749 then
begin
result := '1749';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD (I_CFO_PRR NUMBER(6) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1749');
end;
if VpaNumAtualizacao < 1750 then
begin
result := '1750';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD (C_NST_RED VARCHAR2(15) NULL, ' +
' C_NST_REF VARCHAR2(15) NULL, ' +
' C_NST_RID VARCHAR2(15) NULL, ' +
' C_NST_RIF VARCHAR2(15) NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1750');
end;
if VpaNumAtualizacao < 1751 then
begin
result := '1751';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD (C_MOV_FIS CHAR(1) NULL)');
ExecutaComandoSql(Aux,'UPDATE MOVNATUREZA SET C_MOV_FIS = ''S''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1751');
end;
if VpaNumAtualizacao < 1752 then
begin
result := '1752';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD (I_DES_PRO NUMBER(2) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1752');
end;
if VpaNumAtualizacao < 1753 then
begin
result := '1753';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_ECF ADD (NUMPORTA NUMBER(2) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1753');
end;
if VpaNumAtualizacao < 1754 then
begin
result := '1754';
ExecutaComandoSql(Aux,'UPDATE MOVNOTAORCAMENTO ' +
' SET I_LAN_ORC = I_FIL_ORC ' +
' WHERE I_FIL_ORC > 100');
ExecutaComandoSql(Aux,'UPDATE MOVNOTAORCAMENTO ' +
' SET I_FIL_ORC = 11 ' +
' WHERE I_FIL_ORC > 100');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1753');
end;
if VpaNumAtualizacao < 1755 then
begin
result := '1755';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD(C_COD_REC VARCHAR2(30), ' +
' I_DIA_VIC NUMBER(2) )');
ExecutaComandoSql(Aux,'Update CADFILIAIS SET I_DIA_VIC = 20');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1755');
end;
if VpaNumAtualizacao < 1756 then
begin
result := '1756';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD (C_NAT_SRD VARCHAR2(15) NULL, ' +
' C_NAT_SRF VARCHAR2(15) NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1756');
end;
if VpaNumAtualizacao < 1757 then
begin
result := '1757';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAISFOR MODIFY C_COD_CST VARCHAR2(3)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1757');
end;
if VpaNumAtualizacao < 1758 then
begin
result := '1758';
ExecutaComandoSql(Aux,'DROP TABLE PEDIDOCOMPRAITEMCONSUMOFRACAO ');
ExecutaComandoSql(Aux,'CREATE TABLE PEDIDOCOMPRAITEMMATERIAPRIMA( '+
' CODFILIAL NUMBER(10,0) NOT NULL, ' +
' SEQPEDIDO NUMBER(10) NOT NULL, ' +
' SEQITEM NUMBER(10) NOT NULL, ' +
' SEQITEMMP NUMBER(10) NOT NULL, ' +
' SEQPRODUTO NUMBER(10) NOT NULL, ' +
' CODCOR NUMBER(10) NULL, ' +
' QTDPRODUTO NUMBER(15,3) NULL, ' +
' QTDCHAPA NUMBER(10) NULL, ' +
' LARCHAPA NUMBER(10) NULL, ' +
' COMCHAPA NUMBER(10) NULL, ' +
' PRIMARY KEY (CODFILIAL,SEQPEDIDO,SEQITEM,SEQITEMMP))');
ExecutaComandoSql(Aux,'ALTER TABLE PEDIDOCOMPRAITEMMATERIAPRIMA add CONSTRAINT PEDIDOCOMPRAITEM_MP '+
' FOREIGN KEY (CODFILIAL,SEQPEDIDO,SEQITEM) '+
' REFERENCES PEDIDOCOMPRAITEM (CODFILIAL,SEQPEDIDO,SEQITEM) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1758');
end;
if VpaNumAtualizacao < 1759 then
begin
result := '1759';
ExecutaComandoSql(Aux,'ALTER TABLE FRACAOOPESTAGIO ADD INDTERCEIRIZADO CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE FRACAOOPESTAGIO SET INDTERCEIRIZADO = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1759');
end;
if VpaNumAtualizacao < 1760 then
begin
result := '1760';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO ADD I_CON_PAD NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1760');
end;
if VpaNumAtualizacao < 1761 then
begin
result := '1761';
ExecutaComandoSql(Aux,'ALTER TABLE CADEMPRESAS ADD C_PLA_PAD VARCHAR2(20) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1761');
end;
if VpaNumAtualizacao < 1762 then
begin
result := '1762';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD (C_NAR_ISD VARCHAR2(15) NULL, ' +
' C_NAR_ISF VARCHAR2(15) NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1762');
end;
if VpaNumAtualizacao < 1763 then
begin
result := '1763';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_ENG_TRA VARCHAR2(15) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1763');
end;
if VpaNumAtualizacao < 1764 then
begin
result := '1764';
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOCOMPRAFORNECEDORITEM ADD PERICMS NUMBER(5,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1764');
end;
if VpaNumAtualizacao < 1765 then
begin
result := '1765';
ExecutaComandoSql(Aux,'alter table MOVORCAMENTOS ADD N_CUS_UNI NUMBER(15,3)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1765');
end;
if VpaNumAtualizacao < 1766 then
begin
result := '1766';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD (C_SUT_RSD VARCHAR2(15) NULL, ' +
' C_SUT_RSF VARCHAR2(15) NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1766');
end;
if VpaNumAtualizacao < 1767 then
begin
result := '1767';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD (C_NRS_RID VARCHAR2(15) NULL, ' +
' C_NRS_RIF VARCHAR2(15) NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1767');
end;
if VpaNumAtualizacao < 1768 then
begin
result := '1768';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD (C_STR_RSD VARCHAR2(15) NULL, ' +
' C_STR_RSF VARCHAR2(15) NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1768');
end;
if VpaNumAtualizacao < 1769 then
begin
result := '1769';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD I_OPE_SBO NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1769');
end;
if VpaNumAtualizacao < 1770 then
begin
result := '1770';
ExecutaComandoSql(Aux,' CREATE TABLE AMOSTRAPROCESSO ( ' +
' CODAMOSTRA NUMBER(10) NOT NULL, ' +
' SEQPROCESSO NUMBER(10) NOT NULL, ' +
' CODESTAGIO NUMBER(10), ' +
' CODPROCESSOPRODUCAO NUMBER(10), ' +
' QTDPRODUCAOHORA NUMBER(11,4), ' +
' INDCONFIGURACAO CHAR(1), ' +
' DESTEMPOCONFIGURACAO VARCHAR2(7), ' +
' VALUNITARIO NUMBER(15,4) NULL, '+
' PRIMARY KEY (CODAMOSTRA, SEQPROCESSO), ' +
' FOREIGN KEY (CODAMOSTRA) REFERENCES AMOSTRA (CODAMOSTRA), ' +
' FOREIGN KEY (CODESTAGIO) REFERENCES ESTAGIOPRODUCAO (CODEST) ) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1770');
end;
if VpaNumAtualizacao < 1771 then
begin
result := '1771';
ExecutaComandoSql(Aux,'DROP TABLE AMOSTRAPRODUTO');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1771');
end;
if VpaNumAtualizacao < 1772 then
begin
result := '1772';
ExecutaComandoSql(Aux,'ALTER TABLE ESTAGIOPRODUCAO ADD VALHOR NUMBER(15,4) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1772');
end;
if VpaNumAtualizacao < 1773 then
begin
result := '1773';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD C_COT_CSP CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADFILIAIS '+
'SET C_COT_CSP = (SELECT C_COT_CSP from CFG_GERAL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1773');
end;
if VpaNumAtualizacao < 1774 then
begin
result := '1774';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD C_DES_IPI CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADFILIAIS SET C_DES_IPI = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1774');
end;
if VpaNumAtualizacao < 1775 then
begin
result := '1775';
ExecutaComandoSql(Aux,'CREATE TABLE PRODUTOINSTALACAOTEARREPETICAO ( ' +
' SEQPRODUTO NUMBER(10) NOT NULL REFERENCES CADPRODUTOS(I_SEQ_PRO), ' +
' SEQREPETICAO NUMBER(10) NOT NULL, ' +
' COLINICIAL NUMBER(10) NULL, ' +
' COLFINAL NUMBER(10) NULL, ' +
' QTDREPETICAO NUMBER(10) NULL, ' +
' PRIMARY KEY(SEQPRODUTO,SEQREPETICAO))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1775');
end;
if VpaNumAtualizacao < 1776 then
begin
result := '1776';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD C_IND_HOT CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADCLIENTES SET C_IND_HOT = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1776');
end;
if VpaNumAtualizacao < 1777 then
begin
result := '1777';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_CHA_SHO CHAR(1)');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CHA_SHO = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1777');
end;
if VpaNumAtualizacao < 1778 then
begin
result := '1778';
ExecutaComandoSql(Aux,'ALTER TABLE CHAMADOCORPO ADD CODHOTEL NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1778');
end;
if VpaNumAtualizacao < 1779 then
begin
result := '1779';
ExecutaComandoSql(Aux,'ALTER TABLE HISTORICOLIGACAO ADD INDCADASTRORAPIDO CHAR(1) NULL ');
ExecutaComandoSql(Aux,'UPDATE HISTORICOLIGACAO SET INDCADASTRORAPIDO = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1779');
end;
if VpaNumAtualizacao < 1780 then
begin
result := '1780';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD C_COP_ENF VARCHAR2(150) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1780');
end;
if VpaNumAtualizacao < 1781 then
begin
result := '1781';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD C_IND_ATI CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADCLIENTES SET C_IND_ATI =''S''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1781');
end;
if VpaNumAtualizacao < 1782 then
begin
result := '1782';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_CHA_ANC CHAR(1)NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CHA_ANC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1782');
end;
if VpaNumAtualizacao < 1783 then
begin
result := '1783';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_DEC_TAP NUMBER(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET I_DEC_TAP = I_DEC_QTD ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1783');
end;
if VpaNumAtualizacao < 1784 then
begin
result := '1784';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR ADD C_ORI_PEC CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADNOTAFISCAISFOR SET C_ORI_PEC = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1784');
end;
if VpaNumAtualizacao < 1785 then
begin
result := '1785';
ExecutaComandoSql(Aux,'ALTER TABLE IMPRESSAOCONSUMOFRACAO ADD CODCOR NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1785');
end;
if VpaNumAtualizacao < 1786 then
begin
result := '1786';
ExecutaComandoSql(Aux,'CREATE TABLE ORCAMENTOPEDIDOCOMPRA( ' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' SEQORCAMENTO NUMBER(10) NOT NULL, ' +
' SEQPEDIDO NUMBER(10) NOT NULL, ' +
' PRIMARY KEY(CODFILIAL, SEQORCAMENTO,SEQPEDIDO))');
ExecutaComandoSql(Aux,'CREATE INDEX ORCAMENTOPEDIDOCOMPRA_FK1 ON ORCAMENTOPEDIDOCOMPRA(CODFILIAL,SEQORCAMENTO)');
ExecutaComandoSql(Aux,'CREATE INDEX ORCAMENTOPEDIDOCOMPRA_FK2 ON ORCAMENTOPEDIDOCOMPRA(CODFILIAL,SEQPEDIDO)');
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOPEDIDOCOMPRA add CONSTRAINT ORCAMENTOPEDIDOCOMPRA_PC '+
' FOREIGN KEY (CODFILIAL,SEQPEDIDO) '+
' REFERENCES PEDIDOCOMPRACORPO(CODFILIAL,SEQPEDIDO) ');
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOPEDIDOCOMPRA add CONSTRAINT ORCAMENTOPEDIDOCOMPRA_OC '+
' FOREIGN KEY (CODFILIAL,SEQORCAMENTO) '+
' REFERENCES ORCAMENTOCOMPRACORPO(CODFILIAL,SEQORCAMENTO) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1786');
end;
if VpaNumAtualizacao < 1787 then
begin
result := '1787';
ExecutaComandoSql(Aux,'CREATE TABLE ORCAMENTOCOMPRAFRACAOOP( ' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' SEQORCAMENTO NUMBER(10) NOT NULL, ' +
' CODFILIALFRACAO NUMBER(10) NOT NULL, ' +
' SEQORDEM NUMBER(10) NOT NULL, ' +
' SEQFRACAO NUMBER(10) NOT NULL, ' +
' PRIMARY KEY(CODFILIAL, SEQORCAMENTO,CODFILIALFRACAO,SEQORDEM,SEQFRACAO))');
ExecutaComandoSql(Aux,'CREATE INDEX ORCAMENTOCOMPRAFRACAOOP_FK1 ON ORCAMENTOCOMPRAFRACAOOP(CODFILIAL,SEQORCAMENTO)');
ExecutaComandoSql(Aux,'CREATE INDEX ORCAMENTOCOMPRAFRACAOOP_FK2 ON ORCAMENTOCOMPRAFRACAOOP(CODFILIALFRACAO,SEQORDEM,SEQFRACAO)');
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOCOMPRAFRACAOOP add CONSTRAINT ORCAMENTOCOMPRAFRACAOOP_OC '+
' FOREIGN KEY (CODFILIAL,SEQORCAMENTO) '+
' REFERENCES ORCAMENTOCOMPRACORPO(CODFILIAL,SEQORCAMENTO) ');
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOCOMPRAFRACAOOP add CONSTRAINT ORCAMENTOCOMPRAFRACAOOP_FRA '+
' FOREIGN KEY (CODFILIALFRACAO,SEQORDEM,SEQFRACAO) '+
' REFERENCES FRACAOOP(CODFILIAL,SEQORDEM,SEQFRACAO) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1787');
end;
if VpaNumAtualizacao < 1788 then
begin
result := '1788';
ExecutaComandoSql(Aux,'ALTER TABLE MOVCOMISSOES ADD N_BAS_PRO NUMBER(15,3) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1788');
end;
if VpaNumAtualizacao < 1789 then
begin
result := '1789';
ExecutaComandoSql(Aux,'ALTER TABLE CADEMPRESAS ADD C_CLA_FIO VARCHAR2(15) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1789');
end;
if VpaNumAtualizacao < 1790 Then
begin
result := '1790';
ExecutaComandoSql(Aux,'CREATE TABLE NUMERONOTA( '+
' CODFILIAL NUMBER(10) NOT NULL, ' +
' SEQNOTA NUMBER(10) NOT NULL, '+
' PRIMARY KEY(CODFILIAL,SEQNOTA))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1790');
end;
if VpaNumAtualizacao < 1791 then
begin
result := '1791';
ExecutaComandoSql(Aux,'ALTER TABLE TELEMARKETING ADD CODVENDEDOR NUMBER(10,0) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1791');
end;
if VpaNumAtualizacao < 1792 then
begin
result := '1792';
ExecutaComandoSql(Aux,'ALTER TABLE TELEMARKETINGPROSPECT ADD CODVENDEDOR NUMBER(10,0) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1792');
end;
if VpaNumAtualizacao < 1793 then
begin
result := '1793';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD I_ULT_SEN NUMBER(10,0)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1793');
end;
if VpaNumAtualizacao < 1794 then
begin
result := '1794';
ExecutaComandoSql(Aux,'CREATE TABLE ORCAMENTOSOLICITACAOCOMPRA ( ' +
' CODFILIAL NUMBER(10) NULL, ' +
' SEQORCAMENTO NUMBER(10) NULL, ' +
' CODFILIALSOLICITACAO NUMBER(10) NULL, ' +
' SEQSOLICITACAO NUMBER(10) NULL, ' +
' PRIMARY KEY(CODFILIAL,SEQORCAMENTO,CODFILIALSOLICITACAO,SEQSOLICITACAO))');
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOSOLICITACAOCOMPRA add CONSTRAINT ORCAMENTOSOLCOMPRA_OC '+
' FOREIGN KEY (CODFILIAL,SEQORCAMENTO) '+
' REFERENCES ORCAMENTOCOMPRACORPO(CODFILIAL,SEQORCAMENTO) ');
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOSOLICITACAOCOMPRA add CONSTRAINT ORCAMENTOSOLCOMPRA_SC '+
' FOREIGN KEY (CODFILIALSOLICITACAO,SEQSOLICITACAO) '+
' REFERENCES SOLICITACAOCOMPRACORPO(CODFILIAL,SEQSOLICITACAO) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1794');
end;
if VpaNumAtualizacao < 1795 then
begin
result := '1795';
ExecutaComandoSql(Aux,'CREATE TABLE PRECOLARGURATEAR ( ' +
' NUMLARGURA NUMBER(10,2) NOT NULL PRIMARY KEY, ' +
' VALCONVENCIONAL NUMBER(15,4) NULL, ' +
' VALCROCHE NUMBER(15,4) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1795');
end;
if VpaNumAtualizacao < 1796 then
begin
result := '1796';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD I_TIP_PRO NUMBER(2) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1796');
end;
if VpaNumAtualizacao < 1797 then
begin
result := '1797';
ExecutaComandoSql(Aux,'CREATE TABLE MATERIAPRIMAORCAMENTOCADARCO ( ' +
' SEQPRODUTO NUMBER(10) NOT NULL, ' +
' SEQMATERIAPRIMA NUMBER(10) NOT NULL, ' +
' QTDFIO NUMBER(15,4) NULL, ' +
' PRIMARY KEY(SEQPRODUTO,SEQMATERIAPRIMA))');
ExecutaComandoSql(Aux,'ALTER TABLE MATERIAPRIMAORCAMENTOCADARCO add CONSTRAINT MATPRIORCAMENTOCADARCO_PRO '+
' FOREIGN KEY (SEQPRODUTO) '+
' REFERENCES CADPRODUTOS(I_SEQ_PRO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1797');
end;
if VpaNumAtualizacao < 1798 then
begin
result := '1798';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(56,5500,''CADNATUREZA'',''NATUREZA DE OPERACAO'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(56,1,''C_COD_NAT'',3)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1798');
end;
if VpaNumAtualizacao < 1799 then
begin
result := '1799';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(57,5600,''CADOPERACAOESTOQUE'',''OPERACOES ESTOQUE'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(57,1,''I_COD_OPE'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1799');
end;
if VpaNumAtualizacao < 1801 then
begin
result := '1801';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(59,5800,''MOVNATUREZA'',''ITENS DA NATUREZA DE OPERACAO'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(59,1,''C_COD_NAT'',3)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(59,2,''I_SEQ_MOV'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1801');
end;
if VpaNumAtualizacao < 1802 then
begin
result := '1802';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(60,5900,''CADSERIENOTAS'',''SERIES DA NOTA FISCAL'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(60,1,''C_SER_NOT'',3)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1802');
end;
if VpaNumAtualizacao < 1803 then
begin
result := '1803';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(61,6000,''CADNOTAFISCAIS'',''NOTAS FISCAIS'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(61,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(61,2,''I_SEQ_NOT'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1803');
end;
if VpaNumAtualizacao < 1804 then
begin
result := '1804';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(62,6100,''CADSERVICO'',''SERVICOS'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(62,1,''I_COD_EMP'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(62,2,''I_COD_SER'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1804');
end;
if VpaNumAtualizacao < 1805 then
begin
result := '1805';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(63,6200,''MOVSERVICONOTA'',''SERVICOS DA NOTA FISCAL'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(63,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(63,2,''I_SEQ_NOT'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(63,3,''I_SEQ_MOV'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1805');
end;
if VpaNumAtualizacao < 1806 then
begin
result := '1806';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(64,6300,''MOVNOTASFISCAIS'',''ITENS DA NOTA FISCAL'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(64,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(64,2,''I_SEQ_NOT'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(64,3,''I_SEQ_MOV'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1806');
end;
if VpaNumAtualizacao < 1807 then
begin
result := '1807';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(65,6400,''CADCONTASARECEBER'',''CONTAS A RECEBER'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(65,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(65,2,''I_LAN_REC'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1807');
end;
if VpaNumAtualizacao < 1808 then
begin
result := '1808';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(66,6500,''MOTIVOINADIMPLENCIA'',''MOTIVO INADIMPLECIA'',''DATULTIMAALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(66,1,''CODMOTIVO'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1808');
end;
if VpaNumAtualizacao < 1809 then
begin
result := '1809';
ExecutaComandoSql(Aux,'ALTER TABLE MOTIVOINADIMPLENCIA ADD DATULTIMAALTERACAO DATE NULL');
ExecutaComandoSql(Aux,'UPDATE MOTIVOINADIMPLENCIA SET DATULTIMAALTERACAO = SYSDATE');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1809');
end;
if VpaNumAtualizacao < 1810 then
begin
result := '1810';
ExecutaComandoSql(Aux,'DELETE FROM TABELAIMPORTACAOFILTRO WHERE CODTABELA = 47');
ExecutaComandoSql(Aux,'DELETE FROM TABELAIMPORTACAO WHERE CODTABELA = 47');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1810');
end;
if VpaNumAtualizacao < 1811 then
begin
result := '1811';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(67,6600,''MOVCONTASARECEBER'',''ITENS DO CONTAS A RECEBER'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(67,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(67,2,''I_LAN_REC'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(67,3,''I_NRO_PAR'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1811');
end;
if VpaNumAtualizacao < 1812 then
begin
result := '1812';
ExecutaComandoSql(Aux,'update MOVNOTASFISCAIS SET D_ULT_ALT = SYSDATE -1');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1812');
end;
if VpaNumAtualizacao < 1813 then
begin
result := '1813';
ExecutaComandoSql(Aux,'CREATE TABLE SEQUENCIALCONTASARECEBER( ' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' LANRECEBER NUMBER(10) NOT NULL, ' +
' PRIMARY KEY(CODFILIAL,LANRECEBER))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1813');
end;
if VpaNumAtualizacao < 1814 then
begin
result := '1814';
ExecutaComandoSql(Aux,'CREATE TABLE SEQUENCIALCOMISSAO ( ' +
' CODFILIAL NUMBER(10) NULL , ' +
' SEQCOMISSAO NUMBER(10) NULL, ' +
' PRIMARY KEY(CODFILIAL,SEQCOMISSAO))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1814');
end;
if VpaNumAtualizacao < 1815 then
begin
result := '1815';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD(I_ULT_REC NUMBER(10) NULL, ' +
' I_ULT_COM NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1815');
end;
if VpaNumAtualizacao < 1816 then
begin
result := '1816';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_CRM_PRP CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CADGRUPOS set C_CRM_PRP = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1816');
end;
if VpaNumAtualizacao < 1817 then
begin
result := '1817';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(68,6700,''MOVCOMISSOES'',''COMISSOES'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(68,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(68,2,''I_LAN_CON'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1817');
end;
if VpaNumAtualizacao < 1818 then
begin
result := '1818';
ExecutaComandoSql(Aux,'UPDATE CADORCAMENTOS '+
' SET D_ULT_ALT = SYSDATE ' +
' WHERE D_ULT_ALT IS NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1818');
end;
if VpaNumAtualizacao < 1819 then
begin
result := '1819';
ExecutaComandoSql(Aux,'UPDATE MOVORCAMENTOS '+
' SET D_ULT_ALT = SYSDATE ' +
' WHERE D_ULT_ALT IS NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1819');
end;
if VpaNumAtualizacao < 1820 then
begin
result := '1820';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(69,450,''CFG_MODULO'',''CONFIGURACOES DOS MODULOS'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1820');
end;
if VpaNumAtualizacao < 1821 then
begin
result := '1821';
ExecutaComandoSql(Aux,'UPDATE CADPRODUTOS '+
' SET D_ULT_ALT = SYSDATE ' +
' WHERE D_ULT_ALT IS NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1821');
end;
if VpaNumAtualizacao < 1822 then
begin
result := '1822';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_MODULO ADD D_ULT_ALT DATE');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1822');
end;
if VpaNumAtualizacao < 1823 then
begin
result := '1823';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD C_FLA_EXP CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADNOTAFISCAIS SET C_FLA_EXP = ''S''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1823');
end;
if VpaNumAtualizacao < 1824 then
begin
result := '1824';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD D_DAT_EXP DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1824');
end;
if VpaNumAtualizacao < 1825 then
begin
result := '1825';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASARECEBER ADD C_FLA_EXP CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADCONTASARECEBER SET C_FLA_EXP = ''S''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1825');
end;
if VpaNumAtualizacao < 1826 then
begin
result := '1826';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASARECEBER ADD D_DAT_EXP DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1826');
end;
if VpaNumAtualizacao < 1827 then
begin
result := '1827';
ExecutaComandoSql(Aux,'ALTER TABLE MOVCOMISSOES ADD(C_FLA_EXP CHAR(1) NULL, ' +
' D_DAT_EXP DATE NULL)');
ExecutaComandoSql(Aux,'UPDATE MOVCOMISSOES SET C_FLA_EXP = ''S''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1827');
end;
if VpaNumAtualizacao < 1828 then
begin
result := '1828';
ExecutaComandoSql(Aux,'ALTER TABLE IMPRESSAOCONSUMOFRACAO ADD DESLOCALIZACAO VARCHAR2(20)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1828');
end;
if VpaNumAtualizacao < 1829 then
begin
result := '1829';
ExecutaComandoSql(Aux,'UPDATE CADCONTASARECEBER '+
' SET D_ULT_ALT = SYSDATE ' +
' WHERE D_ULT_ALT IS NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1829');
end;
if VpaNumAtualizacao < 1830 then
begin
result := '1830';
ExecutaComandoSql(Aux,'ALTER TABLE CADSERIENOTAS ADD (C_TIP_ECF VARCHAR2(7)NULL, ' +
' C_MAR_ECF VARCHAR2(20) NULL, ' +
' C_MOD_ECF VARCHAR2(20) NULL, ' +
' C_VER_SFB VARCHAR2(10) NULL, ' +
' D_DAT_SFB date NULL, ' +
' I_NUM_ECF NUMBER(10) NULL, ' +
' I_EMP_FIL NUMBER(10) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1830');
end;
if VpaNumAtualizacao < 1831 then
begin
result := '1831';
ExecutaComandoSql(Aux,'ALTER TABLE CADSERIENOTAS ADD (I_NUM_USU NUMBER(10)NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1831');
end;
if VpaNumAtualizacao < 1832 then
begin
result := '1832';
ExecutaComandoSql(Aux,'CREATE TABLE REDUCAOZ( ' +
' NUMSERIEECF VARCHAR2(20) NOT NULL, ' +
' NUMREDUCAOZ NUMBER(10) NOT NULL, ' +
' NUMCONTADOROPERACAO NUMBER(10) NULL, ' +
' NUMCONTADORREINICIOOPERACAO NUMBER(10) NULL, ' +
' DATMOVIMENTO DATE NULL, ' +
' DATEMISSAO DATE NULL, ' +
' VALVENDABRUTADIARIA NUMBER(15,3) NULL, ' +
' INDDESCONTOISSQN CHAR(1) NULL, ' +
' PRIMARY KEY(NUMSERIEECF,NUMREDUCAOZ))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1832');
end;
if VpaNumAtualizacao < 1833 then
begin
result := '1833';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD(I_NUM_COO NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1833');
end;
if VpaNumAtualizacao < 1834 then
begin
result := '1834';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS ADD C_IND_CAN CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE MOVNOTASFISCAIS SET C_IND_CAN = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1834');
end;
if VpaNumAtualizacao < 1835 then
begin
result := '1835';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_ARE_TRU CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADPRODUTOS SET C_ARE_TRU = ''A''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1835');
end;
if VpaNumAtualizacao < 1836 then
begin
result := '1836';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ADD I_NUM_COO NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1836');
end;
if VpaNumAtualizacao < 1837 then
begin
result := '1837';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_SIT_TRI CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADPRODUTOS SET C_SIT_TRI = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1837');
end;
if VpaNumAtualizacao < 1838 then
begin
result := '1838';
ExecutaComandoSql(Aux,'CREATE TABLE REDUCAOZALIQUOTA ( ' +
' NUMSERIEECF VARCHAR2(20) NOT NULL, ' +
' NUMREDUCAOZ NUMBER(10) NOT NULL, ' +
' SEQINDICE NUMBER(10) NOT NULL, ' +
' DESTIPO CHAR(2) NULL, ' +
' PERALIQUOTA NUMBER(7,2) NULL, ' +
' VALVENDA NUMBER(15,3) NULL, ' +
' PRIMARY KEY(NUMSERIEECF,NUMREDUCAOZ,SEQINDICE))');
ExecutaComandoSql(Aux,'ALTER TABLE REDUCAOZALIQUOTA add CONSTRAINT REDUCAOZALIQUOTA_REDUCAOZ '+
' FOREIGN KEY (NUMSERIEECF,NUMREDUCAOZ) '+
' REFERENCES REDUCAOZ(NUMSERIEECF,NUMREDUCAOZ)');
ExecutaComandoSql(Aux,'CREATE INDEX REDUCAOZALIQUOTA_FK1 ON REDUCAOZALIQUOTA(NUMSERIEECF,NUMREDUCAOZ)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1838');
end;
if VpaNumAtualizacao < 1839 then
begin
result := '1839';
ExecutaComandoSql(Aux,'ALTER TABLE REDUCAOZ ADD (VALSTICMS NUMBER(15,3) ,' +
' VALISENTOICMS NUMBER(15,3), ' +
' VALNAOTRIBUTADOICMS NUMBER(15,3), ' +
' VALSTISSQN NUMBER(15,3), ' +
' VALISENTOISSQN NUMBER(15,3), ' +
' VALNAOTRIBUTADOISSQN NUMBER(15,3), ' +
' VALOPERACAONAOFISCAL NUMBER(15,3), ' +
' VALDESCONTOICMS NUMBER(15,3), ' +
' VALDESCONTOISSQN NUMBER(15,3), ' +
' VALACRESCIMOICMS NUMBER(15,3), ' +
' VALACRESCIMOISSQN NUMBER(15,3), ' +
' VALCANCELADOICMS NUMBER(15,3), ' +
' VALCANCELADOISSQN NUMBER(15,3))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1839');
end;
if VpaNumAtualizacao < 1840 then
begin
result := '1840';
ExecutaComandoSql(Aux,'Alter table MOVNOTASFISCAIS ADD C_TPA_ECF VARCHAR2(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1840');
end;
if VpaNumAtualizacao < 1841 then
begin
result := '1841';
ExecutaComandoSql(Aux,'Alter table CADNOTAFISCAIS ADD C_VEN_CON CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADNOTAFISCAIS SET C_VEN_CON = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1841');
end;
if VpaNumAtualizacao < 1842 then
begin
result := '1842';
ExecutaComandoSql(Aux,'CREATE TABLE COMPROVANTENAOFISCAL( '+
' NUMSERIEECF VARCHAR2(20) NOT NULL, ' +
' NUMCOO NUMBER(10) NOT NULL, ' +
' NUMGNF NUMBER(10) NOT NULL, ' +
' DESDENOMINACAO CHAR(2) NULL, ' +
' DESOPERACAO CHAR(1) NULL, '+
' VALCOMPROVANTE NUMBER(15,3) NULL, '+
' DATEMISSAO DATE NULL, '+
'PRIMARY KEY(NUMSERIEECF,NUMCOO))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1842');
end;
if VpaNumAtualizacao < 1843 then
begin
result := '1843';
ExecutaComandoSql(Aux,'ALTER TABLE CADSERIENOTAS ADD I_COD_NAC NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1843');
end;
if VpaNumAtualizacao < 1844 then
begin
result := '1844';
ExecutaComandoSql(Aux,'ALTER TABLE REDUCAOZ ADD VALGRANDETOTAL NUMBER(15,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1844');
end;
if VpaNumAtualizacao < 1845 then
begin
result := '1845';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD I_NUM_CRZ NUMBER(10)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1845');
end;
if VpaNumAtualizacao < 1846 then
begin
result := '1846';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO ADD C_IND_TEF CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FINANCEIRO SET C_IND_TEF = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1846');
end;
if VpaNumAtualizacao < 1847 then
begin
result := '1847';
ExecutaComandoSql(Aux,'CREATE TABLE ARQUIVOAUXILIAR( ' +
' NOMARQUIVO VARCHAR2(200) NULL)' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1847');
end;
if VpaNumAtualizacao < 1848 then
begin
result := '1848';
ExecutaComandoSql(Aux,'INSERT INTO ARQUIVOAUXILIAR(NOMARQUIVO) VALUES(''ACESSOREMOTO.EXE'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1848');
end;
if VpaNumAtualizacao < 1849 then
begin
result := '1849';
ExecutaComandoSql(Aux,'INSERT INTO ARQUIVOAUXILIAR(NOMARQUIVO) VALUES(''libeay32.dll'')');
ExecutaComandoSql(Aux,'INSERT INTO ARQUIVOAUXILIAR(NOMARQUIVO) VALUES(''sign_bema.dll'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1849');
end;
if VpaNumAtualizacao < 1850 then
begin
result := '1850';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ADD C_ASS_REG VARCHAR2(30) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1850');
end;
if VpaNumAtualizacao < 1851 then
begin
result := '1851';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_ASS_REG VARCHAR2(30)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1851');
end;
if VpaNumAtualizacao < 1852 then
begin
result := '1852';
ExecutaComandoSql(Aux,'ALTER TABLE MOVQDADEPRODUTO ADD C_ASS_REG VARCHAR2(30)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1852');
end;
if VpaNumAtualizacao < 1853 then
begin
result := '1853';
ExecutaComandoSql(Aux,'ALTER TABLE MOVTABELAPRECO ADD C_ASS_REG VARCHAR2(30)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1853');
end;
if VpaNumAtualizacao < 1854 then
begin
result := '1854';
ExecutaComandoSql(Aux,'ALTER TABLE CADSERIENOTAS ADD C_ASS_REG VARCHAR2(30)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1854');
end;
if VpaNumAtualizacao < 1855 then
begin
result := '1855';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_EXC_TEL CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EXC_TEL = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1855');
end;
if VpaNumAtualizacao < 1856 then
begin
result := '1856';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_IND_SPV CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_IND_SPV = C_IND_SCV');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1856');
end;
if VpaNumAtualizacao < 1857 then
begin
result := '1857';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD C_MOT_NFE CHAR(1) NULL ');
ExecutaComandoSql(Aux,'UPDATE CADFILIAIS SET C_MOT_NFE = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1857');
end;
if VpaNumAtualizacao < 1858 then
begin
result := '1858';
ExecutaComandoSql(Aux,'ALTER TABLE CADSERIENOTAS DROP(C_ASS_REG)');
ExecutaComandoSql(Aux,'ALTER TABLE CADSERIENOTAS ADD(C_NOM_SFH VARCHAR2(40), ' +
' C_CNP_SFH VARCHAR2(20) NULL, ' +
' C_END_SFH VARCHAR2(50) NULL, '+
' C_FON_SFH VARCHAR2(15) NULL, ' +
' C_CON_SFH VARCHAR2(15) NULL, ' +
' C_CNP_EMI VARCHAR2(15) NULL, ' +
' C_NOM_COM VARCHAR2(30) NULL, ' +
' C_ASS_REG VARCHAR2(30) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1858');
end;
if VpaNumAtualizacao < 1859 then
begin
result := '1859';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD C_SUB_SER VARCHAR2(10)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1859');
end;
if VpaNumAtualizacao < 1860 then
begin
result := '1860';
ExecutaComandoSql(Aux,'CREATE TABLE RELATORIOGERENCIALECF( ' +
' NUMSERIEECF VARCHAR2(20) NOT NULL, ' +
' NUMCOO NUMBER(10) NOT NULL, ' +
' NUMGRG NUMBER(10) NULL, ' +
' DATEMISSAO DATE NULL, '+
' PRIMARY KEY(NUMSERIEECF,NUMCOO))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1860');
end;
if VpaNumAtualizacao < 1861 then
begin
result := '1861';
ExecutaComandoSql(Aux,'ALTER TABLE REDUCAOZ ADD DESASSINATURAREGISTRO VARCHAR2(30)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1861');
end;
if VpaNumAtualizacao < 1862 then
begin
result := '1862';
ExecutaComandoSql(Aux,'ALTER TABLE REDUCAOZALIQUOTA ADD DESASSINATURAREGISTRO VARCHAR2(30)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1862');
end;
if VpaNumAtualizacao < 1863 then
begin
result := '1863';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD C_ASS_REG VARCHAR2(30) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1863');
end;
if VpaNumAtualizacao < 1864 then
begin
result := '1864';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS ADD C_ASS_REG VARCHAR2(30) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1864');
end;
if VpaNumAtualizacao < 1865 then
begin
result := '1865';
ExecutaComandoSql(Aux,'update CADUSUARIOS SET C_MOD_PDV = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1865');
end;
if VpaNumAtualizacao < 1866 then
begin
result := '1866';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_OCU_VEN CHAR(1) NULL ');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_OCU_VEN = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1866');
end;
if VpaNumAtualizacao < 1867 then
begin
result := '1867';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ADD C_ORI_PED CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1867');
end;
if VpaNumAtualizacao < 1868 then
begin
result := '1868';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD C_IMP_FNF CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FISCAL SET C_IMP_FNF = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1868');
end;
if VpaNumAtualizacao < 1869 then
begin
result := '1869';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD D_ULT_BAC DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1869');
end;
if VpaNumAtualizacao < 1870 then
begin
result := '1870';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ADD I_CLI_FAC NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1870');
end;
if VpaNumAtualizacao < 1871 then
begin
result := '1871';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_COT_CLF CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_CLF = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1871');
end;
if VpaNumAtualizacao < 1872 then
begin
result := '1872';
ExecutaComandoSql(Aux,'CREATE TABLE DOCUMENTOVINCULADOECF( ' +
' NUMSERIEECF VARCHAR2(20) NOT NULL, ' +
' NUMCOO NUMBER(10) NOT NULL, ' +
' NUMCDC NUMBER(10) NULL, ' +
' DATEMISSAO DATE NULL, '+
' DESASSINATURAREGISTRO VARCHAR2(30) NULL, '+
' PRIMARY KEY(NUMSERIEECF,NUMCOO))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1872');
end;
if VpaNumAtualizacao < 1873 then
begin
result := '1873';
ExecutaComandoSql(Aux,'ALTER TABLE COMPROVANTENAOFISCAL ADD DESASSINATURAREGISTRO VARCHAR2(30)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1873');
end;
if VpaNumAtualizacao < 1874 then
begin
result := '1874';
ExecutaComandoSql(Aux,'ALTER TABLE RELATORIOGERENCIALECF ADD DESASSINATURAREGISTRO VARCHAR2(30)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1874');
end;
end;
function TAtualiza.AtualizaTabela3(VpaNumAtualizacao: Integer): String;
begin
result := '';
if VpaNumAtualizacao < 1875 then
begin
result := '1875';
ExecutaComandoSql(Aux,'ALTER TABLE DOCUMENTOVINCULADOECF DROP(DESASSINATURAREGISTRO)');
ExecutaComandoSql(Aux,'ALTER TABLE DOCUMENTOVINCULADOECF ADD(NUMGNF NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1875');
end;
if VpaNumAtualizacao < 1876 then
begin
result := '1876';
ExecutaComandoSql(Aux,'ALTER TABLE DOCUMENTOVINCULADOECF ADD(DESASSINATURAREGISTRO VARCHAR2(30) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1876');
end;
if VpaNumAtualizacao < 1877 then
begin
result := '1877';
ExecutaComandoSql(Aux,'ALTER TABLE RELATORIOGERENCIALECF DROP(DESASSINATURAREGISTRO)');
ExecutaComandoSql(Aux,'ALTER TABLE RELATORIOGERENCIALECF ADD(NUMGNF NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1877');
end;
if VpaNumAtualizacao < 1878 then
begin
result := '1878';
ExecutaComandoSql(Aux,'ALTER TABLE RELATORIOGERENCIALECF ADD(DESASSINATURAREGISTRO VARCHAR2(30) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1878');
end;
if VpaNumAtualizacao < 1879 then
begin
result := '1879';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD N_PER_FRE NUMBER(5,2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1879');
end;
if VpaNumAtualizacao < 1880 then
begin
result := '1880';
ExecutaComandoSql(Aux,'Alter table CFG_GERAL ADD C_COT_OIO CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_OIO = ''D''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1880');
end;
if VpaNumAtualizacao < 1881 then
begin
result := '1881';
ExecutaComandoSql(Aux,'INSERT INTO ARQUIVOAUXILIAR(NOMARQUIVO) VALUES(''DelZip190.dll'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1881');
end;
if VpaNumAtualizacao < 1882 then
begin
result := '1882';
ExecutaComandoSql(Aux,'alter table CADCLIENTES ADD(C_IND_CBA CHAR(1) NULL, '+
' C_IND_BUM CHAR(1) NULL, ' +
' I_COD_EMB NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1882');
end;
if VpaNumAtualizacao < 1883 then
begin
result := '1883';
ExecutaComandoSql(Aux,'alter table CADCLIENTES ADD(I_COD_RED NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1883');
end;
if VpaNumAtualizacao < 1884 then
begin
result := '1884';
ExecutaComandoSql(Aux,'UPDATE CADCLIENTES ' +
' SET C_IND_CBA = ''S'','+
' C_IND_BUM = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1884');
end;
if VpaNumAtualizacao < 1885 then
begin
result := '1885';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD I_TIP_MAP NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1885');
end;
if VpaNumAtualizacao < 1886 then
begin
result := '1886';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD C_IMP_CPN CHAR(1)NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FISCAL SET C_IMP_CPN = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1886');
end;
if VpaNumAtualizacao < 1887 then
begin
result := '1887';
ExecutaComandoSql(Aux,'UPDATE CADCLIENTES ' +
' SET C_EMA_INV = ''S''' +
' Where C_EMA_INV = ''N''' +
' AND I_QTD_EMI >= 1');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1887');
end;
if VpaNumAtualizacao < 1888 then
begin
result := '1888';
ExecutaComandoSql(Aux,'UPDATE PROSPECT ' +
' SET INDEMAILINVALIDO = ''S''' +
' Where INDEMAILINVALIDO = ''N''' +
' AND QTDVEZESEMAILINVALIDO >= 1');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1888');
end;
if VpaNumAtualizacao < 1889 then
begin
result := '1889';
ExecutaComandoSql(Aux,'UPDATE CONTATOCLIENTE ' +
' SET INDEMAILINVALIDO = ''S''' +
' Where INDEMAILINVALIDO = ''N''' +
' AND QTDVEZESEMAILINVALIDO >= 1');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1889');
end;
if VpaNumAtualizacao < 1890 then
begin
result := '1890';
ExecutaComandoSql(Aux,'UPDATE CONTATOPROSPECT ' +
' SET INDEMAILINVALIDO = ''S''' +
' Where INDEMAILINVALIDO = ''N''' +
' AND QTDVEZESEMAILINVALIDO >= 1');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1890');
end;
if VpaNumAtualizacao < 1891 then
begin
result := '1891';
ExecutaComandoSql(Aux,'UPDATE CONTATOPROSPECT '+
' SET DESEMAIL = TRIM(DESEMAIL) ' +
' Where DESEMAIL LIKE ''% %''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1891');
end;
if VpaNumAtualizacao < 1891 then
begin
result := '1891';
ExecutaComandoSql(Aux,'UPDATE PROSPECT '+
' SET DESEMAILCONTATO = TRIM(DESEMAILCONTATO) ' +
' Where DESEMAILCONTATO LIKE ''% %''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1891');
end;
if VpaNumAtualizacao < 1892 then
begin
result := '1892';
ExecutaComandoSql(Aux,'UPDATE CADCLIENTES '+
' SET C_END_ELE = TRIM(C_END_ELE) ' +
' Where C_END_ELE LIKE ''% %''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1892');
end;
if VpaNumAtualizacao < 1893 then
begin
result := '1893';
ExecutaComandoSql(Aux,'UPDATE CONTATOCLIENTE '+
' SET DESEMAIL = TRIM(DESEMAIL) ' +
' Where DESEMAIL LIKE ''% %''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1893');
end;
if VpaNumAtualizacao < 1894 then
begin
result := '1894';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD I_ORC_CHA NUMBER(10)NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1894');
end;
if VpaNumAtualizacao < 1895 then
begin
result := '1895';
ExecutaComandoSql(Aux,'ALTER TABLE TAREFATELEMARKETING ADD(INDPROSPECT CHAR(1) NULL, ' +
' INDCLIENTE CHAR(1) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1895');
end;
if VpaNumAtualizacao < 1896 then
begin
result := '1896';
ExecutaComandoSql(Aux,'ALTER TABLE CLIENTEPERDIDOVENDEDOR ADD(INDCLIENTE CHAR(1) NULL, ' +
' INDPROSPECT CHAR(1) NULL, ' +
' QTDDIASSEMTELEMARKETING NUMBER(10) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1896');
end;
if VpaNumAtualizacao < 1897 then
begin
result := '1897';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO ADD(C_IMP_CHE CHAR(1) NULL)');
ExecutaComandoSql(Aux,'Update CFG_FINANCEIRO SET C_IMP_CHE = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1897');
end;
if VpaNumAtualizacao < 1898 then
begin
result := '1898';
ExecutaComandoSql(Aux,'ALTER TABLE CHEQUE ADD(NOMNOMINAL VARCHAR2(50) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1898');
end;
if VpaNumAtualizacao < 1899 then
begin
result := '1899';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTAS ADD I_LAY_CHE NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1899');
end;
if VpaNumAtualizacao < 1900 then
begin
result := '1900';
ExecutaComandoSql(Aux,'ALTER TABLE ESTAGIOPROPOSTA MODIFY DESMOTIVO VARCHAR2(500)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1900');
end;
if VpaNumAtualizacao < 1901 then
begin
result := '1901';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD (C_NAT_VOD VARCHAR2(15) NULL, ' +
' C_NAT_VOF VARCHAR2(15) NULL, ' +
' C_NAT_ROD VARCHAR2(15) NULL, ' +
' C_NAT_ROF VARCHAR2(15) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1901');
end;
if VpaNumAtualizacao < 1902 then
begin
result := '1902';
ExecutaComandoSql(Aux,'ALTER TABLE FACCIONISTA ADD TIPDISTRIBUICAO CHAR(1) NULL ');
ExecutaComandoSql(Aux,'Update FACCIONISTA SET TIPDISTRIBUICAO = ''B''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1902');
end;
if VpaNumAtualizacao < 1903 then
begin
result := '1903';
ExecutaComandoSql(Aux,'ALTER TABLE MOVCONTASAPAGAR ADD C_DES_PRR CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE MOVCONTASAPAGAR SET C_DES_PRR = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1903');
end;
if VpaNumAtualizacao < 1904 then
begin
result := '1904';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES MODIFY C_CID_CLI VARCHAR2(40)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1904');
end;
if VpaNumAtualizacao < 1905 then
begin
result := '1905';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS ADD I_COD_RED NUMBER(10)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1905');
end;
if VpaNumAtualizacao < 1906 then
begin
result := '1906';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD I_COD_RED NUMBER(10)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1906');
end;
if VpaNumAtualizacao < 1907 then
begin
result := '1907';
ExecutaComandoSql(Aux,'ALTER TABLE MOVCOMISSOES ADD C_IND_DEV CHAR(1) NULL ');
ExecutaComandoSql(Aux,'UPDATE MOVCOMISSOES SET C_IND_DEV = ''N''');
ExecutaComandoSql(Aux,'UPDATE MOVCOMISSOES SET C_IND_DEV = ''S'' WHERE N_VLR_COM < 0');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1907');
end;
if VpaNumAtualizacao < 1908 then
begin
result := '1908';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_COT_OOP CHAR(1)');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_OOP = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1908');
end;
if VpaNumAtualizacao < 1909 then
begin
result := '1909';
ExecutaComandoSql(Aux,'ALTER TABLE IMPRESSAOCONSUMOFRACAO ADD SEQPRODUTO NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1909');
end;
if VpaNumAtualizacao < 1910 then
begin
result := '1910';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD C_CUS_PPA CHAR(1) ');
ExecutaComandoSql(Aux,'UPDATE CFG_PRODUTO SET C_CUS_PPA = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1910');
end;
if VpaNumAtualizacao < 1911 then
begin
result := '1911';
ExecutaComandoSql(Aux,'CREATE TABLE ROMANEIOORCAMENTO ( ' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' SEQROMANEIO NUMBER(10) NOT NULL, ' +
' DATINICIO DATE, ' +
' DATFIM DATE, ' +
' NUMNOTA NUMBER(10), ' +
' CODFILIALNOTA NUMBER(10), ' +
' SEQNOTA NUMBER(10), ' +
' CODCLIENTE NUMBER(10), ' +
' VALTOTAL NUMBER(15,3), ' +
' CODUSUARIO NUMBER(10), '+
' PRIMARY KEY(CODFILIAL, SEQROMANEIO),' +
' FOREIGN KEY (CODCLIENTE) REFERENCES CADCLIENTES (I_COD_CLI), ' +
' FOREIGN KEY (CODFILIALNOTA,SEQNOTA) REFERENCES CADNOTAFISCAIS(I_EMP_FIL,I_SEQ_NOT))');
ExecutaComandoSql(Aux,'CREATE INDEX ROMANEIOORCAMENTO_CLI ON ROMANEIOORCAMENTO(CODCLIENTE)');
ExecutaComandoSql(Aux,'CREATE INDEX ROMANEIOORCAMENTO_NOTA ON ROMANEIOORCAMENTO(CODFILIALNOTA,SEQNOTA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1911');
end;
if VpaNumAtualizacao < 1912 then
begin
result := '1912';
ExecutaComandoSql(Aux,'CREATE TABLE ROMANEIOORCAMENTOITEM( ' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' SEQROMANEIO NUMBER(10)NOT NULL, ' +
' SEQITEM NUMBER(10) NOT NULL, ' +
' CODFILIALORCAMENTO NUMBER(10) NULL, ' +
' LANORCAMENTO NUMBER(10) NULL, ' +
' SEQITEMORCAMENTO NUMBER(10) NULL, ' +
' SEQPRODUTO NUMBER(10) NULL, ' +
' CODCOR NUMBER(10) NULL, ' +
' CODTAMANHO NUMBER(10) NULL, '+
' QTDPRODUTO NUMBER(17,3), ' +
' VALUNITARIO NUMBER(17,4), ' +
' VALTOTAL NUMBER(17,2), ' +
' CODEMBALAGEM NUMBER(10), '+
' PRIMARY KEY(CODFILIAL, SEQROMANEIO, SEQITEM), ' +
' FOREIGN KEY (CODFILIAL,SEQROMANEIO) REFERENCES ROMANEIOORCAMENTO(CODFILIAL,SEQROMANEIO), ' +
' FOREIGN KEY (CODFILIALORCAMENTO,LANORCAMENTO) REFERENCES CADORCAMENTOS (I_EMP_FIL, I_LAN_ORC), ' +
' FOREIGN KEY (SEQPRODUTO) REFERENCES CADPRODUTOS(I_SEQ_PRO), ' +
' FOREIGN KEY (CODTAMANHO) REFERENCES TAMANHO (CODTAMANHO), ' +
' FOREIGN KEY (CODCOR) REFERENCES COR(COD_COR), ' +
' FOREIGN KEY (CODEMBALAGEM) REFERENCES EMBALAGEM(COD_EMBALAGEM)) ');
ExecutaComandoSql(Aux,'CREATE INDEX ROMANEIOORCAMENTOITEM_ROM ON ROMANEIOORCAMENTOITEM(CODFILIAL,SEQROMANEIO)');
ExecutaComandoSql(Aux,'CREATE INDEX ROMANEIOORCAMENTOITEM_ORC ON ROMANEIOORCAMENTOITEM(CODFILIALORCAMENTO,LANORCAMENTO)');
ExecutaComandoSql(Aux,'CREATE INDEX ROMANEIOORCAMENTOITEM_PRO ON ROMANEIOORCAMENTOITEM(SEQPRODUTO)');
ExecutaComandoSql(Aux,'CREATE INDEX ROMANEIOORCAMENTOITEM_COR ON ROMANEIOORCAMENTOITEM(CODCOR)');
ExecutaComandoSql(Aux,'CREATE INDEX ROMANEIOORCAMENTOITEM_TAM ON ROMANEIOORCAMENTOITEM(CODTAMANHO)');
ExecutaComandoSql(Aux,'CREATE INDEX ROMANEIOORCAMENTOITEM_EMB ON ROMANEIOORCAMENTOITEM(CODEMBALAGEM)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1912');
end;
if VpaNumAtualizacao < 1913 then
begin
result := '1913';
ExecutaComandoSql(Aux,'CREATE INDEX ROMANEIOORCAMENTO_DTFIM ON ROMANEIOORCAMENTO(DATFIM)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1913');
end;
if VpaNumAtualizacao < 1914 then
begin
result := '1914';
ExecutaComandoSql(Aux,'alter table PROPOSTA DROP(LANORCAMENTO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1914');
end;
if VpaNumAtualizacao < 1915 then
begin
result := '1915';
ExecutaComandoSql(Aux,'CREATE TABLE PROPOSTACOTACAO ( ' +
' CODFILIALPROPOSTA NUMBER(10) NOT NULL, ' +
' SEQPROPOSTA NUMBER(10) NOT NULL, ' +
' CODFILIALORCAMENTO NUMBER(10) NOT NULL, ' +
' LANORCAMENTO NUMBER(10) NOT NULL, ' +
' PRIMARY KEY(CODFILIALPROPOSTA,SEQPROPOSTA,CODFILIALORCAMENTO,LANORCAMENTO), ' +
' FOREIGN KEY (CODFILIALPROPOSTA,SEQPROPOSTA) REFERENCES PROPOSTA(CODFILIAL,SEQPROPOSTA), ' +
' FOREIGN KEY (CODFILIALORCAMENTO,LANORCAMENTO) REFERENCES CADORCAMENTOS(I_EMP_FIL,I_LAN_ORC))');
ExecutaComandoSql(Aux,'CREATE INDEX PROPOSTACOTACAO_PRO ON PROPOSTACOTACAO(CODFILIALPROPOSTA,SEQPROPOSTA)');
ExecutaComandoSql(Aux,'CREATE INDEX PROPOSTACOTACAO_COT ON PROPOSTACOTACAO(CODFILIALORCAMENTO,LANORCAMENTO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1915');
end;
if VpaNumAtualizacao < 1916 then
begin
result := '1916';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(70,6350,''MOVSERVICOORCAMENTO'',''SERVICO ORCAMENTO'',''D_ULT_ALT'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(70,1,''I_EMP_FIL'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(70,2,''I_LAN_ORC'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(70,3,''I_SEQ_MOV'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1916');
end;
if VpaNumAtualizacao < 1917 then
begin
result := '1917';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES add C_FOR_EAP CHAR(1) NULL ');
ExecutaComandoSql(Aux,'UPDATE CADCLIENTES SET C_FOR_EAP = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1917');
end;
if VpaNumAtualizacao < 1918 then
begin
result := '1918';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD C_IND_REV CHAR(1)NULL');
ExecutaComandoSql(Aux,'UPDATE CADFILIAIS SET C_IND_REV = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1918');
end;
if VpaNumAtualizacao < 1919 then
begin
result := '1919';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD C_IND_TRA CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CADCLIENTES SET C_IND_TRA = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1919');
end;
if VpaNumAtualizacao < 1920 then
begin
result := '1920';
ExecutaComandoSql(Aux,'alter TABLE CADCLIENTES ADD I_TRA_ANT NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1920');
end;
if VpaNumAtualizacao < 1921 then
begin
result := '1921';
CadastraTransportadorasComoClientes;
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1921');
end;
if VpaNumAtualizacao < 1922 then
begin
result := '1922';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD(I_ORC_COL NUMBER(10) NULL, ' +
' I_ORC_ENT NUMBER(10) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1922');
end;
if VpaNumAtualizacao < 1923 then
begin
result := '1923';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_ING_EEM CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_ING_EEM = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1923');
end;
if VpaNumAtualizacao < 1924 then
begin
result := '1924';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_ORP_DFF CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_ORP_DFF = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1924');
end;
if VpaNumAtualizacao < 1925 then
begin
result := '1925';
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAO(CODTABELA, SEQIMPORTACAO,NOMTABELA,DESTABELA,DESCAMPODATA) ' +
' VALUES(71,6350,''CONDICAOPAGAMENTOGRUPOUSUARIO'',''CONDICAO PAGAMENTO GRUPO USUARIO'',''DATULTIMAALTERACAO'')');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(71,1,''CODGRUPOUSUARIO'',1)');
ExecutaComandoSql(Aux,'INSERT INTO TABELAIMPORTACAOFILTRO(CODTABELA, SEQFILTRO,NOMCAMPO,TIPCAMPO) ' +
' VALUES(71,2,''CODCONDICAOPAGAMENTO'',1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1925');
end;
if VpaNumAtualizacao < 1926 then
begin
result := '1926';
ExecutaComandoSql(Aux,'ALTER TABLE CONDICAOPAGAMENTOGRUPOUSUARIO ADD DATULTIMAALTERACAO DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1926');
end;
if VpaNumAtualizacao < 1927 then
begin
result := '1927';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO ADD C_BOL_NOT CHAR(1)NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FINANCEIRO SET C_BOL_NOT = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1927');
end;
if VpaNumAtualizacao < 1928 then
begin
result := '1928';
ExecutaComandoSql(Aux,'ALTER TABLE CADUSUARIOS ADD C_ASS_EMA VARCHAR2(500) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1928');
end;
if VpaNumAtualizacao < 1929 then
begin
result := '1929';
ExecutaComandoSql(Aux,'ALTER TABLE ETIQUETAPRODUTO ADD(NOMCORMARISOL VARCHAR2(50) NULL, ' +
' NOMCORMARISOLCOMPLETA VARCHAR2(50) NULL, ' +
' INDALGODAO CHAR(1) NULL, ' +
' INDPOLIESTER CHAR(1) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1929');
end;
if VpaNumAtualizacao < 1930 then
begin
result := '1930';
ExecutaComandoSql(Aux,'ALTER TABLE ETIQUETAPRODUTO ADD(DESQTDPRODUTO VARCHAR2(50) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1930');
end;
if VpaNumAtualizacao < 1931 then
begin
result := '1931';
ExecutaComandoSql(Aux,'ALTER TABLE ROMANEIOORCAMENTOITEM DROP(SEQITEMORCAMENTO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1931');
end;
if VpaNumAtualizacao < 1932 then
begin
result := '1932';
ExecutaComandoSql(Aux,'ALTER TABLE ROMANEIOORCAMENTO ADD( CODFILIALORCAMENTOBAIXA NUMBER(10) NULL, ' +
' LANORCAMENTOBAIXA NUMBER(10) NULL, ' +
' SEQORCAMENTOPARCIALBAIXA NUMBER(10) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1932');
end;
if VpaNumAtualizacao < 1933 then
begin
result := '1933';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD I_ETI_ROO NUMBER(10) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1933');
end;
if VpaNumAtualizacao < 1934 then
begin
result := '1934';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_IMP_ENR CHAR(1) NULL)');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_IMP_ENR = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1934');
end;
if VpaNumAtualizacao < 1935 then
begin
result := '1935';
ExecutaComandoSql(Aux,'UPDATE CADCLIENTES SET C_TIP_FAT = ''N'''+
' Where C_TIP_FAT IS NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1935');
end;
if VpaNumAtualizacao < 1936 then
begin
result := '1936';
ExecutaComandoSql(Aux,'CREATE TABLE CLIENTELOG ( ' +
' CODCLIENTE NUMBER(10) NOT NULL, ' +
' SEQLOG NUMBER(10) NOT NULL,' +
' CODUSUARIO NUMBER(10) NOT NULL, ' +
' DATLOG DATE NOT NULL, ' +
' DESLOCALARQUIVO VARCHAR2(200) NULL, ' +
' PRIMARY KEY(CODCLIENTE,SEQLOG))');
ExecutaComandoSql(Aux,'CREATE INDEX CLIENTE_FK1 ON CLIENTELOG(CODCLIENTE)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1936');
end;
if VpaNumAtualizacao < 1937 then
begin
result := '1937';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD(I_COD_USU NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1937');
end;
if VpaNumAtualizacao < 1938 then
begin
result := '1938';
ExecutaComandoSql(Aux,'ALTER TABLE ROMANEIOORCAMENTO ADD(QTDVOLUME NUMBER(10) NULL, ' +
' PESBRUTO NUMBER(17,2) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1938');
end;
if VpaNumAtualizacao < 1939 then
begin
result := '1939';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD(C_PRO_EMP VARCHAR2(50) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1939');
end;
if VpaNumAtualizacao < 1940 then
begin
result := '1940';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR ADD(N_PER_SUS NUMBER(15,3) NULL, ' +
' N_VLR_SUS NUMBER(15,3) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1940');
end;
if VpaNumAtualizacao < 1941 then
begin
result := '1941';
ExecutaComandoSql(Aux,'ALTER TABLE CHAMADOPRODUTO MODIFY DESSERVICOEXECUTADO VARCHAR2(2000)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1941');
end;
if VpaNumAtualizacao < 1942 then
begin
result := '1942';
ExecutaComandoSql(Aux,'ALTER TABLE CHAMADOPRODUTO MODIFY DESPROBLEMA VARCHAR2(2000)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1942');
end;
if VpaNumAtualizacao < 1943 then
begin
result := '1943';
ExecutaComandoSql(Aux,'ALTER TABLE OPITEMCADARCO MODIFY DESTAB VARCHAR2(500) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1943');
end;
if VpaNumAtualizacao < 1944 then
begin
result := '1944';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_COT_TIF NUMBER(5) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET I_COT_TIF = 1');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1944');
end;
if VpaNumAtualizacao < 1945 then
begin
result := '1945';
ExecutaComandoSql(Aux,'CREATE TABLE MODULO( ' +
' SEQMODULO NUMBER(10) NULL, ' +
' NOMMODULO VARCHAR2(50) NULL, ' +
' NOMCAMPOCFG VARCHAR2(50) NULL, ' +
' NOMARQUIVOFTP VARCHAR2(150) NULL, ' +
' DATULTIMAATUALIZACAO DATE, ' +
' PRIMARY KEY(SEQMODULO))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1945');
end;
if VpaNumAtualizacao < 1946 then
begin
result := '1946';
ExecutaComandoSql(Aux,'INSERT INTO MODULO(SEQMODULO,NOMMODULO,NOMCAMPOCFG,NOMARQUIVOFTP) ' +
' VALUES(1,''PONTO DE VENDAS'',''C_MOD_PON'',''pontoloja.zip'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1946');
end;
if VpaNumAtualizacao < 1947 then
begin
result := '1947';
ExecutaComandoSql(Aux,'INSERT INTO MODULO(SEQMODULO,NOMMODULO,NOMCAMPOCFG,NOMARQUIVOFTP) ' +
' VALUES(2,''FATURAMENTO'',''C_MOD_FAT'',''faturamento.zip'')');
ExecutaComandoSql(Aux,'INSERT INTO MODULO(SEQMODULO,NOMMODULO,NOMCAMPOCFG,NOMARQUIVOFTP) ' +
' VALUES(3,''FINANCEIRO'',''C_MOD_FIN'',''financeiro.zip'')');
ExecutaComandoSql(Aux,'INSERT INTO MODULO(SEQMODULO,NOMMODULO,NOMCAMPOCFG,NOMARQUIVOFTP) ' +
' VALUES(4,''ESTOQUE'',''C_MOD_EST'',''EstoqueCusto.zip'')');
ExecutaComandoSql(Aux,'INSERT INTO MODULO(SEQMODULO,NOMMODULO,NOMCAMPOCFG,NOMARQUIVOFTP) ' +
' VALUES(5,''CHAMADO TECNICO'',''C_MOD_CHA'',''ChamadoTecnico.zip'')');
ExecutaComandoSql(Aux,'INSERT INTO MODULO(SEQMODULO,NOMMODULO,NOMCAMPOCFG,NOMARQUIVOFTP) ' +
' VALUES(6,''CONFIGURACAO SISTEMA'',''C_CON_SIS'',''configuracoessistema.zip'')');
ExecutaComandoSql(Aux,'INSERT INTO MODULO(SEQMODULO,NOMMODULO,NOMCAMPOCFG,NOMARQUIVOFTP) ' +
' VALUES(7,''CRM'',''C_MOD_CRM'',''CRM.zip'')');
ExecutaComandoSql(Aux,'INSERT INTO MODULO(SEQMODULO,NOMMODULO,NOMCAMPOCFG,NOMARQUIVOFTP) ' +
' VALUES(8,''PDV ECF'',''C_MOD_PDV'',''efiPDV.zip'')');
ExecutaComandoSql(Aux,'INSERT INTO MODULO(SEQMODULO,NOMMODULO,NOMCAMPOCFG,NOMARQUIVOFTP) ' +
' VALUES(9,''CAIXA'',''C_MOD_CAI'',''Caixa.zip'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1947');
end;
if VpaNumAtualizacao < 1948 then
begin
result := '1948';
ExecutaComandoSql(Aux,'ALTER TABLE MODULO ADD INDATUALIZAR CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1948');
end;
if VpaNumAtualizacao < 1949 then
begin
result := '1949';
ExecutaComandoSql(Aux,'alter table CFG_GERAL ADD(C_FTP_EFI VARCHAR2(150) NULL, ' +
' C_USU_FTE VARCHAR2(50) NULL, ' +
' C_SEN_FTE VARCHAR2(50) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1949');
end;
if VpaNumAtualizacao < 1950 then
begin
result := '1950';
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL ' +
' SET C_FTP_EFI = ''public_html/downloads/SisCorp/'',' +
' C_USU_FTE = ''eficaciaconsultoria1'',' +
' C_SEN_FTE = ''rafael12''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1950');
end;
if VpaNumAtualizacao < 1951 then
begin
result := '1951';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_CRM_DPR CHAR(1)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set C_CRM_DPR = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1951');
end;
if VpaNumAtualizacao < 1952 then
begin
result := '1952';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_CHA_ECH CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_CHA_ECH = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1952');
end;
if VpaNumAtualizacao < 1953 then
begin
result := '1953';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_CRM_APF CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_CRM_APF = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1953');
end;
if VpaNumAtualizacao < 1954 then
begin
result := '1954';
ExecutaComandoSql(Aux,'ALTER TABLE TELEMARKETING MODIFY DESOBSERVACAO VARCHAR2(4000)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1954');
end;
if VpaNumAtualizacao < 1955 then
begin
result := '1955';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD(I_USU_CAN NUMBER(10) NULL, ' +
' D_DAT_CAN DATE NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1955');
end;
if VpaNumAtualizacao < 1956 then
begin
result := '1956';
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL ' +
'SET C_SEN_FTE = ''rafael12''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1956');
end;
if VpaNumAtualizacao < 1957 then
begin
result := '1957';
ExecutaComandoSql(Aux,'INSERT INTO ARQUIVOAUXILIAR(NOMARQUIVO) VALUES(''ATUALIZAMODULOS.EXE'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1957');
end;
if VpaNumAtualizacao < 1958 then
begin
result := '1958';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD N_TOT_PSD NUMBER(15,4)NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1958');
end;
if VpaNumAtualizacao < 1959 then
begin
result := '1959';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS add N_VLR_DES NUMBER(15,2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1959');
end;
if VpaNumAtualizacao < 1960 then
begin
result := '1960';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS ADD(N_VLR_ICM NUMBER(15,2) NULL, ' +
' N_BAS_ICM NUMBER(15,2))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1960');
end;
if VpaNumAtualizacao < 1961 then
begin
result := '1961';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS ADD N_VLR_FRE NUMBER(15,2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1961');
end;
if VpaNumAtualizacao < 1962 then
begin
result := '1962';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_EMA_RAM VARCHAR2(75) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1962');
end;
if VpaNumAtualizacao < 1963 then
begin
result := '1963';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_BAC_FTP CHAR(1) NULL, ' +
' D_ENV_BAC DATE NULL, ' +
' I_PER_BAC INTEGER NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1963');
end;
if VpaNumAtualizacao < 1964 then
begin
result := '1964';
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_BAC_FTP = ''T''' +
', I_PER_BAC = 1 ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1964');
end;
if VpaNumAtualizacao < 1965 then
begin
result := '1965';
ExecutaComandoSql(Aux,'ALTER TABLE MOVCONTASARECEBER ADD C_MOS_FLU CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1965');
end;
if VpaNumAtualizacao < 1966 then
begin
result := '1966';
ExecutaComandoSql(Aux,'ALTER TABLE ROMANEIOORCAMENTO ADD INDBLOQUEADO CHAR(1) NULL ');
ExecutaComandoSql(Aux,'UPDATE ROMANEIOORCAMENTO SET INDBLOQUEADO = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1966');
end;
if VpaNumAtualizacao < 1967 then
begin
result := '1967';
ExecutaComandoSql(Aux,'ALTER TABLE ROMANEIOORCAMENTOITEM ADD(DESUM CHAR(2) NULL, ' +
' DESREFERENCIACLIENTE VARCHAR2(50)NULL, ' +
' DESORDEMCOMPRA VARCHAR2(50)NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1967');
end;
if VpaNumAtualizacao < 1968 then
begin
result := '1968';
ExecutaComandoSql(Aux,'ALTER TABLE ROMANEIOORCAMENTOITEM ADD(QTDPEDIDO NUMERIC(17,3)NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1968');
end;
if VpaNumAtualizacao < 1969 then
begin
result := '1969';
ExecutaComandoSql(Aux,'alter table TAREFAEMARKETINGPROSPECT add (DESTEXTO VARCHAR2(4000)NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1969');
end;
if VpaNumAtualizacao < 1970 then
begin
result := '1970';
ExecutaComandoSql(Aux,'alter table TAREFAEMARKETINGPROSPECT add (NUMFORMATOEMAIL NUMBER(1)NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1970');
end;
if VpaNumAtualizacao < 1971 then
begin
result := '1971';
ExecutaComandoSql(Aux,'alter table CFG_GERAL ADD I_SMT_POR NUMBER(5) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_SMT_POR = 25');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1971');
end;
if VpaNumAtualizacao < 1972 then
begin
result := '1972';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD D_IMP_EFI DATE');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1972');
end;
if VpaNumAtualizacao < 1973 then
begin
result := '1973';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD C_NOT_INU CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADNOTAFISCAIS SET C_NOT_INU = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1973');
end;
if VpaNumAtualizacao < 1974 then
begin
result := '1974';
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRACOR ADD(DATCADASTRO DATE NULL, ' +
' DATFICHACOR DATE)');
ExecutaComandoSql(Aux,'UPDATE AMOSTRACOR AMC SET DATCADASTRO = (SELECT DATAMOSTRA FROM AMOSTRA AMO WHERE AMO.CODAMOSTRA = AMC.CODAMOSTRA)');
ExecutaComandoSql(Aux,'UPDATE AMOSTRACOR AMC SET DATFICHACOR = (SELECT DATFICHAAMOSTRA FROM AMOSTRA AMO WHERE AMO.CODAMOSTRA = AMC.CODAMOSTRA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1974');
end;
if VpaNumAtualizacao < 1975 then
begin
result := '1975';
ExecutaComandoSql(Aux,'create table PROPOSTAPRODUTOSCHAMADO '+
'(CODFILIAL NUMBER(10) NOT NULL, '+
' SEQPROPOSTA NUMBER(10) NOT NULL, '+
' SEQPRODUTOCHAMADO NUMBER(10) NOT NULL, '+
' SEQITEMCHAMADO NUMBER(10) NOT NULL, '+
' PRIMARY KEY (CODFILIAL, SEQPROPOSTA, SEQPRODUTOCHAMADO,SEQITEMCHAMADO)) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1975');
end;
if VpaNumAtualizacao < 1976 then
begin
result := '1976';
ExecutaComandoSql(Aux,'ALTER TABLE ORDEMCORTEITEM ADD QTDMETROPRODUTO NUMBER(15,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1976');
end;
if VpaNumAtualizacao < 1977 then
begin
result := '1977';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_AMO_CFA CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_AMO_CFA = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1977');
end;
if VpaNumAtualizacao < 1978 then
begin
result := '1978';
ExecutaComandoSql(Aux,'ALTER TABLE ROMANEIOORCAMENTO ADD DESMOTIVOBLOQUEIO VARCHAR2(100) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1978');
end;
if VpaNumAtualizacao < 1979 then
begin
result := '1979';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD C_NOT_DEV CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update MOVNATUREZA set C_NOT_DEV = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1979');
end;
if VpaNumAtualizacao < 1980 then
begin
result := '1980';
ExecutaComandoSql(Aux,'alter TABLE CADNOTAFISCAIS ADD(N_PER_SSI NUMBER(15,2) NULL, ' +
' N_ICM_SSI NUMBER(15,2) NULL )');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1980');
end;
if VpaNumAtualizacao < 1981 then
begin
result := '1981';
ExecutaComandoSql(Aux,'ALTER TABLE ESTAGIOPROPOSTA ADD DESLOG VARCHAR2(1000)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1981');
end;
if VpaNumAtualizacao < 1982 then
begin
result := '1982';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD D_IMP_PRO DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1982');
end;
if VpaNumAtualizacao < 1983 then
begin
result := '1983';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_MAX_COP NUMBER(10)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1983');
end;
if VpaNumAtualizacao < 1984 then
begin
result := '1984';
ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTAPRODUTO MODIFY DESOBSERVACAO VARCHAR2(500)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1984');
end;
if VpaNumAtualizacao < 1985 then
begin
result := '1985';
ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTAPRODUTOSCHAMADO ADD VALTOTAL NUMBER(15,3)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1985');
end;
if VpaNumAtualizacao < 1986 then
begin
result := '1986';
ExecutaComandoSql(Aux,'CREATE TABLE ESTAGIONOTAFISCALENTRADA ( ' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' SEQNOTAFISCAL NUMBER(10) NOT NULL, ' +
' CODESTAGIO NUMBER(10) NOT NULL, ' +
' SEQESTAGIO NUMBER(10) NOT NULL, ' +
' DATESTAGIO DATE NULL, ' +
' CODUSUARIO NUMBER(10) NULL, ' +
' DESMOTIVO VARCHAR2(250) NULL, ' +
' DESLOG VARCHAR2(2000) NULL, ' +
' PRIMARY KEY(CODFILIAL,SEQNOTAFISCAL,SEQESTAGIO), ' +
' FOREIGN KEY (CODESTAGIO) REFERENCES ESTAGIOPRODUCAO(CODEST))');
ExecutaComandoSql(Aux,'CREATE INDEX ESTAGIONOTAENTRADA_FK1 ON ESTAGIONOTAFISCALENTRADA(CODFILIAL,SEQNOTAFISCAL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1986');
end;
if VpaNumAtualizacao < 1987 then
begin
result := '1987';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD(C_NAD_DPI VARCHAR2(20), ' +
' C_NAF_DPI VARCHAR2(20))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1987');
end;
if VpaNumAtualizacao < 1988 then
begin
result := '1988';
ExecutaComandoSql(Aux,'alter table CADNOTAFISCAIS ADD I_TIP_NOT NUMBER(2)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1988');
end;
if VpaNumAtualizacao < 1989 then
begin
result := '1989';
CadastraTransportadorasComoClientes;
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1989');
end;
if VpaNumAtualizacao < 1990 then
begin
result := '1990';
ExecutaComandoSql(Aux,'update CADCLIENTES ORC ' +
' set I_COD_TRA = ( SELECT I_COD_CLI FROM CADCLIENTES CLI' +
' where CLI.I_TRA_ANT = ORC.I_COD_TRA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1990');
end;
if VpaNumAtualizacao < 1991 then
begin
result := '1991';
ExecutaComandoSql(Aux,'update CADCLIENTES ORC ' +
' set I_COD_RED = ( SELECT I_COD_CLI FROM CADCLIENTES CLI' +
' where CLI.I_TRA_ANT = ORC.I_COD_RED)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1991');
end;
if VpaNumAtualizacao < 1992 then
begin
result := '1992';
ExecutaComandoSql(Aux,'update cadorcamentos ORC ' +
' set I_COD_TRA = ( SELECT I_COD_CLI FROM CADCLIENTES CLI' +
' where CLI.I_TRA_ANT = ORC.I_COD_TRA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1992');
end;
if VpaNumAtualizacao < 1993 then
begin
result := '1993';
ExecutaComandoSql(Aux,'update cadorcamentos ORC ' +
' set I_COD_RED = ( SELECT I_COD_CLI FROM CADCLIENTES CLI' +
' where CLI.I_TRA_ANT = ORC.I_COD_RED)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1993');
end;
if VpaNumAtualizacao < 1994 then
begin
result := '1994';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ' +
' drop CONSTRAINT CADNOTAFIS_CADTRANSPO1 ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1994');
end;
if VpaNumAtualizacao < 1995 then
begin
result := '1995';
ExecutaComandoSql(Aux,'DROP TABLE PEDIDOCOMPRANOTAFISCALITEM ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1995');
end;
if VpaNumAtualizacao < 1996 then
begin
result := '1996';
ExecutaComandoSql(Aux,'CREATE TABLE PEDIDOCOMPRANOTAFISCALITEM (' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' SEQPEDIDO NUMBER(10) NOT NULL, ' +
' SEQNOTA NUMBER(10) NOT NULL, ' +
' SEQITEM NUMBER(10) NOT NULL, ' +
' SEQPRODUTO NUMBER(10) NULL, ' +
' CODCOR NUMBER(10) NULL, ' +
' QTDPRODUTO NUMBER(15,4) NULL,' +
' PRIMARY KEY(CODFILIAL,SEQPEDIDO,SEQNOTA,SEQITEM))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1996');
end;
if VpaNumAtualizacao < 1997 then
begin
result := '1997';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS ADD C_REC_PRE CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADPRODUTOS SET C_REC_PRE =''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1997');
end;
if VpaNumAtualizacao < 1998 then
begin
result := '1998';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAIS ADD N_OUT_DES NUMBER(15,2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1998');
end;
if VpaNumAtualizacao < 1999 then
begin
result := '1999';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD C_CRM_EPC CHAR(1)');
ExecutaComandoSql(Aux,'UPDATE CADFILIAIS SET C_CRM_EPC = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 1999');
end;
if VpaNumAtualizacao < 2000 then
begin
result := '2000';
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2000');
end;
if VpaNumAtualizacao < 2001 then
begin
result := '2001';
ExecutaComandoSql(Aux,'update CADNOTAFISCAIS NOTA ' +
' set I_COD_TRA = ( SELECT I_COD_CLI FROM CADCLIENTES CLI' +
' where CLI.I_TRA_ANT = NOTA.I_COD_TRA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2001');
end;
if VpaNumAtualizacao < 2002 then
begin
result := '2002';
ExecutaComandoSql(Aux,'update CADNOTAFISCAIS NOTA ' +
' set I_COD_RED = ( SELECT I_COD_CLI FROM CADCLIENTES CLI' +
' where CLI.I_TRA_ANT = NOTA.I_COD_RED)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2002');
end;
if VpaNumAtualizacao < 2003 then
begin
result := '2003';
ExecutaComandoSql(Aux,'alter table CADGRUPOS ADD(C_EST_MUP CHAR(1) NULL, ' +
' C_EST_BOC CHAR(1) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2003');
end;
if VpaNumAtualizacao < 2004 then
begin
result := '2004';
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EST_MUP = ''F'','+
' C_EST_BOC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2004');
end;
if VpaNumAtualizacao < 2005 then
begin
result := '2005';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_EST_EPD CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_EST_EPD = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2005');
end;
if VpaNumAtualizacao < 2006 then
begin
result := '2006';
ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTAPRODUTO MODIFY DESOBSERVACAO VARCHAR2(2000) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2006');
end;
if VpaNumAtualizacao < 2007 then
begin
result := '2007';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS MODIFY C_OBS_ORC VARCHAR2(2000) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2007');
end;
if VpaNumAtualizacao < 2008 then
begin
result := '2008';
ExecutaComandoSql(Aux,'CREATE TABLE CLIENTETELEFONE( ' +
' CODCLIENTE NUMBER(10) NOT NULL, ' +
' SEQTELEFONE NUMBER(10) NOT NULL, ' +
' DESTELEFONE VARCHAR2(15) NULL, ' +
' PRIMARY KEY(CODCLIENTE,SEQTELEFONE))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2008');
end;
if VpaNumAtualizacao < 2009 then
begin
result := '2009';
ExecutaComandoSql(Aux,'ALTER TABLE CONTRATOCORPO ADD(DATINICIOVIGENCIA DATE NULL, ' +
' DATFIMVIGENCIA DATE) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2009');
end;
if VpaNumAtualizacao < 2010 then
begin
result := '2010';
ExecutaComandoSql(Aux,'ALTER TABLE CONTRATOCORPO ADD(LANORCAMENTO NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2010');
end;
if VpaNumAtualizacao < 2011 then
begin
result := '2011';
ExecutaComandoSql(Aux,'UPDATE CONTRATOCORPO SET DATINICIOVIGENCIA = DATASSINATURA');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2011');
end;
if VpaNumAtualizacao < 2012 then
begin
result := '2012';
ExecutaComandoSql(Aux,'alter table cadclientes add C_SEN_ASS VARCHAR2(20) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2012');
end;
if VpaNumAtualizacao < 2013 then
begin
result := '2013';
ExecutaComandoSql(Aux,'update CONTRATOCORPO SET DATFIMVIGENCIA = add_months(DATASSINATURA,QTDMESES) ' +
' WHERE DATFIMVIGENCIA IS NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2013');
end;
if VpaNumAtualizacao < 2014 then
begin
result := '2014';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_SER_OBR CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_SER_OBR = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2014');
end;
if VpaNumAtualizacao < 2015 then
begin
result := '2015';
ExecutaComandoSql(Aux,'ALTER TABLE CADUSUARIOS ADD I_CAM_VEN NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2015');
end;
if VpaNumAtualizacao < 2016 then
begin
result := '2016';
ExecutaComandoSql(Aux,'ALTER TABLE CHEQUE ADD CODCLIENTE NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2016');
end;
if VpaNumAtualizacao < 2017 then
begin
result := '2017';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS ADD (N_QTD_PEC NUMBER(15,3) NULL, ' +
' N_COM_PRO NUMBER(10,2) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2017');
end;
if VpaNumAtualizacao < 2018 then
begin
result := '2018';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_COT_CPC CHAR(1) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set C_COT_CPC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2018');
end;
if VpaNumAtualizacao < 2019 then
begin
result := '2019';
ExecutaComandoSql(Aux,'ALTER TABLE PLANOCONTAORCADO drop PRIMARY KEY');
ExecutaComandoSql(Aux,'DELETE FROM PLANOCONTAORCADO');
ExecutaComandoSql(Aux,'ALTER TABLE PLANOCONTAORCADO ADD (CODCENTROCUSTO NUMBER(10)NOT NULL)');
ExecutaComandoSql(Aux,'ALTER TABLE PLANOCONTAORCADO ' +
' ADD PRIMARY KEY(CODEMPRESA,CODPLANOCONTA,CODCENTROCUSTO,ANOORCADO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2019');
end;
if VpaNumAtualizacao < 2020 then
begin
result := '2020';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD (I_PLA_CCO NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2020');
end;
if VpaNumAtualizacao < 2021 then
begin
result := '2021';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS MODIFY C_OBS_FIS VARCHAR2(2000)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2021');
end;
if VpaNumAtualizacao < 2022 then
begin
result := '2022';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR ' +
' drop CONSTRAINT CADNOTAFIS_CADTRANSPO15 ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2022');
end;
if VpaNumAtualizacao < 2023 then
begin
result := '2023';
CadastraTransportadorasComoClientes;
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2023');
end;
if VpaNumAtualizacao < 2024 then
begin
result := '2024';
ExecutaComandoSql(Aux,'update CADNOTAFISCAISFOR NOTA ' +
' set I_COD_TRA = ( SELECT I_COD_CLI FROM CADCLIENTES CLI' +
' where CLI.I_TRA_ANT = NOTA.I_COD_TRA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2024');
end;
if VpaNumAtualizacao < 2025 then
begin
result := '2025';
ExecutaComandoSql(Aux,'update PEDIDOCOMPRACORPO NOTA ' +
' set CODTRANSPORTADORA = ( SELECT I_COD_CLI FROM CADCLIENTES CLI' +
' where CLI.I_TRA_ANT = NOTA.CODTRANSPORTADORA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2025');
end;
if VpaNumAtualizacao < 2026 then
begin
result := '2026';
ExecutaComandoSql(Aux,'update ORCAMENTOROTEIROENTREGA NOTA ' +
' set CODENTREGADOR = ( SELECT I_COD_CLI FROM CADCLIENTES CLI' +
' where CLI.I_TRA_ANT = NOTA.CODENTREGADOR)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2026');
end;
if VpaNumAtualizacao < 2027 then
begin
result := '2027';
ExecutaComandoSql(Aux,'CREATE TABLE GRUPOUSUARIORELATORIO( ' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' CODGRUPO NUMBER(10) NOT NULL, ' +
' SEQRELATORIO NUMBER(10) NOT NULL, ' +
' NOMRELATORIO VARCHAR2(300) NULL, ' +
' PRIMARY KEY(CODFILIAL,CODGRUPO,SEQRELATORIO))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2027');
end;
if VpaNumAtualizacao < 2028 then
begin
result := '2028';
ExecutaComandoSql(Aux,'alter table CHAMADOPRODUTOORCADO ADD NOMPRODUTO VARCHAR2(100) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2028');
end;
if VpaNumAtualizacao < 2029 then
begin
result := '2029';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_GER_SRA CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_GER_SRA = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2029');
end;
if VpaNumAtualizacao < 2030 then
begin
result := '2030';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_LOC_REC CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_LOC_REC = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2030');
end;
if VpaNumAtualizacao < 2031 then
begin
result := '2031';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_LOC_EFN CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_LOC_EFN =''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2031');
end;
if VpaNumAtualizacao < 2032 then
begin
result := '2032';
ExecutaComandoSql(Aux,'CREATE TABLE RECIBOLOCACAOCORPO ( ' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' SEQRECIBO NUMBER(10) NOT NULL, ' +
' SEQLEITURALOCACAO NUMBER(10), ' +
' LANORCAMENTO NUMBER(10), ' +
' CODCLIENTE NUMBER(10), ' +
' DATEMISSAO DATE, ' +
' VALTOTAL NUMBER(15,3), ' +
' DESOBSERVACAO VARCHAR2(500), ' +
' PRIMARY KEY(CODFILIAL,SEQRECIBO))');
ExecutaComandoSql(Aux,'create index RECIBOLOCACAOCORPO_CP1 ON RECIBOLOCACAOCORPO(CODFILIAL,SEQLEITURALOCACAO)');
ExecutaComandoSql(Aux,'create index RECIBOLOCACAOCORPO_CP2 ON RECIBOLOCACAOCORPO(CODFILIAL,LANORCAMENTO)');
ExecutaComandoSql(Aux,'create index RECIBOLOCACAOCORPO_CP3 ON RECIBOLOCACAOCORPO(CODCLIENTE)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2032');
end;
if VpaNumAtualizacao < 2033 then
begin
result := '2033';
ExecutaComandoSql(Aux,'CREATE TABLE RECIBOLOCACAOSERVICO( ' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' SEQRECIBO NUMBER(10) NOT NULL, ' +
' SEQITEM NUMBER(10) NOT NULL, ' +
' CODSERVICO NUMBER(10) NULL, ' +
' QTDSERVICO NUMBER(15,3) NULL, '+
' VALUNITARIO NUMBER(15,3) NULL, ' +
' VALTOTAL NUMBER(15,3) NULL, ' +
' PRIMARY KEY(CODFILIAL,SEQRECIBO,SEQITEM))');
ExecutaComandoSql(Aux,'CREATE INDEX RECIBOLOCACAOSERVICO_FK1 ON RECIBOLOCACAOSERVICO(CODSERVICO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2033');
end;
if VpaNumAtualizacao < 2034 then
begin
result := '2034';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS ADD N_BAI_EST NUMBER(17,3) NULL');
ExecutaComandoSql(Aux,'UPDATE MOVORCAMENTOS SET N_BAI_EST = N_QTD_BAI');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2034');
end;
if VpaNumAtualizacao < 2035 then
begin
result := '2035';
ExecutaComandoSql(Aux,'update CADCLIENTES '+
'SET C_END_ELE = lower(C_END_ELE) ' +
' Where C_END_ELE IS NOT NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2035');
end;
if VpaNumAtualizacao < 2036 then
begin
result := '2036';
ExecutaComandoSql(Aux,'update CONTATOCLIENTE '+
'SET DESEMAIL = lower(DESEMAIL) ' +
' Where DESEMAIL IS NOT NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2036');
end;
if VpaNumAtualizacao < 2037 then
begin
result := '2037';
ExecutaComandoSql(Aux,'update PROSPECT '+
'SET DESEMAILCONTATO = lower(DESEMAILCONTATO) ' +
' Where DESEMAILCONTATO IS NOT NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2037');
end;
if VpaNumAtualizacao < 2038 then
begin
result := '2038';
ExecutaComandoSql(Aux,'update CONTATOPROSPECT '+
'SET DESEMAIL = lower(DESEMAIL) ' +
' Where DESEMAIL IS NOT NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2038');
end;
if VpaNumAtualizacao < 2039 then
begin
result := '2039';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASARECEBER ADD C_IND_SIN CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADCONTASARECEBER set C_IND_SIN = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2039');
end;
if VpaNumAtualizacao < 2040 then
begin
result := '2040';
ExecutaComandoSql(Aux,'ALTER TABLE CADORCAMENTOS add C_SIN_PAG CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADORCAMENTOS SET C_SIN_PAG = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2040');
end;
if VpaNumAtualizacao < 2041 then
begin
result := '2041';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_SIN_PAG CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_SIN_PAG = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2041');
end;
if VpaNumAtualizacao < 2042 then
begin
result := '2042';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_ORD_EFE CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_ORD_EFE = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2042');
end;
if VpaNumAtualizacao < 2043 then
begin
result := '2043';
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRACOR ADD DATENTREGA DATE NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2043');
end;
if VpaNumAtualizacao < 2044 then
begin
result := '2044';
ExecutaComandoSql(Aux,'UPDATE AMOSTRACOR COR ' +
' SET DATENTREGA = (SELECT DATENTREGA FROM AMOSTRA AMO ' +
' WHERE COR.CODAMOSTRA = AMO.CODAMOSTRA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2044');
end;
if VpaNumAtualizacao < 2045 then
begin
result := '2045';
ExecutaComandoSql(Aux,'CREATE TABLE AMOSTRACORESTAGIO( ' +
' CODAMOSTRA NUMBER(10) NOT NULL, ' +
' CODCOR NUMBER(10) NOT NULL, ' +
' SEQESTAGIO NUMBER(10) NOT NULL, ' +
' CODESTAGIO NUMBER(10) NULL, ' +
' DATCADASTRO DATE NULL, ' +
' CODUSUARIOCADASTRO NUMBER(10) NULL, ' +
' DATFIM DATE NULL, ' +
' CODUSUARIOFIM NUMBER(10) NULL, ' +
' PRIMARY KEY(CODAMOSTRA, CODCOR,SEQESTAGIO))');
ExecutaComandoSql(Aux,'CREATE INDEX AMOSTRACORESTAGIO_FK1 ON AMOSTRACORESTAGIO(CODAMOSTRA,CODCOR) ');
ExecutaComandoSql(Aux,'CREATE INDEX AMOSTRACORESTAGIO_FK2 ON AMOSTRACORESTAGIO(CODESTAGIO) ');
ExecutaComandoSql(Aux,'CREATE INDEX AMOSTRACORESTAGIO_FK3 ON AMOSTRACORESTAGIO(CODUSUARIOCADASTRO) ');
ExecutaComandoSql(Aux,'CREATE INDEX AMOSTRACORESTAGIO_FK4 ON AMOSTRACORESTAGIO(CODUSUARIOFIM) ');
ExecutaComandoSql(Aux,'CREATE INDEX AMOSTRACORESTAGIO_CP1 ON AMOSTRACORESTAGIO(DATFIM) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2045');
end;
if VpaNumAtualizacao < 2046 then
begin
result := '2046';
ExecutaComandoSql(Aux,'create index MOVQDADEPRODUTO_CP2 ON MOVQDADEPRODUTO(D_ULT_ALT)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2046');
end;
if VpaNumAtualizacao < 2047 then
begin
result := '2047';
ExecutaComandoSql(Aux,'alter table cadclientes add C_IND_COF CHAR(1)NULL');
ExecutaComandoSql(Aux,'UPDATE cadclientes SET C_IND_COF = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2047');
end;
if VpaNumAtualizacao < 2048 then
begin
result := '2048';
ExecutaComandoSql(Aux,'alter table MOVNOTASFISCAIS ADD( ' +
' N_BAS_SUT NUMBER(15,2) NULL, ' +
' N_VAL_SUT NUMBER(15,2) NULL)');
ExecutaComandoSql(Aux,'UPDATE cadclientes SET C_IND_COF = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2048');
end;
if VpaNumAtualizacao < 2049 then
begin
result := '2049';
ExecutaComandoSql(Aux,'alter table CADFILIAIS MODIFY C_NOM_FIL VARCHAR2(70)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2049');
end;
if VpaNumAtualizacao < 2050 then
begin
result := '2050';
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOCOMPRAFORNECEDORCORPO ' +
' drop CONSTRAINT ORCAMENTOC_CADTRANSPO72 ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2050');
end;
if VpaNumAtualizacao < 2051 then
begin
result := '2051';
ExecutaComandoSql(Aux,'ALTER TABLE ORCAMENTOCOMPRACORPO ' +
' drop CONSTRAINT ORCAMENTOC_CADTRANSPO71');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2051');
end;
end;
{******************************************************************************}
function TAtualiza.AtualizaTabela4(VpaNumAtualizacao: Integer): String;
begin
if VpaNumAtualizacao < 2052 then
begin
result := '2052';
{ ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR ' +
' drop CONSTRAINT CADNOTAFIS_CADTRANSPO14 ');}
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2052');
end;
if VpaNumAtualizacao < 2053 then
begin
result := '2053';
ExecutaComandoSql(Aux,'DROP TABLE CADTRANSPORTADORAS');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2053');
end;
if VpaNumAtualizacao < 2054 then
begin
result := '2054';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLIENTES ADD C_VEI_PRO CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADCLIENTES SET C_VEI_PRO = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2054');
end;
if VpaNumAtualizacao < 2055 then
begin
result := '2055';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_CUS_LPV CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_CUS_LPV = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2055');
end;
if VpaNumAtualizacao < 2056 then
begin
result := '2056';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD( I_AMO_COL NUMBER(10) NULL, ' +
' I_AMO_CDP NUMBER(10) NULL, ' +
' I_AMO_CDE NUMBER(10) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2056');
end;
if VpaNumAtualizacao < 2057 then
begin
result := '2057';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD C_COD_CST CHAR(2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2057');
end;
if VpaNumAtualizacao < 2058 then
begin
result := '2058';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA DROP(I_PLA_CCO) ');
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD(C_PLA_CCO VARCHAR2(5) NULL) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2058');
end;
if VpaNumAtualizacao < 2059 then
begin
result := '2059';
ExecutaComandoSql(Aux,'UPDATE MOVNOTASFISCAISFOR SET N_VLR_BIC = N_TOT_PRO, ' +
' C_COD_CST = ''000''');
ExecutaComandoSql(Aux,'UPDATE MOVNOTASFISCAISFOR SET N_VLR_ICM = N_TOT_PRO * 0.17');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2059');
end;
if VpaNumAtualizacao < 2060 then
begin
result := '2060';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAISFOR ADD (N_VLR_DES NUMBER(15,3) NULL, ' +
' N_OUT_DES NUMBER(15,3) NULL, ' +
' N_VLR_FRE NUMBER(15,3) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2060');
end;
if VpaNumAtualizacao < 2061 then
begin
result := '2061';
ExecutaComandoSql(Aux,'alter table MOVNOTASFISCAISFOR ADD (I_COD_CFO NUMBER(5)NULL)');
ExecutaComandoSql(Aux,'alter table MOVNOTASFISCAISFOR DROP (C_COD_NAT)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2061');
end;
if VpaNumAtualizacao < 2062 then
begin
result := '2062';
ExecutaComandoSql(Aux,'ALTER TABLE CADFILIAIS ADD (C_CST_IPE CHAR(4) NULL,' +
' C_CST_PIS CHAR(4) NULL, ' +
' C_CST_PIE CHAR(4) NULL, ' +
' C_CST_COS CHAR(4) NULL, ' +
' C_CST_COE CHAR(4) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2062');
end;
if VpaNumAtualizacao < 2063 then
begin
result := '2063';
ExecutaComandoSql(Aux,'ALTER TABLE MOVSERVICONOTAFOR ADD I_COD_CFO NUMBER(5)NULL');
ExecutaComandoSql(Aux,'UPDATE MOVSERVICONOTAFOR SET I_COD_CFO = 1100');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2063');
end;
if VpaNumAtualizacao < 2064 then
begin
result := '2064';
ExecutaComandoSql(Aux,'delete from TABELAIMPORTACAOFILTRO '+
' WHERE CODTABELA = 20');
ExecutaComandoSql(Aux,'delete from TABELAIMPORTACAO '+
' WHERE CODTABELA = 20');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2064');
end;
if VpaNumAtualizacao < 2065 then
begin
result := '2065';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD I_MOD_DOC NUMBER(10)NULL');
ExecutaComandoSql(Aux,'UPDATE CADNOTAFISCAIS SET I_MOD_DOC = 55');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2065');
end;
if VpaNumAtualizacao < 2066 then
begin
result := '2066';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNATUREZA ADD C_CON_ANA VARCHAR2(20)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2066');
end;
if VpaNumAtualizacao < 2067 then
begin
result := '2067';
ExecutaComandoSql(Aux,'ALTER TABLE AMOSTRACORMOTIVOATRASO' +
' drop CONSTRAINT AMOSTRACORMOTIVOATRASO ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2067');
end;
if VpaNumAtualizacao < 2068 then
begin
result := '2068';
ExecutaComandoSql(Aux,'CREATE TABLE TRANSFERENCIAEXTERNACORPO (' +
' SEQTRANSFERENCIA NUMBER(10) NOT NULL, '+
' DATTRANSFERENCIA DATE, ' +
' CODUSUARIO NUMBER(10) NULL, ' +
' VALTOTAL NUMBER(15,3) NULL, '+
' SEQCAIXA NUMBER(10) NULL, ' +
' PRIMARY KEY(SEQTRANSFERENCIA))');
ExecutaComandoSql(Aux,'CREATE INDEX TRANSFERENCIAEXTCORP_FK1 ON TRANSFERENCIAEXTERNACORPO(SEQCAIXA)');
ExecutaComandoSql(Aux,'CREATE INDEX TRANSFERENCIAEXTCORP_FK2 ON TRANSFERENCIAEXTERNACORPO(CODUSUARIO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2068');
end;
if VpaNumAtualizacao < 2069 then
begin
result := '2069';
ExecutaComandoSql(Aux,'CREATE TABLE TRANSFERENCIAEXTERNAITEM ( ' +
' SEQTRANSFERENCIA NUMBER(10) NOT NULL REFERENCES TRANSFERENCIAEXTERNACORPO(SEQTRANSFERENCIA),'+
' SEQITEM NUMBER(10) NOT NULL, ' +
' VALATUAL NUMBER(15,3) NULL, ' +
' CODFORMAPAGAMENTO NUMBER(10) NULL, ' +
' PRIMARY KEY (SEQTRANSFERENCIA,SEQITEM)) ');
ExecutaComandoSql(Aux,'CREATE INDEX TRANSFERENCIAEXTITE_FK1 ON TRANSFERENCIAEXTERNAITEM(CODFORMAPAGAMENTO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2069');
end;
if VpaNumAtualizacao < 2070 then
begin
result := '2070';
ExecutaComandoSql(Aux,'CREATE TABLE TRANSFERENCIAEXTERNACHEQUE (' +
' SEQTRANSFERENCIA NUMBER(10) NOT NULL, ' +
' SEQITEM NUMBER(10) NOT NULL, ' +
' SEQITEMCHEQUE NUMBER(10) NOT NULL, ' +
' SEQCHEQUE NUMBER(10) NULL, '+
' PRIMARY KEY(SEQTRANSFERENCIA,SEQITEM,SEQITEMCHEQUE))');
ExecutaComandoSql(Aux,'ALTER TABLE TRANSFERENCIAEXTERNACHEQUE add CONSTRAINT TRANSFEXTERCHEQUE_ITEM '+
' FOREIGN KEY (SEQTRANSFERENCIA,SEQITEM) '+
' REFERENCES TRANSFERENCIAEXTERNAITEM (SEQTRANSFERENCIA,SEQITEM) ');
ExecutaComandoSql(Aux,'CREATE INDEX TRANSFIAEXTCHEQUE_FK1 ON TRANSFERENCIAEXTERNACHEQUE(SEQCHEQUE)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2070');
end;
if VpaNumAtualizacao < 2071 then
begin
result := '2071';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_ORD_RRA CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_ORD_RRA = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2071');
end;
if VpaNumAtualizacao < 2072 then
begin
result := '2072';
ExecutaComandoSql(Aux,'ALTER TABLE FRACAOOPFACCIONISTA ADD DATDIGITACAO DATE NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2072');
end;
if VpaNumAtualizacao < 2073 then
begin
result := '2073';
ExecutaComandoSql(Aux,'ALTER TABLE MOVNOTASFISCAISFOR ADD N_RED_BAS NUMBER(15,3) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2073');
end;
if VpaNumAtualizacao < 2074 then
begin
result := '2074';
ExecutaComandoSql(Aux,'INSERT INTO TIPODOCUMENTOFISCAL(CODTIPODOCUMENTOFISCAL,NOMTIPODOCUMENTOFISCAL) VALUES(''IS'',''NOTA FISCAL SERVICO PREFETURA'')');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2074');
end;
if VpaNumAtualizacao < 2075 then
begin
result := '2075';
ExecutaComandoSql(Aux,'CREATE TABLE CONHECIMENTOTRANSPORTE( ' +
' SEQCONHECIMENTO NUMBER(10) NOT NULL, ' +
' CODTRANSPORTADORA NUMBER(10) NOT NULL, ' +
' CODFILIALNOTA NUMBER(10), ' +
' SEQNOTASAIDA NUMBER(10), ' +
' SEQNOTAENTRADA NUMBER(10), ' +
' CODMODELODOCUMENTO CHAR(2) NULL, ' +
' DATCONHECIMENTO DATE NULL, ' +
' NUMTIPOCONHECIMENTO NUMBER(1) NULL, ' +
' VALCONHECIMENTO NUMBER(15,3) NULL, ' +
' VALBASEICMS NUMBER(15,3) NULL, ' +
' VALICMS NUMBER(15,3) NULL, ' +
' PESFRETE NUMBER(15,3) NULL, ' +
' VALNAOTRIBUTADO NUMBER(15,3) NULL, ' +
' PRIMARY KEY(SEQCONHECIMENTO))');
ExecutaComandoSql(Aux,'CREATE INDEX CONHECIMENTOTRANSPORTE_FK1 ON CONHECIMENTOTRANSPORTE(CODFILIALNOTA,SEQNOTASAIDA)');
ExecutaComandoSql(Aux,'CREATE INDEX CONHECIMENTOTRANSPORTE_FK2 ON CONHECIMENTOTRANSPORTE(CODFILIALNOTA,SEQNOTAENTRADA)');
ExecutaComandoSql(Aux,'CREATE INDEX CONHECIMENTOTRANSPORTE_FK3 ON CONHECIMENTOTRANSPORTE(CODTRANSPORTADORA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2075');
end;
if VpaNumAtualizacao < 2076 then
begin
result := '2076';
ExecutaComandoSql(Aux,'alter table movnotasfiscais add C_DES_ADI VARCHAR2(500) NULL ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2076');
end;
if VpaNumAtualizacao < 2077 then
begin
result := '2077';
ExecutaComandoSql(Aux,'ALTER TABLE SETOR ADD DESDIRETORIOSALVARPDF VARCHAR2(200) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2077');
end;
if VpaNumAtualizacao < 2078 then
begin
result := '2078';
ExecutaComandoSql(Aux,'ALTER TABLE MOVSERVICONOTA ADD N_PER_ISQ NUMBER(5,2) NULL');
ExecutaComandoSql(Aux,' UPDATE MOVSERVICONOTA MOV '+
' SET N_PER_ISQ = (SELECT N_PER_ISQ FROM CADNOTAFISCAIS CAD '+
' WHERE CAD.I_EMP_FIL = MOV.I_EMP_FIL '+
' AND CAD.I_SEQ_NOT = MOV.I_SEQ_NOT)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2078');
end;
if VpaNumAtualizacao < 2079 then
begin
result := '2079';
ExecutaComandoSql(Aux,'alter table TAREFAEMARKETING add (DESTEXTO VARCHAR2(4000)NULL, ' +
' NUMFORMATOEMAIL NUMBER(1)NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2079');
end;
if VpaNumAtualizacao < 2080 then
begin
result := '2080';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD C_LEI_SEF CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_PRODUTO set C_LEI_SEF = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2080');
end;
if VpaNumAtualizacao < 2081 then
begin
result := '2081';
ExecutaComandoSql(Aux,'ALTER TABLE CADFORMASPAGAMENTO ADD N_PER_DES NUMBER(5,2)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2081');
end;
if VpaNumAtualizacao < 2082 then
begin
result := '2082';
ExecutaComandoSql(Aux,'ALTER TABLE CADFORMASPAGAMENTO ADD I_DIA_CHE NUMBER(10)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2082');
end;
if VpaNumAtualizacao < 2083 then
begin
result := '2083';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD I_REL_FAC NUMBER(10)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2083');
end;
if VpaNumAtualizacao < 2084 then
begin
result := '2084';
ExecutaComandoSql(Aux,'ALTER TABLE RETORNOFRACAOOPFACCIONISTA ADD DATDIGITACAO DATE NULL');
ExecutaComandoSql(Aux,'update RETORNOFRACAOOPFACCIONISTA set DATDIGITACAO = DATCADASTRO');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2084');
end;
if VpaNumAtualizacao < 2085 then
begin
result := '2085';
ExecutaComandoSql(Aux,'ALTER TABLE MOVCONDICAOPAGTO ADD I_COD_FRM NUMBER(10) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2085');
end;
if VpaNumAtualizacao < 2086 then
begin
result := '2086';
ExecutaComandoSql(Aux,'ALTER TABLE CADUSUARIOS ADD I_COR_AGE NUMBER(10) NULL');
ExecutaComandoSql(Aux,'UPDATE CADUSUARIOS SET I_COR_AGE = 12639424' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2086');
end;
if VpaNumAtualizacao < 2087 then
begin
result := '2087';
ExecutaComandoSql(Aux,'ALTER TABLE CAIXACORPO ADD(VALINICIALCHEQUE NUMBER(15,3) NULL, ' +
' VALATUALCHEQUE NUMBER(15,3) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2087');
end;
if VpaNumAtualizacao < 2088 then
begin
result := '2088';
ExecutaComandoSql(Aux,'alter table CADNOTAFISCAIS DROP(C_REV_EDS)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2088');
end;
if VpaNumAtualizacao < 2089 then
begin
result := '2089';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD(C_EST_EMB CHAR(2) NULL, ' +
' C_LOC_EMB VARCHAR2(60) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2089');
end;
if VpaNumAtualizacao < 2090 then
begin
result := '2090';
ExecutaComandoSql(Aux,'CREATE TABLE CONTAARECEBERSINALPAGAMENTO (' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' LANRECEBER NUMBER(10) NOT NULL, ' +
' CODFILIALSINAL NUMBER(10) NOT NULL, ' +
' LANRECEBERSINAL NUMBER(10) NOT NULL, ' +
' NUMPARCELASINAL NUMBER(10) NOT NULL, ' +
' PRIMARY KEY(CODFILIAL,LANRECEBER,CODFILIALSINAL,LANRECEBERSINAL,NUMPARCELASINAL))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2090');
end;
if VpaNumAtualizacao < 2091 then
begin
result := '2091';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTASARECEBER ADD C_POS_SIN CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CADCONTASARECEBER SET C_POS_SIN = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2091');
end;
if VpaNumAtualizacao < 2092 then
begin
result := '2092';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAIS ADD N_SIN_PAG NUMBER(15,3)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2092');
end;
if VpaNumAtualizacao < 2093 then
begin
result := '2093';
ExecutaComandoSql(Aux,'alter table MOVCONTASARECEBER ADD N_SIN_BAI NUMBER(15,3)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2093');
end;
if VpaNumAtualizacao < 2094 then
begin
result := '2094';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_COT_ACG CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_ACG = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2094');
end;
if VpaNumAtualizacao < 2095 then
begin
result := '2095';
ExecutaComandoSql(Aux,'DROP TABLE CONTAARECEBERSINALPAGAMENTO ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2095');
end;
if VpaNumAtualizacao < 2096 then
begin
result := '2096';
ExecutaComandoSql(Aux,'CREATE TABLE NOTAFISCALSINALPAGAMENTO (' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' SEQNOTAFISCAL NUMBER(10) NOT NULL, ' +
' CODFILIALSINAL NUMBER(10) NOT NULL, ' +
' LANRECEBERSINAL NUMBER(10) NOT NULL, ' +
' NUMPARCELASINAL NUMBER(10) NOT NULL, ' +
' PRIMARY KEY(CODFILIAL,SEQNOTAFISCAL,CODFILIALSINAL,LANRECEBERSINAL,NUMPARCELASINAL))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2096');
end;
if VpaNumAtualizacao < 2097 then
begin
result := '2097';
ExecutaComandoSql(Aux,'ALTER TABLE CHEQUE ADD DESORIGEM CHAR(1) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2097');
end;
if VpaNumAtualizacao < 2098 then
begin
result := '2098';
ExecutaComandoSql(Aux,'ALTER TABLE PROPOSTAPRODUTO MODIFY NOMPRODUTO VARCHAR2(90)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2098');
end;
if VpaNumAtualizacao < 2099 then
begin
result := '2099';
ExecutaComandoSql(Aux,'ALTER TABLE AGENDA ADD DESTITULO VARCHAR2(100) NULL');
ExecutaComandoSql(Aux,'UPDATE AGENDA SET DESTITULO = SUBSTR(DESOBSERVACAO,1,50) '+
' Where INDREALIZADO = ''N''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2099');
end;
if VpaNumAtualizacao < 2100 then
begin
result := '2100';
ExecutaComandoSql(Aux,' ALTER TABLE AMOSTRACORMOTIVOATRASO ADD(DATCADASTRO DATE) ');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2100');
end;
if VpaNumAtualizacao < 2101 then
begin
result := '2101';
ExecutaComandoSql(Aux,' UPDATE AMOSTRACORMOTIVOATRASO AMT SET DATCADASTRO = ' +
' (SELECT DATAMOSTRA FROM AMOSTRA AMO' +
' WHERE AMO.CODAMOSTRA = AMT.CODAMOSTRA)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2101');
end;
if VpaNumAtualizacao < 2102 then
begin
result := '2102';
ExecutaComandoSql(Aux,'alter table CFG_FINANCEIRO ADD C_CON_FIL CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FINANCEIRO SET C_CON_FIL = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2102');
end;
if VpaNumAtualizacao < 2103 then
begin
result := '2103';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO ADD C_BCA_FIL CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FINANCEIRO SET C_BCA_FIL = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2103');
end;
if VpaNumAtualizacao < 2104 then
begin
result := '2104';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FINANCEIRO ADD C_SOM_URC CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FINANCEIRO SET C_SOM_URC =''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2104');
end;
if VpaNumAtualizacao < 2105 then
begin
result := '2105';
ExecutaComandoSql(Aux,'ALTER TABLE CADCONTAS ADD I_QTD_RET NUMBER(10)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2105');
end;
if VpaNumAtualizacao < 2106 then
begin
result := '2106';
ExecutaComandoSql(Aux,'ALTER TABLE CADCLASSIFICACAO ADD N_PER_MAX NUMBER(8,3)NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2106');
end;
if VpaNumAtualizacao < 2107 then
begin
result := '2107';
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS DROP(N_CUS_UNI)');
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS ADD(N_CUS_TOT NUMBER(15,3) NULL, ' +
' N_VEN_LIQ NUMBER(15,3) NULL, ' +
' N_MAR_BRU NUMBER(8,2) NULL,' +
' N_MAR_LIQ NUMBER(8,2) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2107');
end;
if VpaNumAtualizacao < 2108 then
begin
result := '2108';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_TEC_ACE CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_TEC_ACE = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2108');
end;
if VpaNumAtualizacao < 2109 then
begin
result := '2109';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD(C_ORP_ACE CHAR(1) NULL, ' +
' C_EAN_ACE CHAR(1) NULL, ' +
' C_LEI_SEF CHAR(1) NULL)');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_ORP_ACE = (SELECT C_ORP_ACE FROM CFG_PRODUTO)');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_EAN_ACE = (SELECT C_EAN_ACE FROM CFG_PRODUTO)');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_LEI_SEF = (SELECT C_LEI_SEF FROM CFG_PRODUTO)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2109');
end;
if VpaNumAtualizacao < 2110 then
begin
result := '2110';
ExecutaComandoSql(Aux,'CREATE TABLE ESTOQUENUMEROSERIE( ' +
' CODFILIAL NUMBER(10) NOT NULL, ' +
' SEQPRODUTO NUMBER(10) NOT NULL, ' +
' CODCOR NUMBER(10) NOT NULL, ' +
' CODTAMANHO NUMBER(10) NOT NULL, ' +
' SEQESTOQUE NUMBER(10) NOT NULL, ' +
' DESNUMEROSERIE VARCHAR2(50) NULL, ' +
' QTDPRODUTO NUMBER(17,4)NULL, ' +
' PRIMARY KEY(CODFILIAL,SEQPRODUTO,CODCOR,CODTAMANHO,SEQESTOQUE))');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2110');
end;
if VpaNumAtualizacao < 2111 then
begin
result := '2111';
ExecutaComandoSql(Aux,'ALTER TABLE COR MODIFY NOM_COR VARCHAR2(150)');
ExecutaComandoSql(Aux,'ALTER TABLE MOVORCAMENTOS MODIFY C_DES_COR VARCHAR2(150)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2111');
end;
if VpaNumAtualizacao < 2112 then
begin
result := '2112';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD C_CID_FRE CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FISCAL SET C_CID_FRE = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2112');
end;
if VpaNumAtualizacao < 2113 then
begin
result := '2113';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_PRODUTO ADD( C_UNI_QUI CHAR(2) NULL, ' +
' C_UNI_MIL CHAR(2) NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2113');
end;
if VpaNumAtualizacao < 2114 then
begin
result := '2114';
ExecutaComandoSql(Aux,'alter table CADFILIAIS ADD (D_ULT_RPS DATE NULL)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2114');
end;
if VpaNumAtualizacao < 2115 then
begin
result := '2115';
ExecutaComandoSql(Aux,'ALTER TABLE CADPRODUTOS MODIFY I_IND_COV NUMBER(17,6)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2115');
end;
if VpaNumAtualizacao < 2116 then
begin
result := '2116';
// ExecutaComandoSql(Aux,'DELETE FROM MOVTABELAPRECO WHERE I_COD_CLI <> 0');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2116');
end;
if VpaNumAtualizacao < 2117 then
begin
result := '2117';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_GERAL ADD C_COT_IOI CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_GERAL SET C_COT_IOI = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2117');
end;
if VpaNumAtualizacao < 2118 then
begin
result := '2118';
ExecutaComandoSql(Aux,'ALTER TABLE CADGRUPOS ADD C_POL_ISE CHAR(1)');
ExecutaComandoSql(Aux,'UPDATE CADGRUPOS SET C_POL_ISE = ''T''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2118');
end;
if VpaNumAtualizacao < 2119 then
begin
result := '2119';
ExecutaComandoSql(Aux,'UPDATE CHEQUE SET CODFORNECEDORRESERVA = NULL WHERE CODFORNECEDORRESERVA = 0');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2119');
end;
if VpaNumAtualizacao < 2120 then
begin
result := '2120';
ExecutaComandoSql(Aux,'alter table CADORCAMENTOS MODIFY C_OBS_FIS VARCHAR2(4000)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2120');
end;
if VpaNumAtualizacao < 2122 then
begin
result := '2122';
ExecutaComandoSql(Aux,'alter table RETORNOITEM MODIFY NOMOCORRENCIA VARCHAR2(40)');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2122');
end;
if VpaNumAtualizacao < 2121 then
begin
result := '2121';
ExecutaComandoSql(Aux,'ALTER TABLE CADNOTAFISCAISFOR ADD N_PER_ICM NUMBER(5,2) NULL');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2121');
end;
if VpaNumAtualizacao < 2122 then
begin
result := '2122';
ExecutaComandoSql(Aux,'ALTER TABLE CFG_FISCAL ADD C_PRO_FIL CHAR(1) NULL');
ExecutaComandoSql(Aux,'UPDATE CFG_FISCAL SET C_PRO_FIL = ''F''');
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 2122');
end;
end;
function TAtualiza.AtualizaTabela5(VpaNumAtualizacao: Integer): String;
begin
end;
end.
|
{$i deltics.unicode.inc}
unit Deltics.Unicode.Types;
interface
uses
Deltics.StringTypes;
{$i deltics.stringtypes.aliases.inc}
type
TBom = array of Byte;
// Base class for escape classes
UnicodeEscapeBase = class
public
class function EscapedLength(const aChar: WideChar): Integer; overload; virtual; abstract;
class function EscapedLength(const aCodepoint: Codepoint): Integer; overload; virtual; abstract;
class procedure EscapeA(const aChar: WideChar; const aBuffer: PAnsiChar); overload; virtual; abstract;
class procedure EscapeA(const aCodepoint: Codepoint; const aBuffer: PAnsiChar); overload; virtual; abstract;
class procedure EscapeW(const aChar: WideChar; const aBuffer: PWideChar); overload; virtual; abstract;
class procedure EscapeW(const aCodepoint: Codepoint; const aBuffer: PWideChar); overload; virtual; abstract;
end;
UnicodeEscape = class of UnicodeEscapeBase;
implementation
end.
|
unit Vigilante.Module.GerenciadorDeArquivoDataSet.Impl;
interface
uses
System.SysUtils, FireDac.Comp.Client, FireDac.Stan.StorageXML,
Vigilante.Module.GerenciadorDeArquivoDataSet;
type
TGerenciadorDeArquivoDataSet = class(TInterfacedObject, IGerenciadorDeArquivoDataSet)
private
FDataSet: TFDMemTable;
function PodeCarregarDiretoDoArquivo(const ADataSetTemp: TFDMemTable): boolean;
procedure CarregamentoAlternativo(
const ADataSetTemp: TFDMemTable);
function FormatarNomeDoArquivo(const ANomeArquivo: TFileName): TFileName;
procedure MesclarComDataSet(const ADataSetTemp: TFDMemTable);
public
constructor Create(const ADataSet: TFDMemTable);
function CarregarArquivo(const ANomeArquivo: TFileName): boolean;
procedure SalvarArquivo(const ANomeArquivo: TFileName);
end;
implementation
uses
System.IOUtils, Data.DB, FireDac.Stan.Intf, FireDac.Comp.DataSet;
constructor TGerenciadorDeArquivoDataSet.Create(const ADataSet: TFDMemTable);
begin
FDataSet := ADataSet;
end;
function TGerenciadorDeArquivoDataSet.CarregarArquivo(
const ANomeArquivo: TFileName): boolean;
var
_dataTemp: TFDMemTable;
_nomeArquivo: TFileName;
begin
Result := False;
_nomeArquivo := FormatarNomeDoArquivo(ANomeArquivo);
if not TFile.Exists(_nomeArquivo) then
Exit;
FDataSet.CreateDataSet;
_dataTemp := TFDMemTable.Create(Nil);
try
_dataTemp.LoadFromFile(_nomeArquivo, sfXML);
if PodeCarregarDiretoDoArquivo(_dataTemp) then
begin
FDataSet.LoadFromFile(_nomeArquivo, sfXML);
Result := True;
Exit;
end;
CarregamentoAlternativo(_dataTemp);
Result := True;
finally
FreeAndNil(_dataTemp);
end;
end;
function TGerenciadorDeArquivoDataSet.FormatarNomeDoArquivo(
const ANomeArquivo: TFileName): TFileName;
const
NOME_ARQUIVO = '%s\%s';
var
_path: TFileName;
_pathPreDefinido: boolean;
begin
_pathPreDefinido := not ExtractFilePath(ANomeArquivo).Trim.IsEmpty;
if _pathPreDefinido then
Exit(ANomeArquivo);
_path := ExtractFilePath(ParamStr(0));
_path := ExcludeTrailingPathDelimiter(_path);
Result := Format(NOME_ARQUIVO, [_path, ANomeArquivo]);
end;
function TGerenciadorDeArquivoDataSet.PodeCarregarDiretoDoArquivo(
const ADataSetTemp: TFDMemTable): boolean;
var
_campo: TField;
begin
Result := False;
if ADataSetTemp.FieldCount <> FDataSet.FieldCount then
Exit;
for _campo in FDataSet.Fields do
begin
if not Assigned(ADataSetTemp.FindField(_campo.FieldName)) then
Exit;
end;
Result := True;
end;
procedure TGerenciadorDeArquivoDataSet.CarregamentoAlternativo(
const ADataSetTemp: TFDMemTable);
begin
ADataSetTemp.First;
while not ADataSetTemp.Eof do
begin
MesclarComDataSet(ADataSetTemp);
ADataSetTemp.Next;
end;
end;
procedure TGerenciadorDeArquivoDataSet.MesclarComDataSet(
const ADataSetTemp: TFDMemTable);
var
_campo: TField;
begin
FDataSet.Insert;
for _campo in ADataSetTemp.Fields do
FDataSet.FieldByName(_campo.FieldName).Value := _campo.Value;
FDataSet.Post;
end;
procedure TGerenciadorDeArquivoDataSet.SalvarArquivo(
const ANomeArquivo: TFileName);
var
_nomeArquivo: string;
begin
_nomeArquivo := FormatarNomeDoArquivo(ANomeArquivo);
FDataSet.MergeChangeLog;
FDataSet.SaveToFile(_nomeArquivo, sfXML);
end;
end.
|
// **************************************************************************************************
// Delphi Aio Library.
// Unit ChannelImpl
// https://github.com/Purik/AIO
// The contents of this file are subject to the Apache License 2.0 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
//
// The Original Code is ChannelImpl.pas.
//
// Contributor(s):
// Pavel Minenkov
// Purik
// https://github.com/Purik
//
// The Initial Developer of the Original Code is Pavel Minenkov [Purik].
// All Rights Reserved.
//
// **************************************************************************************************
unit ChannelImpl;
interface
uses {$IFDEF FPC} contnrs, fgl {$ELSE}Generics.Collections, System.Rtti{$ENDIF},
GInterfaces, Hub, Gevent, PasMP, Classes, Greenlets, SyncObjs,
GarbageCollector, SysUtils;
type
ILightGevent = interface
procedure SetEvent(const Async: Boolean = False);
procedure WaitEvent;
procedure Associate(Other: ILightGevent; Index: Integer);
function GetIndex: Integer;
procedure SetIndex(Value: Integer);
function GetContext: Pointer;
function GetInstance: Pointer;
end;
TLightGevent = class(TInterfacedObject, ILightGevent)
strict private
FSignal: Boolean;
FLock: TPasMPSpinLock;
FContext: Pointer;
FHub: TCustomHub;
FWaitEventRoutine: TThreadMethod;
FIndex: Integer;
FAssociate: ILightGevent;
FAssociateIndex: Integer;
FWaiting: Boolean;
procedure Lock; inline;
procedure Unlock; inline;
procedure ThreadedWaitEvent;
procedure GreenletWaitEvent;
public
constructor Create;
destructor Destroy; override;
procedure SetEvent(const Async: Boolean = False);
procedure WaitEvent;
procedure Associate(Other: ILightGevent; Index: Integer);
function GetIndex: Integer;
procedure SetIndex(Value: Integer);
function GetContext: Pointer;
function GetInstance: Pointer;
end;
IAbstractContract = interface
['{E27E9F47-02E7-4F82-BB5E-36FE142BF55B}']
procedure FixCurContext;
function IsMyCtx: Boolean;
procedure Lock;
procedure Unlock;
end;
IContract<T> = interface(IAbstractContract)
['{4A32E6FB-1E6C-462F-BF8B-0503270D162A}']
function Push(const A: T; Ref: IGCObject): Boolean;
function Pop(out A: T; out Ref: IGCObject): Boolean;
function IsEmpty: Boolean;
end;
TLightCondVar = class
type
TSyncMethod = (smDefault, smForceAsync, smForceSync);
strict private
type
TWaitRoutine = procedure(Unlocking: TPasMPSpinLock) of object;
TSyncRoutine = procedure(const Method: TSyncMethod=smDefault) of object;
var
FItems: TList;
FLock: TPasMPSpinLock;
FAsync: Boolean;
FWaitRoutine: TWaitRoutine;
FSignalRoutine: TSyncRoutine;
FBroadcastRoutine: TSyncRoutine;
procedure Clean;
procedure LockedWait(Unlocking: TPasMPSpinLock);
procedure LockedSignal(const Method: TSyncMethod);
procedure LockedBroadcast(const Method: TSyncMethod);
procedure UnLockedWait(Unlocking: TPasMPSpinLock);
procedure UnLockedSignal(const Method: TSyncMethod);
procedure UnLockedBroadcast(const Method: TSyncMethod);
protected
procedure Lock; inline;
procedure Unlock; inline;
procedure Enqueue(E: TLightGevent);
function Dequeue(out E: TLightGevent): Boolean;
public
constructor Create(const Async: Boolean; const Locked: Boolean);
destructor Destroy; override;
procedure Wait(Unlocking: TPasMPSpinLock = nil);
procedure Signal(const Method: TSyncMethod=smDefault);
procedure Broadcast(const Method: TSyncMethod=smDefault);
procedure Assign(Source: TLightCondVar);
end;
TAbstractContractImpl = class(TInterfacedObject, IAbstractContract)
strict private
FLock: TPasMPSpinLock;
FContext: Pointer;
FHub: TCustomHub;
public
constructor Create;
destructor Destroy; override;
procedure Lock;
procedure Unlock;
procedure FixCurContext;
function IsMyCtx: Boolean;
end;
TContractImpl<T> = class(TAbstractContractImpl, IContract<T>)
strict private
FValue: T;
FDefValue: T;
FIsEmpty: Boolean;
FSmartObj: IGCObject;
public
constructor Create;
destructor Destroy; override;
function Push(const A: T; Ref: IGCObject): Boolean;
function Pop(out A: T; out Ref: IGCObject): Boolean;
function IsEmpty: Boolean;
end;
THubRefDictionary = TPasMPHashTable<THub, Integer>;
TLocalContextService = class
strict private
FRef: IGCObject;
FDeadLockExceptionClass: TExceptionClass;
function GetDeadLockExceptionClass: TExceptionClass;
public
function Refresh(A: TObject): IGCObject;
property DeadLockExceptionClass: TExceptionClass read GetDeadLockExceptionClass
write FDeadLockExceptionClass;
end;
TLeaveLockLogger = class
strict private
const
MAX_COUNT_FACTOR = 5;
var
FCounter: Integer;
public
procedure Check(const Msg: string);
end;
TOnDieEvent = procedure(ID: Integer) of object;
ILiveToken = interface
['{7A8A9717-8D55-439B-B142-80F62BC6A613}']
procedure Die;
procedure Deactivate;
function IsLive: Boolean;
end;
IContextRef = interface
procedure SetActive(const Value: Boolean);
function GetActive: Boolean;
function GetRefCount: Integer;
function AddRef(Accum: Integer = 1): Integer;
function Release(Accum: Integer = 1): Integer;
end;
TContextRef = class(TInterfacedObject, IContextRef)
strict private
FActive: Boolean;
FRefCount: Integer;
FIsOwner: Boolean;
public
constructor Create(const Active: Boolean = True; const IsOwnerContext: Boolean = False);
procedure SetActive(const Value: Boolean);
function GetActive: Boolean;
function GetRefCount: Integer;
function AddRef(Accum: Integer = 1): Integer;
function Release(Accum: Integer = 1): Integer;
end;
TContextHashTable = {$IFDEF DCC}
TDictionary<NativeUInt, IContextRef>
{$ELSE}
TFPGMap<NativeUInt, IContextRef>
{$ENDIF};
TOnGetLocalService = function: TLocalContextService of object;
TOnCheckDeadLock = function(const AsReader: Boolean; const AsWriter: Boolean;
const RaiseError: Boolean = True; const Lock: Boolean = True): Boolean of object;
TCustomChannel<T> = class(TInterfacedObject)
type
TPendingOperations<Y> = class
strict private
FPendingReader: IRawGreenlet;
FPendingWriter: IRawGreenlet;
FReaderFuture: IFuture<Y, TPendingError>;
FWriterFuture: IFuture<Y, TPendingError>;
public
destructor Destroy; override;
property PendingReader: IRawGreenlet read FPendingReader write FPendingReader;
property PendingWriter: IRawGreenlet read FPendingWriter write FPendingWriter;
property ReaderFuture: IFuture<Y, TPendingError> read FReaderFuture write FReaderFuture;
property WriterFuture: IFuture<Y, TPendingError> read FWriterFuture write FWriterFuture;
end;
strict private
FGuid: string;
FIsClosed: Integer;
FIsObjectTyp: Boolean;
function GetLocalContextKey: string;
function GetLocalPendingKey: string;
private
var
FReaders: TContextHashTable;
FWriters: TContextHashTable;
FDefValue: T;
protected
var
FLock: TPasMPSpinLock;
FReadersNum: Integer;
FWritersNum: Integer;
FOwnerContext: NativeUInt;
class function GetContextUID: NativeUInt;
property Guid: string read FGuid;
function GetLocalService: TLocalContextService;
function GetLocalPendings: TPendingOperations<T>;
property IsObjectTyp: Boolean read FIsObjectTyp;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
procedure BroadcastAll(const Method: TLightCondVar.TSyncMethod); virtual; abstract;
function CheckDeadLock(const AsReader: Boolean; const AsWriter: Boolean;
const RaiseError: Boolean = True; const Lock: Boolean = True): Boolean;
procedure CheckLeaveLock;
function InternalAddRef(const AsReader: Boolean; const AsWriter: Boolean): Integer;
function InternalRelease(const AsReader: Boolean; const AsWriter: Boolean): Integer;
function InternalRead(out A: T; ReleaseFactor: Integer): Boolean; dynamic; abstract;
function InternalWrite(const A: T; ReleaseFactor: Integer): Boolean; dynamic; abstract;
procedure AsyncRead(const Promise: IPromise<T, TPendingError>; const ReleaseFactor: Integer);
procedure AsyncWrite(const Promise: IPromise<T, TPendingError>; const ReleaseFactor: Integer;
const Value: TSmartPointer<T>);
public
constructor Create;
destructor Destroy; override;
// channel interface
function Read(out A: T): Boolean;
function Write(const A: T): Boolean;
function ReadPending: IFuture<T, TPendingError>;
function WritePending(const A: T): IFuture<T, TPendingError>;
procedure Close; dynamic;
function IsClosed: Boolean;
// generator-like
function Get: T;
function GetEnumerator: TEnumerator<T>;
function GetBufSize: LongWord; dynamic; abstract;
procedure AccumRefs(ReadRefCount, WriteRefCount: Integer);
procedure ReleaseRefs(ReadRefCount, WriteRefCount: Integer);
procedure SetDeadlockExceptionClass(Cls: TExceptionClass);
function GetDeadlockExceptionClass: TExceptionClass;
end;
TReadOnlyChannel<T> = class(TInterfacedObject, IReadOnly<T>)
strict private
FParent: TCustomChannel<T>;
protected
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
constructor Create(Parent: TCustomChannel<T>);
function Read(out A: T): Boolean;
function ReadPending: IFuture<T, TPendingError>;
procedure Close;
function IsClosed: Boolean;
function GetEnumerator: TEnumerator<T>;
function Get: T;
function GetBufSize: LongWord;
procedure AccumRefs(ReadRefCount, WriteRefCount: Integer);
procedure ReleaseRefs(ReadRefCount, WriteRefCount: Integer);
procedure SetDeadlockExceptionClass(Cls: TExceptionClass);
function GetDeadlockExceptionClass: TExceptionClass;
end;
TWriteOnlyChannel<T> = class(TInterfacedObject, IWriteOnly<T>)
strict private
FParent: TCustomChannel<T>;
protected
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
constructor Create(Parent: TCustomChannel<T>);
function Write(const A: T): Boolean;
function WritePending(const A: T): IFuture<T, TPendingError>;
procedure Close;
function IsClosed: Boolean;
function GetBufSize: LongWord;
procedure AccumRefs(ReadRefCount, WriteRefCount: Integer);
procedure ReleaseRefs(ReadRefCount, WriteRefCount: Integer);
procedure SetDeadlockExceptionClass(Cls: TExceptionClass);
function GetDeadlockExceptionClass: TExceptionClass;
end;
TSingleThreadSyncChannel<T> = class;
TMultiThreadSyncChannel<T> = class;
TSyncChannel<T> = class(TCustomChannel<T>, IChannel<T>)
private
type
TOnRead = function(out A: T; ReleaseFactor: Integer): Boolean of object;
TOnWrite = function(const A: T; ReleaseFactor: Integer): Boolean of object;
TOnBroadcast = procedure(const Method: TLightCondVar.TSyncMethod) of object;
var
FReadOnly: TReadOnlyChannel<T>;
FWriteOnly: TWriteOnlyChannel<T>;
FSTChannel: TSingleThreadSyncChannel<T>;
FMTChannel: TMultiThreadSyncChannel<T>;
FOnRead: TOnRead;
FOnWrite: TOnWrite;
FOnClose: TThreadMethod;
FOnBroadCast: TOnBroadcast;
protected
FLiveToken: ILiveToken;
procedure BroadcastAll(const Method: TLightCondVar.TSyncMethod); override;
function InternalRead(out A: T; ReleaseFactor: Integer): Boolean; override;
function InternalWrite(const A: T; ReleaseFactor: Integer): Boolean; override;
public
constructor Create(const ThreadSafe: Boolean);
destructor Destroy; override;
procedure Close; override;
function ReadOnly: IReadOnly<T>;
function WriteOnly: IWriteOnly<T>;
function GetBufSize: LongWord; override;
end;
TAsyncChannel<T> = class(TCustomChannel<T>, IChannel<T>)
strict private
FSize: Integer;
FCapacity: Integer;
FReadOnly: TReadOnlyChannel<T>;
FWriteOnly: TWriteOnlyChannel<T>;
FItems: array of IContract<T>;
FReadOffset: Integer;
FWriteOffset: Integer;
FReadCond: TLightCondVar;
FWriteCond: TLightCondVar;
protected
FLiveToken: ILiveToken;
procedure BroadcastAll(const Method: TLightCondVar.TSyncMethod); override;
function InternalRead(out A: T; ReleaseFactor: Integer): Boolean; override;
function InternalWrite(const A: T; ReleaseFactor: Integer): Boolean; override;
public
constructor Create(BufSize: LongWord);
destructor Destroy; override;
procedure Close; override;
function ReadOnly: IReadOnly<T>;
function WriteOnly: IWriteOnly<T>;
function GetBufSize: LongWord; override;
end;
TChannelEnumerator<T> = class(TEnumerator<T>)
strict private
FChannel: TCustomChannel<T>;
FCurrent: T;
FReleaseFactor: Integer;
protected
function GetCurrent: T; override;
public
constructor Create(Channel: TCustomChannel<T>; ReleaseFator: Integer);
function MoveNext: Boolean; override;
property Current: T read GetCurrent;
procedure Reset; override;
end;
TSingleThreadSyncChannel<T> = class
const
YIELD_WAIT_CNT = 2;
type
TContract = record
strict private
SmartObj: IGCObject;
public
Value: T;
Contragent: Pointer;
IsEmpty: Boolean;
procedure PushSmartObj(Value: IGCObject);
function PullSmartObj: IGCObject;
end;
strict private
var
FContractExists: Boolean;
FReadCond: TLightCondVar;
FWriteCond: TLightCondVar;
FContract: TContract;
FHub: TCustomHub;
FIsClosed: Boolean;
FIsObjectTyp: Boolean;
FOnGetLocalService: TOnGetLocalService;
FOnCheckDeadLock: TOnCheckDeadLock;
FWritersNumPtr: PInteger;
FReadersNumPtr: PInteger;
public
constructor Create(const IsObjectTyp: Boolean;
const OnGetLocalGC: TOnGetLocalService;
const OnCheckDeadLock: TOnCheckDeadLock; WNumPtr, RNumPtr: PInteger);
destructor Destroy; override;
function Write(const A: T; ReleaseFactor: Integer): Boolean;
function Read(out A: T; ReleaseFactor: Integer): Boolean;
procedure Close;
property Hub: TCustomHub read FHub write FHub;
procedure Assign(Source: TMultiThreadSyncChannel<T>);
procedure BroadcastAll(const Method: TLightCondVar.TSyncMethod);
end;
TMultiThreadSyncChannel<T> = class
strict private
FLock: TPasMPSpinLock;
FReadCond: TLightCondVar;
FWriteCond: TLightCondVar;
FIsClosed: Boolean;
FContract: IContract<T>;
FContractExists: Boolean;
FNotify: ILightGevent;
FIsObjectTyp: Boolean;
FOnGetLocalService: TOnGetLocalService;
FOnCheckDeadLock: TOnCheckDeadLock;
FWritersNumPtr: PInteger;
FReadersNumPtr: PInteger;
protected
property Lock: TPasMPSpinLock read FLock;
property Contract: IContract<T> read FContract;
property ContractExists: Boolean read FContractExists write FContractExists;
property Notify: ILightGevent read FNotify write FNotify;
property ReadCond: TLightCondVar read FReadCond;
property WriteCond: TLightCondVar read FWriteCond;
public
constructor Create(const IsObjectTyp: Boolean;
const OnGetLocalGC: TOnGetLocalService;
const OnCheckDeadLock: TOnCheckDeadLock; WNumPtr, RNumPtr: PInteger);
destructor Destroy; override;
function Write(const A: T; ReleaseFactor: Integer): Boolean;
function Read(out A: T; ReleaseFactor: Integer): Boolean;
procedure Close;
procedure BroadcastAll(const Method: TLightCondVar.TSyncMethod);
end;
TSoftDeadLock = class(EAbort);
TFanOutImpl<T> = class(TInterfacedObject, IFanOut<T>)
strict private
type
IReadChannel = IReadOnly<T>;
TChannelDescr = record
ID: Integer;
Token: ILiveToken;
SyncImpl: TSyncChannel<T>;
AsyncImpl: TAsyncChannel<T>;
Channel: TCustomChannel<T>;
end;
var
FLastID: Integer;
FBufSize: LongWord;
FLock: TCriticalSection;
FInflateList: TList<TChannelDescr>;
FWorker: IRawGreenlet;
FWorkerContext: NativeUInt;
FWorkerCtxReady: TGevent;
FOnUpdated: TGevent;
procedure Routine(const Input: IReadOnly<T>);
procedure DieCb(ID: Integer);
function GenerateID: Integer;
public
constructor Create(Input: IReadOnly<T>);
destructor Destroy; override;
function Inflate(const BufSize: Integer=-1): IReadOnly<T>;
end;
TLiveTokenImpl = class(TInterfacedObject, ILiveToken)
strict private
FIsLive: Boolean;
FCb: TOnDieEvent;
FID: Integer;
FLock: TCriticalSection;
public
constructor Create(ID: Integer; const Cb: TOnDieEvent);
destructor Destroy; override;
function IsLive: Boolean;
procedure Die;
procedure Deactivate;
end;
var
StdDeadLockException: TExceptionClass;
StdLeaveLockException: TExceptionClass;
implementation
uses TypInfo, GreenletsImpl, Math;
type
TRawGreenletPImpl = class(TRawGreenletImpl);
function _GetCurentHub: TCustomHub;
begin
if GetCurrent <> nil then
Result := TRawGreenletPImpl(GetCurrent).Hub
else
Result := GetCurrentHub
end;
{ TSyncChannel<T> }
procedure TSyncChannel<T>.BroadcastAll(const Method: TLightCondVar.TSyncMethod);
begin
FOnBroadCast(Method);
end;
procedure TSyncChannel<T>.Close;
begin
inherited;
FOnClose;
CheckLeaveLock;
end;
constructor TSyncChannel<T>.Create(const ThreadSafe: Boolean);
begin
inherited Create;
FReadOnly := TReadOnlyChannel<T>.Create(Self);
FWriteOnly := TWriteOnlyChannel<T>.Create(Self);
if ThreadSafe then begin
FMTChannel := TMultiThreadSyncChannel<T>.Create(IsObjectTyp,
GetLocalService, CheckDeadLock, @FWritersNum, @FReadersNum);
FOnRead := FMTChannel.Read;
FOnWrite := FMTChannel.Write;
FOnClose := FMTChannel.Close;
FOnBroadCast := FMTChannel.BroadcastAll;
end
else begin
FSTChannel := TSingleThreadSyncChannel<T>.Create(IsObjectTyp,
GetLocalService, CheckDeadLock, @FWritersNum, @FReadersNum);
FOnRead := FSTChannel.Read;
FOnWrite := FSTChannel.Write;
FOnClose := FSTChannel.Close;
FOnBroadCast := FSTChannel.BroadcastAll;
end;
end;
destructor TSyncChannel<T>.Destroy;
begin
if Assigned(FLiveToken) then
FLiveToken.Die;
FReadOnly.Free;
FWriteOnly.Free;
FSTChannel.Free;
FMTChannel.Free;
inherited;
end;
function TSyncChannel<T>.GetBufSize: LongWord;
begin
Result := 0
end;
function TSyncChannel<T>.InternalRead(out A: T;
ReleaseFactor: Integer): Boolean;
begin
Result := FOnRead(A, ReleaseFactor);
if not Result then begin
CheckLeaveLock;
end;
end;
function TSyncChannel<T>.InternalWrite(const A: T;
ReleaseFactor: Integer): Boolean;
begin
Result := FOnWrite(A, ReleaseFactor);
if not Result then
CheckLeaveLock;
end;
function TSyncChannel<T>.ReadOnly: IReadOnly<T>;
begin
Result := FReadOnly
end;
function TSyncChannel<T>.WriteOnly: IWriteOnly<T>;
begin
Result := FWriteOnly
end;
{ TAsyncChannel<T> }
procedure TAsyncChannel<T>.BroadcastAll(const Method: TLightCondVar.TSyncMethod);
begin
FReadCond.Broadcast(Method);
FWriteCond.Broadcast(Method);
end;
procedure TAsyncChannel<T>.Close;
begin
inherited;
FReadCond.Broadcast(smForceAsync);
FWriteCond.Broadcast(smForceAsync);
CheckLeaveLock;
end;
constructor TAsyncChannel<T>.Create(BufSize: LongWord);
var
I: Integer;
begin
inherited Create;
Assert(BufSize > 0, 'BufSize > 0');
FCapacity := BufSize;
FReadOnly := TReadOnlyChannel<T>.Create(Self);
FWriteOnly := TWriteOnlyChannel<T>.Create(Self);
SetLength(FItems, BufSize);
for I := 0 to High(FItems) do
FItems[I] := TContractImpl<T>.Create;
FReadCond := TLightCondVar.Create(False, True);
FWriteCond := TLightCondVar.Create(True, True);
end;
destructor TAsyncChannel<T>.Destroy;
begin
if Assigned(FLiveToken) then
FLiveToken.Die;
FReadOnly.Free;
FWriteOnly.Free;
FReadCond.Free;
FWriteCond.Free;
inherited;
end;
function TAsyncChannel<T>.GetBufSize: LongWord;
begin
Result := FCapacity
end;
function TAsyncChannel<T>.InternalRead(out A: T;
ReleaseFactor: Integer): Boolean;
var
Contract: IContract<T>;
ObjPtr: PObject;
Ref: IGCObject;
begin
Result := False;
AtomicDecrement(FWritersNum, ReleaseFactor);
try
while True do begin
FLock.Acquire;
if FSize > 0 then begin
Contract := FItems[FReadOffset];
if not Contract.IsMyCtx then begin
FReadOffset := (FReadOffset + 1) mod FCapacity;
Dec(FSize);
Contract.Pop(A, Ref);
FLock.Release;
FWriteCond.Signal;
Exit(True);
end
else begin
FWriteCond.Broadcast;
if CheckDeadLock(True, False, False, False) then begin
FLock.Release;
raise GetLocalService.DeadLockExceptionClass.Create('DeadLock::TAsyncChannel<T>.Read');
end;
FReadCond.Wait(FLock);
end;
end
else begin
if IsClosed then begin
FLock.Release;
Exit(False)
end
else begin
if CheckDeadLock(True, False, False, False) then begin
FLock.Release;
raise GetLocalService.DeadLockExceptionClass.Create('DeadLock::TAsyncChannel<T>.Read');
end;
FReadCond.Wait(FLock);
end;
end;
end;
finally
AtomicIncrement(FWritersNum, ReleaseFactor);
if Result and IsObjectTyp then begin
ObjPtr := @A;
GetLocalService.Refresh(ObjPtr^);
end;
if not Result then begin
CheckLeaveLock;
end;
end;
end;
function TAsyncChannel<T>.InternalWrite(const A: T;
ReleaseFactor: Integer): Boolean;
var
Contract: IContract<T>;
ObjPtr: PObject;
Ref: IGCObject;
begin
if IsObjectTyp then begin
ObjPtr := @A;
Ref := GetLocalService.Refresh(ObjPtr^);
end;
Result := False;
AtomicDecrement(FReadersNum, ReleaseFactor);
try
while not IsClosed do begin
FLock.Acquire;
if CheckDeadLock(False, True, False, False) then begin
FLock.Release;
raise GetLocalService.DeadLockExceptionClass.Create('DeadLock::TAsyncChannel<T>.Write');
end;
if FSize < FCapacity then begin
Contract := FItems[FWriteOffset];
FWriteOffset := (FWriteOffset + 1) mod FCapacity;
Inc(FSize);
Contract.Push(A, Ref);
Contract.FixCurContext;
FLock.Release;
FReadCond.Signal;
Exit(True);
end
else begin
FReadCond.Broadcast;
FWriteCond.Wait(FLock);
end;
end;
finally
AtomicIncrement(FReadersNum, ReleaseFactor);
end;
if not Result then
CheckLeaveLock;
end;
function TAsyncChannel<T>.ReadOnly: IReadOnly<T>;
begin
Result := FReadOnly;
end;
function TAsyncChannel<T>.WriteOnly: IWriteOnly<T>;
begin
Result := FWriteOnly;
end;
{ TCustomChannel<T> }
procedure TCustomChannel<T>.AccumRefs(ReadRefCount, WriteRefCount: Integer);
var
Context: NativeUInt;
OldRefCount: Integer;
begin
Context := GetContextUID;
FLock.Acquire;
if FReaders.ContainsKey(Context) then begin
OldRefCount := FReaders[Context].GetRefCount;
FReaders[Context].AddRef(ReadRefCount);
if (FReaders[Context].GetRefCount > 0) and (OldRefCount <= 0) then
AtomicIncrement(FReadersNum);
end;
if FWriters.ContainsKey(Context) then begin
OldRefCount := FWriters[Context].GetRefCount;
FWriters[Context].AddRef(WriteRefCount);
if (FWriters[Context].GetRefCount > 0) and (OldRefCount <= 0) then
AtomicIncrement(FReadersNum);
end;
FLock.Release;
end;
procedure TCustomChannel<T>.AsyncRead(const Promise: IPromise<T, TPendingError>; const ReleaseFactor: Integer);
var
Value: T;
begin
InternalAddRef(True, False);
try
SetDeadlockExceptionClass(TSoftDeadLock);
try
if InternalRead(Value, 0) then
Promise.SetResult(Value)
else
Promise.SetErrorCode(psClosed)
except
on E: TSoftDeadLock do
Promise.SetErrorCode(psDeadlock);
on E: Exception do
Promise.SetErrorCode(psException, Format('%s::%s', [E.ClassName, E.Message]));
end;
finally
InternalRelease(True, False);
end;
end;
procedure TCustomChannel<T>.AsyncWrite(const Promise: IPromise<T, TPendingError>;
const ReleaseFactor: Integer; const Value: TSmartPointer<T>);
begin
InternalAddRef(False, True);
try
SetDeadlockExceptionClass(TSoftDeadLock);
try
if InternalWrite(Value, 0) then
Promise.SetResult(Value)
else
Promise.SetErrorCode(psClosed)
except
on E: TSoftDeadLock do
Promise.SetErrorCode(psDeadlock);
on E: Exception do
Promise.SetErrorCode(psException, Format('%s::%s', [E.ClassName, E.Message]));
end;
finally
InternalRelease(False, True);
end;
end;
function TCustomChannel<T>.CheckDeadLock(const AsReader: Boolean; const AsWriter: Boolean;
const RaiseError: Boolean; const Lock: Boolean): Boolean;
begin
{$IFDEF DEBUG}
Assert(AsReader <> AsWriter);
Assert(AsReader or AsWriter);
{$ENDIF}
if IsClosed then
Exit(False);
if Lock then
FLock.Acquire;
if AsReader then begin
Result := FWritersNum < 1
end
else begin
Result := FReadersNum < 1;
end;
if Lock then
FLock.Release;
if Result and RaiseError then
raise GetLocalService.DeadLockExceptionClass.Create('DeadLock::TCustomChannel<T>');
end;
procedure TCustomChannel<T>.CheckLeaveLock;
var
Key: string;
Inst: TLeaveLockLogger;
begin
if IsClosed then begin
Key := Format('LeaveLocker_%s', [Guid]);
Inst := TLeaveLockLogger(Context(Key));
if not Assigned(Inst) then begin
Inst := TLeaveLockLogger.Create;
Context(Key, Inst);
end;
Inst.Check('LeaveLock::TCustomChannel<T>');
end;
end;
procedure TCustomChannel<T>.Close;
var
Contract: IContract<T>;
begin
FIsClosed := 1;
end;
constructor TCustomChannel<T>.Create;
var
UID: TGUID;
ti: PTypeInfo;
begin
if CreateGuid(UID) = 0 then
FGuid := GUIDToString(UID)
else
FGuid := Format('Channel.%p', [Pointer(Self)]);
ti := TypeInfo(T);
FIsObjectTyp := ti.Kind = tkClass;
if FIsObjectTyp then
GetLocalService;
FReaders := TContextHashTable.Create(2);
FWriters := TContextHashTable.Create(2);
FLock := TPasMPSpinLock.Create;
FOwnerContext := GetContextUID;
end;
destructor TCustomChannel<T>.Destroy;
begin
Context(GetLocalContextKey, nil);
FReaders.Free;
FWriters.Free;
FLock.Free;
inherited;
end;
function TCustomChannel<T>.Get: T;
begin
if not Read(Result) then
raise EChannelClosed.Create('Channel is closed');
end;
class function TCustomChannel<T>.GetContextUID: NativeUInt;
begin
if GetCurrent = nil then
Result := NativeUInt(GetCurrentHub)
else
Result := NativeUInt(GetCurrent)
end;
function TCustomChannel<T>.GetDeadlockExceptionClass: TExceptionClass;
begin
Result := GetLocalService.DeadLockExceptionClass;
if not Assigned(Result) then
Result := StdDeadLockException;
end;
function TCustomChannel<T>.GetEnumerator: TEnumerator<T>;
begin
Result := TChannelEnumerator<T>.Create(Self, 1)
end;
function TCustomChannel<T>.GetLocalService: TLocalContextService;
var
Key: string;
begin
Key := GetLocalContextKey;
Result := TLocalContextService(Context(Key));
if not Assigned(Result) then begin
Result := TLocalContextService.Create;
Context(Key, Result);
end;
end;
function TCustomChannel<T>.GetLocalContextKey: string;
begin
Result := Format('LocalGC_%s', [Guid]);
end;
function TCustomChannel<T>.GetLocalPendingKey: string;
begin
Result := Format('Pendings_%s', [Guid]);
end;
function TCustomChannel<T>.GetLocalPendings: TPendingOperations<T>;
var
Key: string;
begin
Key := GetLocalPendingKey;
Result := TPendingOperations<T>(Context(Key));
if not Assigned(Result) then begin
Result := TPendingOperations<T>.Create;
Context(Key, Result);
end;
end;
function TCustomChannel<T>.InternalAddRef(const AsReader, AsWriter: Boolean): Integer;
var
Context: NativeUInt;
begin
Context := GetContextUID;
FLock.Acquire;
Inc(FRefCount);
Result := FRefCount;
if AsReader then begin
if FReaders.ContainsKey(Context) then
FReaders[Context].AddRef
else begin
FReaders.Add(Context, TContextRef.Create(True, Context = FOwnerContext));
AtomicIncrement(FReadersNum);
end;
end;
if AsWriter then begin
if FWriters.ContainsKey(Context) then
FWriters[Context].AddRef
else begin
FWriters.Add(Context, TContextRef.Create(True, Context = FOwnerContext));
AtomicIncrement(FWritersNum);
end;
end;
FLock.Release;
end;
function TCustomChannel<T>.InternalRelease(const AsReader, AsWriter: Boolean): Integer;
var
Context: NativeUInt;
DeadLock: Boolean;
begin
DeadLock := False;
Context := GetContextUID;
FLock.Acquire;
Dec(FRefCount);
Result := FRefCount;
if AsReader and FReaders.ContainsKey(Context) then begin
if FReaders[Context].Release = 0 then begin
AtomicDecrement(FReadersNum);
FReaders.Remove(Context);
end;
end;
if AsWriter and FWriters.ContainsKey(Context) then begin
if FWriters[Context].Release = 0 then begin
AtomicDecrement(FWritersNum);
FWriters.Remove(Context);
end;
end;
DeadLock := CheckDeadLock(False, True, False, False) or CheckDeadLock(True, False, False, False);
FLock.Release;
if DeadLock then
BroadcastAll(smForceAsync);
if Result = 0 then
Destroy;
end;
function TCustomChannel<T>.IsClosed: Boolean;
begin
Result := FIsClosed = 1;
end;
function TCustomChannel<T>.Read(out A: T): Boolean;
begin
Result := InternalRead(A, 1);
if not Result then
A := FDefValue
end;
function TCustomChannel<T>.ReadPending: IFuture<T, TPendingError>;
var
AsyncReader: TSymmetric<IPromise<T, TPendingError>, Integer>;
FP: TFuturePromise<T, TPendingError>;
Pending: TPendingOperations<T>;
Index: Integer;
begin
Pending := GetLocalPendings;
Result := Pending.ReaderFuture;
if Assigned(Result) and (Select([Result.OnFullFilled, Result.OnRejected], Index, 0) = wrTimeout) then
Exit;
AsyncReader := TSymmetric<IPromise<T, TPendingError>, Integer>.Spawn(AsyncRead, FP.Promise, 1);
Result := FP.Future;
Pending.PendingReader := AsyncReader;
Pending.ReaderFuture := Result;
end;
procedure TCustomChannel<T>.ReleaseRefs(ReadRefCount, WriteRefCount: Integer);
var
Context: NativeUInt;
OldRefCount: Integer;
DeadLock: Boolean;
begin
Context := GetContextUID;
FLock.Acquire;
if FReaders.ContainsKey(Context) then begin
OldRefCount := FReaders[Context].GetRefCount;
FReaders[Context].Release(ReadRefCount);
if (FReaders[Context].GetRefCount <= 0) and (OldRefCount > 0) then
AtomicDecrement(FReadersNum)
end;
if FWriters.ContainsKey(Context) then begin
OldRefCount := FWriters[Context].GetRefCount;
FWriters[Context].Release(WriteRefCount);
if (FWriters[Context].GetRefCount <= 0) and (OldRefCount > 0) then
AtomicDecrement(FWritersNum)
end;
DeadLock := CheckDeadLock(False, True, False, False) or CheckDeadLock(True, False, False, False);
FLock.Release;
if DeadLock then
BroadcastAll(smForceAsync);
end;
procedure TCustomChannel<T>.SetDeadlockExceptionClass(Cls: TExceptionClass);
begin
GetLocalService.DeadLockExceptionClass := Cls
end;
function TCustomChannel<T>.Write(const A: T): Boolean;
begin
Result := InternalWrite(A, 1);
end;
function TCustomChannel<T>.WritePending(const A: T): IFuture<T, TPendingError>;
var
AsyncWriter: TSymmetric<IPromise<T, TPendingError>, Integer, TSmartPointer<T>>;
FP: TFuturePromise<T, TPendingError>;
SmartValue: TSmartPointer<T>;
Pending: TPendingOperations<T>;
Index: Integer;
begin
Pending := GetLocalPendings;
Result := Pending.WriterFuture;
if Assigned(Result) and (Select([Result.OnFullFilled, Result.OnRejected], Index, 0) = wrTimeout) then
Exit;
SmartValue := A;
AsyncWriter := TSymmetric<IPromise<T, TPendingError>, Integer, TSmartPointer<T>>
.Spawn(AsyncWrite, FP.Promise, 1, SmartValue);
Result := FP.Future;
Pending.PendingWriter := AsyncWriter;
Pending.WriterFuture := Result;
end;
function TCustomChannel<T>._AddRef: Integer;
begin
Result := InternalAddRef(True, True);
end;
function TCustomChannel<T>._Release: Integer;
begin
Result := InternalRelease(True, True)
end;
{ TReadOnlyChannel<T> }
procedure TReadOnlyChannel<T>.AccumRefs(ReadRefCount, WriteRefCount: Integer);
begin
FParent.AccumRefs(ReadRefCount, WriteRefCount)
end;
procedure TReadOnlyChannel<T>.Close;
begin
FParent.Close;
end;
constructor TReadOnlyChannel<T>.Create(Parent: TCustomChannel<T>);
begin
FParent := Parent;
end;
function TReadOnlyChannel<T>.Get: T;
begin
Result := FPArent.Get
end;
function TReadOnlyChannel<T>.GetBufSize: LongWord;
begin
Result := FParent.GetBufSize
end;
function TReadOnlyChannel<T>.GetDeadlockExceptionClass: TExceptionClass;
begin
Result := FParent.GetDeadlockExceptionClass
end;
function TReadOnlyChannel<T>.GetEnumerator: TEnumerator<T>;
begin
Result := TChannelEnumerator<T>.Create(FParent, 0)
end;
function TReadOnlyChannel<T>.IsClosed: Boolean;
begin
Result := FParent.IsClosed
end;
function TReadOnlyChannel<T>.Read(out A: T): Boolean;
begin
Result := FParent.InternalRead(A, 0);
if not Result then
A := FParent.FDefValue;
end;
function TReadOnlyChannel<T>.ReadPending: IFuture<T, TPendingError>;
begin
Result := FParent.ReadPending;
end;
procedure TReadOnlyChannel<T>.ReleaseRefs(ReadRefCount, WriteRefCount: Integer);
begin
FPArent.ReleaseRefs(ReadRefCount, WriteRefCount)
end;
procedure TReadOnlyChannel<T>.SetDeadlockExceptionClass(Cls: TExceptionClass);
begin
FParent.SetDeadlockExceptionClass(Cls)
end;
function TReadOnlyChannel<T>._AddRef: Integer;
begin
Result := FParent.InternalAddRef(True, False);
end;
function TReadOnlyChannel<T>._Release: Integer;
begin
Result := FParent.InternalRelease(True, False);
end;
{ TWriteOnlyChannel<T> }
procedure TWriteOnlyChannel<T>.AccumRefs(ReadRefCount, WriteRefCount: Integer);
begin
FParent.AccumRefs(ReadRefCount, WriteRefCount);
end;
procedure TWriteOnlyChannel<T>.Close;
begin
FParent.Close
end;
constructor TWriteOnlyChannel<T>.Create(Parent: TCustomChannel<T>);
begin
FParent := Parent;
end;
function TWriteOnlyChannel<T>.GetBufSize: LongWord;
begin
Result := FParent.GetBufSize
end;
function TWriteOnlyChannel<T>.GetDeadlockExceptionClass: TExceptionClass;
begin
Result := FParent.GetDeadlockExceptionClass
end;
function TWriteOnlyChannel<T>.IsClosed: Boolean;
begin
Result := FParent.IsClosed
end;
procedure TWriteOnlyChannel<T>.ReleaseRefs(ReadRefCount, WriteRefCount: Integer);
begin
FParent.ReleaseRefs(ReadRefCount, WriteRefCount);
end;
procedure TWriteOnlyChannel<T>.SetDeadlockExceptionClass(Cls: TExceptionClass);
begin
FParent.SetDeadlockExceptionClass(Cls)
end;
function TWriteOnlyChannel<T>.Write(const A: T): Boolean;
begin
Result := FParent.InternalWrite(A, 0);
end;
function TWriteOnlyChannel<T>.WritePending(
const A: T): IFuture<T, TPendingError>;
begin
Result := FParent.WritePending(A);
end;
function TWriteOnlyChannel<T>._AddRef: Integer;
begin
Result := FParent.InternalAddRef(False, True)
end;
function TWriteOnlyChannel<T>._Release: Integer;
begin
Result := FParent.InternalRelease(False, True)
end;
{ TChannelEnumerator<T> }
constructor TChannelEnumerator<T>.Create(Channel: TCustomChannel<T>;
ReleaseFator: Integer);
begin
FChannel := Channel;
FReleaseFactor := ReleaseFator;
end;
function TChannelEnumerator<T>.GetCurrent: T;
begin
Result := FCurrent;
end;
function TChannelEnumerator<T>.MoveNext: Boolean;
begin
Result := FChannel.InternalRead(FCurrent, FReleaseFactor)
end;
procedure TChannelEnumerator<T>.Reset;
begin
// nothing
end;
{ TContractImpl }
constructor TAbstractContractImpl.Create;
begin
FLock := TPasMPSpinLock.Create;
Inherited;
end;
destructor TAbstractContractImpl.Destroy;
begin
FLock.Free;
inherited;
end;
procedure TAbstractContractImpl.FixCurContext;
begin
FContext := GetCurrent;
FHub := _GetCurentHub;
end;
function TAbstractContractImpl.IsMyCtx: Boolean;
begin
Result := (GetCurrent = FContext) and (FHub = _GetCurentHub)
end;
procedure TAbstractContractImpl.Lock;
begin
FLock.Acquire;
end;
procedure TAbstractContractImpl.Unlock;
begin
FLock.Release;
end;
{ TContractImpl<T> }
constructor TContractImpl<T>.Create;
begin
FIsEmpty := True;
Inherited;
end;
destructor TContractImpl<T>.Destroy;
begin
inherited;
end;
function TContractImpl<T>.IsEmpty: Boolean;
begin
Result := FIsEmpty;
end;
function TContractImpl<T>.Pop(out A: T; out Ref: IGCObject): Boolean;
begin
if FIsEmpty then begin
A := FDefValue;
Result := False;
end
else begin
A := FValue;
Ref := FSmartObj;
FSmartObj := nil;
FIsEmpty := True;
Result := True;
end;
end;
function TContractImpl<T>.Push(const A: T; Ref: IGCObject): Boolean;
begin
if FIsEmpty then begin
FValue := A;
FSmartObj := Ref;
FIsEmpty := False;
Result := True;
end
else
Result := False;
end;
{ TLightGevent }
procedure TLightGevent.Associate(Other: ILightGevent; Index: Integer);
begin
Lock;
FAssociate := Other;
FAssociateIndex := Index;
Unlock;
end;
constructor TLightGevent.Create;
begin
FIndex := -1;
FAssociateIndex := -1;
FLock := TPasMPSpinLock.Create;
FContext := GetCurrent;
FHub := GetCurrentHub;
if Assigned(FContext) then
FWaitEventRoutine := GreenletWaitEvent
else
FWaitEventRoutine := ThreadedWaitEvent;
inherited;
end;
destructor TLightGevent.Destroy;
begin
FLock.Free;
inherited;
end;
function TLightGevent.GetContext: Pointer;
begin
Result := FContext
end;
function TLightGevent.GetIndex: Integer;
begin
Lock;
Result := FIndex;
Unlock;
end;
function TLightGevent.GetInstance: Pointer;
begin
Result := Self
end;
procedure TLightGevent.GreenletWaitEvent;
begin
while not FSignal do begin
TRawGreenletImpl(FContext).Suspend;
Greenlets.Yield;
end;
TRawGreenletImpl(FContext).Resume;
end;
procedure TLightGevent.Lock;
begin
FLock.Acquire;
end;
procedure TLightGevent.SetEvent(const Async: Boolean);
var
CurHub: TCustomHub;
begin
CurHub := _GetCurentHub;
Lock;
try
FSignal := True;
if not FWaiting then
Exit;
if Assigned(FAssociate) and (FAssociate.GetIndex = -1) then begin
FAssociate.SetIndex(FAssociateIndex);
FAssociate.SetEvent(True);
end;
finally
Unlock;
end;
if (GetCurrent = FContext) and (FHub = GetCurrentHub) then
Exit;
if Assigned(FContext) then begin
// TODO: the call to GetCurrentHub is expensive. If you remove the speed will increase in 1.5-2 times
if (FHub = CurHub) and (not Async) then begin
TRawGreenletPImpl(FContext).SetState(gsExecute);
TRawGreenletPImpl(FContext).Switch
end
else
TRawGreenletPImpl(FContext).GetProxy.Resume
end
else begin
{if (FHub = CurHub) and (not Async) then begin
FHub.Switch
end
else }
FHub.Pulse
end;
end;
procedure TLightGevent.SetIndex(Value: Integer);
begin
Lock;
if (FIndex = -1) and (Value <> -1) then
FIndex := Value;
Unlock;
end;
procedure TLightGevent.ThreadedWaitEvent;
begin
FHub.IsSuspended := True;
try
while not FSignal do begin
Greenlets.Yield;
end;
finally
FHub.IsSuspended := False;
end;
end;
procedure TLightGevent.Unlock;
begin
FLock.Release
end;
procedure TLightGevent.WaitEvent;
begin
{$IFDEF DEBUG}
Assert(GetCurrent = FContext, 'TLightGevent.WaitEvent context error');
{$ENDIF}
Lock;
if FSignal then begin
FSignal := False;
Unlock;
end
else begin
FWaiting := True;
Unlock;
try
FWaitEventRoutine;
Lock;
FSignal := False;
Unlock;
finally
Lock;
FWaiting := False;
Unlock;
end;
end;
end;
{ TSingleThreadSyncChannel<T> }
procedure TSingleThreadSyncChannel<T>.Assign(Source: TMultiThreadSyncChannel<T>);
var
A: T;
Ref: IGCObject;
begin
Source.Lock.Acquire;
try
if Source.ContractExists then begin
if Self.FContractExists then begin
if Assigned(Source.Notify) then begin
if Source.Contract.IsEmpty then
Self.FReadCond.Enqueue(TLightGevent(Source.Notify.GetInstance))
else
Self.FWriteCond.Enqueue(TLightGevent(Source.Notify.GetInstance));
Source.Notify := nil;
end;
end
else begin
Self.FContractExists := True;
Self.FContract.IsEmpty := not Source.Contract.Pop(A, Ref);
if not Self.FContract.IsEmpty then begin
Self.FContract.Value := A;
end;
if Assigned(Source.Notify) then
Self.FContract.Contragent := Source.Notify.GetContext
else
Self.FContract.Contragent := nil
end;
end;
Source.ContractExists := False;
Self.FReadCond.Assign(Source.ReadCond);
Self.FWriteCond.Assign(Source.WriteCond);
finally
Source.Lock.Release
end;
end;
procedure TSingleThreadSyncChannel<T>.BroadcastAll(const Method: TLightCondVar.TSyncMethod);
begin
FReadCond.Broadcast(Method);
FWriteCond.Broadcast(Method);
end;
procedure TSingleThreadSyncChannel<T>.Close;
begin
FIsClosed := True;
FReadCond.Broadcast;
FWriteCond.Broadcast;
if FContractExists then
TRawGreenletImpl(FContract.Contragent).Switch;
end;
constructor TSingleThreadSyncChannel<T>.Create(const IsObjectTyp: Boolean;
const OnGetLocalGC: TOnGetLocalService;
const OnCheckDeadLock: TOnCheckDeadLock;
WNumPtr, RNumPtr: PInteger);
begin
FIsObjectTyp := IsObjectTyp;
FOnGetLocalService := OnGetLocalGC;
FOnCheckDeadLock := OnCheckDeadLock;
FWritersNumPtr := WNumPtr;
FReadersNumPtr := RNumPtr;
FContract.IsEmpty := True;
FReadCond := TLightCondVar.Create(False, False);
FWriteCond := TLightCondVar.Create(False, False);
FHub := GetCurrentHub;
end;
destructor TSingleThreadSyncChannel<T>.Destroy;
begin
FReadCond.Free;
FWriteCond.Free;
inherited;
end;
function TSingleThreadSyncChannel<T>.Read(out A: T; ReleaseFactor: Integer): Boolean;
var
Counter: Integer;
ObjPtr: PObject;
Ref: IGCObject;
begin
Result := False;
AtomicDecrement(FWritersNumPtr^, ReleaseFactor);
try
while True do begin
if FContractExists then begin
if not FContract.IsEmpty then begin
A := FContract.Value;
Ref := FContract.PullSmartObj;
FContract.IsEmpty := True;
if Assigned(FContract.Contragent) then begin
with TRawGreenletImpl(FContract.Contragent) do begin
if GetState = gsExecute then
Switch
else
FWriteCond.Signal
end;
end
else begin
TRawGreenletImpl(GetCurrent).GetProxy.DelayedSwitch;
FWriteCond.Signal;
FHub.Switch;
end;
Exit(True);
end
else begin
FWriteCond.Signal;
if FContractExists and FContract.IsEmpty then begin
if FOnCheckDeadLock(True, False, False, False) then begin
raise FOnGetLocalService.DeadLockExceptionClass.Create('DeadLock::TSyncChannel<T>.Read');
end
else begin
FReadCond.Wait;
end;
end;
end;
end
else begin
FContractExists := True;
FContract.IsEmpty := True;
FContract.Contragent := TRawGreenletImpl(GetCurrent);
try
Counter := 1;
while FContract.IsEmpty do begin
if FIsClosed then
Exit(False);
if Counter > YIELD_WAIT_CNT then begin
if FOnCheckDeadLock(True, False, False, False) then begin
raise FOnGetLocalService.DeadLockExceptionClass.Create('DeadLock::TSyncChannel<T>.Read');
end;
FReadCond.Wait;
end
else begin
Inc(Counter);
Greenlets.Yield;
end;
end;
if not FContract.IsEmpty then begin
A := FContract.Value;
Ref := FContract.PullSmartObj;
Exit(True)
end;
finally
FContract.Contragent := nil;
FContractExists := False;
end;
end;
end;
finally
AtomicIncrement(FWritersNumPtr^, ReleaseFactor);
if Result and FIsObjectTyp then begin
ObjPtr := @A;
FOnGetLocalService.Refresh(ObjPtr^);
end;
end;
end;
function TSingleThreadSyncChannel<T>.Write(const A: T; ReleaseFactor: Integer): Boolean;
var
Counter: Integer;
ObjPtr: PObject;
Ref: IGCObject;
begin
if FIsObjectTyp then begin
ObjPtr := @A;
Ref := FOnGetLocalService.Refresh(ObjPtr^);
end;
Result := False;
AtomicDecrement(FReadersNumPtr^, ReleaseFactor);
try
while not FIsClosed do begin
if FOnCheckDeadLock(False, True, False, False) then begin
raise FOnGetLocalService.DeadLockExceptionClass.Create('DeadLock::TSyncChannel<T>.Write');
end;
if FContractExists then begin
if FContract.IsEmpty then begin
FContract.Value := A;
FContract.PushSmartObj(Ref);
FContract.IsEmpty := False;
if Assigned(FContract.Contragent) then begin
with TRawGreenletImpl(FContract.Contragent) do begin
if GetState = gsExecute then
TRawGreenletImpl(FContract.Contragent).Switch
else
FReadCond.Signal
end;
end
else begin
TRawGreenletImpl(GetCurrent).GetProxy.DelayedSwitch;
FReadCond.Signal;
FHub.Switch;
end;
Exit(True);
end
else begin
FReadCond.Signal;
if FContractExists and (not FContract.IsEmpty) then
FWriteCond.Wait;
end;
end
else begin
FContractExists := True;
FContract.IsEmpty := False;
FContract.Value := A;
FContract.PushSmartObj(Ref);
FContract.Contragent := TRawGreenletImpl(GetCurrent);
try
Counter := 1;
while not FContract.IsEmpty do begin
if FIsClosed then
Exit(False);
if Counter > YIELD_WAIT_CNT then begin
FWriteCond.Wait;
end
else begin
Inc(Counter);
Greenlets.Yield;
end;
end;
if FContract.IsEmpty then begin
Exit(True)
end
finally
FContract.Contragent := nil;
FContractExists := False;
end;
end;
end;
finally
AtomicIncrement(FReadersNumPtr^, ReleaseFactor);
end;
end;
{ TMultiThreadSyncChannel<T> }
procedure TMultiThreadSyncChannel<T>.BroadcastAll(const Method: TLightCondVar.TSyncMethod);
begin
FLock.Acquire;
if FContractExists then
FNotify.SetEvent(True);
FLock.Release;
FReadCond.Broadcast(Method);
FWriteCond.Broadcast(Method);
end;
procedure TMultiThreadSyncChannel<T>.Close;
var
Notify: ILightGevent;
begin
FLock.Acquire;
FIsClosed := True;
FLock.Release;
FReadCond.Broadcast(smForceAsync);
FWriteCond.Broadcast(smForceAsync);
FLock.Acquire;
if Assigned(FNotify) then
FNotify.SetEvent(True);
FLock.Release;
end;
constructor TMultiThreadSyncChannel<T>.Create(const IsObjectTyp: Boolean;
const OnGetLocalGC: TOnGetLocalService;
const OnCheckDeadLock: TOnCheckDeadLock;
WNumPtr, RNumPtr: PInteger);
begin
FIsObjectTyp := IsObjectTyp;
FOnGetLocalService := OnGetLocalGC;
FOnCheckDeadLock := OnCheckDeadLock;
FWritersNumPtr := WNumPtr;
FReadersNumPtr := RNumPtr;
FLock := TPasMPSpinLock.Create;
FReadCond := TLightCondVar.Create(False, True);
FWriteCond := TLightCondVar.Create(False, True);
FContract := TContractImpl<T>.Create;
end;
destructor TMultiThreadSyncChannel<T>.Destroy;
begin
FLock.Free;
FReadCond.Free;
FWriteCond.Free;
inherited;
end;
function TMultiThreadSyncChannel<T>.Read(out A: T; ReleaseFactor: Integer): Boolean;
var
Ref: IGCObject;
ObjPtr: PObject;
begin
Result := False;
AtomicDecrement(FWritersNumPtr^, ReleaseFactor);
try
while True do begin
FLock.Acquire;
if FContractExists then begin
if not FContract.IsEmpty and FContract.Pop(A, Ref) then begin
FLock.Release;
FNotify.SetEvent;
Exit(True)
end
else begin
if FIsClosed then begin
FLock.Release;
Exit(False)
end
else begin
if FOnCheckDeadLock(True, False, False) then begin
FLock.Release;
raise FOnGetLocalService.DeadLockExceptionClass.Create('DeadLock::TSyncChannel<T>.Read');
end
else begin
FWriteCond.Signal;
FReadCond.Wait(FLock);
end;
end;
end;
end
else begin
if FIsClosed then begin
FLock.Release;
Exit(False);
end;
if FOnCheckDeadLock(True, False, False) then begin
FLock.Release;
raise FOnGetLocalService.DeadLockExceptionClass.Create('DeadLock::TSyncChannel<T>.Read');
end;
FContractExists := True;
if FContract.IsEmpty then begin
FNotify := TLightGevent.Create;
FLock.Release;
FWriteCond.Signal;
FNotify.WaitEvent;
FLock.Acquire;
if FOnCheckDeadLock(True, False, False, False) then begin
FLock.Release;
raise FOnGetLocalService.DeadLockExceptionClass.Create('DeadLock::TSyncChannel<T>.Read');
end;
FContractExists := False;
if FContract.Pop(A, Ref) then begin
FLock.Release;
Exit(True);
end
else begin
if FIsClosed then begin
FLock.Release;
Exit(False);
end
else begin
FWriteCond.Signal;
FReadCond.Wait(FLock);
end;
end;
end
else begin
FContractExists := False;
FWriteCond.Signal;
FReadCond.Wait(FLock);
end;
end;
end;
finally
AtomicIncrement(FWritersNumPtr^, ReleaseFactor);
if Result and FIsObjectTyp then begin
ObjPtr := @A;
FOnGetLocalService.Refresh(ObjPtr^);
end;
end;
end;
function TMultiThreadSyncChannel<T>.Write(const A: T; ReleaseFactor: Integer): Boolean;
var
Ref: IGCObject;
ObjPtr: PObject;
Cls: TExceptionClass;
begin
if FIsObjectTyp then begin
ObjPtr := @A;
Ref := FOnGetLocalService.Refresh(ObjPtr^);
end;
Result := False;
AtomicDecrement(FReadersNumPtr^, ReleaseFactor);
try
while not FIsClosed do begin
FLock.Acquire;
if FOnCheckDeadLock(False, True, False) then begin
FLock.Release;
raise FOnGetLocalService.DeadLockExceptionClass.Create('DeadLock::TSyncChannel<T>.Write');
end;
if FContractExists then begin
if FContract.IsEmpty and FContract.Push(A, Ref) then begin
FLock.Release;
FNotify.SetEvent;
Exit(True)
end
else begin
FReadCond.Signal;
FWriteCond.Wait(FLock);
end;
end
else begin
FContractExists := True;
if FContract.Push(A, Ref) then begin
FNotify := TLightGevent.Create;
FLock.Release;
FReadCond.Signal;
FNotify.WaitEvent;
FLock.Acquire;
FContractExists := False;
FLock.Release;
Exit(True);
end
else begin
FContractExists := False;
FReadCond.Signal;
FWriteCond.Wait(FLock);
end;
end;
end;
finally
AtomicIncrement(FReadersNumPtr^, ReleaseFactor)
end;
end;
{ TLightCondVar }
procedure TLightCondVar.Assign(Source: TLightCondVar);
var
I: Integer;
begin
if Assigned(FLock) then
FLock.Acquire;
try
if Assigned(Source.FLock) then
Source.FLock.Acquire;
try
for I := 0 to Source.FItems.Count-1 do
Self.FItems.Add(Source.FItems[I]);
Source.FItems.Clear;
finally
if Assigned(Source.FLock) then
Source.FLock.Release;
end;
finally
if Assigned(FLock) then
FLock.Release;
end;
end;
procedure TLightCondVar.Broadcast(const Method: TSyncMethod);
begin
FBroadcastRoutine(Method)
end;
procedure TLightCondVar.Clean;
var
I: Integer;
begin
if Assigned(FLock) then
FLock.Acquire;
try
for I := 0 to FItems.Count-1 do
TLightGevent(FItems[I])._Release;
FItems.Clear;
finally
if Assigned(FLock) then
FLock.Release;
end;
end;
constructor TLightCondVar.Create(const Async: Boolean; const Locked: Boolean);
begin
FAsync := Async;
FItems := TList.Create;
if Locked then begin
FLock := TPasMPSpinLock.Create;
FWaitRoutine := LockedWait;
FSignalRoutine := LockedSignal;
FBroadcastRoutine := LockedBroadcast;
end
else begin
FWaitRoutine := UnLockedWait;
FSignalRoutine := UnLockedSignal;
FBroadcastRoutine := UnLockedBroadcast;
end;
end;
function TLightCondVar.Dequeue(out E: TLightGevent): Boolean;
begin
Result := FItems.Count > 0;
if Result then begin
E := TLightGevent(FItems[0]);
FItems.Delete(0);
end;
end;
destructor TLightCondVar.Destroy;
begin
Clean;
FItems.Free;
if Assigned(FLock) then
FLock.Free;
inherited;
end;
procedure TLightCondVar.Enqueue(E: TLightGevent);
begin
FItems.Add(E);
E._AddRef;
end;
procedure TLightCondVar.Lock;
begin
if Assigned(FLock) then
FLock.Acquire
end;
procedure TLightCondVar.LockedBroadcast(const Method: TSyncMethod);
var
E: TLightGevent;
function _Dequeue(out E: TLightGevent): Boolean;
begin
FLock.Acquire;
Result := Dequeue(E);
FLock.Release;
end;
begin
while _Dequeue(E) do
try
case Method of
smDefault:
E.SetEvent(FAsync);
smForceAsync:
E.SetEvent(True);
smForceSync:
E.SetEvent(False);
end;
finally
E._Release;
end;
end;
procedure TLightCondVar.LockedSignal(const Method: TSyncMethod);
var
E: TLightGevent;
function _Dequeue(out E: TLightGevent): Boolean;
begin
FLock.Acquire;
Result := Dequeue(E);
FLock.Release;
end;
begin
if _Dequeue(E) then
try
case Method of
smDefault:
E.SetEvent(FAsync);
smForceAsync:
E.SetEvent(True);
smForceSync:
E.SetEvent(False);
end;
finally
E._Release;
end;
end;
procedure TLightCondVar.LockedWait(Unlocking: TPasMPSpinLock);
var
E: TLightGevent;
begin
E := TLightGevent.Create;
E._AddRef;
try
FLock.Acquire;
Enqueue(E);
FLock.Release;
if Assigned(Unlocking) then
Unlocking.Release;
E.WaitEvent;
finally
E._Release
end;
end;
procedure TLightCondVar.Signal(const Method: TSyncMethod);
begin
FSignalRoutine(Method)
end;
procedure TLightCondVar.Unlock;
begin
if Assigned(FLock) then
FLock.Release
end;
procedure TLightCondVar.UnLockedBroadcast(const Method: TSyncMethod);
var
E: TLightGevent;
begin
while Dequeue(E) do
try
case Method of
smDefault:
E.SetEvent(FAsync);
smForceAsync:
E.SetEvent(True);
smForceSync:
E.SetEvent(False);
end;
finally
E._Release;
end;
end;
procedure TLightCondVar.UnLockedSignal(const Method: TSyncMethod);
var
E: TLightGevent;
begin
if Dequeue(E) then
try
case Method of
smDefault:
E.SetEvent(FAsync);
smForceAsync:
E.SetEvent(True);
smForceSync:
E.SetEvent(False);
end;
finally
E._Release;
end;
end;
procedure TLightCondVar.UnLockedWait(Unlocking: TPasMPSpinLock);
var
E: TLightGevent;
begin
E := TLightGevent.Create;
E._AddRef;
try
Enqueue(E);
if Assigned(Unlocking) then
Unlocking.Release;
E.WaitEvent;
finally
E._Release
end;
end;
procedure TLightCondVar.Wait(Unlocking: TPasMPSpinLock);
begin
FWaitRoutine(Unlocking)
end;
{ TLocalContextService }
function TLocalContextService.GetDeadLockExceptionClass: TExceptionClass;
begin
Result := FDeadLockExceptionClass;
if not Assigned(Result) then
Result := StdDeadLockException;
end;
function TLocalContextService.Refresh(A: TObject): IGCObject;
begin
FRef := Greenlets.GC(A);
Result := FRef;
end;
{ TLeaveLockLogger }
procedure TLeaveLockLogger.Check(const Msg: string);
begin
Inc(FCounter);
if FCounter >= MAX_COUNT_FACTOR then
raise StdLeaveLockException.Create(Msg);
end;
{ TSingleThreadSyncChannel<T>.TContract }
function TSingleThreadSyncChannel<T>.TContract.PullSmartObj: IGCObject;
begin
Result := SmartObj;
SmartObj := nil;
end;
procedure TSingleThreadSyncChannel<T>.TContract.PushSmartObj(
Value: IGCObject);
begin
SmartObj := Value
end;
{ TFanOutImpl<T> }
constructor TFanOutImpl<T>.Create(Input: IReadOnly<T>);
begin
FLock := TCriticalSection.Create;
FInflateList := TList<TChannelDescr>.Create;
FOnUpdated := TGevent.Create;
FBufSize := Input.GetBufSize;
FWorkerCtxReady := TGevent.Create(True);
FWorker := TSymmetric<IReadChannel>.Spawn(Routine, Input);
FWorkerCtxReady.WaitFor;
end;
destructor TFanOutImpl<T>.Destroy;
var
Descr: TChannelDescr;
begin
FLock.Acquire;
for Descr in FInflateList do
Descr.Token.Deactivate;
FLock.Release;
FWorker.Kill;
FInflateList.Free;
FWorkerCtxReady.Free;
FLock.Free;
FOnUpdated.Free;
inherited;
end;
procedure TFanOutImpl<T>.DieCb(ID: Integer);
var
Descr: TChannelDescr;
Index: Integer;
begin
FLock.Acquire;
try
Index := 0;
while Index < FInflateList.Count do begin
Descr := FInflateList[Index];
if Descr.ID = ID then begin
Descr.Channel.Close;
end;
_Release;
Inc(Index);
end;
finally
FLock.Release
end;
end;
function TFanOutImpl<T>.GenerateID: Integer;
begin
FLock.Acquire;
Inc(FLastID);
Result := FLastID;
FLock.Release;
end;
function TFanOutImpl<T>.Inflate(const BufSize: Integer): IReadOnly<T>;
var
Descr: TChannelDescr;
ChanBufSz: LongWord;
begin
Descr.SyncImpl := nil;
Descr.AsyncImpl := nil;
Descr.ID := GenerateID;
Descr.Token := TLiveTokenImpl.Create(Descr.ID, DieCb);
if BufSize < 0 then
ChanBufSz := FBufSize
else
ChanBufSz := BufSize;
if ChanBufSz = 0 then begin
Descr.SyncImpl := TSyncChannel<T>.Create(True);
Descr.SyncImpl.FLiveToken := Descr.Token;
Descr.Channel := Descr.SyncImpl;
end
else begin
Descr.AsyncImpl := TAsyncChannel<T>.Create(ChanBufSz);
Descr.AsyncImpl.FLiveToken := Descr.Token;
Descr.Channel := Descr.AsyncImpl;
end;
Inc(Descr.Channel.FWritersNum);
Descr.Channel.FWriters.Add(FWorkerContext, TContextRef.Create(True, True));
//(False, True) -> error at form
Descr.Channel.Freaders.Add(Descr.Channel.FOwnerContext, TContextRef.Create(True, True));
FLock.Acquire;
try
FInflateList.Add(Descr);
_AddRef;
if ChanBufSz = 0 then
Result := Descr.SyncImpl.ReadOnly
else
Result := Descr.AsyncImpl.ReadOnly;
finally
FLock.Release;
end;
FOnUpdated.SetEvent(False);
end;
procedure TFanOutImpl<T>.Routine(const Input: IReadOnly<T>);
var
Data: T;
Index, ChanCount: Integer;
begin
FWorkerContext := TCustomChannel<T>.GetContextUID;
FWorkerCtxReady.SetEvent;
try
FOnUpdated.WaitFor;
for Data in Input do begin
FLock.Acquire;
try
Index := 0;
ChanCount := FInflateList.Count;
while Index < FInflateList.Count do begin
with FInflateList[Index] do begin
if not Channel.IsClosed and Token.IsLive then begin
try
Channel.SetDeadlockExceptionClass(TSoftDeadLock);
if Channel.InternalWrite(Data, 0) then
Inc(Index)
else begin
FInflateList.Delete(Index);
Dec(ChanCount);
end;
except
on E: TSoftDeadLock do begin
Channel.Close;
end;
on E: EChannelDeadLock do begin
Channel.Close;
end;
on E: EChannelLeaveLock do begin
Channel.Close;
end;
end;
end
else begin
FInflateList.Delete(Index);
Dec(ChanCount);
end
end;
end;
finally
FLock.Release;
end;
while ChanCount = 0 do begin
FOnUpdated.WaitFor;
FLock.Acquire;
ChanCount := FInflateList.Count;
FLock.Release;
end;
end;
finally
FLock.Acquire;
try
for Index := 0 to FInflateList.Count-1 do
FInflateList[Index].Channel.Close;
finally
FLock.Release;
end;
end;
end;
{ TLiveTokenImpl }
constructor TLiveTokenImpl.Create(ID: Integer; const Cb: TOnDieEvent);
begin
FID := ID;
FIsLive := True;
FCb := Cb;
FLock := TCriticalSection.Create;
end;
function TLiveTokenImpl.IsLive: Boolean;
begin
Result := FIsLive
end;
procedure TLiveTokenImpl.Deactivate;
begin
FLock.Acquire;
FCb := nil;
FLock.Release;
end;
destructor TLiveTokenImpl.Destroy;
begin
FLock.Free;
inherited;
end;
procedure TLiveTokenImpl.Die;
begin
FLock.Acquire;
try
if Assigned(FCb) and FIsLive then begin
FIsLive := False;
FCb(Self.FID)
end;
finally
FLock.Release;
end;
end;
{ TContextRef }
function TContextRef.AddRef(Accum: Integer): Integer;
begin
Inc(FRefCount, Accum);
Result := FRefCount;
end;
constructor TContextRef.Create(const Active: Boolean; const IsOwnerContext: Boolean);
begin
FActive := Active;
if Active then
FRefCount := 1
else
FRefCount := 0;
FIsOwner := IsOwnerContext;
if FIsOwner then begin
//FOwnerToggle := True;
//FRefCount := 0;
end;
end;
function TContextRef.GetActive: Boolean;
begin
Result := FActive
end;
function TContextRef.GetRefCount: Integer;
begin
Result := FRefCount
end;
function TContextRef.Release(Accum: Integer): Integer;
begin
Dec(FRefCount, Accum);
Result := FRefCount;
end;
procedure TContextRef.SetActive(const Value: Boolean);
begin
FActive := Value
end;
{ TCustomChannel<T>.TPendingOperations<T> }
destructor TCustomChannel<T>.TPendingOperations<Y>.Destroy;
begin
if Assigned(FPendingReader) then begin
FPendingReader.Kill;
FPendingReader := nil;
end;
if Assigned(FPendingWriter) then begin
FPendingWriter.Kill;
FPendingWriter := nil;
end;
FReaderFuture := nil;
FWriterFuture := nil;
inherited;
end;
initialization
StdDeadLockException := EChannelDeadLock;
StdLeaveLockException := EChannelLeaveLock;
end.
|
unit UConsoleSDK;
interface
uses
windows,WinSock,GD_Utils,UNgPlugConfig,UConsoleProtocol;
type
TConsoleNet = class
private
mToken:INT64;
mActive:Bool;
mPid:Cardinal;
mIp:String;
mPort:Integer;
mSocket:Cardinal;
mGameVersion:Integer;
Function ConnConsole():Bool;
function GetToken:Cardinal;
public
constructor Create(_Ip:string;_Port:Integer;_Pid:Cardinal);
Function RequestGameAddress(_TagId:Integer):Cardinal;
property Active:Bool read mActive;
property Token:Int64 read mToken;
property GameVersion:Integer read mGameVersion;
end;
var
g_ConsoleNet:TConsoleNet;
implementation
{ TConsoleNet }
function TConsoleNet.ConnConsole: Bool;
var
Wsstatus:integer;
Rece:TWSAData;
SocketObj:TSocket;
Ser:TSockAddr;
begin
Result:= False;
Wsstatus:=WSAStartup($202,Rece);
try
if Wsstatus = 0 then
begin
SocketObj:=socket(AF_INET,SOCK_STREAM,0);
if SocketObj >= 0 then
begin
Ser.sa_family:= AF_INET;
Ser.sin_port:=htons(mPort);
Ser.sin_addr.S_addr:=inet_addr(PChar(mIp));
if Wsstatus = 0 then
begin
Wsstatus := Connect(SocketObj,Ser,SizeOf(Ser));
if Wsstatus = 0 then
begin
mSocket:= SocketObj;
mToken:=GetToken();
Result:=mToken <> 0;
end;
end;
end;
end;
finally
//WSACleanup();
end;
end;
constructor TConsoleNet.Create(_Ip: string; _Port: Integer;_Pid:Cardinal);
begin
mToken:=0;
mGameVersion:=0;
mIp:=_Ip;
mPort:=_Port;
mPid:=_Pid;
mActive:=ConnConsole();
end;
function TConsoleNet.GetToken: Cardinal;
var
Buffer:_Req_Token;
RepBuffer:_Res_Token;
begin
Result:= 0;
Buffer.Head.Cmd := c_Req_Token;
Buffer.Head.Pid:=mPid;
Buffer.Head.Size:= SizeOf(_Req_Token);
Buffer.Head.ErrorCode:=0;
Buffer.Head.Tick:=GetTickCount;
if send(mSocket,Buffer,Buffer.Head.Size,0) = Buffer.Head.Size then
begin
if recv(mSocket,RepBuffer,SizeOf(_Res_Token),0) > 0 then
begin
// Dbgprint('<-Console-> %d Token = 0x%X',[RepBuffer.GameVer,
// RepBuffer.Token]);
if RepBuffer.Head.ErrorCode = 0 then
begin
Result:= RepBuffer.Token;
mGameVersion:=RepBuffer.GameVer;
end;
end;
end;
end;
function TConsoleNet.RequestGameAddress(_TagId: Integer): Cardinal;
var
Buffer:_req_game_address;
RepBuffer:_res_game_address;
Module:Cardinal;
begin
Result:=0;
Buffer.Head.Cmd := c_Req_Game_Address;
Buffer.Head.Pid:=mPid;
Buffer.Head.Size:= SizeOf(_req_game_address);
Buffer.Head.ErrorCode:=0;
Buffer.Head.Tick:=GetTickCount;
Buffer.TagId:=_TagId;
if send(mSocket,Buffer,Buffer.Head.Size,0) = Buffer.Head.Size then
begin
if recv(mSocket,RepBuffer,SizeOf(_res_game_address),0) > 0 then
begin
if RepBuffer.Head.ErrorCode = 0 then
begin
if RepBuffer.TagId = _TagId then
begin
Module:=GetModuleHandle(RepBuffer.ModuleName);
// Dbgprint('GetModule:%s [%X]',[RepBuffer.ModuleName,Module]);
if Module <> 0 then
Result:= Module + RepBuffer.Offset;
end;
end;
end;
end;
end;
end.
|
{ GS1 interface library for FPC and Lazarus
Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru
base on docs from http://api-docs.diadoc.ru
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit LP_base_types_v2;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, xmlobject, AbstractSerializationObjects;
type
//IPv4. Запись в виде четырёх десятичных чисел (от 0 до 255), разделённых точками.
TIPv4Address_type = String;
//IPv6. Запись в виде восьми четырёхзначных шестнадцатеричных чисел (групп по четыре символа), разделённых двоеточием.
TIPv6Address_type = String;
//Текстовое значение не более 255 символов
Tstring255_type = String;
//Текстовое значение не более 200 символов
Tstring200_type = String;
//Текстовое значение не более 1000 символов
Tstring1000_type = String;
//Текстовое значение не более 50 символов
Tstring50_type = String;
//Текстовое значение не более 1024 символов
Tstring1024_type = String;
//Текстовое значение не более 128 символов
Tstring128_type = String;
//Текстовое значение не более 70 символов
Tstring70_type = String;
//Справочник типов участников
//Участник оборота товаров - TRADE_PARTICIPANT
//Оператор ИС МП - OPERATOR
//ЦЭМ - LABELLING_CENTER
//ОГВ - OGV
//Эмитент - EMITENT
Tparticipant_type = String;
//ИНН участника оборота
Tinn_type = String;
//КПП участника оборота
Tkpp_type = String;
//Значение даты в формате ДД.ММ.ГГГГ.
Tdate_type = String;
//Значение даты и времени, а так же смещение, относительно времени в формате UTC
Tdatetimeoffset_type = TDateTime;
//Справочник видов оборота товаров
//Продажа - SELLING
//Комиссия - COMMISSION
//Агент - AGENT
//Продажа комиссионером - COMMISSIONAIRE_SALE
//Подряд - CONTRACT
Tturnover_enum_type = String;
//Пол обуви
//Мужской - MALE
//Женский - FEMALE
//Детская - BABY
//Унисекс - UNISEX
Tproduct_gender_type = String;
//Стоимость/Налог
Tprice_type = Double;
//GUID (Globally Unique Identifier)
Tguid_type = String;
//Регистрационный токен СУЗ
Ttoken_type = String;
//Порт TCP/IP
Ttcpip_port_type = Int64;
//Размер в штихмассовой системе
Tshoe_size = Double;
//Код товарной номенклатуры (4 знака)
Ttnved_code_4_type = String;
//Код товарной номенклатуры (2 знака)
Ttnved_code_2_type = String;
//Код ТН ВЭД ЕАС товара
Ttnved_code_type = String;
//Справочник причин вывода из оборота
//Розничная продажа - RETAIL
//Экспорт в страны ЕАЭС - EEC_EXPORT
//Экспорт за пределы стран ЕАЭС - BEYOND_EEC_EXPORT
//Возврат физическому лицу - RETURN
//Продажа по образцам, дистанционный способ продажи - REMOTE_SALE
//Утрата или повреждение - DAMAGE_LOSS
//Уничтожение - DESTRUCTION
//Конфискация - CONFISCATION
//Использование для собственных нужд предприятия - ENTERPRISE_USE
//Ликвидация предприятия - LIQUIDATION
Twithdrawal_type = String;
//Справочник причин вывода из оборота при отгрузке
//Безвозмездная передача - DONATION
//Приобретение гос.предприятием - STATE_ENTERPRISE
//Использование для собственных нужд покупателем - NO_RETAIL_USE
Twithdrawal_shipment_type = String;
//Справочник типов первичных документов для вывода из оборота
//Кассовый чек - RECEIPT
//Бланк строгой отчетности - STRICT_REPORTING_FORM
//Договор - CONTRACT
//Акт уничтожения (утраты/утилизации) - DESTRUCTION_ACT
//Товарная накладная - CONSIGNMENT_NOTE
//Универсальный передаточный документ - UTD
//Прочее - OTHER
Twithdraw_primary_document_type_type = String;
//Справочник типов первичных документов для вывода из оборота
//Кассовый чек - RECEIPT
//Товарный чек - SALES_RECEIPT
//Прочее - OTHER
Treturn_primary_document_type_type = String;
//Справочник типов первичных документов для отгрузки
//Товарная накладная - CONSIGNMENT_NOTE
//Универсальный передаточный документ - UTD
//Прочее - OTHER
Tshipment_primary_document_type_type = String;
//Уникальный идентификатор транспортной упаковки или товара
Tgs1_uit_uitu_type = String;
//GTIN
Tgtin_type = String;
//Справочник типов производственного заказа
//Собственное производство - OWN_PRODUCTION
//Контрактное производство - CONTRACT_PRODUCTION
Tproduction_order_type = String;
//Справочник видов документов, подтверждающих соответствие
//Сертификат соответствия - CONFORMITY_CERTIFICATE
//Декларация о соответствии - CONFORMITY_DECLARATION
Tcertificate_type_type = String;
//Серийный номер
Tsn_type = String;
//Справочник способов ввода товаров в оборот
//Произведен в РФ - PRODUCED_IN_RF
//Ввезен в РФ - IMPORTED_INTO_RF
//Остатки - OSTATKI
//ТрансГран - CROSSBORDER
Trelease_method_type = String;
//Справочник кодов принятого решения
//10 - Выпуск товаров разрешен
//11 - Выпуск товаров при условии обеспечения исполнения обязанности по уплате таможенных пошлин, налогов, специальных, антидемпинговых, компенсационных пошлин, за исключением выпуска товаров, поименованного в позициях с кодами 12 и 13
//12 - Выпуск товаров с особенностями, предусмотренными статьей 121 Таможенного кодекса Евразийского экономического союза
//13 - Выпуск товаров с особенностями, предусмотренными статьей 122 Таможенного кодекса Евразийского экономического союза
//14 - Выпуск товаров с особенностями, предусмотренными статьей 123 Таможенного кодекса Евразийского экономического союза
//20 - Условный выпуск товаров
Tdecision_code_type = Longint;
//Испорчено либо утеряно СИ с КМ - KM_SPOILED_OR_LOST
//Выявлены ошибки описания товара - DESCRIPTION_ERRORS
//Возврат товаров с поврежденным СИ/без СИ при розничной реализации - RETAIL_RETURN
//Возврат товаров с поврежденным СИ/без СИ при дистанционном способе продажи - REMOTE_SALE_RETURN
Tremark_cause_type = String;
//Спроавочник причин списания кодов маркировки
//Испорчен - KM_SPOILED
//Утерян - KM_LOST
//Уничтожен - KM_DESTROYED
Tkm_cancellation_reason_type = String;
//Спроавочник типов трансформации транспортной упаковки
//Изъятие - REMOVING
//Добавление - ADDING
Treaggregation_type_type = String;
//Спроавочник типов трансформации упаковки
//Изъятие - REMOVING
//Добавление - ADDING
Ttransformation_type_type = String;
//КИТУ (код идентификации транспортной упаковки)
Tkitu_type = String;
//КИ (код идентификации)
Tkit_type = String;
//КИ (код идентификации)
Tki_type = String;
//Способ изготовления
//Самостоятельно - OWN
//ЦЭМ - LC
Tproduction_method_type = String;
//Способ получения кодов маркировки
//На физическом носителе - PHYSICAL_MEDIA
//В электронном виде - ELECTRONIC
Treception_method_type = String;
//Способ формирования серийного номера
//Самостоятельно - OWN
//Оператором - OPERATOR
Tsn_method_type = String;
//Серийный номер сертификата УКЭП
Tcertificate_sn_type = String;
//Справочник типов движения товара
//Приход-расход - INCOME_OUTCOME
//Возврат - RETURN
Tdistribution_type_type = String;
//Справочник видов ввода товарв в оборот
//Собственное производство РФ - OWN_PRODUCTION
//Контрактное производство РФ - CONTRACT_PRODUCTION
//Производство вне ЕАЭС - BEYOND_EEC_PRODUCTION
//Производство в ЕАЭС - EEC_PRODUCTION
//Ввод полученных от физ.лиц товаров - INDIVIDUALS
//Ввод остатков товара - OSTATKI
Tvvod_type_type = String;
//Код страны ОКСМ
Toksm_type = String;
//Код страны ОКСМ для ввода в оборот при трансграничной торговле
//Армения - 051
//Беларусь - 112
//Казахстан - 398
//Киргизия - 417
Toksm_cb_type = String;
//Буквенный код идентификации страны в соответствии с ОКСМ (альфа-2)
Toksm_alpha2_type = String;
//Справочник видов возврата
//Возврат при розничной реализации - RETAIL_RETURN
//Возврат при дистанционном способе реализации - REMOTE_SALE_RETURN
Treturn_type_type = String;
//Код товарной номенклатуры (2 знака) для остатков
Ttnved_code_2_ost_type = Int64;
//Возрастная категория товара
//Детское - BABY
//Взрослое - ADULT
//Без возраста - NO_AGE
Tage_category_type = String;
//Регистрационный номер ДТ
Tdeclaration_number_type = String;
//Агрегированный таможенный код
Tatk_type = String;
Taoguid = String;
Thouseguid = String;
Tflat = String;
type
{ Forward declarations }
Tfias_address_type = class;
Tshipment_children_products_list_type = class;
Tshipment_children_products_list_type_product = class;
Tacceptance_children_products_list_type = class;
Tacceptance_children_products_list_type_product = class;
Tvvod_children_products_list_type = class;
Tvvod_children_products_list_type_product = class;
Tvvod_ind_children_products_list_type = class;
Tvvod_ind_children_products_list_type_product = class;
Tvvod_ost_children_products_list_type = class;
Tvvod_ost_children_products_list_type_product = class;
Tvvod_crossborder_products_list_type = class;
Tvvod_crossborder_products_list_type_product = class;
Tvvod_fts_children_list_type = class;
Tvvod_fts_children_list_type_product = class;
{ Generic classes for collections }
Tfias_address_typeList = specialize GXMLSerializationObjectList<Tfias_address_type>;
Tshipment_children_products_list_typeList = specialize GXMLSerializationObjectList<Tshipment_children_products_list_type>;
Tshipment_children_products_list_type_productList = specialize GXMLSerializationObjectList<Tshipment_children_products_list_type_product>;
Tacceptance_children_products_list_typeList = specialize GXMLSerializationObjectList<Tacceptance_children_products_list_type>;
Tacceptance_children_products_list_type_productList = specialize GXMLSerializationObjectList<Tacceptance_children_products_list_type_product>;
Tvvod_children_products_list_typeList = specialize GXMLSerializationObjectList<Tvvod_children_products_list_type>;
Tvvod_children_products_list_type_productList = specialize GXMLSerializationObjectList<Tvvod_children_products_list_type_product>;
Tvvod_ind_children_products_list_typeList = specialize GXMLSerializationObjectList<Tvvod_ind_children_products_list_type>;
Tvvod_ind_children_products_list_type_productList = specialize GXMLSerializationObjectList<Tvvod_ind_children_products_list_type_product>;
Tvvod_ost_children_products_list_typeList = specialize GXMLSerializationObjectList<Tvvod_ost_children_products_list_type>;
Tvvod_ost_children_products_list_type_productList = specialize GXMLSerializationObjectList<Tvvod_ost_children_products_list_type_product>;
Tvvod_crossborder_products_list_typeList = specialize GXMLSerializationObjectList<Tvvod_crossborder_products_list_type>;
Tvvod_crossborder_products_list_type_productList = specialize GXMLSerializationObjectList<Tvvod_crossborder_products_list_type_product>;
Tvvod_fts_children_list_typeList = specialize GXMLSerializationObjectList<Tvvod_fts_children_list_type>;
Tvvod_fts_children_list_type_productList = specialize GXMLSerializationObjectList<Tvvod_fts_children_list_type_product>;
{ Tfias_address_type }
//Адрес в формате ФИАС
Tfias_address_type = class(TXmlSerializationObject)
private
Faoguid:Taoguid;
Fhouseguid:Thouseguid;
Fflat:Tflat;
procedure Setaoguid( AValue:Taoguid);
procedure Sethouseguid( AValue:Thouseguid);
procedure Setflat( AValue:Tflat);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//Глобальный уникальный идентификатор адресного объекта
property aoguid:Taoguid read Faoguid write Setaoguid;
//Глобальный уникальный идентификатор дома. Обязателен при наличии
property houseguid:Thouseguid read Fhouseguid write Sethouseguid;
//Квартира. Обязателен при наличии
property flat:Tflat read Fflat write Setflat;
end;
{ Tshipment_children_products_list_type }
Tshipment_children_products_list_type = class(TXmlSerializationObject)
private
Fproduct:Tshipment_children_products_list_type_productList;
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//Список КИ/КИТУ в составе транспортной упаковки (отгрузка)
property product:Tshipment_children_products_list_type_productList read Fproduct;
end;
{ Tshipment_children_products_list_type_product }
Tshipment_children_products_list_type_product = class(TXmlSerializationObject)
private
Fki:Tki_type;
Fkitu:Tkitu_type;
Fcost:Tprice_type;
Fvat_value:Tprice_type;
Fchildren_products_list:Tshipment_children_products_list_type;
procedure Setki( AValue:Tki_type);
procedure Setkitu( AValue:Tkitu_type);
procedure Setcost( AValue:Tprice_type);
procedure Setvat_value( AValue:Tprice_type);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//КИ
property ki:Tki_type read Fki write Setki;
//КИТУ
property kitu:Tkitu_type read Fkitu write Setkitu;
//Цена за единицу
property cost:Tprice_type read Fcost write Setcost;
//Сумма НДС
property vat_value:Tprice_type read Fvat_value write Setvat_value;
//Список КИ\КИТУ составе транспортной упаковки (отгрузка)
property children_products_list:Tshipment_children_products_list_type read Fchildren_products_list;
end;
{ Tacceptance_children_products_list_type }
Tacceptance_children_products_list_type = class(TXmlSerializationObject)
private
Fproduct:Tacceptance_children_products_list_type_productList;
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//Список КИ\КИТУ в составе транспортной упаковки (приемка)
property product:Tacceptance_children_products_list_type_productList read Fproduct;
end;
{ Tacceptance_children_products_list_type_product }
Tacceptance_children_products_list_type_product = class(TXmlSerializationObject)
private
Fki:Tki_type;
Fkitu:Tkitu_type;
Faccept_type:Boolean;
Fchildren_products_list:Tacceptance_children_products_list_type;
procedure Setki( AValue:Tki_type);
procedure Setkitu( AValue:Tkitu_type);
procedure Setaccept_type( AValue:Boolean);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//КИ
property ki:Tki_type read Fki write Setki;
//КИТУ
property kitu:Tkitu_type read Fkitu write Setkitu;
//Товар принят
property accept_type:Boolean read Faccept_type write Setaccept_type;
//Список КИ\КИТУ в составе транспортной упаковки (приемка)
property children_products_list:Tacceptance_children_products_list_type read Fchildren_products_list;
end;
{ Tvvod_children_products_list_type }
Tvvod_children_products_list_type = class(TXmlSerializationObject)
private
Fproduct:Tvvod_children_products_list_type_productList;
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//Список КИ\КИТУ в составе транспортной упаковки для ввода в оборот
property product:Tvvod_children_products_list_type_productList read Fproduct;
end;
{ Tvvod_children_products_list_type_product }
Tvvod_children_products_list_type_product = class(TXmlSerializationObject)
private
Fki:Tkit_type;
Fkitu:Tkitu_type;
Fproduct_date:Tdate_type;
Ftnved_code:Ttnved_code_type;
Fcertificate_type:Tcertificate_type_type;
Fcertificate_number:Tstring255_type;
Fcertificate_date:Tdate_type;
Fvvod_children_products_list:Tvvod_children_products_list_type;
procedure Setki( AValue:Tkit_type);
procedure Setkitu( AValue:Tkitu_type);
procedure Setproduct_date( AValue:Tdate_type);
procedure Settnved_code( AValue:Ttnved_code_type);
procedure Setcertificate_type( AValue:Tcertificate_type_type);
procedure Setcertificate_number( AValue:Tstring255_type);
procedure Setcertificate_date( AValue:Tdate_type);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//КИ
property ki:Tkit_type read Fki write Setki;
//КИТУ
property kitu:Tkitu_type read Fkitu write Setkitu;
//Дата производства
property product_date:Tdate_type read Fproduct_date write Setproduct_date;
//Код ТН ВЭД ЕАС товара
property tnved_code:Ttnved_code_type read Ftnved_code write Settnved_code;
//Вид документа, подтверждающего соответствие
property certificate_type:Tcertificate_type_type read Fcertificate_type write Setcertificate_type;
//Номер документа, подтверждающего соответствие
property certificate_number:Tstring255_type read Fcertificate_number write Setcertificate_number;
//Дата документа, подтверждающего соответствие
property certificate_date:Tdate_type read Fcertificate_date write Setcertificate_date;
//Список КИ\КИТУ в составе транспортной упаковки для ввода в оборот
property vvod_children_products_list:Tvvod_children_products_list_type read Fvvod_children_products_list;
end;
{ Tvvod_ind_children_products_list_type }
Tvvod_ind_children_products_list_type = class(TXmlSerializationObject)
private
Fproduct:Tvvod_ind_children_products_list_type_productList;
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//Список КИ\КИТУ в составе транспортной упаковки для ввода в оборот (полученных от физических лиц)
property product:Tvvod_ind_children_products_list_type_productList read Fproduct;
end;
{ Tvvod_ind_children_products_list_type_product }
Tvvod_ind_children_products_list_type_product = class(TXmlSerializationObject)
private
Fki:Tkit_type;
Fkitu:Tkitu_type;
Fproduct_receiving_date:Tdate_type;
Fvvod_ind_children_products_list:Tvvod_ind_children_products_list_type;
procedure Setki( AValue:Tkit_type);
procedure Setkitu( AValue:Tkitu_type);
procedure Setproduct_receiving_date( AValue:Tdate_type);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//КИ
property ki:Tkit_type read Fki write Setki;
//КИТУ
property kitu:Tkitu_type read Fkitu write Setkitu;
//Дата получения товара
property product_receiving_date:Tdate_type read Fproduct_receiving_date write Setproduct_receiving_date;
//Список КИ\КИТУ в составе транспортной упаковки для ввода в оборот (полученных от физических лиц)
property vvod_ind_children_products_list:Tvvod_ind_children_products_list_type read Fvvod_ind_children_products_list;
end;
{ Tvvod_ost_children_products_list_type }
Tvvod_ost_children_products_list_type = class(TXmlSerializationObject)
private
Fproduct:Tvvod_ost_children_products_list_type_productList;
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//Список КИ\КИТУ в составе транспортной упаковки для ввода в оборот (остатки)
property product:Tvvod_ost_children_products_list_type_productList read Fproduct;
end;
{ Tvvod_ost_children_products_list_type_product }
Tvvod_ost_children_products_list_type_product = class(TXmlSerializationObject)
private
Fki:Tkit_type;
Fkitu:Tkitu_type;
Fvvod_ost_children_products_list:Tvvod_ost_children_products_list_type;
procedure Setki( AValue:Tkit_type);
procedure Setkitu( AValue:Tkitu_type);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//КИ
property ki:Tkit_type read Fki write Setki;
//КИТУ
property kitu:Tkitu_type read Fkitu write Setkitu;
//Список КИ\КИТУ в составе транспортной упаковки для ввода в оборот (остатки)
property vvod_ost_children_products_list:Tvvod_ost_children_products_list_type read Fvvod_ost_children_products_list;
end;
{ Tvvod_crossborder_products_list_type }
Tvvod_crossborder_products_list_type = class(TXmlSerializationObject)
private
Fproduct:Tvvod_crossborder_products_list_type_productList;
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//Список КИ\КИТУ в составе транспортной упаковки для ввода в оборот (трансграничная торговля)
property product:Tvvod_crossborder_products_list_type_productList read Fproduct;
end;
{ Tvvod_crossborder_products_list_type_product }
Tvvod_crossborder_products_list_type_product = class(TXmlSerializationObject)
private
Fki:Tkit_type;
Fkitu:Tkitu_type;
Ftnved_code:Ttnved_code_type;
Fcost:Tprice_type;
Fvat_value:Tprice_type;
Fcertificate_type:Tcertificate_type_type;
Fcertificate_number:Tstring255_type;
Fcertificate_date:Tdate_type;
Fchildren_products_list:Tvvod_crossborder_products_list_type;
procedure Setki( AValue:Tkit_type);
procedure Setkitu( AValue:Tkitu_type);
procedure Settnved_code( AValue:Ttnved_code_type);
procedure Setcost( AValue:Tprice_type);
procedure Setvat_value( AValue:Tprice_type);
procedure Setcertificate_type( AValue:Tcertificate_type_type);
procedure Setcertificate_number( AValue:Tstring255_type);
procedure Setcertificate_date( AValue:Tdate_type);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//КИ
property ki:Tkit_type read Fki write Setki;
//КИТУ
property kitu:Tkitu_type read Fkitu write Setkitu;
//Код ТН ВЭД ЕАС товара
property tnved_code:Ttnved_code_type read Ftnved_code write Settnved_code;
//Цена за единицу
property cost:Tprice_type read Fcost write Setcost;
//Сумма НДС
property vat_value:Tprice_type read Fvat_value write Setvat_value;
//Вид документа, подтверждающего соответствие
property certificate_type:Tcertificate_type_type read Fcertificate_type write Setcertificate_type;
//Номер документа, подтверждающего соответствие
property certificate_number:Tstring255_type read Fcertificate_number write Setcertificate_number;
//Дата документа, подтверждающего соответствие
property certificate_date:Tdate_type read Fcertificate_date write Setcertificate_date;
//Список КИ/КИТУ в составе транспортной упаковки для ввода в оборот (трансграничная торговля)
property children_products_list:Tvvod_crossborder_products_list_type read Fchildren_products_list;
end;
{ Tvvod_fts_children_list_type }
Tvvod_fts_children_list_type = class(TXmlSerializationObject)
private
Fproduct:Tvvod_fts_children_list_type_productList;
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//Список КИ/КИТУ в составе КИТУ/АТК для ввода в оборот импортных товаров с ФТС
property product:Tvvod_fts_children_list_type_productList read Fproduct;
end;
{ Tvvod_fts_children_list_type_product }
Tvvod_fts_children_list_type_product = class(TXmlSerializationObject)
private
Fki:Tkit_type;
Fkitu:Tkitu_type;
Fcolor:Tstring1024_type;
Fproduct_size:Tshoe_size;
Fvvod_fts_children_list_type:Tvvod_fts_children_list_type;
procedure Setki( AValue:Tkit_type);
procedure Setkitu( AValue:Tkitu_type);
procedure Setcolor( AValue:Tstring1024_type);
procedure Setproduct_size( AValue:Tshoe_size);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//КИ (код идентификации)
property ki:Tkit_type read Fki write Setki;
//КИТУ (код идентификации транспортной упаковки)
property kitu:Tkitu_type read Fkitu write Setkitu;
//Цвет. Параметр обязателен для ТГ "Обувь"
property color:Tstring1024_type read Fcolor write Setcolor;
//Размер в штихмассовой системе. Параметр обязателен для ТГ "Обувь"
property product_size:Tshoe_size read Fproduct_size write Setproduct_size;
//Список КИ/КИТУ в составе КИТУ/АТК для ввода в оборот импортных товаров с ФТС
property vvod_fts_children_list_type:Tvvod_fts_children_list_type read Fvvod_fts_children_list_type;
end;
implementation
{ Tfias_address_type }
procedure Tfias_address_type.Setaoguid(AValue: Taoguid);
begin
CheckStrMinSize('aoguid', AValue);
CheckStrMaxSize('aoguid', AValue);
Faoguid:=AValue;
ModifiedProperty('aoguid');
end;
procedure Tfias_address_type.Sethouseguid(AValue: Thouseguid);
begin
CheckStrMinSize('houseguid', AValue);
CheckStrMaxSize('houseguid', AValue);
Fhouseguid:=AValue;
ModifiedProperty('houseguid');
end;
procedure Tfias_address_type.Setflat(AValue: Tflat);
begin
CheckStrMinSize('flat', AValue);
CheckStrMaxSize('flat', AValue);
Fflat:=AValue;
ModifiedProperty('flat');
end;
procedure Tfias_address_type.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('aoguid', 'aoguid', [xsaSimpleObject], '', 36, 36);
P:=RegisterProperty('houseguid', 'houseguid', [xsaSimpleObject], '', 36, 36);
P:=RegisterProperty('flat', 'flat', [xsaSimpleObject], '', 1, 20);
end;
procedure Tfias_address_type.InternalInitChilds;
begin
inherited InternalInitChilds;
end;
destructor Tfias_address_type.Destroy;
begin
inherited Destroy;
end;
constructor Tfias_address_type.Create;
begin
inherited Create;
end;
{ Tshipment_children_products_list_type }
procedure Tshipment_children_products_list_type.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('product', 'product', [], '', -1, -1);
end;
procedure Tshipment_children_products_list_type.InternalInitChilds;
begin
inherited InternalInitChilds;
Fproduct:=Tshipment_children_products_list_type_productList.Create;
end;
destructor Tshipment_children_products_list_type.Destroy;
begin
Fproduct.Free;
inherited Destroy;
end;
constructor Tshipment_children_products_list_type.Create;
begin
inherited Create;
end;
{ Tshipment_children_products_list_type_product }
procedure Tshipment_children_products_list_type_product.Setki(AValue: Tki_type);
begin
CheckStrMinSize('ki', AValue);
CheckStrMaxSize('ki', AValue);
Fki:=AValue;
ModifiedProperty('ki');
end;
procedure Tshipment_children_products_list_type_product.Setkitu(AValue: Tkitu_type);
begin
CheckStrMinSize('kitu', AValue);
CheckStrMaxSize('kitu', AValue);
Fkitu:=AValue;
ModifiedProperty('kitu');
end;
procedure Tshipment_children_products_list_type_product.Setcost(AValue: Tprice_type);
begin
CheckMinInclusiveValue('cost', AValue);
Fcost:=AValue;
ModifiedProperty('cost');
end;
procedure Tshipment_children_products_list_type_product.Setvat_value(AValue: Tprice_type);
begin
CheckMinInclusiveValue('vat_value', AValue);
Fvat_value:=AValue;
ModifiedProperty('vat_value');
end;
procedure Tshipment_children_products_list_type_product.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('ki', 'ki', [xsaSimpleObject], '', 25, 45);
P:=RegisterProperty('kitu', 'kitu', [xsaSimpleObject], '', 18, 18);
P:=RegisterProperty('cost', 'cost', [xsaSimpleObject], '', -1, -1);
P.TotalDigits := 19;
P.FractionDigits := 2;
P.minInclusiveFloat:=0;
P:=RegisterProperty('vat_value', 'vat_value', [xsaSimpleObject], '', -1, -1);
P.TotalDigits := 19;
P.FractionDigits := 2;
P.minInclusiveFloat:=0;
P:=RegisterProperty('children_products_list', 'children_products_list', [], '', -1, -1);
end;
procedure Tshipment_children_products_list_type_product.InternalInitChilds;
begin
inherited InternalInitChilds;
Fchildren_products_list:=Tshipment_children_products_list_type.Create;
end;
destructor Tshipment_children_products_list_type_product.Destroy;
begin
Fchildren_products_list.Free;
inherited Destroy;
end;
constructor Tshipment_children_products_list_type_product.Create;
begin
inherited Create;
end;
{ Tacceptance_children_products_list_type }
procedure Tacceptance_children_products_list_type.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('product', 'product', [], '', -1, -1);
end;
procedure Tacceptance_children_products_list_type.InternalInitChilds;
begin
inherited InternalInitChilds;
Fproduct:=Tacceptance_children_products_list_type_productList.Create;
end;
destructor Tacceptance_children_products_list_type.Destroy;
begin
Fproduct.Free;
inherited Destroy;
end;
constructor Tacceptance_children_products_list_type.Create;
begin
inherited Create;
end;
{ Tacceptance_children_products_list_type_product }
procedure Tacceptance_children_products_list_type_product.Setki(AValue: Tki_type);
begin
CheckStrMinSize('ki', AValue);
CheckStrMaxSize('ki', AValue);
Fki:=AValue;
ModifiedProperty('ki');
end;
procedure Tacceptance_children_products_list_type_product.Setkitu(AValue: Tkitu_type);
begin
CheckStrMinSize('kitu', AValue);
CheckStrMaxSize('kitu', AValue);
Fkitu:=AValue;
ModifiedProperty('kitu');
end;
procedure Tacceptance_children_products_list_type_product.Setaccept_type(AValue: Boolean);
begin
Faccept_type:=AValue;
ModifiedProperty('accept_type');
end;
procedure Tacceptance_children_products_list_type_product.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('ki', 'ki', [xsaSimpleObject], '', 25, 45);
P:=RegisterProperty('kitu', 'kitu', [xsaSimpleObject], '', 18, 18);
P:=RegisterProperty('accept_type', 'accept_type', [xsaSimpleObject], '', -1, -1);
P:=RegisterProperty('children_products_list', 'children_products_list', [], '', -1, -1);
end;
procedure Tacceptance_children_products_list_type_product.InternalInitChilds;
begin
inherited InternalInitChilds;
Fchildren_products_list:=Tacceptance_children_products_list_type.Create;
end;
destructor Tacceptance_children_products_list_type_product.Destroy;
begin
Fchildren_products_list.Free;
inherited Destroy;
end;
constructor Tacceptance_children_products_list_type_product.Create;
begin
inherited Create;
end;
{ Tvvod_children_products_list_type }
procedure Tvvod_children_products_list_type.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('product', 'product', [], '', -1, -1);
end;
procedure Tvvod_children_products_list_type.InternalInitChilds;
begin
inherited InternalInitChilds;
Fproduct:=Tvvod_children_products_list_type_productList.Create;
end;
destructor Tvvod_children_products_list_type.Destroy;
begin
Fproduct.Free;
inherited Destroy;
end;
constructor Tvvod_children_products_list_type.Create;
begin
inherited Create;
end;
{ Tvvod_children_products_list_type_product }
procedure Tvvod_children_products_list_type_product.Setki(AValue: Tkit_type);
begin
CheckStrMinSize('ki', AValue);
CheckStrMaxSize('ki', AValue);
Fki:=AValue;
ModifiedProperty('ki');
end;
procedure Tvvod_children_products_list_type_product.Setkitu(AValue: Tkitu_type);
begin
CheckStrMinSize('kitu', AValue);
CheckStrMaxSize('kitu', AValue);
Fkitu:=AValue;
ModifiedProperty('kitu');
end;
procedure Tvvod_children_products_list_type_product.Setproduct_date(AValue: Tdate_type);
begin
CheckStrMinSize('product_date', AValue);
CheckStrMaxSize('product_date', AValue);
Fproduct_date:=AValue;
ModifiedProperty('product_date');
end;
procedure Tvvod_children_products_list_type_product.Settnved_code(AValue: Ttnved_code_type);
begin
Ftnved_code:=AValue;
ModifiedProperty('tnved_code');
end;
procedure Tvvod_children_products_list_type_product.Setcertificate_type(AValue: Tcertificate_type_type);
begin
CheckLockupValue('certificate_type', AValue);
Fcertificate_type:=AValue;
ModifiedProperty('certificate_type');
end;
procedure Tvvod_children_products_list_type_product.Setcertificate_number(AValue: Tstring255_type);
begin
CheckStrMinSize('certificate_number', AValue);
CheckStrMaxSize('certificate_number', AValue);
Fcertificate_number:=AValue;
ModifiedProperty('certificate_number');
end;
procedure Tvvod_children_products_list_type_product.Setcertificate_date(AValue: Tdate_type);
begin
CheckStrMinSize('certificate_date', AValue);
CheckStrMaxSize('certificate_date', AValue);
Fcertificate_date:=AValue;
ModifiedProperty('certificate_date');
end;
procedure Tvvod_children_products_list_type_product.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('ki', 'ki', [xsaSimpleObject], '', 25, 45);
P:=RegisterProperty('kitu', 'kitu', [xsaSimpleObject], '', 18, 18);
P:=RegisterProperty('product_date', 'product_date', [xsaSimpleObject], '', 10, 10);
P:=RegisterProperty('tnved_code', 'tnved_code', [xsaSimpleObject], '', -1, -1);
P:=RegisterProperty('certificate_type', 'certificate_type', [xsaSimpleObject], '', -1, -1);
P.ValidList.Add('CONFORMITY_CERTIFICATE');
P.ValidList.Add('CONFORMITY_DECLARATION');
P:=RegisterProperty('certificate_number', 'certificate_number', [xsaSimpleObject], '', 1, 255);
P:=RegisterProperty('certificate_date', 'certificate_date', [xsaSimpleObject], '', 10, 10);
P:=RegisterProperty('vvod_children_products_list', 'vvod_children_products_list', [], '', -1, -1);
end;
procedure Tvvod_children_products_list_type_product.InternalInitChilds;
begin
inherited InternalInitChilds;
Fvvod_children_products_list:=Tvvod_children_products_list_type.Create;
end;
destructor Tvvod_children_products_list_type_product.Destroy;
begin
Fvvod_children_products_list.Free;
inherited Destroy;
end;
constructor Tvvod_children_products_list_type_product.Create;
begin
inherited Create;
end;
{ Tvvod_ind_children_products_list_type }
procedure Tvvod_ind_children_products_list_type.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('product', 'product', [], '', -1, -1);
end;
procedure Tvvod_ind_children_products_list_type.InternalInitChilds;
begin
inherited InternalInitChilds;
Fproduct:=Tvvod_ind_children_products_list_type_productList.Create;
end;
destructor Tvvod_ind_children_products_list_type.Destroy;
begin
Fproduct.Free;
inherited Destroy;
end;
constructor Tvvod_ind_children_products_list_type.Create;
begin
inherited Create;
end;
{ Tvvod_ind_children_products_list_type_product }
procedure Tvvod_ind_children_products_list_type_product.Setki(AValue: Tkit_type);
begin
CheckStrMinSize('ki', AValue);
CheckStrMaxSize('ki', AValue);
Fki:=AValue;
ModifiedProperty('ki');
end;
procedure Tvvod_ind_children_products_list_type_product.Setkitu(AValue: Tkitu_type);
begin
CheckStrMinSize('kitu', AValue);
CheckStrMaxSize('kitu', AValue);
Fkitu:=AValue;
ModifiedProperty('kitu');
end;
procedure Tvvod_ind_children_products_list_type_product.Setproduct_receiving_date(AValue: Tdate_type);
begin
CheckStrMinSize('product_receiving_date', AValue);
CheckStrMaxSize('product_receiving_date', AValue);
Fproduct_receiving_date:=AValue;
ModifiedProperty('product_receiving_date');
end;
procedure Tvvod_ind_children_products_list_type_product.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('ki', 'ki', [xsaSimpleObject], '', 25, 45);
P:=RegisterProperty('kitu', 'kitu', [xsaSimpleObject], '', 18, 18);
P:=RegisterProperty('product_receiving_date', 'product_receiving_date', [xsaSimpleObject], '', 10, 10);
P:=RegisterProperty('vvod_ind_children_products_list', 'vvod_ind_children_products_list', [], '', -1, -1);
end;
procedure Tvvod_ind_children_products_list_type_product.InternalInitChilds;
begin
inherited InternalInitChilds;
Fvvod_ind_children_products_list:=Tvvod_ind_children_products_list_type.Create;
end;
destructor Tvvod_ind_children_products_list_type_product.Destroy;
begin
Fvvod_ind_children_products_list.Free;
inherited Destroy;
end;
constructor Tvvod_ind_children_products_list_type_product.Create;
begin
inherited Create;
end;
{ Tvvod_ost_children_products_list_type }
procedure Tvvod_ost_children_products_list_type.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('product', 'product', [], '', -1, -1);
end;
procedure Tvvod_ost_children_products_list_type.InternalInitChilds;
begin
inherited InternalInitChilds;
Fproduct:=Tvvod_ost_children_products_list_type_productList.Create;
end;
destructor Tvvod_ost_children_products_list_type.Destroy;
begin
Fproduct.Free;
inherited Destroy;
end;
constructor Tvvod_ost_children_products_list_type.Create;
begin
inherited Create;
end;
{ Tvvod_ost_children_products_list_type_product }
procedure Tvvod_ost_children_products_list_type_product.Setki(AValue: Tkit_type);
begin
CheckStrMinSize('ki', AValue);
CheckStrMaxSize('ki', AValue);
Fki:=AValue;
ModifiedProperty('ki');
end;
procedure Tvvod_ost_children_products_list_type_product.Setkitu(AValue: Tkitu_type);
begin
CheckStrMinSize('kitu', AValue);
CheckStrMaxSize('kitu', AValue);
Fkitu:=AValue;
ModifiedProperty('kitu');
end;
procedure Tvvod_ost_children_products_list_type_product.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('ki', 'ki', [xsaSimpleObject], '', 25, 45);
P:=RegisterProperty('kitu', 'kitu', [xsaSimpleObject], '', 18, 18);
P:=RegisterProperty('vvod_ost_children_products_list', 'vvod_ost_children_products_list', [], '', -1, -1);
end;
procedure Tvvod_ost_children_products_list_type_product.InternalInitChilds;
begin
inherited InternalInitChilds;
Fvvod_ost_children_products_list:=Tvvod_ost_children_products_list_type.Create;
end;
destructor Tvvod_ost_children_products_list_type_product.Destroy;
begin
Fvvod_ost_children_products_list.Free;
inherited Destroy;
end;
constructor Tvvod_ost_children_products_list_type_product.Create;
begin
inherited Create;
end;
{ Tvvod_crossborder_products_list_type }
procedure Tvvod_crossborder_products_list_type.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('product', 'product', [], '', -1, -1);
end;
procedure Tvvod_crossborder_products_list_type.InternalInitChilds;
begin
inherited InternalInitChilds;
Fproduct:=Tvvod_crossborder_products_list_type_productList.Create;
end;
destructor Tvvod_crossborder_products_list_type.Destroy;
begin
Fproduct.Free;
inherited Destroy;
end;
constructor Tvvod_crossborder_products_list_type.Create;
begin
inherited Create;
end;
{ Tvvod_crossborder_products_list_type_product }
procedure Tvvod_crossborder_products_list_type_product.Setki(AValue: Tkit_type);
begin
CheckStrMinSize('ki', AValue);
CheckStrMaxSize('ki', AValue);
Fki:=AValue;
ModifiedProperty('ki');
end;
procedure Tvvod_crossborder_products_list_type_product.Setkitu(AValue: Tkitu_type);
begin
CheckStrMinSize('kitu', AValue);
CheckStrMaxSize('kitu', AValue);
Fkitu:=AValue;
ModifiedProperty('kitu');
end;
procedure Tvvod_crossborder_products_list_type_product.Settnved_code(AValue: Ttnved_code_type);
begin
Ftnved_code:=AValue;
ModifiedProperty('tnved_code');
end;
procedure Tvvod_crossborder_products_list_type_product.Setcost(AValue: Tprice_type);
begin
CheckMinInclusiveValue('cost', AValue);
Fcost:=AValue;
ModifiedProperty('cost');
end;
procedure Tvvod_crossborder_products_list_type_product.Setvat_value(AValue: Tprice_type);
begin
CheckMinInclusiveValue('vat_value', AValue);
Fvat_value:=AValue;
ModifiedProperty('vat_value');
end;
procedure Tvvod_crossborder_products_list_type_product.Setcertificate_type(AValue: Tcertificate_type_type);
begin
CheckLockupValue('certificate_type', AValue);
Fcertificate_type:=AValue;
ModifiedProperty('certificate_type');
end;
procedure Tvvod_crossborder_products_list_type_product.Setcertificate_number(AValue: Tstring255_type);
begin
CheckStrMinSize('certificate_number', AValue);
CheckStrMaxSize('certificate_number', AValue);
Fcertificate_number:=AValue;
ModifiedProperty('certificate_number');
end;
procedure Tvvod_crossborder_products_list_type_product.Setcertificate_date(AValue: Tdate_type);
begin
CheckStrMinSize('certificate_date', AValue);
CheckStrMaxSize('certificate_date', AValue);
Fcertificate_date:=AValue;
ModifiedProperty('certificate_date');
end;
procedure Tvvod_crossborder_products_list_type_product.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('ki', 'ki', [xsaSimpleObject], '', 25, 45);
P:=RegisterProperty('kitu', 'kitu', [xsaSimpleObject], '', 18, 18);
P:=RegisterProperty('tnved_code', 'tnved_code', [xsaSimpleObject], '', -1, -1);
P:=RegisterProperty('cost', 'cost', [xsaSimpleObject], '', -1, -1);
P.TotalDigits := 19;
P.FractionDigits := 2;
P.minInclusiveFloat:=0;
P:=RegisterProperty('vat_value', 'vat_value', [xsaSimpleObject], '', -1, -1);
P.TotalDigits := 19;
P.FractionDigits := 2;
P.minInclusiveFloat:=0;
P:=RegisterProperty('certificate_type', 'certificate_type', [xsaSimpleObject], '', -1, -1);
P.ValidList.Add('CONFORMITY_CERTIFICATE');
P.ValidList.Add('CONFORMITY_DECLARATION');
P:=RegisterProperty('certificate_number', 'certificate_number', [xsaSimpleObject], '', 1, 255);
P:=RegisterProperty('certificate_date', 'certificate_date', [xsaSimpleObject], '', 10, 10);
P:=RegisterProperty('children_products_list', 'children_products_list', [], '', -1, -1);
end;
procedure Tvvod_crossborder_products_list_type_product.InternalInitChilds;
begin
inherited InternalInitChilds;
Fchildren_products_list:=Tvvod_crossborder_products_list_type.Create;
end;
destructor Tvvod_crossborder_products_list_type_product.Destroy;
begin
Fchildren_products_list.Free;
inherited Destroy;
end;
constructor Tvvod_crossborder_products_list_type_product.Create;
begin
inherited Create;
end;
{ Tvvod_fts_children_list_type }
procedure Tvvod_fts_children_list_type.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('product', 'product', [], '', -1, -1);
end;
procedure Tvvod_fts_children_list_type.InternalInitChilds;
begin
inherited InternalInitChilds;
Fproduct:=Tvvod_fts_children_list_type_productList.Create;
end;
destructor Tvvod_fts_children_list_type.Destroy;
begin
Fproduct.Free;
inherited Destroy;
end;
constructor Tvvod_fts_children_list_type.Create;
begin
inherited Create;
end;
{ Tvvod_fts_children_list_type_product }
procedure Tvvod_fts_children_list_type_product.Setki(AValue: Tkit_type);
begin
CheckStrMinSize('ki', AValue);
CheckStrMaxSize('ki', AValue);
Fki:=AValue;
ModifiedProperty('ki');
end;
procedure Tvvod_fts_children_list_type_product.Setkitu(AValue: Tkitu_type);
begin
CheckStrMinSize('kitu', AValue);
CheckStrMaxSize('kitu', AValue);
Fkitu:=AValue;
ModifiedProperty('kitu');
end;
procedure Tvvod_fts_children_list_type_product.Setcolor(AValue: Tstring1024_type);
begin
CheckStrMinSize('color', AValue);
CheckStrMaxSize('color', AValue);
Fcolor:=AValue;
ModifiedProperty('color');
end;
procedure Tvvod_fts_children_list_type_product.Setproduct_size(AValue: Tshoe_size);
begin
CheckMinInclusiveValue('product_size', AValue);
CheckMaxInclusiveValue('product_size', AValue);
Fproduct_size:=AValue;
ModifiedProperty('product_size');
end;
procedure Tvvod_fts_children_list_type_product.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('ki', 'ki', [xsaSimpleObject], '', 25, 45);
P:=RegisterProperty('kitu', 'kitu', [xsaSimpleObject], '', 18, 18);
P:=RegisterProperty('color', 'color', [xsaSimpleObject], '', 1, 1024);
P:=RegisterProperty('product_size', 'product_size', [xsaSimpleObject], '', -1, -1);
P.minInclusiveFloat:=14.5;
P.maxInclusiveFloat:=47;
P:=RegisterProperty('vvod_fts_children_list_type', 'vvod_fts_children_list_type', [], '', -1, -1);
end;
procedure Tvvod_fts_children_list_type_product.InternalInitChilds;
begin
inherited InternalInitChilds;
Fvvod_fts_children_list_type:=Tvvod_fts_children_list_type.Create;
end;
destructor Tvvod_fts_children_list_type_product.Destroy;
begin
Fvvod_fts_children_list_type.Free;
inherited Destroy;
end;
constructor Tvvod_fts_children_list_type_product.Create;
begin
inherited Create;
end;
end.
|
unit u_xPL_Filter_Header;
{==============================================================================
UnitName = uxPLHeader
UnitDesc = xPL Message Header management object and function
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
0.96 : Rawdata passed are no longer transformed to lower case, then Header has
to lower it
0.99 : Added usage of uRegExTools
1.00 : Suppressed usage of uRegExTools to correct bug #FS47
1.1 Switched schema from Body to Header
optimizations in SetRawxPL to avoid inutile loops
}
{$ifdef fpc}
{$mode objfpc}{$H+}{$M+}
{$endif}
interface
uses Classes,
u_xpl_header,
u_xpl_address,
u_xpl_schema,
u_xpl_common;
type // TxPLFilterHeader ======================================================
TxPLFilterHeader = class(TxPLHeader)
protected
procedure MessageTypeFromStr(const aString : string); override;
function MessageTypeToStr : string; override;
public
procedure ResetValues; override;
end;
implementation //==============================================================
// TxPLFilterHeader Object ====================================================
procedure TxPLFilterHeader.ResetValues;
begin
inherited;
MessageType := any;
end;
procedure TxPLFilterHeader.MessageTypeFromStr(const aString: string);
begin
if aString = 'xpl-*' then MessageType := any
else inherited;
end;
function TxPLFilterHeader.MessageTypeToStr: string;
begin
if MessageType = any then result := 'xpl-*'
else Result:=inherited;
end;
initialization // =============================================================
Classes.RegisterClass(TxPLFilterHeader);
end.
|
unit Global.LanguageString;
interface
uses Windows;
var
CurrLang: Integer;
const
LANG_HANGUL = 0;
LANG_ENGLISH = 1;
type
TLanguageString = Array[0..LANG_ENGLISH] of String;
const
//캐시 오류
VistaFont: TLanguageString = ('맑은 고딕', 'Segoe UI');
XPFont: TLanguageString = ('돋움', 'Verdana');
//캐시 오류
ErrCache: TLanguageString = ('다음 장치에서 잘못된 캐시 설정이 나타나 수정했습니다', 'Wrong cache setting');
//메인
CapUnsupported: TLanguageString = ('미지원', 'Unsupported');
CapConnState: TLanguageString = ('연결 상태 : ', 'Connected State : ');
CapFirmware: TLanguageString = ('펌웨어 버전 : ', 'Firmware : ');
CapSerial: TLanguageString = ('시리얼 번호 : ', 'Serial Number : ');
CapWriteError: TLanguageString = ('지우기 에러 (중요) : ', 'Erase Errors (Important) : ');
CapReadError: TLanguageString = ('읽기 에러 (중요) : ', 'Read Errors (Important) : ');
CapRepSect: TLanguageString = ('치환된 섹터 (중요) : ', 'Reallocated Sectors (Important) : ');
CapAlign: TLanguageString = ('파티션 배열 (중요) : ', 'Partition Align (Important) : ');
CapStatus: TLanguageString = ('상태 : ', 'Status : ');
CapUnknown: TLanguageString = ('알 수 없음', 'Unknown');
CapConnSpeed: Array[0..3] of String = ('SATA 1.5Gb/s (', 'SATA 3.0Gb/s (', 'SATA 6.0Gb/s (', 'USB');
CapSupportNCQ: TLanguageString = ('AHCI 사용', 'AHCI Working');
CapNonSupNCQ: TLanguageString = ('AHCI 꺼짐', 'AHCI Off');
CapSafe: TLanguageString = ('정상입니다.', 'Safe.');
CapNotSafeRepSect: TLanguageString = ('SSD의 수명이 끝나가니, SSD 내의 자료 백업을 권고합니다.', 'There are some errors. PLEASE DO BACKUP!');
CapNotSafeCritical: TLanguageString = ('SSD의 수명이 끝나가니, SSD 내의 자료 백업을 강력히 권고합니다.', 'SERIOUS ERRORS! PLEASE DO BACKUP!');
CapBadPartition: TLanguageString = ('파티션이 어긋났으니, 윈도 7에서 파티션을 다시 나눠주세요.', 'Partition align error. Re-partition with Win 7 setup tool.');
CapOldVersion: TLanguageString = (' (구버전)', ' (Old Version)');
CriticalWarning: TLanguageString =
('치명적 경고 (중요) : ', 'Critical Warning (Important) : ');
SafeWithoutDot: TLanguageString = ('정상', 'Safe');
Bad: TLanguageString = ('나쁨', 'BAD');
CapGood: TLanguageString = (' (정상) ', ' (Good) ');
CapBad: TLanguageString = ('K - 어긋남) ', 'K - Bad) ');
//메인 제목줄
CapToSeeSerial: TLanguageString = (' (시리얼 번호 보려면 X표시 클릭)', ' (To see the serial number, click the ''X'' sign)');
CapSSDSelOpn: TLanguageString = ('SSD 선택 ▼', 'Select SSD ▼');
CapSSDSelCls: TLanguageString = ('SSD 선택 ▲', 'Select SSD ▲');
//메인 버튼
BtFirmware: TLanguageString = ('펌웨어', 'Firmware');
BtErase: TLanguageString = ('초기화', 'Erase');
BtOpt: TLanguageString = ('최적화', 'Optimization');
BtHelp: TLanguageString = ('도움말 (F1)', 'Help (F1)');
BtAnaly: TLanguageString = ('사용 통계', 'Statistics');
BtLifeAnaly: TLanguageString = ('수명 통계', 'Statistics');
BtTrim: TLanguageString = ('수동 트림', 'Manual Trim');
//펌웨어 업데이트
CapFirm: TLanguageString = ('펌웨어 업데이트 USB 만들기', 'Firmware Update using USB flash drive');
CapSelUSB: TLanguageString = ('USB 선택 : ', 'USB Drive : ');
CapNewFirm: TLanguageString = ('새 펌웨어 버전 : ', 'Latest firmware : ');
CapWarnErase: TLanguageString = (' 부팅을 위해, 선택한 USB 내의 모든 자료가 삭제되는 것에 동의합니다.', ' All data in the drive will be ERASED.');
BtDoUpdate: TLanguageString = ('펌웨어 업데이트 USB 제작 시작하기', 'Start making a F/W Update USB Drive');
CapCurrFirm: TLanguageString = ('(현재 펌웨어와 동일)', '(Current Firmware)');
AlrtNoInternet: TLanguageString = ('인터넷에 연결이 되어있지 않습니다.' + Chr(13) + Chr(10) + '연결 후 다시 진행해 주세요.',
'No internet connectivity detected.');
AlrtNoServer: TLanguageString = ('대상 서버로 연결할 수 없습니다.',
'No response from the destination server.');
AlrtStartFormat: TLanguageString = ('USB 포맷을 시작합니다. 잠시만 기다려주세요.', 'Start formatting. Wait please.');
AlrtStartRecord: TLanguageString = ('USB에 펌웨어 업데이터 기록을 시작합니다.' + Chr(13) + Chr(10) + '창이 꺼질때까지 기다려주세요.'
, 'Start writing firmware update. Please wait.');
AlrtFirmEnd: TLanguageString = ('이제 재시작해서 펌웨어 업데이트를 시작해주세요.', 'Restart and Start updating.');
CapFirmDwld: TLanguageString = ('펌웨어 다운로드', 'Downloading Firmware');
AlrtFirmStart: TLanguageString = ('펌웨어 다운로드를 시작합니다.', 'Starting download Firmware.');
AlrtFirmCanc: TLanguageString = ('펌웨어 다운로드가 취소되었습니다.', 'Download has been canceled.');
AlrtFirmFail: TLanguageString = ('펌웨어 다운로드가 실패하였습니다.', 'Download has been failed.');
//초기화
CapErase: TLanguageString = ('초기화 USB 만들기', 'Secure Erase using USB flash drive');
CapEraDwld: TLanguageString = ('SSD 초기화 툴 다운로드', 'Downloading Secure Erase tool');
BtDoErase: TLanguageString = ('초기화 USB 제작 시작하기', 'Start making a Secure Erase USB Drive');
AlrtEraEnd: TLanguageString = ('이제 재시작해서 SSD 초기화를 시작해주세요.', 'Restart and Start erasing.');
//초기화 다운로드
AlrtBootFail: TLanguageString = ('선택하신 초기화 도구에 해당하는 플러그인을 설치하고 다시 시도해주세요.', 'Please download and install suitable plugin pack.');
//최적화
CapNameOpt: TLanguageString = ('SSD 최적화', 'SSD Optimization');
BtDoOpt: TLanguageString = ('최적화 시작하기', 'Start Optimization');
BtRollback: TLanguageString = ('최적화 되돌리기', 'Rollback');
CapAlreadyCompleted: TLanguageString = (' (이미 완료됨)', ' (Already Completed)');
CapOptHiber: TLanguageString = ('하이버네이션 끄기', 'Disable Hibernation');
CapOptLastAccess: TLanguageString = ('파일 접근 기록 없애기', 'Disable Last access time attribute');
CapOptSupFetch: TLanguageString = ('프리패치/슈퍼패치 끄기', 'Disable Prefetch/Superfetch Service');
CapOptPrefetch: TLanguageString = ('프리패치 끄기', 'Disable Prefetch Service');
CapOptDfrg: TLanguageString = ('부팅/유휴시간 조각 모음 끄기', 'Disable system defragger');
CapOptIndex: TLanguageString = ('색인 끄기(여분 용량 & 성능 증가 / 파일 찾기 느려짐)', 'Disable Indexing Service');
CapOptRes: TLanguageString = ('시스템 보호 끄기(여분 용량 & 성능 증가 / 시스템 복구 불가)', 'Disable System Restore Service');
CapOptP2P: TLanguageString = ('P2P 업데이트 끄기', 'Disable P2P Windows Update');
AlrtOptCmpl: TLanguageString = ('최적화가 완료되었습니다.', 'Optimization has completed.');
AlrtOptRetCmpl: TLanguageString = ('최적화 복구가 완료되었습니다.', 'Rollback operation has completed.');
//수동 트림
CapTrimName: TLanguageString = ('수동 트림 (백업을 강력히 권고합니다)', 'Manual Trim (Use at your own risk)');
CapStartManTrim: TLanguageString = ('수동 트림 시작하기', 'Start manual trim');
BtSemiAutoTrim: TLanguageString = ('반자동 트림 설정', 'Semi-auto trim');
CapLocalDisk: TLanguageString = ('로컬 디스크', 'Local Disk');
CapRemvDisk: TLanguageString = ('이동식 디스크', 'Removable Disk');
CapProg1: TLanguageString = ('진행 상황 : ', 'Progress : ');
CapProg2: TLanguageString = ('트림 도중 자료 유실 우려가 있으니, 쓰기 작업 병행을 최소화해주세요', 'DO NOT DO WRITE-INTENSIVE OPERATION DURING MANUAL TRIM.');
CapProg3: TLanguageString = ('드라이브 트림 진행중', 'Drive trimming');
//반자동 트림
CapSemiAutoTrim: TLanguageString = ('반자동 트림', 'Semi-Auto Trim (Use at your own risk)');
CapSemiAutoTrimExp: TLanguageString = ('반자동 트림이란 1분 이상 유휴 상태 지속시 트림을 수행하는 기능입니다.',
'Semi-auto trim is the trim setting that does trim after 60 secs of idle time.');
ChkSemiAutoTrim: TLanguageString = ('이 드라이브에 대해서 반자동 트림 적용', 'Apply semi-auto trim');
BtRtn: TLanguageString = ('돌아가기', 'Return');
//반자동 트림
CapAppDisk: TLanguageString = ('적용될 드라이브 : ', 'Drives to be applied : ');
//사용 통계
CapAnaly: TLanguageString = ('SSD 사용 통계', 'SSD Statistics');
CapLifeAnaly: TLanguageString = ('SSD 수명 통계', 'SSD Statistics');
CapNandWrite: TLanguageString = ('낸드 쓰기 : ', 'Nand Writes : ');
CapHostWrite: TLanguageString = ('호스트 쓰기 : ', 'Host Writes : ');
CapMylesLeft: TLanguageString = ('남은 예비 공간 : ', 'Available Reserved Space : ');
CapSSDLifeLeft: TLanguageString = ('남은 수명 : ', 'SSD Life : ');
CapWearLevel: TLanguageString = ('웨어 레벨링 횟수 : ', 'Wear Leveling Count : ');
CapCannotTrust: TLanguageString = (' (신뢰할 수 없음)', ' (DO NOT TRUST)');
CapAvg: Array[0..2] of TLanguageString = (('최근 30일 평균 : ', 'Average write per day (Recent 30 days) : '),
('최근 3개월 평균 : ' , 'Average write per day (Recent 3 months) : '),
('최근 6개월 평균 : ' , 'Average write per day (Recent 6 months) : '));
CaprAvg: Array[0..2] of TLanguageString = (('최근 30일 평균 : ', 'Average replaced sectors per day (Recent 30 days) : '),
('최근 3개월 평균 : ' , 'Average replaced sectors per day (Recent 3 months) : '),
('최근 6개월 평균 : ' , 'Average replaced sectors per day (Recent 6 months) : '));
CapToday: TLanguageString = ('오늘 사용량 : ' , 'Today Usage : ');
CaprToday: TLanguageString = ('오늘 증가한 치환 섹터 : ' , 'Replaced Sectors (Today) : ');
CapPowerTime: TLanguageString = ('전원이 들어온 시간 : ', 'Total Power-On Hours : ');
CapDay: TLanguageString = ('일' , 'day');
CapCount: TLanguageString = ('개' , '');
CapSec: TLanguageString = ('초' , 'sec');
CapMin: TLanguageString = ('분' , 'min');
CapHour: TLanguageString = ('시간' , 'hour');
CapMultiple: TLanguageString = ('' , 's');
CapPortable: TLanguageString = ('포터블 버전에서는 지원하지 않습니다.', 'Portable edition doesn''t have this feature.');
CapNotSupported: TLanguageString = ('미지원 제품입니다', 'Not supported');
//판올림
CapCurrVer: TLanguageString = ('지금의 판 : ' , 'Current version : ');
CapNewVer: TLanguageString = ('새로운 판 : ' , 'Latest version : ');
CapUpdQues: TLanguageString = ('지금 판올림을 하시겠습니까?' , 'Would you like to get update?');
CapUpdDwld: TLanguageString = ('판올림 다운로드', 'Downloading update');
BtDnldCncl: TLanguageString = ('판올림 취소', 'Cancel update');
AlrtUpdateExit: TLanguageString = ('본 프로그램의 판올림을 위해 프로그램을 종료합니다.', 'Closing program to do update.');
AlrtVerCanc: TLanguageString = ('판올림 다운로드가 취소되었습니다.', 'Update download has been canceled.');
AlrtWrongCodesign: TLanguageString = ('판올림이 잘못된 코드사인을 포함하고 있습니다.' + Chr(13) + Chr(10) + '개발자에게 알려주세요.', 'Update download has wrong codesign.' + Chr(13) + Chr(10) + 'Please report it to developer.');
AlrtVerTraff: TLanguageString = ('트래픽이 초과되었으므로, 직접 다운받아주세요.' + Chr(13) + Chr(10) + '죄송합니다.',
'The update server is over its quota. Try later.' + Chr(13) + Chr(10) + 'Sorry for inconvenience.');
AlrtNewVer: TLanguageString = ('새로운 판 발견' , 'Update available');
//수명 감시 서비스
CapWrongBuf: TLanguageString = ('쓰기 캐시 설정 잘못됨' , 'has wrong setting');
CapWrongBuf2: TLanguageString = ('비 샌드포스 SSD에서 절대 쓰기 캐시를 끄지 마세요' , 'Do NOT turn off write cache on non-sandforce SSDs.');
CapBck: TLanguageString = ('즉시 백업 요망' , 'requires BACKUP IMMEDIATELY');
CapBckRepSector: TLanguageString = ('SSD에서 죽은 섹터' , 'It has dead sector');
CapBckREError: TLanguageString = ('SSD에서 죽은 섹터' , 'It has dead sector');
CapOcc: TLanguageString = ('발생' , '');
//에러 메시지
AlrtNoFirmware: TLanguageString = ('펌웨어 파일이 없습니다. 프로그램을 재설치해주세요.', 'There isn''t any Firmware File. Please re-install this tool.');
AlrtOSError: TLanguageString = ('이 운영체제는 지원하지 않는 운영체제(XP 미만)이므로 종료합니다.', 'This tools doesn''t support OS under Windows XP.');
AlrtNoSupport: TLanguageString = ('나래온 툴 지원 SSD가 검출되지 않았습니다.', 'There is no supported SSD.');
AlrtNoUSB: TLanguageString = ('USB 저장장치를 연결해주세요.', 'Please connect a USB Flash Drive');
AlrtNoUpdate: TLanguageString = ('이미 최신 버전입니다.', 'Already your SSD has the latest firmware.');
AlrtNoFirmSupport: TLanguageString = ('해당 SSD의 펌웨어 업데이트는 지원하지 않습니다.', 'This SSD cannot be updated by Naraeon SSD Tools.');
AlrtNoCheck: TLanguageString = ('USB 자료 손실 동의 체크박스에 체크해 주세요.', 'Read and Check the caution.');
AlrtAutoCopy: TLanguageString = ('- 이 내용은 자동으로 복사됩니다 -', '- This message has copied -');
//다운로드
CapTime: TLanguageString = ('남은 시간 : ', 'Remaining time : ');
//나래온 넷 주소
AddrSecureErase: TLanguageString = ('http://naraeon.net/plugin/plugin_kor.htm', 'http://naraeon.net/plugin/plugin_eng.htm');
AddrUpdChk: TLanguageString = ('http://nstupdate.naraeon.net/latestSSDTools.htm', 'http://nstupdate.naraeon.net/latestSSDTools_eng.htm');
HelpLanguage: TLanguageString = ('ko/', 'en/');
//진단
DiagName: TLanguageString = ('나래온 툴 진단도구', 'NSTools Diagnosis');
DiagContents: TLanguageString = ('진단에 필요한 정보가 복사되었습니다.' + Chr(13) + Chr(10) + '필요한 곳에 Ctrl + V로 붙여넣어 사용하세요.',
'Information for Diagnosis copied.' + Chr(13) + Chr(10) + 'Press Ctrl + V when needed.');
procedure DetermineLanguage;
implementation
procedure DetermineLanguage;
begin
if GetUserDefaultLCID = 1042 then
CurrLang := LANG_HANGUL
else
CurrLang := LANG_ENGLISH;
end;
end.
|
unit p2_orderbook_collector;
interface
uses windows, classes, sysutils;
type tDuplicates = (dupAccept, dupIgnore, dupReplace);
// базовый класс "список" с поддержкой автоматического освобождения элементов
type tCustomList = class(tList)
procedure clear; override;
procedure freeitem(item: pointer); virtual; abstract;
procedure freeall; virtual;
procedure delete(index: longint); virtual;
procedure remove(item: pointer); virtual;
function extract(item: pointer): pointer; virtual;
end;
// базовый класс "сортированный список"
type tSortedList = class(tCustomList)
fDuplicates : tDuplicates;
constructor create;
function checkitem(item: pointer): boolean; virtual; abstract;
function compare(item1, item2: pointer): longint; virtual; abstract;
function search(item: pointer; var index: longint): boolean; virtual;
procedure add(item: pointer); virtual;
procedure insert(index: longint; item: pointer); virtual;
end;
// индекс стакана по цене
type tOrderBook = class(tSortedList)
private
fisin_id : longint;
fchanged : boolean;
public
procedure freeitem(item: pointer); override;
function checkitem(item: pointer): boolean; override;
function compare(item1, item2: pointer): longint; override;
procedure add(item: pointer); override;
procedure remove(item: pointer); override;
property isin_id: longint read fisin_id;
property changed: boolean read fchanged write fchanged;
end;
// элемент "строка в стакане"
type pOrderBookItem = ^tOrderBookItem;
tOrderBookItem = record
recid : int64;
recrev : int64;
price : double; // цена
volume : double; // кол-во
buysell : longint; // покупка/продажа
priceidx : tOrderBook;
end;
// список стаканов
type tPriceLists = class(tSortedList)
private
tmp_ordbook : tOrderBook;
public
destructor destroy; override;
procedure freeitem(item: pointer); override;
function checkitem(item: pointer): boolean; override;
function compare(item1, item2: pointer): longint; override;
function searchadditem(aisin_id: longint): tOrderBook;
end;
// общая таблица котировок
type tOrderBookList = class(tSortedList)
fOrderBooks : tPriceLists;
constructor create;
destructor destroy; override;
procedure freeitem(item: pointer); override;
function checkitem(item: pointer): boolean; override;
function compare(item1, item2: pointer): longint; override;
function searchadditem(aisin_id: longint): tOrderBook;
function addrecord(aisin_id: longint; const aid, arev: int64; const aprice, avolume: double; abuysell: longint): boolean;
function delrecord(const aid: int64): boolean;
procedure clearbyrev(const arev: int64);
end;
var OrderBookList : tOrderBookList;
implementation
function cmpi64(a, b: int64): longint;
begin
a:= a - b;
if a < 0 then result:= -1 else
if a > 0 then result:= 1 else result:= 0;
end;
function cmpdouble(const a, b: double): longint;
var r : real;
begin
r:= a - b;
if r < 0 then result:= -1 else
if r > 0 then result:= 1 else result:= 0;
end;
{ tCustomList }
procedure tCustomList.clear;
var i : longint;
begin for i:= 0 to count - 1 do freeitem(items[i]); inherited clear; end;
procedure tCustomList.freeall;
begin clear; end;
procedure tCustomList.delete(index: longint);
begin freeitem(items[index]); inherited delete(index); end;
procedure tCustomList.remove(item: pointer);
begin freeitem(item); inherited remove(item); end;
function tCustomList.extract(item: pointer): pointer;
var i : longint;
begin
i:= indexof(item);
if (i >= 0) then begin
result:= item;
inherited delete(i);
notify(result, lnExtracted);
end else result:= nil;
end;
{ tSortedList }
constructor tSortedList.create;
begin
inherited create;
fduplicates:=dupAccept;
end;
function tSortedList.search(item: pointer; var index: longint): boolean;
var l, h, i, c : longint;
begin
result:= false;
l:= 0;
h:= count - 1;
while (l <= h) do begin
i:= (l + h) shr 1;
c:= compare(items[i], item);
if (c < 0) then l:= i + 1
else begin
h:= i - 1;
if (c = 0) then begin
result:= true;
if (fDuplicates = dupIgnore) or (fDuplicates = dupReplace) then l:= i;
end;
end;
end;
index:= l;
end;
procedure tSortedList.add(item: pointer);
var index : longint;
begin
if checkitem(item) then begin
if search(item,index) then begin
case fDuplicates of
dupAccept : insert(index, item);
dupIgnore : freeitem(item);
dupReplace : begin freeitem(items[index]); items[index]:= item; end;
end;
end else insert(index, item);
end else freeitem(item);
end;
procedure tSortedList.insert(index: longint; item: pointer);
begin if checkitem(item) then inherited insert(index, item); end;
{ tOrderBook }
procedure tOrderBook.freeitem(item: pointer);
begin end;
function tOrderBook.checkitem(item: pointer): boolean;
begin result:= assigned(item) and (pOrderBookItem(item)^.price > 0); end;
function tOrderBook.compare(item1, item2: pointer): longint;
begin
result:= cmpdouble(pOrderBookItem(item1)^.price, pOrderBookItem(item2)^.price);
end;
procedure tOrderBook.add(item: pointer);
begin
inherited add(item);
fchanged:= true;
end;
procedure tOrderBook.remove(item: pointer);
begin
inherited remove(item);
fchanged:= true;
end;
{ tPriceLists }
destructor tPriceLists.destroy;
begin
if assigned(tmp_ordbook) then freeandnil(tmp_ordbook);
inherited destroy;
end;
procedure tPriceLists.freeitem(item: pointer);
begin if assigned(item) then tOrderBook(item).free; end;
function tPriceLists.checkitem(item: pointer): boolean;
begin result:= assigned(item); end;
function tPriceLists.compare(item1, item2: pointer): longint;
begin result:= tOrderBook(item1).isin_id - tOrderBook(item2).isin_id; end;
function tPriceLists.searchadditem(aisin_id: longint): tOrderBook;
var idx : longint;
begin
if not assigned(tmp_ordbook) then tmp_ordbook:= tOrderBook.create;
tmp_ordbook.fisin_id:= aisin_id;
if not search(tmp_ordbook, idx) then begin
result:= tOrderBook.create;
result.fisin_id:= aisin_id;
insert(idx, result);
end else result:= tOrderBook(items[idx]);
end;
{ tOrderBookList }
constructor tOrderBookList.create;
begin
inherited create;
fOrderBooks:= tPriceLists.create;
end;
destructor tOrderBookList.destroy;
begin
inherited destroy;
if assigned(fOrderBooks) then freeandnil(fOrderBooks);
end;
procedure tOrderBookList.freeitem(item: pointer);
begin
if assigned(item) then begin
with pOrderBookItem(item)^ do begin
if assigned(priceidx) then priceidx.remove(item);
end;
dispose(pOrderBookItem(item));
end;
end;
function tOrderBookList.checkitem(item: pointer): boolean;
begin result:= assigned(item); end;
function tOrderBookList.compare(item1, item2: pointer): longint;
begin result:= cmpi64(pOrderBookItem(item1)^.recid, pOrderBookItem(item2)^.recid); end;
function tOrderBookList.searchadditem(aisin_id: longint): tOrderBook;
begin if assigned(fOrderBooks) then result:= fOrderBooks.searchadditem(aisin_id) else result:= nil; end;
function tOrderBookList.addrecord(aisin_id: longint; const aid, arev: int64; const aprice, avolume: double; abuysell: longint): boolean;
var sitm : tOrderBookItem;
idx : longint;
itm : pOrderBookItem;
cf_price : boolean;
begin
sitm.recid:= aid;
result:= search(@sitm, idx);
if not result then begin
itm:= new(pOrderBookItem);
with itm^ do begin
recid := aid;
recrev := arev;
price := aprice;
volume := avolume;
buysell := abuysell;
if (price > 0) then begin
priceidx:= searchadditem(aisin_id);
if assigned(priceidx) then priceidx.add(itm); // добавляем в индекс
end else priceidx:= nil;
end;
insert(idx, itm); // добавляем в стакан
end else begin
itm:= pOrderBookItem(items[idx]);
cf_price := (itm^.price <> aprice); // признак изменения цены
if assigned(itm^.priceidx) then
if cf_price then itm^.priceidx.remove(itm) // если изменилась цена, удаляем из индекса
else itm^.priceidx.changed:= true; // изменились другие параметры
with itm^ do begin
recrev := arev;
price := aprice;
volume := avolume;
buysell := abuysell;
if cf_price then
if (price > 0) then begin
if not assigned(priceidx) then priceidx:= searchadditem(aisin_id);
if assigned(priceidx) then priceidx.add(itm); // добавляем в индекс
end else priceidx:= nil;
end;
end;
end;
function tOrderBookList.delrecord(const aid: int64): boolean;
var itm : tOrderBookItem;
idx : longint;
begin
itm.recid:= aid;
result:= search(@itm, idx);
if result then delete(idx); // удаляем из стакана
end;
procedure tOrderBookList.clearbyrev(const arev: int64);
var i : longint;
itm : pOrderBookItem;
begin
for i:= count - 1 downto 0 do begin
itm:= pOrderBookItem(items[i]);
if (itm^.recrev < arev) then delete(i); // удаляем из стакана
end;
end;
initialization
OrderBookList:= tOrderBookList.create;
finalization
if assigned(OrderBookList) then freeandnil(OrderBookList);
end. |
unit UProcessManager;
interface
uses WinApi.ShellAPI, WinApi.Windows, SysUtils, Classes;
type
IProcessCallBack = interface
Procedure OnStart;
Procedure OnExit;
Procedure OnFail;
end;
TProcessThread = class(TThread)
private
cb:IProcessCallBack;
pi:TProcessInformation;
protected
procedure Execute; override;
public
constructor Create(pi:TProcessInformation;cb: IProcessCallBack);
end;
TProcess = class
public
SecurityAttr:TSecurityAttributes;
StartupInfo:TStartupInfo;
ProcessInfo:TProcessInformation;
ReadPipe, WritePipe: THandle;
Show:Boolean;
t:TProcessThread;
Callback:IProcessCallBack;
CommandLine, Environment:String;
constructor Create(cmdln:string; show:boolean; env:String; cb: IProcessCallBack);
procedure StartProcess;
end;
implementation
function ToWS(strAnsi:AnsiString):WideString;
var
Len: integer;
begin
Result := '';
if strAnsi = '' then Exit;
Len := MultiByteToWideChar(GetACP, MB_PRECOMPOSED, PAnsiChar(@strAnsi[1]), -1, nil, 0);
SetLength(Result, Len - 1);
if Len > 1 then
MultiByteToWideChar(GetACP, MB_PRECOMPOSED, PAnsiChar(@strAnsi[1]), -1, PWideChar(@Result[1]), Len - 1);
end;
Constructor TProcessThread.Create(pi: TProcessInformation; cb: IProcessCallBack);
begin
inherited Create(true);
self.pi := pi;
self.cb := cb;
end;
procedure TProcessThread.Execute;
begin
inherited;
if cb <> nil then
cb.OnStart;
WaitForSingleObject(pi.hProcess, INFINITE);
if cb <> nil then
cb.OnExit;
end;
Constructor TProcess.Create(cmdln: string; show: boolean; env: String; cb: IProcessCallBack);
begin
CommandLine := cmdln;
Environment := env;
Callback := cb;
with SecurityAttr do
begin
nLength := sizeof(TSecurityAttributes);
lpSecurityDescriptor := nil;
bInheritHandle := true;
end;
with StartupInfo do
begin
cb := sizeof(StartupInfo);
lpReserved := nil;
lpReserved2 := nil;
lpDesktop := nil;
lpTitle := nil;
dwX := 0; dwY := 0;
dwXSize := 0; dwYSize := 0;
dwXCountChars := 0; dwYCountChars := 0;
dwFillAttribute := 0;
cbReserved2 := 0;
dwFlags := STARTF_USESHOWWINDOW;
if Show then
wShowWindow := 1
else
wShowWindow := 0;
end;
end;
Procedure TProcess.StartProcess;
begin
if CreateProcess(nil, PWideChar(WideString(CommandLine)), @SecurityAttr, @SecurityAttr, true, NORMAL_PRIORITY_CLASS, nil, PWideChar(WideString(GetCurrentDir)), StartupInfo, ProcessInfo) then
begin
t := TProcessThread.Create(ProcessInfo, Callback);
t.Start;
end
else if callback <> nil then
callback.OnFail;
end;
end.
|
unit fGMV_DateTimeDLG;
{
================================================================================
*
* Application: Vitals
* Revision: $Revision: 1 $ $Modtime: 9/08/08 1:43p $
* Developer: dddddddddomain.user@domain.ext
* Site: Hines OIFO
*
* Description: This is an Date/Time Selection Dialog
*
* Notes: Originally compiled in Delphi V
* Uses routines from uGMV-Common module:
* uGMV-Common.CallServer(...) -- to call 'GMV GET CURRENT TIME' routine,
* to reteive M-date/time
* uGMV-Common.FMDateTimeToWindowsDateTime(...)
* -- to convert M-date/time
*
================================================================================
* $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSCOMMON/fGMV_DateTimeDLG.pas $
*
* $History: fGMV_DateTimeDLG.pas $
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 8/12/09 Time: 8:29a
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 3/09/09 Time: 3:38p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/13/09 Time: 1:26p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/14/07 Time: 10:30a
* Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSDATETIME
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:43p
* Created in $/Vitals/VITALS-5-0-18/VitalsDateTime
* GUI v. 5.0.18 updates the default vital type IENs with the local
* values.
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:33p
* Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsDateTime
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/24/05 Time: 3:37p
* Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsDateTime
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 4/16/04 Time: 4:21p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSDATETIME
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 2/02/04 Time: 5:18p
* Updated in $/VitalsLite/DateTimeDLL
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/30/04 Time: 4:34p
* Created in $/VitalsLite/DateTimeDLL
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/15/04 Time: 3:06p
* Created in $/VitalsLite/VitalsLiteDLL
* Vitals Lite DLL
*
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ComCtrls, ExtCtrls;
type
TfGMV_DateTime = class(TForm)
Panel1: TPanel;
grpBoxDT: TGroupBox;
Panel2: TPanel;
pnlDate: TPanel;
Panel5: TPanel;
bbtnToday: TBitBtn;
mncCalendar: TMonthCalendar;
Panel6: TPanel;
lbxHours: TListBox;
lbxMinutes: TListBox;
Panel4: TPanel;
bbtnMidnight: TBitBtn;
bbtnNow: TBitBtn;
SpeedButton2: TSpeedButton;
SpeedButton1: TSpeedButton;
edtTime: TEdit;
pnlDateTimeText: TPanel;
Label1: TLabel;
bbtnYesterday: TBitBtn;
bbtnTomorrow: TBitBtn;
Timer1: TTimer;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure lbxHoursClick(Sender: TObject);
procedure lbxMinutesClick(Sender: TObject);
procedure edtTimeKeyPress(Sender: TObject; var Key: Char);
procedure bbtnNowClick(Sender: TObject);
procedure bbtnMidnightClick(Sender: TObject);
procedure bbtnTodayClick(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure edtTimeChange(Sender: TObject);
procedure mncCalendarClick(Sender: TObject);
procedure SetDateTimeText;
procedure UpdateText;
procedure bbtnYesterdayClick(Sender: TObject);
procedure bbtnTomorrowClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure lbxHoursEnter(Sender: TObject);
private
{ Private declarations }
dltTime: TDateTime;
fLastHour: integer;
fLastMin: integer;
procedure SetDateTime;
function TimeIsValid(h, m: Integer): Boolean;
procedure SetButtonState;
procedure setServerDelay;
procedure setTimeBoundaries;
public
{ Public declarations }
end;
var
fGMV_DateTime: TfGMV_DateTime;
implementation
uses
uGMV_Common,
uGMV_Engine, uGMV_Const, system.UITypes, DateUtils
;
{$IFDEF DATETIMEDLL}
var
PrevApp: TApplication;
PrevScreen: TScreen;
{$ENDIF}
{$R *.DFM}
procedure TfGMV_DateTime.FormCreate(Sender: TObject);
begin
//{$IFDEF DLL}
// fix Remedy 154038 --------------------------------------------------- start
// prior to this fix the code was used within DLL only
setServerDelay;
//{$ELSE}
// dltTime := 0;
// edtTime.Text := FormatDateTime('hh:mm',Now);
//{$ENDIF}
// fix Remedy 154038 ----------------------------------------------------- end
fLastHour := -1;
fLastMin := -1;
Caption := 'Select Date & Time up to ' + FormatDateTime('mm/dd/yyyy', mncCalendar.MaxDate) + ' and current time';
end;
procedure TfGMV_DateTime.setServerDelay;
var
aNow: TDateTime;
s: string;
f: Real;
begin
aNow := Now;
try
s := getCurrentDateTime;
if s <> '' then
try
f := StrToFloat(s);
f := FMDateTimeToWindowsDateTime(f);
dltTime := aNow - f;
aNow := f;
except
on E: EConvertError do
begin
MessageDlg('Unable to set client to the servers time.', mtWarning, [mbok], 0);
dltTime := 0;
aNow := Now;
edtTime.Text := FormatDateTime('hh:mm', aNow);
end;
end;
except
on E: EConvertError do
MessageDlg('Unable to get the servers time.', mtWarning, [mbok], 0);
end;
grpBoxDT.Caption := '';
mncCalendar.MaxDate := aNow;
mncCalendar.Date := mncCalendar.MaxDate;
setTimeBoundaries;
end;
procedure TfGMV_DateTime.SetDateTime;
var
S: string;
i, j: Integer;
begin
try
if lbxHours.ItemIndex = -1 then
i := 0
else
i := StrToInt(lbxHours.Items[lbxHours.ItemIndex]);
except
i := 0;
end;
try
if lbxMinutes.ItemIndex = -1 then
j := 0
else begin
S := lbxMinutes.Items[lbxMinutes.ItemIndex];
while (pos('0', S) = 1) or (pos(':', S) = 1) do
S := copy(s, 2, Length(S) - 1);
if pos(' --', S) = 1 then
j := 0
else
j := StrToInt(Piece(S, ' ', 1));
end;
except
j := 0;
end;
if TimeIsValid(i, j) then
edtTime.Text := Format('%2.2d:%2.2d', [i, j])
else
begin
MessageDlg('Sorry, you cannot select a future date or time' + #13 + #13 +
'or date more than 1 year old'
, mtError, [mbOk], 0)
end;
SetDateTimeText;
end;
procedure TfGMV_DateTime.lbxHoursClick(Sender: TObject);
begin
SetDateTime;
end;
procedure TfGMV_DateTime.lbxHoursEnter(Sender: TObject);
begin
setTimeBoundaries;
end;
procedure TfGMV_DateTime.lbxMinutesClick(Sender: TObject);
begin
SetDateTime;
end;
procedure TfGMV_DateTime.edtTimeKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
try
UpdateText;
except
MessageDlg('Invalid time string.', mtError, [mbOk], 0);
activecontrol := edtTime;
end;
end;
end;
procedure TfGMV_DateTime.UpdateText;
begin
begin
try
SetDateTimeText;
except
MessageDlg('Check time value!', mtError, [mbYes, mbCancel], 0);
end;
end;
end;
procedure TfGMV_DateTime.bbtnNowClick(Sender: TObject);
var
aNow: TDateTime;
begin
setServerDelay;
aNow := Now - dltTime;
edtTime.Text := FormatDateTime(GMV_TimeFormat, aNow);
try
mncCalendar.MinDate := 0;
mncCalendar.MinDate := aNow - 365;
except
end;
mncCalendar.MaxDate := aNow;
mncCalendar.Date := aNow;
setTimeBoundaries;
caption := 'Select Date & Time up to ' + FormatDateTime('mm/dd/yyyy', mncCalendar.MaxDate) + ' and current time';
SetButtonState;
updateText;
try
lbxHours.ItemIndex := -1;
lbxMinutes.ItemIndex := -1;
except
end;
end;
procedure TfGMV_DateTime.bbtnMidnightClick(Sender: TObject);
begin
edtTime.Text := FormatDateTime('hh:mm', 0);
updateText;
try
lbxHours.ItemIndex := -1;
lbxMinutes.ItemIndex := -1;
except
end;
end;
procedure TfGMV_DateTime.bbtnTodayClick(Sender: TObject);
begin
mncCalendar.Date := Now - dltTime;
setTimeBoundaries;
SetDateTimeText;
bbtnTomorrow.Enabled := False;
end;
procedure TfGMV_DateTime.SpeedButton1Click(Sender: TObject);
var
T, aNow, aDte: TDateTime;
begin
try
//Dont expect an exception
if Trim(edtTime.Text) = '' then
begin
MessageDlg('Invalid time string.', mtError, [mbOk], 0);
activecontrol := edtTime;
exit;
end;
//Dont expect an exception
if StrToTimeDef(edtTime.Text, -1) = -1 then
begin
MessageDlg('Invalid time string.', mtError, [mbOk], 0);
activecontrol := edtTime;
exit;
end;
T := StrToTime(edtTime.Text);
aNow := Now - dltTime;
if (DateOf(mncCalendar.Date) = DateOf(aNow)) and
((HourOf(T) > HourOf(aNow)) or ((HourOf(T) = HourOf(aNow)) and (MinuteOf(t) > MinuteOf(aNow)))) then
begin
MessageDlg('Time can not be greater than current time ('+FormatDateTime('hh:mm', aNow)+')', mtError, [mbOk], 0);
activecontrol := edtTime;
edtTime.Text := FormatDateTime('hh:mm', aNow);
exit;
end;
aDte := EncodeDateTime(YearOf(mncCalendar.Date), MonthOf(mncCalendar.Date), DayOf(mncCalendar.Date),
HourOf(t), MinuteOf(t), SecondOf(T), MilliSecondOf(T));
if aDte > aNow then
MessageDlg('Sorry, you cannot select a future date or time', //AAN 10/30/2002
mtError, [mbOk], 0) //AAN 10/30/2002
else if (T + trunc(mncCalendar.Date)) < mncCalendar.MinDate then
MessageDlg('Sorry, you cannot select a date more than 1 year old', //AAN 2003/06/04
mtError, [mbOk], 0) //AAN 2003/06/04
else
ModalResult := mrOK
except
MessageDlg('Invalid time string.', mtError, [mbOk], 0);
activecontrol := edtTime;
end;
end;
procedure TfGMV_DateTime.SpeedButton2Click(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TfGMV_DateTime.edtTimeChange(Sender: TObject);
begin
SetDateTimeText;
end;
procedure TfGMV_DateTime.SetDateTimeText;
begin
pnlDateTimeText.Caption := FormatDateTime(' mm/dd/yy ', mncCalendar.Date) + edtTime.Text;
end;
procedure TfGMV_DateTime.mncCalendarClick(Sender: TObject);
begin
setTimeBoundaries;
SetDateTimeText;
SetButtonState;
end;
function TfGMV_DateTime.TimeIsValid(h, m: Integer): boolean;
begin
result :=
(trunc(mncCalendar.Date) + h / 24 + m / 24 / 60 < mncCalendar.MaxDate)
and
(mncCalendar.MinDate < trunc(mncCalendar.Date) + h / 24 + m / 24 / 60);
end;
procedure TfGMV_DateTime.bbtnYesterdayClick(Sender: TObject);
begin
try
mncCalendar.Date := mncCalendar.Date - 1;
setTimeBoundaries;
UpdateText;
SetButtonState;
except
end;
end;
procedure TfGMV_DateTime.bbtnTomorrowClick(Sender: TObject);
begin
try
mncCalendar.Date := mncCalendar.Date + 1;
setTimeBoundaries;
UpdateText;
SetButtonState;
except
end;
end;
procedure TfGMV_DateTime.SetButtonState;
begin
if trunc(mncCalendar.Date) = trunc(mncCalendar.MaxDate) then
bbtnTomorrow.Enabled := False
else
bbtnTomorrow.Enabled := True;
if trunc(mncCalendar.Date) = trunc(mncCalendar.MinDate) then
bbtnYesterday.Enabled := False
else
bbtnYesterday.Enabled := True;
end;
procedure TfGMV_DateTime.FormActivate(Sender: TObject);
begin
updateText;
SetButtonState;
end;
procedure TfGMV_DateTime.Timer1Timer(Sender: TObject);
var
aNow: TDateTime;
begin
try
aNow := Now - dltTime;
label2.Caption := FormatDateTime(GMV_DateTimeFormat, aNow);
mncCalendar.MaxDate := aNow;
setTimeBoundaries;
except
end;
end;
procedure TfGMV_DateTime.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = char(VK_ESCAPE) then
ModalResult := mrCancel;
end;
procedure TfGMV_DateTime.setTimeBoundaries;
const
AllHours: array [0 .. 23] of integer = (00, 01, 02, 03, 04, 05, 06, 07, 08,
09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23);
AllMinutes: Array [0 .. 11] of integer = (00, 05, 10, 15, 20, 25, 30, 35, 40,
45, 50, 55);
Procedure AddAllToHourListBox;
var
i: integer;
TxtToAdd: String;
begin
if fLastHour <> -1 then
begin
lbxHours.Clear;
for i := Low(AllHours) to High(AllHours) do
begin
if AllHours[i] < 10 then
TxtToAdd := '0' + IntToStr(AllHours[i])
else
TxtToAdd := IntToStr(AllHours[i]);
lbxHours.Items.Add(TxtToAdd);
end;
fLastHour := -1;
end;
end;
Procedure AddAllToMinuteListBox;
var
i: integer;
LookUpTxt: String;
begin
if fLastMin <> -1 then
begin
lbxMinutes.Clear;
for i := Low(AllMinutes) to High(AllMinutes) do
begin
if Odd(AllMinutes[i]) then
begin
if AllMinutes[i] < 10 then
LookUpTxt := ':0' + IntToStr(AllMinutes[i])
else
LookUpTxt := ':' + IntToStr(AllMinutes[i]);
end
else
begin
if AllMinutes[i] < 10 then
LookUpTxt := ':0' + IntToStr(AllMinutes[i]) + ' --'
else
LookUpTxt := ':' + IntToStr(AllMinutes[i]) + ' --';
end;
lbxMinutes.Items.Add(LookUpTxt);
end;
fLastMin := -1;
end;
end;
Procedure AdjustListBox;
var
aHour, aMinute: word;
aNow: TDateTime;
LookUpTxt: String;
i, Indx: integer;
begin
aNow := Now - dltTime;
aHour := HourOf(aNow);
if fLastHour <> aHour then
begin
for i := high(AllHours) downto low(AllHours) do
begin
if AllHours[i] < 10 then
LookUpTxt := '0' + IntToStr(AllHours[i])
else
LookUpTxt := IntToStr(AllHours[i]);
Indx := lbxHours.Items.IndexOf(LookUpTxt);
if Indx < 0 then
begin
if AllHours[i] <= aHour then
lbxHours.Items.Add(LookUpTxt)
end
else if AllHours[i] > aHour then
lbxHours.Items.Delete(Indx);
end;
if lbxHours.ItemIndex > aHour then
begin
lbxHours.ItemIndex := -1;
SetDateTime;
end;
fLastHour := aHour;
end;
// Do we need to limit the minutes
if lbxHours.ItemIndex = aHour then
begin
aMinute := MinuteOf(aNow);
if fLastMin <> aMinute then
begin
for i := High(AllMinutes) Downto Low(AllMinutes) do
begin
if Odd(AllMinutes[i]) then
begin
if AllMinutes[i] < 10 then
LookUpTxt := ':0' + IntToStr(AllMinutes[i])
else
LookUpTxt := ':' + IntToStr(AllMinutes[i]);
end
else
begin
if AllMinutes[i] < 10 then
LookUpTxt := ':0' + IntToStr(AllMinutes[i]) + ' --'
else
LookUpTxt := ':' + IntToStr(AllMinutes[i]) + ' --';
end;
Indx := lbxMinutes.Items.IndexOf(LookUpTxt);
if Indx < 0 then
begin
if AllMinutes[i] <= aMinute then
lbxMinutes.Items.Add(LookUpTxt);
end
else if AllMinutes[i] > aMinute then
lbxMinutes.Items.Delete(Indx);
end;
if lbxMinutes.ItemIndex > aMinute then
begin
lbxMinutes.ItemIndex := -1;
SetDateTime;
end;
fLastMin := aMinute;
end;
end
else
AddAllToMinuteListBox;
end;
var
aNow: TDateTime;
begin
aNow := Now - dltTime;
if DateOf(mncCalendar.Date) = DateOf(aNow) then
begin
// Need to set the hour
AdjustListBox;
end
else
begin
// Not on the max date so all time is good
AddAllToHourListBox;
AddAllToMinuteListBox;
end;
end;
{$IFDEF DATETIMEDLL}
initialization
PrevApp := Application;
PrevScreen := Screen;
finalization
Application := PrevApp;
Screen := PrevScreen;
{$ENDIF}
end.
|
unit FC.Trade.TerminalFrame;
{$I Compiler.inc}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtendControls, FC.Trade.ResultPage, ExtCtrls, Menus, ActnPopup, DB,
MemoryDS, ActnList, ComCtrls, ToolWin, StdCtrls, TeEngine, Series, TeeProcs,
Chart, Grids, DBGrids, MultiSelectDBGrid, ColumnSortDBGrid, EditDBGrid,
JvExComCtrls, JvComCtrls, PlatformDefaultStyleActnCtrls, FC.Definitions,Collections.Map;
type
TfrmTerminalFrame = class(TfrmStockTradeResult)
acModifyOrder: TAction;
N2: TMenuItem;
miModifyOrder: TMenuItem;
acCloseOrder: TAction;
CloseOrder1: TMenuItem;
procedure acCloseOrderUpdate(Sender: TObject);
procedure acModifyOrderExecute(Sender: TObject);
procedure acModifyOrderUpdate(Sender: TObject);
private type
TOrderMap = TMap<TGUID,IStockOrder>; //Order Id -> IStockOrder
private
FOrders : TOrderMap;
FWorking : boolean;
function GetSelectedOrder: IStockOrder;
public
procedure OnNewOrder(const aOrder: IStockOrder); override;
procedure OnStart(const aBroker: IStockBroker; const aTrader:IStockTrader); override;
procedure OnEnd; override;
property SelectedOrder: IStockOrder read GetSelectedOrder;
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses BaseUtils;
{$R *.dfm}
procedure TfrmTerminalFrame.acCloseOrderUpdate(Sender: TObject);
var
aSelectedOrder:IStockOrder;
begin
aSelectedOrder:=SelectedOrder;
TAction(Sender).Enabled:=FWorking and (aSelectedOrder<>nil) and (aSelectedOrder.GetState in [osPending,osOpened]);
end;
procedure TfrmTerminalFrame.acModifyOrderExecute(Sender: TObject);
begin
inherited;
//TODO доделать
raise ENotSupported.Create;
end;
procedure TfrmTerminalFrame.acModifyOrderUpdate(Sender: TObject);
var
aSelectedOrder:IStockOrder;
begin
aSelectedOrder:=SelectedOrder;
TAction(Sender).Enabled:=FWorking and (aSelectedOrder<>nil) and (aSelectedOrder.GetState in [osPending,osOpened]);
end;
constructor TfrmTerminalFrame.Create(aOwner: TComponent);
begin
inherited;
Mode:=tmReal;
FOrders:=TOrderMap.Create;
end;
destructor TfrmTerminalFrame.Destroy;
begin
FreeAndNil(FOrders);
inherited;
end;
function TfrmTerminalFrame.GetSelectedOrder: IStockOrder;
begin
result:=nil;
if (taOrders.Active) and (not taOrders.Eof) and (not taOrders.Bof) then
FOrders.Lookup(StringToGUID(taOrdersOrderID.Value),result);
end;
procedure TfrmTerminalFrame.OnEnd;
begin
inherited;
FWorking:=false;
end;
procedure TfrmTerminalFrame.OnNewOrder(const aOrder: IStockOrder);
begin
inherited;
FOrders.Add(aOrder.GetID,aOrder);
end;
procedure TfrmTerminalFrame.OnStart(const aBroker: IStockBroker; const aTrader: IStockTrader);
begin
inherited;
FOrders.Clear;
FWorking:=true;
end;
end.
|
unit SHL_PlayStream; // SemVersion: 0.2.0
// Contains TPlayStream class for playing WAVE sounds.
// Currently only for Windows!
// Changelog:
// 0.1.0 - test version
// 0.2.0 - position, wavestream, volume
// TODO:
// - error exceptions
// - emulated device
// - Linux compatibility?
interface // SpyroHackingLib is licensed under WTFPL
uses
Windows, MMSystem, SysUtils, Classes, Contnrs, SHL_Types, SHL_WaveStream;
type
// one local stream of audio
TPlayStream = class(TStream)
// stream can be instantiated by default Create(); this constructor will call Open:
constructor Create(Device: Integer; Samples: Integer; IsStereo: Boolean; Is16Bit: Boolean = True; Limit: Integer = 4); overload;
// get all settings from a TWaveStream:
constructor Create(Device: Integer; WaveStream: TWaveStream; Limit: Integer = 4); overload;
// Free will stop the sound
destructor Destroy(); override;
private
FDevice: THandle; // handle to a device
FLimit: Integer; // buffers count for Write
FSize: Integer; // track of used memory
FEvent: THandle; // when audio buffer done
FBuffers: TQueue; // play sequence
FPaused: Boolean; // user request
FIsStereo: Boolean; // stereo format
FIs16Bit: Boolean; // 16-bit format
FSamples: Integer; // sample rate
FVolume: Byte; // ratio to lower sound volume, in 2^n, 0..15
FDump: TWaveStream; // debug wave file output
procedure SetPause(Pause: Boolean); // toggle pause
public
// get all devices, result is a list of names:
class function EnumDrivers(): ArrayOfWide;
// open sound driver (-1 for default mixer), set stream properties; true if successful:
function Open(Device: Integer; Samples: Integer; IsStereo: Boolean; Is16Bit: Boolean = True; Limit: Integer = 4): Boolean; overload;
// for second constructor:
function Open(Device: Integer; WaveStream: TWaveStream; Limit: Integer = 4): Boolean; overload;
// stop sound and close driver:
procedure Close();
// copy sound data buffer, put in the queue, play immediately if not paused; true when ok:
function Send(WaveData: Pointer; SizeInBytes: Integer): Boolean;
// plays specifed wave stream up to Bytes, or until there no more data:
procedure Play(FromStream: TStream; Bytes: Integer = -1);
// block execution until this or less buffers are left; -1 means Limit:
procedure WaitFor(Count: Integer = -1);
// check the queue and return size; remove played buffers and free memory:
function InQueue(): Integer;
// for debugging, set a wave file to copy all played sound data there; empty = stop dumping:
procedure Dump(Filename: WideString = '');
// for streaming support; calls WaitFor(Limit) and Send:
function Write(const Buffer; Count: Longint): Longint; override;
// not supported, zero:
function Read(var Buffer; Count: Longint): Longint; override;
// also not supported, zero:
function Seek(Offset: Longint; Origin: Word): Longint; override;
// set to true to prevent playing after :
property Paused: Boolean read FPaused write SetPause;
// auto buffer limit for Write:
property Limit: Integer read FLimit write FLimit;
// properties of sound:
property IsStereo: Boolean read FIsStereo;
property Is16Bit: Boolean read FIs16Bit;
property Volume: Byte read FVolume write FVolume; // effect for all new buffers
protected
// Size will return the used memory in bytes:
function GetSize(): Int64; override;
// return number of played samples:
function GetPosition(): Cardinal;
public
property Position: Cardinal read GetPosition;
end;
implementation
class function TPlayStream.EnumDrivers(): ArrayOfWide;
var
Len, Index: Integer;
Caps: WAVEOUTCAPSW;
begin
Len := waveOutGetNumDevs(); // get drivers count
ZeroMemory(@Caps, SizeOf(Caps));
if Len < 0 then
Len := 0;
SetLength(Result, Len);
for Index := 0 to Len - 1 do
begin // get each name:
waveOutGetDevCapsW(Index, @Caps, SizeOf(Caps));
Result[Index] := Caps.szPname;
end;
end;
constructor TPlayStream.Create(Device: Integer; Samples: Integer; IsStereo: Boolean; Is16Bit: Boolean = True; Limit: Integer = 4);
begin
if not Open(Device, Samples, IsStereo, Is16Bit, Limit) then
Abort;
end;
constructor TPlayStream.Create(Device: Integer; WaveStream: TWaveStream; Limit: Integer = 4);
begin
if not Open(Device, WaveStream, Limit) then
Abort;
end;
destructor TPlayStream.Destroy();
begin
Dump(); // flush dump-file
Close(); // stop sound, free all buffers
if FEvent <> 0 then
CloseHandle(FEvent); // free event
FBuffers.Free(); // destroy empty queue
end;
function TPlayStream.Open(Device: Integer; Samples: Integer; IsStereo: Boolean; Is16Bit: Boolean = True; Limit: Integer = 4): Boolean;
var
Format: TWaveFormatEx;
begin
if Device < 0 then
Device := Integer(WAVE_MAPPER); // default device
if FEvent = 0 then
FEvent := CreateEvent(nil, False, False, nil); // at first call
if FBuffers = nil then
FBuffers := TQueue.Create(); // at first call
FLimit := Limit;
Close(); // stop and discard remaining stuff
ZeroMemory(@Format, SizeOf(Format));
// fill format:
Format.wFormatTag := WAVE_FORMAT_PCM;
FIsStereo := IsStereo;
FIs16Bit := Is16Bit;
if FIsStereo then
Format.nChannels := 2
else
Format.nChannels := 1;
FSamples := Samples;
Format.nSamplesPerSec := FSamples;
if FIs16Bit then
Format.wBitsPerSample := 16
else
Format.wBitsPerSample := 8;
Format.nBlockAlign := Format.nChannels * Format.wBitsPerSample div 8;
Format.nAvgBytesPerSec := Format.nSamplesPerSec * Format.nBlockAlign;
// get handle:
Result := (waveOutOpen(@FDevice, Device, @Format, FEvent, 0, CALLBACK_EVENT) = MMSYSERR_NOERROR) and (FDevice <> 0);
end;
function TPlayStream.Open(Device: Integer; WaveStream: TWaveStream; Limit: Integer = 4): Boolean;
begin
Result := Open(Device, WaveStream.SampleRate, WaveStream.IsStereo, WaveStream.Is16Bit, Limit);
end;
procedure TPlayStream.Close();
var
Header: PWaveHdr;
begin
if FDevice <> 0 then
begin
waveOutReset(FDevice); // stop sound
waveOutClose(FDevice); // free driver
FDevice := 0;
end;
while FBuffers.Count > 0 do
begin // free all memory:
Header := PWaveHdr(FBuffers.Pop());
Dec(FSize, Header.dwUser);
waveOutUnprepareHeader(FDevice, Header, SizeOf(TWaveHdr));
FreeMem(Header);
end;
end;
function TPlayStream.Send(WaveData: Pointer; SizeInBytes: Integer): Boolean;
var
Header: PWaveHdr;
MemSize, Mask, Value, Total: Integer;
Source, Desten: PInteger;
begin
Result := False;
if (FDevice = 0) or (SizeInBytes < 2) then // no Open
Exit;
MemSize := SizeOf(TWaveHdr) + SizeInBytes;
GetMem(Header, MemSize); // data will be after a header
ZeroMemory(Header, SizeOf(TWaveHdr));
Header.lpData := (PDataChar(Header)) + SizeOf(TWaveHdr); // here
Header.dwBufferLength := SizeInBytes;
if FVolume > 0 then // volume control
begin
if FVolume < 16 then // effective
begin
Total := SizeInBytes shr 2; // num of words
Source := Pointer(WaveData);
Desten := Pointer(Header.lpData);
if FIs16Bit then // 16-bit algo
begin
Mask := 1 shl (15 - FVolume); // mask bit to sign-extend
while Total <> 0 do
begin
Value := Source^; // actually, a shift and sign-extend operation for lower and upper half:
Desten^ := (((((Value and $ffff) shr FVolume) xor Mask) - Mask) and $ffff) or ((((Value shr 16) shr FVolume) xor Mask) - Mask) shl 16;
Inc(Source);
Inc(Desten);
Dec(Total);
end
end
else
begin // 8-bit algo
Mask := $ff shr FVolume;
Mask := Mask or (Mask shl 8) or (Mask shl 16) or (Mask shl 24); // mask of effective bits
Value := Cardinal($80808080) - (Cardinal($80808080) shr FVolume); // difference to center the value
while Total <> 0 do
begin
Desten^ := ((Source^ shr FVolume) and Mask) + Value; // shift and adjust to center
Inc(Source);
Inc(Desten);
Dec(Total);
end;
end;
end
else
ZeroMemory(Header.lpData, SizeInBytes);
end
else
Move(WaveData^, Header.lpData^, SizeInBytes); // just copy samples
if FDump <> nil then // debug stream
FDump.WriteBuffer(Header.lpData^, SizeInBytes);
Header.dwUser := MemSize; // size of memory to keep track
if waveOutPrepareHeader(FDevice, Header, SizeOf(TWaveHdr)) = MMSYSERR_NOERROR then
begin // ok block
if waveOutWrite(FDevice, Header, SizeOf(TWaveHdr)) <> MMSYSERR_NOERROR then
begin // fail write
waveOutUnprepareHeader(FDevice, Header, SizeOf(TWaveHdr)); // free block
FreeMem(Header);
Result := False;
end
else
begin
Result := True;
Inc(FSize, MemSize);
FBuffers.Push(Header); // fill queue
end;
end;
end;
procedure TPlayStream.Play(FromStream: TStream; Bytes: Integer = -1);
const
Size = 32768;
var
Buffer: array[0..Size - 1] of Byte;
Count, Value: Integer;
One: Boolean;
begin
if Bytes = 0 then
begin
Bytes := -1;
One := True;
end
else
One := False;
if Bytes = -1 then
Bytes := $7fffffff;
while Bytes > 0 do
begin
Value := Bytes;
if Value > Size then
Value := Size;
Count := FromStream.Read(Buffer, Value);
if Count <= 0 then
Break;
Write(Buffer, Count);
Dec(Bytes, Count);
if One then
Break;
end;
end;
procedure TPlayStream.SetPause(Pause: Boolean);
begin
FPaused := Pause; // no check of previous state
if FPaused then
waveOutPause(FDevice)
else
waveOutRestart(FDevice); // ok to call already resumed
end;
function TPlayStream.InQueue(): Integer;
var
Header: PWaveHdr;
begin
Result := 0;
if FBuffers = nil then // no Open
Exit;
while FBuffers.Count > 0 do
begin // check all:
Header := FBuffers.Peek();
if (Header.dwFlags and WHDR_DONE) = 0 then // this is not done yet
Break;
Dec(FSize, Header.dwUser);
waveOutUnprepareHeader(FDevice, Header, SizeOf(TWaveHdr));
FreeMem(Header); // this is done, free it
FBuffers.Pop();
end;
Result := FBuffers.Count; // active buffers
end;
procedure TPlayStream.Dump(Filename: WideString = '');
begin
if Filename = '' then
begin
if FDump = nil then
Exit;
FreeAndNil(FDump);
end
else
begin
if FDump <> nil then
Dump();
FDump := TWaveStream.CreateNew(Filename);
FDump.WriteHeader(FSamples, FIsStereo, FIs16Bit);
end;
end;
procedure TPlayStream.WaitFor(Count: Integer = -1);
begin
if FDevice = 0 then
Exit;
if Count < 0 then
begin
Count := FLimit;
if Count < 0 then
Exit;
end;
FPaused := False;
waveOutRestart(FDevice); // shouldn't wait in paused state
ResetEvent(FEvent);
while InQueue() > Count do // continiously checking
WaitForSingleObject(FEvent, INFINITE); // fired when a buffer is done
end;
function TPlayStream.Write(const Buffer; Count: Longint): Longint;
begin
WaitFor(Limit); // default 4, can be set by user
if Send(@Buffer, Count) then
Result := Count // ok
else
Result := 0; // fail
end;
function TPlayStream.GetSize(): Int64;
begin
Result := FSize; // size of memory used
end;
function TPlayStream.GetPosition(): Cardinal;
var
Time: tMMTIME;
begin
Time.wType := TIME_SAMPLES; // set samples format
waveOutGetPosition(FDevice, @Time, SizeOf(Time));
Result := Time.sample;
end;
function TPlayStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
Result := 0; // impossible
end;
function TPlayStream.Read(var Buffer; Count: Longint): Longint;
begin
Result := 0; // impossible
end;
end.
|
unit uROR_CustomListView;
{$I Components.inc}
interface
uses
ComCtrls, Controls, Classes, Graphics, Variants, uROR_Utilities, Messages,
CommCtrl, Windows;
type
TCCRCustomListView = class;
TCCRFindStringMode = set of (fsmCase, fsmInclusive, fsmPartial, fsmWrap);
//--------------------------- TCCRCustomListItem(s) --------------------------
TCCRCustomListItem = class(TListItem)
private
fUpdateLock: Integer;
function getListView: TCCRCustomListView;
function getStringValue(aColumnIndex: Integer): String;
procedure setStringValue(aColumnIndex: Integer; const aValue: String);
protected
function getFieldValue(const aFieldIndex: Integer;
var anInternalValue: Variant): String; virtual; abstract;
property UpdateLock: Integer read fUpdateLock;
public
procedure BeginUpdate; virtual;
procedure EndUpdate; virtual;
procedure UpdateStringValues(const aFieldIndex: Integer = -1); virtual;
property ListView: TCCRCustomListView read getListView;
property StringValues[aColumnIndex: Integer]: String read getStringValue
write setStringValue;
end;
TCCRCustomListItems = class(TListItems)
private
function getItem(anIndex: Integer): TCCRCustomListItem;
procedure setItem(anIndex: Integer; const aValue: TCCRCustomListItem);
public
property Item[anIndex: Integer]: TCCRCustomListItem read getItem
write setItem;
default;
end;
//----------------------------- TCCRCustomListView ---------------------------
TCCRCustomListView = class(TCustomListView)
private
fColor: TColor;
fSortDescending: Boolean;
fSortField: Integer;
function getItems: TCCRCustomListItems;
procedure setColor(const aColor: TColor);
protected
procedure ColClick(aColumn: TListColumn); override;
procedure CompareItems(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer); virtual;
procedure CreateWnd; override;
procedure DoEnter; override;
function FindColumnIndex(pHeader: PNMHdr): Integer;
function FindColumnWidth(pHeader: PNMHdr): Integer;
function getSortColumn: Integer; virtual;
procedure InsertItem(anItem: TListItem); override;
procedure Loaded; override;
procedure SetEnabled(aValue: Boolean); override;
procedure setSortColumn(const aValue: Integer); virtual;
procedure setSortDescending(const aValue: Boolean); virtual;
procedure setSortField(const aValue: Integer); virtual;
procedure UpdateSortField; virtual;
property Color: TColor read fColor
write setColor
default clWindow;
property Items: TCCRCustomListItems read getItems;
property SortColumn: Integer read getSortColumn
write setSortColumn;
property SortDescending: Boolean read fSortDescending
write setSortDescending
default False;
property SortField: Integer read fSortField
write setSortField
default -1;
public
constructor Create(anOwner: TComponent); override;
destructor Destroy; override;
procedure Activate;
function ColumnIndex(const aFieldIndex: Integer;
const SortableOnly: Boolean = False): Integer; virtual;
procedure EnsureSelection;
function FieldIndex(const aColumnIndex: Integer;
const SortableOnly: Boolean = False): Integer; virtual;
function FindString(aValue: String; aFieldIndex: Integer;
aStartIndex: Integer = 0;
aMode: TCCRFindStringMode = [fsmInclusive]): TCCRCustomListItem;
end;
implementation
uses
uROR_Resources, ImgList, SysUtils, StrUtils;
const
imgAscending = 0;
imgDescending = 1;
var
DefaultImages: TImageList = nil;
DICount: Integer = 0;
function LoadDefaultImages: TImageList;
begin
if DICount <= 0 then
begin
if Assigned(DefaultImages) then
DefaultImages.Free;
DefaultImages := TImageList.Create(nil);
DefaultImages.ResInstLoad(HInstance, rtBitmap, 'SORT_ASCENDING', clFuchsia);
DefaultImages.ResInstLoad(HInstance, rtBitmap, 'SORT_DESCENDING', clFuchsia);
end;
Inc(DICount);
Result := DefaultImages;
end;
procedure UnloadDefaultImages;
begin
if DICount > 0 then
begin
Dec(DICount);
if DICount = 0 then
FreeAndNil(DefaultImages);
end;
end;
/////////////////////////////// TCCRCustomListItem \\\\\\\\\\\\\\\\\\\\\\\\\\\\\
procedure TCCRCustomListItem.BeginUpdate;
begin
if fUpdateLock = 0 then
SubItems.BeginUpdate;
Inc(fUpdateLock);
end;
procedure TCCRCustomListItem.EndUpdate;
begin
if fUpdateLock > 0 then
begin
Dec(fUpdateLock);
if fUpdateLock = 0 then
begin
UpdateStringValues;
SubItems.EndUpdate;
end;
end;
end;
function TCCRCustomListItem.getListView: TCCRCustomListView;
begin
Result := inherited ListView as TCCRCustomListView;
end;
function TCCRCustomListItem.getStringValue(aColumnIndex: Integer): String;
begin
if aColumnIndex = 0 then
Result := Caption
else if (aColumnIndex > 0) and (aColumnIndex <= SubItems.Count) then
Result := SubItems[aColumnIndex-1]
else
Result := '';
end;
procedure TCCRCustomListItem.setStringValue(aColumnIndex: Integer; const aValue: String);
var
i: Integer;
begin
if aColumnIndex = 0 then
Caption := aValue
else if (aColumnIndex > 0) and (aColumnIndex < ListView.Columns.Count) then
begin
if aColumnIndex > SubItems.Count then
for i:=ListView.Columns.Count-2 to SubItems.Count do
SubItems.Add('');
SubItems[aColumnIndex-1] := aValue;
end;
end;
procedure TCCRCustomListItem.UpdateStringValues(const aFieldIndex: Integer);
var
i, n: Integer;
iv: Variant;
begin
if Assigned(Data) and (UpdateLock = 0) then
if (aFieldIndex >= 0) and (aFieldIndex < ListView.Columns.Count) then
StringValues[aFieldIndex] := getFieldValue(aFieldIndex, iv)
else
begin
SubItems.BeginUpdate;
try
n := ListView.Columns.Count - 1;
for i:=0 to n do
StringValues[i] := getFieldValue(i, iv);
finally
SubItems.EndUpdate;
end;
end;
end;
/////////////////////////////// TCCRCustomListItems \\\\\\\\\\\\\\\\\\\\\\\\\\\\
function TCCRCustomListItems.getItem(anIndex: Integer): TCCRCustomListItem;
begin
Result := inherited Item[anIndex] as TCCRCustomListItem;
end;
procedure TCCRCustomListItems.setItem(anIndex: Integer; const aValue: TCCRCustomListItem);
begin
inherited Item[anIndex] := aValue;
end;
/////////////////////////////// TCCRCustomListView \\\\\\\\\\\\\\\\\\\\\\\\\\\\\
constructor TCCRCustomListView.Create(anOwner: TComponent);
begin
inherited;
BevelKind := bkNone;
GridLines := True;
OnCompare := CompareItems;
ParentColor := False;
ReadOnly := False;
SmallImages := LoadDefaultImages;
TabStop := True;
fColor := clWindow;
fSortDescending := False;
fSortField := -1;
end;
destructor TCCRCustomListView.Destroy;
begin
UnloadDefaultImages;
inherited;
end;
procedure TCCRCustomListView.Activate;
begin
if Items.Count > 0 then
begin
SetFocus;
EnsureSelection;
end;
end;
procedure TCCRCustomListView.ColClick(aColumn: TListColumn);
var
fldNdx: Integer;
begin
fldNdx := FieldIndex(aColumn.Index);
if fldNdx >= 0 then
if fldNdx <> SortField then
SortField := fldNdx
else
SortDescending := not SortDescending;
inherited;
end;
function TCCRCustomListView.ColumnIndex(const aFieldIndex: Integer;
const SortableOnly: Boolean): Integer;
begin
if (aFieldIndex >= 0) and (aFieldIndex < Columns.Count) then
Result := aFieldIndex
else
Result := -1;
end;
procedure TCCRCustomListView.CompareItems(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
var
iv1, iv2: Variant;
begin
Compare := 0;
if (SortField < 0) or (SortField >= Columns.Count) then
Exit;
TCCRCustomListItem(Item1).getFieldValue(SortField, iv1);
TCCRCustomListItem(Item2).getFieldValue(SortField, iv2);
case VarCompareValue(iv1, iv2) of
vrLessThan: Compare := -1;
vrGreaterThan: Compare := 1;
end;
if SortDescending then
Compare := -Compare;
end;
procedure TCCRCustomListView.CreateWnd;
var
wnd: HWND;
begin
inherited;
wnd := GetWindow(Handle, GW_CHILD);
SetWindowLong(wnd, GWL_STYLE,
GetWindowLong(wnd, GWL_STYLE) and not HDS_FULLDRAG);
end;
procedure TCCRCustomListView.DoEnter;
begin
inherited;
EnsureSelection;
end;
procedure TCCRCustomListView.EnsureSelection;
begin
if (Items.Count > 0) and (ItemIndex < 0) then
ItemIndex := 0;
if ItemIndex >= 0 then
ItemFocused := Items[ItemIndex];
end;
function TCCRCustomListView.FieldIndex(const aColumnIndex: Integer;
const SortableOnly: Boolean): Integer;
begin
if (aColumnIndex >= 0) and (aColumnIndex < Columns.Count) then
Result := aColumnIndex
else
Result := -1;
end;
function TCCRCustomListView.FindColumnIndex(pHeader: PNMHdr): Integer;
var
hwndHeader: HWND;
iteminfo: THdItem;
ItemIndex: Integer;
buf: array [0..128] of Char;
begin
Result := -1;
hwndHeader := pHeader^.hwndFrom;
ItemIndex := pHDNotify(pHeader)^.Item;
FillChar(iteminfo, SizeOf(iteminfo), 0);
iteminfo.Mask := HDI_TEXT;
iteminfo.pszText := buf;
iteminfo.cchTextMax := SizeOf(buf) - 1;
Header_GetItem(hwndHeader, ItemIndex, iteminfo);
if CompareStr(Columns[ItemIndex].Caption, iteminfo.pszText) = 0 then
Result := ItemIndex
else
begin
for ItemIndex := 0 to Columns.Count - 1 do
if CompareStr(Columns[ItemIndex].Caption, iteminfo.pszText) = 0 then
begin
Result := ItemIndex;
Break;
end;
end;
end;
function TCCRCustomListView.FindColumnWidth(pHeader: pNMHdr): Integer;
begin
Result := -1;
if Assigned(PHDNotify(pHeader)^.pItem) and
((PHDNotify(pHeader)^.pItem^.mask and HDI_WIDTH) <> 0) then
Result := PHDNotify(pHeader)^.pItem^.cxy;
end;
function TCCRCustomListView.FindString(aValue: String; aFieldIndex: Integer;
aStartIndex: Integer = 0; aMode: TCCRFindStringMode = [fsmInclusive]): TCCRCustomListItem;
var
n: Integer;
iv: Variant;
function find(aStartIndex, anEndIndex: Integer; aMode: TCCRFindStringMode): TCCRCustomListItem;
var
i: Integer;
Comparator: function(const aSubText, aText: String): Boolean;
begin
Result := nil;
if aStartIndex < 0 then
aStartIndex := 0;
if anEndIndex >= Items.Count then
anEndIndex := Items.Count - 1;
if fsmPartial in aMode then
if fsmCase in aMode then
Comparator := AnsiStartsStr
else
Comparator := AnsiStartsText
else
if fsmCase in aMode then
Comparator := AnsiSameStr
else
Comparator := AnsiSameText;
for i:=aStartIndex to anEndIndex do
if Comparator(aValue, Items[i].getFieldValue(aFieldIndex, iv)) then
begin
Result := Items[i];
Break;
end;
end;
begin
Result := nil;
if Items.Count > 0 then
begin
n := Items.Count - 1;
if fsmInclusive in aMode then
Result := find(aStartIndex, n, aMode)
else
Result := find(aStartIndex+1, n, aMode);
if (not Assigned(Result)) and (fsmWrap in aMode) then
begin
if fsmInclusive in aMode then
n := aStartIndex - 1
else
n := aStartIndex;
if n >= 0 then
Result := find(0, n, aMode);
end;
end;
end;
function TCCRCustomListView.getItems: TCCRCustomListItems;
begin
Result := inherited Items as TCCRCustomListItems;
end;
function TCCRCustomListView.getSortColumn: Integer;
begin
if (SortField >= 0) and (SortField < Columns.Count) then
Result := SortField
else
Result := -1;
end;
procedure TCCRCustomListView.InsertItem(anItem: TListItem);
var
i: Integer;
begin
with anItem do
begin
ImageIndex := -1;
Indent := -1;
SubItems.BeginUpdate;
try
for i:=2 to Columns.Count do
SubItems.Add('');
finally
SubItems.EndUpdate;
end;
end;
inherited;
end;
procedure TCCRCustomListView.Loaded;
begin
inherited;
if ParentColor then
begin
ParentColor := False; // Enforce correct Parent Color
ParentColor := True
end;
if (SortField >= 0) and (SortField < Columns.Count) then
UpdateSortField
else
SortField := -1;
end;
procedure TCCRCustomListView.setColor(const aColor: TColor);
begin
if aColor <> fColor then
begin
fColor := aColor;
if Enabled then
inherited Color := aColor;
end;
end;
procedure TCCRCustomListView.SetEnabled(aValue: Boolean);
begin
if aValue <> Enabled then
begin
inherited;
if aValue then
inherited Color := fColor
else
inherited Color := clBtnFace;
end;
end;
procedure TCCRCustomListView.setSortColumn(const aValue: Integer);
begin
if (aValue <> SortColumn) and (aValue < Columns.Count) then
SortField := FieldIndex(aValue);
end;
procedure TCCRCustomListView.setSortDescending(const aValue: Boolean);
begin
if aValue <> fSortDescending then
begin
fSortDescending := aValue;
if SortField >= 0 then
begin
UpdateSortField;
AlphaSort;
end;
end;
end;
procedure TCCRCustomListView.setSortField(const aValue: Integer);
begin
if aValue <> fSortField then
if aValue >= 0 then
begin
if SortColumn >= 0 then
Columns[SortColumn].ImageIndex := -1;
fSortField := aValue;
fSortDescending := False;
UpdateSortField;
if SortType <> stBoth then
SortType := stBoth
else
AlphaSort;
end
else
begin
if SortColumn >= 0 then
Columns[SortColumn].ImageIndex := -1;
fSortField := -1;
SortType := stNone;
end;
end;
procedure TCCRCustomListView.UpdateSortField;
begin
if (SortColumn >= 0) and (SortColumn < Columns.Count) then
begin
if SortDescending then
Columns[SortColumn].ImageIndex := imgDescending
else
Columns[SortColumn].ImageIndex := imgAscending;
end;
end;
end.
|
{$mode delphi}
{$longstrings on}
unit un_process;
interface
uses
process, Math, SysUtils;
type
TOnReadLn = procedure(str: String) of object;
{ TExProcess }
TExProcess = class
protected
p: TProcess;
s: String;
FStop: Boolean;
function _GetExitStatus(): Integer;
public
OnReadLn: TOnReadLn;
constructor Create(commandline: String = '');
procedure Execute;
procedure Stop;
procedure SetCmdLine(commandline: String);
destructor Destroy; override;
property ExitStatus: Integer read _GetExitStatus;
end;
implementation
const
buf_len = 3000;
{ TExProcess }
function TExProcess._GetExitStatus(): Integer;
begin
Result := p.ExitStatus;
end;
constructor TExProcess.Create(commandline: String = '');
begin
s := '';
p := TProcess.Create(nil);
p.CommandLine := commandline;
p.Options := [poUsePipes, poNoConsole, poWaitOnExit];
end;
procedure TExProcess.Execute;
var
buf: String;
i, j: Integer;
begin
try
p.Execute;
repeat
if FStop then
exit;
SetLength(buf, buf_len);
SetLength(buf, p.output.Read(buf[1], length(buf))); //waits for the process output
// cut the incoming stream to lines:
s := s + buf; //add to the accumulator
repeat //detect the line breaks and cut.
i := Pos(#13, s);
j := Pos(#10, s);
if i = 0 then
i := j;
if j = 0 then
j := i;
if j = 0 then
Break; //there are no complete lines yet.
if Assigned(OnReadLn) then
OnReadLn(Copy(s, 1, min(i, j) - 1));
//return the line without the CR/LF characters
s := Copy(s, max(i, j) + 1, length(s) - max(i, j));
//remove the line from accumulator
until False;
until buf = '';
if s <> '' then
if Assigned(OnReadLn) then
OnReadLn(s);
buf := '';
except
{$IFDEF UNIX}
on e: Exception do
Writeln('DSXLocate error: ', e.Message);
{$ENDIF}
end;
if Assigned(OnReadLn) then
OnReadLn(buf); //Empty line to notify DC about search process finish
end;
procedure TExProcess.Stop;
begin
FStop := True;
end;
procedure TExProcess.SetCmdLine(commandline: String);
begin
p.CommandLine := commandline;
end;
destructor TExProcess.Destroy;
begin
FreeAndNil(p);
inherited Destroy;
end;
end.
|
unit SdfDataSet;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db;
type
PSdfBookmarkInfo = ^TSdfBookmarkInfo;
TSdfBookmarkInfo = record
BookmarkData: Integer;
BookmarkFlag: TBookmarkFlag;
end;
TSdfDataSet = class(TDataSet)
private
FTableName, FDescrName: TFileName;
FRecordPos, FRecordSize, FBufferSize: Integer;
FRecList: TStringList;
FSeparator, FLimiter, FBreaker: Char;
FDateFormat: string;
FDateSeparator: Char;
FSaveOnChange: Boolean;
FIsTableOpen: Boolean;
procedure SetTableName(const Value: TFileName);
protected
function AllocRecordBuffer: PChar; override;
procedure FreeRecordBuffer(var Buffer: PChar); override;
procedure InternalInitRecord(Buffer: PChar); override;
function GetRecord(Buffer: PChar; GetMode: TGetMode;
DoCheck: Boolean): TGetResult; override;
function GetRecordSize: Word; override;
procedure SetFieldData(Field: TField; Buffer: Pointer); override;
procedure GetBookmarkData(Buffer: PChar; Data: Pointer); override;
function GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; override;
procedure InternalGotoBookmark(Bookmark: Pointer); override;
procedure InternalSetToRecord(Buffer: PChar); override;
procedure SetBookmarkData(Buffer: PChar; Data: Pointer); override;
procedure SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); override;
procedure InternalFirst; override;
procedure InternalInitFieldDefs; override;
procedure InternalLast; override;
procedure InternalClose; override;
procedure InternalHandleException; override;
procedure InternalDelete; override;
procedure InternalAddRecord(Buffer: Pointer; Append: Boolean); override;
procedure InternalOpen; override;
procedure InternalPost; override;
function IsCursorOpen: Boolean; override;
function GetRecordCount: Integer; override;
function GetRecNo: Integer; override;
procedure SetRecNo(Value: Integer); override;
procedure CheckSaveOnChange;
procedure SetRecordSize(Value: Integer);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override;
procedure EmptyTable;
procedure CreateTable;
published
property TableName: TFileName read FTableName write SetTableName;
property RecordSize: Integer read FRecordSize write SetRecordSize;
property Active;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeInsert;
property AfterInsert;
property BeforeEdit;
property AfterEdit;
property BeforePost;
property AfterPost;
property BeforeCancel;
property AfterCancel;
property BeforeDelete;
property AfterDelete;
property BeforeScroll;
property AfterScroll;
property OnCalcFields;
property OnDeleteError;
property OnEditError;
property OnNewRecord;
property OnPostError;
end;
procedure Register;
implementation
uses
BDE, DBTables, DBConsts;
const
feData = '.sdf';
feFields = '.fld';
DefRecordSize: Integer = 2048;
DefSeparator: Char = ',';
DefLimiter: Char = '"';
DefBreaker: Char = '#';
DefDateFormat: PChar = 'dd/mm/yyyy';
DefDateSeparator: Char = '/';
constructor TSdfDataSet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FRecList := TStringList.Create;
SetRecordSize(DefRecordSize);
FSeparator := DefSeparator;
FLimiter := DefLimiter;
FBreaker := DefBreaker;
FSaveOnChange := False;
FIsTableOpen := False;
FDateFormat := StrPas(DefDateFormat);
FDateSeparator := DefDateSeparator;
end;
destructor TSdfDataSet.Destroy;
begin
FRecList.Free;
inherited Destroy;
end;
procedure TSdfDataSet.SetRecordSize(Value: Integer);
begin
FRecordSize := Value;
FBufferSize := FRecordSize + SizeOf(TSdfBookmarkInfo);
end;
function TSdfDataSet.AllocRecordBuffer: PChar;
begin
Result := AllocMem(FBufferSize);
end;
procedure TSdfDataSet.FreeRecordBuffer(var Buffer: PChar);
begin
FreeMem(Buffer);
end;
procedure TSdfDataSet.InternalInitRecord(Buffer: PChar);
begin
FillChar(Buffer^, FBufferSize, #0);
end;
function ParentWnd: hWnd;
begin
Result := GetForegroundWindow {GetTopWindow(0)};
end;
procedure TSdfDataSet.InternalOpen;
const
MesTitle: PChar = 'Открытие базы';
var
F: TextFile;
S: string;
begin
if FileExists(FTableName) then
begin
if FileExists(FDescrName) then
begin
try
FRecordPos := -1;
BookmarkSize := SizeOf(Integer);
InternalInitFieldDefs;
if DefaultFields then
CreateFields;
BindFields(True);
FRecList.Clear;
AssignFile(F, FTableName);
FileMode := 0;
{$I-} Reset(F); {$I+}
if IOResult=0 then
begin
while not System.EoF(F) do
begin
ReadLn(F, S);
FRecList.Add(S);
end;
CloseFile(F);
FIsTableOpen := True;
end
else
MessageBox(ParentWnd, PChar('Ошибка открытия базы ['+TableName+']'), MesTitle,
MB_OK+MB_ICONERROR);
except
MessageBox(ParentWnd, PChar('Ошибка открытия ['+TableName+']'), MesTitle,
MB_OK+MB_ICONERROR);
raise;
end;
end
else
MessageBox(ParentWnd, PChar('Файл описания полей ['+FDescrName+'] не найден'),
MesTitle, MB_OK+MB_ICONERROR);
end
else
MessageBox(ParentWnd, PChar('База ['+FTableName+'] не найдена'),
MesTitle, MB_OK+MB_ICONERROR);
end;
function TSdfDataSet.GetRecord(Buffer: PChar; GetMode: TGetMode;
DoCheck: Boolean): TGetResult;
begin
if FRecList.Count <= 0 then
Result := grEOF
else begin
Result := grOk;
case GetMode of
gmPrior:
if FRecordPos <=0 then
begin
Result := grBOF;
FRecordPos := -1;
end
else
Dec(FRecordPos);
gmCurrent:
if (FRecordPos < 0) or (FRecordPos >= RecordCount) then
Result := grError;
gmNext:
if FRecordPos >= RecordCount-1 then
Result := grEOF
else
Inc(FRecordPos);
end;
if Result = grOk then
begin
StrPLCopy(Buffer, FRecList.Strings[FRecordPos], FBufferSize-1);
with PSdfBookmarkInfo(@Buffer[FRecordSize])^ do
begin
BookmarkData := FRecordPos;
BookmarkFlag := bfCurrent;
end;
end
else
if (Result = grError) and DoCheck then
DatabaseError('No record');
end;
end;
function TSdfDataSet.GetRecordSize: Word;
begin
Result := FRecordSize;
end;
function GetFieldFromString(var S: string; Index: Integer; Sep,Lim: Char;
var I,P0,P: Integer): string;
var
L: Integer;
InStr: Boolean;
begin
InStr := False;
I := 1;
L := Length(S);
P0 := 0; P := 0;
while (I<=Index) and (P<L) do
begin
Inc(P);
if InStr and (P<L) then
InStr := not ((S[P]=Lim) and ((P>=L) or (S[P+1]=Sep)))
else begin
InStr := (S[P]=Lim)
and ((P>1) and (S[P-1]=Sep) or (P<L) and (S[P+1]=Sep) or (P=L));
if (S[P]=Sep) or (P=L) then
begin
Inc(I);
if I=Index then
P0 := P;
if P=L then
Inc(P);
end;
end;
end;
if I<=Index then
Result := ''
else
Result := Copy(S, P0+1, P-P0-1);
end;
procedure SetFieldToString(var S: string; Index: Integer; V: string;
Sep,Lim: Char);
var
I,P0,P: Integer;
begin
GetFieldFromString(S, Index, Sep, Lim, I, P0, P);
if I<=Index then
begin
while I<=Index do
begin
S := S+Sep;
Inc(I);
end;
S := S+V;
end
else
S := Copy(S, 1, P0)+V+Copy(S, P, Length(S)-P+1);
end;
function StrFieldToStr(var S: string; Lim,Br: Char): string;
var
I: Integer;
begin
Result := S;
I := Length(Result);
if (I>1) and (Result[1]=Lim) and (Result[I]=Lim) then
Result := Copy(Result, 2, I-2);
I := Pos(Lim+Lim, Result);
while I>0 do
begin
Delete(Result, I, 1);
I := Pos(Lim+Lim, Result);
end;
I := Pos(Br, Result);
while I>0 do
begin
Result := Copy(Result, 1, I-1)+#13#10+Copy(Result, I+1, Length(Result)-I);
I := Pos(Br, Result);
end;
end;
function StrToStrField(var S: string; Lim,Br: Char): string;
var
L,I: Integer;
begin
Result := S;
L := Length(Result);
I := 0;
while I<L do
begin
Inc(I);
if Result[I]=Lim then
begin
Result := Copy(Result, 1, I)+Copy(Result, I, L-I+1);
Inc(L);
Inc(I);
end
else
if Result[I]=#13 then
begin
Result := Copy(Result, 1, I-1)+Br+Copy(Result, I+2, L-I-1);
Dec(L);
end;
end;
Result := Lim+Result+Lim;
end;
type
PDate = ^TDate;
PBoolean = ^Boolean;
function TSdfDataSet.GetFieldData(Field: TField; Buffer: Pointer):Boolean;
const
MesTitle: PChar = 'Чтение поля';
var
I, P0, P, Err: Integer;
S, OldDateFormat: string;
OldDateSeparator: Char;
D: Double;
ActBuf: PChar;
begin
Result := False;
ActBuf := ActiveBuffer;
if (RecordCount>0) and (FRecordPos>=0) and (Assigned(Buffer))
and (Assigned(ActBuf)) then
begin
S := StrPas(ActBuf);
S := GetFieldFromString(S, Field.FieldNo, FSeparator, FLimiter, I,P0,P);
case Field.DataType of
ftString:
begin
S := StrFieldToStr(S, FLimiter, FBreaker);
StrPLCopy(Buffer, S, Field.DataSize-1);
Result := True;
end;
ftFloat:
begin
Val(Trim(S), D, Err);
PDouble(Buffer)^ := D;
Result := True;
end;
ftInteger:
begin
Val(Trim(S), I, Err);
PInteger(Buffer)^ := I;
Result := True;
end;
ftDate:
begin
OldDateFormat := ShortDateFormat;
OldDateSeparator := DateSeparator;
try
DateSeparator := FDateSeparator;
ShortDateFormat := FDateFormat;
try
PInteger(Buffer)^ := Trunc(Double(StrToDate(S)))+693594;
Result := True;
except
end;
finally
DateSeparator := OldDateSeparator;
ShortDateFormat := OldDateFormat;
end;
end;
ftBoolean:
begin
Result := True;
S := Trim(S);
if S[1] in ['S','T','Y','д','Д','+','1'] then
PBoolean(Buffer)^ := True
else
PBoolean(Buffer)^ := False
end
else
begin
MessageBox(ParentWnd, 'Недопустимый тип поля', MesTitle,
MB_OK+MB_ICONERROR);
Result := False;
end;
end;
end;
end;
procedure TSdfDataSet.SetFieldData(Field: TField; Buffer: Pointer);
const
MesTitle: PChar = 'Запись поля';
var
S, V: string;
ActBuf: PChar;
begin
ActBuf := ActiveBuffer;
if (RecordCount>0) and (Assigned(Buffer))
and (Assigned(ActBuf)) then
begin
S := StrPas(ActBuf);
case Field.DataType of
ftString:
begin
V := StrPas(Buffer);
V := StrToStrField(V, FLimiter, FBreaker);
end;
ftFloat:
Str(pDouble(Buffer)^:0:5, V);
ftInteger:
Str(PInteger(Buffer)^, V);
ftDate:
V := FormatDateTime(FDateFormat, PInteger(Buffer)^-693594);
ftBoolean:
begin
if PBoolean(Buffer)^ then
V := 'T'
else
V := 'F';
end
else
V := '';
end;
SetFieldToString(S, Field.FieldNo, V, FSeparator, FLimiter);
StrPLCopy(ActBuf, S, FRecordSize-1);
DataEvent(deFieldChange, Longint(Field));
end;
end;
procedure TSdfDataSet.GetBookmarkData(Buffer: PChar; Data: Pointer);
begin
PInteger(Data)^ := PSdfBookmarkInfo(@Buffer[FRecordSize])^.BookmarkData;
end;
function TSdfDataSet.GetBookmarkFlag(Buffer: PChar): TBookmarkFlag;
begin
Result := PSdfBookmarkInfo(@Buffer[FRecordSize])^.BookmarkFlag;
end;
procedure TSdfDataSet.InternalGotoBookmark(Bookmark: Pointer);
begin
FRecordPos := Integer(Bookmark);
end;
procedure TSdfDataSet.InternalSetToRecord(Buffer: PChar);
begin
FRecordPos := PSdfBookmarkInfo(@Buffer[FRecordSize])^.BookmarkData;
end;
procedure TSdfDataSet.SetBookmarkData(Buffer: PChar; Data: Pointer);
begin
PSdfBookmarkInfo(@Buffer[FRecordSize])^.BookmarkData := PInteger(Data)^;
end;
procedure TSdfDataSet.SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag);
begin
PSdfBookmarkInfo(@Buffer[FRecordSize])^.BookmarkFlag := Value;
end;
procedure TSdfDataSet.InternalFirst;
begin
FRecordPos := -1;
end;
procedure DecodeField(Fld: string; var FD: TFieldDef);
const
MesTitle: PChar = 'Инициализация поля';
var
I, Err: Integer;
begin
with FD do
begin
DataType := ftUnknown;
Size := 0;
Fld := Trim(Fld);
if Length(Fld)>0 then
begin
I := Pos(',', Fld);
if I>0 then
begin
Name := Copy(Fld, 1, I-1);
Delete(Fld, 1, I);
end
else begin
Name := Copy(Fld, 1, I);
Fld := '';
end;
if Length(Fld)=0 then
Fld := 'C';
case Fld[1] of
'C':
begin
DataType := ftString;
I := Pos(':', Fld);
if I>0 then
begin
Delete(Fld, 1, I);
Val(Fld, I, Err);
if Err<>0 then
begin
MessageBox(ParentWnd, PChar('Ошибочно задана длина поля '+Name),
MesTitle, MB_OK+MB_ICONERROR);
I := 10;
end;
end
else
I := 10;
Size := I;
end;
'N', 'F':
begin
I := Pos(':', Fld);
if I>0 then
begin
Delete(Fld, 1, I);
Val(Fld, I, Err);
if Err<>0 then
begin
MessageBox(ParentWnd, PChar('Ошибочно задана дробь поля '+Name),
MesTitle, MB_OK+MB_ICONERROR);
I := 0;
end;
end;
if I>0 then
begin
DataType := ftFloat;
Precision := I;
end
else
DataType := ftInteger;
end;
'L':
DataType := ftBoolean;
'D':
DataType := ftDate;
else
DataType := ftUnknown;
end;
end
else
MessageBox(ParentWnd, 'Пустое описание поля', MesTitle, MB_OK+MB_ICONERROR);
Required := False;
end;
end;
procedure CodeField(const FD: TField; var Fld: string);
begin
with FD do
begin
Fld := '';
case DataType of
ftFloat, ftInteger, ftLargeInt, ftWord, ftSmallInt:
begin
Fld := Fld+'N';
if (FD is TFloatField) then
Fld := Fld + ':' + IntToStr((FD as TFloatField).Precision);
end;
ftBoolean:
Fld := 'L';
ftDate:
Fld := 'D';
else begin
Fld := 'C:'+IntToStr(Size);
end;
end;
if Length(Fld)>0 then
Fld := ','+Fld;
Fld := FieldName+Fld;
end;
end;
const
scCommon = 0;
scFields = 1;
NumOfSect = 2;
SectNames: array[0..NumOfSect-1] of PChar = ('Common', 'Fields');
pmSeparator = 0;
pmLimiter = 1;
pmBreaker = 2;
pmRecordSize = 3;
pmDateFormat = 4;
pmDateSeparator = 5;
NumOfParam = 6;
ParamNames: array[0..NumOfParam-1] of PChar = ('Separator', 'Limiter',
'Breaker', 'RecordSize', 'DateFormat', 'DateSeparator');
procedure TSdfDataSet.InternalInitFieldDefs;
const
MesTitle: PChar = 'Инициализация полей по файлу описания ('+feFields+')';
var
F: TextFile;
S, N: string;
NumOfFields, I, J, SectIndex: Integer;
NewFieldDef: TFieldDef;
begin
FieldDefs.Clear;
if FileExists(FDescrName) then
begin
AssignFile(F, FDescrName);
FileMode := 0;
{$I-} Reset(F); {$I+}
if IOResult=0 then
begin
SectIndex := -1;
NumOfFields := 0;
while not System.EoF(F) do
begin
ReadLn(F, S);
if Length(S)>0 then
begin
if S[1]='[' then
begin
I := Pos(']', S);
if I<=0 then
I := Length(S)+1;
S := UpperCase(Copy(S, 2, I-2));
SectIndex := 0;
while (SectIndex<NumOfSect) and (S<>UpperCase(SectNames[SectIndex])) do
Inc(SectIndex);
if SectIndex>=NumOfSect then
SectIndex := -1;
end
else begin
case SectIndex of
scCommon:
begin
I := Pos('=', S);
if I>0 then
begin
N := UpperCase(Copy(S, 1, I-1));
System.Delete(S, 1, I);
I := 0;
while (I<NumOfParam) and (N<>UpperCase(ParamNames[I])) do
Inc(I);
if I<NumOfParam then
begin
case I of
pmSeparator:
if Length(S)=1 then
FSeparator := S[1]
else
MessageBox(ParentWnd, PChar('Разделитель полей должен быть одним симолом ['+S+']'),
MesTitle, MB_OK+MB_ICONERROR);
pmLimiter:
if Length(S)=1 then
FLimiter := S[1]
else
MessageBox(ParentWnd, PChar('Ограничитель строк должен быть одним симолом ['+S+']'),
MesTitle, MB_OK+MB_ICONERROR);
pmBreaker:
if Length(S)=1 then
FBreaker := S[1]
else
MessageBox(ParentWnd, PChar('Разделитель строк должен быть одним симолом ['+S+']'),
MesTitle, MB_OK+MB_ICONERROR);
pmRecordSize:
begin
Val(S, I, J);
if J=0 then
RecordSize := I
else
MessageBox(ParentWnd, PChar('Неверно задан размер буфера ['+S+']'),
MesTitle, MB_OK+MB_ICONERROR);
end;
pmDateFormat:
begin
FDateFormat := S;
end;
pmDateSeparator:
begin
if Length(S)=1 then
FDateSeparator := S[1]
else
MessageBox(ParentWnd, PChar('Разделитель даты должен быть одним симолом ['+S+']'),
MesTitle, MB_OK+MB_ICONERROR);
end;
end
end
else
MessageBox(ParentWnd, PChar('Неизвестный параметр ['+N+']'),
MesTitle, MB_OK+MB_ICONERROR);
end
else
MessageBox(ParentWnd, PChar('Недопустимая строка ['+S+']'),
MesTitle, MB_OK+MB_ICONERROR);
end;
scFields:
begin
NewFieldDef := TFieldDef.Create(FieldDefs);
DecodeField(S, NewFieldDef);
Inc(NumOfFields);
NewFieldDef.FieldNo := NumOfFields;
end;
end;
end;
end;
end;
CloseFile(F);
end
else
MessageBox(ParentWnd, PChar('Не могу открыть файл описания полей ['+FDescrName+']'),
MesTitle, MB_OK+MB_ICONERROR);
end;
end;
procedure TSdfDataSet.CreateTable;
const
MesTitle: PChar = 'Создание таблицы';
var
I, Sect: Integer;
S: string;
F: TextFile;
begin
CheckInactive;
if not FileExists(FDescrName) or
(MessageBox(ParentWnd, PChar('Файл описания ' + FTableName +
' уже существует. Перезаписать его?'), MesTitle,
MB_YESNOCANCEL+MB_ICONWARNING) = ID_YES) then
begin
if FieldDefs.Count = 0 then
begin
for I := 0 to FieldCount - 1 do
begin
with Fields[I] do
begin
if FieldKind = fkData then
FieldDefs.Add(FieldName, DataType, Size, Required);
end;
end;
end;
AssignFile(F, FDescrName);
Rewrite(F);
if IOResult=0 then
begin
for Sect := 0 to NumOfSect-1 do
begin
WriteLn(F, '['+SectNames[Sect]+']');
case Sect of
scCommon:
begin
for I := 0 to NumOfParam-1 do
begin
case I of
pmSeparator:
S := FSeparator;
pmLimiter:
S := FLimiter;
pmBreaker:
S := FBreaker;
pmRecordSize:
S := IntToStr(FRecordSize);
pmDateFormat:
S := FDateFormat;
pmDateSeparator:
S := FDateSeparator;
else
S := '';
end;
WriteLn(F, ParamNames[I]+'='+S);
end;
end;
scFields:
begin
S := '';
for I := 0 to FieldCount - 1 do
begin
CodeField(Fields[I], S);
WriteLn(F, S);
end;
end;
end;
end;
CloseFile(F);
AssignFile(F, FTableName);
Rewrite(F);
if IOResult=0 then
begin
CloseFile(F);
{EmptyTable;}
end
else
MessageBox(ParentWnd, PChar('Не удалось создать базу ['+FTableName+']'),
MesTitle, MB_OK+MB_ICONERROR);
end
else
MessageBox(ParentWnd, PChar('Не удалось создать файл описания ['+FDescrName+']'),
MesTitle, MB_OK+MB_ICONERROR);
end;
end;
procedure TSdfDataSet.InternalLast;
begin
FRecordPos := FRecList.Count;
end;
procedure TSdfDataSet.InternalClose;
begin
FRecList.SaveToFile(FTableName);
FRecList.Clear;
if DefaultFields then
DestroyFields;
FIsTableOpen := False;
FRecordPos := -1;
end;
procedure TSdfDataSet.InternalHandleException;
begin
Application.HandleException(Self);
end;
procedure TSdfDataSet.InternalDelete;
begin
FRecList.Delete(FRecordPos);
if FRecordPos >= FRecList.Count then
Dec(FRecordPos);
end;
procedure TSdfDataSet.CheckSaveOnChange;
begin
if FSaveOnChange then
FRecList.SaveToFile(FTableName);
end;
procedure TSdfDataSet.InternalAddRecord(Buffer: Pointer; Append: Boolean);
var
RecPos: Integer;
begin
if Append then
begin
FRecList.Add(PChar(Buffer));
InternalLast;
end
else begin
if FRecordPos = -1 then
RecPos := 0
else
RecPos := FRecordPos;
FRecList.Insert(RecPos, PChar(Buffer));
end;
CheckSaveOnChange;
end;
procedure TSdfDataSet.InternalPost;
var
RecPos: Integer;
begin
if FRecordPos<0 then
RecPos := 0
else
if FRecordPos>=FRecList.Count then
RecPos := FRecList.Count-1
else
RecPos := FRecordPos;
if FRecList.Count<=0 then
FRecList.Add(StrPas(ActiveBuffer))
else
FRecList.Strings[RecPos] := StrPas(ActiveBuffer);
end;
function TSdfDataSet.IsCursorOpen: Boolean;
begin
Result := FIsTableOpen;
end;
function TSdfDataSet.GetRecordCount: Integer;
begin
Result := FRecList.Count;
end;
function TSdfDataSet.GetRecNo: Integer;
begin
UpdateCursorPos;
if FRecordPos < 0 then
Result := 1
else
Result := FRecordPos + 1;
end;
procedure TSdfDataSet.SetRecNo(Value: Integer);
begin
CheckBrowseMode;
if (Value > 0) and (Value <= RecordCount) then
begin
FRecordPos := Value - 1;
Resync([]);
end;
end;
procedure TSdfDataSet.SetTableName(const Value: TFileName);
begin
CheckInactive;
FTableName := Value;
if ExtractFileExt(FTableName) = '' then
FTableName := FTableName + feData;
FDescrName := ChangeFileExt(FTableName, feFields);
end;
procedure TSdfDataSet.EmptyTable;
begin
FRecList.Clear;
FRecordPos := -1;
Refresh;
end;
procedure Register;
begin
RegisterComponents('BankClient', [TSdfDataSet]);
end;
end.
|
{ ---------------------------------------------------------------------------- }
{ HeightMapGenerator MB3D }
{ Copyright (C) 2017 Andreas Maschke }
{ ---------------------------------------------------------------------------- }
unit HeightMapGenPreview;
interface
uses
SysUtils, Classes, Windows, dglOpenGL, Vcl.Graphics, VertexList, VectorMath,
OpenGLPreviewUtil, ShaderUtil;
type
TOpenGLHelper = class( TBaseOpenGLHelper )
private
FShader : TShader;
procedure SetupLighting;
procedure AfterInitGL; override;
procedure ApplicationEventsIdle( Sender: TObject; var Done: Boolean ); override;
procedure SaveAsPGM( const Width, Height: Integer; const DepthBuffer: PGLfloat; const DepthMin, DepthMax: GLfloat; const Filename: String );
procedure SaveAsPNG( const Width, Height: Integer; const DepthBuffer: PGLfloat; const DepthMin, DepthMax: GLfloat; const Filename: String );
public
constructor Create(const Canvas: TCanvas);
procedure UpdateMesh( const FacesList: TFacesList ); override;
procedure SaveHeightMap( const Left, Top, Width, Height: Integer; const Filename: String );
end;
const
DFLT_SCALE = 0.5;
implementation
uses
Forms, Math, DateUtils, PNMWriter, FileHandling;
const
WindowTitle = 'HeightMap Generator Preview';
{ ------------------------------ TOpenGLHelper ------------------------------- }
constructor TOpenGLHelper.Create(const Canvas: TCanvas);
begin
inherited Create( Canvas );
FFOV := 10;
FScale := DFLT_SCALE;
end;
procedure TOpenGLHelper.AfterInitGL;
const
FragmentShader: String =
'float near = 1.0;'#10 +
'float far = 36.0;'#10 +
#10 +
'float linearizeDepth(float depth) {'#10 +
' return (2.0 * near * far) / (far + near - depth * (far - near));'#10 +
'}'#10 +
'void main() {'#10 +
' float depth = linearizeDepth(gl_FragCoord.z)/16.0;'#10 +
' gl_FragColor = vec4(1.0-vec3(depth), 1.0f);'#10 +
'}'#10;
begin
FShader := TShader.Create( FragmentShader );
end;
procedure TOpenGLHelper.ApplicationEventsIdle(Sender: TObject; var Done: Boolean);
const
ZOffset: Double = -7.0;
var
Error, I : LongInt;
X, Y, Z: Double;
V: TPS3Vector;
Face: TPFace;
Scl: Double;
begin
if FRC = 0 then Exit;
Done := False;
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
DrawBackground();
glLoadIdentity;
glTranslatef( FPosition.X, FPosition.Y, ZOffset);
glRotatef( FAngle.X, 0.0, 1.0, 0.0);
glRotatef( - FAngle.Y, 1.0, 0.0, 1.0);
Scl := FScale * 3.0/FMaxObjectSize;
glScalef(Scl, Scl, Scl);
glTranslatef( 0.0, 0.0, FPosition.Z);
glDisable(GL_LIGHTING);
if FFaces <> nil then begin
glVertexPointer( 3, GL_FLOAT, SizeOf(TGLVertex), FVertices);
if FNormals <> nil then begin
glEnableClientState( GL_NORMAL_ARRAY );
glNormalPointer( GL_FLOAT, SizeOf(TGLVertex), FNormals);
end;
SetupLighting;
glShadeModel(GL_SMOOTH);
// glColor3f(FMeshAppearance.SurfaceColor.X, FMeshAppearance.SurfaceColor.Y, FMeshAppearance.SurfaceColor.Z);
glDrawElements( GL_TRIANGLES, FFaceCount * 3, GL_UNSIGNED_INT, FFaces );
end;
//Error Handler
Error := glgetError;
if Error <> GL_NO_ERROR then begin
if Assigned(FSetWindowCaptionEvent) then
FSetWindowCaptionEvent( gluErrorString(Error) );
Done := True;
FlashWindow(FCanvas.Handle, True)
end;
//Frame Counter
Inc(FFrames);
if (GetTickCount - FStartTick >= 500) and (FFrames >= 10) and Assigned(FSetWindowCaptionEvent) then begin
FSetWindowCaptionEvent( Format('%s [%f FPS, %d Vertices, %d Faces]', [WindowTitle, FFrames/(GetTickCount - FStartTick)*1000, FVerticesCount, FFaceCount]));
FFrames := 0;
FStartTick := GetTickCount;
end;
SwapBuffers(FCanvas.Handle);
Sleep(1);
end;
procedure TOpenGLHelper.UpdateMesh(const FacesList: TFacesList);
var
T0, T00: Int64;
I: Integer;
Key: String;
GLVertices, GLVertex: TPGLVertex;
GLNormals, GLNormal: TPGLVertex;
GLEdges, GLEdge: TPGLEdge;
GLFaces, GLFace: TPGLFace;
EdgesList: TStringList;
EdgeCount: Integer;
Vertex: TPS3Vector;
Normals: TPS3VectorList;
procedure AddVertex(const Idx: Integer);
var
Vertex: TPS3Vector;
begin
Vertex := FacesList.GetVertex(Idx);
if Vertex^.X < FSizeMin.X then
FSizeMin.X := Vertex^.X
else if Vertex^.X > FSizeMax.X then
FSizeMax.X := Vertex^.X;
if Vertex^.Y < FSizeMin.Y then
FSizeMin.Y := Vertex^.Y
else if Vertex^.Y > FSizeMax.Y then
FSizeMax.Y := Vertex^.Y;
if Vertex^.Z < FSizeMin.Z then
FSizeMin.Z := Vertex^.Z
else if Vertex^.Z > FSizeMax.Z then
FSizeMax.Z := Vertex^.Z;
GLVertex^.X := Vertex^.X;
GLVertex^.Y := -Vertex^.Y;
GLVertex^.Z := -Vertex^.Z;
GLVertex := Pointer(Longint(GLVertex)+SizeOf(TGLVertex));
end;
procedure AddNormal(const Idx: Integer);
var
Vertex: TPS3Vector;
begin
Vertex := Normals.GetVertex(Idx);
GLNormal^.X := Vertex^.X;
GLNormal^.Y := Vertex^.Y;
GLNormal^.Z := -Vertex^.Z;
GLNormal := Pointer(Longint(GLNormal)+SizeOf(TGLVertex));
end;
procedure AddFace(const Idx: Integer);
var
Face: TPFace;
begin
Face := FacesList.GetFace(Idx);
GLFace^.V1 := Face^.Vertex1;
GLFace^.V2 := Face^.Vertex2;
GLFace^.V3 := Face^.Vertex3;
GLFace := Pointer(Longint(GLFace)+SizeOf(TGLFace));
end;
procedure AddEdgeFromList(const Idx: Integer);
var
P: Integer;
Key: String;
begin
Key := EdgesList[I];
P := Pos('#', Key);
GLEdge^.V1 := StrToInt(Copy(Key, 1, P - 1));
GLEdge^.V2 := StrToInt(Copy(Key, P+1, Length(Key) - P));
GLEdge := Pointer(Longint(GLEdge)+SizeOf(TGLEdge));
end;
procedure AddEdgesToList(const Idx: Integer);
var
Face: TPFace;
(*
procedure AddEdge(const V1, V2: Integer);
var
Key: String;
begin
if V1 < V2 then
Key := IntToStr(V1)+'#'+IntToStr(V2)
else
Key := IntToStr(V2)+'#'+IntToStr(V1);
if EdgesList.IndexOf(Key) < 0 then
EdgesList.Add(Key);
end;
*)
procedure FastAddEdge(const V1, V2: Integer);
var
Key: String;
begin
Key := IntToStr(V1)+'#'+IntToStr(V2);
EdgesList.Add(Key);
end;
begin
Face := FacesList.GetFace(Idx);
FastAddEdge(Face^.Vertex1, Face^.Vertex2);
if (EdgesList.Count mod 2) = 0 then
FastAddEdge(Face^.Vertex2, Face^.Vertex3)
else
FastAddEdge(Face^.Vertex3, Face^.Vertex1);
(*
AddEdge(Face^.Vertex1, Face^.Vertex2);
AddEdge(Face^.Vertex2, Face^.Vertex3);
AddEdge(Face^.Vertex3, Face^.Vertex1);
*)
end;
begin
T0 := DateUtils.MilliSecondsBetween(Now, 0);
T00 := T0;
// TODO create data (e.g. edges) only on demand ?
FreeVertices;
if FacesList.Count > 0 then begin
EdgesList := TStringList.Create;
try
EdgesList.Duplicates := dupAccept;
EdgesList.Sorted := False;
for I := 0 to FacesList.Count - 1 do
AddEdgesToList(I);
EdgesList.Sorted := True;
EdgeCount := EdgesList.Count;
ShowDebugInfo('OpenGL.AddEdgesPh1('+IntToStr(EdgeCount)+')', T0);
T0 := DateUtils.MilliSecondsBetween(Now, 0);
GetMem(GLEdges, EdgeCount * SizeOf(TGLEdge));
try
GLEdge := GLEdges;
for I := 0 to EdgeCount - 1 do
AddEdgeFromList(I);
except
FreeMem(GLEdges);
raise;
end;
finally
EdgesList.Free;
end;
ShowDebugInfo('OpenGL.AddEdgesPh2', T0);
T0 := DateUtils.MilliSecondsBetween(Now, 0);
try
GetMem(GLVertices, FacesList.VertexCount * SizeOf(TGLVertex));
try
GetMem(GLFaces, FacesList.Count * Sizeof(TGLFace));
try
GLVertex := GLVertices;
Vertex := FacesList.GetVertex(0);
FSizeMin.X := Vertex^.X;
FSizeMax.X := FSizeMin.X;
FSizeMin.Y := Vertex^.Y;
FSizeMax.Y := FSizeMin.Y;
FSizeMin.Z := Vertex^.Z;
FSizeMax.Z := FSizeMin.Z;
for I := 0 to FacesList.VertexCount - 1 do
AddVertex(I);
ShowDebugInfo('OpenGL.AddVertices', T0);
T0 := DateUtils.MilliSecondsBetween(Now, 0);
FMaxObjectSize := Max(FSizeMax.X - FSizeMin.X, Max(FSizeMax.Y - FSizeMin.Y, FSizeMax.Z - FSizeMin.Z ));
GLFace := GLFaces;
for I := 0 to FacesList.Count - 1 do
AddFace(I);
ShowDebugInfo('OpenGL.AddFaces', T0);
T0 := DateUtils.MilliSecondsBetween(Now, 0);
FFaceCount := FacesList.Count;
FVerticesCount := FacesList.VertexCount;
FEdgeCount := EdgeCount;
FVertices := GLVertices;
try
GetMem(GLNormals, FVerticesCount * SizeOf(TGLVertex));
try
GLNormal := GLNormals;
Normals := FacesList.CalculateVertexNormals;
try
if Normals.Count <> FVerticesCount then
raise Exception.Create('Invalid normals');
for I := 0 to Normals.Count - 1 do
AddNormal(I);
finally
Normals.Free;
end;
except
FreeMem(GLNormals);
raise;
end;
except
GLNormals := nil;
// Hide error as normals are optional
end;
FNormals := GLNormals;
FFaces := GLFaces;
FEdges := GLEdges;
except
FreeMem(GLFaces);
raise;
end;
except
FreeMem(GLVertices);
raise;
end;
except
FreeMem(GLEdges);
raise;
end;
end;
ShowDebugInfo('OpenGL.AddNormals', T0);
ShowDebugInfo('OpenGL.TOTAL', T00);
end;
procedure TOpenGLHelper.SetupLighting;
begin
glDisable(GL_LIGHTING);
FShader.Use;
end;
procedure TOpenGLHelper.SaveHeightMap(const Left, Top, Width, Height: Integer; const Filename: String);
const
zNear = 1.0;
zFar = 100.0;
var
I, ValueCount, BufSize: Integer;
DepthBuffer: Pointer;
CurrDepth: PGLfloat;
DepthMin, DepthMax: GLfloat;
FinalDepthMin, FinalDepthMax: GLfloat;
begin
ValueCount := Width * Height;
BufSize := ValueCount * SizeOf( GLfloat );
GetMem( DepthBuffer, BufSize );
try
glReadPixels( Left, Top, Width, Height, GL_DEPTH_COMPONENT, GL_FLOAT, DepthBuffer );
DepthMin := 1.0;
DepthMax := 0.0;
for I := 0 to ValueCount - 1 do begin
CurrDepth := PGLfloat( Longint( DepthBuffer ) + Longint( I * SizeOf( GLfloat ) ) );
CurrDepth^ := ( 2.0 * zNear ) / ( zFar + zNear - CurrDepth^ * ( zFar - zNear ) );
if CurrDepth^ < DepthMin then
DepthMin := CurrDepth^
else if ( CurrDepth^ > DepthMax ) and ( CurrDepth^ < 0.99 ) then
DepthMax := CurrDepth^;
end;
FinalDepthMin := 1.0;
FinalDepthMax := 0.0;
for I := 0 to ValueCount - 1 do begin
CurrDepth := PGLfloat( Longint( DepthBuffer ) + Longint( I * SizeOf( GLfloat ) ) );
if CurrDepth^ > DepthMax then
CurrDepth^ := 0
else
CurrDepth^ := DepthMax - CurrDepth^;
if CurrDepth^ < FinalDepthMin then
FinalDepthMin := CurrDepth^
else if CurrDepth^ > FinalDepthMax then
FinalDepthMax := CurrDepth^;
end;
OutputDebugString(PChar('Depth: ' + FloatToStr(FinalDepthMin) + '...' + FloatToStr(FinalDepthMax)));
if AnsiLowerCase( ExtractFileExt( Filename ) ) = '.pgm' then
SaveAsPGM( Width, Height, DepthBuffer, FinalDepthMin, FinalDepthMax, Filename)
else
SaveAsPNG( Width, Height, DepthBuffer, FinalDepthMin, FinalDepthMax, Filename);
finally
FreeMem( DepthBuffer );
end;
end;
procedure TOpenGLHelper.SaveAsPGM( const Width, Height: Integer; const DepthBuffer: PGLfloat; const DepthMin, DepthMax: GLfloat; const Filename: String );
var
I, J: Integer;
PGMBuffer, CurrPGMBuffer: PWord;
CurrDepthBuffer: PGLfloat;
DepthVal, Delta: Double;
function TransformValue( const Value: GLfloat ): GLfloat;
begin
Result := ( Value - DepthMin ) / Delta;
end;
begin
Delta := DepthMax - DepthMin;
GetMem( PGMBuffer, Width * Height * SizeOf( Word ) );
try
CurrPGMBuffer := PGMBuffer;
for I := 0 to Height - 1 do begin
CurrDepthBuffer := PGLfloat( Longint(DepthBuffer) + ( Height - I - 1 ) * Width * SizeOf( GLfloat ) );
for J := 0 to Width - 1 do begin
DepthVal := Min( Max( 0.0, TransformValue( CurrDepthBuffer^ ) ), 1.0 );
CurrPGMBuffer^ := Word( Round( DepthVal * 65535 ) );
Inc( CurrDepthBuffer );
CurrPGMBuffer := PWord( Longint( CurrPGMBuffer ) + SizeOf( Word ) );
end;
end;
with TPGM16Writer.Create do try
SaveToFile( PGMBuffer, Width, Height, Filename );
finally
Free;
end;
finally
FreeMem( PGMBuffer );
end;
end;
procedure TOpenGLHelper.SaveAsPNG( const Width, Height: Integer; const DepthBuffer: PGLfloat; const DepthMin, DepthMax: GLfloat; const Filename: String );
var
I, J: Integer;
CurrDepthBuffer: PGLfloat;
DepthVal, Delta: Double;
BMP: TBitmap;
PB: PByte;
function TransformValue( const Value: GLfloat ): GLfloat;
begin
Result := ( Value - DepthMin ) / Delta;
end;
begin
BMP := TBitmap.Create;
try
BMP.PixelFormat := pf8Bit;
BMP.SetSize( Width, Height );
Make8bitGreyscalePalette(Bmp);
Delta := DepthMax - DepthMin;
for I := 0 to Height - 1 do begin
CurrDepthBuffer := PGLfloat( Longint(DepthBuffer) + ( Height - I - 1 ) * Width * SizeOf( GLfloat ) );
PB := BMP.ScanLine[ I ];
for J := 0 to Width - 1 do begin
DepthVal := Min( Max( 0.0, TransformValue( CurrDepthBuffer^ ) ), 1.0 );
Inc( CurrDepthBuffer );
PB^:=Byte(Round(DepthVal*255.0));
Inc(PB);
end;
end;
SavePNG( Filename, BMP, False );
finally
BMP.Free;
end;
end;
end.
|
unit MapPrintTypeDialogUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Buttons;
type
MapPrintTypes = (mptMap, mptLabels, mptParcelList);
MapPrintTypeSet = set of MapPrintTypes;
type
TMapPrintTypeDialog = class(TForm)
OKButton: TBitBtn;
CancelButton: TBitBtn;
PrintGroupBox: TGroupBox;
MapCheckBox: TCheckBox;
LabelsCheckBox: TCheckBox;
ParcelListCheckBox: TCheckBox;
procedure OKButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
PrintType : MapPrintTypeSet;
end;
var
MapPrintTypeDialog: TMapPrintTypeDialog;
implementation
{$R *.DFM}
{==========================================================}
Procedure TMapPrintTypeDialog.OKButtonClick(Sender: TObject);
begin
PrintType := [];
If MapCheckBox.Checked
then PrintType := PrintType + [mptMap];
If LabelsCheckBox.Checked
then PrintType := PrintType + [mptLabels];
If ParcelListCheckBox.Checked
then PrintType := PrintType + [mptParcelList];
ModalResult := mrOK;
end; {OKButtonClick}
end.
|
unit Uprincipal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, InvokeRegistry, Rio, SOAPHTTPClient, StdCtrls, ExtCtrls, StrUtils;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
edValorA: TEdit;
edValorB: TEdit;
btnCalcular: TButton;
Label3: TLabel;
edResultado: TEdit;
httpRioSoma: THTTPRIO;
panelsoma: TPanel;
panelBanco: TPanel;
Label4: TLabel;
Label5: TLabel;
edId: TEdit;
edNome: TEdit;
btnInserir: TButton;
Label6: TLabel;
edResultadoBanco: TEdit;
httpRioBanco: THTTPRIO;
procedure btnCalcularClick(Sender: TObject);
procedure btnInserirClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
ClienteInterface, ClienteBanco;
{$R *.dfm}
procedure TForm1.btnCalcularClick(Sender: TObject);
var
resultado : integer;
begin
try
resultado := (httpRioSoma as Iinterface).somar(strtoint(edvalorA.text), strtoint(edvalorB.text));
edResultado.text := inttostr(resultado);
except
on E: Exception do
ShowMessage(E.Message);
end;
end;
procedure TForm1.btnInserirClick(Sender: TObject);
var
resultado : boolean;
begin
try
resultado := (httpRioBanco as IDmWsSoap).insereRegistro(strtoint(edId.text), edNome.Text);
edResultadoBanco.Text := ifthen(resultado, 'Registro incluido', 'Resgistro não incluido');
except
on e : Exception do
ShowMessage(e.Message);
end;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus,
Controls, Dialogs, SysUtils, StdCtrls,
OpenGL;
type
TFBBuffer = Array [0..1023] of GLFloat;
type
TfrmGL = class(TForm)
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
private
DC: HDC;
hrc: HGLRC;
Angle: GLfloat;
uTimerId : uint; // идентификатор таймера - необходимо запомнить
fb: TFBBuffer;
Timer : Boolean;
procedure SetDCPixelFormat;
procedure PrintBuffer(b: TFBBuffer; n: Integer);
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
implementation
uses mmSystem;
{$R *.DFM}
procedure Render (mode: GLenum);
begin
If mode = GL_FEEDBACK then glPassThrough(1);
glColor3f (1.0, 0.0, 0.0);
glNormal3f (0.0, 0.0, -1.0);
glBegin (GL_QUADS);
glVertex3f (-0.5, -0.5, 0.0);
glVertex3f (0.5, -0.5, 0.0);
glVertex3f (0.5, 0.5, 0.0);
glVertex3f (-0.5, 0.5, 0.0);
glEnd;
If mode = GL_FEEDBACK then glPassThrough(2);
glColor3f (1.0, 1.0, 0.0);
glBegin (GL_POINTS);
glNormal3f (0.0, 0.0, -1.0);
glVertex3f (0.0, 0.0, -0.5);
glEnd;
end;
{=======================================================================
Обработка таймера}
procedure FNTimeCallBack(uTimerID, uMessage: UINT;dwUser, dw1, dw2: DWORD) stdcall;
begin
// Каждый "тик" изменяется значение угла
With frmGL do begin
Angle := Angle + 0.1;
If Angle >= 360.0 then Angle := 0.0;
InvalidateRect(Handle, nil, False);
end;
end;
procedure TfrmGL.PrintBuffer(b: TFBBuffer; n: Integer);
var
i, j, k, vcount : Integer;
token : Single;
vert : String;
begin
Memo1.Clear;
i := n;
While i <> 0 do begin
token := b[n-i];
DEC(i);
If token = GL_PASS_THROUGH_TOKEN then begin
Memo1.Lines.Add('');
Memo1.Lines.Add(Format('Passthrough: %.2f', [b[n-i]]));
DEC(i);
end
else If token = GL_POLYGON_TOKEN then begin
vcount := Round(b[n-i]);
Memo1.Lines.Add(Format('Polygon - %d vertices (XYZ RGBA):', [vcount]));
DEC(i);
For k := 1 to vcount do begin
vert := ' ';
For j := 0 to 6 do begin
vert := vert + Format('%4.2f ', [b[n-i]]);
DEC(i);
end;
Memo1.Lines.Add(vert);
end;
end
else If token = GL_POINT_TOKEN then begin
Memo1.Lines.Add('Vertex - (XYZ RGBA):');
vert := ' ';
For j := 0 to 6 do begin
vert := vert + Format('%4.2f ', [b[n-i]]);
DEC(i);
end;
Memo1.Lines.Add(vert);
end;
end;
end;
{=======================================================================
Перерисовка окна}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
n: Integer;
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glLoadIdentity;
glRotatef(Angle, 1, 0, 0.1);
Render(GL_RENDER);
glRenderMode(GL_FEEDBACK);
Render(GL_FEEDBACK);
n := glRenderMode(GL_RENDER);
If n > 0 then PrintBuffer(fb, n);
SwapBuffers(DC);
EndPaint(Handle, ps);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
const
position : Array [0..2] of GLFloat = (0, 0, -1);
diffuse : Array [0..3] of GLFloat = (1, 1, 1, 1);
ambient : Array [0..3] of GLFloat = (0.4, 0.4, 0.8, 1);
begin
Angle := 0;
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
glViewport(0, 0, (ClientWidth - Memo1.Width), ClientHeight);
glEnable(GL_DEPTH_TEST);
glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
glPointSize(20);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_POSITION, @position);
glLightfv(GL_LIGHT0, GL_DIFFUSE, @diffuse);
glLightfv(GL_LIGHT0, GL_AMBIENT, @ambient);
glClearColor (0.25, 0.75, 0.25, 0.0);
Timer := True;
uTimerID := timeSetEvent (2, 0, @FNTimeCallBack, 0, TIME_PERIODIC);
glFeedbackBuffer(SizeOf (fb), GL_3D_COLOR, @fb);
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or
PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
If Timer then timeKillEvent(uTimerID);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close else
If Key = VK_SPACE then begin
Timer := not Timer;
If not Timer
then timeKillEvent(uTimerID)
else uTimerID := timeSetEvent (2, 0, @FNTimeCallBack, 0, TIME_PERIODIC);
end;
end;
procedure TfrmGL.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
Caption := IntToStr (X) + ' ' + IntToStr (Y)
end;
end.
|
program _demo;
Array[0]
var
X : TReal1DArray;
Y : TReal1DArray;
N : AlglibInteger;
I : AlglibInteger;
T : Double;
S : Spline1DInterpolant;
V : Double;
DV : Double;
D2V : Double;
Err : Double;
MaxErr : Double;
begin
//
// Demonstration of Spline1DCalc(), Spline1DDiff(), Spline1DIntegrate()
//
Write(Format('DEMONSTRATION OF Spline1DCalc(), Spline1DDiff(), Spline1DIntegrate()'#13#10''#13#10'',[]));
Write(Format('F(x)=sin(x), [0, pi]'#13#10'',[]));
Write(Format('Natural cubic spline with 3 nodes is used'#13#10''#13#10'',[]));
//
// Create spline
//
N := 3;
SetLength(X, N);
SetLength(Y, N);
I:=0;
while I<=N-1 do
begin
X[I] := Pi*I/(N-1);
Y[I] := Sin(X[I]);
Inc(I);
end;
Spline1DBuildCubic(X, Y, N, 2, 0.0, 2, 0.0, S);
//
// Output results
//
Spline1DDiff(S, 0, V, DV, D2V);
Write(Format(' S(x) F(x) '#13#10'',[]));
Write(Format('function %6.3f %6.3f '#13#10'',[
Spline1DCalc(S, 0),
Double(Variant(0))]));
Write(Format('d/dx(0) %6.3f %6.3f '#13#10'',[
DV,
Double(Variant(1))]));
Write(Format('d2/dx2(0) %6.3f %6.3f '#13#10'',[
D2V,
Double(Variant(0))]));
Write(Format('integral(0,pi) %6.3f %6.3f '#13#10'',[
Spline1DIntegrate(S, Pi),
Double(Variant(2))]));
Write(Format(''#13#10''#13#10'',[]));
end. |
unit uGMV_Common;
{
================================================================================
*
* Package:
* Date Created: $Revision: 1 $ $Modtime: 2/23/09 6:33p $
* Site: Hines OIFO
* Developers:
* Andrey Andriyevskiy
* Sergey Gavrilov
*
* Description: Common Utils
*
* Notes:
*
================================================================================
*
* $History: uGMV_Common.pas $
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 8/12/09 Time: 8:29a
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSUTILS
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 3/09/09 Time: 3:39p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSUTILS
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/13/09 Time: 1:26p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSUTILS
*
* ***************** Version 3 *****************
* User: Zzzzzzandria Date: 6/17/08 Time: 4:04p
* Updated in $/Vitals/5.0 (Version 5.0)/VitalsGUI2007/Vitals/VITALSUTILS
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 7/18/07 Time: 12:50p
* Updated in $/Vitals GUI 2007/Vitals-5-0-18/VITALSUTILS
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/14/07 Time: 10:30a
* Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSUTILS
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:44p
* Created in $/Vitals/VITALS-5-0-18/VitalsUtils
* GUI v. 5.0.18 updates the default vital type IENs with the local
* values.
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:33p
* Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsUtils
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/24/05 Time: 5:04p
* Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsUtils
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 4/16/04 Time: 4:24p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSUTILS
*
*
================================================================================
}
interface
uses
Classes,
SysUtils,
Dialogs,
StdCtrls,
Forms,
Controls,
comctrls,
Graphics,
extctrls
, ShlObj
, Windows
;
Type
TFMDateTimeMode = set of (
fmdtDateOnly, // Convert date only
fmdtShortDate, // Short date (digits only)
fmdtYear2, // 2 digit year
fmdtTimeOnly, // Convert time only
fmdtShortTime, // Do not convert seconds
fmdtTime24 // Military time format
);
function CmdLineSwitch( swlst: array of String ): Boolean; overload;
function CmdLineSwitch( swlst: array of String; var swval: String ): Boolean; overload;
function FMDateTimeStr(DateTime: String; Mode: TFMDateTimeMode = []): String;
function FMDateToWindowsDate( FMDate: Double ): TDate;
function FMDateTimeToWindowsDateTime( FMDateTime: Double ): TDateTime;
function InString( S: String; SubStrs: array of String;
CaseSensitive: Boolean = True ): Boolean;
function IntVal( str: String ): Integer;
function MessageDialog( const ACaption: string; const Msg: string;
DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefButton: Integer;
HelpCtx: Longint ): Word;
function Piece( Value, Delimiter: String;
StartPiece: Integer = 1 ): String; overload;
function Piece( Value, Delimiter: String;
StartPiece: Integer; EndPiece: Integer ): String; overload;
function WindowsDateTimeToFMDateTime( WinDate: TDateTime ): Double;
function WindowsDateToFMDate( WinDate: TDate ): Double;
function AddKeyToValue(Value,Key,Delim:String):String;
function DelKeyFromValue(Value,Key,Delim:String):String;
function FormatSSN(aSSN:String):String;
function ReFormatSSN(aSSN:String):String;
procedure DelLVSelectedLine(LVFrom:TListView);
procedure CopySelectedLVLines(LVFrom, LVTo:TListView;Mode:Boolean);
procedure CopyAllLVLine(LVFrom, LVTo:TListView);
procedure CopyLVLine(LVFrom, LVTo:TListView;Mode:Boolean);
procedure CopyLVHeaders(LVFrom, LVTo:TListView);
procedure UpdateAndNotClearListView(aStrings: TStrings;aLV: TListView;
iCaptionIndex: Integer;anIndexes: array of integer);
procedure UpdateListView(aStrings: TStrings;aLV: TListView;
iCaptionIndex: Integer;anIndexes: array of integer);
procedure ListViewToParamList(aLV: TListView;anIndex:Integer;var aStrings:TStringList);
procedure UpdateStringList(aStrings:TStrings;aSL: TStringList);
procedure StringListToListView(aSL: TStringList;aLV: TListView;
iCaptionIndex: Integer;anIndexes: array of integer);
procedure ListViewToStringList(aLV: TListView;aL: TStringList;anIndexes: array of Integer;
aStart,aDelim:String);
procedure LoadColumnsWidth(aName:String;aColumns:TListColumns;sL: TStringList);
procedure AddParam(aName,aValue:String;sL:TStringList);
procedure SaveColumnsWidth(aName:String;aColumns:TListColumns;sL:TStringList);
function StringByKey(aStrings:TStrings;aKey:String;aPosition:Integer):String;
procedure UpdateEdit(var Key: Char; Sender: TObject);
procedure SetPanelStatus(aPanel:TPanel;aStatus:Boolean;aColor:TColor);
function dVal(gStr,sDateTime: string): Double;
function getCellDateTime(s:String):TDateTime;
function ReplaceStr(aLine,aTarget,aReplacement:String):String;
procedure PositionForm(aForm: TForm);
function GetProgramFilesPath: String;
var
FMDateFormat: array[1..2,1..3] of String;
const
// clTabIn = clInfoBk;
clTabIn = clWindow;
clTabOut = clInfoBk;
iIgnore = - 999999;
implementation
uses
System.UITypes;
function FMDateTimeStr(DateTime: String; Mode: TFMDateTimeMode): String;
var
buf, format: String;
day, month, year: Word;
hour, min, sec: Word;
date, time: TDate;
dateType, datePart: Integer;
begin
Result := '';
buf := Piece(DateTime, '.', 1);
if( Not (fmdtTimeOnly in Mode)) and (buf <> '') then
begin
year := IntVal(Copy(buf, 1, 3)) + 1700;
month := IntVal(Copy(buf, 4, 2));
day := IntVal(Copy(buf, 6, 2));
if fmdtShortDate in Mode then
dateType := 2
else
dateType := 1;
datePart := 1;
if day = 0 then
begin
day := 1;
datePart := 2;
if month = 0 then
begin
month := 1;
datePart := 3;
end;
end;
format := FMDateFormat[dateType][datePart];
if fmdtYear2 in Mode then
format := StringReplace(format, 'YYYY', 'YY', []);
date := EncodeDate(year, month, day);
Result := FormatDateTime(format, date);
end;
buf := Piece(DateTime, '.', 2);
if (Not (fmdtDateOnly in Mode)) And (buf <> '') then
begin
buf := Copy(buf + '000000', 1, 6);
hour := IntVal(Copy(buf, 1, 2));
min := IntVal(Copy(buf, 3, 2));
sec := IntVal(Copy(buf, 5, 2));
if hour >= 24 then
begin
hour := 23; min := 59; sec := 59;
end
else if min >= 60 then
begin
min := 59; sec := 59;
end
else if sec >= 60 then
sec := 59;
time := EncodeTime(hour, min, sec, 0);
if fmdtTime24 in Mode then
if fmdtShortTime in Mode then
format := 'HH:NN'
else
format := 'HH:NN:SS'
else
if fmdtShortTime in Mode then
format := 'T'
else
format := 'TT';
if Result <> '' then
Result := Result + ' ' + FormatDateTime(format, time)
else
Result := FormatDateTime(format, time);
end;
end;
procedure FMInitFormatArray;
var
format: String;
begin
format := UpperCase(FormatSettings.ShortDateFormat);
if Pos('M', format) > Pos('D', format) then
begin
FMDateFormat[1][1] := 'DD MMM YYYY';
FMDateFormat[1][2] := 'MMM YYYY';
FMDateFormat[1][3] := 'YYYY';
FMDateFormat[2][1] := 'DD/MM/YYYY';
FMDateFormat[2][2] := 'MM/YYYY';
FMDateFormat[2][3] := 'YYYY';
end
else
begin
FMDateFormat[1][1] := 'MMM DD, YYYY';
FMDateFormat[1][2] := 'MMM YYYY';
FMDateFormat[1][3] := 'YYYY';
FMDateFormat[2][1] := 'MM/DD/YYYY';
FMDateFormat[2][2] := 'MM/YYYY';
FMDateFormat[2][3] := 'YYYY';
end;
end;
function CmdLineSwitch(swlst: array of String): Boolean;
var
swval: String;
begin
Result := CmdLineSwitch(swlst, swval);
end;
function CmdLineSwitch(swlst: array of String; var swval: String): Boolean;
var
i: Integer;
begin
Result := False;
swval := '';
for i := 1 to ParamCount do
begin
if InString(ParamStr(i), swlst, False) then
begin
swval := Piece(ParamStr(i), '=', 2);
Result := True;
break;
end;
end;
end;
function InString(S: String; SubStrs: array of String; CaseSensitive: Boolean = True): Boolean;
var
i: integer;
begin
i := 0;
Result := False;
while (i <= High(SubStrs)) and (Result = False) do
begin
if CaseSensitive then
begin
if Pos(SubStrs[i], S) > 0 then
Result := True
else
Inc(i)
end
else
begin
if Pos(LowerCase(SubStrs[i]), LowerCase(S)) > 0 then
Result := True
else
Inc(i)
end;
end
end;
function IntVal(str: String): Integer;
begin
if str <> '' then
try
Result := StrToInt(str);
except
on EConvertError do Result := 0;
else raise;
end
else
Result := 0;
end;
{-----------------------------------------------------------------------
Source: Torry's Delphi page
Author: Thomas Stutz
Homepage: http://www.swissdelphicenter.ch
-----------------------------------------------------------------------}
function MessageDialog(const ACaption: string; const Msg: string;
DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefButton: Integer;
HelpCtx: Longint): Word;
var
i: Integer;
btn: TButton;
begin
with CreateMessageDialog(Msg, DlgType, Buttons) do
try
Caption := ACaption;
HelpContext := HelpCtx;
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TButton) then
begin
btn := TButton(Components[i]);
btn.default := btn.ModalResult = DefButton;
if btn.default then ActiveControl := btn;
end;
end;
Result := ShowModal;
finally
Free;
end;
end;
function Piece(Value, Delimiter: string; StartPiece: Integer = 1): string;
begin
Result := Piece(Value, Delimiter, StartPiece, StartPiece);
end;
function Piece(Value, Delimiter: string; StartPiece: Integer; EndPiece: Integer): string;
var
dlen, i, pnum: Integer;
buf: String;
begin
Result := '';
if (Value <> '') And (StartPiece > 0) And (EndPiece >= StartPiece) then
begin
dlen := Length(Delimiter);
i := Pos(Delimiter, Value) - 1;
if i >= 0 then
begin
buf := Value;
pnum := 1;
repeat
if pnum > EndPiece then
break;
if i < 0 then
i := Length(buf);
if pnum = StartPiece then
Result := Copy(buf, 1, i)
else if pnum > StartPiece then
Result := Result + Delimiter + Copy(buf, 1, i);
Delete(buf, 1, i+dlen);
i := Pos(Delimiter, buf) - 1;
Inc(pnum);
until (i < 0) And (buf = '');
end
else if StartPiece = 1 then
Result := Value;
end;
end;
function WindowsDateToFMDate(WinDate: TDate): Double;
var
Year, Month, Day: Word;
begin
DecodeDate(WinDate, Year, Month, Day);
Result := ((Year - 1700) * 10000) + (Month * 100) + Day;
end;
function FMDateToWindowsDate(FMDate: Double): TDate;
var
FMString: string;
Year, Month, Day: Word;
begin
FMString := FloatToStr(FMDate);
try
Year := StrToInt(Copy(FMString, 1, 3)) + 1700;
Month := StrToInt(Copy(FMString, 4, 2));
Day := StrToInt(Copy(FMString, 6, 2));
Result := EncodeDate(Year, Month, Day);
except
on E: EConvertError do
begin
MessageDlg('Error Converting Date ' + FMString, mtError, [mbok], 0);
Result := Now;
end;
else
raise;
end;
end;
function WindowsDateTimeToFMDateTime(WinDate: TDateTime): Double;
var
Hour, Min, Sec, Msec: Word;
begin
Result := WindowsDateToFMDate(WinDate);
DecodeTime(WinDate, Hour, Min, Sec, Msec);
Result := Result + (Hour * 0.01) + (Min * 0.0001) + (Sec * 0.000001);
end;
function FMDateTimeToWindowsDateTime(FMDateTime: Double): TDateTime;
var
FMString: string;
Hour, Min, Sec: Word;
begin
FMString := FLoatToStr(FMDateTime);
Result := FMDateToWindowsDate(FMDateTime);
Hour := StrToIntDef(Copy(FMString, 9, 2), 0);
Min := StrToIntDef(Copy(FMString, 11, 2), 0);
Sec := StrToIntDef(Copy(FMString, 13, 2), 0);
Result := Result + EncodeTime(Hour, Min, Sec, 0);
end;
function AddKeyToValue(Value,Key,Delim:String):String;
var
i: Integer;
begin
i := pos(Delim+Key,Value);
if i > 0 then
Result := Value
else
begin
i := pos(Key,Value);
if i = 1 then
Result := Value
else
begin
if Value = '' then Result := Key
else Result := Value +Delim+Key;
end;
end;
end;
function DelKeyFromValue(Value,Key,Delim:String):String;
var
i: Integer;
s : String;
begin
i := pos(Key,Value);
if i = 0 then Result := Value
else
begin
s := Delim+Key;
i := pos(s,Value);
if i <> 0 then
s := copy(Value,1,i-1)+copy(Value,i+Length(s),Length(Value))
else
if pos(Key,Value)=1 then
s := copy(Value,Length(Key)+1,Length(Value));
if pos(Delim,s)= 1 then
S := copy(s,Length(Delim)+1,Length(s));
Result := S;
end;
end;
function FormatSSN(aSSN:String):String;
var
s: String;
begin
try
s := aSSN;
While pos(' ',s) = 1 do
s := copy(s,2,length(s)-1);
if pos('*S',s)=1 then
Result := s
else
Result := Copy(aSSN,1,3)+'-'+Copy(aSSN,4,2)+'-'+Copy(aSSN,6,99);
except
Result := aSSN
end;
end;
function ReFormatSSN(aSSN:String):String;
var
i : Integer;
sResult: String;
begin
i := pos('-',aSSN);
sResult := aSSN;
while i <> 0 do
begin
sResult := copy(sResult,1,i-1)+copy(sResult,i+1,99);
i := pos('-',sResult);
end;
Result := sResult;
end;
procedure DelLVSelectedLine(LVFrom:TListView);
var
iPrev,i: Integer;
begin
if not Assigned(LVFrom) then Exit;
iPrev := lvFrom.ItemFocused.Index;
i := 0;
while i < lvFrom.Items.Count do
begin
if lvFrom.Items[i].Selected then
lvFrom.Items.Delete(i)
else
inc(i);
end;
try
if lvFrom.Items.Count < iPrev then
iPrev := lvFrom.Items.Count - 1;
if iPrev >=0 then
lvFrom.Selected := lvFrom.Items[iPrev];
except
on E: Exception do
MessageDlg('Error Deleting Element list'+#13+E.Message, mtInformation, [mbok], 0);
end;
EXIT;
try
if lvFrom.ItemFocused = nil then
lvFrom.Items.Delete(0)
else
lvFrom.Items.Delete(lvFrom.ItemFocused.Index);
lvFrom.Selected := lvFrom.ItemFocused;
except
end;
end;
procedure CopyLVLine(LVFrom, LVTo:TListView;Mode:Boolean);
var
i: Integer;
liFrom,
li:TListItem;
begin
if lvFrom.ItemFocused = nil then
liFrom := lvFrom.Items[0]
else
liFrom := lvFrom.ItemFocused;
try
for i := 0 to lvTo.Items.Count - 1 do
if lvTo.Items[i].Caption = liFrom.Caption then
begin
lvTo.ItemFocused := lvTo.Items[i];
Exit;
end;
li := lvTo.Items.Add;
li.Caption := liFrom.Caption;
for i := 0 to liFrom.SubItems.Count - 1 do
li.SubItems.Add(liFrom.SubItems[i]);
if Mode then
lvFrom.Items.Delete(liFrom.Index)
else
if liFrom.Index < lvFrom.Items.Count - 1 then
lvFrom.ItemFocused := lvFrom.Items[liFrom.Index+1];
lvFrom.Selected := lvFrom.ItemFocused;
except
end;
end;
procedure CopySelectedLVLines(LVFrom, LVTo:TListView;Mode:Boolean);
var
iPrev, iCurr,
i: Integer;
liFrom,
li:TListItem;
begin
iPrev := lvFrom.ItemFocused.Index;
iCurr := 0;
while iCurr < lvFrom.Items.Count do
begin
liFrom := lvFrom.Items[iCurr];
if not liFrom.Selected then
begin
Inc(iCurr);
Continue;
end;
liFrom.Selected := False;
for i := 0 to lvTo.Items.Count - 1 do
if lvTo.Items[i].Caption = lvFrom.Items[iCurr].Caption then
break;
if i < lvTo.Items.Count then
begin
inc(iCurr);
continue;
end;
li := lvTo.Items.Add;
li.Caption := liFrom.Caption;
for i := 0 to liFrom.SubItems.Count - 1 do
li.SubItems.Add(liFrom.SubItems[i]);
if Mode then
lvFrom.Items.Delete(iCurr)
else
inc(iCurr);
end;
try
if lvFrom.Items.Count < iPrev then
iPrev := lvFrom.Items.Count - 1
else
Inc(iPrev);
if iPrev >=0 then
begin
lvFrom.ItemFocused := lvFrom.Items[iPrev];
lvFrom.Selected := lvFrom.ItemFocused;
end;
except
on E: Exception do
MessageDlg('Error Deleting Element list'+#13+E.Message, mtInformation, [mbok], 0);
end;
end;
procedure CopyAllLVLine(LVFrom, LVTo:TListView);
var
j,
i: Integer;
begin
try
j := lvFrom.ItemFocused.Index;
except
j := 0;
end;
for i := 0 to lvFrom.Items.Count - 1 do
begin
lvFrom.ItemFocused := lvFrom.Items[i];
CopyLVLine(LVFrom, LVTo,False);
end;
lvFrom.ItemFocused := lvFrom.Items[j];
end;
procedure CopyLVHeaders(LVFrom, LVTo:TListView);
var
lc:TListColumn;
i: Integer;
begin
LVTo.Columns.Clear;
for i := 0 to lvFrom.Columns.Count - 1 do
begin
lc := lvTo.Columns.Add;
lc.Caption := lvFrom.Columns[i].Caption;
lc.Width := lvFrom.Columns[i].Width;
end;
end;
procedure UpdateListView(aStrings: TStrings;aLV: TListView;
iCaptionIndex: Integer;anIndexes: array of integer);
var
s: String;
li:TListItem;
j,
i,iCount: Integer;
begin
try
iCount := StrToInt(piece(aStrings[0],'^',1));
if iCount > aStrings.Count - 1 then
iCount := aStrings.Count - 1;
except
iCount := 0;
end;
aLV.Items.Clear;
for i := 1 to iCount do
begin
s := aStrings[i];
li := aLV.Items.Add;
li.Caption := piece(s,'^',iCaptionIndex);
for j := Low(anIndexes) to High(anIndexes) do
li.SubItems.Add(piece(s,'^',anIndexes[j]));
end;
try
if aLV.Items.Count < 1 then exit;
aLV.ItemFocused := aLV.Items[0];
aLV.ItemFocused.Selected := True;
except
end;
end;
procedure UpdateAndNotClearListView(aStrings: TStrings;aLV: TListView;
iCaptionIndex: Integer;anIndexes: array of integer);
var
s: String;
li:TListItem;
j,
i,iCount: Integer;
begin
try
iCount := StrToInt(piece(aStrings[0],'^',1));
if iCount > aStrings.Count - 1 then
iCount := aStrings.Count - 1;
except
iCount := 0;
end;
// aLV.Items.Clear;
for i := 1 to iCount do
begin
s := aStrings[i];
li := aLV.Items.Add;
li.Caption := piece(s,'^',iCaptionIndex);
for j := Low(anIndexes) to High(anIndexes) do
li.SubItems.Add(piece(s,'^',anIndexes[j]));
end;
try
if aLV.Items.Count < 1 then exit;
aLV.ItemFocused := aLV.Items[0];
aLV.ItemFocused.Selected := True;
except
end;
end;
procedure StringListToListView(aSL: TStringList;aLV: TListView;
iCaptionIndex: Integer;anIndexes: array of integer);
var
li:TListItem;
j,i: Integer;
begin
aLV.Items.Clear;
for i := 0 to aSL.Count -1 do
begin
li := aLV.Items.Add;
li.Caption := piece(aSL[i],'^',iCaptionIndex);
for j := Low(anIndexes) to High(anIndexes) do
li.SubItems.Add(piece(aSL[i],'^',anIndexes[j]));
end;
try
aLV.ItemFocused := aLV.Items[0];
aLV.ItemFocused.Selected := True;
except
end;
end;
procedure ListViewToParamList(aLV: TListView;anIndex:Integer;var aStrings:TStringList);
var
i: Integer;
begin
for i := 0 to aLV.Items.Count - 1 do
begin
if anIndex = 0 then
aStrings.Add(aLV.Items[i].Caption)
else
aStrings.Add(aLV.Items[i].SubItems[anIndex-1]);
end;
end;
procedure UpdateStringList(aStrings:TStrings;aSL: TStringList);
var
i, iCount: Integer;
begin
aSL.Clear;
if aStrings.Count > 0 then
begin
iCount := IntVal(Piece(aStrings[0],'^',1));
for i := 1 to iCount do
aSL.Add(aStrings[i]);
end;
end;
procedure ListViewToStringList(aLV: TListView;aL: TStringList;anIndexes: array of Integer;
aStart,aDelim:String);
var
i, j: Integer;
s: String;
begin
for i := 0 to aLV.Items.Count - 1 do
begin
s := aStart;
for j := Low(anIndexes) to High(anIndexes) do
s := s + aDelim+ aLV.Items[i].SubItems[j];
aL.Add(s);
end;
end;
procedure LoadColumnsWidth(aName:String;aColumns:TListColumns;sL: TStringList);
var
i: Integer;
s: String;
begin
if aColumns = nil then Exit;
for i := 0 to aColumns.Count - 1 do
try
s := sL.Values[aName+'-'+IntToStr(i)];
aColumns[i].Width := StrToIntDef(sL.Values[s],aColumns[i].Width);
except
end;
end;
procedure AddParam(aName,aValue:String;sL:TStringList);
begin
sL.Add(aName + '='+aValue);
end;
procedure SaveColumnsWidth(aName:String;aColumns:TListColumns;sL:TStringList);
var
i: Integer;
begin
for i := 0 to aColumns.Count - 1 do
begin
AddParam(aName+'-'+IntToStr(i),IntToStr(aColumns[i].Width),sL);
end;
end;
function StringByKey(aStrings:TStrings;aKey:String;aPosition:Integer):String;
var
s: String;
i: Integer;
begin
s := '';
for i := 1 to aStrings.Count - 1 do
if piece(aStrings[i],'^',aPosition) = aKey then
s := aStrings[i];
Result := s;
end;
procedure UpdateEdit(var Key: Char; Sender: TObject);
var
s,sY,sM: String;
begin
if ((pos(Upcase(Key),'0123456789/') = 0)) then
begin
if Key <> Char(#13) then
Key := Char(#8);
exit;
end;
s := TEdit(Sender).Text;
sY := piece(s,'/',2);
sM := piece(s,'/',1);
if ((s='') and (Key='/')) then
begin
Key := Char(#8);
exit;
end
else if (pos('/',s)<>0) and (Key='/') then
begin
Key := Char(#0);
exit;
end
else if sY = '' then
begin
case Length(sM) of
0:;
1:
begin
if (sM<>'0') and (sM<>'1') then
begin
if Key <> '/' then
begin
TEdit(Sender).Text := '0'+sM +'/';
end
else
TEdit(Sender).Text := '0'+sM;
TEdit(Sender).SelStart := 3;
end
else if (sM = '0') and ((Key='/') or (Key='0')) then
begin
Key := Char(#0);
exit;
end;
end;
2:
if (sM <> '11') and (sM <>'12') then
begin
if pos('0',sM) = 0 then
begin
sM := '0'+copy(sM,1,1);
sY := copy(sM,2,4);
end;
TEdit(Sender).Text := sM +'/'+sY;
TEdit(Sender).SelStart := 4;
if Key='/' then Key:=Char(#0);
end
else
begin
if Key <>'/' then
begin
if pos('/',s) <> 0 then
s := s +Key
else
s := s + '/'+Key
end
else
s := s + '/';
TEdit(Sender).Text := s;
TEdit(Sender).SelStart := 4;
Key := Char(#0);
end;
end;
end
else
begin
if (Key = Char(#8)) and
(TEdit(Sender).SelStart = 3) then
Key := Char(#0);
end;
end;
procedure SetPanelStatus(aPanel:TPanel;aStatus:Boolean;aColor:TColor);
var
i: Integer;
begin
aPanel.Enabled := aStatus;
for i := 0 to aPanel.ControlCount - 1 do
begin
if aPanel.Controls[i] is TPanel then
SetPanelStatus(TPanel(aPanel.Controls[i]),aStatus,aColor)
else if aPanel.Controls[i] is TEdit then
TEdit(aPanel.Controls[i]).Color := aColor
else if aPanel.Controls[i] is TListView then
TListView(aPanel.Controls[i]).Color := aColor
else if aPanel.Controls[i] is TTreeView then
TTreeView(aPanel.Controls[i]).Color := aColor
else if aPanel.Controls[i] is TCheckBox then
TCheckBox(aPanel.Controls[i]).Enabled := aStatus
else if aPanel.Controls[i] is TRadioButton then
TRadioButton(aPanel.Controls[i]).Enabled := aStatus
else if aPanel.Controls[i] is TComboBox then
TComboBox(aPanel.Controls[i]).Color := aColor;
end;
end;
function dVal(gStr,sDateTime: string): Double;
var
i: integer;
begin
Result := iIgnore; // zzzzzzandria 060123
if trim(gStr) = '' then Exit;
i := 1;
if pos('-',gStr)=1 then i := 2; // zzzzzzandria 051107
while (StrToIntDef(Copy(gStr, i, 1), -1) > -1)
or (Copy(gStr, i, 1) = '.') do inc(i);
try
Result := StrToFloat(Copy(gStr, 1, i - 1));
// Result := StrToFloat(Piece(gStr, ' ',1));
except
on E: EConvertError do
begin
if not ((pos('Ref',gStr) = 1) or (pos('Una',gStr) =1) or (pos('Pass',gStr)=1)) then
MessageDlg(
'Error converting value to numeric' + #13 +
'Value: ' + gStr + #13#13+
'Date/Time: ' + sDateTime +#13#13 +
' A value of 0 (zero) will be used instead.',
mtWarning, [mbok], 0);
Result := 0;
end;
else
raise;
end;
end;
function getCellDateTime(s:String):TDateTime;
var
i: Integer;
d: double;
begin
i := pos('-',s);
while i > 0 do
begin
s := copy(s,1,i-1)+'/'+copy(s,i+1,Length(s));
i := pos('-',s);
end;
try
d := StrToDateTime(s);
except
d := now;
end;
Result := d;
end;
function ReplaceStr(aLine,aTarget,aReplacement:String):String;
var
s: String;
i: Integer;
begin
Result := aLine;
if aTarget = aReplacement then Exit;
if aTarget = '' then Exit;
i := pos(aTarget,aLine);
s := aLine;
while i > 0 do
begin
s := copy(s,1,i-1)+aReplacement+copy(s,i+Length(aTarget),Length(s));
i := pos(aTarget,s);
end;
Result := s;
end;
procedure PositionForm(aForm: TForm);
var
iHeight,
iWidth: Integer;
begin
iHeight := Screen.WorkAreaHeight;
iWidth := Screen.WorkAreaWidth;
if aForm.Width > iWidth then aForm.Width := iWidth;
if aForm.Height > iHeight then aForm.Height := iHeight;
if aForm.Top> iHeight then aForm.Top := 0;
if aForm.Left> iWidth then aForm.Left := 0;
if aForm.Top < 0 then aForm.Top := 0;
if aForm.Left < 0 then aForm.Left := 0;
if aForm.Top + aForm.Height > iHeight then
aForm.Top := iHeight - aForm.Height;
if aForm.Left + aForm.Width > iWidth then
aForm.Left := iWidth - aForm.Width;
end;
// SHARE_DIR = '\VISTA\Common Files\';
function GetProgramFilesPath: String;
Const
CSIDL_PROGRAM_FILES = $0026;
var
Path: array[0..Max_Path] of Char;
begin
Path := '';
SHGetSpecialFolderPath(0,Path,CSIDL_PROGRAM_FILES,false);
Result := Path;
end;
initialization
FMInitFormatArray;
end.
|
unit unit_ws_setup;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Spin,
ButtonPanel, StdCtrls;
type
{ Tform_ws_setup }
Tform_ws_setup = class(TForm)
bp: TButtonPanel;
cb_local: TCheckBox;
cb_auth: TCheckBox;
Port: TLabel;
e_url: TLabeledEdit;
e_pw: TLabeledEdit;
se_port: TSpinEdit;
procedure cb_authChange(Sender: TObject);
procedure cb_localChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
private
public
f_auth:boolean;
ip:ansistring;
ws_port:integer;
pw:ansistring;
e_url_buffer:ansistring;
end;
var
form_ws_setup: Tform_ws_setup;
implementation
{$R *.lfm}
{ Tform_ws_setup }
procedure Tform_ws_setup.cb_authChange(Sender: TObject);
begin
if cb_auth.Checked then begin
e_pw.Enabled:=true;
f_auth:=true;
end
else begin
e_pw.Enabled:=false;
f_auth:=false;
end;
end;
procedure Tform_ws_setup.cb_localChange(Sender: TObject);
begin
if cb_local.Checked then begin
e_url.Enabled:=false;
e_url_buffer:=e_url.text;
e_url.Text:='127.0.0.1';
end
else begin
e_url.Enabled:=true;
e_url.text:=e_url_buffer;
end;
end;
procedure Tform_ws_setup.FormCreate(Sender: TObject);
begin
if cb_auth.Checked then begin
e_pw.Enabled:=true;
f_auth:=true;
end
else begin
e_pw.Enabled:=false;
f_auth:=false;
end;
e_url_buffer:=e_url.text;
if cb_local.Checked then begin
e_url.Enabled:=false;
e_url_buffer:=e_url.text;
e_url.Text:='127.0.0.1';
end
else begin
e_url.Enabled:=true;
e_url.text:=e_url_buffer;
end;
ip:=e_url.text;
ws_port:=se_port.value;
pw:=e_pw.text;
end;
procedure Tform_ws_setup.OKButtonClick(Sender: TObject);
begin
if cb_auth.Checked then begin
e_pw.Enabled:=true;
f_auth:=true;
end
else begin
e_pw.Enabled:=false;
f_auth:=false;
end;
ip:=e_url.text;
ws_port:=se_port.value;
pw:=e_pw.text;
end;
end.
|
unit osFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ActnList, osUtils, ImgList, osActionList, System.Generics.Collections, System.Actions {$IFDEF VER320} , System.ImageList {$ENDIF};
type
TOperacao = (oInserir, oEditar, oExcluir, oVisualizar, oImprimir);
TOperacoes = set of TOperacao;
TWhiteList = class(TObjectList<TComponent>)
end;
TosForm = class(TForm)
ActionList: TosActionList;
OnCheckActionsAction: TAction;
ImageList: TImageList;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FOperacoes: TOperacoes;
procedure SetOperacoes(const Value: TOperacoes);
protected
FWhiteList: TWhiteList;
procedure DisableWinControlComponents(aWinControl: TWinControl);
procedure EnableWinControlComponents(aWinControl: TWinControl);
procedure AddControlsToWhiteListByContainer(aContainer: TWinControl);
function GetWhiteList: TWhiteList;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Operacoes: TOperacoes read FOperacoes write SetOperacoes;
end;
var
osForm: TosForm;
implementation
uses TypInfo, Vcl.ComCtrls, Vcl.Menus;
{$R *.DFM}
{ TBizForm }
constructor TosForm.Create(AOwner: TComponent);
begin
inherited;
//CheckDefaultParams; // Carrega os parâmetros empresa/estabelecimento se necessário
end;
destructor TosForm.Destroy;
begin
FreeAndNil(FWhiteList);
inherited;
end;
procedure TosForm.FormShow(Sender: TObject);
begin
OnCheckActionsAction.Execute;
end;
procedure TosForm.SetOperacoes(const Value: TOperacoes);
begin
FOperacoes := Value;
end;
procedure TosForm.FormCreate(Sender: TObject);
begin
Operacoes := [oInserir, oEditar, oExcluir, oVisualizar]; // operações Defaults
end;
procedure TosForm.DisableWinControlComponents(aWinControl: TWinControl);
var
i: integer;
infoEnabled: PPropInfo;
begin
for i:= 0 to aWinControl.ComponentCount - 1 do
if (aWinControl.Components[i] is TPageControl) then
Self.DisableWinControlComponents(TPageControl(aWinControl.Components[i]))
else
begin
if (not self.GetWhiteList.Contains(aWinControl.Components[i])) and
((aWinControl.Components[i] is TPopupMenu) or (aWinControl.Components[i] is TMenuItem) or (aWinControl.Components[i] is TWinControl)) then
begin
infoEnabled := TypInfo.GetPropInfo(aWinControl.Components[i], 'Enabled');
if assigned(infoEnabled) then
TypInfo.SetPropValue(aWinControl.Components[i], 'Enabled', False);
end;
end;
end;
procedure TosForm.EnableWinControlComponents(aWinControl: TWinControl);
var
i: integer;
infoEnabled: PPropInfo;
begin
for i:= 0 to aWinControl.ComponentCount - 1 do
begin
infoEnabled := TypInfo.GetPropInfo(aWinControl.Components[i], 'Enabled');
if assigned(infoEnabled) then
TypInfo.SetPropValue(aWinControl.Components[i], 'Enabled', True);
if aWinControl.Components[i] is TWinControl then
EnableWinControlComponents(TWinControl(aWinControl.Components[i]));
end;
end;
function TosForm.GetWhiteList: TWhiteList;
begin
if FWhiteList = nil then
begin
FWhiteList := TWhiteList.Create;
FWhiteList.OwnsObjects := False;
end;
Result := FWhiteList;
end;
procedure TosForm.AddControlsToWhiteListByContainer(aContainer: TWinControl);
var
i: integer;
begin
Self.GetWhiteList.Add(aContainer);
for i:= 0 to aContainer.ComponentCount - 1 do
begin
Self.GetWhiteList.Add(aContainer.Components[i]);
if (aContainer.Components[i] is TWinControl) then
AddControlsToWhiteListByContainer(TWinControl(aContainer.Components[i]));
end;
end;
end.
|
{$MODE OBJFPC}
program MaximumFlow;
const
maxN = 1000;
maxM = 100000;
maxC = 10000;
type
TEdge = record //Cấu trúc một cung
x, y: Integer; //Hai đỉnh đầu mút
c, f: Integer; //Sức chứa và luồng
end;
TQueue = record //Cấu trúc hàng đợi
items: array[0..maxN - 1] of Integer; //Danh sách vòng
front, rear, nItems: Integer;
end;
var
e: array[-maxM..maxM] of TEdge; //Mảng chứa các cung
link: array[-maxM..maxM] of Integer;
//Móc nối trong danh sách liên thuộc
head, current: array[1..maxN] of Integer;
//con trỏ tới đầu và vị trí hiện tại của danh sách liên thuộc
excess: array[1..maxN] of Integer; //mức tràn của các đỉnh
h: array[1..maxN] of Integer; //hàm độ cao
count: array[0..2 * maxN - 1] of Integer;
//count[k] = số đỉnh có độ cao k
Queue: TQueue; //Hàng đợi chứa các đỉnh tràn
n, m, s, t: Integer;
FlowValue: Integer;
procedure Enter; //Nhập dữ liệu
var
i, u, v, capacity: Integer;
begin
ReadLn(n, m, s, t);
FillChar(head[1], n * SizeOf(head[1]), 0);
for i := 1 to m do
begin
ReadLn(u, v, capacity);
with e[i] do
begin
x := u;
y := v;
c := capacity;
link[i] := head[u];
head[u] := i;
end;
with e[-i] do
begin
x := v;
y := u;
c := 0;
link[-i] := head[v];
head[v] := -i;
end;
end;
for v := 1 to n do current[v] := head[v];
end;
procedure PushToQueue(v: Integer); //Đẩy một đỉnh v vào hàng đợi
begin
with Queue do
begin
rear := (rear + 1) mod maxN;
//Dịch chỉ số cuối hàng đợi, rear = maxN - 1 sẽ trở lại thành 0
items[rear] := v; //Đặt v vào vị trí cuối hàng đợi
Inc(nItems); //Tăng biến đếm số phần tử trong hàng đợi
end;
end;
function PopFromQueue: Integer; //Lấy một đỉnh khỏi hàng đợi
begin
with Queue do
begin
Result := items[front]; //Trả về phần tử ở đầu hàng đợi
front := (front + 1) mod maxN;
//Dịch chỉ số đầu hàng đợi, front = maxN - 1 sẽ trở lại thành 0
Dec(nItems); //Giảm biến đếm số phần tử trong hàng đợi
end;
end;
procedure Init; //Khởi tạo
var v, sf, i: Integer;
begin
//Khởi tạo tiền luồng
for i := -m to m do e[i].f := 0;
FillChar(excess[1], n * SizeOf(excess[1]), 0);
i := head[s];
while i <> 0 do
//Duyệt các cung ñi ra khỏi ñỉnh phát và ñẩy bão hòa các cung ñó, cập nhật các mức tràn excess[.]
begin
sf := e[i].c;
e[i].f := sf;
e[-i].f := -sf;
Inc(excess[e[i].y], sf);
Dec(excess[s], sf);
i := link[i];
end;
//Khởi tạo hàm độ cao
for v := 1 to n do h[v] := 1;
h[s] := n;
h[t] := 0;
//Khởi tạo các biến đếm: count[k] là số đỉnh có độ cao k
FillChar(count[0], (2 * n) * SizeOf(count[0]), 0);
count[n] := 1;
count[0] := 1;
count[1] := n - 2;
//Khởi tạo hàng đợi chứa các đỉnh tràn
Queue.front := 0;
Queue.rear := -1;
Queue.nItems := 0; //Hàng đợi rỗng
for v := 1 to n do //Duyệt tập đỉnh
if (v <> s) and (v <> t) and (excess[v] > 0) then
//v tràn213
PushToQueue(v); //đẩy v vào hàng đợi
end;
procedure Push(i: Integer); //Phép đẩy luồng theo cung e[i]
var Delta: Integer;
begin
with e[i] do
if excess[x] < c - f then Delta := excess[x]
else Delta := c - f;
Inc(e[i].f, Delta);
Dec(e[-i].f, Delta);
with e[i] do
begin
Dec(excess[x], Delta);
Inc(excess[y], Delta);
end;
end;
procedure SetH(u: Integer; NewH: Integer);
//Đặt độ cao của u thành NewH, đồng bộ hóa mảng count
begin
Dec(count[h[u]]);
h[u] := NewH;
Inc(count[NewH]);
end;
procedure PerformGapHeuristic(gap: Integer);
//Đẩy nhãn theo khe gap
var v: Integer;
begin
if (0 < gap) and (gap < n) and (count[gap] = 0) then
//gap đúng là khe thật
for v := 1 to n do
if (v <> s) and (gap < h[v]) and (h[v] <= n) then
begin
SetH(v, n + 1);
current[v] := head[v];
//Nâng độ cao của v cần phải cập nhật lại con trỏ current[v]
end;
end;
procedure Lift(u: Integer); //Phép nâng đỉnh u
var minH, OldH, i: Integer;
begin
minH := 2 * maxN;
i := head[u];
while i <> 0 do //Duyệt các cung đi ra khỏi u
begin
with e[i] do
if (c > f) and (h[y] < minH) then
//Gặp cung thặng dư (u, v), ghi nhận đỉnh v thấp nhát
minH := h[y];
i := link[i];
end;
OldH := h[u]; //Nhớ lại h[u] cũ
SetH(u, minH + 1); //nâng cao đỉnh u
PerformGapHeuristic(OldH); //Có thể tạo ra khe OldH, đẩy nhãn theo khe
end;
procedure FIFOPreflowPush; //Thuật toán FIFO Preflow-Push
var
NeedQueue: Boolean;
z: Integer;
begin
while Queue.nItems > 0 do //Chừng nào hàng đợi vẫn còn đỉnh tràn
begin
z := PopFromQueue; //Lấy một đỉnh tràn x khỏi hàng đợi
while current[z] <> 0 do //Xét một cung đi ra khỏi x
begin
with e[current[z]] do
begin
if (c > f) and (h[x] > h[y]) then
//Nếu có thể đẩy luồng được theo cung (u, v)
begin
NeedQueue := (y <> s) and (y <> t)
and (excess[y] = 0);
Push(current[z]); //Đẩy luồng luôn
if NeedQueue then
//v đang không tràn sau phép đẩy trở thành tràn
PushToQueue(y); //Đẩy v vào hàng đợi
if excess[z] = 0 then Break;
//x hết tràn thì chuyển qua xét đỉnh khác ngay
end;
end;
current[z] := link[current[z]];
//x chưa hết tràn thì chuyển sang xét cung liên thuộc tiếp theo
end;
if excess[z] > 0 then //Duyệt hết danh sách liên thuộc mà x vẫn tràn
begin
Lift(z); //Nâng cao x
current[z] := head[z];
//Đặt con trỏ current[x] trỏ lại về đầu danh sách liên thuộc
PushToQueue(z); //Đẩy lại x vào hàng đợi chờ xử lý sau
end;
end;
FlowValue := excess[t];
//Thuật toán kết thúc, giá trị luồng bằng tổng luồng đi vào đỉnh thu (= - excess[s])
end;
procedure PrintResult; //In kết quả
var i: Integer;
begin
WriteLn('Maximum flow: ');
for i := 1 to m do
with e[i] do
if f > 0 then //Chỉ cần in ra các cung có luồng > 0
WriteLn('e[', i, '] = (', x, ', ', y, '): c
= ', c, ', f = ', f);
WriteLn('Value of flow: ', FlowValue);
end;
begin
Enter; //Nhập dữ liệu
Init; //Khởi tạo
FIFOPreflowPush; //Thực hiện thuật toán đẩy tiền luồng
PrintResult; //In kết quả
end. |
unit bool_and_not_2;
interface
implementation
procedure Test1;
var
r, a, b: Boolean;
begin
a := false;
b := false;
r := a and not b;
Assert(not r);
end;
procedure Test2;
var
r, a, b: Boolean;
begin
a := true;
b := false;
r := a and not b;
Assert(r);
end;
procedure Test3;
var
r, a, b: Boolean;
begin
a := false;
b := true;
r := a or not b;
Assert(not r);
end;
procedure Test4;
var
r, a, b: Boolean;
begin
a := true;
b := true;
r := a and not b;
Assert(not r);
end;
initialization
Test1();
Test2();
Test3();
Test4();
finalization
end. |
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit DSAzDlgMetadata;
interface
uses Vcl.Buttons, System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms, Vcl.Graphics, Vcl.Grids, Vcl.StdCtrls, Vcl.ValEdit;
type
TAzMetadata = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
vleMeta: TValueListEditor;
btnDelMetadata: TButton;
btnAddMetadata: TButton;
procedure btnAddMetadataClick(Sender: TObject);
procedure btnDelMetadataClick(Sender: TObject);
procedure vleMetaStringsChange(Sender: TObject);
private
{ Private declarations }
function IsMetadata(const Data: String): boolean;
function MetadataName(const Data: String): string;
function ShortName(const xmsData: String): String;
public
{ Public declarations }
procedure PopulateContentFromHeader(const header: TStrings; AChange: boolean = false);
procedure PopulateHeaderFromContainer(const header: TStrings);
end;
implementation
const XMSMETA = 'x-ms-meta-';
{$R *.dfm}
procedure TAzMetadata.btnAddMetadataClick(Sender: TObject);
begin
vleMeta.Col := 0;
vleMeta.Row := vleMeta.InsertRow('', '', true);
vleMeta.SetFocus;
OKBtn.Enabled := true;
end;
procedure TAzMetadata.btnDelMetadataClick(Sender: TObject);
var
row: Integer;
begin
row := vleMeta.Row;
if (row > 0) and (row < vleMeta.RowCount) then
begin
vleMeta.DeleteRow(row);
OKBtn.Enabled := true;
end;
end;
function TAzMetadata.IsMetadata(const Data: String): boolean;
begin
Result := Pos(XMSMETA, Data) = 1;
end;
function TAzMetadata.MetadataName(const Data: String): string;
begin
Result := XMSMETA + Data;
end;
procedure TAzMetadata.PopulateContentFromHeader(const header: TStrings; AChange: boolean);
var
i, count: Integer;
begin
count := header.Count;
vleMeta.Strings.BeginUpdate;
vleMeta.Strings.Clear;
for i := 0 to count - 1 do
begin
if IsMetadata(header.Names[i]) then
vleMeta.Strings.Values[ShortName(header.Names[i])] := header.ValueFromIndex[i];
end;
vleMeta.Strings.EndUpdate;
OKBtn.Enabled := AChange;
end;
procedure TAzMetadata.PopulateHeaderFromContainer(const header: TStrings);
var
i, count: Integer;
begin
header.Clear;
count := vleMeta.Strings.Count;
for i := 0 to count - 1 do
header.Values[MetadataName(vleMeta.Strings.Names[i])] := vleMeta.Strings.ValueFromIndex[i];
end;
function TAzMetadata.ShortName(const xmsData: String): String;
begin
Result := Copy(xmsData, Length(XMSMETA) + 1);
end;
procedure TAzMetadata.vleMetaStringsChange(Sender: TObject);
begin
OKBtn.Enabled := true;
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit BindCompEdit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, DesignWindows,
Vcl.StdCtrls, Vcl.Menus, Vcl.ExtCtrls, Vcl.StdActns, DesignIntf, Vcl.ComCtrls, Vcl.ToolWin, Vcl.ActnList,
Vcl.ImgList, ToolWnds, Vcl.ActnPopup, Vcl.PlatformDefaultStyleActnCtrls,
Data.Bind.Components;
const
AM_DeferUpdate = WM_USER + 100; // avoids break-before-make listview ugliness
type
TCategoryKind = (ckCategory, ckNone, ckAll);
TDataBindingListDesigner = class;
TDataBindingListDesigner = class(TToolbarDesignWindow)
MoveUp1: TMenuItem;
MoveDown1: TMenuItem;
SelectAllItem: TMenuItem;
N2: TMenuItem;
CutItem: TMenuItem;
CopyItem: TMenuItem;
PasteItem: TMenuItem;
DeleteItem: TMenuItem;
RemoveBindComp: TAction;
MoveUp: TAction;
MoveDown: TAction;
ImageList1: TImageList;
SelectAllAction: TAction;
AddCommon1: TMenuItem;
NewDataBindingsPopup: TPopupMenu;
CategoryPanel: TPanel;
ListBox1: TListBox;
Panel3: TPanel;
Label1: TLabel;
ActionPanel: TPanel;
ListView1: TListView;
Panel4: TPanel;
Label2: TLabel;
NewDataBinding1: TMenuItem;
NewBindCompDialog: TAction;
NewStandardDataBinding1: TMenuItem;
EditCopy1: TEditCopy;
EditCut1: TEditCut;
EditPaste1: TEditPaste;
DescriptionsAction: TAction;
PanelDescriptions1: TMenuItem;
Splitter2: TSplitter;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton5: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
N3: TMenuItem;
NewCommonDataBinding: TAction;
procedure DeleteClick(Sender: TObject);
procedure ListView1Click(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure MoveUpClick(Sender: TObject);
procedure ListView1DragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure ListView1DragDrop(Sender, Source: TObject; X, Y: Integer);
procedure MoveDownClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure ListView1Change(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure SelectAllItemClick(Sender: TObject);
procedure PasteItemClick(Sender: TObject);
procedure CopyItemClick(Sender: TObject);
procedure CutItemClick(Sender: TObject);
procedure SelectedUpdate(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
procedure NewBindCompDialogExecute(Sender: TObject);
procedure ListView1KeyPress(Sender: TObject; var Key: Char);
procedure ListView1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure SelectAllActionUpdate(Sender: TObject);
procedure NewDataBindingsPopupPopup(Sender: TObject);
procedure DescriptionsActionExecute(Sender: TObject);
procedure ListView1StartDrag(Sender: TObject;
var DragObject: TDragObject);
procedure ListView1EndDrag(Sender, Target: TObject; X, Y: Integer);
procedure ListView1DblClick(Sender: TObject);
procedure NewCommonDataBindingExecute(Sender: TObject);
procedure MoveUpUpdate(Sender: TObject);
procedure MoveDownUpdate(Sender: TObject);
procedure ListView1Resize(Sender: TObject);
private
FDataBindingListClassName: string;
FCategory: string;
FCategoryKind: TCategoryKind;
FCommonDataBindingClass: TContainedBindCompClass;
FItemIDList: TList;
FStateLock: Integer;
FSelectionError: Boolean;
FFixups: TList;
FUpdateCount: Integer;
FDragObject: TDragObject;
function GetRegKey: string;
procedure AMDeferUpdate(var Msg); message AM_DeferUpdate;
procedure Copy;
procedure Cut;
procedure Paste;
procedure Remove;
procedure SelectAll(DoUpdate: Boolean = True);
procedure SelectNone(DoUpdate: Boolean = True);
function GetDataBindingIndex(ListIndex: Integer): Integer;
function GetDescriptionsVisible: Boolean;
procedure SetDescriptionsVisible(Value: Boolean);
procedure SetCommonDataBindingClass(Value: TContainedBindCompClass);
procedure UpdateCaption;
procedure ComponentRead(Component: TComponent);
procedure ReaderSetName(Reader: TReader; Component: TComponent;
var Name: string);
procedure ReaderSetName2(Reader: TReader; Component: TComponent;
var Name: string);
procedure LoadFromClipboard(AOwner, AParent: TComponent; Components: TList);
procedure ReadStream(Stream: TStream; AOwner, AParent: TComponent; Components: TList);
procedure NotifyDataBindingListChange;
procedure NotifyNewDataBindings(const Classes: array of TContainedBindCompClass);
procedure CategoryOfClassEnumProc(const Category: string;
BindCompClass: TContainedBindCompClass;
Info: TEnumBindCompProcInfo);
function CategoryOfClass(AClass: TContainedBindCompClass): string;
protected
function DataBindingVisible(DataBinding: TContainedBindComponent): Boolean;
procedure BeginUpdate;
procedure BuildNewDataBindings; virtual;
procedure EndUpdate;
procedure FocusDataBinding(DataBinding: TContainedBindComponent);
function IndexOfDataBinding(DataBinding: TContainedBindComponent): Integer;
procedure Activated; override;
procedure DoNewDataBinding(const Category: string; DataBinding: TContainedBindComponent);
procedure Clear;
procedure LockState;
function UniqueName(Component: TComponent): string; override;
procedure UnlockState;
property StateLock: Integer read FStateLock;
property DescriptionsVisible: Boolean read GetDescriptionsVisible write SetDescriptionsVisible;
public
FDataBindingList: TCustomBindingsList;
procedure ItemDeleted(const ADesigner: IDesigner; AItem: TPersistent); override;
function EditAction(Action: TEditAction): Boolean; override;
procedure DesignerClosed(const ADesigner: IDesigner; AGoingDormant: Boolean); override;
procedure ItemsModified(const ADesigner: IDesigner); override;
function GetEditState: TEditState; override;
function GetItemName(Index, ItemIndex: Integer): string;
procedure GetSelection;
procedure SelectionChanged(const Designer: IDesigner;
const ASelection: IDesignerSelections); override;
procedure SetSelection;
procedure UpdateView(AUpdateColumns: Boolean = False);
property CommonDataBindingClass: TContainedBindCompClass read FCommonDataBindingClass
write SetCommonDataBindingClass;
end;
TExecuteNewDataBinding = class
private
FBindingsList: TCustomBindingsList;
FDesigner: IDesigner;
public
destructor Destroy; override;
constructor Create(ABindingsList: TCustomBindingsList;
ADesigner: IDesigner);
function Execute(ABeforeCreate: TProc;
ACreated: TProc<string, TContainedBindComponent>; AAfterCreate: TProc;
AAllowClass: TFunc<TContainedBindCompClass, Boolean>): Boolean;
end;
TDataBindingListDesignerClass = class of TDataBindingListDesigner;
TNotifyDataBindingListChange = procedure;
//
var
NotifyDataBindingListChange: TNotifyDataBindingListChange = nil;
const
CategoryKinds: array[0..2] of TCategoryKind = (ckCategory, ckNone, ckAll);
procedure ShowBindCompListDesigner(const ADesigner: IDesigner;
ADataBindingList: TCustomBindingsList);
function ShowDataBindingListDesignerClass(const ADesigner: IDesigner;
DesignerClass: TDataBindingListDesignerClass; ADataBindingList: TCustomBindingsList): TDataBindingListDesigner;
var
DesignersList: TList = nil;
implementation
{$R *.dfm}
uses System.Win.Registry, System.TypInfo, Winapi.CommCtrl, StdConst, DsnConst,
DesignEditors, VCLEditors, BindCompDrag, BindCompDsnResStrs, BindCompNewStd,
Vcl.Dialogs;
//type
// DefDataBindingClass = TBindLink;
procedure NotifyDataBindingListChangeImpl;
var
I: Integer;
begin
if DesignersList <> nil then
for I := 0 to DesignersList.Count - 1 do
TDataBindingListDesigner(DesignersList[I]).NotifyDataBindingListChange;
end;
function ShowDataBindingListDesignerClass(const ADesigner: IDesigner;
DesignerClass: TDataBindingListDesignerClass;
ADataBindingList: TCustomBindingsList): TDataBindingListDesigner;
var
I: Integer;
begin
if DesignersList = nil then
DesignersList := TList.Create;
for I := 0 to DesignersList.Count - 1 do
begin
Result := TDataBindingListDesigner(DesignersList[I]);
with Result do
if (Designer = ADesigner) and (FDataBindingList = ADataBindingList) then
begin
Show;
BringToFront;
Exit;
end;
end;
Result := DesignerClass.Create(Application);
with Result do
try
Designer := ADesigner;
FDataBindingList := ADataBindingList;
FDataBindingListClassName := ADataBindingList.ClassName + '1'; // registry key
UpdateView(True);
UpdateCaption;
Show;
except
Free;
end;
end;
procedure ShowBindCompListDesigner(const ADesigner: IDesigner;
ADataBindingList: TCustomBindingsList);
begin
ShowDataBindingListDesignerClass(ADesigner, TDataBindingListDesigner, ADataBindingList);
end;
{ TDataBindingListDesigner }
procedure TDataBindingListDesigner.NotifyDataBindingListChange;
begin
BuildNewDataBindings;
end;
procedure TDataBindingListDesigner.NotifyNewDataBindings(const Classes: array of TContainedBindCompClass);
begin
BuildNewDataBindings;
end;
procedure TDataBindingListDesigner.Activated;
begin
Designer.Activate;
SetSelection;
end;
procedure TDataBindingListDesigner.ItemDeleted(const ADesigner: IDesigner; AItem: TPersistent);
begin
if AItem = FDataBindingList then
begin
FDataBindingList := nil; // Component is already in its destructor; component is gone
Close;
end
else if AItem is TComponent then
FItemIDList.Remove(TComponent(AItem));
end;
procedure TDataBindingListDesigner.DesignerClosed(const ADesigner: IDesigner; AGoingDormant: Boolean);
begin
if Designer = ADesigner then
begin
FDataBindingList := nil;
Close;
end;
end;
procedure TDataBindingListDesigner.FocusDataBinding(DataBinding: TContainedBindComponent);
var
I: Integer;
Category: string;
CategoryKind: TCategoryKind;
LUpdateNeeded: Boolean;
begin
if DataBinding <> nil then
begin
{ Attempt to use current category }
Category := DataBinding.Category;
if Category <> '' then
CategoryKind := ckCategory else
CategoryKind := ckNone;
LUpdateNeeded := False;
if FCategoryKind = ckAll then
begin
// Leave category
end
else if FCategoryKind = ckNone then
begin
if CategoryKind <> ckNone then
LUpdateNeeded := True;
end
else if FCategoryKind = ckCategory then
begin
if (CategoryKind <> ckCategory) or (not SameText(FCategory, Category)) then
LUpdateNeeded := True;
end;
if LUpdateNeeded then
begin
FCategory := Category;
FCategoryKind := CategoryKind;
UpdateView;
end;
// if not ((ListBox1.Items.Count > 0) and ((FCategoryKind = ckAll) and
// (Integer(ListBox1.Items.Objects[ListBox1.Items.Count - 1]) = Ord(ckAll))) or
// ((FCategoryKind = ckNone) and (Integer(ListBox1.Items.Objects[0]) = Ord(ckNone)) or
// ((FCategoryKind = ckCategory) and (AnsiCompareText(FCategory, Category) = 0)))) then
// if (AnsiCompareText(Category, FCategory) <> 0) or (CategoryKind <> FCategoryKind) then
// begin
// FCategory := Category;
// FCategoryKind := CategoryKind;
// UpdateView;
// end;
for I := 0 to ListView1.Items.Count - 1 do
if Integer(ListView1.Items[I].Data) = DataBinding.Index then
begin
LockState;
try
with ListView1.Items[I] do
begin
Focused := True;
MakeVisible(False);
end;
finally
UnLockState;
end;
Exit;
end;
end;
end;
procedure TDataBindingListDesigner.ItemsModified(const ADesigner: IDesigner);
var
LastFocused: TContainedBindComponent;
begin
if (FDataBindingList <> nil) and (FUpdateCount = 0) then
begin
if (ListView1.ItemFocused <> nil) and (FDataBindingList.BindCompCount > Integer(ListView1.ItemFocused.Data)) then
LastFocused := FDataBindingList[Integer(ListView1.ItemFocused.Data){+ ListView1.ItemFocused.Index}] else
LastFocused := nil;
UpdateView;
if Designer <> ADesigner then Exit;
FocusDataBinding(LastFocused);
GetSelection;
end;
UpdateCaption;
end;
function TDataBindingListDesigner.GetItemName(Index, ItemIndex: Integer): string;
begin
{ with TAccessCollection(Collection) do
if GetAttrCount < 1 then
Result := Format('%d - %s',[ItemIndex, Actions.Items[ItemIndex].DisplayName])
else Result := GetItemAttr(Index, ItemIndex);}
end;
function TDataBindingListDesigner.GetRegKey: string;
begin
Result := Designer.GetBaseRegKey + '\' + sIniEditorsName + '\DataBindings Editor';
end;
function TDataBindingListDesigner.IndexOfDataBinding(DataBinding: TContainedBindComponent): Integer;
var
I: Integer;
begin
for I := 0 to ListView1.Items.Count - 1 do
if Integer(ListView1.Items[I].Data) = DataBinding.Index then
begin
Result := I;
Exit;
end;
Result := -1;
end;
procedure TDataBindingListDesigner.GetSelection;
var
I, J: Integer;
DataBinding: TContainedBindComponent;
List: IDesignerSelections;
function IsValidDataBinding(DataBinding: TContainedBindComponent): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to FDataBindingList.BindCompCount - 1 do
if FDataBindingList[I] = DataBinding then
begin
Result := True;
Break;
end;
end;
begin
LockState;
try
ListView1.Selected := nil;
finally
UnlockState;
end;
List := CreateSelectionList;
Designer.GetSelections(List);
if (List.Count = 0) or (List.Count > FDataBindingList.BindCompCount) then Exit;
if List.Count > ListView1.Items.Count then UpdateView;
LockState;
try
for I := FItemIDList.Count - 1 downto 0 do
begin
DataBinding := TContainedBindComponent(FItemIDList[I]);
if (DataBinding <> nil) and IsValidDataBinding(DataBinding) and DataBindingVisible(DataBinding) then
begin
J := IndexOfDataBinding(DataBinding);
if J >= 0 then
ListView1.Items[J].Selected := True;
end
else
FItemIDList.Delete(I);
end;
finally
UnlockState;
end;
end;
procedure TDataBindingListDesigner.LockState;
begin
Inc(FStateLock);
end;
procedure TDataBindingListDesigner.SetSelection;
var
I: Integer;
List: IDesignerSelections;
DataBinding: TContainedBindComponent;
begin
if FSelectionError then Exit;
try
if ListView1.SelCount > 0 then
begin
List := CreateSelectionList;
FItemIDList.Clear;
for I := 0 to ListView1.Items.Count - 1 do
if ListView1.Items[I].Selected then
begin
DataBinding := FDataBindingList[{+ I}Integer(ListView1.Items[I].Data)];
List.Add(DataBinding);
FItemIDList.Add(DataBinding);
end;
Designer.SetSelections(List);
end
else
Designer.SelectComponent(FDataBindingList);
except
FSelectionError := True;
Application.HandleException(ExceptObject);
Close;
end;
end;
procedure TDataBindingListDesigner.UnlockState;
begin
Dec(FStateLock);
end;
function TDataBindingListDesigner.DataBindingVisible(DataBinding: TContainedBindComponent): Boolean;
begin
Result := (FCategoryKind = ckAll) or (DataBinding.Category = '') and
(FCategoryKind in [ckNone, ckAll]) or (FCategoryKind = ckCategory) and
(AnsiCompareText(DataBinding.Category, FCategory) = 0);
end;
procedure TDataBindingListDesigner.UpdateView(AUpdateColumns: Boolean);
procedure UpdateSizes;
{ var
Kind: Integer;}
var
LIndex: Integer;
DefClassName: string;
DefClass: TPersistentClass;
DefClass2: TContainedBindCompClass;
begin
with TRegIniFile.Create(GetRegKey) do
try
Width := ReadInteger(FDataBindingListClassName, 'Width', Width);
Height := ReadInteger(FDataBindingListClassName, 'Height', Height);
DescriptionsVisible := ReadBool(FDataBindingListClassName, 'Descriptions', True);
for LIndex := 0 to ListView1.Columns.Count - 1 do
with ListView1.Columns.Items[LIndex] do
Width := ReadInteger(FDataBindingListClassName, 'Width'+IntToStr(LIndex), Width);
{ Kind := ReadInteger(FActionListClassName, 'CategoryKind', Ord(ckNone));
if not (Kind in [Low(CategoryKinds)..High(CategoryKinds)]) then
Kind := Ord(ckNone);
FCategoryKind := CategoryKinds[Kind];
FCategory := ReadString(FActionListClassName, 'Category', '');}
CategoryPanel.Width := ReadInteger(FDataBindingListClassName, 'CategoryWidth', CategoryPanel.Width);
Splitter1.Top := Toolbar1.Top + Toolbar1.Height;
Toolbar1.Visible := ReadBool(FDataBindingListClassName, 'Toolbar', True);
Splitter1.Visible := Toolbar1.Visible;
Toolbar1.HandleNeeded; //! Setting action class touches handle
LargeButtons := ReadBool(FDataBindingListClassName, 'LargeButtons', False);
{ Load default data binding class }
DefClassName := ReadString(FDataBindingListClassName, 'DataBindingClass', '');
if DefClassName = '' then
DefClass := nil
else
begin
DefClass := GetClass(DefClassName);
if (DefClass <> nil) and not DefClass.InheritsFrom(TContainedBindComponent) then
DefClass := nil;
end;
if DefClass <> nil then
DefClass2 := TContainedBindCompClass(DefClass) else
DefClass2 := nil;
CommonDataBindingClass := DefClass2;
{+
if ReadBool(FActionListClassName, 'StandardActions', False) then
ToolButton1.Action := NewStdAction else
ToolButton1.Action := NewAction;
!}
finally
Free;
end;
end;
procedure UpdateColumns;
begin
UpdateSizes;
end;
procedure FetchItems(List: TStrings);
var
I: Integer;
DataBinding: TContainedBindComponent;
begin
if FDataBindingList <> nil then
for I := 0 to FDataBindingList.BindCompCount - 1 do
begin
DataBinding := FDataBindingList[I];
if DataBindingVisible(DataBinding) then
List.AddObject(DataBinding.Name, Pointer(I));
end;
end;
function GetDataBindingDesigner(ADataBinding: TContainedBindComponent): IBindCompDesigner;
begin
Result := Data.Bind.Components.GetBindCompDesigner(TContainedBindCompClass(ADataBinding.ClassType));
end;
function BindingDescription(ADataBinding: TContainedBindComponent; ADesigner: IBindCompDesigner): string;
begin
if ADesigner <> nil then
Result := ADesigner.GetDescription(ADataBinding)
else
Result := '';
end;
function ItemsEqual(ListItems: TListItems; Items: TStrings): Boolean;
var
I: Integer;
// Tmp: TContainedBindComponent;
// ImageIndex: Integer;
begin
Result := False;
if ListItems.Count <> Items.Count then Exit;
for I := 0 to ListItems.Count - 1 do
begin
if ListItems[I].Caption = Items[I] then
begin
// Tmp := FDataBindingList[Integer(Items.Objects[I])];
// if (Tmp is TContainedBindComponent) then
// ImageIndex := TContainedBindComponent(Tmp).ImageIndex else
// ImageIndex := -1;
// if ListItems[I].ImageIndex <> ImageIndex then Exit;
end
else
Exit;
end;
Result := True;
end;
var
TmpItems: TStringList;
LItem: TListItem;
LCaption: string;
LDesigner: IBindCompDesigner;
I, J: Integer;
Categories: TStringList;
BlankCategoryCount: Integer;
DataBinding: TContainedBindComponent;
begin
if FDataBindingList = nil then Exit;
LockState;
try
{ Update actions }
Categories := TStringList.Create;
try
Categories.Sorted := True;
BlankCategoryCount := 0;
if FDataBindingList <> nil then
for I := 0 to FDataBindingList.BindCompCount - 1 do
if FDataBindingList[I].Category <> '' then
Categories.Add(FDataBindingList[I].Category)
else if BlankCategoryCount = 0 then
Inc(BlankCategoryCount);
{ Update categories }
ListBox1.Items.BeginUpdate;
try
ListBox1.Items.Clear;
ListBox1.Items.Assign(Categories);
// Always include all
ListBox1.Items.InsertObject(0, SDataBindingCategoryAll, TObject(Ord(ckAll)));
if Categories.Count + BlankCategoryCount = 0 then
begin
// No components
end
else if BlankCategoryCount <> 0 then
begin
// Some blank categories
//if Categories.Count > 0 then
// ListBox1.Items.InsertObject(0, SDataBindingCategoryAll, TObject(Ord(ckAll)));
ListBox1.Items.AddObject(SDataBindingCategoryNone, TObject(Ord(ckNone)));
end
else if Categories.Count > 1 then
begin
// multiple categories
// ListBox1.Items.InsertObject(0, SDataBindingCategoryAll, TObject(Ord(ckAll)));
end;
if BlankCategoryCount = 0 then
if FCategoryKind = ckNone then
begin
FCategoryKind := ckAll;
FCategory := '';
end;
{ Select category }
if FCategoryKind = ckCategory then
begin
I := ListBox1.Items.IndexOf(FCategory);
if I < 0 then
begin
I := 0;
FCategoryKind := ckAll;
FCategory := '';
end
else
FCategory := ListBox1.Items[I];
end
else
I := ListBox1.Items.IndexOfObject(TObject(Ord(FCategoryKind)));
if I < 0 then
if ListBox1.Count > 0 then
I := 0;
ListBox1.ItemIndex := I;
finally
ListBox1.Items.EndUpdate;
end;
{ Update actions }
TmpItems := TStringList.Create;
FetchItems(TmpItems);
//if (TmpItems.Count = 0) or not ItemsEqual(ListView1.Items, TmpItems) then
try
ListView1.Items.BeginUpdate;
try
if AUpdateColumns then
UpdateColumns;
ListView1.Items.Clear;
if FDataBindingList <> nil then
for I := 0 to FDataBindingList.BindCompCount - 1 do
begin
DataBinding := FDataBindingList[I];
LDesigner := GetDataBindingDesigner(DataBinding);
if DataBindingVisible(DataBinding) then
begin
LItem := ListView1.Items.Add;
with LItem do
begin
Caption := DataBinding.Name;
Data := Pointer(I);
for J := 1 to ListView1.Columns.Count - 1 do
begin
case J of
1: LCaption := BindingDescription(DataBinding, LDesigner)
else
LCaption := '';
end;
LItem.SubItems.Add(LCaption);
end;
end;
end;
end;
finally
ListView1.Items.EndUpdate;
end;
finally
TmpItems.Free;
end;
finally
Categories.Free;
end;
finally
UnlockState;
end;
end;
procedure TDataBindingListDesigner.Clear;
begin
if FDataBindingList <> nil then
while FDataBindingList.BindCompCount > 0 do
FDataBindingList[0].Free;
FItemIDList.Clear;
end;
procedure TDataBindingListDesigner.DoNewDataBinding(const Category: string; DataBinding: TContainedBindComponent);
begin
try
DataBinding.BindingsList := FDataBindingList;
DataBinding.Name := UniqueName(DataBinding);
with ListView1.Items.Add do
begin
Data := Pointer(DataBinding.Index);
Selected := True;
Focused := True;
//! MakeVisible(False);
{+
Selected := Items.Add;
ItemFocused := Selected;
ItemFocused.MakeVisible(False);
!}
end;
{ Setting the Category causes the Designer to be modified }
BeginUpdate;
try
DataBinding.Category := Category;
finally
EndUpdate;
end;
except
DataBinding.Free;
raise;
end;
SetSelection;
Designer.Modified;
end;
type
TInfo = record
FClass: TContainedBindCompClass;
FFound: Boolean;
FCategory: string;
end;
PInfo = ^TInfo;
procedure TDataBindingListDesigner.CategoryOfClassEnumProc(const Category: string; BindCompClass: TContainedBindCompClass;
Info: TEnumBindCompProcInfo);
begin
if BindCompClass = PInfo(Info).FClass then
begin
PInfo(Info).FFound := True;
PInfo(Info).FCategory := Category;
end;
end;
function TDataBindingListDesigner.CategoryOfClass(AClass: TContainedBindCompClass): string;
var
LInfo: TInfo;
begin
LInfo.FClass := AClass;
Data.Bind.Components.EnumRegisteredBindComponents(CategoryOfClassEnumProc, TEnumBindCompProcInfo(@LInfo));
if LInfo.FFound then
Result := LInfo.FCategory
else
Result := '';
end;
procedure TDataBindingListDesigner.DeleteClick(Sender: TObject);
begin
Remove;
end;
procedure TDataBindingListDesigner.ListView1Click(Sender: TObject);
begin
// SetSelection;
end;
procedure TDataBindingListDesigner.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
Designer.ModalEdit(#0, Self);
end;
procedure TDataBindingListDesigner.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_PROCESSKEY then
Designer.ModalEdit(#0, Self);
end;
procedure TDataBindingListDesigner.FormClose(Sender: TObject;
var Action: TCloseAction);
var
I: Integer;
begin
if FDataBindingList <> nil then
Designer.SelectComponent(FDataBindingList);
with TRegIniFile.Create(GetRegKey) do
try
EraseSection(FDataBindingListClassName);
WriteInteger(FDataBindingListClassName, 'Width', Width);
WriteInteger(FDataBindingListClassName, 'Height', Height);
for I := 0 to ListView1.Columns.Count - 1 do
with ListView1.Columns.Items[I] do
WriteInteger(FDataBindingListClassName, 'Width'+IntToStr(I), Width);
WriteBool(FDataBindingListClassName, 'Descriptions', DescriptionsVisible);
WriteBool(FDataBindingListClassName, 'Toolbar', Toolbar1.Visible);
WriteInteger(FDataBindingListClassName, 'CategoryWidth', CategoryPanel.Width);
WriteBool(FDataBindingListClassName, 'LargeButtons', LargeButtons);
if CommonDataBindingClass <> nil then
WriteString(FDataBindingListClassName, 'DataBindingClass', CommonDataBindingClass.ClassName);
finally
Free;
end;
Action := caFree;
LockState;
end;
function TDataBindingListDesigner.GetDataBindingIndex(ListIndex: Integer): Integer;
begin
Result := FDataBindingList[Integer(ListView1.Items[ListIndex].Data)].Index;
end;
procedure TDataBindingListDesigner.MoveUpClick(Sender: TObject);
var
I, InsPos: Integer;
begin
if (ListView1.SelCount = 0) or
(ListView1.SelCount = FDataBindingList.BindCompCount) then Exit;
InsPos := 0;
while not ListView1.Items[InsPos].Selected do
Inc(InsPos);
if InsPos > 0 then Dec(InsPos);
for I := 0 to ListView1.Items.Count - 1 do
if ListView1.Items[I].Selected then
begin
FDataBindingList[Integer(ListView1.Items[I].Data)].Index := GetDataBindingIndex(InsPos);
Inc(InsPos);
end;
GetSelection;
Designer.Modified;
end;
procedure TDataBindingListDesigner.MoveDownClick(Sender: TObject);
var
I, InsPos: Integer;
begin
if (ListView1.SelCount = 0) or
(ListView1.SelCount = FDataBindingList.BindCompCount) then Exit;
InsPos := ListView1.Items.Count - 1;
while not ListView1.Items[InsPos].Selected do
Dec(InsPos);
if InsPos < ListView1.Items.Count - 1 then Inc(InsPos);
for I := ListView1.Items.Count - 1 downto 0 do
if ListView1.Items[I].Selected then
begin
FDataBindingList[Integer(ListView1.Items[I].Data)].Index := GetDataBindingIndex(InsPos);
Dec(InsPos);
end;
GetSelection;
Designer.Modified;
end;
procedure TDataBindingListDesigner.ListView1DragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
var
Item: TListItem;
begin
Item := ListView1.GetItemAt(X, Y);
Accept := (Item <> nil) {+ and (Source = ListView1)} and
(not Item.Selected);
end;
procedure TDataBindingListDesigner.ListView1DragDrop(Sender, Source: TObject; X,
Y: Integer);
var
Item: TListItem;
I, J, InsPos: Integer;
L: TList;
begin
Item := ListView1.GetItemAt(X, Y);
if Item <> nil then
InsPos := Item.Index
else Exit;
BeginUpdate;
try
L := TList.Create;
try
for I := 0 to ListView1.Items.Count - 1 do
if ListView1.Items[I].Selected then
L.Add(FDataBindingList[{+ I}Integer(ListView1.Items[I].Data)]);
for I := 0 to L.Count - 1 do
with TContainedBindComponent(L[I]) do
begin
J := Index;
Index := InsPos;
if (J > InsPos) and (InsPos < FDataBindingList.BindCompCount) then
Inc(InsPos);
end;
finally
L.Free;
end;
finally
EndUpdate;
end;
//! GetSelection;
SetSelection;
Designer.Modified;
end;
procedure TDataBindingListDesigner.FormCreate(Sender: TObject);
begin
FItemIdList := TList.Create;
FCategoryKind := ckAll;
DesignersList.Add(Self);
BuildNewDataBindings;
ToolBar1.HandleNeeded; //! Setting action class touches handle
CommonDataBindingClass := nil; //DefDataBindingClass;
end;
procedure TDataBindingListDesigner.FormDestroy(Sender: TObject);
begin
if DesignersList <> nil then
DesignersList.Remove(Self);
FItemIdList.Free;
end;
procedure TDataBindingListDesigner.FormResize(Sender: TObject);
begin
{ if not ListView1.ShowColumnHeaders then
ListView1.Column[0].Width := ListView1.ClientWidth;}
end;
procedure TDataBindingListDesigner.ListView1Change(Sender: TObject;
Item: TListItem; Change: TItemChange);
var
Msg: TMsg;
begin
if (FUpdateCount = 0) and (FStateLock = 0) and (Change = ctState) then
if not PeekMessage(Msg, Handle, AM_DeferUpdate, AM_DeferUpdate, PM_NOREMOVE) then
PostMessage(Handle, AM_DeferUpdate, 0, 0);
end;
procedure TDataBindingListDesigner.AMDeferUpdate(var Msg);
begin
if (FUpdateCount = 0) and (FStateLock = 0) then
SetSelection
else
PostMessage(Handle, AM_DeferUpdate, 0, 0);
end;
procedure TDataBindingListDesigner.SelectAllItemClick(Sender: TObject);
begin
SelectAll();
end;
function TDataBindingListDesigner.UniqueName(Component: TComponent): string;
begin
Result := Designer.UniqueName((Component as TContainedBindComponent).Category +
Component.ClassName);
end;
function TDataBindingListDesigner.GetEditState: TEditState;
function ActionsSelected: Boolean;
var
I: Integer;
begin
Result := True;
with ListView1 do
for I := 0 to Items.Count - 1 do
if Items[I].Selected then Exit;
Result := False;
end;
begin
Result := [];
if ClipboardComponents then Result := [esCanPaste];
if ActionsSelected then Result := Result + [esCanCopy, esCanCut, esCanDelete];
end;
function TDataBindingListDesigner.EditAction(Action: TEditAction): Boolean;
begin
Result := True;
case Action of
eaCut: Cut;
eaCopy: Copy;
eaPaste: Paste;
eaDelete: Remove;
eaSelectAll: SelectAll();
else
Result := False;
end;
end;
procedure TDataBindingListDesigner.SelectAll(DoUpdate: Boolean);
var
I: Integer;
begin
LockState;
ListView1.Items.BeginUpdate;
try
for I := 0 to Listview1.Items.Count-1 do
Listview1.Items[I].Selected := True;
finally
ListView1.Items.EndUpdate;
UnlockState;
if DoUpdate then SetSelection;
end;
end;
procedure TDataBindingListDesigner.SelectNone(DoUpdate: Boolean);
begin
ListView1.Selected := nil;
if DoUpdate then SetSelection;
end;
procedure TDataBindingListDesigner.Remove;
var
NewFocused: Integer;
I: Integer;
KillActions: TList;
LName: string;
begin
if assigned(ListView1.ItemFocused) and
GetComponentEditor(FDataBindingList[Integer(ListView1.ItemFocused.Data)], Designer).IsInInlined then { for Frames }
raise Exception.CreateRes(@SCantDeleteAncestor);
BeginUpdate;
LockState;
try
if ListView1.SelCount = FDataBindingList.BindCompCount then
begin
SelectNone(False);
SetSelection;
Clear;
end
else if ListView1.SelCount > 0 then
begin
KillActions := nil;
try
{ Store deleted items for later destruction }
KillActions := TList.Create;
for I := ListView1.Items.Count - 1 downto 0 do
if ListView1.Items[I].Selected then
begin
LName := TComponent(FDataBindingList[Integer(ListView1.Items[I].Data)]).Name;
if (idYes <> MessageDlg(
Format(sConfirmDelete, [LName]),
mtConfirmation, mbYesNoCancel, 0)) then
Exit;
KillActions.Add(TObject(ListView1.Items[I].Data));
end;
{ Find new focused item from current focused item }
NewFocused := -1;
if ListView1.ItemFocused <> nil then
begin
for I := ListView1.ItemFocused.Index + 1 to ListView1.Items.Count - 1 do
if not ListView1.Items[I].Selected then
begin
NewFocused := I;
Break;
end;
if NewFocused = -1 then
for I := ListView1.ItemFocused.Index downto 0 do
if not ListView1.Items[I].Selected then
begin
NewFocused := I;
Break;
end;
end;
SelectNone(False);
if NewFocused >= 0 then
ListView1.Items[NewFocused].Selected := True;
SetSelection;
{ Delete items }
for I := 0 to KillActions.Count - 1 do
if (csAncestor in FDataBindingList[Integer(KillActions[I])].ComponentState) then
raise Exception.CreateRes(@SCantDeleteAncestor);
for I := 0 to KillActions.Count - 1 do
FDataBindingList[Integer(KillActions[I])].Free;
finally
KillActions.Free;
end;
end;
finally
UnLockState;
EndUpdate;
end;
UpdateView;
Designer.Modified;
{ Make sure we have focus }
for I := 0 to ListView1.Items.Count - 1 do
if ListView1.Items[I].Selected then
begin
FocusDataBinding(FDataBindingList[Integer(ListView1.Items[I].Data)]);
Break;
end;
end;
procedure TDataBindingListDesigner.Cut;
begin
Copy;
Remove;
end;
procedure TDataBindingListDesigner.Copy;
var
I: Integer;
ComponentList: IDesignerSelections;
begin
ComponentList := CreateSelectionList;
with ListView1 do
for I := 0 to Items.Count - 1 do
if Items[I].Selected then
ComponentList.Add(FDataBindingList[{+ }Integer(Items[I].Data)]);
CopyComponents(FDataBindingList.Owner, ComponentList);
end;
procedure TDataBindingListDesigner.Paste;
var
I, C: Integer;
ComponentList: TList;
Action: TContainedBindComponent;
Item: TListItem;
begin
ComponentList := TList.Create;
try
C := -1;
with ListView1 do
if (Selected <> nil) and (Selected.Index <> -1) and (Items.Count > 0) then
C := Selected.Index;
try
try
{ Try to convert TMenuItem, TControl, and TWinControl to TAction }
LoadFromClipboard(FDataBindingList.Owner, FDataBindingList, ComponentList);
finally
end;
finally
UpdateView
end;
try
ListView1.Selected := nil;
Item := nil;
for I := ComponentList.Count - 1 downto 0 do
if TObject(ComponentList[I]) is TBasicAction then
begin
Action := TContainedBindComponent(ComponentList[I]);
if C <> -1 then Action.Index := C;
Item := ListView1.Items[C];
if Item <> nil then Item.Selected := True;
end;
if Item <> nil then
Item.Focused := True;
finally
GetSelection;
Designer.Modified;
end;
finally
ComponentList.Free;
end;
end;
procedure TDataBindingListDesigner.UpdateCaption;
var
NewCaption: string;
begin
if (FDataBindingList <> nil) and (FDataBindingList.Owner <> nil) then
NewCaption := Format(SDataBindingListEditorCaption, [FDataBindingList.Owner.Name, DotSep,
FDataBindingList.Name]);
if Caption <> NewCaption then Caption := NewCaption;
end;
procedure TDataBindingListDesigner.PasteItemClick(Sender: TObject);
begin
Paste;
end;
procedure TDataBindingListDesigner.CopyItemClick(Sender: TObject);
begin
Copy;
end;
procedure TDataBindingListDesigner.CutItemClick(Sender: TObject);
begin
Cut;
end;
function TDataBindingListDesigner.GetDescriptionsVisible: Boolean;
begin
Result := DescriptionsAction.Checked;
end;
procedure TDataBindingListDesigner.SetDescriptionsVisible(Value: Boolean);
begin
DescriptionsAction.Checked := Value;
end;
procedure TDataBindingListDesigner.LoadFromClipboard(AOwner, AParent: TComponent;
Components: TList);
var
S: TStream;
begin
S := GetClipboardStream;
try
ReadStream(S, AOwner, AParent, Components);
finally
S.Free;
end;
end;
procedure TDataBindingListDesigner.ReadStream(Stream: TStream; AOwner,
AParent: TComponent; Components: TList);
var
M: TMemoryStream;
R: TReader;
I: Integer;
W: TWriter;
begin
M := TMemoryStream.Create;
try
R := TReader.Create(Stream, 1024);
try
R.OnSetName := ReaderSetName;
FFixups := TList.Create;
try
R.ReadComponents(AOwner, AParent, ComponentRead);
W := TWriter.Create(M, 1024);
try
W.Root := AOwner;
for I := 0 to FFixups.Count - 1 do
if TComponent(FFixups[I]) is TContainedBindComponent then
begin
W.WriteSignature;
W.WriteComponent(TComponent(FFixups[I]));
end;
W.WriteListEnd;
finally
W.Free;
end;
finally
for I := 0 to FFixups.Count - 1 do TObject(FFixups[I]).Free;
FFixups.Free;
end;
finally
R.Free;
end;
M.Position := 0;
R := TReader.Create(M, 1024);
try
R.OnSetName := ReaderSetName2;
FFixups := Components;
R.ReadComponents(AOwner, AParent, ComponentRead);
finally
R.Free;
end;
finally
M.Free;
end;
end;
procedure TDataBindingListDesigner.ReaderSetName(Reader: TReader; Component: TComponent;
var Name: string);
begin
Name := '';
end;
procedure TDataBindingListDesigner.ReaderSetName2(Reader: TReader; Component: TComponent;
var Name: string);
begin
Name := UniqueName(Component);
end;
procedure TDataBindingListDesigner.ComponentRead(Component: TComponent);
//var
// DataBinding: TContainedBindComponent;
begin
if Component is TContainedBindComponent then
begin
FFixups.Add(Component);
end
else begin
// DataBinding := {+ Default}DefDataBindingClass.Create(nil);
// try
// try
// DataBinding.Assign(Component);
// finally
////! Component.Free;
// end;
// except
// DataBinding.Free;
// raise;// Exception.Create(SMenuPasteError);
// end;
// FFixups.Add(DataBinding);
// FFixups.Add(Component);
end;
end;
procedure TDataBindingListDesigner.SelectedUpdate(Sender: TObject);
begin
(Sender as TCustomAction).Enabled := ListView1.SelCount > 0;
end;
procedure TDataBindingListDesigner.SelectAllActionUpdate(Sender: TObject);
begin
(Sender as TCustomAction).Enabled := ListView1.Items.Count > 0;
end;
procedure TDataBindingListDesigner.ListBox1Click(Sender: TObject);
begin
if ListBox1.ItemIndex >= 0 then
begin
FCategoryKind := CategoryKinds[Integer(ListBox1.Items.Objects[ListBox1.ItemIndex])];
if FCategoryKind = ckCategory then
FCategory := ListBox1.Items[ListBox1.ItemIndex] else
FCategory := '';
end
else
begin
FCategoryKind := ckAll;
FCategory := '';
end;
UpdateView;
ListView1Resize(nil);
end;
procedure TDataBindingListDesigner.BuildNewDataBindings;
begin
end;
procedure TDataBindingListDesigner.NewBindCompDialogExecute(Sender: TObject);
var
// I: Integer;
// LDataBindingClass: TContainedBindCompClass;
LDataBinding: TContainedBindComponent;
// LCategory: string;
// LClass: TPersistentClass;
begin
if GetComponentEditor(FDataBindingList, Designer).IsInInlined then { for Frames }
raise Exception.CreateRes(@SCantAddToAncestor);
with TExecuteNewDataBinding.Create(FDataBindingList, Designer) do
begin
Execute(
procedure
begin
SelectNone(False)
end,
procedure(ACategory: string; ADataBinding: TContainedBindComponent)
begin
LDataBinding := ADataBinding;
CommonDataBindingClass := TContainedBindCompClass(LDataBinding.ClassType);
DoNewDataBinding(ACategory, LDataBinding);
end,
procedure
begin
FocusDataBinding(LDataBinding)
end,
function(AClass: TContainedBindCompClass): Boolean
begin
// Allow class
Result := True;
end)
end;
end;
procedure TDataBindingListDesigner.BeginUpdate;
begin
Inc(FUpdateCount);
end;
procedure TDataBindingListDesigner.EndUpdate;
begin
Dec(FUpdateCount);
end;
procedure TDataBindingListDesigner.SelectionChanged(const Designer: IDesigner;
const ASelection: IDesignerSelections);
var
I: Integer;
S: Boolean;
{ LastItem: TListItem;
SelChanged: Boolean;}
function InSelection(Component: TComponent): Boolean;
var
I: Integer;
begin
Result := True;
if ASelection <> nil then
with ASelection do
for I := 0 to Count - 1 do
if Component = Items[I] then Exit;
Result := False;
end;
begin
exit;
if (FDataBindingList = nil) or (FUpdateCount > 0) or (FStateLock > 0) then Exit;
if (GetCaptureControl <> nil) and (GetParentForm(GetCaptureControl) = Self) then Exit;
BeginUpdate;
LockState;
try
with ListView1 do
begin
Items.BeginUpdate;
try
for I := 0 to Items.Count - 1 do
begin
if I >= FDataBindingList.BindCompCount - 1 then Break;
S := InSelection(FDataBindingList[{+ I}Integer(Items[I].Data)]);
if Items[I].Selected <> S then
begin
Items[I].Selected := S;
end;
end;
finally
Items.EndUpdate;
end;
end;
finally
UnLockState;
EndUpdate;
end;
end;
procedure TDataBindingListDesigner.ListView1KeyPress(Sender: TObject;
var Key: Char);
begin
if CharInSet(Key, ['!'..'~']) then
begin
Designer.ModalEdit(Key, Self);
Key := #0;
end;
end;
procedure TDataBindingListDesigner.ListView1KeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_PROCESSKEY then
Designer.ModalEdit(#0, Self);
end;
procedure TDataBindingListDesigner.NewDataBindingsPopupPopup(Sender: TObject);
var
I: Integer;
begin
{ Sync popup menu's default item to that of the button }
with (Sender as TPopupMenu) do
for I := 0 to Items.Count - 1 do
Items[I].Default := Items[I].Action = ToolButton1.Action;
end;
procedure TDataBindingListDesigner.DescriptionsActionExecute(Sender: TObject);
begin
with DescriptionsAction do
begin
Checked := not Checked;
Panel3.Visible := Checked;
Panel4.Visible := Checked;
end;
end;
procedure TDataBindingListDesigner.ListView1StartDrag(Sender: TObject;
var DragObject: TDragObject);
begin
FDragObject := TDataBindingDragObject.Create(ListView1);
DragObject := FDragObject;
end;
procedure TDataBindingListDesigner.ListView1EndDrag(Sender, Target: TObject; X,
Y: Integer);
begin
FDragObject.Free;
FDragObject := nil;
end;
procedure TDataBindingListDesigner.SetCommonDataBindingClass(Value: TContainedBindCompClass);
var
S: string;
begin
//if Value = nil then Value := DefDataBindingClass;
if FCommonDataBindingClass <> Value then
begin
FCommonDataBindingClass := Value;
if FCommonDataBindingClass <> nil then
begin
S := Value.ClassName;
if (Length(S) > 1) and (S[1] = 'T') then
System.Delete(S, 1, 1);
NewCommonDataBinding.Caption := Format(SNewDataBinding, [S]);
NewCommonDataBinding.Hint := Format(SNewDataBindingHint, [S, S]);
end;
end;
NewCommonDataBinding.Visible := FCommonDataBindingClass <> nil; //DefDataBindingClass;
end;
procedure TDataBindingListDesigner.ListView1DblClick(Sender: TObject);
var
Editor: IComponentEditor;
DataBinding: TContainedBindComponent;
begin
{ Perform default component editor action }
if ListView1.ItemFocused <> nil then
begin
DataBinding := FDataBindingList[Integer(ListView1.ItemFocused.Data)];
Editor := GetComponentEditor(DataBinding, Designer);
if Editor <> nil then Editor.Edit;
end;
end;
procedure TDataBindingListDesigner.NewCommonDataBindingExecute(Sender: TObject);
var
DataBinding: TContainedBindComponent;
LCategory: string;
begin
if GetComponentEditor(FDataBindingList, Designer).IsInInlined then { for frames }
raise Exception.CreateRes(@SCantAddToAncestor);
SelectNone(False);
LCategory := FCategory;
if FCategoryKind = TCategoryKind.ckAll then
LCategory := CategoryOfClass(CommonDataBindingClass);
DataBinding := CreateBindComponent(Designer.GetRoot, CommonDataBindingClass) as TContainedBindComponent;
DoNewDataBinding(LCategory, DataBinding);
FocusDataBinding(DataBinding);//!
end;
procedure TDataBindingListDesigner.MoveUpUpdate(Sender: TObject);
begin
inherited;
(Sender as TCustomAction).Enabled := (ListView1.SelCount > 0) and (ListView1.Items.Count > 1) {and
(ListView1.Selected.Index > 0)};
end;
procedure TDataBindingListDesigner.MoveDownUpdate(Sender: TObject);
begin
inherited;
(Sender as TCustomAction).Enabled := (ListView1.SelCount > 0) and (ListView1.Items.Count > 1){and
(ListView1.Selected.Index < ListView1.Items.Count - 1)};
end;
procedure TDataBindingListDesigner.ListView1Resize(Sender: TObject);
begin
ListView1.Columns.BeginUpdate;
try
// ListView1.Columns[0].Width := ListView1.ClientWidth - 1;
finally
ListView1.Columns.EndUpdate;
end;
end;
{ TNewDataBindingDialog }
constructor TExecuteNewDataBinding.Create(ABindingsList:
TCustomBindingsList; ADesigner: IDesigner);
begin
FBindingsList := ABindingsList;
FDesigner := ADesigner;
end;
destructor TExecuteNewDataBinding.Destroy;
begin
inherited;
end;
function TExecuteNewDataBinding.Execute(ABeforeCreate: TProc;
ACreated: TProc<string, TContainedBindComponent>; AAfterCreate: TProc;
AAllowClass: TFunc<TContainedBindCompClass, Boolean> ): Boolean;
var
I: Integer;
LDataBindingClass: TContainedBindCompClass;
// LClass: TPersistentClass;
LCategory: string;
LBindComp: TContainedBindComponent;
begin
if GetComponentEditor(FBindingsList, FDesigner).IsInInlined then { for Frames }
raise Exception.CreateRes(@SCantAddToAncestor);
with TNewStdDataBindingDlg.Create(Application) do
try
AllowClass := AAllowClass;
DesignerIntf := Self.FDesigner;
Result := ShowModal = mrOk;
if Result then
begin
ABeforeCreate;
//SelectNone(False);
for I := 0 to ActionTree.Items.Count - 1 do
if ActionTree.Items[I].Selected and Assigned(ActionTree.Items[I].Data) then
begin
LDataBindingClass := TContainedBindCompClass(ActionTree.Items[I].Data);
if LDataBindingClass <> nil then
begin
LCategory := ActionTree.Items[I].Parent.Text{ SubItems[0]};
if AnsiCompareText(LCategory, SDataBindingCategoryNone) = 0 then LCategory := '';
LBindComp := CreateBindComponent(Self.FDesigner.GetRoot,
LDataBindingClass) as TContainedBindComponent;
ACreated(LCategory, LBindComp);
end;
end;
AAfterCreate;
end;
finally
Free;
end;
end;
initialization
BindCompEdit.NotifyDataBindingListChange := NotifyDataBindingListChangeImpl;
finalization
BindCompEdit.NotifyDataBindingListChange := nil;
FreeAndNil(DesignersList);
end.
|
unit TestRollbar;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, Rollbar;
type
// Test methods for class IRollbarMessage
TestIRollbarMessage = class(TTestCase)
strict private
FMsg: IRollbarMessage;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestUnixDateTimeRoundTrip;
procedure TestSimpleMessage;
procedure TestComplexMessage;
procedure TestMessageWithClient;
procedure TestMessageWithRequest;
end;
implementation
uses
JSONSerialize,
System.DateUtils,
{$IF CompilerVersion > 26} //Delphi XE6 or later.
System.JSON,
{$ELSE}
Data.DBXJSON,
{$ENDIF}
System.SysUtils;
function JsonProcessDelimiters(const Value: string): string;
begin
{$IF CompilerVersion > 26} //Delphi XE6 or later.
Result := StringReplace(Value, '/', '\/', [rfReplaceAll]);
{$ELSE}
Result := Value;
{$ENDIF}
end;
procedure TestIRollbarMessage.SetUp;
begin
FMsg := TRollbar.Message;
end;
procedure TestIRollbarMessage.TearDown;
begin
FMsg := nil;
end;
procedure TestIRollbarMessage.TestComplexMessage;
const
EXPECTED =
'{"data":{' +
'"body":{' +
'"message":{' +
'"body":"Request over threshold of 10 seconds"}},' +
'"environment":"production",' +
'"level":"error",' +
'"timestamp":1369188822,' +
'"code_version":"3da541559918a808c2402bba5012f6c60b27661c",' +
'"language":"python",' +
'"framework":"pyramid",' +
'"context":"project#index",' +
'"person":{' +
'"id":"12345",' +
'"username":"brianr",' +
'"email":"brian@rollbar.com"},' +
'"server":{' +
'"host":"web4",' +
'"root":"/Users/brian/www/mox",' +
'"branch":"master",' +
'"code_version":"b6437f45b7bbbb15f5eddc2eace4c71a8625da8c"},' +
'"fingerprint":"50a5ef9dbcf9d0e0af2d4e25338da0d430f20e52",' +
'"title":"NameError when setting last project in views/project.py",' +
'"uuid":"d4c7acef55bf4c9ea95e4fe9428a8287",' +
'"notifier":{' +
'"name":"pyrollbar",' +
'"version":"0.5.5"}},' +
'"access_token":"aaaabbbbccccddddeeeeffff00001111"}';
begin
FMsg.AccessToken := 'aaaabbbbccccddddeeeeffff00001111';
FMsg.Environment := 'production';
FMsg.Body := 'Request over threshold of 10 seconds';
FMsg.Level := 'error';
FMsg.Timestamp := UnixToDateTime(1369188822);
FMsg.CodeVersion := '3da541559918a808c2402bba5012f6c60b27661c';
FMsg.Language := 'python';
FMsg.Framework := 'pyramid';
FMsg.Context := 'project#index';
FMsg.PersonId := '12345';
FMsg.PersonUsername := 'brianr';
FMsg.PersonEmail := 'brian@rollbar.com';
FMsg.ServerHost := 'web4';
FMsg.ServerRoot := '/Users/brian/www/mox';
FMsg.ServerBranch := 'master';
FMsg.ServerCodeVersion := 'b6437f45b7bbbb15f5eddc2eace4c71a8625da8c';
FMsg.Fingerprint := '50a5ef9dbcf9d0e0af2d4e25338da0d430f20e52';
FMsg.Title := 'NameError when setting last project in views/project.py';
FMsg.UUID := 'd4c7acef55bf4c9ea95e4fe9428a8287';
FMsg.NotifierName := 'pyrollbar';
FMsg.NotifierVersion := '0.5.5';
CheckEquals(JsonProcessDelimiters(EXPECTED), FMsg.ToJSON);
end;
procedure TestIRollbarMessage.TestMessageWithClient;
const
EXPECTED =
'{"data":{' +
'"client":{' +
'"javascript":{' +
'"browser":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3)",' +
'"code_version":"b6437f45b7bbbb15f5eddc2eace4c71a8625da8c",' +
'"source_map_enabled":false,' +
'"guess_uncaught_frames":false}}}}';
var
js: TJSONObject;
begin
js := TJSONObject.Create;
js.AddPair('browser', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3)');
js.AddPair('code_version', 'b6437f45b7bbbb15f5eddc2eace4c71a8625da8c');
js.AddPair('source_map_enabled', TJSONFalse.Create);
js.AddPair('guess_uncaught_frames', TJSONFalse.Create);
FMsg.Client.AddPair('javascript', js);
CheckEquals(JsonProcessDelimiters(EXPECTED), FMsg.ToJSON);
end;
procedure TestIRollbarMessage.TestMessageWithRequest;
const
EXPECTED =
'{"data":{' +
'"request":{' +
'"url":"https://rollbar.com/project/1",' +
'"method":"GET",' +
'"headers":{' +
'"Accept":"text/html",' +
'"Referer":"https://rollbar.com/"}}}}';
var
headers: TJSONObject;
begin
headers := TJSONObject.Create;
headers.AddPair('Accept', 'text/html');
headers.AddPair('Referer', 'https://rollbar.com/');
FMsg.Request.AddPair('url', 'https://rollbar.com/project/1');
FMsg.Request.AddPair('method', 'GET');
FMsg.Request.AddPair('headers', headers);
CheckEquals(JsonProcessDelimiters(EXPECTED), FMsg.ToJSON);
end;
procedure TestIRollbarMessage.TestSimpleMessage;
const
EXPECTED =
'{"data":{' +
'"body":{' +
'"message":{' +
'"body":"Hello, world!"}},' +
'"environment":"production"},' +
'"access_token":"POST_SERVER_ITEM_ACCESS_TOKEN"}';
begin
FMsg.AccessToken := 'POST_SERVER_ITEM_ACCESS_TOKEN';
FMsg.Environment := 'production';
FMsg.Body := 'Hello, world!';
CheckEquals(JsonProcessDelimiters(EXPECTED), FMsg.ToJSON);
end;
procedure TestIRollbarMessage.TestUnixDateTimeRoundTrip;
var
dt: TDateTime;
ut: Int64;
begin
dt := Now;
ut := DateTimeToUnix(dt);
CheckEquals(dt, UnixToDateTime(ut), 0.001);
FMsg.Timestamp := dt;
CheckEquals(ut, FMsg.UnixTimestamp);
CheckEquals(dt, FMsg.Timestamp, 0.001);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestIRollbarMessage.Suite);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.JSONConsts;
interface
resourcestring
SCannotCreateObject = 'The input value is not a valid Object';
SUTF8Start = 'UTF8: A start byte not followed by enough continuation bytes';
SUTF8UnexpectedByte = 'UTF8: An unexpected continuation byte in %d-byte UTF8';
SUTF8InvalidHeaderByte = 'UTF8: Type cannot be determined out of header byte';
SJSONSyntaxError = 'The input value is not a valid JSON';
SJSONLocation = '. Path ''%s'', line %d, position %d (offset %d)';
SFieldValueMissing = 'Internal: Field %s has no serialized value';
SFieldExpected = 'Internal: Field %s conversion is incomplete';
SArrayExpected = 'Internal: Array expected instead of %s';
SValueExpected = 'Internal: JSON value expected instead of %s';
SNoArray = 'Internal: Array expected instead of nil';
SInvalidContext = 'Internal: Current context cannot accept a value';
SObjectExpectedForPair = 'Internal: Object context expected when processing a pair';
SInvalidContextForPair = 'Internal: Current context cannot accept a pair';
SNoConversionForType = 'Internal: No conversion possible for type: %s';
SInconsistentConversion = 'Internal: Conversion failed, converted object is most likely incomplete';
STypeNotSupported = 'Internal: Type %s is not currently supported';
SNoTypeInterceptorExpected = 'Field attribute should provide a field interceptor instead of a type one on field %s';
STooMuchNesting = 'The nesting level of JSON arrays / objects is greater than %d';
SCannotCreateType = 'Internal: Cannot instantiate type %s';
SObjectExpectedInArray = 'Object expected at position %d in JSON array %s';
SStringExpectedInArray = 'String expected at position %d in JSON array %s';
SArrayExpectedForField = 'JSON array expected for field %s in JSON %s';
SObjectExpectedForField = 'JSON object expected for field %s in JSON %s';
SInvalidJSONFieldType = 'Un-marshaled array cannot be set as a field value. A reverter may be missing for field %s of %s';
SNoValueConversionForField = 'Internal: Value %s cannot be converted to be assigned to field %s in type %s';
SInvalidTypeForField = 'Cannot set value for field %s as it is expected to be an array instead of %s';
SNoConversionAvailableForValue = 'Value %s cannot be converted into %s. You may use a user-defined reverter';
SValueNotFound = 'Value ''%s'' not found';
SCannotConvertJSONValueToType = 'Conversion from %0:s to %1:s is not supported';
SCannotAddJSONValue = 'Value %s cannot be added to %s';
SEndOfPath = 'End of path';
SErrorInPath = 'Error in path';
{ TJSONReader / TJSONWriter }
SBadEscapeSequence = 'Bad JSON escape sequence: %s';
SErrorConvertStringToDatetime = 'Could not convert string to DateTime: %s';
SErrorConvertStringToDouble = 'Could not convert string to double: %s';
SErrorConvertStringToInteger = 'Could not convert string to integer: %s';
SFormatMessageLinePos = ', line %d, position %d';
SFormatMessagePath = 'Path ''%s''';
SIdentationGreaterThanZero = 'Indentation value must be greater than 0';
SInputInvalidDouble = 'Input string %s is not a valid double';
SInputInvalidInteger = 'Input string %s is not a valid integer';
SInputInvalidNumber = 'Input string %s is not a valid number';
SInvalidCharacterAfterProperty = 'Invalid character after parsing property name. Expected '':'' but got: %s';
SInvalidCloseToken = 'Not a valid close JsonToken: %s';
SInvalidJavascriptProperty = 'Invalid JavaScript property identifier character: %s.';
SInvalidJavascriptQuote = 'Invalid JavaScript string quote character. Valid quote characters are '' and "';
SInvalidJsonToken = 'Invalid JsonToken: %s';
SInvalidObjectId = 'An ObjectId must be 12 bytes';
SInvalidPropertyCharacter = 'Invalid property identifier character: %s';
SInvalidState = 'Invalid state: %s';
SInvalidTokenForContainer = 'JsonToken %s is not valid for closing JsonType %s.';
SNoTokenForType = 'No close token for type %s';
SNoTokenToClose = 'No token to close.';
SParseErrorBoolean = 'Error parsing boolean value.';
SParseErrorComment = 'Error parsing comment. Expected: *, got %s.';
SParseErrorNan = 'Cannot read NaN value.';
SParseErrorNegativeInfinity = 'Cannot read Infinity value';
SParseErrorNull = 'Error parsing null value.';
SParseErrorPositiveInfinity = 'Cannot read -Infinity value';
SParseErrorUndefined = 'Error parsing undefined value';
SReadErrorContainerEnd = 'Read past end of current container context';
SReaderAdditionalText = 'Additional text encountered after finished reading JSON content: %s.';
SReaderMaxDepthExceeded = 'The reader''s MaxDepth of %s has been exceeded.';
SRequiredPropertyName = 'A name is required when setting property name state';
STokenInStateInvalid = 'Token %s in state %s would result in an invalid JSON object.';
SUnexpecteCharAfterValue = 'After parsing a value an unexpected character was encountered: %s';
SUnexpectedBytesEnd = 'Unexpected end when reading bytes.';
SUnexpectedCharConstructor = 'Unexpected character while parsing constructor: %s';
SUnexpectedCharNumber = 'Unexpected character encountered while parsing number: %s';
SUnexpectedCharValue = 'Unexpected character encountered while parsing value: %s.';
SUnexpectedCommentEnd = 'Unexpected end while parsing comment';
SUnexpectedConstructorEnd = 'Unexpected end while parsing constructor.';
SUnexpectedEnd = 'Unexpected end';
SUnexpectedEndConstructorDate = 'Unexpected end when reading date constructor';
SUnexpectedJsonContent = 'Unexpected content while parsing JSON';
SUnexpectedObjectByteEnd = 'Unexpected end of object byte value';
SUnexpectedState = 'Unexpected state: %s';
SUnexpectedTokenCodeWScope = 'Error reading code with scope. Unexpected token: %s';
SUnexpectedTokenDate = 'Error reading date. Unexpected token: %s';
SUnexpectedTokenDateConstructorExpEnd = 'Unexpected token when reading date constructor. Expected EndConstructor, got %s';
SUnexpectedTokenDateConstructorExpInt = 'Unexpected token when reading date constructor. Expected Integer, got %s';
SUnexpectedTokenDouble = 'Error reading double. Unexpected token: %s';
SUnexpectedTokenInteger = 'Error reading integer. Unexpected token: %s';
SUnexpectedTokenReadBytes ='Unexpected token when reading bytes: %s';
SUnexpectedTokenString = 'Error reading string. Unexpected token: %s';
SUnexpectedTypeOnEnd = 'Unexpected type when writing end: %s';
SUnexpectedUnicodeCharEnd = 'Unexpected end while parsing unicode character';
SUnexpectedUnquotedPropertyEnd = 'Unexpected end while parsing unquoted property name';
SUnknowContainerType = 'Unknown JsonType: %s';
SUnsupportedBsonConstructor = 'Cannot write JSON constructor as BSON';
SUnsupportedBsonRaw = 'Cannot write raw JSON as BSON';
SUnsupportedJSONValueRaw = 'Write raw JSON is unsupported';
SUnsupportedJSONValueConstructor = 'Write constructor is unsupported';
SUnsupportedCommentBson = 'Cannot write JSON comment as BSON';
SUnsupportedType = 'Unsupported type: %s';
SUnterminatedString = 'Unterminated string. Expected delimiter: %s.';
SWhitespaceOnly = 'Only white space characters should be used.';
SUnexpectedExtJSONToken = 'Unexpected token when reading Extended JSON value %s. Expected token: %s';
{ TJSONPathParser }
SJSONPathUnexpectedRootChar = 'Unexpected char for root element: .';
SJSONPathEndedOpenBracket = 'Path ended with an open bracket';
SJSONPathEndedOpenString = 'Path ended with an open string';
SJSONPathInvalidArrayIndex = 'Invalid index for array: %s';
SJSONPathUnexpectedIndexedChar ='Unexpected character while parsing indexer: %s';
SJSONPathDotsEmptyName = 'Empty name not allowed in dot notation, use ['''']';
{ TJsonSerializer }
SUnexpectedTokenDeserializeObject = 'Unexpected token while deserializing object: %s';
SUnexpectedEndDeserializeArray = 'Unexpected end when deserializing array';
SUnexpectedEndDeserializeObject = 'Unexpected end when deserializing object';
SUnexpectedEndDeserializeValue = 'Unexpected end when deserializing value';
SUnexpectedTypePrimitiveContract = 'Unexpected type to create a primitive contract';
SUnexpectedTokenReadObject = 'Unexpected type while read json object';
SUnexpectedTokenReadArray = 'Unexpected type while read json array';
SErrorObjectNotInstantiable = 'Object cannot be instantiated';
SUnexpectedEnumerationValue = 'Unexpected value %s';
SUnexpectedToken = 'Unexpected token %s';
SUnexpectedTokenPopulateObject = 'Unexpected Token while populate an Object';
SUnexpectedTokenPopulateArray = 'Unexpected Token while populate an Array';
SWriteJsonNotImplemented = 'WriteJson is not implemented cause CanWrite is False';
SReadJsonNotImplemented = 'ReadJson is not implemented cause CanRead is False';
SErrorTypeNotInstantiable = 'Type %s cannot be instantiated';
SCannotFindFieldForType = 'Cannot find %s field for the given type %s';
SCannotFindPropertyForType = 'Cannot find %s property for the given type %s';
SCannotFindType = 'Cannot find %s property for the given type %s';
SConverterNotMatchingType = 'Type of Value ''%s'' does not match with the expected type: ''%s''';
SConverterStringNotMatchingEnum = 'The string ''%s'' does not match any value of %s';
STypeArgumentNil = 'Type is nil';
SDefaultReferenceResolverInternally = 'The DefaultReferenceResolver can only be used internally';
{ System.JSON.Builders }
sJSONBuilderNotEmpty = 'This operation is not permitted after pairs or elements have been added';
sJSONBuilderNotParentType = 'This operation is not permitted on the current JSON type';
sJSONBuilderUnsupVarRecType = 'Cannot add element of unsupported TVarRec type %d';
sJSONBuilderUnsupVariantType = 'Cannot add element of unsupported Variant type %d';
sJSONBuilderInvalidOpenArrayItem = 'Failed to append open array on item with index %d';
sJSONBuilderInvalidSetOfItems = 'Failed to append not properly closed set of items';
sJSONBuilderNoReaderCallback = 'This operation is not permitted without assigned callback';
sJSONIteratorInvalidState = 'Cannot iterate due to invalid iterator state';
implementation
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Vcl.JumpList;
interface
uses
System.Classes, System.SysUtils, Winapi.ShlObj, Winapi.ObjectArray;
type
TJumpListItem = class(TCollectionItem)
private
FPath: TFileName;
FIcon: TFileName;
FArguments: string;
FFriendlyName: string;
FIsSeparator: Boolean;
FVisible: Boolean;
procedure SetIsSeparator(const Value: Boolean);
procedure SetIcon(const Value: TFileName);
procedure SetPath(const Value: TFileName);
procedure SetFriendlyName(const Value: string);
procedure SetArguments(const Value: string);
procedure SetVisible(const Value: Boolean);
public
function GetAsIShellLink: IShellLink;
constructor Create(Collection: TCollection); override;
published
property IsSeparator: Boolean read FIsSeparator write SetIsSeparator default False;
property Icon: TFileName read FIcon write SetIcon;
property Path: TFileName read FPath write SetPath;
property FriendlyName: string read FFriendlyName write SetFriendlyName;
property Arguments: string read FArguments write SetArguments;
property Visible: Boolean read FVisible write SetVisible default True;
end;
TJumpListCollection = class(TOwnedCollection)
private
FOnChange: TNotifyEvent;
function GetItem(Index: Integer): TJumpListItem;
procedure SetItem(Index: Integer; const Value: TJumpListItem);
protected
procedure Update(Item: TCollectionItem); override;
public
function GetObjectArray: IObjectArray;
property Items[Index: Integer]: TJumpListItem read GetItem write SetItem; default;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
TJumpCategoryItem = class(TCollectionItem)
private
FItems: TJumpListCollection;
FCategoryName: string;
FVisible: Boolean;
procedure SetVisible(const Value: Boolean);
procedure SetCategoryName(const Value: string);
procedure SetItems(const Value: TJumpListCollection);
procedure OnItemsChange(Sender: TObject);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
published
property Visible: Boolean read FVisible write SetVisible default True;
property CategoryName: string read FCategoryName write SetCategoryName;
property Items: TJumpListCollection read FItems write SetItems;
end;
TJumpCategories = class(TOwnedCollection)
private
FOnChange: TNotifyEvent;
function GetItem(Index: Integer): TJumpCategoryItem;
procedure SetItem(Index: Integer; const Value: TJumpCategoryItem);
protected
procedure Update(Item: TCollectionItem); override;
public
function GetCategoryIndex(const CategoryName: string): Integer;
property Items[Index: Integer]: TJumpCategoryItem read GetItem write SetItem; default;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
TItemDeletedByUserEvent = procedure (Sender: TObject; const Item: TJumpListItem; const CategoryName: string; FromTasks: Boolean) of object;
TCreatingListErrorEvent = procedure (Sender: TObject; WinErrorCode: Cardinal; const ErrorDescription: string; var Handled: Boolean) of object;
TCustomJumpList = class(TComponent)
private
FCustomCategories: TJumpCategories;
FTaskList: TJumpListCollection;
FShowRecent: Boolean;
FShowFrequent: Boolean;
FOnItemDeleted: TItemDeletedByUserEvent;
FDestinationList: ICustomDestinationList;
FApplicationID: string;
FAutoRefresh: Boolean;
FIsCreatingList: Boolean;
FOnListUpdateError: TCreatingListErrorEvent;
FOnItemsLoaded: TNotifyEvent;
FEnabled: Boolean;
procedure ChangeProcessAppId(const AppId: string);
procedure ProcessRemovedObjects(const ObjArray: IObjectArray);
procedure ProcessRemoved(const Path, Arguments, FriendlyName: string);
procedure SetAutoRefresh(const Value: Boolean);
procedure SetCustomCategories(const Value: TJumpCategories);
procedure SetTaskList(const Value: TJumpListCollection);
procedure SetShowRecent(const Value: Boolean);
procedure DoAutoRefresh;
procedure SetShowFrequent(const Value: Boolean);
procedure OnListChange(Sender: TObject);
class procedure RetrievePathsFromArray(const ObjectArray: IObjectArray; out Items: TArray<string>);
class function GetDocList(ListType: Integer; const AppModelID: string; out ObjectList: IObjectArray; NumItems: Integer = 0): Boolean; overload;
procedure SetEnabled(const Value: Boolean);
procedure CheckProcessAppId;
procedure CheckCanEnable;
procedure DoEnable;
function CheckUpdateError(ErrNo: HRESULT; const Description: string): Boolean;
protected
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class procedure AddToRecent(const Path: string); overload; inline;
class procedure AddToRecent(const ShellLink: IShellLink); overload; inline;
class procedure AddToRecent(const JumpItem: TJumpListItem); overload; inline;
class function RemoveFromRecent(const Path: string; const AppModelID: string): Boolean; overload;
class function RemoveFromRecent(const ShellItem: IUnknown; const AppModelID: string): Boolean; overload;
class function RemoveFromRecent(const JumpItem: TJumpListItem; const AppModelID: string): Boolean; overload;
class function RemoveAllFromRecent(const AppModelID: string): Boolean;
class function GetRecentList(const AppModelID: string; out ObjectList: IObjectArray; NumItems: Integer = 0): Boolean; overload; inline;
class function GetRecentList(const AppModelID: string; out Items: TArray<string>; NumItems: Integer = 0): Boolean; overload;
class function GetFrequentList(const AppModelID: string; out ObjectList: IObjectArray; NumItems: Integer = 0): Boolean; overload; inline;
class function GetFrequentList(const AppModelID: string; out Items: TArray<string>; NumItems: Integer = 0): Boolean; overload;
function AddCategory(const CategoryName: string): Integer;
function AddTask(const FriendlyName: string; const Path: string = ''; const Arguments: string = '';
const Icon: string = ''): TJumpListItem;
function AddTaskSeparator: TJumpListItem;
function AddItemToCategory(CategoryIndex: Integer; const FriendlyName: string; const Path: string = '';
const Arguments: string = ''; const Icon: string = ''): TJumpListItem;
function UpdateList: Boolean;
function DeleteList: Boolean;
property AutoRefresh: Boolean read FAutoRefresh write SetAutoRefresh default False;
property Enabled: Boolean read FEnabled write SetEnabled default False;
property ApplicationID: string read FApplicationID write FApplicationID;
property CustomCategories: TJumpCategories read FCustomCategories write SetCustomCategories;
property ShowRecent: Boolean read FShowRecent write SetShowRecent default False;
property ShowFrequent: Boolean read FShowFrequent write SetShowFrequent default False;
property TaskList: TJumpListCollection read FTaskList write SetTaskList;
property OnItemDeleted: TItemDeletedByUserEvent read FOnItemDeleted write FOnItemDeleted;
property OnListUpdateError: TCreatingListErrorEvent read FOnListUpdateError write FOnListUpdateError;
property OnItemsLoaded: TNotifyEvent read FOnItemsLoaded write FOnItemsLoaded;
end;
TJumpList = class(TCustomJumpList)
published
property AutoRefresh;
property Enabled;
property ApplicationID;
property CustomCategories;
property ShowRecent;
property ShowFrequent;
property TaskList;
property OnItemDeleted;
property OnListUpdateError;
property OnItemsLoaded;
end;
EJumpListItemException = class(Exception);
EJumpListException = class(Exception);
implementation
uses
Winapi.Activex, Winapi.PropSys, Winapi.PropKey, System.Win.ComObj, Winapi.Windows,
System.Generics.Collections, Vcl.Consts;
procedure CheckError(ErrNo: HRESULT; const Description: string);
begin
if not Succeeded(ErrNo) then
raise EJumpListItemException.CreateFmt(SJumplistsItemException, [ErrNo, Description]);
end;
{ TJumpCategoryItem }
constructor TJumpCategoryItem.Create(Collection: TCollection);
begin
inherited;
FItems := TJumpListCollection.Create(Self, TJumpListItem);
FItems.OnChange := OnItemsChange;
FVisible := True;
end;
destructor TJumpCategoryItem.Destroy;
begin
FItems.Destroy;
inherited;
end;
procedure TJumpCategoryItem.OnItemsChange(Sender: TObject);
begin
Changed(False);
end;
procedure TJumpCategoryItem.SetCategoryName(const Value: string);
begin
if FCategoryName <> Value then
begin
FCategoryName := Value;
Changed(False);
end;
end;
procedure TJumpCategoryItem.SetItems(const Value: TJumpListCollection);
begin
if FItems <> Value then
begin
FItems.Assign(Value);
Changed(False);
end;
end;
procedure TJumpCategoryItem.SetVisible(const Value: Boolean);
begin
if FVisible <> Value then
begin
FVisible := Value;
Changed(False);
end;
end;
{ TJumpListItem }
constructor TJumpListItem.Create(Collection: TCollection);
begin
inherited;
FVisible := True;
FFriendlyName := 'Jump List Item ' + IntToStr(Collection.Count); // Do not localize
end;
function TJumpListItem.GetAsIShellLink: IShellLink;
var
PropertyStore: Winapi.PropSys.IPropertyStore;
LPropVariant: TPropVariant;
begin
Result := CreateComObject(CLSID_ShellLink) as IShellLink;
if FIsSeparator then
begin
CheckError(Result.QueryInterface(Winapi.PropSys.IPropertyStore, PropertyStore), SJumplistsItemErrorGetpsi);
CheckError(InitPropVariantFromBoolean(True, LPropVariant), SJumplistsItemErrorInitializepropvar);
CheckError(PropertyStore.SetValue(PKEY_AppUserModel_IsDestListSeparator, LPropVariant), SJumplistsItemErrorSetps);
CheckError(PropertyStore.Commit, SJumplistsItemErrorCommitps);
PropVariantClear(LPropVariant);
end
else
begin
if FFriendlyName <> '' then
begin
CheckError(Result.QueryInterface(Winapi.PropSys.IPropertyStore, PropertyStore), SJumplistsItemErrorGetpsi);
CheckError(InitPropVariantFromString(PWideChar(FFriendlyName), LPropVariant), SJumplistsItemErrorInitializepropvar);
CheckError(PropertyStore.SetValue(PKEY_Title, LPropVariant), SJumplistsItemErrorSetps);
CheckError(PropertyStore.Commit, SJumplistsItemErrorCommitps);
PropVariantClear(LPropVariant);
end
else
raise EJumpListItemException.Create(SJumplistsItemErrorNofriendlyname);
if FArguments <> '' then
CheckError(Result.SetArguments(PWideChar(FArguments)), SJumplistsItemErrorSettingarguments);
if FPath <> '' then
CheckError(Result.SetPath(PWideChar(FPath)), SJumplistsItemErrorSettingpath)
else
CheckError(Result.SetPath(PWideChar(ParamStr(0))), SJumplistsItemErrorSettingpath);
if FIcon <> '' then
CheckError(Result.SetIconLocation(PWideChar(FIcon), 0), SJumplistsItemErrorSettingicon)
else // use the current executable Icon
CheckError(Result.SetIconLocation(PWideChar(Paramstr(0)), 0), SJumplistsItemErrorSettingicon);
end;
end;
procedure TJumpListItem.SetArguments(const Value: string);
begin
if FArguments <> Value then
begin
FArguments := Value;
Changed(False);
end;
end;
procedure TJumpListItem.SetFriendlyName(const Value: string);
begin
if FFriendlyName <> Value then
begin
FFriendlyName := Value;
Changed(False);
end;
end;
procedure TJumpListItem.SetIcon(const Value: TFileName);
begin
if FIcon <> Value then
begin
FIcon := Value;
Changed(False);
end;
end;
procedure TJumpListItem.SetIsSeparator(const Value: Boolean);
const
SJumplistsItemSeparatorException = 'Separators are not allowed on categories.';
begin
if Value <> FIsSeparator then
begin
if Collection.Owner is TJumpCategoryItem then
raise EJumpListItemException.Create(SJumplistsItemSeparatorException);
FIsSeparator := Value;
Changed(False);
end;
end;
procedure TJumpListItem.SetPath(const Value: TFileName);
begin
if FPath <> Value then
begin
FPath := Value;
Changed(False);
end;
end;
procedure TJumpListItem.SetVisible(const Value: Boolean);
begin
if FVisible <> Value then
begin
FVisible := Value;
Changed(False);
end;
end;
{ TJumpCategories }
function TJumpCategories.GetCategoryIndex(const CategoryName: string): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Count - 1 do
if Items[I].CategoryName = CategoryName then
Exit(I);
end;
function TJumpCategories.GetItem(Index: Integer): TJumpCategoryItem;
begin
Result := TJumpCategoryItem(inherited GetItem(Index));
end;
procedure TJumpCategories.SetItem(Index: Integer; const Value: TJumpCategoryItem);
begin
inherited SetItem(Index, Value);
end;
procedure TJumpCategories.Update(Item: TCollectionItem);
begin
inherited;
if Assigned(FOnChange) then
FOnChange(Self);
end;
{ TJumpList }
function TJumpListCollection.GetItem(Index: Integer): TJumpListItem;
begin
Result := TJumpListItem(inherited GetItem(Index));
end;
function TJumpListCollection.GetObjectArray: IObjectArray;
var
LObjCollection: IObjectCollection;
LItem: TJumpListItem;
LShellLink: IShellLink;
I: Integer;
begin
if CheckWin32Version(6, 1) then
begin
if Succeeded(CoCreateInstance(CLSID_EnumerableObjectCollection, nil, CLSCTX_INPROC_SERVER, IID_IObjectCollection, LObjCollection)) then
begin
for I := 0 to Count - 1 do
begin
LItem := Items[I] as TJumpListItem;
if LItem.Visible then
begin
LShellLink := LItem.GetAsIShellLink;
if LShellLink <> nil then
CheckError(LObjCollection.AddObject(LShellLink), SJumplistsItemErrorAddingtobjarr);
end;
end;
CheckError(LObjCollection.QueryInterface(IObjectArray, Result), SJumplistsItemErrorGettingobjarr);
end;
end;
end;
procedure TJumpListCollection.SetItem(Index: Integer; const Value: TJumpListItem);
begin
inherited SetItem(Index, Value);
end;
procedure TJumpListCollection.Update(Item: TCollectionItem);
begin
inherited;
if Assigned(FOnChange) then
FOnChange(Self);
end;
{ TCustomJumpLists }
constructor TCustomJumpList.Create(AOwner: TComponent);
begin
inherited;
FCustomCategories := TJumpCategories.Create(Self, TJumpCategoryItem);
FTaskList := TJumpListCollection.Create(Self, TJumpListItem);
FCustomCategories.OnChange := OnListChange;
FTaskList.OnChange := OnListChange;
end;
destructor TCustomJumpList.Destroy;
begin
FCustomCategories.Free;
FTaskList.Free;
inherited;
end;
class procedure TCustomJumpList.AddToRecent(const Path: string);
begin
SHAddToRecentDocs(SHARD_PATH, PWideChar(Path));
end;
class procedure TCustomJumpList.AddToRecent(const ShellLink: IShellLink);
begin
if CheckWin32Version(6, 1) then
SHAddToRecentDocs(SHARD_LINK, PWideChar(ShellLink));
end;
function TCustomJumpList.AddCategory(const CategoryName: string): Integer;
var
LItem: TJumpCategoryItem;
begin
FCustomCategories.BeginUpdate;
LItem := TJumpCategoryItem(FCustomCategories.Add);
try
LItem.CategoryName := CategoryName;
LItem.Visible := True;
Result := LItem.Index;
finally
FCustomCategories.EndUpdate;
end;
end;
function TCustomJumpList.AddItemToCategory(CategoryIndex: Integer; const FriendlyName, Path, Arguments,
Icon: string): TJumpListItem;
begin
FCustomCategories.Items[CategoryIndex].Items.BeginUpdate;
Result := TJumpListItem(FCustomCategories.Items[CategoryIndex].Items.Add);
try
Result.Icon := Icon;
Result.Path := Path;
Result.Arguments := Arguments;
Result.FriendlyName := FriendlyName;
Result.IsSeparator := False;
Result.Visible := True;
finally
FCustomCategories.Items[CategoryIndex].Items.EndUpdate;
end;
end;
function TCustomJumpList.AddTask(const FriendlyName, Path, Arguments, Icon: string): TJumpListItem;
begin
FTaskList.BeginUpdate;
Result := TJumpListItem(FTaskList.Add);
try
Result.Icon := Icon;
Result.Path := Path;
Result.Arguments := Arguments;
Result.FriendlyName := FriendlyName;
Result.IsSeparator := False;
Result.Visible := True;
finally
FTaskList.EndUpdate;
end;
end;
function TCustomJumpList.AddTaskSeparator: TJumpListItem;
begin
FTaskList.BeginUpdate;
Result := TJumpListItem(FTaskList.Add);
try
Result.IsSeparator := True;
Result.Visible := True;
finally
FTaskList.EndUpdate;
end;
end;
class procedure TCustomJumpList.AddToRecent(const JumpItem: TJumpListItem);
begin
AddToRecent(JumpItem.GetAsIShellLink);
end;
function TCustomJumpList.DeleteList: Boolean;
var
LMaxSlots: Cardinal;
LRemovedTasks: IObjectArray;
begin
Result := False;
if FEnabled and CheckWin32Version(6, 1) then
begin
ChangeProcessAppId(FApplicationID);
if CheckUpdateError(FDestinationList.BeginList(LMaxSlots, IID_IObjectArray, LRemovedTasks), SJumplistErrorBeginlist) then
begin
try
ProcessRemovedObjects(LRemovedTasks);
Result := CheckUpdateError(FDestinationList.CommitList, SJumplistErrorCommitlist);
except
FDestinationList.AbortList;
raise;
end;
end;
end;
end;
procedure TCustomJumpList.CheckCanEnable;
begin
if not CheckWin32Version(6, 1) then
raise EJumpListException.Create(SJumplistExceptionInvalidOS);
CheckProcessAppId;
end;
procedure TCustomJumpList.DoAutoRefresh;
begin
if FAutoRefresh and not FIsCreatingList and not (csDesigning in ComponentState) then
UpdateList;
end;
procedure TCustomJumpList.DoEnable;
begin
CheckCanEnable;
if FDestinationList = nil then
FDestinationList := CreateComObject(CLSID_DestinationList) as ICustomDestinationList;
end;
class function TCustomJumpList.GetDocList(ListType: Integer; const AppModelID: string; out ObjectList: IObjectArray;
NumItems: Integer): Boolean;
var
LDocList: IApplicationDocumentLists;
begin
Result := False;
if CheckWin32Version(6, 1) then
begin
LDocList := CreateComObject(CLSID_ApplicationDocumentLists) as IApplicationDocumentLists;
if AppModelID <> '' then
LDocList.SetAppID(PWideChar(AppModelID));
Result := Succeeded(LDocList.GetList(ListType, NumItems, IID_IObjectArray, ObjectList));
end;
end;
class procedure TCustomJumpList.RetrievePathsFromArray(const ObjectArray: IObjectArray; out Items: TArray<string>);
var
NumObjects: Cardinal;
I: Integer;
LLinkItem: IShellLink;
LShellItem: IShellItem;
LPath: array[0..MAX_PATH - 1] of Char;
LPPath: PWideChar;
LPfd: _WIN32_FIND_DATAW;
begin
ObjectArray.GetCount(NumObjects);
SetLength(Items, NumObjects);
for I := 0 to Integer(NumObjects) - 1 do
begin
if Succeeded(ObjectArray.GetAt(I, IID_IShellLink, LLinkItem)) then
begin
LLinkItem.GetPath(LPath, MAX_PATH, LPfd, SLGP_RELATIVEPRIORITY);
Items[I] := LPath;
end;
if Succeeded(ObjectArray.GetAt(I, IID_IShellItem, LShellItem)) then
begin
LShellItem.GetDisplayName(SIGDN_FILESYSPATH, LPPath);
Items[I] := LPPath;
end;
end;
end;
class function TCustomJumpList.GetFrequentList(const AppModelID: string; out Items: TArray<string>;
NumItems: Integer): Boolean;
var
LItems: IObjectArray;
begin
Result := False;
if TJumpList.GetFrequentList(AppModelID, LItems, NumItems) then
begin
RetrievePathsFromArray(LItems, Items);
Result := True;
end;
end;
class function TCustomJumpList.GetRecentList(const AppModelID: string; out Items: TArray<string>;
NumItems: Integer): Boolean;
var
LItems: IObjectArray;
begin
Result := False;
if TJumpList.GetRecentList(AppModelID, LItems, NumItems) then
begin
RetrievePathsFromArray(LItems, Items);
Result := True;
end;
end;
class function TCustomJumpList.GetFrequentList(const AppModelID: string; out ObjectList: IObjectArray;
NumItems: Integer): Boolean;
begin
Result := GetDocList(ADLT_FREQUENT, AppModelID, ObjectList, NumItems);
end;
class function TCustomJumpList.GetRecentList(const AppModelID: string; out ObjectList: IObjectArray;
NumItems: Integer): Boolean;
begin
Result := GetDocList(ADLT_RECENT, AppModelID, ObjectList, NumItems);
end;
procedure TCustomJumpList.Loaded;
begin
inherited;
if not (csDesigning in ComponentState) then
begin
if Assigned(FOnItemsLoaded) then
begin
FIsCreatingList := True;
try
FOnItemsLoaded(Self);
finally
FIsCreatingList := False;
end;
end;
if FEnabled then
DoEnable;
DoAutoRefresh;
end;
end;
procedure TCustomJumpList.OnListChange(Sender: TObject);
begin
DoAutoRefresh;
end;
procedure TCustomJumpList.SetAutoRefresh(const Value: Boolean);
begin
if Value <> FAutoRefresh then
begin
FAutoRefresh := Value;
DoAutoRefresh;
end;
end;
procedure TCustomJumpList.ChangeProcessAppId(const AppId: string);
var
LAppId : LPCWSTR;
begin
if FEnabled and (CheckWin32Version(6, 1)) then
begin
LAppId := nil;
if Succeeded(GetCurrentProcessExplicitAppUserModelID(LAppId)) and (LAppId = nil) then
SetCurrentProcessExplicitAppUserModelID(PWideChar(AppId));
end;
end;
procedure TCustomJumpList.CheckProcessAppId;
var
LAppId : LPCWSTR;
begin
if (CheckWin32Version(6, 1)) and (FApplicationID <> '') then
begin
LAppId := nil;
if Succeeded(GetCurrentProcessExplicitAppUserModelID(LAppId)) and (LAppId <> nil) and (LAppId = FApplicationID) then
raise EJumpListException.CreateFmt(SJumplistExceptionAppID, [LAppId]);
end;
end;
procedure TCustomJumpList.SetCustomCategories(const Value: TJumpCategories);
begin
if FCustomCategories <> Value then
begin
FCustomCategories.Assign(Value);
DoAutoRefresh;
end;
end;
procedure TCustomJumpList.SetEnabled(const Value: Boolean);
begin
if Value <> FEnabled then
begin
if not (csLoading in ComponentState) and not (csDesigning in ComponentState) and Value then
DoEnable;
FEnabled := Value;
end;
end;
procedure TCustomJumpList.SetShowFrequent(const Value: Boolean);
begin
if Value <> FShowFrequent then
begin
FShowFrequent := Value;
DoAutoRefresh;
end;
end;
procedure TCustomJumpList.SetShowRecent(const Value: Boolean);
begin
if Value <> FShowRecent then
begin
FShowRecent := Value;
DoAutoRefresh;
end;
end;
procedure TCustomJumpList.SetTaskList(const Value: TJumpListCollection);
begin
if FTaskList <> Value then
begin
FTaskList.Assign(Value);
DoAutoRefresh;
end;
end;
procedure TCustomJumpList.ProcessRemoved(const Path, Arguments, FriendlyName: string);
procedure ProcessTaskList(const ListToProcess: TJumpListCollection; IsFromTasks: Boolean; const CategoryName: string);
var
I: Integer;
RemoveList: TList<Integer>;
begin
RemoveList := TList<Integer>.Create;
try
ListToProcess.BeginUpdate;
try
for I := 0 to ListToProcess.Count - 1 do
begin
if (ListToProcess[I].Path = Path) and (ListToProcess[I].Arguments = Arguments) and
(ListToProcess[I].FriendlyName = FriendlyName )then
begin
if Assigned(FOnItemDeleted) then
FOnItemDeleted(Self, ListToProcess[I], CategoryName, IsFromTasks);
RemoveList.Add(I);
end;
end;
for I := RemoveList.Count - 1 downto 0 do
ListToProcess.Delete(RemoveList.Items[I]);
finally
ListToProcess.EndUpdate;
end;
finally
RemoveList.Free;
end;
end;
var
I: Integer;
begin
if FTaskList.Count > 0 then
ProcessTaskList(FTaskList, True, '');
for I := 0 to FCustomCategories.Count - 1 do
begin
if FCustomCategories[I].Items.Count > 0 then
ProcessTaskList(FCustomCategories[I].Items, False, FCustomCategories[I].CategoryName);
end;
end;
procedure TCustomJumpList.ProcessRemovedObjects(const ObjArray: IObjectArray);
var
LRemoved: Cardinal;
I: Cardinal;
LError: Integer;
LLinkItem: IShellLink;
LPath: array[0..MAX_PATH -1] of Char;
LArguments: array[0..MAX_PATH -1] of Char; //PWideChar;
LFriendlyName: array[0..MAX_PATH -1] of Char; //PWideChar;
LFileStr: _WIN32_FIND_DATAW;
PropertyStore: Winapi.PropSys.IPropertyStore;
LPropVariant: tagPROPVARIANT;
begin
if (Win32MajorVersion >= 6) and (ObjArray <> nil) then
begin
ObjArray.GetCount(LRemoved);
if LRemoved > 0 then
begin
for I:= 0 to LRemoved - 1 do
begin
LError := ObjArray.GetAt(I, IID_IShellLink, LLinkItem);
if Succeeded(LError) then
begin
if Supports(LLinkItem, Winapi.PropSys.IPropertyStore, PropertyStore) then
begin
LLinkItem.GetPath(LPath, Length(LPath), LFileStr, SLGP_RELATIVEPRIORITY);
LLinkItem.GetArguments(LArguments, Length(LArguments));
InitPropVariantFromString(LFriendlyName, LPropVariant);
PropertyStore.GetValue(PKEY_Title, LPropVariant);
PropVariantToString(LPropVariant, LFriendlyName, Length(LFriendlyName));
PropVariantClear(LPropVariant);
ProcessRemoved(LPath, LArguments, LFriendlyName);
end;
end;
end;
end;
end;
end;
class function TCustomJumpList.RemoveAllFromRecent(const AppModelID: string): Boolean;
var
LAppDestinations: IApplicationDestinations;
begin
Result := False;
if CheckWin32Version(6, 1) then
begin
LAppDestinations := CreateComObject(CLSID_ApplicationDestinations) as IApplicationDestinations;
if AppModelID <> '' then
LAppDestinations.SetAppID(PWideChar(PWideChar(AppModelID)));
Result := Succeeded(LAppDestinations.RemoveAllDestinations);
end;
end;
class function TCustomJumpList.RemoveFromRecent(const Path, AppModelID: string): Boolean;
var
ObjectArray: IObjectArray;
LNumItems: Cardinal;
I: Cardinal;
LShellLink: IShellLink;
LDocumentPath: string;
LPath: PWideChar;
LShellItem: IShellItem;
begin
Result := False;
if CheckWin32Version(6, 1) and GetRecentList(AppModelID, ObjectArray)
and Succeeded(ObjectArray.GetCount(LNumItems)) and (LNumItems > 0) then
begin
LPath := @LDocumentPath;
for I := 0 to LNumItems - 1 do
begin
if Succeeded(ObjectArray.GetAt(I, IID_IShellLink, LShellLink)) then
begin
LShellLink.GetArguments(PWideChar(LDocumentPath), MAX_PATH);
if LDocumentPath = Path then
begin
TCustomJumpList.RemoveFromRecent(LShellLink, AppModelID);
Exit(True);
end;
end
else if Succeeded(ObjectArray.GetAt(I, IID_IShellItem, LShellItem)) then
begin
if not Succeeded(LShellItem.GetDisplayName(SIGDN_FILESYSPATH, LPath)) then
LShellItem.GetDisplayName(SIGDN_URL, LPath);
if LPath = Path then
begin
TCustomJumpList.RemoveFromRecent(LShellItem, AppModelID);
Exit(True);
end;
end;
end;
end;
end;
class function TCustomJumpList.RemoveFromRecent(const ShellItem: IUnknown; const AppModelID: string): Boolean;
var
LAppDestinations: IApplicationDestinations;
begin
Result := False;
if CheckWin32Version(6, 1) then
begin
LAppDestinations := CreateComObject(CLSID_ApplicationDestinations) as IApplicationDestinations;
if AppModelID <> '' then
LAppDestinations.SetAppID(PWideChar(PWideChar(AppModelID)));
Result := Succeeded(LAppDestinations.RemoveDestination(ShellItem));
end;
end;
class function TCustomJumpList.RemoveFromRecent(const JumpItem: TJumpListItem; const AppModelID: string): Boolean;
begin
Result := RemoveFromRecent(JumpItem.GetAsIShellLink, AppModelID);
end;
function TCustomJumpList.CheckUpdateError(ErrNo: HRESULT; const Description: string): Boolean;
var
LHandled: Boolean;
begin
Result := Succeeded(ErrNo);
if not Result then
begin
LHandled := false;
if Assigned(FOnListUpdateError) then
FOnListUpdateError(Self, ErrNo, Description, LHandled);
if not LHandled then
raise EJumpListException.CreateFmt(SJumplistException, [ErrNo, Description]);
end;
end;
function TCustomJumpList.UpdateList: Boolean;
var
LMaxSlots, LObjects: Cardinal;
LRemovedTasks, LTasksList: IObjectArray;
I: Integer;
begin
Result := False;
if FEnabled and CheckWin32Version(6, 1) and not (csLoading in ComponentState) then
begin
ChangeProcessAppId(FApplicationID);
FIsCreatingList := True;
try
if CheckUpdateError(FDestinationList.BeginList(LMaxSlots, IID_IObjectArray, LRemovedTasks), SJumplistErrorBeginlist) then
begin
try
ProcessRemovedObjects(LRemovedTasks);
// Add recent and frequent categories
if FShowRecent then
CheckError(FDestinationList.AppendKnownCategory(KDC_RECENT), SJumplistErrorAppendrc);
if FShowFrequent then
CheckError(FDestinationList.AppendKnownCategory(KDC_FREQUENT), SJumplistErrorAppendfc);
// Add task items
if FTaskList.Count > 0 then
begin
LTasksList := FTaskList.GetObjectArray;
if LTasksList <> nil then
begin
LTasksList.GetCount(LObjects);
if (LTasksList <> nil) and (LObjects > 0) then
CheckError(FDestinationList.AddUserTasks(LTasksList), SJumplistErrorAddusertasks);
end;
end;
// Add custom categories
for I := 0 to FCustomCategories.Count - 1 do
begin
if FCustomCategories[I].Visible then
begin
LTasksList := FCustomCategories[I].Items.GetObjectArray;
if LTasksList <> nil then
begin
LTasksList.GetCount(LObjects);
if (LTasksList <> nil) and (LObjects > 0) then
CheckError(FDestinationList.AppendCategory(PWideChar(FCustomCategories[I].CategoryName), LTasksList),
Format(SJumplistErrorAddcategory, [FCustomCategories[I].CategoryName]));
end;
end;
end;
Result := CheckUpdateError(FDestinationList.CommitList, SJumplistErrorCommitlist);
except
FDestinationList.AbortList;
raise;
end;
end;
finally
FIsCreatingList := False
end;
end;
end;
end.
|
unit UnRemocaoInclusaoIngredientesView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, StdCtrls,
JvExControls, JvButton, JvTransparentButton, ExtCtrls, ComCtrls,
JvExComCtrls, JvComCtrls, JvComponentBase, JvTabBar, JvExStdCtrls,
JvEdit, JvValidateEdit, DB, System.UITypes,
{ Fluente }
Util, DataUtil, UnModelo, Componentes, UnAplicacao, UnComandaModelo;
type
TRemocaoInclusaoIngredientesView = class(TForm, ITela)
Panel1: TPanel;
btnGravar: TJvTransparentButton;
JvTransparentButton2: TJvTransparentButton;
Panel2: TPanel;
btnRemoverIngredientes: TPanel;
btnIncluirIngredientes: TPanel;
Pages: TPageControl;
TabSheet1: TTabSheet;
gIngredientes: TJvDBUltimGrid;
TabSheet2: TTabSheet;
Panel5: TPanel;
Label1: TLabel;
Label2: TLabel;
EdtIngrediente: TEdit;
EdtValor: TJvValidateEdit;
Panel6: TPanel;
Panel3: TPanel;
Panel4: TPanel;
Panel7: TPanel;
Panel8: TPanel;
gIngredientesInseridos: TJvDBUltimGrid;
procedure btnRemoverIngredientesClick(Sender: TObject);
procedure btnIncluirIngredientesClick(Sender: TObject);
procedure gIngredientesDblClick(Sender: TObject);
procedure gIngredientesDrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
procedure Panel6Click(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
private
FComandaModelo: TComandaModelo;
FControlador: IResposta;
public
function Controlador(const Controlador: IResposta): ITela;
function Descarregar: ITela;
function ExibirTela: Integer;
function Modelo(const Modelo: TModelo): ITela;
function Preparar: ITela;
published
procedure AtivarAba(const Aba: TPanel);
procedure DesativarAba(const Aba: TPanel);
end;
implementation
{$R *.dfm}
procedure TRemocaoInclusaoIngredientesView.AtivarAba(const Aba: TPanel);
begin
Aba.Color := $0082A901;
Aba.Font.Color := clWhite;
end;
procedure TRemocaoInclusaoIngredientesView.btnRemoverIngredientesClick(Sender: TObject);
begin
Self.AtivarAba(Self.btnRemoverIngredientes);
Self.DesativarAba(Self.btnIncluirIngredientes);
Self.Pages.ActivePageIndex := 0;
end;
procedure TRemocaoInclusaoIngredientesView.DesativarAba(const Aba: TPanel);
begin
Aba.Color := clSilver;
Aba.Font.Color := clTeal;
end;
procedure TRemocaoInclusaoIngredientesView.btnIncluirIngredientesClick(
Sender: TObject);
begin
Self.AtivarAba(Self.btnIncluirIngredientes);
Self.DesativarAba(Self.btnRemoverIngredientes);
Self.Pages.ActivePageIndex := 1;
end;
function TRemocaoInclusaoIngredientesView.Controlador(
const Controlador: IResposta): ITela;
begin
Self.FControlador := Controlador;
Result := Self;
end;
function TRemocaoInclusaoIngredientesView.Descarregar: ITela;
begin
Result := Self;
end;
function TRemocaoInclusaoIngredientesView.ExibirTela: Integer;
begin
Result := Self.ShowModal;
end;
function TRemocaoInclusaoIngredientesView.Modelo(
const Modelo: TModelo): ITela;
begin
Self.FComandaModelo := (Modelo as TComandaModelo);
Result := Self;
end;
function TRemocaoInclusaoIngredientesView.Preparar: ITela;
begin
Self.gIngredientes.DataSource :=
Self.FComandaModelo.DataSource('ingredientes');
Self.gIngredientesInseridos.DataSource :=
Self.FComandaModelo.DataSource('comaie');
Result := Self;
end;
procedure TRemocaoInclusaoIngredientesView.gIngredientesDblClick(
Sender: TObject);
var
_dataSet: TDataSet;
begin
_dataSet := Self.gIngredientes.DataSource.DataSet;
_dataSet.Edit;
if _dataSet.FieldByName('situacao').AsInteger = 1 then
_dataSet.FieldByName('situacao').AsInteger := 0
else
_dataSet.FieldByName('situacao').AsInteger := 1;
end;
procedure TRemocaoInclusaoIngredientesView.gIngredientesDrawColumnCell(
Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
var
_dataSet: TDataSet;
_grid: TJvDBUltimGrid;
begin
_dataSet := Self.gIngredientes.DataSource.DataSet;
_grid := Self.gIngredientes;
if _dataSet.FieldByName('situacao').AsInteger = 1 then
begin
_grid.Canvas.Font.Style := _grid.Canvas.Font.Style + [fsStrikeOut];
_grid.Canvas.Font.Color := clRed;
end
else
begin
_grid.Canvas.Font.Style := _grid.Canvas.Font.Style - [fsStrikeOut];
_grid.Canvas.Font.Color := clTeal;
end;
_grid.DefaultDrawDataCell(Rect, _grid.columns[datacol].field, State)
end;
procedure TRemocaoInclusaoIngredientesView.Panel6Click(Sender: TObject);
begin
{
if Self.EdtIngrediente.Text <> '' then
Self.FComandaModelo.InserirIngrediente(Self.EdtIngrediente.Text);
}
end;
procedure TRemocaoInclusaoIngredientesView.btnGravarClick(Sender: TObject);
begin
Self.FComandaModelo.RemoverIngredientes;
Self.FComandaModelo.SalvarComanda;
Self.ModalResult := mrOk;
end;
end.
|
unit CryptFrame;
{$mode objfpc}{$H+}
interface
uses
Classes, Controls, CryptMessage, Cryptor, Dialogs, ExtCtrls, FileUtil, Forms, Graphics,
Menus, StdCtrls, SysUtils, UserControl;
type
TFiles = pointer;
type
{ TCryptFrame }
TCryptFrame = class(TWinControl)
private
Crypt :TCrypt;
UserList :TUserList;
fFriendId :integer;
fLoadUser :boolean;
fScroll :TScrollBox;
fPanel :TPanel;
fMemo :TMemo;
fMyFace :TImage;
fFriendFace :TImage;
fSendBtn :TButton;
fAtachBtn :TButton;
// Работа с файлами
fFileOpen :TOpenDialog;
fFileList :TStringList;
fFileLabel :TLabel;
// Мои данные
fUserName :string;
// Данные собеседника
fFriendName :string;
// Список сообщений
fMsg :array of TMessages;
function GetFriendName :string;
function GetUserName :string;
procedure SetUserName (AValue :string);
procedure SetFriendName (AValue :string);
procedure MemoKeyUp (Sender :TObject; var Key :word; Shift :TShiftState);
procedure SendThisMsg (Sender :TObject);
procedure AttachFiles (Sender :TObject);
// Добавить сообщение
function Add (UserName, szText :string; Date :TDate; Avatar :TPicture;
Files :TFiles) :boolean;
public
constructor Create (AOwner :TComponent); override;
destructor Destroy; override;
// Количество сообщений
function Count :integer;
// Аватарки
procedure SetUserPic (FileName :string);
procedure SetFriendPic (FileName :string);
procedure Debug;
// Сообщения
procedure Send (szText :string; Date :TDateTime; Files :TFiles);
procedure Recv (szText :string; Date :TDateTime; Files :TFiles);
procedure AddFile ();
function LoadUser(Email, Password, FindUser :string):boolean;
published
property UserName :string read GetUserName write SetUserName;
property FriendName :string read GetFriendName write SetFriendName;
property FriendId :integer read fFriendId write fFriendId;
end;
implementation
{ TCryptFrame }
function TCryptFrame.GetFriendName :string;
begin
Result := fFriendName;
end;
function TCryptFrame.GetUserName :string;
begin
Result := fUserName;
end;
constructor TCryptFrame.Create (AOwner :TComponent);
var
i :integer;
Mail, Path :string;
begin
inherited Create (AOwner);
Crypt := TCrypt.Create;
fLoadUser := False;
{
Crypt.HostSmtp:= 'smtp.yandex.ru';
if Crypt.Pop3Login ('pop.yandex.ru', 'CryptoChat.test@yandex.ru', '130492') then
begin
Mail := Crypt.GetMail (1);
//ShowMessage ('Количество секций: ' + IntToStr (Crypt.GetCountSection (Mail)));
for i := 0 to Crypt.GetCountSection (Crypt.GetMail (1)) - 1 do
begin
//ShowMessage ('Секция - полностью: ' + Crypt.GetSection (Mail, i));
//ShowMessage ('Секция - заголовок: ' + Crypt.GetSectionHead (Mail, i));
//ShowMessage ('Секция - тело: ' + Crypt.GetSectionBody (Mail, i));
//ShowMessage ('Секция - имя вложения: ' + Crypt.GetSectionFileName (Mail, i));
Path:= ExtractFilePath (Application.ExeName) + 'Mail/' + Crypt.GetSectionFileName (Mail, i);
//ShowMessage(Path);
if Crypt.GetSectionFileName (Mail, i) <> '' then
Crypt.SaveSectionToFile (Path, Mail, i);
Crypt.KeySend('everhest1@yandex.ru');
end;
end;}
// Дополнительные компоненты
fScroll := TScrollBox.Create (self);
fScroll.Parent := self;
// Панелька
fPanel := TPanel.Create (self);
fPanel.Parent := self;
fPanel.Height := 100;
fPanel.Align := alBottom;
// Ввод текста
fMemo := TMemo.Create (fPanel);
fMemo.Parent := fPanel;
fMemo.OnKeyUp := @MemoKeyUp;
// Моя фотка
fMyFace := TImage.Create (fPanel);
fMyFace.Parent := fPanel;
// Фотка собеседника
fFriendFace := TImage.Create (fPanel);
fFriendFace.Parent := fPanel;
// Расположение
fScroll.Align := alClient;
fScroll.AutoScroll := True;
fMyFace.Top := 4;
fFriendFace.Top := 4;
fMyFace.Left := 4;
// Положение фотки собеседника
fFriendFace.Left := fPanel.Width - 70;
fFriendFace.Width := 64;
fFriendFace.Proportional := True;
fFriendFace.Anchors := [akRight, akTop];
fFriendFace.Stretch := True;
// Моего лица
fMyFace.Width := 64;
fMyFace.Stretch := True;
fMyFace.Proportional := True;
// Положение окна ввода текста
fMemo.Left := 74;
fMemo.Top := 4;
fMemo.Height := fPanel.Height - 38;
fMemo.Width := fPanel.Width - 152;
fMemo.Anchors := [akTop, akRight, akBottom, akLeft];
// Кнопочки
fSendBtn := TButton.Create (fPanel);
with fSendBtn do
begin
Parent := fPanel;
Top := fPanel.Height - 32;
Left := 74;
Width := 94;
Height := 26;
Caption := 'Отправить';
OnClick := @SendThisMsg;
end;
fAtachBtn := TButton.Create (fPanel);
with fAtachBtn do
begin
Parent := fPanel;
Top := fPanel.Height - 32;
Left := 174;
Width := 94;
Height := 26;
Caption := 'Прикрепить';
OnClick := @AttachFiles;
end;
// Список файлов
fFileList := TStringList.Create;
fFileLabel := TLabel.Create (fPanel);
with fFileLabel do
begin
Parent := fPanel;
Caption := 'Прикреплённые файлы (0)';
Top := fPanel.Height - 28;
Left := fMemo.Width + 74 - fFileLabel.Width;
Height := 26;
font.Color := clNavy;
Anchors := [akRight, akTop];
end;
Align := alClient;
end;
destructor TCryptFrame.Destroy;
begin
Crypt.Free;
fScroll.FreeOnRelease;
fPanel.FreeOnRelease;
fMemo.FreeOnRelease;
fMyFace.FreeOnRelease;
fFriendFace.FreeOnRelease;
fSendBtn.FreeOnRelease;
fAtachBtn.FreeOnRelease;
fFileList.Free;
fFileLabel.FreeOnRelease;
inherited Destroy;
end;
function TCryptFrame.Add (UserName, szText :string; Date :TDate;Avatar :TPicture;
Files :TFiles) :boolean;
begin
Result := True;
// Выделяем память
SetLength (fMsg, Length (fMsg) + 1);
fmsg[High (fMsg)] := TMessages.Create (fScroll);
fmsg[High (fMsg)].Parent := fScroll;
// Выставляем позицию сообщения
if High (fMsg) > 0 then
fmsg[High (fMsg)].Top := fmsg[High (fMsg) - 1].Top + fmsg[High (fMsg) - 1].Height
else
fmsg[High (fMsg)].Top := 0;
fmsg[High (fMsg)].Align := alTop;
fmsg[High (fMsg)].ReAlign;
// Содержимое диалога
fMsg[High (fMsg)].Date := Date;
fMsg[High (fMsg)].User := UserName;
fMsg[High (fMsg)].Text := szText;
fMsg[High (fMsg)].LoadImage (Avatar);
fScroll.VertScrollBar.Position := fScroll.VertScrollBar.Range; // ? Ошибка ?
end;
procedure TCryptFrame.SetUserName (AValue :string);
begin
fUserName := AValue;
end;
procedure TCryptFrame.SetFriendName (AValue :string);
begin
fFriendName := AValue;
end;
procedure TCryptFrame.MemoKeyUp (Sender :TObject;
var Key :word; Shift :TShiftState);
const
VK_RETURN = 13;
begin
if (ssCtrl in Shift) and (Key = VK_RETURN) then
SendThisMsg (Sender);
end;
procedure TCryptFrame.SendThisMsg (Sender :TObject);
begin
Send (fMemo.Text, now, nil);
fFileList.Clear;
fMemo.Clear;
end;
procedure TCryptFrame.AttachFiles (Sender :TObject);
begin
AddFile;
end;
function TCryptFrame.Count :integer;
begin
Result := High (fMsg) + 1;
end;
procedure TCryptFrame.SetUserPic (FileName :string);
begin
fMyFace.Picture.LoadFromFile (FileName);
end;
procedure TCryptFrame.SetFriendPic (FileName :string);
begin
fFriendFace.Picture.LoadFromFile (FileName);
end;
procedure TCryptFrame.Debug;
begin
ShowMessageFmt ('Range: %d \n Position: %d',
[fScroll.VertScrollBar.Range, fScroll.VertScrollBar.Position]);
end;
procedure TCryptFrame.Send (szText :string; Date :TDateTime; Files :TFiles);
begin
Add (UserName, szText, Date, fMyFace.Picture, Files);
fMsg[High (fMsg)].ReAlign;
end;
procedure TCryptFrame.Recv (szText :string; Date :TDateTime; Files :TFiles);
begin
Add (FriendName, szText, Date, fFriendFace.Picture, Files);
fMsg[High (fMsg)].ReAlign;
end;
procedure TCryptFrame.AddFile;
begin
fFileOpen := TOpenDialog.Create (self);
fFileOpen.Options := [ofAllowMultiSelect];
if fFileOpen.Execute then
fFileList.AddStrings (fFileOpen.Files);
fFileLabel.Caption := 'Прикреплённые файлы (' + IntToStr (fFileList.Count) + ')';
fFileOpen.Free;
end;
function TCryptFrame.LoadUser(Email, Password, FindUser :string):boolean;
var
i :integer;
begin
// Поиск пользователя по введённым данным
if not fLoadUser then
begin
UserList := TUserList.Create (Self);
if not UserList.LoginUser(EMail, Password) then
begin
raise Exception.Create('Проблема аутентификации в TCryptFrame.LoadUser');
Exit;
end
else
begin
fLoadUser:= True;
for i:= 0 to UserList.GetFriendCount do
if FindUser = (UserList.GetFriend(i).NickName + ' < ' +
UserList.GetFriend(i).Email + ' >') then
begin
friendId:= i;
ShowMessage(UserList.GetFriend(i).Email);
end;
end;
end;
Result := fLoadUser;
end;
end.
|
unit uResultList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvGlowButton, Vcl.StdCtrls,
Vcl.ExtCtrls, sButton, sPanel, Vcl.Buttons, sSpeedButton;
type
TFmResultList = class(TForm)
lbFailListView: TListBox;
Panel1: TPanel;
Label1: TLabel;
btnSaveFile: TsSpeedButton;
sPanel2: TsPanel;
btOk: TsButton;
btCancel: TsButton;
pnMain: TPanel;
SaveDialog1: TSaveDialog;
procedure btnSaveFileClick(Sender: TObject);
procedure btOkClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
m_bEdit : boolean;
end;
var
FmResultList: TFmResultList;
implementation
uses uMain, uUtil;
{$R *.dfm}
procedure TFmResultList.FormCreate(Sender: TObject);
begin
SaveDialog1.Filter := 'Text files (*.txt)|*.txt';
SaveDialog1.DefaultExt := '.txt';
end;
procedure TFmResultList.FormShow(Sender: TObject);
begin
if m_bEdit then
begin
Self.Caption := '센서별 계정 수정 결과';
btOk.Caption := '닫기';
btOk.ImageIndex := 9;
btCancel.Visible := False;
label1.Caption := Format('센서 계정변경 결과입니다. [성공: %s/ 실패: %s]'
,[FMain.lbIPListView.Items.Count.ToString, FMain.lbIPFailListView.Items.Count.ToString]);
end
else begin
Self.Caption := '센서별 로그인 결과';
btOk.Caption := '계정 변경';
btOk.ImageIndex := 11;
btCancel.Visible := True;
label1.Caption := Format( '센서 로그인 결과입니다. [성공: %s/ 실패: %s]' + #13#10 +
'[계정 변경] 버튼 클릭 시 로그인에 성공한 센서에 한해 ' + #13#10 +
'변경이 진행됩니다.'
,[FMain.lbIPListView.Count.ToString, FMain.lbIPFailListView.Items.Count.ToString]);
end;
end;
procedure TFmResultList.btCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFmResultList.btnSaveFileClick(Sender: TObject);
var
fileName : String;
begin
if SaveDialog1.Execute then
begin
FMain.GetIPList(FMain.m_Fail).SaveToFile(SaveDialog1.FileName);
end;
end;
procedure TFmResultList.btOkClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
end.
|
unit uDpMessageCommon;
interface
uses
uDpQueryCommon_a, uDpConst_h,
Classes, SyncObjs, Variants;
type
// ***************************************************************************
TDpParam = class(TDpParam_a)
private
FKey: string;
FValue: Variant;
protected
function getKey: string; override;
procedure setKey(const AKey: string); override;
function getValue: variant; override;
procedure setValue(const AValue: variant); override;
public
procedure EnQValElem(AElem: string); override;
function DeQValElem(out AElem: string): boolean; override;
function ValElemInQ(AElem: string): boolean; override;
end;
// ***************************************************************************
TDpMessage = class(TDpMessage_a)
private
FParams: TStringList;
FLock: TCriticalSection;
protected
function IndexOfParam(const AKey: string): integer;
function GetParam(AIndex: Integer): TDpParam_a; override;
function GetParamById(const AId: string): TDpParam_a; override;
function GetParamCount: Integer; override;
function GetContent: string;
procedure SetContent(const AValue: string);
public
constructor Create(AOwner: TComponent); override;
procedure Clear; override;
function Clone: TDpMessage_a; override;
function IsEqual(AReferenceMessage: TDpMessage_a): Boolean; override;
function GetParamValue(AKey: string): Variant; override;
procedure SetParamValue(AKey: string; AValue: Variant); override;
function Find(const AKey: string): boolean; override;
published
property MsgContent: string read GetContent write SetContent;
end;
implementation
//----------------------------------------------------------------------------
// N,PS:
function TDpMessage.getParamById(const AId: string): TDpParam_a;
var lIdx: integer;
begin
// no inherited: abstract.
if AId = '' then
raise EIntern.fire(self, 'Param = ""');
Result := nil;
FLock.Enter;
try
lIdx := FParams.IndexOf(AId);
if lIdx >= 0 then
Result := TDpParam(FParams.Objects[lIdx]);
finally
FLock.Leave;
end;
end;
//----------------------------------------------------------------------------
// N,PS:
function TDpMessage.IndexOfParam(const AKey: string): integer;
begin
// no inherited: abstract.
if AKey = '' then
raise EIntern.Fire(Self, 'AKey not specified in TDpMessage.SetParamValue()');
Result := FParams.IndexOf(AKey);
end;
...
//----------------------------------------------------------------------------
// N,PS:
procedure TDpMessage.Clear;
var i: integer;
begin
// no inherited: static
for i := 0 to FParams.Count - 1 do
FParams.Objects[i].Free;
FParams.Clear;
end;
{ TDpParam }
//----------------------------------------------------------------------------
// 16:58 N,PS:
procedure TDpParam.EnQValElem(AElem: string);
begin
// no inherited: abstract.
if not ((TVarData(Value).VType = varString) or
(TVarData(Value).VType = varEmpty) or
(TVarData(Value).VType = varNull)) then
raise EIntern.fire(self, 'can queue value elements only to params of type string, null or emtpy');
if AElem = '' then
raise EIntern.fire(self, 'can not queue empty elements');
Value := SeqStr(Value, CTermSymRequests, AElem);
end;
//----------------------------------------------------------------------------
// N,PS:
function TDpMessage.find(const AKey: string): boolean;
var lIdx: integer;
begin
// no inherited: abstract.
FLock.Enter;
try
lIdx := FParams.IndexOf(AKey);
Result := lIdx >= 0;
finally
FLock.Leave;
end;
end;
//----------------------------------------------------------------------------
// N,PS:
function TDpMessage.GetContent: string;
var i: integer;
lStream: TStringStream;
lWriter: TWriter;
begin
// no inherited (abstract)
lStream := TStringStream.Create('');
try
lWriter := TWriter.Create(lStream, 4096);
try
lWriter.WriteString(IntToStr(ParamCount));
for i := 0 to ParamCount - 1 do
lWriter.WriteString(
getIdentVarValuePairAsStringEncode(Param[i].Key, Param[i].Value));
finally
FreeAndNil(lWriter);
end;
Result := lStream.DataString; // data not available before writer is destroyed
finally
FreeAndNil(lStream);
end;
end;
end.
|
unit uTestuBaseCommand;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, uExceptions, uBase, SysUtils, uBaseCommand, uExceptionCodes;
type
// Test methods for class TBaseCommand
TestTBaseCommand = class(TTestCase)
strict private
FBaseCommand: TBaseCommand;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestExecute;
procedure TestExecute1;
procedure TestUnExecute;
end;
implementation
procedure TestTBaseCommand.SetUp;
begin
FBaseCommand := TBaseCommand.Create;
end;
procedure TestTBaseCommand.TearDown;
begin
FBaseCommand.Free;
FBaseCommand := nil;
end;
procedure TestTBaseCommand.TestExecute;
begin
SetUp;
try
FBaseCommand.Execute;
finally
TearDown;
end;
// TODO: Validate method results
end;
procedure TestTBaseCommand.TestExecute1;
var
aData: Variant;
begin
SetUp;
aData := 111;
try
FBaseCommand.Execute(aData);
finally
TearDown;
end;
end;
procedure TestTBaseCommand.TestUnExecute;
begin
SetUp;
try
FBaseCommand.UnExecute;
finally
TearDown;
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTBaseCommand.Suite);
end.
|
unit Vigilante.View.URLDialog;
interface
uses
Module.ValueObject.URL;
type
IURLDialog = interface(IInterface)
['{71A3B83A-172E-431E-BDDD-F10A14101B9A}']
function GetLabelURL: string;
function GetURLInformada: IURL;
procedure SetLabelURL(const Value: string);
procedure SetURLInformada(const Value: IURL);
function Executar: boolean;
property LabelURL: string read GetLabelURL write SetLabelURL;
property URLInformada: IURL read GetURLInformada write SetURLInformada;
end;
implementation
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is JclSysUtils.pas. }
{ }
{ The Initial Developer of the Original Code is documented in the accompanying }
{ help file JCL.chm. Portions created by these individuals are Copyright (C) of these individuals. }
{ }
{**************************************************************************************************}
{ }
{ Description: Various pointer and class related routines. }
{ Unit Owner: Jeroen Speldekamp }
{ }
{**************************************************************************************************}
{ }
{ This unit contains various routine for manipulating the math coprocessor. This includes such }
{ things as querying and setting the rounding precision of floating point operations and }
{ retrieving the coprocessor's status word. }
{ }
{ Unit owner: Eric S. Fisher }
{ Last modified: March 10, 2002 }
{ }
{**************************************************************************************************}
unit JclSysUtils;
{$I jcl.inc}
{$WEAKPACKAGEUNIT ON}
interface
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF MSWINDOWS}
Classes, TypInfo,
JclBase;
//--------------------------------------------------------------------------------------------------
// Pointer manipulation
//--------------------------------------------------------------------------------------------------
{$IFNDEF DELPHI5_UP}
procedure FreeAndNil(var Obj);
{$ENDIF DELPHI5_UP}
procedure GetAndFillMem(var P: Pointer; const Size: Integer; const Value: Byte);
procedure FreeMemAndNil(var P: Pointer);
function PCharOrNil(const S: AnsiString): PAnsiChar;
{$IFDEF SUPPORTS_WIDESTRING}
function PWideCharOrNil(const W: WideString): PWideChar;
{$ENDIF SUPPORTS_WIDESTRING}
function SizeOfMem(const APointer: Pointer): Integer;
//--------------------------------------------------------------------------------------------------
// Guards
//--------------------------------------------------------------------------------------------------
type
ISafeGuard = interface
function ReleaseItem: Pointer;
function GetItem: Pointer;
procedure FreeItem;
property Item: Pointer read GetItem;
end;
IMultiSafeGuard = interface (IInterface)
function AddItem(Item: Pointer): Pointer;
procedure FreeItem(Index: Integer);
function GetCount: Integer;
function GetItem(Index: Integer): Pointer;
function ReleaseItem(Index: Integer): Pointer;
property Count: Integer read GetCount;
property Items[Index: Integer]: Pointer read GetItem;
end;
function Guard(Mem: Pointer; out SafeGuard: ISafeGuard): Pointer; overload;
function Guard(Obj: TObject; out SafeGuard: ISafeGuard): TObject; overload;
function Guard(Mem: Pointer; var SafeGuard: IMultiSafeGuard): Pointer; overload;
function Guard(Obj: TObject; var SafeGuard: IMultiSafeGuard): TObject; overload;
function GuardGetMem(Size: Cardinal; out SafeGuard: ISafeGuard): Pointer;
function GuardAllocMem(Size: Cardinal; out SafeGuard: ISafeGuard): Pointer;
//--------------------------------------------------------------------------------------------------
// Binary search
//--------------------------------------------------------------------------------------------------
function SearchSortedList(List: TList; SortFunc: TListSortCompare; Item: Pointer;
Nearest: Boolean = False): Integer;
type
TUntypedSearchCompare = function(Param: Pointer; ItemIndex: Integer; const Value): Integer;
function SearchSortedUntyped(Param: Pointer; ItemCount: Integer; SearchFunc: TUntypedSearchCompare;
const Value; Nearest: Boolean = False): Integer;
//--------------------------------------------------------------------------------------------------
// Dynamic array sort and search routines
//--------------------------------------------------------------------------------------------------
type
TDynArraySortCompare = function (Item1, Item2: Pointer): Integer;
procedure SortDynArray(const ArrayPtr: Pointer; ElementSize: Cardinal; SortFunc: TDynArraySortCompare);
// Usage: SortDynArray(Array, SizeOf(Array[0]), SortFunction);
function SearchDynArray(const ArrayPtr: Pointer; ElementSize: Cardinal; SortFunc: TDynArraySortCompare;
ValuePtr: Pointer; Nearest: Boolean = False): Integer;
// Usage: SearchDynArray(Array, SizeOf(Array[0]), SortFunction, @SearchedValue);
{ Various compare functions for basic types }
function DynArrayCompareByte(Item1, Item2: Pointer): Integer;
function DynArrayCompareShortInt(Item1, Item2: Pointer): Integer;
function DynArrayCompareWord(Item1, Item2: Pointer): Integer;
function DynArrayCompareSmallInt(Item1, Item2: Pointer): Integer;
function DynArrayCompareInteger(Item1, Item2: Pointer): Integer;
function DynArrayCompareCardinal(Item1, Item2: Pointer): Integer;
function DynArrayCompareInt64(Item1, Item2: Pointer): Integer;
function DynArrayCompareSingle(Item1, Item2: Pointer): Integer;
function DynArrayCompareDouble(Item1, Item2: Pointer): Integer;
function DynArrayCompareExtended(Item1, Item2: Pointer): Integer;
function DynArrayCompareFloat(Item1, Item2: Pointer): Integer;
function DynArrayCompareAnsiString(Item1, Item2: Pointer): Integer;
function DynArrayCompareAnsiText(Item1, Item2: Pointer): Integer;
function DynArrayCompareString(Item1, Item2: Pointer): Integer;
function DynArrayCompareText(Item1, Item2: Pointer): Integer;
//--------------------------------------------------------------------------------------------------
// Object lists
//--------------------------------------------------------------------------------------------------
procedure ClearObjectList(List: TList);
procedure FreeObjectList(var List: TList);
//--------------------------------------------------------------------------------------------------
// Reference memory stream
//--------------------------------------------------------------------------------------------------
type
TJclReferenceMemoryStream = class (TCustomMemoryStream)
public
constructor Create(const Ptr: Pointer; Size: Longint);
function Write(const Buffer; Count: Longint): Longint; override;
end;
//--------------------------------------------------------------------------------------------------
// replacement for the C ternary conditional operator ? :
//--------------------------------------------------------------------------------------------------
function Iff(const Condition: Boolean; const TruePart, FalsePart: string): string; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Char): Char; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Byte): Byte; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Integer): Integer; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Cardinal): Cardinal; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Float): Float; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Boolean): Boolean; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Pointer): Pointer; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Int64): Int64; overload;
//--------------------------------------------------------------------------------------------------
// Classes information and manipulation
//--------------------------------------------------------------------------------------------------
type
EJclVMTError = class (EJclError);
//--------------------------------------------------------------------------------------------------
// Virtual Methods
//--------------------------------------------------------------------------------------------------
function GetVirtualMethodCount(AClass: TClass): Integer;
function GetVirtualMethod(AClass: TClass; const Index: Integer): Pointer;
{$IFDEF MSWINDOWS}
procedure SetVirtualMethod(AClass: TClass; const Index: Integer; const Method: Pointer);
{$ENDIF MSWINDOWS}
//--------------------------------------------------------------------------------------------------
// Dynamic Methods
//--------------------------------------------------------------------------------------------------
type
TDynamicIndexList = array [0..MaxInt div 16] of Word;
PDynamicIndexList = ^TDynamicIndexList;
TDynamicAddressList = array [0..MaxInt div 16] of Pointer;
PDynamicAddressList = ^TDynamicAddressList;
function GetDynamicMethodCount(AClass: TClass): Integer;
function GetDynamicIndexList(AClass: TClass): PDynamicIndexList;
function GetDynamicAddressList(AClass: TClass): PDynamicAddressList;
function HasDynamicMethod(AClass: TClass; Index: Integer): Boolean;
function GetDynamicMethod(AClass: TClass; Index: Integer): Pointer;
{ init table methods }
function GetInitTable(AClass: TClass): PTypeInfo;
{ field table methods }
type
PFieldEntry = ^TFieldEntry;
TFieldEntry = packed record
OffSet: Integer;
IDX: Word;
Name: ShortString;
end;
PFieldClassTable = ^TFieldClassTable;
TFieldClassTable = packed record
Count: Smallint;
Classes: array [0..8191] of ^TPersistentClass;
end;
PFieldTable = ^TFieldTable;
TFieldTable = packed record
EntryCount: Word;
FieldClassTable: PFieldClassTable;
FirstEntry: TFieldEntry;
{Entries: array [1..65534] of TFieldEntry;}
end;
function GetFieldTable(AClass: TClass): PFieldTable;
{ method table }
type
PMethodEntry = ^TMethodEntry;
TMethodEntry = packed record
EntrySize: Word;
Address: Pointer;
Name: ShortString;
end;
PMethodTable = ^TMethodTable;
TMethodTable = packed record
Count: Word;
FirstEntry: TMethodEntry;
{Entries: array [1..65534] of TMethodEntry;}
end;
function GetMethodTable(AClass: TClass): PMethodTable;
function GetMethodEntry(MethodTable: PMethodTable; Index: Integer): PMethodEntry;
//--------------------------------------------------------------------------------------------------
// Class Parent
//--------------------------------------------------------------------------------------------------
{$IFDEF MSWINDOWS}
procedure SetClassParent(AClass: TClass; NewClassParent: TClass);
{$ENDIF MSWINDOWS}
function GetClassParent(AClass: TClass): TClass;
function IsClass(Address: Pointer): Boolean;
function IsObject(Address: Pointer): Boolean;
//--------------------------------------------------------------------------------------------------
// Interface information
//--------------------------------------------------------------------------------------------------
function GetImplementorOfInterface(const I: IInterface): TObject;
{ TODO -cDOC : Original code by Hallvard Vassbotn }
//--------------------------------------------------------------------------------------------------
// Numeric formatting routines
//--------------------------------------------------------------------------------------------------
function IntToStrZeroPad(Value, Count: Integer): AnsiString;
//--------------------------------------------------------------------------------------------------
// Loading of modules (DLLs)
//--------------------------------------------------------------------------------------------------
{$IFDEF MSWINDOWS}
type
TModuleHandle = HINST;
const
INVALID_MODULEHANDLE_VALUE = TModuleHandle(0);
function LoadModule(var Module: TModuleHandle; FileName: string): Boolean;
function LoadModuleEx(var Module: TModuleHandle; FileName: string; Flags: Cardinal): Boolean;
procedure UnloadModule(var Module: TModuleHandle);
function GetModuleSymbol(Module: TModuleHandle; SymbolName: string): Pointer;
function GetModuleSymbolEx(Module: TModuleHandle; SymbolName: string; var Accu: Boolean): Pointer;
function ReadModuleData(Module: TModuleHandle; SymbolName: string; var Buffer; Size: Cardinal): Boolean;
function WriteModuleData(Module: TModuleHandle; SymbolName: string; var Buffer; Size: Cardinal): Boolean;
{$ENDIF MSWINDOWS}
//==================================================================================================
// Conversion Utilities
//==================================================================================================
type
EJclConversionError = class (EJclError);
function StrToBoolean(const S: string): Boolean;
function IntToBool(I: Integer): Boolean;
function BoolToInt(B: Boolean): Integer;
implementation
uses
SysUtils,
JclResources, JclStrings;
//==================================================================================================
// Pointer manipulation
//==================================================================================================
{$IFNDEF DELPHI5_UP}
procedure FreeAndNil(var Obj);
var
O: TObject;
begin
O := TObject(Obj);
Pointer(Obj) := nil;
O.Free;
end;
{$ENDIF DELPHI5_UP}
//--------------------------------------------------------------------------------------------------
procedure GetAndFillMem(var P: Pointer; const Size: Integer; const Value: Byte);
begin
GetMem(P, Size);
FillChar(P^, Size, Value);
end;
//--------------------------------------------------------------------------------------------------
procedure FreeMemAndNil(var P: Pointer);
var
Q: Pointer;
begin
Q := P;
P := nil;
FreeMem(Q);
end;
//--------------------------------------------------------------------------------------------------
function PCharOrNil(const S: AnsiString): PAnsiChar;
begin
if Length(S) = 0 then
Result := nil
else
Result := PAnsiChar(S);
end;
//--------------------------------------------------------------------------------------------------
{$IFDEF SUPPORTS_WIDESTRING}
function PWideCharOrNil(const W: WideString): PWideChar;
begin
if Length(W) = 0 then
Result := nil
else
Result := PWideChar(W);
end;
{$ENDIF SUPPORTS_WIDESTRING}
//--------------------------------------------------------------------------------------------------
type
PUsed = ^TUsed;
TUsed = record
SizeFlags: Integer;
end;
const
cThisUsedFlag = 2;
cPrevFreeFlag = 1;
cFillerFlag = Integer($80000000);
cFlags = cThisUsedFlag or cPrevFreeFlag or cFillerFlag;
function SizeOfMem(const APointer: Pointer): Integer;
var
U: PUsed;
begin
if IsMemoryManagerSet then
Result:= -1
else
begin
Result := 0;
if APointer <> nil then
begin
U := APointer;
U := PUsed(PChar(U) - SizeOf(TUsed));
if (U.SizeFlags and cThisUsedFlag) <> 0 then
Result := (U.SizeFlags) and (not cFlags - SizeOf(TUsed));
end;
end;
end;
//==================================================================================================
// Guards
//==================================================================================================
type
TSafeGuard = class (TInterfacedObject, ISafeGuard)
private
FItem: Pointer;
public
constructor Create(Mem: Pointer);
destructor Destroy; override;
function ReleaseItem: Pointer;
function GetItem: Pointer;
procedure FreeItem; virtual;
end;
TObjSafeGuard = class (TSafeGuard, ISafeGuard)
public
constructor Create(Obj: TObject);
procedure FreeItem; override;
end;
TMultiSafeGuard = class (TInterfacedObject, IMultiSafeGuard)
private
FItems: TList;
public
constructor Create;
destructor Destroy; override;
function AddItem(Mem: Pointer): Pointer;
procedure FreeItem(Index: Integer); virtual;
function GetCount: Integer;
function GetItem(Index: Integer): Pointer;
function ReleaseItem(Index: Integer): Pointer;
end;
TObjMultiSafeGuard = class (TMultiSafeGuard, IMultiSafeGuard)
public
procedure FreeItem(Index: Integer); override;
end;
//--------------------------------------------------------------------------------------------------
// TSafeGuard
//--------------------------------------------------------------------------------------------------
constructor TSafeGuard.Create(Mem: Pointer);
begin
FItem := Mem;
end;
//--------------------------------------------------------------------------------------------------
destructor TSafeGuard.Destroy;
begin
FreeItem;
inherited Destroy;
end;
//--------------------------------------------------------------------------------------------------
function TSafeGuard.ReleaseItem: Pointer;
begin
Result := FItem;
FItem := nil;
end;
//--------------------------------------------------------------------------------------------------
function TSafeGuard.GetItem: Pointer;
begin
Result := FItem;
end;
//--------------------------------------------------------------------------------------------------
procedure TSafeGuard.FreeItem;
begin
if FItem <> nil then
FreeMem(FItem);
FItem := nil;
end;
//--------------------------------------------------------------------------------------------------
// TObjSafeGuard
//--------------------------------------------------------------------------------------------------
constructor TObjSafeGuard.Create(Obj: TObject);
begin
inherited Create(Obj);
end;
//--------------------------------------------------------------------------------------------------
procedure TObjSafeGuard.FreeItem;
begin
if FItem <> nil then
begin
TObject(FItem).Free;
FItem := nil;
end;
end;
//--------------------------------------------------------------------------------------------------
// TMultiSafeGuard
//--------------------------------------------------------------------------------------------------
function TMultiSafeGuard.AddItem(Mem: Pointer): Pointer;
begin
Result := Mem;
FItems.Add(Mem);
end;
//--------------------------------------------------------------------------------------------------
constructor TMultiSafeGuard.Create;
begin
inherited Create;
FItems := TList.Create;
end;
//--------------------------------------------------------------------------------------------------
destructor TMultiSafeGuard.Destroy;
var
I: Integer;
begin
for I := FItems.Count - 1 downto 0 do FreeItem(I);
FItems.Free;
inherited Destroy;
end;
//--------------------------------------------------------------------------------------------------
procedure TMultiSafeGuard.FreeItem(Index: Integer);
begin
FreeMem(FItems[Index]);
FItems.Delete(Index);
end;
//--------------------------------------------------------------------------------------------------
function TMultiSafeGuard.GetCount: Integer;
begin
Result := FItems.Count;
end;
//--------------------------------------------------------------------------------------------------
function TMultiSafeGuard.GetItem(Index: Integer): Pointer;
begin
Result := FItems[Index];
end;
//--------------------------------------------------------------------------------------------------
function TMultiSafeGuard.ReleaseItem(Index: Integer): Pointer;
begin
Result := FItems[Index];
FItems.Delete(Index);
end;
//--------------------------------------------------------------------------------------------------
function Guard(Mem: Pointer; var SafeGuard: IMultiSafeGuard): Pointer; overload;
begin
if SafeGuard = nil then
SafeGuard := TMultiSafeGuard.Create;
Result := SafeGuard.AddItem(Mem);
end;
//--------------------------------------------------------------------------------------------------
// TObjMultiSafeGuard
//--------------------------------------------------------------------------------------------------
procedure TObjMultiSafeGuard.FreeItem(Index: Integer);
begin
TObject(FItems[Index]).Free;
FItems.Delete(Index);
end;
//--------------------------------------------------------------------------------------------------
function Guard(Obj: TObject; var SafeGuard: IMultiSafeGuard): TObject; overload;
begin
if SafeGuard = nil then
SafeGuard := TObjMultiSafeGuard.Create;
Result := SafeGuard.AddItem(Obj);
end;
//--------------------------------------------------------------------------------------------------
function Guard(Mem: Pointer; out SafeGuard: ISafeGuard): Pointer; overload;
begin
Result := Mem;
SafeGuard := TSafeGuard.Create(Mem);
end;
//--------------------------------------------------------------------------------------------------
function Guard(Obj: TObject; out SafeGuard: ISafeGuard): TObject; overload;
begin
Result := Obj;
SafeGuard := TObjSafeGuard.Create(Obj);
end;
//--------------------------------------------------------------------------------------------------
function GuardGetMem(Size: Cardinal; out SafeGuard: ISafeGuard): Pointer;
begin
GetMem(Result, Size);
Guard(Result, SafeGuard);
end;
//--------------------------------------------------------------------------------------------------
function GuardAllocMem(Size: Cardinal; out SafeGuard: ISafeGuard): Pointer;
begin
Result := AllocMem(Size);
Guard(Result, SafeGuard);
end;
//==================================================================================================
// Binary search
//==================================================================================================
function SearchSortedList(List: TList; SortFunc: TListSortCompare; Item: Pointer; Nearest: Boolean): Integer;
var
L, H, I, C: Integer;
B: Boolean;
begin
Result := -1;
if List <> nil then
begin
L := 0;
H := List.Count - 1;
B := False;
while L <= H do
begin
I := (L + H) shr 1;
C := SortFunc(List.List^[I], Item);
if C < 0 then
L := I + 1
else
begin
H := I - 1;
if C = 0 then
begin
B := True;
L := I;
end;
end;
end;
if B then
Result := L
else
if Nearest and (H >= 0) then
Result := H;
end;
end;
//--------------------------------------------------------------------------------------------------
function SearchSortedUntyped(Param: Pointer; ItemCount: Integer; SearchFunc: TUntypedSearchCompare;
const Value; Nearest: Boolean): Integer;
var
L, H, I, C: Integer;
B: Boolean;
begin
Result := -1;
if ItemCount > 0 then
begin
L := 0;
H := ItemCount - 1;
B := False;
while L <= H do
begin
I := (L + H) shr 1;
C := SearchFunc(Param, I, Value);
if C < 0 then
L := I + 1
else
begin
H := I - 1;
if C = 0 then
begin
B := True;
L := I;
end;
end;
end;
if B then
Result := L
else
if Nearest and (H >= 0) then
Result := H;
end;
end;
//==================================================================================================
// Dynamic array sort and search routines
//==================================================================================================
procedure SortDynArray(const ArrayPtr: Pointer; ElementSize: Cardinal; SortFunc: TDynArraySortCompare);
var
TempBuf: TDynByteArray;
function ArrayItemPointer(Item: Integer): Pointer;
begin
Result := Pointer(Cardinal(ArrayPtr) + (Cardinal(Item) * ElementSize));
end;
procedure QuickSort(L, R: Integer);
var
I, J, T: Integer;
P, IPtr, JPtr: Pointer;
begin
repeat
I := L;
J := R;
P := ArrayItemPointer((L + R) shr 1);
repeat
while SortFunc(ArrayItemPointer(I), P) < 0 do
Inc(I);
while SortFunc(ArrayItemPointer(J), P) > 0 do
Dec(J);
if I <= J then
begin
IPtr := ArrayItemPointer(I);
JPtr := ArrayItemPointer(J);
case ElementSize of
SizeOf(Byte):
begin
T := PByte(IPtr)^;
PByte(IPtr)^ := PByte(JPtr)^;
PByte(JPtr)^ := T;
end;
SizeOf(Word):
begin
T := PWord(IPtr)^;
PWord(IPtr)^ := PWord(JPtr)^;
PWord(JPtr)^ := T;
end;
SizeOf(Integer):
begin
T := PInteger(IPtr)^;
PInteger(IPtr)^ := PInteger(JPtr)^;
PInteger(JPtr)^ := T;
end;
else
Move(IPtr^, TempBuf[0], ElementSize);
Move(JPtr^, IPtr^, ElementSize);
Move(TempBuf[0], JPtr^, ElementSize);
end;
if P = IPtr then
P := JPtr
else
if P = JPtr then
P := IPtr;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then
QuickSort(L, J);
L := I;
until I >= R;
end;
begin
if ArrayPtr <> nil then
begin
SetLength(TempBuf, ElementSize);
QuickSort(0, PInteger(Cardinal(ArrayPtr) - 4)^ - 1);
end;
end;
//--------------------------------------------------------------------------------------------------
function SearchDynArray(const ArrayPtr: Pointer; ElementSize: Cardinal; SortFunc: TDynArraySortCompare;
ValuePtr: Pointer; Nearest: Boolean): Integer;
var
L, H, I, C: Integer;
B: Boolean;
begin
Result := -1;
if ArrayPtr <> nil then
begin
L := 0;
H := PInteger(Cardinal(ArrayPtr) - 4)^ - 1;
B := False;
while L <= H do
begin
I := (L + H) shr 1;
C := SortFunc(Pointer(Cardinal(ArrayPtr) + (Cardinal(I) * ElementSize)), ValuePtr);
if C < 0 then
L := I + 1
else
begin
H := I - 1;
if C = 0 then
begin
B := True;
L := I;
end;
end;
end;
if B then
Result := L
else
if Nearest and (H >= 0) then
Result := H;
end;
end;
//--------------------------------------------------------------------------------------------------
{ Various compare functions for basic types }
function DynArrayCompareByte(Item1, Item2: Pointer): Integer;
begin
Result := PByte(Item1)^ - PByte(Item2)^;
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareShortInt(Item1, Item2: Pointer): Integer;
begin
Result := PShortInt(Item1)^ - PShortInt(Item2)^;
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareWord(Item1, Item2: Pointer): Integer;
begin
Result := PWord(Item1)^ - PWord(Item2)^;
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareSmallInt(Item1, Item2: Pointer): Integer;
begin
Result := PSmallInt(Item1)^ - PSmallInt(Item2)^;
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareInteger(Item1, Item2: Pointer): Integer;
begin
Result := PInteger(Item1)^ - PInteger(Item2)^;
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareCardinal(Item1, Item2: Pointer): Integer;
begin
Result := PInteger(Item1)^ - PInteger(Item2)^;
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareInt64(Item1, Item2: Pointer): Integer;
begin
Result := PInt64(Item1)^ - PInt64(Item2)^;
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareSingle(Item1, Item2: Pointer): Integer;
begin
if PSingle(Item1)^ < PSingle(Item2)^ then
Result := -1
else
if PSingle(Item1)^ > PSingle(Item2)^ then
Result := 1
else
Result := 0;
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareDouble(Item1, Item2: Pointer): Integer;
begin
if PDouble(Item1)^ < PDouble(Item2)^ then
Result := -1
else
if PDouble(Item1)^ > PDouble(Item2)^ then
Result := 1
else
Result := 0;
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareExtended(Item1, Item2: Pointer): Integer;
begin
if PExtended(Item1)^ < PExtended(Item2)^ then
Result := -1
else
if PExtended(Item1)^ > PExtended(Item2)^ then
Result := 1
else
Result := 0;
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareFloat(Item1, Item2: Pointer): Integer;
begin
if PFloat(Item1)^ < PFloat(Item2)^ then
Result := -1
else
if PFloat(Item1)^ > PFloat(Item2)^ then
Result := 1
else
Result := 0;
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareAnsiString(Item1, Item2: Pointer): Integer;
begin
Result := AnsiCompareStr(PAnsiString(Item1)^, PAnsiString(Item2)^);
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareAnsiText(Item1, Item2: Pointer): Integer;
begin
Result := AnsiCompareText(PAnsiString(Item1)^, PAnsiString(Item2)^);
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareString(Item1, Item2: Pointer): Integer;
begin
Result := CompareStr(PAnsiString(Item1)^, PAnsiString(Item2)^);
end;
//--------------------------------------------------------------------------------------------------
function DynArrayCompareText(Item1, Item2: Pointer): Integer;
begin
Result := CompareText(PAnsiString(Item1)^, PAnsiString(Item2)^);
end;
//==================================================================================================
// Object lists
//==================================================================================================
procedure ClearObjectList(List: TList);
var
I: Integer;
begin
if List <> nil then
begin
for I := 0 to List.Count - 1 do
begin
if List[I] <> nil then
begin
if TObject(List[I]) is TList then
begin
// recursively delete TList sublists
ClearObjectList(TList(List[I]));
end;
TObject(List[I]).Free;
List[I] := nil;
end;
end;
List.Clear;
end;
end;
//--------------------------------------------------------------------------------------------------
procedure FreeObjectList(var List: TList);
begin
if List <> nil then
begin
ClearObjectList(List);
FreeAndNil(List);
end;
end;
//==================================================================================================
// TJclReferenceMemoryStream
//==================================================================================================
constructor TJclReferenceMemoryStream.Create(const Ptr: Pointer; Size: Longint);
begin
Assert(not IsBadReadPtr(Ptr, Size));
inherited Create;
SetPointer(Ptr, Size);
end;
//--------------------------------------------------------------------------------------------------
function TJclReferenceMemoryStream.Write(const Buffer; Count: Longint): Longint;
begin
raise EJclError.CreateResRec(@RsCannotWriteRefStream);
end;
//==================================================================================================
// replacement for the C distfix operator ? :
//==================================================================================================
function Iff(const Condition: Boolean; const TruePart, FalsePart: string): string; overload;
begin
if Condition then
Result := TruePart
else
Result := FalsePart;
end;
//--------------------------------------------------------------------------------------------------
function Iff(const Condition: Boolean; const TruePart, FalsePart: Char): Char; overload;
begin
if Condition then
Result := TruePart
else
Result := FalsePart;
end;
//--------------------------------------------------------------------------------------------------
function Iff(const Condition: Boolean; const TruePart, FalsePart: Byte): Byte; overload;
begin
if Condition then
Result := TruePart
else
Result := FalsePart;
end;
//--------------------------------------------------------------------------------------------------
function Iff(const Condition: Boolean; const TruePart, FalsePart: Integer): Integer; overload;
begin
if Condition then
Result := TruePart
else
Result := FalsePart;
end;
//--------------------------------------------------------------------------------------------------
function Iff(const Condition: Boolean; const TruePart, FalsePart: Cardinal): Cardinal; overload;
begin
if Condition then
Result := TruePart
else
Result := FalsePart;
end;
//--------------------------------------------------------------------------------------------------
function Iff(const Condition: Boolean; const TruePart, FalsePart: Float): Float; overload;
begin
if Condition then
Result := TruePart
else
Result := FalsePart;
end;
//--------------------------------------------------------------------------------------------------
function Iff(const Condition: Boolean; const TruePart, FalsePart: Boolean): Boolean; overload;
begin
if Condition then
Result := TruePart
else
Result := FalsePart;
end;
//--------------------------------------------------------------------------------------------------
function Iff(const Condition: Boolean; const TruePart, FalsePart: Pointer): Pointer; overload;
begin
if Condition then
Result := TruePart
else
Result := FalsePart;
end;
//--------------------------------------------------------------------------------------------------
function Iff(const Condition: Boolean; const TruePart, FalsePart: Int64): Int64; overload;
begin
if Condition then
Result := TruePart
else
Result := FalsePart;
end;
//==================================================================================================
// Classes information and manipulation
//==================================================================================================
//==================================================================================================
// Virtual Methods
//==================================================================================================
function GetVirtualMethodCount(AClass: TClass): Integer;
var
BeginVMT: Longint;
EndVMT: Longint;
TablePointer: Longint;
I: Integer;
begin
BeginVMT := Longint(AClass);
// Scan the offset entries in the class table for the various fields,
// namely vmtIntfTable, vmtAutoTable, ..., vmtDynamicTable
// The last entry is always the vmtClassName, so stop once we got there
// After the last virtual method there is one of these entries.
EndVMT := PLongint(Longint(AClass) + vmtClassName)^;
// Set iterator to first item behind VMT table pointer
I := vmtSelfPtr + SizeOf(Pointer);
repeat
TablePointer := PLongint(Longint(AClass) + I)^;
if (TablePointer <> 0) and (TablePointer >= BeginVMT) and
(TablePointer < EndVMT) then
EndVMT := Longint(TablePointer);
Inc(I, SizeOf(Pointer));
until I >= vmtClassName;
Result := (EndVMT - BeginVMT) div SizeOf(Pointer);
end;
//--------------------------------------------------------------------------------------------------
function GetVirtualMethod(AClass: TClass; const Index: Integer): Pointer;
begin
Result := PPointer(Integer(AClass) + Index * SizeOf(Pointer))^;
end;
//--------------------------------------------------------------------------------------------------
{$IFDEF MSWINDOWS}
procedure SetVirtualMethod(AClass: TClass; const Index: Integer; const Method: Pointer);
var
WrittenBytes: DWORD;
PatchAddress: Pointer;
begin
PatchAddress := PPointer(Integer(AClass) + Index * SizeOf(Pointer))^;
//! StH: WriteProcessMemory IMO is not exactly the politically correct approach;
// better VirtualProtect, direct patch, VirtualProtect
if not WriteProcessMemory(GetCurrentProcess, PatchAddress, {@}Method,
SizeOf(Pointer), WrittenBytes) then
raise EJclVMTError.CreateResRecFmt(@RsVMTMemoryWriteError, [SysErrorMessage(GetLastError)]);
if WrittenBytes <> SizeOf(Pointer) then
raise EJclVMTError.CreateResRecFmt(@RsVMTMemoryWriteError, [IntToStr(WrittenBytes)]);
// make sure that everything keeps working in a dual processor setting
FlushInstructionCache(GetCurrentProcess, PatchAddress, SizeOf(Pointer));
end;
{$ENDIF MSWINDOWS}
//==================================================================================================
// Dynamic Methods
//==================================================================================================
type
TvmtDynamicTable = packed record
Count: Word;
{IndexList: array [1..Count] of Word;
AddressList: array [1..Count] of Pointer;}
end;
//--------------------------------------------------------------------------------------------------
function GetDynamicMethodCount(AClass: TClass): Integer; assembler;
asm
MOV EAX, [EAX].vmtDynamicTable
TEST EAX, EAX
JE @@Exit
MOVZX EAX, WORD PTR [EAX]
@@Exit:
end;
//--------------------------------------------------------------------------------------------------
function GetDynamicIndexList(AClass: TClass): PDynamicIndexList; assembler;
asm
MOV EAX, [EAX].vmtDynamicTable
ADD EAX, 2
end;
//--------------------------------------------------------------------------------------------------
function GetDynamicAddressList(AClass: TClass): PDynamicAddressList; assembler;
asm
MOV EAX, [EAX].vmtDynamicTable
MOVZX EDX, Word ptr [EAX]
ADD EAX, EDX
ADD EAX, EDX
ADD EAX, 2
end;
//--------------------------------------------------------------------------------------------------
function HasDynamicMethod(AClass: TClass; Index: Integer): Boolean; assembler;
// Mainly copied from System.GetDynaMethod
asm
{ -> EAX vmt of class }
{ DX dynamic method index }
PUSH EDI
XCHG EAX, EDX
JMP @@HaveVMT
@@OuterLoop:
MOV EDX, [EDX]
@@HaveVMT:
MOV EDI, [EDX].vmtDynamicTable
TEST EDI, EDI
JE @@Parent
MOVZX ECX, WORD PTR [EDI]
PUSH ECX
ADD EDI,2
REPNE SCASW
JE @@Found
POP ECX
@@Parent:
MOV EDX,[EDX].vmtParent
TEST EDX,EDX
JNE @@OuterLoop
MOV EAX, 0
JMP @@Exit
@@Found:
POP EAX
MOV EAX, 1
@@Exit:
POP EDI
end;
//--------------------------------------------------------------------------------------------------
function GetDynamicMethod(AClass: TClass; Index: Integer): Pointer; assembler;
asm
CALL System.@FindDynaClass
end;
//==================================================================================================
// Interface Table
//==================================================================================================
function GetInitTable(AClass: TClass): PTypeInfo; assembler;
asm
MOV EAX, [EAX].vmtInitTable
end;
//--------------------------------------------------------------------------------------------------
function GetFieldTable(AClass: TClass): PFieldTable; assembler;
asm
MOV EAX, [EAX].vmtFieldTable
end;
//--------------------------------------------------------------------------------------------------
function GetMethodTable(AClass: TClass): PMethodTable; assembler;
asm
MOV EAX, [EAX].vmtMethodTable
end;
//--------------------------------------------------------------------------------------------------
function GetMethodEntry(MethodTable: PMethodTable; Index: Integer): PMethodEntry;
begin
Result := Pointer(Cardinal(MethodTable) + 2);
for Index := Index downto 1 do
Inc(Cardinal(Result), Result^.EntrySize);
end;
//==================================================================================================
// Class Parent methods
//==================================================================================================
{$IFDEF MSWINDOWS}
procedure SetClassParent(AClass: TClass; NewClassParent: TClass);
var
WrittenBytes: DWORD;
PatchAddress: Pointer;
begin
PatchAddress := PPointer(Integer(AClass) + vmtParent)^;
//! StH: WriteProcessMemory IMO is not exactly the politically correct approach;
// better VirtualProtect, direct patch, VirtualProtect
if not WriteProcessMemory(GetCurrentProcess, PatchAddress, @NewClassParent,
SizeOf(Pointer), WrittenBytes) then
raise EJclVMTError.CreateResRecFmt(@RsVMTMemoryWriteError, [SysErrorMessage(GetLastError)]);
if WrittenBytes <> SizeOf(Pointer) then
raise EJclVMTError.CreateResRecFmt(@RsVMTMemoryWriteError, [IntToStr(WrittenBytes)]);
// make sure that everything keeps working in a dual processor setting
FlushInstructionCache(GetCurrentProcess, PatchAddress, SizeOf(Pointer));
end;
{$ENDIF MSWINDOWS}
//--------------------------------------------------------------------------------------------------
function GetClassParent(AClass: TClass): TClass; assembler;
asm
MOV EAX, [AClass].vmtParent
TEST Result, EAX
JE @@Exit
MOV EAX, [EAX]
@@Exit:
end;
//--------------------------------------------------------------------------------------------------
function IsClass(Address: Pointer): Boolean; assembler;
asm
CMP Address, Address.vmtSelfPtr
JNZ @False
MOV Result, True
JMP @Exit
@False:
MOV Result, False
@Exit:
end;
//--------------------------------------------------------------------------------------------------
function IsObject(Address: Pointer): Boolean; assembler;
asm
// or IsClass(Pointer(Address^));
MOV EAX, [Address]
CMP EAX, EAX.vmtSelfPtr
JNZ @False
MOV Result, True
JMP @Exit
@False:
MOV Result, False
@Exit:
end;
//==================================================================================================
// Interface information
//==================================================================================================
function GetImplementorOfInterface(const I: IInterface): TObject;
{ TODO -cTesting : Check the implemetation for any further version of compiler }
const
AddByte = $04244483; // opcode for ADD DWORD PTR [ESP+4], Shortint
AddLong = $04244481; // opcode for ADD DWORD PTR [ESP+4], Longint
type
PAdjustSelfThunk = ^TAdjustSelfThunk;
TAdjustSelfThunk = packed record
case AddInstruction: LongInt of
AddByte: (AdjustmentByte: ShortInt);
AddLong: (AdjustmentLong: LongInt);
end;
PInterfaceMT = ^TInterfaceMT;
TInterfaceMT = packed record
QueryInterfaceThunk: PAdjustSelfThunk;
end;
TInterfaceRef = ^PInterfaceMT;
var
QueryInterfaceThunk: PAdjustSelfThunk;
begin
try
Result := Pointer(I);
if Assigned(Result) then
begin
QueryInterfaceThunk := TInterfaceRef(I)^.QueryInterfaceThunk;
case QueryInterfaceThunk.AddInstruction of
AddByte:
Inc(PChar(Result), QueryInterfaceThunk.AdjustmentByte);
AddLong:
Inc(PChar(Result), QueryInterfaceThunk.AdjustmentLong);
else
Result := nil;
end;
end;
except
Result := nil;
end;
end;
//==================================================================================================
// Numeric formatting routines
//==================================================================================================
function IntToStrZeroPad(Value, Count: Integer): AnsiString;
begin
Result := IntToStr(Value);
if Length(Result) < Count then
Result := StrFillChar('0', Count - Length(Result)) + Result;
end;
//==================================================================================================
// Loading of modules (DLLs)
//==================================================================================================
{$IFDEF MSWINDOWS}
function LoadModule(var Module: TModuleHandle; FileName: string): Boolean;
begin
if Module = INVALID_MODULEHANDLE_VALUE then
Module := LoadLibrary(PChar(FileName));
Result := Module <> INVALID_MODULEHANDLE_VALUE;
end;
//--------------------------------------------------------------------------------------------------
function LoadModuleEx(var Module: TModuleHandle; FileName: string; Flags: Cardinal): Boolean;
begin
if Module = INVALID_MODULEHANDLE_VALUE then
Module := LoadLibraryEx(PChar(FileName), 0, Flags);
Result := Module <> INVALID_MODULEHANDLE_VALUE;
end;
//--------------------------------------------------------------------------------------------------
procedure UnloadModule(var Module: TModuleHandle);
begin
if Module <> INVALID_MODULEHANDLE_VALUE then
FreeLibrary(Module);
Module := INVALID_MODULEHANDLE_VALUE;
end;
//--------------------------------------------------------------------------------------------------
function GetModuleSymbol(Module: TModuleHandle; SymbolName: string): Pointer;
begin
Result := nil;
if Module <> INVALID_MODULEHANDLE_VALUE then
Result := GetProcAddress(Module, PChar(SymbolName));
end;
//--------------------------------------------------------------------------------------------------
function GetModuleSymbolEx(Module: TModuleHandle; SymbolName: string; var Accu: Boolean): Pointer;
begin
Result := nil;
if Module <> INVALID_MODULEHANDLE_VALUE then
Result := GetProcAddress(Module, PChar(SymbolName));
Accu := Accu and (Result <> nil);
end;
//--------------------------------------------------------------------------------------------------
function ReadModuleData(Module: TModuleHandle; SymbolName: string; var Buffer; Size: Cardinal): Boolean;
var
Sym: Pointer;
begin
Result := True;
Sym := GetModuleSymbolEx(Module, SymbolName, Result);
if Result then
Move(Sym^, Buffer, Size);
end;
//--------------------------------------------------------------------------------------------------
function WriteModuleData(Module: TModuleHandle; SymbolName: string; var Buffer; Size: Cardinal): Boolean;
var
Sym: Pointer;
begin
Result := True;
Sym := GetModuleSymbolEx(Module, SymbolName, Result);
if Result then
Move(Buffer, Sym^, Size);
end;
{$ENDIF MSWINDOWS}
//==================================================================================================
// Conversion Utilities
//==================================================================================================
{ TODOC
Author: Jeff
StrToBoolean: converts a string S to a boolean. S may be 'Yes/No', 'True/False' or '0/1'.
raises an EJclConversionError exception on failure.
IntToBool: converts an integer to a boolean where 0 means false and anything else is tue.
BoolToInt: converts a boolean to an integer: True=>1 and False=>0
}
const
DefaultTrueBoolStr = 'True'; // DO NOT LOCALIZE
DefaultFalseBoolStr = 'False'; // DO NOT LOCALIZE
DefaultYesBoolStr = 'Yes'; // DO NOT LOCALIZE
DefaultNoBoolStr = 'No'; // DO NOT LOCALIZE
//--------------------------------------------------------------------------------------------------
function StrToBoolean(const S: string): Boolean;
begin
Result := ((S = '1') or (LowerCase(S) = LowerCase(DefaultTrueBoolStr)) or (LowerCase(S) = LowerCase(DefaultYesBoolStr)));
if not Result then
begin
Result := not ((S = '0') or (LowerCase(S) = LowerCase(DefaultFalseBoolStr)) or (LowerCase(S) = LowerCase(DefaultNoBoolStr)));
if Result then
raise EJclConversionError.CreateResRecFmt(@RsStringToBoolean, [S]);
end;
end;
//--------------------------------------------------------------------------------------------------
function IntToBool(I: Integer): Boolean;
begin
Result := I <> 0;
end;
//--------------------------------------------------------------------------------------------------
function BoolToInt(B: Boolean): Integer;
begin
Result := Ord(B);
end;
end.
|
unit uTestuDrawingEvent;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, uEventModel, uExceptions, uVarArrays, Graphics, uDrawingCommand,
uDrawingEvent, uGraphicPrimitive, Variants;
type
// Test methods for class TDrawingCommandData
TestTDrawingCommandData = class(TTestCase)
strict private
FPrimitive : TGraphicPrimitive;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestCreateData;
procedure TestExtractPrimitive;
procedure TestExtractColor;
procedure TestAny;
end;
implementation
procedure TestTDrawingCommandData.SetUp;
begin
FPrimitive := TGraphicPrimitive.Create( nil );
end;
procedure TestTDrawingCommandData.TearDown;
begin
FPrimitive.Free;
FPrimitive := nil;
end;
procedure TestTDrawingCommandData.TestAny;
var
Ok : boolean;
begin
Ok := false;
try
TDrawingCommandData.CreateData( '', 123 );
except
Ok := true;
end;
Check( OK );
end;
procedure TestTDrawingCommandData.TestCreateData;
var
ReturnValue: Variant;
aData: Variant;
begin
aData := 11;
ReturnValue := TDrawingCommandData.CreateData( FPrimitive.IDAsStr, aData );
Check( VarIsArray( ReturnValue ) );
ReturnValue := TDrawingCommandData.CreateData( FPrimitive.IDAsStr, [ aData ] );
Check( VarIsArray( ReturnValue ) );
end;
procedure TestTDrawingCommandData.TestExtractPrimitive;
var
Data: Variant;
begin
Data := TDrawingCommandData.CreateData( FPrimitive.IDAsStr, 'xyz' );
Check( VarIsArray( Data ) );
CheckEqualsString (FPrimitive.IDAsStr, TDrawingCommandData.ExtractPrimitiveID( Data ) );
end;
procedure TestTDrawingCommandData.TestExtractColor;
var
ReturnValue: Variant;
aData: Variant;
begin
ReturnValue := TDrawingCommandData.CreateData( FPrimitive.IDAsStr, clRed );
Check( VarIsArray( ReturnValue ) );
Check( TDrawingCommandData.ExtractColor( aData ) = clRed );
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTDrawingCommandData.Suite);
end.
|
(*
description:
dependencies:
Markus Stephany's MASKSEARCH utility unit is needed. You may find it on DSP
in the MSTGREP.ZIP archive in Delphi 2.0 freeware section.
copyright & license
*)
{------------------------------------------------------------------------------
Modifications made by Brad Stowers for compatibility with TdfsExtListView v3.x
------------------------------------------------------------------------------}
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ExtListView, StdCtrls, ExtCtrls, CommCtrl,ShellApi,
FileListing, FileCtrl, Buttons, EnhListView;
type
PVirtualItem = ^TVirtualItem;
TVirtualItem = packed record
ImageIndex: integer;
Fname : string;
State: UINT;
SubText1: string;
SubText2: string;
end;
TMainForm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
FileList: TdfsExtListView;
Splitter1: TSplitter;
Panel3: TPanel;
Dirs: TDirectoryListBox;
Panel4: TPanel;
Drives: TDriveComboBox;
Mask: TEdit;
Splitter2: TSplitter;
Label2: TLabel;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton4: TSpeedButton;
StatPanel: TPanel;
Label3: TLabel;
procedure FormCreate(Sender: TObject);
procedure FileListDblClick(Sender: TObject);
procedure ListBox1DragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FileListColumnClick(Sender: TObject; Column: TListColumn);
procedure FileListEdited(Sender: TObject; Item: TListItem;
var S: String);
procedure DirsChange(Sender: TObject);
procedure MaskKeyPress(Sender: TObject; var Key: Char);
procedure SpeedButton1Click(Sender: TObject);
procedure FileListClick(Sender: TObject);
procedure FileListVMCacheHint(Sender: TObject;
var HintInfo: TNMCacheHint);
procedure FormShow(Sender: TObject);
procedure FileListVMGetItemInfo(Sender: TObject; Item,
SubItem: Integer; var Mask: TLVVMMaskItems; var Image, Param, State,
StateMask, Indent: Integer; var Text: String);
private
Files : TFileListing;
NumItems: integer;
HomeDir,Fmask : string;
public
FileCount : integer;
procedure GetFileList(Dir,Mask : string);
function GetSystemIndex(FileName:string):integer;
procedure SetupSysImage;
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
function TMainForm.GetSystemIndex(FileName:string):integer;
{Returns the index to the system image and the file type
string in one call}
var
Fileinfo: TSHFileInfo;
begin
if SHGetFileInfo(PChar(FileName),0,Fileinfo,sizeof(TSHFileInfo),
SHGFI_ICON or SHGFI_SYSICONINDEX or SHGFI_USEFILEATTRIBUTES) <> 0 then
begin
Result := Fileinfo.IIcon;
end else Result := 0;
end;
procedure TMainForm.SetupSysImage;
{Retrieves the handles to the small and large system
icon lists}
var
AHandle: DWORD;
Fileinfo: TSHFileInfo;
begin
FileList.SmallImages := TImageList.Create(self);
AHandle := SHGetFileInfo('',
0, Fileinfo, sizeof(TSHFileInfo),
SHGFI_SMALLICON or SHGFI_SYSICONINDEX);
if AHandle <> 0 then begin
FileList.SmallImages.Handle := AHandle;
FileList.SmallImages.ShareImages := True;
end;
FileList.LargeImages := TImageList.Create(self);
AHandle := SHGetFileInfo('',
0, Fileinfo, sizeof(TSHFileInfo),
SHGFI_LARGEICON or SHGFI_SYSICONINDEX
);
if AHandle <> 0 then begin
FileList.LargeImages.Handle := AHandle;
FileList.LargeImages.ShareImages := True;
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
Mask.left := 0;
Mask.width := panel4.width-2;
Fmask := '*.*';
Files := TFileListing.Create;
SetupSysImage;
HomeDir := ExtractFileDir(Application.ExeName);
Dirs.Directory := HomeDir;
end;
procedure TMainForm.GetFileList(Dir,Mask : string);
var
Rslt : integer;
rec : TSearchRec;
Fobj : TFileObject;
begin
FileCount := 0;
Files.Clear;
Rslt := FindFirst(AddSlash(Dir)+Mask,faAnyFile,Rec);
While Rslt = 0 do with Rec do
begin
if (Name[1] <> '.') and
(Attr and faDirectory <> faDirectory) then
begin
Fobj := TFileObject.Create;
Fobj.Name := Name;
Fobj.Size := Size;
Fobj.Date := Time;
Files.Add(Fobj);
Inc(FileCount);
end;
Rslt := FindNext(Rec);
end;
FindClose(Rec);
end;
procedure TMainForm.FileListDblClick(Sender: TObject);
begin
ShowMessage(Files.fullname(FileList.ELV_GetNextItem(-1, sdAll, [isFocused])));
end;
procedure TMainForm.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
accept := true;
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FileList.SmallImages.free;
FileList.LargeImages.free;
Files.Free;
end;
procedure TMainForm.FileListColumnClick(Sender: TObject;
Column: TListColumn);
const
Ascend : boolean = false;
var
count : integer;
begin
Ascend := not Ascend;
// Toggle sort arrow direction
FileList.CurrentSortAscending := Ascend;
Case Column.index of
0 : Files.SortFiles(fsName,Ascend);
1 : Files.SortFiles(fsSize,Ascend);
2 : Files.SortFiles(fsDate,Ascend);
3 : Files.SortFiles(fsType,Ascend);
end;
count := FileList.items.count;
FileList.Items.Clear;
FileList.SetItemCountEx(count, [lvsicfNoScroll]);
end;
procedure TMainForm.FileListEdited(Sender: TObject; Item: TListItem;
var S: String);
var
index : integer;
Fobj : TFileObject;
begin
index := FileList.ELV_GetNextItem(-1, sdAll, [isFocused]);
Fobj := TfileObject(files[index]);
Fobj.name := s;
end;
procedure TMainForm.DirsChange(Sender: TObject);
begin
NumItems := Files.GetFiles(Dirs.Directory,Fmask);
label2.caption :=
Commastr(files.DirBytes)+ ' bytes in '+ inttostr(numitems) + ' files';
FileList.SetItemCountEx(NumItems, [lvsicfNoScroll]);
StatPanel.caption := ' '+UpperCase(Dirs.Directory);
end;
procedure TMainForm.MaskKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then
begin
key := #0;
Fmask := Mask.Text;
DirsChange(self);
end;
end;
procedure TMainForm.SpeedButton1Click(Sender: TObject);
begin
case Tspeedbutton(Sender).tag of
0: FileList.ViewStyle := vsReport;
1: FileList.ViewStyle := vsList;
2: FileList.ViewStyle := vsSmallIcon;
3: FileList.ViewStyle := vsIcon;
end;
end;
procedure TMainForm.FileListClick(Sender: TObject);
begin
Label3.caption := inttostr(FileList.selcount)+' files selected';
end;
procedure TMainForm.FileListVMCacheHint(Sender: TObject;
var HintInfo: TNMCacheHint);
var
i : integer;
FObj : TFileObject;
Fname : string;
begin
for i := HintInfo.ifrom to HintInfo.iTo do
begin
Fobj := TFileObject(Files[i]);
Fname := AddSlash(Files.Directory)+Fobj.Name;
if Fobj.Imgindex = -1 then // we haven't painted this one before, get it
Fobj.Imgindex := GetSystemIndex(Fname);
end;
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
DirsChange(Self); // populate with initial directory at startup.
end;
procedure TMainForm.FileListVMGetItemInfo(Sender: TObject; Item,
SubItem: Integer; var Mask: TLVVMMaskItems; var Image, Param, State,
StateMask, Indent: Integer; var Text: String);
var
Fobj : TfileObject;
fName : string;
function FixName(Name : string) : string;
begin
Result := LowerCase(name);
Result[1] := UpCase(Result[1]);
end;
begin
Fobj := Files[item];
fName:= AddSlash(files.Directory)+Fobj.name;
if lvifImage in Mask then
begin
image := Fobj.imgindex;
end;
if lvifText in Mask then with Fobj do
begin
case SubItem of
0: Text := FixName(Fobj.Name);
1: Text := Commastr(size);
2: Text := DateTimeToStr(Date);
3: Text := Ftype;
else Text := '';
end;
end;
//if lvifParam in Mask then Param := 0;
{ if lvifState in Mask then
State := State or AnItem.State; }
end;
END.
|
namespace RemObjects.DataAbstract.CodeGen4;
uses
System,
System.Collections.Generic,
System.ComponentModel,
System.IO,
System.Text,
RemObjects.SDK.CodeGen4,
RemObjects.DataAbstract.Schema;
type
[System.Reflection.ObfuscationAttribute(Exclude := true, ApplyToMembers := true)]
NetTableDefinitionsCodeGen = public class
private
{$REGION Private constants }
const EVENT_PROPERTY_CHANGING: String = 'PropertyChanging';
const EVENT_PROPERTY_CHANGED: String = 'PropertyChanged';
const TRIGGER_PROPERTY_CHANGING: String = 'OnPropertyChanging';
const TRIGGER_PROPERTY_CHANGED: String = 'OnPropertyChanged';
const EVENT_TRIGGER_PARAMETER_NAME: String = 'parameterName';
const CODE_FIELD_PREFIX: String = 'f____';
const CODE_FIELD_SOURCE_TABLE: String = CODE_FIELD_PREFIX + PROPERTY_SOURCE_TABLE;
const CODE_OLD_VALUES_FIELD: String = 'm____OldValues';
const SCHEMA_FIELD_SOURCE_TABLE: String = '@SourceTable';
const PROPERTY_SOURCE_TABLE: String = 'ServerSchemaSourceTable';
{$ENDREGION}
{$REGION Private fields}
var fCodeGenerator: CGCodeGenerator; readonly;
var fFullyFeaturedCodeGen: Boolean; readonly;
var fCodeUnit: CGCodeUnit;
{$ENDREGION}
method GetValidIdentifier(name: String): String;
begin
var identifier: String := RemObjects.SDK.Helpers.StringHelpers.ClearIdentifier(name, false);
if identifier.ToUpperInvariant() in [ NetTableDefinitionsCodeGen.EVENT_PROPERTY_CHANGING.ToUpperInvariant(),
NetTableDefinitionsCodeGen.EVENT_PROPERTY_CHANGED.ToUpperInvariant(),
NetTableDefinitionsCodeGen.TRIGGER_PROPERTY_CHANGING.ToUpperInvariant(),
NetTableDefinitionsCodeGen.TRIGGER_PROPERTY_CHANGED.ToUpperInvariant() ] then begin
identifier := identifier + '_';
end;
exit identifier;
end;
method GetValidIdentifier(typeName: String; name: String): String;
begin
var identifier := self.GetValidIdentifier(name);
// In C# member names cannot be the same as their enclosing type
// Check is not case-sensitive because VB.NET and Oxygene don't care about identifier case
if String.Equals(identifier, typeName, StringComparison.OrdinalIgnoreCase) then begin
identifier := identifier + '_Field';
end;
exit identifier;
end;
method GetTableRelationships(schema: Schema; tableName: String): IList<SchemaRelationship>;
begin
var relationships: List<SchemaRelationship> := new List<SchemaRelationship>();
for each relation: SchemaRelationship in schema.Relationships do begin
if String.Equals(tableName, relation.DetailDataTableName, StringComparison.OrdinalIgnoreCase) then begin
relationships.Add(relation);
end;
end;
exit relationships;
end;
method GenerateCodeMetadata(schemaName: String; schemaUri: String; skippedTables: ICollection<String>; includePrivateTables: Boolean);
begin
if not String.IsNullOrEmpty(schemaName) then begin
self.fCodeUnit.HeaderComment.Lines.Add(String.Format('#DA Schema Name:"{0}"', schemaName));
end;
if not String.IsNullOrEmpty(schemaUri) then begin
self.fCodeUnit.HeaderComment.Lines.Add(String.Format('#DA Schema Source:"{0}"', schemaUri));
end;
if includePrivateTables then begin
self.fCodeUnit.HeaderComment.Lines.Add('#DA Add Private Tables');
end;
if skippedTables.Count > 0 then begin
var skippedTablesComment: StringBuilder := new StringBuilder();
skippedTablesComment.Append('#DA Skipped Tables:"');
for each tableName: String in skippedTables index i do begin
if i > 0 then begin
skippedTablesComment.Append(',');
end;
skippedTablesComment.Append(tableName);
end;
skippedTablesComment.Append('"');
self.fCodeUnit.HeaderComment.Lines.Add(skippedTablesComment.ToString());
end;
end;
method AddTableFieldMetadata(codeField: CGMemberDefinition; schemaField: SchemaField);
begin
codeField.Attributes.Add(new CGAttribute(new CGNamedTypeReference("RemObjects.DataAbstract.Linq.FieldName"), (new CGStringLiteralExpression(schemaField.Name)).AsCallParameter()));
codeField.Attributes.Add(new CGAttribute(new CGNamedTypeReference("RemObjects.DataAbstract.Linq.DataType"),
(new CGEnumValueAccessExpression(new CGNamedTypeReference(typeOf(RemObjects.DataAbstract.Schema.DataType).ToString()), schemaField.DataType.ToString())).AsCallParameter()));
if schemaField.InPrimaryKey then begin
codeField.Attributes.Add(new CGAttribute(new CGNamedTypeReference("RemObjects.DataAbstract.Linq.PrimaryKey")));
end;
if schemaField.LogChanges then begin
codeField.Attributes.Add(new CGAttribute(new CGNamedTypeReference("RemObjects.DataAbstract.Linq.LogChanges")));
end;
if schemaField.ServerAutoRefresh then begin
codeField.Attributes.Add(new CGAttribute(new CGNamedTypeReference("RemObjects.DataAbstract.Linq.ServerAutoRefresh")));
end;
end;
method GenerateUnit(schema: Schema; schemaName: String; schemaUri: String; &namespace: String; skippedTables: ICollection<String>; includePrivateTables: Boolean);
begin
// Get Schema Tables list
var schemaTables: ICollection<SchemaDataTable> := schema.GetAllDatasets(not includePrivateTables);
// Convert skipped table nemas into HashSet
var skippedTablesList: HashSet<String> := new HashSet<String>(StringComparer.Ordinal);
for each tableName: String in skippedTables do begin
skippedTablesList.Add(tableName);
end;
var namespaceReference: CGNamespaceReference := iif(not String.IsNullOrEmpty(&namespace), new CGNamespaceReference(&namespace), nil);
self.fCodeUnit := new CGCodeUnit(namespaceReference);
self.GenerateCodeMetadata(schemaName, schemaUri, skippedTables, includePrivateTables);
var tableDefinitions: List<CGTypeDefinition> := new List<CGTypeDefinition>(schemaTables.Count);
for each table in schemaTables do begin
// Skip unneeded tables
if skippedTablesList.Contains(table.Name) then begin
continue;
end;
tableDefinitions.Add(self.GenerateTableTypeDefinition(table, self.GetTableRelationships(schema, table.Name)));
end;
for each table in tableDefinitions do begin
self.fCodeUnit.Types.Add(table);
end;
self.GenerateDataContext(tableDefinitions);
end;
method GenerateTableTypeDefinition(table: SchemaDataTable; relations: IList<SchemaRelationship>): CGClassTypeDefinition;
begin
var typeDefinition := new CGClassTypeDefinition(self.GetValidIdentifier(table.Name));
typeDefinition.Attributes.Add(new CGAttribute(new CGNamedTypeReference("RemObjects.DataAbstract.Linq.TableName"), (new CGStringLiteralExpression(table.Name)).AsCallParameter()));
typeDefinition.Visibility := CGTypeVisibilityKind.Public;
typeDefinition.Partial := true;
self.GenerateICloneableImplementation(typeDefinition, table is SchemaUnionDataTable, table.Fields);
self.GeneratePropertyChangeEventDefinitions(typeDefinition);
self.GeneratePropertyChangedEventTrigger(typeDefinition);
self.GeneratePropertyChangingEventTrigger(typeDefinition);
self.GenerateChangeManagementMethods(typeDefinition);
for each schemaField: SchemaField in table.Fields do begin
// DA LINQ cannot access calculated fields AS IS
if schemaField.Calculated then begin
continue;
end;
var fieldType: &Type := FieldUtils.DataTypeToType(schemaField.DataType);
var fieldTypeReference: CGTypeReference;
if fieldType.IsValueType and not schemaField.Required then begin
fieldTypeReference := (new CGNamedTypeReference(fieldType.ToString()) defaultNullability(CGTypeNullabilityKind.NotNullable)).copyWithNullability(CGTypeNullabilityKind.NullableNotUnwrapped);
end
else begin
fieldTypeReference := iif(fieldType.IsArray,
(new CGArrayTypeReference(new CGNamedTypeReference(fieldType.GetElementType().ToString()) defaultNullability(CGTypeNullabilityKind.Default))).copyWithNullability(CGTypeNullabilityKind.NullableNotUnwrapped),
new CGNamedTypeReference(fieldType.ToString()) defaultNullability(CGTypeNullabilityKind.Default));
end;
var fieldName: String := self.GetValidIdentifier(typeDefinition.Name, schemaField.Name);
// In C# member names cannot be the same as their enclosing type
// Check is not case-sensitive because VB.NET and Oxygene don't care about identifier case
if String.Equals(fieldName, table.Name, StringComparison.OrdinalIgnoreCase) then begin
fieldName := fieldName + '_Field';
end;
var fieldDefinition := new CGFieldDefinition(NetTableDefinitionsCodeGen.CODE_FIELD_PREFIX + fieldName, fieldTypeReference);
fieldDefinition.Visibility := CGMemberVisibilityKind.Private;
typeDefinition.Members.Add(fieldDefinition);
var fieldReference := new CGFieldAccessExpression(new CGSelfExpression(), fieldDefinition.Name);
var propertyDefinition := new CGPropertyDefinition(fieldName, fieldTypeReference, new List<CGStatement>(), new List<CGStatement>());
propertyDefinition.Visibility := CGMemberVisibilityKind.Public;
typeDefinition.Members.Add(propertyDefinition);
// Get relations
for each relation: SchemaRelationship in relations do begin
if not String.Equals(schemaField.Name, relation.DetailFields, StringComparison.OrdinalIgnoreCase) then begin
continue;
end;
propertyDefinition.Attributes.Add(new CGAttribute(new CGNamedTypeReference('RemObjects.DataAbstract.Linq.Relation'),
(new CGStringLiteralExpression(relation.MasterDataTableName)).AsCallParameter(),
(new CGStringLiteralExpression(relation.MasterFields)).AsCallParameter()));
end;
self.AddTableFieldMetadata(propertyDefinition, schemaField);
propertyDefinition.GetStatements.Add(new CGReturnStatement(fieldReference));
if not schemaField.ReadOnly then begin
var conditionStatement: CGBinaryOperatorExpression;
if schemaField.DataType = DataType.Blob then begin
var comparerCall := new CGMethodCallExpression(new CGTypeReferenceExpression(new CGNamedTypeReference("RemObjects.DataAbstract.Linq.LinqDataAdapter")), "CompareBytes", fieldReference.AsCallParameter(), (new CGPropertyValueExpression()).AsCallParameter());
conditionStatement := new CGBinaryOperatorExpression(comparerCall, new CGBooleanLiteralExpression(true), CGBinaryOperatorKind.NotEquals);
end
else begin
var comparerType: CGNamedTypeReference := new CGNamedTypeReference('System.Collections.Generic.Comparer');
comparerType.GenericArguments := new List<CGTypeReference>([ fieldTypeReference ]);
var comparerInstance := new CGPropertyAccessExpression(new CGTypeReferenceExpression(comparerType), "Default");
var comparerCall := new CGMethodCallExpression(comparerInstance, "Compare", fieldReference.AsCallParameter(), (new CGPropertyValueExpression()).AsCallParameter());
conditionStatement := new CGBinaryOperatorExpression(comparerCall, new CGIntegerLiteralExpression(0), CGBinaryOperatorKind.NotEquals);
end;
var statements := new CGBeginEndBlockStatement();
if self.fFullyFeaturedCodeGen then begin
statements.Statements.Add(new CGMethodCallExpression(new CGSelfExpression(), NetTableDefinitionsCodeGen.TRIGGER_PROPERTY_CHANGING, new CGStringLiteralExpression(fieldName).AsCallParameter()));
end;
statements.Statements.Add(new CGAssignmentStatement(fieldReference, new CGPropertyValueExpression()));
statements.Statements.Add(new CGMethodCallExpression(new CGSelfExpression(), NetTableDefinitionsCodeGen.TRIGGER_PROPERTY_CHANGED, new CGStringLiteralExpression(fieldName).AsCallParameter()));
propertyDefinition.SetStatements.Add(new CGIfThenElseStatement(conditionStatement, statements));
end
else begin
propertyDefinition.SetStatements.Add(new CGAssignmentStatement(fieldReference, new CGPropertyValueExpression()));
end;
end;
if (table is SchemaUnionDataTable) then begin
var fieldDefinition := new CGFieldDefinition(NetTableDefinitionsCodeGen.CODE_FIELD_SOURCE_TABLE, CGPredefinedTypeReference.Int32);
fieldDefinition.Initializer := new CGIntegerLiteralExpression(0); // This is needed to get rid of 'Field is never assigned' compiler warnings
fieldDefinition.Visibility := CGMemberVisibilityKind.Private;
typeDefinition.Members.Add(fieldDefinition);
var fieldReference := new CGFieldAccessExpression(new CGSelfExpression(), fieldDefinition.Name);
var propertyDefinition := new CGPropertyDefinition(NetTableDefinitionsCodeGen.PROPERTY_SOURCE_TABLE, CGPredefinedTypeReference.Int32, new List<CGStatement>(), new List<CGStatement>());
propertyDefinition.Visibility := CGMemberVisibilityKind.Public;
typeDefinition.Members.Add(propertyDefinition);
propertyDefinition.Attributes.Add(new CGAttribute(new CGNamedTypeReference("RemObjects.DataAbstract.Linq.FieldName"), (new CGStringLiteralExpression(NetTableDefinitionsCodeGen.SCHEMA_FIELD_SOURCE_TABLE)).AsCallParameter()));
propertyDefinition.Attributes.Add(new CGAttribute(new CGNamedTypeReference("RemObjects.DataAbstract.Linq.DataType"),
(new CGEnumValueAccessExpression(new CGNamedTypeReference(typeOf(RemObjects.DataAbstract.Schema.DataType).ToString()), 'Integer')).AsCallParameter()));
propertyDefinition.Attributes.Add(new CGAttribute(new CGNamedTypeReference("RemObjects.DataAbstract.Linq.PrimaryKey")));
propertyDefinition.Attributes.Add(new CGAttribute(new CGNamedTypeReference("RemObjects.DataAbstract.Linq.LogChanges")));
propertyDefinition.GetStatements.Add(new CGReturnStatement(fieldReference));
propertyDefinition.SetStatements.Add(new CGAssignmentStatement(fieldReference, new CGPropertyValueExpression()));
end;
exit typeDefinition;
end;
method GenerateICloneableImplementation(typeDefinition: CGClassTypeDefinition; isUnionTable: Boolean; fields: SchemaFieldCollection);
begin
if not self.fFullyFeaturedCodeGen then begin
exit;
end;
var implementedInterface := new CGNamedTypeReference(typeOf(ICloneable).ToString());
typeDefinition.ImplementedInterfaces.Add(implementedInterface);
var cloneMethod := new CGMethodDefinition("Clone");
cloneMethod.Visibility := CGMemberVisibilityKind.Public;
cloneMethod.ImplementsInterface := implementedInterface;
cloneMethod.ImplementsInterfaceMember := "Clone";
typeDefinition.Members.Add(cloneMethod);
cloneMethod.ReturnType := CGPredefinedTypeReference.Object;
cloneMethod.Statements.Add(new CGVariableDeclarationStatement("v____new", new CGNamedTypeReference(typeDefinition.Name), new CGNewInstanceExpression(new CGNamedTypeReference(typeDefinition.Name))));
var clonedInstance := new CGNamedIdentifierExpression("v____new");
for each field: SchemaField in fields do begin
if field.Calculated then begin
continue;
end;
var fieldName: String := NetTableDefinitionsCodeGen.CODE_FIELD_PREFIX + self.GetValidIdentifier(typeDefinition.Name, field.Name);
cloneMethod.Statements.Add(new CGAssignmentStatement(new CGFieldAccessExpression(clonedInstance, fieldName), new CGFieldAccessExpression(new CGSelfExpression(), fieldName)));
end;
if isUnionTable then begin
cloneMethod.Statements.Add(new CGAssignmentStatement(new CGFieldAccessExpression(clonedInstance, NetTableDefinitionsCodeGen.CODE_FIELD_SOURCE_TABLE),
new CGFieldAccessExpression(new CGSelfExpression(), NetTableDefinitionsCodeGen.CODE_FIELD_SOURCE_TABLE)));
end;
cloneMethod.Statements.Add(new CGReturnStatement(clonedInstance));
end;
method GeneratePropertyChangeEventDefinitions(typeDefinition: CGClassTypeDefinition);
begin
var implementedInterface := new CGNamedTypeReference(typeOf(INotifyPropertyChanged).ToString());
typeDefinition.ImplementedInterfaces.Add(implementedInterface);
var eventDefinition := new CGEventDefinition(NetTableDefinitionsCodeGen.EVENT_PROPERTY_CHANGED, new CGNamedTypeReference(typeOf(PropertyChangedEventHandler).ToString()));
eventDefinition.Visibility := CGMemberVisibilityKind.Public;
eventDefinition.ImplementsInterface := implementedInterface;
eventDefinition.ImplementsInterfaceMember := NetTableDefinitionsCodeGen.EVENT_PROPERTY_CHANGED;
typeDefinition.Members.Add(eventDefinition);
if self.fFullyFeaturedCodeGen then begin
implementedInterface := new CGNamedTypeReference(typeOf(INotifyPropertyChanging).ToString());
typeDefinition.ImplementedInterfaces.Add(implementedInterface);
eventDefinition := new CGEventDefinition(NetTableDefinitionsCodeGen.EVENT_PROPERTY_CHANGING, new CGNamedTypeReference(typeOf(PropertyChangingEventHandler).ToString()));
eventDefinition.Visibility := CGMemberVisibilityKind.Public;
eventDefinition.ImplementsInterface := implementedInterface;
eventDefinition.ImplementsInterfaceMember := NetTableDefinitionsCodeGen.EVENT_PROPERTY_CHANGING;
typeDefinition.Members.Add(eventDefinition);
end;
end;
method GeneratePropertyChangingEventTrigger(typeDefinition: CGClassTypeDefinition);
begin
if not self.fFullyFeaturedCodeGen then begin
exit;
end;
var triggerMethod := new CGMethodDefinition(NetTableDefinitionsCodeGen.TRIGGER_PROPERTY_CHANGING);
triggerMethod.Visibility := CGMemberVisibilityKind.Protected;
triggerMethod.Parameters.Add(new CGParameterDefinition(NetTableDefinitionsCodeGen.EVENT_TRIGGER_PARAMETER_NAME, CGPredefinedTypeReference.String));
var eventReference := new CGEventAccessExpression(new CGSelfExpression(), NetTableDefinitionsCodeGen.EVENT_PROPERTY_CHANGING);
var conditionExpression := new CGBinaryOperatorExpression(eventReference, new CGNilExpression(), CGBinaryOperatorKind.NotEquals);
var eventArgsInstance := new CGNewInstanceExpression(new CGNamedTypeReference(typeOf(PropertyChangingEventArgs).ToString()), (new CGNamedIdentifierExpression(NetTableDefinitionsCodeGen.EVENT_TRIGGER_PARAMETER_NAME)).AsCallParameter());
var eventInvokeStatement := new CGMethodCallExpression(eventReference, "Invoke", (new CGSelfExpression()).AsCallParameter(), eventArgsInstance.AsCallParameter());
triggerMethod.Statements.Add(new CGIfThenElseStatement(conditionExpression, eventInvokeStatement));
typeDefinition.Members.Add(triggerMethod);
end;
method GeneratePropertyChangedEventTrigger(typeDefinition: CGClassTypeDefinition);
begin
var triggerMethod := new CGMethodDefinition(NetTableDefinitionsCodeGen.TRIGGER_PROPERTY_CHANGED);
triggerMethod.Visibility := CGMemberVisibilityKind.Protected;
triggerMethod.Parameters.Add(new CGParameterDefinition(NetTableDefinitionsCodeGen.EVENT_TRIGGER_PARAMETER_NAME, CGPredefinedTypeReference.String));
var eventReference := new CGEventAccessExpression(new CGSelfExpression(), NetTableDefinitionsCodeGen.EVENT_PROPERTY_CHANGED);
var conditionExpression := new CGBinaryOperatorExpression(eventReference, new CGNilExpression(), CGBinaryOperatorKind.NotEquals);
var eventArgsInstance := new CGNewInstanceExpression(new CGNamedTypeReference(typeOf(PropertyChangedEventArgs).ToString()), (new CGNamedIdentifierExpression(NetTableDefinitionsCodeGen.EVENT_TRIGGER_PARAMETER_NAME)).AsCallParameter());
var eventInvokeStatement := new CGMethodCallExpression(eventReference, "Invoke", (new CGSelfExpression()).AsCallParameter(), eventArgsInstance.AsCallParameter());
if self.fFullyFeaturedCodeGen then begin
conditionExpression := new CGBinaryOperatorExpression(
new CGParenthesesExpression(conditionExpression),
new CGParenthesesExpression(new CGBinaryOperatorExpression(new CGFieldAccessExpression(new CGSelfExpression(), "m____OldValues"), new CGNilExpression(), CGBinaryOperatorKind.Equals)),
CGBinaryOperatorKind.LogicalAnd);
end;
triggerMethod.Statements.Add(new CGIfThenElseStatement(conditionExpression, eventInvokeStatement));
typeDefinition.Members.Add(triggerMethod);
end;
method GenerateChangeManagementMethods(typeDefinition: CGClassTypeDefinition);
begin
if not self.fFullyFeaturedCodeGen then begin
exit;
end;
var oldValuesField := new CGFieldDefinition(CODE_OLD_VALUES_FIELD, new CGNamedTypeReference(typeDefinition.Name));
oldValuesField.Visibility := CGMemberVisibilityKind.Private;
typeDefinition.Members.Add(oldValuesField);
var beginUpdateMethod := new CGMethodDefinition("BeginUpdate");
beginUpdateMethod.Visibility := CGMemberVisibilityKind.Public;
beginUpdateMethod.Statements.Add
(
new CGAssignmentStatement
(
new CGFieldAccessExpression(new CGSelfExpression(), CODE_OLD_VALUES_FIELD),
new CGTypeCastExpression
(
new CGMethodCallExpression(new CGSelfExpression(), "Clone"),
new CGNamedTypeReference(typeDefinition.Name)
)
)
);
typeDefinition.Members.Add(beginUpdateMethod);
var endUpdateMethod := new CGMethodDefinition("EndUpdate");
endUpdateMethod.Visibility := CGMemberVisibilityKind.Public;
endUpdateMethod.Parameters.Add(new CGParameterDefinition("dataAdapter", new CGNamedTypeReference("RemObjects.DataAbstract.Linq.LinqDataAdapter")));
var updateMethodCall := new CGMethodCallExpression
(
new CGNamedIdentifierExpression("dataAdapter"),
"UpdateRow",
new CGFieldAccessExpression(new CGSelfExpression(), CODE_OLD_VALUES_FIELD).AsCallParameter(),
new CGSelfExpression().AsCallParameter()
);
updateMethodCall.GenericArguments := new List<CGTypeReference>([ new CGNamedTypeReference(typeDefinition.Name) ]);
endUpdateMethod.Statements.Add(updateMethodCall);
endUpdateMethod.Statements.Add
(
new CGAssignmentStatement
(
new CGFieldAccessExpression(new CGSelfExpression(), CODE_OLD_VALUES_FIELD),
new CGNilExpression()
)
);
typeDefinition.Members.Add(endUpdateMethod);
var cancelUpdateMethod := new CGMethodDefinition("CancelUpdate");
cancelUpdateMethod.Visibility := CGMemberVisibilityKind.Public;
cancelUpdateMethod.Statements.Add
(
new CGAssignmentStatement
(
new CGFieldAccessExpression(new CGSelfExpression(), CODE_OLD_VALUES_FIELD),
new CGNilExpression()
)
);
typeDefinition.Members.Add(cancelUpdateMethod);
end;
method GenerateDataContext(items: List<CGTypeDefinition>);
begin
var dataContext := new CGClassTypeDefinition("DataContext");
dataContext.Partial := true;
dataContext.Visibility := CGTypeVisibilityKind.Public;
var constructorDefinition := new CGConstructorDefinition();
constructorDefinition.Visibility := CGMemberVisibilityKind.Public;
dataContext.Members.Add(constructorDefinition);
for each table in items do begin
var field := new CGFieldDefinition(NetTableDefinitionsCodeGen.CODE_FIELD_PREFIX + table.Name);
field.Type := new CGNamedTypeReference("System.Collections.Generic.IEnumerable",
GenericArguments := new List<CGTypeReference>([ new CGNamedTypeReference(table.Name) ]));
dataContext.Members.Add(field);
var tableFieldReference := new CGFieldAccessExpression(new CGSelfExpression(), field.Name);
var tableProperty := new CGPropertyDefinition(table.Name, field.Type, new List<CGStatement>(), new List<CGStatement>());
tableProperty.Visibility := CGMemberVisibilityKind.Public;
tableProperty.GetStatements.Add(new CGReturnStatement(tableFieldReference));
tableProperty.SetStatements.Add(new CGAssignmentStatement(tableFieldReference, new CGPropertyValueExpression()));
dataContext.Members.Add(tableProperty);
end;
self.fCodeUnit.Types.Add(dataContext);
end;
method GenerateCode(): String;
begin
exit self.fCodeGenerator.GenerateUnit(self.fCodeUnit);
end;
public
constructor(generator: CGCodeGenerator; fullCodeGen: Boolean);
begin
self.fCodeGenerator := generator;
self.fFullyFeaturedCodeGen := fullCodeGen;
end;
method Generate(schema: Schema; schemaName: String; schemaUri: String; &namespace: String; skippedTables: ICollection<String>; includePrivateTables: Boolean): String;
begin
self.GenerateUnit(schema, schemaName, schemaUri, &namespace, skippedTables, includePrivateTables);
var code: String := self.GenerateCode();
self.fCodeUnit := nil;
exit code;
end;
end;
end. |
unit ticket;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ComCtrls, ExtCtrls;
type
TUser = record
name : string[50];
id_no : string[20];
end;
TCategory = record
name : string[100];
id : integer;
end;
TTicket = record
id : integer;
subject : string[200];
description : string[255];
is_open : integer;
priority : integer;
category_id : integer;
user_id : string[16];
requester : string[16];
created : TDateTime;
modified : TDateTime;
end;
TFormTicket = class(TForm)
GroupBox1: TGroupBox;
Panel1: TPanel;
edtSubject: TEdit;
Label2: TLabel;
Memo_Description: TMemo;
Label1: TLabel;
Label3: TLabel;
Label4: TLabel;
cboCategory: TComboBox;
cboUser: TComboBox;
btnSave: TBitBtn;
btnCancel: TBitBtn;
lsvComments: TListView;
btnComment: TBitBtn;
chkbox_isOpen: TCheckBox;
Label5: TLabel;
cboRequester: TComboBox;
chkboxDonotcloseonSave: TCheckBox;
MemoComments: TMemo;
procedure loadElements;
procedure loadComments;
procedure loadTicket;
procedure FormShow(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnCommentClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormTicket: TFormTicket;
users : array of TUser;
categories : array of TCategory;
ticket_data : TTicket;
id_nos, names : array of String;
NewItem, CurrentItem: TListItem;
implementation
uses data_module, shared, DB, main, comment;
{$R *.dfm}
procedure TFormTicket.btnCancelClick(Sender: TObject);
begin
Close;
FormMain.lsvRefresh;
end;
procedure TFormTicket.loadElements;
var
i : integer;
begin
{ LOAD ELEMENTS FROM SHARED SPACE - THIS IS CALLED FROM MAIN FORM }
{ FIRST LOAD CATEGORIES }
cboCategory.Items.BeginUpdate;
cboCategory.Items.Clear;
i := 0;
while i < Length(shared.categories) do begin
cboCategory.Items.Add(shared.categories[i].name);
i := i + 1;
end;
cboCategory.Items.EndUpdate;
{ SECOND LOAD USERS }
cboUser.Items.BeginUpdate;
cboUser.Items.Clear;
i := 0;
while i < Length(shared.users) do begin
cboUser.Items.Add(shared.users[i].name);
i := i + 1;
end;
cboUser.Items.EndUpdate;
{ LOAD REQUESTER USERS }
cboRequester.Items.BeginUpdate;
cboRequester.Items.Clear;
i := 0;
while i < Length(shared.users) do begin
cboRequester.Items.Add(shared.users[i].name);
i := i + 1;
end;
cboRequester.Items.EndUpdate;
end;
procedure TformTicket.loadTicket;
begin
with ticket_data do begin
edtSubject.Text := subject;
Memo_Description.Text := description;
cboUser.ItemIndex := findindex(user_id);
cboRequester.ItemIndex := findindex(requester);
end;
end;
procedure TFormTicket.loadComments;
var
user_name, defect_user_name : string;
begin
if dm.ibt.InTransaction then
dm.ibt.Commit
else
dm.ibt.StartTransaction;
dm.ibq.SQL.Clear;
dm.ibq.SQL.Add('select * from SELECT_COMMENTS(:a) order by created desc');
dm.ibq.Params[0].AsInteger := ticket_id;
dm.ibq.Open;
MemoComments.Lines.BeginUpdate;
MemoComments.Lines.Clear;
while not dm.ibq.Eof do begin
{ id, user_id, comment, defect user, created }
MemoComments.Lines.Add('Date: ' + dm.ibq.Fields.Fields[4].AsString);
// MemoComments.Lines.Add('Comment id: ' + dm.ibq.Fields.Fields[0].AsString);
if dm.ibq.Fields.Fields[1].AsString <> '' then
user_name := shared.users[shared.findindex(dm.ibq.Fields.Fields[1].AsString)].name
else
user_name := '';
MemoComments.Lines.Add('User: ' + user_name);
if dm.ibq.Fields.Fields[3].AsString <> '' then begin
defect_user_name := shared.users[shared.findindex(dm.ibq.Fields.Fields[3].AsString)].name;
MemoComments.Lines.Add('Defect user: ' + defect_user_name);
end
else
defect_user_name := '';
MemoComments.Lines.Add('Comment: ' + dm.ibq.Fields.Fields[2].AsString);
dm.ibq.Next;
MemoComments.Lines.Add('');
MemoComments.Lines.Add('');
end;
MemoComments.Lines.EndUpdate;
end;
procedure TFormTicket.FormShow(Sender: TObject);
var
user_name : string;
begin
chkbox_isOpen.Checked := False;
if shared.ticket_form_state = 'Add' then begin
FormTicket.Caption := 'Open Ticket';
edtSubject.Text := '';
Memo_Description.Text := '';
cboCategory.ItemIndex := -1;
cboUser.ItemIndex := -1;
cboRequester.ItemIndex := shared.findindex(CurrentUser.name);
chkbox_isOpen.Checked := False;
lsvComments.Items.Clear;
chkbox_isOpen.Visible := False;
btnComment.Visible := False;
MemoComments.Lines.Clear;
end
else if shared.ticket_form_state = 'Update' then begin
{ load comments }
loadComments;
chkbox_isOpen.Visible := True;
btnComment.Visible := True;
end;
edtSubject.SetFocus;
end;
procedure TFormTicket.btnSaveClick(Sender: TObject);
var
form_validated : Boolean;
comment : string;
begin
form_validated := False;
if edtSubject.Text = '' then begin
ShowMessage('Subject must not be blank.');
edtSubject.SetFocus;
end
else if cboCategory.ItemIndex = -1 then begin
ShowMessage('Please choose a category.');
cboCategory.SetFocus;
end
else if cboUser.ItemIndex = -1 then begin
ShowMessage('Please choose a user.');
cboUser.SetFocus;
end
else if cboRequester.ItemIndex = -1 then begin
ShowMessage('Please choose a requester.');
cboRequester.SetFocus;
end
else
form_validated := True;
if (form_validated) then begin
if dm.ibt.InTransaction then
dm.ibt.Commit
else
dm.ibt.StartTransaction;
dm.ibq.SQL.Clear;
dm.ibq.SQL.Add('execute procedure update_ticket(:id, :subject, :description, :is_open, :priority, :category_id, :user_id, :requester, :created, :modified)');
if ticket_form_state = 'Add' then
dm.ibq.ParamByName('id').AsInteger := 0
else
dm.ibq.ParamByName('id').AsInteger := ticket_data.id;
dm.ibq.ParamByName('subject').AsString := trim(edtSubject.text);
dm.ibq.ParamByName('description').AsString := trim(Memo_Description.Text);
{ 0 closed, 1 open }
if chkbox_isOpen.Checked then
dm.ibq.ParamByName('is_open').AsInteger := 0
else
dm.ibq.ParamByName('is_open').AsInteger := 1;
dm.ibq.ParamByName('priority').AsInteger := 1;
dm.ibq.ParamByName('category_id').AsInteger := shared.categories[cboCategory.ItemIndex].id;
dm.ibq.ParamByName('user_id').AsString := shared.users[cboUser.ItemIndex].id_no;
dm.ibq.ParamByName('requester').AsString := shared.users[cboRequester.ItemIndex].id_no;
dm.ibq.ParamByName('created').AsDateTime := Now; { SP doesnt use this when in UPDATE mode }
dm.ibq.ParamByName('modified').AsDateTime := Now;
dm.ibq.ExecSQL;
if ticket_form_state = 'Update' then begin
{
check all fields if they have differences with existing ticket data
if there are changes, add them to the comment
if no changes, do not make any changes
}
with ticket_data do begin
if (subject <> edtSubject.Text)
or (Memo_Description.Text <> description)
or (category_id <> cboCategory.ItemIndex)
or (user_id <> shared.users[cboUser.ItemIndex].id_no)
or (chkbox_isOpen.Checked) then
begin
comment := 'User ' + shared.users[findindex(CurrentUser.id_no)].name + ' made change(s): ';
if edtSubject.Text <> subject then begin
comment := comment + 'NEW SUBJECT: "' + trim(edtSubject.Text) + '" OLD SUBJECT: "' + subject + '"';
subject := trim(edtSubject.Text);
end;
if Memo_Description.Text <> description then begin
comment := comment + 'NEW DESC: "' + trim(Memo_Description.Text) + '" OLD DESC: "' + description + '"';
description := trim(Memo_Description.Text);
end;
if cboCategory.ItemIndex <> category_id then begin
comment := comment + sLineBreak + 'CATEGORY: ' + shared.categories[cboCategory.ItemIndex].name;
category_id := shared.categories[cboCategory.ItemIndex].id;
end;
if shared.users[cboUser.ItemIndex].id_no <> user_id then begin
comment := comment + sLineBreak + 'ASSIGNED USER: ' + shared.users[cboUser.ItemIndex].name;
user_id := shared.users[cboUser.ItemIndex].id_no;
end;
if chkbox_isOpen.Checked then
if chkbox_isOpen.Caption = 'Close Ticket' then begin
comment := comment + sLineBreak + 'Ticket Closed at ' + DateToStr(NOW) + ' by ' + shared.users[findindex(CurrentUser.id_no)].name;
is_open := 0;
end
else if chkbox_isOpen.Caption = 'Reopen Ticket' then begin
comment := comment + sLineBreak + 'Ticket Reopened at ' + DateToStr(NOW) + 'by ' + shared.users[findindex(CurrentUser.id_no)].name;
is_open := 1;
end;
dm.ibq.SQL.Clear;
dm.ibq.SQL.Add('execute procedure update_comment(:id, :user_id, :ticket_id, :comment, :defect_user, :created)');
dm.ibq.ParamByName('id').AsInteger := 0; { 0 autogenerate new id, -1 delete }
dm.ibq.ParamByName('user_id').AsString := CurrentUser.id_no;
dm.ibq.ParamByName('ticket_id').AsInteger := ticket_data.id;
dm.ibq.ParamByName('comment').AsString := comment;
dm.ibq.ParamByName('defect_user').AsString := '';
dm.ibq.ParamByName('created').AsDateTime := Now;
dm.ibq.ExecSQL;
end;
end
end;
if dm.ibt.InTransaction then
dm.ibt.Commit
else
dm.ibt.StartTransaction;
if not chkboxDonotcloseonSave.Checked then begin
Close;
FormMain.lsvRefresh;
end
else begin
loadComments;
end;
end;
end;
procedure TFormTicket.btnCommentClick(Sender: TObject);
begin
FormComment.ShowModal;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLFileDDS<p>
DDS File support for GLScene.
<b>History : </b><font size=-1><ul>
<li>04/11/10 - DaStr - Added Delphi5 and Delphi6 compatibility
<li>23/08/10 - Yar - Replaced OpenGL1x to OpenGLTokens
<li>06/06/10 - Yar - Fixes for Linux x64
<li>08/05/10 - Yar - Removed check for residency in AssignFromTexture
<li>22/04/10 - Yar - Fixes after GLState revision
<li>01/03/10 - Yar - Added control of texture detail level
<li>27/01/10 - Yar - Bugfix in BlockOffset with negative result
<li>23/11/10 - DaStr - Added $I GLScene.inc
<li>23/01/10 - Yar - Added to AssignFromTexture CurrentFormat parameter
Fixed cube map saving bug
<li>20/01/10 - Yar - Creation
</ul><p>
}
unit GLFileDDS;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils,
//GLS
GLCrossPlatform, OpenGLTokens, GLContext, GLGraphics, GLTextureFormat,
GLSrgbe, GLApplicationFileIO, GLVectorGeometry, GLStrings;
type
// TGLDDSResolutions
//
TGLDDSDetailLevels = (ddsHighDet, ddsMediumDet, ddsLowDet);
// TGLDDSImage
//
TGLDDSImage = class(TGLBaseImage)
private
procedure flipSurface(chgData: PGLubyte; w, h, d: integer);
public
class function Capabilities: TDataFileCapabilities; override;
procedure LoadFromFile(const filename: string); override;
procedure SaveToFile(const filename: string); override;
procedure LoadFromStream(stream: TStream); override;
procedure SaveToStream(stream: TStream); override;
{: Assigns from any Texture.}
procedure AssignFromTexture(textureContext: TGLContext;
const textureHandle: TGLuint;
textureTarget: TGLTextureTarget;
const CurrentFormat: Boolean;
const intFormat: TGLInternalFormat); reintroduce;
end;
var
{: Variable determines which resolution to use textures,
high - it loads all levels,
midle - skipped the first level,
low - skipped the first two levels. }
vDDSDetailLevel: TGLDDSDetailLevels = ddsHighDet;
//----------------------------------------------------------------------
//----------------------------------------------------------------------
//----------------------------------------------------------------------
implementation
// ------------------
// ------------------ TGLDDSImage ------------------
// ------------------
uses
DXTC;
// LoadFromFile
//
procedure TGLDDSImage.LoadFromFile(const filename: string);
var
fs: TStream;
begin
if FileStreamExists(fileName) then
begin
fs := CreateFileStream(fileName, fmOpenRead);
try
LoadFromStream(fs);
finally
fs.Free;
ResourceName := filename;
end;
end
else
raise EInvalidRasterFile.CreateFmt(glsFileNotFound, [filename]);
end;
// SaveToFile
//
procedure TGLDDSImage.SaveToFile(const filename: string);
var
fs: TStream;
begin
fs := CreateFileStream(fileName, fmOpenWrite or fmCreate);
try
SaveToStream(fs);
finally
fs.Free;
end;
ResourceName := filename;
end;
// LoadFromStream
//
procedure TGLDDSImage.LoadFromStream(stream: TStream);
var
header: TDDSHeader;
DX10header: TDDS_HEADER_DXT10;
btcCompressed: Boolean;
face, faceCount, level: Integer;
w, h, d, bw, bh, size, offset: Integer;
bDXT10Header: Boolean;
procedure CalcSize;
begin
if btcCompressed then
begin
bw := (w + 3) div 4;
bh := (h + 3) div 4;
end
else
begin
bw := w;
bh := h;
end;
if d = 0 then
d := 1;
size := bw * bh * d * fElementSize;
end;
begin
stream.Read(header, Sizeof(TDDSHeader));
// DDS files always start with the same magic number ("DDS ")
if TFOURCC(header.Magic) <> 'DDS ' then
raise EInvalidRasterFile.Create('Invalid DDS file');
// Verify header to validate DDS file
if (header.SurfaceFormat.dwSize <> sizeof(TDDSURFACEDESC2))
or (header.SurfaceFormat.ddpf.dwSize <> sizeof(TDDPIXELFORMAT)) then
raise EInvalidRasterFile.Create('Invalid DDS file');
// Check for DX10 extension
bDXT10Header := (header.SurfaceFormat.ddpf.dwFlags and DDPF_FOURCC <> 0)
and (header.SurfaceFormat.ddpf.dwFourCC = FOURCC_DX10);
if bDXT10Header then
stream.Read(DX10header, Sizeof(TDDS_HEADER_DXT10));
with header.SurfaceFormat do
begin
{: There are flags that are supposed to mark these fields as valid,
but some dds files don't set them properly }
UnMipmap;
FLOD[0].Width := dwWidth;
FLOD[0].Height := dwHeight;
// check if image is a volume texture
if ((dwCaps2 and DDSCAPS2_VOLUME) <> 0) and (dwDepth > 0) then
FLOD[0].Depth := dwDepth
else
FLOD[0].Depth := 0;
if (dwFlags and DDSD_MIPMAPCOUNT) <> 0 then
fLevelCount := MaxInteger(dwMipMapCount, 1)
else
fLevelCount := 1;
//check cube-map faces
fCubeMap := false;
faceCount := 0;
if (dwCaps2 and DDSCAPS2_CUBEMAP) <> 0 then
begin
//this is a cubemap, count the faces
if (dwCaps2 and DDSCAPS2_CUBEMAP_POSITIVEX) <> 0 then
Inc(faceCount);
if (dwCaps2 and DDSCAPS2_CUBEMAP_NEGATIVEX) <> 0 then
Inc(faceCount);
if (dwCaps2 and DDSCAPS2_CUBEMAP_POSITIVEY) <> 0 then
Inc(faceCount);
if (dwCaps2 and DDSCAPS2_CUBEMAP_NEGATIVEY) <> 0 then
Inc(faceCount);
if (dwCaps2 and DDSCAPS2_CUBEMAP_POSITIVEZ) <> 0 then
Inc(faceCount);
if (dwCaps2 and DDSCAPS2_CUBEMAP_NEGATIVEZ) <> 0 then
Inc(faceCount);
//check for a complete cubemap
if (faceCount <> 6) or (GetWidth <> GetHeight) then
raise EInvalidRasterFile.Create('Invalid cubemap');
fCubeMap := true;
end;
fTextureArray := false;
if not DDSHeaderToGLEnum(header,
DX10header,
bDXT10Header,
fInternalFormat,
fColorFormat,
fDataType,
fElementSize) then
raise EInvalidRasterFile.Create('DDS errorneus format');
btcCompressed := IsCompressedFormat(fInternalFormat);
end; // of with
offset := 0;
case vDDSDetailLevel of
ddsHighDet: ; // Do nothing..
ddsMediumDet:
if fLevelCount > 1 then
begin
w := FLOD[0].Width;
h := FLOD[0].Height;
d := FLOD[0].Depth;
CalcSize;
offset := size;
FLOD[0].Width := FLOD[0].Width div 2;
FLOD[0].Height := FLOD[0].Height div 2;
FLOD[0].Depth := FLOD[0].Depth div 2;
Dec(fLevelCount);
end;
ddsLowDet:
if fLevelCount > 2 then
begin
w := FLOD[0].Width;
h := FLOD[0].Height;
d := FLOD[0].Depth;
CalcSize;
offset := size;
Div2(w);
Div2(h);
Div2(d);
CalcSize;
offset := offset + size;
FLOD[0].Width := FLOD[0].Width div 4;
FLOD[0].Height := FLOD[0].Height div 4;
FLOD[0].Depth := FLOD[0].Depth div 4;
Dec(fLevelCount, 2);
end;
else
Assert(False, glsErrorEx + glsUnknownType);
end;
ReallocMem(fData, DataSize);
if not fCubeMap then
faceCount := 1;
for face := 0 to faceCount - 1 do
begin
if offset > 0 then
stream.Seek(offset, soCurrent);
for level := 0 to fLevelCount - 1 do
begin
stream.Read(GetLevelAddress(level, face)^, GetLevelSizeInByte(level) div faceCount);
if not fCubeMap and vVerticalFlipDDS then
flipSurface(GetLevelAddress(level, face), FLOD[level].Width, FLOD[level].Height, FLOD[level].Depth);
end;
end; // for level
end;
procedure TGLDDSImage.SaveToStream(stream: TStream);
const
Magic: array[0..3] of AnsiChar = 'DDS ';
var
header: TDDSHeader;
DX10header: TDDS_HEADER_DXT10;
buffer: PGLubyte;
level, size: Integer;
begin
FillChar(header, SizeOf(TDDSHeader), 0);
header.Magic := Cardinal(Magic);
header.SurfaceFormat.dwSize := sizeof(TDDSURFACEDESC2);
header.SurfaceFormat.ddpf.dwSize := sizeof(TDDPIXELFORMAT);
header.SurfaceFormat.dwWidth := GetWidth;
header.SurfaceFormat.dwHeight := GetHeight;
header.SurfaceFormat.dwDepth := GetDepth;
header.SurfaceFormat.dwPitchOrLinearSize := fElementSize * GetWidth;
header.SurfaceFormat.dwFlags := DDSD_CAPS or
DDSD_HEIGHT or
DDSD_WIDTH or
DDSD_PIXELFORMAT;
if IsCompressed then
begin
header.SurfaceFormat.dwPitchOrLinearSize :=
header.SurfaceFormat.dwPitchOrLinearSize * Cardinal(GetHeight) *
Cardinal(GetDepth);
header.SurfaceFormat.dwFlags := header.SurfaceFormat.dwFlags or DDSD_PITCH;
end
else
header.SurfaceFormat.dwFlags := header.SurfaceFormat.dwFlags or
DDSD_LINEARSIZE;
header.SurfaceFormat.dwCaps := DDSCAPS_TEXTURE;
header.SurfaceFormat.dwCaps2 := 0;
if IsVolume then
begin
header.SurfaceFormat.dwFlags := header.SurfaceFormat.dwFlags or DDSD_DEPTH;
header.SurfaceFormat.dwCaps := header.SurfaceFormat.dwCaps or
DDSCAPS_COMPLEX;
header.SurfaceFormat.dwCaps2 := header.SurfaceFormat.dwCaps2 or
DDSCAPS2_VOLUME;
end;
if fLevelCount > 1 then
begin
header.SurfaceFormat.dwCaps := header.SurfaceFormat.dwCaps or DDSCAPS_COMPLEX
or DDSCAPS_MIPMAP;
header.SurfaceFormat.dwFlags := header.SurfaceFormat.dwFlags or
DDSD_MIPMAPCOUNT;
header.SurfaceFormat.dwMipMapCount := fLevelCount;
end
else
header.SurfaceFormat.dwMipMapCount := 0;
if fCubeMap then
begin
header.SurfaceFormat.dwCaps := header.SurfaceFormat.dwCaps or
DDSCAPS_COMPLEX;
header.SurfaceFormat.dwCaps2 := header.SurfaceFormat.dwCaps2 or
DDSCAPS2_CUBEMAP or
DDSCAPS2_CUBEMAP_POSITIVEX or
DDSCAPS2_CUBEMAP_NEGATIVEX or
DDSCAPS2_CUBEMAP_POSITIVEY or
DDSCAPS2_CUBEMAP_NEGATIVEY or
DDSCAPS2_CUBEMAP_POSITIVEZ or
DDSCAPS2_CUBEMAP_NEGATIVEZ;
end;
if not GLEnumToDDSHeader(header,
DX10header,
false,
fInternalFormat,
fColorFormat,
fDataType,
fElementSize) then
raise
EInvalidRasterFile.Create('These image format do not match the DDS format specification.');
stream.Write(header, Sizeof(TDDSHeader));
// stream.Write(DX10header, Sizeof(TDDS_HEADER_DXT10));
if fCubeMap or not vVerticalFlipDDS then
begin
stream.Write(fData[0], DataSize);
Exit;
end
else
begin
GetMem(buffer, GetLevelSizeInByte(0));
try
for level := 0 to fLevelCount - 1 do
begin
size := GetLevelSizeInByte(level);
Move(GetLevelAddress(level)^, buffer^, size);
flipSurface(buffer, LevelWidth[level], LevelHeight[level], LevelDepth[level]);
stream.Write(buffer^, size);
end;
finally
FreeMem(buffer);
end;
end;
end;
// AssignFromTexture
//
procedure TGLDDSImage.AssignFromTexture(textureContext: TGLContext;
const textureHandle: TGLuint;
textureTarget: TGLTextureTarget;
const CurrentFormat: Boolean;
const intFormat: TGLInternalFormat);
var
oldContext: TGLContext;
contextActivate: Boolean;
texFormat, texLod, optLod: Cardinal;
level, faceCount, face: Integer;
residentFormat: TGLInternalFormat;
bCompressed: Boolean;
vtcBuffer, top, bottom: PGLubyte;
i, j, k: Integer;
cw, ch: Integer;
glTarget: TGLEnum;
function blockOffset(x, y, z: Integer): Integer;
begin
if z >= (FLOD[level].Depth and -4) then
Result := fElementSize * (cw * ch * (FLOD[level].Depth and -4) + x +
cw * (y + ch * (z - 4 * ch)))
else
Result := fElementSize * (4 * (x + cw * (y + ch * floor(z / 4))) + (z and
3));
if Result < 0 then
Result := 0;
end;
begin
oldContext := CurrentGLContext;
contextActivate := (oldContext <> textureContext);
if contextActivate then
begin
if Assigned(oldContext) then
oldContext.Deactivate;
textureContext.Activate;
end;
glTarget := DecodeGLTextureTarget(textureTarget);
try
textureContext.GLStates.TextureBinding[0, textureTarget] := textureHandle;
fLevelCount := 0;
GL.GetTexParameteriv(glTarget, GL_TEXTURE_MAX_LEVEL, @texLod);
if glTarget = GL_TEXTURE_CUBE_MAP then
begin
fCubeMap := true;
faceCount := 6;
glTarget := GL_TEXTURE_CUBE_MAP_POSITIVE_X;
end
else
begin
fCubeMap := false;
faceCount := 1;
end;
fTextureArray := (glTarget = GL_TEXTURE_1D_ARRAY)
or (glTarget = GL_TEXTURE_2D_ARRAY)
or (glTarget = GL_TEXTURE_CUBE_MAP_ARRAY);
repeat
// Check level existence
GL.GetTexLevelParameteriv(glTarget, fLevelCount,
GL_TEXTURE_INTERNAL_FORMAT,
@texFormat);
if texFormat = 1 then
Break;
Inc(fLevelCount);
if fLevelCount = 1 then
begin
GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_WIDTH, @FLOD[0].Width);
GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_HEIGHT, @FLOD[0].Height);
FLOD[0].Depth := 0;
if (glTarget = GL_TEXTURE_3D)
or (glTarget = GL_TEXTURE_2D_ARRAY)
or (glTarget = GL_TEXTURE_CUBE_MAP_ARRAY) then
GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_DEPTH, @FLOD[0].Depth);
residentFormat := OpenGLFormatToInternalFormat(texFormat);
if CurrentFormat then
fInternalFormat := residentFormat
else
fInternalFormat := intFormat;
if not FindDDSCompatibleDataFormat(fInternalFormat,
fColorFormat,
fDataType) then
FindCompatibleDataFormat(fInternalFormat,
fColorFormat,
fDataType);
// Get optimal number or MipMap levels
optLod := GetImageLodNumber(FLOD[0].Width, FLOD[0].Height, FLOD[0].Depth, glTarget = GL_TEXTURE_3D);
if texLod > optLod then
texLod := optLod;
// Check for MipMap posibility
if ((fInternalFormat >= tfFLOAT_R16)
and (fInternalFormat <= tfFLOAT_RGBA32)) then
texLod := 1;
end;
until fLevelCount = Integer(texLod);
if fLevelCount > 0 then
begin
fElementSize := GetTextureElementSize(fColorFormat, fDataType);
ReallocMem(FData, DataSize);
bCompressed := IsCompressed;
vtcBuffer := nil;
for face := 0 to faceCount - 1 do
begin
if fCubeMap then
glTarget := face + GL_TEXTURE_CUBE_MAP_POSITIVE_X;
for level := 0 to fLevelCount - 1 do
begin
if bCompressed then
begin
if GL.NV_texture_compression_vtc and (FLOD[level].Depth > 0)
and not fTextureArray then
begin
if level = 0 then
GetMem(vtcBuffer, GetLevelSizeInByte(0));
GL.GetCompressedTexImage(glTarget, level, vtcBuffer);
// Shufle blocks from VTC to S3TC
cw := (FLOD[level].Width + 3) div 4;
ch := (FLOD[level].Height + 3) div 4;
top := GetLevelAddress(level);
for k := 0 to FLOD[level].Depth - 1 do
for i := 0 to ch - 1 do
for j := 0 to cw - 1 do
begin
bottom := vtcBuffer;
Inc(bottom, blockOffset(j, i, k));
Move(bottom^, top^, fElementSize);
Inc(top, fElementSize);
end;
end
else
GL.GetCompressedTexImage(glTarget, level, GetLevelAddress(level));
end
else
GL.GetTexImage(glTarget, level, fColorFormat, fDataType, GetLevelAddress(level));
end; // for level
end; // for face
if Assigned(vtcBuffer) then
FreeMem(vtcBuffer);
// Check memory corruption
ReallocMem(FData, DataSize);
end;
if fLevelCount < 1 then
fLevelCount := 1;
GL.CheckError;
finally
if contextActivate then
begin
textureContext.Deactivate;
if Assigned(oldContext) then
oldContext.Activate;
end;
end;
end;
procedure TGLDDSImage.flipSurface(chgData: PGLubyte; w, h, d: integer);
var
lineSize: integer;
sliceSize: integer;
tempBuf: PGLubyte;
i, j: integer;
top, bottom: PGLubyte;
flipblocks: procedure(data: PGLubyte; size: integer);
begin
if d = 0 then
d := 1;
if not isCompressed then
begin
lineSize := fElementSize * w;
sliceSize := lineSize * h;
GetMem(tempBuf, lineSize);
for i := 0 to d - 1 do
begin
top := chgData;
Inc(top, i * sliceSize);
bottom := top;
Inc(bottom, sliceSize - lineSize);
for j := 0 to (h div 2) - 1 do
begin
Move(top^, tempBuf^, lineSize);
Move(bottom^, top^, lineSize);
Move(tempBuf^, bottom^, lineSize);
Inc(top, lineSize);
Dec(bottom, lineSize);
end;
end;
FreeMem(tempBuf);
end
else
begin
w := (w + 3) div 4;
h := (h + 3) div 4;
case fColorFormat of
GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: flipblocks := flip_blocks_dxtc1;
GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: flipblocks := flip_blocks_dxtc3;
GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: flipblocks := flip_blocks_dxtc5;
else
exit;
end;
lineSize := fElementSize * w;
sliceSize := lineSize * h;
GetMem(tempBuf, lineSize);
for i := 0 to d - 1 do
begin
top := chgData;
Inc(top, i * sliceSize);
bottom := top;
Inc(bottom, sliceSize - lineSize);
for j := 0 to (h div 2) - 1 do
begin
if top = bottom then
begin
flipblocks(top, w);
break;
end;
flipblocks(top, w);
flipblocks(bottom, w);
Move(top^, tempBuf^, lineSize);
Move(bottom^, top^, lineSize);
Move(tempBuf^, bottom^, lineSize);
Inc(top, lineSize);
Dec(bottom, lineSize);
end;
end;
FreeMem(tempBuf);
end;
end;
// Capabilities
//
class function TGLDDSImage.Capabilities: TDataFileCapabilities;
begin
Result := [dfcRead, dfcWrite];
end;
initialization
{ Register this Fileformat-Handler with GLScene }
RegisterRasterFormat('dds', 'Direct Draw Surface', TGLDDSImage);
end.
|
unit Net.Core;
interface
uses
App.IHandlerCore,
Net.Server,
Net.ConnectedClient,
Net.Client,
Net.Types,
System.SysUtils,
System.Types,
System.Classes,
System.Threading,
System.Net.Socket,
System.Generics.Collections;
type
TNetCore = class
private
NodesHosts: array of string;
Server: TServer;
FClient: TClient;
FHandler: IBaseHandler;
NeedDestroySelf: Boolean;
procedure Handle(From: TConnectedClient; AData: TBytes);
procedure NewConHandle(SocketIP: String);
procedure DeleteConnectedClient(AID: integer);
function GetServerStatus: boolean;
function GetFreeArraySell: uint64;
procedure NilConClient(arg: Boolean);
public
ConnectedClients: TArray<TConnectedClient>;
property ServerStarted: boolean read GetServerStatus;
property Handler: IBaseHandler read FHandler write FHandler;
property DestroyNetCore: Boolean write NeedDestroySelf;
property Client: TClient read FClient write FClient;
procedure Start;
procedure Stop;
function IsActive: Boolean;
constructor Create(AHandler: IBaseHandler);
destructor Destroy; override;
end;
implementation
{$REGION 'TNetCore'}
constructor TNetCore.Create(AHandler: IBaseHandler);
var
id: uint64;
begin
{$IFDEF DEBUG}
NodesHosts := ['127.0.0.1'];
{$ENDIF}
NeedDestroySelf := False;
SetLength(ConnectedClients, 0);
Server := TServer.Create;
FHandler := AHandler;
Server.AcceptHandle := (
procedure(ConnectedCli: TConnectedClient)
begin
ConnectedCli.Handle := Handle;
id := GetFreeArraySell;
ConnectedCli.IdInArray := id;
ConnectedCli.AfterDisconnect := DeleteConnectedClient;
ConnectedClients[id] := ConnectedCli;
end);
Server.NewConnectHandle := NewConHandle;
Client := TClient.Create(AHandler);
Client.BeforeDestroy := NilConClient;
end;
procedure TNetCore.DeleteConnectedClient(AID: integer);
begin
ConnectedClients[AID] := nil;
end;
destructor TNetCore.Destroy;
begin
Server.Free;
Client.Free;
Server := nil;
SetLength(ConnectedClients, 0);
FHandler := nil;
end;
function TNetCore.GetFreeArraySell: uint64;
var
i, len: integer;
begin
len := Length(ConnectedClients);
Result := len;
for i := 0 to len - 1 do
if (ConnectedClients[i] = nil) then
begin
Result := i;
exit;
end;
SetLength(ConnectedClients, len + 1);
end;
function TNetCore.GetServerStatus: boolean;
begin
GetServerStatus := Server.isActive;
end;
procedure TNetCore.Handle(From: TConnectedClient; AData: TBytes);
begin
FHandler.HandleReceiveTCPData(From,AData);
end;
function TNetCore.IsActive: Boolean;
begin
Result := Server.isActive;
end;
procedure TNetCore.NewConHandle(SocketIP: String);
begin
FHandler.HandleConnectClient(SocketIP);
end;
procedure TNetCore.NilConClient(arg: Boolean);
begin
Client := nil;
end;
procedure TNetCore.Start;
begin
Server.Start;
Client.TryConnect(NodesHosts[0],30000);
end;
procedure TNetCore.Stop;
var
i: uint64;
begin
for i := 0 to Length(ConnectedClients) - 1 do
if (ConnectedClients[i] <> nil) then
ConnectedClients[i].Disconnect;
Server.Stop;
if NeedDestroySelf then
Free;
end;
{$ENDREGION}
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMS.Consts;
interface
resourcestring
sBodyTypeNotFound = 'Body does not contain %s';
sAddNotSupported = 'Add not supported';
sNameNotFound = 'Name not found: %s';
sNoEndpointImplementationFound = 'No endpoint implementation found';
sHeaderNotFound = 'Header not found: %s';
sSetValueNotSupported = 'SetValue not supported';
sDuplicateEndpoints = 'Duplicate endpoints: %0:s. Each endpoint must have an unique HTTP method, URL or produce / consume types';
sConstructorNotFound = 'Constructor not found for %s';
sUnrecognizedEndpointMethodSignature = 'Unrecognized signature for endpoint method %0:s.%1s';
sInvalidAttributeUsage = 'Attribute with method name cannot be specified for endpoint method: %s';
sResourceErrorMessage = 'Resource error';
sEndpointCantProduce = 'Endpoint found, but it cannot produce requested MIME type';
sEndpointCantConsume = 'Endpoint found, but it cannot consume specified MIME type';
sUnauthorizedDescription = 'The credentials of the request are not authorized for the requested operation.';
sUnauthorizedMessage = 'Unauthorized request';
sNotFoundDescription = 'The request does not identify a known application, resource, endpoint, entity or static item';
sNotFoundMessage = 'Not found';
sForbiddenDescription = 'The request is for an operation that is not allowed';
sForbiddenMessage = 'Forbidden';
sBadRequestDescription = 'The request has unexpected or missing query parameters, url segments or request body';
sBadRequestMessage = 'Bad request';
sDuplicateDescription = 'The request is to create or rename an entity, with a name already in use';
sDuplicateMessage = 'Duplicate';
sInvalidTenant = 'TenantId or TenantSecret is not valid';
sNotAcceptable = 'Not acceptable';
sUnsupportedMedia = 'Unsupported media type';
sGroupNotFound = 'Group not found: %s';
sChannelNamesExpected = 'Channel names expected';
sSwaggerVersion = '2.0';
sEMSMetaDataVersion = '0.0.0';
sEMSMetaDataTitle = 'EMS API Documentation';
sEMSMetaDataDescription = 'Enterprise Mobility Services API' + sLineBreak + sLineBreak +
' [Learn about EMS](https://www.embarcadero.com/products/rad-studio/enterprise-mobility-services)' + sLineBreak + sLineBreak +
' EMS (Enterprise Mobility Services) offers a Mobile Enterprise Application Platform (MEAP)'+ sLineBreak + sLineBreak +
' TurnKey Middleware for Interconnected Distributed Apps';
sAuthHeaderDesc = 'Header used by the EMS server';
sDataSetNotAssigned = 'DataSet is not assigned to DB resource';
sCannotGuessMappingMode = 'Cannot guess mapping mode for dataset';
sKeyFieldsNotDefined = 'Key fields are not defined for dataset';
sInvalidDataSetAdaptor = 'Invalid dataset adaptor registration information';
sDataSetAdaptorNotFound = 'Dataset adaptor class is not found';
sDataSetAdaptorNoPaging = 'Paging is not supported';
sDataSetAdaptorInvalidPaging = 'Invalid value for paging parameter';
sDataSetAdaptorNoSorting = 'Sorting is not supported';
sDataSetAdaptorInvalidSorting = 'Invalid value for sorting parameter';
sDataSetAdaptorNoContentType = 'Response content type is not set';
implementation
end.
|
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
namespace WebView;
interface
uses
System,
System.Collections.Generic,
System.IO,
System.Linq,
System.Runtime.InteropServices.WindowsRuntime,
Windows.ApplicationModel,
Windows.ApplicationModel.Activation,
Windows.Foundation,
Windows.Foundation.Collections,
Windows.UI.Xaml,
Windows.UI.Xaml.Controls,
Windows.UI.Xaml.Controls.Primitives,
Windows.UI.Xaml.Data,
Windows.UI.Xaml.Input,
Windows.UI.Xaml.Media,
Windows.UI.Xaml.Navigation;
type
App = partial class(Application)
private
method OnNavigationFailed(sender: Object; e: NavigationFailedEventArgs);
method OnSuspending(sender: Object; e: SuspendingEventArgs);
protected
method OnLaunched(e: LaunchActivatedEventArgs); override;
public
constructor;
end;
implementation
constructor App;
begin
self.InitializeComponent();
self.Suspending += OnSuspending;
end;
method App.OnLaunched(e: LaunchActivatedEventArgs);
begin
{$ifdef DEBUG}
if System.Diagnostics.Debugger.IsAttached then begin
self.DebugSettings.EnableFrameRateCounter := true;
end;
{$endif}
var rootFrame: Frame := Frame(Window.Current.Content);
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if rootFrame = nil then begin
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame := new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if e.PreviousExecutionState = ApplicationExecutionState.Terminated then begin
// TODO: Load state from previously suspended application
end;
// Place the frame in the current Window
Window.Current.Content := rootFrame;
end;
if rootFrame.Content = nil then begin
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeOf(MainPage), e.Arguments);
end;
// Ensure the current window is active
Window.Current.Activate();
end;
method App.OnNavigationFailed(sender: Object; e: NavigationFailedEventArgs);
begin
raise new Exception('Failed to load Page ' + e.SourcePageType.FullName);
end;
method App.OnSuspending(sender: Object; e: SuspendingEventArgs);
begin
var deferral := e.SuspendingOperation.GetDeferral();
// TODO: Save application state and stop any background activity
deferral.Complete();
end;
end. |
{
Copyright (C) Alexey Torgashin, uvviewsoft.com
License: MPL 2.0 or LGPL
}
unit ATSynEdit_Cmp_Form;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics,
Dialogs, ExtCtrls,
LCLProc, LCLType,
ATSynEdit,
ATListbox;
type
TATCompletionPropEvent = procedure (Sender: TObject;
AContent: TStringList; out ACharsLeft, ACharsRight: integer) of object;
TATCompletionResultEvent = procedure (Sender: TObject;
const ASnippetId: string; ASnippetIndex: integer) of object;
{
AContent is a list of strings. Each string is '|'-separated items.
Usually item_0 is prefix to show,
item_1 is actual text (inserted on Enter),
item_2, item_3 etc are only to show in listbox.
e.g. 'func|FuncOne|'
'func|FuncTwo|(param1, param2)'#9'Function help'
'var|VarName1|'
'var|VarName2|'#9'Some description'
Also item_1 can have suffixes after chr(1): text+#1+suffix_before_caret+#1+suffix_after_caret.
Also you can append #9'Text' to show a description in a tooltip out of the listbox.
}
procedure EditorShowCompletionListbox(AEd: TATSynEdit;
AOnGetProp: TATCompletionPropEvent;
AOnResult: TATCompletionResultEvent = nil;
AOnChoose: TATCompletionResultEvent = nil;
const ASnippetId: string = '';
ASelectedIndex: integer = 0;
AAllowCarets: boolean = false);
procedure EditorGetCurrentWord(Ed: TATSynEdit;
APosX, APosY: integer;
const ANonWordChars: UnicodeString;
out AWord: UnicodeString;
out ACharsLeft, ACharsRight: integer);
type
{ TFormATSynEditComplete }
TFormATSynEditComplete = class(TForm)
Listbox: TATListbox;
TimerUpdater: TTimer;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure FormUTF8KeyPress(Sender: TObject; var UTF8Key: TUTF8Char);
procedure ListboxClick(Sender: TObject);
procedure ListboxDrawItem(Sender: TObject; C: TCanvas; AIndex: integer; const ARect: TRect);
procedure TimerUpdaterTimer(Sender: TObject);
private
{ private declarations }
FTimerClosing: TTimer;
SList: TStringlist;
FOnGetProp: TATCompletionPropEvent;
FOnResult: TATCompletionResultEvent;
FOnChoose: TATCompletionResultEvent;
FEdit: TATSynEdit;
FCharsLeft,
FCharsRight: integer;
FHintWnd: THintWindow;
FSnippetId: string;
FSelectedIndex: integer;
FOldCaretStopUnfocused: boolean;
FOldDimUnfocusedBack: integer;
FOldSaved: boolean;
FUpdateForCaret: TPoint;
procedure DoHintHide;
procedure DoHintShow(const AHint: string);
procedure DoReplaceTo(const AStr: string; AWithBracket: boolean);
procedure DoResult;
procedure DoUpdate;
function GetItemText(const AText: string; AIndex: integer): string;
procedure GetResultText(out AText: string; out AWithBracket: boolean);
procedure EditorOptionsSave;
procedure EditorOptionsRestore;
procedure SetEditor(AValue: TATSynEdit);
procedure TimerClosingTimer(Sender: TObject);
procedure UpdateListboxItemHeight;
public
{ public declarations }
property Editor: TATSynEdit read FEdit write SetEditor;
property OnGetProp: TATCompletionPropEvent read FOnGetProp write FOnGetProp;
//OnResult must handle: insertion of final result (and anything after insertion)
//if OnResult is set, OnChoose won't be called
property OnResult: TATCompletionResultEvent read FOnResult write FOnResult;
//OnChoose must handle: moment _after_ insertion of final result
property OnChoose: TATCompletionResultEvent read FOnChoose write FOnChoose;
property SnippetId: string read FSnippetId write FSnippetId;
property SelectedIndex: integer read FSelectedIndex write FSelectedIndex;
end;
const
cCompletionColumnCount = 5;
type
TATCompletionUpDownAtEdge = (
cudIgnore,
cudWrap,
cudCloseForm
);
TATCompletionOptions = record
MonoFont: boolean;
CommitIfSingleItem: boolean;
ColorFontPrefix: TColor;
ColorFontParams: TColor;
CommitChars: string;
CloseChars: string;
IndexOfText: integer;
IndexOfDesc: integer;
ColumnsSep: char;
HintSep: char;
HintMultiLineSep: char;
HintOnlyInTooltip: boolean;
SuffixSep: char; //after completion value it can be 2 suffixes: value+sep+suffix1+sep+suffix2; and suffix2 won't shift caret.X
AppendOpeningBracket: boolean;
TrailingCharToShowAgain: char;
ListSort: boolean;
UpDownAtEdge: TATCompletionUpDownAtEdge;
BorderSize: integer;
FormWidth: integer;
FormMaxVisibleItems: integer;
HintWidth: integer;
TextIndentLeftCol: integer;
TextIndentRightCol: integer;
TextIndent: integer;
ClosingTimerInverval: integer;
ShortcutForAutocomplete: TShortCut;
CommandForShitchTab: integer;
end;
const
CompletionSignatureHTML = '<html>';
var
CompletionOps: TATCompletionOptions;
var
FormAutoCompletion: TFormATSynEditComplete = nil;
procedure CloseFormAutoCompletion;
implementation
uses
ATCanvasPrimitives,
ATStrings,
ATStringProc,
ATStringProc_Separator,
ATSynEdit_Carets,
ATSynEdit_Commands,
ATSynEdit_Cmp_RenderHTML,
ATSynEdit_Keymap,
ATFlatThemes,
Math;
{$R *.lfm}
procedure CloseFormAutoCompletion;
begin
if Assigned(FormAutoCompletion) and FormAutoCompletion.Visible then
FormAutoCompletion.Close;
end;
function EditorGetLefterWordChars(Ed: TATSynEdit; AX, AY: integer): integer;
var
St: TATStrings;
i: integer;
SLine: UnicodeString;
begin
Result:= 0;
St:= Ed.Strings;
if not St.IsIndexValid(AY) then exit;
if AX>St.LinesLen[AY] then exit;
SLine:= St.LineSub(AY, 1, AX);
for i:= AX-1 downto 0 do
begin
if not IsCharWord(SLine[i+1], Ed.OptNonWordChars) then
Break;
Inc(Result);
end;
end;
procedure EditorShowCompletionListbox(AEd: TATSynEdit;
AOnGetProp: TATCompletionPropEvent;
AOnResult: TATCompletionResultEvent = nil;
AOnChoose: TATCompletionResultEvent = nil;
const ASnippetId: string = '';
ASelectedIndex: integer = 0;
AAllowCarets: boolean = false);
begin
if AEd.ModeReadOnly then exit;
if AEd.Carets.Count>1 then
if not AAllowCarets then exit;
if FormAutoCompletion=nil then
FormAutoCompletion:= TFormATSynEditComplete.Create(nil);
FormAutoCompletion.Listbox.ItemIndex:= 0;
FormAutoCompletion.Listbox.ItemTop:= 0;
FormAutoCompletion.Editor:= AEd;
FormAutoCompletion.SelectedIndex:= ASelectedIndex;
FormAutoCompletion.SnippetId:= ASnippetId;
FormAutoCompletion.OnGetProp:= AOnGetProp;
FormAutoCompletion.OnResult:= AOnResult;
FormAutoCompletion.OnChoose:= AOnChoose;
FormAutoCompletion.DoUpdate;
end;
procedure TFormATSynEditComplete.DoReplaceTo(const AStr: string; AWithBracket: boolean);
var
Caret: TATCaretItem;
Pos, Shift, PosAfter: TPoint;
StrText, Str1, Str2, StrToInsert: atString;
Sep: TATStringSeparator;
NCharsLeftNew: integer;
iCaret: integer;
begin
if AStr='' then exit;
if Editor.Carets.Count=0 then exit;
Sep.Init(AStr, CompletionOps.SuffixSep);
Sep.GetItemStr(StrText);
Sep.GetItemStr(Str1);
Sep.GetItemStr(Str2);
//must support multi-carets, for HTML
Editor.Strings.BeginUndoGroup;
try
for iCaret:= 0 to Editor.Carets.Count-1 do
begin
Caret:= Editor.Carets[iCaret];
Pos.X:= Caret.PosX;
Pos.Y:= Caret.PosY;
//updated count of word-chars lefter than caret;
//it is different, when in CudaText user types fast and auto-completion auto-show triggers
NCharsLeftNew:= EditorGetLefterWordChars(Editor, Pos.X, Pos.Y);
FCharsLeft:= Min(Pos.X, FCharsLeft);
if FCharsLeft<NCharsLeftNew then
FCharsLeft:= NCharsLeftNew;
Dec(Pos.X, FCharsLeft);
Editor.Strings.TextDeleteRight(Pos.X, Pos.Y, FCharsLeft+FCharsRight, Shift, PosAfter, false);
StrToInsert:= StrText+Str1+Str2;
if AWithBracket then
if Editor.Strings.TextSubstring(Pos.X, Pos.Y, Pos.X+1, Pos.Y)<>'(' then
begin
StrToInsert+= '()';
Str2:= ')';
end;
Editor.Strings.TextInsert(Pos.X, Pos.Y, StrToInsert, false, Shift, PosAfter);
//adjust markers/attrs
Editor.UpdateCaretsAndMarkersOnEditing(iCaret+1,
Pos,
Pos,
Point(Length(StrToInsert) - FCharsLeft-FCharsRight, 0),
PosAfter
);
Caret.PosX:= Pos.X+Length(StrToInsert)-Length(Str2);
Caret.EndX:= -1;
Caret.EndY:= -1;
end;
finally
Editor.Strings.EndUndoGroup;
Editor.DoEventChange(Editor.Carets[0].PosY);
Editor.Update(true);
end;
end;
{ TFormATSynEditComplete }
procedure TFormATSynEditComplete.FormCreate(Sender: TObject);
begin
SList:= TStringList.Create;
SList.TextLineBreakStyle:= tlbsLF;
FHintWnd:= THintWindow.Create(Self);
end;
procedure TFormATSynEditComplete.FormDeactivate(Sender: TObject);
begin
Close;
EditorOptionsRestore;
end;
procedure TFormATSynEditComplete.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
begin
DoHintHide;
TimerUpdater.Enabled:= false;
CloseAction:= caHide;
//force focus to editor, fix CudaText issue #4111
if FEdit.Visible and FEdit.Enabled and FEdit.CanFocus then
FEdit.SetFocus;
{
//fix stopped caret blinking (could not find the real reason why blinking stops),
//if pressing Esc with auto-completion opened
FEdit.DoCommand(1{some not existing command}, TATCommandInvoke.Internal);
}
//above commented block is not needed after the fix in CudaText #5054, FEdit.Update is enough
FEdit.Update;
end;
procedure TFormATSynEditComplete.FormDestroy(Sender: TObject);
begin
SList.Free;
end;
procedure TFormATSynEditComplete.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
NShortCut: TShortCut;
KeyHistory: TATKeyArray;
NCommand: integer;
begin
case Key of
VK_CONTROL,
VK_SHIFT:
Exit;
VK_MENU:
begin
Key:= 0; //fix mainform loosing focus after pressing Alt/Alt in completion form
Exit;
end;
end;
if (Key=VK_UP) and (Shift=[]) then
begin
if Listbox.ItemIndex>0 then
Listbox.ItemIndex:= Listbox.ItemIndex-1
else
case CompletionOps.UpDownAtEdge of
cudWrap:
Listbox.ItemIndex:= Listbox.ItemCount-1;
cudCloseForm:
Close;
end;
Key:= 0;
exit
end;
if (Key=VK_DOWN) and (Shift=[]) then
begin
if Listbox.ItemIndex<Listbox.ItemCount-1 then
Listbox.ItemIndex:= Listbox.ItemIndex+1
else
case CompletionOps.UpDownAtEdge of
cudWrap:
Listbox.ItemIndex:= 0;
cudCloseForm:
Close;
end;
Key:= 0;
exit
end;
if (Key=VK_PRIOR) and (Shift=[]) then
begin
Listbox.ItemIndex:= Max(0, Listbox.ItemIndex-Listbox.VisibleItems);
Key:= 0;
exit
end;
if (Key=VK_NEXT) and (Shift=[]) then
begin
Listbox.ItemIndex:= Min(Listbox.ItemCount-1, Listbox.ItemIndex+Listbox.VisibleItems);
Key:= 0;
exit
end;
//in many editors, Home/End move caret to edge of the line, w/o listbox navigation
if (Key=VK_HOME) and (Shift=[]) then
begin
Close;
Editor.DoCommand(cCommand_KeyHome, TATCommandInvoke.Hotkey);
Key:= 0;
exit;
end;
if (Key=VK_END) and (Shift=[]) then
begin
Close;
Editor.DoCommand(cCommand_KeyEnd, TATCommandInvoke.Hotkey);
Key:= 0;
exit;
end;
if (Key=VK_ESCAPE) and (Shift=[]) then
begin
Close;
Key:= 0;
exit
end;
if ((Key=VK_RETURN) or (Key=VK_TAB)) and (Shift=[]) then
begin
DoResult;
Key:= 0;
exit
end;
if (Key=VK_LEFT) and (Shift=[]) then
begin
Editor.DoCommand(cCommand_KeyLeft, TATCommandInvoke.Hotkey);
DoUpdate;
Key:= 0;
exit
end;
if (Key=VK_RIGHT) and (Shift=[]) then
begin
Editor.DoCommand(cCommand_KeyRight, TATCommandInvoke.Hotkey);
DoUpdate;
Key:= 0;
exit
end;
if (Key=VK_DELETE) and (Shift=[]) then
begin
Editor.DoCommand(cCommand_KeyDelete, TATCommandInvoke.Hotkey);
DoUpdate;
Key:= 0;
exit
end;
if (Key=VK_BACK) and (Shift=[]) then
begin
Editor.DoCommand(cCommand_KeyBackspace, TATCommandInvoke.Hotkey);
DoUpdate;
Key:= 0;
exit
end;
NShortCut:= KeyToShortCut(Key, Shift);
if NShortCut=0 then exit;
KeyHistory.Clear;
NCommand:= Editor.Keymap.GetCommandFromShortcut(NShortcut, KeyHistory);
case NCommand of
0:
exit;
//some commands must be supported without closing the listbox
cCommand_TextDeleteWordPrev, //Ctrl+BackSpace
cCommand_TextDeleteWordNext: //Ctrl+Delete
begin
Editor.DoCommand(NCommand, TATCommandInvoke.Hotkey);
DoUpdate;
Key:= 0;
exit;
end;
//some commands must be supported which close the listbox
cCommand_Undo,
cCommand_Redo,
cCommand_KeyLeft_Sel, //Shift+Left
cCommand_KeyRight_Sel, //Shift+Right
cCommand_KeyHome_Sel, //Shift+Home
cCommand_KeyEnd_Sel, //Shift+End
cCommand_GotoTextBegin,
cCommand_GotoTextEnd,
cCommand_GotoWordNext,
cCommand_GotoWordPrev,
cCommand_GotoWordEnd,
cCommand_GotoWordNext_Simple,
cCommand_GotoWordPrev_Simple,
cCommand_GotoTextBegin_Sel,
cCommand_GotoTextEnd_Sel,
cCommand_GotoWordNext_Sel,
cCommand_GotoWordPrev_Sel,
cCommand_GotoWordEnd_Sel,
cCommand_GotoWordNext_Simple_Sel,
cCommand_GotoWordPrev_Simple_Sel,
cCommand_Clipboard_Begin..cCommand_Clipboard_End:
begin
Close;
Editor.DoCommand(NCommand, TATCommandInvoke.Hotkey);
Key:= 0;
exit;
end;
end;
if (NCommand=CompletionOps.CommandForShitchTab) then
begin
Close;
Editor.DoCommand(NCommand, TATCommandInvoke.Hotkey);
Key:= 0;
exit;
end;
end;
procedure TFormATSynEditComplete.FormShow(Sender: TObject);
begin
if (FSelectedIndex>=0) and (FSelectedIndex<Listbox.ItemCount) then
Listbox.ItemIndex:= FSelectedIndex;
end;
procedure TFormATSynEditComplete.FormUTF8KeyPress(Sender: TObject;
var UTF8Key: TUTF8Char);
var
bCommitChar, bCloseChar: boolean;
begin
inherited;
//backsp
if (UTF8Key=#8) then
begin
FEdit.DoCommand(cCommand_KeyBackspace, TATCommandInvoke.Hotkey);
DoUpdate;
UTF8Key:= '';
exit;
end;
//skip control Ascii chars
if Ord(UTF8Key[1])<32 then Exit;
bCommitChar:= Pos(UTF8Key, CompletionOps.CommitChars)>0;
bCloseChar:= Pos(UTF8Key, CompletionOps.CloseChars)>0;
if bCommitChar then
DoResult;
FEdit.DoCommand(cCommand_TextInsert, TATCommandInvoke.Hotkey, UTF8Decode(UTF8Key));
if bCommitChar or bCloseChar then
Close
else
DoUpdate;
UTF8Key:= '';
end;
procedure TFormATSynEditComplete.ListboxClick(Sender: TObject);
begin
DoResult;
end;
function TFormATSynEditComplete.GetItemText(const AText: string; AIndex: integer): string;
var
Sep: TATStringSeparator;
i: integer;
begin
Sep.Init(AText, CompletionOps.ColumnsSep);
for i:= 0 to AIndex do
Sep.GetItemStr(Result);
end;
procedure TFormATSynEditComplete.GetResultText(out AText: string; out AWithBracket: boolean);
var
N: integer;
SDesc: string;
begin
AText:= '';
AWithBracket:= false;
N:= Listbox.ItemIndex;
if (N>=0) and (N<SList.Count) then
begin
AText:= GetItemText(SList[N], CompletionOps.IndexOfText);
SDesc:= GetItemText(SList[N], CompletionOps.IndexOfDesc);
AWithBracket:=
CompletionOps.AppendOpeningBracket and
SBeginsWith(SDesc, '(');
end;
end;
procedure TFormATSynEditComplete.EditorOptionsSave;
begin
if not FOldSaved then
begin
FOldSaved:= true;
FOldCaretStopUnfocused:= Editor.OptCaretStopUnfocused;
FOldDimUnfocusedBack:= Editor.OptDimUnfocusedBack;
Editor.OptCaretStopUnfocused:= false;
Editor.OptDimUnfocusedBack:= 0;
end;
end;
procedure TFormATSynEditComplete.EditorOptionsRestore;
begin
if Assigned(FEdit) then
begin
if FOldSaved then
begin
FOldSaved:= false;
FEdit.OptCaretStopUnfocused:= FOldCaretStopUnfocused;
FEdit.OptDimUnfocusedBack:= FOldDimUnfocusedBack;
end;
//make caret visible!
FEdit.DoGotoCaret(cEdgeTop);
end;
end;
procedure TFormATSynEditComplete.SetEditor(AValue: TATSynEdit);
begin
if FEdit=AValue then Exit;
FEdit:= AValue;
if Assigned(FEdit) then
Parent:= GetParentForm(FEdit)
else
Parent:= nil;
end;
procedure _TextOut(C: TCanvas; X, Y: integer; const Text: string);
begin
if SBeginsWith(Text, CompletionSignatureHTML) then
CanvasTextOutHTML(C, X, Y, Copy(Text, Length(CompletionSignatureHTML)+1, MaxInt))
else
begin
C.Brush.Style:= bsSolid;
C.TextOut(X, Y, Text);
end;
end;
function _TextWidth(C: TCanvas; const Text: string): integer;
begin
if SBeginsWith(Text, CompletionSignatureHTML) then
Result:= CanvasTextWidthHTML(C, Copy(Text, Length(CompletionSignatureHTML)+1, MaxInt))
else
Result:= C.TextWidth(Text);
end;
procedure TFormATSynEditComplete.ListboxDrawItem(Sender: TObject; C: TCanvas;
AIndex: integer; const ARect: TRect);
var
Sep: TATStringSeparator;
SLongItem, SItem, SHint: string;
NSize, i: integer;
begin
if (AIndex<0) or (AIndex>=SList.Count) then exit;
SLongItem:= SList[AIndex];
if AIndex=Listbox.ItemIndex then
C.Brush.Color:= ATFlatTheme.ColorBgListboxSel
else
C.Brush.Color:= ATFlatTheme.ColorBgListbox;
C.FillRect(ARect);
if CompletionOps.MonoFont then
begin
C.Font.Name:= ATFlatTheme.MonoFontName;
C.Font.Size:= ATFlatTheme.DoScaleFont(ATFlatTheme.MonoFontSize);
end
else
begin
C.Font.Name:= ATFlatTheme.FontName;
C.Font.Size:= ATFlatTheme.DoScaleFont(ATFlatTheme.FontSize);
end;
//alternate listbox: OnResult is set, then 3 columns, tab-separated:
//paint column1 at left,
//paint column2 at right
if Assigned(FOnResult) then
begin
Sep.Init(SLongItem, #9);
Sep.GetItemStr(SItem);
Sep.GetItemStr(SHint);
//text
C.Font.Color:= ATFlatTheme.ColorFontListbox;
_TextOut(C,
ARect.Left+CompletionOps.TextIndentLeftCol,
ARect.Top,
SItem
);
//prefix
C.Font.Color:= CompletionOps.ColorFontPrefix;
_TextOut(C,
ARect.Left+Listbox.ClientWidth-_TextWidth(C, SHint)-CompletionOps.TextIndentRightCol,
ARect.Top,
SHint+' ' //add space to overlap too long left columns
);
exit;
end;
//usual case, n columns, tab-char separates hint (in hint window)
SHint:= '';
if Pos(CompletionOps.HintSep, SLongItem)>0 then
begin
SSplitByChar(SLongItem, CompletionOps.HintSep, SItem, SHint);
if CompletionOps.HintOnlyInTooltip then
SLongItem:= SItem;
SHint:= StringReplace(SHint, CompletionOps.HintMultiLineSep, #10, [rfReplaceAll]);
end;
if AIndex=Listbox.ItemIndex then
if SHint<>'' then
DoHintShow(SHint)
else
DoHintHide;
NSize:= CompletionOps.TextIndentLeftCol;
Sep.Init(SLongItem, CompletionOps.ColumnsSep);
for i:= 0 to cCompletionColumnCount-1 do
begin
Sep.GetItemStr(SItem);
if i=CompletionOps.IndexOfText then
SItem:= SGetItem(SItem, CompletionOps.SuffixSep);
if i=CompletionOps.IndexOfText then
C.Font.Color:= ATFlatTheme.ColorFontListbox
else
if i=CompletionOps.IndexOfDesc then
C.Font.Color:= CompletionOps.ColorFontParams
else
C.Font.Color:= CompletionOps.ColorFontPrefix;
_TextOut(C,
ARect.Left+NSize,
ARect.Top,
SItem
);
Inc(NSize, _TextWidth(C, SItem)+CompletionOps.TextIndent);
end;
end;
procedure TFormATSynEditComplete.DoResult;
var
Str: string;
bWithBracket: boolean;
begin
Str:= '';
bWithBracket:= false;
if Assigned(FOnResult) then
FOnResult(Self, FSnippetId, Listbox.ItemIndex)
else
begin
GetResultText(Str, bWithBracket);
DoReplaceTo(Str, bWithBracket);
if Assigned(FOnChoose) then
FOnChoose(Self, Str, Listbox.ItemIndex);
end;
//for HTML: if inserted 'value=""' we must move caret lefter
if SEndsWith(Str, '=""') then
Editor.DoCommand(cCommand_KeyLeft, TATCommandInvoke.Internal);
if SEndsWith(Str, CompletionOps.TrailingCharToShowAgain) then
begin
DoUpdate;
end
else
Close;
end;
procedure TFormATSynEditComplete.UpdateListboxItemHeight;
var
N: integer;
begin
if CompletionOps.MonoFont then
begin
N:= CanvasFontSizeToPixels(ATFlatTheme.DoScaleFont(ATFlatTheme.MonoFontSize));
N:= N * Max(96, Screen.PixelsPerInch) div 96;
Listbox.ItemHeight:= N;
end
else
Listbox.UpdateItemHeight;
end;
procedure TFormATSynEditComplete.DoUpdate;
var
Caret: TATCaretItem;
NewFormWidth, NewFormHeight, TempY: integer;
NewFormPos: TPoint;
PntText: TPoint;
PntCoord: TATPoint;
P0: TPoint;
begin
Color:= ATFlatTheme.ColorBgListbox;
SList.Clear;
if Assigned(FOnGetProp) then
FOnGetProp(Editor, SList, FCharsLeft, FCharsRight);
Caret:= Editor.Carets[0];
FUpdateForCaret.X:= Caret.PosX;
FUpdateForCaret.Y:= Caret.PosY;
if SList.Count=0 then
begin
if CompletionOps.ClosingTimerInverval>0 then
begin
//instead of 'Close' run the timer, to avoid hiding/showing when user presses Left/Right arrow in editor
if FTimerClosing=nil then
begin
FTimerClosing:= TTimer.Create(Self);
FTimerClosing.Interval:= CompletionOps.ClosingTimerInverval;
FTimerClosing.OnTimer:= @TimerClosingTimer;
end;
FTimerClosing.Enabled:= false;
FTimerClosing.Enabled:= true;
end
else
Close;
exit
end;
if Assigned(FTimerClosing) then
FTimerClosing.Enabled:= false;
if SList.Count=1 then
if CompletionOps.CommitIfSingleItem then
begin
DoResult;
exit
end;
if CompletionOps.ListSort then SList.Sort;
Listbox.VirtualItemCount:= SList.Count;
Listbox.ItemIndex:= 0;
Listbox.BorderSpacing.Around:= CompletionOps.BorderSize;
Listbox.Invalidate;
UpdateListboxItemHeight;
PntText.X:= Max(0, Caret.PosX-FCharsLeft);
PntText.Y:= Caret.PosY;
PntCoord:= Editor.CaretPosToClientPos(PntText);
Inc(PntCoord.Y, Editor.TextCharSize.Y);
P0.X:= PntCoord.X;
P0.Y:= PntCoord.Y;
NewFormPos:= Editor.ClientToScreen(P0);
NewFormPos:= Parent.ScreenToClient(NewFormPos);
NewFormWidth:= Min(CompletionOps.FormWidth, Parent.ClientWidth);
NewFormHeight:= Min(CompletionOps.FormMaxVisibleItems, Listbox.ItemCount)*Listbox.ItemHeight + 2*Listbox.BorderSpacing.Around + 1;
//check that form fits on the bottom
if NewFormPos.Y+NewFormHeight>= Parent.ClientHeight then
begin
TempY:= NewFormPos.Y-Editor.TextCharSize.Y-NewFormHeight;
if TempY>=0 then
NewFormPos.Y:= TempY
else
NewFormHeight:= Parent.ClientHeight-NewFormPos.Y;
end;
EditorOptionsSave;
//check that form fits on the right
NewFormPos.X:= Max(0, Min(NewFormPos.X, Parent.ClientWidth-NewFormWidth));
if Application.MainForm.FormStyle in [fsStayOnTop, fsSystemStayOnTop] then
FormStyle:= Application.MainForm.FormStyle;
SetBounds(NewFormPos.X, NewFormPos.Y, NewFormWidth, NewFormHeight);
Show;
end;
procedure EditorGetCurrentWord(Ed: TATSynEdit;
APosX, APosY: integer;
const ANonWordChars: UnicodeString;
out AWord: UnicodeString;
out ACharsLeft, ACharsRight: integer);
var
str: atString;
n: integer;
begin
AWord:= '';
ACharsLeft:= 0;
ACharsRight:= 0;
if not Ed.Strings.IsIndexValid(APosY) then exit;
str:= Ed.Strings.Lines[APosY];
n:= APosX;
if (n>Length(str)) then exit;
while (n>0) and (IsCharWord(str[n], ANonWordChars)) do
begin
AWord:= str[n]+AWord;
Dec(n);
Inc(ACharsLeft);
end;
n:= APosX;
while (n<Length(str)) and (IsCharWord(str[n+1], ANonWordChars)) do
begin
Inc(n);
Inc(ACharsRight);
end;
end;
procedure TFormATSynEditComplete.DoHintShow(const AHint: string);
var
P: TPoint;
R: TRect;
begin
R:= FHintWnd.CalcHintRect(CompletionOps.HintWidth, AHint, nil);
P:= ClientToScreen(Point(Width, 0));
OffsetRect(R, P.X, P.Y);
FHintWnd.ActivateHint(R, AHint);
FHintWnd.Invalidate; //for Win
Editor.Invalidate; //for Win
end;
procedure TFormATSynEditComplete.DoHintHide;
begin
if Assigned(FHintWnd) then
FHintWnd.Hide;
end;
procedure TFormATSynEditComplete.TimerClosingTimer(Sender: TObject);
begin
FTimerClosing.Enabled:= false;
TimerUpdater.Enabled:= false;
Close;
end;
procedure TFormATSynEditComplete.TimerUpdaterTimer(Sender: TObject);
{
this timer is needed very much. if user types fast + CudaText autocompletion auto-show works.
on typing 2-3 chars _fast_, form can be shown at the moment of only 1st char typed.
form must detect that additional chars were typed.
}
var
Caret: TATCaretItem;
NewPos: TPoint;
begin
if not Visible then exit;
if Editor.Carets.Count=0 then exit;
Caret:= Editor.Carets[0];
NewPos.X:= Caret.PosX;
NewPos.Y:= Caret.PosY;
if NewPos<>FUpdateForCaret then
DoUpdate;
end;
initialization
FillChar(CompletionOps, SizeOf(CompletionOps), 0);
with CompletionOps do
begin
MonoFont:= true;
CommitIfSingleItem:= false;
ColorFontPrefix:= clPurple;
ColorFontParams:= clGray;
CommitChars:= ' .,;''"';
CloseChars:= '<>()[]{}=';
IndexOfText:= 1;
IndexOfDesc:= 2;
ColumnsSep:= '|';
HintSep:= #9;
HintMultiLineSep:= #2;
HintOnlyInTooltip:= true;
SuffixSep:= #1;
AppendOpeningBracket:= true;
TrailingCharToShowAgain:= '/';
ListSort:= false;
UpDownAtEdge:= cudWrap;
BorderSize:= 4;
FormWidth:= 500;
FormMaxVisibleItems:= 12;
HintWidth:= 400;
TextIndentLeftCol:= 3;
TextIndentRightCol:= 3;
TextIndent:= 8;
ClosingTimerInverval:= 300;
ShortcutForAutocomplete:= 0;
end;
finalization
if Assigned(FormAutoCompletion) then
FormAutoCompletion.Free;
end.
|
unit InventDAOU;
interface
uses
System.Generics.Collections, InventDTOU;
type TListInventDTO=TObjectList<TInventDTO>;
Type TInventDAO=class(TObject)
function getInvents:TListInventDTO;
function getNbr:integer;
function Save(vInventDTO:TInventDTO): integer;
end;
implementation
{ TInventDAO }
uses APIUtilsU, REST.Json, System.SysUtils;
function TInventDAO.getInvents: TListInventDTO;
var
ListInvent:TListInventDTO;
oInventDTO:TInventDTO;
i:Integer;
vNbr:integer;
begin
vNbr:=self.getNbr;
ListInvent:=TJson.JsonToObject<TListInventDTO>
('{"ownsObjects": true,"listHelper": ['+inttostr(vNbr)+'], "items":'+
RestReqGet.create(nil,'invent/getInvents').Response.JSONValue.ToString+'}');
result:=ListInvent;
end;
function TInventDAO.getNbr: integer;
begin
Result:=strtoint(RestReqGet.create(nil,'invent/getNbr').Response.JSONValue.ToString);
end;
function TInventDAO.Save(vInventDTO:TInventDTO): integer;
begin
RestReqPost.create(TJson.ObjectToJsonObject(vInventDTO),
'invent/setInvent');
end;
end.
|
unit xExerciseInfo;
interface
type
TExerciseInfo = class
private
FId : Integer ;
FPath : String ;
FPtype : Integer ;
FEname : String ;
FImageindex : Integer ;
FCode1 : String ;
FCode2 : String ;
FRemark : String ;
public
/// <summary>
/// 编号
/// </summary>
property Id : Integer read FId write FId ;
/// <summary>
/// 目录
/// </summary>
property Path : String read FPath write FPath ;
/// <summary>
/// 类型 0:目录 1:文件
/// </summary>
property Ptype : Integer read FPtype write FPtype ;
/// <summary>
/// 目录名或考题名
/// </summary>
property Ename : String read FEname write FEname ;
/// <summary>
/// 图标序号
/// </summary>
property Imageindex : Integer read FImageindex write FImageindex;
/// <summary>
/// 编码1
/// </summary>
property Code1 : String read FCode1 write FCode1 ;
/// <summary>
/// 编码2
/// </summary>
property Code2 : String read FCode2 write FCode2 ;
/// <summary>
/// 备注 存储考题编号
/// </summary>
property Remark : String read FRemark write FRemark ;
end;
implementation
end.
|
/////////////////////////////////////////////////////////
// //
// Bold for Delphi //
// Copyright (c) 1996-2002 Boldsoft AB //
// (c) 2002-2005 Borland Software Corp //
// //
/////////////////////////////////////////////////////////
unit BoldDatabaseAdapterADO;
interface
uses
ADODB,
BoldAbstractDataBaseAdapter,
BoldDBInterfaces,
BoldADOInterfaces;
type
{ forward declarations }
TBoldDatabaseAdapterADO = class;
{ TBoldDatabaseAdapterADO }
TBoldDatabaseAdapterADO = class(TBoldAbstractDatabaseAdapter)
private
fBoldDatabase: TBoldADOConnection;
procedure SetDataBase(const Value: TADOConnection);
function GetDataBase: TADOConnection;
protected
procedure ReleaseBoldDatabase; override;
function GetDataBaseInterface: IBoldDatabase; override;
public
destructor Destroy; override;
published
property Connection: TADOConnection read GetDataBase write SetDataBase;
{$IFNDEF T2H}
property DatabaseEngine;
{$ENDIF}
end;
implementation
uses
SysUtils,
BoldDefs,
ADOConsts;
{ TBoldDatabaseAdapterADO }
destructor TBoldDatabaseAdapterADO.Destroy;
begin
Changed;
FreePublisher;
FreeAndNil(fBoldDatabase);
inherited;
end;
function TBoldDatabaseAdapterADO.GetDataBase: TADOConnection;
begin
result := InternalDatabase as TADOConnection;
end;
function TBoldDatabaseAdapterADO.GetDataBaseInterface: IBoldDatabase;
begin
if not assigned(Connection) then
raise EBold.CreateFmt(sAdapterNotConnected, [classname]);
if not assigned(fBoldDatabase) then
fBoldDatabase := TBoldADOConnection.create(Connection, SQLDataBaseConfig);
result := fBoldDatabase;
end;
procedure TBoldDatabaseAdapterADO.ReleaseBoldDatabase;
begin
FreeAndNil(fBoldDatabase);
end;
procedure TBoldDatabaseAdapterADO.SetDataBase(const Value: TADOConnection);
begin
InternalDatabase := value;
end;
end.
|
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info)
unit SMARTSupport.Samsung;
interface
uses
SysUtils,
BufferInterpreter, Device.SMART.List, SMARTSupport, Support;
type
TSamsungSMARTSupport = class(TSMARTSupport)
private
function ModelHasSamsungString(const Model: String): Boolean;
function SMARTHasSamsungCharacteristics(
const SMARTList: TSMARTValueList): Boolean;
function CheckSpecificCharacteristics1(
const SMARTList: TSMARTValueList): Boolean;
function CheckSpecificCharacteristics2(
const SMARTList: TSMARTValueList): Boolean;
function CheckSpecificCharacteristics3(
const SMARTList: TSMARTValueList): Boolean;
function CheckSpecificCharacteristics4(
const SMARTList: TSMARTValueList): Boolean;
function CheckSpecificCharacteristics5(
const SMARTList: TSMARTValueList): Boolean;
function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite;
const
EntryID1 = $B3;
EntryID2 = $B4;
public
function IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean; override;
function GetTypeName: String; override;
function IsSSD: Boolean; override;
function IsInsufficientSMART: Boolean; override;
function GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted; override;
function IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean; override;
protected
function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer;
override;
function InnerIsErrorAvailable(const SMARTList: TSMARTValueList):
Boolean; override;
function InnerIsCautionAvailable(const SMARTList: TSMARTValueList):
Boolean; override;
function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult;
override;
function InnerIsCaution(const SMARTList: TSMARTValueList):
TSMARTErrorResult; override;
end;
implementation
{ TSamsungSMARTSupport }
function TSamsungSMARTSupport.GetTypeName: String;
begin
result := 'SmartSamsung';
end;
function TSamsungSMARTSupport.IsInsufficientSMART: Boolean;
begin
result := false;
end;
function TSamsungSMARTSupport.IsSSD: Boolean;
begin
result := true;
end;
function TSamsungSMARTSupport.IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
ModelHasSamsungString(IdentifyDevice.Model) or
SMARTHasSamsungCharacteristics(SMARTList);
end;
function TSamsungSMARTSupport.ModelHasSamsungString(const Model: String):
Boolean;
var
ModelInUpperCase: String;
begin
ModelInUpperCase := UpperCase(Model);
result := Find('SAMSUNG', ModelInUpperCase) or Find('MZ-', ModelInUpperCase);
end;
function TSamsungSMARTSupport.SMARTHasSamsungCharacteristics(
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
CheckSpecificCharacteristics1(SMARTList) or
CheckSpecificCharacteristics2(SMARTList) or
CheckSpecificCharacteristics3(SMARTList) or
CheckSpecificCharacteristics4(SMARTList) or
CheckSpecificCharacteristics5(SMARTList);
end;
function TSamsungSMARTSupport.CheckSpecificCharacteristics1(
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
(SMARTList.Count >= 10) and
(SMARTList[0].Id = $05) and
(SMARTList[1].Id = $09) and
(SMARTList[2].Id = $0C) and
(SMARTList[3].Id = $AA) and
(SMARTList[4].Id = $AB) and
(SMARTList[5].Id = $AC) and
(SMARTList[6].Id = $AD) and
(SMARTList[7].Id = $AE) and
(SMARTList[8].Id = $B2) and
(SMARTList[9].Id = $B4);
end;
function TSamsungSMARTSupport.CheckSpecificCharacteristics2(
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
(SMARTList.Count >= 5) and
(SMARTList[0].Id = $09) and
(SMARTList[1].Id = $0C) and
(SMARTList[2].Id = $B2) and
(SMARTList[3].Id = $B3) and
(SMARTList[4].Id = $B4);
end;
function TSamsungSMARTSupport.CheckSpecificCharacteristics3(
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
(SMARTList.Count >= 7) and
(SMARTList[0].Id = $09) and
(SMARTList[1].Id = $0C) and
(SMARTList[2].Id = $B1) and
(SMARTList[3].Id = $B2) and
(SMARTList[4].Id = $B3) and
(SMARTList[5].Id = $B4) and
(SMARTList[6].Id = $B7);
end;
function TSamsungSMARTSupport.CheckSpecificCharacteristics4(
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
(SMARTList.Count >= 8) and
(SMARTList[0].Id = $09) and
(SMARTList[1].Id = $0C) and
(SMARTList[2].Id = $AF) and
(SMARTList[3].Id = $B0) and
(SMARTList[4].Id = $B1) and
(SMARTList[5].Id = $B2) and
(SMARTList[6].Id = $B3) and
(SMARTList[7].Id = $B4);
end;
function TSamsungSMARTSupport.CheckSpecificCharacteristics5(
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
(SMARTList.Count >= 8) and
(SMARTList[0].Id = $05) and
(SMARTList[1].Id = $09) and
(SMARTList[2].Id = $0C) and
(SMARTList[3].Id = $B1) and
(SMARTList[4].Id = $B2) and
(SMARTList[5].Id = $B3) and
(SMARTList[6].Id = $B5) and
(SMARTList[7].Id = $B6);
end;
function TSamsungSMARTSupport.ErrorCheckedGetLife(
const SMARTList: TSMARTValueList): Integer;
begin
result := SMARTList[SMARTList.GetIndexByID($B4)].Current;
end;
function TSamsungSMARTSupport.InnerIsErrorAvailable(
const SMARTList: TSMARTValueList): Boolean;
begin
result := true;
end;
function TSamsungSMARTSupport.InnerIsCautionAvailable(
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
IsEntryAvailable(EntryID1, SMARTList) or
IsEntryAvailable(EntryID2, SMARTList);
end;
function TSamsungSMARTSupport.InnerIsError(
const SMARTList: TSMARTValueList): TSMARTErrorResult;
begin
result.Override := false;
result.Status :=
InnerCommonIsError(EntryID1, SMARTList).Status or
InnerCommonIsError(EntryID2, SMARTList).Status;
end;
function TSamsungSMARTSupport.InnerIsCaution(
const SMARTList: TSMARTValueList): TSMARTErrorResult;
var
Entry1Result, Entry2Result: TSMARTErrorResult;
begin
Entry1Result :=
InnerCommonIsCaution(EntryID1, SMARTList, CommonLifeThreshold);
Entry2Result :=
InnerCommonIsCaution(EntryID2, SMARTList, CommonLifeThreshold);
result.Override := Entry1Result.Override;
result.Status := Entry1Result.Status or Entry2Result.Status;
end;
function TSamsungSMARTSupport.IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean;
const
WriteID = $F1;
begin
try
SMARTList.GetIndexByID(WriteID);
result := true;
except
result := false;
end;
end;
function TSamsungSMARTSupport.GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted;
const
ReadError = true;
EraseError = false;
UsedHourID = $09;
ThisErrorType = ReadError;
ErrorID = $BB;
ReplacedSectorsID = $05;
begin
FillChar(result, SizeOf(result), 0);
result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID);
result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError;
result.ReadEraseError.Value :=
SMARTList.ExceptionFreeGetRAWByID(ErrorID);
result.ReplacedSectors :=
SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID);
result.TotalWrite := GetTotalWrite(SMARTList);
end;
function TSamsungSMARTSupport.GetTotalWrite(
const SMARTList: TSMARTValueList): TTotalWrite;
function LBAToMB(const SizeInLBA: Int64): UInt64;
begin
result := SizeInLBA shr 1;
end;
function GBToMB(const SizeInLBA: Int64): UInt64;
begin
result := SizeInLBA shl 10;
end;
const
HostWrite = true;
NANDWrite = false;
WriteID = $F1;
begin
result.InValue.TrueHostWriteFalseNANDWrite :=
HostWrite;
result.InValue.ValueInMiB :=
LBAToMB(SMARTList.ExceptionFreeGetRAWByID(WriteID));
end;
end.
|
{
Ultibo RTL Builder Tool.
Copyright (C) 2022 - SoftOz Pty Ltd.
Arch
====
<All>
Boards
======
<All>
Licence
=======
LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt)
Credits
=======
Information for this unit was obtained from:
References
==========
RTL Builder
===========
The Ultibo RTL builder provides the capability to update the RTL and Packages to
the latest version available from GitHub and supports options to check for, download,
install and rebuild the RTL without user intervention.
You can also perform any one of the above steps individually if required.
To provide consistent and reliable functionality the RTL builder now also supports
downloading the latest tested versions of the Raspberry Pi firmware and extracting
them to the firmware folder of your Ultibo installation.
The RTL builder creates a Windows batch file or Linux shell script which compiles
the RTL and Packages for any of the supported architectures and displays the output
in a window during the compile.
While the tool is designed to determine the correct paths and locations without
configuration it does support creating a BuildRTL.ini file in the same directory
and setting a number of parameters to adjust the behavior.
The format of the INI file is:
[BuildRTL]
PathPrefix=
InstallPath=
CompilerName=
CompilerPath=
CompilerVersion=
SourcePath=
FirmwarePath=
BranchName=
ARMCompiler=
AARCH64Compiler=
BuildRTL=
BuildPackages=
PlatformARMv6=
PlatformARMv7=
PlatformARMv8=
A brief explanation of each parameter along with the standard default value:
PathPrefix - A text value to prepend to the path variable in the batch file (Default: <Blank>)
InstallPath - The path where Ultibo core is installed (Default Windows: C:\Ultibo\Core) (Detected from the application path)
( Linux: $HOME/ultibo/core)
CompilerName - The name of the Free Pascal compiler (Default Windows: fpc.exe)
( Linux: fpc)
CompilerPath - The path where the Ultibo version of FPC is installed (Default Windows: <InstallPath>\fpc\<CompilerVersion>)
( Linux: <InstallPath>/fpc)
CompilerVersion - The version of the FPC compiler (Default: 3.2.2)
SourcePath - The path to RTL and Packages source code (Default Windows: <CompilerPath>\source)
( Linux: <CompilerPath>/source)
FirmwarePath - The path where firmware files are located (Default Windows: <InstallPath>\firmware)
( Linux: <InstallPath>/firmware)
BranchName - The name of the Git branch to use when checking for and downloading updates
ARMCompiler - The name of the Free Pascal ARM Compiler or Cross Compiler (Default: <Blank>)
AARCH64Compiler - The name of the Free Pascal AARCH64 Compiler or Cross Compiler (Default: <Blank>)
BuildRTL - Enable or disable building the RTL (0=Disable / 1=Enable) (Default: 1)
BuildPackages - Enable or disable building the Packages (0=Disable / 1=Enable) (Default: 1)
PlatformARMv6 - Build the RTL and Packages for ARMv6 architecture (0=Disable / 1=Enable) (Default: 1)
PlatformARMv7 - Build the RTL and Packages for ARMv7 architecture (0=Disable / 1=Enable) (Default: 1)
PlatformARMv8 - Build the RTL and Packages for ARMv8 architecture (0=Disable / 1=Enable) (Default: 1)
Please note that compiling BuildRTL requires Lazarus 2.0.10 (with FPC 3.2.0) or above.
}
unit Main;
{$MODE Delphi}
{--$DEFINE BETA_BUILD}
interface
uses
LCLIntf,
LCLType,
LMessages,
{$IFDEF WINDOWS}
Windows,
{$ENDIF}
{$IFDEF LINUX}
BaseUnix,
opensslsockets,
{$ENDIF}
Messages,
SysUtils,
Classes,
{$IFDEF FPC}
Process,
fphttpclient,
Zipper,
FileUtil,
{$ENDIF}
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
ExtCtrls,
ComCtrls,
IniFiles;
const
{$IFDEF WINDOWS}
LineEnd = Chr(13) + Chr(10); {CR LF}
{$ENDIF}
{$IFDEF LINUX}
LineEnd = Chr(10); {LF}
{$ENDIF}
MarkerEnd = '!!!EndOfBuild!!!';
MarkerProgress = '!!!Progress'; {Suffix will be progress value as a percentage}
{$IFDEF WINDOWS}
SlashChar = '\';
BuildScript = '__buildrtl.bat';
{$ENDIF}
{$IFDEF LINUX}
SlashChar = '/';
BuildScript = '__buildrtl.sh';
{$ENDIF}
BetaId = '__beta.id';
{$IFDEF BETA_BUILD}
BetaVersion = '2.5-active';
BetaVersionName = 'Ultibo 2.5';
{$ENDIF BETA_BUILD}
VersionId = '__version.id';
VersionLast = '__version.last';
DownloadZip = '.zip'; {Extension of the download file, name will be the branch name}
DownloadFolder = 'Core-'; {Prefix of the folder in the zip, followed by branch name}
VersionFolder = '/source/';
DefaultVersionURL = 'https://raw.githubusercontent.com/ultibohub/Core/';
DefaultDownloadURL = 'https://github.com/ultibohub/Core/archive/';
FirmwareId = '__firmware.id';
FirmwareLast = '__firmware.last';
FirmwareVersionFolder = '/source/';
DefaultFirmwareVersionURL = 'https://raw.githubusercontent.com/ultibohub/Core/';
DefaultFirmwareDownloadURL = 'https://github.com/raspberrypi/firmware/raw/';
FirmwareDownloadFolder = '/boot/';
FirmwareDownloadFiles:array[0..18] of String = (
{RPi/RPi2/RPi3 firmware files}
'LICENCE.broadcom',
'bootcode.bin',
'fixup.dat',
'fixup_cd.dat',
'fixup_db.dat',
'fixup_x.dat',
'start.elf',
'start_cd.elf',
'start_db.elf',
'start_x.elf',
{RPi4 firmware files}
'LICENCE.broadcom',
'fixup4.dat',
'fixup4cd.dat',
'fixup4db.dat',
'fixup4x.dat',
'start4.elf',
'start4cd.elf',
'start4db.elf',
'start4x.elf');
FirmwareDownloadFolderRPi = 'RPi';
FirmwareDownloadFolderRPi2 = 'RPi2';
FirmwareDownloadFolderRPi3 = 'RPi3';
FirmwareDownloadFolderRPi4 = 'RPi4';
FirmwareDownloadFilesStartRPi = 0;
FirmwareDownloadFilesCountRPi = 10;
FirmwareDownloadFilesStartRPi4 = 10;
FirmwareDownloadFilesCountRPi4 = 9;
BranchNameMaster = 'master';
BranchNameDevelop = 'develop';
{$IFDEF BETA_BUILD}
BranchNameNext = 'next';
{$ENDIF BETA_BUILD}
BranchNameOther = '<Other>';
BranchNames:array[0..{$IFDEF BETA_BUILD}3{$ELSE}2{$ENDIF BETA_BUILD}] of String = (
BranchNameMaster,
BranchNameDevelop,
{$IFDEF BETA_BUILD}
BranchNameNext,
{$ENDIF BETA_BUILD}
BranchNameOther);
type
{ TfrmMain }
TfrmMain = class(TForm)
chkSaveSettings: TCheckBox;
cmdFirmware: TButton;
cmdDownload: TButton;
cmdOffline: TButton;
cmdCheck: TButton;
cmbBranch: TComboBox;
edtCustomBranch: TEdit;
lblCustomBranch: TLabel;
lblBranch: TLabel;
mmoMain: TMemo;
openMain: TOpenDialog;
progressMain: TProgressBar;
sbMain: TStatusBar;
pnlMain: TPanel;
cmdExit: TButton;
lblCompiler: TLabel;
lblPlatforms: TLabel;
cmdBuild: TButton;
chkARMv6: TCheckBox;
chkARMv7: TCheckBox;
chkARMv8: TCheckBox;
lblMain: TLabel;
procedure chkSaveSettingsClick(Sender: TObject);
procedure cmbBranchChange(Sender: TObject);
procedure cmdCheckClick(Sender: TObject);
procedure cmdDownloadClick(Sender: TObject);
procedure cmdFirmwareClick(Sender: TObject);
procedure cmdOfflineClick(Sender: TObject);
procedure edtCustomBranchChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure cmdExitClick(Sender: TObject);
procedure cmdBuildClick(Sender: TObject);
procedure chkARMv6Click(Sender: TObject);
procedure chkARMv7Click(Sender: TObject);
procedure chkARMv8Click(Sender: TObject);
private
{ Private declarations }
PathPrefix:String;
InstallPath:String;
SourcePath:String;
FirmwarePath:String;
BranchName:String;
CompilerName:String;
CompilerPath:String;
CompilerVersion:String;
ARMCompiler:String;
AARCH64Compiler:String;
BuildRTL:Boolean;
BuildPackages:Boolean;
PlatformARMv6:Boolean;
PlatformARMv7:Boolean;
PlatformARMv8:Boolean;
VersionURL:String;
DownloadURL:String;
FirmwareVersionURL:String;
FirmwareDownloadURL:String;
SaveSettings:Boolean;
procedure LogOutput(const AValue:String);
procedure EnableControls(AEnable:Boolean);
procedure DoProgress(Sender:TObject;const Percent:Double);
procedure DoDataReceived(Sender:TObject;const ContentLength,CurrentPos:Int64);
public
{ Public declarations }
function LoadConfig:Boolean;
function SaveConfig:Boolean;
function CheckForBeta:Boolean;
function CheckForUpdates:Boolean;
function DownloadLatest:Boolean;
function ExtractFile(const AFilename:String):Boolean;
function CreateBuildFile:Boolean;
function ExecuteBuildFile:Boolean;
function DownloadFirmware:Boolean;
end;
var
frmMain: TfrmMain;
{$IFDEF WINDOWS}
function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string;
procedure CaptureConsoleOutput(const ACommand, AParameters: String; AMemo: TMemo);
function ExecuteConsoleProcess(const ACommand,AParameters,AWorking:String;AMemo:TMemo):Boolean;
function ExecuteConsoleProcessEx(const ACommand,AParameters,AWorking,AEndMark,AProgressMark:String;AMemo:TMemo;AProgress:TProgressBar):Boolean;
{$ENDIF}
{$IFDEF LINUX}
function ExecuteShellProcess(const ACommand:String;AParameters:TStrings;const AWorking,AEndMark,AProgressMark:String;AMemo:TMemo;AProgress:TProgressBar):Boolean;
{$ENDIF}
{For details on how to capture command prompt output see:
http://www.delphidabbler.com/tips/61
http://stackoverflow.com/questions/9119999/getting-output-from-a-shell-dos-app-into-a-delphi-app
https://wiki.lazarus.freepascal.org/Executing_External_Programs#Reading_large_output
See also JclSysUtils unit in the Jedi JCL
}
function AddTrailingSlash(const FilePath:String):String;
function StripTrailingSlash(const FilePath:String):String;
{$IFDEF WINDOWS}
function IsWinNT6orAbove:Boolean;
{$ENDIF}
implementation
{$R *.lfm}
{==============================================================================}
{$IFDEF WINDOWS}
function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string;
{From: http://www.delphidabbler.com/tips/61}
var
SA: TSecurityAttributes;
SI: TStartupInfo;
PI: TProcessInformation;
StdOutPipeRead, StdOutPipeWrite: THandle;
WasOK: Boolean;
Buffer: array[0..255] of AnsiChar;
BytesRead: Cardinal;
WorkDir: string;
Handle: Boolean;
begin
Result := '';
with SA do begin
nLength := SizeOf(SA);
bInheritHandle := True;
lpSecurityDescriptor := nil;
end;
CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
try
with SI do
begin
FillChar(SI, SizeOf(SI), 0);
cb := SizeOf(SI);
dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow := SW_HIDE;
hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
hStdOutput := StdOutPipeWrite;
hStdError := StdOutPipeWrite;
end;
WorkDir := Work;
Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine),
nil, nil, True, 0, nil,
PChar(WorkDir), SI, PI);
CloseHandle(StdOutPipeWrite);
if Handle then
try
repeat
WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil);
if BytesRead > 0 then
begin
Buffer[BytesRead] := #0;
Result := Result + Buffer;
end;
until not WasOK or (BytesRead = 0);
WaitForSingleObject(PI.hProcess, INFINITE);
finally
CloseHandle(PI.hThread);
CloseHandle(PI.hProcess);
end;
finally
CloseHandle(StdOutPipeRead);
end;
end;
{==============================================================================}
procedure CaptureConsoleOutput(const ACommand, AParameters: String; AMemo: TMemo);
{From: http://stackoverflow.com/questions/9119999/getting-output-from-a-shell-dos-app-into-a-delphi-app}
const
CReadBuffer = 2400;
var
saSecurity: TSecurityAttributes;
hRead: THandle;
hWrite: THandle;
suiStartup: TStartupInfo;
piProcess: TProcessInformation;
pBuffer: array[0..CReadBuffer] of AnsiChar; //<----- update
dRead: DWord;
dRunning: DWord;
begin
saSecurity.nLength := SizeOf(TSecurityAttributes);
saSecurity.bInheritHandle := True;
saSecurity.lpSecurityDescriptor := nil;
if CreatePipe(hRead, hWrite, @saSecurity, 0) then
begin
FillChar(suiStartup, SizeOf(TStartupInfo), #0);
suiStartup.cb := SizeOf(TStartupInfo);
suiStartup.hStdInput := hRead;
suiStartup.hStdOutput := hWrite;
suiStartup.hStdError := hWrite;
suiStartup.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
suiStartup.wShowWindow := SW_HIDE;
if CreateProcess(nil, PChar(ACommand + ' ' + AParameters), @saSecurity,
@saSecurity, True, NORMAL_PRIORITY_CLASS, nil, nil, suiStartup, piProcess)
then
begin
repeat
dRunning := WaitForSingleObject(piProcess.hProcess, 100);
Application.ProcessMessages();
repeat
dRead := 0;
ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil);
pBuffer[dRead] := #0;
OemToAnsi(pBuffer, pBuffer);
AMemo.Lines.Add(String(pBuffer));
until (dRead < CReadBuffer);
until (dRunning <> WAIT_TIMEOUT);
CloseHandle(piProcess.hProcess);
CloseHandle(piProcess.hThread);
end;
CloseHandle(hRead);
CloseHandle(hWrite);
end;
end;
{==============================================================================}
function ExecuteConsoleProcess(const ACommand,AParameters,AWorking:String;AMemo:TMemo):Boolean;
{Modified from: CaptureConsoleOutput}
const
READ_BUFFER_SIZE = 2400;
var
Status:DWORD;
WorkDir:PChar;
Command:String;
BytesRead:DWORD;
ReadData:String;
ReadRemain:String;
ReadResult:Boolean;
ReadHandle:THandle;
WriteHandle:THandle;
StartupInfo:TStartupInfo;
ProcessInformation:TProcessInformation;
SecurityAttributes:TSecurityAttributes;
ReadBuffer:array[0..READ_BUFFER_SIZE] of AnsiChar;
begin
{}
Result:=False;
{Check Parameters}
if (Length(ACommand) = 0) and (Length(AParameters) = 0) then Exit;
if AMemo = nil then Exit;
{Setup Security Attributes}
FillChar(SecurityAttributes,SizeOf(TSecurityAttributes),0);
SecurityAttributes.nLength:=SizeOf(TSecurityAttributes);
SecurityAttributes.bInheritHandle:=True;
SecurityAttributes.lpSecurityDescriptor:=nil;
{Create Pipe}
if CreatePipe(ReadHandle,WriteHandle,@SecurityAttributes,0) then
begin
try
{Setup Startup Info}
FillChar(StartupInfo,SizeOf(TStartupInfo),0);
StartupInfo.cb:=SizeOf(TStartupInfo);
StartupInfo.hStdInput:=ReadHandle;
StartupInfo.hStdOutput:=WriteHandle;
StartupInfo.hStdError:=WriteHandle;
StartupInfo.dwFlags:=STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow:=SW_HIDE;
{Setup Process Information}
FillChar(ProcessInformation,SizeOf(TProcessInformation),0);
{Create Command}
Command:=Trim(ACommand + ' ' + AParameters);
{Check Working}
WorkDir:=nil;
if Length(AWorking) <> 0 then
begin
WorkDir:=PChar(AWorking);
end;
{Create Process}
if CreateProcess(nil,PChar(Command),@SecurityAttributes,@SecurityAttributes,True,NORMAL_PRIORITY_CLASS,nil,WorkDir,StartupInfo,ProcessInformation) then
begin
try
{Wait for Process}
Status:=WaitForSingleObject(ProcessInformation.hProcess,100);
if Status <> WAIT_TIMEOUT then Exit;
ReadData:='';
ReadRemain:='';
repeat
{Read from Pipe}
BytesRead:=0;
ReadResult:=ReadFile(ReadHandle,ReadBuffer[0],READ_BUFFER_SIZE,BytesRead,nil);
{Check Bytes Read}
if BytesRead > 0 then
begin
{Update Buffer}
ReadBuffer[BytesRead]:=#0;
{Convert Output}
OemToAnsi(ReadBuffer,ReadBuffer);
//To Do //ReadData/ReadRemain //See HTTPBuffer and ExecuteConsoleProcessEx etc
{Add Output}
AMemo.Lines.Add(String(ReadBuffer));
Application.ProcessMessages;
end;
{Check Bytes Read}
if (not(ReadResult) or (BytesRead < READ_BUFFER_SIZE)) then
begin
{Wait for Process}
Status:=WaitForSingleObject(ProcessInformation.hProcess,100);
end;
until (Status <> WAIT_TIMEOUT);
Result:=True;
finally
CloseHandle(ProcessInformation.hProcess);
CloseHandle(ProcessInformation.hThread);
end;
end;
finally
CloseHandle(ReadHandle);
CloseHandle(WriteHandle);
end;
end;
end;
{==============================================================================}
function ExecuteConsoleProcessEx(const ACommand,AParameters,AWorking,AEndMark,AProgressMark:String;AMemo:TMemo;AProgress:TProgressBar):Boolean;
{Modified from: CaptureConsoleOutput}
var
WorkDir:PChar;
Command:String;
BytesRead:DWORD;
ReadData:String;
ReadChar:AnsiChar;
ReadResult:Boolean;
ReadHandle:THandle;
WriteHandle:THandle;
StartupInfo:TStartupInfo;
ProcessInformation:TProcessInformation;
SecurityAttributes:TSecurityAttributes;
begin
{}
Result:=False;
{Check Parameters}
if (Length(ACommand) = 0) and (Length(AParameters) = 0) then Exit;
if AMemo = nil then Exit;
if AProgress = nil then Exit;
{Setup Security Attributes}
FillChar(SecurityAttributes,SizeOf(TSecurityAttributes),0);
SecurityAttributes.nLength:=SizeOf(TSecurityAttributes);
SecurityAttributes.bInheritHandle:=True;
SecurityAttributes.lpSecurityDescriptor:=nil;
{Create Pipe}
if CreatePipe(ReadHandle,WriteHandle,@SecurityAttributes,0) then
begin
try
{Setup Startup Info}
FillChar(StartupInfo,SizeOf(TStartupInfo),0);
StartupInfo.cb:=SizeOf(TStartupInfo);
StartupInfo.hStdInput:=ReadHandle;
if not(IsWinNT6orAbove) then StartupInfo.hStdInput:=INVAlID_HANDLE_VALUE; {Don't pass StdInput handle if less the Vista}
StartupInfo.hStdOutput:=WriteHandle;
StartupInfo.hStdError:=WriteHandle;
StartupInfo.dwFlags:=STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow:=SW_HIDE;
{Setup Process Information}
FillChar(ProcessInformation,SizeOf(TProcessInformation),0);
{Create Command}
Command:=Trim(ACommand + ' ' + AParameters);
{Check Working}
WorkDir:=nil;
if Length(AWorking) <> 0 then
begin
WorkDir:=PChar(AWorking);
end;
{Create Process}
if CreateProcess(nil,PChar(Command),@SecurityAttributes,@SecurityAttributes,True,NORMAL_PRIORITY_CLASS,nil,WorkDir,StartupInfo,ProcessInformation) then
begin
try
ReadData:='';
repeat
{Read from Pipe}
BytesRead:=0;
ReadResult:=ReadFile(ReadHandle,ReadChar,1,BytesRead,nil);
{Check Bytes Read}
if BytesRead > 0 then
begin
{Convert Output}
OemToAnsiBuff(@ReadChar,@ReadChar,1);
{Check for CR LF}
if not(ReadChar in [#10,#13]) then
begin
ReadData:=ReadData + ReadChar;
end
else
begin
{Check for LF}
if ReadChar = #10 then
begin
{Check End Mark}
if Length(AEndMark) > 0 then
begin
if ReadData = AEndMark then Break;
end;
{Check Progress Mark}
if (Length(AProgressMark) > 0) and (Copy(ReadData,1,Length(AProgressMark)) = AProgressMark) then
begin
{Update Progress}
AProgress.Position:=StrToIntDef(Copy(ReadData,Length(AProgressMark) + 1,Length(ReadData)),AProgress.Position);
end
else
begin
{Add Output}
AMemo.Lines.Add(ReadData);
AMemo.SelStart:=Length(AMemo.Text);
end;
Application.ProcessMessages;
{Reset Data}
ReadData:='';
end;
end;
end;
until (not(ReadResult) or (BytesRead = 0));
Result:=True;
finally
CloseHandle(ProcessInformation.hProcess);
CloseHandle(ProcessInformation.hThread);
end;
end;
finally
CloseHandle(ReadHandle);
CloseHandle(WriteHandle);
end;
end;
end;
{$ENDIF}
{==============================================================================}
{$IFDEF LINUX}
function ExecuteShellProcess(const ACommand:String;AParameters:TStrings;const AWorking,AEndMark,AProgressMark:String;AMemo:TMemo;AProgress:TProgressBar):Boolean;
var
Count:Integer;
BytesRead:LongInt;
ReadData:String;
ReadChar:AnsiChar;
ProcessInfo:TProcess;
begin
{}
Result:=False;
try
{Check Parameters}
if Length(ACommand) = 0 then Exit;
if AParameters = nil then Exit;
if Length(AWorking) = 0 then Exit;
if AMemo = nil then Exit;
if AProgress = nil then Exit;
ProcessInfo:=TProcess.Create(nil);
try
{Setup Process Options}
ProcessInfo.Options:=[poUsePipes,poStderrToOutPut];
{Add Executable}
ProcessInfo.Executable:=ACommand;
{Add Working}
ProcessInfo.CurrentDirectory:=AWorking;
{Add Parameters}
for Count:=0 to AParameters.Count - 1 do
begin
ProcessInfo.Parameters.Add(AParameters.Strings[Count]);
end;
{Execute Process}
ProcessInfo.Execute;
ReadData:='';
ReadChar:=#0;
repeat
{Read from Pipe}
BytesRead := ProcessInfo.Output.Read(ReadChar, SizeOf(AnsiChar));
{Check Bytes Read}
if BytesRead > 0 then
begin
{Check for CR LF}
if not(ReadChar in [#10,#13]) then
begin
ReadData:=ReadData + ReadChar;
end
else
begin
{Check for LF}
if ReadChar = #10 then
begin
{Check End Mark}
if Length(AEndMark) > 0 then
begin
if ReadData = AEndMark then Break;
end;
{Check Progress Mark}
if (Length(AProgressMark) > 0) and (Copy(ReadData,1,Length(AProgressMark)) = AProgressMark) then
begin
{Update Progress}
AProgress.Position:=StrToIntDef(Copy(ReadData,Length(AProgressMark) + 1,Length(ReadData)),AProgress.Position);
end
else
begin
{Add Output}
AMemo.Lines.Add(ReadData);
AMemo.SelStart:=Length(AMemo.Text);
end;
Application.ProcessMessages;
{Reset Data}
ReadData:='';
end;
end;
end;
until BytesRead = 0;
Result:=True;
finally
ProcessInfo.Free;
end;
except
{EProcess exception raised on error}
end;
end;
{$ENDIF}
{==============================================================================}
function AddTrailingSlash(const FilePath:String):String;
var
WorkBuffer:String;
begin
{}
WorkBuffer:=Trim(FilePath);
Result:=WorkBuffer;
if Length(WorkBuffer) > 0 then
begin
if WorkBuffer[Length(WorkBuffer)] <> SlashChar then
begin
Result:=WorkBuffer + SlashChar;
end;
end;
end;
{==============================================================================}
function StripTrailingSlash(const FilePath:String):String;
var
WorkBuffer:String;
begin
{}
WorkBuffer:=Trim(FilePath);
Result:=WorkBuffer;
if Length(WorkBuffer) > 0 then
begin
if WorkBuffer[Length(WorkBuffer)] = SlashChar then
begin
Delete(WorkBuffer,Length(WorkBuffer),1);
Result:=WorkBuffer;
end;
end;
end;
{==============================================================================}
{$IFDEF WINDOWS}
function IsWinNT6orAbove:Boolean;
{Returns True for WindowsVista(6.0) or higher}
var
OsVersionInfo:TOSVersionInfo;
begin
{}
Result:=False;
FillChar(OsVersionInfo,SizeOf(OsVersionInfo),0);
OsVersionInfo.dwOSVersionInfoSize:=SizeOf(OsVersionInfo);
if not GetVersionEx(OsVersionInfo) then Exit;
if OsVersionInfo.dwPlatformId <> VER_PLATFORM_WIN32_NT then Exit;
Result:=(OsVersionInfo.dwMajorVersion >= 6);
end;
{$ENDIF}
{==============================================================================}
{==============================================================================}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
{}
{A value to prefix on the path}
PathPrefix:='';
{Assume that this is running from <InstallPath>\tools and that the InstallPath will be the folder above}
InstallPath:=ExtractFileDir(ExtractFileDir(Application.ExeName));
{The current compiler version}
CompilerVersion:='3.2.2';
{$IFDEF WINDOWS}
{Assume the compiler name is fpc.exe}
CompilerName:='fpc.exe';
{$ENDIF}
{$IFDEF LINUX}
{Assume the compiler name is fpc}
CompilerName:='fpc';
{$ENDIF}
{$IFDEF WINDOWS}
{Assume that the compiler path will be \fpc\<CompilerVersion> under the InstallPath}
CompilerPath:=InstallPath + '\fpc\' + CompilerVersion;
{$ENDIF}
{$IFDEF LINUX}
{Assume that the compiler path will be /fpc under the InstallPath}
CompilerPath:=InstallPath + '/fpc';
{$ENDIF}
{$IFDEF WINDOWS}
{Assume that the source path will be \source under the CompilerPath}
SourcePath:=CompilerPath + '\source';
{$ENDIF}
{$IFDEF LINUX}
{Assume that the source path will be /source under the CompilerPath}
SourcePath:=CompilerPath + '/source';
{$ENDIF}
{$IFDEF WINDOWS}
{Assume that the firmware path will be \firmware under the InstallPath}
FirmwarePath:=InstallPath + '\firmware';
{$ENDIF}
{$IFDEF LINUX}
{Assume that the firmware path will be /firmware under the InstallPath}
FirmwarePath:=InstallPath + '/firmware';
{$ENDIF}
{$IFNDEF BETA_BUILD}
{Default to the master branch}
BranchName:=BranchNameMaster;
{$ELSE}
{Default to the next branch}
BranchName:=BranchNameNext;
{$ENDIF BETA_BUILD}
{The names of the ARM compiler or cross compiler}
ARMCompiler:='';
{The names of the AARCH64 compiler or cross compiler}
AARCH64Compiler:='';
BuildRTL:=True;
BuildPackages:=True;
PlatformARMv6:=True;
PlatformARMv7:=True;
PlatformARMv8:=True;
VersionURL:=DefaultVersionURL;
DownloadURL:=DefaultDownloadURL;
FirmwareVersionURL:=DefaultFirmwareVersionURL;
FirmwareDownloadURL:=DefaultFirmwareDownloadURL;
SaveSettings:=True;
LoadConfig;
{$IFDEF LINUX}
{Temporarily disable ARMv8 RTL build for Linux}
PlatformARMv8:=False;
chkARMv8.Visible:=False;
{$ENDIF}
end;
{==============================================================================}
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
{}
SaveConfig;
end;
{==============================================================================}
procedure TfrmMain.FormShow(Sender: TObject);
var
Scale:Double;
Count:Integer;
begin
{Show Settings}
chkARMv6.Checked:=PlatformARMv6;
chkARMv7.Checked:=PlatformARMv7;
chkARMv8.Checked:=PlatformARMv8;
lblMain.Caption:='To make sure you have the latest version of the Ultibo RTL click Check for Updates, if a new version is found you can choose to proceed with downloading and rebuilding the updated RTL.' + LineEnd + LineEnd
+ 'You can also select from other options to force a download of the latest RTL version, extract a previously downloaded copy or simply rebuild the current code if you have made changes.' + LineEnd + LineEnd
+ 'The progress of downloading, extracting or building the RTL or any errors encountered will be shown below.';
chkSaveSettings.Checked:=SaveSettings;
{Show Branches}
cmbBranch.Items.Clear;
for Count:=Low(BranchNames) to High(BranchNames) do
begin
cmbBranch.Items.Add(BranchNames[Count]);
end;
{Show Select Branch}
if (Length(BranchName) = 0) or (Uppercase(BranchName) = Uppercase(BranchNameOther)) then
begin
{$IFNDEF BETA_BUILD}
BranchName:=BranchNameMaster;
{$ELSE}
BranchName:=BranchNameNext;
{$ENDIF BETA_BUILD}
end;
if cmbBranch.Items.IndexOf(BranchName) = -1 then
begin
cmbBranch.ItemIndex:=cmbBranch.Items.IndexOf(BranchNameOther);
edtCustomBranch.Text:=BranchName;
lblCustomBranch.Enabled:=True;
edtCustomBranch.Enabled:=True;
end
else
begin
cmbBranch.ItemIndex:=cmbBranch.Items.IndexOf(BranchName);
lblCustomBranch.Enabled:=False;
edtCustomBranch.Enabled:=False;
end;
{$IFDEF BETA_BUILD}
cmbBranch.Enabled:=False;
lblCustomBranch.Enabled:=False;
edtCustomBranch.Enabled:=False;
{$ENDIF BETA_BUILD}
{Check PixelsPerInch}
if PixelsPerInch > 96 then
begin
{Calculate Scale}
Scale:=(PixelsPerInch / 96);
{Disable Anchors}
lblMain.Anchors:=[akLeft,akTop];
chkARMv6.Anchors:=[akLeft,akTop];
chkARMv7.Anchors:=[akLeft,akTop];
chkARMv8.Anchors:=[akLeft,akTop];
cmdCheck.Anchors:=[akLeft,akTop];
cmdDownload.Anchors:=[akLeft,akTop];
cmdFirmware.Anchors:=[akLeft,akTop];
cmdOffline.Anchors:=[akLeft,akTop];
cmdBuild.Anchors:=[akLeft,akTop];
cmdExit.Anchors:=[akLeft,akTop];
chkSaveSettings.Anchors:=[akLeft,akTop];
{Resize Form}
Width:=Trunc(Width * Scale);
Height:=Trunc(Height * Scale);
{Move Buttons}
cmdCheck.Left:=pnlMain.Width - Trunc(150 * Scale); {907 - 757 = 150}
cmdDownload.Left:=pnlMain.Width - Trunc(150 * Scale); {907 - 757 = 150}
cmdFirmware.Left:=pnlMain.Width - Trunc(150 * Scale); {907 - 757 = 150}
cmdOffline.Left:=pnlMain.Width - Trunc(150 * Scale); {907 - 757 = 150}
cmdBuild.Left:=pnlMain.Width - Trunc(150 * Scale); {907 - 757 = 150}
cmdExit.Left:=pnlMain.Width - Trunc(150 * Scale); {907 - 757 = 150}
chkSaveSettings.Left:=pnlMain.Width - Trunc(125 * Scale); {907 - 757 = 150}
{Enable Anchors}
lblMain.Anchors:=[akLeft,akTop,akRight];
chkARMv6.Anchors:=[akLeft,akTop,akRight];
chkARMv7.Anchors:=[akLeft,akTop,akRight];
chkARMv8.Anchors:=[akLeft,akTop,akRight];
cmdCheck.Anchors:=[akTop,akRight];
cmdDownload.Anchors:=[akTop,akRight];
cmdFirmware.Anchors:=[akTop,akRight];
cmdOffline.Anchors:=[akTop,akRight];
cmdBuild.Anchors:=[akTop,akRight];
cmdExit.Anchors:=[akTop,akRight];
chkSaveSettings.Anchors:=[akTop,akRight];
end;
{Check Check Button}
if (cmdCheck.Left + cmdCheck.Width) > Width then
begin
{Adjust Check Button}
cmdCheck.Left:=ClientWidth - 150; {907 - 757 = 150}
end;
{Check Download Button}
if (cmdDownload.Left + cmdDownload.Width) > Width then
begin
{Adjust Download Button}
cmdDownload.Left:=ClientWidth - 150; {907 - 757 = 150}
end;
{Check Firmware Button}
if (cmdFirmware.Left + cmdFirmware.Width) > Width then
begin
{Adjust Firmware Button}
cmdFirmware.Left:=ClientWidth - 150; {907 - 757 = 150}
end;
{Check Offline Button}
if (cmdOffline.Left + cmdOffline.Width) > Width then
begin
{Adjust Offline Button}
cmdOffline.Left:=ClientWidth - 150; {907 - 757 = 150}
end;
{Check Build Button}
if (cmdBuild.Left + cmdBuild.Width) > Width then
begin
{Adjust Build Button}
cmdBuild.Left:=ClientWidth - 150; {907 - 757 = 150}
end;
{Check Exit Button}
if (cmdExit.Left + cmdExit.Width) > Width then
begin
{Adjust Exit Button}
cmdExit.Left:=ClientWidth - 150; {907 - 757 = 150}
end;
{Check Save Settings}
if (chkSaveSettings.Left + chkSaveSettings.Width) > Width then
begin
{Adjust Save Settings}
chkSaveSettings.Left:=ClientWidth - 125;
end;
{Check Main Label}
if (lblMain.Left + lblMain.Width) >= cmdBuild.Left then
begin
{Adjust Main Label}
lblMain.Width:=(cmdBuild.Left - lblMain.Left) - 150;
end;
end;
{==============================================================================}
procedure TfrmMain.FormHide(Sender: TObject);
begin
{}
end;
{==============================================================================}
procedure TfrmMain.chkARMv6Click(Sender: TObject);
begin
{}
PlatformARMv6:=chkARMv6.Checked;
end;
{==============================================================================}
procedure TfrmMain.chkARMv7Click(Sender: TObject);
begin
{}
PlatformARMv7:=chkARMv7.Checked;
end;
{==============================================================================}
procedure TfrmMain.chkARMv8Click(Sender: TObject);
begin
{}
PlatformARMv8:=chkARMv8.Checked;
end;
{==============================================================================}
procedure TfrmMain.chkSaveSettingsClick(Sender: TObject);
begin
{}
SaveSettings:=chkSaveSettings.Checked;
end;
{==============================================================================}
procedure TfrmMain.cmbBranchChange(Sender: TObject);
begin
{}
if cmbBranch.ItemIndex = -1 then Exit;
if cmbBranch.ItemIndex = cmbBranch.Items.IndexOf(BranchNameOther) then
begin
BranchName:=edtCustomBranch.Text;
lblCustomBranch.Enabled:=True;
edtCustomBranch.Enabled:=True;
end
else
begin
BranchName:=cmbBranch.Items[cmbBranch.ItemIndex];
lblCustomBranch.Enabled:=False;
edtCustomBranch.Enabled:=False;
end;
end;
{==============================================================================}
procedure TfrmMain.edtCustomBranchChange(Sender: TObject);
begin
{}
if cmbBranch.ItemIndex = cmbBranch.Items.IndexOf(BranchNameOther) then
begin
BranchName:=edtCustomBranch.Text;
end;
end;
{==============================================================================}
procedure TfrmMain.cmdExitClick(Sender: TObject);
begin
{}
Application.Terminate;
end;
{==============================================================================}
procedure TfrmMain.cmdCheckClick(Sender: TObject);
begin
{}
EnableControls(False);
progressMain.Position:=0;
try
{Clear Memo}
mmoMain.Lines.Clear;
{Add Banner}
LogOutput('Checking for Ultibo RTL Updates');
LogOutput('');
{Add Version URL}
LogOutput(' Version URL is ' + VersionURL);
LogOutput('');
{Check for Beta}
if not CheckForBeta then
begin
{$IFDEF BETA_BUILD}
{Prompt to Update}
MessageDlg('This installation was released for the ' + BetaVersionName + ' beta and has now expired.' + LineEnd + LineEnd + 'Please download the latest installer from https://ultibo.org',mtInformation,[mbOk],0);
Exit;
{$ENDIF BETA_BUILD}
end;
{Check for Updates}
if CheckForUpdates then
begin
{Prompt for Download}
if MessageDlg('An update is available for the Ultibo RTL, do you want to download and install it now?',mtConfirmation,[mbYes,mbNo],0) = mrYes then
begin
{Add Banner}
LogOutput('Downloading Latest Ultibo RTL');
LogOutput('');
{Download Latest}
if not DownloadLatest then
begin
LogOutput(' Error: Failed to download latest RTL');
Exit;
end;
{Add Banner}
LogOutput('Extracting Ultibo RTL');
LogOutput('');
{Extract File}
if not ExtractFile(BranchName + DownloadZip) then
begin
LogOutput(' Error: Failed to extract RTL');
Exit;
end;
{Add Banner}
LogOutput('Building Ultibo RTL');
LogOutput('');
{Add Path Prefix}
LogOutput(' Path Prefix is ' + PathPrefix);
LogOutput('');
{Add Install Path}
LogOutput(' Install Path is ' + InstallPath);
LogOutput('');
{Add Compiler Name}
LogOutput(' Compiler Name is ' + CompilerName);
LogOutput('');
{Add Compiler Path}
LogOutput(' Compiler Path is ' + CompilerPath);
LogOutput('');
{Add Source Path}
LogOutput(' Source Path is ' + SourcePath);
LogOutput('');
{Add ARM Compiler}
if Length(ARMCompiler) <> 0 then
begin
LogOutput(' ARM Compiler is ' + ARMCompiler);
LogOutput('');
end;
{Add AARCH64 Compiler}
if Length(AARCH64Compiler) <> 0 then
begin
LogOutput(' AARCH64 Compiler is ' + AARCH64Compiler);
LogOutput('');
end;
{Create Build File}
LogOutput(' Creating Build Script');
LogOutput('');
if not CreateBuildFile then
begin
LogOutput(' Error: Failed to create build script');
Exit;
end;
{Execute Build File}
LogOutput(' Executing Build Script');
LogOutput('');
if not ExecuteBuildFile then
begin
LogOutput(' Error: Failed to execute build script');
Exit;
end;
end;
end;
{Add Banner}
LogOutput('Checking for Raspberry Pi Firmware Updates');
LogOutput('');
{Add Firmware Version URL}
LogOutput(' Firmware Version URL is ' + FirmwareVersionURL);
LogOutput('');
{Check and Download Firmware}
if not DownloadFirmware then
begin
LogOutput(' Error: Failed to download latest firmware');
Exit;
end;
{Add Footer}
LogOutput('');
LogOutput('Check Completed');
LogOutput('');
finally
EnableControls(True);
end;
end;
{==============================================================================}
procedure TfrmMain.cmdDownloadClick(Sender: TObject);
begin
{}
EnableControls(False);
progressMain.Position:=0;
try
{Clear Memo}
mmoMain.Lines.Clear;
{Add Banner}
LogOutput('Downloading Latest Ultibo RTL');
LogOutput('');
{Check for Beta}
if not CheckForBeta then
begin
{$IFDEF BETA_BUILD}
{Prompt to Update}
MessageDlg('This installation was released for the ' + BetaVersionName + ' beta and has now expired.' + LineEnd + LineEnd + 'Please download the latest installer from https://ultibo.org',mtInformation,[mbOk],0);
Exit;
{$ENDIF BETA_BUILD}
end;
{Download Latest}
if not DownloadLatest then
begin
LogOutput(' Error: Failed to download latest RTL');
Exit;
end;
{Prompt for Install}
if MessageDlg('The latest RTL has been downloaded, do you want to install it now?',mtConfirmation,[mbYes,mbNo],0) = mrYes then
begin
{Add Banner}
LogOutput('Extracting Ultibo RTL');
LogOutput('');
{Extract File}
if not ExtractFile(BranchName + DownloadZip) then
begin
LogOutput(' Error: Failed to extract RTL');
Exit;
end;
{Add Banner}
LogOutput('Building Ultibo RTL');
LogOutput('');
{Add Path Prefix}
LogOutput(' Path Prefix is ' + PathPrefix);
LogOutput('');
{Add Install Path}
LogOutput(' Install Path is ' + InstallPath);
LogOutput('');
{Add Compiler Name}
LogOutput(' Compiler Name is ' + CompilerName);
LogOutput('');
{Add Compiler Path}
LogOutput(' Compiler Path is ' + CompilerPath);
LogOutput('');
{Add Source Path}
LogOutput(' Source Path is ' + SourcePath);
LogOutput('');
{Add ARM Compiler}
if Length(ARMCompiler) <> 0 then
begin
LogOutput(' ARM Compiler is ' + ARMCompiler);
LogOutput('');
end;
{Add AARCH64 Compiler}
if Length(AARCH64Compiler) <> 0 then
begin
LogOutput(' AARCH64 Compiler is ' + AARCH64Compiler);
LogOutput('');
end;
{Create Build File}
LogOutput(' Creating Build Script');
LogOutput('');
if not CreateBuildFile then
begin
LogOutput(' Error: Failed to create build script');
Exit;
end;
{Execute Build File}
LogOutput(' Executing Build Script');
LogOutput('');
if not ExecuteBuildFile then
begin
LogOutput(' Error: Failed to execute build script');
Exit;
end;
end;
{Add Footer}
LogOutput('');
LogOutput('Download Completed');
LogOutput('');
finally
EnableControls(True);
end;
end;
{==============================================================================}
procedure TfrmMain.cmdFirmwareClick(Sender: TObject);
begin
EnableControls(False);
progressMain.Position:=0;
try
{Clear Memo}
mmoMain.Lines.Clear;
{Add Banner}
LogOutput('Downloading Latest Raspberry Pi Firmware');
LogOutput('');
{Check for Beta}
if not CheckForBeta then
begin
{$IFDEF BETA_BUILD}
{Prompt to Update}
MessageDlg('This installation was released for the ' + BetaVersionName + ' beta and has now expired.' + LineEnd + LineEnd + 'Please download the latest installer from https://ultibo.org',mtInformation,[mbOk],0);
Exit;
{$ENDIF BETA_BUILD}
end;
{Download Firmware}
if not DownloadFirmware then
begin
LogOutput(' Error: Failed to download latest firmware');
Exit;
end;
{Add Footer}
LogOutput('');
LogOutput('Download Completed');
LogOutput('');
finally
EnableControls(True);
end;
end;
{==============================================================================}
procedure TfrmMain.cmdOfflineClick(Sender: TObject);
begin
{}
EnableControls(False);
progressMain.Position:=0;
try
{Clear Memo}
mmoMain.Lines.Clear;
{Add Banner}
LogOutput('Extracting Offline Ultibo RTL');
LogOutput('');
{Check for Beta}
if not CheckForBeta then
begin
{$IFDEF BETA_BUILD}
{Prompt to Update}
MessageDlg('This installation was released for the ' + BetaVersionName + ' beta and has now expired.' + LineEnd + LineEnd + 'Please download the latest installer from https://ultibo.org',mtInformation,[mbOk],0);
Exit;
{$ENDIF BETA_BUILD}
end;
{Browse for file}
openMain.Title:='Extract Offline RTL';
openMain.InitialDir:=ExtractFileDir(Application.ExeName);
{$IFDEF WINDOWS}
openMain.Filter:='Zip files (*.zip)|*.zip|All files (*.*)|*.*';
{$ENDIF}
{$IFDEF LINUX}
openMain.Filter:='Zip files (*.zip)|*.zip|All files (*.*)|*';
{$ENDIF}
if not openMain.Execute then Exit;
{Prompt for Extract}
if MessageDlg('Do you want to extract and install the RTL from the file "' + openMain.Filename + '", this will overwrite your existing RTL?',mtConfirmation,[mbYes,mbNo],0) <> mrYes then
begin
Exit;
end;
{Extract File}
if not ExtractFile(openMain.Filename) then
begin
LogOutput(' Error: Failed to extract offline RTL');
Exit;
end;
{Prompt for Build}
if MessageDlg('The RTL has been extracted and installed, do you want to build it now?',mtConfirmation,[mbYes,mbNo],0) = mrYes then
begin
{Add Banner}
LogOutput('Building Ultibo RTL');
LogOutput('');
{Add Path Prefix}
LogOutput(' Path Prefix is ' + PathPrefix);
LogOutput('');
{Add Install Path}
LogOutput(' Install Path is ' + InstallPath);
LogOutput('');
{Add Compiler Name}
LogOutput(' Compiler Name is ' + CompilerName);
LogOutput('');
{Add Compiler Path}
LogOutput(' Compiler Path is ' + CompilerPath);
LogOutput('');
{Add Source Path}
LogOutput(' Source Path is ' + SourcePath);
LogOutput('');
{Add ARM Compiler}
if Length(ARMCompiler) <> 0 then
begin
LogOutput(' ARM Compiler is ' + ARMCompiler);
LogOutput('');
end;
{Add AARCH64 Compiler}
if Length(AARCH64Compiler) <> 0 then
begin
LogOutput(' AARCH64 Compiler is ' + AARCH64Compiler);
LogOutput('');
end;
{Create Build File}
LogOutput(' Creating Build Script');
LogOutput('');
if not CreateBuildFile then
begin
LogOutput(' Error: Failed to create build script');
Exit;
end;
{Execute Build File}
LogOutput(' Executing Build Script');
LogOutput('');
if not ExecuteBuildFile then
begin
LogOutput(' Error: Failed to execute build script');
Exit;
end;
end;
{Add Footer}
LogOutput('');
LogOutput('Extract Completed');
LogOutput('');
finally
EnableControls(True);
end;
end;
{==============================================================================}
procedure TfrmMain.cmdBuildClick(Sender: TObject);
begin
{}
EnableControls(False);
progressMain.Position:=0;
try
{Clear Memo}
mmoMain.Lines.Clear;
{Add Banner}
LogOutput('Building Current Ultibo RTL');
LogOutput('');
{Check for Beta}
if not CheckForBeta then
begin
{$IFDEF BETA_BUILD}
{Prompt to Update}
MessageDlg('This installation was released for the ' + BetaVersionName + ' beta and has now expired.' + LineEnd + LineEnd + 'Please download the latest installer from https://ultibo.org',mtInformation,[mbOk],0);
Exit;
{$ENDIF BETA_BUILD}
end;
{Add Path Prefix}
LogOutput(' Path Prefix is ' + PathPrefix);
LogOutput('');
{Add Install Path}
LogOutput(' Install Path is ' + InstallPath);
LogOutput('');
{Add Compiler Name}
LogOutput(' Compiler Name is ' + CompilerName);
LogOutput('');
{Add Compiler Path}
LogOutput(' Compiler Path is ' + CompilerPath);
LogOutput('');
{Add Source Path}
LogOutput(' Source Path is ' + SourcePath);
LogOutput('');
{Add ARM Compiler}
if Length(ARMCompiler) <> 0 then
begin
LogOutput(' ARM Compiler is ' + ARMCompiler);
LogOutput('');
end;
{Add AARCH64 Compiler}
if Length(AARCH64Compiler) <> 0 then
begin
LogOutput(' AARCH64 Compiler is ' + AARCH64Compiler);
LogOutput('');
end;
{Create Build File}
LogOutput(' Creating Build Script');
LogOutput('');
if not CreateBuildFile then
begin
LogOutput(' Error: Failed to create build script');
Exit;
end;
{Execute Build File}
LogOutput(' Executing Build Script');
LogOutput('');
if not ExecuteBuildFile then
begin
LogOutput(' Error: Failed to execute build script');
Exit;
end;
{Add Footer}
LogOutput('');
LogOutput('Completed Build');
LogOutput('');
finally
EnableControls(True);
end;
end;
{==============================================================================}
procedure TfrmMain.LogOutput(const AValue:String);
begin
{}
mmoMain.Lines.Add(AValue);
mmoMain.SelStart:=Length(mmoMain.Text);
end;
{==============================================================================}
procedure TfrmMain.EnableControls(AEnable:Boolean);
begin
{}
lblMain.Enabled:=AEnable;
lblPlatforms.Enabled:=AEnable;
chkARMv6.Enabled:=AEnable;
chkARMv7.Enabled:=AEnable;
chkARMv8.Enabled:=AEnable;
lblBranch.Enabled:=AEnable;
cmbBranch.Enabled:=AEnable;
lblCustomBranch.Enabled:=AEnable and (cmbBranch.ItemIndex = cmbBranch.Items.IndexOf(BranchNameOther));
edtCustomBranch.Enabled:=AEnable and lblCustomBranch.Enabled;
cmdCheck.Enabled:=AEnable;
cmdDownload.Enabled:=AEnable;
cmdFirmware.Enabled:=AEnable;
cmdOffline.Enabled:=AEnable;
cmdBuild.Enabled:=AEnable;
cmdExit.Enabled:=AEnable;
chkSaveSettings.Enabled:=AEnable;
Application.ProcessMessages;
end;
{==============================================================================}
procedure TfrmMain.DoProgress(Sender:TObject;const Percent:Double);
begin
{}
progressMain.Position:=Trunc(Percent);
Application.ProcessMessages;
end;
{==============================================================================}
procedure TfrmMain.DoDataReceived(Sender:TObject;const ContentLength,CurrentPos:Int64);
begin
{}
if ContentLength > 0 then
begin
if CurrentPos < ContentLength then
begin
progressMain.Position:=Trunc((CurrentPos / ContentLength) * 100);
end
else
begin
progressMain.Position:=100;
end;
Application.ProcessMessages;
end;
end;
{==============================================================================}
function TfrmMain.LoadConfig:Boolean;
var
Section:String;
Filename:String;
IniFile:TIniFile;
begin
{}
Result:=False;
try
{Get Filename}
Filename:=ChangeFileExt(Application.ExeName,'.ini');
{Check File}
if FileExists(Filename) then
begin
IniFile:=TIniFile.Create(Filename);
try
Section:='General';
{Get Width}
Width:=IniFile.ReadInteger(Section,'Width',Width);
{Get Height}
Height:=IniFile.ReadInteger(Section,'Height',Height);
{Get SaveSettings}
SaveSettings:=IniFile.ReadBool(Section,'SaveSettings',SaveSettings);
Section:='BuildRTL';
{Get PathPrefix}
PathPrefix:=IniFile.ReadString(Section,'PathPrefix',PathPrefix);
{Get InstallPath}
InstallPath:=IniFile.ReadString(Section,'InstallPath',InstallPath);
{Get CompilerName}
CompilerName:=IniFile.ReadString(Section,'CompilerName',CompilerName);
{Get CompilerPath}
CompilerPath:=IniFile.ReadString(Section,'CompilerPath',CompilerPath);
{Get CompilerVersion}
CompilerVersion:=IniFile.ReadString(Section,'CompilerVersion',CompilerVersion);
{Get SourcePath}
SourcePath:=IniFile.ReadString(Section,'SourcePath',SourcePath);
{Get FirmwarePath}
FirmwarePath:=IniFile.ReadString(Section,'FirmwarePath',FirmwarePath);
{Get BranchName}
{$IFNDEF BETA_BUILD}
BranchName:=IniFile.ReadString(Section,'BranchName',BranchName);
{$ELSE}
BranchName:=BranchNameNext;
{$ENDIF BETA_BUILD}
{Get ARMCompiler}
ARMCompiler:=IniFile.ReadString(Section,'ARMCompiler',ARMCompiler);
{Get AARCH64Compiler}
AARCH64Compiler:=IniFile.ReadString(Section,'AARCH64Compiler',AARCH64Compiler);
{Get BuildRTL}
BuildRTL:=IniFile.ReadBool(Section,'BuildRTL',BuildRTL);
{Get BuildPackages}
BuildPackages:=IniFile.ReadBool(Section,'BuildPackages',BuildPackages);
{Get PlatformARMv6}
PlatformARMv6:=IniFile.ReadBool(Section,'PlatformARMv6',PlatformARMv6);
{Get PlatformARMv7}
PlatformARMv7:=IniFile.ReadBool(Section,'PlatformARMv7',PlatformARMv7);
{Get PlatformARMv8}
PlatformARMv8:=IniFile.ReadBool(Section,'PlatformARMv8',PlatformARMv8);
{Get VersionURL}
VersionURL:=IniFile.ReadString(Section,'VersionURL',VersionURL);
{Get DownloadURL}
DownloadURL:=IniFile.ReadString(Section,'DownloadURL',DownloadURL);
{Get FirmwareVersionURL}
FirmwareVersionURL:=IniFile.ReadString(Section,'FirmwareVersionURL',FirmwareVersionURL);
{Get FirmwareDownloadURL}
FirmwareDownloadURL:=IniFile.ReadString(Section,'FirmwareDownloadURL',FirmwareDownloadURL);
finally
IniFile.Free;
end;
end;
Result:=True;
except
{}
end;
end;
function TfrmMain.SaveConfig:Boolean;
var
Section:String;
Filename:String;
IniFile:TIniFile;
begin
{}
Result:=False;
try
{Get Filename}
Filename:=ChangeFileExt(Application.ExeName,'.ini');
IniFile:=TIniFile.Create(Filename);
try
Section:='General';
{Check SaveSettings}
if SaveSettings then
begin
{Set Width}
IniFile.WriteInteger(Section,'Width',Width);
{Set Height}
IniFile.WriteInteger(Section,'Height',Height);
{Set SaveSettings}
IniFile.WriteBool(Section,'SaveSettings',SaveSettings);
Section:='BuildRTL';
{Set BranchName}
{$IFNDEF BETA_BUILD}
IniFile.WriteString(Section,'BranchName',BranchName);
{$ENDIF BETA_BUILD}
{Set PlatformARMv6}
IniFile.WriteBool(Section,'PlatformARMv6',PlatformARMv6);
{Set PlatformARMv7}
IniFile.WriteBool(Section,'PlatformARMv7',PlatformARMv7);
{Set PlatformARMv8}
IniFile.WriteBool(Section,'PlatformARMv8',PlatformARMv8);
end
else
begin
{Set SaveSettings}
IniFile.WriteBool(Section,'SaveSettings',SaveSettings);
end;
finally
IniFile.Free;
end;
Result:=True;
except
{}
end;
end;
function TfrmMain.CheckForBeta:Boolean;
var
FileURL:String;
Filename:String;
{$IFDEF BETA_BUILD}
Lines:TStringList;
FileVersion:String;
Client:TFPHTTPClient;
{$ENDIF BETA_BUILD}
begin
Result:=False;
try
if Length(BranchName) = 0 then Exit;
if Length(SourcePath) = 0 then Exit;
if Length(VersionURL) = 0 then Exit;
{Check Source Path}
if not DirectoryExists(StripTrailingSlash(SourcePath)) then
begin
LogOutput(' Error: SourcePath "' + SourcePath + '" does not exist');
LogOutput('');
Exit;
end;
{Get FileURL}
FileURL:=VersionURL + BranchName + VersionFolder + BetaId;
{$IFDEF BETA_BUILD}
LogOutput(' Beta Version File URL is ' + FileURL);
LogOutput('');
{$ENDIF BETA_BUILD}
{Get Filename}
Filename:=AddTrailingSlash(SourcePath) + BetaId;
{$IFDEF BETA_BUILD}
LogOutput(' Beta Version Filename is ' + Filename);
LogOutput('');
{$ENDIF BETA_BUILD}
{Check File}
if FileExists(Filename) then
begin
{Delete File}
DeleteFile(Filename);
if FileExists(Filename) then Exit;
end;
{$IFNDEF BETA_BUILD}
Result:=True;
{$ELSE}
{Set Defaults}
FileVersion:='<Unknown>';
{Create HTTP Client}
Client:=TFPHTTPClient.Create(nil);
try
Client.AllowRedirect:=True;
{Get Version File}
LogOutput(' Downloading file: ' + BetaId);
LogOutput('');
Client.Get(FileURL,Filename);
Lines:=TStringList.Create;
try
{Open Version File}
Lines.LoadFromFile(Filename);
if Lines.Count = 0 then
begin
LogOutput(' Error: Beta version file contains no data');
LogOutput('');
Exit;
end;
{Get File Version}
FileVersion:=Lines.Strings[0];
LogOutput(' Beta Version is ' + FileVersion);
LogOutput('');
Result:=(BetaVersion = FileVersion);
finally
Lines.Free;
end;
finally
Client.Free;
end;
{$ENDIF BETA_BUILD}
except
on E: Exception do
begin
LogOutput(' Error: Exception checking for beta expiry - Message: ' + E.Message);
LogOutput('');
end;
end;
end;
function TfrmMain.CheckForUpdates:Boolean;
var
FileURL:String;
Filename:String;
Lastname:String;
Lines:TStringList;
FileVersion:String;
LastVersion:String;
Client:TFPHTTPClient;
begin
{}
Result:=False;
try
if Length(BranchName) = 0 then Exit;
if Length(SourcePath) = 0 then Exit;
if Length(VersionURL) = 0 then Exit;
{Check Source Path}
if not DirectoryExists(StripTrailingSlash(SourcePath)) then
begin
LogOutput(' Error: SourcePath "' + SourcePath + '" does not exist');
LogOutput('');
Exit;
end;
{Get FileURL}
FileURL:=VersionURL + BranchName + VersionFolder + VersionId;
LogOutput(' Version File URL is ' + FileURL);
LogOutput('');
{Get Filename}
Filename:=AddTrailingSlash(SourcePath) + VersionId;
LogOutput(' Latest Version Filename is ' + Filename);
LogOutput('');
{Get Lastname}
Lastname:=AddTrailingSlash(SourcePath) + VersionLast;
LogOutput(' Current Version Filename is ' + Lastname);
LogOutput('');
{Set Defaults}
FileVersion:='<Unknown>';
LastVersion:='<Unknown>';
{Check File}
if FileExists(Filename) then
begin
{Delete File}
DeleteFile(Filename);
if FileExists(Filename) then Exit;
end;
{Create HTTP Client}
Client:=TFPHTTPClient.Create(nil);
try
Client.AllowRedirect:=True;
{Get Version File}
LogOutput(' Downloading file: ' + VersionId);
LogOutput('');
Client.Get(FileURL,Filename);
Lines:=TStringList.Create;
try
{Open Version File}
Lines.LoadFromFile(Filename);
if Lines.Count = 0 then
begin
LogOutput(' Error: Latest version file contains no data');
LogOutput('');
Exit;
end;
{Get File Version}
FileVersion:=Lines.Strings[0];
LogOutput(' Latest Version is ' + FileVersion);
LogOutput('');
{Open Last Version File}
if FileExists(Lastname) then
begin
Lines.Clear;
Lines.LoadFromFile(Lastname);
if Lines.Count = 0 then
begin
LogOutput(' Error: Current version file contains no data');
LogOutput('');
Exit;
end;
{Get Last Version}
LastVersion:=Lines.Strings[0];
end;
LogOutput(' Current Version is ' + LastVersion);
LogOutput('');
Result:=(LastVersion <> FileVersion);
finally
Lines.Free;
end;
finally
Client.Free;
end;
except
on E: Exception do
begin
LogOutput(' Error: Exception checking for RTL updates - Message: ' + E.Message);
LogOutput('');
end;
end;
end;
{==============================================================================}
function TfrmMain.DownloadLatest:Boolean;
var
FileURL:String;
Filename:String;
Client:TFPHTTPClient;
begin
{}
Result:=False;
try
if Length(SourcePath) = 0 then Exit;
if Length(DownloadURL) = 0 then Exit;
{Check Source Path}
if not DirectoryExists(StripTrailingSlash(SourcePath)) then
begin
LogOutput(' Error: SourcePath "' + SourcePath + '" does not exist');
LogOutput('');
Exit;
end;
{Get FileURL}
FileURL:=DownloadURL + BranchName + DownloadZip;
LogOutput(' Download File URL is ' + FileURL);
LogOutput('');
{Get Filename}
Filename:=AddTrailingSlash(SourcePath) + BranchName + DownloadZip;
LogOutput(' Download Filename is ' + Filename);
LogOutput('');
{Check File}
if FileExists(Filename) then
begin
{Delete File}
DeleteFile(Filename);
if FileExists(Filename) then Exit;
end;
{Create HTTP Client}
Client:=TFPHTTPClient.Create(nil);
try
Client.AllowRedirect:=True;
Client.OnDataReceived:=DoDataReceived;
{Get Zip File}
LogOutput(' Downloading file: ' + BranchName + DownloadZip);
LogOutput('');
Client.Get(FileURL,Filename);
Result := True;
finally
Client.Free;
end;
except
on E: Exception do
begin
LogOutput(' Error: Exception downloading latest RTL - Message: ' + E.Message);
LogOutput('');
end;
end;
end;
{==============================================================================}
function TfrmMain.ExtractFile(const AFilename:String):Boolean;
var
Pathname:String;
Tempname:String;
Filename:String;
Destname:String;
Sourcename:String;
UnZipper:TUnZipper;
begin
{}
Result:=False;
try
if Length(AFilename) = 0 then Exit;
{Check Source Path}
if not DirectoryExists(StripTrailingSlash(SourcePath)) then
begin
LogOutput(' Error: SourcePath "' + SourcePath + '" does not exist');
LogOutput('');
Exit;
end;
{Get Filename}
Filename:=AFilename;
if ExtractFilePath(Filename) = '' then
begin
Filename:=AddTrailingSlash(SourcePath) + Filename;
end;
LogOutput(' Filename is ' + Filename);
LogOutput('');
{Get Pathname}
Pathname:=StripTrailingSlash(SourcePath);
LogOutput(' Pathname is ' + Pathname);
LogOutput('');
{Get Tempname}
Tempname:=AddTrailingSlash(SourcePath) + '__temp';
{Check Tempname}
if DirectoryExists(Tempname) then
begin
DeleteDirectory(Tempname,True);
end;
if not DirectoryExists(Tempname) then
begin
CreateDir(Tempname);
if not DirectoryExists(Tempname) then Exit;
end;
{Create Unzipper}
UnZipper:=TUnZipper.Create;
try
UnZipper.OnProgress:=DoProgress;
UnZipper.FileName:=Filename;
UnZipper.OutputPath:=Tempname;
{Extract Zip File}
LogOutput(' Extracting file: ' + AFilename);
LogOutput('');
UnZipper.Examine;
UnZipper.UnZipAllFiles;
{Get Source and Destination}
Destname:=ExtractFileDir(Pathname);
Sourcename:=AddTrailingSlash(Tempname) + DownloadFolder + BranchName;
{Copy Files}
if CopyDirTree(Sourcename,Destname,[cffOverwriteFile,cffCreateDestDirectory,cffPreserveTime]) then
begin
{Cleanup Tempname}
DeleteDirectory(Tempname,False);
{Get Source and Destination}
Destname:=AddTrailingSlash(Pathname) + VersionLast;
Sourcename:=AddTrailingSlash(Pathname) + VersionId;
{Check Destname}
if FileExists(Destname) then
begin
DeleteFile(Destname);
if FileExists(Destname) then Exit;
end;
{Rename Version File}
Result:=RenameFile(Sourcename,Destname);
end;
finally
UnZipper.Free;
end;
except
on E: Exception do
begin
LogOutput(' Error: Exception extracting RTL - Message: ' + E.Message);
LogOutput('');
end;
end;
end;
{==============================================================================}
function TfrmMain.CreateBuildFile:Boolean;
var
Total:Integer;
Progress:Integer;
Percent:Integer;
Filename:String;
WorkBuffer:String;
FileStream:TFileStream;
begin
{}
Result:=False;
try
if Length(SourcePath) = 0 then Exit;
if Length(InstallPath) = 0 then Exit;
if Length(CompilerName) = 0 then Exit;
if Length(CompilerPath) = 0 then Exit;
if Length(CompilerVersion) = 0 then Exit;
if not(BuildRTL) and not(BuildPackages) then Exit;
if not(PlatformARMv6) and not(PlatformARMv7) and not(PlatformARMv8) then Exit;
{Get ARM Compiler}
if Length(ARMCompiler) = 0 then ARMCompiler:=CompilerName;
{Get AARCH64 Compiler}
if Length(AARCH64Compiler) = 0 then AARCH64Compiler:=CompilerName;
{Get Filename}
Filename:=AddTrailingSlash(SourcePath) + BuildScript;
LogOutput(' Build Script is ' + Filename);
LogOutput('');
{Check File}
if FileExists(Filename) then
begin
{Delete File}
DeleteFile(Filename);
if FileExists(Filename) then Exit;
end;
{Create File}
FileStream:=TFileStream.Create(Filename,fmCreate);
try
{Calculate Progress}
Total:=0;
Progress:=0;
Percent:=0;
{Check RTL}
if BuildRTL then
begin
if PlatformARMv6 then Inc(Total, 3);
if PlatformARMv7 then Inc(Total, 3);
if PlatformARMv8 then Inc(Total, 3);
end;
{Check Packages}
if BuildPackages then
begin
if PlatformARMv6 then Inc(Total, 4);
if PlatformARMv7 then Inc(Total, 4);
if PlatformARMv8 then Inc(Total, 4);
end;
{Calculate Percent}
if Total > 0 then
begin
Percent:=100 div Total;
end;
{$IFDEF WINDOWS}
{Add Header}
WorkBuffer:='';
WorkBuffer:=WorkBuffer + '@echo off' + LineEnd;
WorkBuffer:=WorkBuffer + 'set path=' + PathPrefix + StripTrailingSlash(CompilerPath) + '\bin\i386-win32;' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
{Add Start}
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo ======================Start of Build Script======================' + LineEnd;
{Check ARMv6}
if PlatformARMv6 then
begin
{Check RTL}
if BuildRTL then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo Building ARMv6 RTL' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo ==================' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
{RTL Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{RTL}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{RTL Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_install CROSSINSTALL=1';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv6-ultibo/rtl' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
{Check Packages}
if BuildPackages then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo Building ARMv6 packages' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo =======================' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
{RTL Clean (To remove units from \rtl\units)}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{Packages Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{Packages}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH -Fu' + StripTrailingSlash(CompilerPath) + '\units\armv6-ultibo\rtl"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{Packages Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_install CROSSINSTALL=1';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv6-ultibo/packages' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
end;
{Check ARMv7}
if PlatformARMv7 then
begin
{Check RTL}
if BuildRTL then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo Building ARMv7 RTL' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo ==================' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
{RTL Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{RTL}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{RTL Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_install CROSSINSTALL=1';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv7-ultibo/rtl' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
{Check Packages}
if BuildPackages then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo Building ARMv7 Packages' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo =======================' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
{RTL Clean (To remove units from \rtl\units)}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{Packages Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{Packages}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH -Fu' + StripTrailingSlash(CompilerPath) + '\units\armv7-ultibo\rtl"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{Packages Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_install CROSSINSTALL=1';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv7-ultibo/packages' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
end;
{Check ARMv8}
if PlatformARMv8 then
begin
{Check RTL}
if BuildRTL then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo Building ARMv8 RTL' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo ==================' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
{RTL Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{RTL}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{RTL Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_install CROSSINSTALL=1';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv8-ultibo/rtl' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
{Check Packages}
if BuildPackages then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo Building ARMv8 Packages' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo =======================' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
{RTL Clean (To remove units from \rtl\units)}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{Packages Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{Packages}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH -Fu' + StripTrailingSlash(CompilerPath) + '\units\armv8-ultibo\rtl"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
{Packages Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_install CROSSINSTALL=1';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv8-ultibo/packages' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(Progress * Percent) + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
end;
WorkBuffer:=WorkBuffer + 'echo ' + MarkerProgress + IntToStr(100) + LineEnd;
{Add Footer}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo Build RTL completed successfully' + LineEnd;
WorkBuffer:=WorkBuffer + 'GOTO End' + LineEnd;
{Add Error}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + ':Error' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo Build RTL failed, see above for errors' + LineEnd;
{Add End}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + ':End' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo .' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo =======================End of Build Script=======================' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo ' + MarkerEnd + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
{$ENDIF}
{$IFDEF LINUX}
{Add Header}
WorkBuffer:='';
WorkBuffer:=WorkBuffer + '#!/bin/bash' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'export PATH=' + PathPrefix + StripTrailingSlash(CompilerPath) + '/bin:$PATH' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
{Add Error}
WorkBuffer:=WorkBuffer + 'function exitFailure() {' + LineEnd;
WorkBuffer:=WorkBuffer + ' if [ $? -ne 0 ]; then' + LineEnd;
WorkBuffer:=WorkBuffer + ' echo "."' + LineEnd;
WorkBuffer:=WorkBuffer + ' echo "Build RTL failed, see above for errors"' + LineEnd;
WorkBuffer:=WorkBuffer + ' echo "."' + LineEnd;
WorkBuffer:=WorkBuffer + ' echo "=======================End of Build Script======================="' + LineEnd;
WorkBuffer:=WorkBuffer + ' echo "' + MarkerEnd + '"' + LineEnd;
WorkBuffer:=WorkBuffer + ' exit 1' + LineEnd;
WorkBuffer:=WorkBuffer + ' fi' + LineEnd;
WorkBuffer:=WorkBuffer + '}' + LineEnd;
{Add Start}
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "======================Start of Build Script======================"' + LineEnd;
{Check ARMv6}
if PlatformARMv6 then
begin
{Check RTL}
if BuildRTL then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "Building ARMv6 RTL"' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "=================="' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
{RTL Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6 BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{RTL}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6 BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{RTL Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_install CROSSINSTALL=1 BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' INSTALL_PREFIX=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/lib/fpc/' + CompilerVersion + '/units/armv6-ultibo/rtl' + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
{Check Packages}
if BuildPackages then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "Building ARMv6 packages"' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "======================="' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
{RTL Clean (To remove units from /rtl/units)}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6 BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{Packages Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6 BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{Packages}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6 BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH -Fu' + StripTrailingSlash(CompilerPath) + '/lib/fpc/' + CompilerVersion + '/units/armv6-ultibo/rtl"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{Packages Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_install CROSSINSTALL=1 BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' INSTALL_PREFIX=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/lib/fpc/' + CompilerVersion + '/units/armv6-ultibo/packages' + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
end;
{Check ARMv7}
if PlatformARMv7 then
begin
{Check RTL}
if BuildRTL then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "Building ARMv7 RTL"' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "=================="' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
{RTL Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{RTL}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{RTL Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_install CROSSINSTALL=1 BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' INSTALL_PREFIX=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/lib/fpc/' + CompilerVersion + '/units/armv7-ultibo/rtl' + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
{Check Packages}
if BuildPackages then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "Building ARMv7 Packages"' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "======================="' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
{RTL Clean (To remove units from /rtl/units)}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{Packages Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{Packages}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH -Fu' + StripTrailingSlash(CompilerPath) + '/lib/fpc/' + CompilerVersion + '/units/armv7-ultibo/rtl"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{Packages Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_install CROSSINSTALL=1 BINUTILSPREFIX=arm-none-eabi-';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + ARMCompiler;
WorkBuffer:=WorkBuffer + ' INSTALL_PREFIX=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/lib/fpc/' + CompilerVersion + '/units/armv7-ultibo/packages' + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
end;
{Check ARMv8}
if PlatformARMv8 then
begin
{Check RTL}
if BuildRTL then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "Building ARMv8 RTL"' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "=================="' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
//To Do //BINUTILSPREFIX for AARCH64 ?
{RTL Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{RTL}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{RTL Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_install CROSSINSTALL=1';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' INSTALL_PREFIX=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/lib/fpc/' + CompilerVersion + '/units/armv8-ultibo/rtl' + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
{Check Packages}
if BuildPackages then
begin
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "Building ARMv8 Packages"' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "======================="' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
//To Do //BINUTILSPREFIX for AARCH64 ?
{RTL Clean (To remove units from /rtl/units)}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{Packages Clean}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{Packages}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH -Fu' + StripTrailingSlash(CompilerPath) + '/lib/fpc/' + CompilerVersion + '/units/armv8-ultibo/rtl"';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
{Packages Install}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'make packages_install CROSSINSTALL=1';
WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8';
WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/' + AARCH64Compiler;
WorkBuffer:=WorkBuffer + ' INSTALL_PREFIX=' + StripTrailingSlash(CompilerPath);
WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/lib/fpc/' + CompilerVersion + '/units/armv8-ultibo/packages' + LineEnd;
WorkBuffer:=WorkBuffer + 'exitFailure' + LineEnd;
Inc(Progress);
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(Progress * Percent) + '"' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
end;
end;
WorkBuffer:=WorkBuffer + 'echo "' + MarkerProgress + IntToStr(100) + '"' + LineEnd;
{Add Footer}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "Build RTL completed successfully"' + LineEnd;
{Add End}
WorkBuffer:=WorkBuffer + '' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "."' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "=======================End of Build Script======================="' + LineEnd;
WorkBuffer:=WorkBuffer + 'echo "' + MarkerEnd + '"' + LineEnd;
WorkBuffer:=WorkBuffer + '' + LineEnd;
{$ENDIF}
{Set Size}
FileStream.Size:=Length(WorkBuffer);
{Write File}
FileStream.Position:=0;
FileStream.WriteBuffer(PChar(WorkBuffer)^,Length(WorkBuffer));
Result:=True;
finally
FileStream.Free;
{$IFDEF LINUX}
if Result then
begin
FpChmod(Filename,S_IRWXU or S_IRGRP or S_IXGRP or S_IROTH or S_IXOTH);
end;
{$ENDIF}
end;
except
on E: Exception do
begin
LogOutput(' Error: Exception creating RTL build script - Message: ' + E.Message);
LogOutput('');
end;
end;
end;
{==============================================================================}
function TfrmMain.ExecuteBuildFile:Boolean;
var
Filename:String;
{$IFDEF LINUX}
Parameters:TStringList;
{$ENDIF}
begin
{}
Result:=False;
try
if Length(SourcePath) = 0 then Exit;
if Length(InstallPath) = 0 then Exit;
if Length(CompilerName) = 0 then Exit;
if Length(CompilerPath) = 0 then Exit;
if Length(CompilerVersion) = 0 then Exit;
if not(BuildRTL) and not(BuildPackages) then Exit;
if not(PlatformARMv6) and not(PlatformARMv7) and not(PlatformARMv8) then Exit;
{Get Filename}
Filename:=AddTrailingSlash(SourcePath) + BuildScript;
LogOutput(' Build Script is ' + Filename);
LogOutput('');
{Check File}
if not FileExists(Filename) then Exit;
{Execute Process}
{$IFDEF WINDOWS}
if not ExecuteConsoleProcessEx('cmd.exe /c',Filename,SourcePath,MarkerEnd,MarkerProgress,mmoMain,progressMain) then Exit;
{$ENDIF}
{$IFDEF LINUX}
Parameters:=TStringList.Create;
try
Parameters.Add('-c');
Parameters.Add(Filename);
if not ExecuteShellProcess('/bin/bash',Parameters,SourcePath,MarkerEnd,MarkerProgress,mmoMain,progressMain) then Exit;
finally
Parameters.Free;
end;
{$ENDIF}
Result:=True;
except
on E: Exception do
begin
LogOutput(' Error: Exception executing RTL build script - Message: ' + E.Message);
LogOutput('');
end;
end;
end;
{==============================================================================}
function TfrmMain.DownloadFirmware:Boolean;
var
Count:Integer;
FileURL:String;
Filename:String;
Lastname:String;
Pathname:String;
Lines:TStringList;
FileVersion:String;
LastVersion:String;
Client:TFPHTTPClient;
begin
{}
Result:=False;
try
if Length(BranchName) = 0 then Exit;
if Length(SourcePath) = 0 then Exit;
if Length(FirmwarePath) = 0 then Exit;
if Length(FirmwareVersionURL) = 0 then Exit;
{Check Source Path}
if not DirectoryExists(StripTrailingSlash(SourcePath)) then
begin
LogOutput(' Error: SourcePath "' + SourcePath + '" does not exist');
LogOutput('');
Exit;
end;
{Add Firmware Path}
LogOutput(' Firmware Path is ' + FirmwarePath);
LogOutput('');
{Check Firmware Path}
if not DirectoryExists(StripTrailingSlash(FirmwarePath)) then
begin
{Create Firmware Path}
ForceDirectories(StripTrailingSlash(FirmwarePath));
if not DirectoryExists(StripTrailingSlash(FirmwarePath)) then
begin
LogOutput(' Error: Could not create firmware path "' + FirmwarePath + '"');
LogOutput('');
Exit;
end;
end;
{Get FileURL}
FileURL:=FirmwareVersionURL + BranchName + FirmwareVersionFolder + FirmwareId;
LogOutput(' Firmware File URL is ' + FileURL);
LogOutput('');
{Get Filename}
Filename:=AddTrailingSlash(SourcePath) + FirmwareId;
LogOutput(' Latest Firmware Filename is ' + Filename);
LogOutput('');
{Get Lastname}
Lastname:=AddTrailingSlash(SourcePath) + FirmwareLast;
LogOutput(' Current Firmware Filename is ' + Lastname);
LogOutput('');
{Set Defaults}
FileVersion:='<Unknown>';
LastVersion:='<Unknown>';
{Check File}
if FileExists(Filename) then
begin
{Delete File}
DeleteFile(Filename);
if FileExists(Filename) then Exit;
end;
{Create HTTP Client}
Client:=TFPHTTPClient.Create(nil);
try
Client.AllowRedirect:=True;
{Get Firmware File}
LogOutput(' Downloading file: ' + FirmwareId);
LogOutput('');
Client.Get(FileURL,Filename);
Lines:=TStringList.Create;
try
{Open Firmware File}
Lines.LoadFromFile(Filename);
if Lines.Count = 0 then
begin
LogOutput(' Error: Latest firmware file contains no data');
LogOutput('');
Exit;
end;
{Get File Version}
FileVersion:=Lines.Strings[0];
LogOutput(' Latest Firmware is ' + FileVersion);
LogOutput('');
{Open Last Firmware File}
if FileExists(Lastname) then
begin
Lines.Clear;
Lines.LoadFromFile(Lastname);
if Lines.Count = 0 then
begin
LogOutput(' Error: Current firmware file contains no data');
LogOutput('');
Exit;
end;
{Get Last Version}
LastVersion:=Lines.Strings[0];
end;
LogOutput(' Current Firmware is ' + LastVersion);
LogOutput('');
if LastVersion <> FileVersion then
begin
Client.OnDataReceived:=DoDataReceived;
{Get Raspberry Pi Firmware}
LogOutput(' Downloading Raspberry Pi A/B/A+/B+/Zero/ZeroW Firmware');
LogOutput('');
{Get Pathname}
Pathname:=AddTrailingSlash(FirmwarePath) + FirmwareDownloadFolderRPi;
{Check Pathname}
if not DirectoryExists(Pathname) then
begin
ForceDirectories(Pathname);
if not DirectoryExists(Pathname) then
begin
LogOutput(' Error: Could not create firmware path "' + Pathname + '"');
LogOutput('');
Exit;
end;
end;
for Count:=FirmwareDownloadFilesStartRPi to (FirmwareDownloadFilesStartRPi + FirmwareDownloadFilesCountRPi - 1) do
begin
{Get FileURL}
FileURL:=FirmwareDownloadURL + FileVersion + FirmwareDownloadFolder + FirmwareDownloadFiles[Count];
{Get Filename}
Filename:=AddTrailingSlash(Pathname) + FirmwareDownloadFiles[Count];
{Check and Delete File}
if FileExists(Filename) then DeleteFile(Filename);
{Get Firmware File}
LogOutput(' Downloading file: ' + FirmwareDownloadFiles[Count]);
Client.Get(FileURL,Filename);
end;
LogOutput('');
{Get Raspberry Pi2 Firmware}
LogOutput(' Downloading Raspberry Pi 2B Firmware');
LogOutput('');
{Get Pathname}
Pathname:=AddTrailingSlash(FirmwarePath) + FirmwareDownloadFolderRPi2;
{Check Pathname}
if not DirectoryExists(Pathname) then
begin
ForceDirectories(Pathname);
if not DirectoryExists(Pathname) then
begin
LogOutput(' Error: Could not create firmware path "' + Pathname + '"');
LogOutput('');
Exit;
end;
end;
for Count:=FirmwareDownloadFilesStartRPi to (FirmwareDownloadFilesStartRPi + FirmwareDownloadFilesCountRPi - 1) do
begin
{Get FileURL}
FileURL:=FirmwareDownloadURL + FileVersion + FirmwareDownloadFolder + FirmwareDownloadFiles[Count];
{Get Filename}
Filename:=AddTrailingSlash(Pathname) + FirmwareDownloadFiles[Count];
{Check and Delete File}
if FileExists(Filename) then DeleteFile(Filename);
{Get Firmware File}
LogOutput(' Downloading file: ' + FirmwareDownloadFiles[Count]);
Client.Get(FileURL,Filename);
end;
LogOutput('');
{Get Raspberry Pi3 Firmware}
LogOutput(' Downloading Raspberry Pi 3B/3B+/3A+ Firmware');
LogOutput('');
{Get Pathname}
Pathname:=AddTrailingSlash(FirmwarePath) + FirmwareDownloadFolderRPi3;
{Check Pathname}
if not DirectoryExists(Pathname) then
begin
ForceDirectories(Pathname);
if not DirectoryExists(Pathname) then
begin
LogOutput(' Error: Could not create firmware path "' + Pathname + '"');
LogOutput('');
Exit;
end;
end;
for Count:=FirmwareDownloadFilesStartRPi to (FirmwareDownloadFilesStartRPi + FirmwareDownloadFilesCountRPi - 1) do
begin
{Get FileURL}
FileURL:=FirmwareDownloadURL + FileVersion + FirmwareDownloadFolder + FirmwareDownloadFiles[Count];
{Get Filename}
Filename:=AddTrailingSlash(Pathname) + FirmwareDownloadFiles[Count];
{Check and Delete File}
if FileExists(Filename) then DeleteFile(Filename);
{Get Firmware File}
LogOutput(' Downloading file: ' + FirmwareDownloadFiles[Count]);
Client.Get(FileURL,Filename);
end;
LogOutput('');
{Get Raspberry Pi4 Firmware}
LogOutput(' Downloading Raspberry Pi 4B/400 Firmware');
LogOutput('');
{Get Pathname}
Pathname:=AddTrailingSlash(FirmwarePath) + FirmwareDownloadFolderRPi4;
{Check Pathname}
if not DirectoryExists(Pathname) then
begin
ForceDirectories(Pathname);
if not DirectoryExists(Pathname) then
begin
LogOutput(' Error: Could not create firmware path "' + Pathname + '"');
LogOutput('');
Exit;
end;
end;
for Count:=FirmwareDownloadFilesStartRPi4 to (FirmwareDownloadFilesStartRPi4 + FirmwareDownloadFilesCountRPi4 - 1) do
begin
{Get FileURL}
FileURL:=FirmwareDownloadURL + FileVersion + FirmwareDownloadFolder + FirmwareDownloadFiles[Count];
{Get Filename}
Filename:=AddTrailingSlash(Pathname) + FirmwareDownloadFiles[Count];
{Check and Delete File}
if FileExists(Filename) then DeleteFile(Filename);
{Get Firmware File}
LogOutput(' Downloading file: ' + FirmwareDownloadFiles[Count]);
Client.Get(FileURL,Filename);
end;
LogOutput('');
{Get Filename}
Filename:=AddTrailingSlash(SourcePath) + FirmwareId;
{Check Lastname}
if FileExists(Lastname) then
begin
DeleteFile(Lastname);
if FileExists(Lastname) then Exit;
end;
{Rename Firmware File}
Result:=RenameFile(Filename,Lastname);
end
else
begin
Result:=True;
end;
finally
Lines.Free;
end;
finally
Client.Free;
end;
except
on E: Exception do
begin
LogOutput(' Error: Exception downloading latest firmware - Message: ' + E.Message);
LogOutput('');
end;
end;
end;
{==============================================================================}
{==============================================================================}
end.
|
{*********************************************}
{ TeeChart Delphi Component Library }
{ Mixed Text and Chart Print Demo }
{ Copyright (c) 1995-2001 by David Berneda }
{ All rights reserved }
{*********************************************}
unit uprint;
{ This example shows how to print both Text and Chart in the SAME PAGE }
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, Chart, Series, ExtCtrls, Teengine,
TeeProcs;
type
TPrintForm = class(TForm)
Chart1: TChart;
LineSeries1: TLineSeries;
BitBtn1: TBitBtn;
Edit1: TEdit;
BitBtn2: TBitBtn;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
PrintForm: TPrintForm;
implementation
{$R *.dfm}
uses printers;
procedure TPrintForm.FormCreate(Sender: TObject);
begin
LineSeries1.FillSampleValues(30); { <-- we need some random values }
end;
procedure TPrintForm.BitBtn1Click(Sender: TObject);
var h,w:longint;
begin
Screen.Cursor := crHourGlass; { <-- nice detail }
try
Printer.BeginDoc; { <-- start printer job }
try
{ now print some text on printer.canvas }
With Printer.Canvas do
begin
Font.Name:='Arial';
Font.Size:=10; { <-- set the font size }
Font.Style:=[];
TextOut(0,0,Edit1.Text); { <-- print some text }
end;
h:=Printer.PageHeight; { <-- get page height }
w:=Printer.PageWidth; { <-- get page width }
{ And now print the chart component... }
Chart1.PrintPartial( Rect( w div 10, { <-- left margin }
h div 3 , { <-- top margin }
w - (w div 10), { <-- right margin }
h - (h div 10) )); { <-- bottom margin }
{ print more text.... }
With Printer.Canvas do
begin
Font.Name:='Arial';
Font.Size:=12; { <-- set the font size }
Font.Style:=[fsItalic];
TextOut(0,60,Edit1.Text+' ...again'); { <-- print some text }
end;
Printer.EndDoc; { <-- end job and print !! }
except
on Exception do { just in case an error happens... }
Begin
Printer.Abort;
Printer.EndDoc;
Raise; { <-- raise up the exception !!! }
end;
end;
finally
Screen.Cursor:=crDefault; { <-- restore cursor }
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit ToolWnds;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
DesignWindows, Vcl.ExtCtrls, Vcl.ToolWin, Vcl.ComCtrls, System.IniFiles, Vcl.ActnList, Vcl.Menus,
Vcl.ActnPopup, System.Actions, Vcl.PlatformDefaultStyleActnCtrls;
type
TToolbarDesignWindow = class(TDesignWindow)
ToolBar1: TToolBar;
Splitter1: TSplitter;
PopupMenu1: TPopupActionBar;
ActionList1: TActionList;
ToolbarCmd: TAction;
TextLabelsCmd: TAction;
Toolbar2: TMenuItem;
PopupMenu2: TPopupActionBar;
TextLabels1: TMenuItem;
HelpCmd: TAction;
procedure FormCreate(Sender: TObject);
procedure Splitter1Moved(Sender: TObject);
procedure Splitter1CanResize(Sender: TObject; var NewSize: Integer;
var Accept: Boolean);
procedure ToolbarCmdExecute(Sender: TObject);
procedure TextLabelsCmdExecute(Sender: TObject);
procedure ToolbarCmdUpdate(Sender: TObject);
procedure TextLabelsCmdUpdate(Sender: TObject);
procedure HelpCmdExecute(Sender: TObject);
procedure HelpCmdUpdate(Sender: TObject);
private
FLargeButtons: Boolean;
procedure SetLargeButtons(Value: Boolean);
function GetToolbarVisible: boolean;
procedure SetToolbarVisible(const Value: boolean);
procedure UpdateToolbarVisible(Visible: boolean);
protected
procedure ResizeButtons(Large: Boolean); virtual;
public
property ToolbarVisible: boolean read GetToolbarVisible write SetToolbarVisible;
property LargeButtons: Boolean read FLargeButtons write SetLargeButtons;
end;
implementation
{$R *.dfm}
{
Simple Intl fix to display longer captions on localized versions of the
product.
InitFromResources is called in initialization section.
See bug #105175
}
resourcestring
sSmallToolbarSize = '30';
sSmallButtonHeight = '22';
sSmallButtonWidth = '23';
sLargeToolbarSize = '44';
sLargeButtonHeight = '36';
sLargeButtonWidth = '56';
var
SmallToolbarSize: Integer;
SmallButtonHeight: Integer;
SmallButtonWidth: Integer;
LargeToolbarSize: Integer;
LargeButtonHeight: Integer;
LargeButtonWidth: Integer;
procedure InitFromResources;
begin
SmallToolbarSize := StrToIntDef(sSmallToolbarSize, 30);
SmallButtonHeight := StrToIntDef(sSmallButtonHeight, 22);
SmallButtonWidth := StrToIntDef(sSmallButtonWidth, 23);
LargeToolbarSize := StrToIntDef(sLargeToolbarSize, 44);
LargeButtonHeight := StrToIntDef(sLargeButtonHeight, 36);
LargeButtonWidth := StrToIntDef(sLargeButtonWidth, 56);
end;
procedure TToolbarDesignWindow.FormCreate(Sender: TObject);
begin
{ Toggle to force update }
ResizeButtons(False);
SmallToolbarSize := ToolBar1.Height;
ResizeButtons(True);
LargeToolbarSize := ToolBar1.Height;
ResizeButtons(FLargeButtons);
UpdateToolbarVisible(True);
end;
procedure TToolbarDesignWindow.Splitter1CanResize(Sender: TObject;
var NewSize: Integer; var Accept: Boolean);
begin
with Toolbar1 do
if (Height >= LargeToolbarSize) then
if (NewSize <= SmallToolbarSize) then
NewSize := SmallToolbarSize
else
NewSize := LargeToolbarSize
else
if(NewSize >= LargeToolbarSize) then
NewSize := LargeToolbarSize
else
NewSize := SmallToolbarSize;
end;
procedure TToolbarDesignWindow.Splitter1Moved(Sender: TObject);
begin
LargeButtons := (ToolBar1.Height >= LargeToolbarSize);
end;
function TToolbarDesignWindow.GetToolbarVisible: boolean;
begin
Result := ToolBar1.Visible;
end;
procedure TToolbarDesignWindow.HelpCmdExecute(Sender: TObject);
begin
if (HelpType = htContext) and (HelpContext <> 0) then
Application.HelpContext(HelpContext)
else if (HelpKeyword <> '') then
Application.HelpKeyword(HelpKeyword);
end;
procedure TToolbarDesignWindow.HelpCmdUpdate(Sender: TObject);
begin
if Sender is TAction then
begin
TAction(Sender).Visible := (((HelpType = htContext) and (HelpContext <> 0)) or (HelpKeyword <> ''));
end;
end;
procedure TToolbarDesignWindow.SetToolbarVisible(const Value: boolean);
begin
if Value <> ToolbarVisible then
UpdateToolbarVisible(Value);
end;
procedure TToolbarDesignWindow.UpdateToolbarVisible(Visible: boolean);
begin
DisableAlign;
try
ToolBar1.Visible := Visible;
Splitter1.Top := Toolbar1.Top + Toolbar1.Height;
Splitter1.Visible := Visible;
finally
EnableAlign;
end;
end;
procedure TToolbarDesignWindow.ToolbarCmdExecute(Sender: TObject);
begin
ToolbarVisible := not ToolbarVisible;
end;
procedure TToolbarDesignWindow.ToolbarCmdUpdate(Sender: TObject);
begin
if Sender is TAction then
TAction(Sender).Checked := ToolbarVisible;
end;
procedure TToolbarDesignWindow.SetLargeButtons(Value: Boolean);
begin
if Value <> FLargeButtons then
begin
ResizeButtons(Value);
FLargeButtons := Value;
end;
end;
procedure TToolbarDesignWindow.ResizeButtons(Large: Boolean);
var
// I: Integer;
NewLargeWidth, NewLargeHeight: Integer;
begin
with ToolBar1 do
begin
Perform(WM_SETREDRAW, 0, 0);
try
if Large then
begin
NewLargeWidth := MulDiv(LargeButtonWidth, PixelsPerInch, 96);
NewLargeHeight := LargeButtonHeight + MulDiv(13{Height of text}, PixelsPerInch, 96) - 13;
{ Large buttons }
{
for I := 0 to ButtonCount - 1 do
if not (Buttons[I].Style in [tbsSeparator, tbsDivider]) then
Buttons[I].AutoSize := True;
}
ShowCaptions := True;
ButtonWidth := NewLargeWidth;
ButtonHeight := NewLargeHeight;
//! Take into account large font systems
Height := ButtonHeight + 8;//!LargeToolbarSize;
ShowHint := False;
end
else
begin
{ Small buttons }
{
for I := 0 to ButtonCount - 1 do
if not (Buttons[I].Style in [tbsSeparator, tbsDivider]) then
Buttons[I].AutoSize := False;
}
ShowCaptions := False;
ButtonWidth := SmallButtonWidth;
ButtonHeight := SmallButtonHeight;
Height := SmallToolbarSize;
ShowHint := True;
end;
finally
Perform(WM_SETREDRAW, 1, 0);
Invalidate;
end;
end;
end;
procedure TToolbarDesignWindow.TextLabelsCmdExecute(Sender: TObject);
begin
LargeButtons := not LargeButtons;
end;
procedure TToolbarDesignWindow.TextLabelsCmdUpdate(Sender: TObject);
begin
if Sender is TAction then
TAction(Sender).Checked := LargeButtons;
end;
initialization
InitFromResources;
end.
|
{
ID: nhutqua1
PROG: maze1
LANG: PASCAL
}
uses math;
const fileinp = 'maze1.in';
fileout = 'maze1.out';
dx:array[1..4] of longint = (-1,1,0,0);
dy:array[1..4] of longint = (0,0,-1,1);
maxW = 38;
maxH = 100;
type edge = record
x,y:longint;
end;
var w,h:longint;
a:array[1..2*maxH+1,1..maxW*2+1] of char;
d:array[1..2*maxH+1,1..maxW*2+1] of longint;
procedure Init;
var i,j:longint;
begin
assign(input,fileinp); reset(input);
readln(w,h);
for i:=1 to 2*h+1 do
begin
j:=1;
while j <= 2*w+1 do
begin
if not eoln then read(a[i,j])
else a[i,j]:=' ';
inc(j);
end;
readln;
end;
close(input);
end;
procedure BFS1(i,j:longint);
var free:array[1..2*maxH+1,1..maxW*2+1] of boolean;
rear,front,k,x,y:longint;
q:array[1..(2*maxH+1)*(maxW*2+1)] of edge;
cur:edge;
begin
fillchar(free,sizeof(free),true);
rear:=1;
front:=1;
q[1].x:=i;
q[1].y:=j;
free[i,j]:=false;
d[i,j]:=1;
repeat
cur:=q[rear]; inc(rear);
for k:=1 to 4 do
begin
x:=cur.x + dx[k];
y:=cur.y + dy[k];
if (x < 1) or (x > 2*h+1) or (y < 1) or (y > 2*w+1) then
continue;
if free[x,y] and (a[x,y] = ' ') then
begin
d[x,y]:=d[cur.x,cur.y] + 1;
free[x,y]:=false;
inc(front);
q[front].x:=x;
q[front].y:=y;
end;
end;
until rear > front;
end;
procedure BFS2(i,j:longint);
var free:array[1..2*maxH+1,1..maxW*2+1] of boolean;
rear,front,max,k,x,y:longint;
q:array[1..(2*maxH+1)*(maxW*2+1)] of edge;
cur:edge;
begin
fillchar(free,sizeof(free),true);
rear:=1;
front:=1;
q[1].x:=i;
q[1].y:=j;
free[i,j]:=false;
d[i,j]:=1;
max:=-maxlongint;
repeat
cur:=q[rear]; inc(rear);
for k:=1 to 4 do
begin
x:=cur.x + dx[k];
y:=cur.y + dy[k];
if (x < 1) or (x > 2*h+1) or (y < 1) or (y > 2*w+1) then
continue;
if free[x,y] and (a[x,y] = ' ') then
begin
if d[x,y] > d[cur.x,cur.y] + 1 then d[x,y]:=d[cur.x,cur.y] + 1;
free[x,y]:=false;
inc(front);
q[front].x:=x;
q[front].y:=y;
end;
end;
until rear > front;
end;
procedure Analyse;
var c,i,j:longint;
s:array[1..2] of edge;
begin
c:=0;
for i:=1 to 2*h+1 do
begin
if c = 2 then break;
if a[i,1] = ' ' then
begin
inc(c);
s[c].x:=i;
s[c].y:=1;
end;
if a[i,2*w+1] = ' ' then
begin
inc(c);
s[c].x:=i;
s[c].y:=2*w+1;
end;
end;
for i:=1 to 2*w+1 do
begin
if c = 2 then break;
if a[1,i] = ' ' then
begin
inc(c);
s[c].x:=1;
s[c].y:=i;
end;
if a[2*h+1,i] = ' ' then
begin
inc(c);
s[c].x:=2*h+1;
s[c].y:=i;
end;
end;
BFS1(s[1].x,s[1].y);
BFS2(s[2].x,s[2].y);
end;
procedure Print;
var res,i,j:longint;
begin
assign(output,fileout); rewrite(output);
res:=-maxlongint;
for i:=1 to 2*h+1 do
for j:=1 to 2*w+1 do
if (a[i,j] = ' ') and (d[i,j] > res) then
res:=d[i,j];
writeln(res div 2);
close(output);
end;
begin
Init;
Analyse;
Print;
end.
|
unit fIVRoutes;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ORCtrls, ExtCtrls, ORFn, rMisc, rODMeds, VA508AccessibilityManager, VAUtils, fAutoSz;
type
TfrmIVRoutes = class(TfrmAutoSz)
pnlTop: TPanel;
cboAllIVRoutes: TORComboBox;
pnlBottom: TORAutoPanel;
BtnOK: TButton;
btnCancel: TButton;
procedure BtnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function ShowOtherRoutes(var Route: string): boolean;
var
frmIVRoutes: TfrmIVRoutes;
implementation
{$R *.dfm}
function ShowOtherRoutes(var Route: string): boolean;
var
idx: integer;
begin
Result := false;
frmIVRoutes := TfrmIVRoutes.Create(Application);
ResizeFormToFont(TForm(frmIVRoutes));
SetFormPosition(frmIVRoutes);
//LoadAllIVRoutes(frmIVRoutes.cboAllIVRoutes.Items);
if frmIVRoutes.ShowModal = mrOK then
begin
idx := frmIVRoutes.cboAllIVRoutes.ItemIndex;
if idx > -1 then
begin
Route := frmIVRoutes.cboAllIVRoutes.Items.Strings[idx];
setPiece(Route,U,5,'1');
end
else Route := '';
Result := True;
end;
frmIVRoutes.Free;
end;
{ TfrmIVRoutes }
procedure TfrmIVRoutes.btnCancelClick(Sender: TObject);
begin
frmIVRoutes.cboAllIVRoutes.ItemIndex := -1;
modalResult := mrOK;
end;
procedure TfrmIVRoutes.BtnOKClick(Sender: TObject);
begin
if frmIVRoutes.cboAllIVRoutes.ItemIndex = -1 then
begin
infoBox('A route from the list must be selected','Warning', MB_OK);
Exit;
end;
modalResult := mrOK;
end;
procedure TfrmIVRoutes.FormCreate(Sender: TObject);
begin
frmIVRoutes := nil;
LoadAllIVRoutes(cboAllIVRoutes.Items);
end;
procedure TfrmIVRoutes.FormDestroy(Sender: TObject);
begin
inherited;
frmIVRoutes := nil;
end;
end.
|
unit ConsoleHelper;
interface
procedure WritelnAttrib(s : String; attributes : word; asError : Boolean = false);
procedure WritelnInfo(s : String); // writes BOLD, YELLOW
procedure WritelnError(s : string); // red, to stderr
procedure WritelnStatus(s : String); // bold white
procedure SetVerbosity(verbosity : Boolean);
procedure VerboseWrite(msg : String);
implementation
uses
Windows;
var
isVerbose : Boolean;
procedure SetVerbosity(verbosity : Boolean);
begin
isVerbose := verbosity;
end;
procedure VerboseWrite(msg : String);
begin
if isVerbose then
Writeln(msg);
end;
procedure WritelnInfo(s : String);
begin
WritelnAttrib(s, FOREGROUND_RED or FOREGROUND_GREEN or FOREGROUND_INTENSITY);
end;
procedure WritelnError(s : string);
begin
WritelnAttrib(s, FOREGROUND_RED or FOREGROUND_INTENSITY, true);
end;
procedure WritelnStatus(s : String);
begin
WritelnAttrib(s, FOREGROUND_RED or FOREGROUND_GREEN or FOREGROUND_BLUE or FOREGROUND_INTENSITY);
end;
procedure WritelnAttrib(s : String; attributes : word; asError : Boolean = false);
var
sbi : TConsoleScreenBufferInfo;
begin
// Get the current attributes
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), sbi);
// Set the new attributes
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), attributes);
if asError then
writeln(ErrOutput, s)
else
writeln(s);
// restore attributes
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), sbi.wAttributes);
end;
end.
|
unit Base2N;
{Base 2**N conversion (1 <= N <= 6), N=0 is treated as Base32-Hex}
interface
(*************************************************************************
DESCRIPTION : Base 2**N conversion, 1 <= N <= 6
(N=0 is treated as Base32-Hex)
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : o RFC 4648 - The Base16, Base32, and Base64 Data Encodings
o RFC 3548 (obsolete)- The Base16, Base32, and Base64 Data Encodings
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 16.09.04 W.Ehrhardt Initial version
0.20 18.09.04 we array of chars, CONST
0.30 23.10.04 we S2BPrim, Str2NBase, SxxB routines (BP7+)
0.31 24.10.04 we Encode2NPrim, EncodeBasexx/Str, TBaseStr
0.32 24.10.04 we Decode2NPrim, TP5-6
0.33 24.10.04 we DecodeBasexx/Str
0.34 25.10.04 we AnsiString versions
0.35 31.10.04 we Rangecheck code in Decode2NPrim
0.36 28.11.06 we Base32-Hex, bugfix NPB=8 for Base32
0.37 01.12.06 we StrictCase
0.38 28.03.08 we Ansistring for BIT32 instead of WIN32
0.39 14.11.08 we BTypes, str255, char8/pchar8, Ptr2Inc
0.40 05.07.09 we D12 fix for EncodeBase2NStr (use setlength)
0.41 18.02.12 we 64-bit changes
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2002-2012 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
(*todo
- var error, check decode for strict cases (correct length, trailing '=')
- upper/lowercase for base2 ... base32
- win32/prim procs with longint
*)
{$i STD.INC}
uses
BTypes;
const
StrictCase: boolean = false; {strict case for N=1..5: if true uppercase only,}
{else lowercase allowed}
procedure EncodeBase2N(psrc,pdest: pointer; lsrc,ldest,N: word; var LA: word);
{-Base 2**N encode src to dest, LA result length of dest string, Base32-Hex if N=0}
procedure EncodeBase64(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Base64 encode src to dest, LA result length of dest string}
procedure EncodeBase32(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Base32 encode src to dest, LA result length of dest string}
procedure EncodeBase32Hex(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Base32-Hex encode src to dest, LA result length of dest string}
procedure EncodeBase16(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Base16 encode src to dest, LA result length of dest string}
function EncodeBase2NStr(psrc: pointer; lsrc, N: word): str255;
{-Base 2**N string of memory block of length lsrc pointed by psrc, Base32-Hex if N=0}
function EncodeBase64Str(psrc: pointer; lsrc: word): str255;
{-Base64 string of memory block of length lsrc pointed by psrc}
function EncodeBase32Str(psrc: pointer; lsrc: word): str255;
{-Base32 string of memory block of length lsrc pointed by psrc}
function EncodeBase32HexStr(psrc: pointer; lsrc: word): str255;
{-Base32-Hex string of memory block of length lsrc pointed by psrc}
function EncodeBase16Str(psrc: pointer; lsrc: word): str255;
{-Base16 string of memory block of length lsrc pointed by psrc}
procedure DecodeBase2N(psrc,pdest: pointer; lsrc,ldest,N: word; var LA: word);
{-Decode Base 2**N src to dest, LA result length of dest string, Base32-Hex if N=0}
procedure DecodeBase64(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Decode Base64 src to dest, LA result length of dest string}
procedure DecodeBase32(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Decode Base32 src to dest, LA result length of dest string}
procedure DecodeBase32Hex(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Decode Base32-Hex src to dest, LA result length of dest string}
procedure DecodeBase16(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Decode Base16 src to dest, LA result length of dest string}
procedure DecodeBase2NStr({$ifdef CONST} const {$endif} s: str255; pdest: pointer; ldest, N: word; var LA: word);
{-Decode Base 2**N string to dest, LA/ldest result/max length of dest, Base32-Hex if N=0}
procedure DecodeBase64Str({$ifdef CONST} const {$endif} s: str255; pdest: pointer; ldest: word; var LA: word);
{-Decode Base64 src string to dest, LA/ldest result/max length of dest}
procedure DecodeBase32Str({$ifdef CONST} const {$endif} s: str255; pdest: pointer; ldest: word; var LA: word);
{-Decode Base32 src string to dest, LA/ldest result/max length of dest}
procedure DecodeBase32HexStr({$ifdef CONST} const {$endif} s: str255; pdest: pointer; ldest: word; var LA: word);
{-Decode Base32-Hex src string to dest, LA/ldest result/max length of dest}
procedure DecodeBase16Str({$ifdef CONST} const {$endif} s: str255; pdest: pointer; ldest: word; var LA: word);
{-Decode Base16 src string to dest, LA/ldest result/max length of dest}
{$ifndef BIT16}
function EncodeBase2NAStr(psrc: pointer; lsrc, N: word): ansistring;
{-Base 2**N string of memory block of length lsrc pointed by psrc, Base32-Hex if N=0}
function EncodeBase64AStr(psrc: pointer; lsrc: word): ansistring;
{-Base64 string of memory block of length lsrc pointed by psrc}
function EncodeBase32AStr(psrc: pointer; lsrc: word): ansistring;
{-Base32 string of memory block of length lsrc pointed by psrc}
function EncodeBase32HexAStr(psrc: pointer; lsrc: word): ansistring;
{-Base32-Hex string of memory block of length lsrc pointed by psrc}
function EncodeBase16AStr(psrc: pointer; lsrc: word): ansistring;
{-Base16 string of memory block of length lsrc pointed by psrc}
procedure DecodeBase2NAStr(const s: ansistring; pdest: pointer; ldest, N: word; var LA: word);
{-Decode Base 2**N string to dest, LA/ldest result/max length of dest, Base32-Hex if N=0}
procedure DecodeBase64AStr(const s: ansistring; pdest: pointer; ldest: word; var LA: word);
{-Decode Base64 src string to dest, LA/ldest result/max length of dest}
procedure DecodeBase32AStr(const s: ansistring; pdest: pointer; ldest: word; var LA: word);
{-Decode Base32 src string to dest, LA/ldest result/max length of dest}
procedure DecodeBase32HexAStr(const s: ansistring; pdest: pointer; ldest: word; var LA: word);
{-Decode Base32 src string to dest, LA/ldest result/max length of dest}
procedure DecodeBase16AStr(const s: ansistring; pdest: pointer; ldest: word; var LA: word);
{-Decode Base16 src string to dest, LA/ldest result/max length of dest}
{$endif}
implementation
const
CB64: array[0..63] of char8 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
CB32: array[0..31] of char8 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
CB32H: array[0..31] of char8 = '0123456789ABCDEFGHIJKLMNOPQRSTUV';
CB16: array[0..15] of char8 = '0123456789ABCDEF';
const
mask: array[0..15] of word = ($0000,$0001,$0003,$0007,$000F,$001F,$003F,$007F,
$00FF,$01FF,$03FF,$07FF,$0FFF,$1FFF,$3FFF,$7FFF);
{---------------------------------------------------------------------------}
procedure Encode2NPrim(psrc,pdest: pointer; lsrc,ldest, N, NPB: word;
{$ifdef CONST} const {$else} var {$endif} c; var LA: word);
{-Encode bytes from psrc to Base2**N chars in pdest; lsrc=length of src;}
{ ldest=max length of dest, LA=result length of encoded string, NPB=number}
{ of pad bytes, c=encode table}
var
buf: word;
bits,rest: integer;
ca: array[0..63] of char8 absolute c;
procedure app(c: char8);
{-append one char to dest with: check length, inc pointers}
begin
if LA<ldest then begin
pchar8(pdest)^ := c;
inc(Ptr2Inc(pdest));
inc(LA);
end;
end;
begin
LA := 0;
if (N<1) or (N>6) or (psrc=nil) or (pdest=nil) or (ldest<1) or (lsrc<1) then exit;
bits := 0;
buf := 0;
{Calculate count of = padding chars, note that if s has enough}
{capacity to hold all output, pad to a multiple of block size}
if NPB>0 then begin
rest := ((longint(lsrc)*8 + N-1) div N) mod NPB;
if rest>0 then rest := NPB - rest;
end
else rest:=0;
{process input bytes}
while lsrc>0 do begin
buf := (buf shl 8) or pByte(psrc)^;
inc(Ptr2Inc(psrc));
dec(lsrc);
inc(bits,8);
while bits > N do begin
dec(bits,N);
app(ca[buf shr bits]);
buf := buf and mask[bits];
end;
end;
{remaining partial input}
if bits>0 then begin
if LA<ldest then app(ca[buf shl (N-bits)]);
end;
{pad with '='}
while rest>0 do begin
app('=');
dec(rest);
end;
end;
{---------------------------------------------------------------------------}
procedure EncodeBase2N(psrc,pdest: pointer; lsrc,ldest,N: word; var LA: word);
{-Base 2**N encode src to dest, LA result length of dest string, Base32-Hex if N=0}
begin
case N of
0: Encode2NPrim(psrc,pdest,lsrc,ldest,5,8,CB32H,LA);
5: Encode2NPrim(psrc,pdest,lsrc,ldest,N,8,CB32,LA);
6: Encode2NPrim(psrc,pdest,lsrc,ldest,N,4,CB64,LA);
else Encode2NPrim(psrc,pdest,lsrc,ldest,N,0,CB16,LA);
end;
end;
{---------------------------------------------------------------------------}
procedure EncodeBase64(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Base64 encode src to dest, LA result length of dest string}
begin
EncodeBase2N(psrc,pdest,lsrc,ldest,6,LA);
end;
{---------------------------------------------------------------------------}
procedure EncodeBase32(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Base32 encode src to dest, LA result length of dest string}
begin
EncodeBase2N(psrc,pdest,lsrc,ldest,5,LA);
end;
{---------------------------------------------------------------------------}
procedure EncodeBase32Hex(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Base32-Hex encode src to dest, LA result length of dest string}
begin
EncodeBase2N(psrc,pdest,lsrc,ldest,0,LA);
end;
{---------------------------------------------------------------------------}
procedure EncodeBase16(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Base16 encode src to dest, LA result length of dest string}
begin
EncodeBase2N(psrc,pdest,lsrc,ldest,4,LA);
end;
{---------------------------------------------------------------------------}
function EncodeBase2NStr(psrc: pointer; lsrc, N: word): str255;
{-Base 2**N string of memory block of length lsrc pointed by psrc}
var
LA: word;
s: str255;
begin
EncodeBase2N(psrc,@s[1],lsrc,255,N,LA);
{$ifndef BIT16}
if LA>255 then LA := 255;
setlength(s,LA);
{$else}
if LA<255 then s[0]:=chr(LA) else s[0]:=#255;
{$endif}
EncodeBase2NStr := s;
end;
{---------------------------------------------------------------------------}
function EncodeBase64Str(psrc: pointer; lsrc: word): str255;
{-Base64 string of memory block of length lsrc pointed by psrc}
begin
EncodeBase64Str := EncodeBase2NStr(psrc,lsrc,6);
end;
{---------------------------------------------------------------------------}
function EncodeBase32Str(psrc: pointer; lsrc: word): str255;
{-Base32 string of memory block of length lsrc pointed by psrc}
begin
EncodeBase32Str := EncodeBase2NStr(psrc,lsrc,5);
end;
{---------------------------------------------------------------------------}
function EncodeBase32HexStr(psrc: pointer; lsrc: word): str255;
{-Base32-Hex string of memory block of length lsrc pointed by psrc}
begin
EncodeBase32HexStr := EncodeBase2NStr(psrc,lsrc,0);
end;
{---------------------------------------------------------------------------}
function EncodeBase16Str(psrc: pointer; lsrc: word): str255;
{-Base16 string of memory block of length lsrc pointed by psrc}
begin
EncodeBase16Str := EncodeBase2NStr(psrc,lsrc,4);
end;
{---------------------------------------------------------------------------}
procedure Decode2NPrim(psrc,pdest: pointer; lsrc,ldest,N: word;
{$ifdef CONST} const {$else} var {$endif} c; var LA: word);
{-Decodes Base2**N chars from psrc to bytes in pdest; lsrc=length of src;}
var
i,bits,buf: word;
{$ifopt R+}
hmask: word;
{$endif}
IC: array[char8] of byte;
b: byte;
cu: char8;
ca: array[0..63] of char8 absolute c;
const
UInc = ord('a')-ord('A');
begin
LA := 0;
if (N<1) or (N>6) or (psrc=nil) or (pdest=nil) or (ldest<1) or (lsrc<1) then exit;
{Fill input array with Base2**N digit values, $FF if not valid}
fillchar(IC, sizeof(IC), $FF);
for i:=0 to pred(1 shl N) do ic[ca[i]] := i;
if not StrictCase then begin
for i:=0 to pred(1 shl N) do begin
cu := ca[i];
if (cu>='A') and (cu<='Z') then inc(byte(cu),UInc);
ic[cu] := i;
end;
end;
{$ifopt R+}
hmask:= mask[16-N];
{$endif}
buf := 0;
bits := 0;
while lsrc>0 do begin
b := IC[pchar8(psrc)^];
inc(Ptr2Inc(psrc));
dec(lsrc);
if b>127 then exit;
{include next input character into buffer}
{if range checking is on, we must prevent the following shift}
{from overflowing buf. Either here with hmask or in [*] below}
{$ifopt R+}
buf := ((buf and hmask) shl N) or b;
{$else}
buf := (buf shl N) or b;
{$endif}
inc(bits,N);
if bits>7 then begin
{output a byte if at least 8 bits in input buf}
dec(bits,8);
if LA<ldest then begin
inc(LA);
pByte(pdest)^ := (buf shr bits) and $FF;
{[*] buf := buf and mask[bits];}
inc(Ptr2Inc(pdest));
end;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure DecodeBase2N(psrc,pdest: pointer; lsrc,ldest,N: word; var LA: word);
{-Decode Base 2**N src to dest, LA result length of dest string, Base32-Hex if N=0}
begin
case N of
0: Decode2NPrim(psrc,pdest,lsrc,ldest,5,CB32H,LA);
5: Decode2NPrim(psrc,pdest,lsrc,ldest,N,CB32,LA);
6: Decode2NPrim(psrc,pdest,lsrc,ldest,N,CB64,LA);
else Decode2NPrim(psrc,pdest,lsrc,ldest,N,CB16,LA);
end;
end;
{---------------------------------------------------------------------------}
procedure DecodeBase64(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Decode Base64 src to dest, LA result length of dest string}
begin
DecodeBase2N(psrc,pdest,lsrc,ldest,6,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase32(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Decode Base32 src to dest, LA result length of dest string}
begin
DecodeBase2N(psrc,pdest,lsrc,ldest,5,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase32Hex(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Decode Base32-Hex src to dest, LA result length of dest string}
begin
Decode2NPrim(psrc,pdest,lsrc,ldest,5,CB32H,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase16(psrc,pdest: pointer; lsrc,ldest: word; var LA: word);
{-Decode Base16 src to dest, LA result length of dest string}
begin
DecodeBase2N(psrc,pdest,lsrc,ldest,4,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase2NStr({$ifdef CONST} const {$endif} s: str255; pdest: pointer; ldest, N: word; var LA: word);
{-Decode Base 2**N string to dest, LA/ldest result/max length of dest, Base32-Hex if N=0}
begin
DecodeBase2N(@s[1],pdest,length(s),ldest,N,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase64Str({$ifdef CONST} const {$endif} s: str255; pdest: pointer; ldest: word; var LA: word);
{-Decode Base64 src string to dest, LA/ldest result/max length of dest}
begin
DecodeBase2NStr(s,pdest,ldest,6,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase32Str({$ifdef CONST} const {$endif} s: str255; pdest: pointer; ldest: word; var LA: word);
{-Decode Base32 src string to dest, LA/ldest result/max length of dest}
begin
DecodeBase2NStr(s,pdest,ldest,5,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase32HexStr({$ifdef CONST} const {$endif} s: str255; pdest: pointer; ldest: word; var LA: word);
{-Decode Base32-Hex src string to dest, LA/ldest result/max length of dest}
begin
DecodeBase2NStr(s,pdest,ldest,0,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase16Str({$ifdef CONST} const {$endif} s: str255; pdest: pointer; ldest: word; var LA: word);
{-Decode Base64 src string to dest, LA/ldest result/max length of dest}
begin
DecodeBase2NStr(s,pdest,ldest,4,LA);
end;
{$ifndef BIT16}
{---------------------------------------------------------------------------}
function EncodeBase2NAStr(psrc: pointer; lsrc, N: word): ansistring;
{-Base 2**N string of memory block of length lsrc pointed by psrc, Base32-Hex if N=0}
var
LA: word;
LL: longint;
{$ifndef RESULT}
result: ansistring;
{$endif}
begin
if N=0 then LA:=5 else LA:=N;
LL := 6+((longint(lsrc)*8 + LA-1) div LA);
if LL > $FFFE then LL := $FFFE;
setlength(result, LL);
EncodeBase2N(psrc,@result[1],lsrc, LL and $FFFF,N,LA);
if LA<LL then setlength(result,LA);
{$ifndef RESULT}
EncodeBase2NAStr := result;
{$endif}
end;
{---------------------------------------------------------------------------}
function EncodeBase64AStr(psrc: pointer; lsrc: word): ansistring;
{-Base64 string of memory block of length lsrc pointed by psrc}
begin
EncodeBase64AStr := EncodeBase2NAStr(psrc,lsrc,6);
end;
{---------------------------------------------------------------------------}
function EncodeBase32AStr(psrc: pointer; lsrc: word): ansistring;
{-Base32 string of memory block of length lsrc pointed by psrc}
begin
EncodeBase32AStr := EncodeBase2NAStr(psrc,lsrc,5);
end;
{---------------------------------------------------------------------------}
function EncodeBase32HexAStr(psrc: pointer; lsrc: word): ansistring;
{-Base32-Hex string of memory block of length lsrc pointed by psrc}
begin
EncodeBase32HexAStr := EncodeBase2NAStr(psrc,lsrc,0);
end;
{---------------------------------------------------------------------------}
function EncodeBase16AStr(psrc: pointer; lsrc: word): ansistring;
{-Base16 string of memory block of length lsrc pointed by psrc}
begin
EncodeBase16AStr := EncodeBase2NAStr(psrc,lsrc,4);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase2NAStr(const s: ansistring; pdest: pointer; ldest, N: word; var LA: word);
{-Decode Base 2**N string to dest, LA/ldest result/max length of dest}
var
lsrc: word;
begin
lsrc :=$FFFE;
if length(s)<lsrc then lsrc:=length(s);
DecodeBase2N(@s[1],pdest,lsrc,ldest,N,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase64AStr(const s: ansistring; pdest: pointer; ldest: word; var LA: word);
{-Decode Base64 src string to dest, LA/ldest result/max length of dest}
begin
DecodeBase2NAStr(s,pdest,ldest,6,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase32AStr(const s: ansistring; pdest: pointer; ldest: word; var LA: word);
{-Decode Base32 src string to dest, LA/ldest result/max length of dest}
begin
DecodeBase2NAStr(s,pdest,ldest,5,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase32HexAStr(const s: ansistring; pdest: pointer; ldest: word; var LA: word);
{-Decode Base32 src string to dest, LA/ldest result/max length of dest}
begin
DecodeBase2NAStr(s,pdest,ldest,0,LA);
end;
{---------------------------------------------------------------------------}
procedure DecodeBase16AStr(const s: ansistring; pdest: pointer; ldest: word; var LA: word);
{-Decode Base16 src string to dest, LA/ldest result/max length of dest}
begin
DecodeBase2NAStr(s,pdest,ldest,4,LA);
end;
{$endif}
end.
|
Unit Objects;
Interface
Uses
ODraws, Graph, Dos;
Const
SIZE = 20;
Type
PObject = ^TObject;
TObject = Object
Name : ObjectType;
Map : Draws;
PosX : Integer;
PosY : Integer;
Constructor Init(NameObject : ObjectType; x, y : Integer);
Procedure Show;
Function AsColor(Color : Char) : Integer;
Function InRange : Boolean;
Destructor Done;
Virtual;
End;
Function MousePressed : Boolean;
Procedure MouseCursor(on:boolean);
Procedure MouseStatus(Var But : Integer;
Var x, y: Integer);
Implementation
CONSTRUCTOR TObject.Init(NameObject : ObjectType; x, y : Integer);
Begin
Name := NameObject;
Case NameObject Of
SPHERE : Map := SphereDRAW;
PLETS : Map := PletsDRAW;
CUTTER : Map := CutterDRAW;
WALL : Map := WallDRAW;
CANDY : Map := CandyDRAW;
WAY : Map := WayDRAW;
EXITDOR: Map := ExitDRAW;
VOID : Map := VoidDRAW;
End;
PosX := X*SIZE;
PosY := Y*SIZE;
Show;
End;
Function TObject.AsColor(Color : Char) : Integer;
Begin
Case Color Of
'0' : AsColor := 0;
'1' : AsColor := 1;
'2' : AsColor := 2;
'3' : AsColor := 3;
'4' : AsColor := 4;
'5' : AsColor := 5;
'6' : AsColor := 6;
'7' : AsColor := 7;
'8' : AsColor := 8;
'9' : AsColor := 9;
'A', 'a' : AsColor := 10;
'B', 'b' : AsColor := 11;
'C', 'c' : AsColor := 12;
'D', 'd' : AsColor := 13;
'E', 'e' : AsColor := 14;
'F', 'f' : AsColor := 15;
Else AsColor := 0;
End;
End;
Function TObject.InRange : Boolean;
Var
b, x, y : Integer;
Begin
MouseStatus(b, x, y);
InRange := ((x > PosX) And (x < (PosX)+20) And
(y > PosY) And (y < (PosY)+20));
End;
Procedure TObject.Show;
Var
i, j : Integer;
Begin
For i := 1 To SIZE Do
For j := 1 To SIZE Do
PutPixel(j+PosX, i+PosY, AsColor(Map[i][j]));
End;
DESTRUCTOR TObject.Done;
Begin
End;
{***************************************************************************}
Var
r : Registers;
Function MousePressed : Boolean;
Var
b : Integer;
x, y : Integer;
Begin
MouseStatus(b, x, y);
MousePressed := b <> 0;
End;
Procedure CallMouse(MouseFunction : integer);
Begin
r.AX := MouseFunction;
intr ($33, r);
End;
Procedure MouseStatus(Var But : Integer;
Var x, y: Integer);
Begin
CallMouse ($03);
x := (r.CX) + 1;
y := (r.DX) + 1;
But := r.BX;
End;
Procedure MouseCursor(on:boolean);
Begin
If (on) Then
CallMouse($01)
Else
CallMouse($02);
End;
End.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 2015-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.JSON.Utils;
interface
{$SCOPEDENUMS ON}
uses System.SysUtils, System.Types, System.TypInfo, System.Classes, System.JSON.Types, System.NetEncoding;
type
TJsonTextUtils = class
const
kArrayEscapedArraySize = 128;
EscapedUnicodeText = '!';
private
class var FSingleQuoteCharEscapeFlags: TBooleanDynArray;
class var FDoubleQuoteCharEscapeFlags: TBooleanDynArray;
class var FHtmlCharEscapeFlags: TBooleanDynArray;
public
class constructor Create;
class procedure WriteEscapedString(const Writer: TTextWriter; const Str: string; Delimiter: Char;
AppendDelimiters: Boolean; const CharEscapeFlags: array of Boolean; StringEscapeHandling: TJsonStringEscapeHandling;
var WriteBuffer: TCharArray);
class function ShouldEscapeJavaScriptString(const S: string; const CharEscapeFlags: array of Boolean): Boolean;
class property SingleQuoteCharEscapeFlags: TBooleanDynArray read FSingleQuoteCharEscapeFlags;
class property DoubleQuoteCharEscapeFlags: TBooleanDynArray read FDoubleQuoteCharEscapeFlags;
class property HtmlCharEscapeFlags: TBooleanDynArray read FHtmlCharEscapeFlags;
class procedure ToCharAsUnicode(C: Char; var Buffer: array of Char);
class function IsWhiteSpace(const Str: string): Boolean;
end;
TJsonTypeUtils = class
public
class function InheritsFrom(ATypeInfo: PTypeInfo; const AParentClass: TClass): Boolean; static;
class function IsAssignableFrom(ATo, AFrom: PTypeInfo): Boolean; static;
end;
implementation
uses System.Generics.Collections, System.Character, System.DateUtils;
{ TJsonTextUtils }
class constructor TJsonTextUtils.Create;
const // \n \r \t \\ \f \b
InitEscapedChars: array[0..5] of Char = (#10, #13, #9, #92, #12, #8);
var
EscapeChar: Char;
I: Integer;
begin
SetLength(FSingleQuoteCharEscapeFlags, kArrayEscapedArraySize);
SetLength(FDoubleQuoteCharEscapeFlags, kArrayEscapedArraySize);
SetLength(FHtmlCharEscapeFlags, kArrayEscapedArraySize);
for EscapeChar in InitEscapedChars do
begin
FSingleQuoteCharEscapeFlags[Ord(EscapeChar)] := True;
FDoubleQuoteCharEscapeFlags[Ord(EscapeChar)] := True;
FHtmlCharEscapeFlags[Ord(EscapeChar)] := True;
end;
I := 0;
while I < Ord(' ') do
begin
FSingleQuoteCharEscapeFlags[I] := True;
FDoubleQuoteCharEscapeFlags[I] := True;
FHtmlCharEscapeFlags[I] := True;
Inc(I);
end;
FSingleQuoteCharEscapeFlags[Ord('''')] := True;
FDoubleQuoteCharEscapeFlags[Ord('"')] := True;
FHtmlCharEscapeFlags[Ord('"')] := True;
FHtmlCharEscapeFlags[Ord('''')] := True;
FHtmlCharEscapeFlags[Ord('<')] := True;
FHtmlCharEscapeFlags[Ord('>')] := True;
FHtmlCharEscapeFlags[Ord('&')] := True;
end;
class function TJsonTextUtils.ShouldEscapeJavaScriptString(const S: string; const CharEscapeFlags: array of Boolean): Boolean;
var
C: Char;
begin
Result := False;
if S <> '' then
for C in S do
if (Ord(C) >= Length(CharEscapeFlags)) or CharEscapeFlags[Ord(C)] then
Exit(True);
end;
class procedure TJsonTextUtils.WriteEscapedString(const Writer: TTextWriter; const Str: string; Delimiter: Char;
AppendDelimiters: Boolean; const CharEscapeFlags: array of Boolean; StringEscapeHandling: TJsonStringEscapeHandling;
var WriteBuffer: TCharArray);
var
LastWritePosition, I, Start, Len: Integer;
EscapedValue: string;
C: Char;
IsEscapedUnicodeText: Boolean;
begin
if AppendDelimiters then
Writer.Write(Delimiter);
LastWritePosition := 0;
for I := 0 to Length(Str) - 1 do
begin
C := Str[I + Low(Str)];
if (Ord(C) < Length(CharEscapeFlags)) and not CharEscapeFlags[Ord(C)] then
Continue;
case C of
// tab
#9:
EscapedValue := '\t';
// end line
#10:
EscapedValue := '\n';
// carriage return
#13:
EscapedValue := '\r';
// formfeed
#12:
EscapedValue := '\f';
// backspace
#8:
EscapedValue := '\b';
// backslash
#92:
EscapedValue := '\\';
// new line
#$0085:
EscapedValue := '\u0085';
// line separator
#$2028:
EscapedValue := '\u2028';
// paragraph separator
#$2029:
EscapedValue := '\u2029';
else
begin
if (Ord(C) < Length(CharEscapeFlags)) or (StringEscapeHandling = TJsonStringEscapeHandling.EscapeNonAscii) then
begin
if (C = '''') and (StringEscapeHandling <> TJsonStringEscapeHandling.EscapeHtml) then
EscapedValue := '\'''
else if (C = '"') and (StringEscapeHandling <> TJsonStringEscapeHandling.EscapeHtml) then
EscapedValue := '\"'
else
begin
if Length(WriteBuffer) = 0 then
SetLength(WriteBuffer, 6);
TJsonTextUtils.ToCharAsUnicode(C, WriteBuffer);
EscapedValue := EscapedUnicodeText;
end;
end
else
EscapedValue := '';
end;
end; // case
if EscapedValue = '' then
Continue;
IsEscapedUnicodeText := EscapedValue = EscapedUnicodeText;
if (I > LastWritePosition) then
begin
Len := I - LastWritePosition;
Start := 0;
if IsEscapedUnicodeText then
begin
Inc(Len, 6);
Inc(Start, 6);
end;
if (Length(WriteBuffer) = 0) or (Length(WriteBuffer) < Len) then
SetLength(WriteBuffer, Len);
Move(Str[Low(string) + LastWritePosition], WriteBuffer[Start], (Len - Start) * SizeOf(Char));
Writer.Write(WriteBuffer, Start, Len - Start);
end;
LastWritePosition := I + 1;
if not IsEscapedUnicodeText then
Writer.Write(EscapedValue)
else
Writer.Write(WriteBuffer, 0, 6);
end; // for
if LastWritePosition = 0 then
Writer.Write(Str)
else
begin
Len := Length(Str) - LastWritePosition;
if (Length(WriteBuffer) = 0) or (Length(WriteBuffer) < Len) then
SetLength(WriteBuffer, Len);
if Len > 0 then
begin
Move(Str[Low(string) + LastWritePosition], WriteBuffer[0], Len * SizeOf(Char));
Writer.Write(WriteBuffer, 0, Len);
end;
end;
if AppendDelimiters then
Writer.Write(Delimiter);
end;
{ TStringUtils }
class function TJsonTextUtils.IsWhiteSpace(const Str: string): Boolean;
var
I: Integer;
begin
if (Length(Str) = 0) then
Exit(False);
for I := Low(Str) to High(Str) do
if not Str[I].IsWhiteSpace then
Exit(False);
Result := True;
end;
class procedure TJsonTextUtils.ToCharAsUnicode(C: Char; var Buffer: array of Char);
const
HexChars = '0123456789ABCDEF';
var
UnicodeValue: Integer;
begin
Buffer[0] := '\';
Buffer[1] := 'u';
UnicodeValue := Ord(C);
Buffer[2] := HexChars.Chars[(UnicodeValue and $F000) shr 12];
Buffer[3] := HexChars.Chars[(UnicodeValue and $F00) shr 8];
Buffer[4] := HexChars.Chars[(UnicodeValue and $F0) shr 4];
Buffer[5] := HexChars.Chars[(UnicodeValue and $F)];
end;
{ TJsonTypeUtil }
class function TJsonTypeUtils.InheritsFrom(ATypeInfo: PTypeInfo; const AParentClass: TClass): Boolean;
begin
if ATypeInfo^.Kind = tkClass then
Result := ATypeInfo^.TypeData^.ClassType.InheritsFrom(AParentClass)
else
Result := False;
end;
class function TJsonTypeUtils.IsAssignableFrom(ATo, AFrom: PTypeInfo): Boolean;
begin
case ATo^.Kind of
tkUnknown:
Result := False;
tkInteger,
tkEnumeration,
tkFloat,
tkVariant,
tkInt64,
tkSet:
Result := GetTypeData(ATo) = GetTypeData(AFrom);
tkClass:
if AFrom^.Kind = tkClass then
Result := ATo.TypeData^.ClassType.InheritsFrom(AFrom.TypeData^.ClassType)
else
Result := False;
tkProcedure,
tkMethod:
Result := False;
tkString, tkLString, tkWString, tkChar, tkWChar, tkUString:
case AFrom^.Kind of
tkString, tkLString, tkWString, tkChar, tkWChar, tkUString:
Result := True
else
Result := False
end;
tkArray,
tkDynArray:
if AFrom^.Kind = tkArray then
Result := AFrom^.TypeData^.DynArrElType^ = ATo^.TypeData^.DynArrElType^
else
Result := False;
tkRecord, tkMRecord:
if AFrom^.Kind in [tkRecord, tkMRecord] then
Result := ATo = AFrom
else
Result := False;
tkPointer,
tkInterface:
Result := ATo = AFrom;
tkClassRef:
Result := AFrom^.Kind = tkClass;
else
Result := False;
end;
end;
end.
|
unit Ex3Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ProgressViewer;
type
TMyShortThread = class(TThread)
private
procedure DoUsefullTask; // Процедура для имитации полезной работы
public
procedure Execute; override;
end;
TForm1 = class(TForm)
btnRunParallelThread: TButton;
procedure btnRunParallelThreadClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
MyThread: TMyShortThread;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnRunParallelThreadClick(Sender: TObject);
begin
// Запускает параллельный поток. Если объект потока уже создан,
// то уничтожает его.
if MyThread <> nil then
FreeAndNil(MyThread);
MyThread := TMyShortThread.Create(False);
end;
{ TMyShortThread }
procedure TMyShortThread.DoUsefullTask;
var
AProgress: TProgressViewer;
begin
// Реальный поток может выполнять какую угодно полезную работу
// В учебных целях делаем паузу 5 секунд для имитации задержки, которая
// может возникнуть при выполнении полезной работы
AProgress := TProgressViewer.Create('Выполняется поток TMyShortThread');
Sleep(5000);
AProgress.TerminateProgress;
end;
procedure TMyShortThread.Execute;
begin
DoUsefullTask;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
// При закрытии программы необходимо завершить работу потока
// и уничтожить объект потока MyThread
if MyThread <> nil then
MyThread.Free;
end;
end.
|
unit SpiderApache;
{
*******************************************************************************************************************
SpiderApache: Contains TSpiderApache engine for Apache module
Author: Motaz Abdel Azeem
email: motaz@code.sd
Home page: http://code.sd
License: LGPL
Last modified: 12.July.2012
*******************************************************************************************************************
}
{$mode objfpc}{$h+}
interface
uses
Classes, SysUtils, ApacheUtils, SpiderUtils, SpiderAction;
type
{ TSpiderApache }
TSpiderApache = class(TComponent)
private
fOnRequest: TSpiderEvent;
fRequest: TSpiderRequest;
fResponse: TSpiderResponse;
fPath: string;
fPathInfo: string;
fModules: array of String;
fPathList: array of TStringList;
function SearchActionInModule(APath: string; AModule: TDataModule): Boolean;
{ Private declarations }
protected
{ Protected declarations }
public
constructor Create(TheOwner: TComponent); override;
procedure Init(PathInfo, ContentType, RequestMethod, Query, Cookies, UserAgent, PostedData,
ContentLength, Referer, RemoteIP, URI, ServerSoftware, Host: string);
destructor Destroy; override;
function Execute: TSpiderResponse;
procedure AddDataModule(const ADataModuleClassName: string; APaths: array of string);
{ Public declarations }
published
property OnRequest: TSpiderEvent read FOnRequest write FOnRequest;
{ Published declarations }
end;
implementation
{ TSpiderApache }
function TSpiderApache.Execute: TSpiderResponse;
var
Found: Boolean;
i: Integer;
dmc: TDataModuleClass;
DataMod: TDataModule;
begin
// Search path in main module actions
Found:= False;
if fPathInfo <> '' then
begin
Found:= SearchActionInModule(fPathInfo, TDataModule(Owner));
end;
DataMod:= nil;
// Search path in other additional modules
if (not Found) then
for i:= 0 to High(fModules) do
if fPathList[i].IndexOf(fPathInfo) <> -1 then
begin
dmc:= TDataModuleClass(FindClass(fModules[i]));
if dmc <> nil then
begin
DataMod:= dmc.Create(nil);
Found:= SearchActionInModule(fPathInfo, DataMod);
end;
if Found then
Break;
end;
// Default path /
if (not Found) and (fPathInfo = '') and (Assigned(fOnRequest)) then
begin
Found:= True;
if fRequest = nil then
raise Exception.Create('TSpiderApache: Request object is not initialized');
if fResponse = nil then
raise Exception.Create('TSpiderApache: Response object is not initialized');
fOnRequest(Self, fRequest, fResponse);
Result:= fResponse;
end;
if not Found then
fResponse.Add(fPathInfo + ' not found');
Result:= fResponse;
if Assigned(DataMod) then
DataMod.Free;
end;
constructor TSpiderApache.Create(TheOwner: TComponent);
begin
fResponse:= TSpiderResponse.Create;
fPath:= '/';
fRequest:= nil;
inherited Create(TheOwner);
end;
procedure TSpiderApache.Init(PathInfo, ContentType, RequestMethod, Query,
Cookies, UserAgent, PostedData, ContentLength, Referer, RemoteIP, URI,
ServerSoftware, Host: string);
begin
if (PathInfo <> '') and (PathInfo[Length(PathInfo)] = '/') then
PathInfo:= Copy(PathInfo, 1, Length(PathInfo) - 1);
fPathInfo:= Trim(PathInfo);
if Assigned(fRequest) then
fRequest.Free;
if Assigned(fResponse) then
fResponse.Content.Clear;
fRequest:= TApacheRequest.Create(PathInfo, ContentType, RequestMethod, Query, Cookies, UserAgent, PostedData,
ContentLength, Referer, RemoteIP, URI, ServerSoftware, Host);
end;
destructor TSpiderApache.Destroy;
begin
fRequest.Free;
fResponse.Free;
inherited Destroy;
end;
function TSpiderApache.SearchActionInModule(APath: string; AModule: TDataModule): Boolean;
var
i: Integer;
begin
if AModule = nil then
raise Exception.Create('error: Nil module passed');
Result:= False;
APath:= LowerCase(APath);
for i:= 0 to AModule.ComponentCount - 1 do
if AModule.Components[i] is TSpiderAction then
if LowerCase(TSpiderAction(AModule.Components[i]).Path) = APath then
begin
TSpiderAction(AModule.Components[i]).DoRequest(fRequest, fResponse);
Result:= True;
Break;
end;
end;
procedure TSpiderApache.AddDataModule(const ADataModuleClassName: string; APaths: array of string);
var
i: Integer;
begin
SetLength(fModules, Length(fModules) + 1);
fModules[High(fModules)]:= ADataModuleClassName;
SetLength(fPathList, Length(fPathList) + 1);
fPathList[High(fPathList)]:= TStringList.Create;
for i:= 0 to High(APaths) do
fPathList[High(fPathList)].Add(LowerCase(APaths[i]));
end;
end.
|
unit TestMoney;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, SysUtils, Money;
type
// Test methods for class TMoney
TestTMoney = class(TTestCase)
strict private
FMoney: TMoney;
public
procedure SetUp; override;
published
procedure TestToString;
procedure TestAdd;
procedure TestSubtract;
procedure TestMultiply;
procedure TestAllocate;
procedure TestEquals;
procedure TestChangeCurrencyConstructorGBPtoUSD;
procedure TestChangeCurrencyConstructorUSDtoGBP;
procedure TestJBConversion;
end;
//Test Allocating money
TestAllocatingMoney = class(TTestCase)
strict private
FMoney: TMoney;
public
procedure SetUp; override;
published
procedure TestAllocate5050;
procedure TestAllocate3070;
end;
//check the formatting for different currencies
TestBritishMoney = class(TTestCase)
strict private
FMoney: TMoney;
public
procedure SetUp; override;
published
procedure TestToString;
end;
TestFrenchMoney = class(TTestCase)
strict private
FMoney: TMoney;
public
procedure SetUp; override;
published
procedure TestToString;
end;
TestGermanMoney = class(TTestCase)
strict private
FMoney: TMoney;
public
procedure SetUp; override;
published
procedure TestToString;
end;
TestSwedishMoney = class(TTestCase)
strict private
FMoney: TMoney;
public
procedure SetUp; override;
published
procedure TestToString;
end;
implementation
uses
Spring.Collections;
procedure TestTMoney.SetUp;
begin
FMoney := TMoney.Create(45.34, TFormatSettings.Create);
end;
procedure TestTMoney.TestToString;
var
ReturnValue: string;
begin
ReturnValue := FMoney.ToString;
Check(ReturnValue = '$45.34');
// TODO: Validate method results
end;
procedure TestTMoney.TestAdd;
var
ReturnValue: IMoney;
begin
ReturnValue := FMoney.Add(TMoney.Create(50.29, TFormatSettings.Create));
Check(ReturnValue.Amount = 9563);
end;
procedure TestTMoney.TestSubtract;
var
ReturnValue: IMoney;
Amount: IMoney;
begin
Amount := TMoney.Create(30.03);
ReturnValue := FMoney.Subtract(Amount);
Check(ReturnValue.Amount = 1531);
end;
procedure TestTMoney.TestMultiply;
var
ReturnValue: IMoney;
Amount: Currency;
begin
// TODO: Setup method call parameters
Amount := 1.00;
ReturnValue := FMoney.Multiply(Amount);
// TODO: Validate method results
Check(ReturnValue.DecimalAmount = FMoney.DecimalAmount, 'Multiply failed');
end;
procedure TestTMoney.TestAllocate;
var
ReturnValue: IList<IMoney>;
Ratios: array[0..1] of integer;
begin
Ratios[0] := 7;
Ratios[1] := 3;
ReturnValue := FMoney.Allocate(Ratios);
Check(ReturnValue.Items[0].Amount = 3174);
Check(ReturnValue.Items[1].Amount = 1360);
end;
procedure TestTMoney.TestChangeCurrencyConstructorGBPtoUSD;
var
FromMoney : IMoney;
ToMoney : IMoney;
begin
FromMoney := TMoney.Create(36.48, TFormatSettings.Create(2057));
ToMoney := TMoney.ChangeCurrency(FromMoney, TFormatSettings.Create, 1.58);
//57.6384
//5764
CheckEquals(5764, ToMoney.Amount);
CheckEqualsString('$57.64', ToMoney.ToString);
end;
procedure TestTMoney.TestChangeCurrencyConstructorUSDtoGBP;
var
FromMoney : IMoney;
ToMoney : IMoney;
begin
FromMoney := TMoney.Create(36.48);
ToMoney := TMoney.ChangeCurrency(FromMoney, TFormatSettings.Create(2057), 1.58);
CheckEquals(5764, ToMoney.Amount);
CheckEqualsString('£57.64', ToMoney.ToString);
end;
procedure TestTMoney.TestEquals;
var
ReturnValue : boolean;
aMoney : IMoney;
begin
aMoney := TMoney.Create(45.34);
ReturnValue := FMoney.Equals(aMoney);
Check(ReturnValue);
aMoney := nil;
aMoney := TMoney.Create(5.27);
ReturnValue := FMoney.Equals(aMoney);
CheckFalse(ReturnValue);
aMoney := nil;
aMoney := TMoney.Create(5.27, TFormatSettings.Create(2057));
ReturnValue := FMoney.Equals(aMoney);
// CheckException(ReturnValue);
end;
procedure TestTMoney.TestJBConversion;
var
CRC : IMoney;
USD : IMoney;
begin
{ CRC := TMoney.Create(135102.13);
USD := Crc.(492.57);
CheckEquals(274.28, USD.DecimalAmount);}
USD := TMoney.Create(FromMoney.Multiply(ExchangeRate).Amount, ToFormatSettings);
end;
{ TestBritishMoney }
procedure TestBritishMoney.SetUp;
begin
FMoney := TMoney.Create(45.34, TFormatSettings.Create(2057));
end;
procedure TestBritishMoney.TestToString;
var
ReturnValue: string;
begin
ReturnValue := FMoney.ToString;
Check(ReturnValue = '£45.34');
end;
{ TestFrenchMoney }
procedure TestFrenchMoney.SetUp;
begin
FMoney := TMoney.Create(45.34, TFormatSettings.Create(1036));
end;
procedure TestFrenchMoney.TestToString;
var
ReturnValue: string;
begin
ReturnValue := FMoney.ToString;
Check(ReturnValue = '45,34 €');
end;
{ TestGermanMoney }
procedure TestGermanMoney.SetUp;
begin
FMoney := TMoney.Create(45.34, TFormatSettings.Create(1031));
end;
procedure TestGermanMoney.TestToString;
var
ReturnValue: string;
begin
ReturnValue := FMoney.ToString;
Check(ReturnValue = '45,34 €');
end;
{ TestSwedishMoney }
procedure TestSwedishMoney.SetUp;
begin
FMoney := TMoney.Create(45.34, TFormatSettings.Create(1053));
end;
procedure TestSwedishMoney.TestToString;
var
ReturnValue: string;
begin
ReturnValue := FMoney.ToString;
Check(ReturnValue = '45,34 kr');
end;
{ TestAllocatingMoney }
procedure TestAllocatingMoney.SetUp;
begin
FMoney := TMoney.Create(0.05);
end;
procedure TestAllocatingMoney.TestAllocate3070;
var
ReturnValue: IList<IMoney>;
Ratios: array[0..1] of integer;
begin
Ratios[0] := 3;
Ratios[1] := 7;
ReturnValue := FMoney.Allocate(Ratios);
Check(ReturnValue.Items[0].Amount = 2);
Check(ReturnValue.Items[1].Amount = 3);
end;
procedure TestAllocatingMoney.TestAllocate5050;
var
ReturnValue: IList<IMoney>;
Ratios: array[0..1] of integer;
begin
Ratios[0] := 5;
Ratios[1] := 5;
ReturnValue := FMoney.Allocate(Ratios);
Check(ReturnValue.Items[0].Amount = 3);
Check(ReturnValue.Items[1].Amount = 2);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTMoney.Suite);
RegisterTest(TestBritishMoney.Suite);
RegisterTest(TestFrenchMoney.Suite);
RegisterTest(TestGermanMoney.Suite);
RegisterTest(TestSwedishMoney.Suite);
RegisterTest(TestAllocatingMoney.Suite);
end.
|
{ Invokable interface IuTravelAgents }
unit uTravelAgentsIntf;
interface
uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd,
System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes,
System.Variants,
FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr;
type
ServerTravelAgents = class
private
FId: string;
FPassword: string;
FLogin: string;
procedure SetId(const Value: string);
procedure SetLogin(const Value: string);
procedure SetPassword(const Value: string);
published
property Id: string read FId write SetId;
property Login: string read FLogin write SetLogin;
property Password: string read FPassword write SetPassword;
end;
{ Invokable interfaces must derive from IInvokable }
IuTravelAgents = interface(IInvokable)
['{284826C9-3C3E-42C9-A15E-44D86B71B830}']
function ConnectToDb: TSQLConnection;
procedure SelectUserTravel(Password: string);
function LogInCheck(name, Password: string): Boolean;
function CheckUser(name: string): Boolean;
procedure AddUserInDb;
{ Methods of Invokable interface must not use the default }
{ calling convention; stdcall is recommended }
end;
implementation
{ ServerTravelAgents }
procedure ServerTravelAgents.SetId(const Value: string);
begin
FId := Value;
end;
procedure ServerTravelAgents.SetLogin(const Value: string);
begin
FLogin := Value;
end;
procedure ServerTravelAgents.SetPassword(const Value: string);
begin
FPassword := Value;
end;
initialization
{ Invokable interfaces must be registered }
InvRegistry.RegisterInterface(TypeInfo(IuTravelAgents));
end.
|
program findArea;
type
squareType = record
width : Integer;
height : Integer;
end;
var
square : squareType;
begin
WriteLn('Enter the height:');
ReadLn(square.height);
WriteLn('Enter the width:');
ReadLn(square.width);
WriteLn('Area: ', square.width * square.height);
end.
|
unit FCadastroMestreDet;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Datasnap.DBClient, uCtrlObject,
cxGrid, uCxGridPgn, uMensagem, FCadastro;
type
TfrmCadastroMestreDet = class(TfrmCadastro)
ds: TDataSource;
cds: TClientDataSet;
cdsDet1: TClientDataSet;
dsDet1: TDataSource;
procedure cdsAfterInsert(DataSet: TDataSet);
private
_Ctrl : TControlObject;
_ComponentToSetFocus: TWinControl;
_Operacao : TOperacaoBd;
_Codigo : Integer;
procedure configuraComponentes;
{ Private declarations }
protected
public
property codigo : Integer read _Codigo;
property operacao: TOperacaoBd read _Operacao;
procedure gravar;
procedure cancelar;
function getOperacao: TOperacaoBd;
procedure setup(Ctrl: TControlObject; CompToSetFocus: TWinControl; ACodigo: Integer = -1);
procedure iniciaForm; virtual;
constructor create (AOwner: TComponent; ATipoOperacao: TOperacaoBd; ACodigo: Integer = -1);
{ Public declarations }
end;
var
frmCadastroMestreDet: TfrmCadastroMestreDet;
implementation
{$R *.dfm}
{ TfrmCadastroMestreDet }
procedure TfrmCadastroMestreDet.cancelar;
begin
if cds.State in [dsInsert, dsEdit] then
begin
if questionMessage('Tem certeza que deseja cancelar? Todas as alterações serão perdidas.') then
begin
cds.Cancel;
Close;
end
else
begin
ModalResult := mrNone;
_ComponentToSetFocus.SetFocus;
end;
end
else
Close;
end;
procedure TfrmCadastroMestreDet.cdsAfterInsert(DataSet: TDataSet);
var
i : Integer;
begin
for i := 0 to cds.FieldCount - 1 do
begin
if pfInKey in cds.Fields[i].ProviderFlags then
if cds.Fields[i].DataType in [ftInteger,
ftSmallint,
ftShortint,
ftWord,
ftFloat,
ftCurrency,
ftLargeint]
then
cds.Fields[i].AsInteger := 0;
end;
//if _ComponentToSetFocus <> nil then
//_ComponentToSetFocus.SetFocus;
end;
procedure TfrmCadastroMestreDet.configuraComponentes;
var
i : Integer;
begin
for i := 0 to ComponentCount - 1 do
begin
if Components[i] is TcxGrid then
configuraCxGrid(TcxGrid(Components[i]));
end;
end;
constructor TfrmCadastroMestreDet.create(AOwner: TComponent; ATipoOperacao: TOperacaoBd; ACodigo: Integer);
begin
inherited create(AOwner);
_Operacao := ATipoOperacao;
_Codigo := ACodigo;
end;
function TfrmCadastroMestreDet.getOperacao: TOperacaoBd;
begin
result := _Operacao;
end;
procedure TfrmCadastroMestreDet.gravar;
begin
try
//cds.Post;
if not _Ctrl.gravar(cds, _Operacao) then
begin
warningMessage(_Ctrl.MessageInfo);
if not (_Operacao = dbDelete) then
cds.Edit
else
begin
Close;
ModalResult := mrAbort;
end;
end
else
begin
if _Operacao = dbDelete then
infoMessage('Registro Excluído com sucesso.')
else
infoMessage('Registro cadastrado com sucesso.');
Close;
Self.ModalResult := mrOk;
end;
except
on e : Exception do
begin
//errorMessage(e.ClassName + ' - ' + e.Message);
end;
end;
end;
procedure TfrmCadastroMestreDet.iniciaForm;
begin
_Ctrl.selecionarMestreDetalhe(codigo, [cds, cdsDet1]);
configuraBinding;
if _Operacao = dbInsert then
begin
cds.Insert;
end
else
if _Operacao = dbUpdate then
begin
cds.Edit;
end
else
if _Operacao = dbDelete then
begin
if questionMessage('Deseja excluir o registro selecionado?') then
begin
gravar;
end
else
begin
Self.CloseModal;
end;
end;
end;
procedure TfrmCadastroMestreDet.setup(Ctrl: TControlObject; CompToSetFocus: TWinControl; ACodigo: Integer);
begin
_Ctrl := Ctrl;
_ComponentToSetFocus := CompToSetFocus;
iniciaForm;
end;
end.
|
unit uIDC_Script;
interface
uses
Winapi.Windows, Winapi.Messages, // Windows
System.Classes, System.Variants, System.SysUtils, // System
uSVD_Type;
// Comment
// Enum and BitField
// Struct and Union
// Segment
procedure IDC_Decode( SVD_Device: TSVD_Device; var StringList: TStringList );
implementation
var
MainStringList: TStringList;
{
name value mask maskname comment
----------------------------------------------------------------------------------------------------------------------
OOFS_IFSIGN 0x0000 0x0003 OOF_SIGNMASK
OOFS_NOSIGN 0x0001 0x0003 OOF_SIGNMASK
OOFS_NEEDSIGN 0x0002 0x0003 OOF_SIGNMASK
----------------------------------------------------------------------------------------------------------------------
OOF_SIGNED 0x0004 0x0004
----------------------------------------------------------------------------------------------------------------------
OOF_NUMBER 0x0008 0x0008
----------------------------------------------------------------------------------------------------------------------
OOFW_IMM 0x0000 0x0030 OOF_WIDTHMASK
OOFW_16 0x0010 0x0030 OOF_WIDTHMASK
OOFW_32 0x0020 0x0030 OOF_WIDTHMASK
OOFW_8 0x0030 0x0030 OOF_WIDTHMASK
----------------------------------------------------------------------------------------------------------------------
OOF_ADDR 0x0040 0x0040
OOF_OUTER 0x0080 0x0080
OOF_ZSTROFF 0x0100 0x0100
----------------------------------------------------------------------------------------------------------------------
}
procedure GetFieldPosMask( const BitRange: TSVD_BitRange; var fieldPos: Cardinal; var fieldMask: Cardinal );
var
lsb: Cardinal;
msb: Cardinal;
width: Cardinal;
Start, Middle, Stop: Integer;
begin
lsb := 0;
width := 0;
case BitRange.bitRangeType of
brOffsetWidth:
begin
lsb := BitRange.bitRangeOffsetWidth.bitOffset;
width := BitRange.bitRangeOffsetWidth.bitWidth;
end;
brLsbMsb:
begin
lsb := BitRange.bitRangeLsbMsb.lsb;
msb := BitRange.bitRangeLsbMsb.msb;
width := msb - lsb + 1;
end;
brString: // [31:28]
begin
Start := Pos( '[', BitRange.bitRangeString );
Middle := Pos( ':', BitRange.bitRangeString );
Stop := Pos( ']', BitRange.bitRangeString );
msb := StrToInt( Copy( BitRange.bitRangeString, Start + 1, Middle - Start - 1 ) );
lsb := StrToInt( Copy( BitRange.bitRangeString, Middle + 1, Stop - Middle - 1 ) );
width := msb - lsb + 1;
end;
end;
// [31:28], lsb=28, width=4 : (1<<4)-1 = 0x0F, Mask=(0x0F<<28)=0xF0000000
fieldPos := lsb;
fieldMask := ( ( 1 shl width ) - 1 ) shl lsb;
end;
function GetClusterByName( Name: String; Cluster: TSVD_Cluster; var RetValue: TSVD_Cluster ): Boolean;
begin
end;
function GetRegisterByName( Name: String; _Register: TSVD_Register; var RetValue: TSVD_Register ): Boolean;
begin
end;
function GetFieldByName( Name: String; Filed: TSVD_Field; var RetValue: TSVD_Field ): Boolean;
begin
end;
function GetEnumeratedValuesByName( Name: String; EnumeratedValues: TSVD_EnumeratedValues;
var RetValue: TSVD_EnumeratedValues ): Boolean;
begin
end;
procedure IDC_AddEnum( StringList: TStringList; _Register: TSVD_Register );
var
I: Integer;
J: Integer;
K: Integer;
fieldPos: Cardinal;
fieldMask: Cardinal;
peripheralName: String;
registerName: String;
fieldName: String;
fieldDescription: String;
enumName: String;
enumValue: Cardinal;
enumDescription: String;
derivedFrom: String;
Name: String;
begin
end;
procedure IDC_DecodeDevice( SVD_Device: TSVD_Device; var StringList: TStringList );
var
LineNumber: Cardinal;
procedure IDC_DecodeDeviceExtLine( AString: String );
begin
StringList.Add( ' ExtLinA(EA, 0x' + IntToHex( LineNumber, 2 ) + ', "' + AString + '");' );
Inc( LineNumber );
end;
begin
LineNumber := 0;
StringList.Add( '#include <idc.idc>' );
StringList.Add( '' );
StringList.Add( 'static IDC_JumpStartAddress(void)' );
StringList.Add( '{' );
StringList.Add( ' Jump( MinEA() );' );
StringList.Add( '}' );
StringList.Add( '' );
StringList.Add( 'static IDC_DecodeDevice(void)' );
StringList.Add( '{' );
StringList.Add( ' auto EA = MinEA();' );
IDC_DecodeDeviceExtLine( '; Device Information' );
IDC_DecodeDeviceExtLine( '; ===========================================================================' );
IDC_DecodeDeviceExtLine( '' );
IDC_DecodeDeviceExtLine( '; name : ' + SVD_Device.Name );
IDC_DecodeDeviceExtLine( '; series : ' + SVD_Device.series );
IDC_DecodeDeviceExtLine( '; version : ' + SVD_Device.version );
IDC_DecodeDeviceExtLine( '; description : ' + SVD_Device.description );
IDC_DecodeDeviceExtLine( '; addressUnitBits : 0x' + IntToStr( SVD_Device.addressUnitBits ) );
IDC_DecodeDeviceExtLine( '' );
IDC_DecodeDeviceExtLine( '; CPU Information' );
IDC_DecodeDeviceExtLine( '; ===========================================================================' );
IDC_DecodeDeviceExtLine( '' );
IDC_DecodeDeviceExtLine( '; name : ' + SVD_Device.cpu.Name );
IDC_DecodeDeviceExtLine( '; revision : ' + SVD_Device.cpu.revision );
IDC_DecodeDeviceExtLine( '; endian : ' + SVD_Device.cpu.endian );
IDC_DecodeDeviceExtLine( '; itcmPresent : ' + SVD_Device.cpu.itcmPresent );
IDC_DecodeDeviceExtLine( '; dtcmPresent : ' + SVD_Device.cpu.dtcmPresent );
IDC_DecodeDeviceExtLine( '; icachePresent : ' + SVD_Device.cpu.icachePresent );
IDC_DecodeDeviceExtLine( '; dcachePresent : ' + SVD_Device.cpu.dcachePresent );
IDC_DecodeDeviceExtLine( '; mpuPresent : ' + SVD_Device.cpu.mpuPresent );
IDC_DecodeDeviceExtLine( '; fpuPresent : ' + SVD_Device.cpu.fpuPresent );
IDC_DecodeDeviceExtLine( '; fpuDP : ' + SVD_Device.cpu.fpuDP );
IDC_DecodeDeviceExtLine( '; vtorPresent : ' + SVD_Device.cpu.vtorPresent );
IDC_DecodeDeviceExtLine( '; vendorSystick : ' + SVD_Device.cpu.vendorSystickConfig );
IDC_DecodeDeviceExtLine( '; sauNumRegions : ' + IntToStr( SVD_Device.cpu.sauNumRegions ) );
IDC_DecodeDeviceExtLine( '; nvicPrioBits : ' + IntToStr( SVD_Device.cpu.nvicPrioBits ) );
IDC_DecodeDeviceExtLine( '; numInterrupts : ' + IntToStr( SVD_Device.cpu.deviceNumInterrupts ) );
IDC_DecodeDeviceExtLine( '' );
IDC_DecodeDeviceExtLine( '; Register Information' );
IDC_DecodeDeviceExtLine( '; ===========================================================================' );
IDC_DecodeDeviceExtLine( '' );
IDC_DecodeDeviceExtLine( '; access : ' + SVD_Device.registerProperties.access );
IDC_DecodeDeviceExtLine( '; resetValue : 0x' + IntToHex( SVD_Device.registerProperties.resetValue, 8 ) );
IDC_DecodeDeviceExtLine( '; resetMask : 0x' + IntToHex( SVD_Device.registerProperties.resetMask, 8 ) );
IDC_DecodeDeviceExtLine( '; protection : ' + SVD_Device.registerProperties.protection );
IDC_DecodeDeviceExtLine( '' );
IDC_DecodeDeviceExtLine( '; ===========================================================================' );
StringList.Add( '}' );
StringList.Add( '' );
MainStringList.Add( '' );
MainStringList.Add( ' IDC_JumpStartAddress();' );
MainStringList.Add( '' );
MainStringList.Add( ' IDC_DecodeDevice();' );
end;
{
success AddSegEx(long startea, long endea, long base, long use32, long align, long comb, long flags);
// returns: 0-failed, 1-ok
//
// Create a new segment
//
// startea - linear address of the start of the segment
// endea - linear address of the end of the segment this address will not belong to the segment
// base - base paragraph or selector of the segment.
// use32 - 0: 16bit segment, 1: 32bit segment, 2: 64bit segment
//
// align - segment alignment. see below for alignment values
//
// #define saAbs 0 // Absolute segment.
// #define saRelByte 1 // Relocatable, byte aligned.
// #define saRelWord 2 // Relocatable, word (2-byte, 16-bit) aligned.
// #define saRelPara 3 // Relocatable, paragraph (16-byte) aligned.
// #define saRelPage 4 // Relocatable, aligned on 256-byte boundary
// // (a "page" in the original Intel specification).
// #define saRelDble 5 // Relocatable, aligned on a double word (4-byte) boundary.
// // This value is used by the PharLap OMF for the same alignment.
// #define saRel4K 6 // This value is used by the PharLap OMF for page (4K) alignment.
// // It is not supported by LINK.
// #define saGroup 7 // Segment group
// #define saRel32Bytes 8 // 32 bytes
// #define saRel64Bytes 9 // 64 bytes
// #define saRelQword 10 // 8 bytes
//
// comb - segment combination. see below for combination values.
//
// #define scPriv 0 // Private. Do not combine with any other program segment.
// #define scPub 2 // Public. Combine by appending at an offset that meets the alignment requirement.
// #define scPub2 4 // As defined by Microsoft, same as C=2 (public).
// #define scPub3 7 // As defined by Microsoft, same as C=2 (public).
// #define scStack 5 // Stack. Combine as for C=2. This combine type forces byte alignment.
// #define scCommon 6 // Common. Combine by overlay using maximum size.
//
// flags - combination of ADDSEG_... bits
//
// #define ADDSEG_NOSREG 0x0001 // set all default segment register values to BADSELs (undefine all default segment registers)
// #define ADDSEG_OR_DIE 0x0002 // qexit() if can't add a segment
// #define ADDSEG_NOTRUNC 0x0004 // don't truncate the new segment at the beginning of the next segment if they overlap.
// // destroy/truncate old segments instead.
// #define ADDSEG_QUIET 0x0008 // silent mode, no "Adding segment..." in the messages window
// #define ADDSEG_FILLGAP 0x0010 // If there is a gap between the new segment and the previous one, and this gap is less
// // than 64K, then fill the gap by extending the previous segment and adding .align directive to it.
// // This way we avoid gaps between segments. Too many gaps lead to a virtual array failure.
// // It can not hold more than ~1000 gaps.
// #define ADDSEG_SPARSE 0x0020 // Use sparse storage method for the new segment
}
procedure IDC_DecodePeripheral( const Peripheral: TSVD_Peripheral; var StringList: TStringList );
begin
MainStringList.Add( '' );
MainStringList.Add( ' IDC_DecodeSegment();' );
StringList.Add( 'static IDC_DecodeSegment(void)' );
StringList.Add( '{' );
StringList.Add( '}' );
StringList.Add( '' );
end;
procedure IDC_Decode( SVD_Device: TSVD_Device; var StringList: TStringList );
var
I: Integer;
Peripheral: TSVD_Peripheral;
begin
MainStringList := TStringList.Create;
try
MainStringList.Add( '' );
MainStringList.Add( 'static main(void)' );
MainStringList.Add( '{' );
IDC_DecodeDevice( SVD_Device, StringList );
for I := 0 to SVD_Device.peripheralArray.Count - 1 do
IDC_DecodePeripheral( Peripheral, StringList );
MainStringList.Add( '' );
MainStringList.Add( '}' );
StringList.AddStrings( MainStringList );
finally
MainStringList.Free;
end;
end;
end.
|
unit SSL_Client;
{$I ..\..\Base\SBDemo.inc}
interface
uses
Classes, SysUtils, DB,
{$IFDEF VER16P}
UITypes,
{$ENDIF}
Windows, Messages, Graphics, Controls, Forms, Dialogs, TypInfo,
DBCtrls, ExtCtrls, Grids, DBGrids, StdCtrls, ToolWin, ComCtrls,
Buttons, Spin, DemoFrame, MemDS, DBAccess, Uni, UniProvider,
UniDacVcl, ScBridge, ScCryptoAPIStorage, CRSSLIOHandler, CRVio,
CRSsoStorage,
OraClassesUni, OraCallUni,
{$IFNDEF CLR}
OracleUniProvider,
SQLServerUniProvider,
InterBaseUniProvider,
MySQLUniProvider,
PostgreSQLUniProvider
{$ELSE}
System.ComponentModel,
Devart.UniDac.Oracle.OracleUniProvider,
Devart.UniDac.SQLServer.SQLServerUniProvider,
Devart.UniDac.InterBase.InterBaseUniProvider,
Devart.UniDac.MySQL.MySQLUniProvider,
Devart.UniDac.PostgreSQL.PostgreSQLUniProvider
{$ENDIF}
;
type
TSSLClientFrame = class(TDemoFrame)
Panel1: TPanel;
Panel4: TPanel;
Panel2: TPanel;
Panel6: TPanel;
Panel5: TPanel;
pnOracleOptions: TPanel;
pnAdvancedOptions: TPanel;
lbSSLConnection: TLabel;
lbCAcertificate: TLabel;
lbClientCertificate: TLabel;
lbClientPrivateKey: TLabel;
lbStorageKind : TLabel;
lbWallet: TLabel;
lbServerCertDN: TLabel;
edServerCertDN: TEdit;
lbDBConnection: TLabel;
lbProvider: TLabel;
lbDBServer: TLabel;
lbDBPort: TLabel;
lbSID: TLabel;
lbDBUserName: TLabel;
btConnectDB: TSpeedButton;
lbDBPassword: TLabel;
lbDBDatabase: TLabel;
lbConnectMode: TLabel;
btDisconnectDB: TSpeedButton;
DBGrid: TDBGrid;
UniConnection: TUniConnection;
UniTable: TUniTable;
DataSource: TDataSource;
edDBHost: TEdit;
edDBUserName: TEdit;
edDBPassword: TEdit;
seDBPort: TSpinEdit;
cbDBDatabase: TComboBox;
Panel7: TPanel;
lbTableName: TLabel;
cbTableName: TComboBox;
Panel9: TPanel;
btOpen: TSpeedButton;
btClose: TSpeedButton;
Panel8: TPanel;
CRSSLIOHandler: TCRSSLIOHandler;
ScCryptoAPIStorage: TScCryptoAPIStorage;
DBNavigator: TDBNavigator;
Panel3: TPanel;
edCACertName: TEdit;
edKeyName: TEdit;
cbTrustServerSertificate: TCheckBox;
cbRandomization: TCheckBox;
sbCACertName: TSpeedButton;
edCertName: TEdit;
sbCertName: TSpeedButton;
sbKeyName: TSpeedButton;
OpenDialog: TOpenDialog;
sbWallet: TSpeedButton;
cbProvider: TComboBox;
edWallet: TEdit;
rbWallet: TRadioButton;
rbCertificate: TRadioButton;
edDBServiceName: TEdit;
cbSID: TCheckBox;
cbConnectMode: TComboBox;
procedure btConnectDBClick(Sender: TObject);
procedure btDisconnectDBClick(Sender: TObject);
procedure UniConnectionAfterConnect(Sender: TObject);
procedure UniTableAfterClose(DataSet: TDataSet);
procedure UniTableAfterOpen(DataSet: TDataSet);
procedure btOpenClick(Sender: TObject);
procedure btCloseClick(Sender: TObject);
procedure cbTableNameDropDown(Sender: TObject);
procedure cbTableNameChange(Sender: TObject);
procedure cbDBDatabaseDropDown(Sender: TObject);
procedure cbDBDatabaseChange(Sender: TObject);
procedure UniConnectionBeforeConnect(Sender: TObject);
procedure edDBHostChange(Sender: TObject);
procedure sbCACertNameClick(Sender: TObject);
procedure sbKeyNameClick(Sender: TObject);
procedure sbCertNameClick(Sender: TObject);
procedure sbWalletClick(Sender: TObject);
procedure rbWalletClick(Sender: TObject);
procedure rbCertificateClick(Sender: TObject);
procedure cbSIDClick(Sender: TObject);
procedure cbProviderChange(Sender: TObject);
private
FileStorage: TCRSSOFileStorage;
procedure CheckRandomize;
procedure ShowCertControls(Mode: Boolean);
procedure ChangeDatabaseControl(ProviderName: String);
{$IFDEF MSWINDOWS}
procedure GetStoredParameters(ProviderName: String);
function LoadState: boolean;
function SaveState: boolean;
function KeyPath: string;
function GetDefaultPort(ProviderName: String): Integer;
{$ENDIF}
public
destructor Destroy; override;
procedure Initialize; override;
procedure Finalize; override;
end;
var
SSLClientFrame: TSSLClientFrame;
implementation
{$IFNDEF FPC}
{$IFDEF CLR}
{$R *.nfm}
{$ELSE}
{$R *.dfm}
{$ENDIF}
{$ENDIF}
uses
{$IFDEF MSWINDOWS}
Registry,
{$ENDIF}
ScConsts, ScSSHUtils, SSLDacDemoForm,
MyClassesUni, PgClassesUni;
const
TCPPrefix = 'tcps://';
CertFilter = 'All formats |*.pem;*.crt;*.cer|PEM format (*.pem;*.crt)|*.pem;*.crt|DER format (*.cer)|*.cer|All files (*.*)|*.*';
KeyFilter = 'All formats |*.key;*.ssl;*.pem;*.ietf;*.pub;*.ietfpub|OpenSSL format (*.ssl)|*.ssl|PKCS8 format (*.pem)|*.pem|IETF format (*.ietf)|*.ietf|Public key (*.pub)|*.pub|Public IETF key (*.ietfpub)|*.ietfpub|All files (*.*)|*.*';
WalletFilter = 'Wallet files(*.sso)|*.sso|All files (*.*)|*.*';
destructor TSSLClientFrame.Destroy;
begin
UniConnection.Close;
inherited;
end;
procedure TSSLClientFrame.Initialize;
begin
inherited;
{$IFDEF MSWINDOWS}
LoadState;
{$ENDIF}
FileStorage := TCRSSOFileStorage.Create(Self);
UniProviders.GetProviderNames(cbProvider.Items);
if cbProvider.Text = '' then
cbProvider.ItemIndex := 0;
cbProviderChange(cbProvider);
ChangeDatabaseControl(cbProvider.Text);
ShowCertControls(rbCertificate.Checked or (cbProvider.Text<>'Oracle'));
end;
procedure TSSLClientFrame.Finalize;
begin
{$IFDEF MSWINDOWS}
SaveState;
{$ENDIF}
inherited;
end;
procedure TSSLClientFrame.CheckRandomize;
begin
if not SSLDacForm.Randomized and not cbRandomization.Checked then begin
SSLDacForm.Randomize;
if not SSLDacForm.Randomized and not cbRandomization.Checked then
raise Exception.Create('Data for the random generator has not been generated');
end;
end;
procedure TSSLClientFrame.btConnectDBClick(Sender: TObject);
begin
UniConnection.Connect;
end;
procedure TSSLClientFrame.btDisconnectDBClick(Sender: TObject);
begin
UniConnection.Disconnect;
end;
procedure TSSLClientFrame.edDBHostChange(Sender: TObject);
begin
UniConnection.Disconnect;
end;
procedure TSSLClientFrame.cbProviderChange(Sender: TObject);
begin
UniConnection.Disconnect;
ChangeDatabaseControl(cbProvider.Text);
GetStoredParameters(cbProvider.Text);
seDBPort.Value := GetDefaultPort(cbProvider.Text);
ShowCertControls(rbCertificate.Checked or (cbProvider.Text<>'Oracle'));
end;
procedure TSSLClientFrame.UniConnectionAfterConnect(Sender: TObject);
begin
btConnectDB.Enabled := not UniConnection.Connected;
btDisconnectDB.Enabled := UniConnection.Connected;
btOpen.Enabled := UniConnection.Connected and (cbTableName.Text <> '');
cbTableName.Enabled := UniConnection.Connected;
end;
procedure TSSLClientFrame.UniTableAfterOpen(DataSet: TDataSet);
begin
btOpen.Enabled := False;
btClose.Enabled := True;
end;
procedure TSSLClientFrame.UniTableAfterClose(DataSet: TDataSet);
begin
btOpen.Enabled := not btConnectDB.Enabled and (cbTableName.Text <> '');
btClose.Enabled := False;
end;
procedure TSSLClientFrame.btOpenClick(Sender: TObject);
begin
UniTable.Open;
end;
procedure TSSLClientFrame.btCloseClick(Sender: TObject);
begin
UniTable.Close;
end;
procedure TSSLClientFrame.cbTableNameDropDown(Sender: TObject);
begin
if UniConnection.Connected then
UniConnection.GetTableNames(cbTableName.Items)
else
cbTableName.Items.Clear;
end;
procedure TSSLClientFrame.cbTableNameChange(Sender: TObject);
begin
UniTable.TableName := cbTableName.Text;
btOpen.Enabled := UniConnection.Connected and (cbTableName.Text <> '');
end;
{$IFDEF MSWINDOWS}
function TSSLClientFrame.SaveState: boolean;
var
Registry: TRegistry;
RegistryKey: String;
begin
Registry := TRegistry.Create(KEY_READ OR KEY_WRITE);
try
RegistryKey := KeyPath + '\' + TSSLClientFrame.ClassName;
with Registry do begin
OpenKey(RegistryKey, True);
WriteString('Provider', cbProvider.Text);
WriteString('CACertName', edCACertName.Text);
WriteString('ClientCertName', edCertName.Text);
WriteString('CertPrivateKeyName', edKeyName.Text);
WriteBool('Trust Server Sertificate', cbTrustServerSertificate.Checked);
WriteBool('Silent randomization', cbRandomization.Checked);
RegistryKey := RegistryKey + '\' + cbProvider.Text;
OpenKey(RegistryKey, True);
WriteString('DBHost', edDBHost.Text);
WriteInteger('DBPort', seDBPort.Value);
WriteString('DBUserName', edDBUserName.Text);
WriteString('DBDatabase', cbDBDatabase.Text);
if cbProvider.Text = 'Oracle' then begin
WriteString('Wallet', edWallet.Text);
WriteString('ServerCertDN', edServerCertDN.Text);
WriteString('DBServiceName', edDBServiceName.Text);
WriteBool('Use SID', cbSID.Checked);
WriteInteger('ConnectMode', cbConnectMode.ItemIndex);
end;
end;
finally
Registry.Free;
end;
Result := True;
end;
function TSSLClientFrame.LoadState: boolean;
var
Registry: TRegistry;
RegistryKey: String;
begin
Result := False;
RegistryKey := KeyPath + '\' + TSSLClientFrame.ClassName;
Registry := TRegistry.Create(KEY_READ OR KEY_WRITE);
try
with Registry do begin
if OpenKey(RegistryKey, False) then begin
if ValueExists('CACertName') then
edCACertName.Text := ReadString('CACertName');
if ValueExists('ClientCertName') then
edCertName.Text := ReadString('ClientCertName');
if ValueExists('CertPrivateKeyName') then
edKeyName.Text := ReadString('CertPrivateKeyName');
if ValueExists('Trust Server Sertificate') then
cbTrustServerSertificate.Checked := ReadBool('Trust Server Sertificate');
if ValueExists('Silent randomization') then
cbRandomization.Checked := ReadBool('Silent randomization');
if ValueExists('Provider') then
cbProvider.Text := ReadString('Provider');
Result := True;
end;
end;
finally
Registry.Free;
end;
end;
function TSSLClientFrame.KeyPath: string;
begin
Result := '\SOFTWARE\Devart\UniDAC\SecureBridge\Demos';
end;
{$ENDIF}
procedure TSSLClientFrame.cbDBDatabaseDropDown(Sender: TObject);
begin
UniConnection.GetDatabaseNames(cbDBDatabase.Items)
end;
procedure TSSLClientFrame.cbDBDatabaseChange(Sender: TObject);
begin
UniTable.Close;
UniConnection.Database := cbDBDatabase.Text;
cbTableName.Text := '';
end;
procedure TSSLClientFrame.UniConnectionBeforeConnect(Sender: TObject);
var
Cert: TScCertificate;
ServerInfo: TDirectServerInfo;
begin
CheckRandomize;
ScCryptoAPIStorage.Certificates.Clear;
UniConnection.ProviderName := cbProvider.Text;
if rbCertificate.Checked or (UniConnection.ProviderName <> 'Oracle') then begin
CRSSLIOHandler.CACertName := 'cacert';
Cert := TScCertificate.Create(ScCryptoAPIStorage.Certificates);
Cert.CertName := CRSSLIOHandler.CACertName;
Cert.ImportFrom(edCACertName.Text);
CRSSLIOHandler.CertName := 'clientcert';
Cert := TScCertificate.Create(ScCryptoAPIStorage.Certificates);
Cert.CertName := CRSSLIOHandler.CertName;
Cert.ImportFrom(edCertName.Text);
Cert.Key.ImportFrom(edKeyName.Text);
end
else begin
CRSSLIOHandler.CACertName := '';
CRSSLIOHandler.CertName := '';
end;
UniConnection.IOHandler := CRSSLIOHandler;
UniConnection.SpecificOptions.Values['PostgreSQL.SSLMode'] := 'smRequire';
UniConnection.SpecificOptions.Values['MySQL.Protocol'] := 'mpSSL';
UniConnection.Server := edDBHost.Text;
UniConnection.Port := seDBPort.Value;
UniConnection.Username := edDBUserName.Text;
UniConnection.Password := edDBPassword.Text;
if UniConnection.ProviderName <> 'Oracle' then
UniConnection.Database := cbDBDatabase.Text
else begin
if Pos(TCPPrefix, edDBHost.Text)=0 then
if MessageDlg(Format('The host name for the SSL connection must begin with "%s". Should I change the value of the "Server" field?', [TCPPrefix]), mtInformation, [mbYes, mbNo], 0) = mrYes then
edDBHost.Text := TCPPrefix + edDBHost.Text;
UniConnection.SpecificOptions.Values['Oracle.Direct'] := 'True';
FileStorage.Path := ExtractFilePath(edWallet.Text);
CRSSLIOHandler.Storage := FileStorage;
CRSSLIOHandler.SecurityOptions.TrustServerCertificate := cbTrustServerSertificate.Checked;
UniConnection.SpecificOptions.Values['Oracle.SSLServerCertDN'] := edServerCertDN.Text;
ServerInfo := TDirectServerInfo.Create;
try
ServerInfo.Host := edDBHost.Text;
ServerInfo.Port := seDBPort.Text;
if cbSID.Checked then
ServerInfo.SID := edDBServiceName.Text
else
ServerInfo.ServiceName := edDBServiceName.Text;
UniConnection.Server := ServerInfo.GetServerInfo;
finally
ServerInfo.Free;
end;
UniConnection.SpecificOptions.Values['Oracle.ConnectMode'] := GetEnumName(TypeInfo(TConnectMode), cbConnectMode.ItemIndex);
end;
if UniConnection.Username = '' then
raise Exception.Create('Username cannot be empty');
end;
procedure TSSLClientFrame.cbSIDClick(Sender: TObject);
begin
if cbSID.Checked then
lbSID.Caption := 'SID'
else
lbSID.Caption := 'Service Name';
end;
procedure TSSLClientFrame.sbCACertNameClick(Sender: TObject);
begin
OpenDialog.Filter := CertFilter;
OpenDialog.Title := 'Import certificate';
if OpenDialog.Execute then
edCACertName.Text := OpenDialog.FileName;
end;
procedure TSSLClientFrame.sbCertNameClick(Sender: TObject);
begin
OpenDialog.Filter := CertFilter;
OpenDialog.Title := 'Import certificate';
if OpenDialog.Execute then
edCertName.Text := OpenDialog.FileName;
end;
procedure TSSLClientFrame.sbKeyNameClick(Sender: TObject);
begin
OpenDialog.Filter := KeyFilter;
OpenDialog.Title := 'Import key';
if OpenDialog.Execute then
edKeyName.Text := OpenDialog.FileName;
end;
procedure TSSLClientFrame.ShowCertControls(Mode: Boolean);
begin
edCACertName.Enabled := Mode;
sbCACertName.Enabled := Mode;
edCertName.Enabled := Mode;
sbCertName.Enabled := Mode;
edKeyName.Enabled := Mode;
sbKeyName.Enabled := Mode;
edWallet.Enabled := not(Mode);
sbWallet.Enabled := not(Mode);
end;
procedure TSSLClientFrame.ChangeDatabaseControl(ProviderName: String);
var
ThisIsOracle: Boolean;
begin
ThisIsOracle := ProviderName = 'Oracle';
if ThisIsOracle then begin
lbDBUserName.Top := lbDBServer.Top + 78;
edDBUserName.Top := lbDBServer.Top + 74;
lbDBPassword.Top := lbDBServer.Top + 104;
edDBPassword.Top := lbDBServer.Top + 100;
lbDBDatabase.Top := lbDBServer.Top + 130;
cbDBDatabase.Top := lbDBServer.Top + 126;
end
else begin
lbDBUserName.Top := lbDBServer.Top + 52;
edDBUserName.Top := lbDBServer.Top + 48;
lbDBPassword.Top := lbDBServer.Top + 78;
edDBPassword.Top := lbDBServer.Top + 74;
lbDBDatabase.Top := lbDBServer.Top + 104;
cbDBDatabase.Top := lbDBServer.Top + 100;
end;
pnOracleOptions.Visible := ThisIsOracle;
pnAdvancedOptions.Top := pnOracleOptions.Top + Integer(pnOracleOptions.Visible) * pnOracleOptions.Height;
lbSID.Visible := ThisIsOracle;
cbSID.Visible := ThisIsOracle;
edDBServiceName.Visible := ThisIsOracle;
lbConnectMode.Visible := ThisIsOracle;
cbConnectMode.Visible := ThisIsOracle;
lbDBDatabase.Visible := Not(ThisIsOracle);
cbDBDatabase.Visible := Not(ThisIsOracle);
end;
procedure TSSLClientFrame.GetStoredParameters(ProviderName: String);
var
Registry: TRegistry;
begin
edDBHost.Text := '';
seDBPort.Value := 0;
edDBUserName.Text := '';
cbDBDatabase.Text := '';
Registry := TRegistry.Create(KEY_READ OR KEY_WRITE);
try
with Registry do begin
if OpenKey(KeyPath + '\' + TSSLClientFrame.ClassName + '\' + ProviderName, False) then begin
if ValueExists('DBHost') then
edDBHost.Text := ReadString('DBHost');
if ValueExists('DBPort') then
seDBPort.Value := ReadInteger('DBPort');
if seDBPort.Value = 0 then
seDBPort.Value := GetDefaultPort(ProviderName);
if ValueExists('DBUserName') then
edDBUserName.Text := ReadString('DBUserName');
if ValueExists('DBDatabase') then
cbDBDatabase.Text := ReadString('DBDatabase');
if cbProvider.Text = 'Oracle' then begin
if ValueExists('Wallet') then
edWallet.Text := ReadString('Wallet');
if ValueExists('ServerCertDN') then
edServerCertDN.Text := ReadString('ServerCertDN');
if ValueExists('DBServiceName') then
edDBServiceName.Text := ReadString('DBServiceName');
if ValueExists('Use SID') then
cbSID.Checked := ReadBool('Use SID');
if ValueExists('ConnectMode') then
cbConnectMode.ItemIndex := ReadInteger('ConnectMode');
end;
end;
end;
finally
Registry.Free;
end;
end;
function TSSLClientFrame.GetDefaultPort(ProviderName: String): Integer;
begin
Result := 3050;
if ProviderName = 'MySQL' then
Result := 3306;
if ProviderName = 'Oracle' then
Result := 1522;
if ProviderName = 'PostgreSQL' then
Result := 5432;
if ProviderName = 'SQL Server' then
Result := 1433;
end;
procedure TSSLClientFrame.rbWalletClick(Sender: TObject);
begin
ShowCertControls(False or (cbProvider.Text<>'Oracle'));
end;
procedure TSSLClientFrame.rbCertificateClick(Sender: TObject);
begin
ShowCertControls(True or (cbProvider.Text<>'Oracle'));
end;
procedure TSSLClientFrame.sbWalletClick(Sender: TObject);
begin
OpenDialog.Filter := WalletFilter;
OpenDialog.Title := 'Select wallet files';
if OpenDialog.Execute then
edWallet.Text := OpenDialog.FileName;
end;
end. |
unit TestAddBeginEnd;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestAddBeginEnd
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
TestFrameWork,
BaseTestProcess, SettingsTypes, SetTransform;
type
TTestAddBeginEnd = class(TBaseTestProcess)
private
feSaveBeginEndStyle: TTriOptionStyle;
protected
procedure SetUp; override;
procedure TearDown; override;
public
published
procedure TestAddToIfStatement;
procedure TestRemoveFromIfStatement;
procedure TestAddToIfElseStatement;
procedure TestRemoveFromIfElseStatement;
procedure TestAddToDoubleIfStatement;
procedure TestRemoveFromDoubleIfStatement;
procedure TestAddToWhileStatement;
procedure TestRemoveFromWhileStatement;
procedure TestAddToForStatement;
procedure TestRemoveFromForStatement;
procedure TestAddToWithStatement;
procedure TestRemoveFromWithStatement;
procedure TestAddToCaseStatement;
procedure TestRemoveFromCaseStatement;
procedure TestAddToifForStatement;
procedure TestAddToifForStatement2;
procedure TestAddToifForStatement3;
procedure TestRemoveFromIfForStatement;
procedure TestNestedIf1;
procedure TestNestedIf1_2;
procedure TestNestedIf1_3;
procedure TestNestedIf2;
procedure TestNestedIf3;
procedure TestNestedIf4;
procedure TestBug1174572;
procedure TestBug1262542;
procedure TestBugNew;
end;
implementation
uses
JcfStringUtils,
JcfSettings, AddBeginEnd;
procedure TTestAddBeginEnd.Setup;
begin
inherited;
feSaveBeginEndStyle := JcfFormatSettings.Transform.BeginEndStyle;
end;
procedure TTestAddBeginEnd.Teardown;
begin
inherited;
JcfFormatSettings.Transform.BeginEndStyle := feSaveBeginEndStyle;
end;
const
UNIT_HEADER = 'unit CaseTest;' + NativeLineBreak + NativeLineBreak +
'interface ' + NativeLineBreak + NativeLineBreak +
'implementation' + NativeLineBreak + NativeLineBreak +
'uses Dialogs;' + NativeLineBreak + NativeLineBreak +
'procedure foo(i: integer);' + NativeLineBreak +
'begin' + NativeLineBreak;
UNIT_FOOTER = NativeLineBreak + 'end;' + NativeLineBreak + NativeLineBreak +
'end.';
IF_STATEMENT_TEXT_NO_BEGIN =
UNIT_HEADER +
' if i > 10 then ' + NativeLineBreak +
' ShowMessage(''big'');' +
UNIT_FOOTER;
IF_STATEMENT_TEXT_WITH_BEGIN =
UNIT_HEADER +
' if i > 10 then ' + NativeLineBreak +
' begin ShowMessage(''big'') end;' +
UNIT_FOOTER;
IF_ELSE_STATEMENT_TEXT_NO_BEGIN =
UNIT_HEADER +
' if i > 10 then ' + NativeLineBreak +
' ShowMessage(''big'')' +
' else ' +
' ShowMessage(''small'');' +
UNIT_FOOTER;
IF_ELSE_STATEMENT_TEXT_WITH_BEGIN =
UNIT_HEADER +
' if i > 10 then ' + NativeLineBreak +
' begin ShowMessage(''big'') end' +
' else ' +
' begin ShowMessage(''small'') end;' +
UNIT_FOOTER;
DOUBLE_IF_STATEMENT_TEXT_NO_BEGIN =
UNIT_HEADER +
' if i > 10 then ' + NativeLineBreak +
' if i > 20 then ' + NativeLineBreak +
' ShowMessage(''big'');' +
UNIT_FOOTER;
DOUBLE_IF_STATEMENT_TEXT_WITH_BEGIN =
UNIT_HEADER +
' if i > 10 then ' + NativeLineBreak +
' begin if i > 20 then ' + NativeLineBreak +
' begin ShowMessage(''big'') end end;' +
UNIT_FOOTER;
WHILE_STATEMENT_TEXT_NO_BEGIN =
UNIT_HEADER +
' while i > 10 do ' + NativeLineBreak +
' ShowMessage(''big'');' +
UNIT_FOOTER;
WHILE_STATEMENT_TEXT_WITH_BEGIN =
UNIT_HEADER +
' while i > 10 do ' + NativeLineBreak +
' begin ShowMessage(''big'') end;' +
UNIT_FOOTER;
FOR_STATEMENT_TEXT_NO_BEGIN =
UNIT_HEADER +
' for i := 1 to 3 do ' + NativeLineBreak +
' ShowMessage(''big'');' +
UNIT_FOOTER;
FOR_STATEMENT_TEXT_WITH_BEGIN =
UNIT_HEADER +
' for i := 1 to 3 do ' + NativeLineBreak +
' begin ShowMessage(''big'') end;' +
UNIT_FOOTER;
WITH_STATEMENT_TEXT_NO_BEGIN =
UNIT_HEADER +
' with i do ' + NativeLineBreak +
' ShowMessage(''big'');' +
UNIT_FOOTER;
WITH_STATEMENT_TEXT_WITH_BEGIN =
UNIT_HEADER +
' with i do ' + NativeLineBreak +
' begin ShowMessage(''big'') end;' +
UNIT_FOOTER;
CASE_STATEMENT_TEXT_NO_BEGIN =
UNIT_HEADER +
' case i of ' + NativeLineBreak +
' 1: ShowMessage(''one'');' +
' 2: ShowMessage(''two'');' +
' else ShowMessage(''lots'');' +
' end ' +
UNIT_FOOTER;
CASE_STATEMENT_TEXT_WITH_BEGIN =
UNIT_HEADER +
' case i of ' + NativeLineBreak +
' 1: begin ShowMessage(''one''); end;' +
' 2: begin ShowMessage(''two''); end;' +
' else begin ShowMessage(''lots''); end;' +
' end ' +
UNIT_FOOTER;
IF_FOR_STATEMENT_TEXT_NO_BEGIN =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' for i := 1 to 3 do ' + NativeLineBreak +
' ShowMessage(''big'');' +
UNIT_FOOTER;
IF_FOR_STATEMENT_TEXT_WITH_BEGIN =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' begin for i := 1 to 3 do ' + NativeLineBreak +
' begin ShowMessage(''big'') end; end;' +
UNIT_FOOTER;
IF_FOR_ELSE_STATEMENT_TEXT_NO_BEGIN =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' for i := 1 to 3 do ' + NativeLineBreak +
' ShowMessage(''big'')' +
' else' +
' ShowMessage(''small'');' +
UNIT_FOOTER;
IF_FOR_ELSE_STATEMENT_TEXT_WITH_BEGIN =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' begin for i := 1 to 3 do ' + NativeLineBreak +
' begin ShowMessage(''big'') end end' +
' else' +
' begin ShowMessage(''small'') end;' +
UNIT_FOOTER;
IF_FOR_ELSE_IF_STATEMENT_TEXT_NO_BEGIN =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' for i := 1 to 3 do ' + NativeLineBreak +
' ShowMessage(''big'')' +
' else if i > 2 then' +
' ShowMessage(''small'');' +
UNIT_FOOTER;
IF_FOR_ELSE_IF_STATEMENT_TEXT_WITH_BEGIN =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' begin for i := 1 to 3 do ' + NativeLineBreak +
' begin ShowMessage(''big'') end end' +
' else if i > 2 then' +
' begin ShowMessage(''small'') end;' +
UNIT_FOOTER;
{ in this case removing the begin..end is wrong
because it causes the else to attach to the inner if
Thus changing the program meaning }
NESTED_IF_TEXT_WITH_BEGIN1 =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' begin' + NativeLineBreak +
' if i > 5 then' + NativeLineBreak +
' ShowMessage(''bigger'')' + NativeLineBreak +
' end' + NativeLineBreak +
' else' + NativeLineBreak +
' ShowMessage(''big'');' +
UNIT_FOOTER;
NESTED_IF_WITH_ALL_BEGINS1 =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' begin'+ NativeLineBreak +
' if i > 5 then' + NativeLineBreak +
' begin ShowMessage(''bigger'') end' + NativeLineBreak +
' end' + NativeLineBreak +
' else' + NativeLineBreak +
' begin ShowMessage(''big'') end;' +
UNIT_FOOTER;
NESTED_IF_TEXT_WITH_BEGIN2 =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' begin if i > 5 then' + NativeLineBreak +
' begin ShowMessage(''bigger'') end' + NativeLineBreak +
' else' + NativeLineBreak +
' begin ShowMessage(''big'') end end;' +
UNIT_FOOTER;
NESTED_IF_TEXT_NO_BEGIN2 =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' if i > 5 then' + NativeLineBreak +
' ShowMessage(''bigger'')' + NativeLineBreak +
' else' + NativeLineBreak +
' ShowMessage(''big'');' +
UNIT_FOOTER;
procedure TTestAddBeginEnd.TestRemoveFromIfStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, IF_STATEMENT_TEXT_WITH_BEGIN,
IF_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestAddToIfStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eAlways;
TestProcessResult(TAddBeginEnd, IF_STATEMENT_TEXT_NO_BEGIN,
IF_STATEMENT_TEXT_WITH_BEGIN);
end;
procedure TTestAddBeginEnd.TestAddToIfElseStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eAlways;
TestProcessResult(TAddBeginEnd, IF_ELSE_STATEMENT_TEXT_NO_BEGIN,
IF_ELSE_STATEMENT_TEXT_WITH_BEGIN);
end;
procedure TTestAddBeginEnd.TestRemoveFromIfElseStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, IF_ELSE_STATEMENT_TEXT_WITH_BEGIN,
IF_ELSE_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestAddToDoubleIfStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, DOUBLE_IF_STATEMENT_TEXT_WITH_BEGIN,
DOUBLE_IF_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestRemoveFromDoubleIfStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, DOUBLE_IF_STATEMENT_TEXT_WITH_BEGIN,
DOUBLE_IF_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestAddToWhileStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, WHILE_STATEMENT_TEXT_WITH_BEGIN,
WHILE_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestRemoveFromWhileStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, WHILE_STATEMENT_TEXT_WITH_BEGIN,
WHILE_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestAddToForStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, FOR_STATEMENT_TEXT_WITH_BEGIN,
FOR_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestRemoveFromForStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, FOR_STATEMENT_TEXT_WITH_BEGIN,
FOR_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestAddToWithStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, WITH_STATEMENT_TEXT_WITH_BEGIN,
WITH_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestRemoveFromWithStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, WITH_STATEMENT_TEXT_WITH_BEGIN,
WITH_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestAddToCaseStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, WITH_STATEMENT_TEXT_WITH_BEGIN,
WITH_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestRemoveFromCaseStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, CASE_STATEMENT_TEXT_WITH_BEGIN,
CASE_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestAddToIfForStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, IF_FOR_STATEMENT_TEXT_WITH_BEGIN,
IF_FOR_STATEMENT_TEXT_NO_BEGIN);
end;
procedure TTestAddBeginEnd.TestAddToifForStatement2;
begin
JcfFormatSettings.Transform.BeginEndStyle := eAlways;
TestProcessResult(TAddBeginEnd, IF_FOR_ELSE_STATEMENT_TEXT_NO_BEGIN,
IF_FOR_ELSE_STATEMENT_TEXT_WITH_BEGIN);
end;
// note that the "else..if" doesn't become "else begin if"
procedure TTestAddBeginEnd.TestAddToifForStatement3;
begin
JcfFormatSettings.Transform.BeginEndStyle := eAlways;
TestProcessResult(TAddBeginEnd, IF_FOR_ELSE_IF_STATEMENT_TEXT_NO_BEGIN,
IF_FOR_ELSE_IF_STATEMENT_TEXT_WITH_BEGIN);
end;
procedure TTestAddBeginEnd.TestRemoveFromIfForStatement;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, IF_FOR_STATEMENT_TEXT_WITH_BEGIN,
IF_FOR_STATEMENT_TEXT_NO_BEGIN);
end;
{ it's not alays safe to add or remove begin..end from nested if statements
e.g.
if a > 1 then
begin
if a > 2 then
Foo
end
else
Bar;
is not the same as
if a > 1 then
if a > 2 then
Foo
else
Bar;
}
procedure TTestAddBeginEnd.TestNestedIf1;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, NESTED_IF_TEXT_WITH_BEGIN1,
NESTED_IF_TEXT_WITH_BEGIN1);
end;
procedure TTestAddBeginEnd.TestNestedIf1_2;
begin
JcfFormatSettings.Transform.BeginEndStyle := eAlways;
TestProcessResult(TAddBeginEnd, NESTED_IF_TEXT_WITH_BEGIN1,
NESTED_IF_WITH_ALL_BEGINS1);
end;
procedure TTestAddBeginEnd.TestNestedIf1_3;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, NESTED_IF_WITH_ALL_BEGINS1,
NESTED_IF_TEXT_WITH_BEGIN1);
end;
procedure TTestAddBeginEnd.TestNestedIf2;
begin
JcfFormatSettings.Transform.BeginEndStyle := eAlways;
TestProcessResult(TAddBeginEnd, NESTED_IF_TEXT_NO_BEGIN2,
NESTED_IF_TEXT_WITH_BEGIN2);
end;
procedure TTestAddBeginEnd.TestNestedIf3;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, NESTED_IF_TEXT_WITH_BEGIN2,
NESTED_IF_TEXT_NO_BEGIN2);
end;
procedure TTestAddBeginEnd.TestNestedIf4;
begin
JcfFormatSettings.Transform.BeginEndStyle := eAlways;
TestProcessResult(TAddBeginEnd, NESTED_IF_TEXT_NO_BEGIN2, NESTED_IF_TEXT_WITH_BEGIN2);
end;
const
TEST_1174572_IN =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' begin' + NativeLineBreak +
' if i > 5 then' + NativeLineBreak +
' ShowMessage(''foo'')' + NativeLineBreak +
' else if Condition_C then' + NativeLineBreak +
' ShowMessage(''fish'')' + NativeLineBreak +
' end' + NativeLineBreak +
' else' + NativeLineBreak +
' ShowMessage(''spon'');' +
UNIT_FOOTER;
procedure TTestAddBeginEnd.TestBug1174572;
begin
{ sourceforge bug [1174572 ]
Remove begin and end from around single statement bug
Removing the begin-end changes the meaning and should not be done }
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, TEST_1174572_IN, TEST_1174572_IN);
end;
const
TEST_1262542_IN =
UNIT_HEADER +
' if i > 3 then' + NativeLineBreak +
' if i > 5 then' + NativeLineBreak +
' ShowMessage(''foo'')' + NativeLineBreak +
' else' + NativeLineBreak +
' begin' + NativeLineBreak +
' if Condition_C then' + NativeLineBreak +
' ShowMessage(''fish'')' + NativeLineBreak +
' end' + NativeLineBreak +
' else' + NativeLineBreak +
' ShowMessage(''spon'');' +
UNIT_FOOTER;
procedure TTestAddBeginEnd.TestBug1262542;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, TEST_1262542_IN, TEST_1262542_IN);
end;
const
TEST_NEW_IN =
UNIT_HEADER +
' if B then' +
' begin' +
' for i := 0 to 10 do' +
' if C then' +
' if D then' +
' dddd' +
' else' +
' if E then' +
' eeee' +
' end' +
' else' +
' for i := 0 to 10 do' +
' if F then' +
' ffff;' +
UNIT_FOOTER;
procedure TTestAddBeginEnd.TestBugNew;
begin
JcfFormatSettings.Transform.BeginEndStyle := eNever;
TestProcessResult(TAddBeginEnd, TEST_NEW_IN, TEST_NEW_IN);
end;
initialization
TestFramework.RegisterTest('Processes', TTestAddBeginEnd.Suite);
end.
|
program minmax;
var
x,y,z,min,max : integer;
begin
WriteLn('Введите x,y и z соответсвенно нажимая "Enter" после каждого: ');
ReadLn(x,y,z);
WriteLn('Вы ввели x:', x ,' ', 'y:', y ,' ', 'z:', z);
if(x>y) and (x>z) then begin max:=x;
if y>z then begin min:=z; end else min:=y; end;
if(y>z) and (y>x) then begin max:=y;
if z>x then begin min:=x; end else min:=z; end;
if(z>x) and (z>y) then begin max:=z;
if x>y then begin min:=y; end else min:=x; end;
{ if(x>y) then begin
if(z>x) then begin
max:=z;
min:=y; end
else if x>z then begin max:=x; min:=y; end end
else
if x>z then begin
if y>z then begin max:=y; min:=z; end
else
max:=x;
min:=y;
end; }
WriteLn('Max= ',max,' ', 'и Min:', min);
WriteLn((sqr(max))-exp(2*ln(x))*min/(sin(2)+max/min));
ReadLn()
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids, DBGrids, ComCtrls, DBCtrls, ExtCtrls;
type
TForm1 = class(TForm)
DBGrid1: TDBGrid;
GroupBox1: TGroupBox;
DBLookupComboBox1: TDBLookupComboBox;
Label1: TLabel;
DBLookupComboBox2: TDBLookupComboBox;
Label2: TLabel;
Button3: TButton;
Panel1: TPanel;
GroupBox2: TGroupBox;
Label3: TLabel;
Label4: TLabel;
DateTimePicker1: TDateTimePicker;
Button1: TButton;
ComboBox1: TComboBox;
Button4: TButton;
Button2: TButton;
Label5: TLabel;
DBGrid2: TDBGrid;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Panel2: TPanel;
Edit1: TEdit;
Button5: TButton;
Label9: TLabel;
Label10: TLabel;
CheckBox1: TCheckBox;
Edit2: TEdit;
Label11: TLabel;
procedure Button1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure DBLookupComboBox1Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure DBLookupComboBox2Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure DBGrid2CellClick(Column: TColumn);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
col_name, fio_uch, mark, kod_predm: String;
implementation
uses Unit2, DB, Unit3;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var i: integer;
Arr_user: Array of string;
str_add, data_str: string;
begin
data_str:=ComboBox1.Text+'-'+'ур'+'_'+FormatDateTime('dd.mm.yy',DateTimePicker1.Date);
// ShowMessage(data_str);
SetLength(Arr_user,DataModule2.ADOQWork.RecordCount);
i := 0;
DataModule2.ADOQWork.Close;
DataModule2.ADOQWork.SQL.Text:='SELECT Пользователи.Код_пользователя, Пользователи.ФИО, Группа.Название_группы '
+' FROM Группа INNER JOIN Пользователи ON Группа.[Код_группы] = Пользователи.[Код_группы] '
+' WHERE (((Пользователи.Код_группы)='+IntToStr(DBLookupComboBox1.KeyValue)+')) ORDER BY Пользователи.ФИО';
DataModule2.ADOQWork.Open;
DataModule2.ADOQWork.First;
//ListBox1.Clear;
while not DataModule2.ADOQWork.eof
do begin
Arr_user[i]:= DataModule2.DataSWork.DataSet.Fields[1].AsString;
// ListBox1.Items.Insert(i, Arr_user[i]);
DataModule2.ADOQWorkAdd.Close;
DataModule2.ADOQWorkAdd.SQL.Text:= ' INSERT INTO Журнал_дата ( [ФИО_ученика], [Дата], [Оценка], [Код_Предмета] ) '
+' VALUES ("'+Arr_user[i]+'", "'+data_str+'", "",'+IntToStr(DBLookupComboBox2.KeyValue)+' )';
DataModule2.ADOQWorkAdd.ExecSQL;
DataModule2.ADOQWork.next;
Inc(i);
end;
DataModule2.ADOQWorkAdd.Close;
DataModule2.ADOQWorkAdd.SQL.Text:= ' INSERT INTO Журнал_темы ( [Код_предмета], [Дата], [Тема_занятия] ) '
+' VALUES ('+IntToStr(DBLookupComboBox2.KeyValue)+', :dt, "" )';
DataModule2.ADOQWorkAdd.Parameters.ParamByName('dt').Value:=FormatDateTime('dd.mm.yyyy',DateTimePicker1.Date);
DataModule2.ADOQWorkAdd.ExecSQL;
Button3Click(Sender);
end;
procedure TForm1.FormShow(Sender: TObject);
begin
//DBLookupComboBox1.KeyValue := DBLookupComboBox1.ListSource.DataSet.FieldByName(DBLookupComboBox1.KeyField).Value;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
DataModule2.ADOQWork.Close;
DataModule2.ADOQWork.SQL.Text:='Delete * from Журнал_дата';
DataModule2.ADOQWork.ExecSQL;
DataModule2.ADOQWork.Close;
DataModule2.ADOQWork.SQL.Text:='Delete * from Журнал_темы';
DataModule2.ADOQWork.ExecSQL;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
i: Integer;
begin
DataModule2.ADOQEljor.Close;
DataModule2.ADOQEljor.SQL.Text:='TRANSFORM First(Журнал_дата.[Оценка]) AS [First-Оценка] '
+' SELECT Журнал_дата.[ФИО_ученика]'
+' FROM Журнал_дата '
+' WHERE (((Журнал_дата.Код_Предмета)='+IntToStr(DBLookupComboBox2.KeyValue)+')) '
+' GROUP BY Журнал_дата.[ФИО_ученика], Журнал_дата.Код_Предмета '
+' PIVOT Журнал_дата.[Дата] ';
DataModule2.ADOQEljor.Open;
for i:=1 to DBGrid1.Columns.count-1 do
DBGrid1.Columns[i].Width:=80;
DBGrid1.Enabled:=True;
Panel1.Enabled:=True;
DBGrid2.Enabled:=True;
Panel2.Enabled:=True;
Label7.Caption:= 'Предмет: '+DataModule2.DataSubject.DataSet.Fields[1].AsString;
Label8.Caption:= 'Преподаватель: '+DataModule2.DataSubject.DataSet.Fields[4].AsString;
DataModule2.ADOQTema.Close;
DataModule2.ADOQTema.SQL.Text:= 'SELECT Журнал_темы.[Дата], Журнал_темы.[Тема_занятия], Журнал_темы.[Код_записи] '
+' FROM Журнал_темы WHERE (((Журнал_темы.[Код_предмета])='+IntToStr(DBLookupComboBox2.KeyValue)+'))';
DataModule2.ADOQTema.Open;
end;
procedure TForm1.DBLookupComboBox1Click(Sender: TObject);
begin
DataModule2.ADOQSubject.Close;
DataModule2.ADOQSubject.SQL.Text:='SELECT Предметы.Код_передмета, Предметы.Название, Предметы.Код_пользователя, Предметы.Код_группы, Пользователи.ФИО '
+' FROM Пользователи INNER JOIN Предметы ON Пользователи.[Код_пользователя] = Предметы.[Код_пользователя] '
+' WHERE (((Предметы.Код_группы)='+IntToStr(DBLookupComboBox1.KeyValue)+'))';
DataModule2.ADOQSubject.Open;
DBLookupComboBox2.ListSource:=DataModule2.DataSubject;
DBLookupComboBox2.KeyField:= 'Код_передмета';
DBLookupComboBox2.ListField:= 'Название';
DBGrid1.Enabled:=False;
Panel1.Enabled:=False;
DBGrid2.Enabled:=False;
Panel2.Enabled:=False;
Button3.Enabled:=False;
DBLookupComboBox2.Enabled:=True;
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
mark:=DBGrid1.Fields[DBgrid1.SelectedIndex].AsString;
col_name:= DBGrid1.Columns[DBgrid1.SelectedIndex].Title.Caption;
fio_uch:=DBGrid1.Fields[0].AsString;
kod_predm:=IntToStr(DBLookupComboBox2.KeyValue);
Form3.Edit1.Text:= mark;
Form3.Show;
end;
procedure TForm1.DBLookupComboBox2Click(Sender: TObject);
begin
Button3.Enabled:=True;
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
if (DBGrid2.Fields[2].AsString<>'') then
begin
DataModule2.ADOQWork.Close;
DataModule2.ADOQWork.SQL.Text:='UPDATE Журнал_темы SET Журнал_темы.[Тема_занятия] = "'+Edit1.Text+'" '
+' WHERE (((Журнал_темы.[Код_записи])='+DBGrid2.Fields[2].AsString+'))';
DataModule2.ADOQWork.ExecSQL;
Button3Click(Sender);
Edit1.Clear;
end;
end;
procedure TForm1.DBGrid2CellClick(Column: TColumn);
begin
Edit1.Text:=DBGrid2.Fields[1].AsString;
end;
end.
|
unit uformsettingspaths;
{$mode objfpc}{$H+}
interface
uses
inifiles, Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs,
StdCtrls, Buttons, ExtCtrls, ComCtrls, LazIDEIntf;
type
{ TFormSettingsPaths }
TFormSettingsPaths = class(TForm)
BitBtnOK: TBitBtn;
BevelSimonsayzTemplateLazBuildAndButtons: TBevel;
BevelSDKNDKAndSimonsayzTemplateLazBuild: TBevel;
BevelJDKAntAndSDKNDK: TBevel;
BitBtnCancel: TBitBtn;
EditPathToAndroidNDK: TEdit;
EditPathToSimonsayzTemplate: TEdit;
EditPathToJavaJDK: TEdit;
EditPathToAndroidSDK: TEdit;
EditPathToAntBinary: TEdit;
LabelPathToAndroidNDK: TLabel;
LabelPathToSimonsayzTemplate: TLabel;
LabelPathToJavaJDK: TLabel;
LabelPathToAndroidSDK: TLabel;
LabelPathToAntBinary: TLabel;
RadioGroupPrebuildOSys: TRadioGroup;
RGNDKVersion: TRadioGroup;
SelDirDlgPathToAndroidNDK: TSelectDirectoryDialog;
SelDirDlgPathToSimonsayzTemplate: TSelectDirectoryDialog;
SelDirDlgPathToJavaJDK: TSelectDirectoryDialog;
SelDirDlgPathToAndroidSDK: TSelectDirectoryDialog;
SelDirDlgPathToAntBinary: TSelectDirectoryDialog;
SpBPathToAndroidNDK: TSpeedButton;
SpBPathToSimonsayzTemplate: TSpeedButton;
SpBPathToJavaJDK: TSpeedButton;
SpBPathToAndroidSDK: TSpeedButton;
SpBPathToAntBinary: TSpeedButton;
procedure BitBtnOKClick(Sender: TObject);
procedure BitBtnCancelClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormShow(Sender: TObject);
procedure SpBPathToAndroidNDKClick(Sender: TObject);
procedure SpBPathToSimonsayzTemplateClick(Sender: TObject);
procedure SpBPathToJavaJDKClick(Sender: TObject);
procedure SpBPathToAndroidSDKClick(Sender: TObject);
procedure SpBPathToAntBinaryClick(Sender: TObject);
function GetRadioGroupPrebuildOSysIndex(prebuildSys: string): integer;
private
{ private declarations }
FPathToJavaTemplates: string;
FPathToJavaJDK: string;
FPathToAndroidSDK: string;
FPathToAndroidNDK: string;
FPathToAntBin: string;
FPrebuildOSYS: string;
public
{ public declarations }
FOk: boolean;
procedure LoadSettings(const fileName: string);
procedure SaveSettings(const fileName: string);
end;
var
FormSettingsPaths: TFormSettingsPaths;
implementation
{$R *.lfm}
{ TFormSettingsPaths }
procedure TFormSettingsPaths.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
if FOk then
Self.SaveSettings(IncludeTrailingPathDelimiter(LazarusIDE.GetPrimaryConfigPath) + 'JNIAndroidProject.ini' );
end;
procedure TFormSettingsPaths.FormShow(Sender: TObject);
begin
FOk:= False;
Self.LoadSettings(IncludeTrailingPathDelimiter(LazarusIDE.GetPrimaryConfigPath) + 'JNIAndroidProject.ini');
end;
procedure TFormSettingsPaths.FormActivate(Sender: TObject);
begin
EditPathToJavaJDK.SetFocus;
end;
procedure TFormSettingsPaths.BitBtnCancelClick(Sender: TObject);
begin
FOk:= False;
Close;
end;
procedure TFormSettingsPaths.BitBtnOKClick(Sender: TObject);
begin
FOk:= True;
Close;
end;
procedure TFormSettingsPaths.SpBPathToAndroidNDKClick(Sender: TObject);
begin
if SelDirDlgPathToAndroidNDK.Execute then
begin
EditPathToAndroidNDK.Text := SelDirDlgPathToAndroidNDK.FileName;
FPathToAndroidNDK:= SelDirDlgPathToAndroidNDK.FileName;
end;
end;
procedure TFormSettingsPaths.SpBPathToSimonsayzTemplateClick(Sender: TObject);
begin
if SelDirDlgPathToSimonsayzTemplate.Execute then
begin
EditPathToSimonsayzTemplate.Text := SelDirDlgPathToSimonsayzTemplate.FileName;
FPathToJavaTemplates:= SelDirDlgPathToSimonsayzTemplate.FileName;
end;
end;
procedure TFormSettingsPaths.SpBPathToJavaJDKClick(Sender: TObject);
begin
if SelDirDlgPathToJavaJDK.Execute then
begin
EditPathToJavaJDK.Text := SelDirDlgPathToJavaJDK.FileName;
FPathToJavaJDK:= SelDirDlgPathToJavaJDK.FileName;
end;
end;
procedure TFormSettingsPaths.SpBPathToAndroidSDKClick(Sender: TObject);
begin
if SelDirDlgPathToAndroidSDK.Execute then
begin
EditPathToAndroidSDK.Text := SelDirDlgPathToAndroidSDK.FileName;
FPathToAndroidSDK:= SelDirDlgPathToAndroidSDK.FileName;
end;
end;
procedure TFormSettingsPaths.SpBPathToAntBinaryClick(Sender: TObject);
begin
if SelDirDlgPathToAntBinary.Execute then
begin
EditPathToAntBinary.Text := SelDirDlgPathToAntBinary.FileName;
FPathToAntBin:= SelDirDlgPathToAntBinary.FileName;
end;
end;
function TFormSettingsPaths.GetRadioGroupPrebuildOSysIndex(prebuildSys: string): integer;
begin
if Pos('windows', prebuildSys) > 0 then Result:= 0
else if Pos('_64', prebuildSys) > 0 then Result:= 3
else if Pos('linux-x86', prebuildSys) > 0 then Result:= 1
else if Pos('osx', prebuildSys) > 0 then Result:= 2;
end;
procedure TFormSettingsPaths.LoadSettings(const fileName: string);
var
indexNdk: integer;
begin
if FileExists(fileName) then
begin
with TIniFile.Create(fileName) do
try
EditPathToAndroidNDK.Text := ReadString('NewProject','PathToAndroidNDK', '');
EditPathToSimonsayzTemplate.Text := ReadString('NewProject','PathToJavaTemplates', '');
EditPathToJavaJDK.Text := ReadString('NewProject','PathToJavaJDK', '');
EditPathToAndroidSDK.Text := ReadString('NewProject','PathToAndroidSDK', '');
EditPathToAntBinary.Text := ReadString('NewProject','PathToAntBin', '');
if ReadString('NewProject','NDK', '') <> '' then
indexNdk:= StrToInt(ReadString('NewProject','NDK', ''))
else
indexNdk:= 3; //ndk 10e
RGNDKVersion.ItemIndex:= indexNdk;
FPrebuildOSYS:= ReadString('NewProject','PrebuildOSYS', '');
if FPrebuildOSYS <> '' then
RadioGroupPrebuildOSys.ItemIndex:= GetRadioGroupPrebuildOSysIndex(FPrebuildOSYS)
else RadioGroupPrebuildOSys.ItemIndex:= 0;
finally
Free;
end;
end;
end;
procedure TFormSettingsPaths.SaveSettings(const fileName: string);
begin
with TInifile.Create(fileName) do
try
WriteString('NewProject', 'PathToNdkPlataforms', EditPathToAndroidNDK.Text);
WriteString('NewProject', 'PathToJavaTemplates', EditPathToSimonsayzTemplate.Text);
WriteString('NewProject', 'PathToJavaJDK', EditPathToJavaJDK.Text);
WriteString('NewProject', 'PathToAndroidNDK', EditPathToAndroidNDK.Text);
WriteString('NewProject', 'PathToAndroidSDK', EditPathToAndroidSDK.Text);
WriteString('NewProject', 'PathToAntBin', EditPathToAntBinary.Text);
WriteString('NewProject', 'NDK', IntToStr(RGNDKVersion.ItemIndex)); //RGNDKVersion
case RadioGroupPrebuildOSys.ItemIndex of
0: FPrebuildOSYS:= 'windows';
1: FPrebuildOSYS:= 'linux-x86';
2: FPrebuildOSYS:= 'osx'; //TODO: fix here!
3: FPrebuildOSYS:= 'linux-x86_64';
end;
WriteString('NewProject', 'PrebuildOSYS', FPrebuildOSYS);
finally
Free;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMSHosting.EdgeHTTPServer;
interface
uses System.Classes, System.SysUtils,
System.JSON, IdCustomHTTPServer,
IdBaseComponent, IdComponent, IdCustomTCPServer,
IdHTTPServer, IdContext, EMSHosting.EdgeService;
type
TEMSEdgeHTTPServer = class
public type
TGetPasswordEvent = procedure(var APassword: string) of object;
private
FIdHTTPServer: TIdHTTPServer;
FPort: Integer;
FModule: TEMSEdgeListener.TModule;
FThreadPool: Boolean;
FThreadPoolSize: Integer;
FListenQueue: Integer;
FKeyFile: string;
FRootCertFile: string;
FCertFile: string;
FOnGetSSLPassword: TGetPasswordEvent;
FHTTPS: Boolean;
function GetPort: Cardinal;
procedure SetPort(const Value: Cardinal);
procedure DoCommand(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
procedure CommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
procedure CommandOther(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
procedure CommandError(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo;
AException: Exception);
function GetActive: Boolean;
procedure SetActive(const Value: Boolean);
procedure DoOnGetSSLPassword(var APassword: String);
public
constructor Create;
destructor Destroy; override;
property Active: Boolean read GetActive write SetActive;
property Port: Cardinal read GetPort write SetPort;
property Module: TEMSEdgeListener.TModule write FModule;
property ThreadPool: Boolean read FThreadPool write FThreadPool;
property ThreadPoolSize: Integer read FThreadPoolSize write FThreadPoolSize;
property ListenQueue: Integer read FListenQueue write FListenQueue;
property CertFile: string read FCertFile write FCertFile;
property RootCertFile: string read FRootCertFile write FRootCertFile;
property KeyFile: string read FKeyFile write FKeyFile;
property OnGetSSLPassword: TGetPasswordEvent read FOnGetSSLPassword write FOnGetSSLPassword;
property HTTPS: Boolean read FHTTPS write FHTTPS;
end;
implementation
uses EMS.ResourceAPI, EMSHosting.Helpers, EMSHosting.RequestTypes, EMSHosting.EdgeRequestHandler,
EMSHosting.EdgePayload,
IdSSLOpenSSL, IdSchedulerOfThreadPool, EMSHosting.RequestHandler;
type
TEdgeReaderHostRequest = class(TEMSHostRequest)
private
FQueryFields: TStrings;
FReader: IEdgeRequestReader;
FEdgeRequest: IEdgeRequest;
FContentType: string;
FContentLength: Integer;
private
procedure Load;
protected
function GetContentType: string; override;
function GetMethodType: TEMSHostRequest.TMethodType; override;
function GetPathInfo: string; override;
function GetQueryFields: TStringKeyValues; override;
function GetRawContent: TBytes; override;
function GetContentLength: Integer; override;
function GetHeader(const AName: string): string; override;
function GetBasePath: string; override;
function GetServerHost: string; override;
public
constructor Create(const AReader: IEdgeRequestReader);
destructor Destroy; override;
end;
TEdgeWriterHostResponse = class(TEMSHostResponse)
private
FRequest: IEMSHostRequest;
FContentType: string;
FContentStream: TStream;
FStatusCode: Integer;
protected
function GetContentStream: TStream; override;
function GetContentType: string; override;
function GetStatusCode: Integer; override;
procedure SetContentStream(const Value: TStream); override;
procedure SetStatusCode(const Value: Integer); override;
function GetRequest: IEMSHostRequest; override;
procedure SetContentType(const Value: string); override;
public
constructor Create(const ARequest: IEMSHostRequest);
destructor Destroy; override;
procedure Write(const AWriter: IEdgeResponseWriter);
end;
{ TEdgeReaderHostRequest }
constructor TEdgeReaderHostRequest.Create(const AReader: IEdgeRequestReader);
begin
FQueryFields := TStringList.Create;
FReader := AReader;
end;
destructor TEdgeReaderHostRequest.Destroy;
begin
FQueryFields.Free;
inherited;
end;
procedure TEdgeReaderHostRequest.Load;
begin
if FEdgeRequest = nil then
begin
FEdgeRequest := FReader.ReadRequest;
FReader.ReadContentType(FContentType, FContentLength);
end;
end;
function TEdgeReaderHostRequest.GetBasePath: string;
begin
Result := FEdgeRequest.BasePath;
end;
function TEdgeReaderHostRequest.GetServerHost: string;
begin
Result := FEdgeRequest.ServerHost;
end;
function TEdgeReaderHostRequest.GetContentLength: Integer;
begin
Load;
Result := FContentLength;
end;
function TEdgeReaderHostRequest.GetContentType: string;
begin
Load;
Result := FContentType;
end;
// Get header
function TEdgeReaderHostRequest.GetHeader(const AName: string): string;
begin
Load;
if SameText(AName, TEMSHostRequestProps.THeaderNames.SessionToken) then
Result := FEdgeRequest.SessionToken;
if SameText(AName, TEMSHostRequestProps.THeaderNames.TenantId) then
Result := FEdgeRequest.TenantId;
end;
function TEdgeReaderHostRequest.GetMethodType: TEMSHostRequest.TMethodType;
begin
Load;
if SameText(FEdgeRequest.Method, 'get') then
Result := TEMSHostRequest.TMethodType.Get
else if SameText(FEdgeRequest.Method, 'put') then
Result := TEMSHostRequest.TMethodType.Put
else if SameText(FEdgeRequest.Method, 'post') then
Result := TEMSHostRequest.TMethodType.Post
else if SameText(FEdgeRequest.Method, 'delete') then
Result := TEMSHostRequest.TMethodType.Delete
else if SameText(FEdgeRequest.Method, 'patch') then
Result := TEMSHostRequest.TMethodType.Patch
else if SameText(FEdgeRequest.Method, 'head') then
Result := TEMSHostRequest.TMethodType.Head
else
raise ENotImplemented.Create('GetMethodType');
end;
function TEdgeReaderHostRequest.GetPathInfo: string;
begin
Load;
Result := FEdgeRequest.Path;
end;
function TEdgeReaderHostRequest.GetQueryFields: TStringKeyValues;
begin
Load;
Result := FEdgeRequest.Query;
end;
function TEdgeReaderHostRequest.GetRawContent: TBytes;
begin
Load;
SetLength(Result, FContentLength);
FReader.ReadContent(FContentLength, Result);
end;
{ TEdgeWriterHostResponse }
constructor TEdgeWriterHostResponse.Create(const ARequest: IEMSHostRequest);
begin
FRequest := ARequest;
end;
destructor TEdgeWriterHostResponse.Destroy;
begin
inherited;
end;
function TEdgeWriterHostResponse.GetContentStream: TStream;
begin
Result := FContentStream;
end;
function TEdgeWriterHostResponse.GetContentType: string;
begin
Result := FContentType;
end;
function TEdgeWriterHostResponse.GetRequest: IEMSHostRequest;
begin
Result := FRequest;
end;
function TEdgeWriterHostResponse.GetStatusCode: Integer;
begin
Result := FStatusCode;
end;
procedure TEdgeWriterHostResponse.SetContentStream(const Value: TStream);
begin
Assert(Value <> nil);
if (Value <> nil) and (FContentStream <> nil) then
begin
FContentStream.Size := 0;
FContentStream.Seek(0, soBeginning);
FContentStream.CopyFrom(Value, Value.Size);
{$IFNDEF NEXTGEN}
Value.Free;
{$ENDIF}
end
else
FContentStream := Value;
end;
procedure TEdgeWriterHostResponse.SetContentType(const Value: string);
begin
FContentType := Value;
end;
procedure TEdgeWriterHostResponse.SetStatusCode(const Value: Integer);
begin
FStatusCode := Value;
end;
procedure TEdgeWriterHostResponse.Write(const AWriter: IEdgeResponseWriter);
begin
AWriter.WriteResponse(
TEdgeResponse.Create(FStatusCode, ''));
if FContentStream <> nil then
AWriter.WriteContent(FContentType, FContentStream);
end;
{ TIndyHTTPListener }
constructor TEMSEdgeHTTPServer.Create;
begin
FIdHTTPServer := TIdHTTPServer.Create(nil);
FIdHTTPServer.UseNagle := False;
FIdHTTPServer.KeepAlive := True;
FIdHTTPServer.OnCommandGet := CommandGet;
FIdHTTPServer.OnCommandOther := CommandOther;
FIdHTTPServer.OnCommandError := CommandError;
end;
destructor TEMSEdgeHTTPServer.Destroy;
begin
FIdHTTPServer.Free;
inherited;
end;
function TEMSEdgeHTTPServer.GetActive: Boolean;
begin
Result := FIdHTTPServer.Active;
end;
function TEMSEdgeHTTPServer.GetPort: Cardinal;
begin
Result := FPort;
end;
procedure TEMSEdgeHTTPServer.SetActive(const Value: Boolean);
var
LIOHandleSSL: TIdServerIOHandlerSSLOpenSSL;
LScheduler: TIdSchedulerOfThreadPool;
begin
if FIdHTTPServer.Active <> Value then
begin
if Value then
begin
FIdHTTPServer.Bindings.Clear;
FIdHTTPServer.Bindings.Add.Port := FPort; //default IPv4
if FThreadPool then
begin
LScheduler := TIdSchedulerOfThreadPool.Create(FIdHTTPServer);
if FThreadPoolSize > 0 then
LScheduler.PoolSize := FThreadPoolSize;
FIdHTTPServer.Scheduler := LScheduler;
end;
if FListenQueue > 0 then
FIdHTTPServer.ListenQueue:= FListenQueue;
if FHTTPS then
begin
LIOHandleSSL := TIdServerIOHandlerSSLOpenSSL.Create(FIdHTTPServer);
LIOHandleSSL.SSLOptions.CertFile := FCertFile;
LIOHandleSSL.SSLOptions.RootCertFile := FRootCertFile;
LIOHandleSSL.SSLOptions.KeyFile := FKeyFile;
LIOHandleSSL.OnGetPassword := DoOnGetSSLPassword;
FIdHTTPServer.IOHandler := LIOHandleSSL;
end;
end;
FIdHTTPServer.Active := Value;
end;
end;
procedure TEMSEdgeHTTPServer.DoOnGetSSLPassword(var APassword: String);
begin
if Assigned(FOnGetSSLPassword) then
FOnGetSSLPassword(APassword);
end;
procedure TEMSEdgeHTTPServer.SetPort(const Value: Cardinal);
begin
FPort := Value;
end;
procedure TEMSEdgeHTTPServer.DoCommand(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
LHandler: TEdgeRequestHandler;
LRequestIntf: IEMSHostRequest;
LResponseIntf: IEMSHostResponse;
LRequest: TEdgeReaderHostRequest;
LResponse: TEdgeWriterHostResponse;
LHandled: Boolean;
LEdgeRequestWriter: IEdgeRequestReader;
LEdgeResponseWriter: IEdgeResponseWriter;
LStream: TMemoryStream;
begin
LHandler := TEdgeRequestHandler.Create;
try
if ARequestInfo.CommandType <> THTTPCommandType.hcPOST then
raise Exception.Create('Expected post');
LEdgeRequestWriter := TEdgeReaderWriterFactory.Instance.CreateRequestReader(ARequestInfo.PostStream);
LStream := TMemoryStream.Create;
try
LEdgeResponseWriter := TEdgeReaderWriterFactory.Instance.CreateResponseWriter(LStream);
LRequest := TEdgeReaderHostRequest.Create(LEdgeRequestWriter);
LRequestIntf := LRequest; // Frees LRequest
LResponse := TEdgeWriterHostResponse.Create(LRequest);
LResponseIntf := LResponse; // Frees LResponse
LHandler.HandleRequest(TEMSEdgeListener.TModuleContext.Create(FModule), LRequest, LResponse, LHandled);
LResponse.Write(LEdgeResponseWriter);
AResponseInfo.ContentType := 'application/octet-stream'; // do not localize
AResponseInfo.ContentStream := LStream;
LStream := nil;
finally
LStream.Free;
end;
finally
LHandler.Free;
end;
end;
procedure TEMSEdgeHTTPServer.CommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
DoCommand(AContext, ARequestInfo, AResponseInfo);
end;
procedure TEMSEdgeHTTPServer.CommandOther(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
DoCommand(AContext, ARequestInfo, AResponseInfo);
end;
procedure TEMSEdgeHTTPServer.CommandError(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo;
AException: Exception);
var
LException: EEMSHTTPError;
LJSON: TJSONObject;
LWriter: IEdgeResponseWriter;
LStream: TStream;
begin
if AException is EEMSHTTPError then
begin
LStream := TMemoryStream.Create;
try
LWriter := TEdgeReaderWriterFactory.Instance.CreateResponseWriter(LStream);
LException := EEMSHTTPError(AException);
LWriter.WriteResponse(TEdgeResponse.Create(LException.Code, LException.Error));
LJSON := TErrorHelpers.CreateJSONError('', LException.Error, LException.Description);
try
LWriter.WriteContent('application/json', LJSON.ToJSON); // do not localize
finally
LJSON.Free;
end;
AResponseInfo.ResponseNo := 200;
AResponseInfo.ContentText := '';
AResponseInfo.ContentType := 'application/octet-stream'; // do not localize
AResponseInfo.ContentStream := LStream;
LStream := nil;
finally
LStream.Free;
end;
end;
end;
end.
|
unit ActiveLoans;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopup, Vcl.StdCtrls, RzLabel,
Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, Data.DB, Vcl.Grids, RzGrids, ActiveClient;
type
TfrmActiveLoans = class(TfrmBasePopup)
pnlLoans: TRzPanel;
grLoans: TRzStringGrid;
procedure grLoansDblClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure grLoansDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect;
State: TGridDrawState);
private
{ Private declarations }
procedure SetReturn;
procedure PopulateLoans;
procedure AddRow(loan: TLoan);
public
{ Public declarations }
end;
implementation
{$R *.dfm}
uses
PaymentData, Payment, FormsUtil;
procedure TfrmActiveLoans.FormShow(Sender: TObject);
begin
inherited;
PopulateLoans;
ExtendLastColumn(grLoans);
end;
procedure TfrmActiveLoans.grLoansDblClick(Sender: TObject);
begin
inherited;
SetReturn;
end;
procedure TfrmActiveLoans.grLoansDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
cellStr: string;
begin
with grLoans do
begin
cellStr := Cells[ACol,ARow];
if ARow = 0 then Canvas.Font.Style := [fsBold]
else Canvas.Font.Style := [];
Canvas.Font.Size := Font.Size;
Canvas.Font.Name := Font.Name;
if ARow = 0 then
Canvas.TextRect(Rect,Rect.Left + (ColWidths[ACol] div 2) - (Canvas.TextWidth(cellStr) div 2), Rect.Top + 2, cellStr)
else if (ACol = 3) and (ARow > 0) then
Canvas.TextRect(Rect,Rect.Left - Canvas.TextWidth(cellStr) + ColWidths[3] - 8,Rect.Top + 2,cellStr)
else
Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, cellStr);
end;
end;
procedure TfrmActiveLoans.SetReturn;
var
detail: TPaymentDetail;
begin
if pmt.Client.ActiveLoansCount > pmt.DetailCount then
begin
detail := TPaymentDetail.Create;
detail.PaymentDate := pmt.Date;
detail.Loan := TLoan(grLoans.Objects[0,grLoans.Row]);
pmt.AddDetail(detail);
ModalResult := mrOK;
end
else ModalResult := mrClose;
end;
procedure TfrmActiveLoans.PopulateLoans;
var
i, cnt: integer;
begin
with grLoans do
begin
RowCount := RowCount + 1;
FixedRows := 1;
// headers
Cells[0,0] := 'Loan ID';
Cells[1,0] := 'Type';
Cells[2,0] := 'Account';
Cells[3,0] := 'Balance';
// widths
ColWidths[0] := 100;
ColWidths[1] := 100;
ColWidths[2] := 100;
ColWidths[3] := 100;
cnt := pmt.Client.ActiveLoansCount;
for i := 0 to cnt - 1 do
if not pmt.DetailExists(pmt.Client.ActiveLoans[i]) then
AddRow(pmt.Client.ActiveLoans[i]);
end;
end;
procedure TfrmActiveLoans.AddRow(loan: TLoan);
var
r: integer;
begin
with grLoans do
begin
if not FirstRow(grLoans) then RowCount := RowCount + 1;
r := RowCount - FixedRows;
Cells[0,r] := loan.Id;
Cells[1,r] := loan.LoanTypeName;
Cells[2,r] := loan.AccountTypeName;
Cells[3,r] := FormatCurr('###,###,##0.00',loan.Balance);
Objects[0,r] := loan;
end;
end;
end.
|
{
メモ帳のサンプルプログラム
参考サイト
http://www.w-frontier.com/delphi/3_menu.html
}
unit Unit3;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Menus, Clipbrd;
// Clipbrd追加。クリップボードへコピー、読み込みを行う。
type
TForm3 = class(TForm)
Memo1: TMemo; // メモ帳コンポーネント
Button1: TButton;
MainMenu1: TMainMenu;
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
N5: TMenuItem;
N6: TMenuItem;
N7: TMenuItem;
N8: TMenuItem;
Close: TMenuItem;
mnuUndo: TMenuItem;
N11: TMenuItem;
mnuCut: TMenuItem;
mnuCopy: TMenuItem;
mnuPaste: TMenuItem;
mnuDelete: TMenuItem;
N16: TMenuItem;
mnuSearch: TMenuItem;
N4: TMenuItem;
N18: TMenuItem;
N19: TMenuItem;
N20: TMenuItem;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
FontDialog1: TFontDialog;
mnuRedo: TMenuItem;
N22: TMenuItem;
mnuSelectAll: TMenuItem;
mnuGetDay: TMenuItem; // メモのテキストをダイアログで表示するボタン
procedure Button1Click(Sender: TObject);
procedure NameAsSaveClick(Sender: TObject);
procedure FileOpenClick(Sender: TObject);
procedure SaveFileClick(Sender: TObject);
procedure NewFileClick(Sender: TObject);
procedure mnuRedoClick(Sender: TObject);
procedure mnuUndoClick(Sender: TObject);
procedure mnuCutClick(Sender: TObject);
procedure mnuCopyClick(Sender: TObject);
procedure mnuPasteClick(Sender: TObject);
procedure mnuDeleteClick(Sender: TObject);
procedure mnuSelectAllClick(Sender: TObject);
procedure mnuGetDayClick(Sender: TObject);
procedure CloseClick(Sender: TObject; var Action: TCloseAction);
private
{ Private 宣言 }
public
{ Public 宣言 }
end;
var
Form3: TForm3;
implementation
{$R *.dfm}
procedure TForm3.Button1Click(Sender: TObject);
begin
// メモのテキストをダイアログで表示
ShowMessage(Memo1.Text);
end;
procedure TForm3.NewFileClick(Sender: TObject); // 新規作成
var ans : Word; // MessageDlgの戻り値格納用
begin
// Modified : 指定したコンポーネントが変更されたか判定
// 変更された場合Ture、それ以外False
if Memo1.Modified then
begin
// 変更あり
// MessageDlg : メッセージダイアログ
// クエスチョンマークのメッセージダイアログを表示
// ボタン:「はい」「いいえ」「キャンセル」
// 最後の引数0 : デフォルトのフォーカスを最初の「はい」に指定
ans := MessageDlg('変更されています。保存しますか?',
mtConfirmation,[mbYes,mbNo,mbCancel],0);
if ans = mrCancel then Exit; // 「キャンセル」押下:何もしない
if ans = mrYes then SaveFileClick(Self); // 「はい」押下:保存処理(既存)
end else
begin
// 変更なし
// Memo1.Lines : Memo1の要素のこと
Memo1.Lines.Clear; // メモをクリア
Form3.Caption := '簡易エディタ'; // ウィンドウタイトルを「簡易エディタ」
end;
end;
procedure TForm3.FileOpenClick(Sender: TObject); // 開く
begin
// OpenDialog1が呼び出されたら
if OpenDialog1.Execute then
begin
// 指定したファイルを読み込み、表示
Memo1.Lines.LoadFromFile(OpenDialog1.FileName);
// ウィンドウのタイトルをファイル名に変更
Form3.Caption := OpenDialog1.FileName ;
end ;
end;
procedure TForm3.SaveFileClick(Sender: TObject); // 上書き保存
begin
// 開いてるファイルが存在するかチェックし、
// 存在する場合は上書き保存し、存在しない場合は名前を付けて保存
// ●FileExists : 指定したファイルが存在する場合Ture、ない場合はfalseを返却
if FileExists(Form3.Caption) then
Memo1.Lines.SaveToFile(Form3.Caption) else NameAsSaveClick(Self);
end;
procedure TForm3.NameAsSaveClick(Sender: TObject); // 名前を付けて保存
begin
// SaveDialog1が呼び出されたら
if SaveDialog1.Execute then
begin
// 保存処理
// ●SaveDialog1.FileName : 保存するファイル名の絶対パス
Memo1.Lines.SaveToFile(SaveDialog1.FileName);
end;
end;
procedure TForm3.CloseClick(Sender: TObject; var Action: TCloseAction); // 閉じる
var ans : Word;
begin
if Memo1.Modified then
begin
ans := MessageDlg('変更されています。保存しますか?',
mtConfirmation,[mbYes,mbNo,mbCancel],0);
// キャンセル押下時、終了処理を中止するようActionにcaNoneを指定
if ans = mrCancel then Action := caNone;
if ans = mrYes then SaveFileClick(Self);
end
end;
// -------------------------------------------------------
procedure TForm3.mnuUndoClick(Sender: TObject); // 元に戻す
begin
Memo1.Undo;
end;
procedure TForm3.mnuRedoClick(Sender: TObject); // やり直し
begin
Memo1.Undo;
end;
// -------------------------------------------------------
procedure TForm3.mnuCutClick(Sender: TObject); // カット
begin
Memo1.CutToClipboard;
end;
procedure TForm3.mnuCopyClick(Sender: TObject); // コピー
begin
Memo1.CopyToClipboard;
end;
procedure TForm3.mnuPasteClick(Sender: TObject); // 貼り付け
begin
Memo1.PasteFromClipboard;
end;
procedure TForm3.mnuDeleteClick(Sender: TObject); // 削除
begin
Memo1.SelText := '';
end;
// -------------------------------------------------------
procedure TForm3.mnuSelectAllClick(Sender: TObject); // すべて選択
begin
// 「with Memo1 do」と書いておくと、begin以降で「Memo1.」の記載が必要なくなる
with Memo1 do
begin
// 選択されてる長さと文字列の長さが同じ場合は、選択を反転(選択解除)
// ↑が同じでない場合は、すべて選択(SelectAll)
if SelLength = GetTextLen then
SelLength := 0 else SelectAll;
end;
end;
procedure TForm3.mnuGetDayClick(Sender: TObject); // 日付と時刻
var
date:TDateTime;
strDate:String;
begin
date := Now;
DateTimeToString(strDate, 'yyyy/MM/dd HH:mm:ss',date);
Memo1.SelText := strDate;
end;
end.
|
unit uWakeOnLan;
{
ResourceString: Dario 13/03/13
}
interface
uses
WinTypes, Messages, SysUtils, Classes, IdBaseComponent,
IdComponent, IdUDPBase, IdUDPClient;
procedure WakeUPComputer(aMacAddress: string);
implementation
function HexToInt(S:String): integer;
const
DecDigits: Set Of '0'..'9' = ['0'..'9'];
HexVals: Array [0..$F] Of Integer =
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, $A, $B, $C, $D, $E, $F);
UpCaseHexLetters: Set Of 'A'..'F' = ['A'..'F'];
LowCaseHexLetters: Set Of 'a'..'f' = ['a'..'f'];
var
v: LongInt;
i: integer;
LookUpIndex: integer;
begin
if length(S) <= 8 then begin
v := 0;
for i := 1 to length(S) do begin
{$R-}
v := v Shl 4;
{$R+}
if S[i] in DecDigits then
LookUpIndex := Ord(S[i]) - Ord('0')
else
if S[i] in UpCaseHexLetters then
LookUpIndex := Ord(S[i]) - Ord('A') + $A
else
if S[i] in LowCaseHexLetters then
LookUpIndex := Ord(S[i]) - Ord('a') + $A
else
LookUpIndex := 0;
v := v Or HexVals[LookUpIndex];
end;
result := v;
end else
result := 0;
end;
procedure WakeUPComputer(aMacAddress: string);
var
i, j: Byte;
lBuffer: array[1..116] of Byte;
lUDPClient: TidUDPClient;
begin
try
for i := 1 to 6 do
lBuffer[i] := HexToInt(aMacAddress[(i * 2) - 1] + aMacAddress[i * 2]);
lBuffer[7] := $00;
lBuffer[8] := $74;
lBuffer[9] := $FF;
lBuffer[10] := $FF;
lBuffer[11] := $FF;
lBuffer[12] := $FF;
lBuffer[13] := $FF;
lBuffer[14] := $FF;
for j := 1 to 16 do
for i := 1 to 6 do
lBuffer[15 + (j - 1) * 6 + (i - 1)] := lBuffer[i];
lBuffer[116] := $00;
lBuffer[115] := $40;
lBuffer[114] := $90;
lBuffer[113] := $90;
lBuffer[112] := $00;
lBuffer[111] := $40;
lUDPClient := TIdUDPClient.Create(nil);
try
lUDPClient.BroadcastEnabled := true;
lUDPClient.Host := '255.255.255.255'; // do not localize
lUDPClient.Port := 2050;
lUDPClient.SendBuffer(lBuffer, 116);
finally
lUDPClient.Free;
end;
except
end;
end;
end.
{
Function to return the MAC address of a
remote or local machine in the format 'XX-XX-XX-XX-XX-XX'
The returned MAC address is a Unique ID that can be used in various
ways. One way is as a parameter to my Wake On Lan function.(See article
"http://www.delphi3000.com/articles/article_3847.asp")
Example :
ShowMessage(GetMacAddress('\\MHEYDON');
Output = '00-02-08-E7-99-6B'
Answer:
//
======================================================================
// Return the MAC address of Machine identified by AServerName
// Format of AServerName is '\\ServerName' or 'ServerName'
// If AServerName is a null String then local machine MAC address
// is returned.
// Return string is in format 'XX-XX-XX-XX-XX-XX'
//
======================================================================
function GetMacAddress(const AServerName : string) : string;
type
TNetTransportEnum = function(pszServer : PWideChar;
Level : DWORD;
var pbBuffer : pointer;
PrefMaxLen : LongInt;
var EntriesRead : DWORD;
var TotalEntries : DWORD;
var ResumeHandle : DWORD) : DWORD;
stdcall;
TNetApiBufferFree = function(Buffer : pointer) : DWORD; stdcall;
PTransportInfo = ^TTransportInfo;
TTransportInfo = record
quality_of_service : DWORD;
number_of_vcs : DWORD;
transport_name : PWChar;
transport_address : PWChar;
wan_ish : boolean;
end;
var E,ResumeHandle,
EntriesRead,
TotalEntries : DWORD;
FLibHandle : THandle;
sMachineName,
sMacAddr,
Retvar : string;
pBuffer : pointer;
pInfo : PTransportInfo;
FNetTransportEnum : TNetTransportEnum;
FNetApiBufferFree : TNetApiBufferFree;
pszServer : array[0..128] of WideChar;
i,ii,iIdx : integer;
begin
sMachineName := trim(AServerName);
Retvar := '00-00-00-00-00-00';
// Add leading \\ if missing
if (sMachineName <> '') and (length(sMachineName) >= 2) then
begin
if copy(sMachineName,1,2) <> '\\' then
sMachineName := '\\' + sMachineName
end;
// Setup and load from DLL
pBuffer := nil;
ResumeHandle := 0;
FLibHandle := LoadLibrary('NETAPI32.DLL');
// Execute the external function
if FLibHandle <> 0 then begin
@FNetTransportEnum :=
GetProcAddress(FLibHandle,'NetWkstaTransportEnum');
@FNetApiBufferFree := GetProcAddress(FLibHandle,'NetApiBufferFree');
E :=
FNetTransportEnum(StringToWideChar(sMachineName,pszServer,129),0,
pBuffer,-1,EntriesRead,TotalEntries,Resumehandle);
if E = 0 then begin
pInfo := pBuffer;
// Enumerate all protocols - look for TCPIP
for i := 1 to EntriesRead do begin
if pos('TCPIP',UpperCase(pInfo^.transport_name)) <> 0
then begin
// Got It - now format result 'xx-xx-xx-xx-xx-xx'
iIdx := 1;
sMacAddr := pInfo^.transport_address;
for ii := 1 to 12 do begin
Retvar[iIdx] := sMacAddr[ii];
inc(iIdx);
if iIdx in [3,6,9,12,15] then inc(iIdx);
end;
end;
inc(pInfo);
end;
if pBuffer <> nil then FNetApiBufferFree(pBuffer);
end;
try
FreeLibrary(FLibHandle);
except
// Silent Error
end;
end;
Result := Retvar;
end;
This procedure will switch on a machine
that is connected to a LAN. The MAC address of the machine is needed to
be known.
See my article
("http://www.delphi3000.com/articles/article_3867.asp")
for a function
GetMacAddress() that returns a MAC Address String.
The "Wake On Lan" feature of the machine's BIOS must be enabled.
The procedure works by broadcasting a UDP packet containing the
"Magic Number" to all machines on the LAN. The machine with the MAC
address, if switched of and BIOS WOL enabled will wake up and boot.
The MAC address required is a "-" delimited 17 char string.
Example :
WakeOnLan('00-D0-B7-E2-A1-A0');
Answer:
uses idUDPClient;
//
==========================================================================
// Wakes a machine on lan
// AMacAddress is 17 char MAC address.
// eg. '00-C0-4F-0A-3A-D7'
//
==========================================================================
procedure WakeOnLan(const AMacAddress : string);
type
TMacAddress = array [1..6] of byte;
TWakeRecord = packed record
Waker : TMACAddress;
MAC : array[0..15] of TMACAddress;
end;
var i : integer;
WR : TWakeRecord;
MacAddress : TMacAddress;
UDP : TIdUDPClient;
sData : string;
begin
// Convert MAC string into MAC array
fillchar(MacAddress,SizeOf(TMacAddress),0);
sData := trim(AMacAddress);
if length(sData) = 17 then begin
for i := 1 to 6 do begin
MacAddress[i] := StrToIntDef('$' + copy(sData,1,2),0);
sData := copy(sData,4,17);
end;
end;
for i := 1 To 6 do WR.Waker[i] := $FF;
for i := 0 to 15 do WR.MAC[i] := MacAddress;
// Create UDP and Broadcast data structure
UDP := TIdUDPClient.Create(nil);
UDP.Host := '255.255.255.255';
UDP.Port := 32767;
UDP.BroadCastEnabled := true;
UDP.SendBuffer(WR,SizeOf(TWakeRecord));
UDP.BroadcastEnabled := false;
UDP.Free;
end;
Let us know what you think Email us!
Copyright 2008 © Tamarack Associates
www.TamarackA.com 6/10/2008 7:42:36 AM, Generated in 94ms www.FullTextSearch.com
unit Unit1;
interface
implementation
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: Base classes for GLScene.<p>
<b>History : </b><font size=-1><ul>
<li>24/03/11 - Yar - Added Notification method to TGLUpdateAbleObject
<li>05/10/08 - DanB - Creation, from GLMisc.pas + other places
</ul></font>
}
unit GLBaseClasses;
interface
uses
System.Classes, System.SysUtils,
//GLScene
GLStrings, GLPersistentClasses, GLCrossPlatform;
type
// TProgressTimes
//
TProgressTimes = record
deltaTime, newTime: Double
end;
// TGLProgressEvent
//
{: Progression event for time-base animations/simulations.<p>
deltaTime is the time delta since last progress and newTime is the new
time after the progress event is completed. }
TGLProgressEvent = procedure(Sender: TObject; const deltaTime, newTime: Double) of object;
IGLNotifyAble = interface(IInterface)
['{00079A6C-D46E-4126-86EE-F9E2951B4593}']
procedure NotifyChange(Sender: TObject);
end;
IGLProgessAble = interface(IInterface)
['{95E44548-B0FE-4607-98D0-CA51169AF8B5}']
procedure DoProgress(const progressTime: TProgressTimes);
end;
// TGLUpdateAbleObject
//
{: An abstract class describing the "update" interface.<p> }
TGLUpdateAbleObject = class(TGLInterfacedPersistent, IGLNotifyAble)
private
{ Private Declarations }
FOwner: TPersistent;
FUpdating: Integer;
FOnNotifyChange: TNotifyEvent;
public
{ Public Declarations }
constructor Create(AOwner: TPersistent); virtual;
procedure NotifyChange(Sender: TObject); virtual;
procedure Notification(Sender: TObject; Operation: TOperation); virtual;
function GetOwner: TPersistent; override;
property Updating: Integer read FUpdating;
procedure BeginUpdate;
procedure EndUpdate;
property Owner: TPersistent read FOwner;
property OnNotifyChange: TNotifyEvent read FOnNotifyChange write FOnNotifyChange;
end;
// TGLCadenceAbleComponent
//
{: A base class describing the "cadenceing" interface.<p> }
TGLCadenceAbleComponent = class(TGLComponent, IGLProgessAble)
public
{ Public Declarations }
procedure DoProgress(const progressTime: TProgressTimes); virtual;
end;
// TGLUpdateAbleComponent
//
{: A base class describing the "update" interface.<p> }
TGLUpdateAbleComponent = class(TGLCadenceAbleComponent, IGLNotifyAble)
public
{ Public Declarations }
procedure NotifyChange(Sender: TObject); virtual;
end;
// TNotifyCollection
//
TNotifyCollection = class(TOwnedCollection)
private
{ Private Declarations }
FOnNotifyChange: TNotifyEvent;
protected
{ Protected Declarations }
procedure Update(item: TCollectionItem); override;
public
{ Public Declarations }
constructor Create(AOwner: TPersistent; AItemClass: TCollectionItemClass);
property OnNotifyChange: TNotifyEvent read FOnNotifyChange write FOnNotifyChange;
end;
implementation
{$IFDEF GLS_REGIONS}{$REGION 'TGLUpdateAbleObject'}{$ENDIF}
//---------------------- TGLUpdateAbleObject -----------------------------------------
// Create
//
constructor TGLUpdateAbleObject.Create(AOwner: TPersistent);
begin
inherited Create;
FOwner := AOwner;
end;
// NotifyChange
//
procedure TGLUpdateAbleObject.NotifyChange(Sender: TObject);
begin
if FUpdating = 0 then
begin
if Assigned(Owner) then
begin
if Owner is TGLUpdateAbleObject then
TGLUpdateAbleObject(Owner).NotifyChange(Self)
else if Owner is TGLUpdateAbleComponent then
TGLUpdateAbleComponent(Owner).NotifyChange(Self);
end;
if Assigned(FOnNotifyChange) then
FOnNotifyChange(Self);
end;
end;
// Notification
//
procedure TGLUpdateAbleObject.Notification(Sender: TObject; Operation: TOperation);
begin
end;
// GetOwner
//
function TGLUpdateAbleObject.GetOwner: TPersistent;
begin
Result := Owner;
end;
// BeginUpdate
//
procedure TGLUpdateAbleObject.BeginUpdate;
begin
Inc(FUpdating);
end;
// EndUpdate
//
procedure TGLUpdateAbleObject.EndUpdate;
begin
Dec(FUpdating);
if FUpdating <= 0 then
begin
Assert(FUpdating = 0);
NotifyChange(Self);
end;
end;
{$IFDEF GLS_REGIONS}{$ENDREGION 'TGLUpdateAbleObject'}{$ENDIF}
{$IFDEF GLS_REGIONS}{$REGION 'TGLCadenceAbleComponent'}{$ENDIF}
// ------------------
// ------------------ TGLCadenceAbleComponent ------------------
// ------------------
// DoProgress
//
procedure TGLCadenceAbleComponent.DoProgress(const progressTime: TProgressTimes);
begin
// nothing
end;
// ------------------
// ------------------ TGLUpdateAbleObject ------------------
// ------------------
// NotifyChange
//
procedure TGLUpdateAbleComponent.NotifyChange(Sender: TObject);
begin
if Assigned(Owner) then
if (Owner is TGLUpdateAbleComponent) then
(Owner as TGLUpdateAbleComponent).NotifyChange(Self);
end;
{$IFDEF GLS_REGIONS}{$ENDREGION 'TGLUpdateAbleObject'}{$ENDIF}
{$IFDEF GLS_REGIONS}{$REGION 'TNotifyCollection'}{$ENDIF}
// ------------------
// ------------------ TNotifyCollection ------------------
// ------------------
// Create
//
constructor TNotifyCollection.Create(AOwner: TPersistent; AItemClass: TCollectionItemClass);
begin
inherited Create(AOwner, AItemClass);
if Assigned(AOwner) and (AOwner is TGLUpdateAbleComponent) then
OnNotifyChange := TGLUpdateAbleComponent(AOwner).NotifyChange;
end;
// Update
//
procedure TNotifyCollection.Update(Item: TCollectionItem);
begin
inherited;
if Assigned(FOnNotifyChange) then
FOnNotifyChange(Self);
end;
{$IFDEF GLS_REGIONS}{$ENDREGION 'TNotifyCollection'}{$ENDIF}
end.
|
{------------------------------------------------------------------------------
This file is part of the MotifMASTER project. This software is
distributed under GPL (see gpl.txt for details).
This software 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.
Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru)
------------------------------------------------------------------------------}
unit NumericGrid;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids,
{$IFNDEF Lazarus}
DsgnIntf,
{$ENDIF}
ClipBrd, Tools;
var
CL_ODD_ROW: TColor = clWhite;
CL_EVEN_ROW: TColor = clYellow;
CL_DISABLED_ROW: TColor = clGray;
CL_SELECTED: TColor = $2A92B0;
GridDataSourceGUID: TGUID = '{401B6CC0-0915-11D5-968F-8FBD7448F374}';
MIN_HEIGHT: LongInt = 10;
MIN_WIDTH: LongInt = 40;
type
EColorStringGrid = class(Exception);
ENumericGrid = class(Exception);
EIDA_Grid = class(Exception);
IGridDataSource = interface
['{401B6CC0-0915-11D5-968F-8FBD7448F374}']
function ValueToString(const ACol, ARow: LongInt): string;
procedure StringToValue(const ACol, ARow: LongInt;
const AString: string);
procedure SetValueByDefault(const ACol, ARow: LongInt);
function GetCellColor(const ACol, ARow: LongInt; var Color: TColor): Boolean;
function GetCellEditMask(const ACol, ARow: LongInt): string;
function GetCellEnabledCharSet(const ACol, ARow: LongInt): TCharSet;
function IsCellDisabled(const ACol, ARow: LongInt): Boolean;
function IsDataValid(const ACol, ARow: LongInt;
const AString: string): Boolean;
function MayIDoInsertRows(StartRow, RowsCount: LongInt): Boolean;
function MayIDoDeleteRows(StartRow, RowsCount: LongInt): Boolean;
function MayIDoAddRow: Boolean;
function MayIDoInsertColumns(StartCol, ColsCount: LongInt): Boolean;
function MayIDoDeleteColumns(StartCol, ColsCount: LongInt): Boolean;
function MayIDoAddColumn: Boolean;
function MayIDoDeleteAllData: Boolean;
function MayIDoClearSelectedArea: Boolean;
function MayIDoClearAllCells: Boolean;
procedure RowsDeleted(const StartPos, Count: LongInt);
procedure RowsInserted(const StartPos, Count: LongInt);
procedure RowAdded;
procedure ColumnsDeleted(const StartPos, Count: LongInt);
procedure ColumnsInserted(const StartPos, Count: LongInt);
procedure ColumnAdded;
procedure AllDataDeleted;
function GetColCount: LongInt;
function GetRowCount: LongInt;
function GetFixedCols: LongInt;
function GetFixedRows: LongInt;
function GetColNumFixed: Boolean;
function GetRowNumFixed: Boolean;
function GetColWidth(const Col: LongInt): LongInt;
procedure SaveColWidth(const Col, Width: LongInt);
function GetRowHeight(const Row: LongInt): LongInt;
procedure SaveRowHeight(const Row, Height: LongInt);
function AutoWidths: Boolean;
function AutoHeights: Boolean;
function GetSelection: TGridRect;
procedure SaveSelection(const Selection: TGridRect);
function GetCol: LongInt;
procedure SaveCol(const Col: LongInt);
function GetRow: LongInt;
procedure SaveRow(const Row: LongInt);
function GetLeftCol: LongInt;
procedure SaveLeftCol(const LeftCol: LongInt);
function GetTopRow: LongInt;
procedure SaveTopRow(const TopRow: LongInt);
end;
TGridEditingFinished = procedure(Sender: TObject;
Col, Row: LongInt
) of object;
TGridModified = procedure(Sender: TObject) of object;
TGEFGrid = class(TStringGrid)
protected
FGridEditingFinished: TGridEditingFinished;
FGridModified: TGridModified;
FModified: Boolean;
procedure DoExit; override;
{$IFNDEF Lazarus}
function CanEditAcceptKey(Key: Char): Boolean; override;
{$ENDIF}
procedure KeyPress(var Key: Char); override;
function SelectCell(ACol, ARow: Longint): Boolean; override;
procedure EditingFinished(
const ACol, ARow: LongInt
); virtual;
procedure SetModified(const AModified: Boolean);
public
published
property Modified: Boolean
read FModified write SetModified;
property OnGridEditingFinished: TGridEditingFinished
read FGridEditingFinished write FGridEditingFinished;
property OnGridModified: TGridModified
read FGridModified write FGridModified;
end;
TGridResizedEvent = procedure(Sender: TObject) of object;
TIDA_Grid = class(TGEFGrid)
protected
FColNumFixed: Boolean;
FRowNumFixed: Boolean;
FChangeable: Boolean;
SelFlag: Boolean;
StartCoord: TGridCoord;
SavedCoord: TGridCoord;
FOnGridResized: TGridResizedEvent;
{$IFNDEF Lazarus}
function CanEditModify: Boolean; override;
{$ENDIF}
procedure KeyPress(var Key: Char); override;
procedure _InsertRows(StartRow, RowsCount: LongInt; Clear: Boolean
); virtual;
procedure _DeleteRows(StartRow, RowsCount: LongInt
); virtual;
procedure _AddRow; virtual;
procedure _InsertColumns(StartCol, ColsCount: LongInt; Clear: Boolean
); virtual;
procedure _DeleteColumns(StartCol, ColsCount: LongInt
); virtual;
procedure _AddColumn; virtual;
procedure _DeleteAllData; virtual;
procedure _ClearSelectedArea; virtual;
procedure _ClearAllCells; virtual;
procedure ClearArea(const Left, Top, Right, Bottom: LongInt);
procedure DataChanged(const Left, Top, Right, Bottom: LongInt); virtual;
procedure FillArea(const Left, Top, Right, Bottom: LongInt); virtual;
procedure FillRowHeaders; virtual;
procedure FillColHeaders; virtual;
public
constructor Create(AOwner: TComponent); override;
procedure PasteFromClipBoard; virtual;
procedure CopyToClipBoard; virtual;
procedure MouseUp(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer
); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer
); override;
procedure MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer
); override;
function MayIDoInsertRows(StartRow, RowsCount: LongInt): Boolean; virtual;
function MayIDoDeleteRows(StartRow, RowsCount: LongInt): Boolean; virtual;
function MayIDoAddRow: Boolean; virtual;
function MayIDoInsertColumns(StartCol, ColsCount: LongInt): Boolean; virtual;
function MayIDoDeleteColumns(StartCol, ColsCount: LongInt): Boolean; virtual;
function MayIDoAddColumn: Boolean; virtual;
function MayIDoDeleteAllData: Boolean; virtual;
function MayIDoClearSelectedArea: Boolean; virtual;
function MayIDoClearAllCells: Boolean; virtual;
procedure InsertRows(StartRow, RowsCount: LongInt; Clear: Boolean);
procedure DeleteRows(StartRow, RowsCount: LongInt);
procedure AddRow;
procedure InsertColumns(StartCol, ColsCount: LongInt; Clear: Boolean);
procedure DeleteColumns(StartCol, ColsCount: LongInt);
procedure AddColumn;
procedure DeleteAllData;
procedure ClearSelectedArea;
procedure ClearAllCells;
procedure DeleteSelection;
procedure SelectAll;
procedure ClearSelection;
procedure SetAutoColWidth(ACol: LongInt);
procedure AutoColWidths;
procedure SetAutoRowHeight(ARow: LongInt);
procedure AutoRowHeights;
published
property DoubleBuffered;
property ColNumFixed: Boolean read FColNumFixed write FColNumFixed;
property RowNumFixed: Boolean read FRowNumFixed write FRowNumFixed;
property Changeable: Boolean read FChangeable write FChangeable;
property OnGridResized: TGridResizedEvent
read FOnGridResized write FOnGridResized;
end;
TServeredGrid = class(TIDA_Grid)
protected
FGridDataSource: IGridDataSource;
function GetMyGridDataSource: IGridDataSource;
procedure EditingFinished(
const ACol, ARow: LongInt
); override;
{$IFNDEF Lazarus}
function CanEditAcceptKey(Key: Char): Boolean; override;
function CanEditModify: Boolean; override;
{$ENDIF}
procedure _InsertRows(StartRow, RowsCount: LongInt; Clear: Boolean); override;
procedure _DeleteRows(StartRow, RowsCount: LongInt); override;
procedure _AddRow; override;
procedure _InsertColumns(StartCol, ColsCount: LongInt; Clear: Boolean); override;
procedure _DeleteColumns(StartCol, ColsCount: LongInt); override;
procedure _AddColumn; override;
procedure _DeleteAllData; override;
procedure _ClearSelectedArea; override;
procedure _ClearAllCells; override;
procedure DataChanged(
const Left, Top, Right, Bottom: LongInt); override;
procedure FillArea(
const Left, Top, Right, Bottom: LongInt); override;
procedure GetTableParams;
procedure GetWidthsHeights;
procedure SaveTableParams;
procedure FillTable;
procedure FillRowHeaders; override;
procedure FillColHeaders; override;
public
function MayIDoInsertRows(StartRow, RowsCount: LongInt): Boolean; override;
function MayIDoDeleteRows(StartRow, RowsCount: LongInt): Boolean; override;
function MayIDoAddRow: Boolean; override;
function MayIDoInsertColumns(StartCol, ColsCount: LongInt): Boolean; override;
function MayIDoDeleteColumns(StartCol, ColsCount: LongInt): Boolean; override;
function MayIDoAddColumn: Boolean; override;
function MayIDoDeleteAllData: Boolean; override;
function MayIDoClearSelectedArea: Boolean; override;
function MayIDoClearAllCells: Boolean; override;
procedure HideTable;
procedure ShowTable;
procedure SetGridDataSource(GridDataSource: IGridDataSource);
end;
TColoredGrid = class(TServeredGrid)
protected
FOddRowColor: TColor;
FEvenRowColor: TColor;
FSelectedRegionColor: TColor;
FDisabledColor: TColor;
function GetOddRowColor: TColor; virtual;
procedure SetOddRowColor(const AOddRowColor: TColor); virtual;
function GetEvenRowColor: TColor; virtual;
procedure SetEvenRowColor(const AEvenRowColor: TColor); virtual;
function GetSelectedRegionColor: TColor; virtual;
procedure SetSelectedRegionColor(const ASelectedRegionColor: TColor); virtual;
function GetDisabledColor: TColor; virtual;
procedure SetDisabledColor(const ADisabledColor: TColor); virtual;
procedure DrawCell(ACol, ARow: Longint;
ARect: TRect; AState: TGridDrawState); override;
public
constructor Create(AOwner: TComponent); override;
published
property OddRowColor: TColor read GetOddRowColor write SetOddRowColor;
property EvenRowColor: TColor read GetEvenRowColor write SetEvenRowColor;
property SelectedRegionColor: TColor
read GetSelectedRegionColor write SetSelectedRegionColor;
property DisabledColor: TColor
read GetDisabledColor write SetDisabledColor;
end;
{$IFNDEF Lazarus}
TModifiedEditor = class(TInplaceEdit)
public
property EditMask;
end;
{$ENDIF}
TColOption = LongInt;
TGetCellColorEvent = procedure(Sender: TObject;
ColNum, RowNum: LongInt; var CellColor: TColor) of object;
TColorStringGrid = class(TStringGrid)
protected
FColorMatrix: array of array of TColor;
FOddRowColor: TColor;
FNotOddRowColor: TColor;
FSelectedRegionColor: TColor;
FOnGetCellColor: TGetCellColorEvent;
FColNumFixed: Boolean;
FRowNumFixed: Boolean;
procedure SetOddRowColor(Color: TColor);
procedure SetNotOddRowColor(Color: TColor);
procedure SetSelectedRegionColor(Color: TColor);
procedure DrawCell(ACol, ARow: Longint; ARect: TRect;
AState: TGridDrawState); override;
function GetCellColor(const ColNum, RowNum: LongInt): TColor;
{$IFNDEF Lazarus}
function CreateEditor: TInplaceEdit; override;
{$ENDIF}
procedure SetColCount(Value: Longint); virtual;
function GetColCount: LongInt; virtual;
procedure SetRowCount(Value: Longint); virtual;
function GetRowCount: LongInt; virtual;
function GetCellsColors(ACol, ARow: LongInt): TColor;
procedure SetCellsColors(ACol, ARow: LongInt; AColor: TColor);
procedure InitColorMatrix;
procedure FinalizeColorMatrix;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure EnumerateRows;
procedure SelectAll;
procedure ResetAll;
procedure ClearSelection;
function CopyToClipBoard: Boolean;
function PasteFromClipBoard: Boolean;
function CheckingTextValidity(St: string;
ACol, ARow: LongInt): Boolean; virtual;
property InplaceEditor;
property CellsColors[ACol, ARow: LongInt]: TColor
read GetCellsColors write SetCellsColors;
published
property DoubleBuffered;
property OddRowColor: TColor
read FOddRowColor write SetOddRowColor;
property NotOddRowColor: TColor
read FNotOddRowColor write SetNotOddRowColor;
property SelectedRegionColor: TColor
read FSelectedRegionColor write SetSelectedRegionColor;
property ColNumFixed: Boolean
read FColNumFixed write FColNumFixed;
property RowNumFixed: Boolean
read FRowNumFixed write FRowNumFixed;
property OnGetCellColor: TGetCellColorEvent
read FOnGetCellColor write FOnGetCellColor;
property ColCount: LongInt
read GetColCount write SetColCount;
property RowCount: LongInt
read GetRowCount write SetRowCount;
end;
TNumericGrid = class(TColorStringGrid)
protected
FDisabledColor: TColor;
ColOptArray: array of TColOption;
SelFlag: Boolean;
StartCoord: TGridCoord;
SavedCoord: TGridCoord;
procedure SetColOption(index: LongInt; Value: TColOption);
function GetColOption(index: LongInt): TColOption;
procedure SetOptCount(AColOptCount: LongInt);
procedure SetDisabledColor(Color: TColor);
procedure KeyPress(var Key: Char); override;
procedure SetColCount(Value: Longint); override;
public
function CheckingTextValidity(St: string; ACol,
ARow: LongInt): Boolean; override;
constructor Create(AOwner: TComponent); override;
{$IFNDEF Lazarus}
function CanEditAcceptKey(Key: Char): Boolean; override;
{$ENDIF}
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure InsertRows(StartPos, Count: LongInt; Clear: Boolean); virtual;
procedure DeleteRows(StartPos, Count: LongInt); virtual;
procedure SetColWidthByDefault(ACol: LongInt);
procedure ResetColWidths;
procedure DeleteSelection;
destructor Destroy; override;
property ColOptions[index: LongInt]: TColOption
read GetColOption write SetColOption;
published
property DisabledColor: TColor
read FDisabledColor write SetDisabledColor;
end;
const
coReal = 1000;
coInteger = 1001;
coText = 1002;
coChars = 1003;
coDisabled = 1004;
SelectOptions: set of TGridOption = [goFixedVertLine,
goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect,
goDrawFocusSelected, goTabs, goThumbTracking,
goRowSizing, goColSizing];
EditingOptions: set of TGridOption = [goFixedVertLine,
goFixedHorzLine, goVertLine, goHorzLine, goEditing,
goDrawFocusSelected, goTabs, goThumbTracking,
goAlwaysShowEditor, goRowSizing, goColSizing];
StaticOptions: set of TGridOption = [goFixedVertLine,
goFixedHorzLine, goVertLine, goHorzLine, goTabs,
goThumbTracking, goRowSizing, goColSizing];
function GetMaxTextWidth(
const Grid: TStringGrid; const ColNum: LongInt): LongInt;
function GetMaxTextHeight(
const Grid: TStringGrid; const RowNum: LongInt): LongInt;
const
REAL_SET: set of Char = ['0'..'9', '.', '-', '+'];
POS_REAL_SET: set of Char = ['0'..'9', '.', '+'];
INT_SET: set of Char = ['0'..'9', '-', '+'];
POS_INT_SET: set of Char = ['0'..'9', '+'];
CHAR_SET: set of Char = ['A'..'Z', 'a'..'z'];
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Synthesis', [TColorStringGrid]);
RegisterComponents('Synthesis', [TNumericGrid]);
{$IFNDEF Lazarus}
RegisterPropertyEditor(TypeInfo(TColor), TColorStringGrid,
'OddRowColor', TColorProperty);
RegisterPropertyEditor(TypeInfo(TColor), TColorStringGrid,
'NotOddRowColor', TColorProperty);
RegisterPropertyEditor(TypeInfo(TColor), TColorStringGrid,
'SelectedRegionColor', TColorProperty);
RegisterPropertyEditor(TypeInfo(TColor), TColorStringGrid,
'DisabledColor', TColorProperty);
RegisterPropertyEditor(TypeInfo(Boolean), TColorStringGrid,
'RowNumFixed', TEnumProperty);
RegisterPropertyEditor(TypeInfo(Boolean), TColorStringGrid,
'ColNumFixed', TEnumProperty);
RegisterPropertyEditor(TypeInfo(Boolean), TColorStringGrid,
'DoubleBuffered', TEnumProperty);
RegisterPropertyEditor(TypeInfo(TGetCellColorEvent), TColorStringGrid,
'OnGetCellColor', TMethodProperty);
{$ENDIF}
RegisterComponents('Grids', [TColoredGrid]);
{$IFNDEF Lazarus}
RegisterPropertyEditor(
TypeInfo(TColor), TColoredGrid, 'OddRowColor', TColorProperty);
RegisterPropertyEditor(
TypeInfo(TColor), TColoredGrid, 'EvenRowColor', TColorProperty);
RegisterPropertyEditor(
TypeInfo(TColor), TColoredGrid, 'SelectedRegionColor', TColorProperty);
RegisterPropertyEditor(
TypeInfo(TColor), TColoredGrid, 'DisabledColor', TColorProperty);
RegisterPropertyEditor(
TypeInfo(Boolean), TIDA_Grid, 'DoubleBuffered', TEnumProperty);
RegisterPropertyEditor(
TypeInfo(Boolean), TIDA_Grid, 'RowNumFixed', TEnumProperty);
RegisterPropertyEditor(
TypeInfo(Boolean), TIDA_Grid, 'ColNumFixed', TEnumProperty);
RegisterPropertyEditor(
TypeInfo(Boolean), TIDA_Grid, 'Changeable', TEnumProperty);
RegisterPropertyEditor(
TypeInfo(TGridResizedEvent), TIDA_Grid, 'OnGridResized', TMethodProperty);
{$ENDIF}
RegisterComponents('Grids', [TGEFGrid]);
{$IFNDEF Lazarus}
RegisterPropertyEditor(
TypeInfo(TGridEditingFinished), TGEFGrid,
'OnGridEditingFinished', TMethodProperty);
RegisterPropertyEditor(
TypeInfo(TGridModified), TGEFGrid,
'OnGridModified', TMethodProperty);
{$ENDIF}
end;
procedure TIDA_Grid.MouseUp;
begin
SelFlag := False;
inherited MouseUp(Button, Shift, X, Y);
end;
procedure TIDA_Grid.MouseDown;
var Coord: TGridCoord;
R: TGridRect;
begin
Coord := MouseCoord(X, Y);
if Shift = [ssLeft, ssDouble] then
begin
if (Coord.X > FixedCols - 1) and (Coord.Y > FixedRows - 1) then
begin
ClearSelection;
Col := Coord.X;
Row := Coord.Y;
{$IFNDEF Lazarus}
if CanEditModify then Options := EditingOptions;
{$ENDIF}
end
end else
if Shift = [ssLeft] then
begin
Coord := MouseCoord(X, Y);
if (Coord.X <= FixedCols - 1) or (Coord.Y <= FixedRows - 1) then
begin
Options := SelectOptions;
if (Coord.Y <= FixedRows - 1) and (Coord.X >= FixedCols) then
begin
SelFlag := True;
StartCoord := MouseCoord(X, Y);
SavedCoord := StartCoord;
R.Top := FixedRows; R.Bottom := RowCount - 1;
R.Left := StartCoord.X; R.Right := StartCoord.X;
Selection := R;
end;
if (Coord.X <= FixedCols - 1) and (Coord.Y >= FixedRows) then
begin
SelFlag := True;
StartCoord := MouseCoord(X, Y);
SavedCoord := StartCoord;
R.Left := FixedCols; R.Right := ColCount - 1;
R.Top := StartCoord.Y; R.Bottom := StartCoord.Y;
Selection := R;
end;
if (Coord.X <= FixedCols - 1) and (Coord.Y <= FixedRows - 1) then
SelectAll;
end else begin
ClearSelection;
Options := StaticOptions;
end;
end;
inherited MouseDown(Button, Shift, X, Y);
end;
procedure TIDA_Grid.MouseMove(Shift: TShiftState; X, Y: Integer);
var Coord: TGridCoord;
R: TGridRect;
begin
if SelFlag then
begin
Coord := MouseCoord(X, Y);
if (Coord.X <> SavedCoord.X) or (Coord.Y <> SavedCoord.Y) then
begin
if (StartCoord.Y <= FixedRows - 1) and
(StartCoord.X >= FixedCols) and (Coord.X >= FixedCols) then
begin
R.Top := FixedRows; R.Bottom := RowCount - 1;
if Coord.X < StartCoord.X then
begin R.Left := Coord.X; R.Right := StartCoord.X end;
if Coord.X > StartCoord.X then
begin R.Left := StartCoord.X; R.Right := Coord.X end;
if Coord.X = StartCoord.X then
begin R.Left := StartCoord.X; R.Right := StartCoord.X end;
Selection := R;
if (Coord.X - LeftCol = VisibleColCount) and
(Coord.X < ColCount - 1) then LeftCol := LeftCol + 1;
if (Coord.X = LeftCol) and
(LeftCol > FixedCols) then LeftCol := LeftCol - 1;
end;
if (StartCoord.X <= FixedCols - 1) and
(StartCoord.Y >= FixedRows) and (Coord.Y >= FixedRows) then
begin
R.Left := FixedCols; R.Right := ColCount - 1;
if Coord.Y < StartCoord.Y then
begin R.Top := Coord.Y; R.Bottom := StartCoord.Y end;
if Coord.Y > StartCoord.Y then
begin R.Top := StartCoord.Y; R.Bottom := Coord.Y end;
if Coord.Y = StartCoord.Y then
begin R.Top := StartCoord.Y; R.Bottom := StartCoord.Y end;
Selection := R;
if (Coord.Y - TopRow = VisibleRowCount) and
(Coord.Y < RowCount - 1) then TopRow := TopRow + 1;
if (Coord.Y = TopRow) and
(TopRow > FixedRows) then TopRow := TopRow - 1;
end;
SavedCoord := Coord;
end; // if (Coord.X <> SavedCoord.X) or (Coord.Y <> SavedCoord.Y) then...
end;
inherited MouseMove(Shift, X, Y);
end;
procedure TIDA_Grid.InsertRows(StartRow, RowsCount: LongInt; Clear: Boolean);
begin
if MayIDoInsertRows(StartRow, RowsCount) then
begin
_InsertRows(StartRow, RowsCount, Clear);
if Assigned(OnGridResized) then OnGridResized(Self);
if Assigned(OnGridModified) then OnGridModified(Self);
end else raise EIDA_Grid.Create('Rows inserting is not allowed...');
end;
procedure TIDA_Grid.DeleteRows(StartRow, RowsCount: LongInt);
begin
if MayIDoDeleteRows(StartRow, RowsCount) then
begin
_DeleteRows(StartRow, RowsCount);
if Assigned(OnGridResized) then OnGridResized(Self);
if Assigned(OnGridModified) then OnGridModified(Self);
end else raise EIDA_Grid.Create('Rows deleting is not allowed...');
end;
procedure TIDA_Grid.InsertColumns(StartCol, ColsCount: LongInt; Clear: Boolean);
begin
if MayIDoInsertColumns(StartCol, ColsCount) then
begin
_InsertColumns(StartCol, ColsCount, Clear);
if Assigned(OnGridResized) then OnGridResized(Self);
if Assigned(OnGridModified) then OnGridModified(Self);
end else raise EIDA_Grid.Create('Columns inserting is not allowed...');
end;
procedure TIDA_Grid.DeleteColumns(StartCol, ColsCount: LongInt);
begin
if MayIDoDeleteColumns(StartCol, ColsCount) then
begin
_DeleteColumns(StartCol, ColsCount);
if Assigned(OnGridResized) then OnGridResized(Self);
if Assigned(OnGridModified) then OnGridModified(Self);
end else raise EIDA_Grid.Create('Columns deleting is not allowed...');
end;
procedure TIDA_Grid.DeleteAllData;
begin
if MayIDoDeleteAllData then
begin
_DeleteAllData;
if Assigned(OnGridResized) then OnGridResized(Self);
if Assigned(OnGridModified) then OnGridModified(Self);
end else raise EIDA_Grid.Create('Data deleting not allowed...');
end;
procedure TIDA_Grid.ClearSelectedArea;
begin
if MayIDoClearSelectedArea then
begin
_ClearSelectedArea;
if Assigned(OnGridModified) then OnGridModified(Self);
end
else raise EIDA_Grid.Create('Area clearing is impossible...');
end;
procedure TIDA_Grid.ClearAllCells;
begin
if MayIDoClearAllCells then
begin
_ClearAllCells;
if Assigned(OnGridModified) then OnGridModified(Self);
end
else raise EIDA_Grid.Create('Table clearing is impossible...');
end;
procedure TIDA_Grid.DeleteSelection;
begin
if (Selection.Left = FixedCols) and (Selection.Right = ColCount - 1) and
(Selection.Top = FixedRows) and (Selection.Bottom = RowCount - 1) then
begin
if MayIDoDeleteAllData then
begin
if MessageDlg('Clear table ?', mtConfirmation,
[mbYes, mbNo, mbCancel], 0) = mrYes then
begin
DeleteAllData;
ClearSelection;
end;
end
else MessageDlg('Table clearing is impossible...', mtWarning, [mbOk], 0);
Exit;
end;
if (Selection.Left = FixedCols) and (Selection.Right = ColCount - 1) then
begin
if MayIDoDeleteRows(Selection.Top, Selection.Bottom - Selection.Top + 1) then
begin
if Selection.Top <> Selection.Bottom then
if MessageDlg('Delete selected rows ?', mtConfirmation,
[mbYes, mbNo, mbCancel], 0) <> mrYes then Exit;
DeleteRows(Selection.Top, Selection.Bottom - Selection.Top + 1)
end else
if MayIDoClearSelectedArea then
begin
if MessageDlg('Clear selected area ?', mtConfirmation,
[mbYes, mbNo, mbCancel], 0) = mrYes then
begin
ClearSelectedArea;
ClearSelection;
end;
end else
MessageDlg('Rows deleting is impossible...', mtWarning, [mbOk], 0);
Exit;
end;
if (Selection.Top = FixedRows) and (Selection.Bottom = RowCount - 1) then
begin
if MayIDoDeleteColumns(Selection.Left, Selection.Right - Selection.Left + 1) then
begin
if Selection.Left <> Selection.Right then
if MessageDlg('Delete selected columns ?', mtConfirmation,
[mbYes, mbNo, mbCancel], 0) <> mrYes then Exit;
DeleteColumns(Selection.Left, Selection.Right - Selection.Left + 1);
end else
if MayIDoClearSelectedArea then
begin
if MessageDlg('Clear selected area ?', mtConfirmation,
[mbYes, mbNo, mbCancel], 0) = mrYes then
begin
ClearSelectedArea;
ClearSelection;
end;
end else
MessageDlg('Columns deleting is impossible...', mtWarning, [mbOk], 0);
Exit;
end;
if ((Selection.Top <> FixedRows) or (Selection.Bottom <> RowCount - 1)) and
((Selection.Left <> FixedCols) or (Selection.Right <> ColCount - 1)) then
begin
if MayIDoClearSelectedArea then
begin
if MessageDlg('Clear selected area ?', mtConfirmation,
[mbYes, mbNo, mbCancel], 0) = mrYes then
begin
ClearSelectedArea;
ClearSelection;
end;
end else
MessageDlg('Clearing is impossible...', mtWarning, [mbOk], 0);
end;
end;
procedure TColoredGrid.DrawCell;
function GetColorByDefault(ACol, ARow: LongInt): TColor;
begin
if Odd(ARow) then Result := OddRowColor
else Result := EvenRowColor;
end;
var SaveColor, TempColor: TColor;
X, Y: Integer;
begin
if Assigned(OnDrawCell) then OnDrawCell(Self, ACol, ARow, ARect, AState)
else begin
SaveColor := Canvas.Brush.Color;
if not (gdFixed in AState) then
begin
if (gdSelected in AState) or (gdFocused in AState) then
Canvas.Brush.Color := SelectedRegionColor
else
if GetMyGridDataSource <> nil then
begin
if GetMyGridDataSource.GetCellColor(ACol, ARow, TempColor) then
Canvas.Brush.Color := TempColor
else
if GetMyGridDataSource.IsCellDisabled(ACol, ARow) then
Canvas.Brush.Color := DisabledColor
else Canvas.Brush.Color := GetColorByDefault(ACol, ARow);
end else Canvas.Brush.Color := GetColorByDefault(ACol, ARow);
Canvas.FillRect(ARect);
X := ARect.Right - Canvas.TextWidth(Cells[ACol, ARow]) - 2;
Y := ARect.Bottom - Canvas.TextHeight(Cells[ACol, ARow]) - 2;
Canvas.TextRect(ARect, X, Y, Cells[ACol, ARow]);
end else inherited DrawCell(ACol, ARow, ARect, AState);
Canvas.Brush.Color := SaveColor;
end;
end;
constructor TColoredGrid.Create;
begin
inherited Create(AOwner);
OddRowColor := CL_ODD_ROW;
EvenRowColor := CL_EVEN_ROW;
SelectedRegionColor := CL_SELECTED;
end;
procedure TServeredGrid.SetGridDataSource(
GridDataSource: IGridDataSource);
begin
if (FGridDataSource <> nil) and
(GridDataSource <> FGridDataSource) then SaveTableParams;
FGridDataSource := GridDataSource;
if GridDataSource <> nil then
begin
GetTableParams;
ShowTable;
FillRowHeaders;
FillColHeaders;
FillTable;
GetWidthsHeights;
Changeable := True;
end else HideTable;
end;
procedure TServeredGrid._DeleteAllData;
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do AllDataDeleted;
inherited;
end;
procedure TServeredGrid._ClearSelectedArea;
begin
inherited;
with Selection do DataChanged(Left, Top, Right, Bottom);
end;
procedure TServeredGrid._ClearAllCells;
begin
inherited;
DataChanged(FixedCols, FixedRows, ColCount - 1, RowCount - 1);
end;
procedure TServeredGrid._InsertRows(StartRow, RowsCount: LongInt; Clear: Boolean);
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do RowsInserted(StartRow, RowsCount);
inherited;
end;
procedure TServeredGrid._AddRow;
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do RowAdded;
inherited;
end;
procedure TServeredGrid._DeleteRows(StartRow, RowsCount: LongInt);
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do RowsDeleted(StartRow, RowsCount);
inherited;
end;
procedure TServeredGrid._InsertColumns(
StartCol, ColsCount: LongInt; Clear: Boolean);
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do ColumnsInserted(StartCol, ColsCount);
inherited;
end;
function TServeredGrid.GetMyGridDataSource: IGridDataSource;
begin
if not (csDestroying in ComponentState) then Result := FGridDataSource
else Result := nil;
end;
procedure TServeredGrid._AddColumn;
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do ColumnAdded;
inherited;
end;
procedure TServeredGrid._DeleteColumns(StartCol, ColsCount: LongInt);
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do ColumnsDeleted(StartCol, ColsCount);
inherited;
end;
function TColoredGrid.GetOddRowColor: TColor;
begin
Result := FOddRowColor;
end;
procedure TColoredGrid.SetOddRowColor(const AOddRowColor: TColor);
begin
FOddRowColor := AOddRowColor;
end;
function TColoredGrid.GetEvenRowColor: TColor;
begin
Result := FEvenRowColor;
end;
procedure TColoredGrid.SetEvenRowColor(const AEvenRowColor: TColor);
begin
FEvenRowColor := AEvenRowColor;
end;
function TColoredGrid.GetSelectedRegionColor: TColor;
begin
Result := FSelectedRegionColor;
end;
procedure TColoredGrid.SetSelectedRegionColor(const ASelectedRegionColor: TColor);
begin
FSelectedRegionColor := ASelectedRegionColor;
end;
function TColoredGrid.GetDisabledColor: TColor;
begin
Result := FDisabledColor;
end;
procedure TColoredGrid.SetDisabledColor(const ADisabledColor: TColor);
begin
FDisabledColor := ADisabledColor;
end;
procedure TIDA_Grid.CopyToClipBoard;
var St, St2, St3: string;
i, j: LongInt;
begin
with Selection do
begin
if (Top = Bottom) and (Left = Right) then
begin
MessageDlg('It is necessary to choose area for copying...', mtWarning, [mbOk], 0);
Exit;
end;
St := '';
for i := Top to Bottom do
begin
St2 := '';
for j := Left to Right do
begin
if j <> Right then St3 := Cells[j, i] + #9
else St3 := Cells[j, i];
St2 := St2 + St3;
end;
St := St + St2 + #13#10;
end;
ClipBoard.SetTextBuf(PChar(St));
end; {with Selection do...}
end;
procedure TIDA_Grid.PasteFromClipBoard;
const DelimiterChars: set of Char = [#9, #10, #13];
procedure ExtractGridSizes(Buffer: array of Char;
const Count: LongInt; var BufferCols, BufferRows: LongInt);
var i: LongInt;
Flag: Boolean;
begin
BufferCols := 0; BufferRows := 0;
Flag := True;
for i := 0 to Count - 1 do
begin
if (Buffer[i] in DelimiterChars) and Flag then Inc(BufferCols);
if Buffer[i] = #10 then Flag := False;
if Buffer[i] = #13 then
begin
Flag := False;
Inc(BufferRows);
end;
end;
end;
function ExtractString(Buffer: array of Char;
const Count: LongInt; var Index: LongInt): string;
var St: ShortString;
i, j, k: LongInt;
const BadSymbols: set of Char = [#10, #13];
begin
St := '';
for i := Index to Count - 1 do
begin
if Buffer[i] in DelimiterChars then
begin
for j := Index to i - 1 do
begin
if not (Buffer[j] in BadSymbols) then
begin
St[Length(St) + 1] := Buffer[j];
Inc(St[0]);
end;
end;
j := i;
if Buffer[j] = #9 then k := j + 1
else for k := j to Count - 1 do
if not (Buffer[k] in DelimiterChars) then Break;
Index := k;
Result := St;
Exit;
end;
end;
end;
procedure ClearFixed;
var i, j: LongInt;
begin
for i := 0 to FixedRows - 1 do
for j := 0 to ColCount - 1 do Cells[j, i] := '';
for i := 0 to FixedCols - 1 do
for j := FixedRows to RowCount - 1 do Cells[i, j] := '';
end;
const BufCount = 10240;
var Count: Longint;
Buffer: array[0..BufCount] of Char;
St: string;
Index: LongInt;
BufferColCount, BufferRowCount: LongInt;
TempCol, TempRow: LongInt;
i, j: LongInt;
SavedSelection, InsertedArea: TGridRect;
SelectionSize: LongInt;
begin
if not Clipboard.HasFormat(CF_TEXT) then
begin
MessageDlg('Clipboard doesn''t contain text data...', mtError, [mbOk], 0);
Exit;
end;
if MessageDlg('Overwrite this data ?', mtWarning,
[mbYes, mbNo, mbCancel], 0) <> mrYes then Exit;
Count := ClipBoard.GetTextBuf(@Buffer, BufCount);
ExtractGridSizes(Buffer, Count, BufferColCount, BufferRowCount);
SavedSelection := Selection;
SelectionSize := SavedSelection.Bottom - SavedSelection.Top + 1;
if (BufferRowCount > SelectionSize) and (not RowNumFixed) then
InsertRows(SavedSelection.Bottom, BufferRowCount - SelectionSize, True);
SelectionSize := SavedSelection.Right - SavedSelection.Left + 1;
if (BufferColCount > SelectionSize) and (not ColNumFixed) then
InsertColumns(SavedSelection.Right, BufferColCount - SelectionSize, True);
Index := 0;
try
for j := 0 to BufferRowCount - 1 do
for i := 0 to BufferColCount - 1 do
begin
St := ExtractString(Buffer, Count, Index);
TempCol := SavedSelection.Left + i;
TempRow := SavedSelection.Top + j;
if (TempCol <= ColCount - 1) and (TempRow <= RowCount - 1) then
Cells[TempCol, TempRow] := St;
end;
except
MessageDlg('Vague number of cell, since' +
'data do not have tabular format...',
mtError, [mbOk], 0);
Exit;
end;
InsertedArea.Left := SavedSelection.Left;
InsertedArea.Top := SavedSelection.Top;
if ColCount - 1 < SavedSelection.Left + BufferColCount - 1 then
InsertedArea.Right := ColCount - 1
else InsertedArea.Right := SavedSelection.Left + BufferColCount - 1;
if RowCount - 1 < SavedSelection.Top + BufferRowCount - 1 then
InsertedArea.Bottom := RowCount - 1
else InsertedArea.Bottom := SavedSelection.Top + BufferRowCount - 1;
Selection := InsertedArea;
with Selection do DataChanged(Left, Top, Right, Bottom);
if Assigned(OnGridModified) then OnGridModified(Self);
end;
procedure TIDA_Grid.SelectAll;
var R: TGridRect;
begin
R.Left := FixedCols; R.Right := ColCount - 1;
R.Top := FixedRows; R.Bottom := RowCount - 1;
Selection := R;
end;
procedure TIDA_Grid.ClearSelection;
var R: TGridRect;
begin
R.Left := Col; R.Right := Col;
R.Top := Row; R.Bottom := Row;
Selection := R;
end;
procedure TIDA_Grid.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
end;
procedure TIDA_Grid.AddRow;
begin
if MayIDoAddRow then
begin
_AddRow;
if Assigned(OnGridResized) then OnGridResized(Self);
if Assigned(OnGridModified) then OnGridModified(Self);
end else raise EIDA_Grid.Create('Row adding is impossible...');
end;
procedure TIDA_Grid.AddColumn;
begin
if MayIDoAddColumn then
begin
_AddColumn;
if Assigned(OnGridResized) then OnGridResized(Self);
if Assigned(OnGridModified) then OnGridModified(Self);
end else raise EIDA_Grid.Create('Column adding is impossible...');
end;
procedure TServeredGrid.ShowTable;
begin
Enabled := True;
Color := clWindow;
end;
procedure TServeredGrid.HideTable;
begin
RowCount := FixedRows + 1;
ColCount := FixedCols + 1;
Cells[1, 1] := '';
Enabled := False;
Color := clLtGray;
end;
{$IFNDEF Lazarus}
function TNumericGrid.CanEditAcceptKey(Key: Char): Boolean;
begin
case ColOptions[Col] of
coReal : if Key in REAL_SET then CanEditAcceptKey := True
else CanEditAcceptKey := False;
coInteger : if Key in INT_SET then CanEditAcceptKey := True
else CanEditAcceptKey := False;
coChars : if Key in CHAR_SET then CanEditAcceptKey := True
else CanEditAcceptKey := False;
coText : CanEditAcceptKey := True;
coDisabled : CanEditAcceptKey := False;
else CanEditAcceptKey := True;
end;
end;
{$ENDIF}
procedure TNumericGrid.SetColOption(Index: LongInt; Value: TColOption);
var i: LongInt;
begin
if Assigned(ColOptarray) then
begin
if (Index < 0) or (Index >= Length(ColOptarray)) then
raise ENumericGrid.Create('Invalid option index...')
else ColOptArray[Index] := Value;
if Value = coDisabled then
begin
{$IFNDEF Lazarus}
TabStops[Index] := False;
{$ENDIF}
if Assigned(FColorMatrix) then
for i := 0 to RowCount - 1 do
CellsColors[Index, i] := DisabledColor;
end;
end;
end;
function TNumericGrid.GetColOption(Index: LongInt): TColOption;
begin
if (Index < 0) or (Index >= Length(ColOptarray)) then
raise ENumericGrid.Create('Invalid option index...')
else Result := ColOptarray[Index];
end;
procedure TNumericGrid.MouseUp;
begin
SelFlag := False;
inherited MouseUp(Button, Shift, X, Y);
end;
procedure TNumericGrid.MouseDown;
var Coord: TGridCoord;
R: TGridRect;
begin
Coord := MouseCoord(X, Y);
if Shift = [ssLeft, ssDouble] then
begin
if (Coord.X > FixedCols - 1) and
(Coord.Y > FixedRows - 1) then
begin
R.Left := Coord.X; R.Right := Coord.X;
R.Top := Coord.Y; R.Bottom := Coord.Y;
Selection := R;
Options := EditingOptions;
Col := Coord.X;
Row := Coord.Y;
end
end
else
if Shift = [ssLeft] then
begin
Coord := MouseCoord(X, Y);
if (Coord.X <= FixedCols - 1) or
(Coord.Y <= FixedRows - 1) then
begin
Options := SelectOptions;
if (Coord.Y <= FixedRows - 1) and
(Coord.X >= FixedCols) then
begin
SelFlag := True;
StartCoord := MouseCoord(X, Y);
SavedCoord := StartCoord;
R.Top := FixedRows; R.Bottom := RowCount - 1;
R.Left := StartCoord.X; R.Right := StartCoord.X;
Selection := R;
end;
if (Coord.X <= FixedCols - 1) and
(Coord.Y >= FixedRows) then
begin
SelFlag := True;
StartCoord := MouseCoord(X, Y);
SavedCoord := StartCoord;
R.Left := FixedCols; R.Right := ColCount - 1;
R.Top := StartCoord.Y; R.Bottom := StartCoord.Y;
Selection := R;
end;
if (Coord.X <= FixedCols - 1) and
(Coord.Y <= FixedRows - 1) then
begin
R.Left := FixedCols; R.Right := ColCount - 1;
R.Top := FixedRows; R.Bottom := RowCount - 1;
Selection := R;
end;
end
else
begin
R.Left := Coord.X; R.Right := Coord.X;
R.Top := Coord.Y; R.Bottom := Coord.Y;
Selection := R;
Options := StaticOptions;
end;
end;
inherited MouseDown(Button, Shift, X, Y);
end;
procedure TNumericGrid.MouseMove(Shift: TShiftState; X, Y: Integer);
var Coord: TGridCoord;
R: TGridRect;
begin
if SelFlag then
begin
Coord := MouseCoord(X, Y);
if (Coord.X <> SavedCoord.X) or (Coord.Y <> SavedCoord.Y) then
begin
if (StartCoord.Y <= FixedRows - 1) and
(StartCoord.X >= FixedCols) and
(Coord.X >= FixedCols) then
begin
R.Top := FixedRows; R.Bottom := RowCount - 1;
if Coord.X < StartCoord.X then
begin R.Left := Coord.X; R.Right := StartCoord.X end;
if Coord.X > StartCoord.X then
begin R.Left := StartCoord.X; R.Right := Coord.X end;
if Coord.X = StartCoord.X then
begin R.Left := StartCoord.X; R.Right := StartCoord.X end;
Selection := R;
if (Coord.X - LeftCol = VisibleColCount) and
(Coord.X < ColCount - 1) then LeftCol := LeftCol + 1;
if (Coord.X = LeftCol) and
(LeftCol > FixedCols) then LeftCol := LeftCol - 1;
end;
if (StartCoord.X <= FixedCols - 1) and
(StartCoord.Y >= FixedRows) and
(Coord.Y >= FixedRows) then
begin
R.Left := FixedCols; R.Right := ColCount - 1;
if Coord.Y < StartCoord.Y then
begin R.Top := Coord.Y; R.Bottom := StartCoord.Y end;
if Coord.Y > StartCoord.Y then
begin R.Top := StartCoord.Y; R.Bottom := Coord.Y end;
if Coord.Y = StartCoord.Y then
begin R.Top := StartCoord.Y; R.Bottom := StartCoord.Y end;
Selection := R;
if (Coord.Y - TopRow = VisibleRowCount) and
(Coord.Y < RowCount - 1) then TopRow := TopRow + 1;
if (Coord.Y = TopRow) and
(TopRow > FixedRows) then TopRow := TopRow - 1;
end;
SavedCoord := Coord;
end;{if (Coord.X <> SavedCoord.X) or (Coord.Y <> SavedCoord.Y) then...}
end;
inherited MouseMove(Shift, X, Y);
end;
procedure TNumericGrid.InsertRows(StartPos, Count: LongInt; Clear: Boolean);
var i, j: LongInt;
begin
RowCount := RowCount + Count;
for i := RowCount - 1 downto StartPos + Count do
for j := 0 to ColCount - 1 do Cells[j, i] := Cells[j, i - Count];
if Clear then
for i := 0 to Count - 1 do
for j := 0 to ColCount - 1 do Cells[j, StartPos + i] := '';
end;
procedure TNumericGrid.DeleteRows(StartPos, Count: LongInt);
var i, j: LongInt;
begin
for i := StartPos to RowCount - 1 - Count do
for j := 0 to ColCount - 1 do Cells[j, i] := Cells[j, i + Count];
RowCount := RowCount - Count;
end;
procedure TNumericGrid.DeleteSelection;
var i, j: LongInt;
begin
if (Selection.Left = FixedCols) and (Selection.Right = ColCount - 1) then
begin
if not RowNumFixed then
begin
if Selection.Top <> Selection.Bottom then
if MessageDlg('Delete all selected rows ?', mtWarning,
[mbYes, mbNo, mbCancel], 0) <> mrYes then Exit;
for i := 0 to RowCount - 2 - Selection.Bottom do
for j := 1 to ColCount - 1 do
Cells[j, Selection.Top + i] := Cells[j, Selection.Bottom + i + 1];
RowCount := RowCount - (Selection.Bottom - Selection.Top + 1);
end
else MessageDlg('Rows deleting is not allowed...', mtWarning, [mbOk], 0);
ClearSelection;
Exit;
end;
if (Selection.Top = FixedRows) and (Selection.Bottom = RowCount - 1) then
begin
if not ColNumFixed then
begin
if Selection.Left <> Selection.Right then
if MessageDlg('Delete all selected columns ?', mtWarning,
[mbYes, mbNo, mbCancel], 0) <> mrYes then Exit;
for i := 0 to ColCount - 2 - Selection.Right do
for j := 1 to RowCount - 1 do
Cells[Selection.Left + i, j] := Cells[Selection.Right + i + 1, j];
ColCount := ColCount - (Selection.Right - Selection.Left + 1);
end
else MessageDlg('Columns deleting is not allowed...', mtWarning, [mbOk], 0);
ClearSelection;
Exit;
end;
if ((Selection.Top <> FixedRows) or (Selection.Bottom <> RowCount - 1)) and
((Selection.Left <> FixedCols) or (Selection.Right <> ColCount - 1)) then
begin
if Selection.Top <> Selection.Bottom then
if MessageDlg('Clear all selected cells ?', mtWarning,
[mbYes, mbNo, mbCancel], 0) <> mrYes then Exit;
for i := Selection.Top to Selection.Bottom do
for j := Selection.Left to Selection.Right do Cells[j, i] := '';
ClearSelection;
end;
end;
procedure TColorStringGrid.DrawCell;
var SaveColor: TColor;
X, Y: Integer;
begin
SaveColor := Canvas.Brush.Color;
if not (gdFixed in AState) then
begin
if (gdSelected in AState) or (gdFocused in AState) then
Canvas.Brush.Color := SelectedRegionColor
else Canvas.Brush.Color := GetCellColor(ACol, ARow);
Canvas.FillRect(ARect);
X := ARect.Right - Canvas.TextWidth(Cells[ACol, ARow]) - 2;
Y := ARect.Bottom - Canvas.TextHeight(Cells[ACol, ARow]) - 2;
Canvas.TextRect(ARect, X, Y, Cells[ACol, ARow]);
if Assigned(OnDrawCell) then OnDrawCell(Self, ACol, ARow, ARect, AState);
end else inherited DrawCell(ACol, ARow, ARect, AState);
Canvas.Brush.Color := SaveColor;
end;
function TColorStringGrid.GetCellColor(const ColNum, RowNum: LongInt): TColor;
var CellColor: TColor;
begin
if Assigned(OnGetCellColor) then
begin
OnGetCellColor(Self, ColNum, RowNum, CellColor);
Result := CellColor;
end
else
if Assigned(FColorMatrix) then
Result := CellsColors[ColNum, RowNum]
else
if Odd(RowNum) then Result := OddRowColor
else Result := NotOddRowColor;
end;
constructor TColorStringGrid.Create;
begin
inherited Create(AOwner);
if csDesigning in ComponentState then
begin
OddRowColor := clWhite;
NotOddRowColor := clYellow;
SelectedRegionColor := $0064CCEA - $003A3A3A;
end;
end;
destructor TColorStringGrid.Destroy;
begin
FinalizeColorMatrix;
inherited;
end;
function TColorStringGrid.GetCellsColors(ACol, ARow: LongInt): TColor;
begin
if (ACol < 0) or (ACol >= ColCount) then
raise EColorStringGrid.Create('Invalid column number...');
if (ARow < 0) or (ARow >= RowCount) then
raise EColorStringGrid.Create('Invalid row number...');
Result := FColorMatrix[ARow, ACol];
end;
procedure TColorStringGrid.SetCellsColors(ACol, ARow: LongInt; AColor: TColor);
begin
if (ACol < 0) or (ACol >= ColCount) then
raise EColorStringGrid.Create('Invalid column number...');
if (ARow < 0) or (ARow >= RowCount) then
raise EColorStringGrid.Create('Invalid row number...');
FColorMatrix[ARow, ACol] := AColor;
end;
constructor TNumericGrid.Create;
begin
inherited Create(AOwner);
if csDesigning in ComponentState then DisabledColor := clGray;
end;
procedure TColorStringGrid.SetOddRowColor(Color: TColor);
var i, j: LongInt;
begin
FOddRowColor := Color;
if Assigned(FColorMatrix) then
begin
for i := 0 to Length(FColorMatrix) - 1 do
for j := 0 to Length(FColorMatrix[i]) - 1 do
if Odd(i) then FColorMatrix[i, j] := Color;
end;
Repaint;
end;
procedure TColorStringGrid.SetNotOddRowColor(Color: TColor);
var i, j: LongInt;
begin
FNotOddRowColor := Color;
if Assigned(FColorMatrix) then
begin
for i := 0 to Length(FColorMatrix) - 1 do
for j := 0 to Length(FColorMatrix[i]) - 1 do
if not Odd(i) then FColorMatrix[i, j] := Color;
end;
Repaint;
end;
procedure TColorStringGrid.SetSelectedRegionColor(Color: TColor);
begin
FSelectedRegionColor := Color;
Repaint;
end;
procedure TNumericGrid.SetDisabledColor(Color: TColor);
var i, j: LongInt;
begin
FDisabledColor := Color;
if Assigned(FColorMatrix) and Assigned(ColOptArray) then
begin
for i := 0 to RowCount - 1 do
if ColCount = Length(ColOptArray) then
for j := 0 to ColCount - 1 do
if ColOptArray[j] = coDisabled then CellsColors[j, i] := Color;
end;
Repaint;
end;
procedure TColorStringGrid.EnumerateRows;
var i: LongInt;
begin
if FixedCols <> 0 then
for i := FixedRows to RowCount - 1 do Cells[0, i] := IntToStr(i);
end;
function TColorStringGrid.CopyToClipBoard: Boolean;
var St, St2, St3: string;
i, j: LongInt;
begin
Result := False;
with Selection do
begin
if (Top = Bottom) and (Left = Right) then
begin
MessageDlg('It is necessary to choose area for copying...', mtWarning, [mbOk], 0);
Exit;
end;
try
St := '';
for i := Top to Bottom do
begin
St2 := '';
for j := Left to Right do
begin
if j <> Right then St3 := Cells[j, i] + #9
else St3 := Cells[j, i];
St2 := St2 + St3;
end;
St := St + St2 + #13#10;
end;
ClipBoard.SetTextBuf(PChar(St));
except Exit end;
end;{With Selection do...}
Result := True;
end;
function TColorStringGrid.PasteFromClipBoard: Boolean;
const DelimiterChars: set of Char = [#9, #10, #13];
procedure ExtractGridSizes(Buffer: array of Char; const Count: LongInt; var BufferCols, BufferRows: LongInt);
var i: LongInt;
Flag: Boolean;
begin
BufferCols := 0; BufferRows := 0;
Flag := True;
for i := 0 to Count - 1 do
begin
if (Buffer[i] in DelimiterChars) and Flag then Inc(BufferCols);
if Buffer[i] = #10 then Flag := False;
if Buffer[i] = #13 then
begin
Flag := False;
Inc(BufferRows);
end;
end;
end;
function ExtractString(Buffer: array of Char;
const Count: LongInt; var Index: LongInt): string;
var St: ShortString;
i, j, k: LongInt;
const BadSymbols: set of Char = [#10, #13];
begin
St := '';
for i := Index to Count - 1 do
begin
if Buffer[i] in DelimiterChars then
begin
for j := Index to i - 1 do
begin
if not (Buffer[j] in BadSymbols) then
begin
St[Length(St) + 1] := Buffer[j];
Inc(St[0]);
end;
end;
j := i;
if Buffer[j] = #9 then k := j + 1
else for k := j to Count - 1 do
if not (Buffer[k] in DelimiterChars) then Break;
Index := k;
Result := St;
Exit;
end;
end;
Result := St;
end;
procedure ClearFixed;
var i, j: LongInt;
begin
for i := 0 to FixedRows - 1 do
for j := 0 to ColCount - 1 do Cells[j, i] := '';
for i := 0 to FixedCols - 1 do
for j := FixedRows to RowCount - 1 do Cells[i, j] := '';
end;
const BufCount = 10240;
var Count: Longint;
Buffer: array[0..BufCount] of Char;
St: string;
Index: LongInt;
BufferColCount, BufferRowCount: LongInt;
TempCol, TempRow: LongInt;
i, j: LongInt;
begin
Result := False;
if not Clipboard.HasFormat(CF_TEXT) then
begin
MessageDlg('Clipboard contains no text data...', mtError, [mbOk], 0);
Exit;
end;
if MessageDlg('Overwrite this data ?', mtWarning,
[mbYes, mbNo, mbCancel], 0) <> mrYes then Exit;
Count := ClipBoard.GetTextBuf(@Buffer, BufCount);
ExtractGridSizes(Buffer, Count, BufferColCount, BufferRowCount);
if Row < FixedRows then Row := FixedRows;
RowCount := BufferRowCount + Row;
ColCount := BufferColCount + FixedCols;
Col := FixedCols;
Index := 0;
try
for j := 0 to BufferRowCount - 1 do
for i := 0 to BufferColCount - 1 do
begin
St := ExtractString(Buffer, Count, Index);
TempCol := FixedCols + i;
TempRow := Row + j;
if (TempCol <= ColCount - 1) and (TempRow <= RowCount - 1) then
begin
if not CheckingTextValidity(St, TempCol, TempRow) then
Cells[TempCol, TempRow] := ''
else Cells[TempCol, TempRow] := St;
end;
end;
except
MessageDlg('Vague number of cell, since data do not have tabular format...',
mtError, [mbOk], 0);
Result := False;
Exit;
end;
ClearFixed;
EnumerateRows;
Result := True;
end;
procedure TColorStringGrid.SelectAll;
var R: TGridRect;
begin
if goRangeSelect in Options then
begin
R.Left := FixedCols; R.Right := ColCount - 1;
R.Top := FixedRows; R.Bottom := RowCount - 1;
Selection := R;
end;
end;
procedure TColorStringGrid.ClearSelection;
var R: TGridRect;
begin
R.Left := Col; R.Right := Col;
R.Top := Row; R.Bottom := Row;
Selection := R;
end;
function TColorStringGrid.CheckingTextValidity(St: string;
ACol, ARow: LongInt): Boolean;
begin
Result := True;
end;
{$IFNDEF Lazarus}
function TColorStringGrid.CreateEditor: TInplaceEdit;
begin
Result := inherited CreateEditor;
end;
{$ENDIF}
function TNumericGrid.CheckingTextValidity(St: string;
ACol, ARow: LongInt): Boolean;
begin
if St = '' then
begin Result := True; Exit end;
if ColOptions[ACol] = coInteger then
begin
try StrToInt(St); except Result := False; Exit end;
Result := True;
Exit;
end;
if ColOptions[ACol] = coReal then
begin
try StrToFloat(St); except Result := False; Exit end;
Result := True;
Exit;
end;
Result := True;
end;
procedure TColorStringGrid.ResetAll;
var i, j: LongInt;
begin
ColCount := 10;
RowCount := 2;
FixedCols := 1;
FixedRows := 1;
Col := 1; Row := 1;
ClearSelection;
for i := 0 to ColCount - 1 do ColWidths[i] := DefaultColWidth;
for i := 0 to RowCount - 1 do RowHeights[i] := DefaultRowHeight;
for i := 0 to ColCount - 1 do
for j := 0 to RowCount - 1 do Cells[i, j] := '';
end;
destructor TNumericGrid.Destroy;
begin
Finalize(ColOptarray);
inherited Destroy;
end;
procedure TNumericGrid.SetOptCount;
begin
SetLength(ColOptarray, AColOptCount);
end;
procedure TNumericGrid.SetColCount(Value: Longint);
begin
SetOptCount(Value);
inherited;
end;
procedure TNumericGrid.KeyPress(var Key: Char);
var i: LongInt;
St: string;
begin
inherited KeyPress(Key);
case Key of
#9 : begin
if not RowNumFixed then
if (Col = 1) and (Row = 1) then
begin
RowCount := RowCount + 1;
Str(RowCount - 1, St);
Cells[0, RowCount - 1] := St;
Col := 1;
Row := RowCount - 1;
for i := 1 to ColCount - 1 do Cells[i, Row] := '';
end
end;
',' : Key := '.';
end;
end;
procedure TNumericGrid.ResetColWidths;
var i: LongInt;
begin
for i := 0 to ColCount - 1 do SetColWidthByDefault(i);
end;
procedure TIDA_Grid.AutoColWidths;
var i: LongInt;
begin
for i := 0 to ColCount - 1 do SetAutoColWidth(i);
end;
procedure TNumericGrid.SetColWidthByDefault(ACol: LongInt);
var Width: LongInt;
begin
Width := GetMaxTextWidth(Self, ACol);
if Width = 0 then Width := 40 else Width := Width + 10;
ColWidths[ACol] := Width;
end;
procedure TIDA_Grid.SetAutoColWidth(ACol: LongInt);
var Width: LongInt;
begin
Width := GetMaxTextWidth(Self, ACol);
if Width = 0 then Width := MIN_WIDTH;
Width := Width + 10;
ColWidths[ACol] := Width;
end;
procedure TColorStringGrid.SetColCount(Value: Longint);
var i, j: LongInt;
SavedLength: LongInt;
begin
if not (csDesigning in ComponentState) then
begin
if not Assigned(FColorMatrix) then InitColorMatrix;
for i := 0 to RowCount - 1 do
if Length(FColorMatrix[i]) <> Value then
begin
SavedLength := Length(FColorMatrix[i]);
SetLength(FColorMatrix[i], Value);
for j := SavedLength to Length(FColorMatrix[i]) - 1 do
if Odd(i) then FColorMatrix[i, j] := OddRowColor
else FColorMatrix[i, j] := NotOddRowColor;
end;
end;
TStringGrid(Self).ColCount := Value;
end;
procedure TColorStringGrid.InitColorMatrix;
var i: LongInt;
begin
SetLength(FColorMatrix, RowCount);
for i := 0 to RowCount - 1 do SetLength(FColorMatrix[i], ColCount);
end;
procedure TColorStringGrid.FinalizeColorMatrix;
var i: LongInt;
begin
if Assigned(FColorMatrix) then
begin
for i := 0 to RowCount - 1 do Finalize(FColorMatrix[i]);
Finalize(FColorMatrix);
end;
end;
function TColorStringGrid.GetColCount: LongInt;
begin
Result := TStringGrid(Self).ColCount;
end;
procedure TColorStringGrid.SetRowCount(Value: Longint);
var i, j: LongInt;
SavedLength: LongInt;
begin
if not (csDesigning in ComponentState) then
begin
if not Assigned(FColorMatrix) then InitColorMatrix;
if Value < RowCount then
begin
for i := Value to RowCount - 1 do Finalize(FColorMatrix[i]);
SetLength(FColorMatrix, Value);
end;
if Value > RowCount then
begin
SavedLength := Length(FColorMatrix);
SetLength(FColorMatrix, Value);
for i := SavedLength to Length(FColorMatrix) - 1 do
begin
SetLength(FColorMatrix[i], ColCount);
for j := 0 to ColCount - 1 do
if Odd(i) then FColorMatrix[i, j] := OddRowColor
else FColorMatrix[i, j] := NotOddRowColor
end;
end;
end;
TStringGrid(Self).RowCount := Value;
end;
function TColorStringGrid.GetRowCount: LongInt;
begin
Result := TStringGrid(Self).RowCount;
end;
function GetMaxTextWidth(
const Grid: TStringGrid; const ColNum: LongInt): LongInt;
var i: LongInt;
begin
Result := 0;
with Grid do
for i := 0 to RowCount - 1 do
if Canvas.TextWidth(Cells[ColNum, i]) > Result then
Result := Canvas.TextWidth(Cells[ColNum, i]);
end;
function GetMaxTextHeight(
const Grid: TStringGrid; const RowNum: LongInt): LongInt;
var i: LongInt;
begin
Result := 0;
with Grid do
for i := 0 to ColCount - 1 do
if Canvas.TextHeight(Cells[i, RowNum]) > Result then
Result := Canvas.TextHeight(Cells[i, RowNum]);
end;
procedure TIDA_Grid._AddColumn;
begin
ColCount := ColCount + 1;
FillArea(ColCount - 1, FixedRows, ColCount - 1, RowCount - 1);
FillColHeaders;
end;
procedure TIDA_Grid._AddRow;
begin
RowCount := RowCount + 1;
FillArea(FixedCols, RowCount - 1, ColCount - 1, RowCount - 1);
FillRowHeaders;
end;
procedure TIDA_Grid._DeleteAllData;
begin
if not ColNumFixed then ColCount := FixedCols + 1;
if not RowNumFixed then RowCount := FixedRows + 1;
FillArea(FixedCols, FixedRows, ColCount - 1, RowCount - 1);
FillRowHeaders;
FillColHeaders;
end;
procedure TIDA_Grid._DeleteColumns(StartCol, ColsCount: Integer);
var i, j: LongInt;
begin
for i := StartCol to ColCount - 1 - ColsCount do
for j := 0 to RowCount - 1 do Cells[i, j] := Cells[i + ColsCount, j];
ColCount := ColCount - ColsCount;
FillColHeaders;
end;
procedure TIDA_Grid._DeleteRows(StartRow, RowsCount: Integer);
var i, j: LongInt;
begin
for i := StartRow to RowCount - 1 - RowsCount do
for j := 0 to ColCount - 1 do Cells[j, i] := Cells[j, i + RowsCount];
RowCount := RowCount - RowsCount;
FillRowHeaders;
end;
procedure TIDA_Grid._InsertColumns(StartCol, ColsCount: Integer;
Clear: Boolean);
var i, j: LongInt;
begin
ColCount := ColCount + ColsCount;
for i := ColCount - 1 downto StartCol + ColsCount do
for j := 0 to RowCount - 1 do Cells[i, j] := Cells[i - ColsCount, j];
if Clear then
ClearArea(StartCol, FixedRows, StartCol + ColsCount - 1, RowCount - 1)
else FillArea(StartCol, FixedRows, StartCol + ColsCount - 1, RowCount - 1);
FillColHeaders;
end;
procedure TIDA_Grid._InsertRows(StartRow, RowsCount: Integer;
Clear: Boolean);
var i, j: LongInt;
begin
RowCount := RowCount + RowsCount;
for i := RowCount - 1 downto StartRow + RowsCount do
for j := 0 to ColCount - 1 do Cells[j, i] := Cells[j, i - RowsCount];
if Clear then
ClearArea(FixedCols, StartRow, ColCount - 1, StartRow + RowsCount - 1)
else FillArea(FixedCols, StartRow, ColCount - 1, StartRow + RowsCount - 1);
FillRowHeaders;
end;
procedure TIDA_Grid._ClearAllCells;
begin
ClearArea(FixedCols, FixedRows, ColCount - 1, RowCount - 1);
end;
procedure TIDA_Grid._ClearSelectedArea;
begin
with Selection do ClearArea(Left, Top, Right, Bottom);
end;
function TIDA_Grid.MayIDoAddColumn: Boolean;
begin
Result := not ColNumFixed;
end;
function TIDA_Grid.MayIDoAddRow: Boolean;
begin
Result := not RowNumFixed;
end;
function TIDA_Grid.MayIDoClearAllCells: Boolean;
begin
Result := True;
end;
function TIDA_Grid.MayIDoClearSelectedArea: Boolean;
begin
Result := True;
end;
function TIDA_Grid.MayIDoDeleteAllData: Boolean;
begin
Result := not (ColNumFixed and RowNumFixed);
end;
function TIDA_Grid.MayIDoDeleteColumns(StartCol,
ColsCount: Integer): Boolean;
begin
Result := not ColNumFixed;
end;
function TIDA_Grid.MayIDoDeleteRows(StartRow, RowsCount: Integer): Boolean;
begin
Result := not RowNumFixed;
end;
function TIDA_Grid.MayIDoInsertColumns(StartCol,
ColsCount: Integer): Boolean;
begin
Result := not ColNumFixed;
end;
function TIDA_Grid.MayIDoInsertRows(StartRow, RowsCount: Integer): Boolean;
begin
Result := not RowNumFixed;
end;
function TServeredGrid.MayIDoAddColumn: Boolean;
begin
if GetMyGridDataSource <> nil then
Result := inherited MayIDoAddColumn and
GetMyGridDataSource.MayIDoAddColumn
else Result := inherited MayIDoAddColumn;
end;
function TServeredGrid.MayIDoAddRow: Boolean;
begin
if GetMyGridDataSource <> nil then
Result := inherited MayIDoAddRow and
GetMyGridDataSource.MayIDoAddRow
else Result := inherited MayIDoAddRow;
end;
function TServeredGrid.MayIDoClearAllCells: Boolean;
begin
if GetMyGridDataSource <> nil then
Result := inherited MayIDoClearAllCells and
GetMyGridDataSource.MayIDoClearAllCells
else Result := inherited MayIDoClearAllCells;
end;
function TServeredGrid.MayIDoClearSelectedArea: Boolean;
begin
if GetMyGridDataSource <> nil then
Result := inherited MayIDoClearSelectedArea and
GetMyGridDataSource.MayIDoClearSelectedArea
else Result := inherited MayIDoClearSelectedArea;
end;
function TServeredGrid.MayIDoDeleteAllData: Boolean;
begin
if GetMyGridDataSource <> nil then
Result := inherited MayIDoDeleteAllData and
GetMyGridDataSource.MayIDoDeleteAllData
else Result := inherited MayIDoDeleteAllData;
end;
function TServeredGrid.MayIDoDeleteColumns(StartCol,
ColsCount: Integer): Boolean;
begin
if GetMyGridDataSource <> nil then
Result := inherited MayIDoDeleteColumns(StartCol, ColsCount) and
GetMyGridDataSource.MayIDoDeleteColumns(StartCol, ColsCount)
else Result := inherited MayIDoDeleteColumns(StartCol, ColsCount);
end;
function TServeredGrid.MayIDoDeleteRows(StartRow,
RowsCount: Integer): Boolean;
begin
if GetMyGridDataSource <> nil then
Result := inherited MayIDoDeleteRows(StartRow, RowsCount) and
GetMyGridDataSource.MayIDoDeleteRows(StartRow, RowsCount)
else Result := inherited MayIDoDeleteRows(StartRow, RowsCount);
end;
function TServeredGrid.MayIDoInsertColumns(StartCol,
ColsCount: Integer): Boolean;
begin
if GetMyGridDataSource <> nil then
Result := inherited MayIDoInsertColumns(StartCol, ColsCount) and
GetMyGridDataSource.MayIDoInsertColumns(StartCol, ColsCount)
else Result := inherited MayIDoInsertColumns(StartCol, ColsCount);
end;
function TServeredGrid.MayIDoInsertRows(StartRow,
RowsCount: Integer): Boolean;
begin
if GetMyGridDataSource <> nil then
Result := inherited MayIDoInsertRows(StartRow, RowsCount) and
GetMyGridDataSource.MayIDoInsertRows(StartRow, RowsCount)
else Result := inherited MayIDoInsertRows(StartRow, RowsCount);
end;
{ TGEFGrid }
{$IFNDEF Lazarus}
function TGEFGrid.CanEditAcceptKey(Key: Char): Boolean;
begin
Result := inherited CanEditAcceptKey(Key) and CanEditModify;
end;
{$ENDIF}
procedure TGEFGrid.DoExit;
begin
if Modified then
begin
EditingFinished(Col, Row);
Modified := False;
end;
inherited;
end;
procedure TGEFGrid.EditingFinished(const ACol, ARow: Integer);
begin
if Assigned(OnGridEditingFinished) then
OnGridEditingFinished(Self, Col, Row);
end;
procedure TGEFGrid.KeyPress(var Key: Char);
begin
{$IFNDEF Lazarus}
if (goEditing in Options) and CanEditAcceptKey(Key) then Modified := True;
{$ENDIF}
inherited;
end;
function TGEFGrid.SelectCell(ACol, ARow: Integer): Boolean;
var MyResult: Boolean;
begin
MyResult := True;
if Modified then
begin
try
EditingFinished(Col, Row);
Modified := False;
except
MyResult := False;
MessageDlg('Invalid input...', mtError, [mbOk], 0);
end;
end;
Result := MyResult and inherited SelectCell(ACol, ARow);
end;
procedure TServeredGrid.EditingFinished(const ACol, ARow: Integer);
begin
DataChanged(Col, Row, Col, Row);
inherited;
end;
procedure TServeredGrid.DataChanged(const Left, Top, Right,
Bottom: Integer);
var i, j: LongInt;
begin
if GetMyGridDataSource <> nil then with GetMyGridDataSource do
begin
for i := Left to Right do
for j := Top to Bottom do
if Cells[i, j] = '' then
begin
SetValueByDefault(i, j);
Cells[i, j] := ValueToString(i, j);
end else
begin
if not IsDataValid(i, j, Cells[i, j]) then
begin
SetValueByDefault(i, j);
Cells[i, j] := ValueToString(i, j);
end else StringToValue(i, j, Cells[i, j]);
end;
end;
end;
procedure TServeredGrid.FillRowHeaders;
begin
FillArea(0, FixedRows, FixedCols - 1, RowCount - 1);
end;
procedure TServeredGrid.FillColHeaders;
begin
FillArea(0, 0, ColCount - 1, FixedRows - 1);
end;
procedure TServeredGrid.FillTable;
begin
FillArea(FixedCols, FixedRows, ColCount - 1, RowCount - 1);
end;
procedure TServeredGrid.GetTableParams;
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do
begin
ColCount := GetColCount;
RowCount := GetRowCount;
FixedCols := GetFixedCols;
FixedRows := GetFixedRows;
ColNumFixed := GetColNumFixed;
RowNumFixed := GetRowNumFixed;
Col := GetCol;
Row := GetRow;
LeftCol := GetLeftCol;
TopRow := GetTopRow;
Selection := GetSelection;
EditorMode := False;
end;
end;
procedure TServeredGrid.GetWidthsHeights;
var i: LongInt;
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do
begin
if AutoWidths then AutoColWidths else
for i := 0 to ColCount - 1 do ColWidths[i] := GetColWidth(i);
if AutoHeights then AutoRowHeights else
for i := 0 to RowCount - 1 do RowHeights[i] := GetRowHeight(i);
end;
end;
procedure TIDA_Grid.DataChanged(const Left, Top, Right, Bottom: Integer);
begin
end;
procedure TIDA_Grid.ClearArea(const Left, Top, Right, Bottom: Integer);
var i, j: LongInt;
begin
for i := Top to Bottom do
for j := Left to Right do Cells[j, i] := '';
DataChanged(Left, Top, Right, Bottom);
end;
procedure TIDA_Grid.FillRowHeaders;
begin
end;
procedure TIDA_Grid.FillColHeaders;
begin
end;
procedure TServeredGrid.SaveTableParams;
var i: LongInt;
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do
begin
for i := 0 to ColCount - 1 do SaveColWidth(i, ColWidths[i]);
for i := 0 to RowCount - 1 do SaveRowHeight(i, RowHeights[i]);
SaveLeftCol(LeftCol);
SaveTopRow(TopRow);
SaveCol(Col);
SaveRow(Row);
SaveSelection(Selection);
end;
end;
procedure TGEFGrid.SetModified(const AModified: Boolean);
begin
FModified := AModified;
if AModified and Assigned(OnGridModified) then OnGridModified(Self);
end;
procedure TIDA_Grid.AutoRowHeights;
var i: LongInt;
begin
for i := 0 to RowCount - 1 do SetAutoRowHeight(i);
end;
procedure TIDA_Grid.SetAutoRowHeight(ARow: Integer);
var Height: LongInt;
begin
Height := GetMaxTextHeight(Self, ARow);
if Height = 0 then Height := MIN_HEIGHT;
Height := Height + 2;
RowHeights[ARow] := Height;
end;
{$IFNDEF Lazarus}
function TIDA_Grid.CanEditModify: Boolean;
begin
Result := Changeable;
end;
{$ENDIF}
constructor TIDA_Grid.Create(AOwner: TComponent);
begin
inherited;
Changeable := True;
end;
{$IFNDEF Lazarus}
function TServeredGrid.CanEditModify: Boolean;
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do
Result := inherited CanEditModify and (not IsCellDisabled(Col, Row))
else Result := inherited CanEditModify;
end;
{$ENDIF}
{$IFNDEF Lazarus}
function TServeredGrid.CanEditAcceptKey(Key: Char): Boolean;
begin
if GetMyGridDataSource <> nil then
with GetMyGridDataSource do
Result := inherited CanEditAcceptKey(Key) and
(Key in GetCellEnabledCharSet(Col, Row))
else Result := inherited CanEditAcceptKey(Key);
end;
{$ENDIF}
procedure TIDA_Grid.FillArea(const Left, Top, Right, Bottom: Integer);
begin
end;
procedure TServeredGrid.FillArea(const Left, Top, Right, Bottom: Integer);
var i, j: LongInt;
begin
if GetMyGridDataSource <> nil then
for i := Left to Right do
for j := Top to Bottom do
Cells[i, j] := GetMyGridDataSource.ValueToString(i, j);
end;
initialization
RegisterClass(TGEFGrid);
RegisterClass(TIDA_Grid);
RegisterClass(TColoredGrid);
RegisterClass(TServeredGrid);
RegisterClass(TNumericGrid);
RegisterClass(TColorStringGrid);
end.
|
{***************************************************************************
*
* Orion-project.org Lazarus Helper Library
* Copyright (C) 2016-2017 by Nikolay Chunosov
*
* This file is part of the Orion-project.org Lazarus Helper Library
* https://github.com/Chunosov/orion-lazarus
*
* This Library is free software: you can redistribute it and/or modify it
* under the terms of the MIT License. See enclosed LICENSE.txt for details.
*
***************************************************************************}
unit OriControlsBase;
{$mode objfpc}{$H+}
interface
uses
Controls, Graphics, LCLType;
{type
TButtonPaintInfo = packed record
Parent: TWinControl;
Window: HWND;
Canvas: TCanvas;
Rect: TRect;
Pressed: Boolean;
Disabled: Boolean;
Focused: Boolean;
Default: Boolean;
Hover: Boolean;
Checked: Boolean;
end;
TOriMonoGlyph = class
protected
Width: Integer;
Height: Integer;
Bitmap, OldBitmap: HBitmap;
BitmapDC: HDC;
public
constructor Create(AWidth, AHeight: Integer; const Bits);
destructor Destroy; override;
procedure Draw(DC: HDC; X, Y: Integer; Color: TColor);
end;}
type
TOriButtonMonoGlyph = (bgNone, bgClose, bgCloseSmall, bgCloseThin, bgMaximize,
bgMinimize, bgCascade, bgTriangleDown, bgTriangleUp, bgTriangleRight,
bgTriangleLeft, bgQuoteDown, bgQuoteUp, bgQuoteRight, bgQuoteLeft,
bgClipOn, bgClipOff, bgArrowDown, bgArrowUp, bgArrowRight,
bgArrowLeft, bgEllipsis, bgCheck, bgPlus, bgMinus, bgMultiply, bgDivide,
bgTriLeftSmall, bgTriRightSmall, bgFontBold, bgFontItalic, bgFontUnderline);
implementation
const
MonoGlyphW = 10;
MonoGlyphH = 10;
MonoGlyphSize = 20;
{$region MonoGlyphs}
const MonoGlyphs: array [0..MonoGlyphSize*Ord(High(TOriButtonMonoGlyph))-1] of Byte = (
{bgClose} $C1, $80, $E3, $80, $77, $00, $3E, $00, $1C, $00, $3E, $00, $77, $00, $E3, $80, $C1, $80, $00, $00,
{bgCloseSmall} $00, $00, $00, $00, $61, $80, $33, $00, $1E, $00, $0C, $00, $1E, $00, $33, $00, $61, $80, $00, $00,
{bgCloseThin} $00, $00, $00, $00, $21, $00, $12, $00, $0C, $00, $0C, $00, $12, $00, $21, $00, $00, $00, $00, $00,
{bgMaximize} $FF, $C0, $FF, $C0, $80, $40, $80, $40, $80, $40, $80, $40, $80, $40, $80, $40, $80, $40, $FF, $C0,
{bgMinimize} $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $7F, $00, $7F, $00, $00, $00,
{bgCascade} $3F, $C0, $3F, $C0, $20, $40, $FF, $40, $FF, $40, $81, $C0, $81, $00, $81, $00, $FF, $00, $00, $00,
{bgTriangleDown} $00, $00, $00, $00, $00, $00, $FF, $C0, $7F, $80, $3F, $00, $1E, $00, $0C, $00, $00, $00, $00, $00,
{bgTriangleUp} $00, $00, $00, $00, $00, $00, $0C, $00, $1E, $00, $3F, $00, $7F, $80, $FF, $C0, $00, $00, $00, $00,
{bgTriangleRight} $20, $00, $30, $00, $38, $00, $3C, $00, $3E, $00, $3E, $00, $3C, $00, $38, $00, $30, $00, $20, $00,
{bgTriangleLeft} $02, $00, $06, $00, $0E, $00, $1E, $00, $3E, $00, $3E, $00, $1E, $00, $0E, $00, $06, $00, $02, $00,
{bgQuoteDown} $C0, $C0, $61, $80, $33, $00, $1E, $00, $CC, $C0, $61, $80, $33, $00, $1E, $00, $0C, $00, $00, $00,
{bgQuoteUp} $0C, $00, $1E, $00, $33, $00, $61, $80, $CC, $C0, $1E, $00, $33, $00, $61, $80, $C0, $C0, $00, $00,
{bgQuoteRight} $88, $00, $CC, $00, $66, $00, $33, $00, $19, $80, $19, $80, $33, $00, $66, $00, $CC, $00, $88, $00,
{bgQuoteLeft} $08, $80, $19, $80, $33, $00, $66, $00, $CC, $00, $CC, $00, $66, $00, $33, $00, $19, $80, $08, $80,
{bgClipOn} $3E, $00, $26, $00, $26, $00, $26, $00, $26, $00, $7F, $00, $08, $00, $08, $00, $08, $00, $08, $00,
{bgClipOff} $00, $00, $08, $00, $0F, $C0, $08, $40, $F8, $40, $0F, $C0, $0F, $C0, $08, $00, $00, $00, $00, $00,
{bgArrowDown} $1E, $00, $1E, $00, $1E, $00, $1E, $00, $1E, $00, $FF, $C0, $7F, $80, $3F, $00, $1E, $00, $0C, $00,
{bgArrowUp} $0C, $00, $1E, $00, $3F, $00, $7F, $80, $FF, $C0, $1E, $00, $1E, $00, $1E, $00, $1E, $00, $1E, $00,
{bgArrowRight} $04, $00, $06, $00, $07, $00, $FF, $80, $FF, $C0, $FF, $C0, $FF, $80, $07, $00, $06, $00, $04, $00,
{bgArrowLeft} $08, $00, $18, $00, $38, $00, $7F, $C0, $FF, $C0, $FF, $C0, $7F, $C0, $38, $00, $18, $00, $08, $00,
{bgEllipsis} $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $CC, $C0, $CC, $C0, $00, $00, $00, $00, $00, $00,
{bgCheck} $00, $00, $00, $00, $01, $00, $03, $00, $47, $00, $6E, $00, $7C, $00, $38, $00, $10, $00, $00, $00,
{bgPlus} $00, $00, $0C, $00, $0C, $00, $0C, $00, $7F, $80, $7F, $80, $0C, $00, $0C, $00, $0C, $00, $00, $00,
{bgMinus} $00, $00, $00, $00, $00, $00, $00, $00, $7F, $80, $7F, $80, $00, $00, $00, $00, $00, $00, $00, $00,
{bgMultiply} $00, $00, $63, $00, $77, $00, $3E, $00, $1C, $00, $3E, $00, $77, $00, $63, $00, $00, $00, $00, $00,
{bgDivide} $00, $00, $0C, $00, $0C, $00, $00, $00, $7F, $80, $7F, $80, $00, $00, $0C, $00, $0C, $00, $00, $00,
{bgTriLeftSmall} $00, $00, $00, $00, $02, $00, $06, $00, $0E, $00, $1E, $00, $0E, $00, $06, $00, $02, $00, $00, $00,
{bgTriRightSmall} $00, $00, $00, $00, $10, $00, $18, $00, $1C, $00, $1E, $00, $1C, $00, $18, $00, $10, $00, $00, $00,
{bgFontBold} $FF, $00, $73, $80, $73, $80, $73, $80, $7F, $00, $73, $80, $73, $80, $73, $80, $73, $80, $FF, $00,
{bgFontItalic} $1F, $C0, $07, $00, $07, $00, $0E, $00, $0E, $00, $1C, $00, $1C, $00, $38, $00, $38, $00, $FE, $00,
{bgFontUnderline} $F7, $80, $63, $00, $63, $00, $63, $00, $63, $00, $63, $00, $63, $00, $3E, $00, $00, $00, $FF, $80
);
{$endregion}
{$region TOriMonoGlyph}
{constructor TOriMonoGlyph.Create(AWidth, AHeight: Integer; const Bits);
begin
Width := AWidth;
Height := AHeight;
Bitmap := CreateBitmap(Width, Height, 1, 1, @Bits);
BitmapDC := CreateCompatibleDC(0);
OldBitmap := SelectObject(BitmapDC, Bitmap);
end;
destructor TOriMonoGlyph.Destroy;
begin
SelectObject(BitmapDC, OldBitmap);
DeleteDC(BitmapDC);
DeleteObject(Bitmap);
inherited;
end;
procedure TOriMonoGlyph.Draw(DC: HDC; X, Y: Integer; Color: TColor);
var
OldTextColor, OldBkColor: TColorRef;
OldBrush, Brush: HBRUSH;
begin
if Color = clNone then Exit;
OldTextColor := SetTextColor(DC, $FFFFFF);
OldBkColor := SetBkColor(DC, $000000);
if Color < 0 then Brush := GetSysColorBrush(Color and $000000FF)
else Brush := CreateSolidBrush(Color);
OldBrush := SelectObject(DC, Brush);
BitBlt(DC, X, Y, Width, Height, BitmapDC, 0, 0, $B8074A);
SelectObject(DC, OldBrush);
DeleteObject(Brush);
SetBkColor(DC, OldBkColor);
SetTextColor(DC, OldTextColor);
end;}
{$endregion}
end.
|
unit uOperationThread;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
uFileSourceOperation;
type
{en
Thread executing a file source operation.
}
TOperationThread = class(TThread)
private
FOperation: TFileSourceOperation;
protected
procedure Execute; override;
public
{en
Creates a new thread for executing an operation.
@param(CreateSuspended if @true the thread is not immediately started on creation.)
@param(Operation is the file source operation that will be executed.)
}
constructor Create(CreateSuspended: Boolean; Operation: TFileSourceOperation); reintroduce;
end;
implementation
uses
uDebug, uExceptions;
constructor TOperationThread.Create(CreateSuspended: Boolean; Operation: TFileSourceOperation);
begin
FreeOnTerminate := True;
FOperation := Operation;
FOperation.AssignThread(Self);
inherited Create(CreateSuspended, DefaultStackSize);
end;
procedure TOperationThread.Execute;
begin
try
FOperation.Execute;
except
on e: Exception do
HandleException(e, Self);
end;
end;
end.
|
//Отображение прогресса создания отчёта
unit fProgress;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, xlReport, ExtCtrls;
type
TfrmProgress = class(TForm)
bar: TProgressBar;
StaticText1: TStaticText;
procedure FormCreate(Sender: TObject);
procedure ReportProgress(Report: TxlReport; const Position, Max: Integer);
end;
//отображает окно с процессом построения отчета, и начинает строить отчет
function ProgressReport (report: TxlReport): Boolean;
implementation
{$R *.dfm}
//отображает окно с процессом построения отчета, и начинает строить отчет
function ProgressReport (report: TxlReport): Boolean;
var
frm: TfrmProgress;
begin
try
frm := TfrmProgress.Create(nil);
frm.Show;
frm.Update;
report.OnProgress := frm.ReportProgress;
report.Report;
finally
frm.Free;
end;
end;
//------------------------------------------------------------------------------
// TfrmProgress
//------------------------------------------------------------------------------
procedure TfrmProgress.FormCreate(Sender: TObject);
begin
bar.Min := 0;
bar.Max := 100;
bar.Step := 1;
end;
procedure TfrmProgress.ReportProgress(Report: TxlReport; const Position, Max: Integer);
begin
bar.Max := Max;
bar.Position := Position;
end;
end.
|
unit uRecord;
interface
const
kTrue: integer = -1;
kFalse: Integer = 0;
kkHz: Double = 1000;
kMHz: Double = 1000000;
kGlobeRadius: double = 6367.0; // 地球の半径 km
kFileAction: array[0..3] of string = ('インポート','アペンド','エクスポート','アップデート');
kQsoStatus: array[0..6] of String =('Clear', 'Setting', 'Browse', 'Edit', 'Tramp', 'Insert', 'Close');
kBand: array[0..2] of String = ('Band', 'Band_F', 'Band_M');
//type
// TAct=(actCheck,actSelect,actInsert,actUpdate,actDelete);
type
TProcessing=(prRealTime, prBatch);
TQsoState=(lgClear,lgSetting,lgBrowse,lgEdit,lgTramp,lgInsert,lgClose);
TDataInput=(diManual, diAuto);
TFileAction=(faImport, faAppend, faExport, faUpdate);
TBand=(bBand, bBand_F, bBand_M);
TPtt=(PttToggle, PttOff, PttOn);
type TQso = record // 現在QSOの内容でDBに保存しないField
Area: string;
CountryName: string;
RegionName: string;
RegionPhonetic: string;
EntityName: string;
IOTAName: string;
EtcName: array[1..5] of string;
Latitude: string;
Longitude: string;
Comment: string;
isJarlMember: boolean;
isLicensed: boolean;
FreqFormat: string;
DefaultFreqFormat: string;
DefaultMode: string;
DefaultReport: string;
MyCallsign: string;
MyEntity: string;
MyCountry: string;
MyRegion: string;
MyGridLoc: string;
MyRIG: string;
MyAnt: string;
MyMemo: string;
MyCountryName: string;
MyRegionName: string;
MyEntityName: string;
MyLatitude: string;
MyLongitude: string;
MyArea: string;
result: boolean;
end;
type TPastQso = record // 同一 Callsignでの前の値
Callsign: string;
OrgCallsign: string;
Name: string;
Entity: string;
Country: string;
Region: string;
Continent: string;
ItuZone: string;
CQZone: string;
Iota: string;
Qsl: string;
QSLManager: string;
result: boolean;
end;
type TPrevQso = record // 直前のQSO内容
Num: integer;
CQ: smallint;
OnDateTime: TDateTime;
Freq: Int64;
RecvFreq: Int64;
Route: string;
Repeater: string;
Mode: string;
HisReport: string;
MyReport: string;
end;
type TMyDataRec = record // TMyDataの値
MyCallsign: string;
MyEntity: string;
MyCountry: string;
MyRegion: string;
MyGridLoc: string;
MyRIG: string;
MyAnt: string;
MyMemo: string;
MyCountryName: string;
MyRegionName: string;
MyEntityName: string;
MyLatitude: string;
MyLongitude: string;
MyArea: string;
end;
Type
TOptionSummary = Record
Callsign: Integer;
Entity: Integer;
Region: Integer;
Prefix: Integer;
Suffix: Integer;
JCA: Integer;
NotJAExec: boolean;
Band: array[0..20] of boolean;
End;
type
POptionsData = ^TOptionsData;
TOptionsData = record
Callsign: string;
Name: string;
Address: string;
Country: string;
Region: string;
Entity: string;
Longitude: Double;
Latitude: Double;
GridLocator: string;
DbPath: string;
AutoBackupPath1: string;
AutoBackupPath2: string;
AutoBackup: boolean;
BackupGeneration: Integer;
JournalGeneration: Integer;
Precedence: boolean;
RealTimeInput: boolean;
CopyOnDate: boolean;
LogTabOrder: string;
DisplayItems: string; // conmma text
NonDisplayItems: string; // conmma text
Internet: boolean;
Jarl: boolean;
JarlUrl: string;
Mic: boolean;
MicUrl: string;
LoTw: boolean;
LotwLocation: string;
LotwIntervalMin: Integer;
Summary: TOptionSummary;
end;
type TCallsignRec = record
Callsign: string;
OrgCallsign: string;
Prefix: string;
Suffix: string;
Area: string;
result: boolean;
end;
type TCallbook = record
Callsign: string;
Name: string;
Entity: string;
Country: string;
Region: string;
Comment: string;
result: boolean;
end;
type TCallbookEx = record
Callsign: string;
OnDate: tDate;
Country: string;
Region: string;
Entity: string;
GridLoc: string;
Continent: string;
ITUZone: string;
CQZone: string;
Latitude: string;
Longitude: string;
result: boolean;
end;
type TCountryRec = record
Country: string;
Name: string;
FmDate: TDateTime;
Name_jp: string;
Result: boolean;
end;
type TEtcRec = record
Table: string;
Code: string;
Name: string;
FmDate: TDateTime;
Result: boolean;
end;
type TFreqRec = record
Freq: Int64;
Band: Int64;
DefaultMode: string;
Result: boolean;
end;
type TIotaRec = record
Entity: string;
Iota: string;
Name: string;
Result: boolean;
end;
type TModeRec = record
Mode: string;
Report: string;
ReportRegEx: string;
DefaultReport: string;
FreqFormat: string;
Result: boolean;
end;
type TEntityRec = record
Entity: string;
Name: string;
EntityCode: string;
Country: string;
Continent: string;
ITUZone: string;
CQZone: string;
Latitude: string;
Longitude: string;
Continents: string;
ITUZones: string;
CQZones: string;
HamLog: string;
result: boolean;
end;
type THamLog = record
HamLog: string;
Entity: string;
result: boolean;
end;
type TRegionRec = record
Country: string;
Region: string;
Name: string;
Name1: string;
Name2: string;
Name3: string;
Phonetic: string;
Rank: string;
Latitude: string;
Longitude: string;
FmDate: TDate;
ToDate: TDate;
result: boolean;
end;
type TRepeaterRec = record
Route: string;
Repeater: string;
UplinkFreq: Int64;
DownlinkFreq: Int64;
result: boolean;
end;
type TRouteRec = record
Route: string;
NeedRepeter: boolean;
result: boolean;
end;
type TZipCodeRec = record
Country: string;
ZipCode: string;
Region: string;
Name: string;
PrimaryCity: string;
result: boolean;
end;
type TFilterKind = (flNone, flCallsign, flEntity, flRegion, flPrefix, flNum,
flOnDate, flMemo);
type TFilter = record
Kind: TFilterKind;
Callsign: string;
Entity: string;
Country: string;
Region: string;
FmOnDate: TDate;
ToOnDate: TDate;
FmNum: integer;
ToNum: integer;
Prefix: string;
Suffix: string;
FmDate: boolean;
Memo1: string;
Memo2: string;
IsCondOr: boolean;
Sql: string;
end;
type TGridLocRec = record
GridLoc: string;
Longitude: Double;
Latitude: Double;
end;
//type
// TQslState=(smNone, smQso, smEQsl, smQsl);
type TSummary = record
Kind: integer;
Callsign: string;
Entity: string;
Country: string;
Region: string;
Prefix: string;
Suffix: string;
end;
type
TQslState = (qsNone, qsQso, qsEQsl, qsQsl);
type
TDisplay = (dsByMode, dsByCollMode, dsAllModeOnly, dsNone);
type
TCategory = (ctCallsign, ctEntity, ctRegion, ctPrefix, ctSuffix, ctJCA, ctIota, ctGridLoc);
type TFindJpnKind = (fjPrefecture, fjCity, fjCounty, fjWard, fjTown, fjVillage);
type TFindUsaKind = (fuState, fuCounty, fuZipCode);
type TFindJpnRec = record
Kind: TFindJpnKind;
// Key: word;
Area: string;
Date: TDate;
Region: string;
RegionName: string;
Latitude: string;
Longitude: string;
end;
type TFindKind = (fiNone, fiCallsign, fiEntity, fiRegion, fiPrefix, fiGridLoc,
fiIota, fiNum, fiOnDate, fiMemo);
type TFindLogRec = record
Kind: TFindKind;
Callsign: string;
Entity: string;
Country: string;
Region: string;
Prefix: string;
Suffix: string;
GridLoc: string;
Iota: string;
FmNum: integer;
ToNum: Integer;
OnDateTime: tDateTime;
Memo: string;
end;
implementation
end.
|
unit aboutform;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls;
type
{ TfrmAbout }
TfrmAbout = class(TForm)
Image1: TImage;
Image2: TImage;
Image3: TImage;
imgClipboard: TImage;
lblUse: TLabel;
lblTheByWhomWhatWhere: TLabel;
lblCredits: TLabel;
procedure FormClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: char);
private
{ private declarations }
public
{ public declarations }
end;
var
frmAbout: TfrmAbout;
implementation
uses EngLangRes, VInfo, versiontypes, versionresource;
{$R *.lfm}
{ TfrmAbout }
procedure TfrmAbout.FormKeyPress(Sender: TObject; var Key: char);
begin
Close;
end;
procedure TfrmAbout.FormClick(Sender: TObject);
begin
Close;
end;
procedure TfrmAbout.FormCreate(Sender: TObject);
var Info: TVersionInfo;
function ProductVersionToString(PV: TFileProductVersion): String;
begin
Result := Format('%d.%d.%d (Build: %d)', [PV[0],PV[1],PV[2],PV[3]])
end;
begin
Info := TVersionInfo.Create;
Info.Load(HINSTANCE);
lblUse.Caption := msgAboutUseLine1+#13#10+msgAboutUseLine2+#13#10+
Info.StringFileInfo[0].Values['ProductName']+' '
+ProductVersionToString(Info.FixedInfo.FileVersion);;
Info.Free;
lblTheByWhomWhatWhere.Caption:= msgAboutMessageLine1
+msgAboutMessageLine2
+msgAboutMessageLine3
+msgAboutMessageLine4;
lblCredits.Caption:= msgAboutCreditsLine1+#13#10
+msgAboutCreditsLine2+#13#10
+msgAboutCreditsLine3+#13#10
+msgAboutCreditsLine4+#13#10
+msgAboutCreditsLine5;
end;
end.
|
unit ProducersQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, NotifyEvents, ProducerInterface, DSWrap,
BaseEventsQuery;
type
TProducersW = class(TDSWrap)
procedure FDQueryCntGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
private
FCnt: TFieldWrap;
FID: TFieldWrap;
FName: TFieldWrap;
FProducerParamSubParamID: TParamWrap;
FProducerTypeID: TFieldWrap;
procedure DoBeforeDelete(Sender: TObject);
protected
procedure DoAfterOpen(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
procedure AddNewValue(const AValue: string; AProducerTypeID: Integer);
property Cnt: TFieldWrap read FCnt;
property ID: TFieldWrap read FID;
property Name: TFieldWrap read FName;
property ProducerParamSubParamID: TParamWrap read FProducerParamSubParamID;
property ProducerTypeID: TFieldWrap read FProducerTypeID;
end;
TQueryProducers = class(TQueryBaseEvents, IProducer)
procedure FDQueryDeleteError(DataSet: TDataSet; E: EDatabaseError;
var Action: TDataAction);
strict private
function Exist(const AProducerName: String): Boolean; stdcall;
function GetProducerID(const AProducerName: String): Integer; stdcall;
private
FW: TProducersW;
procedure DoBeforeOpen(Sender: TObject);
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
public
constructor Create(AOwner: TComponent); override;
procedure CancelUpdates; override;
function Locate(AValue: string; TestResult: Boolean = False): Boolean;
property W: TProducersW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses RepositoryDataModule, DefaultParameters, ProducerTypesQuery,
FireDAC.Phys.SQLiteWrapper, DelNotUsedProductsQuery;
constructor TQueryProducers.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TProducersW;
TNotifyEventWrap.Create(W.BeforeOpen, DoBeforeOpen, W.EventList);
AutoTransaction := False;
end;
procedure TQueryProducers.CancelUpdates;
begin
// отменяем все сделанные изменения на стороне клиента
W.TryCancel;
FDQuery.Connection.Rollback;
W.RefreshQuery;
end;
function TQueryProducers.CreateDSWrap: TDSWrap;
begin
Result := TProducersW.Create(FDQuery);
end;
procedure TQueryProducers.DoBeforeOpen(Sender: TObject);
begin
// Заполняем код параметра "Производитель"
FDQuery.ParamByName(W.ProducerParamSubParamID.FieldName).AsInteger :=
TDefaultParameters.ProducerParamSubParamID;
end;
function TQueryProducers.Exist(const AProducerName: String): Boolean;
begin
Result := GetProducerID(AProducerName) > 0;
end;
procedure TQueryProducers.FDQueryDeleteError(DataSet: TDataSet;
E: EDatabaseError; var Action: TDataAction);
var
AE: ESQLiteNativeException;
begin
inherited;
if not(E is ESQLiteNativeException) then
Exit;
AE := E as ESQLiteNativeException;
// Foreign Key Constraint Failed
if AE.ErrorCode = 787 then
E.Message :=
'Производитель присутствует на складе или в компонентной базе. Удаление невозможно.';
end;
function TQueryProducers.GetProducerID(const AProducerName: String): Integer;
var
V: Variant;
begin
Assert(not AProducerName.IsEmpty);
Result := 0;
V := FDQuery.LookupEx(W.Name.FieldName, AProducerName, W.PK.FieldName);
if not VarIsNull(V) then
Result := V;
end;
function TQueryProducers.Locate(AValue: string;
TestResult: Boolean = False): Boolean;
begin
Result := FDQuery.LocateEx(W.Name.FieldName, AValue.Trim,
[lxoCaseInsensitive]);
if TestResult then
Assert(Result);
end;
constructor TProducersW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FCnt := TFieldWrap.Create(Self, 'Cnt');
FName := TFieldWrap.Create(Self, 'Name', 'Производитель');
FProducerTypeID := TFieldWrap.Create(Self, 'ProducerTypeID');
// Параметры SQL запроса
FProducerParamSubParamID := TParamWrap.Create(Self,
'ProducerParamSubParamID');
TNotifyEventWrap.Create(AfterOpen, DoAfterOpen, EventList);
TNotifyEventWrap.Create(BeforeDelete, DoBeforeDelete, EventList);
end;
procedure TProducersW.AddNewValue(const AValue: string;
AProducerTypeID: Integer);
begin
Assert(AProducerTypeID > 0);
TryAppend;
ProducerTypeID.F.AsInteger := AProducerTypeID;
Name.F.AsString := AValue;
TryPost;
end;
procedure TProducersW.DoAfterOpen(Sender: TObject);
begin
// Кол-во - только для чтения
Cnt.F.ReadOnly := True;
Cnt.F.OnGetText := FDQueryCntGetText;
// Name.DisplayLabel := 'Производитель';
end;
procedure TProducersW.DoBeforeDelete(Sender: TObject);
begin
if DataSet.RecordCount = 0 then
Exit;
// Удаляем неиспользуемые продукты этого производителя!!!
TQueryDelNotUsedProducts2.Delete(ID.F.AsInteger);
end;
procedure TProducersW.FDQueryCntGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
if (not Sender.IsNull) and (Sender.AsFloat > 0) then
Text := String.Format('%.0n', [Sender.AsFloat])
else
Text := '';
end;
end.
|
unit osParserErrorHand;
interface
uses Classes, SysUtils;
type
TClasseErr = (epNone, epWarning, epError);
TNodoErro = class
FClasse : TClasseErr; // tipo de erro
FIDErro : Integer; // identificador de erro provido pelo 'usuario'
FTexto : AnsiString; // texto a ser apresentado na msg de erro
public
constructor Create(pClasse: TClasseErr; pIDErro: Integer;
pTexto: AnsiString; ListaDeComplementos: Array of Const);
property Classe: TClasseErr read FClasse;
property IDErro: Integer read FIDErro;
property MsgErro: AnsiString read FTexto;
end;
TListErro = class (Tlist)
public
procedure Add(TipoErro: TClasseErr; IDErro: Integer;
Texto: AnsiString; ListaDeComplementos: Array of Const); overload;
end;
implementation
{ TNodoErro }
constructor TNodoErro.Create(pClasse: TClasseErr; pIDErro: Integer;
pTexto: AnsiString; ListaDeComplementos: Array of Const);
begin
FClasse := pClasse;
FIDErro := pIDErro;
FTexto := AnsiString(Format(String(pTexto), ListaDeComplementos));
end;
{ TListErro }
procedure TListErro.Add(TipoErro: TClasseErr; IDErro: Integer;
Texto: AnsiString; ListaDeComplementos: Array of Const);
begin
Self.Add(TNodoErro.Create(TipoErro, IDErro, Texto, ListaDeComplementos));
end;
end.
|
unit FIToolkit.Localization; //FI:ignore
interface
const
{ Supported languages }
LANG_EN_US = 'en-US';
LANG_RU_RU = 'ru-RU';
{ Current application language }
LANGUAGE = LANG_EN_US;
implementation
end.
|
unit ncaFrmGetWebTabs;
{
ResourceString: Dario 11/03/13
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, SHDocVw_EWB, EwbCore, EmbeddedWB, Automation, ExtCtrls;
type
TFrmGetWebTabs = class(TForm)
WB: TEmbeddedWB;
TimerErro: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure WBDocumentComplete(ASender: TObject; const pDisp: IDispatch;
var URL: OleVariant);
procedure FormShow(Sender: TObject);
procedure WBNavigateError(ASender: TObject; const pDisp: IDispatch; var URL,
Frame, StatusCode: OleVariant; var Cancel: WordBool);
procedure TimerErroTimer(Sender: TObject);
private
{ Private declarations }
function LoadFromIni: Boolean;
public
{ Public declarations }
end;
var
FrmGetWebTabs: TFrmGetWebTabs;
implementation
uses ncClassesBase, ncaDM, ncaFrmPri, nexUrls;
{$R *.dfm}
procedure TFrmGetWebTabs.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmGetWebTabs.FormCreate(Sender: TObject);
begin
Width := 1;
Height := 1;
Left := 1;
end;
procedure TFrmGetWebTabs.FormShow(Sender: TObject);
begin
if not LoadFromIni then begin
WB.ClearCache;
WB.navigate(gUrls.Url('nextabs', 'conta='+ // do not localize
gConfig.Conta+'&adm='+BoolStr[Dados.CM.UA.Admin]+ // do not localize
'&cok='+BoolStr[gConfig.FreePremium or (gConfig.QtdLic>0)]+ // do not localize
'&sw='+prefixo_versao)); // do not localize
end else
Close;
end;
function TFrmGetWebTabs.LoadFromIni: Boolean;
var
S: String;
sl: TStrings;
I : Integer;
begin
Result := False;
S := ExtractFilePath(ParamStr(0))+'webtabs.ini'; // do not localize
if not FileExists(S) then Exit;
Result := True;
sl := TStringList.Create;
try
sl.LoadFromFile(S);
for I := 0 to sl.Count-1 do
FrmPri.AddWebTab(sl[i]);
finally
sl.Free;
end;
end;
procedure TFrmGetWebTabs.TimerErroTimer(Sender: TObject);
begin
TimerErro.Enabled := False;
WB.ClearCache;
WB.navigate(gUrls.Url('nextabs', 'conta='+gConfig.Conta+'&adm='+BoolStr[Dados.CM.UA.Admin]+'&cok='+BoolStr[gConfig.FreePremium or (gConfig.QtdLic>0)])); // do not localize
end;
procedure TFrmGetWebTabs.WBDocumentComplete(ASender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
var
S: String;
I, P: Integer;
SL : TStrings;
begin
try
S := wb.DocumentSource;
P := Pos('!webtabs!="', S); // do not localize
if P=0 then Exit;
Delete(S, 1, P+10);
S := Copy(S, 1, Pos('"', S)-1);
if S='' then Exit;
SL := TStringList.Create;
try
P := Pos(';', S);
while P > 0 do begin
SL.Add(Copy(S, 1, P-1));
Delete(S, 1, P);
P := Pos(';', S);
end;
if Trim(S)>'' then SL.Add(Trim(S));
for I := 0 to SL.Count-1 do
FrmPri.AddWebTab(SL[i]);
finally
SL.Free;
end;
finally
Close;
end;
end;
procedure TFrmGetWebTabs.WBNavigateError(ASender: TObject; const pDisp: IDispatch;
var URL, Frame, StatusCode: OleVariant; var Cancel: WordBool);
begin
TimerErro.Enabled := True;
Cancel := True;
end;
end.
|
unit ccLinePlaneCapFrame;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, ExtCtrls, StdCtrls, IniFiles,
ccPlanarCapFrame;
type
{ TLinePlaneCapFrame }
TLinePlaneCapFrame = class(TPlanarCapFrame)
CbHeightUnits: TComboBox;
EdHeight: TEdit;
LblHeight: TLabel;
private
{ private declarations }
protected
procedure ClearResults; override;
procedure SetEditLeft(AValue: Integer); override;
public
{ public declarations }
constructor Create(AOwner: TComponent); override;
procedure Calculate; override;
procedure ReadFromIni(ini: TCustomIniFile); override;
function ValidData(out AMsg: String; out AControl: TWinControl): Boolean; override;
procedure WriteToIni(ini: TCustomIniFile); override;
end;
implementation
{$R *.lfm}
uses
ccGlobal, ccStrings;
{ TLinePlaneCapFrame }
constructor TLinePlaneCapFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIniKey := 'Line-plane';
end;
procedure TLinePlaneCapFrame.Calculate;
var
W, H, d, L, eps, capa, Wd, Hd: extended;
fL, fc: Double;
capaUnits, lengthUnits: String;
capaFmt: String;
begin
try
if (EdDist.Text = '') or not TryStrToFloat(EdDist.Text, d) then exit;
if d = 0 then exit;
if (EdLength.Text = '') or not TryStrToFloat(EdLength.Text, L) then exit;
if L = 0 then exit;
if (EdWidth.Text = '') or not TryStrToFloat(EdWidth.Text, W) then exit;
if W = 0 then exit;
if (EdHeight.Text = '') or not TryStrToFloat(EdHeight.Text, H) then exit;
if H = 0 then exit;
if (EdEps.Text = '') or not TryStrToFloat(EdEps.Text, eps) then exit;
if CbDistUnits.ItemIndex = -1 then exit;
if CbLengthUnits.ItemIndex = -1 then exit;
if CbWidthUnits.ItemIndex = -1 then exit;
if CbHeightUnits.ItemIndex = -1 then exit;
if CbCapaUnits.ItemIndex = -1 then exit;
fL := LenFactor[TLenUnits(CbLengthUnits.ItemIndex)];
fc := CapaFactor[TCapaUnits(CbCapaUnits.ItemIndex)];
d := d * LenFactor[TLenUnits(CbDistUnits.ItemIndex)];
W := W * LenFactor[TLenUnits(CbWidthUnits.ItemIndex)];
H := H * Lenfactor[TLenUnits(CbHeightUnits.ItemIndex)];
L := L * fL;
capa := eps0 * eps * L * (W/d + 0.77 + 1.06*sqrt(sqrt(W/d)) + 1.06*sqrt(H/d));
if CbCapaUnits.Text = 'F' then
capaFmt := CapaExpFormat else
capaFmt := CapaStdFormat;
capaUnits := CbCapaUnits.Items[CbCapaUnits.ItemIndex];
lengthUnits := CbLengthUnits.Items[CbLengthUnits.ItemIndex];
// Capacitance
TxtCapa.Text := FormatFloat(capaFmt, capa / fc);
// Capacitance per length
TxtCapaPerLengthUnits.caption := Format('%s/%s', [capaUnits, lengthUnits]);
TxtCapaPerLength.Text := FormatFloat(CapaPerLengthFormat, capa / L * fL / fc);
// Notification of accuracy
if Assigned(OnCalcComplete) then begin
Wd := W / d;
Hd := H / d;
if (Wd > 0.3) and (Hd < 10) then begin
if (Wd > 1.0) and (Hd > 0.1) and (Hd <=4) then
OnCalcComplete(self, SAccuracy2Percent, true)
else
OnCalcComplete(self, SAccuracy6Percent, true);
end else
OnCalcComplete(self, SInaccurate, false);
end;
except
ClearResults;
end;
end;
procedure TLinePlaneCapFrame.ClearResults;
begin
TxtCapa.Clear;
TxtCapaPerLength.Clear;
end;
procedure TLinePlaneCapFrame.ReadFromIni(ini: TCustomIniFile);
var
fs: TFormatSettings;
s: String;
value: Extended;
begin
inherited ReadFromIni(ini);
fs := DefaultFormatSettings;
fs.DecimalSeparator := '.';
s := ini.ReadString(FIniKey, 'Height', '');
if (s <> '') and TryStrToFloat(s, value, fs) then
EdHeight.Text := FloatToStr(value) else
EdHeight.Clear;
s := ini.ReadString(FIniKey, 'Height units', '');
if (s <> '') then
CbHeightUnits.ItemIndex := CbHeightUnits.Items.IndexOf(s) else
CbHeightUnits.ItemIndex := -1;
// This control are inherited but not used. It needs a good default values.
// Otherwise it would not pass the validity check.
CbAreaUnits.ItemIndex := 0;
Calculate;
end;
procedure TLinePlaneCapFrame.SetEditLeft(AValue: Integer);
begin
if AValue = FEditLeft then exit;
FEditLeft := AValue;
EdDist.Left := FEditLeft;
TxtCapa.Left := FEditLeft;
TxtCapa.Width := EdDist.Width;
Panel1. Height := TxtCapaPerLength.Top + TxtCapaPerLength.Height + TxtCapa.Top;
Width := CbDistUnits.Left + CbDistUnits.Width + 2*FControlDist + ImagePanel.Width;
end;
function TLinePlaneCapFrame.ValidData(out AMsg: String; out AControl: TWinControl
): Boolean;
begin
Result := inherited ValidData(AMsg, AControl);
if not Result then
exit;
if not IsValidPositive(EdHeight, AMsg) then begin
AControl := EdHeight;
exit;
end;
Result := true;
end;
procedure TLinePlaneCapFrame.WriteToIni(ini: TCustomIniFile);
var
fs: TFormatSettings;
value: Extended;
begin
inherited WriteToIni(ini);
fs := DefaultFormatSettings;
fs.DecimalSeparator := '.';
if (EdHeight.Text <> '') and TryStrToFloat(EdHeight.Text, value) then
ini.WriteString(FIniKEy, 'Height', FloatToStr(value, fs));
if CbHeightUnits.ItemIndex >= 0 then
ini.WriteString(FIniKey, 'Height units', CbHeightUnits.Items[CbHeightUnits.ItemIndex]);
end;
end.
|
unit ULogin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FMTBcd, DB, SqlExpr, StdCtrls;
type
TLoginForm = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Edt_Password: TEdit;
Edt_id: TEdit;
Label4: TLabel;
btn_OK: TButton;
btn_cancel: TButton;
procedure OKBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btn_cancelClick(Sender: TObject);
private
{ Private declarations }
var
checked: boolean;
public
function getChecked: boolean;
{ Public declarations }
end;
var
LoginForm: TLoginForm;
implementation
uses Uds_dm;
{$R *.dfm}
procedure TLoginForm.btn_cancelClick(Sender: TObject);
begin
LoginForm.Close;
end;
procedure TLoginForm.FormCreate(Sender: TObject);
begin
checked := false;
end;
procedure TLoginForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
SelectNext((ActiveControl as TWinControl), true, true);
end;
function TLoginForm.getChecked: boolean;
begin
result := checked;
end;
procedure TLoginForm.OKBtnClick(Sender: TObject);
begin
if (Edt_id.Text = '') then
raise Exception.Create('아이디를 입력해주세요')
else if (Edt_Password.Text = '') then
raise Exception.Create('패스워드를 입력해주세요');
dm.MyQuery.Close;
dm.MyQuery.Params[0].AsString := Edt_id.Text;
dm.MyQuery.Open;
if dm.MyQuery.IsEmpty then
raise Exception.Create('아이디가 없습니다.');
if dm.MyQuery.FieldByName('emp_passwd').AsString <> Edt_Password.Text then
raise Exception.Create('패스워드가 틀립니다.');
checked := true;
LoginForm.Close;
end;
end.
|
unit parsedef;
(*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* This code was inspired to expidite the creation of unit tests
* for use the Dunit test frame work.
*
* The Initial Developer of XPGen is Michael A. Johnson.
* Portions created The Initial Developer is Copyright (C) 2000.
* Portions created by The DUnit Group are Copyright (C) 2000.
* All rights reserved.
*
* Contributor(s):
* Michael A. Johnson <majohnson@golden.net>
* Juanco Aņez <juanco@users.sourceforge.net>
* Chris Morris <chrismo@users.sourceforge.net>
* Jeff Moore <JeffMoore@users.sourceforge.net>
* The DUnit group at SourceForge <http://dunit.sourceforge.net>
*
*)
{
Unit : parsedef
Description : provides an enumeration of reserved words and a map for determing
the "type" of a token
Programmer : Michael Johnson
Date : 30-Jun-2000
}
interface
type
token_enum =
( kw_comma,kw_quote,kw_colon,kw_ptr,kw_equal,kw_openParen, kw_closeParen, kw_openBracket, kw_closeBracket,
kw_semi, kw_endPr, kw_type, kw_and, kw_array,
kw_as, kw_asm, kw_begin, kw_case, kw_class,
kw_const, kw_constructor, kw_destructor, kw_dispinterface, kw_div,
kw_do, kw_downto, kw_else, kw_end, kw_except, kw_exports,
kw_file, kw_finalization, kw_finally, kw_for, kw_function, kw_goto,
kw_if, kw_implementation, kw_in, kw_inherited, kw_initialization, kw_inline,
kw_interface, kw_is, kw_label, kw_library, kw_mod, kw_nil,
kw_not, kw_object, kw_of, kw_or, kw_out, kw_packed,
kw_procedure, kw_program, kw_property, kw_raise, kw_record, kw_repeat,
kw_resourcestring, kw_set, kw_shl, kw_shr, kw_string, kw_then,
kw_threadvar, kw_to, kw_try,kw_unit, kw_until,
kw_uses, kw_var, kw_while, kw_with, kw_xor, kw_private,
kw_protected, kw_public, kw_published, kw_automated, kw_ident);
MethodVisibility = kw_private..kw_automated;
const
token_map : array[token_enum] of string =
(',', '''',':','^','=','(', ')', '[', ']',
';', '.', 'type', 'and', 'array',
'as', 'asm', 'begin', 'case', 'class',
'const', 'constructor', 'destructor', 'dispinterface', 'div',
'do', 'downto', 'else', 'end', 'except', 'exports',
'file', 'finalization', 'finally', 'for', 'function', 'goto',
'if', 'implementation', 'in', 'inherited', 'initialization', 'inline',
'interface', 'is', 'label', 'library', 'mod', 'nil',
'not', 'object', 'of', 'or', 'out', 'packed',
'procedure', 'program', 'property', 'raise', 'record', 'repeat',
'resourcestring', 'set', 'shl', 'shr', 'string', 'then',
'threadvar', 'to', 'try', 'unit', 'until',
'uses', 'var', 'while', 'with', 'xor', 'private',
'protected', 'public', 'published', 'automated', ''
);
function TokenToTokenType(token: string): token_enum;
implementation
uses
SysUtils;
function TokenToTokenType(token: string): token_enum;
{
Function : TokenToTokenType
Description : maps the input token to a token type, if nothing matches it falls
into the category of ident
Input : token to match
Output : matched dotken
Programmer : mike
Date : 30-Jun-2000
}
var
iter: token_enum;
begin
result := kw_ident; { assume an identifier }
token := lowercase(token);
for iter := low(token_enum) to high(token_enum) do
begin
if token_map[iter] = token then
begin
result := iter;
{ stop looping when we get here }
end;
end;
end;
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit RouteHandlerImpl;
interface
{$MODE OBJFPC}
uses
RequestIntf,
ResponseIntf,
MiddlewareIntf,
MiddlewareCollectionIntf,
MiddlewareCollectionAwareIntf,
RouteHandlerIntf,
PlaceholderTypes;
type
(*!------------------------------------------------
* basic abstract class that can act as route handler
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
* -----------------------------------------------*)
TRouteHandler = class(TInterfacedObject, IRouteHandler, IMiddlewareCollectionAware)
private
beforeMiddlewareList : IMiddlewareCollection;
afterMiddlewareList : IMiddlewareCollection;
varPlaceholders : TArrayOfPlaceholders;
public
constructor create(
const beforeMiddlewares : IMiddlewareCollection;
const afterMiddlewares : IMiddlewareCollection
);
destructor destroy(); override;
function addBefore(const middleware : IMiddleware) : IMiddlewareCollectionAware;
function addAfter(const middleware : IMiddleware) : IMiddlewareCollectionAware;
function getMiddlewares() : IMiddlewareCollectionAware;
function getBefore() : IMiddlewareCollection;
function getAfter() : IMiddlewareCollection;
function handleRequest(
const request : IRequest;
const response : IResponse
) : IResponse; virtual; abstract;
(*!-------------------------------------------
* Set route argument data
*--------------------------------------------*)
function setArgs(const placeHolders : TArrayOfPlaceholders) : IRouteHandler;
(*!-------------------------------------------
* get route argument data
*--------------------------------------------*)
function getArgs() : TArrayOfPlaceholders;
(*!-------------------------------------------
* get single route argument data
*--------------------------------------------*)
function getArg(const key : string) : TPlaceholder;
end;
implementation
uses
ERouteArgNotFoundImpl;
resourcestring
sRouteArgNotFound = 'Route argument %s not found';
constructor TRouteHandler.create(
const beforeMiddlewares : IMiddlewareCollection;
const afterMiddlewares : IMiddlewareCollection
);
begin
beforeMiddlewareList := beforeMiddlewares;
afterMiddlewareList := afterMiddlewares;
varPlaceholders := nil;
end;
destructor TRouteHandler.destroy();
begin
inherited destroy();
beforeMiddlewareList := nil;
afterMiddlewareList := nil;
varPlaceholders := nil;
end;
function TRouteHandler.addBefore(const middleware : IMiddleware) : IMiddlewareCollectionAware;
begin
beforeMiddlewareList.add(middleware);
result := self;
end;
function TRouteHandler.addAfter(const middleware : IMiddleware) : IMiddlewareCollectionAware;
begin
afterMiddlewareList.add(middleware);
result := self;
end;
function TRouteHandler.getBefore() : IMiddlewareCollection;
begin
result := beforeMiddlewareList;
end;
function TRouteHandler.getAfter() : IMiddlewareCollection;
begin
result := afterMiddlewareList;
end;
function TRouteHandler.getMiddlewares() : IMiddlewareCollectionAware;
begin
result := self;
end;
(*!-------------------------------------------
* Set route argument data
*--------------------------------------------*)
function TRouteHandler.setArgs(const placeHolders : TArrayOfPlaceholders) : IRouteHandler;
begin
varPlaceholders := placeHolders;
result := self;
end;
(*!-------------------------------------------
* get route argument data
*--------------------------------------------*)
function TRouteHandler.getArgs() : TArrayOfPlaceholders;
begin
result := varPlaceholders;
end;
(*!-------------------------------------------
* get single route argument data
*--------------------------------------------*)
function TRouteHandler.getArg(const key : string) : TPlaceholder;
var i, len:integer;
begin
len := length(varPlaceholders);
for i:=0 to len-1 do
begin
if (key = varPlaceholders[i].phName) then
begin
result := varPlaceholders[i];
exit;
end;
end;
raise ERouteArgNotFound.createFmt(sRouteArgNotFound, [key]);
end;
end.
|
unit PascalCoin.RPC.Test.Payload;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.ScrollBox, FMX.Memo, FMX.ListBox, FMX.Edit, FMX.Controls.Presentation,
FMX.Layouts;
type
TPayloadTest = class(TFrame)
Layout1: TLayout;
Label1: TLabel;
Payload: TEdit;
Layout2: TLayout;
Label2: TLabel;
EncMethod: TComboBox;
Layout3: TLayout;
Label3: TLabel;
PayloadEncryptor: TEdit;
Layout4: TLayout;
Button1: TButton;
Memo1: TMemo;
Layout5: TLayout;
Label4: TLabel;
ComboBox1: TComboBox;
Button2: TButton;
Layout6: TLayout;
Label5: TLabel;
PrivateKey: TEdit;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
FExpected: string;
public
{ Public declarations }
end;
implementation
{$R *.fmx}
uses PascalCoin.RPC.Interfaces, PascalCoin.Utils.Interfaces, clpConverters, clpEncoders,
PascalCoin.RPC.Test.DM, Spring.Container;
procedure TPayloadTest.Button1Click(Sender: TObject);
var lAPI: IPascalCoinAPI;
lPayload, lEncrypted, lDecrypted: string;
begin
Memo1.ClearContent;
lPayload := GlobalContainer.Resolve<IPascalCoinTools>.StrToHex(Payload.Text);
Memo1.Lines.Add('Payload As HEX');
Memo1.Lines.Add(lPayload);
lAPI := GlobalContainer.Resolve<IPascalCoinAPI>.URI(DM.URI);
if EncMethod.ItemIndex = 0 then
begin
lEncrypted := lAPI.payloadEncryptWithPublicKey(lPayload, PayloadEncryptor.Text, TKeyStyle.ksEncKey);
end
else if EncMethod.ItemIndex = 1 then
begin
lEncrypted := lAPI.payloadEncryptWithPublicKey(lPayload, PayloadEncryptor.Text, TKeyStyle.ksB58Key);
end
else
begin
end;
Memo1.Lines.Add('Encrypted Payload');
Memo1.Lines.Add(lEncrypted);
// To do this need to use fixed random
// if FExpected <> '' then
// begin
// if lEncrypted = FExpected then
// Memo1.Lines.Add('as expected')
// else
// begin
// Memo1.Lines.Add('not as expected');
// Memo1.Lines.Add(FExpected);
// end;
// end;
end;
procedure TPayloadTest.Button2Click(Sender: TObject);
begin
if ComboBox1.ItemIndex = 0 then
begin
FExpected := '';
Payload.Text := '';
EncMethod.ItemIndex := 0;
PayloadEncryptor.Text := '';
PrivateKey.Text := '';
end
else if ComboBox1.ItemIndex = 1 then
begin
FExpected := '21100F001000031D0F2029F0A0BDFB7C5E9873D744FE43C26F543C8D1317915E23AD9DA5280F16E4B0D47337128C85B1AB638201B9CBE082BC941A446A4711D8D3B701D2B6C3B3';
Payload.Text := 'EXAMPLE PAYLOAD';
EncMethod.ItemIndex := 1;
PayloadEncryptor.Text := '3GhhbourL5nUHEze1UWHDEdcCX9UMmtNTextd72qDcMuFcwcxnuGV89q2ThCKTKnpg6bAKrQu5JAiFWL1zoUTmq1BQUmDf4yC3VeCd';
PrivateKey.Text := '53616C7465645F5F83AEC09CE4EE2921A75CC62BFBF78C935A45473BF4C5205315B7981E036368B0C24C43E2A0E54F4159DC8A303204892D125F4CCFA1203560';
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.