text stringlengths 14 6.51M |
|---|
unit AsyncIO.Detail.StreamBufferImpl;
interface
uses
System.SysUtils, System.Classes, AsyncIO;
type
StreamBufferImpl = class(TInterfacedObject, StreamBuffer.IStreamBuffer)
strict private
type
StreamBufferStreamImpl = class(TStream)
strict private
FStreamBuffer: StreamBufferImpl;
FPosition: Int64;
protected
function GetSize: Int64; override;
procedure SetSize(NewSize: Longint); override;
procedure SetSize(const NewSize: Int64); override;
public
constructor Create(const StreamBuffer: StreamBufferImpl);
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
end;
strict private
FBuffer: TArray<Byte>;
FMaxBufferSize: integer;
FCommitPosition: UInt64;
FCommitSize: UInt32;
FConsumeSize: UInt64;
FStream: TStream;
public
constructor Create(const MaxBufferSize: UInt64); overload;
destructor Destroy; override;
function GetData: pointer;
function GetBufferSize: UInt64;
function GetMaxBufferSize: UInt64;
function GetStream: TStream;
function PrepareCommit(const Size: UInt32): MemoryBuffer;
procedure Commit(const Size: UInt32);
function PrepareConsume(const Size: UInt32): MemoryBuffer;
procedure Consume(const Size: UInt32);
property BufferSize: UInt64 read GetBufferSize;
property Data: pointer read GetData;
end;
implementation
uses
System.Math;
{$POINTERMATH ON}
{ StreamBufferImpl }
procedure StreamBufferImpl.Commit(const Size: UInt32);
begin
if (Size > FCommitSize) then
raise EArgumentException.Create('ByteStreamAdapter commit size larger than prepared size');
SetLength(FBuffer, FCommitPosition + Size);
end;
procedure StreamBufferImpl.Consume(const Size: UInt32);
var
len: UInt32;
begin
if (Size > FConsumeSize) then
raise EArgumentException.Create('ByteStreamAdapter consume size larger than prepared size');
len := Length(FBuffer);
Move(FBuffer[Size], FBuffer[0], len - Size);
SetLength(FBuffer, len - Size);
end;
constructor StreamBufferImpl.Create(const MaxBufferSize: UInt64);
begin
inherited Create;
FMaxBufferSize := MaxBufferSize;
end;
destructor StreamBufferImpl.Destroy;
begin
FStream.Free;
inherited;
end;
function StreamBufferImpl.GetBufferSize: UInt64;
begin
result := Length(FBuffer);
end;
function StreamBufferImpl.GetData: pointer;
begin
result := @FBuffer[0];
end;
function StreamBufferImpl.GetMaxBufferSize: UInt64;
begin
result := FMaxBufferSize;
end;
function StreamBufferImpl.GetStream: TStream;
begin
if (FStream = nil) then
begin
FStream := StreamBufferStreamImpl.Create(Self);
end;
result := FStream;
end;
function StreamBufferImpl.PrepareCommit(const Size: UInt32): MemoryBuffer;
var
bufSize: UInt32;
begin
bufSize := Length(FBuffer);
SetLength(FBuffer, bufSize + Size);
FCommitSize := Size;
FCommitPosition := bufSize;
result := MakeBuffer(@FBuffer[FCommitPosition], FCommitSize);
end;
function StreamBufferImpl.PrepareConsume(const Size: UInt32): MemoryBuffer;
begin
if (Size > BufferSize) then
raise EArgumentException.Create('StreamBufferImpl.PrepareConsume size larger than buffer size');
FConsumeSize := Size;
result := MakeBuffer(FBuffer, FConsumeSize);
end;
{ StreamBufferImpl.StreamBufferStreamImpl }
constructor StreamBufferImpl.StreamBufferStreamImpl.Create(const StreamBuffer: StreamBufferImpl);
begin
inherited Create;
FStreamBuffer := StreamBuffer;
end;
function StreamBufferImpl.StreamBufferStreamImpl.GetSize: Int64;
begin
result := FStreamBuffer.GetBufferSize;
end;
function StreamBufferImpl.StreamBufferStreamImpl.Read(var Buffer; Count: Integer): Longint;
var
data: PByte;
len: NativeInt;
begin
result := 0;
if (Count <= 0) then
exit;
if (FPosition < 0) then
exit;
if (FPosition >= FStreamBuffer.BufferSize) then
exit;
// non-consuming read
data := PByte(FStreamBuffer.Data) + FPosition;
len := Min(Int64(Count), FStreamBuffer.BufferSize - FPosition);
Move(data^, Buffer, len);
FPosition := FPosition + len;
result := len;
end;
procedure StreamBufferImpl.StreamBufferStreamImpl.SetSize(NewSize: Integer);
begin
SetSize(Int64(NewSize));
end;
function StreamBufferImpl.StreamBufferStreamImpl.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
case Origin of
soBeginning: FPosition := Offset;
soCurrent: FPosition := FPosition + Offset;
soEnd: FPosition := FStreamBuffer.BufferSize - Offset;
else
raise ENotSupportedException.CreateFmt(
'StreamBufferImpl.StreamBufferStreamImpl.Seek: Invalid seek origin (%d)',
[Ord(Origin)]);
end;
result := FPosition;
end;
procedure StreamBufferImpl.StreamBufferStreamImpl.SetSize(const NewSize: Int64);
begin
//raise ENotSupportedException.Create('StreamBufferStreamImpl.SetSize');
end;
function StreamBufferImpl.StreamBufferStreamImpl.Write(const Buffer; Count: Integer): Longint;
var
buf: MemoryBuffer;
begin
if (FPosition <> FStreamBuffer.BufferSize) then
raise ENotSupportedException.Create('StreamBufferImpl.StreamBufferStreamImpl.Write: Unsupported writing position (must be at end of stream)');
result := 0;
if (Count <= 0) then
exit;
buf := FStreamBuffer.PrepareCommit(Count);
Move(Buffer, buf.Data^, Count);
FStreamBuffer.Commit(Count);
FPosition := FPosition + Count;
result := Count;
end;
end.
|
/// <summary>
/// Provides interfaces for working with the projects and logentries tables
/// of our database. NOTE:!! The IProjectData and ILogData interfaces and
/// their respective implementations are sufficiently similar that it may
/// make sense to use Generics instead of individual interfaces /
/// implementations. In this case, each interface and class is kept
/// separate for simplicity, however, generics would make for easier
/// scaling of this CRUD based system.
/// </summary>
unit fieldlogger.data;
interface
uses
FMX.Graphics, classes, data.DB, FireDAC.Comp.Client;
type
{$REGION ' Project Data'}
/// <summary>
/// A record representing a single entry into the projects database table.
/// </summary>
TProject = record
ID: uint32;
Title: string;
Description: string;
end;
/// <summary>
/// Dynamic array of TProject for passing collections of projects to
/// IProjectData.
/// </summary>
TArrayOfProject = array of TProject;
/// <summary>
/// Dynamic array of uint32, used for passing project or log entry
/// ID's to the Delete() methods of IProjectData and ILogData.
/// </summary>
TArrayOfUInt32 = array of uint32;
{$ENDREGION}
{$REGION ' Log Data'}
/// <summary>
/// Used by members of TLogEntry to represent origin, heading, bearing etc.
/// </summary>
TVector = record
X: Double;
Y: Double;
Z: Double;
end;
/// <sumamry>
/// A record representing a single entry into the log_entires database
/// table.
/// </summary>
TLogEntry = record
private
// - Going to store the image data in a dynamic array so that we don't have
// - to marshal a TBitmap.
ImageData: array of uint8;
public
ID: uint32;
ProjectID: uint32;
Longitude: Double;
Latitude: Double;
TimeDateStamp: TDateTime;
Origin: TVector;
Heading: TVector;
Acceleration: TVector;
Angle: TVector;
Distance: Double;
Motion: Double;
Speed: Double;
Note: string;
end;
/// <summary>
/// A dynamic array of log entries.
/// </summary>
TArrayOfLogEntry = array of TLogEntry;
{$ENDREGION}
implementation
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
@abstract(Website : http://www.ormbr.com.br)
@abstract(Telagram : https://t.me/ormbr)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit ormbr.mapping.attributes;
interface
uses
DB,
Rtti,
Classes,
SysUtils,
TypInfo,
Generics.Collections,
ormbr.mapping.exceptions,
ormbr.types.mapping;
type
Entity = class(TCustomAttribute)
private
FName: String;
FSchemaName: String;
public
constructor Create; overload;
constructor Create(AName: string; ASchemaName: String); overload;
property Name: String Read FName;
property SchemaName: String Read FSchemaName;
end;
Table = class(TCustomAttribute)
private
FName: String;
FDescription: string;
public
constructor Create; overload;
constructor Create(AName: String); overload;
constructor Create(AName, ADescription: String); overload;
property Name: String Read FName;
property Description: string read FDescription;
end;
View = class(TCustomAttribute)
private
FName: String;
FDescription: string;
public
constructor Create; overload;
constructor Create(AName: String); overload;
constructor Create(AName, ADescription: String); overload;
property Name: String Read FName;
property Description: string read FDescription;
end;
Trigger = class(TCustomAttribute)
private
FName: String;
FTableName: String;
FDescription: string;
public
constructor Create; overload;
constructor Create(AName, ATableName: String); overload;
constructor Create(AName, ATableName, ADescription: String); overload;
property TableName: String Read FTableName;
property Name: String Read FName;
property Description: string read FDescription;
end;
Sequence = class(TCustomAttribute)
private
FName: string;
FInitial: Integer;
FIncrement: Integer;
public
constructor Create(AName: string; AInitial: Integer = 0; AIncrement: Integer = 1);
property Name: string read FName;
property Initial: Integer read FInitial;
property Increment: Integer read FIncrement;
end;
Column = class(TCustomAttribute)
private
FColumnName: String;
FFieldType: TFieldType;
FScale: Integer;
FSize: Integer;
FPrecision: Integer;
FDescription: string;
public
constructor Create(AColumnName: String; AFieldType: TFieldType; ADescription: string = ''); overload;
constructor Create(AColumnName: string; AFieldType: TFieldType; ASize: Integer; ADescription: string = ''); overload;
constructor Create(AColumnName: string; AFieldType: TFieldType; APrecision, AScale: Integer; ADescription: string = ''); overload;
property ColumnName: String read FColumnName;
property FieldType: TFieldType read FFieldType;
property Size: Integer read FSize;
property Scale: Integer read FScale;
property Precision: Integer read FPrecision;
property Description: string read FDescription;
end;
AggregateField = class(TCustomAttribute)
private
FFieldName: string;
FExpression: string;
FAlignment: TAlignment;
FDisplayFormat: string;
public
constructor Create(AFieldName: string; AExpression: string;
AAlignment: TAlignment = taLeftJustify; ADisplayFormat: string = '');
property FieldName: string read FFieldName;
property Expression: string read FExpression;
property Alignment: TAlignment read FAlignment;
property DisplayFormat: string read FDisplayFormat;
end;
CalcField = class(TCustomAttribute)
private
FFieldName: string;
FFieldType: TFieldType;
FSize: Integer;
FAlignment: TAlignment;
FDisplayFormat: string;
public
constructor Create(AFieldName: string; AFieldType: TFieldType; ASize: Integer = 0;
AAlignment: TAlignment = taLeftJustify; ADisplayFormat: string = '');
property FieldName: string read FFieldName;
property FieldType: TFieldType read FFieldType;
property Size: Integer read FSize;
property Alignment: TAlignment read FAlignment;
property DisplayFormat: string read FDisplayFormat;
end;
/// Association 1:1, 1:N, N:N, N:1
Association = class(TCustomAttribute)
private
FMultiplicity: TMultiplicity;
FColumnsName: TArray<string>;
FTabelNameRef: string;
FColumnsNameRef: TArray<string>;
FColumnsSelectRef: TArray<string>;
public
constructor Create(AMultiplicity: TMultiplicity; AColumnsName, ATableNameRef,
AColumnsNameRef: string; AColumnsSelectRef: string = '');
property Multiplicity: TMultiplicity read FMultiplicity;
property ColumnsName: TArray<string> read FColumnsName;
property TableNameRef: string read FTabelNameRef;
property ColumnsNameRef: TArray<string> read FColumnsNameRef;
property ColumnsSelectRef: TArray<string> read FColumnsSelectRef;
end;
CascadeActions = class(TCustomAttribute)
private
FCascadeActions: TCascadeActions;
public
constructor Create(ACascadeActions: TCascadeActions);
property CascadeActions: TCascadeActions read FCascadeActions;
end;
ForeignKey = class(TCustomAttribute)
private
FName: string;
FTableNameRef: string;
FFromColumns: TArray<string>;
FToColumns: TArray<string>;
FRuleUpdate: TRuleAction;
FRuleDelete: TRuleAction;
FDescription: string;
public
constructor Create(AName, AFromColumns, ATableNameRef, AToColumns: string;
ARuleDelete: TRuleAction = None; ARuleUpdate: TRuleAction = None; ADescription: string = ''); overload;
property Name: string read FName;
property TableNameRef: string read FTableNameRef;
property FromColumns: TArray<string> read FFromColumns;
property ToColumns: TArray<string> read FToColumns;
property RuleDelete: TRuleAction read FRuleDelete;
property RuleUpdate: TRuleAction read FRuleUpdate;
property Description: string read FDescription;
end;
PrimaryKey = class(TCustomAttribute)
private
FColumns: TArray<string>;
FSortingOrder: TSortingOrder;
FUnique: Boolean;
FSequenceType: TSequenceType;
FDescription: string;
public
constructor Create(AColumns, ADescription: string); overload;
constructor Create(AColumns: string; ASequenceType: TSequenceType = NotInc; ASortingOrder: TSortingOrder = NoSort; AUnique: Boolean = False; ADescription: string = ''); overload;
property Columns: TArray<string> read FColumns;
property SortingOrder: TSortingOrder read FSortingOrder;
property Unique: Boolean read FUnique;
property SequenceType: TSequenceType read FSequenceType;
property Description: string read FDescription;
end;
Indexe = class(TCustomAttribute)
private
FName: string;
FColumns: TArray<string>;
FSortingOrder: TSortingOrder;
FUnique: Boolean;
FDescription: string;
public
constructor Create(AName, AColumns, ADescription: string); overload;
constructor Create(AName, AColumns: string; ASortingOrder: TSortingOrder = NoSort;
AUnique: Boolean = False; ADescription: string = ''); overload;
property Name: string read FName;
property Columns: TArray<string> read FColumns;
property SortingOrder: TSortingOrder read FSortingOrder;
property Unique: Boolean read FUnique;
property Description: string read FDescription;
end;
Check = class(TCustomAttribute)
private
FName: string;
FCondition: string;
FDescription: string;
public
constructor Create(AName, ACondition: string; ADescription: string = '');
property Name: string read FName;
property Condition: string read FCondition;
property Description: string read FDescription;
end;
// INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN
JoinColumn = class(TCustomAttribute)
private
FColumnName: string;
FRefTableName: string;
FRefColumnName: string;
FRefColumnNameSelect: string;
FJoin: TJoin;
FAlias: string;
public
constructor Create(AColumnName, ARefTableName, ARefColumnName,
ARefColumnNameSelect: string; AJoin: TJoin = InnerJoin; AAlias: string = '');
property ColumnName: string read FColumnName;
property RefColumnName: string read FRefColumnName;
property RefTableName: string read FRefTableName;
property RefColumnNameSelect: string read FRefColumnNameSelect;
property Join: TJoin read FJoin;
property Alias: string read FAlias;
end;
Restrictions = class(TCustomAttribute)
private
FRestrictions: TRestrictions;
public
constructor Create(ARestrictions: TRestrictions);
property Restrictions: TRestrictions read FRestrictions;
end;
Dictionary = class(TCustomAttribute)
private
FDisplayLabel: string;
FDefaultExpression: string;
FConstraintErrorMessage: string;
FDisplayFormat: string;
FEditMask: string;
FAlignment: TAlignment;
public
constructor Create(ADisplayLabel: string); overload;
constructor Create(ADisplayLabel, AConstraintErrorMessage: string); overload;
constructor Create(ADisplayLabel, AConstraintErrorMessage, ADefaultExpression: string); overload;
constructor Create(ADisplayLabel, AConstraintErrorMessage, ADefaultExpression,
ADisplayFormat: string); overload;
constructor Create(ADisplayLabel, AConstraintErrorMessage, ADefaultExpression,
ADisplayFormat, AEditMask: string); overload;
constructor Create(ADisplayLabel, AConstraintErrorMessage, ADefaultExpression,
ADisplayFormat, AEditMask: string; AAlignment: TAlignment); overload;
constructor Create(ADisplayLabel, AConstraintErrorMessage: string; AAlignment: TAlignment); overload;
property DisplayLabel: string read FDisplayLabel;
property ConstraintErrorMessage: string read FConstraintErrorMessage;
property DefaultExpression: string read FDefaultExpression;
property DisplayFormat: string read FDisplayFormat;
property EditMask: string read FEditMask;
property Alignment: TAlignment read FAlignment;
end;
OrderBy = class(TCustomAttribute)
private
FColumnsName: string;
public
constructor Create(AColumnsName: string);
property ColumnsName: string read FColumnsName;
end;
Enumeration = class(TCustomAttribute)
private
FEnumType: TEnumType;
FEnumValues: TList<Variant>;
function ValidateEnumValue(AValue: string): string;
public
constructor Create(AEnumType: TEnumType; AEnumValues: string);
destructor Destroy; override;
property EnumType: TEnumType read FEnumType;
property EnumValues: TList<Variant> read FEnumValues;
end;
NotNullConstraint = class(TCustomAttribute)
public
constructor Create;
procedure Validate(AName: string; AValue: TValue);
end;
ZeroConstraint = class(TCustomAttribute)
public
constructor Create;
procedure Validate(AName: string; AValue: TValue);
end;
implementation
{ Table }
constructor Table.Create;
begin
Create('');
end;
constructor Table.Create(AName: String);
begin
Create(AName, '');
end;
constructor Table.Create(AName, ADescription: String);
begin
FName := AName;
FDescription := ADescription;
end;
{ View }
constructor View.Create;
begin
Create('');
end;
constructor View.Create(AName: String);
begin
Create(AName, '');
end;
constructor View.Create(AName, ADescription: String);
begin
FName := AName;
FDescription := ADescription;
end;
{ ColumnDictionary }
constructor Dictionary.Create(ADisplayLabel: string);
begin
FAlignment := taLeftJustify;
FDisplayLabel := ADisplayLabel;
end;
constructor Dictionary.Create(ADisplayLabel, AConstraintErrorMessage: string);
begin
Create(ADisplayLabel);
FConstraintErrorMessage := AConstraintErrorMessage;
end;
constructor Dictionary.Create(ADisplayLabel, AConstraintErrorMessage, ADefaultExpression: string);
begin
Create(ADisplayLabel, AConstraintErrorMessage);
FDefaultExpression := ADefaultExpression;
end;
constructor Dictionary.Create(ADisplayLabel, AConstraintErrorMessage, ADefaultExpression, ADisplayFormat: string);
begin
Create(ADisplayLabel, AConstraintErrorMessage, ADefaultExpression);
FDisplayFormat := ADisplayFormat;
end;
constructor Dictionary.Create(ADisplayLabel,
AConstraintErrorMessage, ADefaultExpression, ADisplayFormat, AEditMask: string;
AAlignment: TAlignment);
begin
Create(ADisplayLabel, AConstraintErrorMessage, ADefaultExpression, ADisplayFormat, AEditMask);
FAlignment := AAlignment;
end;
constructor Dictionary.Create(ADisplayLabel, AConstraintErrorMessage,
ADefaultExpression, ADisplayFormat, AEditMask: string);
begin
Create(ADisplayLabel, AConstraintErrorMessage, ADefaultExpression, ADisplayFormat);
FEditMask := AEditMask;
end;
constructor Dictionary.Create(ADisplayLabel, AConstraintErrorMessage: string;
AAlignment: TAlignment);
begin
Create(ADisplayLabel, AConstraintErrorMessage);
FAlignment := AAlignment;
end;
{ Column }
constructor Column.Create(AColumnName: String; AFieldType: TFieldType; ADescription: string);
begin
Create(AColumnName, AFieldType, 0, ADescription);
end;
constructor Column.Create(AColumnName: string; AFieldType: TFieldType; ASize: Integer; ADescription: string);
begin
Create(AColumnName, AFieldType, 0, 0, ADescription);
FSize := ASize;
end;
constructor Column.Create(AColumnName: string; AFieldType: TFieldType; APrecision, AScale: Integer; ADescription: string);
begin
FColumnName := AColumnName;
FFieldType := AFieldType;
FPrecision := APrecision;
FScale := AScale;
FDescription := ADescription;
end;
{ ColumnRestriction }
constructor Restrictions.Create(ARestrictions: TRestrictions);
begin
FRestrictions := ARestrictions;
end;
{ NotNull }
constructor NotNullConstraint.Create;
begin
end;
procedure NotNullConstraint.Validate(AName: string; AValue: TValue);
begin
if AValue.AsString = '' then
begin
raise EFieldNotNull.Create(AName);
end;
end;
{ Association }
constructor Association.Create(AMultiplicity: TMultiplicity; AColumnsName, ATableNameRef,
AColumnsNameRef: string; AColumnsSelectRef: string);
var
rColumns: TStringList;
iFor: Integer;
begin
FMultiplicity := AMultiplicity;
/// ColumnsName
if Length(AColumnsName) > 0 then
begin
rColumns := TStringList.Create;
try
rColumns.Duplicates := dupError;
ExtractStrings([',', ';'], [' '], PChar(AColumnsName), rColumns);
SetLength(FColumnsName, rColumns.Count);
for iFor := 0 to rColumns.Count -1 do
FColumnsName[iFor] := Trim(rColumns[iFor]);
finally
rColumns.Free;
end;
end;
FTabelNameRef := ATableNameRef;
/// ColumnsNameRef
if Length(AColumnsNameRef) > 0 then
begin
rColumns := TStringList.Create;
try
rColumns.Duplicates := dupError;
ExtractStrings([',', ';'], [' '], PChar(AColumnsNameRef), rColumns);
SetLength(FColumnsNameRef, rColumns.Count);
for iFor := 0 to rColumns.Count -1 do
FColumnsNameRef[iFor] := Trim(rColumns[iFor]);
finally
rColumns.Free;
end;
end;
/// ColumnsSelect
if (Length(AColumnsSelectRef) > 0) and (AColumnsSelectRef <> '*') then
begin
rColumns := TStringList.Create;
try
rColumns.Duplicates := dupError;
ExtractStrings([',', ';'], [' '], PChar(AColumnsSelectRef), rColumns);
SetLength(FColumnsSelectRef, rColumns.Count);
for iFor := 0 to rColumns.Count -1 do
FColumnsSelectRef[iFor] := Trim(rColumns[iFor]);
finally
rColumns.Free;
end;
end;
end;
{ JoinColumn }
constructor JoinColumn.Create(AColumnName, ARefTableName, ARefColumnName,
ARefColumnNameSelect: string; AJoin: TJoin; AAlias: string);
begin
FColumnName := AColumnName;
FRefTableName := ARefTableName;
FRefColumnName := ARefColumnName;
FRefColumnNameSelect := ARefColumnNameSelect;
FJoin := AJoin;
FAlias := AAlias;
end;
{ ForeignKey }
constructor ForeignKey.Create(AName, AFromColumns, ATableNameRef, AToColumns: string;
ARuleDelete, ARuleUpdate: TRuleAction; ADescription: string);
var
rColumns: TStringList;
iFor: Integer;
begin
FName := AName;
FTableNameRef := ATableNameRef;
if Length(AFromColumns) > 0 then
begin
rColumns := TStringList.Create;
try
rColumns.Duplicates := dupError;
ExtractStrings([',', ';'], [' '], PChar(AFromColumns), rColumns);
SetLength(FFromColumns, rColumns.Count);
for iFor := 0 to rColumns.Count -1 do
FFromColumns[iFor] := Trim(rColumns[iFor]);
finally
rColumns.Free;
end;
end;
if Length(AToColumns) > 0 then
begin
rColumns := TStringList.Create;
try
rColumns.Duplicates := dupError;
ExtractStrings([',', ';'], [' '], PChar(AToColumns), rColumns);
SetLength(FToColumns, rColumns.Count);
for iFor := 0 to rColumns.Count -1 do
FToColumns[iFor] := Trim(rColumns[iFor]);
finally
rColumns.Free;
end;
end;
FRuleDelete := ARuleDelete;
FRuleUpdate := ARuleUpdate;
FDescription := ADescription;
end;
{ PrimaryKey }
constructor PrimaryKey.Create(AColumns, ADescription: string);
begin
Create(AColumns, NotInc, NoSort, False, ADescription);
end;
constructor PrimaryKey.Create(AColumns: string; ASequenceType: TSequenceType;
ASortingOrder: TSortingOrder; AUnique: Boolean; ADescription: string);
var
rColumns: TStringList;
iFor: Integer;
begin
if Length(AColumns) > 0 then
begin
rColumns := TStringList.Create;
try
rColumns.Duplicates := dupError;
ExtractStrings([',', ';'], [' '], PChar(AColumns), rColumns);
SetLength(FColumns, rColumns.Count);
for iFor := 0 to rColumns.Count -1 do
FColumns[iFor] := Trim(rColumns[iFor]);
finally
rColumns.Free;
end;
end;
FSequenceType := ASequenceType;
FSortingOrder := ASortingOrder;
FUnique := AUnique;
FDescription := ADescription;
end;
{ Catalog }
constructor Entity.Create(AName: string; ASchemaName: String);
begin
FName := AName;
FSchemaName := ASchemaName;
end;
constructor Entity.Create;
begin
Create('','');
end;
{ ZeroConstraint }
constructor ZeroConstraint.Create;
begin
end;
procedure ZeroConstraint.Validate(AName: string; AValue: TValue);
begin
if AValue.AsInteger < 0 then
begin
raise EFieldZero.Create(AName);
end;
end;
{ Sequence }
constructor Sequence.Create(AName: string; AInitial, AIncrement: Integer);
begin
FName := AName;
FInitial := AInitial;
FIncrement := AIncrement;
end;
{ Trigger }
constructor Trigger.Create;
begin
Create('','');
end;
constructor Trigger.Create(AName, ATableName: String);
begin
Create(AName, ATableName, '')
end;
constructor Trigger.Create(AName, ATableName, ADescription: String);
begin
FName := AName;
FTableName := ATableName;
FDescription := ADescription;
end;
{ Indexe }
constructor Indexe.Create(AName, AColumns, ADescription: string);
begin
Create(AName, AColumns, NoSort, False, ADescription);
end;
constructor Indexe.Create(AName, AColumns: string; ASortingOrder: TSortingOrder;
AUnique: Boolean; ADescription: string);
var
rColumns: TStringList;
iFor: Integer;
begin
FName := AName;
if Length(AColumns) > 0 then
begin
rColumns := TStringList.Create;
try
rColumns.Duplicates := dupError;
ExtractStrings([',', ';'], [' '], PChar(AColumns), rColumns);
SetLength(FColumns, rColumns.Count);
for iFor := 0 to rColumns.Count -1 do
FColumns[iFor] := Trim(rColumns[iFor]);
finally
rColumns.Free;
end;
end;
FSortingOrder := ASortingOrder;
FUnique := AUnique;
FDescription := ADescription;
end;
{ Check }
constructor Check.Create(AName, ACondition, ADescription: string);
begin
FName := AName;
FCondition := ACondition;
FDescription := ADescription;
end;
{ OrderBy }
constructor OrderBy.Create(AColumnsName: string);
begin
FColumnsName := AColumnsName;
end;
{ AggregateField }
constructor AggregateField.Create(AFieldName, AExpression: string;
AAlignment: TAlignment; ADisplayFormat: string);
begin
FFieldName := AFieldName;
FExpression := AExpression;
FAlignment := AAlignment;
FDisplayFormat := ADisplayFormat;
end;
{ CalcField }
constructor CalcField.Create(AFieldName: string; AFieldType: TFieldType;
ASize: Integer; AAlignment: TAlignment; ADisplayFormat: string);
begin
FFieldName := AFieldName;
FFieldType := AFieldType;
FSize := ASize;
FAlignment := AAlignment;
FDisplayFormat := ADisplayFormat;
end;
{ CascadeActions }
constructor CascadeActions.Create(ACascadeActions: TCascadeActions);
begin
FCascadeActions := ACascadeActions;
end;
{ Enumeration }
constructor Enumeration.Create(AEnumType: TEnumType; AEnumValues: string);
var
LEnumList: TStringList;
LFor: Integer;
begin
FEnumType := AEnumType;
FEnumValues := TList<Variant>.Create;
LEnumList := TStringList.Create;
try
LEnumList.Duplicates := dupError;
ExtractStrings([',', ';'], [' '], PChar(AEnumValues), LEnumList);
for LFor := 0 to LEnumList.Count - 1 do
FEnumValues.Add(ValidateEnumValue(LEnumList[LFor]));
finally
LEnumList.Free;
end;
end;
destructor Enumeration.Destroy;
begin
FEnumValues.Free;
inherited;
end;
function Enumeration.ValidateEnumValue(AValue: string): string;
begin
Result := AValue;
{$IFDEF NEXTGEN}
if (AValue.Length <> 1) or not CharInSet(AValue.Chars[0], ['A'..'Z', '0'..'9']) then
{$ELSE}
if (Length(AValue) <> 1) or not CharInSet(AValue[1], ['A'..'Z', '0'..'9']) then
{$ENDIF}
raise Exception.CreateFmt('Enumeration definido "%s" inválido para o tipo.' +
'Nota: Tipo chars ou strings, defina em maiúsculo.',
[AValue]);
end;
end.
|
unit uOrder;
interface
type
TOrder = class
private
FID: integer;
public
constructor Create(aID: integer);
property ID: integer read FID;
end;
implementation
{ TOrder }
constructor TOrder.Create(aID: integer);
begin
inherited Create;
FID := aID;
end;
end.
|
unit StatePoster;
interface
uses PersistentObjects, DBGate, BaseObjects, DB, State;
type
// для причин ликвидации
TAbandonReasonDataPoster = class(TImplementedDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
// для причин ликвидации скважины
TAbandonReasonWellDataPoster = class(TImplementedDataPoster)
private
FAllAbandonReasons: TAbandonReasons;
procedure SetAllAbandonReasons(const Value: TAbandonReasons);
public
property AllAbandonReasons: TAbandonReasons read FAllAbandonReasons write SetAllAbandonReasons;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
// для состояний скважин
TStateDataPoster = class(TImplementedDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
implementation
uses Facade, SysUtils;
{ TStateDataPoster }
constructor TStateDataPoster.Create;
begin
inherited;
Options := [];
DataSourceString := 'TBL_WELL_STATUS_DICT';
DataDeletionString := '';
DataPostString := '';
KeyFieldNames := 'WELL_STATE_ID';
FieldNames := 'WELL_STATE_ID, VCH_WELL_STATE_NAME';
AccessoryFieldNames := '';
AutoFillDates := false;
Sort := 'VCH_WELL_STATE_NAME';
end;
function TStateDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TStateDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TState;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TState;
o.ID := ds.FieldByName('WELL_STATE_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_WELL_STATE_NAME').AsString);
ds.Next;
end;
ds.First;
end;
end;
function TStateDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
{ TAbandonReasonDataPoster }
constructor TAbandonReasonDataPoster.Create;
begin
inherited;
Options := [];
DataSourceString := 'TBL_ABANDON_REASON_DICT';
DataDeletionString := '';
DataPostString := '';
KeyFieldNames := 'ABANDON_REASON_ID';
FieldNames := 'ABANDON_REASON_ID, VCH_ABANDON_REASON';
AccessoryFieldNames := '';
AutoFillDates := false;
Sort := 'VCH_ABANDON_REASON';
end;
function TAbandonReasonDataPoster.DeleteFromDB(
AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TAbandonReasonDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TAbandonReason;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TAbandonReason;
o.ID := ds.FieldByName('ABANDON_REASON_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_ABANDON_REASON').AsString);
ds.Next;
end;
ds.First;
end;
end;
function TAbandonReasonDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
{ TAbandonReasonWellDataPoster }
constructor TAbandonReasonWellDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_ABANDONED_WELL';
KeyFieldNames := 'WELL_UIN';
FieldNames := 'WELL_UIN, ABANDON_REASON_ID, DTM_ABANDON_DATE';
AccessoryFieldNames := 'WELL_UIN, ABANDON_REASON_ID, DTM_ABANDON_DATE';
AutoFillDates := false;
Sort := 'WELL_UIN';
end;
function TAbandonReasonWellDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TAbandonReasonWellDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TAbandonReasonWell;
Sourse: TAbandonReasonWell;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TAbandonReasonWell;
if Assigned (FAllAbandonReasons) then
begin
Sourse := TAbandonReasonWell(FAllAbandonReasons.ItemsByID[ds.FieldByName('ABANDON_REASON_ID').AsInteger]);
if Assigned (Sourse) then o.Assign(Sourse);
end;
o.DtLiquidation := ds.FieldByName('DTM_ABANDON_DATE').AsDateTime;
ds.Next;
end;
ds.First;
end;
end;
function TAbandonReasonWellDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o : TAbandonReasonWell;
bIsEditing: Boolean;
begin
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
o := AObject as TAbandonReasonWell;
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
bIsEditing := False;
if ds.Locate('WELL_UIN', o.Collection.Owner.ID, []) then
begin
ds.Edit;
bIsEditing := true;
end;
if not bIsEditing then ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
ds := TMainFacade.GetInstance.DBGates.Add(Self);
ds.FieldByName('WELL_UIN').AsInteger := o.Collection.Owner.ID;
ds.FieldByName('ABANDON_REASON_ID').AsInteger := o.ID;
ds.FieldByName('DTM_ABANDON_DATE').Value := DateToStr(o.DtLiquidation);
ds.Post;
end;
procedure TAbandonReasonWellDataPoster.SetAllAbandonReasons(
const Value: TAbandonReasons);
begin
if FAllAbandonReasons <> Value then
FAllAbandonReasons := Value;
end;
end.
|
{******************************************************************************}
{** A Base64 encoding unit ****************************************************}
{******************************************************************************}
{** Written by David Barton (davebarton@bigfoot.com) **************************}
{** http://www.scramdisk.clara.net/ *******************************************}
{** corrected by M.Lach (mlach@mlach.com) based on ****************************}
{** LibTomCrypt, modular cryptographic library -- Tom St Denis ***************}
{******************************************************************************}
unit Base64;
interface
uses
Sysutils;
{ Base64 encode and decode a string }
function B64Encode(const S: array of Byte; Len: Int64): string;
function B64Decode(const S: array of Byte; Len: Int64): string;
{******************************************************************************}
{******************************************************************************}
implementation
const
B64Table= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
(*
code from LibTomCrypt, modular cryptographic library -- Tom St Denis
p = out;
leven = 3*(inlen / 3);
for (i = 0; i < leven; i += 3) {
*p++ = codes[(in[0] >> 2) & 0x3F];
*p++ = codes[(((in[0] & 3) << 4) + (in[1] >> 4)) & 0x3F];
*p++ = codes[(((in[1] & 0xf) << 2) + (in[2] >> 6)) & 0x3F];
*p++ = codes[in[2] & 0x3F];
in += 3;
}
if (i < inlen) {
unsigned a = in[0];
unsigned b = (i+1 < inlen) ? in[1] : 0;
*p++ = codes[(a >> 2) & 0x3F];
*p++ = codes[(((a & 3) << 4) + (b >> 4)) & 0x3F];
*p++ = (i+1 < inlen) ? codes[(((b & 0xf) << 2)) & 0x3F] : '=';
*p++ = '=';
}
*)
function B64Encode(const S: array of Byte; Len: Int64): string;
var
i: integer;
InBuf: array[0..2] of byte;
OutBuf: array[0..3] of char;
leven: integer;
last: integer;
begin
// SetLength(Result,((Length(S)+2) div 3)*4);
SetLength(Result,((Len+2) div 3)*4);
leven:= (Len div 3);
last:= Len mod 3;
for i:= 1 to leven do
begin
Move(S[(i-1)*3{+1}],InBuf,3);
OutBuf[0]:= B64Table[((InBuf[0] shr 2) and $3F) + 1];
OutBuf[1]:= B64Table[(((InBuf[0] and $03) shl 4) or ((InBuf[1] shr 4) and $3F)) + 1];
OutBuf[2]:= B64Table[(((InBuf[1] and $0F) shl 2) or ((InBuf[2] shr 6 ) and $3F)) + 1];
OutBuf[3]:= B64Table[(InBuf[2] and $3F) + 1];
Move(OutBuf,Result[(i-1)*4+1],4);
end;
if (last>0) then begin
Move(S[leven*3{+1}],InBuf,last);
OutBuf[0]:= B64Table[((InBuf[0] shr 2) and $3F) + 1];
if (last=2) then begin
OutBuf[2]:= B64Table[(((InBuf[1] and $0F) shl 2) and $3F) + 1];
end else begin
InBuf[1]:=0;
OutBuf[2]:='=';
end;
OutBuf[1]:= B64Table[(((InBuf[0] and $03) shl 4) or ((InBuf[1] shr 4) and $3F)) + 1];
OutBuf[3]:='=';
Move(OutBuf,Result[leven*4+1],4);
end;
end;
function B64Decode(const S: array of Byte; Len: Int64): string;
var
i: integer;
InBuf: array[0..3] of byte;
OutBuf: array[0..2] of byte;
begin
if (Len mod 4)<> 0 then begin
raise Exception.Create('Base64: Incorrect string format');
end;
SetLength(Result,((Len div 4)-1)*3);
for i:= 1 to ((Len div 4)-1) do
begin
Move(S[(i-1)*4{+1}],InBuf,4);
if (InBuf[0]> 64) and (InBuf[0]< 91) then
Dec(InBuf[0],65)
else if (InBuf[0]> 96) and (InBuf[0]< 123) then
Dec(InBuf[0],71)
else if (InBuf[0]> 47) and (InBuf[0]< 58) then
Inc(InBuf[0],4)
else if InBuf[0]= 43 then
InBuf[0]:= 62
else
InBuf[0]:= 63;
if (InBuf[1]> 64) and (InBuf[1]< 91) then
Dec(InBuf[1],65)
else if (InBuf[1]> 96) and (InBuf[1]< 123) then
Dec(InBuf[1],71)
else if (InBuf[1]> 47) and (InBuf[1]< 58) then
Inc(InBuf[1],4)
else if InBuf[1]= 43 then
InBuf[1]:= 62
else
InBuf[1]:= 63;
if (InBuf[2]> 64) and (InBuf[2]< 91) then
Dec(InBuf[2],65)
else if (InBuf[2]> 96) and (InBuf[2]< 123) then
Dec(InBuf[2],71)
else if (InBuf[2]> 47) and (InBuf[2]< 58) then
Inc(InBuf[2],4)
else if InBuf[2]= 43 then
InBuf[2]:= 62
else
InBuf[2]:= 63;
if (InBuf[3]> 64) and (InBuf[3]< 91) then
Dec(InBuf[3],65)
else if (InBuf[3]> 96) and (InBuf[3]< 123) then
Dec(InBuf[3],71)
else if (InBuf[3]> 47) and (InBuf[3]< 58) then
Inc(InBuf[3],4)
else if InBuf[3]= 43 then
InBuf[3]:= 62
else
InBuf[3]:= 63;
OutBuf[0]:= (InBuf[0] shl 2) or ((InBuf[1] shr 4) and $03);
OutBuf[1]:= (InBuf[1] shl 4) or ((InBuf[2] shr 2) and $0F);
OutBuf[2]:= (InBuf[2] shl 6) or (InBuf[3] and $3F);
Move(OutBuf,Result[(i-1)*3+1],3);
end;
if Len<> 0 then
begin
Move(S[Len-4],InBuf,4);
if InBuf[2]= 61 then
begin
if (InBuf[0]> 64) and (InBuf[0]< 91) then
Dec(InBuf[0],65)
else if (InBuf[0]> 96) and (InBuf[0]< 123) then
Dec(InBuf[0],71)
else if (InBuf[0]> 47) and (InBuf[0]< 58) then
Inc(InBuf[0],4)
else if InBuf[0]= 43 then
InBuf[0]:= 62
else
InBuf[0]:= 63;
if (InBuf[1]> 64) and (InBuf[1]< 91) then
Dec(InBuf[1],65)
else if (InBuf[1]> 96) and (InBuf[1]< 123) then
Dec(InBuf[1],71)
else if (InBuf[1]> 47) and (InBuf[1]< 58) then
Inc(InBuf[1],4)
else if InBuf[1]= 43 then
InBuf[1]:= 62
else
InBuf[1]:= 63;
OutBuf[0]:= (InBuf[0] shl 2) or ((InBuf[1] shr 4) and $03);
Result:= Result + char(OutBuf[0]);
end
else if InBuf[3]= 61 then
begin
if (InBuf[0]> 64) and (InBuf[0]< 91) then
Dec(InBuf[0],65)
else if (InBuf[0]> 96) and (InBuf[0]< 123) then
Dec(InBuf[0],71)
else if (InBuf[0]> 47) and (InBuf[0]< 58) then
Inc(InBuf[0],4)
else if InBuf[0]= 43 then
InBuf[0]:= 62
else
InBuf[0]:= 63;
if (InBuf[1]> 64) and (InBuf[1]< 91) then
Dec(InBuf[1],65)
else if (InBuf[1]> 96) and (InBuf[1]< 123) then
Dec(InBuf[1],71)
else if (InBuf[1]> 47) and (InBuf[1]< 58) then
Inc(InBuf[1],4)
else if InBuf[1]= 43 then
InBuf[1]:= 62
else
InBuf[1]:= 63;
if (InBuf[2]> 64) and (InBuf[2]< 91) then
Dec(InBuf[2],65)
else if (InBuf[2]> 96) and (InBuf[2]< 123) then
Dec(InBuf[2],71)
else if (InBuf[2]> 47) and (InBuf[2]< 58) then
Inc(InBuf[2],4)
else if InBuf[2]= 43 then
InBuf[2]:= 62
else
InBuf[2]:= 63;
OutBuf[0]:= (InBuf[0] shl 2) or ((InBuf[1] shr 4) and $03);
OutBuf[1]:= (InBuf[1] shl 4) or ((InBuf[2] shr 2) and $0F);
Result:= Result + char(OutBuf[0]) + char(OutBuf[1]);
end
else
begin
if (InBuf[0]> 64) and (InBuf[0]< 91) then
Dec(InBuf[0],65)
else if (InBuf[0]> 96) and (InBuf[0]< 123) then
Dec(InBuf[0],71)
else if (InBuf[0]> 47) and (InBuf[0]< 58) then
Inc(InBuf[0],4)
else if InBuf[0]= 43 then
InBuf[0]:= 62
else
InBuf[0]:= 63;
if (InBuf[1]> 64) and (InBuf[1]< 91) then
Dec(InBuf[1],65)
else if (InBuf[1]> 96) and (InBuf[1]< 123) then
Dec(InBuf[1],71)
else if (InBuf[1]> 47) and (InBuf[1]< 58) then
Inc(InBuf[1],4)
else if InBuf[1]= 43 then
InBuf[1]:= 62
else
InBuf[1]:= 63;
if (InBuf[2]> 64) and (InBuf[2]< 91) then
Dec(InBuf[2],65)
else if (InBuf[2]> 96) and (InBuf[2]< 123) then
Dec(InBuf[2],71)
else if (InBuf[2]> 47) and (InBuf[2]< 58) then
Inc(InBuf[2],4)
else if InBuf[2]= 43 then
InBuf[2]:= 62
else
InBuf[2]:= 63;
if (InBuf[3]> 64) and (InBuf[3]< 91) then
Dec(InBuf[3],65)
else if (InBuf[3]> 96) and (InBuf[3]< 123) then
Dec(InBuf[3],71)
else if (InBuf[3]> 47) and (InBuf[3]< 58) then
Inc(InBuf[3],4)
else if InBuf[3]= 43 then
InBuf[3]:= 62
else
InBuf[3]:= 63;
OutBuf[0]:= (InBuf[0] shl 2) or ((InBuf[1] shr 4) and $03);
OutBuf[1]:= (InBuf[1] shl 4) or ((InBuf[2] shr 2) and $0F);
OutBuf[2]:= (InBuf[2] shl 6) or (InBuf[3] and $3F);
Result:= Result + Char(OutBuf[0]) + Char(OutBuf[1]) + Char(OutBuf[2]);
end;
end;
end;
end.
|
UNIT SKRZ;
INTERFACE
uses graph, crt;
type sygnaliz = record
name:string;
red, yellow, green:longint;
state:byte;
x, y:word;
end;
type Stany = array[0..60] of record
LPT:longint; {0 - ilosc, a potem n stanow}
Wait:word;
end;
type Skrzyzowanie = object
{elementy ruchome skrzyzowania}
Lights:array[1..12] of sygnaliz;
Lights_Width, Lights_Height:word;
{globalne wlasciwosci skrzyzowania}
Width:word;
Height, StreetWidth:word;{szerokosc i dlugosc calosci}
X, Y:word; {lewy gorny rog}
Lights_Input:longint;
Lights_Seq:Stany;
Pasy_Width, Pasy_d:word;
{colors}
GrassColor, MainColor:LongInt;
Red_on, Red_off:LongInt;
Yellow_on, Yellow_off:LongInt;
Green_on, Green_off:LongInt;
Lights_Back:LongInt;
{Procedures}
Procedure CountRoute;{oblicza drogi po ktorych bedzie poruszal sie samochodzik}
Procedure Move;{przerysowuje samochodziki, symuluje ich ruch}
Procedure Paint;{tysuje obrys skrzyzowania}
Procedure Lights_Update;
Procedure SetDefault;{ustawia domyslna konfiguracje skrzyzowania}
Procedure SetColour(nazwa, stan:string; var data:LongInt);
Procedure DeleteColor(nazwa, stan:string; var data:LongInt);
Procedure LoadFromFile(var input:text);
{Functions}
end;
Procedure InitMyGraph;
var
gm, gd, i:integer; PathToDriver:string;
IMPLEMENTATION
Procedure Skrzyzowanie.SetColour(nazwa, stan:string; var data:LongInt);
var i:byte;
begin
i:=0;
while (Lights[i].name <> nazwa) and (99>i) do i:=i+1;
if i = 99 then writeln(':', nazwa, ':NOT FOUND! (SetColour)');
if stan = 'red' then data:= data or Lights[i].red
else
if stan = 'yellow' then data:= data or Lights[i].yellow
else
if stan = 'green' then data:= data or Lights[i].green
else writeln('state:', stan, ':NOT FOUND! (SetColour)');
end;
Procedure Skrzyzowanie.DeleteColor(nazwa, stan:string; var data:LongInt);
var i:byte;
begin
i:=0;
while (Lights[i].name <> nazwa) and (99>i) do i:=i+1;
if i = 99 then writeln(':', nazwa, ':NOT FOUND! (DeleteColor)');
if stan = 'red' then data:= data and not ( Lights[i].red)
else
if stan = 'yellow' then data:= data and not( Lights[i].yellow)
else
if stan = 'green' then data:= data and not ( Lights[i].green)
else writeln('state:', stan, ':NOT FOUND! (DeleteColor)');
end;
Procedure Skrzyzowanie.LoadFromFile(var input:text);
var i:byte;
nazwy:array[0..14] of string;
n, j, error:word;
wczyt:char;
waitS:string;
waitW:integer;
data:LongInt;
Function GetBit:boolean;
var b:char; null:string;
Begin
read(input, b);
while (b <> '0') and (b <> '1') do
begin
if b = '#' then
begin
readln(input, null); {pomijanie komentarzy}
end;
read(input, b);
end;
if b = '0' then GetBit:= false
else
if b = '1' then GetBit:= true
else writeln('ERR:', b, ': (GetBit)');
end;
Function GetChar:char;
var b:char;
begin
read(input, b);
while (ord(b) < 48) or (ord(b) > 125) do read(input, b);{jesli tylko masz do czynienia z sensownym znakiem - zwroc go}
GetChar:=b;
end;
Procedure GetHeadings;
var i:word;
a:char;
begin
for i:=1 to 13 do
begin
a:=GetChar;
nazwy[i]:='';
while ord(a) <> 124 do{jesli wczytany znak jest rozny od '|', dodaj kolejny znak do nazwy}
begin
nazwy[i]:=nazwy[i]+a;
a:=GetChar;
end;
end;
end;
begin
n:=0;
j:=0;
i:=0;
data:=0;
Lights_Seq[0].LPT:=0;
reset(input);{przechodzi na poczatek pliku}
GetHeadings;{pobieranie 13 naglowow - pierwsza linia}
readln(input, waitS);{pomijanie znaku konca linii znajdujacego sie po naglowkach}
readln(input, n);
For j:=1 to n do{dla ilosci linii z danymi}
begin
For i:=1 to 13 do{dla kazdego naglowka (sam pobiera odpowiednia ilosc)}
begin
if nazwy[i][1] = 'U' then{jesli uliczne}
begin
if GetBit then SetColour(nazwy[i], 'red', data) else DeleteColor(nazwy[i], 'red', data);
if GetBit then SetColour(nazwy[i], 'yellow', data) else DeleteColor(nazwy[i], 'yellow', data);
if GetBit then SetColour(nazwy[i], 'green', data) else DeleteColor(nazwy[i], 'green', data);
end else
if nazwy[i][1] = 'P' then{jesli dla pieszych}
begin
if GetBit then SetColour(nazwy[i], 'red', data) else DeleteColor(nazwy[i], 'red', data);
if GetBit then SetColour(nazwy[i], 'green', data) else DeleteColor(nazwy[i], 'green', data);
end else
if nazwy[i][1] = 'w' then{jesli czas}
begin
read(input, wczyt);
while wczyt = ' ' do read(input, wczyt);{pominiencie spacji}
waitS:='';
while ord(wczyt) > 47 do
begin
waitS:=waitS+wczyt;
read(input, wczyt);
end;
Val(waitS, waitW, error);
{writeln('Delay:', waitW);}
Lights_Seq[0].LPT:=Lights_Seq[0].LPT+1;
Lights_Seq[Lights_Seq[0].LPT].LPT:=data;
Lights_Seq[Lights_Seq[0].LPT].Wait:=waitW;
{Send(data);}
{Delay(waitW);}
end else writeln('NOT FOUND:', ord(nazwy[i][1]), ': (LoadFromFile)');
end
end;
end;
Procedure Skrzyzowanie.SetDefault;
Procedure DefiniujPiny(var a:sygnaliz; r, y, g:word);
var shift:longint;
begin
shift:=1;
a.red:=shift shl (r-1);
a.green:=shift shl (g-1);
a.yellow:=shift shl (y-1);
end;
var shif:longint;
i:byte;
droga:word;
pieszy_h:word;
begin
{Height:=GetMaxY;
Width:=GetMaxX;
x:=1;
y:=1;}
GrassColor:=2;
MainColor:=1;
{wysokosc/szerokosc sygnalozatora i jego kolor}
{ SetRGBPalette(10, 150, 150, 150);}
Lights_Back:=10;
{definicja sygnalizatorow - nazwa i polozenie}
i:=1;
droga:=Height div 3;
pieszy_h:=(Lights_Height div 3) shl 1;
writeln('Lights_Height=', Lights_Height, ' pieszy_h=', pieszy_h);
writeln('droga=', droga);
writeln('Height=', Height);
writeln('Width=', Width);
writeln('X=', X, ' Y=', Y);
writeln(Y + (droga shl 1)+10 - Lights_Height, ' ', Y + (droga*2)+10 - Lights_Height);
{drogowe}
Lights[i].name:='U1';
Lights[i].x:=X + 5;
Lights[i].y:=Y + (droga shl 1)+10;
i:=i+1;
Lights[i].name:='U2';
Lights[i].x:=X + (Width div 2) + (droga div 2) + 10;
Lights[i].y:=Y + Height - Lights_Height - 5;
i:=i+1;
Lights[i].name:='U3';
Lights[i].x:=X + Width-Lights_Height - 5;
Lights[i].y:=Y + droga - Lights_Width - 10;
i:=i+1;
Lights[i].name:='U4';
Lights[i].x:=X + (Width div 2)-(droga div 2)-Lights_Width-10;
Lights[i].y:=Y + 5 ;
i:=i+1;
{dla pieszych}
Lights[i].name:='P1A';
Lights[i].x:=X + (Width - droga) div 2 -(Pasy_Width div 2 + Pasy_d) - Lights_Width div 2;
Lights[i].y:=Y + droga-5 - pieszy_h;
i:=i+1;
Lights[i].name:='P1B';
Lights[i].x:=X + (Width - droga) div 2 -(Pasy_Width div 2 + Pasy_d) - Lights_Width div 2;;
Lights[i].y:=Y + (droga shl 1) +5;
i:=i+1;
Lights[i].name:='P2A';
Lights[i].x:=X + (Width-droga) div 2 - pieszy_h-5;
Lights[i].y:=Y + (droga shl 1) + (Pasy_Width div 2 + Pasy_d) - Lights_Width div 2;
i:=i+1;
Lights[i].name:='P2B';
Lights[i].x:=X + (Width-droga) div 2 +5+droga;
Lights[i].y:=Y + (droga shl 1) + (Pasy_Width div 2 + Pasy_d) - Lights_Width div 2;
i:=i+1;
Lights[i].name:='P3A';
Lights[i].x:=X + ((Width - droga) div 2)+droga+(Pasy_Width div 2 + Pasy_d)-Lights_Width div 2;
Lights[i].y:=Y + droga-5 - pieszy_h;
i:=i+1;
Lights[i].name:='P3B';
Lights[i].x:=X + ((Width - droga) div 2)+droga+(Pasy_Width div 2 + Pasy_d)-Lights_Width div 2;
Lights[i].y:=Y + (droga shl 1) +5;
i:=i+1;
Lights[i].name:='P4A';
Lights[i].x:=X + (Width-droga) div 2 - pieszy_h-5;
Lights[i].y:=Y + droga - (Pasy_Width div 2 + Pasy_d) - Lights_Width div 2;
i:=i+1;
Lights[i].name:='P4B';
Lights[i].x:=X + (Width-droga) div 2 +5+droga;
Lights[i].y:=Y + droga - (Pasy_Width div 2 + Pasy_d) - Lights_Width div 2;
i:=i+1;
{konfiguracja pinow}
DefiniujPiny(Lights[1], 3, 2, 1);
DefiniujPiny(Lights[2], 32, 31, 30);
DefiniujPiny(Lights[3], 18, 17, 16);
DefiniujPiny(Lights[4], 15, 14, 13);
DefiniujPiny(Lights[5], 9, 1, 6);
DefiniujPiny(Lights[6], 5, 1, 4);
DefiniujPiny(Lights[7], 26, 1, 25);
DefiniujPiny(Lights[8], 29, 1, 28);
DefiniujPiny(Lights[9], 27, 1, 24);
DefiniujPiny(Lights[10], 21, 1, 20);
DefiniujPiny(Lights[11], 23, 1, 22);
DefiniujPiny(Lights[12], 12, 1, 10);
{kolory swiatel}
{ SetRGBPalette(4, 255, 0, 0);
SetRGBPalette(5, 100, 0, 0);
SetRGBPalette(6, 0, 255, 0);
SetRGBPalette(7, 0, 100, 0);
SetRGBPalette(8, 255, 255, 0);
SetRGBPalette(9, 100, 100, 0);}
Red_on:=4;
Red_off:=5;
Green_on:=6;
Green_off:=7;
Yellow_on:=8;
Yellow_off:=9;
end;
Procedure Skrzyzowanie.Move;
begin
end;
Procedure Skrzyzowanie.Lights_update;
var j:byte;
r:byte;
pieszy_h:word;
Procedure Circle2(x, y, r:word);
var r2:word;
begin
r2:=0;
Line(x-1, y-1, x+1, y-1);
Line(x-1, y+1, x+1, y+1);
Line(x-1, y, x+1, y);
while r2 <= r do
begin
circle(x, y, r2);
r2:=r2+1;
end;
end;
Procedure Kolko(kolor:string; zapalony:boolean);
begin
if kolor = 'red' then
begin
if zapalony then SetColor(Red_on) else SetColor( Red_off);
if Lights[j].name = 'U1' then
Circle2(Lights[j].X+Lights_Height - Lights_Height div 6, Lights[j].Y+Lights_Width div 2, r) else
if Lights[j].name = 'U2' then Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+Lights_Height div 6, r) else
if Lights[j].name = 'U3' then Circle2(Lights[j].X+Lights_Height div 6, Lights[j].Y+Lights_Width div 2, r) else
if Lights[j].name = 'U4' then
Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+Lights_Height - Lights_Height div 6, r) else
if Lights[j].name = 'P1A' then Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+pieszy_h div 4, r) else
if Lights[j].name = 'P1B' then
Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+pieszy_h - pieszy_h div 4, r) else
if Lights[j].name = 'P2A' then Circle2(Lights[j].X+pieszy_h div 4, Lights[j].Y+Lights_Width div 2, r) else
if Lights[j].name = 'P2B' then
Circle2(Lights[j].X+pieszy_h - pieszy_h div 4, Lights[j].Y+Lights_Width div 2, r) else
if Lights[j].name = 'P3A' then Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+pieszy_h div 4, r) else
if Lights[j].name = 'P3B' then
Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+pieszy_h - pieszy_h div 4, r) else
if Lights[j].name = 'P4A' then Circle2(Lights[j].X+pieszy_h div 4, Lights[j].Y+Lights_Width div 2, r) else
if Lights[j].name = 'P4B' then Circle2(Lights[j].X+pieszy_h - pieszy_h div 4, Lights[j].Y+Lights_Width div 2, r);
end;
if kolor = 'yellow' then
begin
if zapalony then SetColor( Yellow_on) else SetColor( Yellow_off);
if Lights[j].name = 'U1' then Circle2(Lights[j].X+(Lights_Height div 2), Lights[j].Y+Lights_Width div 2, r) else
if Lights[j].name = 'U2' then Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+(Lights_Height div 2), r) else
if Lights[j].name = 'U3' then Circle2(Lights[j].X+(Lights_Height div 2), Lights[j].Y+(Lights_Width div 2), r) else
if Lights[j].name = 'U4' then Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+(Lights_Height div 2), r);
end;
if kolor = 'green' then
begin
if zapalony then SetColor( Green_on) else SetColor( Green_off);
if Lights[j].name = 'U1' then Circle2(Lights[j].X+Lights_Height div 6, Lights[j].Y+Lights_Width div 2, r) else
if Lights[j].name = 'U2' then
Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+Lights_Height - Lights_Height div 6, r) else
if Lights[j].name = 'U3' then
Circle2(Lights[j].X+Lights_Height - Lights_Height div 6, Lights[j].Y+Lights_Width div 2, r) else
if Lights[j].name = 'U4' then Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+Lights_Height div 6, r) else
if Lights[j].name = 'P1A' then Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+pieszy_h - pieszy_h div 4, r) else
if Lights[j].name = 'P1B' then Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+pieszy_h div 4, r) else
if Lights[j].name = 'P2A' then Circle2(Lights[j].X+pieszy_h - pieszy_h div 4, Lights[j].Y+Lights_Width div 2, r) else
if Lights[j].name = 'P2B' then Circle2(Lights[j].X+pieszy_h div 4, Lights[j].Y+Lights_Width div 2, r) else
if Lights[j].name = 'P3A' then Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+pieszy_h - pieszy_h div 4, r) else
if Lights[j].name = 'P3B' then Circle2(Lights[j].X+Lights_Width div 2, Lights[j].Y+pieszy_h div 4, r) else
if Lights[j].name = 'P4A' then Circle2(Lights[j].X+pieszy_h - pieszy_h div 4, Lights[j].Y+Lights_Width div 2, r) else
if Lights[j].name = 'P4B' then Circle2(Lights[j].X+pieszy_h div 4, Lights[j].Y+Lights_Width div 2, r);
end;
end;
begin
r:=Lights_Width div 2 - 4;
pieszy_h:=(Lights_Height div 3) shl 1;
j:=1;
while j <= 12 do
begin
Kolko('red', (Lights_Input and Lights[j].Red)<>0);
Kolko('yellow', (Lights_Input and Lights[j].Yellow)<>0);
Kolko('green', (Lights_Input and Lights[j].Green)<>0);
j:=j+1;
end;
end;
Procedure Skrzyzowanie.CountRoute;
var i:integer;
pas, pas_1_2, Height_1_3:word;
x_in, y_in, x_out, y_out, circle_x, circle_y:word;
mx, my, x1, y1, r:integer;
begin
Height_1_3:=Height div 3;
pas:=Height_1_3 div 2;
pas_1_2:=pas div 2;
x_in:=X;
x_out:=((Width - Height_1_3) div 2)+ pas+pas_1_2;
y_in:=Height_1_3+pas+pas_1_2;
y_out:=Height;
r:=150;
x1:=x_in;
y1:=y_in;
circle_x:=x_out - r;
circle_y:=y_in + r;
{w prawo-gora}
while x1 < (x_out + 1) do
begin
if x1 < (x_out - r) then {jesli prosto}
begin
x1:=x1+1;
PutPixel(x1, y1, 3);
end
else
if x1 < x_out then
begin
PutPixel(circle_x, circle_y, 4);
while x1 < x_out do
begin
mx:=x1 - circle_x;
my:=round(sqrt(abs(mx*mx-r*r)));
PutPixel(x1, circle_y-my, 3);
x1:=x1+1;
end;
y1:=circle_y+my;
end
else
begin
while y1 < y_out do
begin
y1:=y1+1;
PutPixel(x1, y1, 3);
end;
x1:=x1+2
end;
end;
end;
Procedure Skrzyzowanie.Paint;
var Height_1_3, i:word;
GrassWidth, pasiak:word;
Procedure Pas(x1, y1, x2, y2:word; k:string);
var i, count:byte;
begin
if k = 'h' then
begin
count:=(y2 - y1) div 20;
for i:=0 to count-1 do
begin
bar(x1, y1+20*i+5, x2, y1+20*i+15 );
end;
end else
if k = 'v' then
begin
count:=(x2 - x1) div 20;
for i:=0 to count-1 do
begin
bar(x1+20*i+5, y1, x1+20*i+15, y2 );
end;
end;
end;
begin
writeln('< skrzyzowanie - data >');
writeln('x=', X);
writeln('y=', Y);
writeln('Width=', Width);
writeln('Height=', Height);
writeln('GrassColor=', GrassColor);
writeln('MainColor=', MainColor);
writeln;
Height_1_3:=Height div 3;
GrassWidth:=(Width - Height_1_3) div 2;
SetColor(15);
SetFillStyle(SolidFill, GrassColor);
bar(X, Y, GrassWidth+X, Height_1_3+Y);
bar(X, (Height_1_3 shl 1)+Y, GrassWidth+X, Height+Y);
bar(GrassWidth+Height_1_3+X, Y, Width+X, Height_1_3+Y);
bar(GrassWidth+Height_1_3+X, (Height_1_3 shl 1)+Y, Width+X, Height+Y);
SetFillStyle(SolidFill, MainColor);
bar(X, Height_1_3+Y, Width+X, Y+(Height_1_3 shl 1));
bar(GrassWidth+X, Y, GrassWidth+Height_1_3+X, Y+Height);
{pasy}
pasiak:= Y+Height_1_3+Height_1_3-5;
SetFillStyle(SolidFill, 255);
SetColor(15);
Pas(X+(Width div 2) - (Height_1_3 div 2) - (Pasy_Width+Pasy_d), y+Height_1_3+5,
X+(Width div 2) - (Height_1_3 div 2) - Pasy_d, pasiak, 'h');
Pas(X+(Width div 2) + (Height_1_3 div 2) + (Pasy_Width+Pasy_d), y+Height_1_3+5,
X+(Width div 2) + (Height_1_3 div 2) + Pasy_d, pasiak, 'h');
Pas(X+(Width div 2) - (Height_1_3 div 2) +5, y+Height_1_3 - (Pasy_Width+Pasy_d),
X+(Width div 2) + (Height_1_3 div 2) -5, Y+Height_1_3 - Pasy_d, 'v');
Pas(X+(Width div 2) - (Height_1_3 div 2) +5, y+Height - Height_1_3 +Pasy_d,
X+(Width div 2) + (Height_1_3 div 2) -5, Y+Height - Height_1_3 +(Pasy_Width+Pasy_d), 'v');
{swiatla}
SetFillStyle(SolidFill, Lights_Back);
for i:=1 to 12 do
if Lights[i].name[1] = 'U' then
begin
if Lights[i].name[2] = '2' then Bar(Lights[i].X, Lights[i].Y, Lights[i].X+Lights_Width, Lights[i].Y+Lights_Height) else
if Lights[i].name[2] = '1' then Bar(Lights[i].X, Lights[i].Y, Lights[i].X+Lights_Height, Lights[i].Y+Lights_Width)else
if Lights[i].name[2] = '3' then Bar(Lights[i].X, Lights[i].Y, Lights[i].X+Lights_Height, Lights[i].Y+Lights_Width) else
if Lights[i].name[2] = '4' then Bar(Lights[i].X, Lights[i].Y, Lights[i].X+Lights_Width, Lights[i].Y+Lights_Height);
end
else
begin
if (Lights[i].name[2] = '1') or (Lights[i].name[2] = '3') then Bar(Lights[i].X, Lights[i].Y, Lights[i].X+Lights_Width,
Lights[i].Y+((Lights_Height div 3) shl 1))
else Bar(Lights[i].X, Lights[i].Y, Lights[i].X+((Lights_Height div 3) shl 1), Lights[i].Y+Lights_Width);
end;
Lights_Update;
end;
Procedure InitMyGraph;
begin
gd:=detect; { highest possible resolution }
gm:=0; { not needed, auto detection }
PathToDriver:='C:\BP\BGI'; { path to BGI fonts, drivers aren't needed }
InitGraph(gd,gm,PathToDriver);
if GraphResult<>grok then
halt; { whatever you need }
end;
begin
{pusto?}
end. |
unit TextEditor.Undo.List;
interface
uses
System.Classes, TextEditor.Consts, TextEditor.Types, TextEditor.Undo.Item;
type
TTextEditorUndoList = class(TPersistent)
protected
FBlockCount: Integer;
FBlockNumber: Integer;
FChangeBlockNumber: Integer;
FChanged: Boolean;
FChangeCount: Integer;
FInsideRedo: Boolean;
FInsideUndoBlock: Boolean;
FInsideUndoBlockCount: Integer;
FItems: TList;
FLockCount: Integer;
FOnAddedUndo: TNotifyEvent;
function GetCanUndo: Boolean;
function GetItemCount: Integer;
function GetItems(const AIndex: Integer): TTextEditorUndoItem;
procedure SetItems(const AIndex: Integer; const AValue: TTextEditorUndoItem);
public
constructor Create;
destructor Destroy; override;
function PeekItem: TTextEditorUndoItem;
function PopItem: TTextEditorUndoItem;
function LastChangeBlockNumber: Integer; inline;
function LastChangeReason: TTextEditorChangeReason; inline;
function LastChangeString: string;
procedure AddChange(AReason: TTextEditorChangeReason;
const ACaretPosition, ASelectionBeginPosition, ASelectionEndPosition: TTextEditorTextPosition;
const AChangeText: string; SelectionMode: TTextEditorSelectionMode; AChangeBlockNumber: Integer = 0);
procedure BeginBlock(AChangeBlockNumber: Integer = 0);
procedure Clear;
procedure EndBlock;
procedure Lock;
procedure PushItem(const AItem: TTextEditorUndoItem);
procedure Unlock;
public
procedure AddGroupBreak;
procedure Assign(ASource: TPersistent); override;
property BlockCount: Integer read FBlockCount;
property CanUndo: Boolean read GetCanUndo;
property Changed: Boolean read FChanged write FChanged;
property ChangeCount: Integer read FChangeCount;
property InsideRedo: Boolean read FInsideRedo write FInsideRedo default False;
property InsideUndoBlock: Boolean read FInsideUndoBlock write FInsideUndoBlock default False;
property ItemCount: Integer read GetItemCount;
property Items[const AIndex: Integer]: TTextEditorUndoItem read GetItems write SetItems;
property OnAddedUndo: TNotifyEvent read FOnAddedUndo write FOnAddedUndo;
end;
implementation
const
TEXTEDITOR_MODIFYING_CHANGE_REASONS = [crInsert, crPaste, crDragDropInsert, crDelete, crLineBreak, crIndent, crUnindent];
constructor TTextEditorUndoList.Create;
begin
inherited;
FItems := TList.Create;
FInsideRedo := False;
FInsideUndoBlock := False;
FInsideUndoBlockCount := 0;
FChangeCount := 0;
FBlockNumber := TEXT_EDITOR_UNDO_BLOCK_NUMBER_START;
end;
destructor TTextEditorUndoList.Destroy;
begin
Clear;
FItems.Free;
inherited Destroy;
end;
procedure TTextEditorUndoList.Assign(ASource: TPersistent);
var
LIndex: Integer;
LUndoItem: TTextEditorUndoItem;
begin
if Assigned(ASource) and (ASource is TTextEditorUndoList) then
with ASource as TTextEditorUndoList do
begin
Self.Clear;
for LIndex := 0 to (ASource as TTextEditorUndoList).FItems.Count - 1 do
begin
LUndoItem := TTextEditorUndoItem.Create;
LUndoItem.Assign(FItems[LIndex]);
Self.FItems.Add(LUndoItem);
end;
Self.FInsideUndoBlock := FInsideUndoBlock;
Self.FBlockCount := FBlockCount;
Self.FChangeBlockNumber := FChangeBlockNumber;
Self.FLockCount := FLockCount;
Self.FInsideRedo := FInsideRedo;
end
else
inherited Assign(ASource);
end;
procedure TTextEditorUndoList.AddChange(AReason: TTextEditorChangeReason;
const ACaretPosition, ASelectionBeginPosition, ASelectionEndPosition: TTextEditorTextPosition;
const AChangeText: string; SelectionMode: TTextEditorSelectionMode; AChangeBlockNumber: Integer = 0);
var
LNewItem: TTextEditorUndoItem;
begin
if FLockCount = 0 then
begin
if not FChanged then
FChanged := AReason in TEXTEDITOR_MODIFYING_CHANGE_REASONS;
if AReason in TEXTEDITOR_MODIFYING_CHANGE_REASONS then
Inc(FChangeCount);
LNewItem := TTextEditorUndoItem.Create;
with LNewItem do
begin
if AChangeBlockNumber <> 0 then
ChangeBlockNumber := AChangeBlockNumber
else
if FInsideUndoBlock then
ChangeBlockNumber := FChangeBlockNumber
else
ChangeBlockNumber := 0;
ChangeReason := AReason;
ChangeSelectionMode := SelectionMode;
ChangeCaretPosition := ACaretPosition;
ChangeBeginPosition := ASelectionBeginPosition;
ChangeEndPosition := ASelectionEndPosition;
ChangeString := AChangeText;
end;
PushItem(LNewItem);
end;
end;
procedure TTextEditorUndoList.BeginBlock(AChangeBlockNumber: Integer = 0);
begin
Inc(FBlockCount);
if FInsideUndoBlock then
Exit;
if AChangeBlockNumber = 0 then
begin
Inc(FBlockNumber);
FChangeBlockNumber := FBlockNumber;
end
else
FChangeBlockNumber := AChangeBlockNumber;
FInsideUndoBlockCount := FBlockCount;
FInsideUndoBlock := True;
end;
procedure TTextEditorUndoList.Clear;
var
LIndex: Integer;
begin
FBlockCount := 0;
for LIndex := 0 to FItems.Count - 1 do
TTextEditorUndoItem(FItems[LIndex]).Free;
FItems.Clear;
FChangeCount := 0;
end;
procedure TTextEditorUndoList.EndBlock;
begin
Assert(FBlockCount > 0);
if FInsideUndoBlockCount = FBlockCount then
FInsideUndoBlock := False;
Dec(FBlockCount);
end;
function TTextEditorUndoList.GetCanUndo: Boolean;
begin
Result := FItems.Count > 0;
end;
function TTextEditorUndoList.GetItemCount: Integer;
begin
Result := FItems.Count;
end;
procedure TTextEditorUndoList.Lock;
begin
Inc(FLockCount);
end;
function TTextEditorUndoList.PeekItem: TTextEditorUndoItem;
var
LIndex: Integer;
begin
Result := nil;
LIndex := FItems.Count - 1;
if LIndex >= 0 then
Result := FItems[LIndex];
end;
function TTextEditorUndoList.PopItem: TTextEditorUndoItem;
var
LIndex: Integer;
begin
Result := nil;
LIndex := FItems.Count - 1;
if LIndex >= 0 then
begin
Result := FItems[LIndex];
FItems.Delete(LIndex);
FChanged := Result.ChangeReason in TEXTEDITOR_MODIFYING_CHANGE_REASONS;
if FChanged then
Dec(FChangeCount);
end;
end;
procedure TTextEditorUndoList.PushItem(const AItem: TTextEditorUndoItem);
begin
if Assigned(AItem) then
begin
FItems.Add(AItem);
if (AItem.ChangeReason <> crGroupBreak) and Assigned(OnAddedUndo) then
OnAddedUndo(Self);
end;
end;
procedure TTextEditorUndoList.Unlock;
begin
if FLockCount > 0 then
Dec(FLockCount);
end;
function TTextEditorUndoList.LastChangeReason: TTextEditorChangeReason;
begin
if FItems.Count = 0 then
Result := crNothing
else
Result := TTextEditorUndoItem(FItems[FItems.Count - 1]).ChangeReason;
end;
function TTextEditorUndoList.LastChangeBlockNumber: Integer;
begin
if FItems.Count = 0 then
Result := 0
else
Result := TTextEditorUndoItem(FItems[FItems.Count - 1]).ChangeBlockNumber;
end;
function TTextEditorUndoList.LastChangeString: string;
begin
if FItems.Count = 0 then
Result := ''
else
Result := TTextEditorUndoItem(FItems[FItems.Count - 1]).ChangeString;
end;
procedure TTextEditorUndoList.AddGroupBreak;
var
LTextPosition: TTextEditorTextPosition;
begin
if (LastChangeBlockNumber = 0) and (LastChangeReason <> crGroupBreak) then
AddChange(crGroupBreak, LTextPosition, LTextPosition, LTextPosition, '', smNormal);
end;
function TTextEditorUndoList.GetItems(const AIndex: Integer): TTextEditorUndoItem;
begin
Result := TTextEditorUndoItem(FItems[AIndex]);
end;
procedure TTextEditorUndoList.SetItems(const AIndex: Integer; const AValue: TTextEditorUndoItem);
begin
FItems[AIndex] := AValue;
end;
end.
|
{ ----------------- DEMO ---------------- }
Program TestPwd;
{***************************************************************************
Written by Mark S. Van Leeuwen.
This Code is Public Domain.
This is a Test Program that shows the use of the unit.
Please Include my Name in any application that uses this code.
***************************************************************************}
Uses Objects,App,Dialogs,Drivers,Passwd,Views,StdDlg,MsgBox,Menus;
Const
cmPassword = 1001;
Type
PTestApp=^TTestApp;
TTestApp=Object(TApplication)
Procedure HandleEvent(Var Event:TEvent);Virtual;
Procedure InitStatusLine;Virtual;
End;
Procedure TTestApp.HandleEvent(Var Event:TEvent);
Procedure Password;
Var
D : PDialog;
Control : Word;
A : PView;
R : TRect;
S : String[21];
Begin
R.Assign(0,0,30,08);
D := New(PDialog, Init(R, 'Enter password'));
With D^ Do
Begin
Options := Options or ofCentered;
R.Assign(02, 05, 12, 07);
Insert(New(PButton, Init(R, 'O~K', cmOk, bfDefault)));
R.Assign(17, 05, 27, 07);
Insert(New(PButton, Init(R, '~C~ancel', cmCancel, bfNormal)));
R.Assign(02,03,28,04);
Insert(New(PStaticText, Init(R,'Password is not Displayed.')));{}
R.Assign(02,02,28,03);
A:= New(PPasswordLine, Init(R,20));
Insert(A);
End;
Control:=Desktop^.ExecView(D);
IF Control <> cmCancel THEN
Begin
A^.GetData(S);
MessageBox(#3+S,nil,mfInformation+mfOkButton);
End;
Dispose(D, Done);
End;
Begin
TApplication.HandleEvent(Event);
case Event.What of
evCommand:
begin
case Event.Command of
cmPassword: Password;
else
Exit;
end;
ClearEvent(Event);
end;
end;
end;
{***************************************************************************}
{**************** Application Status Line Procedure ************************}
{***************************************************************************}
Procedure TTestApp.InitStatusLine;
Var
R :Trect;
Begin
GetExtent(R);
R.A.Y := R.B.Y - 1;
StatusLine := New(PStatusLine, Init(R,
NewStatusDef(0, $FFFF,
{ NewStatusKey('~F1~ Help', kbF1, cmHelp,}
NewStatusKey('~Alt-X~ Exit', kbAltX, cmQuit,
NewStatusKey('~F2~ Password', kbF2, cmPassword,nil)),
nil)));
End;
Var
TMyApp :TTestApp;
Begin
TMyapp.Init;
TMyapp.Run;
TMyapp.Done;
End.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [PCP_OP_CABECALHO]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit PcpOpCabecalhoVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, PcpInstrucaoOpVO, PcpOpDetalheVO;
type
[TEntity]
[TTable('PCP_OP_CABECALHO')]
TPcpOpCabecalhoVO = class(TVO)
private
FID: Integer;
FID_EMPRESA: Integer;
FINICIO: TDateTime;
FPREVISAO_ENTREGA: TDateTime;
FTERMINO: TDateTime;
FCUSTO_TOTAL_PREVISTO: Extended;
FCUSTO_TOTAL_REALIZADO: Extended;
FPORCENTO_VENDA: Extended;
FPORCENTO_ESTOQUE: Extended;
FListaPcpOpDetalheVO: TObjectList<TPcpOpDetalheVO>;
FListaInstrucaoOpVO: TObjectList<TPcpInstrucaoOpVO>;
public
constructor Create; override;
destructor Destroy; override;
[TId('ID')]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_EMPRESA', 'Id Empresa', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA;
[TColumn('INICIO', 'Inicio', 80, [ldGrid, ldLookup, ldCombobox], False)]
property Inicio: TDateTime read FINICIO write FINICIO;
[TColumn('PREVISAO_ENTREGA', 'Previsao Entrega', 80, [ldGrid, ldLookup, ldCombobox], False)]
property PrevisaoEntrega: TDateTime read FPREVISAO_ENTREGA write FPREVISAO_ENTREGA;
[TColumn('TERMINO', 'Termino', 80, [ldGrid, ldLookup, ldCombobox], False)]
property Termino: TDateTime read FTERMINO write FTERMINO;
[TColumn('CUSTO_TOTAL_PREVISTO', 'Custo Total Previsto', 152, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property CustoTotalPrevisto: Extended read FCUSTO_TOTAL_PREVISTO write FCUSTO_TOTAL_PREVISTO;
[TColumn('CUSTO_TOTAL_REALIZADO', 'Custo Total Realizado', 152, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property CustoTotalRealizado: Extended read FCUSTO_TOTAL_REALIZADO write FCUSTO_TOTAL_REALIZADO;
[TColumn('PORCENTO_VENDA', 'Porcento Venda', 152, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property PorcentoVenda: Extended read FPORCENTO_VENDA write FPORCENTO_VENDA;
[TColumn('PORCENTO_ESTOQUE', 'Porcento Estoque', 152, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property PorcentoEstoque: Extended read FPORCENTO_ESTOQUE write FPORCENTO_ESTOQUE;
[TManyValuedAssociation('ID_PCP_OP_CABECALHO', 'ID')]
property ListaPcpOpDetalheVO: TObjectList<TPcpOpDetalheVO> read FListaPcpOpDetalheVO write FListaPcpOpDetalheVO;
[TManyValuedAssociation('ID_PCP_OP_CABECALHO', 'ID')]
property ListaPcpInstrucaoOpVO: TObjectList<TPcpInstrucaoOpVO> read FListaInstrucaoOpVO write FListaInstrucaoOpVO;
end;
implementation
{ TPcpOpCabecalhoVO }
constructor TPcpOpCabecalhoVO.Create;
begin
inherited;
FListaPcpOpDetalheVO := TObjectList<TPcpOpDetalheVO>.Create;
FListaInstrucaoOpVO := TObjectList<TPcpInstrucaoOpVO>.Create;
end;
destructor TPcpOpCabecalhoVO.Destroy;
begin
FreeAndNil(FListaPcpOpDetalheVO);
FreeAndNil(FListaInstrucaoOpVO);
inherited;
end;
initialization
Classes.RegisterClass(TPcpOpCabecalhoVO);
finalization
Classes.UnRegisterClass(TPcpOpCabecalhoVO);
end.
|
unit MsgSendForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Winshoes, WinshoeMessage, NNTPWinshoe, ComCtrls, FolderList;
type
TformMsgSend = class(TForm)
butnCancel: TButton;
wsMSG: TWinshoeMessage;
NNTP: TWinshoeNNTP;
Animate1: TAnimate;
lablStatus: TLabel;
procedure butnCancelClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure NNTPStatus(Sender: TComponent; const sOut: String);
private
FTreeNode: TTreeNode;
FUserAbort: Boolean;
protected
procedure SetHostData(HostData: THostData);
procedure SendTopTenPrim(NewsItem: TTreeNode);
procedure SendNewsgroupTopTen(NewsItem: TTreeNode);
procedure SendHostTopTen(HostItem: TTreeNode);
procedure SendAllTopTen(RootItem: TTreeNode);
public
procedure SetStatusCaption(Value: string);
property TreeNode: TTreeNode read FTreeNode write FTreeNode;
end;
implementation
{$R *.DFM}
procedure TformMsgSend.SetHostData(HostData: THostData);
begin
with NNTP do begin
Host := HostData.HostName;
Port := HostData.Port;
UserID := HostData.UserID;
Password := HostData.Password;
end;
Caption := 'Sending Reports for '+HostData.HostName;
end;
procedure TformMsgSend.SetStatusCaption(Value: string);
begin
lablStatus.Caption := Value;
lablStatus.Update;
end;
procedure TformMsgSend.SendTopTenPrim(NewsItem: TTreeNode);
var
HostData: THostData;
begin
SetStatusCaption(TNewsgroupData(NewsItem.Data).NewsgroupName);
if TNewsgroupData(NewsItem.Data).List.Count > 0 then begin
HostData := THostData(NewsItem.Parent.Data);
with wsMSG do begin
Clear;
From := HostData.FullName;
ReplyTo := HostData.Email;
Subject := 'Top 10 Article Posters';
Organization := HostData.Organization;
Newsgroups.Text := TNewsgroupData(NewsItem.Data).NewsgroupName;
Text.Assign(TNewsgroupData(NewsItem.Data).List);
Text.Add('=========================================================');
Text.Add('Generated by NGScan. Freely available (with source code)');
Text.Add('as part of Winshoes from http://www.pbe.com/winshoes/');
Text.Add('Best viewed using a fixed font.');
end;
NNTP.Send(wsMSG);
end;
end;
procedure TformMsgSend.SendNewsgroupTopTen(NewsItem: TTreeNode);
begin
SetHostData(THostData(NewsItem.Parent.Data));
NNTP.Connect;
try
SendTopTenPrim(NewsItem);
finally
NNTP.Disconnect;
end;
end;
procedure TformMsgSend.SendHostTopTen(HostItem: TTreeNode);
var
NewsItem: TTreeNode;
begin
SetHostData(THostData(HostItem.Data));
NNTP.Connect;
try
NewsItem := HostItem.GetFirstChild;
while Assigned(NewsItem) and not FUserAbort do begin
SendTopTenPrim(NewsItem);
NewsItem := NewsItem.GetNextChild(NewsItem);
Application.ProcessMessages;
if FUserAbort or not NNTP.Connected then
Break;
end;
finally
NNTP.Disconnect;
end;
end;
procedure TformMsgSend.SendAllTopTen(RootItem: TTreeNode);
var
HostItem: TTreeNode;
begin
HostItem := RootItem.GetFirstChild;
while Assigned(HostItem) and not FUserAbort do begin
SendHostTopTen(HostItem);
HostItem := HostItem.GetNextChild(HostItem);
Application.ProcessMessages;
if FUserAbort or not NNTP.Connected then
Break;
end;
end;
procedure TformMsgSend.butnCancelClick(Sender: TObject);
begin
FUserAbort := True;
end;
procedure TformMsgSend.FormActivate(Sender: TObject);
begin
Refresh;
Animate1.Active := True;
if TObject(TreeNode.Data) is TFolderData then
SendAllTopTen(TreeNode)
else if TObject(TreeNode.Data) is THostData then
SendHostTopTen(TreeNode)
else if TObject(TreeNode.Data) is TNewsgroupData then
SendNewsgroupTopTen(TreeNode);
end;
procedure TformMsgSend.NNTPStatus(Sender: TComponent; const sOut: String);
begin
SetStatusCaption(Trim(sOut));
end;
end.
|
unit Unit7;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.WinXCalendars;
type
TForm7 = class(TForm)
CalendarView1: TCalendarView;
procedure CalendarView1DrawDayItem(Sender: TObject; DrawParams: TDrawViewInfoParams; CalendarViewViewInfo: TCellItemViewInfo);
procedure FormCreate(Sender: TObject);
procedure CalendarView1Click(Sender: TObject);
private
FData: TDate;
public
{ Public declarations }
end;
var
Form7: TForm7;
implementation
uses
DateUtils;
{$R *.dfm}
procedure TForm7.CalendarView1Click(Sender: TObject);
begin
FData := CalendarView1.Date;
end;
procedure TForm7.CalendarView1DrawDayItem(Sender: TObject; DrawParams: TDrawViewInfoParams; CalendarViewViewInfo: TCellItemViewInfo);
begin
if (DayOfWeek(CalendarViewViewInfo.Date) = 1) then
begin
DrawParams.BkColor := clRed;
DrawParams.ForegroundColor := clWhite;
end;
if (DayOfWeek(CalendarViewViewInfo.Date) = 7) then
begin
DrawParams.BkColor := clRed;
DrawParams.ForegroundColor := clWhite;
end;
if (MonthOf(CalendarViewViewInfo.Date) <> MonthOf(FData)) then
begin
DrawParams.BkColor := clSilver;
DrawParams.ForegroundColor := clWhite;
end;
end;
procedure TForm7.FormCreate(Sender: TObject);
begin
FData := Date;
end;
end.
|
program dUnitXTest;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Interfaces, // this includes the LCL widgetset
custapp, Classes, SysUtils, fpcunit, testreport, testregistry,
Test; //Add any other units of test cases here
const
ShortOpts = 'alh';
Longopts: Array[1..5] of String = (
'all','list','format:','suite:','help');
Version = 'Version 0.2';
type
TTestRunner = Class(TCustomApplication)
private
FXMLResultsWriter: TXMLResultsWriter;
protected
procedure DoRun ; Override;
procedure doTestRun(aTest: TTest); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
constructor TTestRunner.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FXMLResultsWriter := TXMLResultsWriter.Create;
end;
destructor TTestRunner.Destroy;
begin
FXMLResultsWriter.Free;
end;
procedure TTestRunner.doTestRun(aTest: TTest);
var
testResult: TTestResult;
begin
testResult := TTestResult.Create;
try
testResult.AddListener(FXMLResultsWriter);
aTest.Run(testResult);
FXMLResultsWriter.WriteResult(testResult);
finally
testResult.Free;
end;
end;
procedure TTestRunner.DoRun;
var
I : Integer;
S : String;
begin
S:=CheckOptions(ShortOpts,LongOpts);
If (S<>'') then
Writeln(S);
if (ParamCount = 0) then
begin
doTestRun(GetTestRegistry);
end
else
if HasOption('h', 'help') {or (ParamCount = 0)} then
begin
writeln(Title);
writeln(Version);
writeln('Usage: ');
writeln('-l or --list to show a list of registered tests');
writeln('default format is xml, add --format=latex to output the list as latex source');
writeln('-a or --all to run all the tests and show the results in xml format');
writeln('The results can be redirected to an xml file,');
writeln('for example: ./testrunner --all > results.xml');
writeln('use --suite=MyTestSuiteName to run only the tests in a single test suite class');
end
else;
if HasOption('l', 'list') then
begin
if HasOption('format') then
begin
if GetOptionValue('format') = 'latex' then
writeln(GetSuiteAsLatex(GetTestRegistry))
else
writeln(GetSuiteAsXML(GetTestRegistry));
end
else
writeln(GetSuiteAsXML(GetTestRegistry));
end;
if HasOption('a', 'all') then
begin
doTestRun(GetTestRegistry)
end
else
if HasOption('suite') then
begin
S := '';
S:=GetOptionValue('suite');
if S = '' then
for I := 0 to GetTestRegistry.GetChildTestCount - 1 do
writeln(GetTestRegistry.Test[i].TestName)
else
for I := 0 to GetTestRegistry.GetChildTestCount - 1 do
if GetTestRegistry.Test[i].TestName = S then
begin
doTestRun(GetTestRegistry[i]);
end;
end;
Terminate;
end;
var
App: TTestRunner;
begin
App := TTestRunner.Create(nil);
App.Initialize;
App.Title := 'FPCUnit Console Test Case runner.';
App.Run;
App.Free;
readln;
end.
|
unit uMainForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ExtDlgs, Spin,
BZGraphic, BZColors, BZBitmap, BZBitmapIO;
type
{ TMainForm }
TMainForm = class(TForm)
Panel1 : TPanel;
btnOpenBmpA : TButton;
btnOpenBmpB : TButton;
opd : TOpenPictureDialog;
GroupBox1 : TGroupBox;
pnlView : TPanel;
Label1 : TLabel;
Label2 : TLabel;
Label3 : TLabel;
Label4 : TLabel;
Label5 : TLabel;
Label6 : TLabel;
speOpacity : TSpinEdit;
sbOpacity : TScrollBar;
cbxPixelDrawMode : TComboBox;
cbxCombineDrawMode : TComboBox;
cbxAlphaDrawMode : TComboBox;
cbxBlendSrcFactor : TComboBox;
cbxBlendDstFactor : TComboBox;
btnSwapAAndB : TButton;
procedure FormCreate(Sender : TObject);
procedure sbOpacityChange(Sender : TObject);
procedure speOpacityChange(Sender : TObject);
procedure cbxDrawModeChange(Sender : TObject);
procedure pnlViewPaint(Sender : TObject);
procedure FormShow(Sender : TObject);
procedure btnOpenBmpAClick(Sender : TObject);
procedure btnOpenBmpBClick(Sender : TObject);
procedure btnSwapAAndBClick(Sender : TObject);
private
BmpSourceA, BmpSourceB, BmpDest : TBZBitmap;
FUpdateOpacity : Boolean;
public
procedure DoFusion;
end;
var
MainForm : TMainForm;
implementation
{$R *.lfm}
{ TMainForm }
procedure TMainForm.FormCreate(Sender : TObject);
Var
i : Integer;
begin
For i:=0 to High(cPixelDrawModeStr) do cbxPixelDrawMode.Items.Add(cPixelDrawModeStr[i]);
cbxPixelDrawMode.ItemIndex := 0;
For i:=0 to High(cCombineDrawModeStr) do cbxCombineDrawMode.Items.Add(cCombineDrawModeStr[i]);
cbxCombineDrawMode.ItemIndex := 0;
For i:=0 to High(cAlphaDrawModeStr) do cbxAlphaDrawMode.Items.Add(cAlphaDrawModeStr[i]);
cbxAlphaDrawMode.ItemIndex := 0;
For i:=0 to High(cBlendingFactorStr) do
begin
cbxBlendSrcFactor.Items.Add(cBlendingFactorStr[i]);
cbxBlendDstFactor.Items.Add(cBlendingFactorStr[i]);
end;
cbxBlendSrcFactor.ItemIndex := 0;
cbxBlendDstFactor.ItemIndex := 0;
BmpSourceA := TBZBitmap.Create;
BmpSourceA.LoadFromFile('../../media/images/Acropole.jpg');
BmpSourceB := TBZBitmap.Create;
BmpSourceB.LoadFromFile('../../media/images/Lazarus_Professional_Logo.tga');
//BmpSourceB.PreMultiplyAlpha;
BmpDest := TBZBitmap.Create;
FUpdateOpacity := False;
end;
procedure TMainForm.sbOpacityChange(Sender : TObject);
begin
if not(FUpdateOpacity) then
begin
// FUpdateOpacity := True;
speOpacity.Value := sbOpacity.Position;
// FUpdateOpacity := False;
DoFusion;
pnlView.Invalidate
end;
end;
procedure TMainForm.speOpacityChange(Sender : TObject);
begin
if not(FUpdateOpacity) then
begin
FUpdateOpacity := True;
sbOpacity.Position := speOpacity.Value;
FUpdateOpacity := False;
DoFusion;
pnlView.Invalidate;
end;
end;
procedure TMainForm.cbxDrawModeChange(Sender : TObject);
begin
DoFusion;
pnlView.Invalidate;
end;
procedure TMainForm.pnlViewPaint(Sender : TObject);
begin
BmpDest.DrawToCanvas(PnlView.Canvas,PnlView.ClientRect,True,True);
end;
procedure TMainForm.FormShow(Sender : TObject);
begin
DoFusion;
pnlView.Invalidate;
end;
procedure TMainForm.btnOpenBmpAClick(Sender : TObject);
begin
if opd.Execute then BmpSourceA.LoadFromFile(opd.FileName);
end;
procedure TMainForm.btnOpenBmpBClick(Sender : TObject);
begin
if opd.Execute then BmpSourceB.LoadFromFile(opd.FileName);
end;
procedure TMainForm.btnSwapAAndBClick(Sender : TObject);
Var
tmp : TBZBitmap;
begin
tmp := BmpSourceA.CreateClone;
BmpSourceA.Assign(BmpSourceB);
BmpSourceB.Assign(tmp);
FreeAndNil(tmp);
DoFusion;
pnlView.Invalidate;
end;
procedure TMainForm.DoFusion;
var
cx, cy : Integer;
begin
BmpSourceA.PreMultiplyAlpha;
BmpSourceB.PreMultiplyAlpha;
BmpDest.Assign(BmpSourceA);
cx := (BmpDest.CenterX - BmpSourceB.CenterX);
cy := (BmpDest.CenterY - BmpSourceB.CenterY);
BmpDest.PutImage(BmpSourceB,0,0,BmpSourceB.Width, BmpSourceB.Height,cx,cy,
TBZBitmapDrawMode(cbxPixelDrawMode.ItemIndex),
TBZBitmapAlphaMode(cbxAlphaDrawMode.ItemIndex),speOpacity.Value,
TBZColorCombineMode(cbxCombineDrawMode.ItemIndex),
TBZBlendingFactor(cbxBlendSrcFactor.ItemIndex),
TBZBlendingFactor(cbxBlendDstFactor.ItemIndex));
end;
end.
|
namespace Moshine.UI.UIKit;
uses
Foundation,UIKit;
type
[IBObject]
MoshineNumberTableViewCell = public class(MoshineBaseTableViewCell, IUITextFieldDelegate)
protected
method createControl:UIView; override;
begin
exit new UITextField;
end;
method setup; override;
begin
inherited setup;
self.textControl.textAlignment := NSTextAlignment.Left;
self.textControl.delegate := self;
self.textControl.addTarget(self) action(selector(textFieldDidChange:)) forControlEvents(UIControlEvents.EditingChanged);
end;
method textFieldDidChange(sender:id);
begin
if((assigned(OnTextChanged)) and (assigned(sender)))then
begin
OnTextChanged(UITextField(sender).text);
end;
end;
method textField(textField: ^UITextField) shouldChangeCharactersInRange(range: NSRange) replacementString(value: NSString): Boolean;
begin
var characterSetAllowed := NSCharacterSet.decimalDigitCharacterSet;
if((not assigned(value)) or ((assigned(value)) and (value.length=0)))then
begin
exit true;
end;
var rangeAllowed := value.rangeOfCharacterFromSet(characterSetAllowed) options(NSStringCompareOptions.CaseInsensitiveSearch);
if(rangeAllowed.length = value.length)then
begin
exit true;
end;
exit false;
end;
method get_textControl:UITextField;
begin
exit cellControl as UITextField;
end;
public
property OnTextChanged:OnTextChangedDelegate;
[IBOutlet]property textControl:weak UITextField read get_textControl;
method touchesBegan(touches: not nullable NSSet) withEvent(&event: nullable UIEvent); override;
begin
self.textControl:becomeFirstResponder;
end;
end;
end. |
{=========================================================================
TTBase MessageDef.pas
=========================================================================}
unit MessageDef;
interface
uses
Windows;
var
// TTBPlugin_WindowsHookで、Msgパラメータにこれらがやってきます。
// 内容は、MSDNで、WH_SHELLの該当ID, WH_MOUSEのHC_ACTIONを参照してください。
TTB_HSHELL_ACTIVATESHELLWINDOW: Word;
TTB_HSHELL_GETMINRECT: Word;
TTB_HSHELL_LANGUAGE: Word;
TTB_HSHELL_REDRAW: Word;
TTB_HSHELL_TASKMAN: Word;
TTB_HSHELL_WINDOWACTIVATED: Word;
TTB_HSHELL_WINDOWCREATED: Word;
TTB_HSHELL_WINDOWDESTROYED: Word;
TTB_HMOUSE_ACTION: Word;
// 内部使用。TaskTrayアイコン関係のメッセージです
TTB_ICON_NOTIFY: Word;
// TTBase.datをTTBaseにロードさせます
TTB_LOAD_DATA_FILE: Word;
// TTBase.datをTTBaseにセーブさせます
TTB_SAVE_DATA_FILE: Word;
implementation
const
TTB_ICON_NOTIFY_MESSAGE = 'TTBase ICON NOTIFY';
TTB_LOAD_DATA_FILE_MESSAGE = 'TTBase LOAD DATA FILE';
TTB_SAVE_DATA_FILE_MESSAGE = 'TTBase SAVE DATA FILE';
TTB_HSHELL_ACTIVATESHELLWINDOW_MESSAGE = 'TTBase HShell Activate ShellWindow';
TTB_HSHELL_GETMINRECT_MESSAGE = 'TTBase HShell GetMinRect';
TTB_HSHELL_LANGUAGE_MESSAGE = 'TTBase HShell Language';
TTB_HSHELL_REDRAW_MESSAGE = 'TTBase HShell Redraw';
TTB_HSHELL_TASKMAN_MESSAGE = 'TTBase HShell TaskMan';
TTB_HSHELL_WINDOWACTIVATED_MESSAGE = 'TTBase HShell WindowActivated';
TTB_HSHELL_WINDOWCREATED_MESSAGE = 'TTBase HShell WindowCreated';
TTB_HSHELL_WINDOWDESTROYED_MESSAGE = 'TTBase HShell WindowDestroyed';
TTB_HMOUSE_ACTION_MESSAGE = 'TTBase HMouse Action';
initialization
TTB_ICON_NOTIFY := RegisterWindowMessage(TTB_ICON_NOTIFY_MESSAGE);
TTB_LOAD_DATA_FILE := RegisterWindowMessage(TTB_LOAD_DATA_FILE_MESSAGE);
TTB_SAVE_DATA_FILE := RegisterWindowMessage(TTB_SAVE_DATA_FILE_MESSAGE);
TTB_HSHELL_ACTIVATESHELLWINDOW := RegisterWindowMessage(TTB_HSHELL_ACTIVATESHELLWINDOW_MESSAGE);
TTB_HSHELL_GETMINRECT := RegisterWindowMessage(TTB_HSHELL_GETMINRECT_MESSAGE);
TTB_HSHELL_LANGUAGE := RegisterWindowMessage(TTB_HSHELL_LANGUAGE_MESSAGE);
TTB_HSHELL_REDRAW := RegisterWindowMessage(TTB_HSHELL_REDRAW_MESSAGE);
TTB_HSHELL_TASKMAN := RegisterWindowMessage(TTB_HSHELL_TASKMAN_MESSAGE);
TTB_HSHELL_WINDOWACTIVATED := RegisterWindowMessage(TTB_HSHELL_WINDOWACTIVATED_MESSAGE);
TTB_HSHELL_WINDOWCREATED := RegisterWindowMessage(TTB_HSHELL_WINDOWCREATED_MESSAGE);
TTB_HSHELL_WINDOWDESTROYED := RegisterWindowMessage(TTB_HSHELL_WINDOWDESTROYED_MESSAGE);
TTB_HMOUSE_ACTION := RegisterWindowMessage(TTB_HMOUSE_ACTION_MESSAGE);
end.
|
/// <summary>
/// <para>
/// Documentation for RPC: <see href="https://www.pascalcoin.org/development/rpc" />
/// </para>
/// <para>
/// <br />Every call MUST include 3 params: {"jsonrpc": "2.0", "method":
/// "XXX", "id": YYY}
/// </para>
/// <para>
/// <br />jsonrpc : String value = "2.0" <br />method : String value,
/// name of the method to call <br />id : Integer value <br />
/// </para>
/// <para>
/// Optionally can contain another param called "params" holding an
/// object. Inside we will include params to send to the method <br />
/// {"jsonrpc": "2.0", "method": "XXX", "id": YYY, "params":{"p1":"
/// ","p2":" "}}
/// </para>
/// </summary>
Unit PascalCoin.RPC.Interfaces;
Interface
Uses
System.Classes,
System.Generics.Collections,
System.JSON,
System.SysUtils,
System.Rtti,
PascalCoin.RPC.Exceptions;
Type
// HEXASTRING: String that contains an hexadecimal value (ex. "4423A39C"). An hexadecimal string is always an even character length.
HexaStr = String;
// PASCURRENCY: Pascal Coin currency is a maximum 4 decimal number (ex. 12.1234). Decimal separator is a "." (dot)
// Currency is limited to 4 decimals (actually stored as Int64)
PascCurrency = Currency;
// PASC64Encode = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-+{}[]_:`|<>,.?/~';
// PASC64EncodeInit = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()-+{}[]_:`|<>,.?/~';
// See PascalCoin.RPC.Consts.pas
TStringPair = TPair<String, String>;
TParamPair = TPair<String, variant>;
IPascalCoinNodeStatus = Interface;
IPascalCoinRPCClient = Interface
['{A04B65F9-345E-44F7-B834-88CCFFFAC4B6}']
Function GetResponseObject: TJSONObject;
Function GetResponseStr: String;
Function GetNodeURI: String;
Procedure SetNodeURI(Const Value: String);
Function RPCCall(Const AMethod: String; Const AParams: Array Of TParamPair): boolean;
Property ResponseObject: TJSONObject Read GetResponseObject;
Property ResponseStr: String Read GetResponseStr;
Property NodeURI: String Read GetNodeURI Write SetNodeURI;
End;
TKeyStyle = (ksUnkown, ksEncKey, ksB58Key);
TAccountData = String; //Array [0 .. 31] Of Byte;
IPascalCoinAccount = Interface
['{10B1816D-A796-46E6-94DA-A4C6C2125F82}']
Function GetAccount: Int64;
Function GetPubKey: HexaStr;
Function GetBalance: Currency;
Function GetN_Operation: integer;
Function GetUpdated_b: integer;
Function GetState: String;
Function GetLocked_Until_Block: integer;
Function GetPrice: Currency;
Function GetSeller_Account: integer;
Function GetPrivate_Sale: boolean;
Function GetNew_Enc_PubKey: HexaStr;
Function GetName: String;
Function GetAccount_Type: integer;
Function GetBalance_s: String;
Function GetUpdated_b_active_mode: integer;
Function GetUpdated_b_passive_mode: integer;
Function GetSeal: String;
Function GetData: TAccountData;
Function SameAs(AAccount: IPascalCoinAccount): boolean;
Procedure Assign(AAccount: IPascalCoinAccount);
/// <summary>
/// Account Number (PASA)
/// </summary>
Property account: Int64 Read GetAccount;
/// <summary>
/// HEXASTRING - Encoded public key value (See decodepubkey)
/// </summary>
Property enc_pubkey: HexaStr Read GetPubKey;
/// <summary>
/// Account Balance
/// </summary>
Property balance: Currency Read GetBalance;
Property balance_s: String Read GetBalance_s;
/// <summary>
/// Operations made by this account (Note: When an account receives a
/// transaction, n_operation is not changed)
/// </summary>
Property n_operation: integer Read GetN_Operation;
/// <summary>
/// Last block that updated this account. If equal to blockchain blocks
/// count it means that it has pending operations to be included to the
/// blockchain.
/// </summary>
Property updated_b: integer Read GetUpdated_b;
/// <summary>
/// ActiveMode = Account Buy; Sending (and signer, if not sender) PASC; AccountInfo changed (signer and target)
/// </summary>
Property updated_b_active_mode: integer Read GetUpdated_b_active_mode;
/// <summary>
/// PassiveMode = Account Sale; Receiving PASC
/// </summary>
Property updated_b_passive_mode: integer Read GetUpdated_b_passive_mode;
/// <summary>
/// Values can be normal or listed. When listed then account is for sale
/// </summary>
Property state: String Read GetState;
/// <summary>
/// Until what block this account is locked. Only set if state is listed
/// </summary>
Property locked_until_block: integer Read GetLocked_Until_Block;
/// <summary>
/// Price of account. Only set if state is listed
/// </summary>
Property price: Currency Read GetPrice;
/// <summary>
/// Seller's account number. Only set if state is listed
/// </summary>
Property seller_account: integer Read GetSeller_Account;
/// <summary>
/// Whether sale is private. Only set if state is listed
/// </summary>
Property private_sale: boolean Read GetPrivate_Sale;
/// <summary>
/// HEXSTRING - Private buyers public key. Only set if state is listed and
/// private_sale is true
/// </summary>
Property new_enc_pubkey: HexaStr Read GetNew_Enc_PubKey;
/// <summary>
/// Public name of account. Follows PascalCoin64 Encoding. Min Length = 3;
/// Max Length = 64
/// </summary>
Property Name: String Read GetName;
/// <summary>
/// Type of account. Valid values range from 0..65535
/// </summary>
Property account_type: integer Read GetAccount_Type;
Property Seal: String Read GetSeal;
Property Data: TAccountData Read GetData;
End;
IPascalCoinAccounts = Interface
['{4C039C2C-4BED-4002-9EA2-7F16843A6860}']
Function GetAccount(Const Index: integer): IPascalCoinAccount;
Function Count: integer;
Procedure Clear;
Function AddAccount(Value: IPascalCoinAccount): integer;
// procedure AddAccounts(Value: IPascalCoinAccounts);
Function FindAccount(Const Value: integer): IPascalCoinAccount; Overload;
Function FindAccount(Const Value: String): IPascalCoinAccount; Overload;
Function FindNamedAccount(Const Value: String): IPascalCoinAccount;
Property account[Const Index: integer]: IPascalCoinAccount Read GetAccount; Default;
End;
IPascalNetStats = Interface
['{0F8214FA-D42F-44A7-9B5B-4D6B3285E860}']
Function GetActive: integer;
Function GetClients: integer;
Function GetServers: integer;
Function GetServers_t: integer;
Function GetTotal: integer;
Function GetTClients: integer;
Function GetTServers: integer;
Function GetBReceived: integer;
Function GetBSend: integer;
Property active: integer Read GetActive;
Property clients: integer Read GetClients;
Property servers: integer Read GetServers;
Property servers_t: integer Read GetServers_t;
Property total: integer Read GetTotal;
Property tclients: integer Read GetTClients;
Property tservers: integer Read GetTServers;
Property breceived: integer Read GetBReceived;
Property bsend: integer Read GetBSend;
End;
IPascalCoinServer = Interface
['{E9878551-ADDF-4D22-93A5-3832588ACC45}']
Function GetIP: String;
Function GetPort: integer;
Function GetLastCon: integer;
Function GetAttempts: integer;
Function GetLastConAsDateTime: TDateTime;
Property ip: String Read GetIP;
Property port: integer Read GetPort;
Property lastcon: integer Read GetLastCon;
Property LastConAsDateTime: TDateTime Read GetLastConAsDateTime;
Property attempts: integer Read GetAttempts;
End;
IPascalCoinNetProtocol = Interface
['{DBAAA45D-5AC1-4805-9FDB-5A6B66B193DC}']
Function GetVer: integer;
Function GetVer_A: integer;
Property ver: integer Read GetVer;
Property ver_a: integer Read GetVer_A;
// Net protocol available
End;
IPascalCoinNodeStatus = Interface
['{9CDDF2CB-3064-4CD6-859A-9E11348FF621}']
Function GetReady: boolean;
Function GetReady_S: String;
Function GetStatus_S: String;
Function GetPort: integer;
Function GetLocked: boolean;
Function GetTimeStamp: integer;
Function GetVersion: String;
Function GetNetProtocol: IPascalCoinNetProtocol;
Function GetBlocks: integer;
Function GetNetStats: IPascalNetStats;
Function GetnodeServer(Const Index: integer): IPascalCoinServer;
Function GetSBH: String;
Function GetPOW: String;
Function GetOpenSSL: String;
Function GetTimeStampAsDateTime: TDateTime;
Function NodeServerCount: integer;
Function GetIsTestNet: boolean;
Property ready: boolean Read GetReady;
// Must be true, otherwise Node is not ready to execute operations
Property ready_s: String Read GetReady_S;
// Human readable information about ready or not
Property status_s: String Read GetStatus_S;
// Human readable information about node status... Running, downloading blockchain, discovering servers...
Property port: integer Read GetPort;
Property locked: boolean Read GetLocked;
// True when this wallet is locked, false otherwise
Property timestamp: integer Read GetTimeStamp;
// Timestamp of the Node
Property TimeStampAsDateTime: TDateTime Read GetTimeStampAsDateTime;
Property version: String Read GetVersion;
Property netprotocol: IPascalCoinNetProtocol Read GetNetProtocol;
Property blocks: integer Read GetBlocks;
// Blockchain blocks
Property netstats: IPascalNetStats Read GetNetStats;
// -JSON Object with net information
// Property nodeservers: TArray<IPascalCoinServer> Read GetNodeServers; // JSON Array with servers candidates
Property nodeServer[Const Index: integer]: IPascalCoinServer Read GetnodeServer;
Property sbh: String Read GetSBH;
Property pow: String Read GetPOW;
Property openssl: String Read GetOpenSSL;
End;
IPascalCoinBlock = Interface
['{9BAA406C-BC52-4DB6-987D-BD458C0766E5}']
Function GetBlock: integer;
Function GetEnc_PubKey: String;
Function GetFee: Currency;
Function GetFee_s: String;
Function GetHashRateKHS: integer;
Function GetMaturation: integer;
Function GetNonce: integer;
Function GetOperations: integer;
Function GetOPH: String;
Function GetPayload: String;
Function GetPOW: String;
Function GetReward: Currency;
Function GetReward_s: String;
Function GetSBH: String;
Function GetTarget: integer;
Function GetTimeStamp: integer;
Function GetVer: integer;
Function GetVer_A: integer;
Function GetTimeStampAsDateTime: TDateTime;
Property block: integer Read GetBlock;
// Encoded public key value used to init 5 created accounts of this block (See decodepubkey )
Property enc_pubkey: String Read GetEnc_PubKey;
// Reward of first account's block
Property reward: Currency Read GetReward;
Property reward_s: String Read GetReward_s;
// Fee obtained by operations
Property fee: Currency Read GetFee;
Property fee_s: String Read GetFee_s;
Property ver: integer Read GetVer;
// Pascal Coin protocol available by the miner
Property ver_a: integer Read GetVer_A;
// Unix timestamp
Property timestamp: integer Read GetTimeStamp;
// target difficulty
Property target: integer Read GetTarget;
// nonce used
Property nonce: integer Read GetNonce;
// Miner's payload
Property payload: String Read GetPayload;
Property sbh: String Read GetSBH;
Property oph: String Read GetOPH;
Property pow: String Read GetPOW;
// Number of operations included in this block
Property operations: integer Read GetOperations;
// Estimated network hashrate calculated by previous 50 blocks average
Property hashratekhs: integer Read GetHashRateKHS;
// Number of blocks in the blockchain higher than this
Property maturation: integer Read GetMaturation;
// helper property
Property TimeStampAsDateTime: TDateTime Read GetTimeStampAsDateTime;
End;
IPascalCoinBlocks = Interface
['{9260792F-A849-4DF0-8944-9E500BFCA951}']
Function GetBlock(Const Index: integer): IPascalCoinBlock;
Function GetBlockNumber(Const Index: integer): IPascalCoinBlock;
Function Count: integer;
Property block[Const Index: integer]: IPascalCoinBlock Read GetBlock; Default;
Property BlockNumber[Const Index: integer]: IPascalCoinBlock Read GetBlockNumber;
End;
/// <summary>
/// straight integer mapping from the returned opType value
/// </summary>
TOperationType = (
/// <summary>
/// 0 - Blockchain Reward
/// </summary>
BlockchainReward,
/// <summary>
/// 1 = Transaction
/// </summary>
Transaction,
/// <summary>
/// 2 = Change Key
/// </summary>
ChangeKey,
/// <summary>
/// 3 = Recover Funds (lost keys)
/// </summary>
RecoverFunds, // (lost keys)
/// <summary>
/// 4 = List account for sale
/// </summary>
ListAccountForSale,
/// <summary>
/// 5 = Delist account (not for sale)
/// </summary>
DelistAccountForSale, // (not for sale)
/// <summary>
/// 6 = Buy account
/// </summary>
BuyAccount,
/// <summary>
/// 7 = Change Key signed by another account
/// </summary>
ChangeAccountKey, // (signed by another account)
/// <summary>
/// 8 = Change account info
/// </summary>
ChangeAccountInfo,
/// <summary>
/// 9 = Multi operation (introduced on Build 3.0; PIP-0017)
/// </summary>
Multioperation,
/// <summary>
/// 10 = Data operation (introduced on Build 4.0; PIP-0016)
/// </summary>
DataOp);
IPascalCoinSender = Interface
['{F66B882F-C16E-4447-B881-CC3CFFABD287}']
Function GetAccount: Cardinal;
Function GetN_Operation: integer;
Function GetAmount: Currency;
Function GetAmount_s: String;
Function GetPayload: HexaStr;
Function GetPayloadType: integer;
/// <summary>
/// Sending account (PASA)
/// </summary>
Property account: Cardinal Read GetAccount;
Property n_operation: integer Read GetN_Operation;
/// <summary>
/// In negative value, due it's outgoing from "account"
/// </summary>
Property amount: Currency Read GetAmount;
Property amount_s: String Read GetAmount_s;
Property payload: HexaStr Read GetPayload;
Property payloadtype: integer Read GetPayloadType;
End;
IPascalCoinReceiver = Interface
['{3036AE17-52D6-4FF5-9541-E0B211FFE049}']
Function GetAccount: Cardinal;
Function GetAmount: Currency;
Function GetAmount_s: String;
Function GetPayload: HexaStr;
Function GetPayloadType: integer;
/// <summary>
/// Receiving account (PASA)
/// </summary>
Property account: Cardinal Read GetAccount;
/// <summary>
/// In positive value, due it's incoming from a sender to "account"
/// </summary>
Property amount: Currency Read GetAmount;
Property amount_s: String Read GetAmount_s;
Property payload: HexaStr Read GetPayload;
Property payloadtype: integer Read GetPayloadType;
End;
IPascalCoinChanger = Interface
['{860CE51D-D0D5-4AF0-9BD3-E2858BF1C59F}']
Function GetAccount: Cardinal;
Function GetN_Operation: integer;
Function GetNew_Enc_PubKey: HexaStr;
Function GetNew_Type: String;
Function GetSeller_Account: Cardinal;
Function GetAccount_price: Currency;
Function GetLocked_Until_Block: UInt64;
Function GetFee: Currency;
/// <summary>
/// changing Account
/// </summary>
Property account: Cardinal Read GetAccount;
Property n_operation: integer Read GetN_Operation;
/// <summary>
/// If public key is changed or when is listed for a private sale <br />
/// property new_name: If name is changed
/// </summary>
Property new_enc_pubkey: HexaStr Read GetNew_Enc_PubKey;
/// <summary>
/// if type is changed
/// </summary>
Property new_type: String Read GetNew_Type;
/// <summary>
/// If is listed for sale (public or private) will show seller account
/// </summary>
Property seller_account: Cardinal Read GetSeller_Account;
/// <summary>
/// If is listed for sale (public or private) will show account price
/// </summary>
Property account_price: Currency Read GetAccount_price;
/// <summary>
/// If is listed for private sale will show block locked
/// </summary>
Property locked_until_block: UInt64 Read GetLocked_Until_Block;
/// <summary>
/// In negative value, due it's outgoing from "account"
/// </summary>
Property fee: Currency Read GetFee;
End;
TOpTransactionStyle = (transaction_transaction, transaction_with_auto_buy_account, buy_account,
transaction_with_auto_atomic_swap);
// transaction = Sinlge standard transaction
// transaction_with_auto_buy_account = Single transaction made over an account listed for private sale. For STORING purposes only
// buy_account = A Buy account operation
// transaction_with_auto_atomic_swap = Single transaction made over an account listed for atomic swap (coin swap or account swap)
IPascalCoinOperation = Interface
['{0C059E68-CE57-4F06-9411-AAD2382246DE}']
Function GetValid: boolean;
Function GetErrors: String;
Function GetBlock: UInt64;
Function GetTime: integer;
Function GetOpblock: integer;
Function GetMaturation: integer;
Function GetOptype: integer;
Function GetOperationType: TOperationType;
Function GetOptxt: String;
Function GetAccount: Cardinal;
Function GetAmount: Currency;
Function GetAmount_s: String;
Function GetFee: Currency;
Function GetFee_s: String;
Function GetBalance: Currency;
Function GetSender_account: Cardinal;
Function GetDest_account: Cardinal;
Function GetEnc_PubKey: HexaStr;
Function GetOphash: HexaStr;
Function GetOld_ophash: HexaStr;
Function GetSubtype: String;
Function GetSigner_account: Cardinal;
Function GetN_Operation: integer;
Function GetPayload: HexaStr;
Function GetSender(Const Index: integer): IPascalCoinSender;
Function GetReceiver(Const Index: integer): IPascalCoinReceiver;
Function GetChanger(Const Index: integer): IPascalCoinChanger;
Function SendersCount: integer;
Function ReceiversCount: integer;
Function ChangersCount: integer;
/// <summary>
/// (optional) - If operation is invalid, value=false
/// </summary>
Property valid: boolean Read GetValid;
/// <summary>
/// (optional) - If operation is invalid, an error description
/// </summary>
Property errors: String Read GetErrors;
/// <summary>
/// Block number (only when valid)
/// </summary>
Property block: UInt64 Read GetBlock;
/// <summary>
/// Block timestamp (only when valid)
/// </summary>
Property time: integer Read GetTime;
/// <summary>
/// Operation index inside a block (0..operations-1). Note: If opblock=-1
/// means that is a blockchain reward (only when valid)
/// </summary>
Property opblock: integer Read GetOpblock;
/// <summary>
/// Return null when operation is not included on a blockchain yet, 0 means
/// that is included in highest block and so on...
/// </summary>
Property maturation: integer Read GetMaturation;
/// <summary>
/// see TOperationType above
/// </summary>
Property optype: integer Read GetOptype;
/// <summary>
/// converts optype to TOperationType
/// </summary>
Property OperationType: TOperationType Read GetOperationType;
/// <summary>
/// Human readable operation type
/// </summary>
Property optxt: String Read GetOptxt;
/// <summary>
/// Account affected by this operation. Note: A transaction has 2 affected
/// accounts.
/// </summary>
Property account: Cardinal Read GetAccount;
/// <summary>
/// Amount of coins transferred from sender_account to dest_account (Only
/// apply when optype=1)
/// </summary>
Property amount: Currency Read GetAmount;
Property amount_s: String read GetAmount_s;
/// <summary>
/// Fee of this operation
/// </summary>
Property fee: Currency Read GetFee;
Property fee_s: String read GetFee_s;
/// <summary>
/// Balance of account after this block is introduced in the Blockchain.
/// Note: balance is a calculation based on current safebox account balance
/// and previous operations, it's only returned on pending operations and
/// account operations <br />
/// </summary>
Property balance: Currency Read GetBalance;
/// <summary>
/// Sender account in a transaction (only when optype = 1) <b>DEPRECATED</b>,
/// use senders array instead
/// </summary>
Property sender_account: Cardinal Read GetSender_account;
/// <summary>
/// Destination account in a transaction (only when optype = 1) <b>DEPRECATED</b>
/// , use receivers array instead
/// </summary>
Property dest_account: Cardinal Read GetDest_account;
/// <summary>
/// HEXASTRING - Encoded public key in a change key operation (only when
/// optype = 2). See decodepubkey <b>DEPRECATED</b>, use changers array
/// instead. See commented out enc_pubkey below. A second definition for use
/// with other operation types: Will return both change key and the private
/// sale public key value <b>DEPRECATED</b><br />
/// </summary>
Property enc_pubkey: HexaStr Read GetEnc_PubKey;
/// <summary>
/// HEXASTRING - Operation hash used to find this operation in the blockchain
/// </summary>
Property ophash: HexaStr Read GetOphash;
/// <summary>
/// /// <summary> <br />/// HEXSTRING - Operation hash as calculated
/// prior to V2. Will only be <br />/// populated for blocks prior to V2
/// activation. <b>DEPRECATED</b><br />
/// </summary>
Property old_ophash: HexaStr Read GetOld_ophash;
/// <summary>
/// Associated with optype param, can be used to discriminate from the point
/// of view of operation (sender/receiver/buyer/seller ...)
/// </summary>
Property subtype: String Read GetSubtype;
/// <summary>
/// Will return the account that signed (and payed fee) for this operation.
/// Not used when is a Multioperation (optype = 9)
/// </summary>
Property signer_account: Cardinal Read GetSigner_account;
Property n_operation: integer Read GetN_Operation;
Property payload: HexaStr Read GetPayload;
/// <summary>
/// Will return both change key and the private sale public key value <b>DEPRECATED</b>, use changers array instead
/// </summary>
Property enc_pubkey: HexaStr Read GetEnc_PubKey;
/// <summary>
/// ARRAY of objects with senders, for example in a transaction (optype = 1)
/// or multioperation senders (optype = 9)
/// </summary>
Property sender[Const Index: integer]: IPascalCoinSender Read GetSender;
/// <summary>
/// ARRAY of objects - When this is a transaction or multioperation, this array
/// contains each receiver
/// </summary>
Property receiver[Const Index: integer]: IPascalCoinReceiver Read GetReceiver;
/// <summary>
/// ARRAY of objects - When accounts changed state
/// </summary>
Property changers[Const Index: integer]: IPascalCoinChanger Read GetChanger;
End;
IPascalCoinOperations = Interface
['{027ACE68-2D60-4E45-A67F-6DB53CE6191E}']
Function GetOperation(Const Index: integer): IPascalCoinOperation;
Function Count: integer;
Property Operation[Const Index: integer]: IPascalCoinOperation Read GetOperation; Default;
End;
IPascalCoinBaseAPI = Interface
['{2EB22047-B7CE-4B6E-8B78-EFB4E8F349F4}']
Function GetNodeURI: String;
Procedure SetNodeURI(Const Value: String);
Function GetLastError: String;
Function GetJSONResult: TJSONValue;
Function GetJSONResultStr: String;
Property JSONResult: TJSONValue Read GetJSONResult;
Property JSONResultStr: String Read GetJSONResultStr;
Property NodeURI: String Read GetNodeURI Write SetNodeURI;
Property LastError: String Read GetLastError;
End;
IPascalCoinNodeAPI = Interface(IPascalCoinBaseAPI)
['{C650A953-E3D7-4ED7-B942-7A6B0B6FC1ED}']
Function NodeStatus: IPascalCoinNodeStatus;
End;
IPascalCoinExplorerAPI = Interface(IPascalCoinBaseAPI)
['{310A40ED-F917-4075-B495-5E4906C4D8EB}']
Function GetBlockCount: integer;
Function GetBlock(Const BlockNumber: integer): IPascalCoinBlock;
/// <summary>
/// Returns a JSON Array with blocks information from "start" to "end"
/// (or "last" n blocks) Blocks are returned in DESCENDING order See
/// getblock <br />Note: Must use param <b>last</b> alone, or <b>start</b>
/// and end <br />
/// Function GetBlocks(const Alast, Astart, Aend: Integer): IPascalCoinBlocks; <br />
/// Simplifying Methods Implemented
/// </summary>
/// <param name="Alast">
/// Last n blocks inthe blockchain (n>0 and n<=1000) <br />
/// </param>
Function GetLastBlocks(const ACount: Integer): IPascalCoinBlocks;
Function GetBlockRange(const AStart, AEnd: Integer): IPascalCoinBlocks;
/// <summary>
/// Params <br />block : Integer - Block number <br />opblock : Integer -
/// Operation <br />
/// </summary>
/// <param name="block">
/// Block Number
/// </param>
/// <param name="opblock">
/// Operation Index (0..operations-1) of this block
/// </param>
Function getblockoperation(const Ablock, Aopblock: Integer): IPascalCoinOperation;
/// <param name="ABlock">
/// Block Number
/// </param>
/// <param name="AStart">
/// Start with operation index (default 0)
/// </param>
/// <param name="Amax">
/// Maximum number of operations to retrieve
/// </param>
Function getblockoperations(Const ABlock: Integer; const AStart: Integer = 0; const Amax: Integer = 100): IPascalCoinOperations;
/// <summary>
/// Returns node pending buffer count ( New on Build 3.0 )
/// </summary>
Function getpendingscount: Integer;
/// <summary>
/// Get pending operations to be included in the blockchain
/// </summary>
/// <param name="AStart">
/// Start at index
/// </param>
/// <param name="AMax">
/// Number to return. Setting this as 0 returns all pending transactions
/// </param>
Function getpendings(const AStart: Integer = 0; Const AMax: Integer = 100): IPascalCoinOperations;
//
// findoperation - Find
Function GetAccount(Const AAccountNumber: Cardinal): IPascalCoinAccount;
/// <summary>
/// Get operations made to an account <br />
/// </summary>
/// <param name="AAcoount">
/// Account number (0..accounts count-1)
/// </param>
/// <param name="ADepth">
/// Optional, default value 100 Depth to search on blocks where this
/// account has been affected. Allowed to use deep as a param name too.
/// </param>
/// <param name="AStart">
/// Optional, default = 0. If provided, will start at this position (index
/// starts at position 0). If start is -1, then will include pending
/// operations, otherwise only operations included on the blockchain
/// </param>
/// <param name="AMax">
/// Optional, default = 100. If provided, will return max registers. If not
/// provided, max=100 by default
/// </param>
Function getaccountoperations(Const AAccount: Cardinal; Const ADepth: integer = 100; Const AStart: integer = 0;
Const AMax: integer = 100): IPascalCoinOperations;
End;
/// <summary>
/// This has been created as an extended explorer to contain explorer
/// methods which require the node to have the AllowUsePrivateKeys set to
/// true and access to the wallet
/// </summary>
IPascalCoinWalletAPI = Interface(IPascalCoinExplorerAPI)
['{1FE4E934-1B75-4614-8EAA-5F71CA27C237}']
Function getwalletaccounts(Const APublicKey: String; Const AKeyStyle: TKeyStyle; Const AStartIndex: integer = 0;
Const AMaxCount: integer = 100): IPascalCoinAccounts;
// Support Methods
Procedure AddWalletAccounts(Const APublicKey: String; Const AKeyStyle: TKeyStyle; AAccountList: IPascalCoinAccounts;
Const AStartIndex: integer; Const AMaxCount: integer = 100);
Function getwalletaccountscount(Const APublicKey: String; Const AKeyStyle: TKeyStyle): integer;
// function getwalletcoins(const APublicKey: String): Currency;
End;
IPascalCoinOperationsAPI = Interface(IPascalCoinBaseAPI)
['{111BF45E-B203-4E9E-A639-5D837EDFCC3F}']
/// <summary>
/// Encrypt a text "payload" using "payload_method" <br /><br /><br /><br />
/// </summary>
/// <param name="APayload">
/// HEXASTRING - Text to encrypt in hexadecimal format
/// </param>
/// <param name="AKey">
/// enc_pubkey : HEXASTRING <br />or <br />b58_pubkey : String
/// </param>
/// <param name="AKeyStyle">
/// ksEncKey or ksB58Key
/// </param>
/// <returns>
/// Returns a HEXASTRING with encrypted payload
/// </returns>
Function payloadEncryptWithPublicKey(Const APayload: String; Const AKey: String;
Const AKeyStyle: TKeyStyle): String;
Function executeoperation(Const RawOperation: String): IPascalCoinOperation;
End;
Implementation
End.
|
unit uTanqueController;
interface
uses uTanqueModel, DBClient;
type
TTanqueController = class
public
function Inserir(oTanque: TTanque; var sError: string): Boolean;
function Atualizar(oTanque: TTanque; var sError: string): Boolean;
function Excluir(oTanque: TTanque; var sError: string): Boolean;
function Consultar(oTanque: TTanque; pFiltro: string; var sError: string): TClientDataSet;
procedure ConsultarId(oTanque: TTanque; pFiltro: string; var sError: string);
function CarregaCombo(pObjeto: TObject; pCampo: string): TClientDataSet;
end;
implementation
uses uPersistencia, SysUtils;
{ TTanqueController }
function TTanqueController.Atualizar(oTanque: TTanque;
var sError: string): Boolean;
begin
Result := TPersistencia.Atualizar(oTanque, sError);
end;
function TTanqueController.CarregaCombo(pObjeto: TObject; pCampo: string): TClientDataSet;
begin
Result := TPersistencia.CarregaLookupChaveEstrangeira(pObjeto, pCampo);
end;
function TTanqueController.Consultar(oTanque: TTanque; pFiltro: string;
var sError: string): TClientDataSet;
begin
Result := TPersistencia.Consultar(oTanque, 'NOME', pFiltro, sError);
end;
procedure TTanqueController.ConsultarId(oTanque: TTanque; pFiltro: string;
var sError: string);
var
ds: TClientDataSet;
begin
ds := TPersistencia.Consultar(oTanque, 'ID', pFiltro, sError);
oTanque.Nome := ds.FieldByName('NOME').AsString;
oTanque.Combustivel := ds.FieldByName('COMBUSTIVEL').AsInteger;
end;
function TTanqueController.Excluir(oTanque: TTanque;
var sError: string): Boolean;
begin
Result := TPersistencia.Excluir(oTanque, sError);
end;
function TTanqueController.Inserir(oTanque: TTanque;
var sError: string): Boolean;
begin
Result := TPersistencia.Inserir(oTanque, sError);
end;
end.
|
unit uMainDM;
interface
uses
SysUtils, Classes, DB, WideStrings, Forms, FireDAC.Phys.IB, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys,
FireDAC.Comp.Client, FireDAC.DBX.Migrate, FireDAC.VCLUI.Wait,
FireDAC.Phys.IBLiteDef, FireDAC.Phys.IBDef, FireDAC.Phys.IBBase,
FireDAC.Comp.UI;
type
TMainDM = class(TDataModule)
SQLConnection: TFDConnection;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDPhysIBDriverLink1: TFDPhysIBDriverLink;
procedure DataModuleCreate(Sender: TObject);
procedure SQLConnectionBeforeConnect(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainDM: TMainDM;
implementation
uses uMainForm, System.IOUtils, Winapi.Windows, Vcl.Dialogs;
{$R *.dfm}
procedure TMainDM.DataModuleCreate(Sender: TObject);
begin
try
if not SQLConnection.Connected then
SQLConnection.Open;
TMainForm(Application.MainForm).DBConnection := SQLConnection;
except
on E: Exception do
raise Exception.Create('Error Message: ' + E.Message);
end;
end;
procedure TMainDM.SQLConnectionBeforeConnect(Sender: TObject);
var
fDebugMode: boolean;
fDBTemp, fDBFile: string;
function GetAppDataFolder: string;
var
Path: array [0 .. MAX_PATH + 1] of Char;
begin
if ExpandEnvironmentStrings('%LOCALAPPDATA%', Path, Length(Path)) > 1 then
Result := IncludeTrailingPathDelimiter(Path)
else
Result := '';
end;
begin
{$IF DEFINED(DEBUG)}
fDebugMode := True;
{$ELSE}
fDebugMode := False;
{$ENDIF}
if not fDebugMode then
begin
fDBTemp := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) +
'MEETINGORGANIZER.IB';
fDBFile := GetAppDataFolder + 'MEETINGORGANIZER.IB';
try
if not TFile.Exists(fDBFile) then
TFile.Copy(fDBTemp, fDBFile);
if TFile.Exists(fDBFile) then
SQLConnection.Params.Values['Database'] := fDBFile
else
raise Exception.Create('Error Message: ' + fDBFile + ' not found!');
except
on E: Exception do
raise Exception.Create('Error Message' + E.Message);
end;
end
else
begin
// keeps the DM configuration...
end;
end;
end.
|
unit StructurePoster;
interface
uses PersistentObjects, DBGate, BaseObjects, DB, Organization, SysUtils;
type
// для структур
TStructureDataPoster = class(TImplementedDataPoster)
private
FAllOrganizations: TOrganizations;
FAllFundTypes: TIDObjects;
FAllFieldTypes: TIDObjects;
procedure SetAllOrganizations(const Value: TOrganizations);
public
property AllOrganizations: TOrganizations read FAllOrganizations write SetAllOrganizations;
property AllFundTypes: TIDObjects read FAllFundTypes write FAllFundTypes;
property AllFieldTypes: TIDObjects read FAllFieldTypes write FAllFieldTypes;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TStructureFundTypeDataPoster = class(TImplementedDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
// для месторождений
TFieldDataPoster = class(TStructureDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TBedDataPoster = class(TImplementedDataPoster)
private
FAllFieldTypes: TIDObjects;
public
property AllFieldTypes: TIDObjects read FAllFieldTypes write FAllFieldTypes;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TStructureBindingDataPoster = class(TImplementedDataPoster)
protected
function GetObjectTypeID: integer; virtual;
function GetSourceObjects: TIDObjects; virtual;
public
property ObjectTypeID: integer read GetObjectTypeID;
property SourceObjects: TIDObjects read GetSourceObjects;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TStructureOwnedDistrictsDataPoster = class(TStructureBindingDataPoster)
protected
function GetObjectTypeID: integer; override;
function GetSourceObjects: TIDObjects; override;
public
constructor Create; override;
end;
TStructureOwnedPetrolRegionsDataPoster = class(TStructureBindingDataPoster)
protected
function GetObjectTypeID: integer; override;
function GetSourceObjects: TIDObjects; override;
public
constructor Create; override;
end;
TStructureOwnedTectonicStructsDataPoster = class(TStructureBindingDataPoster)
protected
function GetObjectTypeID: integer; override;
function GetSourceObjects: TIDObjects; override;
public
constructor Create; override;
end;
TStructureOwnedLicenseZonesDataPoster = class(TStructureBindingDataPoster)
protected
function GetObjectTypeID: integer; override;
function GetSourceObjects: TIDObjects; override;
public
constructor Create; override;
end;
TFieldTypeDataPoster = class(TImplementedDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
implementation
uses Structure, Facade, BaseConsts, District, Variants;
{ TStructureDataPoster }
constructor TStructureDataPoster.Create;
begin
inherited;
Options := [];
DataSourceString :='TBL_STRUCTURE'; //'VW_STRUCTURE';
DataDeletionString := 'TBL_STRUCTURE';
DataPostString := 'TBL_STRUCTURE';
KeyFieldNames := 'STRUCTURE_ID,VERSION_ID';
FieldNames := 'STRUCTURE_ID, ORGANIZATION_ID, VCH_STRUCTURE_NAME, VERSION_ID, STRUCTURE_FUND_TYPE_ID'; //FIELD_TYPE_ID';
AccessoryFieldNames := 'STRUCTURE_ID, ORGANIZATION_ID, VCH_STRUCTURE_NAME, VERSION_ID, STRUCTURE_FUND_TYPE_ID';//, FIELD_TYPE_ID';
AutoFillDates := false;
Sort := 'STRUCTURE_ID,VERSION_ID';
end;
function TStructureDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TStructureDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TStructure;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TStructure;
o.ID := ds.FieldByName('STRUCTURE_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_STRUCTURE_NAME').AsString);
o.Version := ds.FieldByName('Version_ID').AsInteger;
if Assigned(AllOrganizations) then
o.Organization := AllOrganizations.ItemsByID[ds.FieldByName('ORGANIZATION_ID').AsInteger] as TOrganization;
if Assigned(AllFundTypes) then
o.StructureFundType := AllFundTypes.ItemsByID[ds.FieldByName('STRUCTURE_FUND_TYPE_ID').AsInteger] as TStructureFundType;
ds.Next;
end;
ds.First;
end;
end;
function TStructureDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
procedure TStructureDataPoster.SetAllOrganizations(
const Value: TOrganizations);
begin
if FAllOrganizations <> Value then
FAllOrganizations := Value;
end;
{ TFieldDataPoster }
constructor TFieldDataPoster.Create;
begin
inherited;
end;
function TFieldDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TFieldDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TField;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TField;
o.ID := ds.FieldByName('STRUCTURE_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_STRUCTURE_NAME').AsString);
o.Organization := AllOrganizations.ItemsByID[ds.FieldByName('ORGANIZATION_ID').AsInteger] as TOrganization;
if Assigned(AllFundTypes) then
o.StructureFundType := AllFundTypes.ItemsByID[ds.FieldByName('STRUCTURE_FUND_TYPE_ID').AsInteger] as TStructureFundType;
if Assigned(AllFieldTypes) then
o.FieldType := AllFieldTypes.ItemsByID[ds.FieldByName('FIELD_TYPE_ID').AsInteger] as TFieldType;
ds.Next;
end;
ds.First;
end;
end;
function TFieldDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
{ TStructureOwnedDistrictsDataPoster }
constructor TStructureBindingDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_STRUCTURE_OBJECT_BINDING';
FieldNames := 'OBJECT_TYPE_ID, VERSION_ID, STRUCTURE_ID, OBJECT_ID';
AccessoryFieldNames := 'OBJECT_TYPE_ID, VERSION_ID, STRUCTURE_ID, OBJECT_ID';
KeyFieldNames := 'OBJECT_TYPE_ID; VERSION_ID; STRUCTURE_ID; OBJECT_ID';
AutoFillDates := false;
Sort := '';
end;
function TStructureBindingDataPoster.DeleteFromDB(
AObject: TIDObject; ACollection: TIDObjects): integer;
var ds: TCommonServerDataSet;
begin
Result := 0;
ds := TMainFacade.GetInstance.DBGates.Add(Self);
try
ds.First;
if ds.Locate(ds.KeyFieldNames, varArrayOf([ObjectTypeID, (TMainFacade.GetInstance as TMainFacade).ActiveVersion.ID, ACollection.Owner.ID, AObject.ID]), []) then
ds.Delete
except
Result := -1;
end;
end;
function TStructureBindingDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
AObjects.Add(SourceObjects.ItemsByID[ds.FieldByName('OBJECT_ID').AsInteger], false, false);
ds.Next;
end;
ds.First;
end;
end;
function TStructureBindingDataPoster.GetObjectTypeID: integer;
begin
Result := 0;
end;
function TStructureBindingDataPoster.GetSourceObjects: TIDObjects;
begin
Result := nil;
end;
function TStructureBindingDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
begin
Result := 0;
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
if ds.Locate(KeyFieldNames, VarArrayOf([ObjectTypeID, (TMainFacade.GetInstance as TMainFacade).ActiveVersion.ID, ACollection.Owner.ID, AObject.ID]), []) then
ds.Edit
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
ds.FieldByName('OBJECT_TYPE_ID').AsInteger := ObjectTypeID;
ds.FieldByName('VERSION_ID').AsInteger := 0;
ds.FieldByName('STRUCTURE_ID').AsInteger := ACollection.Owner.ID;
ds.FieldByName('OBJECT_ID').AsInteger := AObject.ID;
ds.Post;
end;
{ TStructureOwnedDistrictsDataPoster }
constructor TStructureOwnedDistrictsDataPoster.Create;
begin
inherited;
end;
function TStructureOwnedDistrictsDataPoster.GetObjectTypeID: integer;
begin
Result := DISTRICT_OBJECT_TYPE_ID;
end;
function TStructureOwnedDistrictsDataPoster.GetSourceObjects: TIDObjects;
begin
Result := TMainFacade.GetInstance.AllDistricts;
end;
{ TStructureOwnedPetrolRegionsDataPoster }
constructor TStructureOwnedPetrolRegionsDataPoster.Create;
begin
inherited;
end;
function TStructureOwnedPetrolRegionsDataPoster.GetObjectTypeID: integer;
begin
Result := PETROL_REGION_OBJECT_TYPE_ID;
end;
function TStructureOwnedPetrolRegionsDataPoster.GetSourceObjects: TIDObjects;
begin
Result := TMainFacade.GetInstance.AllPetrolRegions;
end;
{ TStructureOwnedTectonicStructsDataPoster }
constructor TStructureOwnedTectonicStructsDataPoster.Create;
begin
inherited;
end;
function TStructureOwnedTectonicStructsDataPoster.GetObjectTypeID: integer;
begin
Result := TECTONIC_STRUCT_OBJECT_TYPE_ID;
end;
function TStructureOwnedTectonicStructsDataPoster.GetSourceObjects: TIDObjects;
begin
Result := TMainFacade.GetInstance.AllTectonicStructures;
end;
{ TStructureOwnedLicenseZonesDataPoster }
constructor TStructureOwnedLicenseZonesDataPoster.Create;
begin
inherited;
end;
function TStructureOwnedLicenseZonesDataPoster.GetObjectTypeID: integer;
begin
Result := LICENSE_ZONE_OBJECT_TYPE_ID;
end;
function TStructureOwnedLicenseZonesDataPoster.GetSourceObjects: TIDObjects;
begin
Result := TMainFacade.GetInstance.AllLicenseZones;
end;
{ TStructureFundTypeDataPoster }
constructor TStructureFundTypeDataPoster.Create;
begin
inherited;
Options := [];
DataSourceString := 'TBL_STRUCTURE_FUND_TYPE_DICT';
DataDeletionString := '';
DataPostString := '';
KeyFieldNames := 'STRUCTURE_FUND_TYPE_ID';
FieldNames := 'STRUCTURE_FUND_TYPE_ID, VCH_STRUCTURE_FUND_TYPE_NAME';
AccessoryFieldNames := '';
AutoFillDates := false;
Sort := '';
end;
function TStructureFundTypeDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TStructureFundTypeDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TStructureFundType;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TStructureFundType;
o.ID := ds.FieldByName('STRUCTURE_FUND_TYPE_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_STRUCTURE_FUND_TYPE_NAME').AsString);
ds.Next;
end;
ds.First;
end;
end;
function TStructureFundTypeDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
{ TFieldTypeDataPoster }
constructor TFieldTypeDataPoster.Create;
begin
inherited;
Options := [];
DataSourceString := 'TBL_FIELD_TYPE_DICT';
DataDeletionString := '';
DataPostString := '';
KeyFieldNames := 'FIELD_TYPE_ID';
FieldNames := 'FIELD_TYPE_ID, VCH_FIELD_TYPE_NAME, VCH_FIELD_TYPE_SHORT_NAME';
AccessoryFieldNames := '';
AutoFillDates := false;
Sort := '';
end;
function TFieldTypeDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TFieldTypeDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TFieldType;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TFieldType;
o.ID := ds.FieldByName('FIELD_TYPE_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_FIELD_TYPE_NAME').AsString);
ds.Next;
end;
ds.First;
end;
end;
function TFieldTypeDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
{ TBedDataPoster }
constructor TBedDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'VW_BED';
DataDeletionString := 'TBL_BED';
DataPostString := 'TBL_BED';
KeyFieldNames := 'BED_ID';
FieldNames := 'bed_id, structure_id, vch_bed_index, field_type_id';
AccessoryFieldNames := 'bed_id, structure_id, vch_bed_index, field_type_id';
AutoFillDates := false;
Sort := 'VCH_BED_INDEX';
end;
function TBedDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TBedDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TBed;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TBed;
o.ID := ds.FieldByName('bed_id').AsInteger;
o.Name := trim(ds.FieldByName('vch_bed_index').AsString);
if Assigned(AllFieldTypes) then
o.FieldType := AllFieldTypes.ItemsByID[ds.FieldByName('field_type_id').AsInteger] as TFieldType;
ds.Next;
end;
end;
end;
function TBedDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
end.
|
//Aziz Vicentini - Brasil
//E-mail: azizvc@yahoo.com.br
//Arquivo de opções do jogo
unit GameOptions;
interface
uses Windows, Classes, SysUtils, Graphics;
type
TGameOptHeader = packed record //16 bytes
Resolucao: Byte; //Resolução de Tela;
CamDistancia, CamAltura: Single; //Ajustes de camera
Carro: Integer; //Carro selecionado
Cor: TColor;
end;
TGameOpt = class
private
GameOptFile: TFileStream;
public
Header: TGameOptHeader;
constructor Create;
destructor Destroy; override;
procedure SaveToFile (const FileName: string);
procedure LoadFromFile (const FileName: string);
end;
const
cSizeOfHeader = SizeOf(TGameOptHeader);
implementation
constructor TGameOpt.Create;
begin
//---
end;
destructor TGameOpt.Destroy;
begin
inherited Destroy;
end;
procedure TGameOpt.LoadFromFile(const FileName: string);
begin
GameOptFile:= TFileStream.Create(FileName,fmOpenRead);
try
GameOptFile.Read(Header, GameOptFile.Size); //cSizeOfHeader
finally
GameOptFile.Free;
end;
end;
procedure TGameOpt.SaveToFile(const FileName: string);
begin
GameOptFile:= TFileStream.Create(FileName,fmCreate);
try
GameOptFile.Write(Header, cSizeOfHeader);
finally
GameOptFile.Free;
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado Ó tabela [EMPRESA]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
t2ti.com@gmail.com
@author Albert Eije
@version 1.0
*******************************************************************************}
unit EmpresaVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils,
EmpresaEnderecoVO;
type
[TEntity]
[TTable('EMPRESA')]
TEmpresaVO = class(TVO)
private
FID: Integer;
FID_EMPRESA: Integer;
FID_CONTADOR: Integer;
FRAZAO_SOCIAL: String;
FNOME_FANTASIA: String;
FCNPJ: String;
FINSCRICAO_ESTADUAL: String;
FINSCRICAO_ESTADUAL_ST: String;
FINSCRICAO_MUNICIPAL: String;
FINSCRICAO_JUNTA_COMERCIAL: String;
FDATA_INSC_JUNTA_COMERCIAL: TDateTime;
FTIPO: String;
FDATA_CADASTRO: TDateTime;
FDATA_INICIO_ATIVIDADES: TDateTime;
FSUFRAMA: String;
FEMAIL: String;
FIMAGEM_LOGOTIPO: String;
FCRT: String;
FTIPO_REGIME: String;
FALIQUOTA_PIS: Extended;
FCONTATO: String;
FALIQUOTA_COFINS: Extended;
FCODIGO_IBGE_CIDADE: Integer;
FCODIGO_IBGE_UF: Integer;
FCODIGO_TERCEIROS: Integer;
FCODIGO_GPS: Integer;
FALIQUOTA_SAT: Extended;
FCEI: String;
FCODIGO_CNAE_PRINCIPAL: String;
FTIPO_CONTROLE_ESTOQUE: String;
FEnderecoPrincipal: TEmpresaEnderecoVO;
public
[TId('ID', [ldGrid, ldLookup, ldComboBox])]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_EMPRESA','Id Matriz',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdMatriz: Integer read FID_EMPRESA write FID_EMPRESA;
[TColumn('ID_CONTADOR','Id Contador',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdContador: Integer read FID_CONTADOR write FID_CONTADOR;
[TColumn('RAZAO_SOCIAL','Razao Social',450,[ldGrid, ldLookup, ldCombobox], False)]
property RazaoSocial: String read FRAZAO_SOCIAL write FRAZAO_SOCIAL;
[TColumn('NOME_FANTASIA','Nome Fantasia',450,[ldGrid, ldLookup, ldCombobox], False)]
property NomeFantasia: String read FNOME_FANTASIA write FNOME_FANTASIA;
[TColumn('CNPJ','Cnpj',112,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftCnpj, taLeftJustify)]
property Cnpj: String read FCNPJ write FCNPJ;
[TColumn('INSCRICAO_ESTADUAL','Inscricao Estadual',240,[ldGrid, ldLookup, ldCombobox], False)]
property InscricaoEstadual: String read FINSCRICAO_ESTADUAL write FINSCRICAO_ESTADUAL;
[TColumn('INSCRICAO_ESTADUAL_ST','Inscricao Estadual St',240,[ldGrid, ldLookup, ldCombobox], False)]
property InscricaoEstadualSt: String read FINSCRICAO_ESTADUAL_ST write FINSCRICAO_ESTADUAL_ST;
[TColumn('INSCRICAO_MUNICIPAL','Inscricao Municipal',240,[ldGrid, ldLookup, ldCombobox], False)]
property InscricaoMunicipal: String read FINSCRICAO_MUNICIPAL write FINSCRICAO_MUNICIPAL;
[TColumn('INSCRICAO_JUNTA_COMERCIAL','Inscricao Junta Comercial',240,[ldGrid, ldLookup, ldCombobox], False)]
property InscricaoJuntaComercial: String read FINSCRICAO_JUNTA_COMERCIAL write FINSCRICAO_JUNTA_COMERCIAL;
[TColumn('DATA_INSC_JUNTA_COMERCIAL','Data Insc Junta Comercial',80,[ldGrid, ldLookup, ldCombobox], False)]
property DataInscJuntaComercial: TDateTime read FDATA_INSC_JUNTA_COMERCIAL write FDATA_INSC_JUNTA_COMERCIAL;
[TColumn('TIPO','Tipo',8,[ldGrid, ldLookup, ldCombobox], False)]
property Tipo: String read FTIPO write FTIPO;
[TColumn('DATA_CADASTRO','Data Cadastro',80,[ldGrid, ldLookup, ldCombobox], False)]
property DataCadastro: TDateTime read FDATA_CADASTRO write FDATA_CADASTRO;
[TColumn('DATA_INICIO_ATIVIDADES','Data Inicio Atividades',80,[ldGrid, ldLookup, ldCombobox], False)]
property DataInicioAtividades: TDateTime read FDATA_INICIO_ATIVIDADES write FDATA_INICIO_ATIVIDADES;
[TColumn('SUFRAMA','Suframa',72,[ldGrid, ldLookup, ldCombobox], False)]
property Suframa: String read FSUFRAMA write FSUFRAMA;
[TColumn('EMAIL','Email',450,[ldGrid, ldLookup, ldCombobox], False)]
property Email: String read FEMAIL write FEMAIL;
[TColumn('IMAGEM_LOGOTIPO','Imagem Logotipo',450,[ldGrid, ldLookup, ldCombobox], False)]
property ImagemLogotipo: String read FIMAGEM_LOGOTIPO write FIMAGEM_LOGOTIPO;
[TColumn('CRT','Crt',8,[ldGrid, ldLookup, ldCombobox], False)]
property Crt: String read FCRT write FCRT;
[TColumn('TIPO_REGIME','Tipo Regime',8,[ldGrid, ldLookup, ldCombobox], False)]
property TipoRegime: String read FTIPO_REGIME write FTIPO_REGIME;
[TColumn('ALIQUOTA_PIS','Aliquota Pis',168,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property AliquotaPis: Extended read FALIQUOTA_PIS write FALIQUOTA_PIS;
[TColumn('CONTATO','Contato',400,[ldGrid, ldLookup, ldCombobox], False)]
property Contato: String read FCONTATO write FCONTATO;
[TColumn('ALIQUOTA_COFINS','Aliquota Cofins',168,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property AliquotaCofins: Extended read FALIQUOTA_COFINS write FALIQUOTA_COFINS;
[TColumn('CODIGO_IBGE_CIDADE','Codigo Ibge Cidade',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property CodigoIbgeCidade: Integer read FCODIGO_IBGE_CIDADE write FCODIGO_IBGE_CIDADE;
[TColumn('CODIGO_IBGE_UF','Codigo Ibge Uf',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property CodigoIbgeUf: Integer read FCODIGO_IBGE_UF write FCODIGO_IBGE_UF;
[TColumn('CODIGO_TERCEIROS','Codigo Terceiros',168,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property CodigoTerceiros: Integer read FCODIGO_TERCEIROS write FCODIGO_TERCEIROS;
[TColumn('CODIGO_GPS','Codigo Gps',80,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property CodigoGps: Integer read FCODIGO_GPS write FCODIGO_GPS;
[TColumn('ALIQUOTA_SAT','Aliquota Sat',168,[ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property AliquotaSat: Extended read FALIQUOTA_SAT write FALIQUOTA_SAT;
[TColumn('CEI','CEI',100,[ldGrid, ldLookup, ldCombobox], False)]
property Cei: String read FCEI write FCEI;
[TColumn('CODIGO_CNAE_PRINCIPAL','CNAE Principal',100,[ldGrid, ldLookup, ldCombobox], False)]
property CodigoCnaePrincipal: String read FCODIGO_CNAE_PRINCIPAL write FCODIGO_CNAE_PRINCIPAL;
[TColumn('TIPO_CONTROLE_ESTOQUE','Tipo Controle Estoque', 100, [ldGrid, ldLookup, ldCombobox], False)]
property TipoControleEstoque: String read FTIPO_CONTROLE_ESTOQUE write FTIPO_CONTROLE_ESTOQUE;
// Pega da lista de enderešos o principal e seta nessa propriedade
property EnderecoPrincipal: TEmpresaEnderecoVO read FEnderecoPrincipal write FEnderecoPrincipal;
end;
implementation
initialization
Classes.RegisterClass(TEmpresaVO);
finalization
Classes.UnRegisterClass(TEmpresaVO);
end.
|
{------------------------------------
功能说明:展示平台所有服务接口
创建日期:2010.04.21
作者:WZW
版权:WZW
-------------------------------------}
unit ViewSvcInfo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ComCtrls, SvcInfoIntf, StdCtrls, ImgList, ToolWin,
uBaseForm;
type
PSvcInfoRec = ^TSvcInfoRec;
Tfrm_SvcInfo = class(TBaseForm, ISvcInfoGetter)
tv_Svc: TTreeView;
Splitter1: TSplitter;
Pnl_Svc: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
edt_Title: TEdit;
edt_GUID: TEdit;
edt_Ver: TEdit;
edt_ModuleName: TEdit;
mm_Comments: TMemo;
ImageList1: TImageList;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
procedure tv_SvcDeletion(Sender: TObject; Node: TTreeNode);
procedure FormCreate(Sender: TObject);
procedure tv_SvcChange(Sender: TObject; Node: TTreeNode);
procedure ToolButton2Click(Sender: TObject);
procedure ToolButton1Click(Sender: TObject);
private
procedure StartEnum;
function GetNode(const NodeText: String): TTreeNode;
protected
{ISvcInfoGetter}
procedure SvcInfo(SvcInfo: TSvcInfoRec);
public
{ Public declarations }
end;
var
frm_SvcInfo: Tfrm_SvcInfo;
implementation
uses SysSvc;
{$R *.dfm}
{ Tfrm_SvcInfo }
function Tfrm_SvcInfo.GetNode(const NodeText: String): TTreeNode;
var i: Integer;
begin
Result := nil;
for i := 0 to self.tv_Svc.Items.Count - 1 do
begin
if CompareText(self.tv_Svc.Items[i].Text, NodeText) = 0 then
begin
Result := self.tv_Svc.Items[i];
exit;
end;
end;
end;
procedure Tfrm_SvcInfo.StartEnum;
var SvcInfoEx: ISvcInfoEx;
begin
if SysService.QueryInterface(ISvcInfoEx, SvcInfoEx) = S_OK then
begin
self.tv_Svc.Items.BeginUpdate;
try
self.tv_Svc.Items.Clear;
SvcInfoEx.GetSvcInfo(self);
self.tv_Svc.Items[0].Expanded := True;
finally
self.tv_Svc.Items.EndUpdate;
end;
end;
end;
procedure Tfrm_SvcInfo.tv_SvcDeletion(Sender: TObject; Node: TTreeNode);
begin
if Assigned(Node.Data) then
Dispose(PSvcInfoRec(Node.Data));
end;
procedure Tfrm_SvcInfo.FormCreate(Sender: TObject);
begin
StartEnum;
end;
procedure Tfrm_SvcInfo.tv_SvcChange(Sender: TObject; Node: TTreeNode);
var SvcInfo: PSvcInfoRec;
begin
self.edt_Title.Text := '';
self.edt_GUID.Text := '';
self.edt_Ver.Text := '';
self.edt_ModuleName.Text := '';
self.mm_Comments.Text := '';
if Assigned(Node.Data) then
begin
SvcInfo := PSvcInfoRec(Node.Data);
self.edt_Title.Text := SvcInfo^.Title;
self.edt_GUID.Text := Node.Text;
self.edt_Ver.Text := SvcInfo^.Version;
self.edt_ModuleName.Text := SvcInfo^.ModuleName;
self.mm_Comments.Text := SvcInfo^.Comments;
end;
end;
procedure Tfrm_SvcInfo.ToolButton2Click(Sender: TObject);
begin
self.Close;
end;
procedure Tfrm_SvcInfo.ToolButton1Click(Sender: TObject);
var GUID: String;
i: Integer;
begin
if InputQuery('查找接口', '请输入接口的GUID:', GUID) then
begin
for i := 0 to self.tv_Svc.Items.Count - 1 do
begin
if Pos(GUID, self.tv_Svc.Items[i].Text) <> 0 then
begin
self.tv_Svc.Items[i].Selected := True;
self.tv_Svc.Items[i].Expanded := true;
exit;
end;
end;
end;
end;
procedure Tfrm_SvcInfo.SvcInfo(SvcInfo: TSvcInfoRec);
var RNode, PNode, NewNode: TTreeNode;
SvcInfoRec: PSvcInfoRec;
ModuleName: String;
begin
RNode := self.GetNode('所有接口');
if RNode = nil then
begin
RNode := self.tv_Svc.Items.AddChild(nil, '所有接口');
RNode.ImageIndex := 0;
RNode.SelectedIndex := 0;
end;
ModuleName := SvcInfo.ModuleName;
if ModuleName = '' then
ModuleName := '<未知>';
PNode := self.GetNode(ModuleName);
if PNode = nil then
begin
PNode := self.tv_Svc.Items.AddChild(RNode, ModuleName);
PNode.ImageIndex := 1;
PNode.SelectedIndex := 1;
end;
NewNode := self.tv_Svc.Items.AddChild(PNode, SvcInfo.GUID);
NewNode.ImageIndex := 2;
NewNode.SelectedIndex := 2;
New(SvcInfoRec);
SvcInfoRec^.ModuleName := ModuleName;
SvcInfoRec^.Title := SvcInfo.Title;
SvcInfoRec^.Version := SvcInfo.Version;
SvcInfoRec^.Comments := SvcInfo.Comments;
NewNode.Data := SvcInfoRec;
end;
end.
|
unit linklist;
interface
type
entry = double; {may be any type}
node_ptr=^node;
node = record
info:entry;
next:node_ptr;
end;
procedure list_init(var head:node_ptr);
{initializes the list to be empty}
function list_next(p:node_ptr):node_ptr;
{returns a pointer to the next node in the list
asumption: p points to a node in the list }
function list_prev(head:node_ptr; p:node_ptr):node_ptr;
{returns a pointer to the previous node in the list
assumption: p points to a node in the list}
function retrieve(head:node_ptr):entry;
{return the number (x) that is pointing to}
procedure headinsert(var head:node_ptr; x:entry);
{a new node containing 'x' insert at the head of the list}
procedure insert_after(p:node_ptr; x:entry);
{insert x AFTER a node that p point to it}
procedure insert_before(p:node_ptr; x:entry);
{insert x BEFORE a node that p point to it}
procedure delete_num(var head:node_ptr; x:entry);
{if there is a node that contains 'x', then the first
such a node has been removed from the list.
if no node contains 'x', the list is not change}
function search(head:node_ptr; x:entry):node_ptr;
{returns pointer to the first node contains 'x'.
if no node contains 'x', then returns nil.}
function is_empty(head:node_ptr):boolean;
{returns true if the list is empty, and false otherwise.}
procedure destroy_list(var head:node_ptr);
{destroy the list and free the memory}
implementation
procedure list_init(var head:node_ptr);
begin
head:=nil;
end; {list_init}
function list_next(p:node_ptr):node_ptr;
begin
list_next := p^.next;
end; {list_next}
function list_prev(head:node_ptr; p:node_ptr):node_ptr;
begin
while (head <> nil) and (head^.next <> p) do
head:=head^.next;
list_prev:=head;
end; {list_prev}
function retrieve(head:node_ptr):entry;
begin
retrieve:=head^.info;
end; {retrieve}
procedure headinsert(var head:node_ptr; x:entry);
var temp:node_ptr;
begin
new(temp);
temp^.info:=x;
temp^.next:=head;
head:=temp;
end; {headinsert}
procedure insert_after(p:node_ptr; x:entry);
var temp:node_ptr;
begin
new(temp);
temp^.info:=x;
temp^.next:=p^.next;
p^.next:=temp;
end; {insert_after}
procedure insert_before(p:node_ptr; x:entry);
var temp:node_ptr;
begin
new(temp);
temp^:=p^;
p^.info:=x;
p^.next:=temp;
end; {insert_before}
procedure delete_num(var head:node_ptr; x:entry);
var
currptr,prevptr:node_ptr;
begin
if (head <> nil) then
begin {traverse the list}
prevptr:=nil;
currptr:=head;
while (currptr <> nil) and (currptr^.info <> x) do
begin
prevptr:=currptr;
currptr:=currptr^.next;
end;
if (prevptr = nil) then {x is the first elemnt}
begin
head:=head^.next;
dispose(currptr);
end
else if (currptr <> nil) then {x if not the first element}
begin
prevptr^.next:=currptr^.next;
dispose(currptr);
end;
end;
end; {delete_num}
function search(head:node_ptr; x:entry):node_ptr;
begin
while (head <> nil) and (head^.info <> x) do
head:=head^.next;
search:=head;
end; {search}
function is_empty(head:node_ptr):boolean;
begin
is_empty:= (head=nil); {true if head=nil}
end; {is_empty}
procedure destroy_list(var head:node_ptr);
var p:node_ptr;
begin
while head <> nil do
begin
p:=head^.next;
dispose(head);
head:=p;
end;
p := Nil;
end; {destroy_list}
begin
end.
|
{********************************************************}
{ }
{ Zeos Database Objects }
{ Extra dbware functions }
{ }
{ Copyright (c) 1999-2001 Sergey Seroukhov }
{ Copyright (c) 1999-2002 Zeos Development Group }
{ }
{********************************************************}
unit ZSqlExtra;
interface
uses SysUtils, Classes, DB;
{$INCLUDE ../Zeos.inc}
{**************** Extra functions definition ****************}
{ Extract field from string as Db.Table.Field }
function ExtractField(Value: string): string;
{ Extract field precision from type description }
function ExtractPrecision(Value: string): Integer;
{ Replace #10#13#9 charactires with spaces }
function ClearSpaces(Value: string): string;
{ Get index of name case sensetive }
function CaseIndexOf(List: TStrings; Value: string): Integer;
{ Get index of field in list }
function FieldIndexOf(List: string; Field: string): Integer;
{ Invert list delimited with semicolon }
function InvertList(List: string): string;
implementation
uses ZDBaseConst, ZExtra, ZToken;
{************** Extra functions implementation ***************}
{ Extract field name from string as Db.Table.Field }
function ExtractField(Value: string): string;
var
P: Integer;
begin
Result := Value;
P := LastDelimiter('.', Result);
Result := Copy(Result, P+1, Length(Result)-P);
if Pos(' ', Result) > 0 then
Result := '"' + Result + '"';
end;
{ Extract field precision from type description }
function ExtractPrecision(Value: string): Integer;
begin
StrTok(Value,'() ,.');
StrTok(Value,'() ,.');
Result := StrToIntDef(StrTok(Value,'() ,.'),4);
end;
{ Replace #10#13#9 charactires with spaces }
function ClearSpaces(Value: string): string;
var
I: Integer;
Prev: Char;
Quote: Char;
begin
Result := Value;
Prev := #0;
Quote := #0;
I := 1;
while I <= Length(Result) do
begin
if (Result[I] in [' ',#9,#10,#13]) and (Quote = #0) then
begin
if Prev = ' ' then
begin
Delete(Result, I, 1);
Dec(I);
end else
Result[I] := ' ';
end;
if (Result[I] in ['"', '''']) and (Prev <> '\') then
begin
if Quote = #0 then
Quote := Result[I]
else if Quote = Result[I] then
Quote := #0;
end;
Prev := Result[I];
Inc(I);
end;
end;
{ Get index of name }
function CaseIndexOf(List: TStrings; Value: string): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to List.Count-1 do
if StrCaseCmp(List[I], Value) then
begin
Result := I;
Exit;
end;
end;
{ Get index of field in list }
function FieldIndexOf(List: string; Field: string): Integer;
var
Temp: string;
N: Integer;
begin
Result := 0;
N := 1;
while List <> '' do
begin
Temp := Trim(StrTokEx(List, ';,'));
if StrCaseCmp(Temp, Field) then
begin
Result := N;
Exit;
end;
Inc(N);
end;
end;
{ Invert list delimited with semicolon }
function InvertList(List: string): string;
var
Temp: string;
begin
Result := '';
while List <> '' do
begin
Temp := Trim(StrTokEx(List, ';,'));
if Temp = '' then Continue;
if Result <> '' then Result := ';' + Result;
Result := Temp + Result;
end;
end;
end.
|
unit u_CsvWriter;
interface
uses
t_DroneMission,
u_FileWriter;
type
TCsvWriter = class(TFileWriter)
private
procedure WriteRoute(const ARoute: TMissionRoute; const ARouteId: Integer);
public
procedure DoWrite(const AMission: TMission); override;
end;
implementation
uses
SysUtils;
{ TCsvWriter }
procedure TCsvWriter.DoWrite(const AMission: TMission);
var
I: Integer;
begin
WriteText('Point,Lat,Lon');
for I := 0 to Length(AMission) - 1 do begin
WriteRoute(AMission[I], I+1);
end;
end;
procedure TCsvWriter.WriteRoute(
const ARoute: TMissionRoute;
const ARouteId: Integer
);
var
I: Integer;
begin
for I := 0 to Length(ARoute) - 1 do begin
WriteText(
Format('%d,%s,%s', [I+1, ARoute[I].Lat, ARoute[I].Lon])
);
end;
end;
end.
|
{$include kode.inc}
unit kode_canvas_cairo;
// http://cairographics.org/samples/
{
"Why are all my lines fuzzy in cairo?"
http://stevehanov.ca/blog/index.php?id=28
"How do I draw a sharp, single-pixel-wide line?"
http://www.cairographics.org/FAQ/#sharp_lines
}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
//kode_array,
kode_canvas_base,
kode_color,
kode_drawable,
kode_rect,
kode_surface,
kode_surface_cairo,
Cairo;
//----------------------------------------------------------------------
type
//KClipStack = specialize KArray<KRect>;
KCanvas_Cairo = class(KCanvas_Base)
private
FCairo : Pcairo_t;
FSurface : KSurface{_Cairo};
//FTextExt : cairo_text_extents_t;
//FClipRect : KRect;
//FClipStack : KClipStack;
public
property _cairo : Pcairo_t read FCairo;
property _surface : KSurface{_Cairo} read FSurface;
//property _cliprect : KRect read FClipRect write FClipRect;
public
constructor create(ASurface:KSurface{_Cairo});
destructor destroy; override;
public
{ draw }
procedure setDrawColor(AColor:KColor); override;
procedure setPenSize(ASize:LongInt); override;
procedure drawPoint(AX,AY:LongInt); override;
procedure drawHLine(AX1,AY1,AX2:LongInt); override;
procedure drawVLine(AX1,AY1,AY2:LongInt); override;
procedure drawLine(AX1,AY1,AX2,AY2:LongInt); override;
procedure drawRect(AX1,AY1,AX2,AY2:LongInt); override;
procedure drawEllipse(AX1,AY1,AX2,AY2:LongInt); override;
procedure drawArc(AX1,AY1,AX2,AY2:LongInt; AAngle1,AAngle2:Single); override;
{ fill }
procedure setFillColor(AColor:KColor); override;
procedure fillRect(AX1,AY1,AX2,AY2:LongInt); override;
procedure fillEllipse(AX1,AY1,AX2,AY2:LongInt); override;
procedure fillArc(AX1,AY1,AX2,AY2:LongInt; AAngle1,AAngle2:Single); override;
{ text }
procedure setTextColor(AColor:KColor); override;
procedure setTextSize(ASize:LongWord); override;
function getTextWidth(AText:PChar) : LongWord; override;
function getTextHeight(AText:PChar) : LongWord; override;
procedure selectFont(AFontName:PChar; ASlant:LongInt=0; AWeight:LongInt=0); override;
procedure drawText(AX,AY:LongInt; AText:PChar); override;
procedure drawText(AX1,AY1,AX2,AY2:LongInt; AText:PChar; AAlign:LongWord); override;
{ bitmaps }
procedure drawSurface(ADstX,ADstY:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt); override;
procedure blendSurface(ADstX,ADstY:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt); override;
procedure stretchSurface(ADstX,ADstY,ADstW,ADstH:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt); override;
{ clipping }
procedure clip(ARect:KRect); override;
procedure noClip; override;
//public
// procedure pushClip(ARect:KRect);
// procedure popClip;
// function clipIntersection(ARect:KRect) : KRect;
// //function visibleIntersection(ARect:KRect) : KRect;
end;
KCanvas_Implementation = KCanvas_Cairo;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_const,
//kode_debug,
kode_flags;
constructor KCanvas_Cairo.create(ASurface:KSurface{_Cairo});
begin
inherited create;
FSurface := ASurface;
FCairo := cairo_create(FSurface._surface);
cairo_set_line_width(FCairo,1);
end;
//----------
destructor KCanvas_Cairo.destroy;
begin
//self..noClip;
//FClipStack.destroy;
cairo_destroy(FCairo);
inherited;
end;
//----------------------------------------------------------------------
// set/get
//----------------------------------------------------------------------
procedure KCanvas_Cairo.setDrawColor(AColor:KColor);
begin
cairo_set_source_rgb(FCairo,AColor.r,AColor.g,AColor.b);
end;
//----------
procedure KCanvas_Cairo.setFillColor(AColor:KColor);
begin
cairo_set_source_rgb(FCairo,AColor.r,AColor.g,AColor.b);
end;
//----------
procedure KCanvas_Cairo.setTextColor(AColor:KColor);
begin
cairo_set_source_rgb(FCairo,AColor.r,AColor.g,AColor.b);
end;
//----------
procedure KCanvas_Cairo.setPenSize(ASize:LongInt);
begin
cairo_set_line_width(FCairo,ASize);
end;
//----------
const
k_font_slant : array[0..2] of cairo_font_slant_t = (
CAIRO_FONT_SLANT_NORMAL,
CAIRO_FONT_SLANT_ITALIC,
CAIRO_FONT_SLANT_OBLIQUE
);
k_font_weight : array[0..1] of cairo_font_weight_t = (
CAIRO_FONT_WEIGHT_NORMAL,
CAIRO_FONT_WEIGHT_BOLD
);
//---
procedure KCanvas_Cairo.selectFont(AFontName:PChar; ASlant:LongInt; AWeight:LongInt);
begin
cairo_select_font_face(FCairo,AFontName,k_font_slant[ASlant],k_font_weight[AWeight]);
end;
//----------
procedure KCanvas_Cairo.setTextSize(ASize:LongWord);
begin
cairo_set_font_size(FCairo,ASize);
end;
//----------
{
combine width/height into size? w/h var arguments..
}
function KCanvas_Cairo.getTextWidth(AText:PChar) : LongWord;
var
e : cairo_text_extents_t;
begin
cairo_text_extents(FCairo,AText,@e);
result := trunc( e.width );
end;
//----------
function KCanvas_Cairo.getTextHeight(AText:PChar) : LongWord;
var
e : cairo_text_extents_t;
begin
cairo_text_extents(FCairo,AText,@e);
result := trunc( e.height );
end;
//----------------------------------------------------------------------
// draw
//----------------------------------------------------------------------
procedure KCanvas_Cairo.drawPoint(AX,AY:LongInt);
begin
cairo_rectangle(FCairo,AX,AY,1,1);
cairo_fill(FCairo);
end;
//----------
{
"How do I draw a sharp, single-pixel-wide line?"
http://www.cairographics.org/FAQ/#sharp_lines
}
procedure KCanvas_Cairo.drawHLine(AX1,AY1,AX2:LongInt);
begin
//cairo_set_line_width(FCairo,1);
cairo_move_to(FCairo,AX1,AY1+0.5);
cairo_line_to(FCairo,AX2,AY1+0.5);
cairo_stroke(FCairo);
end;
//----------
procedure KCanvas_Cairo.drawVLine(AX1,AY1,AY2:LongInt);
begin
//cairo_set_line_width(FCairo,1);
cairo_move_to(FCairo,AX1+0.5,AY1);
cairo_line_to(FCairo,AX1+0.5,AY2);
cairo_stroke(FCairo);
end;
//----------
procedure KCanvas_Cairo.drawLine(AX1,AY1,AX2,AY2:LongInt);
begin
cairo_move_to(FCairo,AX1,AY1);
cairo_line_to(FCairo,AX2,AY2);
cairo_stroke(FCairo);
end;
//----------
procedure KCanvas_Cairo.drawRect(AX1,AY1,AX2,AY2:LongInt);
begin
cairo_rectangle(FCairo,AX1,AY1,AX2-AX1+1,AY2-AY1+1);
cairo_stroke(FCairo);
end;
//----------
procedure KCanvas_Cairo.drawEllipse(AX1,AY1,AX2,AY2:LongInt);
var
w2, h2 : single;
begin
w2 := Single(AX2 - AX1 + 1) / 2;
h2 := Single(AY2 - AY1 + 1) / 2;
//cairo_new_sub_path(FCairo);
cairo_save(FCairo);
cairo_translate(FCairo,AX1+w2,AY1+h2);
cairo_scale(FCairo,w2,h2);
cairo_new_sub_path(FCairo);
cairo_arc(FCairo,0,0,1,0,KODE_PI2);
cairo_restore(FCairo);
cairo_stroke(FCairo);
end;
//----------
procedure KCanvas_Cairo.drawArc(AX1,AY1,AX2,AY2:LongInt; AAngle1,AAngle2:Single);
var
w2, h2 : single;
a1,a2 : single;
begin
w2 := Single(AX2 - AX1 + 1) / 2;
h2 := Single(AY2 - AY1 + 1) / 2;
a1 := (AAngle1+0.75) * KODE_PI2;
a2 := (AAngle1+AAngle2+0.75) * KODE_PI2;
cairo_save(FCairo);
cairo_translate(FCairo,AX1+w2,AY1+h2);
cairo_scale(FCairo,w2,h2);
cairo_new_sub_path(FCairo);
cairo_arc(FCairo,0,0,1,a1,a2);
cairo_restore(FCairo);
cairo_stroke(FCairo);
end;
//----------------------------------------------------------------------
// text
//----------------------------------------------------------------------
procedure KCanvas_Cairo.drawText(AX,AY:LongInt; AText:PChar);
begin
//cairo_set_source_rgb(FCairo,0,0,0);
//cairo_select_font_face(FCairo,'Arial',CAIRO_FONT_SLANT_NORMAL,CAIRO_FONT_WEIGHT_NORMAL);
//cairo_set_font_size(FCairo,16);
cairo_move_to(FCairo,AX,AY);
cairo_show_text(FCairo,AText);
end;
//----------
procedure KCanvas_Cairo.drawText(AX1,AY1,AX2,AY2:LongInt; AText:PChar; AAlign:LongWord);
var
//e : PKTextExtents;
e : cairo_text_extents_t;
xx,yy{,ww,hh} : single;
x,y,w,h : longint;
begin
x := AX1;
y := AY1;
w := AX2-AX1+1;
h := AY2-AY1+1;
//e := _textExtents(AText);
cairo_text_extents(FCairo,AText,@e);
//ACairo.moveTo(R.x + R.w/2 - ext^.width/2 , R.y + R.h/2 + ext^.height/2 );
case AAlign of
kta_left:
begin
xx := x;
yy := (y+h/2) - (e.height/2 + e.y_bearing);
end;
kta_right:
begin
xx := (x+w-1) - (e.width + e.x_bearing);
yy := (y+h/2) - (e.height/2 + e.y_bearing);
end;
kta_top:
begin
xx := (x + w/2) - (e.width/2 + e.x_bearing);
yy := y + e.height;
end;
kta_bottom:
begin
xx := (x + w/2) - (e.width/2 + e.x_bearing);
yy := (y+h-1) - (e.height + e.y_bearing);
end;
kta_center:
begin
xx := (x + w/2) - (e.width/2 + e.x_bearing);
yy := (y+h/2) - (e.height/2 + e.y_bearing);
end;
end;
{xx := (x + w/2) - (e^.width/2 + e^.x_bearing);}
{yy := (y + h/2) - (e^.height/2 + e^.y_bearing);}
//_moveTo(xx,yy);
cairo_move_to(FCairo,xx,yy);
//_showText(AText);
cairo_show_text(FCairo,AText);
end;
//----------------------------------------------------------------------
// fill
//----------------------------------------------------------------------
procedure KCanvas_Cairo.fillRect(AX1,AY1,AX2,AY2:LongInt);
begin
cairo_rectangle(FCairo,AX1,AY1,AX2-AX1+1,AY2-AY1+1);
cairo_fill(FCairo);
end;
//----------
procedure KCanvas_Cairo.fillEllipse(AX1,AY1,AX2,AY2:LongInt);
var
w2, h2 : single;
begin
w2 := Single(AX2 - AX1 + 1) / 2;
h2 := Single(AY2 - AY1 + 1) / 2;
//cairo_new_sub_path(FCairo);
cairo_save(FCairo);
cairo_translate(FCairo,AX1+w2,AY1+h2);
cairo_scale(FCairo,w2,h2);
cairo_new_sub_path(FCairo);
cairo_arc(FCairo,0,0,1,0,KODE_PI2);
cairo_restore(FCairo);
cairo_fill(FCairo);
end;
//----------
procedure KCanvas_Cairo.fillArc(AX1,AY1,AX2,AY2:LongInt; AAngle1,AAngle2:Single);
var
w2, h2 : single;
a1,a2 : single;
begin
w2 := Single(AX2 - AX1 + 1) / 2;
h2 := Single(AY2 - AY1 + 1) / 2;
a1 := (AAngle1+0.75) * KODE_PI2;
a2 := (AAngle1+AAngle2+0.75) * KODE_PI2;
//cairo_new_sub_path(FCairo);
cairo_move_to(FCairo,AX1+w2,AY1+h2);
cairo_save(FCairo);
cairo_translate(FCairo,AX1+w2,AY1+h2);
cairo_scale(FCairo,w2,h2);
//cairo_new_sub_path(FCairo);
cairo_arc(FCairo,0,0,1,a1,a2);
cairo_restore(FCairo);
cairo_fill(FCairo);
end;
//----------------------------------------------------------------------
// surface
//----------------------------------------------------------------------
{
The x and y parameters give the user-space coordinate at which the surface
origin should appear. (The surface origin is its upper-left corner before any
transformation has been applied.) The x and y patterns are negated and then
set as translation values in the pattern matrix.
}
{
"How to draw a sliced image in Cairo?"
http://stackoverflow.com/questions/8113432/how-to-draw-a-sliced-image-in-cairo
void DrawImage(cairo_t *ctx,int x,int y,int w,int h,cairo_surface_t *img) {
cairo_save(ctx);
cairo_translate(ctx, x, y);
cairo_pattern_t *pattern=cairo_pattern_create_for_surface(img);
cairo_pattern_set_extend(pattern, CAIRO_EXTEND_PAD);
cairo_set_source(ctx, pattern);
cairo_rectangle(ctx, 0, 0, w?w:cairo_image_surface_get_width(img), h?h:cairo_image_surface_get_height(img));
cairo_fill(ctx);
cairo_pattern_destroy(pattern);
cairo_restore(ctx);
}
void DrawThreeSliceImage(cairo_t* ctx,Point p,int width,cairo_surface_t* imgs[3]) {
#define a (imgs[0])
#define b (imgs[1])
#define c (imgs[2])
DrawImage(ctx, p.x, p.y, cairo_image_surface_get_width(a), cairo_image_surface_get_height(a),a);
DrawImage(ctx, p.x+cairo_image_surface_get_width(a), p.y, width-(cairo_image_surface_get_width(a)+cairo_image_surface_get_width(c)), cairo_image_surface_get_height(b),b);
DrawImage(ctx, p.x+(width-cairo_image_surface_get_width(c)), p.y, cairo_image_surface_get_width(c), cairo_image_surface_get_height(c),c);
#undef a
#undef b
#undef c
}
}
procedure KCanvas_Cairo.drawSurface(ADstX,ADstY:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt);
var
pattern : Pcairo_pattern_t;
begin
cairo_set_source_surface(FCairo,ASurface._surface,{0,0}ADstX-ASrcX,ADstY-ASrcY);
cairo_rectangle(FCairo,ADstX,ADstY,ASrcW,ASrcH);
cairo_fill(FCairo);
{cairo_save(FCairo);
cairo_translate(FCairo,ASrcX,ASrcY);
pattern := cairo_pattern_create_for_surface(ASurface._surface);
cairo_pattern_set_extend(pattern,CAIRO_EXTEND_PAD);
cairo_set_source(FCairo,pattern);
cairo_rectangle(FCairo,ADstX,ADstY{0,0},ASrcW,ASrcH);
cairo_fill(FCairo);
cairo_pattern_destroy(pattern);
cairo_restore(FCairo);}
end;
//----------
procedure KCanvas_Cairo.blendSurface(ADstX,ADstY:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt);
begin
end;
//----------
{
> I am trying to scale an image by 50 %.
Try this:
cairo_save(cr);
cairo_translate(cr, target_x, target_y);
cairo_scale(cr, 0.5, 0.5);
// note: it's important to set the source after setting up the
// user space transformation.
cairo_set_source_surface(cr, local_surf, 0, 0);
cairo_paint(cr);
cairo_restore(cr);
}
procedure KCanvas_Cairo.stretchSurface(ADstX,ADstY,ADstW,ADstH:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt);
var
xscale,yscale : single;
begin
xscale := ADstW / ASrcW;
yscale := ADstH / ASrcH;
cairo_rectangle(FCairo,ADstX,ADstY,ADstW,ADstH);
cairo_save(FCairo);
cairo_translate(FCairo,ADstX,ADstY);
cairo_scale(FCairo,xscale,yscale);
cairo_set_source_surface(FCairo,ASurface._surface,0,0{ASrcX,ASrcY});
//cairo_paint(FCairo);
//cairo_rectangle(FCairo,ADstX,ADstY,ADstW,ADstH);
cairo_fill(FCairo);
cairo_restore(FCairo);
end;
//----------------------------------------------------------------------
// clip
//----------------------------------------------------------------------
{
http://osdir.com/ml/lib.cairo/2004-08/msg00006.html
Within the cairo graphics state, there is a notion of a current clipping
path. Initially, this path is infinitely large, (eg. no clipping is
performed).
Calling cairo_clip computes a new clipping path by intersecting the
current clipping path with the current path, (ie. the path formed with
things like cairo_move_to/line_to/curve_to). After that, the effect of
all subsequent drawing operations will be restricted to the area within
the current clipping path.
It is important to note that cairo_clip does not consume the current
path like cairo_stroke and cairo_fill do. This allows you to retain the
current path for subsequent drawing options, since a cairo_save/restore
cannot be used for this purpose as that would eliminate the effect of
cairo_clip. If the path is no longer needed, the user should call
cairo_new_path after cairo_clip to avoid unexpected behavior.
Calling cairo_clip can only shrink the current clipping region. There
are two ways to expand the clip region:
1) Call cairo_init_clip which restores the clip path to its
original infinite size.
2) Call cairo_restore to restore a graphics state where a larger
clip path was earlier saved with cairo_save.
}
procedure KCanvas_Cairo.clip(ARect:KRect);
begin
cairo_reset_clip(FCairo);
cairo_rectangle(FCairo,
ARect.x{ + FMarginX},
ARect.y{ + FMarginY},
ARect.w{ - FMarginX},
ARect.h{ - FMarginY} );
cairo_clip(FCairo);
cairo_new_path(FCairo); // path not consumed by clip()
end;
//----------
procedure KCanvas_Cairo.noClip;
begin
(*
cairo_reset_clip(FCairo);
*)
end;
//----------------------------------------------------------------------
end.
|
unit uPointOfSale;
interface
uses
Generics.Collections, Aurelius.Engine.ObjectManager, Entidades.Comercial,
Aurelius.Criteria.Base, Entities.Scheduling;
type
IPointOfSale = interface
['{A673D9AC-72CF-49C6-9EE5-FEB6C51C4725}']
function IsRegisterOpen: boolean;
procedure OpenRegister(InitialValue: Currency);
procedure CloseRegister(ShiftId: integer);
procedure RegisterSale(Sale: TVenda);
function GetRegisterSummary(ShiftId: Integer): ICriteriaCursor;
function GetRegisterShifts(StartDate, FinishDate: TDateTime): ICriteriaCursor;
end;
TPointOfSale = class(TInterfacedObject, IPointOfSale)
private
FManager: TObjectManager;
FActiveShift: TRegisterShift;
FItau: TAccount;
FCashAccount: TAccount;
property Manager: TObjectManager read FManager;
function CreateItauAccount: TAccount;
function CreateCashAccount: TAccount;
public
constructor Create;
destructor Destroy; override;
function ActiveShift: TRegisterShift;
function Itau: TAccount;
function CashAccount: TAccount;
function IsRegisterOpen: boolean;
function GetRegisterSummary(ShiftId: Integer): ICriteriaCursor;
procedure RegisterSale(Sale: TVenda);
procedure OpenRegister(InitialValue: Currency);
procedure CloseRegister(ShiftId: integer);
function GetRegisterShifts(StartDate, FinishDate: TDateTime): ICriteriaCursor;
end;
function CreatePointOfSale: IPointOfSale;
implementation
uses
Aurelius.Criteria.Projections,
Aurelius.Drivers.Interfaces,
dConnection, Aurelius.Criteria.Linq, System.SysUtils;
function CreatePointOfSale: IPointOfSale;
begin
Result := TPointOfSale.Create;
end;
{ TPointOfSale }
function TPointOfSale.ActiveShift: TRegisterShift;
begin
if FActiveShift = nil then
begin
FActiveShift := Manager.Find<TRegisterShift>
.Where(TLinq.IsNull('ClosingDate'))
.Take(1)
.UniqueResult;
end;
Result := FActiveShift;
end;
function TPointOfSale.CashAccount: TAccount;
begin
if FCashAccount = nil then
begin
FCashAccount := Manager.Find<TAccount>
.Where(
TLinq.Eq('AccountType', TAccountType.Cash)
and TLinq.Eq('Name', 'Caixa')
)
.Take(1)
.UniqueResult;
if FCashAccount = nil then
FCashAccount := CreateCashAccount;
end;
Result := FCashAccount;
end;
procedure TPointOfSale.CloseRegister(ShiftId: integer);
var
M: TObjectManager;
DBTrans: IDBTransaction;
Shift: TRegisterShift;
Item: TRegisterShiftItem;
Entry: TAccountEntry;
Receivable: TReceivable;
begin
M := dmConnection.CreateManager;
try
Shift := M.Find<TRegisterShift>(ShiftId);
if Shift.Closed then
raise Exception.Create('Caixa já está fechado.');
DBTrans := M.Connection.BeginTransaction;
try
for Item in Shift.Items do
begin
case Item.ItemType of
TRegisterShiftItemType.Payment:
begin
if Item.PaymentType.Mode = TPaymentMode.Cash then
begin
Entry := TAccountEntry.Create;
Entry.Date := Now;
Entry.Account := M.Find<TAccount>(CashAccount.Id);
Entry.Amount := Item.Amount;
M.Save(Entry);
end else
begin
Receivable := TReceivable.Create;
Receivable.DueDate := Now + Item.PaymentType.DaysToReceive;
Receivable.Amount := Item.Amount;
Receivable.RegisterItem := Item;
M.Save(Receivable);
end;
end;
end;
end;
Item := TRegisterShiftItem.Create;
try
Shift.Items.Add(Item);
Item.Shift := Shift;
Item.Date := Now;
Item.ItemType := TRegisterShiftItemType.Close;
Item.Amount := 0;
M.Save(Item);
except
Item.Free;
raise;
end;
Shift.ClosingDate := Now;
M.Flush;
FActiveShift := nil;
DBTrans.Commit;
except
DBTrans.Rollback;
raise;
end;
finally
M.Free;
end;
end;
constructor TPointOfSale.Create;
begin
FManager := dmConnection.CreateManager;
end;
function TPointOfSale.CreateCashAccount: TAccount;
begin
Result := TAccount.Create;
try
Result.AccountType := TAccountType.Cash;
Result.Name := 'Caixa';
Manager.Save(Result);
except
Result.Free;
raise;
end;
end;
function TPointOfSale.CreateItauAccount: TAccount;
begin
Result := TAccount.Create;
try
Result.AccountType := TAccountType.Bank;
Result.Name := 'Itau';
Manager.Save(Result);
except
Result.Free;
raise;
end;
end;
destructor TPointOfSale.Destroy;
begin
FManager.Free;
inherited;
end;
function TPointOfSale.GetRegisterShifts(StartDate, FinishDate: TDateTime): ICriteriaCursor;
begin
Result := Manager.Find<TRegisterShift>
.Where(
TLinq.GreaterOrEqual('OpeningDate', Trunc(StartDate))
and TLinq.LessThan('OpeningDate', Trunc(FinishDate) + 1)
)
.OrderBy('OpeningDate', false)
.Open;
end;
function TPointOfSale.GetRegisterSummary(ShiftId: Integer): ICriteriaCursor;
begin
Result := Manager.Find<TRegisterShiftItem>
.CreateAlias('PaymentType', 'PaymentType')
.CreateAlias('Shift', 'Shift')
.Select(TProjections.ProjectionList
.Add(TProjections.Group('PaymentType.Name').As_('PaymentType'))
.Add(TProjections.Sum('Amount').As_('Total'))
)
.Where(TLinq.Eq('Shift.Id', ShiftId)
and TLinq.IsNotNull('PaymentType.Name'))
.OrderBy('PaymentType')
.Open;
end;
function TPointOfSale.IsRegisterOpen: boolean;
begin
Result := (ActiveShift <> nil);
end;
function TPointOfSale.Itau: TAccount;
begin
if FItau = nil then
begin
FItau := Manager.Find<TAccount>
.Where(
TLinq.Eq('AccountType', TAccountType.Bank)
and TLinq.Eq('Name', 'Itau')
)
.Take(1)
.UniqueResult;
if FItau = nil then
FItau := CreateItauAccount;
end;
Result := FItau;
end;
procedure TPointOfSale.OpenRegister(InitialValue: Currency);
var
Shift: TRegisterShift;
Entry: TRegisterShiftItem;
begin
if IsRegisterOpen then
raise Exception.Create('Caixa já aberto');
Shift := TRegisterShift.Create;
Entry := TRegisterShiftItem.Create;
try
Shift.OpeningDate := Now;
Shift.Items.Add(Entry);
Entry.Shift := Shift;
Entry.Date := Now;
Entry.ItemType := TRegisterShiftItemType.Open;
Entry.PaymentType := Manager.Find<TPaymentType>(1); // Cash REVIEW this
Entry.Amount := InitialValue;
Manager.Save(Shift);
FActiveShift := Shift;
except
Entry.Free;
Shift.Free;
raise;
end;
end;
procedure TPointOfSale.RegisterSale(Sale: TVenda);
var
M: TObjectManager;
DBTrans: IDBTransaction;
ManagedSale: TVenda;
Item: TRegisterShiftItem;
ManagedShift: TRegisterShift;
SaleItem: TItemVenda;
begin
M := dmConnection.CreateManager;
try
DBTrans := M.Connection.BeginTransaction;
try
// Save sale
// Finish Associated Appointments of Sale
ManagedSale := M.Merge<TVenda>(Sale);
for SaleItem in ManagedSale.Itens do
if (SaleItem.Appointment <> nil) then
SaleItem.Appointment.Status := TAppointmentStatus.Paid;
M.Flush;
ManagedShift := M.Find<TRegisterShift>(ActiveShift.Id);
// Register sale item
Item := TRegisterShiftItem.Create;
Item.Date := Now;
Item.ItemType := TRegisterShiftItemType.Sale;
Item.Amount := ManagedSale.ItemsTotal;
Item.Shift := ManagedShift;
Item.Sale := ManagedSale;
M.Save(Item);
// Register payment type item
Item := TRegisterShiftItem.Create;
Item.Date := Now;
Item.ItemType := TRegisterShiftItemType.Payment;
Item.Amount := ManagedSale.ItemsTotal;
Item.Shift := ManagedShift;
Item.PaymentType := ManagedSale.PaymentType;
Item.Sale := ManagedSale;
M.Save(Item);
DBTrans.Commit;
except
DBTrans.Rollback;
raise;
end;
finally
M.Free;
end;
end;
end.
|
{ Collection of routines that convert strings to floating point
* numbers. The low level routine STRING_T_FPMAX does all the actual
* conversion. The remaning routines are various convenient wrappers.
}
module string_t_fp;
define string_t_fp1;
define string_t_fp2;
define string_t_fpm;
define string_t_fpmax;
%include 'string2.ins.pas';
{
*************************
*
* Subroutine STRING_T_FP1 (S, FP, STAT)
*
* Convert string S to single precision floating point number FP.
* STAT is the completions status code.
}
procedure string_t_fp1 ( {convert string to single precision float}
in s: univ string_var_arg_t; {input string}
out fp: sys_fp1_t; {output floating point number}
out stat: sys_err_t); {completion status code}
val_param;
var
fpmax: sys_fp_max_t;
begin
string_t_fpmax ( {call low level conversion routine}
s, {input string}
fpmax, {output floating point number}
[], {additional option flags}
stat);
fp := fpmax;
end;
{
*************************
*
* Subroutine STRING_T_FP2 (S, FP, STAT)
*
* Convert string S to double precision floating point number FP.
* STAT is the completions status code.
}
procedure string_t_fp2 ( {convert string to double precision float}
in s: univ string_var_arg_t; {input string}
out fp: sys_fp2_t; {output floating point number}
out stat: sys_err_t); {completion status code}
val_param;
var
fpmax: sys_fp_max_t;
begin
string_t_fpmax ( {call low level conversion routine}
s, {input string}
fpmax, {output floating point number}
[], {additional option flags}
stat);
fp := fpmax;
end;
{
*************************
*
* Subroutine STRING_T_FPM (S, FP, STAT)
*
* Convert string S to preferred machine floating point number FP.
* STAT is the completions status code.
}
procedure string_t_fpm ( {convert string to machine floating point}
in s: univ string_var_arg_t; {input string}
out fp: real; {output floating point number}
out stat: sys_err_t); {completion status code}
val_param;
var
fpmax: sys_fp_max_t;
begin
string_t_fpmax ( {call low level conversion routine}
s, {input string}
fpmax, {output floating point number}
[], {additional option flags}
stat);
fp := fpmax;
end;
{
*************************
*
* Subroutine STRING_T_FPMAX (S, FP, FLAGS, STAT)
*
* Convert the string S to the single precision floating point number FP.
* FLAGS is a set of one-bit options flags. STAT is the returned completion
* status. The supported flags are:
*
* STRING_TFP_NULL_Z_K
*
* An empty input string has a value of 0.0. This flag is mutually
* exclusive with STRING_TFP_NULL_DEF_K. By default, an empty input
* string is a error.
*
* STRING_TFP_NULL_DEF_K
*
* An empty input string causes the existing value of FP to not be altered.
* This flag is mutually exclusive with STRING_TRP_NULL_Z_K. By default,
* an empty string is an error.
*
* STRING_TFP_GROUP_K
*
* Allow digit grouping in the input number. By default, digit grouping
* is not allowed. In most languages, digits may be grouped into
* fixed-size groups separated by the grouping character. In English,
* digits are grouped in threes separated by commas. The group size
* and group separator character is declared in the language descriptor
* file with the keywords DIGITS_GROUP_SIZE and DIGITS_GROUP_CHAR.
}
procedure string_t_fpmax ( {convert string to max size floating point}
in s: univ string_var_arg_t; {input string}
in out fp: sys_fp_max_t; {output floating point number}
in flags: string_tfp_t; {additional option flags}
out stat: sys_err_t); {completion status code}
val_param;
type
state_k_t = ( {current state in parsing input string}
state_man_bef_k, {before mantissa and its sign}
state_man_left_k, {in mantissa, left of decimal point}
state_man_right_k, {in mantissa, right of decimal point}
state_exp_bef_k, {before start of exponent value}
state_exp_k); {in exponent}
var
man: sys_fp_max_t; {unsigned mantissa value}
pwten: sys_fp_max_t; {current power of ten}
mult: sys_fp_max_t; {mult factor resulting from exponent}
lang_p: sys_lang_p_t; {pointer to info about current language}
p: sys_int_machine_t; {input string parse index}
man_exp: sys_int_machine_t; {implied exponent in mantissa value}
man_sign: sys_fp_max_t; {1.0 or -1.0 mantissa sign}
exp: sys_int_machine_t; {unsigned power of 10 exponent value}
group_n: sys_int_machine_t; {number of chars in current group}
state: state_k_t; {current input string parse state}
exp_pos: boolean; {TRUE if exponent is positive}
group_hard: boolean; {TRUE if in hard group}
group_sep: boolean; {TRUE if any group separator char found}
man_dec: boolean; {mantissa decimal point was found}
label
string_bad, found_nonblank, digit_man, next_char, loop_exp;
begin
sys_error_none (stat); {init to not error}
if {illegal combination of flags ?}
[string_tfp_null_z_k, string_tfp_null_def_k] <= flags
then begin
sys_stat_set (string_subsys_k, string_stat_tfp_bad_k, stat); {set error code}
sys_stat_parm_vstr (s, stat); {pass back string trying to convert}
return; {return with error}
end;
for p := 1 to s.len do begin {scan string looking for first non-blank}
if s.str[p] <> ' ' then goto found_nonblank;
end;
{
* The input string is either empty or all blank.
}
if string_tfp_null_def_k in flags then return; {blank means don't touch FP ?}
if string_tfp_null_z_k in flags then begin {blank means pass back zero ?}
fp := 0.0;
return;
end;
string_bad: {end up here if input string not FP number}
sys_stat_set (string_subsys_k, string_stat_bad_real_k, stat); {set error status code}
sys_stat_parm_vstr (s, stat); {pass back offending string}
return; {return with error}
{
* P is the parse index to the first non-blank character in the input string.
}
found_nonblank:
man := 0.0; {init mantissa value}
man_exp := 0; {init exponent implied in mantissa value}
man_sign := 1.0; {init mantissa sign}
exp := 0; {init exponent value}
exp_pos := true; {init exponent sign}
group_n := 0; {init number characters in current group}
group_hard := false; {init to no hard groups found}
group_sep := false; {init to no group separator chars found}
man_dec := false; {init to no mantissa decimal point was found}
state := state_man_bef_k; {init input string parsing state}
sys_langp_curr_get (lang_p); {get pointer to current language info}
repeat {loop back here for each new input character}
case s.str[p] of {what kind of character is it ?}
{
* This input string character is a minus sign.
}
'-': begin {minus sign}
case state of
state_man_bef_k: begin {minus sign before mantissa}
state := state_man_left_k; {now definately in the mantissa}
man_sign := -1.0; {indicate mantissa is negative}
end;
state_man_left_k,
state_man_right_k, {minus sign while in mantissa}
state_exp_bef_k: begin {minus sign just before exponent}
state := state_exp_k; {now definately in exponent}
exp_pos := false; {indicate exponent is negative}
end;
otherwise
goto string_bad;
end;
end; {done with minus sign}
{
* This input string character is a plus sign.
}
'+': begin {plus sign}
case state of
state_man_bef_k: begin {plus sign before mantissa}
state := state_man_left_k; {now definately in the mantissa}
end;
state_man_left_k,
state_man_right_k, {plus sign while in mantissa}
state_exp_bef_k: begin {plus sign just before exponent}
state := state_exp_k; {now definately in the exponent}
end;
otherwise
goto string_bad;
end;
end; {done with plus sign}
{
* This input string character is a digit.
}
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9': begin {0-9 digit}
case state of
state_man_bef_k,
state_man_left_k: begin {this is next digit left of point in mantissa}
state := state_man_left_k; {now definately in the mantissa}
digit_man: {jump here for common mantissa digit code}
man := (man * 10.0) + {add in this digit}
(ord(s.str[p]) - ord('0'));
group_n := group_n + 1; {one more character in this group}
end;
state_man_right_k: begin {this is next digit right of pnt in mantissa}
man_exp := man_exp - 1; {update exponent to correct mantissa value}
goto digit_man; {to common code to process mantissa digit}
end;
state_exp_bef_k,
state_exp_k: begin {this is next digit in exponent}
state := state_exp_k; {now definately inside the exponent}
exp := (exp * 10) + {add in this digit to exponent value}
(ord(s.str[p]) - ord('0'));
end;
otherwise
goto string_bad;
end;
end; {done with digit}
{
* This input string character signifies the start of the exponent.
}
'E', 'e', 'D', 'd': begin
case state of
state_man_left_k,
state_man_right_k: begin {currently parsing the mantissa}
state := state_exp_bef_k; {we are now just before the mantissa}
end;
otherwise
goto string_bad;
end;
end;
{
* This input string character is a space. This is only allowed at the end
* of the number. The whole rest of the input string must be spaces.
}
' ': begin
p := p + 1; {advance to next input string character}
while p <= s.len do begin {scan reset of input string}
if s.str[p] <> ' ' then goto string_bad; {found other than a space ?}
p := p + 1; {advance to next input string character}
end;
end;
{
* The input string character is not one of the hard-wired special characters
* we recognize. Now check for the the "soft" special characters. These
* are a function of the current language.
}
otherwise
{
* Check for the decimal "point" character.
}
if s.str[p] = lang_p^.decimal then begin {this is decimal "point" character ?}
case state of
state_man_bef_k,
state_man_left_k: begin {we are parsing left side of mantissa}
state := state_man_right_k; {now definately in right side of mantissa}
if
group_sep and {group separator characters were used ?}
(group_n <> lang_p^.digits_group_n) {current group not the right size ?}
then goto string_bad; {this is a syntax error}
group_n := 0; {decimal point starts a new group}
group_hard := true; {the new group definately start here}
group_sep := false; {init to no separator characters found}
man_dec := true; {remember mantissa decimal point was found}
end;
otherwise
goto string_bad;
end;
goto next_char;
end;
{
* Check for the group separator character ("," in English).
}
if s.str[p] = lang_p^.digits_group_c then begin {group separator character ?}
if not (string_tfp_group_k in flags) {separator characters not allowed ?}
then goto string_bad; {this is a syntax error}
case state of
state_man_left_k,
state_man_right_k: begin {only allowed in the mantissa}
if group_n > lang_p^.digits_group_n {current group too big ?}
then goto string_bad;
if
group_hard and {this group has a hard size ?}
(group_n <> lang_p^.digits_group_n) {current group not right size ?}
then goto string_bad;
group_n := 0; {start a new group}
group_hard := true;
group_sep := true; {a separator char was definately used}
end;
otherwise
goto string_bad;
end;
goto next_char;
end;
{
* Unexpected input string character.
}
goto string_bad;
end; {end of input string character cases}
next_char: {jump here to advance to next input char}
p := p + 1; {advance parse index to next character}
until p > s.len; {back to process next input string character}
{
* The end of the input string has been reached.
* Now check the last mantissa group for validity. The relevant variables are:
*
* GROUP_N - number of digits in the last group.
* LANG_P^.DIGITS_GROUP_N - Number of digits required in a whole group.
* GROUP_SEP - TRUE if a group separator character was found.
* MAN_DEC - TRUE if last group is to right of decimal point.
}
if group_sep then begin {group separator characters were used ?}
if man_dec
then begin {mantissa ended right of decimal point}
if (group_n < 1) or (group_n > lang_p^.digits_group_n) {bad size group ?}
then goto string_bad;
end
else begin {mantissa was a whole number without dec pnt}
if group_n <> lang_p^.digits_group_n {group not correct size ?}
then goto string_bad;
end
;
end; {done checking for correct digit grouping}
{
* Done dealing with input string syntax issues. Now compute the final
* floating point value from the individual pieces. The variable which
* hold the values resulting from parsing the input string are:
*
* MAN
*
* Unsigned mantissa raw value. This contains the value as if the
* decimal point was at the end of the mantissa, not where it really
* appreared.
*
* MAN_EXP
*
* The mantissa implied "exponent" value. This contains the power of 10
* exponent that when applied to MAN would result in the true mantissa
* magnitude. This is also -1 times the number of digits found to the
* right of the decimal point.
*
* MAN_SIGN
*
* Mantissa sign. This is either 1.0 or -1.0.
*
* EXP
*
* Unsigned exponent magnitude.
*
* EXP_POS
*
* Indicates exponent sign. Is TRUE if exponent is positive, FALSE
* if negative.
}
if exp_pos
then begin {exponent value is EXP}
exp := exp + man_exp; {add in correction for decimal point}
if exp < 0 then begin {this changes sign of effective exponent ?}
exp := -exp; {restore EXP to exponent magnitude}
exp_pos := false; {indicate exponent is -EXP}
end;
end
else begin {exponent value is -EXP}
exp := exp - man_exp; {add in correction for decimal point}
end
;
{
* EXP and EXP_POS have been updated to take into account the placement of the
* decimal point within the mantissa.
}
pwten := 10.0; {init power of ten for first EXP bit}
mult := 1.0; {init mult factor resulting from EXP}
loop_exp: {back here until all EXP bits used}
if (exp & 1) <> 0 then begin {current bit is set ?}
mult := mult * pwten; {accumulate this power of ten}
end;
exp := rshft(exp, 1); {shift next bit into position}
if exp <> 0 then begin {still some bits left ?}
pwten := sqr(pwten); {make power of ten for next bit}
if {prevent underflow of MULT}
(not exp_pos) and
(man > 1.0) and
(mult > man)
then begin
man := man / mult; {use multiplier accumulated so far}
mult := 1.0; {reset multiplier to empty}
end;
goto loop_exp; {back to process next EXP bit}
end;
{
* The multiplier factor represented by the exponent magnitude is in MULT.
* Now apply this factor, taking the signs into account, to obtain the
* final floating point value.
}
if exp_pos
then begin {exponent value is positive}
fp := man_sign * man * mult;
end
else begin {exponent value is negative}
fp := man_sign * man / mult;
end
;
end;
|
unit UFrmCadastroEquipamento;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCRUD, ExtCtrls, Menus, Buttons, StdCtrls
, UUtilitarios
, UEquipamento
, URegraCRUDEquipamento
;
type
TFrmCadastroEquipamento = class(TFrmCRUD)
gbInformacoes: TGroupBox;
edMarca: TLabeledEdit;
edN_Serie: TLabeledEdit;
edNome: TLabeledEdit;
protected
FEQUIPAMENTO: TEQUIPAMENTO;
FRegraCRUDEquipamento: TRegraCRUDEquipamento;
procedure Inicializa; override;
procedure Finaliza; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
end;
var
FrmCadastroEquipamento: TFrmCadastroEquipamento;
implementation
{$R *.dfm}
uses
UOpcaoPesquisa
;
{ TFrmCadastroEquipamento }
procedure TFrmCadastroEquipamento.Finaliza;
begin
inherited;
FreeAndNil(FRegraCRUDEquipamento);
end;
procedure TFrmCadastroEquipamento.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
gbInformacoes.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao];
end;
procedure TFrmCadastroEquipamento.Inicializa;
begin
inherited;
DefineEntidade(@FEQUIPAMENTO, TEQUIPAMENTO);
DefineRegraCRUD(@FRegraCRUDEquipamento, TRegraCRUDEquipamento);
AdicionaOpcaoPesquisa(TOpcaoPesquisa.Create
.DefineVisao(VW_EQUIPAMENTO)
.DefineNomeCampoRetorno(VW_EQUIPAMENTO_ID)
.AdicionaFiltro(VW_EQUIPAMENTO_NOME)
.DefineNomePesquisa('Pesquisa de Equipamentos'));
end;
procedure TFrmCadastroEquipamento.PosicionaCursorPrimeiroCampo;
begin
inherited;
edNome.SetFocus;
end;
procedure TFrmCadastroEquipamento.PreencheEntidade;
begin
inherited;
FEQUIPAMENTO.NOME := edNome.Text;
FEQUIPAMENTO.MARCA := edMarca.Text;
FEQUIPAMENTO.N_SERIE := edN_Serie.Text;
end;
procedure TFrmCadastroEquipamento.PreencheFormulario;
begin
inherited;
edNome.Text := FEQUIPAMENTO.NOME;
edMarca.Text := FEQUIPAMENTO.MARCA;
edN_Serie.Text := FEQUIPAMENTO.N_SERIE;
end;
end.
|
{: GLNavigator<p>
Unit for navigating TGLBaseObjects.<p>
<b>Historique : </b><font size=-1><ul>
<li>09/11/00 - JAJ - First submitted. Base Class TGLNavigator included.
</ul></font>
}
unit GLNavigator;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Geometry, GLScene, GLMisc;
type
// TGLNavigator
//
{: TGLNavigator is the component for moving a TGLBaseSceneObject, and all Classes based on it,
this includes all the objects from the Scene Editor.<p>
The three calls to get you started is
<ul>
<li>TurnHorisontal : it turns left and right.
<li>TurnVertical : it turns up and down.
<li>MoveForward : moves back and forth.
</ul>
The three properties to get you started is
<ul>
<li>MovingObject : The Object that you are moving.
<li>UseVirtualUp : When UseVirtualUp is set you navigate Quake style. If it isn't
it's more like Descent.
<li>AngleLock : Allows you to block the Vertical angles. Should only be used in
conjunction with UseVirtualUp.
</ul>
}
TGLNavigator = class(TComponent)
private
FObject : TGLBaseSceneObject;
FVirtualRight : TVector;
FVirtualUp : TGLCoordinates;
FUseVirtualUp : Boolean;
FAutoUpdateObject : Boolean;
FMaxAngle : Single;
FMinAngle : Single;
FCurrentAngle : Single;
FAngleLock : Boolean;
public
Constructor Create(AOwner : TComponent); override;
Destructor Destroy; override;
Procedure SetObject(NewObject : TGLBaseSceneObject);
Procedure SetUseVirtualUp(UseIt : Boolean);
Procedure SetVirtualUp(Up : TGLCoordinates);
Function CalcRight : TVector;
protected
public
Procedure TurnHorizontal(Angle : Single);
Procedure TurnVertical(Angle : Single);
Procedure MoveForward(Distance : Single);
Procedure StrafeHorizontal(Distance : Single);
Procedure StrafeVertical(Distance : Single);
Procedure Straighten;
published
property VirtualUp : TGLCoordinates read FVirtualUp write SetVirtualUp;
property MovingObject : TGLBaseSceneObject read FObject write SetObject;
property UseVirtualUp : Boolean read FUseVirtualUp write SetUseVirtualUp;
property AutoUpdateObject : Boolean read FAutoUpdateObject write FAutoUpdateObject;
property MaxAngle : Single read FMaxAngle write FMaxAngle;
property MinAngle : Single read FMinAngle write FMinAngle;
property AngleLock : Boolean read FAngleLock write FAngleLock;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('GLScene', [TGLNavigator]);
end;
Constructor TGLNavigator.Create(AOwner : TComponent);
Begin
inherited;
FVirtualUp := TGLCoordinates.Create(Self);
FCurrentAngle := 0;
End;
Destructor TGLNavigator.Destroy;
Begin
FVirtualUp.Free;
inherited;
End;
Procedure TGLNavigator.SetObject(NewObject : TGLBaseSceneObject);
Begin
FObject := NewObject;
If not Assigned(FObject) then Exit;
if csdesigning in componentstate then
Begin
If VectorLength(FVirtualUp.AsVector) = 0 then
Begin
FVirtualUp.AsVector := FObject.Up.AsVector;
End;
Exit;
End;
If FUseVirtualUp Then FVirtualRight := CalcRight;
End;
Function TGLNavigator.CalcRight : TVector;
Begin
If Assigned(FObject) then
If FUseVirtualUp Then
Begin
VectorCrossProduct(FObject.Direction.AsVector, FVirtualUp.AsVector, Result);
ScaleVector(Result,1/VectorLength(Result));
End else VectorCrossProduct(FObject.Direction.AsVector, FObject.Up.AsVector, Result); { automaticly length(1), if not this is a bug }
End;
Procedure TGLNavigator.TurnHorizontal(Angle : Single);
Var
T : TVector;
U : TAffineVector;
Begin
Angle := DegToRad(Angle); {make it ready for Cos and Sin }
If FUseVirtualUp Then
Begin
SetVector(U, VirtualUp.AsVector);
T := FObject.Up.AsVector;
RotateVector(T,U,Angle);
FObject.Up.AsVector := T;
T := FObject.Direction.AsVector;
RotateVector(T,U,Angle);
FObject.Direction.AsVector := T;
End else FObject.Direction.AsVector := VectorCombine(FObject.Direction.AsVector,CalcRight,Cos(Angle),Sin(Angle));
End;
Procedure TGLNavigator.TurnVertical(Angle : Single);
Var
CosAngle, SinAngle : Single;
Direction : TVector;
Begin
If FAngleLock then
Begin
CosAngle := FCurrentAngle+Angle; {used as a temp angle, to save stack}
If CosAngle > FMaxAngle then
Begin
If FCurrentAngle = FMaxAngle then Exit;
CosAngle := FMaxAngle;
End else
Begin
If CosAngle < FMinAngle then
Begin
If FCurrentAngle = FMinAngle then Exit;
CosAngle := FMinAngle;
End;
End;
End;
FCurrentAngle := CosAngle; {CosAngle temp, use stopped}
Angle := DegToRad(Angle); {make it ready for Cos and Sin }
SinCos(Angle,SinAngle,CosAngle);
Direction := VectorCombine(FObject.Direction.AsVector,FObject.Up.AsVector,CosAngle,SinAngle);
FObject.Up.AsVector := VectorCombine(FObject.Direction.AsVector,FObject.Up.AsVector,SinAngle,CosAngle);
FObject.Direction.AsVector := Direction;
End;
Procedure TGLNavigator.MoveForward(Distance : Single);
Begin
If FUseVirtualUp Then
Begin
FObject.Position.AsVector := VectorCombine(FObject.Position.AsVector,VectorCrossProduct(FVirtualUp.AsVector,CalcRight),1,Distance);
End else FObject.Position.AsVector := VectorCombine(FObject.Position.AsVector,FObject.Direction.AsVector,1,Distance);
End;
Procedure TGLNavigator.StrafeHorizontal(Distance : Single);
Begin
FObject.Position.AsVector := VectorCombine(FObject.Position.AsVector,CalcRight,1,Distance);
End;
Procedure TGLNavigator.StrafeVertical(Distance : Single);
Begin
If UseVirtualUp Then
Begin
FObject.Position.AsVector := VectorCombine(FObject.Position.AsVector,FVirtualUp.AsVector,1,Distance);
End else FObject.Position.AsVector := VectorCombine(FObject.Position.AsVector,FObject.Up.AsVector,1,Distance);
End;
Procedure TGLNavigator.Straighten;
Var
R : TVector;
D : TVector;
A : Single;
Begin
FCurrentAngle := 0;
R := CalcRight;
A := VectorAngle(AffineVectorMake(MovingObject.Up.AsVector), AffineVectorMake(VirtualUp.AsVector));
MovingObject.Up.AsVector := VirtualUp.AsVector;
VectorCrossProduct(R, FVirtualUp.AsVector, D);
If A >= 0 then
ScaleVector(D,-1/VectorLength(D))
else
ScaleVector(D,1/VectorLength(D));
MovingObject.Direction.AsVector := D;
End;
Procedure TGLNavigator.SetUseVirtualUp(UseIt : Boolean);
Begin
FUseVirtualUp := UseIt;
if csdesigning in componentstate then Exit;
If FUseVirtualUp then FVirtualRight := CalcRight;
End;
Procedure TGLNavigator.SetVirtualUp(Up : TGLCoordinates);
Begin
FVirtualUp.Assign(Up);
if csdesigning in componentstate then Exit;
If FUseVirtualUp then FVirtualRight := CalcRight;
End;
end.
|
{
NAME: Harold Toomey
TASK: Hello World
LANG: PASCAL
}
Program HelloWorld;
Begin
Writeln('Hello, World!');
End.
|
// Copyright © 2005-2009 DunconGames. All rights reserved. BSD License. Authors: simsmen
unit dgStrings;
{$DEFINE dgAssert}
{$DEFINE dgTrace}
interface
uses
dgHeader;
type
TdgConcretStrings = class(TdgStrings)
constructor Create;
destructor Destroy; override;
private
fStrings: array[0..100] of string;
fCount: integer;
fIterator: integer;
public
function GetCount: integer; override;
procedure SetCount(const aValue: integer); override;
procedure Add(const aValue: TdgName); override;
procedure StayBeforeFirst; override;
function StayOnNext: boolean; override;
function GetString: TdgName; override;
end;
implementation
uses
dgTraceCore;
const
cnstUnitName = 'dgSpecialObjects';
constructor TdgConcretStrings.Create;
begin
inherited Create;
fCount := 50;
fIterator := -1;
end;
destructor TdgConcretStrings.Destroy;
begin
inherited Destroy;
end;
function TdgConcretStrings.GetCount: integer;
begin
result := fCount;
end;
procedure TdgConcretStrings.SetCount(const aValue: integer);
begin
{$IFDEF dgAssert}
dgTrace.Assert((aValue > 0) and (aValue <= 100), '{1E087124-DA27-4492-81F9-2B91D9AD8E7A}', cnstUnitName);
{$ENDIF}
fCount := aValue;
end;
procedure TdgConcretStrings.Add(const aValue: TdgName);
var
i: integer;
begin
for I := 0 to fCount - 2 do
fStrings[i] := fStrings[i + 1];
fStrings[fCount - 1] := aValue;
end;
procedure TdgConcretStrings.StayBeforeFirst;
begin
fIterator := -1;
end;
function TdgConcretStrings.StayOnNext: boolean;
begin
inc(fIterator);
if fIterator < fCount then
result := true
else
begin
result := false;
fIterator := -1;
end;
end;
function TdgConcretStrings.GetString: TdgName;
begin
result := fStrings[fIterator];
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP 3.0
Description: Model relacionado à tabela [COMPRA_PEDIDO_DETALHE]
The MIT License
Copyright: Copyright (C) 2021 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (alberteije@gmail.com)
@version 1.0.0
*******************************************************************************}
unit CompraPedidoDetalhe;
interface
uses
MVCFramework.Serializer.Commons, ModelBase;
type
[MVCNameCase(ncLowerCase)]
TCompraPedidoDetalhe = class(TModelBase)
private
FId: Integer;
FIdCompraPedidoCabecalho: Integer;
FIdProduto: Integer;
FQuantidade: Extended;
FValorUnitario: Extended;
FValorSubtotal: Extended;
FTaxaDesconto: Extended;
FValorDesconto: Extended;
FValorTotal: Extended;
FCst: string;
FCsosn: string;
FCfop: Integer;
public
// procedure ValidarInsercao; override;
// procedure ValidarAlteracao; override;
// procedure ValidarExclusao; override;
[MVCColumnAttribute('ID', True)]
[MVCNameAsAttribute('id')]
property Id: Integer read FId write FId;
[MVCColumnAttribute('ID_COMPRA_PEDIDO_CABECALHO')]
[MVCNameAsAttribute('idCompraPedidoCabecalho')]
property IdCompraPedidoCabecalho: Integer read FIdCompraPedidoCabecalho write FIdCompraPedidoCabecalho;
[MVCColumnAttribute('ID_PRODUTO')]
[MVCNameAsAttribute('idProduto')]
property IdProduto: Integer read FIdProduto write FIdProduto;
[MVCColumnAttribute('QUANTIDADE')]
[MVCNameAsAttribute('quantidade')]
property Quantidade: Extended read FQuantidade write FQuantidade;
[MVCColumnAttribute('VALOR_UNITARIO')]
[MVCNameAsAttribute('valorUnitario')]
property ValorUnitario: Extended read FValorUnitario write FValorUnitario;
[MVCColumnAttribute('VALOR_SUBTOTAL')]
[MVCNameAsAttribute('valorSubtotal')]
property ValorSubtotal: Extended read FValorSubtotal write FValorSubtotal;
[MVCColumnAttribute('TAXA_DESCONTO')]
[MVCNameAsAttribute('taxaDesconto')]
property TaxaDesconto: Extended read FTaxaDesconto write FTaxaDesconto;
[MVCColumnAttribute('VALOR_DESCONTO')]
[MVCNameAsAttribute('valorDesconto')]
property ValorDesconto: Extended read FValorDesconto write FValorDesconto;
[MVCColumnAttribute('VALOR_TOTAL')]
[MVCNameAsAttribute('valorTotal')]
property ValorTotal: Extended read FValorTotal write FValorTotal;
[MVCColumnAttribute('CST')]
[MVCNameAsAttribute('cst')]
property Cst: string read FCst write FCst;
[MVCColumnAttribute('CSOSN')]
[MVCNameAsAttribute('csosn')]
property Csosn: string read FCsosn write FCsosn;
[MVCColumnAttribute('CFOP')]
[MVCNameAsAttribute('cfop')]
property Cfop: Integer read FCfop write FCfop;
end;
implementation
{ TCompraPedidoDetalhe }
end. |
{-----------------------------------------------------------------------------
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/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: JvGroupBox.PAS, released on 2000-11-22.
The Initial Developer of the Original Code is Peter Below <100113 dott 1101 att compuserve dott com>
Portions created by Peter Below are Copyright (C) 2000 Peter Below.
All Rights Reserved.
Contributor(s):
Roman Ganz
Robert Marquardt
You may retrieve the latest version of this file at the Project JEDI's JVCL home page,
located at http://jvcl.delphi-jedi.org
Known Issues:
-----------------------------------------------------------------------------}
// $Id: JvGroupBox.pas 13139 2011-10-28 19:59:40Z jfudickar $
unit JvGroupBox;
{$I jvcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
SysUtils, Classes, Windows, Messages, Graphics, Controls, Forms, StdCtrls,
JvThemes, JvExControls, JvExStdCtrls, JvCheckBox, JvJCLUtils;
type
{$IFDEF RTL230_UP}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF RTL230_UP}
TJvGroupBox = class(TJvExGroupBox, IJvDenySubClassing)
private
FCheckBox: TJvCheckBox;
FOnHotKey: TNotifyEvent;
FPropagateEnable: Boolean;
FCheckable: Boolean;
FOnCheckBoxClick: TNotifyEvent;
procedure SetPropagateEnable(const Value: Boolean);
procedure SetCheckable(const Value: Boolean);
function GetCaption: TCaption;
procedure SetCaption(const Value: TCaption);
function GetChecked: Boolean;
procedure SetChecked(const Value: Boolean);
function StoredCheckable: Boolean;
procedure CheckBoxClick(Sender: TObject);
protected
function WantKey(Key: Integer; Shift: TShiftState): Boolean; override;
procedure EnabledChanged; override;
procedure DoHotKey; dynamic;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
property Canvas;
published
property HintColor;
{$IFDEF JVCLThemesEnabledD6}
property ParentBackground default True;
{$ENDIF JVCLThemesEnabledD6}
property Caption: TCaption read GetCaption write SetCaption;
property Checkable: Boolean read FCheckable write SetCheckable default False;
property Checked: Boolean read GetChecked write SetChecked stored StoredCheckable;
property PropagateEnable: Boolean read FPropagateEnable write SetPropagateEnable default False;
property OnMouseEnter;
property OnMouseLeave;
property OnParentColorChange;
property OnHotKey: TNotifyEvent read FOnHotKey write FOnHotKey;
property OnCheckBoxClick: TNotifyEvent read FOnCheckBoxClick write FOnCheckBoxClick;
end;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvGroupBox.pas $';
Revision: '$Revision: 13139 $';
Date: '$Date: 2011-10-28 21:59:40 +0200 (ven. 28 oct. 2011) $';
LogPath: 'JVCL\run'
);
{$ENDIF UNITVERSIONING}
implementation
uses
Math;
constructor TJvGroupBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPropagateEnable := False;
FCheckable := False;
ControlStyle := ControlStyle + [csAcceptsControls];
{$IFDEF JVCLThemesEnabledD6}
IncludeThemeStyle(Self, [csParentBackground]);
{$ENDIF JVCLThemesEnabledD6}
end;
procedure TJvGroupBox.Paint;
var
H: Integer;
R: TRect;
Flags: Longint;
{$IFDEF JVCLThemesEnabledD6}
Details: TThemedElementDetails;
CaptionRect: TRect;
{$ENDIF JVCLThemesEnabledD6}
LastBkMode: Integer;
begin
{$IFDEF JVCLThemesEnabled}
if ThemeServices.{$IFDEF RTL230_UP}Enabled{$ELSE}ThemesEnabled{$ENDIF RTL230_UP} then
begin
{$IFDEF COMPILER7_UP}
inherited Paint;
{$ELSE}
if Enabled then
Details := ThemeServices.GetElementDetails(tbGroupBoxNormal)
else
Details := ThemeServices.GetElementDetails(tbGroupBoxDisabled);
R := ClientRect;
Inc(R.Top, Canvas.TextHeight('0') div 2);
ThemeServices.DrawElement(Canvas.Handle, Details, R);
CaptionRect := Rect(8, 0, Min(Canvas.TextWidth(Caption) + 8, ClientWidth - 8),
Canvas.TextHeight(Caption));
Canvas.Brush.Color := Self.Color;
DrawThemedBackground(Self, Canvas, CaptionRect);
ThemeServices.DrawText(Canvas.Handle, Details, Caption, CaptionRect, DT_LEFT, 0);
{$ENDIF COMPILER7_UP}
Exit;
end;
{$ENDIF JVCLThemesEnabled}
with Canvas do
begin
LastBkMode := GetBkMode(Handle);
try
Font := Self.Font;
H := TextHeight('0');
R := Rect(0, H div 2 - 1, Width, Height);
if Ctl3D then
begin
Inc(R.Left);
Inc(R.Top);
Brush.Color := clBtnHighlight;
FrameRect( R);
OffsetRect(R, -1, -1);
Brush.Color := clBtnShadow;
end
else
Brush.Color := clWindowFrame;
FrameRect( R);
if Text <> '' then
begin
if not UseRightToLeftAlignment then
R := Rect(8, 0, 0, H)
else
R := Rect(R.Right - Canvas.TextWidth(Text) - 8, 0, 0, H);
Flags := DrawTextBiDiModeFlags(DT_SINGLELINE);
// calculate text rect
SetBkMode(Handle, OPAQUE);
DrawText(Handle, Text, Length(Text), R, Flags or DT_CALCRECT);
Brush.Color := Color;
if not Enabled then
begin
OffsetRect(R, 1, 1);
Font.Color := clBtnHighlight;
DrawText(Canvas, Text, Length(Text), R, Flags);
OffsetRect(R, -1, -1);
Font.Color := clBtnShadow;
SetBkMode(Handle, TRANSPARENT);
DrawText(Canvas, Text, Length(Text), R, Flags);
end
else
DrawText(Canvas, Text, Length(Text), R, Flags);
end;
finally
SetBkMode(Handle, LastBkMode);
end;
end;
end;
function TJvGroupBox.WantKey(Key: Integer; Shift: TShiftState): Boolean;
begin
Result := inherited WantKey(Key, Shift);
if Result then
DoHotKey;
end;
procedure TJvGroupBox.EnabledChanged;
var
I: Integer;
begin
inherited EnabledChanged;
if PropagateEnable then
for I := 0 to ControlCount - 1 do
if Checkable then
if Enabled then
if Controls[I] = FCheckBox then
Controls[I].Enabled := True
else
Controls[I].Enabled := Checked
else
Controls[I].Enabled := False
else
Controls[I].Enabled := Enabled;
Invalidate;
end;
procedure TJvGroupBox.DoHotKey;
begin
if Assigned(FOnHotKey) then
FOnHotKey(Self);
end;
function TJvGroupBox.GetCaption: TCaption;
begin
if FCheckable then
Result := FCheckBox.Caption
else
Result := inherited Caption;
end;
function TJvGroupBox.GetChecked: Boolean;
begin
if FCheckable then
Result := FCheckBox.Checked
else
Result := False;
end;
procedure TJvGroupBox.SetCaption(const Value: TCaption);
begin
if FCheckable then
FCheckBox.Caption := Value
else
inherited Caption := Value;
end;
procedure TJvGroupBox.SetCheckable(const Value: Boolean);
begin
if FCheckable <> Value then
begin
if Value then
begin
FCheckBox := TJvCheckBox.Create(Self);
FCheckBox.Parent := Self;
FCheckBox.Top := 0;
FCheckBox.Left := 8;
FCheckBox.Caption := Caption;
PropagateEnable := True;
FCheckBox.OnClick := CheckBoxClick;
FCheckBox.Checked := True;
inherited Caption := '';
end
else
begin
inherited Caption := FCheckBox.Caption;
FreeAndNil(FCheckBox);
end;
FCheckable := Value;
end;
end;
procedure TJvGroupBox.SetChecked(const Value: Boolean);
begin
if Checkable then
FCheckBox.Checked := Value;
end;
procedure TJvGroupBox.CheckBoxClick(Sender: TObject);
var
I: Integer;
begin
for I := 0 to ControlCount - 1 do
if Controls[I] <> FCheckBox then
Controls[I].Enabled := FCheckBox.Checked;
if Assigned(FOnCheckBoxClick) then
FOnCheckBoxClick(Self);
end;
procedure TJvGroupBox.SetPropagateEnable(const Value: Boolean);
var
I: Integer;
begin
FPropagateEnable := Value;
for I := 0 to ControlCount - 1 do
Controls[I].Enabled := Enabled;
end;
function TJvGroupBox.StoredCheckable: Boolean;
begin
{ Write "False" to the DFM file because the checkbox is initialized with "True" }
Result := FCheckable and not Checked;
end;
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
unit LoggerEx;
interface
uses System.Classes, LoggerInterface;
type
ILoggerEx = interface(ILogger)
['{8AAC303A-CCC9-4FD3-AE87-D098F18C0719}']
procedure FindOldFiles(AFiles : TStringList);stdcall;
procedure DeleteOldFiles; stdcall;
function FileName : string; stdcall;
function ArchivePath : string; stdcall;
end;
implementation
end.
|
unit
Log;
// 提供日志记录 功能
interface
uses
Windows;
type
HLOGFILE = pointer;
// 设置日志文件名,不包括路径 默认为"log.txt" 全局日志均写入到{app}\log目录
// bUseHDInfo - 是否包含硬件信息
// bClearLog - 是否清空旧信息
// WSLogInit是必须调用的
//void __stdcall WSLogInit(const wchar_t* pFileName, BOOL bUseHDInfo = TRUE, BOOL bClearLog = FALSE, DWORD dwReserved = 0);
procedure WSLogInit(const pFileName: PWideChar; bUseHDInfo : BOOL = TRUE; bClearLog : BOOL = FALSE; dwReserved : DWORD = 0); stdcall;
//void __stdcall WSLogUninit();
procedure WSLogUninit(); stdcall;
// 功能: 记录软件日志
// 返回: 无返回值
//void WSLog(const wchar_t* pText);
procedure WSLog(const pText: PWideChar); stdcall;
//void __stdcall WSOutput(const wchar_t* lpszFormat); // 输出调试信息 使用XTraceMonitor.exe查看
procedure WSOutput(const lpszFormat: PWideChar); stdcall;
//void __stdcall WSOutputEx(COLORREF crText, const wchar_t* lpszFormat); // 输出调试信息 crText为文本颜色
procedure WSOutputEx(crText : COLORREF; const lpszFormat: PWideChar); stdcall;
//void __stdcall WSOutputImg(LPBITMAPINFO lpbi, LPVOID lpBits); //输出图像
procedure WSOutputImg(lpbi: PBitmapInfo; lpBits: Pointer); stdcall;
//创建Log文件 pFileName为创建位置 bUseHDInfo为是否需要包含硬件信息 bClearLog是否要清空原来的Log文件 dwReserve为保留字
//HLOGFILE __stdcall LogFileCreate(const wchar_t* pFileName, BOOL bUseHDInfo, BOOL bClearLog, DWORD dwReserve);
function LogFileCreate(const pFileName : PWideChar; bUseHDInfo : BOOL; bClearLog : BOOL; dwReserve : DWORD) : HLOGFILE; stdcall;
//void __stdcall LogFileDestroy(HLOG hLog);//销毁Log文件
procedure LogFileDestroy(hLog : HLOGFILE); stdcall;
//void __stdcall LogFileLog(HLOG hLog, const wchar_t* pText);//写日志文件
procedure LogFileLog(hLog : HLOGFILE; const pText : PWideChar); stdcall;
//const wchar_t* __stdcall ReadLogFileBuffer(const wchar_t* pFileName); //读取文件,返回字符串指针
function ReadLogFileBuffer(const pFileName: PWideChar): PWideChar; stdcall;
//void __stdcall ReleaseLogFileBuffer(const wchar_t* pLogBuffer);//释放所返回字符串指针
procedure ReleaseLogFileBuffer(const pLogBuffer: PWideChar); stdcall;
implementation
const
DLLNAME = 'WS_Log.dll';
procedure WSLogInit ; external DLLNAME Name 'WSLogInit';
procedure WSLogUninit ; external DLLNAME Name 'WSLogUninit';
procedure WSLog ; external DLLNAME Name 'WSLog';
procedure WSOutput ; external DLLNAME Name 'WSOutput';
procedure WSOutputEx ; external DLLNAME Name 'WSOutputEx';
procedure WSOutputImg ; external DLLNAME Name 'WSOutputImg';
function LogFileCreate ; external DLLNAME Name 'LogFileCreate';
procedure LogFileDestroy ; external DLLNAME Name 'LogFileDestroy';
procedure LogFileLog ; external DLLNAME Name 'LogFileLog';
function ReadLogFileBuffer ; external DLLNAME Name 'ReadLogFileBuffer';
procedure ReleaseLogFileBuffer ; external DLLNAME Name 'ReleaseLogFileBuffer';
end. |
{
ID: a_zaky01
PROG: planting
LANG: PASCAL
}
type
rectangle=record
llx,lly,urx,ury:int64;
col:integer;
end;
var
n,i:integer;
ans:int64;
rect:array[0..1111] of rectangle;
area:array[0..1111] of int64;
procedure calc(rect0:rectangle; cover:integer);
var
temp:rectangle;
begin
while (cover<=n) and ((rect0.llx>=rect[cover].urx)
or (rect0.urx<=rect[cover].llx)
or (rect0.lly>=rect[cover].ury)
or (rect0.ury<=rect[cover].lly)) do inc(cover);
if cover>n then inc(area[rect0.col],(rect0.urx-rect0.llx)*(rect0.ury-rect0.lly))
else
begin
if rect0.ury>rect[cover].ury then
begin
temp:=rect0;
temp.lly:=rect[cover].ury;
rect0.ury:=temp.lly;
calc(temp,cover+1);
end;
if rect0.lly<rect[cover].lly then
begin
temp:=rect0;
temp.ury:=rect[cover].lly;
rect0.lly:=temp.ury;
calc(temp,cover+1);
end;
if rect0.urx>rect[cover].urx then
begin
temp:=rect0;
temp.llx:=rect[cover].urx;
calc(temp,cover+1);
end;
if rect0.llx<rect[cover].llx then
begin
temp:=rect0;
temp.urx:=rect[cover].llx;
calc(temp,cover+1);
end;
end;
end;
begin
assign(input,'planting.in'); reset(input);
assign(output,'planting.out'); rewrite(output);
readln(n);
for i:=1 to n do
with rect[i] do
readln(llx,ury,urx,lly);
for i:=1 to n do rect[i].col:=i;
for i:=1 to n do calc(rect[i],i+1);
ans:=0;
for i:=1 to n do ans:=ans+area[i];
writeln(ans);
close(input); close(output);
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Unit que controla o estoque (incremento e decremento)
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (T2Ti.COM)
@version 2.0
******************************************************************************* }
unit ControleEstoqueController;
interface
uses
Classes, SQLExpr, SysUtils, Generics.Collections, Controller, DBXJSON, DBXCommon,
IWSystem;
type
TControleEstoqueController = class(TController)
protected
public
class function AtualizarEstoque(pQuantidade: Extended; pIdProduto: Integer; pIdEmpresa: Integer = 0; pTipoAtualizacaoEstoque: String = ''): Boolean;
end;
implementation
uses
T2TiORM;
class function TControleEstoqueController.AtualizarEstoque(pQuantidade: Extended; pIdProduto: Integer; pIdEmpresa: Integer; pTipoAtualizacaoEstoque: String): Boolean;
var
ComandoSQL: String;
begin
try
if (pTipoAtualizacaoEstoque <> '') and (pTipoAtualizacaoEstoque <> 'D') then
begin
//atualiza tabela PRODUTO
ComandoSQL :=
'update PRODUTO ' +
'set QUANTIDADE_ESTOQUE = ' +
'case ' +
'when QUANTIDADE_ESTOQUE is null then ' + FloatToStr(pQuantidade) + ' ' +
'when QUANTIDADE_ESTOQUE is not null then QUANTIDADE_ESTOQUE + ' + FloatToStr(pQuantidade) + ' ' +
'end ' +
'where ID= ' + IntToStr(pIdProduto);
end
else if pTipoAtualizacaoEstoque = 'D' then
begin
//atualiza tabela EMPRESA_PRODUTO
ComandoSQL :=
'update EMPRESA_PRODUTO ' +
'set QUANTIDADE_ESTOQUE = ' +
'case ' +
'when QUANTIDADE_ESTOQUE is null then ' + FloatToStr(pQuantidade) + ' ' +
'when QUANTIDADE_ESTOQUE is not null then QUANTIDADE_ESTOQUE + ' + FloatToStr(pQuantidade) + ' ' +
'end ' +
'where ID_PRODUTO= ' + IntToStr(pIdProduto) + ' and ID_EMPRESA= ' + IntToStr(pIdEmpresa);
end;
Result := TT2TiORM.ComandoSQL(ComandoSQL);
finally
end;
end;
end.
|
unit AlfaPetServerUnit;
interface
uses
System.SysUtils,
Sparkle.HttpSys.Server,
Sparkle.HttpServer.Context,
Sparkle.HttpServer.Module;
procedure StartAlfaPetServer;
procedure StopAlfaPetServer;
implementation
uses
RemoteDB.Drivers.Base, RemoteDB.Drivers.Interfaces,
RemoteDB.Server.Module,
RemoteDB.Drivers.FireDac,
dConnection,
System.IOUtils;
var
AlfaPetServer: THttpSysServer;
procedure StartAlfaPetServer;
var
DB: TRemoteDBModule;
begin
if AlfaPetServer <> nil then Exit;
AlfaPetServer := THttpSysServer.Create;
DB := TRemoteDBModule.Create(
// 'http://+:80/tms/alfapet/db',
TFile.ReadAllText(TPath.ChangeExtension(ParamStr(0), '.urlconfig.txt')),
TDBConnectionFactory.Create(
function: IDBConnection
var
DM: TdmConnection;
begin
DM := TdmConnection.Create(nil);
Result := TFireDacConnectionAdapter.Create(DM.FDConnection1, DM);
end
));
DB.UserName := TFile.ReadAllText(TPath.ChangeExtension(ParamStr(0), '.username.txt'));
DB.Password := TFile.ReadAllText(TPath.ChangeExtension(ParamStr(0), '.password.txt'));
AlfaPetServer.AddModule(DB);
AlfaPetServer.Start;
end;
procedure StopAlfaPetServer;
begin
FreeAndNil(AlfaPetServer);
end;
initialization
AlfaPetServer := nil;
finalization
StopAlfaPetServer;
end.
|
unit PasswordForm;
interface
uses
Classes, Forms,
StdCtrls,Graphics, Controls, ExtCtrls, Variants, ActnList, SysUtils,
ComCtrls, Windows;
type
TfrmPassword = class(TForm)
edtUserName: TEdit;
lblUserName: TLabel;
lblPassword: TLabel;
btnOk: TButton;
btnCancel: TButton;
imgPassportIcon: TImage;
lblTitle: TLabel;
edtPassword: TEdit;
btnChangePassword: TButton;
actnList: TActionList;
actnEnter: TAction;
actnExit: TAction;
anmWait: TAnimate;
sbr: TStatusBar;
procedure edtUserNameKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtPasswordKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure actnEnterExecute(Sender: TObject);
procedure actnExitExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure edtPasswordKeyPress(Sender: TObject; var Key: Char);
procedure actnEnterUpdate(Sender: TObject);
procedure actnExitUpdate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FError: boolean;
FUserName: string;
FPwd: string;
FFinished: boolean;
FStatus: string;
function GetStatus: string;
procedure SetStatus(const Value: string);
public
property UserName: string read FUserName;
property Pwd: string read FPwd;
property Finished: boolean read FFinished;
property Status: string read GetStatus write SetStatus;
end;
var
frmPassword: TfrmPassword;
implementation
uses Facade, BaseFacades, PersistentObjects;
{$R *.DFM}
procedure TfrmPassword.edtUserNameKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = 40 then edtPassword.SetFocus();
end;
procedure TfrmPassword.edtPasswordKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = 38 then edtUserName.SetFocus();
end;
procedure TfrmPassword.actnEnterExecute(Sender: TObject);
begin
FFinished := false;
anmWait.Visible := true;
anmWait.Active := true;
anmWait.Update;
Status := 'Идет проверка...';
FUserName := edtUserName.Text;
FPwd := edtPassword.Text;
FFinished := True;
ModalResult := mrOk;
end;
procedure TfrmPassword.actnExitExecute(Sender: TObject);
begin
TMainFacade.GetInstance.DBGates.UninitializeServer;
Close;
FError := false;
end;
procedure TfrmPassword.FormCreate(Sender: TObject);
begin
imgPassportIcon.Picture.Icon:= Application.Icon;
{$IFOPT D+}
edtUserName.Text := '1190';
edtPassword.Text := 'bluebluesky';
{$ENDIF}
FError := false;
end;
procedure TfrmPassword.edtPasswordKeyPress(Sender: TObject; var Key: Char);
begin
if ord(Key) = 13 then actnEnter.Execute;
end;
procedure TfrmPassword.actnEnterUpdate(Sender: TObject);
begin
actnEnter.Enabled := not TMainFacade.GetInstance.DBGates.Autorized;
end;
procedure TfrmPassword.actnExitUpdate(Sender: TObject);
begin
actnExit.Enabled := true;
end;
function TfrmPassword.GetStatus: string;
begin
result := FStatus;
end;
procedure TfrmPassword.SetStatus(const Value: string);
begin
FStatus := Value;
sbr.SimpleText := Value;
sbr.Hint := Value;
end;
procedure TfrmPassword.FormActivate(Sender: TObject);
begin
sbr.SimpleText := Status;
sbr.Repaint
end;
procedure TfrmPassword.FormShow(Sender: TObject);
begin
sbr.SimpleText := Status;
sbr.Repaint;
end;
end.
|
{$include kode.inc}
unit kode_widget_grid;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_canvas,
kode_color,
kode_flags,
kode_rect,
kode_widget;
type
KWidget_Grid = class(KWidget)
protected
FWidth : LongInt;
FHeight : LongInt;
FBackColor : KColor;
FGridColor : KColor;
public
property _width : LongInt read FWidth write FWidth;
property _height : LongInt read FHeight write FHeight;
public
constructor create(ARect:KRect; AAlignment:LongWord=kwa_none);
procedure on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0); override;
procedure on_mouseDown(AXpos,AYpos,AButton,AState:LongInt); override;
public
procedure on_clickCell(AX,AY,AB:LongInt); virtual;
procedure on_paintCell(ACanvas:KCanvas; ARect:KRect; AX,AY:LongInt); virtual;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
//kode_color,
kode_math;
//----------
constructor KWidget_Grid.create(ARect:KRect; AAlignment:LongWord=kwa_none);
begin
inherited;
FName := 'KWidget_Grid';
FWidth := 6;
FHeight := 4;
//FCursor := kmc_Finger;
FBackColor := KLightGrey;
FGridColor := KDarkGrey;
end;
//----------
procedure KWidget_Grid.on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0);
var
i,xx,yy : longint;
xcell,ycell : single;
x,y : single;
R : KRect;
begin
if (FWidth > 0) and (FHeight > 0) then
begin
xcell := ( Single(FRect.w) / Single(FWidth) );
ycell := ( Single(FRect.h) / Single(FHeight) );
// background
//ACanvas.setFillColor(FBackColor);
//ACanvas.fillRect(FRect.x,FRect.y,FRect.x2-1,FRect.y2-1);
// cells
for xx := 0 to FWidth-1 do
begin
for yy := 0 to FHeight-1 do
begin
R.setup( FRect.x+KFloor(xx*xcell), FRect.y+KFloor(yy*ycell), KFloor(xcell), KFloor(ycell) );
on_paintCell(ACanvas,R,xx,yy);
end;
end;
// grid
x := Single(FRect.x) + xcell - 1;
y := Single(FRect.y) + ycell - 1;
//aCanvas->selectPen(mGridPen);
ACanvas.setDrawColor( FGridColor );
if FWidth > 1 then
begin
for i := 0 to FWidth-2 do
begin
ACanvas.drawLine( KFloor(x), FRect.y, KFloor(x), FRect.y2 );
x += xcell;
end; //width
end;
if FHeight > 1 then
begin
for i := 0 to FHeight-2 do
begin
ACanvas.drawLine( FRect.x, KFloor(y), FRect.x2, KFloor(y) );
y += ycell;
end; //height
end;
end; // w&h > 0
//ACanvas.setDrawColor(FBorderColor);
//ACanvas.drawRect(FRect.x,FRect.y,FRect.x2{-1},FRect.y2{-1});
end;
//----------
procedure KWidget_Grid.on_mouseDown(AXpos,AYpos,AButton,AState:LongInt);
var
xcell,ycell : single;
x,y : longint;
begin
xcell := ( Single(FRect.w) / Single(FWidth) );
ycell := ( Single(FRect.h) / Single(FHeight) );
x := KFloor( Single(AXpos-FRect.x) / xcell );
y := KFloor( Single(AYpos-FRect.y) / ycell );
on_clickCell(x,y,AButton);
do_update(self);
end;
//------------------------------
//
//------------------------------
procedure KWidget_Grid.on_clickCell(AX,AY,AB:LongInt);
begin
end;
//----------
procedure KWidget_Grid.on_paintCell(ACanvas:KCanvas; ARect:KRect; AX,AY:LongInt);
begin
end;
//----------------------------------------------------------------------
end.
|
unit Aurelius.Commands.SequenceCreator;
{$I Aurelius.inc}
interface
uses
Generics.Collections,
Aurelius.Commands.AbstractCommandPerformer,
Aurelius.Sql.Metadata,
Aurelius.Sql.Commands;
type
TSequenceCreator = class(TAbstractCommandPerformer)
public
procedure CreateSequence(Database: TDatabaseMetadata);
end;
implementation
uses
Aurelius.Global.Config,
Aurelius.Mapping.Metadata,
Aurelius.Sql.Interfaces;
{ TSequenceCreator }
procedure TSequenceCreator.CreateSequence(Database: TDatabaseMetadata);
var
MappedSequence: TSequence;
Sequence: TSequenceMetadata;
begin
if not (TDBFeature.Sequences in SQLGenerator.SupportedFeatures) then
Exit;
MappedSequence := Explorer.GetSequence(Self.Clazz, False);
Sequence := TSequenceMetadata.Create(Database);
Database.Sequences.Add(Sequence);
Sequence.Name := MappedSequence.SequenceName;
Sequence.InitialValue := MappedSequence.InitialValue;
Sequence.Increment := MappedSequence.Increment;
end;
end.
|
{
CD : Christophe Dufeutrelle - 20010515 - c.dufeutrelle@system-d.fr
Pgm basé sur du code delphi de Micheal Ebner.
Ce petit programme reprend les fonctionalités de slmini
Toutes utilisations possibles.
Sans aucunes garanties de fonctionnement.
Au lieu de sélectioner les ports un par un dans une liste déroulante, je
les ai tous affichés à l'aide de 8 TSHAPES. Les boutons permettent de
passer du mode Input (Bouton au repos) au mode Output (Bouton enfoncé)
pour chaque port. En mode Output on peut passé du mode off au mode On du port
en cliquant sur le TShape concerné.
N'utilise que la VCL Standard.
Testé en DELPHI 5.
Grosses différences d'analyse par rapport à slmini.cpp :
Le tableau booleen ports_out est remplacé par la propriété down du tableau de
SpeedButton SB
Le tableau Out_mode est conservé, mais il est mis à jour par le click sur les
tshape indiquant les 8 bits des ports.
La gestion de la glissière des valeurs est négative pour avoir la valeur minimale
en bas, les valeurs sont donc -<valeur glissière>
SP : Stéphane PEREZ - 16-02-2006 - dmx@avtek.fr
adaptation pour le SUIDI 6C
}
unit UTDMX;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, AdStatLt, ComCtrls, Buttons,Math;
type
TForm1 = class(TForm)
Timer1: TTimer;
GB_Ports: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Bevel1: TBevel;
Shape0: TShape;
Bevel2: TBevel;
Shape1: TShape;
GB_DMX: TGroupBox;
DMX_V: TTrackBar;
DMX_C: TTrackBar;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
SB1: TSpeedButton;
SB2: TSpeedButton;
SB3: TSpeedButton;
SB4: TSpeedButton;
SB5: TSpeedButton;
SB6: TSpeedButton;
SB7: TSpeedButton;
SB8: TSpeedButton;
Shape2: TShape;
Shape3: TShape;
Shape4: TShape;
Shape5: TShape;
Shape6: TShape;
Shape7: TShape;
Shape8: TShape;
Shape9: TShape;
Label7: TLabel;
Label8: TLabel;
StatusBar1: TStatusBar;
btSerial: TSpeedButton;
btVersion: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Timer1Timer(Sender: TObject);
procedure DMX_CChange(Sender: TObject);
procedure DMX_VChange(Sender: TObject);
procedure DMX_display_channel;
procedure DMX_Display_ports(ports : integer);
procedure DMX_Display_Shape(ports,i : integer);
procedure ShapeMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure DMX_Set_Port;
procedure SBClick(Sender: TObject);
procedure btSerialClick(Sender: TObject);
procedure btVersionClick(Sender: TObject);
private
{ Déclarations privées }
interface_open: integer;
dmx_level: array[0..511] of char;
ShapePortColor : TColor;
SB : array[2..9] of TSpeedButton;
SH : array[0..9] of TShape;
Out_Mode : array[2..9] of boolean;
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
implementation
const
DHC_OPEN = 1;
DHC_CLOSE = 2;
DHC_DMXOUTOFF = 3;
DHC_DMXOUT = 4;
DHC_PORTREAD = 5;
DHC_PORTCONFIG = 6;
DHC_VERSION = 7;
DHC_DMXIN = 8;
DHC_INIT = 9;
DHC_EXIT = 10;
DHC_DMXSCODE = 11;
DHC_DMX2ENABLE = 12;
DHC_DMX2OUT = 13;
DHC_SERIAL = 14;
// CD stdcall plante , la pile n'est pas restaurée !!!
//function DasHardCommand(Command, Param: integer; Bloc: PChar): integer;
// stdcall; external 'dashard.dll';
// SP : Changement de la DLL .
function DasUsbCommand(Command, Param: integer; Bloc: PChar): integer;
cdecl; external 'dashard2006.dll';
{$R *.DFM}
////////////////////////////////////////////////////////////////////////////////
// CD - Initialisation
////////////////////////////////////////////////////////////////////////////////
procedure TForm1.FormCreate(Sender: TObject);
var
i,
v: integer;
begin
// SP : Modification de la commande d'ouverture de l'interface
interface_open := DasUSBCommand(DHC_INIT, 0, nil);
interface_open := DasUSBCommand(DHC_OPEN, 0, nil);
if interface_open > 0 then
v := DasUSBCommand(DHC_DMXOUTOFF, 0, nil)
else
begin
showmessage ('Erreur : Ne trouve pas l''interface "Intelligent USB DMX"');
application.terminate;
exit;
end;
for i := 0 to 511
do dmx_level[i] := Char(0);
for i := 2 to 9 do // CD - Attention démarrage à 2
Out_Mode[i] := False;
DMX_C.position := 1;
dmx_display_channel;
// CD - Pas joli, mais efficace !!!
SB[2] := SB1;
SB[3] := SB2;
SB[4] := SB3;
SB[5] := SB4;
SB[6] := SB5;
SB[7] := SB6;
SB[8] := SB7;
SB[9] := SB8;
SH[0] := Shape0; // CD - Bt Next
SH[1] := Shape1; // CD - Bt Prev
SH[2] := Shape2; // CD - Port N° 1
SH[3] := Shape3;
SH[4] := Shape4;
SH[5] := Shape5;
SH[6] := Shape6;
SH[7] := Shape7;
SH[8] := Shape8;
SH[9] := Shape9; // CD - Port N° 8
btSerial.Click;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// SP : Modification de la fermeture de l'interface .
Timer1.Enabled := false;
if interface_open > 0 then
interface_open := DasUSBCommand(DHC_CLOSE, 0, nil);
interface_open := DasUSBCommand(DHC_EXIT, 0, nil);
end;
////////////////////////////////////////////////////////////////////////////////
// CD - Gestion du timer
////////////////////////////////////////////////////////////////////////////////
procedure TForm1.Timer1Timer(Sender: TObject);
var
v, ports: integer;
begin
if interface_open > 0 then
begin
// CD - Lecteur des ports sur 10 Bits
ports := DasUSBCommand(DHC_PORTREAD, 0, nil);
DMX_Display_Ports(ports);
// CD - Envoi du block dmx_level à l'interface
v := DasUSBCommand(DHC_DMXOUT, 512, dmx_level);
if v < 0 then
begin
DasUSBCommand(DHC_CLOSE, 0, nil);
interface_open := DasUSBCommand(DHC_OPEN, 0, nil);
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// CD Affichage
////////////////////////////////////////////////////////////////////////////////
procedure TForm1.DMX_Display_Shape(ports,i : integer);
var
bit : integer;
Shape : TShape;
begin
Shape := SH[i];
{$B-}
if (i < 2) or (not SB[i].down) then // CD - Next Prev et Input
begin
bit := trunc(Intpower(2,i));
// CD - Gestion de la couleur des tshapes pour les ports input
if ((ports and bit) = 0) and (Shape.Brush.color <> ShapePortColor) then
Shape.Brush.Color := ShapePortColor;
if ((ports and bit) = bit) and (Shape.Brush.color <> clgray) then
Shape.Brush.color := clGray;
end
else // CD - mode Output
begin
if Out_Mode[i] and (Shape.Brush.color <> clLime) then
Shape.Brush.Color := clLime;
if (not Out_Mode[i]) and (Shape.Brush.color <> clgray) then
Shape.Brush.color := clGray;
end;
{$B+}
end;
procedure TForm1.DMX_Display_ports(ports : integer);
var
i : integer;
begin
GB_Ports.caption := 'Ports : ' + inttostr(Ports);
ShapePortColor := clred;
for i := 0 to 9 do
DMX_Display_Shape (ports,i);
end;
////////////////////////////////////////////////////////////////////////////////
// CD - Gestion des glissieres avec leurs libelles
////////////////////////////////////////////////////////////////////////////////
procedure TForm1.dmx_display_channel;
begin
Label3.caption := 'Channel : ' + inttostr(DMX_C.position);
DMX_V.position := -ord(dmx_level[DMX_C.position-1]);
Label5.caption := inttostr(-DMX_V.position);
end;
procedure TForm1.DMX_CChange(Sender: TObject);
begin
DMX_Display_Channel;
end;
procedure TForm1.DMX_VChange(Sender: TObject);
begin
dmx_level[DMX_C.position-1] := chr(-DMX_V.position);
DMX_Display_Channel;
end;
////////////////////////////////////////////////////////////////////////////////
// CD - Gestion des ports en output
////////////////////////////////////////////////////////////////////////////////
procedure TForm1.ShapeMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
i : integer;
Sh : TShape;
begin
Sh := TShape(sender);
i := strtoint(copy (Sh.name,6,1));
if SB[i].down then
Out_Mode[i] := not Out_Mode[i];
DMX_Set_Port;
end;
procedure TForm1.SBClick(Sender: TObject);
begin
DMX_Set_Port;
end;
//
// CD - Dans la documentation les 8 bits de poids faibles indiquent Input/output
// et les 8 bits de poids fort indiquent Off ou On
// Or dans l'exemple en CPP (slmini.cpp - fonction Send_Config_port) c'est
// exactement le contraire qui est écrit
// L'exemple suivant prend comme hypothèse que les bits de poids faibles sont
// les bits 0 à 7 (0 à 255), ce qui normalement le cas. Et considère la doc
// sur la DLL DASHARD.DLL correcte.
// De plus peut on envoyer 256 par exemple qui donnerait le port 1 en input ON ?
//
procedure TForm1.DMX_Set_Port;
var
i,conf,ok : integer;
begin
conf := 0;
for i := 2 to 9 do
begin
if SB[i].down then
begin
conf := conf + trunc(IntPower(2,i-2)); // CD - -2 car array [2..9]
if Out_Mode[i] then
conf := conf + trunc(IntPower(2,i-2+8)); // CD - -2 car array [2..9] + 8 pour le décalage des bits de poids fort
end;
end;
ok := DasUSBCommand(DHC_PORTCONFIG, conf, nil);
StatusBar1.Simpletext := 'Status pour configuration ('+inttostr(conf)+') : ' + inttostr(ok);
end;
procedure TForm1.btSerialClick(Sender: TObject);
var
ok : integer;
begin
// SP : Lecture du n° de Série .
ok := DasUSBCommand(DHC_SERIAL, 0, nil);
StatusBar1.Simpletext := 'Serial : ' + inttostr(ok);
end;
procedure TForm1.btVersionClick(Sender: TObject);
var
ok : integer;
begin
// SP : Lecture de la version du firmware .
ok := DasUSBCommand(DHC_VERSION, 0, nil);
StatusBar1.Simpletext := 'Version : ' + inttostr(ok);
end;
end.
|
unit RelatorioFichaCadastral_p;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FMTBcd, DB, DBClient, Provider, SqlExpr, QRCtrls, QuickRpt, ExtCtrls;
type
TRelatorioFichaCadastral = class(TForm)
QuickRep1: TQuickRep;
PageFooterBand1: TQRBand;
QRLabel8: TQRLabel;
QRLabel10: TQRLabel;
PageHeaderBand1: TQRBand;
QRImage1: TQRImage;
QRLabelTitulo: TQRLabel;
DetailBand1: TQRBand;
qRelatorio: TSQLQuery;
dspRelatorio: TDataSetProvider;
cdsRelatorio: TClientDataSet;
dsRelatorio: TDataSource;
cdsRelatorioRAZAO_SOCIAL: TStringField;
cdsRelatorioAPELIDO: TStringField;
cdsRelatorioENDERECO: TStringField;
cdsRelatorioNUMERO: TStringField;
cdsRelatorioBAIRRO: TStringField;
cdsRelatorioCIDADE: TStringField;
cdsRelatorioCEP: TStringField;
cdsRelatorioUF: TStringField;
cdsRelatorioCNPJ: TStringField;
cdsRelatorioIE: TStringField;
cdsRelatorioLOGO: TBlobField;
cdsRelatorioSITE: TStringField;
cdsRelatorioTELEFONE: TStringField;
cdsRelatorioEMAIL: TStringField;
cdsRelatorioOPCAO_TRIBUTARIA: TStringField;
ColumnHeaderBand1: TQRBand;
QRLabel1: TQRLabel;
QRDBText6: TQRDBText;
QRLabel2: TQRLabel;
QRDBText7: TQRDBText;
QRLabel3: TQRLabel;
QRDBText1: TQRDBText;
QRLabel4: TQRLabel;
QRDBText2: TQRDBText;
QRLabel5: TQRLabel;
QRLabel6: TQRLabel;
QRLabel7: TQRLabel;
QRLabel9: TQRLabel;
QRLabel11: TQRLabel;
QRLabel12: TQRLabel;
QRDBText3: TQRDBText;
QRDBText4: TQRDBText;
QRDBText5: TQRDBText;
QRDBText8: TQRDBText;
QRDBText9: TQRDBText;
UF: TQRDBText;
QRLabel13: TQRLabel;
QRDBText10: TQRDBText;
cdsRelatorioNOME_BANCO: TStringField;
cdsRelatorioNUMERO_BANCO: TStringField;
cdsRelatorioAGENCIA: TStringField;
cdsRelatorioCONTA: TStringField;
QRLabel14: TQRLabel;
QRDBText11: TQRDBText;
QRDBText12: TQRDBText;
QRLabel15: TQRLabel;
QRLabel16: TQRLabel;
QRDBText13: TQRDBText;
QRDBText14: TQRDBText;
QRLabel17: TQRLabel;
QRDBText15: TQRDBText;
QRLabel18: TQRLabel;
QRDBText16: TQRDBText;
QRLabel19: TQRLabel;
QRLabel20: TQRLabel;
QRLabel21: TQRLabel;
QRDBText17: TQRDBText;
procedure PageHeaderBand1BeforePrint(Sender: TQRCustomBand;
var PrintBand: Boolean);
private
{ Private declarations }
public
{ Public declarations }
procedure MontaRelatorio;
end;
var
RelatorioFichaCadastral: TRelatorioFichaCadastral;
implementation
uses Principal_p, DMPrincipal_p, Funcoes_p;
{$R *.dfm}
procedure TRelatorioFichaCadastral.MontaRelatorio;
begin
QRLabelTitulo.Caption := 'Ficha Cadastral Empresa';
cdsRelatorio.Open;
if not(cdsRelatorio.IsEmpty) then
QuickRep1.Preview
else
Application.MessageBox('Atenção: Nenhum Registro Encontrado.','Aviso' ,mb_OK);
end;
procedure TRelatorioFichaCadastral.PageHeaderBand1BeforePrint(
Sender: TQRCustomBand; var PrintBand: Boolean);
var b1 : TStream;
begin
// logo da empresa
b1 := DMPrincipal.cdsEmpresa.CreateBlobStream(DMPrincipal.cdsEmpresa.FieldByName('LOGO'),bmRead);
if b1.Size > 0 then
begin
try
//QrImage1.Picture.Assign(b1);
QrImage1.Picture.Bitmap.LoadFromStream(b1);
except
end;
end
else
QrImage1.Picture.Assign(nil);
b1.Free;
end;
end.
|
unit Main;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
System.Threading,
Redis.Commons,
Redis.Client,
Redis.NetLib.INDY,
Redis.Values
;
type
TForm10 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FTask: ITask;
public
{ Public declarations }
end;
var
Form10: TForm10;
implementation
{$R *.dfm}
procedure TForm10.FormCreate(Sender: TObject);
begin
Self.FTask := TTask.Run(
procedure
var
oRedis: IRedisClient;
begin
// Conexão exclusiva com o Redis
oRedis := TRedisClient.Create('localhost', 6379);
oRedis.Connect;
// Inicia a assinatura dos canais (Só retorna quando encerrar a assinatura)
oRedis.SUBSCRIBE(
// Lista de canais sendo assinados
['TDC:POA:2018:SENHA:PUBSUB#'],
// Método anônimo que trata a mensagem recebida
procedure(ACanal: string; AMensagem: string)
var
iSeparador: Integer;
sBalcao: string;
sSenha: string;
begin
iSeparador := Pos('|', AMensagem);
sBalcao := Copy(AMensagem, 0, iSeparador - 1);
sSenha := Copy(AMensagem, iSeparador + 1, MaxInt);
Self.Label2.Caption := 'BALCÃO ' + sBalcao;
Self.Label3.Caption := 'SENHA ' + sSenha;
end
); // oRedis.SUBSCRIBE
// Encerra a conexão com o Redis
oRedis.Disconnect;
end) // Self.FTask := TTask.Run(
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [NFCE_CONFIGURACAO]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 1.0
*******************************************************************************}
unit NfceConfiguracaoVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, NfceResolucaoVO,
NfceCaixaVO, EmpresaVO, NfceConfiguracaoBalancaVO,
NfceConfiguracaoLeitorSerVO,
Biblioteca;
type
[TEntity]
[TTable('NFCE_CONFIGURACAO')]
TNfceConfiguracaoVO = class(TVO)
private
FID: Integer;
FID_EMPRESA: Integer;
FID_NFCE_CAIXA: Integer;
FID_NFCE_RESOLUCAO: Integer;
FMENSAGEM_CUPOM: String;
FTITULO_TELA_CAIXA: String;
FCAMINHO_IMAGENS_PRODUTOS: String;
FCAMINHO_IMAGENS_MARKETING: String;
FCAMINHO_IMAGENS_LAYOUT: String;
FCOR_JANELAS_INTERNAS: String;
FMARKETING_ATIVO: String;
FCFOP: Integer;
FDECIMAIS_QUANTIDADE: Integer;
FDECIMAIS_VALOR: Integer;
FQUANTIDADE_MAXIMA_PARCELA: Integer;
FIMPRIME_PARCELA: String;
FNfceResolucaoVO: TNfceResolucaoVO;
FNfceCaixaVO: TNfceCaixaVO;
FEmpresaVO: TEmpresaVO;
FNfceConfiguracaoBalancaVO: TNfceConfiguracaoBalancaVO;
FNfceConfiguracaoLeitorSerVO: TNfceConfiguracaoLeitorSerVO;
public
constructor Create; override;
destructor Destroy; override;
[TId('ID')]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_EMPRESA', 'Id Empresa', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA;
[TColumn('ID_NFCE_CAIXA', 'Id Nfce Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdNfceCaixa: Integer read FID_NFCE_CAIXA write FID_NFCE_CAIXA;
[TColumn('ID_NFCE_RESOLUCAO', 'Id Nfce Resolucao', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdNfceResolucao: Integer read FID_NFCE_RESOLUCAO write FID_NFCE_RESOLUCAO;
[TColumn('MENSAGEM_CUPOM', 'Mensagem Cupom', 450, [ldGrid, ldLookup, ldCombobox], False)]
property MensagemCupom: String read FMENSAGEM_CUPOM write FMENSAGEM_CUPOM;
[TColumn('TITULO_TELA_CAIXA', 'Titulo Tela Caixa', 450, [ldGrid, ldLookup, ldCombobox], False)]
property TituloTelaCaixa: String read FTITULO_TELA_CAIXA write FTITULO_TELA_CAIXA;
[TColumn('CAMINHO_IMAGENS_PRODUTOS', 'Caminho Imagens Produtos', 450, [ldGrid, ldLookup, ldCombobox], False)]
property CaminhoImagensProdutos: String read FCAMINHO_IMAGENS_PRODUTOS write FCAMINHO_IMAGENS_PRODUTOS;
[TColumn('CAMINHO_IMAGENS_MARKETING', 'Caminho Imagens Marketing', 450, [ldGrid, ldLookup, ldCombobox], False)]
property CaminhoImagensMarketing: String read FCAMINHO_IMAGENS_MARKETING write FCAMINHO_IMAGENS_MARKETING;
[TColumn('CAMINHO_IMAGENS_LAYOUT', 'Caminho Imagens Layout', 450, [ldGrid, ldLookup, ldCombobox], False)]
property CaminhoImagensLayout: String read FCAMINHO_IMAGENS_LAYOUT write FCAMINHO_IMAGENS_LAYOUT;
[TColumn('COR_JANELAS_INTERNAS', 'Cor Janelas Internas', 160, [ldGrid, ldLookup, ldCombobox], False)]
property CorJanelasInternas: String read FCOR_JANELAS_INTERNAS write FCOR_JANELAS_INTERNAS;
[TColumn('MARKETING_ATIVO', 'Marketing Ativo', 8, [ldGrid, ldLookup, ldCombobox], False)]
property MarketingAtivo: String read FMARKETING_ATIVO write FMARKETING_ATIVO;
[TColumn('CFOP', 'Cfop', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Cfop: Integer read FCFOP write FCFOP;
[TColumn('DECIMAIS_QUANTIDADE', 'Decimais Quantidade', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property DecimaisQuantidade: Integer read FDECIMAIS_QUANTIDADE write FDECIMAIS_QUANTIDADE;
[TColumn('DECIMAIS_VALOR', 'Decimais Valor', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property DecimaisValor: Integer read FDECIMAIS_VALOR write FDECIMAIS_VALOR;
[TColumn('QUANTIDADE_MAXIMA_PARCELA', 'Quantidade Maxima Parcela', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property QuantidadeMaximaParcela: Integer read FQUANTIDADE_MAXIMA_PARCELA write FQUANTIDADE_MAXIMA_PARCELA;
[TColumn('IMPRIME_PARCELA', 'Imprime Parcela', 8, [ldGrid, ldLookup, ldCombobox], False)]
property ImprimeParcela: String read FIMPRIME_PARCELA write FIMPRIME_PARCELA;
[TAssociation('ID', 'ID_NFCE_RESOLUCAO')]
property NfceResolucaoVO: TNfceResolucaoVO read FNfceResolucaoVO write FNfceResolucaoVO;
[TAssociation('ID', 'ID_NFCE_CAIXA')]
property NfceCaixaVO: TNfceCaixaVO read FNfceCaixaVO write FNfceCaixaVO;
[TAssociation('ID', 'ID_EMPRESA')]
property EmpresaVO: TEmpresaVO read FEmpresaVO write FEmpresaVO;
[TAssociation('ID_NFCE_CONFIGURACAO', 'ID')]
property NfceConfiguracaoBalancaVO: TNfceConfiguracaoBalancaVO read FNfceConfiguracaoBalancaVO write FNfceConfiguracaoBalancaVO;
[TAssociation('ID_NFCE_CONFIGURACAO', 'ID')]
property NfceConfiguracaoLeitorSerVO: TNfceConfiguracaoLeitorSerVO read FNfceConfiguracaoLeitorSerVO write FNfceConfiguracaoLeitorSerVO;
end;
implementation
constructor TNfceConfiguracaoVO.Create;
begin
inherited;
FNfceResolucaoVO := TNfceResolucaoVO.Create;
FNfceCaixaVO := TNfceCaixaVO.Create;
FEmpresaVO := TEmpresaVO.Create;
FNfceConfiguracaoBalancaVO := TNfceConfiguracaoBalancaVO.Create;
FNfceConfiguracaoLeitorSerVO := TNfceConfiguracaoLeitorSerVO.Create;
end;
destructor TNfceConfiguracaoVO.Destroy;
begin
FreeAndNil(FNfceResolucaoVO);
FreeAndNil(FNfceCaixaVO);
FreeAndNil(FEmpresaVO);
FreeAndNil(FNfceConfiguracaoBalancaVO);
FreeAndNil(FNfceConfiguracaoLeitorSerVO);
inherited;
end;
initialization
Classes.RegisterClass(TNfceConfiguracaoVO);
finalization
Classes.UnRegisterClass(TNfceConfiguracaoVO);
end.
|
{$HIDE CW3}
{$HIDE PW12}
namespace Moshine.Web.Helpers;
interface
uses
System, System.Collections.Generic;
type
ColumnBuilder<T> = public class
where T is class;
private
_propertyGetters : List<Column<T>>;
public
constructor;
method &For(propertyGetter:Func<T, object>):Column<T>;
property PropertyGetters:List<Column<T>> read _propertyGetters;
end;
ColumnBuilder = public class
private
_propertyGetters : List<Column>;
public
constructor;
method &For(ColumnId:String):Column;
property PropertyGetters:List<Column> read _propertyGetters;
end;
implementation
{ ColumnBuilder }
constructor ColumnBuilder<T>;
begin
_propertyGetters := new List<Column<T>>;
end;
method ColumnBuilder<T>.&For(propertyGetter : Func<T, object>) : Column<T>;
begin
var newColumn := new Column<T>( Getter := propertyGetter);
_propertyGetters.Add(newColumn);
exit newColumn;
end;
method ColumnBuilder.For(ColumnId:String): Column;
begin
var newColumn := new Column( ColumnId := ColumnId);
_propertyGetters.Add(newColumn);
exit newColumn;
end;
constructor ColumnBuilder;
begin
_propertyGetters := new List<Column>;
end;
end.
|
object OptionsForm: TOptionsForm
Left = 357
Top = 112
BorderStyle = bsDialog
Caption = 'Options'
ClientHeight = 233
ClientWidth = 271
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poDesktopCenter
PixelsPerInch = 96
TextHeight = 13
object Panel1: TPanel
Left = 0
Top = 195
Width = 271
Height = 38
Align = alBottom
BevelOuter = bvNone
TabOrder = 0
object bnOk: TButton
Left = 10
Top = 8
Width = 75
Height = 25
Caption = 'Ok'
ModalResult = 1
TabOrder = 0
OnClick = bnApplyClick
end
object bnCancel: TButton
Left = 98
Top = 8
Width = 75
Height = 25
Caption = 'Cancel'
ModalResult = 2
TabOrder = 1
end
object bnApply: TButton
Left = 186
Top = 8
Width = 75
Height = 25
Caption = 'Apply'
TabOrder = 2
OnClick = bnApplyClick
end
end
object PageControl: TPageControl
Left = 0
Top = 0
Width = 271
Height = 195
ActivePage = tsServer
Align = alClient
TabOrder = 1
object tsColors: TTabSheet
Caption = 'Colors'
object labcurregColor: TLabel
Left = 8
Top = 1
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object labgridColor: TLabel
Left = 8
Top = 25
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object labwallColor: TLabel
Left = 8
Top = 49
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object labtextColor: TLabel
Left = 8
Top = 73
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object Label1: TLabel
Left = 29
Top = 1
Width = 121
Height = 17
AutoSize = False
Caption = 'Current Region'
Layout = tlCenter
end
object Label2: TLabel
Left = 29
Top = 25
Width = 121
Height = 17
AutoSize = False
Caption = 'Grid'
Layout = tlCenter
end
object Label3: TLabel
Left = 29
Top = 49
Width = 121
Height = 17
AutoSize = False
Caption = 'Wall'
Layout = tlCenter
end
object Label4: TLabel
Left = 29
Top = 73
Width = 121
Height = 17
AutoSize = False
Caption = 'Text'
Layout = tlCenter
end
object labWedge0: TLabel
Left = 184
Top = 21
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object labWedge5: TLabel
Left = 160
Top = 29
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object labWedge4: TLabel
Left = 160
Top = 53
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object labWedge3: TLabel
Left = 184
Top = 61
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object labWedge2: TLabel
Left = 208
Top = 53
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object labWedge1: TLabel
Left = 208
Top = 29
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object Wedges: TLabel
Left = 171
Top = 3
Width = 40
Height = 13
Caption = 'Wedges'
end
object labroadColor: TLabel
Left = 8
Top = 97
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object Label11: TLabel
Left = 29
Top = 97
Width = 57
Height = 17
AutoSize = False
Caption = 'Road'
Layout = tlCenter
end
object Label13: TLabel
Left = 197
Top = 143
Width = 56
Height = 13
Caption = 'Undetected'
end
object Label14: TLabel
Left = 29
Top = 143
Width = 66
Height = 13
Caption = 'Local factions'
end
object Label15: TLabel
Left = 127
Top = 99
Width = 16
Height = 13
Caption = 'Ally'
end
object Label16: TLabel
Left = 127
Top = 121
Width = 36
Height = 13
Caption = 'Friendly'
end
object Label17: TLabel
Left = 197
Top = 99
Width = 47
Height = 13
Caption = 'Unfriendly'
end
object Label18: TLabel
Left = 127
Top = 143
Width = 34
Height = 13
Caption = 'Neutral'
end
object Label19: TLabel
Left = 197
Top = 121
Width = 32
Height = 13
Caption = 'Hostile'
end
object lbAlly: TLabel
Left = 109
Top = 97
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object lbFriend: TLabel
Left = 109
Top = 119
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object lbNeutral: TLabel
Left = 109
Top = 141
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object lbUndetect: TLabel
Left = 178
Top = 141
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object lbUnfrien: TLabel
Left = 178
Top = 97
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object lbHostile: TLabel
Left = 178
Top = 119
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object lbLocF: TLabel
Left = 8
Top = 141
Width = 16
Height = 16
AutoSize = False
Color = clBlack
ParentColor = False
OnDblClick = labColorDblClick
end
object cbColorUnit: TCheckBox
Left = 8
Top = 120
Width = 97
Height = 17
Caption = 'Color units'
TabOrder = 0
end
end
object tsOptions: TTabSheet
Caption = 'Options'
ImageIndex = 1
object Label5: TLabel
Left = 8
Top = 101
Width = 129
Height = 17
AutoSize = False
Caption = 'Town name limit (0 - none)'
Layout = tlBottom
end
object Label10: TLabel
Left = 9
Top = 124
Width = 104
Height = 17
AutoSize = False
Caption = 'Backup orders every'
Layout = tlBottom
end
object Label12: TLabel
Left = 136
Top = 124
Width = 97
Height = 17
AutoSize = False
Caption = ' min (0 - no backup)'
Layout = tlBottom
end
object cbShowEvents: TCheckBox
Left = 8
Top = 4
Width = 161
Height = 17
Caption = 'Show closed Events window'
TabOrder = 0
end
object cbRunRegionOrders: TCheckBox
Left = 8
Top = 24
Width = 249
Height = 17
Caption = 'Run Orders on change'
TabOrder = 1
end
object edTownNameLimit: TEdit
Left = 144
Top = 101
Width = 81
Height = 21
TabOrder = 5
end
object cbMaximizeWindow: TCheckBox
Left = 8
Top = 44
Width = 137
Height = 17
Caption = 'Maximize Client on start'
TabOrder = 2
end
object cbShowLDescFirst: TCheckBox
Left = 8
Top = 64
Width = 153
Height = 17
Caption = 'Show Local Description first'
TabOrder = 3
end
object cbCopyOnSaveOrders: TCheckBox
Left = 8
Top = 84
Width = 225
Height = 17
Caption = 'Copy to Clipboard on Save Orders'
TabOrder = 4
end
object edAutoSaveTimer: TEdit
Left = 112
Top = 124
Width = 25
Height = 21
MaxLength = 2
TabOrder = 6
end
end
object tsEvents: TTabSheet
Caption = 'Events'
ImageIndex = 2
object TLabel
Left = 8
Top = 8
Width = 55
Height = 13
Caption = 'Don'#39't Show'
end
object cbdseRegDataFound: TCheckBox
Left = 8
Top = 60
Width = 113
Height = 17
Caption = 'Region data found'
TabOrder = 0
end
object cbdseIncome: TCheckBox
Left = 8
Top = 80
Width = 129
Height = 17
Caption = 'Tax, Ent, Work Income'
TabOrder = 1
end
object cbdseDiscard: TCheckBox
Left = 8
Top = 20
Width = 97
Height = 17
Caption = 'Discard Warning'
TabOrder = 2
end
object cbdseNoMonth: TCheckBox
Left = 8
Top = 40
Width = 121
Height = 17
Caption = 'No Monthlong Error'
TabOrder = 3
end
object cbdseCantReach: TCheckBox
Left = 8
Top = 100
Width = 169
Height = 17
Caption = 'Move/Sail "can'#39't reach" Error'
TabOrder = 4
end
object cbdseBorrows: TCheckBox
Left = 144
Top = 20
Width = 105
Height = 17
Caption = 'Borrows in region'
TabOrder = 5
end
object cbdseTeachNonLocNotStudy: TCheckBox
Left = 8
Top = 120
Width = 209
Height = 17
Caption = 'Not Study Teach errors for nonlocals'
TabOrder = 6
end
end
object tsServer: TTabSheet
Caption = 'Server'
ImageIndex = 4
object labFlightOverWater: TLabel
Left = 8
Top = 107
Width = 89
Height = 17
AutoSize = False
Caption = 'Flight Over Water'
Layout = tlBottom
end
object cbNoCross: TCheckBox
Left = 8
Top = 8
Width = 161
Height = 17
Caption = 'presents NOCROSS flag'
TabOrder = 0
end
object cbNoSpoils: TCheckBox
Left = 8
Top = 24
Width = 161
Height = 17
Caption = 'presents NOSPOILS flag'
TabOrder = 1
end
object cbGiveAll: TCheckBox
Left = 8
Top = 40
Width = 161
Height = 17
Caption = 'presents Give All Except order'
TabOrder = 2
end
object cbSpoils: TCheckBox
Left = 8
Top = 56
Width = 129
Height = 17
Caption = 'presents SPOILS order'
TabOrder = 3
end
object cbServFlightOverWater: TComboBox
Left = 96
Top = 107
Width = 145
Height = 21
Style = csDropDownList
ItemHeight = 13
TabOrder = 4
Items.Strings = (
'None'
'Must Land'
'Unlimited')
end
object cbTaxIsMonthlong: TCheckBox
Left = 8
Top = 89
Width = 185
Height = 17
Caption = 'TAX, PILLAGE orders is monthlong'
TabOrder = 5
end
object bnChangeGameParams: TButton
Left = 8
Top = 131
Width = 121
Height = 25
Caption = 'Change Game Params'
TabOrder = 6
OnClick = bnChangeGameParamsClick
end
object cbSharing: TCheckBox
Left = 8
Top = 72
Width = 133
Height = 17
Caption = 'presents SHARING flag'
TabOrder = 7
end
end
object tsServerMail: TTabSheet
Caption = 'Server Mail'
ImageIndex = 3
object Label6: TLabel
Left = 8
Top = 8
Width = 63
Height = 17
AutoSize = False
Caption = 'Server E-Mail'
Layout = tlBottom
end
object Label7: TLabel
Left = 8
Top = 32
Width = 65
Height = 17
AutoSize = False
Caption = 'Orders Subj'
Layout = tlBottom
end
object Label8: TLabel
Left = 8
Top = 56
Width = 71
Height = 17
AutoSize = False
Caption = 'Times Request'
Layout = tlBottom
end
object Label9: TLabel
Left = 8
Top = 80
Width = 65
Height = 17
AutoSize = False
Caption = 'Mail Subj'
Layout = tlBottom
end
object edServEMail: TEdit
Left = 80
Top = 8
Width = 121
Height = 21
TabOrder = 0
end
object cbNoServerMail: TCheckBox
Left = 16
Top = 104
Width = 97
Height = 17
Caption = 'No Server Mail'
TabOrder = 1
end
object edOrdersSubj: TEdit
Left = 80
Top = 32
Width = 121
Height = 21
TabOrder = 2
end
object edTimesSubj: TEdit
Left = 80
Top = 56
Width = 65
Height = 21
TabOrder = 3
end
object edTimesBody: TEdit
Left = 152
Top = 56
Width = 97
Height = 21
TabOrder = 4
end
object edMailSubj: TEdit
Left = 80
Top = 80
Width = 121
Height = 21
TabOrder = 5
end
end
end
object ColorDialog: TColorDialog
Options = [cdFullOpen, cdSolidColor]
Left = 88
Top = 192
end
end
|
unit InfraBasicList;
interface
uses
Classes,
InfraCommonIntf,
InfraCommon;
type
TInfraCustomList = class(TInterfaceList, IInfraCustomList)
public
function NewIterator: IInfraIterator;
end;
TInfraCustomListIterator = class(TBaseElement, IInfraIterator)
private
FCurrentIndex: Integer;
FList: IInterfaceList;
protected
function CurrentItem: IInterface;
procedure First; virtual;
function IsDone: Boolean;
procedure Next;
public
constructor Create(const List: IInterfaceList); reintroduce;
end;
implementation
{ TInfraCustomList }
function TInfraCustomList.NewIterator: IInfraIterator;
begin
Result := TInfraCustomListIterator.Create(Self) as IInfraIterator;
end;
{ TInfraCustomListIterator }
constructor TInfraCustomListIterator.Create(const List: IInterfaceList);
begin
inherited Create;
FList := List;
First;
end;
function TInfraCustomListIterator.CurrentItem: IInterface;
begin
if Assigned(FList) and (fCurrentIndex <> -1)
and (fCurrentIndex < FList.Count) then
Result := FList[fCurrentIndex]
else
Result := nil;
end;
procedure TInfraCustomListIterator.First;
begin
if FList.Count > 0 then
fCurrentIndex := 0
else
fCurrentIndex := -1;
end;
function TInfraCustomListIterator.IsDone: Boolean;
begin
Result := (fCurrentIndex <> FList.Count);
end;
procedure TInfraCustomListIterator.Next;
begin
if (FList.Count > 0) and (FCurrentIndex < FList.Count) then
Inc(fCurrentIndex);
end;
end.
|
unit MBRTURequestBase;
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils,
LoggerItf,
MBRTUObjItf, MBRTUMasterDispatcherTypes;
type
{ TMBRTURequestBase }
TMBRTURequestBase = class(TObjectLogged)
private
FCallBackItf : IMBMasterItf;
FDevNum : Byte;
FMBFunc : Byte;
FResponceTimeout : Cardinal;
FLastResponceCRC : Word;
procedure SetDevNum(AValue: Byte);
procedure SetMBFunc(AValue: Byte);
procedure SetResponceTimeout(AValue: Cardinal);
protected
FRequest : TMBPacket;
FResponceSize : Word;
FCurError : Cardinal;
FLastError : Cardinal;
function IsDataChange(ANewCRC : Word): Boolean;
function IsValidResponce(var AResponce: TMBPacket; AResponceLen: Word) : Boolean; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
function GetRequest : TMBPacket;
procedure BuilRequest; virtual; abstract;
procedure SetResponce(var AResponce : TMBPacket; AResponceLen : Word); virtual; abstract;
property CallBackItf : IMBMasterItf read FCallBackItf write FCallBackItf;
property ResponceTimeout : Cardinal read FResponceTimeout write SetResponceTimeout;
property DevNum : Byte read FDevNum write SetDevNum;
property MBFunc : Byte read FMBFunc write SetMBFunc;
property ResponceSize : Word read FResponceSize;
property CurError : Cardinal read FCurError write FCurError;
property LastError : Cardinal read FLastError write FLastError;
end;
implementation
uses MBRTUMasterDispatcherConst,
MBDefine, ExceptionsTypes,
MBRTUMasterDispatcherFunc;
{ TMBRTURequestBase }
constructor TMBRTURequestBase.Create;
begin
FDevNum := 1;
FMBFunc := 1;
FCallBackItf := nil;
FResponceTimeout := DefResponseTimeout;
FResponceSize := 0;
FLastResponceCRC := 0;
end;
destructor TMBRTURequestBase.Destroy;
begin
SetLength(FRequest,0);
inherited Destroy;
end;
function TMBRTURequestBase.GetRequest: TMBPacket;
begin
Result := FRequest;
end;
procedure TMBRTURequestBase.SetDevNum(AValue: Byte);
begin
if FDevNum = AValue then Exit;
FDevNum := AValue;
end;
procedure TMBRTURequestBase.SetMBFunc(AValue: Byte);
begin
if FMBFunc = AValue then Exit;
FMBFunc := AValue;
end;
procedure TMBRTURequestBase.SetResponceTimeout(AValue: Cardinal);
begin
if FResponceTimeout=AValue then Exit;
if AValue < MinResponseTimeout then AValue := MinResponseTimeout;
FResponceTimeout := AValue;
end;
function TMBRTURequestBase.IsDataChange(ANewCRC: Word): Boolean;
begin
Result := FLastResponceCRC <> ANewCRC;
if Result then FLastResponceCRC := ANewCRC;
end;
function TMBRTURequestBase.IsValidResponce(var AResponce: TMBPacket; AResponceLen: Word): Boolean;
var TempErr : Cardinal;
begin
Result := False;
if (CallBackItf = nil) then Exit;
FLastError := FCurError;
FCurError := 0;
// длинна пришедшего пакета
if (FResponceSize <> 0) then
if (AResponceLen <> FResponceSize) and (AResponceLen <> 5) then
begin
if FLastError <> ERR_MASTER_PACK_LEN then
begin
CallBackItf.SendEvent(mdeeMBError,ERR_MASTER_PACK_LEN,AResponceLen);
end;
FCurError := ERR_MASTER_PACK_LEN;
Exit;
end;
// контрольная сумма совпадает с контрольной суммой предыдущего пакета - данные не изменились
if not IsDataChange(PWord(@AResponce[AResponceLen - 2])^) then Exit;
// валидность CRC
if not IsValidCRC(AResponce,AResponceLen) then
begin
if FLastError <> ERR_MASTER_CRC then
begin
CallBackItf.SendEvent(mdeeMBError,ERR_MASTER_CRC);
end;
FCurError := ERR_MASTER_CRC;
Exit;
end;
// ошибка от устройства
if AResponce[1] and $80 = $80 then
begin
TempErr := ERR_MB_ERR_CUSTOM + AResponce[2];
if FLastError <> TempErr then
begin
CallBackItf.SendEvent(mdeeMBError,TempErr);
end;
FCurError := TempErr;
Exit;
end;
Result := True;
end;
end.
|
unit Controller.Compromisso;
interface
uses
System.SysUtils
, Classes.ScriptDDL
, Model.Compromisso
, Controllers.Interfaces.Observers
, Services.ComplexTypes
, System.Generics.Collections
, FireDAC.Comp.Client
, Data.DB;
type
TCompromissoController = class(TInterfacedObject, ISubjectCompromissoController)
strict private
class var _instance : TCompromissoController;
private
FObservers : TList<IObserverCompromissoController>;
FOperacao : TTipoOperacaoController;
FDDL : TScriptDDL;
FModel : TCompromissoModel;
FLista : TList<TCompromissoModel>;
procedure SetAtributes(const aDataSet : TDataSet; aModel : TCompromissoModel);
procedure AdicionarObservador(Observer : IObserverCompromissoController);
procedure RemoverTodosObservadores;
procedure Notificar;
function Find(aID : TGUID; aCodigo : Integer; out aErro : String;
const RETURN_ATTRIBUTES : Boolean = FALSE) : Boolean; overload;
protected
constructor Create;
destructor Destroy; override;
public
class function GetInstance(Observer : IObserverCompromissoController) : TCompromissoController;
property Operacao : TTipoOperacaoController read FOperacao;
property Attributes : TCompromissoModel read FModel;
property Lista : TList<TCompromissoModel> read FLista;
procedure New;
procedure Load(const aQuantidadeRegistros: Integer; aAno, aMes : Word; aTipo : TTipoCompromisso;
var aTotal : TTotalCompromissos; out aErro : String);
procedure RemoverObservador(Observer : IObserverCompromissoController);
function Insert(out aErro : String) : Boolean; virtual; abstract;
function Update(out aErro : String) : Boolean; virtual; abstract;
function Delete(out aErro : String) : Boolean; virtual; abstract;
function Find(aID : TGUID; out aErro : String;
const RETURN_ATTRIBUTES : Boolean = FALSE) : Boolean; overload;
function Find(aCodigo : Integer; out aErro : String;
const RETURN_ATTRIBUTES : Boolean = FALSE) : Boolean; overload;
end;
implementation
uses
DataModule.Conexao
, FMX.Graphics
, System.DateUtils
, System.Math;
{ TCompromissoController }
const
FLAG_SIM = 'S';
FLAG_NAO = 'N';
class function TCompromissoController.GetInstance(Observer: IObserverCompromissoController): TCompromissoController;
begin
if not Assigned(_instance) then
_instance := TCompromissoController.Create;
_instance.AdicionarObservador(Observer);
Result := _instance;
end;
procedure TCompromissoController.Load(const aQuantidadeRegistros: Integer; aAno, aMes: Word; aTipo: TTipoCompromisso;
var aTotal: TTotalCompromissos; out aErro: String);
var
aModel : TCompromissoModel;
aQry : TFDQuery;
begin
FOperacao := TTipoOperacaoController.operControllerBrowser;
aQry := TFDQuery.Create(nil);
try
aQry.Connection := TDMConexao.GetInstance().Conn;
try
with aQry, SQL do
begin
BeginUpdate;
Clear;
Add('Select ');
Add(' a.id_compromisso');
Add(' , a.cd_compromisso');
Add(' , a.tp_compromisso');
Add(' , a.ds_compromisso');
Add(' , a.dt_compromisso');
Add(' , a.vl_compromisso');
Add(' , a.cd_categoria ');
Add(' , c.ds_categoria ');
Add(' , c.ic_categoria ');
Add('from ' + FDDL.getTableNameCompromisso + ' a');
Add(' left join ' + FDDL.getTableNameCategoria + ' c on (c.cd_categoria = a.cd_categoria)');
Add('where (a.tp_compromisso = :tipo)');
if ((aAno > 0) and (aMes > 0)) then
Add(' and (a.dt_compromisso between :data_inicial and :data_final)');
Add('order by');
Add(' datetime(a.dt_compromisso) DESC');
Add(' , a.ds_compromisso ASC');
if (aQuantidadeRegistros > 0) then
Add('limit :limite');
EndUpdate;
ParamByName('tipo').AsInteger := Ord(aTipo);
if ((aAno > 0) and (aMes > 0)) then
begin
ParamByName('data_inicial').AsDateTime := EncodeDate(aAno, aMes, 1);
ParamByName('data_final').AsDateTime := EndOfTheMonth( EncodeDate(aAno, aMes, 1) );
end;
if (aQuantidadeRegistros > 0) then
ParamByName('limite').AsInteger := aQuantidadeRegistros;
Open;
Lista.Clear;
aTotal.Comprometer := 0.0;
aTotal.Comprometido := 0.0;
aTotal.Pendente := 0.0;
while not Eof do
begin
aModel := TCompromissoModel.Create;
SetAtributes(aQry, aModel);
Lista.Add(aModel);
// Totalizar
if (aModel.Tipo = TTipoCompromisso.tipoCompromissoAReceber) then
aTotal.Comprometer := ( aTotal.Comprometer + aModel.Valor )
else
aTotal.Comprometer := ( aTotal.Comprometer + (aModel.Valor * (-1)) );
if aModel.Realizado then
begin
if (aModel.Tipo = TTipoCompromisso.tipoCompromissoAReceber) then
aTotal.Comprometido := ( aTotal.Comprometido + aModel.Valor )
else
aTotal.Comprometido := ( aTotal.Comprometido + (aModel.Valor * (-1)) );
end;
aTotal.Pendente := aTotal.Comprometer - aTotal.Comprometido;
Next;
end;
// Limitar o tamanho da lista à quantidade de objetos instanciados
Lista.TrimExcess;
end;
except
On E : Exception do
aErro := 'Erro ao tentar carregar os compromissos: ' + E.Message;
end;
finally
aQry.Close;
aQry.DisposeOf;
end;
end;
procedure TCompromissoController.AdicionarObservador(Observer: IObserverCompromissoController);
begin
if (FObservers.IndexOf(Observer) = -1) then
FObservers.Add(Observer);
end;
constructor TCompromissoController.Create;
begin
FObservers := TList<IObserverCompromissoController>.Create;
FOperacao := TTipoOperacaoController.operControllerBrowser;
FDDL := TScriptDDL.getInstance();
FModel := TCompromissoModel.New;
FLista := TList<TCompromissoModel>.Create;
TDMConexao
.GetInstance()
.Conn
.ExecSQL(TScriptDDL.getInstance().getCreateTableCompromisso.Text, True);
end;
destructor TCompromissoController.Destroy;
var
aObj : TCompromissoModel;
I : Integer;
begin
RemoverTodosObservadores;
FObservers.DisposeOf;
FDDL.DisposeOf;
FModel.DisposeOf;
if Assigned(FLista) then
begin
for I := 0 to FLista.Count - 1 do
begin
aObj := FLista.Items[I];
FLista.Delete(I);
aObj.DisposeOf;
end;
FLista.Clear;
FLista.TrimExcess;
FLista.DisposeOf;
end;
inherited;
end;
function TCompromissoController.Find(aCodigo: Integer; out aErro: String; const RETURN_ATTRIBUTES: Boolean): Boolean;
begin
Result := Self.Find(TGuid.Empty, aCodigo, aErro, RETURN_ATTRIBUTES);
end;
function TCompromissoController.Find(aID: TGUID; out aErro: String; const RETURN_ATTRIBUTES: Boolean): Boolean;
begin
Result := Self.Find(aID, 0, aErro, RETURN_ATTRIBUTES);
end;
function TCompromissoController.Find(aID: TGUID; aCodigo: Integer; out aErro: String;
const RETURN_ATTRIBUTES: Boolean): Boolean;
var
aQry : TFDQuery;
begin
Result := False;
FOperacao := TTipoOperacaoController.operControllerBrowser;
aQry := TFDQuery.Create(nil);
try
aQry.Connection := TDMConexao.GetInstance().Conn;
try
with aQry, SQL do
begin
BeginUpdate;
Clear;
Add('Select ');
Add(' a.id_compromisso');
Add(' , a.cd_compromisso');
Add(' , a.tp_compromisso');
Add(' , a.ds_compromisso');
Add(' , a.dt_compromisso');
Add(' , a.vl_compromisso');
Add(' , a.sn_realizado');
Add(' , a.cd_categoria ');
Add(' , c.ds_categoria ');
Add(' , c.ic_categoria ');
Add('from ' + FDDL.getTableNameCompromisso + ' a');
Add(' left join ' + FDDL.getTableNameCategoria + ' c on (c.cd_categoria = a.cd_categoria)');
Add('where (a.id_compromisso = :id_compromisso)');
Add(' or (a.cd_compromisso = :cd_compromisso)');
EndUpdate;
ParamByName('id_compromisso').AsString := aID.ToString;
ParamByName('cd_compromisso').AsInteger := aCodigo;
Open;
Result := not IsEmpty;
if Result and RETURN_ATTRIBUTES then
SetAtributes(aQry, FModel);
end;
except
On E : Exception do
aErro := 'Erro ao tentar localizar o compromisso: ' + E.Message;
end;
finally
aQry.Close;
aQry.DisposeOf;
end;
end;
procedure TCompromissoController.New;
begin
FModel := TCompromissoModel.New;
end;
procedure TCompromissoController.Notificar;
var
Observer : IObserverCompromissoController;
begin
try
for Observer in FObservers do
Observer.AtualizarCompromisso;
except
Exit;
end;
end;
procedure TCompromissoController.RemoverObservador(Observer: IObserverCompromissoController);
begin
if (FObservers.IndexOf(Observer) > -1) then
begin
FObservers.Delete(FObservers.IndexOf(Observer));
FObservers.TrimExcess;
end;
end;
procedure TCompromissoController.RemoverTodosObservadores;
var
I : Integer;
begin
for I := 0 to (FObservers.Count - 1) do
FObservers.Delete(I);
FObservers.TrimExcess;
end;
procedure TCompromissoController.SetAtributes(const aDataSet: TDataSet; aModel: TCompromissoModel);
begin
with aDataSet, aModel do
begin
ID := StringToGUID(FieldByName('id_compromisso').AsString);
Codigo := FieldByName('cd_compromisso').AsInteger;
Tipo := TTipoCompromisso(FieldByName('tp_compromisso').AsInteger);
Descricao := FieldByName('ds_compromisso').AsString;
Data := FieldByName('dt_compromisso').AsDateTime;
Valor := FieldByName('vl_compromisso').AsCurrency;
Realizado := (FieldByName('sn_realizado').AsString = FLAG_SIM);
Categoria.Codigo := FieldByName('cd_categoria').AsInteger;
Categoria.Descricao := FieldByName('ds_categoria').AsString;
// #0#0#0#0'IEND®B`‚'
if (Trim(FieldByName('ic_categoria').AsString) <> EmptyStr) then
begin
Categoria.Icone := TBitmap.Create;
Categoria.Icone.LoadFromStream( CreateBlobStream(FieldByName('ic_categoria'), TBlobStreamMode.bmRead) );
end
else
Categoria.Icone := nil;
end;
end;
end.
|
(*
@abstract(Unité de convenance pour la prise en charge de tous les formats image supportés)
-------------------------------------------------------------------------------------------------------------
@created(2018-07-11)
@author(J.Delauney (BeanzMaster))
Historique : @br
@unorderedList(
@item(11/07/2018 : Creation)
@item(11/07/2018 : Dernière mise à jour)
)
-------------------------------------------------------------------------------------------------------------
@bold(Notes) :
-------------------------------------------------------------------------------------------------------------
@bold(Dependances) : BZImageFileBMP, BZImageFileXPM, BZImageFileTGA, BZImageFilePCX,
BZImageFilePPM, BZImageFileJPEG, BZImageFilePNG, BZImageFileGIF, BZImageFileWEBP
-------------------------------------------------------------------------------------------------------------
@bold(Credits) :
-------------------------------------------------------------------------------------------------------------
LICENCE : MPL / GPL
------------------------------------------------------------------------------------------------------------- *)
Unit BZBitmapIO;
//==============================================================================
{$mode objfpc}{$H+}
{$i ..\bzscene_options.inc}
//==============================================================================
Interface
Uses
Classes, Sysutils,
BZImageFileBMP, BZImageFileXPM, BZImageFileTGA, BZImageFilePCX, BZImageFilePPM,
BZImageFileJPEG, BZImageFilePNG, BZImageFileGIF, BZImageFileWEBP; {, BZImageFileTIFF;}
{ TODO -oBZBitmap -cIO : Prise en charge de nouveaux formats de fichier image
- BZImageFileICO
- BZImageFileTIFF
- BZImageFilePSD
- BZImageFileXCF
- BZImageFileDDS
- BZImageFileKTX
- BZImageFileRAW
- BZImageFilePCD
- BZImageFileHDR
- etc...
}
Implementation
End.
|
unit CommonObjectSelectFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, BaseObjects, CommonObjectSelector;
type
TFrameClass = class of TFrame;
TfrmIDObjectSelect = class(TFrame)
edtObject: TEdit;
btnObject: TButton;
lblObjectName: TStaticText;
procedure btnObjectClick(Sender: TObject);
private
{ Private declarations }
FObjectSelector: IObjectSelector;
FSelectorForm: TForm;
FSelectiveFrameClass: TFormClass;
FSelectedObject: TIDObject;
FLabelCaption: string;
procedure SetLabelCaption(const Value: string);
function GetSelectorForm: TForm;
procedure SetSelectedObject(const Value: TIDObject);
public
{ Public declarations }
procedure Clear;
property SelectorForm: TForm read GetSelectorForm;
property SelectiveFormClass: TFormClass read FSelectiveFrameClass write FSelectiveFrameClass;
property ObjectSelector: IObjectSelector read FObjectSelector write FObjectSelector;
property SelectedObject: TIDObject read FSelectedObject write SetSelectedObject;
property LabelCaption: string read FLabelCaption write SetLabelCaption;
end;
implementation
{$R *.dfm}
procedure TfrmIDObjectSelect.btnObjectClick(Sender: TObject);
begin
if not Assigned(FSelectorForm) then
FSelectorForm := SelectiveFormClass.Create(Self);
FSelectorForm.Position := poScreenCenter;
if Assigned(SelectedObject) then
ObjectSelector.SelectedObject := SelectedObject;
if FSelectorForm.ShowModal = mrOK then
SelectedObject := ObjectSelector.SelectedObject;
end;
procedure TfrmIDObjectSelect.Clear;
begin
edtObject.Clear;
end;
function TfrmIDObjectSelect.GetSelectorForm: TForm;
begin
if not Assigned(FSelectorForm) then
FSelectorForm := SelectiveFormClass.Create(Application.MainForm);
Result := FSelectorForm;
end;
procedure TfrmIDObjectSelect.SetLabelCaption(const Value: string);
begin
FLabelCaption := Value;
lblObjectName.Caption := FLabelCaption;
end;
procedure TfrmIDObjectSelect.SetSelectedObject(const Value: TIDObject);
begin
FSelectedObject := Value;
if Assigned(FSelectedObject) then edtObject.Text := FSelectedObject.List(loBrief);
end;
end.
|
unit PtWorker;
interface
uses TestFramework, System.SysUtils, System.Types, System.Classes, Generics.Collections, System.Rtti,
PtMethodInvoker, PtTypes;
type
/// <summary>
/// <b>Do not use directly.</b> Provides one test case for one method.
/// </summary>
TParameterizedTest = class(TTestCase)
strict private
/// <summary>
/// The class that TParameterizedTest will test.
/// </summary>
FClassToTest: TClass;
/// <summary>
/// The object that TParameterizedTest will test (if
/// TPtTestCase.FIsClassMethod = csIsNotClassMethod).
/// </summary>
FObjectForTesting: TValue;
/// <summary>
/// The name of the method that TParameterizedTest will test.
/// </summary>
FMethodName: string;
/// <summary>
/// Test case for this TParameterizedTest instance.
/// </summary>
FTestCase: TPtTestCase;
// Constructor can't be called directly - use CreateTest method
/// <summary>
/// Private constructor
/// </summary>
constructor Create(TestMethodName: string; AClassToTest: TClass; AMethodName: string;
ATestCase: TPtTestCase);
public
/// <summary>
/// Create the instance of FClassToTest class and saves it to
/// FObjectForTesting field.
/// </summary>
procedure SetUp; override;
/// <summary>
/// Call the destructor of FObjectForTesting object.
/// </summary>
procedure TearDown; override;
/// <summary>
/// Public constructor
/// </summary>
class function CreateTest(AClassToTest: TClass; AMethodName: string; ATestCase: TPtTestCase)
: ITestSuite;
class function SmartJoin(const Separator: string; Values: TStringDynArray): string; static;
published
property PtClassToTest: TClass read FClassToTest write FClassToTest;
property PtObjectForTesting: TValue read FObjectForTesting write FObjectForTesting;
property PtMethodName: string read FMethodName write FMethodName;
property PtTestCase: TPtTestCase read FTestCase write FTestCase;
/// <summary>
/// Test FMethodName and validate it's result.
/// </summary>
procedure TestMethod;
end;
implementation
uses Delphi.Mocks.Helpers; // https://github.com/VSoftTechnologies/Delphi-Mocks
constructor TParameterizedTest.Create(TestMethodName: string; AClassToTest: TClass;
AMethodName: string; ATestCase: TPtTestCase);
begin
inherited Create(TestMethodName);
//
FClassToTest := AClassToTest;
FMethodName := AMethodName;
FTestCase := ATestCase;
FObjectForTesting := TValue.From<TObject>(nil);
end;
class function TParameterizedTest.CreateTest(AClassToTest: TClass; AMethodName: string;
ATestCase: TPtTestCase): ITestSuite;
var
LParameterizedTest: TParameterizedTest;
LTestParamsString: string;
LConstructorParamsString: string;
LTestParamsItem: TValue;
LMethodEnumerator: TMethodEnumerator;
LParamTestFuncName: string;
TmpVal: TValue;
i: Integer;
begin
// Reconstruct the function call string
LTestParamsString := string.Empty;
for LTestParamsItem in ATestCase.FTestParams do
LTestParamsString := SmartJoin(', ', [LTestParamsString, LTestParamsItem.ToString]);
// Reconstruct the constructor, if needed
LConstructorParamsString := string.Empty;
if not ATestCase.FIsClassMethod then
begin
for TmpVal in ATestCase.FConstructorParams do
LConstructorParamsString := SmartJoin(', ', [LConstructorParamsString, TmpVal.ToString]);
LConstructorParamsString := ' (constructor arguments: ' + LConstructorParamsString + ')';
end;
// Create the ITestSuite interface for DUnit
Result := TTestSuite.Create(AMethodName + '(' + LTestParamsString + ') = ' +
ATestCase.FExpectedResult.ToString + LConstructorParamsString);
// Create one parameterized test (from TestMethod function)
LMethodEnumerator := TMethodEnumerator.Create(Self);
try
for i := 0 to LMethodEnumerator.MethodCount - 1 do
begin
LParamTestFuncName := LMethodEnumerator.NameOfMethod[i];
LParameterizedTest := TParameterizedTest.Create(LParamTestFuncName, AClassToTest, AMethodName,
ATestCase);
Result.addTest(LParameterizedTest as ITest);
end;
finally
FreeAndNil(LMethodEnumerator);
end;
end;
procedure TParameterizedTest.SetUp;
var
LRttiContext: TRttiContext;
LRttiType: TRttiType;
begin
if not FTestCase.FIsClassMethod then
begin
LRttiContext := TRttiContext.Create;
try
LRttiType := LRttiContext.GetType(FClassToTest);
FObjectForTesting := TPtMethodInvoker.RttiMethodInvokeEx('Create', LRttiType,
LRttiType.AsInstance.MetaclassType, FTestCase.FConstructorParams, csIsNotClassMethod);
finally
LRttiContext.Free;
end;
end;
end;
procedure TParameterizedTest.TearDown;
begin
if not FTestCase.FIsClassMethod then
begin
FObjectForTesting.AsObject.Free;
end;
end;
class function TParameterizedTest.SmartJoin(const Separator: string;
Values: TStringDynArray): string;
begin
if Values[low(Values)].Equals(string.Empty) then
Delete(Values, low(Values), 1);
Result := string.Join(Separator, Values);
end;
procedure TParameterizedTest.TestMethod;
var
LRttiContext: TRttiContext;
LRttiType: TRttiType;
LInvokedMethodResult: TValue;
LTestParamsValuesString: string;
begin
// Invoke RTTI
LRttiContext := TRttiContext.Create;
try
LRttiType := LRttiContext.GetType(FClassToTest);
// Reconstruct the function call string
LTestParamsValuesString := string.Empty;
for LInvokedMethodResult in FTestCase.FTestParams do
LTestParamsValuesString :=
SmartJoin(', ', [LTestParamsValuesString, LInvokedMethodResult.ToString]);
// Get a method result
if FTestCase.FIsClassMethod then
LInvokedMethodResult := TPtMethodInvoker.RttiMethodInvokeEx(FMethodName, LRttiType,
LRttiType.AsInstance.MetaclassType, FTestCase.FTestParams, csIsClassMethod)
else
LInvokedMethodResult := TPtMethodInvoker.RttiMethodInvokeEx(FMethodName, LRttiType,
FObjectForTesting.AsObject, FTestCase.FTestParams, csIsNotClassMethod);
// Validate a result
CheckTrue(FTestCase.FExpectedResult.Equals(LInvokedMethodResult),
'In method ' + FMethodName + ' with arguments (' + LTestParamsValuesString + ')' +
' expected result ' + FTestCase.FExpectedResult.ToString + ', but received ' +
LInvokedMethodResult.ToString);
finally
// Free RTTI
LRttiContext.Free;
end;
end;
end.
|
unit TiTan;
interface
{TitanEngine Delphi SDK - 2.0.3}
{http://www.reversinglabs.com/}
{Types}
type
PE32Structure = ^PE_32_STRUCT;
PE_32_STRUCT = packed record
PE32Offset : LongInt;
ImageBase : LongInt;
OriginalEntryPoint : LongInt;
NtSizeOfImage : LongInt;
NtSizeOfHeaders : LongInt;
SizeOfOptionalHeaders : SmallInt;
FileAlignment : LongInt;
SectionAligment : LongInt;
ImportTableAddress : LongInt;
ImportTableSize : LongInt;
ResourceTableAddress : LongInt;
ResourceTableSize : LongInt;
ExportTableAddress : LongInt;
ExportTableSize : LongInt;
TLSTableAddress : LongInt;
TLSTableSize : LongInt;
RelocationTableAddress : LongInt;
RelocationTableSize : LongInt;
TimeDateStamp : LongInt;
SectionNumber : SmallInt;
CheckSum : LongInt;
SubSystem : SmallInt;
Characteristics : SmallInt;
NumberOfRvaAndSizes : LongInt;
end;
FileStatusInfo = ^FILE_STATUS_INFO;
FILE_STATUS_INFO = packed record
OveralEvaluation : BYTE;
EvaluationTerminatedByException : boolean;
FileIs64Bit : boolean;
FileIsDLL : boolean;
FileIsConsole : boolean;
MissingDependencies : boolean;
MissingDeclaredAPIs : boolean;
SignatureMZ : BYTE;
SignaturePE : BYTE;
EntryPoint : BYTE;
ImageBase : BYTE;
SizeOfImage : BYTE;
FileAlignment : BYTE;
SectionAlignment : BYTE;
ExportTable : BYTE;
RelocationTable : BYTE;
ImportTable : BYTE;
ImportTableSection : BYTE;
ImportTableData : BYTE;
IATTable : BYTE;
TLSTable : BYTE;
LoadConfigTable : BYTE;
BoundImportTable : BYTE;
COMHeaderTable : BYTE;
ResourceTable : BYTE;
ResourceData : BYTE;
SectionTable : BYTE;
end;
FileFixInfo = ^FILE_FIX_INFO;
FILE_FIX_INFO = packed record
OveralEvaluation : BYTE;
FixingTerminatedByException : boolean;
FileFixPerformed : boolean;
StrippedRelocation : boolean;
DontFixRelocations : boolean;
OriginalRelocationTableAddress : LongInt;
OriginalRelocationTableSize : LongInt;
StrippedExports : boolean;
DontFixExports : boolean;
OriginalExportTableAddress : LongInt;
OriginalExportTableSize : LongInt;
StrippedResources : boolean;
DontFixResources : boolean;
OriginalResourceTableAddress : LongInt;
OriginalResourceTableSize : LongInt;
StrippedTLS : boolean;
DontFixTLS : boolean;
OriginalTLSTableAddress : LongInt;
OriginalTLSTableSize : LongInt;
StrippedLoadConfig : boolean;
DontFixLoadConfig : boolean;
OriginalLoadConfigTableAddress : LongInt;
OriginalLoadConfigTableSize : LongInt;
StrippedBoundImports : boolean;
DontFixBoundImports : boolean;
OriginalBoundImportTableAddress : LongInt;
OriginalBoundImportTableSize : LongInt;
StrippedIAT : boolean;
DontFixIAT : boolean;
OriginalImportAddressTableAddress : LongInt;
OriginalImportAddressTableSize : LongInt;
StrippedCOM : boolean;
DontFixCOM : boolean;
OriginalCOMTableAddress : LongInt;
OriginalCOMTableSize : LongInt;
end;
ImportEnumData = ^IMPORT_ENUM_DATA;
IMPORT_ENUM_DATA = packed record
NewDll : boolean;
NumberOfImports : LongInt;
ImageBase : LongInt;
BaseImportThunk : LongInt;
ImportThunk : LongInt;
APIName : PAnsiChar;
DLLName : PAnsiChar;
end;
ThreadItemData = ^THREAD_ITEM_DATA;
THREAD_ITEM_DATA = packed record
hThread : THandle;
dwThreadId : LongInt;
ThreadStartAddress : LongInt;
ThreadLocalBase : LongInt;
end;
LibraryItemData = ^LIBRARY_ITEM_DATA;
LIBRARY_ITEM_DATA = packed record
hFile : THandle;
BaseOfDll : Pointer;
hFileMapping : THandle;
hFileMappingView : Pointer;
szLibraryPath:array[1..260] of AnsiChar;
szLibraryName:array[1..260] of AnsiChar;
end;
ProcessItemData = ^PROCESS_ITEM_DATA;
PROCESS_ITEM_DATA = packed record
hProcess : THandle;
dwProcessId : LongInt;
hThread : THandle;
dwThreadId : LongInt;
hFile : THandle;
BaseOfImage : Pointer;
ThreadStartAddress : Pointer;
ThreadLocalBase : Pointer;
end;
HandlerArray = ^HANDLER_ARRAY;
HANDLER_ARRAY = packed record
ProcessId : LongInt;
hHandle : THandle;
end;
HookEntry = ^HOOK_ENTRY;
HOOK_ENTRY = packed record
IATHook : boolean;
HookType : BYTE;
HookSize : LongInt;
HookAddress : Pointer;
RedirectionAddress : Pointer;
HookBytes:array[1..14] of BYTE;
OriginalBytes:array[1..14] of BYTE;
IATHookModuleBase : Pointer;
IATHookNameHash : LongInt;
HookIsEnabled : boolean;
HookIsRemote : boolean;
PatchedEntry : Pointer;
RelocationInfo:array[1..7] of LongInt;
RelocationCount : LongInt;
end;
PluginInformation = ^PLUGIN_INFORMATION;
PLUGIN_INFORMATION = packed record
PluginName:array[1..64] of AnsiChar;
PluginMajorVersion : LongInt;
PluginMinorVersion : LongInt;
PluginBaseAddress : LongInt;
TitanDebuggingCallBack : Pointer;
TitanRegisterPlugin : Pointer;
TitanReleasePlugin : Pointer;
TitanResetPlugin : Pointer;
PluginDisabled : boolean;
end;
const
{Registers}
UE_EAX = 1;
UE_EBX = 2;
UE_ECX = 3;
UE_EDX = 4;
UE_EDI = 5;
UE_ESI = 6;
UE_EBP = 7;
UE_ESP = 8;
UE_EIP = 9;
UE_EFLAGS = 10;
UE_DR0 = 11;
UE_DR1 = 12;
UE_DR2 = 13;
UE_DR3 = 14;
UE_DR6 = 15;
UE_DR7 = 16;
UE_CIP = 35;
UE_CSP = 36;
UE_SEG_GS = 37;
UE_SEG_FS = 38;
UE_SEG_ES = 39;
UE_SEG_DS = 40;
UE_SEG_CS = 41;
UE_SEG_SS = 42;
{Constants}
UE_PE_OFFSET = 0;
UE_IMAGEBASE = 1;
UE_OEP = 2;
UE_SIZEOFIMAGE = 3;
UE_SIZEOFHEADERS = 4;
UE_SIZEOFOPTIONALHEADER = 5;
UE_SECTIONALIGNMENT = 6;
UE_IMPORTTABLEADDRESS = 7;
UE_IMPORTTABLESIZE = 8;
UE_RESOURCETABLEADDRESS = 9;
UE_RESOURCETABLESIZE = 10;
UE_EXPORTTABLEADDRESS = 11;
UE_EXPORTTABLESIZE = 12;
UE_TLSTABLEADDRESS = 13;
UE_TLSTABLESIZE = 14;
UE_RELOCATIONTABLEADDRESS = 15;
UE_RELOCATIONTABLESIZE = 16;
UE_TIMEDATESTAMP = 17;
UE_SECTIONNUMBER = 18;
UE_CHECKSUM = 19;
UE_SUBSYSTEM = 20;
UE_CHARACTERISTICS = 21;
UE_NUMBEROFRVAANDSIZES = 22;
UE_SECTIONNAME = 23;
UE_SECTIONVIRTUALOFFSET = 24;
UE_SECTIONVIRTUALSIZE = 25;
UE_SECTIONRAWOFFSET = 26;
UE_SECTIONRAWSIZE = 27;
UE_SECTIONFLAGS = 28;
UE_CH_BREAKPOINT = 1;
UE_CH_SINGLESTEP = 2;
UE_CH_ACCESSVIOLATION = 3;
UE_CH_ILLEGALINSTRUCTION = 4;
UE_CH_NONCONTINUABLEEXCEPTION = 5;
UE_CH_ARRAYBOUNDSEXCEPTION = 6;
UE_CH_FLOATDENORMALOPERAND = 7;
UE_CH_FLOATDEVIDEBYZERO = 8;
UE_CH_INTEGERDEVIDEBYZERO = 9;
UE_CH_INTEGEROVERFLOW = 10;
UE_CH_PRIVILEGEDINSTRUCTION = 11;
UE_CH_PAGEGUARD = 12;
UE_CH_EVERYTHINGELSE = 13;
UE_CH_CREATETHREAD = 14;
UE_CH_EXITTHREAD = 15;
UE_CH_CREATEPROCESS = 16;
UE_CH_EXITPROCESS = 17;
UE_CH_LOADDLL = 18;
UE_CH_UNLOADDLL = 19;
UE_CH_OUTPUTDEBUGSTRING = 20;
UE_FUNCTION_STDCALL = 1;
UE_FUNCTION_CCALL = 2;
UE_FUNCTION_FASTCALL = 3;
UE_FUNCTION_STDCALL_RET = 4;
UE_FUNCTION_CCALL_RET = 5;
UE_FUNCTION_FASTCALL_RET = 6;
UE_FUNCTION_STDCALL_CALL = 7;
UE_FUNCTION_CCALL_CALL = 8;
UE_FUNCTION_FASTCALL_CALL = 9;
UE_PARAMETER_BYTE = 0;
UE_PARAMETER_WORD = 1;
UE_PARAMETER_DWORD = 2;
UE_PARAMETER_QWORD = 3;
UE_PARAMETER_PTR_BYTE = 4;
UE_PARAMETER_PTR_WORD = 5;
UE_PARAMETER_PTR_DWORD = 6;
UE_PARAMETER_PTR_QWORD = 7;
UE_PARAMETER_STRING = 8;
UE_PARAMETER_UNICODE = 9;
UE_CMP_NOCONDITION = 0;
UE_CMP_EQUAL = 1;
UE_CMP_NOTEQUAL = 2;
UE_CMP_GREATER = 3;
UE_CMP_GREATEROREQUAL = 4;
UE_CMP_LOWER = 5;
UE_CMP_LOWEROREQUAL = 6;
UE_CMP_REG_EQUAL = 7;
UE_CMP_REG_NOTEQUAL = 8;
UE_CMP_REG_GREATER = 9;
UE_CMP_REG_GREATEROREQUAL = 10;
UE_CMP_REG_LOWER = 11;
UE_CMP_REG_LOWEROREQUAL = 12;
UE_CMP_ALWAYSFALSE = 13;
UE_OPTION_HANDLER_RETURN_HANDLECOUNT = 1;
UE_OPTION_HANDLER_RETURN_ACCESS = 2;
UE_OPTION_HANDLER_RETURN_FLAGS = 3;
UE_OPTION_HANDLER_RETURN_TYPENAME = 4;
UE_BREAKPOINT_INT3 = 1;
UE_BREAKPOINT_LONG_INT3 = 2;
UE_BREAKPOINT_UD2 = 3;
UE_BPXREMOVED = 0;
UE_BPXACTIVE = 1;
UE_BPXINACTIVE = 2;
UE_BREAKPOINT = 0;
UE_SINGLESHOOT = 1;
UE_HARDWARE = 2;
UE_MEMORY = 3;
UE_MEMORY_READ = 4;
UE_MEMORY_WRITE = 5;
UE_BREAKPOINT_TYPE_INT3 = $10000000;
UE_BREAKPOINT_TYPE_LONG_INT3 = $20000000;
UE_BREAKPOINT_TYPE_UD2 = $30000000;
UE_HARDWARE_EXECUTE = 4;
UE_HARDWARE_WRITE = 5;
UE_HARDWARE_READWRITE = 6;
UE_HARDWARE_SIZE_1 = 7;
UE_HARDWARE_SIZE_2 = 8;
UE_HARDWARE_SIZE_4 = 9;
UE_ON_LIB_LOAD = 1;
UE_ON_LIB_UNLOAD = 2;
UE_ON_LIB_ALL = 3;
UE_APISTART = 0;
UE_APIEND = 1;
UE_PLATFORM_x86 = 1;
UE_PLATFORM_x64 = 2;
UE_PLATFORM_ALL = 3;
UE_ACCESS_READ = 0;
UE_ACCESS_WRITE = 1;
UE_ACCESS_ALL = 2;
UE_HIDE_BASIC = 1;
UE_ENGINE_ALOW_MODULE_LOADING = 1;
UE_ENGINE_AUTOFIX_FORWARDERS = 2;
UE_ENGINE_PASS_ALL_EXCEPTIONS = 3;
UE_ENGINE_NO_CONSOLE_WINDOW = 4;
UE_ENGINE_BACKUP_FOR_CRITICAL_FUNCTIONS = 5;
UE_ENGINE_CALL_PLUGIN_CALLBACK = 6;
UE_ENGINE_RESET_CUSTOM_HANDLER = 7;
UE_ENGINE_CALL_PLUGIN_DEBUG_CALLBACK = 8;
UE_OPTION_REMOVEALL = 1;
UE_OPTION_DISABLEALL = 2;
UE_OPTION_REMOVEALLDISABLED = 3;
UE_OPTION_REMOVEALLENABLED = 4;
UE_STATIC_DECRYPTOR_XOR = 1;
UE_STATIC_DECRYPTOR_SUB = 2;
UE_STATIC_DECRYPTOR_ADD = 3;
UE_STATIC_DECRYPTOR_FOREWARD = 1;
UE_STATIC_DECRYPTOR_BACKWARD = 2;
UE_STATIC_KEY_SIZE_1 = 1;
UE_STATIC_KEY_SIZE_2 = 2;
UE_STATIC_KEY_SIZE_4 = 4;
UE_STATIC_KEY_SIZE_8 = 8;
UE_STATIC_APLIB = 1;
UE_STATIC_APLIB_DEPACK = 2;
UE_STATIC_LZMA = 3;
UE_STATIC_HASH_MD5 = 1;
UE_STATIC_HASH_SHA1 = 2;
UE_STATIC_HASH_CRC32 = 3;
UE_RESOURCE_LANGUAGE_ANY = -1;
UE_DEPTH_SURFACE = 0;
UE_DEPTH_DEEP = 1;
UE_UNPACKER_CONDITION_SEARCH_FROM_EP = 1;
UE_UNPACKER_CONDITION_LOADLIBRARY = 1;
UE_UNPACKER_CONDITION_GETPROCADDRESS = 2;
UE_UNPACKER_CONDITION_ENTRYPOINTBREAK = 3;
UE_UNPACKER_CONDITION_RELOCSNAPSHOT1 = 4;
UE_UNPACKER_CONDITION_RELOCSNAPSHOT2 = 5;
UE_FIELD_OK = 0;
UE_FIELD_BROKEN_NON_FIXABLE = 1;
UE_FIELD_BROKEN_NON_CRITICAL = 2;
UE_FIELD_BROKEN_FIXABLE_FOR_STATIC_USE = 3;
UE_FIELD_BROKEN_BUT_CAN_BE_EMULATED = 4;
UE_FILED_FIXABLE_NON_CRITICAL = 5;
UE_FILED_FIXABLE_CRITICAL = 6;
UE_FIELD_NOT_PRESET = 7;
UE_FIELD_NOT_PRESET_WARNING = 8;
UE_RESULT_FILE_OK = 10;
UE_RESULT_FILE_INVALID_BUT_FIXABLE = 11;
UE_RESULT_FILE_INVALID_AND_NON_FIXABLE = 12;
UE_RESULT_FILE_INVALID_FORMAT = 13;
UE_PLUGIN_CALL_REASON_PREDEBUG = 1;
UE_PLUGIN_CALL_REASON_EXCEPTION = 2;
UE_PLUGIN_CALL_REASON_POSTDEBUG = 3;
TEE_HOOK_NRM_JUMP = 1;
TEE_HOOK_NRM_CALL = 3;
TEE_HOOK_IAT = 5;
{TitanEngine.Dumper.functions}
function DumpProcess(hProcess:THandle; ImageBase:LongInt; szDumpFileName:PAnsiChar; EntryPoint:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'DumpProcess';
function DumpProcessEx(ProcessId:LongInt; ImageBase:LongInt; szDumpFileName:PAnsiChar; EntryPoint:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'DumpProcessEx';
function DumpMemory(hProcess:THandle; MemoryStart,MemorySize:LongInt; szDumpFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'DumpMemory';
function DumpMemoryEx(ProcessId:LongInt; MemoryStart,MemorySize:LongInt; szDumpFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'DumpMemoryEx';
function DumpRegions(hProcess:THandle; szDumpFolder:PAnsiChar; DumpAboveImageBaseOnly:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'DumpRegions';
function DumpRegionsEx(ProcessId:LongInt; szDumpFolder:PAnsiChar; DumpAboveImageBaseOnly:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'DumpRegionsEx';
function DumpModule(hProcess:THandle; ModuleBase:LongInt; szDumpFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'DumpModule';
function DumpModuleEx(ProcessId:LongInt; ModuleBase:LongInt; szDumpFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'DumpModuleEx';
function PastePEHeader(hProcess:THandle; ImageBase:LongInt; szDebuggedFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'PastePEHeader';
function ExtractSection(szFileName,szDumpFileName:PAnsiChar; SectionNumber:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'ExtractSection';
function ResortFileSections(szFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ResortFileSections';
function FindOverlay(szFileName:PAnsiChar; OverlayStart,OverlaySize:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'FindOverlay';
function ExtractOverlay(szFileName,szExtactedFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ExtractOverlay';
function AddOverlay(szFileName,szOverlayFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'AddOverlay';
function CopyOverlay(szInFileName,szOutFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'CopyOverlay';
function RemoveOverlay(szFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'RemoveOverlay';
function MakeAllSectionsRWE(szFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'MakeAllSectionsRWE';
function AddNewSectionEx(szFileName,szSectionName:PAnsiChar; SectionSize,SectionAttributes:LongInt; SectionContent:Pointer; ContentSize:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'AddNewSectionEx';
function AddNewSection(szFileName,szSectionName:PAnsiChar; SectionSize:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'AddNewSection';
function ResizeLastSection(szFileName:PAnsiChar; NumberOfExpandBytes:LongInt; AlignResizeData:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'ResizeLastSection';
procedure SetSharedOverlay(szFileName:PAnsiChar); stdcall; external 'TitanEngine.dll' name 'SetSharedOverlay';
function GetSharedOverlay():PAnsiChar; stdcall; external 'TitanEngine.dll' name 'GetSharedOverlay';
function DeleteLastSection(szFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'DeleteLastSection';
function DeleteLastSectionEx(szFileName:PAnsiChar; NumberOfSections:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'DeleteLastSectionEx';
function GetPE32DataFromMappedFile(FileMapVA,WhichSection,WhichData:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'GetPE32DataFromMappedFile';
function GetPE32Data(szFileName:PAnsiChar; WhichSection,WhichData:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'GetPE32Data';
function GetPE32DataFromMappedFileEx(FileMapVA:LongInt; DataStorage:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'GetPE32DataFromMappedFileEx';
function GetPE32DataEx(szFileName:PAnsiChar; DataStorage:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'GetPE32DataEx';
function SetPE32DataForMappedFile(FileMapVA,WhichSection,WhichData,NewDataValue:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'SetPE32DataForMappedFile';
function SetPE32Data(szFileName:PAnsiChar; WhichSection,WhichData,NewDataValue:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'SetPE32Data';
function SetPE32DataForMappedFileEx(szFileName:PAnsiChar; DataStorage:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'SetPE32DataForMappedFileEx';
function SetPE32DataEx(szFileName:PAnsiChar; DataStorage:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'SetPE32DataEx';
function GetPE32SectionNumberFromVA(FileMapVA,AddressToConvert:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'GetPE32SectionNumberFromVA';
function ConvertVAtoFileOffset(FileMapVA,AddressToConvert:LongInt; ReturnType:boolean):LongInt; stdcall; external 'TitanEngine.dll' name 'ConvertVAtoFileOffset';
function ConvertVAtoFileOffsetEx(FileMapVA,FileSize,ImageBase,AddressToConvert:LongInt; AddressIsRVA,ReturnType:boolean):LongInt; stdcall; external 'TitanEngine.dll' name 'ConvertVAtoFileOffsetEx';
function ConvertFileOffsetToVA(FileMapVA,AddressToConvert:LongInt; ReturnType:boolean):LongInt; stdcall; external 'TitanEngine.dll' name 'ConvertFileOffsetToVA';
function ConvertFileOffsetToVAEx(FileMapVA,FileSize,ImageBase,AddressToConvert:LongInt; ReturnType:boolean):LongInt; stdcall; external 'TitanEngine.dll' name 'ConvertFileOffsetToVAEx';
{TitanEngine.Realigner.functions}
function FixHeaderCheckSum(szFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'FixHeaderCheckSum';
function RealignPE(FileMapVA,FileSize,RealingMode:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'RealignPE';
function RealignPEEx(szFileName:PAnsiChar; RealingFileSize,ForcedFileAlignment:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'RealignPEEx';
function WipeSection(szFileName:PAnsiChar; WipeSectionNumber:LongInt; RemovePhysically:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'WipeSection';
function IsPE32FileValidEx(szFileName:PAnsiChar; CheckDepth:LongInt; FileStatusInfo:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'IsPE32FileValidEx';
function FixBrokenPE32FileEx(szFileName:PAnsiChar; FileStatusInfo,FileFixInfo:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'FixBrokenPE32FileEx';
function IsFileDLL(szFileName:PAnsiChar; FileMapVA:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'IsFileDLL';
{TitanEngine.Hider.functions}
function GetPEBLocation(hProcess:THandle):LongInt; stdcall; external 'TitanEngine.dll' name 'GetPEBLocation';
function HideDebugger(hProcess:THandle; PatchAPILevel:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'HideDebugger';
function UnHideDebugger(hProcess:THandle; PatchAPILevel:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'UnHideDebugger';
{TitanEngine.Relocater.functions}
procedure RelocaterCleanup(); stdcall; external 'TitanEngine.dll' name 'RelocaterCleanup';
procedure RelocaterInit(MemorySize,OldImageBase,NewImageBase:LongInt); stdcall; external 'TitanEngine.dll' name 'RelocaterInit';
procedure RelocaterAddNewRelocation(hProcess:THandle; RelocateAddress,RelocateState:LongInt); stdcall; external 'TitanEngine.dll' name 'RelocaterAddNewRelocation';
function RelocaterEstimatedSize():LongInt; stdcall; external 'TitanEngine.dll' name 'RelocaterEstimatedSize';
function RelocaterExportRelocation(StorePlace,StorePlaceRVA,FileMapVA:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'RelocaterExportRelocation';
function RelocaterExportRelocationEx(szFileName,szSectionName:PAnsiChar; StorePlace,StorePlaceRVA:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'RelocaterExportRelocationEx';
function RelocaterGrabRelocationTable(hProcess:THandle; MemoryStart,MemorySize:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'RelocaterGrabRelocationTable';
function RelocaterGrabRelocationTableEx(hProcess:THandle; MemoryStart,MemorySize,NtSizeOfImage:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'RelocaterGrabRelocationTableEx';
function RelocaterMakeSnapshot(hProcess:THandle; szSaveFileName:PAnsiChar; MemoryStart,MemorySize:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'RelocaterMakeSnapshot';
function RelocaterCompareTwoSnapshots(hProcess:THandle; LoadedImageBase,NtSizeOfImage:LongInt; szDumpFile1,szDumpFile2:PAnsiChar; MemStart:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'RelocaterCompareTwoSnapshots';
function RelocaterChangeFileBase(szFileName:PAnsiChar; NewImageBase:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'RelocaterChangeFileBase';
function RelocaterRelocateMemoryBlock(FileMapVA,MemoryLocation:LongInt; RelocateMemory:Pointer; RelocateMemorySize,CurrentLoadedBase,RelocateBase:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'RelocaterRelocateMemoryBlock';
function RelocaterWipeRelocationTable(szFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'RelocaterWipeRelocationTable';
{TitanEngine.Resourcer.functions}
function ResourcerLoadFileForResourceUse(szFileName:PAnsiChar):LongInt; stdcall; external 'TitanEngine.dll' name 'ResourcerLoadFileForResourceUse';
function ResourcerFreeLoadedFile(LoadedFileBase:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'ResourcerFreeLoadedFile';
function ResourcerExtractResourceFromFileEx(FileMapVA:LongInt; szResourceType,szResourceName,szExtractedFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ResourcerExtractResourceFromFileEx';
function ResourcerExtractResourceFromFile(szFileName,szResourceType,szResourceName,szExtractedFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ResourcerExtractResourceFromFile';
function ResourcerFindResource(szFileName,szResourceType:PAnsiChar; ResourceType:LongInt; szResourceName:PAnsiChar; ResourceName,ResourceLanguage:LongInt; pResourceData,pResourceSize:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'ResourcerFindResource';
function ResourcerFindResourceEx(FileMapVA,FileSize:LongInt; szResourceType:PAnsiChar; ResourceType:LongInt; szResourceName:PAnsiChar; ResourceName,ResourceLanguage:LongInt; pResourceData,pResourceSize:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'ResourcerFindResourceEx';
procedure ResourcerEnumerateResource(szFileName:PAnsiChar; CallBack:LongInt); stdcall; external 'TitanEngine.dll' name 'ResourcerEnumerateResource';
procedure ResourcerEnumerateResourceEx(FileMapVA,FileSize:LongInt; CallBack:LongInt); stdcall; external 'TitanEngine.dll' name 'ResourcerEnumerateResourceEx';
{TitanEngine.FindOEP.functions}
procedure FindOEPInit(); stdcall; external 'TitanEngine.dll' name 'FindOEPInit';
procedure FindOEPGenerically(szFileName:PAnsiChar; TraceInitCallBack,CallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'FindOEPGenerically';
{TitanEngine.Threader.functions}
function ThreaderImportRunningThreadData(ProcessId:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderImportRunningThreadData';
function ThreaderGetThreadInfo(hThread:THandle; ThreadId:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'ThreaderGetThreadInfo';
procedure ThreaderEnumThreadInfo(EnumCallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'ThreaderGetThreadInfo';
function ThreaderPauseThread(hThread:THandle):boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderPauseThread';
function ThreaderResumeThread(hThread:THandle):boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderResumeThread';
function ThreaderTerminateThread(hThread:THandle; ThreadExitCode:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderTerminateThread';
function ThreaderPauseAllThreads(LeaveMainRunning:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderPauseAllThreads';
function ThreaderResumeAllThreads(LeaveMainPaused:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderResumeAllThreads';
function ThreaderPauseProcess():boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderPauseProcess';
function ThreaderResumeProcess():boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderResumeProcess';
function ThreaderCreateRemoteThread(ThreadStartAddress:LongInt; AutoCloseTheHandle:boolean; ThreadPassParameter,ThreadId:Pointer):LongInt; stdcall; external 'TitanEngine.dll' name 'ThreaderCreateRemoteThread';
function ThreaderInjectAndExecuteCode(InjectCode:Pointer; StartDelta,InjectSize:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderInjectAndExecuteCode';
function ThreaderCreateRemoteThreadEx(hProcess:THandle; ThreadStartAddress:LongInt; AutoCloseTheHandle:boolean; ThreadPassParameter,ThreadId:Pointer):LongInt; stdcall; external 'TitanEngine.dll' name 'ThreaderCreateRemoteThreadEx';
function ThreaderInjectAndExecuteCodeEx(hProcess:THandle; InjectCode:Pointer; StartDelta,InjectSize:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderInjectAndExecuteCodeEx';
procedure ThreaderSetCallBackForNextExitThreadEvent(exitThreadCallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'ThreaderSetCallBackForNextExitThreadEvent';
function ThreaderIsThreadStillRunning(hThread:THandle):boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderIsThreadStillRunning';
function ThreaderIsThreadActive(hThread:THandle):boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderIsThreadActive';
function ThreaderIsAnyThreadActive():boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderIsAnyThreadActive';
function ThreaderExecuteOnlyInjectedThreads():boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderExecuteOnlyInjectedThreads';
function ThreaderGetOpenHandleForThread(ThreadId:LongInt):THandle; stdcall; external 'TitanEngine.dll' name 'ThreaderGetOpenHandleForThread';
function ThreaderGetThreadData():Pointer; stdcall; external 'TitanEngine.dll' name 'ThreaderGetThreadData';
function ThreaderIsExceptionInMainThread():boolean; stdcall; external 'TitanEngine.dll' name 'ThreaderIsExceptionInMainThread';
{TitanEngine.Debugger.functions}
function StaticDisassembleEx(DisassmStart:LongInt; DisassmAddress:Pointer):PAnsiChar; stdcall; external 'TitanEngine.dll' name 'StaticDisassembleEx';
function StaticDisassemble(DisassmAddress:Pointer):PAnsiChar; stdcall; external 'TitanEngine.dll' name 'StaticDisassemble';
function DisassembleEx(hProcess:THandle; DisassmAddress:Pointer):PAnsiChar; stdcall; external 'TitanEngine.dll' name 'DisassembleEx';
function Disassemble(DisassmAddress:Pointer):PAnsiChar; stdcall; external 'TitanEngine.dll' name 'Disassemble';
function StaticLengthDisassemble(DisassmAddress:Pointer):LongInt; stdcall; external 'TitanEngine.dll' name 'StaticLengthDisassemble';
function LengthDisassembleEx(hProcess:THandle; DisassmAddress:Pointer):LongInt; stdcall; external 'TitanEngine.dll' name 'LengthDisassembleEx';
function LengthDisassemble(DisassmAddress:Pointer):LongInt; stdcall; external 'TitanEngine.dll' name 'LengthDisassemble';
function InitDebug(szFileName,szCommandLine,szCurrentFolder:PAnsiChar): Pointer; stdcall; external 'TitanEngine.dll' name 'InitDebug';
function InitDebugEx(szFileName,szCommandLine,szCurrentFolder:PAnsiChar; EntryCallBack:Pointer): Pointer; stdcall; external 'TitanEngine.dll' name 'InitDebugEx';
function InitDLLDebug(szFileName:PAnsiChar; ReserveModuleBase:boolean; szCommandLine,szCurrentFolder:PAnsiChar; EntryCallBack:Pointer): Pointer; stdcall; external 'TitanEngine.dll' name 'InitDLLDebug';
function StopDebug(): Boolean; stdcall; external 'TitanEngine.dll' name 'StopDebug';
procedure SetBPXOptions(DefaultBreakPointType:LongInt); stdcall; external 'TitanEngine.dll' name 'SetBPXOptions';
function IsBPXEnabled(bpxAddress:LongInt): boolean; stdcall; external 'TitanEngine.dll' name 'IsBPXEnabled';
function EnableBPX(bpxAddress:LongInt): boolean; stdcall; external 'TitanEngine.dll' name 'EnableBPX';
function DisableBPX(bpxAddress:LongInt): boolean; stdcall; external 'TitanEngine.dll' name 'DisableBPX';
function SetBPX(bpxAddress,bpxType:LongInt; bpxCallBack:Pointer): boolean; stdcall; external 'TitanEngine.dll' name 'SetBPX';
function SetBPXEx(bpxAddress,bpxType,NumberOfExecution,CmpRegister,CmpCondition,CmpValue:LongInt; bpxCallBack,bpxCompareCallBack,bpxRemoveCallBack:Pointer): boolean; stdcall; external 'TitanEngine.dll' name 'SetBPXEx';
function DeleteBPX(bpxAddress:LongInt): boolean; stdcall; external 'TitanEngine.dll' name 'DeleteBPX';
function SafeDeleteBPX(bpxAddress:LongInt): boolean; stdcall; external 'TitanEngine.dll' name 'SafeDeleteBPX';
function SetAPIBreakPoint(szDLLName,szAPIName:PAnsiChar; bpxType,bpxPlace:LongInt; bpxCallBack:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'SetAPIBreakPoint';
function DeleteAPIBreakPoint(szDLLName,szAPIName:PAnsiChar; bpxPlace:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'DeleteAPIBreakPoint';
function SafeDeleteAPIBreakPoint(szDLLName,szAPIName:PAnsiChar; bpxPlace:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'SafeDeleteAPIBreakPoint';
function SetMemoryBPX(MemoryStart,SizeOfMemory:LongInt; bpxCallBack:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'SetMemoryBPX';
function SetMemoryBPXEx(MemoryStart,SizeOfMemory,BreakPointType:LongInt; RestoreOnHit:boolean; bpxCallBack:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'SetMemoryBPXEx';
function RemoveMemoryBPX(MemoryStart,SizeOfMemory:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'RemoveMemoryBPX';
function GetContextFPUDataEx(hActiveThread:THandle; FPUSaveArea:Pointer): boolean; stdcall; external 'TitanEngine.dll' name 'GetContextFPUDataEx';
function GetContextDataEx(hActiveThread:THandle; IndexOfRegister:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'GetContextDataEx';
function GetContextData(IndexOfRegister:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'GetContextData';
function SetContextFPUDataEx(hActiveThread:THandle; FPUSaveArea:Pointer): boolean; stdcall; external 'TitanEngine.dll' name 'SetContextFPUDataEx';
function SetContextDataEx(hActiveThread:THandle; IndexOfRegister,NewRegisterValue:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'SetContextDataEx';
function SetContextData(IndexOfRegister,NewRegisterValue:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'SetContextData';
procedure ClearExceptionNumber(); stdcall; external 'TitanEngine.dll' name 'ClearExceptionNumber';
function CurrentExceptionNumber(): LongInt; stdcall; external 'TitanEngine.dll' name 'CurrentExceptionNumber';
function MatchPatternEx(hProcess:THandle; MemoryToCheck,SizeOfMemoryToCheck:LongInt; PatternToMatch:Pointer; SizeOfPatternToMatch:LongInt; WildCard:Pointer): boolean; stdcall; external 'TitanEngine.dll' name 'MatchPatternEx';
function MatchPattern(MemoryToCheck,SizeOfMemoryToCheck:LongInt; PatternToMatch:Pointer; SizeOfPatternToMatch:LongInt; WildCard:Pointer): boolean; stdcall; external 'TitanEngine.dll' name 'MatchPattern';
function FindEx(hProcess:THandle; MemoryStart,MemorySize:LongInt; SearchPattern:Pointer; PatternSize:LongInt; WildCard:Pointer): LongInt; stdcall; external 'TitanEngine.dll' name 'FindEx';
function Find(MemoryStart,MemorySize:LongInt; SearchPattern:Pointer; PatternSize:LongInt; WildCard:Pointer): LongInt; stdcall; external 'TitanEngine.dll' name 'Find';
function FillEx(hProcess:THandle; MemoryStart,MemorySize:LongInt; FillByte:Pointer): boolean; stdcall; external 'TitanEngine.dll' name 'FillEx';
function Fill(MemoryStart,MemorySize:LongInt; FillByte:Pointer): boolean; stdcall; external 'TitanEngine.dll' name 'Fill';
function PatchEx(hProcess:THandle; MemoryStart,MemorySize:LongInt; ReplacePattern:Pointer; ReplaceSize:LongInt; AppendNOP,PrependNOP:boolean): boolean; stdcall; external 'TitanEngine.dll' name 'PatchEx';
function Patch(MemoryStart,MemorySize:LongInt; ReplacePattern:Pointer; ReplaceSize:LongInt; AppendNOP,PrependNOP:boolean): boolean; stdcall; external 'TitanEngine.dll' name 'Patch';
function ReplaceEx(hProcess:THandle; MemoryStart,MemorySize:LongInt; SearchPattern:Pointer; PatternSize,NumberOfRepetitions:LongInt; ReplacePattern:Pointer; ReplaceSize:LongInt; WildCard:Pointer): boolean; stdcall; external 'TitanEngine.dll' name 'ReplaceEx';
function Replace(MemoryStart,MemorySize:LongInt; SearchPattern:Pointer; PatternSize,NumberOfRepetitions:LongInt; ReplacePattern:Pointer; ReplaceSize:LongInt; WildCard:Pointer): boolean; stdcall; external 'TitanEngine.dll' name 'Replace';
function GetDebugData(): Pointer; stdcall; external 'TitanEngine.dll' name 'GetDebugData';
function GetTerminationData(): Pointer; stdcall; external 'TitanEngine.dll' name 'GetTerminationData';
function GetExitCode():LongInt; stdcall; external 'TitanEngine.dll' name 'GetExitCode';
function GetDebuggedDLLBaseAddress(): LongInt; stdcall; external 'TitanEngine.dll' name 'GetDebuggedDLLBaseAddress';
function GetDebuggedFileBaseAddress(): LongInt; stdcall; external 'TitanEngine.dll' name 'GetDebuggedFileBaseAddress';
function GetRemoteString(hProcess:THandle; StringAddress:LongInt; StringStorage:Pointer; MaximumStringSize:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'GetRemoteString';
function GetFunctionParameter(hProcess:THandle; FunctionType,ParameterNumber,ParameterType:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'GetFunctionParameter';
function GetJumpDestinationEx(hProcess:THandle; InstructionAddress:LongInt; JustJumps:boolean): LongInt; stdcall; external 'TitanEngine.dll' name 'GetJumpDestinationEx';
function GetJumpDestination(hProcess:THandle; InstructionAddress:LongInt; JustJumps:boolean): LongInt; stdcall; external 'TitanEngine.dll' name 'GetJumpDestination';
function IsJumpGoingToExecuteEx(hProcess,hThread:THandle; InstructionAddress,RegFlags:LongInt): boolean; stdcall; external 'TitanEngine.dll' name 'IsJumpGoingToExecuteEx';
function IsJumpGoingToExecute(): boolean; stdcall; external 'TitanEngine.dll' name 'IsJumpGoingToExecute';
procedure SetCustomHandler(WhichException:LongInt; CallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'SetCustomHandler';
procedure ForceClose(); stdcall; external 'TitanEngine.dll' name 'ForceClose';
procedure StepInto(traceCallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'StepInto';
procedure StepOver(traceCallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'StepOver';
procedure SingleStep(StepCount:LongInt; StepCallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'SingleStep';
function GetUnusedHardwareBreakPointRegister(RegisterIndex:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'GetUnusedHardwareBreakPointRegister';
function SetHardwareBreakPointEx(hActiveThread:THandle; bpxAddress,IndexOfRegister,bpxType,bpxSize:LongInt; bpxCallBack,IndexOfSelectedRegister:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'SetHardwareBreakPointEx';
function SetHardwareBreakPoint(bpxAddress,IndexOfRegister,bpxType,bpxSize:LongInt; bpxCallBack:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'SetHardwareBreakPoint';
function DeleteHardwareBreakPoint(IndexOfRegister:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'DeleteHardwareBreakPoint';
function RemoveAllBreakPoints(RemoveOption:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'RemoveAllBreakPoints';
function GetProcessInformation(): Pointer; stdcall; external 'TitanEngine.dll' name 'GetProcessInformation';
function GetStartupInformation(): Pointer; stdcall; external 'TitanEngine.dll' name 'GetStartupInformation';
procedure DebugLoop(); stdcall; external 'TitanEngine.dll' name 'DebugLoop';
procedure SetDebugLoopTimeOut(TimeOut:LongInt); stdcall; external 'TitanEngine.dll' name 'SetDebugLoopTimeOut';
procedure SetNextDbgContinueStatus(SetDbgCode:LongInt); stdcall; external 'TitanEngine.dll' name 'SetNextDbgContinueStatus';
function AttachDebugger(ProcessId:LongInt; KillOnExit:Boolean; DebugInfo,CallBack:Pointer): Pointer; stdcall; external 'TitanEngine.dll' name 'AttachDebugger';
function DetachDebugger(ProcessId:LongInt): Pointer; stdcall; external 'TitanEngine.dll' name 'DetachDebugger';
function DetachDebuggerEx(ProcessId:LongInt): Pointer; stdcall; external 'TitanEngine.dll' name 'DetachDebuggerEx';
function DebugLoopEx(TimeOut:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'DebugLoopEx';
procedure AutoDebugEx(szFileName:PAnsiChar; ReserveModuleBase:boolean; szCommandLine,szCurrentFolder:PAnsiChar; TimeOut:LongInt; EntryCallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'AutoDebugEx';
function IsFileBeingDebugged(): boolean; stdcall; external 'TitanEngine.dll' name 'IsFileBeingDebugged';
procedure SetErrorModel(DisplayErrorMessages:boolean); stdcall; external 'TitanEngine.dll' name 'SetErrorModel';
{TitanEngine.Importer.functions}
procedure ImporterCleanup(); stdcall; external 'TitanEngine.dll' name 'ImporterCleanup';
procedure ImporterSetImageBase(ImageBase:LongInt); stdcall; external 'TitanEngine.dll' name 'ImporterSetImageBase';
procedure ImporterSetUnknownDelta(DeltaAddress:LongInt); stdcall; external 'TitanEngine.dll' name 'ImporterSetUnknownDelta';
function ImporterGetCurrentDelta():LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetCurrentDelta';
procedure ImporterInit(MemorySize,ImageBase:LongInt); stdcall; external 'TitanEngine.dll' name 'ImporterInit';
procedure ImporterAddNewDll(DLLName:PAnsiChar; FirstThunk:LongInt); stdcall; external 'TitanEngine.dll' name 'ImporterAddNewDll';
procedure ImporterAddNewAPI(APIName:PAnsiChar; FirstThunk:LongInt); stdcall; external 'TitanEngine.dll' name 'ImporterAddNewAPI';
procedure ImporterAddNewOrdinalAPI(dwAPIName,FirstThunk:LongInt); stdcall; external 'TitanEngine.dll' name 'ImporterAddNewAPI';
function ImporterGetAddedDllCount(): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetAddedDllCount';
function ImporterGetAddedAPICount(): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetAddedAPICount';
function ImporterGetLastAddedDLLName(): PAnsiChar; stdcall; external 'TitanEngine.dll' name 'ImporterGetLastAddedDLLName';
procedure ImporterMoveIAT(); stdcall; external 'TitanEngine.dll' name 'ImporterMoveIAT';
function ImporterExportIAT(StorePlace,FileMap:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'ImporterExportIAT';
function ImporterEstimatedSize(): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterEstimatedSize';
function ImporterExportIATEx(szExportFileName,szSectionName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ImporterExportIATEx';
function ImporterFindAPIWriteLocation(szAPIName:PAnsiChar): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterFindAPIWriteLocation';
function ImporterFindOrdinalAPIWriteLocation(OrdinalNumber:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterFindOrdinalAPIWriteLocation';
function ImporterFindAPIByWriteLocation(APIWriteLocation:PAnsiChar): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterFindAPIByWriteLocation';
function ImporterFindDLLByWriteLocation(APIWriteLocation:PAnsiChar): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterFindDLLByWriteLocation';
function ImporterGetDLLName(APIAddress:LongInt): PAnsiChar; stdcall; external 'TitanEngine.dll' name 'ImporterGetDLLName';
function ImporterGetAPIName(APIAddress:LongInt): PAnsiChar; stdcall; external 'TitanEngine.dll' name 'ImporterGetAPIName';
function ImporterGetAPIOrdinalNumber(APIAddress:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetAPIOrdinalNumber';
function ImporterGetAPINameEx(APIAddress:LongInt; pDLLBases:Pointer): PAnsiChar; stdcall; external 'TitanEngine.dll' name 'ImporterGetAPINameEx';
function ImporterGetRemoteAPIAddress(hProcess:THandle; APIAddress:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetRemoteAPIAddress';
function ImporterGetRemoteAPIAddressEx(szDLLName,szAPIName:PAnsiChar): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetRemoteAPIAddressEx';
function ImporterGetLocalAPIAddress(hProcess:THandle; APIAddress:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetLocalAPIAddress';
function ImporterGetDLLNameFromDebugee(hProcess:THandle; APIAddress:LongInt): PAnsiChar; stdcall; external 'TitanEngine.dll' name 'ImporterGetDLLNameFromDebugee';
function ImporterGetAPINameFromDebugee(hProcess:THandle; APIAddress:LongInt): PAnsiChar; stdcall; external 'TitanEngine.dll' name 'ImporterGetAPINameFromDebugee';
function ImporterGetAPIOrdinalNumberFromDebugee(hProcess:THandle; APIAddress:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetAPIOrdinalNumberFromDebugee';
function ImporterGetDLLIndexEx(APIAddress:LongInt; pDLLBases:Pointer): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetDLLIndexEx';
function ImporterGetDLLIndex(hProcess:THandle; APIAddress:LongInt; pDLLBases:Pointer): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetDLLIndex';
function ImporterGetRemoteDLLBase(hProcess:THandle; LocalModuleBase:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetRemoteDLLBase';
function ImporterRelocateWriteLocation(AddValue:LongInt): boolean; stdcall; external 'TitanEngine.dll' name 'ImporterRelocateWriteLocation';
function ImporterIsForwardedAPI(hProcess:THandle; APIAddress:LongInt): boolean; stdcall; external 'TitanEngine.dll' name 'ImporterIsForwardedAPI';
function ImporterGetForwardedAPIName(hProcess:THandle; APIAddress:LongInt): PAnsiChar; stdcall; external 'TitanEngine.dll' name 'ImporterGetForwardedAPIName';
function ImporterGetForwardedDLLName(hProcess:THandle; APIAddress:LongInt): PAnsiChar; stdcall; external 'TitanEngine.dll' name 'ImporterGetForwardedDLLName';
function ImporterGetForwardedDLLIndex(hProcess:THandle; APIAddress:LongInt; pDLLBases:Pointer): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetForwardedDLLIndex';
function ImporterGetForwardedAPIOrdinalNumber(hProcess:THandle; APIAddress:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetForwardedAPIOrdinalNumber';
function ImporterGetNearestAPIAddress(hProcess:THandle; APIAddress:LongInt): LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterGetNearestAPIAddress';
function ImporterGetNearestAPIName(hProcess:THandle; APIAddress:LongInt): PAnsiChar; stdcall; external 'TitanEngine.dll' name 'ImporterGetNearestAPIName';
function ImporterCopyOriginalIAT(szOriginalFile,szDumpFile:PAnsiChar): boolean; stdcall; external 'TitanEngine.dll' name 'ImporterCopyOriginalIAT';
function ImporterLoadImportTable(szFileName:PAnsiChar): boolean; stdcall; external 'TitanEngine.dll' name 'ImporterLoadImportTable';
function ImporterMoveOriginalIAT(szOriginalFile,szDumpFile,szSectionName:PAnsiChar): boolean; stdcall; external 'TitanEngine.dll' name 'ImporterMoveOriginalIAT';
procedure ImporterAutoSearchIAT(pFileName:PAnsiChar;ImageBase,SearchStart,SearchSize:LongInt;pIATStart,pIATSize:Pointer); stdcall; external 'TitanEngine.dll' name 'ImporterAutoSearchIAT';
procedure ImporterAutoSearchIATEx(hProcess:LongInt;ImageBase,SearchStart,SearchSize:LongInt;pIATStart,pIATSize:Pointer); stdcall; external 'TitanEngine.dll' name 'ImporterAutoSearchIATEx';
procedure ImporterEnumAddedData(EnumCallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'ImporterEnumAddedData';
function ImporterAutoFixIAT(hProcess:LongInt;pFileName:PAnsiChar;ImageBase,SearchStart,SearchSize,SearchStep:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterAutoFixIAT';
function ImporterAutoFixIATEx(hProcess:LongInt;pFileName,szSectionName:PAnsiChar;DumpRunningProcess,RealignFile:boolean;EntryPointAddress,ImageBase,SearchStart,SearchSize,SearchStep:LongInt;TryAutoFix,FixEliminations:boolean;UnknownPointerFixCallback:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'ImporterAutoFixIATEx';
{TitanEngine.Hooks.functions}
function HooksSafeTransitionEx(HookAddressArray:Pointer; NumberOfHooks:LongInt; TransitionStart:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'HooksSafeTransitionEx';
function HooksSafeTransition(HookAddressArray:Pointer; TransitionStart:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'HooksSafeTransition';
function HooksIsAddressRedirected(HookAddressArray:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'HooksIsAddressRedirected';
function HooksGetTrampolineAddress(HookAddressArray:Pointer):Pointer; stdcall; external 'TitanEngine.dll' name 'HooksGetTrampolineAddress';
function HooksGetHookEntryDetails(HookAddressArray:Pointer):Pointer; stdcall; external 'TitanEngine.dll' name 'HooksGetHookEntryDetails';
function HooksInsertNewRedirection(HookAddressArray,RedirectTo:Pointer; HookType:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'HooksInsertNewRedirection';
function HooksInsertNewIATRedirectionEx(FileMapVA,LoadedModuleBase:LongInt; szHookFunction:PAnsiChar; RedirectTo:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'HooksInsertNewIATRedirectionEx';
function HooksInsertNewIATRedirection(szModuleName,szHookFunction:PAnsiChar; RedirectTo:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'HooksInsertNewIATRedirection';
function HooksRemoveRedirection(HookAddressArray:Pointer; RemoveAll:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'HooksRemoveRedirection';
function HooksRemoveRedirectionsForModule(ModuleBase:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'HooksRemoveRedirectionsForModule';
function HooksDisableRedirection(HookAddressArray:Pointer; DisableAll:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'HooksDisableRedirection';
function HooksDisableRedirectionsForModule(ModuleBase:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'HooksDisableRedirectionsForModule';
function HooksEnableRedirection(HookAddressArray:Pointer; EnableAll:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'HooksEnableRedirection';
function HooksEnableRedirectionsForModule(ModuleBase:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'HooksEnableRedirectionsForModule';
function HooksRemoveIATRedirection(szModuleName,szHookFunction:PAnsiChar; RemoveAll:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'HooksRemoveIATRedirection';
function HooksDisableIATRedirection(szModuleName,szHookFunction:PAnsiChar; DisableAll:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'HooksDisableIATRedirection';
function HooksEnableIATRedirection(szModuleName,szHookFunction:PAnsiChar; EnableAll:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'HooksEnableIATRedirection';
procedure HooksScanModuleMemory(ModuleBase:LongInt; CallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'HooksScanModuleMemory';
procedure HooksScanEntireProcessMemory(CallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'HooksScanEntireProcessMemory';
procedure HooksScanEntireProcessMemoryEx(); stdcall; external 'TitanEngine.dll' name 'HooksScanEntireProcessMemoryEx';
{TitanEngine.Tracer.functions}
procedure TracerInit(); stdcall; external 'TitanEngine.dll' name 'TracerInit';
function TracerLevel1(hProcess,APIAddress:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'TracerLevel1';
function HashTracerLevel1(hProcess,APIAddress,NumberOfInstructions:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'HashTracerLevel1';
function TracerDetectRedirection(hProcess,APIAddress:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'TracerDetectRedirection';
function TracerFixKnownRedirection(hProcess,APIAddress,RedirectionId:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'TracerFixKnownRedirection';
function TracerFixRedirectionViaImpRecPlugin(hProcess:LongInt;szPluginName:PAnsiChar;APIAddress:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'TracerFixRedirectionViaImpRecPlugin';
{TitanEngine.Exporter.functions}
procedure ExporterCleanup(); stdcall; external 'TitanEngine.dll' name 'ExporterCleanup';
procedure ExporterSetImageBase(ImageBase:LongInt); stdcall; external 'TitanEngine.dll' name 'ExporterSetImageBase';
procedure ExporterInit(MemorySize,ImageBase,ExportOrdinalBase:LongInt; szExportModuleName:PAnsiChar); stdcall; external 'TitanEngine.dll' name 'ExporterInit';
function ExporterAddNewExport(szExportName:PAnsiChar; ExportRelativeAddress:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'ExporterAddNewExport';
function ExporterAddNewOrdinalExport(OrdinalNumber,ExportRelativeAddress:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'ExporterAddNewOrdinalExport';
function ExporterGetAddedExportCount():LongInt; stdcall; external 'TitanEngine.dll' name 'ExporterGetAddedExportCount';
function ExporterEstimatedSize():LongInt; stdcall; external 'TitanEngine.dll' name 'ExporterEstimatedSize';
function ExporterBuildExportTable(StorePlace,FileMapVA:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'ExporterBuildExportTable';
function ExporterBuildExportTableEx(szExportFileName,szSectionName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ExporterBuildExportTableEx';
function ExporterLoadExportTable(szFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ExporterLoadExportTable';
{TitanEngine.Librarian.functions}
function LibrarianSetBreakPoint(szLibraryName:PAnsiChar; bpxType:LongInt; SingleShoot:boolean; bpxCallBack:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'LibrarianSetBreakPoint';
function LibrarianRemoveBreakPoint(szLibraryName:PAnsiChar; bpxType:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'LibrarianRemoveBreakPoint';
function LibrarianGetLibraryInfo(szLibraryName:PAnsiChar):Pointer; stdcall; external 'TitanEngine.dll' name 'LibrarianGetLibraryInfo';
function LibrarianGetLibraryInfoEx(BaseOfDll:Pointer):Pointer; stdcall; external 'TitanEngine.dll' name 'LibrarianGetLibraryInfoEx';
procedure LibrarianEnumLibraryInfo(BaseOfDll:Pointer); stdcall; external 'TitanEngine.dll' name 'LibrarianEnumLibraryInfo';
{TitanEngine.Process.functions}
function GetActiveProcessId(szImageName:PAnsiChar):LongInt; stdcall; external 'TitanEngine.dll' name 'GetActiveProcessId';
function EnumProcessesWithLibrary(szLibraryName:PAnsiChar; EnumFunction:Pointer):LongInt; stdcall; external 'TitanEngine.dll' name 'EnumProcessesWithLibrary';
{TitanEngine.TLSFixer.functions}
function TLSBreakOnCallBack(ArrayOfCallBacks:Pointer; NumberOfCallBacks:LongInt; bpxCallBack:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'TLSBreakOnCallBack';
function TLSGrabCallBackData(szFileName:PAnsiChar; ArrayOfCallBacks,NumberOfCallBacks:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'TLSGrabCallBackData';
function TLSBreakOnCallBackEx(szFileName:PAnsiChar; bpxCallBack:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'TLSBreakOnCallBackEx';
function TLSRemoveCallback(szFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'TLSRemoveCallback';
function TLSRemoveTable(szFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'TLSRemoveTable';
function TLSBackupData(szFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'TLSBackupData';
function TLSRestoreData():boolean; stdcall; external 'TitanEngine.dll' name 'TLSRestoreData';
function TLSBuildNewTable(FileMapVA,StorePlace,StorePlaceRVA:LongInt; ArrayOfCallBacks:Pointer; NumberOfCallBacks:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'TLSBuildNewTable';
function TLSBuildNewTableEx(szFileName,szSectionName:PAnsiChar; ArrayOfCallBacks:Pointer; NumberOfCallBacks:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'TLSBuildNewTableEx';
{TitanEngine.TranslateName.functions}
function TranslateNativeName(szNativeName:PAnsiChar):PAnsiChar; stdcall; external 'TitanEngine.dll' name 'TranslateNativeName';
{TitanEngine.Handler.functions}
function HandlerGetActiveHandleCount(ProcessId:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'HandlerGetActiveHandleCount';
function HandlerIsHandleOpen(ProcessId:LongInt; hHandle:THandle):boolean; stdcall; external 'TitanEngine.dll' name 'HandlerIsHandleOpen';
function HandlerGetHandleName(hProcess:THandle; ProcessId:LongInt; hHandle:THandle; TranslateName:boolean):PAnsiChar; stdcall; external 'TitanEngine.dll' name 'HandlerGetHandleName';
function HandlerEnumerateOpenHandles(ProcessId:LongInt; HandleBuffer:Pointer; MaxHandleCount:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'HandlerEnumerateOpenHandles';
function HandlerGetHandleDetails(hProcess:THandle; ProcessId:LongInt; hHandle:THandle; InformationReturn:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'HandlerGetHandleDetails';
function HandlerCloseRemoteHandle(ProcessId:LongInt; hHandle:THandle):boolean; stdcall; external 'TitanEngine.dll' name 'HandlerCloseRemoteHandle';
function HandlerEnumerateLockHandles(szFileOrFolderName:PAnsiChar; NameIsFolder,NameIsTranslated:boolean; HandleDataBuffer:Pointer; MaxHandleCount:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'HandlerEnumerateLockHandles';
function HandlerCloseAllLockHandles(szFileOrFolderName:PAnsiChar; NameIsFolder,NameIsTranslated:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'HandlerCloseAllLockHandles';
function HandlerIsFileLocked(szFileOrFolderName:PAnsiChar; NameIsFolder,NameIsTranslated:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'HandlerIsFileLocked';
function HandlerEnumerateOpenMutexes(hProcess:THandle; ProcessId:LongInt; HandleBuffer:Pointer; MaxHandleCount:LongInt):LongInt; stdcall; external 'TitanEngine.dll' name 'HandlerEnumerateOpenMutexes';
function HandlerGetOpenMutexHandle(hProcess:THandle; ProcessId:LongInt; szMutexString:PAnsiChar):LongInt; stdcall; external 'TitanEngine.dll' name 'HandlerGetOpenMutexHandle';
function HandlerGetProcessIdWhichCreatedMutex(szMutexString:PAnsiChar):LongInt; stdcall; external 'TitanEngine.dll' name 'HandlerGetProcessIdWhichCreatedMutex';
{TitanEngine.Injector.functions}
function RemoteLoadLibrary(hProcess:THandle; szLibraryFile:PAnsiChar; WaitForThreadExit:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'RemoteLoadLibrary';
function RemoteFreeLibrary(hProcess:THandle; hModule:LongInt; szLibraryFile:PAnsiChar; WaitForThreadExit:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'RemoteFreeLibrary';
function RemoteExitProcess(hProcess:THandle; ExitCode:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'RemoteExitProcess';
{TitanEngine.StaticUnpacker.functions}
function StaticFileLoad(szFileName:PAnsiChar; DesiredAccess:LongInt; SimulateLoad:boolean; FileHandle,LoadedSize,FileMap,FileMapVA:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'StaticFileLoad';
function StaticFileUnload(szFileName:PAnsiChar; CommitChanges:boolean; FileHandle,LoadedSize,FileMap,FileMapVA:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'StaticFileUnload';
function StaticFileOpen(szFileName:PAnsiChar; DesiredAccess:LongInt; FileHandle,FileSizeLow,FileSizeHigh:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'StaticFileOpen';
function StaticFileGetContent(FileHandle:THandle; FilePositionLow:LongInt; FilePositionHigh,Buffer:Pointer; Size:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'StaticFileGetContent';
procedure StaticFileClose(FileHandle:THandle); stdcall; external 'TitanEngine.dll' name 'StaticFileClose';
procedure StaticMemoryDecrypt(MemoryStart,MemorySize,DecryptionType,DecryptionKeySize,DecryptionKey:LongInt); stdcall; external 'TitanEngine.dll' name 'StaticMemoryDecrypt';
procedure StaticMemoryDecryptEx(MemoryStart,MemorySize,DecryptionKeySize:LongInt; DecryptionCallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'StaticMemoryDecryptEx';
procedure StaticMemoryDecryptSpecial(MemoryStart,MemorySize,DecryptionKeySize,SpecDecryptionType:LongInt; DecryptionCallBack:Pointer); stdcall; external 'TitanEngine.dll' name 'StaticMemoryDecryptSpecial';
procedure StaticSectionDecrypt(FileMapVA,SectionNumber:LongInt; SimulateLoad:boolean; DecryptionType,DecryptionKeySize,DecryptionKey:LongInt); stdcall; external 'TitanEngine.dll' name 'StaticSectionDecrypt';
function StaticMemoryDecompress(Source,SourceSize,Destination,DestinationSize,Algorithm:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'StaticMemoryDecompress';
function StaticRawMemoryCopy(hFile:THandle; FileMapVA,VitualAddressToCopy,Size:LongInt; AddressIsRVA:boolean; szDumpFileName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'StaticRawMemoryCopy';
function StaticHashMemory(MemoryToHash:Pointer; SizeOfMemory:LongInt; HashDigest:Pointer; OutputString:boolean; Algorithm:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'StaticHashMemory';
function StaticHashFile(szFileName,HashDigest:PAnsiChar; OutputString:boolean; Algorithm:LongInt):boolean; stdcall; external 'TitanEngine.dll' name 'StaticHashFile';
{TitanEngine.Engine.functions}
procedure SetEngineVariable(VariableId:LongInt; VariableSet:boolean); stdcall; external 'TitanEngine.dll' name 'SetEngineVariable';
function EngineCreateMissingDependencies(szFileName,szOutputFolder:PAnsiChar; LogCreatedFiles:boolean):boolean; stdcall; external 'TitanEngine.dll' name 'EngineCreateMissingDependencies';
function EngineFakeMissingDependencies(hProcess:THandle):boolean; stdcall; external 'TitanEngine.dll' name 'EngineCreateMissingDependencies';
function EngineDeleteCreatedDependencies():boolean; stdcall; external 'TitanEngine.dll' name 'EngineDeleteCreatedDependencies';
function EngineCreateUnpackerWindow(WindowUnpackerTitle,WindowUnpackerLongTitleWindowUnpackerName,WindowUnpackerAuthor:PChar; StartUnpackingCallBack:Pointer):boolean; stdcall; external 'TitanEngine.dll' name 'EngineCreateUnpackerWindow';
procedure EngineAddUnpackerWindowLogMessage(szLogMessage:PChar); stdcall; external 'TitanEngine.dll' name 'EngineAddUnpackerWindowLogMessage';
{TitanEngine.Extension.functions}
function ExtensionManagerIsPluginLoaded(szPluginName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ExtensionManagerIsPluginLoaded';
function ExtensionManagerIsPluginEnabled(szPluginName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ExtensionManagerIsPluginEnabled';
function ExtensionManagerDisableAllPlugins():boolean; stdcall; external 'TitanEngine.dll' name 'ExtensionManagerDisableAllPlugins';
function ExtensionManagerDisablePlugin(szPluginName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ExtensionManagerDisablePlugin';
function ExtensionManagerEnableAllPlugins():boolean; stdcall; external 'TitanEngine.dll' name 'ExtensionManagerEnableAllPlugins';
function ExtensionManagerEnablePlugin(szPluginName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ExtensionManagerEnablePlugin';
function ExtensionManagerUnloadAllPlugins():boolean; stdcall; external 'TitanEngine.dll' name 'ExtensionManagerUnloadAllPlugins';
function ExtensionManagerUnloadPlugin(szPluginName:PAnsiChar):boolean; stdcall; external 'TitanEngine.dll' name 'ExtensionManagerUnloadPlugin';
function ExtensionManagerGetPluginInfo(szPluginName:PAnsiChar):Pointer; stdcall; external 'TitanEngine.dll' name 'ExtensionManagerGetPluginInfo';
implementation
end.
|
unit bitboxdb;
(*
Permission is hereby granted, on 24-Mar-2003, free of charge, to any person
obtaining a copy of this file (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Author of original version of this file: Michael Ax
*)
{THE POINT: To create checkbox group components that will take a byte or word
and provide dynamically sized boxes containing selected items from a universe
of 8 or 16 choices. Allowing the user to check/set bits via a form.}
{this unit takes advantage of delphi's small set implementation, which works
in bytes and words for sets with less than 9/17 members respectively.}
interface
uses
SysUtils, Messages, Classes, Graphics, Controls
, Windows
, Forms, Dialogs, DB, DBCtrls, DBTables, StdCtrls
, BitBox;
type
TdbBitBox = class(TBitBox)
private
FDataLink: TFieldDataLink;
procedure DataChange(Sender: TObject);
function GetDataField: string;
function GetDataSource: TDataSource;
function GetField: TField;
procedure SetDataField(const Value: string);
procedure SetDataSource(Value: TDataSource);
procedure UpdateData(Sender: TObject);
procedure EditingChange(Sender: TObject);
function GetReadOnly: Boolean;
procedure SetReadOnly(Value: Boolean);
protected
procedure ChangeSelected(Sender:TObject); override;
procedure Notification(AComponent:TComponent; Operation:TOperation); override;
public
constructor Create(aOwner:TComponent); Override;
destructor Destroy; Override;
property Field: TField read GetField;
published
property DataField: string read GetDataField write SetDataField;
property DataSource: TDataSource read GetDataSource write SetDataSource;
end;
implementation
{------------------------------------------------------------------------------}
{------------------------------------------------------------------------------}
constructor TdbBitBox.Create(aOwner:TComponent);
begin
inherited Create(aOwner);
inherited ReadOnly := True;
FDataLink:= TFieldDataLink.Create;
FDataLink.OnDataChange:= DataChange;
FDataLink.Control := Self;
FDataLink.OnEditingChange := EditingChange;
FDataLink.OnUpdateData := UpdateData;
end;
destructor TdbBitBox.Destroy;
begin
FDataLink.Free;
FDataLink := nil;
inherited Destroy;
end;
procedure TdbBitBox.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (FDataLink <> nil) and
(AComponent = DataSource) then DataSource := nil;
end;
{------------------------------------------------------------------------------}
{ PLUMBING AND READ-ONLY }
{------------------------------------------------------------------------------}
function TdbBitBox.GetDataSource: TDataSource;
begin
Result := FDataLink.DataSource;
end;
procedure TdbBitBox.SetDataSource(Value: TDataSource);
begin
FDataLink.DataSource := Value;
end;
function TdbBitBox.GetDataField: string;
begin
Result := FDataLink.FieldName;
end;
procedure TdbBitBox.SetDataField(const Value: string);
begin
FDataLink.FieldName := Value;
end;
function TdbBitBox.GetField: TField;
begin
Result := FDataLink.Field;
end;
function TdbBitBox.GetReadOnly: Boolean;
begin
Result := FDataLink.ReadOnly;
end;
procedure TdbBitBox.SetReadOnly(Value: Boolean);
begin
FDataLink.ReadOnly := Value;
end;
{------------------------------------------------------------------------------}
{ }
{------------------------------------------------------------------------------}
procedure TdbBitBox.DataChange(Sender: TObject);
begin
if FDataLink.Field <> nil then
Numeric := FDataLink.Field.AsInteger
else
if csDesigning in ComponentState then Numeric := 0;
end;
procedure TdbBitBox.ChangeSelected(Sender:TObject);
begin
inherited ChangeSelected(Sender);
if FDataLink.Field <> nil then
if not (csDesigning in ComponentState) then
UpdateData(Sender);
end;
procedure TdbBitBox.EditingChange(Sender: TObject);
begin
inherited ReadOnly := not FDataLink.Editing;
end;
procedure TdbBitBox.UpdateData(Sender: TObject);
begin
if Numeric<>FDataLink.Field.AsInteger then
if FDataLink.Edit then
FDataLink.Field.AsInteger:= Numeric;
end;
{------------------------------------------------------------------------------}
{ }
{------------------------------------------------------------------------------}
end.
|
unit EditAlbumController;
interface
uses
Generics.Collections,
Aurelius.Engine.ObjectManager,
MediaFile;
type
TEditAlbumController = class
private
FManager: TObjectManager;
FAlbum: TAlbum;
public
constructor Create;
destructor Destroy; override;
procedure SaveAlbum(Album: TAlbum);
procedure Load(AlbumId: Variant);
property Album: TAlbum read FAlbum;
end;
implementation
uses
DBConnection;
{ TEditAlbumController }
constructor TEditAlbumController.Create;
begin
FAlbum := TAlbum.Create;
FManager := TDBConnection.GetInstance.CreateObjectManager;
end;
destructor TEditAlbumController.Destroy;
begin
if not FManager.IsAttached(FAlbum) then
FAlbum.Free;
FManager.Free;
inherited;
end;
procedure TEditAlbumController.Load(AlbumId: Variant);
begin
if not FManager.IsAttached(FAlbum) then
FAlbum.Free;
FAlbum := FManager.Find<TAlbum>(AlbumId);
end;
procedure TEditAlbumController.SaveAlbum(Album: TAlbum);
begin
if not FManager.IsAttached(Album) then
FManager.SaveOrUpdate(Album);
FManager.Flush;
end;
end.
|
(*!------------------------------------------------------------
* [[APP_NAME]] ([[APP_URL]])
*
* @link [[APP_REPOSITORY_URL]]
* @copyright Copyright (c) [[COPYRIGHT_YEAR]] [[COPYRIGHT_HOLDER]]
* @license [[LICENSE_URL]] ([[LICENSE]])
*------------------------------------------------------------- *)
program app;
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
fano,
bootstrap;
var
appInstance : IWebApplication;
cliParams : ICliParams;
host : string;
port : word;
begin
cliParams := (TGetOptsParams.create() as ICliParamsFactory)
.addOption('host', 1)
.addOption('port', 1)
.build();
host := cliParams.getOption('host', '::1');
port := cliParams.getOption('port', 20477);
writeln('Starting application at [', host, ']:', port);
(*!-----------------------------------------------
* Bootstrap SCGI application
*
* @author AUTHOR_NAME <author@email.tld>
*------------------------------------------------*)
appInstance := TDaemonWebApplication.create(
TScgiAppServiceProvider.create(
TServerAppServiceProvider.create(
TAppServiceProvider.create(),
(TInet6SvrFactory.create(host, port) as ISocketSvrFactory).build()
)
),
TAppRoutes.create()
);
appInstance.run();
end.
|
unit PasPlayActionProcessor;
interface
uses
PasRequestProcessor, IdCustomHTTPServer, System.SysUtils, System.Classes;
type
TPlayActionProcessor = class(TRequestProcessor)
protected
function innerRequested(requestUri: string; requestAction: string)
: Boolean; override;
function onGet(requestInfo: TIdHTTPRequestInfo;
responseInfo: TIdHTTPResponseInfo): Boolean; override;
end;
TPlayAction2Processor = class(TRequestProcessor)
function innerRequested(requestUri: string; requestAction: string)
: Boolean; override;
function onGet(requestInfo: TIdHTTPRequestInfo;
responseInfo: TIdHTTPResponseInfo): Boolean; override;
end;
implementation
uses
CnDebug, PasMessagerHelper, PasGlobalConfiguration, Winapi.Windows, EncdDecd,
System.JSON, PasYoutubedlHelper, PasLibVlcUserData;
function TPlayActionProcessor.innerRequested(requestUri: string;
requestAction: string): Boolean;
begin
Result := 'play'.Equals(requestAction)
end;
function TPlayActionProcessor.onGet(requestInfo: TIdHTTPRequestInfo;
responseInfo: TIdHTTPResponseInfo): Boolean;
var
url: string;
execYoutubedl: string;
youtubedlResponse: string;
spliter: TStringList;
localPlayUrl: string;
step: Integer;
httpResponse: string;
JSON: TJSONObject;
videoCount: Integer;
userData: TLibVlcUserData;
begin
url := requestInfo.Params.Values['url'];
if EmptyStr.Equals(url) then
begin
// 恢复播放,操作指令不进入队列,直接执行
CnDebugger.TraceMsg('Resume Play');
TMessagerHelper.sendMessage(FM_PLAY, 0);
TMessagerHelper.postMessage(FM_FULL_SCREEN, 0);
httpResponse := '继续播放...';
end
else
begin
// 不处于播放状态 语言提示
if TMessagerHelper.sendMessage(FM_PALY_STATUS, 0) <> PS_PLAYING then
begin
TMessagerHelper.sendMessage(FM_SPEAK, '正在查询播放地址,请稍后。');
end;
// 查询分段视频数量
videoCount := TYoutubeDlHelper.GetPlaylistCount(url);
for step := 1 to videoCount do
begin
userData := TLibVlcUserData.Create;
userData.SrcUrl := url;
userData.LocalUrl :=
Format('?action=transVlc&returnUrl=false&block=%d&url=%s',
[step, EncdDecd.EncodeString(url).Replace(#10, '').Replace(#13, '')]);
userData.PlayStatus := PS_WAIT_PLAY;
userData.Index := step;
TMessagerHelper.sendMessage(FM_PLAY, Cardinal(Pointer(userData)));
end;
if videoCount = -1 then
httpResponse := '添加失败'
else
httpResponse := '添加成功';
TMessagerHelper.sendMessage(FM_SPEAK, httpResponse);
spliter.Free;
end;
if TMessagerHelper.sendMessage(FM_PALY_STATUS, 0) <> PS_PLAYING then
begin
TMessagerHelper.sendMessage(FM_PLAY, 0);
TMessagerHelper.postMessage(FM_FULL_SCREEN, 0);
end;
responseInfo.ContentText := httpResponse;
responseInfo.ContentType := 'plain/text';
responseInfo.CharSet := 'utf-8';
Result := True;
end;
function TPlayAction2Processor.innerRequested(requestUri: string;
requestAction: string): Boolean;
begin
Result := 'transVlc'.Equals(requestAction);
end;
function TPlayAction2Processor.onGet(requestInfo: TIdHTTPRequestInfo;
responseInfo: TIdHTTPResponseInfo): Boolean;
var
returnUrl: Boolean;
block: Integer;
url: string;
youtubedlResponse: string;
begin
CnDebugger.TraceEnter('onGet', Self.ClassName);
returnUrl := StrToBoolDef(requestInfo.Params.Values['returnUrl'], False);
block := StrToIntDef(requestInfo.Params.Values['block'], -1);
url := requestInfo.Params.Values['url'];
if block <> -1 then
begin
url := EncdDecd.DecodeString(url);
youtubedlResponse := TYoutubeDlHelper.GetVideoInfo(url, block);
if (Pos('ERROR', youtubedlResponse) > 0) and
(youtubedlResponse.Chars[0] = '{') then
begin
CnDebugger.TraceMsgWithTag(youtubedlResponse, Self.ClassName);
responseInfo.ResponseNo := 500; // 让vlc重试
end
else
begin
if returnUrl then
begin
responseInfo.ContentText := youtubedlResponse;
end
else
begin
responseInfo.ResponseNo := 302; // 告知vlc转向
responseInfo.Location :=
Format('/?action=vlc&base64=%s',
[EncdDecd.EncodeString(youtubedlResponse).Replace(#10,
'').Replace(#13, '')]);
end;
end;
end;
Result := True;
CnDebugger.TraceLeave('onGet', Self.ClassName);
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP 3.0
Description: Model relacionado à tabela [EMPRESA]
The MIT License
Copyright: Copyright (C) 2021 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (alberteije@gmail.com)
@version 1.0.0
*******************************************************************************}
unit Empresa;
interface
uses
MVCFramework.Serializer.Commons, ModelBase;
type
[MVCNameCase(ncLowerCase)]
TEmpresa = class(TModelBase)
private
FId: Integer;
FRazaoSocial: string;
FNomeFantasia: string;
FCnpj: string;
FInscricaoEstadual: string;
FInscricaoMunicipal: string;
FTipoRegime: string;
FCrt: string;
FDataConstituicao: TDateTime;
FTipo: string;
FEmail: string;
FEmailPagamento: string;
FLogradouro: string;
FNumero: string;
FComplemento: string;
FCep: string;
FBairro: string;
FCidade: string;
FUf: string;
FFone: string;
FContato: string;
FCodigoIbgeCidade: Integer;
FCodigoIbgeUf: Integer;
FLogotipo: string;
FRegistrado: string;
FNaturezaJuridica: string;
FSimei: string;
FDataRegistro: TDateTime;
FHoraRegistro: string;
public
// procedure ValidarInsercao; override;
// procedure ValidarAlteracao; override;
// procedure ValidarExclusao; override;
[MVCColumnAttribute('ID', True)]
[MVCNameAsAttribute('id')]
property Id: Integer read FId write FId;
[MVCColumnAttribute('RAZAO_SOCIAL')]
[MVCNameAsAttribute('razaoSocial')]
property RazaoSocial: string read FRazaoSocial write FRazaoSocial;
[MVCColumnAttribute('NOME_FANTASIA')]
[MVCNameAsAttribute('nomeFantasia')]
property NomeFantasia: string read FNomeFantasia write FNomeFantasia;
[MVCColumnAttribute('CNPJ')]
[MVCNameAsAttribute('cnpj')]
property Cnpj: string read FCnpj write FCnpj;
[MVCColumnAttribute('INSCRICAO_ESTADUAL')]
[MVCNameAsAttribute('inscricaoEstadual')]
property InscricaoEstadual: string read FInscricaoEstadual write FInscricaoEstadual;
[MVCColumnAttribute('INSCRICAO_MUNICIPAL')]
[MVCNameAsAttribute('inscricaoMunicipal')]
property InscricaoMunicipal: string read FInscricaoMunicipal write FInscricaoMunicipal;
[MVCColumnAttribute('TIPO_REGIME')]
[MVCNameAsAttribute('tipoRegime')]
property TipoRegime: string read FTipoRegime write FTipoRegime;
[MVCColumnAttribute('CRT')]
[MVCNameAsAttribute('crt')]
property Crt: string read FCrt write FCrt;
[MVCColumnAttribute('DATA_CONSTITUICAO')]
[MVCNameAsAttribute('dataConstituicao')]
property DataConstituicao: TDateTime read FDataConstituicao write FDataConstituicao;
[MVCColumnAttribute('TIPO')]
[MVCNameAsAttribute('tipo')]
property Tipo: string read FTipo write FTipo;
[MVCColumnAttribute('EMAIL')]
[MVCNameAsAttribute('email')]
property Email: string read FEmail write FEmail;
[MVCColumnAttribute('EMAIL_PAGAMENTO')]
[MVCNameAsAttribute('emailPagamento')]
property EmailPagamento: string read FEmailPagamento write FEmailPagamento;
[MVCColumnAttribute('LOGRADOURO')]
[MVCNameAsAttribute('logradouro')]
property Logradouro: string read FLogradouro write FLogradouro;
[MVCColumnAttribute('NUMERO')]
[MVCNameAsAttribute('numero')]
property Numero: string read FNumero write FNumero;
[MVCColumnAttribute('COMPLEMENTO')]
[MVCNameAsAttribute('complemento')]
property Complemento: string read FComplemento write FComplemento;
[MVCColumnAttribute('CEP')]
[MVCNameAsAttribute('cep')]
property Cep: string read FCep write FCep;
[MVCColumnAttribute('BAIRRO')]
[MVCNameAsAttribute('bairro')]
property Bairro: string read FBairro write FBairro;
[MVCColumnAttribute('CIDADE')]
[MVCNameAsAttribute('cidade')]
property Cidade: string read FCidade write FCidade;
[MVCColumnAttribute('UF')]
[MVCNameAsAttribute('uf')]
property Uf: string read FUf write FUf;
[MVCColumnAttribute('FONE')]
[MVCNameAsAttribute('fone')]
property Fone: string read FFone write FFone;
[MVCColumnAttribute('CONTATO')]
[MVCNameAsAttribute('contato')]
property Contato: string read FContato write FContato;
[MVCColumnAttribute('CODIGO_IBGE_CIDADE')]
[MVCNameAsAttribute('codigoIbgeCidade')]
property CodigoIbgeCidade: Integer read FCodigoIbgeCidade write FCodigoIbgeCidade;
[MVCColumnAttribute('CODIGO_IBGE_UF')]
[MVCNameAsAttribute('codigoIbgeUf')]
property CodigoIbgeUf: Integer read FCodigoIbgeUf write FCodigoIbgeUf;
[MVCColumnAttribute('LOGOTIPO')]
[MVCNameAsAttribute('logotipo')]
property Logotipo: string read FLogotipo write FLogotipo;
[MVCColumnAttribute('REGISTRADO')]
[MVCNameAsAttribute('registrado')]
property Registrado: string read FRegistrado write FRegistrado;
[MVCColumnAttribute('NATUREZA_JURIDICA')]
[MVCNameAsAttribute('naturezaJuridica')]
property NaturezaJuridica: string read FNaturezaJuridica write FNaturezaJuridica;
[MVCColumnAttribute('SIMEI')]
[MVCNameAsAttribute('simei')]
property Simei: string read FSimei write FSimei;
[MVCColumnAttribute('DATA_REGISTRO')]
[MVCNameAsAttribute('dataRegistro')]
property DataRegistro: TDateTime read FDataRegistro write FDataRegistro;
[MVCColumnAttribute('HORA_REGISTRO')]
[MVCNameAsAttribute('horaRegistro')]
property HoraRegistro: string read FHoraRegistro write FHoraRegistro;
end;
implementation
{ TEmpresa }
end. |
unit PWInfoChangesWellFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Well, BaseObjects, CommonFrame, StdCtrls, ComCtrls, ExtCtrls,
CommonValueDictFrame;
type
TInfoChangesWell = class(TfrmCommonFrame)
Panel5: TPanel;
GroupBox8: TGroupBox;
dtmEnteringData: TDateTimePicker;
GroupBox9: TGroupBox;
dtmLastModifyData: TDateTimePicker;
GroupBox1: TGroupBox;
mmBasicChange: TMemo;
frmFilterEmployee: TfrmFilter;
frmFilterReasonChange: TfrmFilter;
private
function GetWell: TWell;
protected
procedure FillControls(ABaseObject: TIDObject); override;
procedure ClearControls; override;
procedure FillParentControls; override;
procedure RegisterInspector; override;
function GetParentCollection: TIDObjects; override;
public
property Well: TWell read GetWell;
procedure Save(AObject: TIDObject = nil); override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
InfoChangesWell: TInfoChangesWell;
implementation
uses Facade, SDFacade, Employee, ReasonChange, DateUtils;
{$R *.dfm}
{ TfrmCommonFrame1 }
procedure TInfoChangesWell.ClearControls;
var EmpID: integer;
begin
inherited;
EmpID := TMainFacade.GetInstance.DBGates.EmployeeID;
frmFilterEmployee.AllObjects := TMainFacade.GetInstance.AllEmployees;
frmFilterEmployee.ActiveObject := TMainFacade.GetInstance.AllEmployees.ItemsByID[EmpID];
frmFilterEmployee.Reload;
frmFilterReasonChange.AllObjects := (TMainFacade.GetInstance as TMainFacade).ReasonChangesByWell;
frmFilterReasonChange.ActiveObject := (TMainFacade.GetInstance as TMainFacade).ReasonChangesByWell.ItemsByID[EmpID];
frmFilterReasonChange.Reload;
end;
constructor TInfoChangesWell.Create(AOwner: TComponent);
begin
inherited;
EditingClass := TWell;
end;
destructor TInfoChangesWell.Destroy;
begin
inherited;
end;
procedure TInfoChangesWell.FillControls(ABaseObject: TIDObject);
begin
inherited;
with Well do
begin
//if Assigned (ReasonChange) then
//if Assigned (ReasonChange.Employee) then
//begin
// frmFilterEmployee.ActiveObject := ReasonChange.Employee;
// frmFilterEmployee.cbxActiveObject.Text := ReasonChange.Employee.Name;
//end;
if ID > 0 then
begin
if EnteringDate > 0 then
dtmEnteringData.Date := EnteringDate
else
dtmEnteringData.Date := Date;
if LastModifyDate > 0 then
dtmLastModifyData.Date := LastModifyDate
else
dtmLastModifyData.Date := Date;
end
else
begin
dtmEnteringData.Date := Date;
dtmLastModifyData.Date := Date;
end;
end;
end;
procedure TInfoChangesWell.FillParentControls;
begin
inherited;
end;
function TInfoChangesWell.GetParentCollection: TIDObjects;
begin
Result := nil;
end;
function TInfoChangesWell.GetWell: TWell;
begin
Result := EditingObject as TWell;
end;
procedure TInfoChangesWell.RegisterInspector;
begin
inherited;
end;
procedure TInfoChangesWell.Save;
begin
inherited;
if Assigned (Well) then
with Well do
begin
EnteringDate := DateOf(dtmEnteringData.Date);
LastModifyDate := Date;
// данные по сотруднику назначается автоматически при сохранении информации в БД
end;
end;
end.
|
{
ID: a_zaky01
PROG: fence8
LANG: PASCAL
}
var
n,r,i,j,max,a,b,depth,totalboard:longint;
board:array[1..50] of longint;
rail,totalrail:array[0..1023] of longint;
fin,fout:text;
label
closefile;
procedure swap(var a,b:longint);
var
temp:longint;
begin
temp:=a;
a:=b;
b:=temp;
end;
procedure sortb(l,r:integer);
var
i,j,temp,mid:integer;
begin
i:=l;
j:=r;
mid:=board[(l+r) div 2];
repeat
while board[i]<mid do inc(i);
while board[j]>mid do dec(j);
if i<=j then
begin
swap(board[i],board[j]);
inc(i);
dec(j);
end;
until i>j;
if l<j then sortb(l,j);
if i<r then sortb(i,r);
end;
procedure sortr(l,r:integer);
var
i,j,temp,mid:integer;
begin
i:=l;
j:=r;
mid:=rail[(l+r) div 2];
repeat
while rail[i]<mid do inc(i);
while rail[j]>mid do dec(j);
if i<=j then
begin
swap(rail[i],rail[j]);
inc(i);
dec(j);
end;
until i>j;
if l<j then sortr(l,j);
if i<r then sortr(i,r);
end;
function cut(depth0,n0,notused0:integer):boolean;
var
i,notused:longint;
temp:boolean;
begin
if depth0=0 then exit(true);
cut:=false;
for i:=n0 to n do
if rail[depth0]<=board[i] then
begin
dec(board[i],rail[depth0]);
if board[i]<rail[1] then notused:=notused0+board[i]
else notused:=notused0;
if totalboard-notused<totalrail[depth] then
begin
inc(board[i],rail[depth0]);
continue;
end;
if rail[depth0]=rail[depth0-1] then temp:=cut(depth0-1,i,notused)
else temp:=cut(depth0-1,1,notused);
inc(board[i],rail[depth0]);
if temp then exit(true);
end;
end;
begin
assign(fin,'fence8.in');
assign(fout,'fence8.out');
reset(fin);
rewrite(fout);
readln(fin,n);
for i:=1 to n do readln(fin,board[i]);
readln(fin,r);
for i:=1 to r do readln(fin,rail[i]);
sortb(1,n);
sortr(1,r);
i:=1;
while (board[i]<rail[1]) and (i<=n) do inc(i);
if i>n then
begin
writeln(fout,0);
goto closefile;
end;
n:=n-i+1;
for j:=1 to n do board[j]:=board[j+i-1];
while rail[r]>board[n] do dec(r);
totalboard:=0;
totalrail[0]:=0;
for i:=1 to n do inc(totalboard,board[i]);
for i:=1 to r do totalrail[i]:=totalrail[i-1]+rail[i];
while totalrail[r]>totalboard do dec(r);
if r=0 then
begin
writeln(fout,0);
goto closefile;
end;
max:=0;
a:=1;
b:=r;
while a<=b do
begin
depth:=(a+b) div 2;
if cut(depth,1,0) then
begin
if depth>max then max:=depth;
a:=depth+1;
end
else b:=depth-1;
end;
writeln(fout,max);
closefile:
close(fin);
close(fout);
end.
|
//
// Created by the DataSnap proxy generator.
//
unit ClientClasses;
interface
uses DBXCommon, DBXJSON, Classes, SysUtils, DB, SqlExpr, DBXDBReaders;
type
TServerMethods1Client = class
private
FDBXConnection: TDBXConnection;
FInstanceOwner: Boolean;
FEchoStringCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function EchoString(Value: string): string;
end;
TRdmCadastroClient = class
private
FDBXConnection: TDBXConnection;
FInstanceOwner: Boolean;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
end;
implementation
function TServerMethods1Client.EchoString(Value: string): string;
begin
if FEchoStringCommand = nil then
begin
FEchoStringCommand := FDBXConnection.CreateCommand;
FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FEchoStringCommand.Text := 'TServerMethods1.EchoString';
FEchoStringCommand.Prepare;
end;
FEchoStringCommand.Parameters[0].Value.SetWideString(Value);
FEchoStringCommand.ExecuteUpdate;
Result := FEchoStringCommand.Parameters[1].Value.GetWideString;
end;
constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection);
begin
inherited Create;
if ADBXConnection = nil then
raise EInvalidOperation.Create('Connection cannot be nil. Make sure the connection has been opened.');
FDBXConnection := ADBXConnection;
FInstanceOwner := True;
end;
constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create;
if ADBXConnection = nil then
raise EInvalidOperation.Create('Connection cannot be nil. Make sure the connection has been opened.');
FDBXConnection := ADBXConnection;
FInstanceOwner := AInstanceOwner;
end;
destructor TServerMethods1Client.Destroy;
begin
FreeAndNil(FEchoStringCommand);
inherited;
end;
constructor TRdmCadastroClient.Create(ADBXConnection: TDBXConnection);
begin
inherited Create;
if ADBXConnection = nil then
raise EInvalidOperation.Create('Connection cannot be nil. Make sure the connection has been opened.');
FDBXConnection := ADBXConnection;
FInstanceOwner := True;
end;
constructor TRdmCadastroClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create;
if ADBXConnection = nil then
raise EInvalidOperation.Create('Connection cannot be nil. Make sure the connection has been opened.');
FDBXConnection := ADBXConnection;
FInstanceOwner := AInstanceOwner;
end;
destructor TRdmCadastroClient.Destroy;
begin
inherited;
end;
end.
|
{$include kode.inc}
unit syn_thesis_wave;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
const
wave_type_off = 0;
wave_type_const = 1;
wave_type_input = 2;
wave_type_prev = 3;
wave_type_sin = 4;
wave_type_tri = 5;
wave_type_ramp = 6;
wave_type_saw = 7;
wave_type_squ = 8;
wave_type_noise = 9;
wave_type_count = 10;
wave_names : array[0..wave_type_count-1] of PChar = (
'off',
'const',
'input',
'prev',
'sin',
'tri',
'ramp',
'saw',
'squ',
'noise'
);
type
KSynThesis_Wave = class
public // private
FType : LongInt;
//FCounter : Single;
//FAdder : Single;
//FRandom : Single;
public
constructor create;
destructor destroy; override;
procedure setType(AType:LongInt);
procedure setCounter(AValue:Single);
procedure setAdder(AValue:Single);
function process(APhase:Single; AInput:Single=0) : Single;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_const,
kode_random;
//----------
constructor KSynThesis_Wave.create;
begin
inherited;
FType := wave_type_sin;
//FCounter := 0;
//FAdder := 0;
//FRandom := 0;
end;
//----------
destructor KSynThesis_Wave.destroy;
begin
inherited;
end;
//----------------------------------------
procedure KSynThesis_Wave.setType(AType:LongInt);
begin
FType := AType;
end;
//----------
procedure KSynThesis_Wave.setCounter(AValue:Single);
begin
//FCounter := AValue;
end;
//----------
procedure KSynThesis_Wave.setAdder(AValue:Single);
begin
//FAdder := AValue;
end;
//----------------------------------------
// osc
//----------------------------------------
function KSynThesis_Wave.process(APhase:Single; AInput:Single=0) : Single;
var
a : single;
begin
result := 0;
case FType of
//wave_type_off: result := 0;
wave_type_const: result := 1;
wave_type_input: result := AInput;
//wave_type_prev: result := 0;
wave_type_sin: result := sin(APhase*KODE_PI2);
//wave_type_sin: result := KSin(APhase*KODE_PI2*2);
wave_type_tri:
begin
a := (APhase+0.75);
a -= trunc(a);
result := abs( (a*4) - 2 ) - 1;
end;
wave_type_ramp: result := (APhase*2)-1;
wave_type_saw: result := 1 - (APhase*2);
wave_type_squ: if APhase < 0.5 then result := 1 else result := -1;
wave_type_noise:
begin
//FCounter += FAdder;
//if FCounter >= 1 then
//begin
// FCounter -= FAdder;
// FRandom := KRandomSigned;
//end;
//result := FRandom;
result := KRandomSigned;
end;
end;
//FPhase += FPhaseAdd;
//if {(FPhase < 0) or} (FPhase >= 1) then FWrapped := True else FWrapped := False;
//FPhase -= trunc(FPhase);
end;
//----------------------------------------
// phase mod
//----------------------------------------
{function KSynThesis_Wave.process(APhase,AInput:Single) : Single;
var
a : Single;
begin
result := 0;
case FType of
wave_type_const: result := 1;
wave_type_input: result := AInput;
wave_type_sin: result := sin(APhase*KODE_PI2);
wave_type_tri:
begin
a := (FPhase+0.75);
a -= trunc(a);
result := abs( (a*4) - 2 ) - 1;
end;
wave_type_ramp: result := (APhase*2)-1;
wave_type_saw: result := 1-(APhase*2);
wave_type_squ: if APhase < 0.5 then result := 1 else result := -1;
wave_type_noise: result := KRandomSigned;
end;
end;}
//----------------------------------------------------------------------
end.
|
unit uSensorPropNames;
interface
const
// имена свойств объектов (Групп)
sID = 'ID';
sParentID = 'ParentID';
sName = 'Name';
sNameEn = 'NameEn';
sFullName = 'FullName';
sKind = 'Kind';
// имена свойств оборудования (Equipment)
sDevPath = 'Path';
sDevData = 'Data';
sDevInfo = 'DevInfo';
sDevCommands = 'DevCommands';
// имена свойств датчика
sSensorID = 'ID';
sSensorSID = 'SID';
sSensorUseParentSID = 'UseParentSID';
sSensorFullSID = 'FullSID';
sSensorName = 'Name';
sSensorNameEn = 'NameEn';
sSensorFullName = 'FullName';
sSensorConnectionName = 'ConnectionName';
sSensorControllerAddr = 'ControllerAddr';
sSensorAddr = 'Addr';
sSensorPermissions = 'Permissions';
sSensorUnitName = 'UnitName';
sSensorDisplayFormat = 'DisplayFormat';
sSensorMinReadInterval = 'MinReadInterval';
sSensorUpdateInterval = 'UpdateInterval';
sSensorTimeShift = 'TimeShift';
sSensorTimeStart = 'TimeStart';
sSensorCorrectMul = 'CorrectMul';
sSensorCorrectAdd = 'CorrectAdd';
sSensorTransformCount = 'TransformCount';
sSensorTransformIn = 'TransformIn';
sSensorTransformOut = 'TransformOut';
sSensorPrecision = 'SensorPrecision';
sSensorStairs = 'SensorStairs';
sSensorCompression_Precision = 'Compression.Precision';
sSensorCompression_DeadSpace = 'Compression.DeadSpace';
sSensorDataBuffer_MaxInterval = 'DataBuffer.MaxInterval';
sSensorDataBuffer_MaxRecCount = 'DataBuffer.MaxRecCount';
sSensorDataBuffer_DataWriter_Kind = 'DataBuffer.DataWriter.Kind';
sSensorDataBuffer_DataWriter_UpdateDBInterval = 'DataBuffer.DataWriter.UpdateDBInterval';
sSensorDataBuffer_DataWriter_ExtDeadband ='DataBuffer.DataWriter.ExtDeadband';
sSensorSmooth_Kind = 'Smooth.Kind';
sSensorSmooth_Interval = 'Smooth.Interval';
sSensorSmooth_Count = 'Smooth.Count';
sSensorRefAutoFill = 'RefAutoFill';
sSensorRefTableName = 'RefTableName';
sSensorRefValue = 'RefValue';
sSensorRefLayerFileName = 'RefLayerFileName';
sSensorRefLayerFieldName = 'RefLayerFieldName';
sSensorEquipmentID = 'EquipmentID';
sSensorEquipmentPath = 'EquipmentPath';
sSensorFuncName = 'FuncName';
sSensorOnChangValueFuncName = 'OnChangValueFuncName';
sSensorOsSensornReadConvertValueFuncName = 'ReadConvertValueFuncName';
sSensorOnWriteConvertValueFuncName = 'OnWriteConvertValueFuncName';
sApproxPrecision = 'ApproxPrecision';
implementation
end.
|
unit Counter.CRGP;
interface
type
TCounter<T> = class
private class var
FInstanceCount: Integer;
public
constructor Create;
destructor Destroy; override;
class property InstanceCount: Integer read FInstanceCount;
end;
type
TFoo = class(TCounter<TFoo>)
end;
type
TBar = class(TCounter<TBar>)
end;
procedure TestCounterCRGP;
implementation
uses
Utils;
procedure TestCounterCRGP;
begin
StartSection;
WriteLn('A simple instance counter using CRGP:');
{ NOTE: We are creating memory leaks here. }
TFoo.Create;
TBar.Create;
TFoo.Create;
TFoo.Create;
TBar.Create;
WriteLn('* Number of TFoo instances: ', TFoo.InstanceCount);
WriteLn('* Number of TBar instances: ', TBar.InstanceCount);
end;
{ TCounter<T> }
constructor TCounter<T>.Create;
begin
inherited;
Inc(FInstanceCount);
end;
destructor TCounter<T>.Destroy;
begin
Dec(FInstanceCount);
inherited;
end;
end.
|
unit PluginUtilities;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
uses
AdvObjects, System.Generics.Defaults, FHIRBase;
type
TTreeDataPointer = record
expr : TFHIRPathExpressionNode;
op : boolean;
end;
PTreeDataPointer = ^TTreeDataPointer;
TFHIRAnnotationLevel = (alError, alWarning, alHint, alMatch);
TFHIRAnnotation = class (TAdvObject)
private
FLevel: TFHIRAnnotationLevel;
FMessage: String;
FLine : integer;
FStop: integer;
FStart: integer;
FDescription: String;
public
Constructor create(level : TFHIRAnnotationLevel; line : integer; start, stop : integer; message, description : String); overload;
property level : TFHIRAnnotationLevel read FLevel write FLevel;
property start : integer read FStart write FStart;
property stop : integer read FStop write FStop;
property message : String read FMessage write FMessage;
property description : String read FDescription write FDescription;
property line : integer read FLine write FLine;
end;
TFHIRAnnotationComparer = class (TAdvObject, IComparer<TFHIRAnnotation>)
public
function Compare(const Left, Right: TFHIRAnnotation): Integer;
end;
implementation
{ TFHIRAnnotation }
constructor TFHIRAnnotation.create(level: TFHIRAnnotationLevel; line, start, stop: integer; message, description: String);
begin
Create;
self.level := level;
self.line := line;
self.start := start;
self.stop := stop;
self.message := message;
if description <> '' then
self.description := description
else
self.description := message;
end;
{ TFHIRAnnotationComparer }
function TFHIRAnnotationComparer.Compare(const Left, Right: TFHIRAnnotation): Integer;
begin
if (left.Start < Right.Start) then
result := -1
else if (left.Start > Right.Start) then
result := 1
else if (left.Stop < Right.Stop) then
result := -1
else if (left.Stop > Right.Stop) then
result := 1
else if (left.Level < Right.Level) then
result := -1
else if (left.Level > Right.Level) then
result := 1
else
result := 0;
end;
end.
|
unit ExForm;
interface
uses Windows,SysUtils,Classes,Messages,Controls,Graphics,Forms;
var
WindowModalShownMessage:DWOrd=0;
type
TExForm=class(TForm)
private
FDoAfterModal:Boolean;
FModalProc: TThreadMethod;
FAutoCloseModal: Boolean;
protected
procedure ModalShown;virtual;
procedure Activate;override;
procedure WndProc(var Message: TMessage); override;
public
function ShowModal:Integer;override;
property AutoCloseModal:Boolean read FAutoCloseModal write FAutoCloseModal;
property ModalProc:TThreadMethod read FModalProc write FModalProc;
end;
implementation
uses Consts;
{ TExForm }
function TExForm.ShowModal:Integer;
begin
FDoAfterModal:=True;
try
Result:=inherited ShowModal;
finally
FDoAfterModal:=False;
end;
end;
procedure TExForm.ModalShown;
begin
if(Assigned(FModalProc))then FModalProc;
end;
procedure TExForm.Activate;
begin
inherited;
if(FDoAfterModal)then
try
Repaint;
Application.ProcessMessages;
PostMessage(Handle,WindowModalShownMessage,0,0);
finally
FDoAfterModal:=False;
end;
end;
procedure TExForm.WndProc(var Message: TMessage);
begin
if(Message.Msg=WindowModalShownMessage)then begin
FDoAfterModal:=False;
try
ModalShown;
finally
if(AutoCloseModal)and(ModalResult=0)then ModalResult:=mrCancel;
end;
end else inherited;
end;
initialization
WindowModalShownMessage:=RegisterWindowMessage('WindowModalShownMessage_DELPHI_LIKUNQI');
end.
|
unit VRMLtype;
interface
uses GL, GLU;
type
SFEnum = ( AUTO, UNKNOWN_ORDERING, CLOCKWISE, COUNTERCLOCKWISE,
UNKNOWN_SHAPE_TYPE, SOLID, UNKNOWN_FACE_TYPE, CONVEX,
BINDINGS_DEFAULT, OVERALL, PER_PART, PER_PART_INDEXED,
PER_FACE, PER_FACE_INDEXED, PER_VERTEX, PER_VERTEX_INDEXED,
SFLEFT, SFCENTER, SFRIGHT );
Float = GLfloat;
SFFloat = real;//Float;
MFFloat = Float;
SFBool = boolean;
SFVec3f = array [ 0..2 ] of SFFloat;
SFColor = SFVec3f;
MFVec3f = array [ 0..2 ] of SFFloat;
MFColor = MFVec3f;
SFRotation = array [ 0..3 ] of SFFloat;
SFBitMask = longint;
SFLong = longint;
MFLong = longint;
MFString = string;
TCube = object
width,
height,
depth : real;
end;
TSphere = object
radius : SFFloat;
end;
TCone = object
parts : SFBitMask;
bottomRadius : SFFloat;
height : SFFloat;
end;
TCoordinate3 = record
point : MFVec3f;
end;
TShapeHints = object
vertexOrdering : SFEnum;
shapetype : SFEnum;
facetype : SFEnum;
creaseAngle : SFFloat;
end;
TSpotLight = object
lightOn : SFBool;
intensity : SFFloat;
color : SFVec3f;
location : SFVec3f;
direction : SFVec3f;
dropOffRate : SFFloat;
cutOffAngle : SFFloat;
end;
TAsciiText = object
asciiString : MFString;
spacing : SFFloat;
justification : SFEnum;
width : MFFloat;
end;
TDirectionalLight = object
lightOn : SFBool;
intensity : SFFloat;
color : SFColor;
Adirection : SFVec3f;
end;
TIndexedFaceSet = object
coordIndex : MFLong;
materialIndex : MFLong;
normalIndex : MFLong;
textureCoordIndex : MFLong;
end;
TIndexedLineSet = record
coordIndex : MFLong;
materialIndex : MFLong;
normalIndex : MFLong;
textureCoordIndex : MFLong;
end;
TMaterial = record
ambientColor : MFColor;
diffuseColor : MFColor;
specularColor : MFColor;
emissiveColor : MFColor;
shininess : MFFloat;
transparency : MFFloat;
end;
TMaterialBinding = object
value : SFEnum;
end;
TMatrixTransform = array [ 0..3, 0..3 ] of SFFloat;
TTransform = object
translation : SFVec3f;
rotation : SFRotation;
scaleFactor : SFVec3f;
scaleOrientation : SFRotation;
center : SFVec3f;
end;
TPerspectiveCamera = object
position : SFVec3f;
orientation : SFRotation;
focalDistance : SFFloat;
heightAngle : SFFloat;
end;
TCylinder = object
parts : SFBitMask;
radius : SFFloat;
height : SFFloat;
end;
const
// PARTS
PARTS_SIDES = $0001;
PARTS_TOP = $0002;
PARTS_BOTTOM = $0004;
PARTS_ALL = $ffff;
const
// дают возможность по отельности восстанавливать значения по умолчанию
// в любой момент времени для любой переменной
DefaultColor : SFColor = ( 1, 1, 1 );
DefaultLocation : SFVec3f = ( 0, 0, 1 );
DefaultDirection : SFVec3f = ( 0, 0, -1 );
DefaultMaterial : TMaterial =
( ambientColor : ( 0.9, 0.9, 0.9 );
diffuseColor : ( 0.8, 0.8, 0.8 );
specularColor : ( 0, 0, 0 );
emissiveColor : ( 0, 0, 0 );
shininess : 0.2;
transparency : 0 );
DefaultMatrixTransform : TMatrixTransform =
( ( 1, 0, 0, 0),
( 0, 1, 0, 0),
( 0, 0, 1, 0),
( 0, 0, 6.2, 1) );
DefaultTransform : TTransform =
( translation : ( 0, 0, 0 );
rotation : ( 0, 0, 1, 0 );
scaleFactor : ( 1, 1, 1 );
scaleOrientation : ( 0, 0, 1, 0 );
center : ( 0, 0, 0 ) );
DefaultMaterialBinding : TMaterialBinding = ( value : OVERALL );
DefaultPerspectiveCamera : TPerspectiveCamera =
( position : ( 0, 0, 1 );
orientation : ( 0, 0, 1, 0 );
focalDistance : 5;
heightAngle : 0.785398 );
DefaultCylinder : TCylinder =
( parts : PARTS_ALL;
radius : 1;
height : 2 );
var
cube : TCube;
sphere : TSphere;
cone : TCone;
cylinder : TCylinder;
renderculling : SFEnum;
shapehints : TShapeHints;
spotLight : TSpotLight;
AsciiText : TAsciiText;
Coordinate3 : TCoordinate3;
DirectionalLight : TDirectionalLight;
IndexedFaceSet : TIndexedFaceSet;
IndexedLineSet : TIndexedLineSet;
Material : TMaterial;
MaterialBinding : TMaterialBinding;
MatrixTransform : TMatrixTransform;
PerspectiveCamera : TPerspectiveCamera;
Transform : TTransform;
procedure DefaultTypeDeclarations;
implementation
procedure DefaultTypeDeclarations;
begin
cube.width := 2;
cube.height := 2;
cube.depth := 2;
sphere.radius := 1;
renderculling := AUTO;
with shapehints do begin
vertexOrdering := UNKNOWN_ORDERING;
shapetype := UNKNOWN_SHAPE_TYPE;
facetype := CONVEX;
creaseAngle := 0.5;
end;
with SpotLight do begin
lightOn := TRUE;
intensity := 1;
color := DefaultColor;
location := DefaultLocation;
direction := DefaultDirection;
dropOffRate := 0;
cutOffAngle := 0.785398;
end;
with AsciiText do begin
asciiString := '';
spacing := 1;
justification := SFLEFT;
width := 0;
end;
with Cone do begin
parts := PARTS_ALL;
bottomRadius := 1;
height := 2;
end;
cylinder := DefaultCylinder;
with Coordinate3 do begin
point [ 0 ] := 0;
point [ 1 ] := 0;
point [ 2 ] := 0;
end;
with DirectionalLight do begin
lightOn := TRUE;
intensity := 1;
color := DefaultColor;
Adirection [ 0 ] := 0;
Adirection [ 1 ] := 0;
Adirection [ 2 ] := -1;
end;
with IndexedFaceSet do begin
coordIndex := 0;
materialIndex := -1;
normalIndex := -1;
textureCoordIndex := -1;
end;
with IndexedLineSet do begin
coordIndex := 0;
materialIndex := -1;
normalIndex := -1;
textureCoordIndex := -1;
end;
Material := DefaultMaterial;
MaterialBinding := DefaultMaterialBinding;
MatrixTransform := DefaultMatrixTransform;
Transform := DefaultTransform;
PerspectiveCamera := DefaultPerspectiveCamera;
end;
end.
|
unit MD.Buttons;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.Graphics, FMX.Objects, System.Types, System.UITypes, System.Math, FMX.Ani,
FMX.FontGlyphs, System.Rtti, FMX.Consts, Threading, MD.ColorPalette, MD.Opacitys, FMX.Layouts, MD.ColorListBox, FMX.Colors,
FMX.TextLayout, System.Math.Vectors, FMX.Platform, MD.Classes;
type
TMDCustomButton = class(TControl)
private
{ Private declarations }
FText: TText;
FMaterialColor: TMaterialColor;
FFill: TBrush;
FBackgroundFocus: TCircle;
FBackgroundFocused: TRectangle;
FBackgroundPressed: TRectangle;
FMaterialTextSettings: TTextSettings;
procedure SetText(const Value: string);
function GetText: string;
procedure SetTextSettings(const Value: TTextSettings);
function GetTextSettings: TTextSettings;
function GetMaterialColor: TMaterialColor; virtual;
procedure SetMaterialColor(const Value: TMaterialColor); virtual;
procedure DoAnimationFinish(Sender: TObject);
function GetFill: TBrush;
procedure SetFill(const Value: TBrush);
function GetFocusedColor: TMaterialColor;
function GetPressedColor: TMaterialColor;
procedure SetFocusedColor(const Value: TMaterialColor);
procedure SetPressedColor(const Value: TMaterialColor);
procedure DoMaterialTextSettingsChanged(Sender: TObject);
protected
procedure FillChanged(Sender: TObject); virtual;
procedure Resize; override;
procedure Paint; override;
procedure Painting; override;
procedure DoPaint; override;
procedure DoEnter; override;
procedure DoExit; override;
procedure DoMouseEnter; override;
procedure DoMouseLeave; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseClick(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure PaintCircleButtonEffect(AMaterialColor: TMaterialColor; X, Y: Single); virtual;
property PressedColor: TMaterialColor read GetPressedColor write SetPressedColor;
property FocusedColor: TMaterialColor read GetFocusedColor write SetFocusedColor;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Fill: TBrush read GetFill write SetFill;
published
{ Published declarations }
property Align;
property Anchors;
property ClipParent;
property CanFocus default True;
property Cursor;
property DragMode;
property EnableDragHighlight;
property Enabled;
property Locked;
property Height;
property HitTest default True;
property Padding;
property Opacity;
property Margins;
property PopupMenu;
property Position;
property RotationAngle;
property RotationCenter;
property Scale;
property Size;
property TouchTargetExpansion;
property Visible;
property Width;
property TabOrder default -1;
property TabStop default True;
{ Events }
property OnPainting;
property OnPaint;
property OnResize;
{ Drag and Drop events }
property OnDragEnter;
property OnDragLeave;
property OnDragOver;
property OnDragDrop;
property OnDragEnd;
{ Mouse events }
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseEnter;
property OnMouseLeave;
property Text: string read GetText write SetText;
property TextSettings: TTextSettings read GetTextSettings write SetTextSettings;
property MaterialColor: TMaterialColor read GetMaterialColor write SetMaterialColor;
end;
type
TMDRaisedButton = class(TMDCustomButton)
private
protected
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
end;
type
TMDFlatButton = class(TMDCustomButton)
private
{ Private declarations }
protected
// function GetMaterialColor: TMaterialColor; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure SetMaterialColor(const Value: TMaterialColor); override;
function GetMaterialColor: TMaterialColor; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property MaterialColor: TMaterialColor read GetMaterialColor write SetMaterialColor;
end;
implementation
{ TMDCustomButton }
constructor TMDCustomButton.Create(AOwner: TComponent);
var
LClass: TTextSettingsClass;
begin
inherited;
Self.ClipChildren := True;
Self.CanFocus := True;
Self.TabStop := True;
Self.HitTest := True;
FMaterialColor := TMaterialColors.Blue500;
FFill := TBrush.Create(TBrushKind.None, FMaterialColor);
FFill.OnChanged := FillChanged;
FBackgroundFocused := TRectangle.Create(Self);
with FBackgroundFocused do
begin
HitTest := False;
Locked := True;
Parent := Self;
Height := Self.Height;
Width := Self.Width;
Position.X := 0;
Position.Y := 0;
Align := TAlignLayout.Contents;
Anchors := [TAnchorKind.akLeft, TAnchorKind.akTop, TAnchorKind.akRight, TAnchorKind.akBottom];
Fill.Color := TMaterialColors.Black;
Opacity := 0.0;
Stroke.Kind := TBrushKind.None;
XRadius := 2;
YRadius := 2;
SetSubComponent(True);
Stored := False;
end;
FBackgroundPressed := TRectangle.Create(Self);
with FBackgroundPressed do
begin
HitTest := False;
Locked := True;
Parent := Self;
Height := Self.Height;
Width := Self.Width;
Position.X := 0;
Position.Y := 0;
Align := TAlignLayout.Contents;
Align := TAlignLayout.None;
Anchors := [TAnchorKind.akLeft, TAnchorKind.akTop, TAnchorKind.akRight, TAnchorKind.akBottom];
Fill.Color := TMaterialColors.Black;
Opacity := 0.0;
Stroke.Kind := TBrushKind.None;
XRadius := 2;
YRadius := 2;
SetSubComponent(True);
Stored := False;
end;
FBackgroundFocus := TCircle.Create(Self);
with FBackgroundFocus do
begin
HitTest := False;
Locked := True;
Parent := Self;
Height := Self.Height;
Width := Self.Width;
Position.X := 0;
Position.Y := 0;
Align := TAlignLayout.Contents;
Align := TAlignLayout.None;
Anchors := [TAnchorKind.akLeft, TAnchorKind.akTop, TAnchorKind.akRight, TAnchorKind.akBottom];
Fill.Color := TMaterialColors.White;
Opacity := 0.0;
Stroke.Kind := TBrushKind.None;
SetSubComponent(True);
Stored := False;
end;
FText := TText.Create(Self);
with FText do
begin
Margins.Left := 8;
Margins.Right := 8;
HitTest := False;
Locked := True;
Parent := Self;
Align := TAlignLayout.Client;
Opacity := DARKTEXT_PRIMARY_OPACITY;
SetSubComponent(True);
Stored := False;
end;
LClass := nil;
if LClass = nil then
LClass := TMaterialTextSettings;
FMaterialTextSettings := LClass.Create(Self);
FMaterialTextSettings.OnChanged := DoMaterialTextSettingsChanged;
FMaterialTextSettings.BeginUpdate;
try
FMaterialTextSettings.IsAdjustChanged := True;
finally
FMaterialTextSettings.EndUpdate;
end;
end;
destructor TMDCustomButton.Destroy;
begin
Self.FreeNotification(Self);
FreeAndNil(FText);
FreeAndNil(FFill);
FreeAndNil(FBackgroundFocus);
FreeAndNil(FBackgroundFocused);
FreeAndNil(FBackgroundPressed);
FreeAndNil(FMaterialTextSettings);
inherited;
end;
procedure TMDCustomButton.DoAnimationFinish(Sender: TObject);
var
LParent: TCircle;
LAnimation: TFloatAnimation;
begin
LParent := TCircle(TAnimation(Sender).Parent);
LAnimation := TFloatAnimation(Sender);
FreeAndNil(LAnimation);
FreeAndNil(LParent);
end;
procedure TMDCustomButton.DoEnter;
begin
inherited;
if Self.IsFocused then
begin
FBackgroundFocused.Opacity := 0.1;
end;
end;
procedure TMDCustomButton.DoExit;
begin
inherited;
if not Self.IsFocused then
begin
FBackgroundFocused.Opacity := 0;
end;
end;
procedure TMDCustomButton.DoMaterialTextSettingsChanged(Sender: TObject);
begin
// if Assigned(FOnChanged) then
// FOnChanged(Self);
FText.TextSettings.Assign(FMaterialTextSettings);
end;
procedure TMDCustomButton.DoMouseEnter;
begin
inherited;
end;
procedure TMDCustomButton.DoMouseLeave;
begin
inherited;
end;
procedure TMDCustomButton.DoPaint;
begin
inherited;
end;
procedure TMDCustomButton.FillChanged(Sender: TObject);
begin
Repaint;
end;
function TMDCustomButton.GetFill: TBrush;
begin
Result := FFill;
end;
function TMDCustomButton.GetFocusedColor: TMaterialColor;
begin
Result := FBackgroundFocused.Fill.Color;
end;
function TMDCustomButton.GetMaterialColor: TMaterialColor;
begin
Result := FMaterialColor;
end;
function TMDCustomButton.GetPressedColor: TMaterialColor;
begin
Result := FBackgroundPressed.Fill.Color;
end;
function TMDCustomButton.GetText: string;
begin
Result := FText.Text;
end;
function TMDCustomButton.GetTextSettings: TTextSettings;
begin
Result := FMaterialTextSettings;
end;
procedure TMDCustomButton.MouseClick(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
inherited;
end;
procedure TMDCustomButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
inherited;
end;
procedure TMDCustomButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
inherited;
end;
procedure TMDCustomButton.Paint;
begin
inherited;
Canvas.BeginScene;
try
Canvas.FillRect(TRectF.Create(0, 0, Self.Width, Self.Height), 5, 5, [TCorner.BottomLeft, TCorner.BottomRight, TCorner.TopLeft, TCorner.TopRight],
AbsoluteOpacity, FFill, TCornerType.Round);
finally
Canvas.EndScene;
end;
end;
procedure TMDCustomButton.PaintCircleButtonEffect(AMaterialColor: TMaterialColor; X, Y: Single);
var
Circle: TCircle;
Animation: TFloatAnimation;
begin
FBackgroundFocus.StopPropertyAnimation('Opacity');
FBackgroundFocus.Opacity := 0;
Circle := TCircle.Create(nil);
Circle.Parent := Self;
Animation := TFloatAnimation.Create(nil);
Animation.Parent := Circle;
Circle.Fill.Color := AMaterialColor;
Circle.Stroke.Kind := TBrushKind.None;
Circle.HitTest := False;
Circle.Height := 10;
Circle.Width := 10;
Circle.Position.X := X - Circle.Width / 2;
Circle.Position.Y := Y - Circle.Height / 2;
Circle.Opacity := 0;
{$WARN SYMBOL_DEPRECATED OFF}
Circle.AnimateFloat('Opacity', 0.2, 0.2, TAnimationType.InOut, TInterpolationType.Linear);
Circle.AnimateFloat('Height', Self.Width * 2, 0.7, TAnimationType.InOut, TInterpolationType.Linear);
Circle.AnimateFloat('Width', Self.Width * 2, 0.7, TAnimationType.InOut, TInterpolationType.Linear);
Circle.AnimateFloat('Position.X', X - Self.Width, 0.7, TAnimationType.InOut, TInterpolationType.Linear);
Circle.AnimateFloat('Position.Y', Y - Self.Width, 0.7, TAnimationType.InOut, TInterpolationType.Linear);
Circle.StopPropertyAnimation('Opacity');
{$WARN SYMBOL_DEPRECATED ON}
Animation.AnimationType := TAnimationType.InOut;
Animation.Interpolation := TInterpolationType.Linear;
Animation.OnFinish := DoAnimationFinish;
Animation.Duration := 0.8;
Animation.PropertyName := 'Opacity';
Animation.StartFromCurrent := True;
Animation.StopValue := 0;
Animation.Start;
end;
procedure TMDCustomButton.Painting;
begin
inherited;
end;
procedure TMDCustomButton.Resize;
begin
inherited;
if Assigned(FBackgroundFocus) then
begin
with FBackgroundFocus do
begin
Height := Self.Width * 0.85;
Width := Self.Width * 0.85;
Position.X := Self.Width / 2 - Width / 2;
Position.Y := Self.Height / 2 - Height / 2;
end;
end;
end;
procedure TMDCustomButton.SetFill(const Value: TBrush);
begin
FFill.Assign(Value);
end;
procedure TMDCustomButton.SetFocusedColor(const Value: TMaterialColor);
begin
FBackgroundFocused.Fill.Color := Value;
end;
procedure TMDCustomButton.SetMaterialColor(const Value: TMaterialColor);
begin
FMaterialColor := Value;
if Assigned(FFill) then
FFill.Color := FMaterialColor;
end;
procedure TMDCustomButton.SetPressedColor(const Value: TMaterialColor);
begin
FBackgroundPressed.Fill.Color := Value;
end;
procedure TMDCustomButton.SetText(const Value: string);
begin
FText.Text := Value;
end;
procedure TMDCustomButton.SetTextSettings(const Value: TTextSettings);
begin
FText.TextSettings.Assign(Value);
end;
{ TMDRaisedButton }
constructor TMDRaisedButton.Create(AOwner: TComponent);
begin
inherited;
FFill.Kind := TBrushKind.Solid;
end;
destructor TMDRaisedButton.Destroy;
begin
inherited;
end;
procedure TMDRaisedButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
inherited;
PaintCircleButtonEffect(TMaterialColors.Black, X, Y);
end;
{ TMDFlatButton }
constructor TMDFlatButton.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TMDFlatButton.Destroy;
begin
inherited;
end;
function TMDFlatButton.GetMaterialColor: TMaterialColor;
begin
Result := inherited GetMaterialColor;
end;
procedure TMDFlatButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
inherited;
PaintCircleButtonEffect(GetMaterialColor, X, Y);
end;
procedure TMDFlatButton.SetMaterialColor(const Value: TMaterialColor);
begin
inherited SetMaterialColor(Value);
PressedColor := FMaterialColor;
FocusedColor := FMaterialColor;
end;
end.
|
unit uCestaDAO;
interface
uses
BaseDAO, FireDAC.Comp.Client;
type
TCestaDAO = class(TBaseDAO)
private
protected
function VirgulaPorPonto(Valor: string): String;
public
destructor Destroy; override;
function SelectQuery(SQL: String): TFDQuery;
function ExecQuery(SQL: String): Boolean;
function GravaCesta: String;
procedure GravaCestaItens(IDCesta: String);
end;
const
INSERTCESTA
: String = 'INSERT INTO cesta (DataCompra, ValorTotal)VALUES(%s,%s);';
LASTIDCESTA: String = ' SELECT MAX(ID) AS ID FROM cesta';
INSERTCESTAITENS
: String =
'INSERT INTO cesta_itens (cesta_ID, produto_ID, quantidade, valorTotal)VALUES(%s,%s,%s,%s)';
implementation
uses
uDM, System.SysUtils, uFrmPrincipal;
{ TCestaDAO }
destructor TCestaDAO.Destroy;
begin
inherited;
end;
function TCestaDAO.ExecQuery(SQL: String): Boolean;
begin
try
DM.FDConnection.StartTransaction;
DM.FDQuery.SQL.Text := SQL;
DM.FDQuery.ExecSQL;
Result := DM.FDQuery.RowsAffected > 0;
Except
Result := False;
end;
end;
function TCestaDAO.GravaCesta: String;
var
SQL: string;
Query: TFDQuery;
begin
SQL := format(INSERTCESTA,
['Curdate()', VirgulaPorPonto(FrmPrincipal.LTotal.Caption)]);
ExecutarComando(SQL);
Query := SelectQuery(LASTIDCESTA);
Result := Query.FieldByName('ID').AsString;
end;
procedure TCestaDAO.GravaCestaItens(IDCesta: String);
var
SQL: string;
begin
FrmPrincipal.FDMTCesta.First;
while not FrmPrincipal.FDMTCesta.Eof do
begin
SQL := format(INSERTCESTAITENS, [IDCesta, FrmPrincipal.FDMTCestaID.AsString,
FrmPrincipal.FDMTCestaQuantidade.AsString,
VirgulaPorPonto(FrmPrincipal.FDMTCestaPrecoVenda.AsString)]);
ExecutarComando(SQL);
FrmPrincipal.FDMTCesta.Next;
end;
end;
function TCestaDAO.SelectQuery(SQL: String): TFDQuery;
begin
DM.FDQuery.SQL.Text := SQL;
DM.FDQuery.Active := True;
Result := DM.FDQuery;
end;
function TCestaDAO.VirgulaPorPonto(Valor: string): String;
var
i: Integer;
vlrSemPonto: String;
begin
vlrSemPonto := StringReplace(Valor, '.', '', [rfReplaceAll, rfIgnoreCase]);
if vlrSemPonto <> '' then
begin
for i := 0 to Length(vlrSemPonto) do
begin
if vlrSemPonto[i] = ',' then
vlrSemPonto[i] := '.';
end;
end;
Result := vlrSemPonto;
end;
end.
|
unit Expedicao.Controller.uCombustivel;
interface
uses
System.SysUtils,
System.JSON,
FireDAC.Comp.Client,
Base.uControllerBase,
Expedicao.Models.uCombustivel;
type
TCombustivelController = class(TControllerBase)
private
{ Private declarations }
function ObterCombustivelDaQuery(pQry: TFDQuery): TCombustivel;
function ObterCombustivelPeloOID(pCombustivelOID: Integer): TCombustivel;
function IncluirCombustivel(pCombustivel: TCombustivel): Boolean;
function AlterarCombustivel(pCombustivel: TCombustivel): Boolean;
public
{ Public declarations }
function Combustiveis: TJSONValue;
function Combustivel(ID: Integer): TJSONValue;
function updateCombustivel(Combustivel: TJSONObject): TJSONValue;
function acceptCombustivel(Combustivel: TJSONObject): TJSONValue;
function cancelCombustivel(ID: Integer): TJSONValue;
end;
implementation
uses
REST.jSON,
uDataModule,
Expedicao.Services.uCombustivel;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TCombustivelController }
function TCombustivelController.ObterCombustivelDaQuery(
pQry: TFDQuery): TCombustivel;
var
lSvcCombustivel: TCombustivelService;
begin
lSvcCombustivel := TCombustivelService.Create;
try
Result := lSvcCombustivel.ObterCombustivelDaQuery(pQry);
finally
lSvcCombustivel.Free;
end;
end;
function TCombustivelController.ObterCombustivelPeloOID(
pCombustivelOID: Integer): TCombustivel;
var
lSvcCombustivel: TCombustivelService;
begin
lSvcCombustivel := TCombustivelService.Create;
try
Result := lSvcCombustivel.ObterCombustivelPeloOID(pCombustivelOID);
finally
lSvcCombustivel.Free;
end;
end;
function TCombustivelController.IncluirCombustivel(
pCombustivel: TCombustivel): Boolean;
var
lQry: TFDQuery;
begin
Result := False;
lQry := DataModule1.ObterQuery;
try
with lQry do
begin
SQL.Add('INSERT INTO Combustivel (');
SQL.Add('Descricao, Valor, UnidadeMedidaOID');
SQL.Add(') VALUES (');
SQL.Add(':Descricao, :Valor, :UnidadeMedidaOID');
SQL.Add(');');
ParamByName('Descricao').AsString := pCombustivel.Descricao;
ParamByName('Valor').AsFloat := pCombustivel.Valor;
ParamByName('UnidadeMedidaOID').AsInteger := pCombustivel.UnidadeDeMedidaOID;
ExecSQL;
Result := True;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
function TCombustivelController.AlterarCombustivel(
pCombustivel: TCombustivel): Boolean;
var
lQry: TFDQuery;
begin
Result := False;
lQry := DataModule1.ObterQuery;
try
with lQry do
begin
SQL.Add('UPDATE Combustivel SET ');
SQL.Add(' Descricao = :Descricao,');
SQL.Add(' Valor = :Valor, ');
SQL.Add(' UnidadeMedidaOID = :UnidadeMedidaOID ');
SQL.Add('WHERE CombustivelOID = :CombustivelOID');
ParamByName('Descricao').AsString := pCombustivel.Descricao;
ParamByName('Valor').AsFloat := pCombustivel.Valor;
ParamByName('UnidadeMedidaOID').AsInteger := pCombustivel.UnidadeDeMedidaOID;
ParamByName('CombustivelOID').AsInteger := pCombustivel.CombustivelOID;
ExecSQL;
Result := True;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
function TCombustivelController.Combustiveis: TJSONValue;
var
lCombustivel: TCombustivel;
lQry: TFDQuery;
begin
lQry := DataModule1.ObterQuery;
try
with lQry do
begin
Open('SELECT * FROM Combustivel');
if IsEmpty then
begin
Result := TJSONString.Create('Nenhum combustível encontrado!');
ConfigurarResponse(tmNotFound);
end;
Result := TJSONArray.Create;
while not Eof do
begin
lCombustivel := ObterCombustivelDaQuery(lQry);
(Result as TJSONArray).AddElement(TJson.ObjectToJsonObject(lCombustivel));
ConfigurarResponse(tmOK);
Next;
end;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
function TCombustivelController.Combustivel(ID: Integer): TJSONValue;
var
lCombustivel: TCombustivel;
begin
lCombustivel := ObterCombustivelPeloOID(ID);
if not Assigned(lCombustivel) then
begin
Result := TJSONString.Create('Combustível não encontrado!');
ConfigurarResponse(tmNotFound);
end
else
begin
Result := TJson.ObjectToJsonObject(lCombustivel);
ConfigurarResponse(tmOK);
lCombustivel.Free;
end;
end;
function TCombustivelController.acceptCombustivel(
Combustivel: TJSONObject): TJSONValue;
var
lCombustivelEnviado, lCombustivelCadastrado: TCombustivel;
begin
lCombustivelEnviado := TJson.JsonToObject<TCombustivel>(Combustivel);
try
lCombustivelCadastrado := ObterCombustivelPeloOID(lCombustivelEnviado.CombustivelOID);
if Assigned(lCombustivelCadastrado) then
begin
Result := TJSONString.Create('Combustível já cadastrado. Inclusão cancelada!');
ConfigurarResponse(tmObjectAlreadyExists);
lCombustivelCadastrado.Free;
Exit;
end;
try
if IncluirCombustivel(lCombustivelEnviado) then
begin
Result := TJSONString.Create('Combustível gravado com sucesso!');
ConfigurarResponse(tmOK);
end
else
raise Exception.Create('Erro ao gravar o combustível!');
except
on e: Exception do
begin
Result := TJSONString.Create(e.Message);
ConfigurarResponse(tmUndefinedError);
end;
end;
finally
lCombustivelEnviado.Free;
end;
end;
function TCombustivelController.updateCombustivel(
Combustivel: TJSONObject): TJSONValue;
var
lCombustivelEnviado, lCombustivelCadastrado: TCombustivel;
begin
lCombustivelEnviado := TJson.JsonToObject<TCombustivel>(Combustivel);
try
lCombustivelCadastrado := ObterCombustivelPeloOID(lCombustivelEnviado.CombustivelOID);
if not Assigned(lCombustivelCadastrado) then
begin
Result := TJSONString.Create('Combustível não encontrado!');
ConfigurarResponse(tmNotFound);
Exit;
end;
lCombustivelCadastrado.Free;
try
if AlterarCombustivel(lCombustivelEnviado) then
begin
Result := TJSONString.Create('Combustível gravado com sucesso!');
ConfigurarResponse(tmOK);
end
else
raise Exception.Create('Erro ao gravar a combustível!');
except
on e: Exception do
begin
Result := TJSONString.Create(e.Message);
ConfigurarResponse(tmUndefinedError);
end;
end;
finally
lCombustivelEnviado.Free;
end;
end;
function TCombustivelController.cancelCombustivel(ID: Integer): TJSONValue;
var
lQry: TFDQuery;
lCombustivel: TCombustivel;
begin
lCombustivel := ObterCombustivelPeloOID(ID);
if not Assigned(lCombustivel) then
begin
Result := TJSONString.Create('Combustível não encontrado!');
ConfigurarResponse(tmNotFound);
Exit;
end;
lCombustivel.Free;
lQry := DataModule1.ObterQuery;
try
try
with lQry do
begin
SQL.Add('DELETE FROM Combustivel WHERE CombustivelOID = :CombustivelOID');
ParamByName('CombustivelOID').AsInteger := ID;
ExecSQL;
Result := TJSONString.Create('Combustível excluído com sucesso!');
ConfigurarResponse(tmOK);
end;
except
on e: Exception do
begin
Result := TJSONString.Create('Erro ao excluir o combustível!');
ConfigurarResponse(tmUndefinedError);
end;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
end.
|
unit NeoEcommerceService.Model.Connections.ClientDataSet;
interface
uses
NeoEcommerceService.Model.Connections.Interfaces, System.Classes, Data.DB, Datasnap.DBClient, MidasLib;
type
TModelConnetionsClientDataSet = class(TInterfacedObject, iModelClientDataSet)
private
FDataSet: TClientDataSet;
public
constructor Create;
destructor Destroy; override;
class function New: iModelClientDataSet;
function SetDataSet(aValue: TClientDataSet): iModelClientDataSet;
function EndDataSet: TClientDataSet;
function Free: iModelClientDataSet;
end;
implementation
uses
System.SysUtils;
{ TModelConnetionsClientDataSet }
constructor TModelConnetionsClientDataSet.Create;
begin
//FDataSet := TFDTable.Create(nil);
if not Assigned(FDataSet) then
FDataSet := TClientDataSet.Create(nil);
end;
destructor TModelConnetionsClientDataSet.Destroy;
begin
FreeAndNil(FDataSet);
inherited;
end;
function TModelConnetionsClientDataSet.EndDataSet: TClientDataSet;
begin
Result := FDataSet;
end;
function TModelConnetionsClientDataSet.Free: iModelClientDataSet;
begin
Result := Self;
//FDataSet.Free;
Self.Destroy;
end;
class function TModelConnetionsClientDataSet.New: iModelClientDataSet;
begin
Result := Self.Create();
end;
function TModelConnetionsClientDataSet.SetDataSet(aValue: TClientDataSet): iModelClientDataSet;
begin
Result := Self;
FDataSet := aValue as TClientDataSet;
end;
end.
|
{
TabSet
作者: Terry(江晓德)
QQ: 67068633
Email:jxd524@163.com
创建时间:2012-1-30
最后修改时间 2012-1-31
}
unit uJxdGpTabSet;
interface
uses
Classes, Windows, Controls, Graphics, Messages, ExtCtrls, SysUtils,
GDIPAPI, GDIPOBJ, uJxdGpBasic, uJxdGpCommon, uJxdGpStyle;
type
TxdGpTabSet = class(TxdGpCommon)
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function AddTabItem(const ACaption: string; const AItemTag: Integer): Integer;
procedure DeleteTabItem(const AIndex: Integer);
protected
procedure DrawGraphics(const AGh: TGPGraphics); override;
function DoGetDrawState(const Ap: PDrawInfo): TxdGpUIState; override;
procedure DoSubItemMouseDown(const Ap: PDrawInfo); override;
procedure Resize; override;
procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE;
private
FCurCloseRect: TGPRect;
FCurCloseState: TxdGpUIState;
FTabItemGuid: Integer;
FCurTabItemWidth: Integer;
function GetLastRect: TGPRect;
procedure CalcCurTabItemWidth;
procedure ReSetAllTabItemWidth;
procedure ChangedNewTabItem(const Ap: PDrawInfo);
private
FTabItemDrawStyle: TxdGpDrawStyle;
FItemIndex: Integer;
FImageTabItemClose: TImageInfo;
procedure SetTabItemDrawStyle(const Value: TxdGpDrawStyle);
procedure SetItemIndex(const Value: Integer);
procedure SetImageTabItemClose(const Value: TImageInfo);
published
property ImageTabItemClose: TImageInfo read FImageTabItemClose write SetImageTabItemClose;
property TabItemDrawStyle: TxdGpDrawStyle read FTabItemDrawStyle write SetTabItemDrawStyle;
property ItemIndex: Integer read FItemIndex write SetItemIndex;
end;
implementation
uses
uJxdGpSub;
const
CtTabItemMaxWidth = 220;
CtTabItemMinWidth = 5;
{ TxdGpTabSet }
function TxdGpTabSet.AddTabItem(const ACaption: string; const AItemTag: Integer): Integer;
var
it: TDrawInfo;
R: TGPRect;
nTemp, nImgW: Integer;
begin
if not Assigned(ImageInfo.Image) then
begin
Result := -1;
Exit;
end;
R := GetLastRect;
if R.Width = 0 then
begin
//first
R.Width := FCurTabItemWidth;
R.Height := Height;
end
else
begin
Inc( R.X, FCurTabItemWidth );
end;
it.FText := ACaption;
it.FDestRect := R;
it.FItemTag := AItemTag;
it.FLayoutIndex := 0;
it.FClickID := FTabItemGuid;
it.FDrawStyle := TabItemDrawStyle;
nTemp := Integer(ImageInfo.Image.GetHeight) div ImageInfo.ImageCount;
nImgW := Integer(ImageInfo.Image.GetWidth);
//Down
if ImageInfo.ImageCount >= 3 then
it.FDownSrcRect := MakeRect(0, nTemp * 2, nImgW, nTemp)
else
it.FDownSrcRect := MakeRect(0, nTemp, nImgW, nTemp);
//Active
if ImageInfo.ImageCount >= 2 then
it.FActiveSrcRect := MakeRect(0, nTemp, nImgW, nTemp)
else
it.FActiveSrcRect := MakeRect(0, 0, nImgW, nTemp);
//Normal
it.FNormalSrcRect := MakeRect(0, 0, nImgW, nTemp);
Result := ImageDrawMethod.AddDrawInfo( @it );
if FItemIndex = -1 then
FItemIndex := FTabItemGuid;
Inc( FTabItemGuid );
CalcCurTabItemWidth;
ReSetAllTabItemWidth;
Invalidate;
end;
procedure TxdGpTabSet.CalcCurTabItemWidth;
var
nWidth: Integer;
begin
FCurTabItemWidth := CtTabItemMaxWidth;
if ImageDrawMethod.CurDrawInfoCount = 0 then Exit;
nWidth := Width div ImageDrawMethod.CurDrawInfoCount;
if nWidth > CtTabItemMaxWidth then
FCurTabItemWidth := CtTabItemMaxWidth
else if nWidth >= CtTabItemMinWidth then
FCurTabItemWidth := nWidth
else
FCurTabItemWidth := CtTabItemMinWidth;
end;
procedure TxdGpTabSet.ChangedNewTabItem(const Ap: PDrawInfo);
var
p: PDrawInfo;
i, nOldIndex: Integer;
begin
if FItemIndex <> Ap^.FClickID then
begin
nOldIndex := FItemIndex;
FItemIndex := Ap^.FClickID;
InvalidateRect( Ap^.FDestRect );
for i := 0 to ImageDrawMethod.CurDrawInfoCount - 1 do
begin
p := ImageDrawMethod.GetDrawInfo(i);
if p^.FClickID = nOldIndex then
begin
InvalidateRect( p^.FDestRect );
Break;
end;
end;
end;
end;
constructor TxdGpTabSet.Create(AOwner: TComponent);
begin
inherited;
ImageDrawMethod.DrawStyle := dsDrawByInfo;
Width := 500;
Height := 25;
FCurTabItemWidth := CtTabItemMaxWidth;
FTabItemDrawStyle := dsStretchByVH;
FItemIndex := -1;
Caption := '';
ImageDrawMethod.AutoSort := False;
FTabItemGuid := 999;
FImageTabItemClose := TImageInfo.Create;
FImageTabItemClose.OnChange := DoObjectChanged;
FCurCloseRect := MakeRect(0, 0, 0, 0);
FCurCloseState := uiNormal;
end;
procedure TxdGpTabSet.DeleteTabItem(const AIndex: Integer);
var
nIndex: Integer;
p: PDrawInfo;
begin
if (AIndex >= 0) and (AIndex < ImageDrawMethod.CurDrawInfoCount) then
begin
p := ImageDrawMethod.GetDrawInfo( AIndex );
if FItemIndex = p^.FClickID then
FItemIndex := -1;
ImageDrawMethod.DeleteDrawInfo( AIndex );
CalcCurTabItemWidth;
ReSetAllTabItemWidth;
if FItemIndex = -1 then
begin
nIndex := AIndex mod ImageDrawMethod.CurDrawInfoCount;
p := ImageDrawMethod.GetDrawInfo( nIndex );
if Assigned(p) then
FItemIndex := p^.FClickID;
end;
Invalidate;
end;
end;
destructor TxdGpTabSet.Destroy;
begin
inherited;
end;
function TxdGpTabSet.DoGetDrawState(const Ap: PDrawInfo): TxdGpUIState;
begin
if Assigned(Ap) and (FItemIndex = Ap^.FClickID) then
Result := uiDown
else
Result := inherited DoGetDrawState(Ap);
end;
procedure TxdGpTabSet.DoSubItemMouseDown(const Ap: PDrawInfo);
begin
if Assigned(Ap) then
ChangedNewTabItem( Ap );
end;
procedure TxdGpTabSet.DrawGraphics(const AGh: TGPGraphics);
var
pt: TPoint;
p: PDrawInfo;
bmpR: TGPRect;
nW, nH: Integer;
st: TxdGpUIState;
begin
//TabItem
DrawImageCommon( AGh, MakeRect(0, 0, Width, Height), ImageInfo, ImageDrawMethod,
DoGetDrawState, DoIsDrawSubItem, DoDrawSubItemText, DoChangedSrcBmpRect );
//TabItem Close Button
p := CurActiveSubItem;
if Assigned(p) and Assigned(FImageTabItemClose.Image) then
begin
GetCursorPos( pt );
pt := ScreenToClient(pt);
nW := FImageTabItemClose.Image.GetWidth;
nH := Integer(FImageTabItemClose.Image.GetHeight) div FImageTabItemClose.ImageCount;
FCurCloseRect := MakeRect( p^.FDestRect.X + p^.FDestRect.Width - nW - 2,
2, nW, nH );
//
if PtInGpRect(pt.X, pt.Y, FCurCloseRect) then
begin
st := uiActive;
if GetCurControlState = uiDown then
st := uiDown;
end
else
st := uiNormal;
case st of
uiDown:
begin
if FImageTabItemClose.ImageCount >= 3 then
BmpR := MakeRect(0, nH * 2, nW, nH)
else
bmpR := MakeRect(0, nH, nW, nH)
end;
uiActive:
begin
if FImageTabItemClose.ImageCount >= 2 then
bmpR := MakeRect(0, nH, nW, nH)
else
bmpR := MakeRect(0, 0, nW, nH)
end;
else
bmpR := MakeRect(0, 0, nW, nH);
end;
//Paste
AGh.DrawImage( FImageTabItemClose.Image, FCurCloseRect, BmpR.X, BmpR.Y, nW, nH, UnitPixel );
end;
end;
function TxdGpTabSet.GetLastRect: TGPRect;
var
i: Integer;
p: PDrawInfo;
begin
Result := MakeRect(0, 0, 0, 0);
for i := 0 to ImageDrawMethod.CurDrawInfoCount - 1 do
begin
p := ImageDrawMethod.GetDrawInfo(i);
if p^.FDestRect.X >= Result.X then
Result := p^.FDestRect;
end;
end;
procedure TxdGpTabSet.ReSetAllTabItemWidth;
var
i, X: Integer;
p: PDrawInfo;
begin
x := 0;
for i := 0 to ImageDrawMethod.CurDrawInfoCount - 1 do
begin
p := ImageDrawMethod.GetDrawInfo(i);
p^.FDestRect.X := x;
p^.FDestRect.Width := FCurTabItemWidth;
Inc( x, FCurTabItemWidth );
end;
end;
procedure TxdGpTabSet.Resize;
begin
inherited;
CalcCurTabItemWidth;
ReSetAllTabItemWidth;
end;
procedure TxdGpTabSet.SetImageTabItemClose(const Value: TImageInfo);
begin
FImageTabItemClose.Assign( Value );
end;
procedure TxdGpTabSet.SetItemIndex(const Value: Integer);
var
p: PDrawInfo;
begin
if (Value >= 0) and (Value < ImageDrawMethod.CurDrawInfoCount) then
begin
p := ImageDrawMethod.GetDrawInfo(Value);
if Assigned(p) then
ChangedNewTabItem( p );
end;
end;
procedure TxdGpTabSet.SetTabItemDrawStyle(const Value: TxdGpDrawStyle);
begin
if FTabItemDrawStyle <> Value then
begin
FTabItemDrawStyle := Value;
Invalidate;
end;
end;
procedure TxdGpTabSet.WMMouseMove(var Message: TWMMouseMove);
begin
inherited;
end;
end.
|
unit Aurelius.Schema.SQLite;
{$I Aurelius.Inc}
interface
uses
Generics.Collections,
Aurelius.Drivers.Interfaces,
Aurelius.Schema.AbstractImporter,
Aurelius.Sql.Metadata;
type
TSQLiteSchemaImporter = class(TAbstractSchemaImporter)
strict protected
procedure GetDatabaseMetadata(Connection: IDBConnection; Database: TDatabaseMetadata); override;
end;
TSQLiteSchemaRetriever = class(TSchemaRetriever)
strict private
function AreSameColumns(OldCols, NewCols: TList<TColumnMetadata>): boolean;
procedure GetTables;
procedure GetColumns(Table: TTableMetadata; const SQL: string);
procedure GetUniqueKeys(Table: TTableMetadata);
procedure GetUniqueKeyColumns(UniqueKey: TUniqueKeyMetadata);
procedure GetForeignKeys;
public
constructor Create(AConnection: IDBConnection; ADatabase: TDatabaseMetadata); override;
procedure RetrieveDatabase; override;
end;
implementation
uses
SysUtils,
Aurelius.Schema.Register,
Aurelius.Schema.Utils;
{ TSQLiteSchemaImporter }
procedure TSQLiteSchemaImporter.GetDatabaseMetadata(Connection: IDBConnection;
Database: TDatabaseMetadata);
var
Retriever: TSchemaRetriever;
begin
Retriever := TSQLiteSchemaRetriever.Create(Connection, Database);
try
Retriever.RetrieveDatabase;
finally
Retriever.Free;
end;
end;
{ TSQLiteSchemaRetriever }
function TSQLiteSchemaRetriever.AreSameColumns(OldCols, NewCols: TList<TColumnMetadata>): boolean;
var
OldCol, NewCol: TColumnMetadata;
Found: boolean;
begin
if OldCols.Count <> NewCols.Count then
Exit(false);
for OldCol in OldCols do
begin
Found := false;
for NewCol in NewCols do
if SameText(NewCol.Name, OldCol.Name) then
begin
Found := true;
break;
end;
if not Found then Exit(false);
end;
Result := true;
end;
constructor TSQLiteSchemaRetriever.Create(AConnection: IDBConnection;
ADatabase: TDatabaseMetadata);
begin
inherited Create(AConnection, ADatabase);
end;
procedure TSQLiteSchemaRetriever.GetColumns(Table: TTableMetadata; const SQL: string);
var
ResultSet: IDBResultSet;
Column: TColumnMetadata;
begin
ResultSet := Open(Format('pragma table_info("%s")', [Table.Name]));
while ResultSet.Next do
begin
Column := TColumnMetadata.Create(Table);
Table.Columns.Add(Column);
Column.Name := AsString(ResultSet.GetFieldValue('name'));
Column.NotNull := AsInteger(ResultSet.GetFieldValue('notnull')) <> 0;
Column.DataType := AsString(ResultSet.GetFieldValue('type'));
// If column is primary key, add it to IdColumns
if AsInteger(ResultSet.GetFieldValue('pk')) <> 0 then
Table.IdColumns.Add(Column);
end;
// Set autoincrement in a quick and dirty way. We could parse the SQL or use sqlite3_table_column_metadata but
// this way should work fine for Aurelius usage
if (Table.IdColumns.Count = 1) and (Pos('autoincrement', Lowercase(SQL)) > 0) then
Table.IdColumns[0].AutoGenerated := true;
end;
procedure TSQLiteSchemaRetriever.GetForeignKeys;
var
Table: TTableMetadata;
ResultSet: IDBResultSet;
ForeignKey: TForeignKeyMetadata;
LastId: integer;
begin
for Table in Database.Tables do
begin
ResultSet := Open(Format('pragma foreign_key_list("%s")', [Table.Name]));
ForeignKey := nil;
LastId := -1;
while ResultSet.Next do
begin
if (ForeignKey = nil) or (LastId <> AsInteger(ResultSet.GetFieldValue('id'))) then
begin
ForeignKey := TForeignKeyMetadata.Create(Table);
Table.ForeignKeys.Add(ForeignKey);
ForeignKey.Name := Format('FK_%s_%s', [AsString(ResultSet.GetFieldValue('id')), Table.Name]);
ForeignKey.ToTable := TSchemaUtils.GetTable(Database, AsString(ResultSet.GetFieldValue('table')), '');
LastId := AsInteger(ResultSet.GetFieldValue('id'));
end;
ForeignKey.FromColumns.Add(TSchemaUtils.GetColumn(ForeignKey.FromTable, AsString(ResultSet.GetFieldValue('from'))));
ForeignKey.ToColumns.Add(TSchemaUtils.GetColumn(ForeignKey.ToTable, AsString(ResultSet.GetFieldValue('to'))));
end;
end;
end;
procedure TSQLiteSchemaRetriever.GetTables;
var
ResultSet: IDBResultSet;
Table: TTableMetadata;
SQL: string;
begin
ResultSet := Open(
'SELECT tbl_name as TABLE_NAME, '+
'sql as TABLE_SQL '+
'FROM sqlite_master '+
'WHERE type = ''table'' '+
'AND tbl_name NOT LIKE ''sqlite_%'' '+
'ORDER BY tbl_name'
);
while ResultSet.Next do
begin
Table := TTableMetadata.Create(Database);
Database.Tables.Add(Table);
Table.Name := AsString(ResultSet.GetFieldValue('TABLE_NAME'));
SQL := AsString(ResultSet.GetFieldValue('TABLE_SQL'));
GetColumns(Table, SQL);
GetUniqueKeys(Table);
end;
end;
procedure TSQLiteSchemaRetriever.GetUniqueKeyColumns(UniqueKey: TUniqueKeyMetadata);
var
ResultSet: IDBResultSet;
begin
ResultSet := Open(Format('pragma index_info("%s")', [UniqueKey.Name]));
while ResultSet.Next do
UniqueKey.Columns.Add(TSchemaUtils.GetColumn(UniqueKey.Table, AsString(ResultSet.GetFieldValue('name'))));
end;
procedure TSQLiteSchemaRetriever.GetUniqueKeys(Table: TTableMetadata);
var
ResultSet: IDBResultSet;
UniqueKey: TUniqueKeyMetadata;
Column: TColumnMetadata;
begin
ResultSet := Open(Format('pragma index_list("%s")', [Table.Name]));
while ResultSet.Next do
if AsInteger(ResultSet.GetFieldValue('unique')) <> 0 then
begin
UniqueKey := TUniqueKeyMetadata.Create(Table);
Table.UniqueKeys.Add(UniqueKey);
UniqueKey.Name := AsString(ResultSet.GetFieldValue('name'));
GetUniqueKeyColumns(UniqueKey);
// If unique key relates to primary key, then now we have the correct
// order for the primary key. We should then set the correct column order
// in primary key, then remove the unique key
if AreSameColumns(UniqueKey.Columns, Table.IdColumns) then
begin
Table.IdColumns.Clear;
for Column in UniqueKey.Columns do
Table.IdColumns.Add(Column);
Table.UniqueKeys.Remove(UniqueKey);
end;
end;
end;
procedure TSQLiteSchemaRetriever.RetrieveDatabase;
begin
Database.Clear;
GetTables;
GetForeignKeys;
end;
initialization
TSchemaImporterRegister.GetInstance.RegisterImporter('SQLite', TSQLiteSchemaImporter.Create);
end.
|
unit UMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls;
type
TForm1 = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Com_drvie: TComboBox;
TreeView1: TTreeView;
Button1: TButton;
Button2: TButton;
Drive_Background: TShape;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
IsSearching: Boolean;
{ Private declarations }
procedure GetDiskType(DriveList: TComboBox);
public
property myIsSearching: Boolean read IsSearching write IsSearching;
procedure startdemo();
end;
var
Form1: TForm1;
implementation
uses
UMy_Disk;
{$R *.dfm}
{ TForm1 }
var
disk: My_Disk;
procedure TForm1.Button1Click(Sender: TObject);
begin
TThread.CreateAnonymousThread(startdemo).Start;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Com_drvie.ItemIndex := 0;
disk:= My_Disk.Create;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
GetDiskType(Com_drvie);
end;
procedure TForm1.GetDiskType(DriveList: TComboBox);
var
str: string;
Drivers: Integer;
driver: char;
i, temp: integer;
d1, d2, d3, d4: DWORD;
ss: string;
begin
ss := '';
Drivers := GetLogicalDrives;
temp := (1 and Drivers);
for i := 0 to 26 do
begin
if temp = 1 then
begin
driver := char(i + integer('A'));
str := driver;
if (driver <> '') and (getdrivetype(pchar(str)) <> drive_cdrom) and (getdrivetype(pchar(str)) <> DRIVE_REMOVABLE) then //这里可以修改 获取光盘 可移动磁盘
begin
GetDiskFreeSpace(pchar(str), d1, d2, d3, d4);
DriveList.Items.Add(str + ':');
end;
end;
Drivers := (Drivers shr 1);
temp := (1 and Drivers);
end;
end;
procedure TForm1.startdemo;
begin
disk.myStart;
end;
end.
|
unit Expedicao.Controller.uRomaneio;
interface
uses
System.SysUtils,
System.JSON,
FireDAC.Comp.Client,
Base.uControllerBase,
Expedicao.Models.uRomaneio;
type
TRomaneioController = class(TControllerBase)
private
{ Private declarations }
function ObterRomaneioDaQuery(pQry: TFDQuery): TRomaneio;
function ObterRomaneioPeloOID(pRomaneioOID: Integer): TRomaneio;
function IncluirRomaneio(pRomaneio: TRomaneio): Boolean;
function AlterarRomaneio(pRomaneio: TRomaneio): Boolean;
function TestarVeiculoCadastrado(pVeiculoOID: Integer): Boolean;
public
{ Public declarations }
function Romaneios: TJSONValue;
function Romaneio(ID: Integer): TJSONValue;
function updateRomaneio(Romaneio: TJSONObject): TJSONValue;
function acceptRomaneio(Romaneio: TJSONObject): TJSONValue;
function cancelRomaneio(ID: Integer): TJSONValue;
end;
implementation
uses
REST.jSON,
uDataModule;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TRomaneioController }
function TRomaneioController.ObterRomaneioDaQuery(pQry: TFDQuery): TRomaneio;
begin
Result := TRomaneio.Create;
with Result do
begin
RomaneioOID := pQry.FieldByName('RomaneioOID').AsInteger;
VeiculoOID := pQry.FieldByName('VeiculoOID').AsInteger;
CondutorOID := pQry.FieldByName('CondutorOID').AsInteger;
Saida := pQry.FieldByName('Saida').AsDateTime;
Retorno := pQry.FieldByName('Retorno').AsDateTime;
KMSaida := pQry.FieldByName('KMSaida').AsFloat;
KMRetorno := pQry.FieldByName('KMRetorno').AsFloat;
KMRodado := pQry.FieldByName('KMRodado').AsFloat;
FuncionarioSaidaOID := pQry.FieldByName('FuncionarioSaidaOID').AsInteger;
FuncionarioRetornoOID := pQry.FieldByName('FuncionarioRetornoOID').AsInteger;
end;
end;
function TRomaneioController.ObterRomaneioPeloOID(
pRomaneioOID: Integer): TRomaneio;
var
lQry: TFDQuery;
begin
Result := nil;
lQry := DataModule1.ObterQuery;
try
lQry.Open('SELECT * FROM Romaneio WHERE RomaneioOID = :RomaneioOID',
[pRomaneioOID]);
if lQry.IsEmpty then
Exit;
Result := ObterRomaneioDaQuery(lQry);
finally
DataModule1.DestruirQuery(lQry);
end;
end;
function TRomaneioController.IncluirRomaneio(pRomaneio: TRomaneio): Boolean;
var
lQry: TFDQuery;
begin
Result := False;
lQry := DataModule1.ObterQuery;
try
with lQry do
begin
SQL.Add('INSERT INTO Romaneio (');
SQL.Add('VeiculoOID, CondutorOID, Saida, Retorno, KMSaida, KMRetorno, KMRodado, FuncionarioSaidaOID, FuncionarioRetornoOID');
SQL.Add(') VALUES (');
SQL.Add(':VeiculoOID, :CondutorOID, :Saida, :Retorno, :KMSaida, :KMRetorno, :KMRodado, :FuncionarioSaidaOID, :FuncionarioRetornoOID');
SQL.Add(');');
ParamByName('VeiculoOID').AsInteger := pRomaneio.VeiculoOID;
ParamByName('CondutorOID').AsInteger := pRomaneio.CondutorOID;
ParamByName('Saida').AsDateTime := pRomaneio.Saida;
ParamByName('Retorno').AsDateTime := pRomaneio.Retorno;
ParamByName('KMSaida').AsFloat := pRomaneio.KMSaida;
ParamByName('KMRetorno').AsFloat := pRomaneio.KMRetorno;
ParamByName('KMRodado').AsFloat := pRomaneio.KMRodado;
ParamByName('FuncionarioSaidaOID').AsInteger := pRomaneio.FuncionarioSaidaOID;
ParamByName('FuncionarioRetornoOID').AsInteger := pRomaneio.FuncionarioRetornoOID;
ExecSQL;
Result := True;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
function TRomaneioController.AlterarRomaneio(pRomaneio: TRomaneio): Boolean;
var
lQry: TFDQuery;
begin
Result := False;
lQry := DataModule1.ObterQuery;
try
with lQry do
begin
SQL.Add('UPDATE Romaneio SET ');
SQL.Add(' VeiculoOID = :VeiculoOID,');
SQL.Add(' CondutorOID = :CondutorOID, ');
SQL.Add(' Saida = :Saida, ');
SQL.Add(' Retorno = :Retorno, ');
SQL.Add(' KMSaida = :KMSaida, ');
SQL.Add(' KMRetorno = :KMRetorno, ');
SQL.Add(' KMRodado = :KMRodado, ');
SQL.Add(' FuncionarioSaidaOID = :FuncionarioSaidaOID, ');
SQL.Add(' FuncionarioRetornoOID = :FuncionarioRetornoOID ');
SQL.Add('WHERE RomaneioOID = :RomaneioOID');
ParamByName('RomaneioOID').AsInteger := pRomaneio.RomaneioOID;
ParamByName('VeiculoOID').AsInteger := pRomaneio.VeiculoOID;
ParamByName('CondutorOID').AsInteger := pRomaneio.CondutorOID;
ParamByName('Saida').AsDateTime := pRomaneio.Saida;
ParamByName('Retorno').AsDateTime := pRomaneio.Retorno;
ParamByName('KMSaida').AsFloat := pRomaneio.KMSaida;
ParamByName('KMRetorno').AsFloat := pRomaneio.KMRetorno;
ParamByName('KMRodado').AsFloat := pRomaneio.KMRodado;
ParamByName('FuncionarioSaidaOID').AsInteger := pRomaneio.FuncionarioSaidaOID;
ParamByName('FuncionarioRetornoOID').AsInteger := pRomaneio.FuncionarioRetornoOID;
ExecSQL;
Result := True;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
function TRomaneioController.Romaneios: TJSONValue;
var
lRomaneio: TRomaneio;
lQry: TFDQuery;
begin
lQry := DataModule1.ObterQuery;
try
with lQry do
begin
Open('SELECT * FROM Romaneio');
if IsEmpty then
begin
Result := TJSONString.Create('Nenhum romaneio encontrado!');
ConfigurarResponse(tmNotFound);
end;
Result := TJSONArray.Create;
while not Eof do
begin
lRomaneio := ObterRomaneioDaQuery(lQry);
(Result as TJSONArray).AddElement(TJson.ObjectToJsonObject(lRomaneio));
ConfigurarResponse(tmOK);
Next;
end;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
function TRomaneioController.TestarVeiculoCadastrado(
pVeiculoOID: Integer): Boolean;
var
lQry: TFDQuery;
begin
Result := False;
lQry := DataModule1.ObterQuery;
try
with lQry do
begin
Open('SELECT COUNT(*) AS Total FROM Veiculo WHERE VeiculoOID = :VeiculoOID', [pVeiculoOID]);
Result := FieldByName('Total').AsInteger > 0;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
function TRomaneioController.Romaneio(ID: Integer): TJSONValue;
var
lRomaneio: TRomaneio;
begin
lRomaneio := ObterRomaneioPeloOID(ID);
if not Assigned(lRomaneio) then
begin
Result := TJSONString.Create('Romaneio não encontrado!');
ConfigurarResponse(tmNotFound);
end
else
begin
Result := TJson.ObjectToJsonObject(lRomaneio);
ConfigurarResponse(tmOK);
lRomaneio.Free;
end;
end;
function TRomaneioController.acceptRomaneio(Romaneio: TJSONObject): TJSONValue;
var
lRomaneioEnviado, lRomaneioCadastrado: TRomaneio;
begin
lRomaneioEnviado := TJson.JsonToObject<TRomaneio>(Romaneio);
try
lRomaneioCadastrado := ObterRomaneioPeloOID(lRomaneioEnviado.RomaneioOID);
if Assigned(lRomaneioCadastrado) then
begin
Result := TJSONString.Create('Romaneio já cadastrado. Inclusão cancelada!');
ConfigurarResponse(tmObjectAlreadyExists);
lRomaneioCadastrado.Free;
Exit;
end;
try
if not TestarVeiculoCadastrado(lRomaneioEnviado.VeiculoOID) then
begin
Result := TJSONString.Create('Veículo informado não existe!');
ConfigurarResponse(tmUnprocessableEntity);
Exit;
end;
if IncluirRomaneio(lRomaneioEnviado) then
begin
Result := TJSONString.Create('Romaneio gravado com sucesso!');
ConfigurarResponse(tmOK);
end
else
raise Exception.Create('Erro ao gravar o Romaneio!');
except
on e: Exception do
begin
Result := TJSONString.Create(e.Message);
ConfigurarResponse(tmUndefinedError);
end;
end;
finally
lRomaneioEnviado.Free;
end;
end;
function TRomaneioController.updateRomaneio(Romaneio: TJSONObject): TJSONValue;
var
lRomaneioEnviado, lRomaneioCadastrado: TRomaneio;
begin
lRomaneioEnviado := TJson.JsonToObject<TRomaneio>(Romaneio);
try
lRomaneioCadastrado := ObterRomaneioPeloOID(lRomaneioEnviado.RomaneioOID);
if not Assigned(lRomaneioCadastrado) then
begin
Result := TJSONString.Create('Romaneio não encontrado!');
ConfigurarResponse(tmNotFound);
Exit;
end;
lRomaneioCadastrado.Free;
try
if not TestarVeiculoCadastrado(lRomaneioEnviado.VeiculoOID) then
begin
Result := TJSONString.Create('Veículo informado não existe!');
ConfigurarResponse(tmUnprocessableEntity);
Exit;
end;
if AlterarRomaneio(lRomaneioEnviado) then
begin
Result := TJSONString.Create('Romaneio gravado com sucesso!');
ConfigurarResponse(tmOK);
end
else
raise Exception.Create('Erro ao gravar o romaneio!');
except
on e: Exception do
begin
Result := TJSONString.Create(e.Message);
ConfigurarResponse(tmUndefinedError);
end;
end;
finally
lRomaneioEnviado.Free;
end;
end;
function TRomaneioController.cancelRomaneio(ID: Integer): TJSONValue;
var
lQry: TFDQuery;
lRomaneio: TRomaneio;
begin
lRomaneio := ObterRomaneioPeloOID(ID);
if not Assigned(lRomaneio) then
begin
Result := TJSONString.Create('Romaneio não encontrado!');
ConfigurarResponse(tmNotFound);
Exit;
end;
lRomaneio.Free;
lQry := DataModule1.ObterQuery;
try
try
with lQry do
begin
SQL.Add('DELETE FROM Romaneio WHERE RomaneioOID = :RomaneioOID');
ParamByName('RomaneioOID').AsInteger := ID;
ExecSQL;
Result := TJSONString.Create('Romaneio excluído com sucesso!');
ConfigurarResponse(tmOK);
end;
except
on e: Exception do
begin
Result := TJSONString.Create('Erro ao excluir o Romaneio!');
ConfigurarResponse(tmUndefinedError);
end;
end;
finally
DataModule1.DestruirQuery(lQry);
end;
end;
end.
|
unit Tag;
interface
type
int = integer;
Tags = class
private
public
end;
const
tplus : int = 256;
tApostroph : int = 257;
tArray : int = 258;
tBegin : int = 259;
tPoin : int = 260;
tCase : int = 261;
tString : int = 262;
tColon : int = 263;
tColonEqual : int = 264;
tcomma : int = 265;
tconst : int = 266;
tdigit : int = 267;
tDo : int = 268;
tDot : int = 269;
tDoubleDot : int = 270;
tDownto : int = 271;
tElse : int = 272;
tEnd : int = 273;
tEqual : int = 274;
tFor : int = 275;
tFunction : int = 276;
tGoTo : int = 277;
tId : int = 278;
tIf : int = 279;
tLabel : int = 280;
tLeftSk : int = 281;
tLeftBar : int = 282;
tLetter : int = 283;
tMult_Op : int = 284;
tNil : int = 285;
tNot : int = 286;
tOf : int = 287;
tPacked : int = 288;
tProcedure : int = 289;
tProgram : int = 290;
tRecord : int = 291;
tminus : int = 292;
tRepeat : int = 293;
tRightSk : int = 294;
tRightBar : int = 295;
tSignFact : int = 296; //signed integer
tSemicolon : int = 297;
tFile : int = 298;
tSet : int = 299;
tSignplus : int = 300;
tString_Char : int = 301;
tThen : int = 302;
tTo : int = 303;
tType : int = 304;
tUnsigInte : int = 305;
tUnsigReal : int = 306;
tUntil : int = 307;
tVar : int = 308;
tWhile : int = 309;
tWith : int = 310;
tbasic_type : int = 311;
tarray_type : int = 312;
tleftsk2 : int = 313;
trightsk2 : int = 314;
tcommand : int = 315;
terror : int = 316;
tbreak : int = 317;
tequal_op : int = 318;
tnotequal_op : int = 319;
tlower : int = 320;
tbiger : int = 321;
tloweeq : int = 322;
tbigereq : int = 323;
tin : int = 324;
tor_op : int = 325;
tdApostroph : int = 326;
tdivchar_Op : int = 327;
tmode_Op : int = 328;
tand_Op : int = 329;
tSignminus : int = 330;
ttrue : int = 331;
tfalse : int = 332;
tchar : int = 333;
twrite : int = 334;
twriteln : int = 335;
tread : int = 336;
treadln : int = 337;
// tprivate : int = 313;
//tpublic : int = 314;
implementation
end.
|
unit UTempActions;
interface
uses
Controls;
function SetWaitCursor(cursor: TCursor = crHourGlass): IUnknown;
function SetDisableActions: IUnknown;
function SetDecimalSeparator(separator: char = '.'): IUnknown;
implementation
uses
SysUtils, Forms;
type
TWaitCursor = class(TInterfacedObject, IUnknown)
private
FOldCursor: TCursor;
public
constructor Create(cursor: TCursor); virtual;
destructor Destroy; override;
end;
function SetWaitCursor(cursor: TCursor = crHourGlass): IUnknown;
begin
Result := TWaitCursor.Create(cursor);
end;
{ TWaitCursor }
constructor TWaitCursor.Create(cursor: TCursor);
begin
inherited Create;
FOldCursor := Screen.Cursor;
Screen.Cursor := cursor;
end;
destructor TWaitCursor.Destroy;
begin
Screen.Cursor := FOldCursor;
inherited;
end;
{ TDisableActions }
var
gl_DisableActions: boolean = false;
type
TDisableActions = class(TInterfacedObject, IUnknown)
private
FHasSet: boolean; // remember if i have changed the gl_DisableActions
public
constructor Create; virtual;
destructor Destroy; override;
end;
constructor TDisableActions.Create;
begin
FHasSet := False;
if gl_DisableActions then
Abort;
gl_DisableActions := True;
FHasSet := True;
end;
destructor TDisableActions.Destroy;
begin
if FHasSet then
gl_DisableActions := False;
inherited;
end;
function SetDisableActions: IUnknown;
begin
Result := TDisableActions.Create();
end;
type
TDecimalSeparator = class(TInterfacedObject, IUnknown)
private
FOldSeparator: char;
public
constructor Create(separator: char); virtual;
destructor Destroy; override;
end;
function SetDecimalSeparator(separator: char = '.'): IUnknown;
begin
Result := TDecimalSeparator.Create(separator);
end;
{ TDecimalSeparator }
constructor TDecimalSeparator.Create(separator: char);
begin
inherited Create;
FOldSeparator := FormatSettings.DecimalSeparator;
FormatSettings.DecimalSeparator := separator;
end;
destructor TDecimalSeparator.Destroy;
begin
FormatSettings.DecimalSeparator := FOldSeparator;
inherited;
end;
end.
|
{----------------------------------------------------------------------
DEVIUM Content Management System
Copyright (C) 2004 by DEIV Development Team.
http://www.deiv.com/
$Header: /devium/Devium\040CMS\0402/Source/Products/prodMainForm.pas,v 1.7 2004/05/06 15:24:06 paladin Exp $
------------------------------------------------------------------------}
unit prodMainForm;
interface
uses
Forms, PluginManagerIntf, TBSkinPlus, TB2Dock, TB2Toolbar, Classes,
Controls, ImgList, ActnList, Menus, TB2Item, ComCtrls, cxStyles,
cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData,
cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
ExtCtrls;
type
TNC = class(TTreeNode)
private
FID: Integer;
FParentID: Integer;
public
property ID: Integer read FID write FID;
property ParentID: Integer read FParentID write FParentID;
end;
TMainForm = class(TForm)
TBDock1: TTBDock;
TBToolbar1: TTBToolbar;
TBSkin: TTBSkin;
TBPopupMenu1: TTBPopupMenu;
ActionList1: TActionList;
ImageList20: TImageList;
TBSubmenuItem1: TTBSubmenuItem;
TBItem1: TTBItem;
CatNew: TAction;
CanEdit: TAction;
CatDelete: TAction;
ItemAdd: TAction;
ItemEdit: TAction;
ItemDel: TAction;
ItemCopy: TAction;
TBItem2: TTBItem;
TBItem3: TTBItem;
TBItem4: TTBItem;
TBItem5: TTBItem;
TBSeparatorItem1: TTBSeparatorItem;
TBItem6: TTBItem;
TBItem7: TTBItem;
TBItem8: TTBItem;
TBItem9: TTBItem;
TBItem10: TTBItem;
TBSeparatorItem2: TTBSeparatorItem;
TBItem11: TTBItem;
TBItem12: TTBItem;
TBItem13: TTBItem;
TBItem14: TTBItem;
TBSeparatorItem3: TTBSeparatorItem;
StatusBar: TStatusBar;
StatsuBasrUpdate: TAction;
ReFrash: TAction;
Syn: TAction;
TBItem15: TTBItem;
TBSeparatorItem5: TTBSeparatorItem;
TBItem16: TTBItem;
TBItem17: TTBItem;
Products: TcxGridDBTableView;
GridLevel1: TcxGridLevel;
Grid: TcxGrid;
ImageList16: TImageList;
title: TcxGridDBColumn;
is_folder: TcxGridDBColumn;
Panel1: TPanel;
TreeView: TTreeView;
Splitter1: TSplitter;
Panel2: TPanel;
parent_id: TcxGridDBColumn;
UnitNames: TAction;
TBSeparatorItem6: TTBSeparatorItem;
TBItem18: TTBItem;
Types: TAction;
TBItem19: TTBItem;
Price: TAction;
TBItem20: TTBItem;
is_visible: TcxGridDBColumn;
product_article: TcxGridDBColumn;
name: TcxGridDBColumn;
SortUp: TAction;
SortDown: TAction;
TBSeparatorItem7: TTBSeparatorItem;
TBItem23: TTBItem;
TBItem24: TTBItem;
TBSeparatorItem9: TTBSeparatorItem;
TBSeparatorItem4: TTBSeparatorItem;
TBItem21: TTBItem;
TBItem22: TTBItem;
sort_order: TcxGridDBColumn;
PriceTemp: TAction;
TBSeparatorItem8: TTBSeparatorItem;
TBItem25: TTBItem;
procedure StatsuBasrUpdateUpdate(Sender: TObject);
procedure SynExecute(Sender: TObject);
procedure SynUpdate(Sender: TObject);
procedure ReFrashExecute(Sender: TObject);
procedure TreeViewCreateNodeClass(Sender: TCustomTreeView;
var NodeClass: TTreeNodeClass);
procedure TreeViewChange(Sender: TObject; Node: TTreeNode);
procedure UnitNamesExecute(Sender: TObject);
procedure ItemEditExecute(Sender: TObject);
procedure is_folderCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure TypesExecute(Sender: TObject);
procedure ProductsDblClick(Sender: TObject);
procedure ItemAddExecute(Sender: TObject);
procedure CanEditExecute(Sender: TObject);
procedure CatNewExecute(Sender: TObject);
procedure ItemDelExecute(Sender: TObject);
procedure CatDeleteExecute(Sender: TObject);
procedure PriceExecute(Sender: TObject);
procedure CanEditUpdate(Sender: TObject);
procedure ItemEditUpdate(Sender: TObject);
procedure TreeViewCollapsing(Sender: TObject; Node: TTreeNode;
var AllowCollapse: Boolean);
procedure SortUpExecute(Sender: TObject);
procedure SortDownExecute(Sender: TObject);
procedure SortUpUpdate(Sender: TObject);
procedure PriceTempExecute(Sender: TObject);
private
FPluginManager: IPluginManager;
FDataPath: String;
procedure SetDataPath(const Value: String);
procedure SetPluginManager(const Value: IPluginManager);
{ Private declarations }
procedure FillTree;
function FindNode(AID: Integer): TNC;
procedure DeleteProduct;
procedure DeleteProductCategory;
public
property PluginManager: IPluginManager read FPluginManager write SetPluginManager;
property DataPath: String read FDataPath write SetDataPath;
end;
function GetMainForm(const PluginManager: IPluginManager; const DataPath: String): Integer;
implementation
uses progDataModule, SysUtils, prodUnitnamesForm, prodProductForm,
Graphics, Types, prodTypesForm, DBClient, prodPriceForm, DeviumLib,
Windows;
{$R *.dfm}
function GetMainForm;
var
Form: TMainForm;
begin
Form := TMainForm.Create(Application);
try
Form.DataPath := DataPath;
Form.PluginManager := PluginManager;
Result := Form.ShowModal;
finally
Form.Free;
end;
end;
{ TMainForm }
procedure TMainForm.SetDataPath(const Value: String);
begin
FDataPath := Value;
end;
procedure TMainForm.SetPluginManager(const Value: IPluginManager);
begin
FPluginManager := Value;
DM := TDM.Create(Self);
DM.PluginManager := FPluginManager;
DM.DataPath := FDataPath;
DM.Open;
Products.DataController.DataSource := DM.dsProducts;
FillTree;
end;
procedure TMainForm.StatsuBasrUpdateUpdate(Sender: TObject);
begin
StatusBar.Panels[0].Text := DM.GetStatsuBarString;
end;
procedure TMainForm.SynExecute(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
try
DM.ApplyUpdates;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TMainForm.SynUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := DM.CanApplyUpdates;
end;
procedure TMainForm.ReFrashExecute(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
try
Dm.Refresh;
FillTree;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TMainForm.FillTree;
var
Node, PNode: TNC;
i: Integer;
OldKey: Integer;
begin
OldKey := 0;
with TreeView, DM.Products do
begin
// Сохраняем старое выделение
if Assigned(Selected) then
OldKey := TNC(Selected).ID;
// заполняем дерево
Items.Clear;
Node := TNC(Items.AddChild(nil, 'Каталог продукции'));
Node.ID := 0;
Node.ParentID := -1;
Node.ImageIndex := 121;
Node.SelectedIndex := 121;
First;
while not EOF do
begin
if FieldValues['is_folder'] = 1 then
begin
// добавление элемента
Node := TNC(Items.AddChild(nil, FieldByName('title').AsString));
Node.ID := FieldValues['product_id'];
Node.ParentID := FieldValues['parent_id'];
Node.ImageIndex := 20;
Node.SelectedIndex := 20;
end;
Next;
end;
// пересортировка дерева
i := 0;
while i < Items.Count do
begin
Node := TNC(Items[i]);
// поиск в дереве родителя
PNode := FindNode(Node.ParentID);
if (PNode <> nil) and (Node.Parent <> PNode) then
begin
// сделать детёнком
Node.MoveTo(PNode, naAddChild);
i := -1;
end;
Inc(i);
end;
// востонавливаем старое выделение
if OldKey > 0 then
begin
Node := FindNode(OldKey);
Selected := Node;
end else // root
Selected := Items[0];
Selected.MakeVisible;
// конец пересортировки
end;
end;
procedure TMainForm.TreeViewCreateNodeClass(Sender: TCustomTreeView;
var NodeClass: TTreeNodeClass);
begin
NodeClass := TNC;
end;
function TMainForm.FindNode(AID: Integer): TNC;
var
i: Integer;
begin
Result := nil;
for i := 0 to TreeView.Items.Count - 1 do
begin
if TNC(TreeView.Items[i]).ID = AID then
begin
Result := TNC(TreeView.Items[i]);
Exit;
end;
end;
end;
procedure TMainForm.TreeViewChange(Sender: TObject; Node: TTreeNode);
begin
Products.DataController.Filter.Clear;
Products.DataController.Filter.AddItem(nil, parent_id, foEqual,
TNC(TreeView.Selected).ID, TreeView.Selected.Text);
Products.DataController.Filter.Active := True;
end;
procedure TMainForm.UnitNamesExecute(Sender: TObject);
begin
GetUnitnamesForm;
end;
procedure TMainForm.ItemEditExecute(Sender: TObject);
begin
with DM.Products do
begin
Edit;
if GetProductForm(FPluginManager) = mrOK then
Post
else
Cancel;
end;
end;
procedure TMainForm.is_folderCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
var
ARec: TRect;
ImageIndex: Integer;
begin
ImageIndex := 20;
ARec := AViewInfo.Bounds;
ACanvas.FillRect(ARec);
if AViewInfo.Value = 0 then ImageIndex := 40;
ACanvas.DrawImage(ImageList16, ARec.Left + 5, ARec.Top + 1, ImageIndex);
ADone := True;
end;
procedure TMainForm.TypesExecute(Sender: TObject);
begin
GetTypesForm;
end;
procedure TMainForm.ProductsDblClick(Sender: TObject);
begin
ItemEdit.Execute;
end;
procedure TMainForm.ItemAddExecute(Sender: TObject);
begin
with DM.Products do
begin
Append;
FieldValues['parent_id'] := TNC(TreeView.Selected).ID;
FieldValues['is_folder'] := 0;
FieldValues['is_visible'] := 1;
FieldValues['is_printable'] := 1;
FieldValues['title'] := 'Новый товар';
FieldValues['name'] := TransLiterStr(FieldValues['title']);
Post;
Edit;
if GetProductForm(FPluginManager) = mrOK then
Post
else
DeleteProduct;
end;
end;
procedure TMainForm.CanEditExecute(Sender: TObject);
begin
with DM.Products do
begin
Locate('product_id', TNC(TreeView.Selected).ID, []);
Edit;
if GetProductForm(FPluginManager) = mrOK then
begin
Post;
TreeView.Selected.Text := FieldValues['title'];
end
else
Cancel;
end;
end;
procedure TMainForm.CatNewExecute(Sender: TObject);
begin
with DM.Products do
begin
Append;
FieldValues['is_visible'] := 1;
FieldValues['is_printable'] := 1;
FieldValues['is_folder'] := 1;
FieldValues['parent_id'] := TNC(TreeView.Selected).ID;
FieldValues['title'] := 'Новая группа';
FieldValues['name'] := TransLiterStr(FieldValues['title']);
{ TODO 1 -oPaladin : Придумать уникальность формирования имени!!! }
Post;
Edit;
if GetProductForm(FPluginManager) = mrOK then
Post
else
Delete;
end;
FillTree;
end;
procedure TMainForm.DeleteProduct;
// удаление подчиннх датасетов
procedure DeleteChRecords(DataSet: TDataSet; product_id: Integer);
begin
DataSet.DisableControls;
DataSet.First;
while DataSet.Locate('product_id', product_id, []) do
DataSet.Delete;
DataSet.EnableControls;
end;
begin
with DM.Products do
begin
// удаление из свойств
DeleteChRecords(DM.Values, FieldValues['product_id']);
// удаление из цен
DeleteChRecords(DM.Prices, FieldValues['product_id']);
// удаление еденицы
DeleteChRecords(DM.Units, FieldValues['product_id']);
Delete;
end;
end;
procedure TMainForm.DeleteProductCategory;
begin
{ TODO 1 -oPaladin : Доделать удаление группы со всеми вхождениями }
end;
procedure TMainForm.ItemDelExecute(Sender: TObject);
begin
if MessageBox(Handle, 'Вы точно уверены что хотите это сделать',
PChar(Caption), MB_YESNO + MB_ICONQUESTION) = IDNO then Exit;
DeleteProduct;
FillTree;
end;
procedure TMainForm.CatDeleteExecute(Sender: TObject);
begin
DeleteProductCategory;
end;
procedure TMainForm.PriceExecute(Sender: TObject);
begin
GetPriceForm;
end;
procedure TMainForm.CanEditUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := (Dm.Products.RecordCount > 0)
and Assigned(TreeView.Selected) and Assigned(TreeView.Selected.Parent);
end;
procedure TMainForm.ItemEditUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := (Dm.Products.RecordCount > 0);
end;
procedure TMainForm.TreeViewCollapsing(Sender: TObject; Node: TTreeNode;
var AllowCollapse: Boolean);
begin
if Node.Parent = nil then AllowCollapse := False;
end;
procedure TMainForm.SortUpExecute(Sender: TObject);
begin
DM.ReSort(DM.Products, 'sort_order', -15,
Format('parent_id=%d', [TNC(TreeView.Selected).ID]));
FillTree;
end;
procedure TMainForm.SortDownExecute(Sender: TObject);
begin
DM.ReSort(DM.Products, 'sort_order', 15,
Format('parent_id=%d', [TNC(TreeView.Selected).ID]));
FillTree;
end;
procedure TMainForm.SortUpUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := Assigned(TreeView.Selected);
end;
procedure TMainForm.PriceTempExecute(Sender: TObject);
begin
GetPriceFormTmp;
end;
end.
|
unit uthrImportarAero;
interface
uses
System.Classes, Dialogs, Windows, Forms, SysUtils, clUtil, clEntregador,
clStatus, clAgentes, clEntrega,
Messages, Controls, System.DateUtils;
type
TCSVEntrega = record
_agenteTFO: String;
_descricaoAgenteTFO: String;
_nossonumero: String;
_cliente: String;
_nota: String;
_consumidor: String;
_cuidados: String;
_logradouro: String;
_complemento: String;
_bairro: String;
_cidade: String;
_cep: String;
_telefone: String;
_expedicao: String;
_previsao: String;
_status: String;
_descricaoStatus: String;
_entregador: String;
_volumes: String;
_peso: String;
_ctrc: String;
_manifesto: String end;
type
thrImportarAero = class(TThread)
private
entregador: TEntregador;
entrega: TEntrega;
agentes: TAgente;
status: TStatus;
CSVEntrega: TCSVEntrega;
procedure AtualizaLog;
procedure AtualizaProgress;
procedure TerminaProcesso;
function TrataLinha(sLinha: String): String;
function MontaLista(campo: String): TStringList;
protected
procedure Execute; override;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure thrImportarAero.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ thrImportarAero }
uses
ufrmImportaentrega, uGlobais;
function thrImportarAero.TrataLinha(sLinha: String): String;
var
iConta: Integer;
sLin: String;
bFlag: Boolean;
begin
if Pos('"', sLinha) = 0 then
begin
Result := sLinha;
Exit;
end;
iConta := 1;
bFlag := False;
sLin := '';
while sLinha[iConta] >= ' ' do
begin
if sLinha[iConta] = '"' then
begin
if bFlag then
bFlag := False
else
bFlag := True;
end;
if bFlag then
begin
if sLinha[iConta] = ';' then
sLin := sLin + ' '
else
sLin := sLin + sLinha[iConta];
end
else
sLin := sLin + sLinha[iConta];
Inc(iConta);
end;
Result := sLin;
end;
function thrImportarAero.MontaLista(campo: string): TStringList;
var
lList: TStringList;
iI2: Integer;
sCampo: String;
begin
sCampo := '';
iI2 := 0;
Inc(iI2, 1);
lList := TStringList.Create();
lList.Clear;
while campo[iI2] >= ' ' do
begin
if campo[iI2] = '\' then
begin
lList.Add(sCampo);
Inc(iI2, 1);
sCampo := '';
end;
sCampo := sCampo + campo[iI2];
Inc(iI2, 1);
end;
if not(TUtil.Empty(sCampo)) then
begin
lList.Add(sCampo);
sCampo := '';
end;
Result := lList;
end;
procedure thrImportarAero.Execute;
var
lLista, sItens: TStringList;
ArquivoCSV: TextFile;
Contador, I, LinhasTotal, iRet, iI, iCliente: Integer;
Linha, campo, codigo, sMess, sData, sNN: String;
d: Real;
// Lê Linha e Monta os valores
function MontaValor: String;
var
ValorMontado: String;
begin
ValorMontado := '';
Inc(I);
While Linha[I] >= ' ' do
begin
If Linha[I] = ';' then // vc pode usar qualquer delimitador ... eu
// estou usando o ";"
break;
ValorMontado := ValorMontado + Linha[I];
Inc(I);
end;
Result := ValorMontado;
end;
begin
entregador := TEntregador.Create;
entrega := TEntrega.Create;
agentes := TAgente.Create;
status := TStatus.Create;
LinhasTotal := TUtil.NumeroDeLinhasTXT(frmImportaEntregas.cxArquivo.Text);
// Carregando o arquivo ...
AssignFile(ArquivoCSV, frmImportaEntregas.cxArquivo.Text);
try
Reset(ArquivoCSV);
iCliente := StrToInt(frmImportaEntregas.cxCliente.Text);
Readln(ArquivoCSV, Linha);
{ if Copy(Linha,0,18) <> 'AERONOVA;;;;;;;;;;' then begin
MessageDlg('Arquivo informado não é de ENTREGAS AERONOVA.',mtWarning,[mbOK],0);
Abort;
end;
Readln(ArquivoCSV, Linha); }
Contador := 1;
lLista := TStringList.Create();
sItens := TStringList.Create();
while not Eoln(ArquivoCSV) do
begin
Readln(ArquivoCSV, Linha);
Linha := TrataLinha(Linha);
I := 0;
with CSVEntrega do
begin
campo := MontaValor;
_consumidor := MontaValor;
_logradouro := MontaValor;
_bairro := MontaValor;
_cep := MontaValor;
_cidade := MontaValor;
campo := MontaValor;
_ctrc := MontaValor;
sNN := MontaValor;
_nossonumero := sNN;
campo := MontaValor;
campo := MontaValor;
_volumes := MontaValor;
_peso := MontaValor;
campo := MontaValor;
_expedicao := MontaValor;
campo := MontaValor;
_manifesto := MontaValor;
_nota := sNN;
_cliente := IntToStr(iCliente);
_telefone := '';
_status := '4';
end;
if not(entrega.getObject(sNN, 'NOSSONUMERO')) then
begin
entrega.Agente := 0;
entrega.entregador := 0;
entrega.NossoNumero := sNN;
entrega.Cliente := StrToInt(CSVEntrega._cliente);
entrega.Consumidor := CSVEntrega._consumidor;
entrega.Endereco := CSVEntrega._logradouro;
entrega.Complemento := CSVEntrega._complemento;
entrega.Bairro := CSVEntrega._bairro;
entrega.Cidade := CSVEntrega._cidade;
entrega.Cep := CSVEntrega._cep;
entrega.Telefone := CSVEntrega._telefone;
entrega.Expedicao := StrToDate(CSVEntrega._expedicao);
entrega.PrevDistribuicao := IncDay(StrToDate(CSVEntrega._expedicao), 2);
entrega.status := StrToInt(CSVEntrega._status);
entrega.Volumes := StrToInt(CSVEntrega._volumes);
entrega.PesoReal := StrToFloat(CSVEntrega._peso);
entrega.Ctrc := StrToInt(CSVEntrega._ctrc);
entrega.Manifesto := StrToInt(CSVEntrega._manifesto);
entrega.VolumesExtra := 0;
entrega.ValorExtra := 0;
entrega.DiasAtraso := 0;
entrega.Recebido := 'N';
entrega.Rastreio := '';
sItens.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm', Now) +
' | Importação ao banco de dados. | ' + 'Por ' +
uGlobais.sNomeUsuario + ' |');
entrega.Rastreio := sItens.Text;
sItens.Clear;
if not(entrega.Insert) then
begin
sMensagem := 'Erro ao Incluir os dados do NN ' +
entrega.NossoNumero + ' !';
Synchronize(AtualizaLog);
end;
end
else
begin
entrega.Cliente := StrToInt(CSVEntrega._cliente);
entrega.Consumidor := CSVEntrega._consumidor;
entrega.Endereco := CSVEntrega._logradouro;
entrega.Complemento := CSVEntrega._complemento;
entrega.Bairro := CSVEntrega._bairro;
entrega.Cidade := CSVEntrega._cidade;
entrega.Cep := CSVEntrega._cep;
entrega.Telefone := CSVEntrega._telefone;
entrega.Expedicao := StrToDate(CSVEntrega._expedicao);
entrega.PrevDistribuicao := IncDay(StrToDate(CSVEntrega._expedicao), 2);
entrega.status := StrToInt(CSVEntrega._status);
entrega.Volumes := StrToInt(CSVEntrega._volumes);
entrega.PesoReal := StrToFloat(CSVEntrega._peso);
entrega.Ctrc := StrToInt(CSVEntrega._ctrc);
entrega.Manifesto := StrToInt(CSVEntrega._manifesto);
sItens.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm', Now) +
' | Importação ao banco de dados. | ' + 'Por ' +
uGlobais.sNomeUsuario + ' |');
entrega.Rastreio := sItens.Text;
sItens.Clear;
if entrega.Pago <> 'S' then
begin
if not(entrega.Update) then
begin
sMensagem := 'Erro ao Alterar os dados do NN ' +
entrega.NossoNumero + ' !';
Synchronize(AtualizaLog);
end;
end;
end;
I := 0;
iConta := Contador;
iTotal := LinhasTotal;
dPosicao := (iConta / iTotal) * 100;
Inc(Contador, 1);
if not(Self.Terminated) then
begin
Synchronize(AtualizaProgress);
end
else
begin
entregador.Free;
entrega.Free;
agentes.Free;
status.Free;
Abort;
end;
end;
finally
CloseFile(ArquivoCSV);
Application.MessageBox('Importação concluída!', 'Importação de Entregas',
MB_OK + MB_ICONINFORMATION);
sMensagem := 'Importação terminada em ' +
FormatDateTime('dd/mm/yyyy hh:mm:ss', Now);
Synchronize(AtualizaLog);
Synchronize(TerminaProcesso);
entregador.Free;
entrega.Free;
agentes.Free;
status.Free;
end;
end;
procedure thrImportarAero.AtualizaLog;
begin
frmImportaEntregas.cxLog.Lines.Add(sMensagem);
frmImportaEntregas.cxLog.Refresh;
end;
procedure thrImportarAero.AtualizaProgress;
begin
frmImportaEntregas.cxProgressBar1.Position := dPosicao;
frmImportaEntregas.cxProgressBar1.Properties.Text := 'Registro ' +
IntToStr(iConta) + ' de ' + IntToStr(iTotal);
frmImportaEntregas.cxProgressBar1.Refresh;
if not(frmImportaEntregas.actImportaEntregaCancelar.Visible) then
begin
frmImportaEntregas.actImportaEntregaCancelar.Visible := True;
frmImportaEntregas.actImportaEntregaSair.Enabled := False;
end;
end;
procedure thrImportarAero.TerminaProcesso;
begin
frmImportaEntregas.actImportaEntregaCancelar.Visible := False;
frmImportaEntregas.actImportaEntregaSair.Enabled := True;
frmImportaEntregas.cxArquivo.Clear;
frmImportaEntregas.cxProgressBar1.Properties.Text := '';
frmImportaEntregas.cxProgressBar1.Position := 0;
frmImportaEntregas.cxProgressBar1.Clear;
end;
end.
|
unit uDateTimeInput;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls, AppEvnts;
type
TDateTimeInputForm = class(TForm)
bOk: TButton;
bCancel: TButton;
lCaption: TLabel;
dtDate: TDateTimePicker;
chTime: TCheckBox;
tmTime: TDateTimePicker;
chNow: TCheckBox;
Bevel1: TBevel;
ApplicationEvents1: TApplicationEvents;
procedure chTimeClick(Sender: TObject);
procedure chNowClick(Sender: TObject);
procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
private
procedure SafeSetComboBox(aComboBox: TCheckBox; aValue: Boolean);
procedure UpdateEnabled;
function GetDateTime: TDateTime;
procedure SetDateTime(const Value: TDateTime);
{ Private declarations }
public
property DateTime: TDateTime read GetDateTime write SetDateTime;
end;
//var
// fDateTimeInput: TfDateTimeInput;
function OPCInputDateTime(aDateTime: TDateTime; aCaption: string = ''): TDateTime;
function InputDateTime(var aDateTime: TDateTime; aCaption: string = ''): Boolean;
implementation
uses
Math;
{$R *.dfm}
function OPCInputDateTime(aDateTime: TDateTime; aCaption: string = ''): TDateTime;
var
DTI_Form: TDateTimeInputForm;
begin
DTI_Form := TDateTimeInputForm.Create(nil);
try
if aCaption <> '' then
DTI_Form.lCaption.Caption := aCaption;
DTI_Form.DateTime := aDateTime;
if DTI_Form.ShowModal = mrOk then
Result := DTI_Form.DateTime
else
Result := aDateTime;
finally
FreeAndNil(DTI_Form);
end;
end;
function InputDateTime(var aDateTime: TDateTime; aCaption: string = ''): Boolean;
var
DTI_Form: TDateTimeInputForm;
begin
DTI_Form := TDateTimeInputForm.Create(nil);
try
if aCaption <> '' then
DTI_Form.lCaption.Caption := aCaption;
DTI_Form.DateTime := aDateTime;
Result := DTI_Form.ShowModal = mrOk;
if Result then
aDateTime := DTI_Form.DateTime;
finally
FreeAndNil(DTI_Form);
end;
end;
{ TfDateTimeInput }
procedure TDateTimeInputForm.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
var
//mp: TPoint;
//c: TControl;
//v: Extended;
//vStr: string;
//aFormat: string;
//aDotFounded: boolean;
//aDeltaStr: string;
//aDelta: Extended;
//i: Integer;
aHandle: Cardinal;
//KeyState: TKeyboardState;
//ShiftState: TShiftState;
begin
if Msg.message = WM_MOUSEWHEEL then
begin
if ActiveControl is TDateTimePicker then
begin
aHandle := TDateTimePicker(ActiveControl).Handle;
if Msg.wParam > 0 then
SendMessage(aHandle, WM_KEYDOWN, VK_UP, 0)
else
SendMessage(aHandle, WM_KEYDOWN, VK_DOWN, 0);
end;
end;
end;
procedure TDateTimeInputForm.chNowClick(Sender: TObject);
begin
UpdateEnabled;
end;
procedure TDateTimeInputForm.chTimeClick(Sender: TObject);
begin
UpdateEnabled;
end;
function TDateTimeInputForm.GetDateTime: TDateTime;
begin
if chNow.Checked then
Result := Now
else
begin
Result := Trunc(dtDate.DateTime);
if chTime.Checked then
Result := Result + Frac(tmTime.DateTime);
end;
end;
procedure TDateTimeInputForm.SafeSetComboBox(aComboBox: TCheckBox; aValue: Boolean);
var
aSaveEvent: TNotifyEvent;
begin
aSaveEvent := aComboBox.OnClick;
try
aComboBox.OnClick := nil;
aComboBox.Checked := aValue;
finally
aComboBox.OnClick := aSaveEvent;
end;
end;
procedure TDateTimeInputForm.SetDateTime(const Value: TDateTime);
begin
dtDate.Date := Trunc(Value);
if Frac(Value) <> 0.0 then
begin
tmTime.Time := Frac(Value);
SafeSetComboBox(chTime, True);
end
else
begin
SafeSetComboBox(chTime, False);
end;
UpdateEnabled;
end;
procedure TDateTimeInputForm.UpdateEnabled;
begin
dtDate.Enabled := not chNow.Checked;
chTime.Enabled := not chNow.Checked;
tmTime.Enabled := not chNow.Checked and chTime.Checked;
end;
end.
|
(*********************************************************************)
(* Programmname : INFOMENU.PAS V2.0 *)
(* Programmautor : Michael Rippl *)
(* Compiler : Quick Pascal V1.0 *)
(* Inhalt : Men Information des Kopierprogramms Venus V2.1 *)
(* Bemerkung : - *)
(* Letzte nderung : 05-Aug-1991 *)
(*********************************************************************)
UNIT InfoMenu;
INTERFACE
(* Diese Prozedur gibt Copyright-Informationen und eine Seriennummer aus *)
PROCEDURE DoVenusInfo(SerialNumber : LONGINT; UserName : STRING);
(* Diese Prozedur gibt Informationen ber das Computersystem aus *)
PROCEDURE DoSystemInfo;
(* Diese Prozedur gibt Informationen ber den Speicher des Computers aus *)
PROCEDURE DoMemorySizes(XmsUsage : BOOLEAN);
(* Diese Prozedur gibt Informationen ber eine Diskette oder Festplatte aus *)
PROCEDURE DoDiskInfo;
IMPLEMENTATION
USES Dos, SysInfo, Memory, KeyMouse, Primitiv,
Windows, Intuitiv, VenColor, FileInfo,
Disk, Extended, Expanded, HiMem, CopyMenu; (* Units einbinden *)
VAR BiosDate : ARRAY [1..8] OF CHAR ABSOLUTE $F000:$FFF5;
(* Diese Prozedur gibt Copyright-Informationen und eine Seriennummer aus *)
PROCEDURE DoVenusInfo(SerialNumber : LONGINT; UserName : STRING);
VAR i : BYTE; (* Dient nur als Zhler *)
TextString : STRING [8]; (* Text der Seriennummer *)
TxtSerial, (* Seriennummer *)
TxtTit1, (* Texte auf dem Requester *)
TxtTit2,
TxtTit3,
TxtTit4,
TxtTit5,
TxtTit6,
TxtTit7,
TxtTit8,
TxtTit9,
TxtOk : pIntuiText; (* Text fr Ok-Gadget *)
GadOk : pGadget; (* Ok-Gadget *)
InfoReq : pRequester; (* Requester Information *)
Status : BOOLEAN; (* Status des Requesters *)
BEGIN
Str(SerialNumber + 2 : 8, TextString);
InitIntuiText(TxtSerial, 21, 8, cBlack, cCyan, TextString, NIL);
FOR i := 1 TO Length(UserName) DO (* Buchstaben dekodieren *)
Inc(UserName[i], 4);
InitIntuiText(TxtTit1, 7, 1, cYellow, cRed,
' VENUS DISKCOPY V2.1 ', TxtSerial);
InitIntuiText(TxtTit2, 7, 2, cYellow, cRed,
' (C) 1990, 1991 BY DIGITAL IMAGE ', TxtTit1);
InitIntuiText(TxtTit3, 13, 4, cBlack, cCyan, 'REVISION 05-AUG-1991',
TxtTit2);
InitIntuiText(TxtTit4, 1, 5, cBlack, cCyan,
'ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ', TxtTit3);
InitIntuiText(TxtTit5, 21, 7, cBlack, cCyan, UserName, TxtTit4);
InitIntuiText(TxtTit6, 5, 7, cBlack, cCyan,
'USER NAME [ ]', TxtTit5);
InitIntuiText(TxtTit7, 5, 8, cBlack, cCyan,
'SERIAL NUMBER [ ]', TxtTit6);
InitIntuiText(TxtTit8, 7, 10, cBlack, cCyan,
'PROGRAM WRITTEN BY', TxtTit7);
InitIntuiText(TxtTit9, 3, 11, cBlack, cCyan,
'EDV SERVICE MICHAEL RIPPL', TxtTit8);
InitIntuiText(TxtOk, 36, 10, cBlack, cCyan, '', NIL);
InitGadget(GadOk, 36, 10, 8, 3, TxtOk, cWhite, cCyan, NIL, OkGadget);
InitRequester(InfoReq, 15, 5, 47, 14, cBlack, cCyan, '',
[rMove, rShadow, rDouble], GadOk, TxtTit9);
Status := OpenRequester(InfoReq); (* Requester ffnen *)
IF Status THEN
Status := CloseRequester(InfoReq); (* Requester schlieáen *)
END; (* DoVenusInfo *)
(* Diese Prozedur gibt Informationen ber das Computersystem aus *)
PROCEDURE DoSystemInfo;
VAR IsColor : BOOLEAN; (* Farbe oder Monochrom *)
VideoAdapter : VideoModes; (* Typ der Grafikkarte *)
Lines, (* Anzahl der Zeilen *)
Columns : BYTE; (* Anzahl der Spalten *)
VideoAddress : WORD; (* Segment des Videorams *)
VerLowStr, (* Dos Text nach Punkt *)
VerHighStr : STRING[2]; (* Dos Text vor Punkt *)
TextString : STRING[20]; (* Allgemeiner Textstring *)
VerLow, (* Dos Version vor Punkt *)
VerHigh : BYTE; (* Dos Version nach Punkt *)
TxtTit1, (* Texte auf dem Requester *)
TxtTit2,
TxtTit3,
TxtTit4,
TxtTit5,
TxtTit6,
TxtTit7,
TxtTit8,
TxtTit9,
TxtTit10,
TxtTit11,
TxtTit12,
TxtTit13,
TxtTit14,
TxtTit15,
TxtTit16,
TxtTit17,
TxtTit18,
TxtTit19,
TxtTit20,
TxtTit21,
TxtTit22,
TxtTit23,
TxtTit24,
TxtOk : pIntuiText; (* Text fr Ok-Gadget *)
GadOk : pGadget; (* Ok-Gadget *)
InfoReq : pRequester; (* Requester Information *)
Status : BOOLEAN; (* Status des Requesters *)
LastDrive, (* Letztes Laufwerk *)
FirstDrive : CHAR; (* Erstes Laufwerk *)
BEGIN
InitIntuiText(TxtTit1, 3, 2, cBlack, cMagenta,
'COMPUTER -', NIL);
InitIntuiText(TxtTit2, 3, 3, cBlack, cMagenta,
'OPERATING SYSTEM -', TxtTit1);
InitIntuiText(TxtTit3, 3, 4, cBlack, cMagenta,
'CPU TYPE -', TxtTit2);
InitIntuiText(TxtTit22, 26, 2, cBlack, cMagenta,
'IBM/PC AT', TxtTit3);
InitIntuiText(TxtTit23, 26, 3, cBlack, cMagenta,
'MS DOS V', TxtTit22);
InitIntuiText(TxtTit24, 26, 4, cBlack, cMagenta,
'Intel', TxtTit23);
InitIntuiText(TxtTit4, 3, 5, cBlack, cMagenta,
'DISPLAY ADAPTER -', TxtTit24);
InitIntuiText(TxtTit5, 3, 6, cBlack, cMagenta,
'MOUSE -', TxtTit4);
InitIntuiText(TxtTit6, 3, 7, cBlack, cMagenta,
'SERIAL PORTS -', TxtTit5);
InitIntuiText(TxtTit7, 3, 8, cBlack, cMagenta,
'PARALLEL PORTS -', TxtTit6);
InitIntuiText(TxtTit8, 3, 9, cBlack, cMagenta,
'DISK DRIVES -', TxtTit7);
InitIntuiText(TxtTit9, 3, 10, cBlack, cMagenta,
'HARDDISK -', TxtTit8);
InitIntuiText(TxtTit10, 3, 11, cBlack, cMagenta,
'BIOS DATED AT -', TxtTit9);
InitIntuiText(TxtTit20, 3, 12, cBlack, cMagenta,
'DRIVES FOUND -', TxtTit10);
MsDosVersion(VerHigh, VerLow); (* Dos Version ermitteln *)
Str(VerHigh, VerHighStr); (* Ziffer vor dem Punkt *)
Str(VerLow, VerLowStr); (* Ziffer hinter dem Punkt *)
InitIntuiText(TxtTit11, 34, 3, cBlack, cMagenta,
VerHighStr + '.' + VerLowStr, TxtTit20);
IF GetCPUType = Intel80286 THEN (* Prozessortyp ermitteln *)
TextString := '80286'
ELSE TextString := '80386';
InitIntuiText(TxtTit12, 32, 4, cBlack, cMagenta, TextString, TxtTit11);
GetVideoMode(VideoAdapter, IsColor, Lines, Columns, VideoAddress);
CASE VideoAdapter OF (* Grafikkarte zuweisen *)
MDA : TextString := 'MDA';
CGA : TextString := 'CGA';
EGA : TextString := 'EGA';
mEGA : TextString := 'MONOCHROM EGA';
VGA : TextString := 'VGA';
mVGA : TextString := 'MONOCHROM VGA';
MCGA : TextString := 'MCGA';
mMCGA : TextString := 'MONOCHROM MCGA';
END;
InitIntuiText(TxtTit13, 26, 5, cBlack, cMagenta, TextString, TxtTit12);
IF MouseAvail THEN TextString := 'PRESENT' (* Maus angeschlossen *)
ELSE TextString := 'NOT PRESENT';
InitIntuiText(TxtTit14, 26, 6, cBlack, cMagenta, TextString, TxtTit13);
Str(SerialPorts, TextString); (* Anzahl serieller Ports *)
InitIntuiText(TxtTit15, 26, 7, cBlack, cMagenta, TextString, TxtTit14);
Str(ParallelPorts, TextString); (* Anzahl paralleler Ports *)
InitIntuiText(TxtTit16, 26, 8, cBlack, cMagenta, TextString, TxtTit15);
Str(NrOfDiskDrives, TextString); (* Anzahl Laufwerke *)
InitIntuiText(TxtTit17, 26, 9, cBlack, cMagenta, TextString, TxtTit16);
IF HardDiskAvail THEN TextString := 'PRESENT' (* HardDisk angeschlossen *)
ELSE TextString := 'NOT PRESENT';
InitIntuiText(TxtTit18, 26, 10, cBlack, cMagenta, TextString, TxtTit17);
InitIntuiText(TxtTit19, 26, 11, cBlack, cMagenta, BiosDate, TxtTit18);
FirstDrive := 'A'; (* Ab hier wird gesucht *)
WHILE NOT DriveExist(FirstDrive) DO (* Erstes Laufwerk suchen *)
Inc(FirstDrive);
LastDrive := FirstDrive; (* Ab hier weitersuchen *)
WHILE DriveExist(LastDrive) DO Inc(LastDrive); (* Letztes Laufwerk suchen *)
InitIntuiText(TxtTit21, 26, 12, cBlack, cMagenta,
FirstDrive + ':\ ' + Chr(26) + ' ' + Pred(LastDrive) +
':\', TxtTit19);
InitIntuiText(TxtOk, 32, 13, cBlack, cMagenta, '', NIL);
InitGadget(GadOk, 32, 13, 8, 3, TxtOk, cWhite, cMagenta, NIL, OkGadget);
InitRequester(InfoReq, 17, 4, 43, 17, cYellow, cMagenta,
' System Information ',
[rMove, rShadow, rClose, rTitle, rDouble], GadOk, TxtTit21);
Status := OpenRequester(InfoReq); (* Requester ffnen *)
IF Status THEN
Status := CloseRequester(InfoReq); (* Requester schlieáen *)
END; (* DoSystemInfo *)
(* Diese Prozedur gibt Informationen ber den Speicher des Computers aus *)
PROCEDURE DoMemorySizes(XmsUsage : BOOLEAN);
VAR TextString : STRING [10]; (* Textstring einer Zahl *)
VerLowStr, (* EMM Text vor Punkt *)
VerHighStr : STRING[2]; (* EMM Text nach Punkt *)
VerLow, (* EMM Version nach Punkt *)
VerHigh, (* EMM Version vor Punkt *)
SizeLow, (* Low-Byte von Ext-Size *)
SizeHigh : BYTE; (* High-Byte von Ext-Size *)
TotalXms, (* Gesamter XMS Speicher *)
LargestXms : WORD; (* Gráter XMS Block frei *)
TxtTit1, (* Texte auf dem Requester *)
TxtTit2,
TxtTit3,
TxtTit4,
TxtTit5,
TxtTit6,
TxtTit7,
TxtTit8,
TxtTit9,
TxtTit10,
TxtTit11,
TxtTit12,
TxtTit13,
TxtTit14,
TxtTit15,
TxtTit16,
TxtTit17,
TxtTit18,
TxtTit19,
TxtTit20,
TxtTit21,
TxtTit22,
TxtOk : pIntuiText; (* Text fr Ok-Gadget *)
GadOk : pGadget; (* Ok-Gadget *)
InfoReq : pRequester; (* Requester Information *)
Status : BOOLEAN; (* Status des Requesters *)
BEGIN
InitIntuiText(TxtTit1, 3, 2, cBlack, cMagenta,
'DOS MEMORY - INSTALLED', NIL);
InitIntuiText(TxtTit2, 21, 3, cBlack, cMagenta, 'FREE', TxtTit1);
InitIntuiText(TxtTit3, 3, 5, cBlack, cMagenta,
'EXTENDED MEMORY - STARTADDRESS', TxtTit2);
InitIntuiText(TxtTit15, 21, 6, cBlack, cMagenta, 'INSTALLED', TxtTit3);
InitIntuiText(TxtTit4, 21, 7, cBlack, cMagenta, 'FREE', TxtTit15);
InitIntuiText(TxtTit5, 3, 9, cBlack, cMagenta,
'EXPANDED MEMORY - VERSION', TxtTit4);
InitIntuiText(TxtTit6, 21, 10, cBlack, cMagenta, 'INSTALLED', TxtTit5);
InitIntuiText(TxtTit7, 21, 11, cBlack, cMagenta, 'FREE', TxtTit6);
InitIntuiText(TxtTit17, 3, 13, cBlack, cMagenta,
'XMS MEMORY - VERSION', TxtTit7);
InitIntuiText(TxtTit18, 21, 14, cBlack, cMagenta, 'LARGEST', TxtTit17);
InitIntuiText(TxtTit19, 21, 15, cBlack, cMagenta, 'FREE', TxtTit18);
Str(MainMemSize, TextString); (* Hauptspeichergráe *)
InitIntuiText(TxtTit8, 34, 2, cBlack, cMagenta, TextString, TxtTit19);
Str(MemAvail, TextString); (* Hauptspeicher noch da *)
InitIntuiText(TxtTit9, 34, 3, cBlack, cMagenta, TextString, TxtTit8);
Str(ExtMemStart, TextString); (* Startadresse vom EXT *)
InitIntuiText(TxtTit10, 34, 5, cBlack, cMagenta, TextString, TxtTit9);
ReadCMos($17, SizeLow); (* Daten aus CMOS lesen *)
ReadCMos($18, SizeHigh);
Str((LONGINT(SizeLow) + 256 * LONGINT(SizeHigh)) * 1024, TextString);
InitIntuiText(TxtTit16, 34, 6, cBlack, cMagenta, TextString, TxtTit10);
Str(LONGINT(ExtMemSize) * 1024, TextString); (* Speichergráe vom EXT *)
InitIntuiText(TxtTit11, 34, 7, cBlack, cMagenta, TextString, TxtTit16);
IF EmsMemAvail THEN (* Expandend Speicher da *)
BEGIN
GetEmsVersion(VerHigh, VerLow); (* EMS Version ermitteln *)
Str(VerHigh, VerHighStr); (* Ziffer vor dem Punkt *)
Str(VerLow, VerLowStr); (* Ziffer hinter dem Punkt *)
InitIntuiText(TxtTit12, 34, 9, cBlack, cMagenta,
'V' + VerHighStr + '.' + VerLowStr, TxtTit11);
Str(LONGINT(EmsNrOfPages) * 16384, TextString);
InitIntuiText(TxtTit13, 34, 10, cBlack, cMagenta, TextString, TxtTit12);
Str(LONGINT(NrOfAvailablePages) * 16384, TextString);
InitIntuiText(TxtTit14, 34, 11, cBlack, cMagenta, TextString, TxtTit13);
END
ELSE (* Kein EMS Speicher da *)
BEGIN
InitIntuiText(TxtTit12, 34, 9, cBlack, cMagenta, 'NOT PRESENT', TxtTit11);
InitIntuiText(TxtTit13, 34, 10, cBlack, cMagenta, '0', TxtTit12);
InitIntuiText(TxtTit14, 34, 11, cBlack, cMagenta, '0', TxtTit13);
END;
IF XmsUsage THEN (* XMS Speicher benutzt *)
BEGIN
GetInternRevision(VerHigh, VerLow); (* XMS Version ermitteln *)
VerHighStr[1] := Chr((VerHigh AND $0F) + Ord('0'));
VerHighStr[0] := Chr(1); (* Version vor dem Punkt *)
VerLowStr[1] := Chr(((VerLow AND $F0) SHR 4) + Ord('0'));
VerLowStr[2] := Chr((VerLow AND $0F) + Ord('0'));
VerLowStr[0] := Chr(2); (* Version nach dem Punkt *)
InitIntuiText(TxtTit20, 34, 13, cBlack, cMagenta,
'V' + VerHighStr + '.' + VerLowStr, TxtTit14);
QueryFreeXms(LargestXms, TotalXms); (* Freier XMS Speicher *)
Str(LONGINT(LargestXms) * 1024, TextString);
InitIntuiText(TxtTit21, 34, 14, cBlack, cMagenta, TextString, TxtTit20);
Str(LONGINT(TotalXms) * 1024, TextString);
InitIntuiText(TxtTit22, 34, 15, cBlack, cMagenta, TextString, TxtTit21);
END
ELSE (* Kein XMS Speicher da *)
BEGIN
InitIntuiText(TxtTit20, 34, 13, cBlack, cMagenta, 'NOT PRESENT',
TxtTit14);
InitIntuiText(TxtTit21, 34, 14, cBlack, cMagenta, '0', TxtTit20);
InitIntuiText(TxtTit22, 34, 15, cBlack, cMagenta, '0', TxtTit21);
END;
InitIntuiText(TxtOk, 37, 16, cBlack, cMagenta, '', NIL);
InitGadget(GadOk, 37, 16, 8, 3, TxtOk, cWhite, cMagenta, NIL, OkGadget);
InitRequester(InfoReq, 14, 3, 48, 20, cYellow, cMagenta,
' Memory Sizes ',
[rMove, rShadow, rClose, rTitle, rDouble], GadOk, TxtTit22);
Status := OpenRequester(InfoReq); (* Requester ffnen *)
IF Status THEN
Status := CloseRequester(InfoReq); (* Requester schlieáen *)
END; (* DoMemorySizes *)
(*$F+ Diese Prozedur ist eine Gadgetaktion und schreibt Laufwerkszeichen groá *)
PROCEDURE UpCaseDrive(GadgetPtr : pGadget);
BEGIN
WITH GadgetPtr^ DO
BEGIN
Buffer[1] := _UpCase(Buffer[1]); (* Nur Groábuchstaben *)
SetVirtualXY(OneText^.LeftEdge + Length(OneText^.Buffer) + 2,
OneText^.TopEdge);
WriteString(Buffer[1], OneText^.DetailPen, OneText^.BlockPen);
END;
END; (*$F- UpCaseDrive *)
(* Diese Prozedur gibt Informationen ber eine Diskette oder Festplatte aus *)
PROCEDURE DoDiskInfo;
VAR Dummy, (* Dient als Platzhalter *)
DoCont : BOOLEAN; (* Information fortsetzen *)
DiskTyp : DiskType; (* Typ einer Diskette *)
TextStr : STRING[15]; (* Allgemeiner Text *)
Regs : REGISTERS; (* Register des Prozessors *)
TxtTit1, (* Informationstexte *)
TxtTit2,
TxtTit3,
TxtTit4,
TxtTit5,
TxtTit6,
TxtTit7,
TxtTit8,
TxtTit9,
TxtTit10,
TxtTit11,
TxtTit12,
TxtTit13,
TxtTit14,
TxtTit15,
TxtTit16,
TxtTit17,
TxtTit18,
TxtTit19,
TxtTit20,
TxtTit21,
TxtTit22,
TxtTit23,
TxtTit24,
TxtOk : pIntuiText; (* Text fr Ok-Gadget *)
GadOk : pGadget; (* Ok-Gadget *)
InfoReq : pRequester; (* Requester Information *)
VerLow, (* Dos Version vor Punkt *)
VerHigh : BYTE; (* Dos Version nach Punkt *)
Drive : CHAR;
Status : BOOLEAN; (* Status des Requesters *)
TYPE DriveParamBlock = RECORD (* Laufwerksparameter *)
DriveNumber, (* Zugehriges Laufwerk *)
DeviceDriverNr : BYTE; (* Zugehriger Treiber *)
BytePerSector : WORD; (* Bytes pro Sektor *)
SecPerClusMin1, (* Sektoren pro Cluster -1 *)
Interleave : BYTE; (* Cluster - Cluster Shift *)
NrOfBootSecs : WORD; (* Anzahl Boot Sektoren *)
NrOfFats : BYTE; (* Anzahl der FAT's *)
NrOfRootItem, (* Anzahl Eintrge in Root *)
FirstDataSec, (* Erster Datensektor *)
LastCluster : WORD; (* Letzter Cluster *)
SectorsPerFat, (* Sektoren pro FAT *)
RootDirSec3 : BYTE; (* Erster Root Sektor Dos3 *)
RootDirSec4 : WORD; (* Erster Root Sektor Dos4 *)
END;
pDriveParBlock = ^DriveParamBlock; (* Zeiger auf Parameter *)
(* Diese Prozedur fragt einen Laufwerksbuchstaben ab *)
PROCEDURE AskDiskDrive(VAR Drive : CHAR; VAR DoCont : BOOLEAN);
VAR TxtOk, (* Text des Ok-Gadgets *)
TxtExit, (* Text des Exit-Gadgets *)
TxtDrive : pIntuiText; (* Text fr Laufwerk *)
GadOk, (* Ok-Gadget *)
GadExit, (* Exit-Gadget *)
GadDrive : pGadget; (* Gadget fr Laufwerk *)
DriveOk, (* Laufwerksbuchstabe Ok *)
Status : BOOLEAN; (* Status des Requesters *)
InfoReq : pRequester; (* Requester fr DriveInfo *)
BEGIN
InitIntuiText(TxtExit, 3, 4, cBlack, cMagenta, '', NIL);
InitIntuiText(TxtOk, 27, 4, cBlack, cMagenta, '', NIL);
InitIntuiText(TxtDrive, 4, 2, cBlack, cMagenta, (* Eingabe des Laufwerks *)
'Get Information From Drive', NIL);
InitGadget(GadExit, 3, 4, 8, 3, TxtExit, cWhite, cMagenta, NIL, ExitGadget);
InitGadget(GadDrive, 4, 2, 26, 1, TxtDrive, cWhite, cMagenta, GadExit,
TextGadget);
InitGadget(GadOk, 27, 4, 8, 3, TxtOk, cWhite, cMagenta, GadDrive, OkGadget);
WITH GadDrive^ DO (* Textpufferdaten *)
BEGIN
Buffer := Drive;
Size := 1;
Mask := ['A'..'Z', 'a'..'z'];
DoAction := TRUE; (* Aktion Groábuchstaben *)
Action := UpCaseDrive;
END;
InitRequester(InfoReq, 20, 7, 38, 8, cYellow, cMagenta,
' Get Disk Information ',
[rClose, rMove, rShadow, rTitle, rDouble], GadOk, NIL);
SetKeyStatus(CapsLockKey); (* CapsLock anschalten *)
Status := OpenRequester(InfoReq); (* Requester ffnen *)
DriveOk := Length(GadDrive^.Buffer) = 1; (* Lnge vom Laufwerktext *)
IF GetEndGadget(GadOk) = GadOk THEN (* Laufwerksname zuweisen *)
BEGIN
IF DriveOk THEN Drive := GadDrive^.Buffer[1];
DoCont := TRUE; (* Information fortsetzen *)
END
ELSE DoCont := FALSE; (* Information abgebrochen *)
IF Status THEN
Status := CloseRequester(InfoReq); (* Requester schlieáen *)
IF DoCont AND NOT DriveOk THEN (* Laufwerkbuchstabe fehlt *)
BEGIN
DoMessage(' Error - Missing Drive Character', FALSE, DoCont);
DoCont := FALSE; (* Information abgebrochen *)
END;
DelKeyStatus(CapsLockKey); (* CapsLock ausschalten *)
END; (* AskDiskDrive *)
BEGIN (* DoDiskInfo *)
Drive := 'A';
AskDiskDrive(Drive, DoCont); (* Laufwerk erfragen *)
IF DoCont THEN (* Information fortsetzen *)
BEGIN
DiskTyp := GetDiskType(Drive); (* Typ der Diskette *)
CASE DiskTyp OF (* Disktyp unterscheiden *)
UnknownDisk :
DoMessage(' Error - Type Of Disk Is Illegal', FALSE, Dummy);
DiskFailure :
DoMessage(' Error - Disk Has Read Errors', FALSE, Dummy);
DriveNotReady :
DoMessage(' Error - Disk Drive Is Not Ready', FALSE, Dummy);
UnknownDrive :
DoMessage(' Error - Drive Is Not Installed', FALSE, Dummy);
ELSE (* Alles in Ordnung *)
Regs.AH := $32; (* Hole Parameter Block *)
Regs.DL := Ord(Drive) - Ord('A') + 1; (* Nummer des Laufwerks *)
MsDos(Regs); (* Dos Interrupt *)
WITH pDriveParBlock(Ptr(Regs.DS, Regs.BX))^ DO
BEGIN
InitIntuiText(TxtTit1, 3, 2, cBlack, cMagenta,
'DISK SIZE -', NIL);
InitIntuiText(TxtTit2, 3, 3, cBlack, cMagenta,
'DISK FREE -', TxtTit1);
InitIntuiText(TxtTit3, 3, 4, cBlack, cMagenta,
'DISK VOLUME ID -', TxtTit2);
InitIntuiText(TxtTit4, 3, 5, cBlack, cMagenta,
'BYTES PER SECTOR -', TxtTit3);
InitIntuiText(TxtTit5, 3, 6, cBlack, cMagenta,
'SECTORS PER CLUSTER -', TxtTit4);
InitIntuiText(TxtTit6, 3, 7, cBlack, cMagenta,
'NUMBER OF BOOT SECTORS -', TxtTit5);
InitIntuiText(TxtTit7, 3, 8, cBlack, cMagenta,
'NUMBER OF FATS -', TxtTit6);
InitIntuiText(TxtTit8, 3, 9, cBlack, cMagenta,
'NUMBER OF ROOT ITEMS -', TxtTit7);
InitIntuiText(TxtTit9, 3, 10, cBlack, cMagenta,
'FIRST DATA SECTOR -', TxtTit8);
InitIntuiText(TxtTit10, 3, 11, cBlack, cMagenta,
'NUMBER OF CLUSTERS -', TxtTit9);
InitIntuiText(TxtTit11, 3, 12, cBlack, cMagenta,
'SECTORS PER FAT -', TxtTit10);
InitIntuiText(TxtTit12, 3, 13, cBlack, cMagenta,
'FIRST ROOT SECTOR -', TxtTit11);
Str(DiskSize(Ord(Drive) - Ord('A') + 1), TextStr);
InitIntuiText(TxtTit13, 32, 2, cBlack, cMagenta, TextStr,
TxtTit12);
Str(DiskFree(Ord(Drive) - Ord('A') + 1), TextStr);
InitIntuiText(TxtTit14, 32, 3, cBlack, cMagenta, TextStr,
TxtTit13);
TextStr := GetVolume(Drive);
IF Length(TextStr) = 0 THEN TextStr := 'NO VOLUME ID';
InitIntuiText(TxtTit15, 32, 4, cBlack, cMagenta, TextStr,
TxtTit14);
Str(BytePerSector, TextStr);
InitIntuiText(TxtTit16, 32, 5, cBlack, cMagenta, TextStr,
TxtTit15);
Str(SecPerClusMin1 + 1, TextStr);
InitIntuiText(TxtTit17, 32, 6, cBlack, cMagenta, TextStr,
TxtTit16);
Str(NrOfBootSecs, TextStr);
InitIntuiText(TxtTit18, 32, 7, cBlack, cMagenta, TextStr,
TxtTit17);
Str(NrOfFats, TextStr);
InitIntuiText(TxtTit19, 32, 8, cBlack, cMagenta, TextStr,
TxtTit18);
Str(NrOfRootItem, TextStr);
InitIntuiText(TxtTit20, 32, 9, cBlack, cMagenta, TextStr,
TxtTit19);
Str(FirstDataSec, TextStr);
InitIntuiText(TxtTit21, 32, 10, cBlack, cMagenta, TextStr,
TxtTit20);
Str(LastCluster - 1, TextStr);
InitIntuiText(TxtTit22, 32, 11, cBlack, cMagenta, TextStr,
TxtTit21);
Str(SectorsPerFat, TextStr);
InitIntuiText(TxtTit23, 32, 12, cBlack, cMagenta, TextStr,
TxtTit22);
MsDosVersion(VerHigh, VerLow); (* Dos Version ermitteln *)
IF VerHigh > 3 THEN (* Dos Version gráer V3 *)
Str(RootDirSec4, TextStr)
ELSE Str(RootDirSec3, TextStr);
InitIntuiText(TxtTit24, 32, 13, cBlack, cMagenta, TextStr,
TxtTit23);
InitIntuiText(TxtOk, 36, 14, cBlack, cMagenta, '', NIL);
InitGadget(GadOk, 36, 14, 8, 3, TxtOk, cWhite, cMagenta, NIL,
OkGadget);
InitRequester(InfoReq, 15, 3, 47, 18, cYellow, cMagenta,
' Disk Information ', [rMove, rShadow, rClose,
rTitle, rDouble], GadOk, TxtTit24);
Status := OpenRequester(InfoReq); (* Requester ffnen *)
IF Status THEN
Status := CloseRequester(InfoReq); (* Requester schlieáen *)
END;
END;
END;
END; (* DoDiskInfo *)
END. (* InfoMenu *)
|
unit wwEmailWithAttachment;
{
// Copyright (c) 2017 by Woll2Woll Software
//
// Methods: wwEmail (Email with attachment for ios, android, and windows)
//
procedure wwEmail(
Recipients: Array of String;
ccRecipients: Array of String;
bccRecipients: Array of String;
Subject, Content,
AttachmentPath: string;
mimeTypeStr: string = '');
// If you require Mapi protocol for windows instead of ole, see the firepower
// product demos and source
//
// In order for this routine to compile and link for iOS, you will need to
// add the MessageUI framework to your ios sdk
// The steps are simple, but as follows.
//
// 1. Select from the IDE - Tools | Options | SDK Manager
//
// 2. Then for your 64 bit platform (and 32 bit if you like) do the following
// a) Scroll to the bottom of your Frameworks list and select the last one
//
// b) Click the add button on the right to add a new library refence and
// then enter the following data for your entry
// Path on remote machine:
// $(SDKROOT)/System/Library/Frameworks
// File Mask
// MessageUI
// Path Type
// Leave unselected
//
// 3. Click the button Update Local File Cache to update your sdk
//
// 4. Click the OK Button to close the dialog
//
// Now when you compile it should not yield a link error
}
interface
{$SCOPEDENUMS ON}
uses
System.SysUtils, System.Classes, System.Types, System.Math, System.Generics.Collections,
System.IOUtils, System.StrUtils,
{$ifdef mswindows}
Comobj,
Winapi.ShellAPI,
Winapi.Windows,
Winapi.ActiveX,
System.Win.registry,
{$endif}
{$ifdef macos}
Macapi.ObjectiveC, Macapi.Helpers,
Macapi.ObjCRuntime,
{$ifdef ios}
iOSapi.AssetsLibrary,
iOSapi.CocoaTypes, iOSapi.Helpers,
FMX.Helpers.iOS, iOSapi.MediaPlayer, iOSapi.Foundation, iOSapi.UIKit, iOSapi.CoreGraphics,
{$else}
macAPI.CocoaTypes,
{$endif}
{$endif}
System.TypInfo;
type
TwwEmailAttachmentLocation = (Default, Cache, Files, ExternalDrive, ExternalCache);
procedure wwEmail(
Recipients: Array of String;
ccRecipients: Array of String;
bccRecipients: Array of String;
Subject, Content,
AttachmentPath: string;
mimeTypeStr: string = '');
implementation
{$ifdef android}
uses
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.App,
Androidapi.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.Helpers,
Androidapi.JNI.Net,
Androidapi.JNI.Os,
Androidapi.IOUtils;
{$endif}
{$region 'ios'}
{$ifdef ios}
{$IF not defined(CPUARM)}
uses
Posix.Dlfcn;
{$ENDIF}
const
libMessageUI = '/System/Library/Frameworks/MessageUI.framework/MessageUI';
type
MFMessageComposeResult = NSInteger;
MFMailComposeResult = NSInteger;
MFMailComposeViewControllerDelegate = interface;
MFMailComposeViewControllerClass = interface(UINavigationControllerClass)
['{B6292F63-0DE9-4FE7-BEF7-871D5FE75362}']
function canSendMail: Boolean; cdecl;
end;
MFMailComposeViewController = interface(UINavigationController)
['{5AD35A29-4418-48D3-AB8A-2F114B4B0EDC}']
function mailComposeDelegate: MFMailComposeViewControllerDelegate; cdecl;
procedure setMailComposeDelegate(mailComposeDelegate
: MFMailComposeViewControllerDelegate); cdecl;
procedure setSubject(subject: NSString); cdecl;
procedure setToRecipients(toRecipients: NSArray); cdecl;
procedure setCcRecipients(ccRecipients: NSArray); cdecl;
procedure setBccRecipients(bccRecipients: NSArray); cdecl;
procedure setMessageBody(body: NSString; isHTML: Boolean); cdecl;
procedure addAttachmentData(attachment: NSData; mimeType: NSString;
fileName: NSString); cdecl;
end;
TMFMailComposeViewController = class
(TOCGenericImport<MFMailComposeViewControllerClass,
MFMailComposeViewController>)
end;
MFMailComposeViewControllerDelegate = interface(IObjectiveC)
['{068352EB-9182-4581-86F5-EAFCE7304E32}']
procedure mailComposeController(controller: MFMailComposeViewController;
didFinishWithResult: MFMailComposeResult; error: NSError); cdecl;
end;
{ ***************************************************************************************** }
TMFMailComposeViewControllerDelegate = class(TOCLocal,
MFMailComposeViewControllerDelegate)
private
MFMailComposeViewController: MFMailComposeViewController;
public
constructor Create(aMFMailComposeViewController
: MFMailComposeViewController);
procedure mailComposeController(controller: MFMailComposeViewController;
didFinishWithResult: MFMailComposeResult; error: NSError); cdecl;
end;
var
mailComposeDelegate: TMFMailComposeViewControllerDelegate;
constructor TMFMailComposeViewControllerDelegate.Create
(aMFMailComposeViewController: MFMailComposeViewController);
begin
inherited Create;
MFMailComposeViewController := aMFMailComposeViewController;
end;
// /Callback function when mail completes
procedure TMFMailComposeViewControllerDelegate.mailComposeController
(controller: MFMailComposeViewController;
didFinishWithResult: MFMailComposeResult; error: NSError);
var
aWindow: UIWindow;
begin
aWindow := TiOSHelper.SharedApplication.keyWindow;
if Assigned(aWindow) and Assigned(aWindow.rootViewController) then
aWindow.rootViewController.dismissModalViewControllerAnimated
(True { animated } );
MFMailComposeViewController.release;
MFMailComposeViewController := nil;
end;
procedure wwEmail(
Recipients: Array of String;
ccRecipients: Array of String;
bccRecipients: Array of String;
Subject, Content,
AttachmentPath: string;
mimeTypeStr: string = '');
var
MailController: MFMailComposeViewController;
attachment: NSData;
fileName: string;
mimeType: NSString;
//controller: UIViewController;
Window: UIWindow;
nsRecipients, nsccRecipients, nsbccRecipients: NSArray;
function ConvertStringArrayToNSArray(InArray: Array of String): NSArray;
var
LRecipients: Array of Pointer;
i: integer;
begin
SetLength(LRecipients, length(InArray));
for i:= low(InArray) to high(InArray) do
LRecipients[i]:= (StrToNSStr(InArray[i]) as ILocalObject).GetObjectID;
Result := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(
@LRecipients[0], Length(LRecipients)));
MailController.setToRecipients(Result);
end;
begin
fileName := AttachmentPath;
MailController := TMFMailComposeViewController.Wrap
(TMFMailComposeViewController.Alloc.init);
mailComposeDelegate := TMFMailComposeViewControllerDelegate.Create(MailController);
MailController.setMailComposeDelegate(mailComposeDelegate);
MailController.setSubject(StrToNSStr(Subject));
MailController.setMessageBody(StrToNSStr(Content), false);
if length(Recipients)>0 then
begin
nsRecipients:= ConvertStringArrayToNSArray(Recipients);
MailController.setToRecipients(nsRecipients);
end;
if length(ccRecipients)>0 then
begin
nsccRecipients:= ConvertStringArrayToNSArray(ccRecipients);
MailController.setCcRecipients(nsccRecipients);
end;
if length(bccRecipients)>0 then
begin
nsbccRecipients:= ConvertStringArrayToNSArray(bccRecipients);
MailController.setBccRecipients(nsbccRecipients);
end;
if fileName <> '' then
begin
attachment := TNSData.Wrap(TNSData.Alloc.initWithContentsOfFile
(StrToNSStr(fileName)));
try
if mimeTypeStr = '' then
mimeTypeStr := 'text/plain';
mimeType := StrToNSStr(mimeTypeStr);
MailController.addAttachmentData(attachment, mimeType,
StrToNSStr(TPath.GetFileName(fileName))); // shorten form
finally
attachment.release;
end;
end;
Window := TiOSHelper.SharedApplication.keyWindow;
if (Window <> nil) and (Window.rootViewController <> nil) then
Window.rootViewController.presentModalViewController(MailController, True);
end;
{$IF defined(CPUARM)}
procedure LibMessageUIFakeLoader; cdecl; external libMessageUI;
{$ELSE}
var iMessageUIModule: THandle;
initialization
iMessageUIModule := dlopen(MarshaledAString(libMessageUI), RTLD_LAZY);
finalization
dlclose(iMessageUIModule);
{$ENDIF}
{$endif}
{$endregion}
{$region 'android'}
{$ifdef android}
procedure wwEmail(Recipients: Array of String; ccRecipients: Array of String;
bccRecipients: Array of String; subject, Content, AttachmentPath: string;
mimeTypeStr: string = '');
var
Intent: JIntent;
Uri: Jnet_Uri;
AttachmentFile: JFile;
i: integer;
emailAddresses: TJavaObjectArray<JString>;
fileNameTemp: JString;
CacheName: string;
IntentChooser: JIntent;
ChooserCaption: string;
begin
Intent := TJIntent.Create;
Intent.setAction(TJIntent.JavaClass.ACTION_Send);
Intent.setFlags(TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK);
emailAddresses := TJavaObjectArray<JString>.Create(length(Recipients));
for i := Low(Recipients) to High(Recipients) do
emailAddresses.Items[i] := StringToJString(Recipients[i]);
Intent.putExtra(TJIntent.JavaClass.EXTRA_EMAIL, emailAddresses);
Intent.putExtra(TJIntent.JavaClass.EXTRA_SUBJECT, StringToJString(subject));
Intent.putExtra(TJIntent.JavaClass.EXTRA_TEXT, StringToJString(Content));
// Just filename portion for android services
CacheName := GetExternalCacheDir + TPath.DirectorySeparatorChar +
TPath.GetFileName(AttachmentPath);
if FileExists(CacheName) then
Tfile.Delete(CacheName);
Tfile.Copy(AttachmentPath, CacheName);
fileNameTemp := StringToJString(CacheName);
AttachmentFile := TJFile.JavaClass.init(fileNameTemp);
if AttachmentFile <> nil then // attachment found
begin
AttachmentFile.setReadable(True, false);
Uri := TJnet_Uri.JavaClass.fromFile(AttachmentFile);
Intent.putExtra(TJIntent.JavaClass.EXTRA_STREAM,
TJParcelable.Wrap((Uri as ILocalObject).GetObjectID));
end;
Intent.setType(StringToJString('vnd.android.cursor.dir/email'));
ChooserCaption := 'Send To';
IntentChooser := TJIntent.JavaClass.createChooser(Intent,
StrToJCharSequence(ChooserCaption));
TAndroidHelper.Activity.startActivityForResult(IntentChooser, 0);
end;
{$endif}
{$endregion}
{$region 'MSWindows'}
{$ifdef MSWINDOWS}
function Succeeded(Res: HResult): Boolean;
begin
Result := Res and $80000000 = 0;
end;
// Want to Bypass exception so we check this without using the activex unit
function HaveActiveOleObject(const ClassName: string): boolean;
var
ClassID: TCLSID;
Unknown: IUnknown;
oleresult: HResult;
begin
ClassID := ProgIDToClassID(ClassName);
oleResult:= GetActiveObject(ClassID, nil, Unknown);
result:= Succeeded(oleResult);
end;
procedure DisplayMail(Address, ccAddress, bccAddress,
Subject, Body: string; Attachment: TFileName);
var
Outlook: OleVariant;
Mail: Variant;
const
olMailItem = $00000000;
begin
if not HaveActiveOleObject('Outlook.Application') then
Outlook := CreateOleObject('Outlook.Application')
else
Outlook:= GetActiveOleObject('Outlook.Application');
Mail := Outlook.CreateItem(olMailItem);
Mail.To := Address;
Mail.BCC:= bccAddress;
Mail.CC:= ccAddress;
Mail.Subject := Subject;
Mail.Body := Body;
if Attachment <> '' then
Mail.Attachments.Add(Attachment);
Mail.Display;
end;
// Attachment seems to only work with Outlook
procedure wwEmail(Recipients: Array of String; ccRecipients: Array of String;
bccRecipients: Array of String; subject, Content, AttachmentPath: string;
mimeTypeStr: string = '');
var mailcommand: string;
Recipient, ccRecipient, bccRecipient: string;
function GetAddress(AAddresses: Array of String): string;
var
LAddress: string;
Address: string;
begin
Address:= '';
for LAddress in AAddresses do
begin
StringReplace(LAddress, ' ', '%20%', [rfReplaceAll, rfIgnoreCase]);
if Address <> '' then
Address := Address + ';' + LAddress
else
Address := LAddress;
end;
result:= Address;
end;
begin
// Later should do url encoding for recipients
Recipient:= GetAddress(Recipients);
ccRecipient:= GetAddress(ccRecipients);
bccRecipient:= GetAddress(bccRecipients);
if (AttachmentPath<>'') then
DisplayMail(Recipient, ccRecipient, bccRecipient, Subject, Content, AttachmentPath)
else begin
mailcommand:= 'mailto:' + Recipient + '?Subject=' + Subject +
'&Body=' + Content +
'&Attachment=' + '"' + AttachmentPath + '"';
ShellExecute(0, 'OPEN', pchar(mailcommand),
nil, nil, sw_shownormal);
end
end;
{$endif}
{$endregion}
{$region 'OSX'}
{$ifndef nextgen}
{$ifdef macos}
procedure wwEmail(
Recipients: Array of String;
ccRecipients: Array of String;
bccRecipients: Array of String;
Subject, Content,
AttachmentPath: string;
mimeTypeStr: string = '');
begin
// Currently does nothing in osx
end;
{$endif}
{$endif}
{$endregion}
end.
|
{$D-,L-,O+,Q-,R-,Y-,S-}
unit unOptionsPageDlg;
interface
uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms,
Vcl.Controls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls, Vcl.ExtCtrls,
Vcl.Dialogs, Vcl.ActnMan, Vcl.ActnColorMaps, Vcl.ToolWin,Vcl.Menus,
Vcl.ImgList, Vcl.Mask, unGlobUnit, EditNumerical, SuperSubLabel;
type
TOptionsPagesDlg = class(TForm)
Panel1: TPanel;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet4: TTabSheet;
ShapeROIMonoColor: TShape;
ColorDialogROI: TColorDialog;
CheckBoxUseSameColForROI: TCheckBox;
TitleSetROIColor: TLabel;
BevelSetColor: TBevel;
TitleROIthickness: TLabel;
TitleROIthickFactor: TLabel;
trbThickerROI: TTrackBar;
trbROIthickness: TTrackBar;
BevelThickness: TBevel;
ShapeROI: TShape;
ShapeROIthicker: TShape;
trbFreeHandThickness: TTrackBar;
ShapeFreeHand: TShape;
TitleFreeHand: TLabel;
ShapeFontColor: TShape;
TitleSetFontColor: TLabel;
CheckBoxUseSameFontCol: TCheckBox;
BevelFontColor: TBevel;
CheckBoxEnableROINumbers: TCheckBox;
BevelROINr: TBevel;
trbMarkWith: TTrackBar;
trbMarkSize: TTrackBar;
TitleSetMarkTable1Color: TLabel;
imgMarkBkg: TImage;
BevelMark: TBevel;
Label1: TLabel;
TitMarkThick: TLabel;
shSmEvent: TShape;
shBigEvent: TShape;
TitTable2MarkColor: TLabel;
DisplayBigMarks: TCheckBox;
DisplaySmallMarks: TCheckBox;
Bevel1: TBevel;
Bevel2: TBevel;
titMainWindow: TLabel;
titAvWindow: TLabel;
Bevel3: TBevel;
EnableROIonAverWin: TCheckBox;
ShowSmMarksOnAverWin: TCheckBox;
ShowBigMarksOnAverWin: TCheckBox;
trbSymbSize: TTrackBar;
shSymbSize: TShape;
lblSymbSize: TLabel;
Bevel5: TBevel;
Label2: TLabel;
AlwaysUseSymb: TCheckBox;
GenGenSetComm: TCheckBox;
GenAutoSearchComm: TCheckBox;
PromptForComment: TCheckBox;
Bevel6: TBevel;
Bevel7: TBevel;
Label3: TLabel;
Label4: TLabel;
trbMesLineThickness: TTrackBar;
Label5: TLabel;
MesLineColor: TShape;
Label6: TLabel;
Bevel8: TBevel;
MesLineThickness: TShape;
ckbKeepOldROI: TCheckBox;
Bevel9: TBevel;
MaxRatio: TTrackBar;
lbMaxRatio: TLabel;
Label7: TLabel;
Bevel10: TBevel;
btCorrectTime: TButton;
Bevel11: TBevel;
Label8: TLabel;
Im1: TImage;
Im15: TImage;
Im3: TImage;
Im19: TImage;
Im5: TImage;
Im2: TImage;
Im7: TImage;
Im17: TImage;
Im9: TImage;
Im11: TImage;
Im13: TImage;
Bevel13: TBevel;
Im4: TImage;
Im6: TImage;
Im8: TImage;
Im10: TImage;
Im12: TImage;
Im14: TImage;
Im16: TImage;
Im18: TImage;
Im20: TImage;
ShapeSelFrame: TShape;
Label9: TLabel;
ListBoxColor: TListBox;
UndueColors: TToolBar;
ColUnDo: TToolButton;
ColReDo: TToolButton;
ResToOriginal: TButton;
Label10: TLabel;
ResetToInitial: TButton;
PopupMenuYesNo: TPopupMenu;
Yes: TMenuItem;
Cancel: TMenuItem;
Bevel14: TBevel;
AllowFullPathOfLastFile: TCheckBox;
Bevel15: TBevel;
MaxGamma: TTrackBar;
lbMaxGamma: TLabel;
tlGamma: TLabel;
Gam: TLabel;
ImageListArrowsEnabled: TImageList;
ImageListArrowsDisabl: TImageList;
TabSheet3: TTabSheet;
Panel2: TPanel;
OKBtn: TButton;
tlMajorPixSetTitle: TLabel;
Bevel17: TBevel;
tl100micr: TLabel;
lbMicronsPix: TLabel;
Bevel18: TBevel;
ChBoxNikonND2orTiff: TCheckBox;
ChBoxNoranPrairie: TCheckBox;
ChBoxTiffStack: TCheckBox;
CbAndorTiffs: TCheckBox;
ChBoxTIFF: TCheckBox;
tlCheckToOverride: TLabel;
lbPixPer100Microns: TLabel;
lbCurFileInfo: TLabel;
lbBinning: TLabel;
Bevel19: TBevel;
cbUseMoviFilePath: TCheckBox;
Bevel20: TBevel;
cbAlignXofImagePlayback: TCheckBox;
TtlTimeSerPlot: TLabel;
tlFrmSec: TLabel;
Bevel21: TBevel;
ChbCheckAllFilesExist: TCheckBox;
ChBLoadTimeStamps: TCheckBox;
Bevel22: TBevel;
CbStreamPix: TCheckBox;
NoranPrairieEdPix: TEditNumerical;
StreamPixEdPix: TEditNumerical;
AndorEdPix: TEditNumerical;
NikonEdPix: TEditNumerical;
StackGenTiffEdPix: TEditNumerical;
SingleGenTiffEdPix: TEditNumerical;
StackTiffFrmSec: TEditNumerical;
SingleGenTiffFrmSec: TEditNumerical;
Bevel4: TBevel;
Label11: TLabel;
Label12: TLabel;
LSTimeBarColor: TShape;
Label13: TLabel;
trbLSTimeBarThickness: TTrackBar;
LSTimeBarThickness: TShape;
Label14: TLabel;
Label15: TLabel;
enLSTimeBarDuration: TEditNumerical;
cbLSTimeBarVisible: TCheckBox;
ChBoxBioRad: TCheckBox;
BioRadEdPix: TEditNumerical;
enLineCapsWidth: TEditNumerical;
Label16: TLabel;
ChBoxZeiss: TCheckBox;
ZeissLSMEdPix: TEditNumerical;
Label17: TLabel;
Label18: TLabel;
enSizeBarLenghtINµm: TEditNumerical;
Label19: TLabel;
Label20: TLabel;
enGridDensity: TEditNumerical;
Label21: TLabel;
procedure SingleGenTiffFrmSecReturnPressed(Sender: TObject);
procedure StackTiffFrmSecReturnPressed(Sender: TObject);
procedure NikonEdPixReturnPressed(Sender: TObject);
procedure SingleGenTiffEdPixReturnPressed(Sender: TObject);
procedure StackGenTiffEdPixReturnPressed(Sender: TObject);
procedure AndorEdPixReturnPressed(Sender: TObject);
procedure StreamPixEdPixReturnPressed(Sender: TObject);
procedure NoranPrairieEdPixReturnPressed(Sender: TObject);
procedure ShapeROIMonoColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure CheckBoxUseSameColForROIClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OKBtnClick(Sender: TObject);
procedure trbROIthicknessChange(Sender: TObject);
procedure trbThickerROIChange(Sender: TObject);
procedure trbFreeHandThicknessChange(Sender: TObject);
procedure CheckBoxUseSameFontColClick(Sender: TObject);
procedure ShapeFontColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure CheckBoxEnableROINumbersClick(Sender: TObject);
procedure trbMarkWithChange(Sender: TObject);
procedure trbMarkSizeChange(Sender: TObject);
procedure shSmEventMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure shBigEventMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure DisplaySmallMarksClick(Sender: TObject);
procedure DisplayBigMarksClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ShowSmMarksOnAverWinClick(Sender: TObject);
procedure ShowBigMarksOnAverWinClick(Sender: TObject);
procedure EnableROIonAverWinClick(Sender: TObject);
procedure trbSymbSizeChange(Sender: TObject);
procedure shSymbSizeMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure AlwaysUseSymbClick(Sender: TObject);
procedure PromptForCommentClick(Sender: TObject);
procedure GenGenSetCommClick(Sender: TObject);
procedure GenAutoSearchCommClick(Sender: TObject);
procedure trbMesLineThicknessChange(Sender: TObject);
procedure MesLineColorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ckbKeepOldROIClick(Sender: TObject);
procedure MaxRatioChange(Sender: TObject);
procedure btCorrectTimeClick(Sender: TObject);
procedure Im1Click(Sender: TObject);
procedure Im2Click(Sender: TObject);
procedure Im3Click(Sender: TObject);
procedure Im4Click(Sender: TObject);
procedure Im5Click(Sender: TObject);
procedure Im6Click(Sender: TObject);
procedure Im7Click(Sender: TObject);
procedure Im8Click(Sender: TObject);
procedure Im9Click(Sender: TObject);
procedure Im10Click(Sender: TObject);
procedure Im11Click(Sender: TObject);
procedure Im12Click(Sender: TObject);
procedure Im13Click(Sender: TObject);
procedure Im14Click(Sender: TObject);
procedure Im15Click(Sender: TObject);
procedure Im16Click(Sender: TObject);
procedure Im17Click(Sender: TObject);
procedure Im18Click(Sender: TObject);
procedure Im19Click(Sender: TObject);
procedure Im20Click(Sender: TObject);
procedure ShapeSelFrameMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ColUnDoClick(Sender: TObject);
procedure ColReDoClick(Sender: TObject);
procedure ResToOriginalClick(Sender: TObject);
procedure ResetToInitialClick(Sender: TObject);
procedure YesClick(Sender: TObject);
procedure AllowFullPathOfLastFileClick(Sender: TObject);
procedure MaxGammaChange(Sender: TObject);
procedure ChBoxNikonND2orTiffClick(Sender: TObject);
procedure ChBoxNoranPrairieClick(Sender: TObject);
procedure ChBoxTiffStackClick(Sender: TObject);
procedure CbAndorTiffsClick(Sender: TObject);
procedure ChBoxTIFFClick(Sender: TObject);
procedure cbUseMoviFilePathClick(Sender: TObject);
procedure cbAlignXofImagePlaybackClick(Sender: TObject);
procedure ChbCheckAllFilesExistClick(Sender: TObject);
procedure ChBLoadTimeStampsClick(Sender: TObject);
procedure CbStreamPixClick(Sender: TObject);
procedure LSTimeBarColorMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure trbLSTimeBarThicknessChange(Sender: TObject);
procedure enLSTimeBarDurationReturnPressed(Sender: TObject);
procedure cbLSTimeBarVisibleClick(Sender: TObject);
procedure BioRadEdPixReturnPressed(Sender: TObject);
procedure ChBoxBioRadClick(Sender: TObject);
procedure enLineCapsWidthReturnPressed(Sender: TObject);
procedure ChBoxZeissClick(Sender: TObject);
procedure ZeissLSMEdPixReturnPressed(Sender: TObject);
procedure enSizeBarLenghtINµmReturnPressed(Sender: TObject);
procedure enGridDensityReturnPressed(Sender: TObject);
private
{ Private declarations }
ResetCode : Byte;
ChangeInMarks : Boolean;
ChangePlotSet : Boolean;
AvImSmoothChange : Boolean;
ROIcolChange : Boolean;
PixSetChange : Boolean;
LSSettingChange : Boolean;
MesLineChange : Boolean;
ButCol : TROIColArr; {20 ROI }
FntCol : TFontColArr;
ButColBack : TROIColArr; {20 ROI }
FntColBack : TFontColArr;
SelFrameColorBack : TColor;
{last Color [ROI or Font}
LastCol : Byte;
{Last Type changed - ROI [= 1]; or Font[=2]; or Frame[=3]}
LastType : Byte;
{Last State: 1 = Use ButCol or FntCol; 2 = Use BackUp array}
LastState : Byte;
Procedure DrawMark;
procedure ReplotAverImage;
Procedure ChangeButCol(const Img : TImage);
Procedure RestoreColSettings(const Img : TImage);
Procedure GetImNrAndDoReset;
Procedure SetButImages;
Procedure SetFinalColorSettings;
Procedure ResToBuildIn;
procedure ResetToBeg;
public
{ Public declarations }
end;
Var
OptionsPagesDlg : TOptionsPagesDlg;
implementation
Uses unMainWindow, unAverIm, unTimeSerAnal,unImageControl,
unPlayBack, unLineScan, unMergeWindow, un2ndWin;
{$R *.dfm}
procedure TOptionsPagesDlg.ShapeROIMonoColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
If ColorDialogROI.Execute Then Begin
ShapeROIMonoColor.Brush.Color := ColorDialogROI.Color;
ROIvar.MonoCol := ColorDialogROI.Color;
End;
end;
procedure TOptionsPagesDlg.CheckBoxUseSameColForROIClick(Sender: TObject);
begin
ROIvar.UseMonoCol := CheckBoxUseSameColForROI.Checked;
end;
procedure TOptionsPagesDlg.FormCreate(Sender: TObject);
var i : integer;
TemFTitle : AnsiString;
begin
AllowFullPathOfLastFile.Checked := AllowFullPath;
ChbCheckAllFilesExist.Checked := CheckAllFilesExist;
ChBLoadTimeStamps.Checked := LoadStreamPixAndND2TimeSt;
ShapeROIMonoColor.Brush.Color := ROIvar.MonoCol;
trbThickerROI.Position := ROIvar.Ticker div ROIvar.TckNess;
trbThickerROI.Tag := trbThickerROI.Position;
trbROIthickness.Position := ROIvar.TckNess;
trbROIthickness.Tag := trbROIthickness.Position;
trbFreeHandThickness.Position := ROIvar.FhTickness;
trbFreeHandThickness.Tag := trbFreeHandThickness.Position;
CheckBoxUseSameColForROI.Checked := ROIvar.UseMonoCol;
CheckBoxUseSameFontCol.Checked := ROIvar.UseMonoFontCol;
ShapeFontColor.Brush.Color := ROIvar.MonoFontCol;
CheckBoxEnableROINumbers.Checked := ROIvar.UseROINr;
trbMarkSize.Position := MarkPar.Size;
trbMarkSize.Tag := trbMarkSize.Position;
trbMarkWith.Position := Markpar.Thick;
trbMarkWith.Tag := trbMarkWith.Position;
DrawMark;
shSmEvent .Brush.Color := MarkPar.SmallEventColor;
shBigEvent.Brush.Color := MarkPar.BigEventColor;
DisplaySmallMarks.Checked := MarkPar.DisplaySmEvents;
DisplayBigMarks.Checked := MarkPar.DisplayBigEvents;
ChangeInMarks := False;
EnableROIonAverWin.Checked := ROIvar.ROIonAverWin;
ShowSmMarksOnAverWin.Checked := MarkPar.ShowSmEvOnAverWin;
ShowBigMarksOnAverWin.Checked := MarkPar.ShowBigEvOnAverWin;
AvImSmoothChange := False;
ChangePlotSet := False;
trbSymbSize.Position := TimPltSlid.SymbSize;
trbSymbSize.Tag := trbSymbSize.Position;
shSymbSize.Brush.Color := TimPltSlid.SymbFromTableCol;
shSymbSize.Pen.Color := TimPltSlid.SymbFromTableCol;
AlwaysUseSymb.Checked := TimPltSlid.AlwaysUseSymb;
PromptForComment.Checked := MarkPar.PromptForComment;
GenAutoSearchComm.Checked := MarkPar.GenAutoSearchComm;
GenGenSetComm.Checked := MarkPar.GenGenSetComm;
ckbKeepOldROI.Checked := ROIvar.KeepOldROI;
//Measuring Line
trbMesLineThickness.Position := MesLineVar.Thickness;
MesLineColor.Brush.Color := MesLineVar.Color;
MesLineThickness.Brush.Color := MesLineVar.Color;
MesLineThickness.Pen.Color := MesLineVar.Color;
if (MesLineVar.CapsWitdh <> 0) then
enLineCapsWidth.NumberOne := MesLineVar.CapsWitdh*2 + 1 else
enLineCapsWidth.NumberOne := 0;
MesLineChange := False;
// Line Scan Time Bar
cbLSTimeBarVisible.Checked := LSTimeBarPar.Visible;
LSTimeBarColor.Brush.Color := LSTimeBarPar.Color;
LSTimeBarThickness.Brush.Color := LSTimeBarPar.Color;
LSTimeBarThickness.Pen.Color := LSTimeBarPar.Color;
trbLSTimeBarThickness.Position := LSTimeBarPar.Thickness;
enLSTimeBarDuration.NumberFloat := LSTimeBarPar.Duration;
LSSettingChange := False;
//2D Windows Size Bar (µm)
enSizeBarLenghtINµm.NumberOne := ExportDial.SizeBarLenghtINµm;
if (TimPltSlid.YmaxRatOn = 10) then MaxRatio.Position := -1 else
if (TimPltSlid.YmaxRatOn = 30) then MaxRatio.Position := 0 else
if (TimPltSlid.YmaxRatOn > 30) then MaxRatio.Position := TimPltSlid.YmaxRatOn div 50;
lbMaxRatio.Caption := IntToStr(TimPltSlid.YmaxRatOn div 10);
MaxRatio.Tag := MaxRatio.Position;
ImageContrVar.MaxGamma := frmImageControl.trbGamma.Max;
MaxGamma.Position := ImageContrVar.MaxGamma div 50;
lbMaxGamma.Caption := IntToStr(5*MaxGamma.Position);
if (MainImLoaded = True) and (MovFType = NORAN_SGI_MOV{Noran}) then btCorrectTime.Enabled := True
else btCorrectTime.Enabled := False;
{copies color to Temp Arrays}
for i := 1 to 21 do ButCol[i] := ROIvar.ROICol[i];
for i := 1 to 20 do FntCol[i] := ROIvar.FontCol[i];
for i := 1 to 21 do ButColBack[i] := ROIvar.ROICol[i];
for i := 1 to 20 do FntColBack[i] := ROIvar.FontCol[i];
{---------- Initializes Pixel/Micron Setting Page --- }
If MainImLoaded = True then Begin
if MovFType = NIKON_ND2_MOV then TemFTitle := 'Nikon NIS-Elements Multi-Image ND2 File' else
if MovFType = NIKON_TIFF_MOV then TemFTitle := 'Nikon Multi-Image Tiff' else
if MovFType = NORAN_PRARIE_MOV then TemFTitle := 'Noran Prarie' else
if MovFType = StreamPix_Mov then TemFTitle := 'StreamPix' else
if MovFType = ANDOR_MOV then begin
if (ImageFileType > SINGLE_IMAGE) then TemFTitle := 'Andor Multi-Image Tiff';
if (NrIm > 1) and (ImageFileType = SINGLE_IMAGE) then
TemFTitle := 'Stack of Andor Tiff';
if (NrIm = 1) then TemFTitle := 'Andor Single Image Tiff';
end else
if MovFType = STACK_BW_TIFF then begin
if TIFFfileType = TIFF_GENERIC then
TemFTitle := 'Stack of Generic Tiffs' else
if TIFFfileType = TIFF_QED then
TemFTitle := 'Stack of QED Tiffs Open as Generic ' else
if TIFFfileType = TIFF_NORAN_PRARIE then
TemFTitle := 'Stack of Noran (Prarie) Tiffs Open as Generic';
end else
if MovFType = SINGLE_BW_TIFF then begin
if TIFFfileType = TIFF_GENERIC then
TemFTitle := 'Generic Grayscale Tiff' else
if TIFFfileType = TIFF_QED then
TemFTitle := 'QED Tiff Open as Generic ' else
if TIFFfileType = TIFF_NORAN_PRARIE then
TemFTitle := 'Noran (Prarie) Tiff Open as Generic' else
if TIFFfileType = TIFF_ImageJ then
TemFTitle := 'ImageJ Tiff Open as Generic';
end else
if MovFType = BIORAD_PIC then TemFTitle := 'BioRad' else
if MovFType = ZEISS_CZI_LSM_MOV then Begin
if (ExtractFileExt(ImFname) = '.lsm') then TemFTitle := 'Zeiss "LSM"'
else
if (ExtractFileExt(ImFname) = '.czi') then TemFTitle := 'Zeiss "CZI"';
end
else
if MovFType = NORAN_SGI_MOV then TemFTitle := 'Noran SGI';
lbCurFileInfo.Caption := TemFTitle + ' / ' +
IntToStr(imXsize) + ' x ' + IntToStr(imYsize) + ' pixels';
{Initializes Windows for PixSettings}
If (MovFType <> NORAN_SGI_MOV) and ((MovFType <> QED_MOV)) then Begin //NORAN_SGI_MOV does Not Have Entry in PixSettings Record
if (MovFType in [ANDOR_MOV, NIKON_ND2_MOV,NIKON_TIFF_MOV]) then begin
if (PixSettings.ImageBinning > 0) then
lbBinning.Caption := 'Binning (as recorded in file) = ' +
IntToStr(PixSettings.ImageBinning) +'x' + IntToStr(PixSettings.ImageBinning)
else
lbBinning.Caption := 'Binning not recorded in file';
end else
if Not(MovFType in [ANDOR_MOV, NIKON_ND2_MOV,NIKON_TIFF_MOV]) then lbBinning.Caption := '';
if (PixSettings.FileHasOwnPixSize = True) then begin
if Not(PixSettings.UseOptionPixSize[MovFType]) then begin
lbMicronsPix.Caption := 'File Info: 1 pixel = ' + FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / not adjusted'
end
else
If(PixSettings.UseOptionPixSize[MovFType]) then Begin
if (MovFType = ANDOR_MOV) then begin
if (PixSettings.ImageBinning > 0) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF((100*PixSettings.ImageBinning)/PixSettings.PixPer100Micr[ANDOR_MOV],ffFixed,6,6) + ' µm'
else
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(100/PixSettings.PixPer100Micr[ANDOR_MOV],ffFixed,6,6) + ' µm'
end
else
if (MovFType in[NIKON_ND2_MOV,NIKON_TIFF_MOV]) then begin
if (PixSettings.ImageBinning > 0) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF((100*PixSettings.ImageBinning)/PixSettings.PixPer100Micr[NIKON_ND2_MOV],ffFixed,6,6) + ' µm'
else
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(100/PixSettings.PixPer100Micr[NIKON_ND2_MOV],ffFixed,6,6) + ' µm'
end
else
if (MovFType = SINGLE_BW_TIFF) and (TIFFfileType = TIFF_ImageJ) and (ChBoxTIFF.Checked) then begin
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm'
end;
End; //if(PixSettings.UseOptionPixSize[MovFType]) then begin
lbPixPer100Microns.Caption := '100 µm = ' + IntToStr(Round(100/PixSettings.FilePixSize)) + ' pixels';
end
else
begin
lbMicronsPix.Caption := 'File Has No Information on Pixel Size';
lbPixPer100Microns.Caption := 'Pixel Size adjusted to: ' +
FloatToStrF(100/PixSettings.PixPer100Micr[MovFType],ffFixed,6,6) + ' µm/pixel';
end;
End Else
If (MovFType = NORAN_SGI_MOV) then Begin //NORAN_SGI_MOV does Not Have Entry in PixSettings Record
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm';
lbBinning.Caption := 'Noran SGI type file does not have adjustment option';
lbPixPer100Microns.Caption := '';
End;
if MovFType = ANDOR_MOV then CbAndorTiffs.Color := $00FFFFBB else
if MovFType = SINGLE_BW_TIFF then ChBoxTIFF.Color := $00FFFFBB else
if MovFType = STACK_BW_TIFF then ChBoxTiffStack.Color := $00FFFFBB else
if MovFType = BIORAD_PIC then ChBoxBioRad.Color := $00FFFFBB else
if MovFType = NORAN_PRARIE_MOV then ChBoxNoranPrairie.Color:= $00FFFFBB else
if MovFType = StreamPix_Mov then CbStreamPix.Color := $00FFFFBB else
if MovFType in[NIKON_ND2_MOV,NIKON_TIFF_MOV] then ChBoxNikonND2orTiff.Color := $00FFFFBB else
if MovFType = ZEISS_CZI_LSM_MOV then ChBoxZeiss.Color := $00FFFFBB;
End else Begin
lbCurFileInfo.Caption := '';
lbBinning.Caption := '';
lbMicronsPix.Caption := ' No File Open';
lbPixPer100Microns.Caption := '';
End;
// Nikon ND2 Movies . Nikon TIFF Movies take the values of Nikon ND2 Movies
ChBoxNikonND2orTiff.Checked := PixSettings.UseOptionPixSize[NIKON_ND2_MOV];
NikonEdPix.NumberOne := PixSettings.PixPer100Micr[NIKON_ND2_MOV];
//Noran Prarie
//The paragraph below will be enabled when Noran Prarie inroduces Pixes Size in Files
{ChBoxNoranPrairie.Checked := PixSettings.UseOptionPixSize[NORAN_PRARIE_MOV]; }
NoranPrairieEdPix.NumberOne := PixSettings.PixPer100Micr[NORAN_PRARIE_MOV];
//StreamPix
//The paragraph below will be enabled when StreamPix inroduces Pixes Size in Files
{CbStreamPix.Checked := PixSettings.UseOptionPixSize[StreamPix_MOV];}
StreamPixEdPix.NumberOne := PixSettings.PixPer100Micr[StreamPix_MOV];
//ANDOR_MOV
//The paragraph below will be enabled when Andor inroduces Pixes Size in Files
CbAndorTiffs.Checked := PixSettings.UseOptionPixSize[ANDOR_MOV];
AndorEdPix.NumberOne := PixSettings.PixPer100Micr[ANDOR_MOV];
//Tiff Stack of Generic Tiffs
ChBoxTiffStack.Checked := PixSettings.UseOptionPixSize[STACK_BW_TIFF];
StackGenTiffEdPix.NumberOne := PixSettings.PixPer100Micr[STACK_BW_TIFF];
StackTiffFrmSec.NumberFloat := PixSettings.FramesPerSec[0];
//Any Single TIFF
ChBoxTIFF.Checked := PixSettings.UseOptionPixSize[SINGLE_BW_TIFF];
SingleGenTiffEdPix.NumberOne := PixSettings.PixPer100Micr[SINGLE_BW_TIFF];
SingleGenTiffFrmSec.NumberFloat := PixSettings.FramesPerSec[1];
//BioRad
ChBoxBioRad.Checked := PixSettings.UseOptionPixSize[BIORAD_PIC];
BioRadEdPix.NumberOne := PixSettings.PixPer100Micr[BIORAD_PIC];
//Zeiss LSM
ChBoxZeiss.Checked := PixSettings.UseOptionPixSize[ZEISS_CZI_LSM_MOV];
ZeissLSMEdPix.NumberOne := PixSettings.PixPer100Micr[ZEISS_CZI_LSM_MOV];
{if MovFType = NORAN_SGI_MOV des not have checkbox}
{--------End - Initializes Pixel/Micron Setting Page --- }
enGridDensity.NumberOne := WindowGrid.NrNodes;
cbUseMoviFilePath.Checked := UseMoviFilePath;
cbAlignXofImagePlayback.Checked := AlignfrmPlayback;
{fills Bitmaps for Button Color Change}
SetButImages;
ROIcolChange := False;
PixSetChange := False;
OptionsPagesDlg.ShowModal;
{for this to Work OptionsPagesDlg Visible sold be Set to False at Design Time}
End;
procedure TOptionsPagesDlg.OKBtnClick(Sender: TObject);
Begin
{0 = No Smoothing, 1 = Boxcar; 2 = Median, 3 = Box & Median;}
{first Set Button and Font Settings}
If (MainImLoaded = True) and (NrIm > 1) then Begin
If ROIcolChange = True then Begin
If (LastState = 2) Then Begin {if Somethin in BackUp}
if LastType in[1,3] then ButCol[LastCol] := ButColBack[LastCol] else
if LastType = 2 then FntCol[LastCol] := FntColBack[LastCol];
End;
SetFinalColorSettings;
End;
If (AvImSmoothChange) and (RatioOn = True) and (SmoothMode in [1,3]) Then Begin
Screen.Cursor := crHourGlass;
if (AutoSearchPar.SmoothBeforeDoRatio) then SmoothAverIm(AvImRaw,AvIm);
DoBkgonAvIm; {Subtracts Bkg from AvIm Only}
DoRatio(DO_COPY);
UpdateMainImage(True);
Screen.Cursor := crDefault; ShowMessage('here 2');
end; {(AvImSmoothChange) and (RatioOn = True) and (SmoothMode in [1,3])}
If (ROIvar.NrROI > 0) or (High(MarkSmEvCoor[CurIm]) >= 0) or
(High(MarkBigEvCoor[CurIm]) >= 0) or (ChangeInMarks) or
(ROIcolChange) or (MesLineChange) then Begin
{Main Window}
if (AvImSmoothChange = False) then UpdateMainImage(True);
{now Average Image}
if (frmAverIm <> nil) and (AvImExists > 0) Then Begin
UpdateAverImage(True);
end; { if (frmAverIm <> nil) and (AvImExists > 0) Then Begin}
{end with Average Image}
if (LSSettingChange) then if (LineScanExist) then begin
frmLineScan.SetTimeBar;
frmLineScan.UpdateLSwindows(REFRESH_ONLY);
end;
End;
if (NrChannels > 1) and (frmMergeWin <> nil) then DisplayMergeImage;
if (NrChannels > 1) and (frm2ndWin <> nil) then Display2ndChannel;
If ROIcolChange = True then ChangePlotSet := True;
If (ChangePlotSet = True) and (TimeSerAnalDone = True) Then Begin
frmTimeSerPlot.RePlot(Sender);
End; {If (ChangePlotSet = True) and (TimeSerAnalDone = True)}
End; {If (MainImLoaded = True) and (NrIm > 1)then Begin}
If (PixSetChange) Then Begin
frmImageControl.Select.Down := True;
frmImageControl.Select.Click;
End;
OptionsPagesDlg.Close;
End;
{*************************************************************}
procedure TOptionsPagesDlg.trbROIthicknessChange(Sender: TObject);
begin
If trbROIthickness.Tag <> trbROIthickness.Position Then Begin
trbROIthickness.Tag := trbROIthickness.Position;
ShapeROI.Pen.Width := trbROIthickness.Position;
ROIvar.TckNess := trbROIthickness.Position;
ROIvar.Ticker := trbThickerROI.Position*ROIvar.TckNess;
ShapeROIthicker.Pen.Width := ROIvar.Ticker;
ROIrct.LT := (ROIvar.TckNess div 2) + (ROIvar.TckNess mod 2);
ROIrct.RB := (ROIvar.TckNess div 2) + 1 + 1;
{the formula to draw a rectangle with different thickness
and keeping interior the same is:
L := Xl - canvas.Pen.Width div 2 - canvas.Pen.Width mod 2;
R := Xr + canvas.Pen.Width div 2 + 1 + 1;
T := Yup - canvas.Pen.Width div 2 - canvas.Pen.Width mod 2;
B := Yd + canvas.Pen.Width div 2 + 1 + 1; }
End;
End;
procedure TOptionsPagesDlg.trbThickerROIChange(Sender: TObject);
begin
If trbThickerROI.Tag <> trbThickerROI.Position Then Begin
trbThickerROI.Tag := trbThickerROI.Position;
ROIvar.Ticker := trbThickerROI.Position*ROIvar.TckNess;
ShapeROIthicker.Pen.Width := ROIvar.Ticker;
ROIrct.tLT := (ROIvar.Ticker div 2) + (ROIvar.Ticker mod 2);
ROIrct.tRB := (ROIvar.Ticker div 2) + 1 + 1;
End;
End;
procedure TOptionsPagesDlg.trbFreeHandThicknessChange(Sender: TObject);
begin
If trbFreeHandThickness.Tag <> trbFreeHandThickness.Position Then Begin
trbFreeHandThickness.Tag := trbFreeHandThickness.Position;
ShapeFreeHand.Pen.Width := trbFreeHandThickness.Position;
ROIvar.FhTickness := trbFreeHandThickness.Position;
End;
End;
procedure TOptionsPagesDlg.CheckBoxUseSameFontColClick(Sender: TObject);
begin
ROIvar.UseMonoFontCol := CheckBoxUseSameFontCol.Checked;
end;
procedure TOptionsPagesDlg.ShapeFontColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
If ColorDialogROI.Execute Then Begin
ShapeFontColor.Brush.Color := ColorDialogROI.Color;
ROIvar.MonoFontCol := ColorDialogROI.Color;
End;
end;
procedure TOptionsPagesDlg.CheckBoxEnableROINumbersClick(Sender: TObject);
begin
ROIvar.UseROINr := CheckBoxEnableROINumbers.Checked;
end;
procedure TOptionsPagesDlg.trbMarkWithChange(Sender: TObject);
begin
If trbMarkWith.Tag <> trbMarkWith.Position Then Begin
trbMarkWith.Tag := trbMarkWith.Position;
MarkPar.Thick := trbMarkWith.Position;
DrawMark;
End;
end;
procedure TOptionsPagesDlg.trbMarkSizeChange(Sender: TObject);
begin
If trbMarkSize.Tag <> trbMarkSize.Position Then Begin
trbMarkSize.Tag := trbMarkSize.Position;
MarkPar.Size := trbMarkSize.Position;
DrawMark;
End;
end;
Procedure TOptionsPagesDlg.DrawMark;
Var Xb,Xe,Yb,Ye : integer;
Begin
With OptionsPagesDlg Do Begin
imgMarkBkg.Canvas.Brush.Color := RGB(255,255,255);
imgMarkBkg.Canvas.FillRect(Rect(0,0,40,40));
imgMarkBkg.Canvas.Pen.Color := RGB(0,0,0);
imgMarkBkg.Canvas.Pen.Width := trbMarkWith.Position;
Xb := 20 - trbMarkSize.Position;
Yb := Xb;
Xe := 20 + trbMarkSize.Position;
Ye := Xe;
{Horiz}
imgMarkBkg.Canvas.MoveTo(Xb,20);
imgMarkBkg.Canvas.LineTo(Xe,20);
{Vert}
imgMarkBkg.Canvas.MoveTo(20,Yb);
imgMarkBkg.Canvas.LineTo(20,Ye)
End;
{----}
End;
procedure TOptionsPagesDlg.shSmEventMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if ColorDialogROI.Execute then Begin
MarkPar.SmallEventColor := ColorDialogROI.Color;
shSmEvent.Brush.Color := MarkPar.SmallEventColor;
End;
End;
procedure TOptionsPagesDlg.shBigEventMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if ColorDialogROI.Execute then Begin
MarkPar.BigEventColor := ColorDialogROI.Color;
shBigEvent.Brush.Color := MarkPar.BigEventColor;
End;
end;
procedure TOptionsPagesDlg.DisplaySmallMarksClick(Sender: TObject);
begin
MarkPar.DisplaySmEvents := DisplaySmallMarks.Checked;
ChangeInMarks := True;
end;
procedure TOptionsPagesDlg.DisplayBigMarksClick(Sender: TObject);
begin
MarkPar.DisplayBigEvents := DisplayBigMarks.Checked;
ChangeInMarks := True;
end;
procedure TOptionsPagesDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
OptionsPagesDlg := nil;
end;
procedure TOptionsPagesDlg.ShowSmMarksOnAverWinClick(Sender: TObject);
begin
MarkPar.ShowSmEvOnAverWin := ShowSmMarksOnAverWin.Checked;
ChangeInMarks := True;
end;
procedure TOptionsPagesDlg.ShowBigMarksOnAverWinClick(Sender: TObject);
begin
MarkPar.ShowBigEvOnAverWin := ShowBigMarksOnAverWin.Checked;
ChangeInMarks := True;
end;
procedure TOptionsPagesDlg.enGridDensityReturnPressed(Sender: TObject);
begin
WindowGrid.NrNodes := enGridDensity.NumberOne;
end;
procedure TOptionsPagesDlg.EnableROIonAverWinClick(Sender: TObject);
begin
ROIvar.ROIonAverWin := EnableROIonAverWin.Checked;
ChangeInMarks := True;
end;
procedure TOptionsPagesDlg.ReplotAverImage;
begin
CopyAvImToDisplBuffer;
If frmAverIm <> nil then Begin
UpdateAverImage(True);
End;
End;
procedure TOptionsPagesDlg.trbSymbSizeChange(Sender: TObject);
begin
If trbSymbSize.Tag <> trbSymbSize.Position Then Begin
trbSymbSize.Tag := trbSymbSize.Position;
lblSymbSize.Caption := IntToStr(2*trbSymbSize.Position + 1) + ' pix';;
shSymbSize.Width := 2*trbSymbSize.Position + 1;
shSymbSize.Height := 2*trbSymbSize.Position + 1;
shSymbSize.Top := 69 + 2 - trbSymbSize.Position;
shSymbSize.Left := 260 + 2 - trbSymbSize.Position;
TimPltSlid.SymbSize := trbSymbSize.Position;
ChangePlotSet := True;
End;
end;
procedure TOptionsPagesDlg.shSymbSizeMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
If ColorDialogROI.Execute Then Begin
shSymbSize.Pen.Color := ColorDialogROI.Color;
shSymbSize.Brush.Color := ColorDialogROI.Color;
TimPltSlid.SymbFromTableCol := ColorDialogROI.Color;
ChangePlotSet := True;
End;
end;
procedure TOptionsPagesDlg.AlwaysUseSymbClick(Sender: TObject);
begin
TimPltSlid.AlwaysUseSymb := AlwaysUseSymb.Checked;
ChangePlotSet := True;
end;
procedure TOptionsPagesDlg.PromptForCommentClick(Sender: TObject);
begin
MarkPar.PromptForComment := PromptForComment.Checked;
end;
procedure TOptionsPagesDlg.GenGenSetCommClick(Sender: TObject);
begin
MarkPar.GenGenSetComm := GenGenSetComm.Checked;
end;
procedure TOptionsPagesDlg.GenAutoSearchCommClick(Sender: TObject);
begin
MarkPar.GenAutoSearchComm := GenAutoSearchComm.Checked;
end;
procedure TOptionsPagesDlg.trbMesLineThicknessChange(Sender: TObject);
begin
If trbMesLineThickness.Tag <> trbMesLineThickness.Position Then Begin
trbMesLineThickness.Tag := trbMesLineThickness.Position;
MesLineVar.Thickness := trbMesLineThickness.Position;
if (MesLineVar.Thickness = 1) then
MesLine.SelTol := 3 else
MesLine.SelTol := MesLineVar.Thickness + 1;
MesLineThickness.Height := MesLineVar.Thickness;
MesLineThickness.Top := 54 - MesLineVar.Thickness div 2;
MesLineChange := True;
End;
End;
procedure TOptionsPagesDlg.enLineCapsWidthReturnPressed(Sender: TObject);
begin
if (enLineCapsWidth.NumberOne mod 2 = 0) and (enLineCapsWidth.NumberOne <> 0) then
enLineCapsWidth.NumberOne := enLineCapsWidth.NumberOne + 1;
if (enLineCapsWidth.NumberOne = 1) then enLineCapsWidth.NumberOne := 0;
MesLineVar.CapsWitdh := enLineCapsWidth.NumberOne div 2;
end;
procedure TOptionsPagesDlg.MesLineColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
If (ColorDialogROI.Execute) Then Begin
if (MesLineVar.Color <> ColorDialogROI.Color) then begin
MesLineVar.Color := ColorDialogROI.Color;
MesLineColor.Brush.Color := ColorDialogROI.Color;
MesLineThickness.Brush.Color := ColorDialogROI.Color;
MesLineThickness.Pen.Color := ColorDialogROI.Color;
MesLineChange := True;
end;
End;
End;
procedure TOptionsPagesDlg.trbLSTimeBarThicknessChange(Sender: TObject);
begin
If trbLSTimeBarThickness.Tag <> trbLSTimeBarThickness.Position Then Begin
trbLSTimeBarThickness.Tag := trbLSTimeBarThickness.Position;
LSTimeBarPar.Thickness := trbLSTimeBarThickness.Position;
LSTimeBarThickness.Height := LSTimeBarPar.Thickness;
LSTimeBarThickness.Top := 157 - LSTimeBarPar.Thickness div 2;
LSSettingChange := True;
SizeBar.YT := SizeBar.YB - LSTimeBarPar.Thickness;
End;
end;
procedure TOptionsPagesDlg.LSTimeBarColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
If (ColorDialogROI.Execute) Then Begin
if (LSTimeBarPar.Color <> ColorDialogROI.Color) then begin
LSTimeBarPar.Color := ColorDialogROI.Color;
LSTimeBarColor.Brush.Color := ColorDialogROI.Color;
LSTimeBarThickness.Brush.Color := ColorDialogROI.Color;
LSTimeBarThickness.Pen.Color := ColorDialogROI.Color;
LSSettingChange := True;
end;
End;
end;
procedure TOptionsPagesDlg.cbLSTimeBarVisibleClick(Sender: TObject);
begin
LSTimeBarPar.Visible := cbLSTimeBarVisible.Checked;
LSSettingChange := True;
end;
procedure TOptionsPagesDlg.enLSTimeBarDurationReturnPressed(Sender: TObject);
begin
LSTimeBarPar.Duration := enLSTimeBarDuration.NumberFloat;
LSSettingChange := True;
end;
procedure TOptionsPagesDlg.enSizeBarLenghtINµmReturnPressed(Sender: TObject);
begin
ExportDial.SizeBarLenghtINµm := enSizeBarLenghtINµm.NumberOne;
if (MainImLoaded) then SizeBar.XL := SizeBar.XR - round(ExportDial.SizeBarLenghtINµm/PixSize);
end;
procedure TOptionsPagesDlg.ckbKeepOldROIClick(Sender: TObject);
begin
ROIvar.KeepOldROI := ckbKeepOldROI.Checked;
end;
procedure TOptionsPagesDlg.MaxGammaChange(Sender: TObject);
begin
If ImageContrVar.MaxGamma <> 50*MaxGamma.Position Then Begin
frmImageControl.trbGamma.Max := 50*MaxGamma.Position;
frmImageControl.enGamma.Max := 5*MaxGamma.Position;
ImageContrVar.MaxGamma := frmImageControl.trbGamma.Max;
lbMaxGamma.Caption := IntToStr(5*MaxGamma.Position);
End;
End;
procedure TOptionsPagesDlg.MaxRatioChange(Sender: TObject);
var DrawY : Boolean;
begin
If MaxRatio.Tag <> MaxRatio.Position Then Begin
MaxRatio.Tag := MaxRatio.Position;
if MaxRatio.Position = -1 then TimPltSlid.YmaxRatOn := 10 else
if MaxRatio.Position = 0 then TimPltSlid.YmaxRatOn := 30 else
TimPltSlid.YmaxRatOn := MaxRatio.Position*50;
lbMaxRatio.Caption := IntToStr(TimPltSlid.YmaxRatOn div 10);
frmImageControl.trbMaxRatio.Max := TimPltSlid.YmaxRatOn*10;
If (PLOTvar.AnalType in[RATIO_TIME,Ch_div_Ch_RATIO_TIME,Ca_CONC_TIME]) Then Begin
with frmTimeSerPlot do begin
if dsYaxes.PosTo > TimPltSlid.YmaxRatOn then begin
DrawY := True;
dsYaxes.PosTo := TimPltSlid.YmaxRatOn;
end else DrawY := False;
enYtop.Max := TimPltSlid.YmaxRatOn/10;
dsYaxes.Max := TimPltSlid.YmaxRatOn;
dsYaxesChange(sender);
if (DrawY = True) then frmTimeSerPlot.RePlot(Sender);
end; { with frmTimeSerPlot}
End; {PLOTvar.RatOn = True}
End; {If MaxRatio.Tag <> MaxRatio.Position Then Begin}
End;
procedure TOptionsPagesDlg.btCorrectTimeClick(Sender: TObject);
Var Cnt : Integer;
MinDelt,MaxDelt,TemExt : Extended;
begin
{Checks if Time is O.K. if not corrects it}
{I verified that the precision of Time in sec is the Same as in NanoSec}
MinDelt := 1.18E4932; {Extended ranges from 3.37 x 10-4932 to 1.18 x 104932}
MaxDelt := 0;
For Cnt := 0 to High(TimeSt) - 1 do begin
TemExt := TimeSt[Cnt+1] - TimeSt[Cnt];
if TemExt > 0 then Begin
if MinDelt > TemExt then MinDelt := TemExt;
if MaxDelt < TemExt then MaxDelt := TemExt;
end;
End;
If (MaxDelt - MinDelt) > MinDelt/10 then Begin
MessageDlg('Time will be Replaced by the Minimum Image Time Offset of: '
+ FloatToStrF(MinDelt,ffFixed,20,12) + ' s',mtInformation,[mbOK],0);
TemExt := 0;
For Cnt := 0 to High(TimeSt) do begin
TimeSt[Cnt] := TemExt;
TemExt := TemExt + MinDelt;
End;
End;
frmPlayback.lbImageNr.Caption := 'im ' + IntToStr(CurIm + 1) +
' / ' + (FloatToStrF(TimeSt[CurIm],ffFixed,5,3) + ' s');
{----------- End of Check and Correction}
End; {procedure TOptionsPagesDlg.btCorrectTimeClick}
{*************** From Here Button Color Change ********************}
Procedure TOptionsPagesDlg.ChangeButCol(const Img : TImage);
var ButNr : AnsiString;
Xt,Yt : integer;
Begin
If ListBoxColor.ItemIndex = 0 Then Begin {Button or Frame Color}
ColorDialogROI.Color := ButCol[Img.Tag];
If ColorDialogROI.Execute then Begin
ButCol[Img.Tag] := ColorDialogROI.Color;
ColUnDo.Enabled := True;
ColReDo.Enabled := False;
ROIcolChange := True;
{Makes Working and BackUp Arrays the Same for the Previous Item}
If (LastType > 0) then Begin
If LastType in[1,3] then Begin
if LastState = 1 Then ButColBack[LastCol] := ButCol[LastCol] else
if LastState = 2 Then ButCol[LastCol] := ButColBack[LastCol];
End Else
If LastType = 2 then Begin
if LastState = 1 Then FntColBack[LastCol] := FntCol[LastCol] else
if LastState = 2 Then FntCol[LastCol] := FntCol[LastCol];
End;
End;
LastCol := Img.Tag; {last Color [ROI or Font}
LastType := 1;
LastState := 1;
With Img Do Begin
Canvas.Font.Name := 'Arial Narrow';
Canvas.Font.Pitch := fpVariable;
Canvas.Font.Size := 9;
Canvas.Brush.Color := ButCol[Img.Tag];
Canvas.Pen.Color := Canvas.Brush.Color;
Canvas.FillRect(Canvas.ClipRect);
Canvas.Brush.Style := bsClear; {to make transparent text}
ButNr := IntToStr(Img.Tag);
Xt := Width div 2 - Canvas.TextWidth(ButNr) div 2;
Yt := Height div 2 - Canvas.TextHeight(ButNr) div 2;
Canvas.Font.Color := FntCol[Img.Tag];
Canvas.TextOut(Xt,Yt,ButNr);
End; {with}
End;
End Else
If ListBoxColor.ItemIndex = 1 Then Begin {Button Font Color}
ColorDialogROI.Color := FntCol[Img.Tag];
If ColorDialogROI.Execute then Begin
FntCol[Img.Tag] := ColorDialogROI.Color;
ColUnDo.Enabled := True;
ColReDo.Enabled := False;
{Makes Working and BackUp Arrays the Same for the Previous Item}
If (LastType > 0) then Begin
If LastType in[1,3] then Begin
if LastState = 1 Then ButColBack[LastCol] := ButCol[LastCol] else
if LastState = 2 Then ButCol[LastCol] := ButColBack[LastCol];
End Else
If LastType = 2 then Begin
if LastState = 1 Then FntColBack[LastCol] := FntCol[LastCol] else
if LastState = 2 Then FntCol[LastCol] := FntCol[LastCol];
End;
End;
LastCol := Img.Tag; {last Color [ROI or Font}
LastType := 2;
LastState := 1;
With Img Do Begin
Canvas.Font.Name := 'Arial Narrow';
Canvas.Font.Pitch := fpVariable;
Canvas.Font.Size := 9;
Canvas.Brush.Style := bsClear; {to make transparent text}
ButNr := IntToStr(Img.Tag);
Xt := Width div 2 - Canvas.TextWidth(ButNr) div 2;
Yt := Height div 2 - Canvas.TextHeight(ButNr) div 2;
Canvas.Font.Color := FntCol[Img.Tag];
Canvas.TextOut(Xt,Yt,ButNr);
End;
End;
End;
End;
procedure TOptionsPagesDlg.Im1Click(Sender: TObject);
begin
ChangeButCol(Im1);
end;
procedure TOptionsPagesDlg.Im2Click(Sender: TObject);
begin
ChangeButCol(Im2);
end;
procedure TOptionsPagesDlg.Im3Click(Sender: TObject);
begin
ChangeButCol(Im3);
end;
procedure TOptionsPagesDlg.Im4Click(Sender: TObject);
begin
ChangeButCol(Im4);
end;
procedure TOptionsPagesDlg.Im5Click(Sender: TObject);
begin
ChangeButCol(Im5);
end;
procedure TOptionsPagesDlg.Im6Click(Sender: TObject);
begin
ChangeButCol(Im6);
end;
procedure TOptionsPagesDlg.Im7Click(Sender: TObject);
begin
ChangeButCol(Im7);
end;
procedure TOptionsPagesDlg.Im8Click(Sender: TObject);
begin
ChangeButCol(Im8);
end;
procedure TOptionsPagesDlg.Im9Click(Sender: TObject);
begin
ChangeButCol(Im9);
end;
procedure TOptionsPagesDlg.Im10Click(Sender: TObject);
begin
ChangeButCol(Im10);
end;
procedure TOptionsPagesDlg.Im11Click(Sender: TObject);
begin
ChangeButCol(Im11);
end;
procedure TOptionsPagesDlg.Im12Click(Sender: TObject);
begin
ChangeButCol(Im12);
end;
procedure TOptionsPagesDlg.Im13Click(Sender: TObject);
begin
ChangeButCol(Im13);
end;
procedure TOptionsPagesDlg.Im14Click(Sender: TObject);
begin
ChangeButCol(Im14);
end;
procedure TOptionsPagesDlg.Im15Click(Sender: TObject);
begin
ChangeButCol(Im15);
end;
procedure TOptionsPagesDlg.Im16Click(Sender: TObject);
begin
ChangeButCol(Im16);
end;
procedure TOptionsPagesDlg.Im17Click(Sender: TObject);
begin
ChangeButCol(Im17);
end;
procedure TOptionsPagesDlg.Im18Click(Sender: TObject);
begin
ChangeButCol(Im18);
end;
procedure TOptionsPagesDlg.Im19Click(Sender: TObject);
begin
ChangeButCol(Im19);
end;
procedure TOptionsPagesDlg.Im20Click(Sender: TObject);
begin
ChangeButCol(Im20);
end;
procedure TOptionsPagesDlg.ShapeSelFrameMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
ColorDialogROI.Color := SelFrameColor;
If ColorDialogROI.Execute then Begin
SelFrameColor := ColorDialogROI.Color;
ShapeSelFrame.Pen.Color := SelFrameColor;
End;
end;
Procedure TOptionsPagesDlg.RestoreColSettings(const Img : TImage);
var Xt,Yt : integer;
ButNr : AnsiString;
Begin
With Img Do Begin
Canvas.Font.Name := 'Arial Narrow';
Canvas.Font.Pitch := fpVariable;
Canvas.Font.Size := 9;
If LastType = 1 Then Begin
if LastState = 1 then
Canvas.Brush.Color := ButCol[Img.Tag] else
if LastState = 2 then
Canvas.Brush.Color := ButColBack[Img.Tag];
Canvas.Pen.Color := Canvas.Brush.Color;
Canvas.FillRect(Canvas.ClipRect);
Canvas.Brush.Style := bsClear; {to make transparent text}
ButNr := IntToStr(Img.Tag);
Xt := Width div 2 - Canvas.TextWidth(ButNr) div 2;
Yt := Height div 2 - Canvas.TextHeight(ButNr) div 2;
Canvas.Font.Color := FntCol[Img.Tag];
Canvas.TextOut(Xt,Yt,ButNr);
End Else
If LastType = 2 Then Begin
Canvas.Brush.Style := bsClear; {to make transparent text}
ButNr := IntToStr(Img.Tag);
Xt := Width div 2 - Canvas.TextWidth(ButNr) div 2;
Yt := Height div 2 - Canvas.TextHeight(ButNr) div 2;
if LastState = 1 then
Canvas.Font.Color := FntCol[Img.Tag] else
if LastState = 2 then
Canvas.Font.Color := FntColBack[Img.Tag];
Canvas.TextOut(Xt,Yt,ButNr);
End;
End; {with}
End;
Procedure TOptionsPagesDlg.GetImNrAndDoReset;
Begin
if LastCol = 1 then RestoreColSettings(Im1) else
if LastCol = 2 then RestoreColSettings(Im2) else
if LastCol = 3 then RestoreColSettings(Im3) else
if LastCol = 4 then RestoreColSettings(Im4) else
if LastCol = 5 then RestoreColSettings(Im5) else
if LastCol = 6 then RestoreColSettings(Im6) else
if LastCol = 7 then RestoreColSettings(Im7) else
if LastCol = 8 then RestoreColSettings(Im8) else
if LastCol = 9 then RestoreColSettings(Im9) else
if LastCol = 10 then RestoreColSettings(Im10) else
if LastCol = 11 then RestoreColSettings(Im11) else
if LastCol = 12 then RestoreColSettings(Im12) else
if LastCol = 13 then RestoreColSettings(Im13) else
if LastCol = 14 then RestoreColSettings(Im14) else
if LastCol = 15 then RestoreColSettings(Im15) else
if LastCol = 16 then RestoreColSettings(Im16) else
if LastCol = 17 then RestoreColSettings(Im17) else
if LastCol = 18 then RestoreColSettings(Im18) else
if LastCol = 19 then RestoreColSettings(Im19) else
if LastCol = 20 then RestoreColSettings(Im20);
End;
Procedure TOptionsPagesDlg.ColUnDoClick(Sender: TObject);
begin
ColReDo.Enabled := ColUnDo.Enabled;
ColUnDo.Enabled := False;
ROIcolChange := True;
LastState := 2;
If LastType = 3 then Begin
ShapeSelFrame.Pen.Color := SelFrameColorBack;
LastType := 3;
End Else
If (LastType in [1,2]) then GetImNrAndDoReset;
End;
procedure TOptionsPagesDlg.ColReDoClick(Sender: TObject);
begin
ColUnDo.Enabled := ColReDo.Enabled;
ColReDo.Enabled := False;
ROIcolChange := True;
LastState := 1;
If LastType = 3 then Begin
ShapeSelFrame.Pen.Color := SelFrameColor;
LastType := 3;
End Else
If (LastType in [1,2]) then GetImNrAndDoReset;
End;
Procedure TOptionsPagesDlg.SetButImages;
var i,Xt,Yt : integer;
ButBMP : TBitmap;
ButNr : AnsiString;
Begin
ButBMP := TBitmap.Create;
ButBMP.Width := 16;
ButBMP.Height := 16;
ButBMP.PixelFormat := pf24bit;
ButBMP.Canvas.Font.Name := 'Arial Narrow';
ButBMP.Canvas.Font.Pitch := fpVariable;
ButBMP.Canvas.Font.Size := 9;
For i := 1 to 20 Do Begin
ButBMP.Canvas.Brush.Color := ButCol[i];
ButBMP.Canvas.Pen.Color := ButBMP.Canvas.Brush.Color;
ButBMP.Canvas.FillRect(ButBMP.Canvas.ClipRect);
ButBMP.Canvas.Brush.Style := bsClear; {to make transparent text}
ButNr := IntToStr(i);
Xt := ButBMP.Width div 2 - ButBMP.Canvas.TextWidth(ButNr) div 2;
Yt := ButBMP.Height div 2 - ButBMP.Canvas.TextHeight(ButNr) div 2;
ButBMP.Canvas.Font.Color := FntCol[i];
ButBMP.Canvas.TextOut(Xt,Yt,ButNr);
if i = 1 then Im1.Picture.Bitmap.Assign(ButBMP) else
if i = 2 then Im2.Picture.Bitmap.Assign(ButBMP) else
if i = 3 then Im3.Picture.Bitmap.Assign(ButBMP) else
if i = 4 then Im4.Picture.Bitmap.Assign(ButBMP) else
if i = 5 then Im5.Picture.Bitmap.Assign(ButBMP) else
if i = 6 then Im6.Picture.Bitmap.Assign(ButBMP) else
if i = 7 then Im7.Picture.Bitmap.Assign(ButBMP) else
if i = 8 then Im8.Picture.Bitmap.Assign(ButBMP) else
if i = 9 then Im9.Picture.Bitmap.Assign(ButBMP) else
if i = 10 then Im10.Picture.Bitmap.Assign(ButBMP) else
if i = 11 then Im11.Picture.Bitmap.Assign(ButBMP) else
if i = 12 then Im12.Picture.Bitmap.Assign(ButBMP) else
if i = 13 then Im13.Picture.Bitmap.Assign(ButBMP) else
if i = 14 then Im14.Picture.Bitmap.Assign(ButBMP) else
if i = 15 then Im15.Picture.Bitmap.Assign(ButBMP) else
if i = 16 then Im16.Picture.Bitmap.Assign(ButBMP) else
if i = 17 then Im17.Picture.Bitmap.Assign(ButBMP) else
if i = 18 then Im18.Picture.Bitmap.Assign(ButBMP) else
if i = 19 then Im19.Picture.Bitmap.Assign(ButBMP) else
if i = 20 then Im20.Picture.Bitmap.Assign(ButBMP);
End;
FreeAndNil(ButBMP);
ShapeSelFrame.Pen.Color := SelFrameColor;
LastCol := 0;
LastType := 0;
LastState := 0;
ListBoxColor.ItemIndex := 0; {sets Highlight to First Choice}
End;
procedure TOptionsPagesDlg.ResToOriginalClick(Sender: TObject);
begin
ResetCode := 1;
Yes.Caption := 'Reset to Original (Build In) Colors';
PopUpMenuYesNo.Popup(Mouse.CursorPos.X,Mouse.CursorPos.Y);
end;
procedure TOptionsPagesDlg.YesClick(Sender: TObject);
begin
if ResetCode = 1 then ResToBuildIn else
if ResetCode = 2 then ResetToBeg;
end;
Procedure TOptionsPagesDlg.ResToBuildIn;
Begin
{Resets to Build In Colors}
ROIcolChange := True;
SetBuildInROIcolors(ButCol,FntCol);
SetBuildInROIcolors(ButColBack,FntColBack);
SetButImages;
ColReDo.Enabled := False;
ColUnDo.Enabled := False;
End;
procedure TOptionsPagesDlg.ResetToBeg;
var i : integer;
Begin
{resets to Current = before Cahnge Settings}
for i := 1 to 21 do ButCol[i] := ROIvar.ROICol[i];
for i := 1 to 20 do FntCol[i] := ROIvar.FontCol[i];
for i := 1 to 21 do ButColBack[i] := ROIvar.ROICol[i];
for i := 1 to 20 do FntColBack[i] := ROIvar.FontCol[i];
SetButImages;
ColReDo.Enabled := False;
ColUnDo.Enabled := False;
ROIcolChange := False;
End;
procedure TOptionsPagesDlg.ResetToInitialClick(Sender: TObject);
begin
ResetCode := 2;
Yes.Caption := 'Reset All to the Initial Colors';
PopUpMenuYesNo.Popup(Mouse.CursorPos.X,Mouse.CursorPos.Y);
end;
Procedure TOptionsPagesDlg.SetFinalColorSettings;
var i : integer;
FirstTime : Boolean;
Begin
for i := 1 to 21 do ROIvar.ROICol[i] := ButCol[i];
for i := 1 to 20 do ROIvar.FontCol[i] := FntCol[i];
FirstTime := False;
frmTimeSerPlot.SetButtons(FirstTime);
End;
procedure TOptionsPagesDlg.AllowFullPathOfLastFileClick(Sender: TObject);
begin
AllowFullPath := AllowFullPathOfLastFile.Checked;
end;
{----------- Microns per Pixel Setting Start from Here ------------------------}
procedure TOptionsPagesDlg.ChBoxNikonND2orTiffClick(Sender: TObject);
begin
PixSettings.UseOptionPixSize[NIKON_ND2_MOV] := ChBoxNikonND2orTiff.Checked;
If MovFType in [NIKON_ND2_MOV,NIKON_TIFF_MOV] Then Begin
PixSetChange := True;
if (PixSettings.UseOptionPixSize[NIKON_ND2_MOV] = True) then begin
if PixSettings.ImageBinning > 0 then
PixSize := (100*PixSettings.ImageBinning)/PixSettings.PixPer100Micr[NIKON_ND2_MOV] else
PixSize := 100/PixSettings.PixPer100Micr[NIKON_ND2_MOV];
if (MainImLoaded) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' + FloatToStrF(PixSize,ffFixed,6,6) + ' µm'
end else
if (PixSettings.UseOptionPixSize[NIKON_ND2_MOV] = False) then begin
PixSize := PixSettings.FilePixSize;
if (MainImLoaded) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' + FloatToStrF(PixSize,ffFixed,6,6) + ' µm / not adjusted';
end;
End;
End;
procedure TOptionsPagesDlg.ChBoxNoranPrairieClick(Sender: TObject);
begin
{Keeps it Always Checked}
ChBoxNoranPrairie.Checked := True;
{Since NoranPrairie Files do Not Have Written Own Pixel Sizes This
paragraph is Disabled}
End;
procedure TOptionsPagesDlg.CbStreamPixClick(Sender: TObject);
begin
{Keeps it Always Checked}
CbStreamPix.Checked := True;
{Since StreamPix Files do Not Have Written Own Pixel Sizes This
paragraph is Disabled}
end;
procedure TOptionsPagesDlg.CbAndorTiffsClick(Sender: TObject);
begin
PixSettings.UseOptionPixSize[ANDOR_MOV] := CbAndorTiffs.Checked;
If MovFType = ANDOR_MOV Then Begin
PixSetChange := True;
if (PixSettings.UseOptionPixSize[ANDOR_MOV] = True) then begin
if PixSettings.ImageBinning > 0 then
PixSize := (100*PixSettings.ImageBinning)/PixSettings.PixPer100Micr[ANDOR_MOV] else
PixSize := 100/PixSettings.PixPer100Micr[ANDOR_MOV];
if (MainImLoaded) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm'
end else
if (PixSettings.UseOptionPixSize[ANDOR_MOV] = False) then begin
PixSize := PixSettings.FilePixSize;
if (MainImLoaded) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' + FloatToStrF(PixSize,ffFixed,6,6) + ' µm / not adjusted';
end;
End;
end;
procedure TOptionsPagesDlg.ChBoxTiffStackClick(Sender: TObject);
begin
if MovFType = STACK_BW_TIFF then if Not(PixSettings.FileHasOwnPixSize)
then ChBoxTiffStack.Checked := True;
PixSettings.UseOptionPixSize[STACK_BW_TIFF] := ChBoxTiffStack.Checked;
If MovFType = STACK_BW_TIFF Then Begin
PixSetChange := True;
if (PixSettings.UseOptionPixSize[STACK_BW_TIFF] = True) then
PixSize := 100/(PixSettings.PixPer100Micr[STACK_BW_TIFF]) else
if (PixSettings.UseOptionPixSize[STACK_BW_TIFF] = False) then
PixSize := PixSettings.FilePixSize;
if (MainImLoaded) then begin
if (PixSettings.FileHasOwnPixSize) then begin
if (PixSettings.UseOptionPixSize[STACK_BW_TIFF]) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm' else
if Not(PixSettings.UseOptionPixSize[STACK_BW_TIFF]) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' + FloatToStrF(PixSize,ffFixed,6,6) + ' µm / not adjusted';
end else
if Not(PixSettings.FileHasOwnPixSize) then
lbPixPer100Microns.Caption := 'Pixel Size adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm/pixel';
end;
End;
end;
procedure TOptionsPagesDlg.ChBoxZeissClick(Sender: TObject);
begin
PixSettings.UseOptionPixSize[ZEISS_CZI_LSM_MOV] := ChBoxZeiss.Checked;
If (MovFType = ZEISS_CZI_LSM_MOV) Then Begin
PixSetChange := True;
if (PixSettings.UseOptionPixSize[ZEISS_CZI_LSM_MOV] = True) then begin
PixSize := 100/PixSettings.PixPer100Micr[ZEISS_CZI_LSM_MOV];
if (MainImLoaded) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm'
end else
if (PixSettings.UseOptionPixSize[ZEISS_CZI_LSM_MOV] = False) then begin
PixSize := PixSettings.FilePixSize;
if (MainImLoaded) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' + FloatToStrF(PixSize,ffFixed,6,6) + ' µm / not adjusted';
end;
End;
end;
procedure TOptionsPagesDlg.ChBoxTIFFClick(Sender: TObject);
begin
if (MovFType = SINGLE_BW_TIFF) then if Not(PixSettings.FileHasOwnPixSize)
then ChBoxTIFF.Checked := True;
PixSettings.UseOptionPixSize[SINGLE_BW_TIFF] := ChBoxTIFF.Checked;
If MovFType = SINGLE_BW_TIFF Then Begin
PixSetChange := True;
if (PixSettings.UseOptionPixSize[SINGLE_BW_TIFF] = True) then
PixSize := 100/(PixSettings.PixPer100Micr[SINGLE_BW_TIFF]) else
if (PixSettings.UseOptionPixSize[SINGLE_BW_TIFF] = False) then
PixSize := PixSettings.FilePixSize;
if (MainImLoaded) then begin
if (PixSettings.FileHasOwnPixSize) then begin
if (PixSettings.UseOptionPixSize[SINGLE_BW_TIFF]) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm' else
if Not(PixSettings.UseOptionPixSize[SINGLE_BW_TIFF]) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' + FloatToStrF(PixSize,ffFixed,6,6) + ' µm / not adjusted';
end else
if Not(PixSettings.FileHasOwnPixSize) then
lbPixPer100Microns.Caption := 'Pixel Size adjusted to: ' + FloatToStrF(PixSize,ffFixed,6,6) + ' µm/pixel';
end;
End;
end;
procedure TOptionsPagesDlg.ChBoxBioRadClick(Sender: TObject);
begin
PixSettings.UseOptionPixSize[BIORAD_PIC] := ChBoxBioRad.Checked;
If MovFType = BIORAD_PIC Then Begin
PixSetChange := True;
if (PixSettings.UseOptionPixSize[BIORAD_PIC] = True) then begin
PixSize := 100/PixSettings.PixPer100Micr[BIORAD_PIC];
if (MainImLoaded) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm'
end else
if (PixSettings.UseOptionPixSize[BIORAD_PIC] = False) then begin
PixSize := PixSettings.FilePixSize;
if (MainImLoaded) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' + FloatToStrF(PixSize,ffFixed,6,6) + ' µm / not adjusted';
end;
End;
End;
procedure TOptionsPagesDlg.NikonEdPixReturnPressed(Sender: TObject);
begin
PixSettings.PixPer100Micr[NIKON_ND2_MOV] := NikonEdPix.NumberOne;
if (MovFType in[NIKON_ND2_MOV,NIKON_TIFF_MOV]) and (PixSettings.UseOptionPixSize[NIKON_ND2_MOV] = True) then begin
PixSetChange := True;
if PixSettings.ImageBinning > 0 then
PixSize := (100*PixSettings.ImageBinning)/PixSettings.PixPer100Micr[NIKON_ND2_MOV] else
PixSize := 100/PixSettings.PixPer100Micr[NIKON_ND2_MOV];
if (MainImLoaded) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm'
end;
end;
//------ end with QED cameras
procedure TOptionsPagesDlg.NoranPrairieEdPixReturnPressed(Sender: TObject);
begin
PixSettings.PixPer100Micr[NORAN_PRARIE_MOV] := NoranPrairieEdPix.NumberOne;
if (MovFType = NORAN_PRARIE_MOV) and (PixSettings.UseOptionPixSize[NORAN_PRARIE_MOV] = True) then begin
PixSetChange := True;
PixSize := 100/PixSettings.PixPer100Micr[NORAN_PRARIE_MOV];
if (MainImLoaded) then
lbPixPer100Microns.Caption := 'Pixel Size adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm/pixel';
end;
end;
procedure TOptionsPagesDlg.StreamPixEdPixReturnPressed(Sender: TObject);
begin
PixSettings.PixPer100Micr[StreamPix_Mov] := StreamPixEdPix.NumberOne;
if (MovFType = StreamPix_Mov) and (PixSettings.UseOptionPixSize[StreamPix_Mov] = True) then begin
PixSetChange := True;
PixSize := 100/PixSettings.PixPer100Micr[StreamPix_Mov];
if (MainImLoaded) then
lbPixPer100Microns.Caption := 'Pixel Size adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm/pixel';
end;
end;
procedure TOptionsPagesDlg.AndorEdPixReturnPressed(Sender: TObject);
begin
PixSettings.PixPer100Micr[ANDOR_MOV] := AndorEdPix.NumberOne;
if (MovFType = ANDOR_MOV) and (PixSettings.UseOptionPixSize[ANDOR_MOV] = True) then begin
PixSetChange := True;
if PixSettings.ImageBinning > 0 then
PixSize := (100*PixSettings.ImageBinning)/PixSettings.PixPer100Micr[ANDOR_MOV] else
PixSize := 100/PixSettings.PixPer100Micr[ANDOR_MOV];
if (MainImLoaded) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm'
end;
end;
procedure TOptionsPagesDlg.StackGenTiffEdPixReturnPressed(Sender: TObject);
begin
PixSettings.PixPer100Micr[STACK_BW_TIFF] := StackGenTiffEdPix.NumberOne;
if (MovFType = STACK_BW_TIFF)and(PixSettings.UseOptionPixSize[STACK_BW_TIFF] = True) then begin
PixSetChange := True;
PixSize := 100/PixSettings.PixPer100Micr[STACK_BW_TIFF];
if (MainImLoaded) then begin
if (PixSettings.FileHasOwnPixSize) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm' else
if Not(PixSettings.FileHasOwnPixSize) then
lbPixPer100Microns.Caption := 'Pixel Size adjusted to: ' +
FloatToStrF(100/PixSettings.PixPer100Micr[MovFType],ffFixed,6,6) + ' µm/pixel';
end;
end;
end;
procedure TOptionsPagesDlg.SingleGenTiffEdPixReturnPressed(Sender: TObject);
begin
PixSettings.PixPer100Micr[SINGLE_BW_TIFF] := SingleGenTiffEdPix.NumberOne;
if (MovFType = SINGLE_BW_TIFF) and (PixSettings.UseOptionPixSize[SINGLE_BW_TIFF] = True) then begin
PixSetChange := True;
PixSize := 100/PixSettings.PixPer100Micr[SINGLE_BW_TIFF];
if (MainImLoaded) then begin
if (PixSettings.FileHasOwnPixSize) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm' else
if Not(PixSettings.FileHasOwnPixSize) then
lbPixPer100Microns.Caption := 'Pixel Size adjusted to: ' +
FloatToStrF(100/PixSettings.PixPer100Micr[MovFType],ffFixed,6,6) + ' µm/pixel';
end;
end;
end;
procedure TOptionsPagesDlg.BioRadEdPixReturnPressed(Sender: TObject);
begin
PixSettings.PixPer100Micr[BIORAD_PIC] := BioRadEdPix.NumberOne;
if (MovFType = BIORAD_PIC) and (PixSettings.UseOptionPixSize[BIORAD_PIC] = True) then begin
PixSetChange := True;
PixSize := 100/PixSettings.PixPer100Micr[BIORAD_PIC];
if (MainImLoaded) then begin
if (PixSettings.FileHasOwnPixSize) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm' else
if Not(PixSettings.FileHasOwnPixSize) then
lbPixPer100Microns.Caption := 'Pixel Size adjusted to: ' +
FloatToStrF(100/PixSettings.PixPer100Micr[MovFType],ffFixed,6,6) + ' µm/pixel';
end;
end;
end;
procedure TOptionsPagesDlg.ZeissLSMEdPixReturnPressed(Sender: TObject);
begin
PixSettings.PixPer100Micr[ZEISS_CZI_LSM_MOV] := ZeissLSMEdPix.NumberOne;
if (MovFType = ZEISS_CZI_LSM_MOV) and (PixSettings.UseOptionPixSize[ZEISS_CZI_LSM_MOV] = True) then begin
PixSetChange := True;
PixSize := 100/PixSettings.PixPer100Micr[ZEISS_CZI_LSM_MOV];
if (MainImLoaded) then begin
if (PixSettings.FileHasOwnPixSize) then
lbMicronsPix.Caption := 'File Info: 1 pixel = ' +
FloatToStrF(PixSettings.FilePixSize,ffFixed,6,6) + ' µm / adjusted to: ' +
FloatToStrF(PixSize,ffFixed,6,6) + ' µm' else
if Not(PixSettings.FileHasOwnPixSize) then
lbPixPer100Microns.Caption := 'Pixel Size adjusted to: ' +
FloatToStrF(100/PixSettings.PixPer100Micr[ZEISS_CZI_LSM_MOV],ffFixed,6,6) + ' µm/pixel';
end;
end;
end;
procedure TOptionsPagesDlg.StackTiffFrmSecReturnPressed(Sender: TObject);
{var Cnt : Integer;
TemDouble,ImageTime : Double;}
begin
PixSettings.FramesPerSec[0] := StackTiffFrmSec.NumberFloat;
End;
procedure TOptionsPagesDlg.SingleGenTiffFrmSecReturnPressed(Sender: TObject);
begin
PixSettings.FramesPerSec[1] := SingleGenTiffFrmSec.NumberFloat;
end;
{--------------- End of Pixel Settings -----------------}
procedure TOptionsPagesDlg.cbUseMoviFilePathClick(Sender: TObject);
begin
UseMoviFilePath := cbUseMoviFilePath.Checked;
end;
procedure TOptionsPagesDlg.cbAlignXofImagePlaybackClick(Sender: TObject);
begin
AlignfrmPlayback := cbAlignXofImagePlayback.Checked;
end;
procedure TOptionsPagesDlg.ChbCheckAllFilesExistClick(Sender: TObject);
begin
CheckAllFilesExist := ChbCheckAllFilesExist.Checked;
{for QED & Stack of TIFF files}
end;
procedure TOptionsPagesDlg.ChBLoadTimeStampsClick(Sender: TObject);
begin
LoadStreamPixAndND2TimeSt := ChBLoadTimeStamps.Checked;
end;
END.
|
unit BinTree;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TItem = integer; // тип информационного поля
TTree =^ TNode;
TNode = record
Data: TItem;
Left: TTree;
Right: TTree;
end;
procedure makeTree(var Work: TTree; x: TItem); // создание нового узла
procedure InsertTree(Work: TTree; x: TItem); // добовление нового узла в дерево
procedure DeleteTree(var Work: TTree; x: TItem);
procedure Preorder(Work: TTree; var str: String); // обход дерева
procedure Inorder(Work: TTree; var str: String); // обход дерева
procedure Order(Work: TTree; var str: String); // обход дерева
function MinTree(Work: TTree): TTree; // нахождение минимального узла в дереве
function MaxTree(Work: TTree): TTree; // нахождение максимального узла в дереве
procedure FindInTree(Work: TTree; x: TItem; var f: boolean; var Work1: TTree);
procedure DepthTree(Work: TTree; sum: Cardinal; var max: Cardinal);
implementation
// функция возвращает ИСТИНУ если дерево пустое, и ЛОЖЬ в противном случае
function EmptyTree(Work: TTree): boolean;
begin
if Work=nil then
Result:=true
else
Result:=false;
end;
// процедура создания нового узла
procedure makeTree(var Work: TTree; x: TItem);
begin
New(Work);
Work^.Data:=x;
Work^.Left:=nil;
Work^.Right:=nil;
end;
// процедура добовления нового узла
procedure InsertTree(Work: TTree; x: TItem);
var Work1: TTree;
begin
// проверка, не пустое ли дерево
if EmptyTree(Work) then
begin
ShowMessage('Дерево пустое!!!');
exit;
end;
while Work<>nil do // нахождение место вставки нового узла
begin
Work1:=Work; // запаминаем предыдущий узел
if x<Work^.Data then
Work:=Work^.Left
else
Work:=Work^.Right;
end;
Work:=Work1;
makeTree(Work1,x); // создаем новый узел
if x<Work^.Data then // проверко в какое поддерево нужно вставить новый узел
Work^.Left:=Work1
else
Work^.Right:=Work1;
end;
// процедура обхода дерева
procedure preorder(Work: TTree; var str: string);
begin
if Work<>nil then
begin
str:=str+IntToStr(Work^.Data)+' ';
preorder(Work^.Left,str);
preorder(Work^.Right,str);
end;
end;
// процедура обхода дерева
procedure inorder(Work: TTree; var str: string);
begin
if Work<>nil then
begin
inorder(Work^.Left,str);
str:=str+IntToStr(Work^.Data)+' ';
inorder(Work^.Right,str);
end;
end;
// процедура обхода дерева
procedure order(Work: TTree; var str: string);
begin
if Work<>nil then
begin
order(Work^.Left,str);
order(Work^.Right,str);
str:=str+IntToStr(Work^.Data)+' ';
end;
end;
// функция нахождения минимума в дереве
function MinTree(Work: TTree): TTree;
begin
// проверка, не пустое ли дерево
if EmptyTree(Work) then
begin
ShowMessage('Дерево пустое!!!');
exit;
end;
while Work^.Left<>nil do
Work:=Work^.Left;
Result:=Work;
end;
// функция нахождения максимума в дереве
function MaxTree(Work: TTree): TTree;
begin
// проверка, не пустое ли дерево
if EmptyTree(Work) then
begin
ShowMessage('Дерево пустое!!!');
exit;
end;
while Work^.Right<>nil do
Work:=Work^.Right;
Result:=Work;
end;
procedure FindInTree(Work: TTree; x: TItem; var f: boolean; var Work1: TTree);
begin
// проверка, не пустое ли дерево
if EmptyTree(Work) then
begin
ShowMessage('Дерево пустое!!!');
exit;
end;
f:=false; // предполагаем, что искомого элемента нет в дереве
while Work<>nil do
begin
if Work^.Data=x then
begin
Work1:=Work; // возвращаем ссылку на найденный элемент
f:=true;
break;
end
else
begin
if x<Work^.Data then
Work:=Work^.Left
else
Work:=Work^.Right;
end;
end;
end;
// функция нахождения глубины дерева
procedure DepthTree(Work: TTree; sum: Cardinal; var max: Cardinal);
begin
if Work<>nil then
begin
inc(sum);
DepthTree(Work^.Left,sum,max);
DepthTree(Work^.Right,sum,max);
end
else
if sum>max then
max:=sum;
end;
// процедура удаления узла из дерева
procedure DeleteTree(var Work: TTree; x: TItem);
var Work1: TTree;
begin
if Work=nil then
ShowMessage('Удоляемого элемента в дереве нет')
else
begin
if x<Work^.Data then
DeleteTree(Work^.Left,x)
else
if x>Work^.Data then
DeleteTree(Work^.Right,x)
else
if Work^.Left=nil then
begin
Work1:=Work;
Work:=Work1^.Right;
Dispose(Work1);
end
else
if Work^.Right=nil then
begin
Work1:=Work;
Work:=Work^.Left;
Dispose(Work1);
end
else
begin
Work1:=MinTree(Work^.Right);
Work^.Data:=Work1^.Data;
DeleteTree(Work^.Right,Work^.Data);
end;
end;
end;
end.
|
//
// Created by the DataSnap proxy generator.
// 09/06/2018 17:49:38
//
unit uCC;
interface
uses
System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON,
Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr,
Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect;
type
TSMClient = class(TDSAdminClient)
private
FGetDataCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function GetData: TDataSet;
end;
implementation
function TSMClient.GetData: TDataSet;
begin
if FGetDataCommand = nil then
begin
FGetDataCommand := FDBXConnection.CreateCommand;
FGetDataCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGetDataCommand.Text := 'TSM.GetData';
FGetDataCommand.Prepare;
end;
FGetDataCommand.ExecuteUpdate;
Result := TCustomSQLDataSet.Create(nil, FGetDataCommand.Parameters[0].Value.GetDBXReader
(False), True);
Result.Open;
if FInstanceOwner then
FGetDataCommand.FreeOnExecute(Result);
end;
constructor TSMClient.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
constructor TSMClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TSMClient.Destroy;
begin
FGetDataCommand.DisposeOf;
inherited;
end;
end.
|
{******************************************************************************}
{ }
{ SVG Shell Extensions: Shell extensions for SVG files }
{ (Preview Panel, Thumbnail Icon, SVG Editor) }
{ }
{ Copyright (c) 2021 (Ethea S.r.l.) }
{ Author: Carlo Barazzetta }
{ }
{ https://github.com/EtheaDev/SVGShellExtensions }
{ }
{******************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{ The Original Code is: }
{ Delphi Preview Handler https://github.com/RRUZ/delphi-preview-handler }
{ }
{ The Initial Developer of the Original Code is Rodrigo Ruz V. }
{ Portions created by Rodrigo Ruz V. are Copyright 2011-2021 Rodrigo Ruz V. }
{ All Rights Reserved. }
{******************************************************************************}
unit SVGEditor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, SynEdit, pngimage,
System.Generics.Collections,
SynEditHighlighter,
ComCtrls, ToolWin, ImgList, SynHighlighterXML,
Vcl.Menus, SynEditExport,
SynExportHTML, SynExportRTF, SynEditRegexSearch, SynEditMiscClasses,
SynEditSearch, uSVGSettings, System.ImageList, SynEditCodeFolding,
SVGIconImageList, SVGIconImageListBase, SVGIconImage;
type
TFrmEditor = class(TForm)
SynEdit: TSynEdit;
PanelTop: TPanel;
PanelEditor: TPanel;
SynXMLSyn: TSynXMLSyn;
StatusBar: TStatusBar;
SynEditSearch: TSynEditSearch;
SynEditRegexSearch: TSynEditRegexSearch;
SVGIconImageList: TSVGIconImageList;
ToolButtonZoomIn: TToolButton;
ToolButtonZommOut: TToolButton;
ToolButtonSearch: TToolButton;
ToolBar: TToolBar;
ToolButtonFont: TToolButton;
ToolButtonAbout: TToolButton;
SeparatorEditor: TToolButton;
ToolButtonShowText: TToolButton;
ToolButtonReformat: TToolButton;
FontDialog: TFontDialog;
SynXMLSynDark: TSynXMLSyn;
ImagePanel: TPanel;
SVGIconImage: TSVGIconImage;
Splitter: TSplitter;
procedure FormCreate(Sender: TObject);
procedure ToolButtonZoomInClick(Sender: TObject);
procedure ToolButtonZommOutClick(Sender: TObject);
procedure ToolButtonFontClick(Sender: TObject);
procedure ToolButtonAboutClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ToolButtonSearchClick(Sender: TObject);
procedure ToolButtonSelectModeClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure ToolButtonShowTextClick(Sender: TObject);
procedure ToolButtonReformatClick(Sender: TObject);
procedure ToolButtonMouseEnter(Sender: TObject);
procedure ToolButtonMouseLeave(Sender: TObject);
procedure SplitterMoved(Sender: TObject);
procedure FormAfterMonitorDpiChanged(Sender: TObject; OldDPI,
NewDPI: Integer);
private
FFontSize: Integer;
FSimpleText: string;
FFileName: string;
fSearchFromCaret: boolean;
FSettings: TSettings;
class var FExtensions: TDictionary<TSynCustomHighlighterClass, TStrings>;
class var FAParent: TWinControl;
procedure AppException(Sender: TObject; E: Exception);
procedure ShowSearchDialog;
procedure DoSearchText(ABackwards: boolean);
procedure UpdateGUI;
procedure UpdateFromSettings;
procedure SaveSettings;
function GetEditorFontSize: Integer;
procedure SetEditorFontSize(const Value: Integer);
procedure UpdateHighlighter;
protected
public
procedure ScaleControls(const ANewPPI: Integer);
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class property Extensions: TDictionary<TSynCustomHighlighterClass, TStrings> read FExtensions write FExtensions;
class property AParent: TWinControl read FAParent write FAParent;
procedure LoadFromFile(const AFileName: string);
procedure LoadFromStream(const AStream: TStream);
property EditorFontSize: Integer read GetEditorFontSize write SetEditorFontSize;
end;
implementation
uses
SynEditTypes,
Vcl.Clipbrd,
Vcl.Themes,
uLogExcept,
System.Types,
Registry,
uMisc,
IOUtils,
ShellAPI,
ComObj,
IniFiles,
GraphUtil,
uAbout,
Xml.XMLDoc,
dlgSearchText;
const
MaxfontSize = 30;
MinfontSize = 8;
{$R *.dfm}
{ TFrmEditor }
procedure TFrmEditor.AppException(Sender: TObject; E: Exception);
begin
// log unhandled exceptions (TSynEdit, etc)
TLogPreview.Add('AppException');
TLogPreview.Add(E);
end;
constructor TFrmEditor.Create(AOwner: TComponent);
begin
FSettings := TSettings.Create;
inherited;
end;
destructor TFrmEditor.Destroy;
begin
FreeAndNil(FSettings);
inherited;
end;
procedure TFrmEditor.DoSearchText(ABackwards: boolean);
var
Options: TSynSearchOptions;
begin
StatusBar.SimpleText := '';
Options := [];
if ABackwards then
Include(Options, ssoBackwards);
if gbSearchCaseSensitive then
Include(Options, ssoMatchCase);
if not fSearchFromCaret then
Include(Options, ssoEntireScope);
if gbSearchSelectionOnly then
Include(Options, ssoSelectedOnly);
if gbSearchWholeWords then
Include(Options, ssoWholeWord);
if gbSearchRegex then
SynEdit.SearchEngine := SynEditRegexSearch
else
SynEdit.SearchEngine := SynEditSearch;
if SynEdit.SearchReplace(gsSearchText, gsReplaceText, Options) = 0 then
begin
MessageBeep(MB_ICONASTERISK);
StatusBar.SimpleText := STextNotFound;
if ssoBackwards in Options then
SynEdit.BlockEnd := SynEdit.BlockBegin
else
SynEdit.BlockBegin := SynEdit.BlockEnd;
SynEdit.CaretXY := SynEdit.BlockBegin;
end;
end;
procedure TFrmEditor.UpdateGUI;
begin
if PanelEditor.Visible then
begin
Splitter.Top := PanelEditor.Top + PanelEditor.Height;
Splitter.Visible := True;
ToolButtonShowText.Caption := 'Hide Text';
ToolButtonShowText.Hint := 'Hide content of SVG file';
ToolButtonShowText.ImageName := 'hide-text';
end
else
begin
Splitter.Visible := False;
ToolButtonShowText.Caption := 'Show Text';
ToolButtonShowText.Hint := 'Show content of SVG file';
ToolButtonShowText.ImageName := 'show-text';
end;
ToolButtonShowText.Visible := True;
ToolButtonAbout.Visible := True;
ToolButtonFont.Visible := PanelEditor.Visible;
ToolButtonReformat.Visible := PanelEditor.Visible;
ToolButtonSearch.Visible := PanelEditor.Visible;
ToolButtonZoomIn.Visible := PanelEditor.Visible;
ToolButtonZommOut.Visible := PanelEditor.Visible;
end;
procedure TFrmEditor.UpdateHighlighter;
var
LBackgroundColor: TColor;
begin
if FSettings.UseDarkStyle then
begin
SynEdit.Highlighter := SynXMLSynDark;
end
else
begin
SynEdit. Highlighter := SynXMLSyn;
end;
SynEdit.Gutter.Font.Color := StyleServices.GetSystemColor(clWindowText);
SynEdit.Gutter.Color := StyleServices.GetSystemColor(clBtnFace);
LBackgroundColor := StyleServices.GetSystemColor(clWindow);
SynXMLSynDark.ElementAttri.Background := LBackgroundColor;
SynXMLSynDark.AttributeAttri.Background := LBackgroundColor;
SynXMLSynDark.NamespaceAttributeAttri.Background := LBackgroundColor;
SynXMLSynDark.AttributeValueAttri.Background := LBackgroundColor;
SynXMLSynDark.NamespaceAttributeValueAttri.Background := LBackgroundColor;
SynXMLSynDark.TextAttri.Background := LBackgroundColor;
SynXMLSynDark.CDATAAttri.Background := LBackgroundColor;
SynXMLSynDark.EntityRefAttri.Background := LBackgroundColor;
SynXMLSynDark.ProcessingInstructionAttri.Background := LBackgroundColor;
SynXMLSynDark.CommentAttri.Background := LBackgroundColor;
SynXMLSynDark.DocTypeAttri.Background := LBackgroundColor;
SynXMLSynDark.SpaceAttri.Background := LBackgroundColor;
SynXMLSynDark.SymbolAttri.Background := LBackgroundColor;
end;
procedure TFrmEditor.FormAfterMonitorDpiChanged(Sender: TObject; OldDPI,
NewDPI: Integer);
begin
TLogPreview.Add('TFrmEditor.FormAfterMonitorDpiChanged: '+
'- Old: '+OldDPI.ToString+' - New: '+NewDPI.ToString);
end;
procedure TFrmEditor.FormCreate(Sender: TObject);
begin
TLogPreview.Add('TFrmEditor.FormCreate');
Application.OnException := AppException;
FSimpleText := StatusBar.SimpleText;
UpdateFromSettings;
UpdateHighlighter;
end;
procedure TFrmEditor.FormDestroy(Sender: TObject);
begin
SaveSettings;
TLogPreview.Add('TFrmEditor.FormDestroy');
inherited;
end;
procedure TFrmEditor.FormResize(Sender: TObject);
begin
PanelEditor.Height := Round(Self.Height * (FSettings.SplitterPos / 100));
Splitter.Top := PanelEditor.Height;
if Self.Width < (550 * Self.ScaleFactor) then
ToolBar.ShowCaptions := False
else
Toolbar.ShowCaptions := True;
UpdateGUI;
end;
function TFrmEditor.GetEditorFontSize: Integer;
begin
Result := FFontSize;
end;
procedure TFrmEditor.LoadFromFile(const AFileName: string);
begin
TLogPreview.Add('TFrmEditor.LoadFromFile Init');
FFileName := AFileName;
SynEdit.Lines.LoadFromFile(FFileName);
SVGIconImage.SVGText := SynEdit.Lines.Text;
TLogPreview.Add('TFrmEditor.LoadFromFile Done');
end;
procedure TFrmEditor.LoadFromStream(const AStream: TStream);
var
LStringStream: TStringStream;
begin
TLogPreview.Add('TFrmEditor.LoadFromStream Init');
AStream.Position := 0;
LStringStream := TStringStream.Create;
try
LStringStream.LoadFromStream(AStream);
SynEdit.Lines.Text := LStringStream.DataString;
SVGIconImage.SVGText := LStringStream.DataString;
finally
LStringStream.Free;
end;
TLogPreview.Add('TFrmEditor.LoadFromStream Done');
end;
procedure TFrmEditor.SaveSettings;
begin
if Assigned(FSettings) then
begin
FSettings.UpdateSettings(SynEdit.Font.Name,
EditorFontSize,
PanelEditor.Visible);
FSettings.WriteSettings;
end;
end;
procedure TFrmEditor.ScaleControls(const ANewPPI: Integer);
var
LCurrentPPI: Integer;
LScaleFactor: Integer;
begin
LCurrentPPI := FCurrentPPI;
if ANewPPI <> LCurrentPPI then
SVGIconImageList.Size := MulDiv(SVGIconImageList.Size, ANewPPI, LCurrentPPI);
end;
procedure TFrmEditor.SetEditorFontSize(const Value: Integer);
var
LScaleFactor: Single;
begin
if (Value >= MinfontSize) and (Value <= MaxfontSize) then
begin
TLogPreview.Add('TFrmEditor.SetEditorFontSize'+
' CurrentPPI: '+Self.CurrentPPI.ToString+
' ScaleFactor: '+ScaleFactor.ToString+
' Value: '+Value.ToString);
if FFontSize <> 0 then
LScaleFactor := SynEdit.Font.Size / FFontSize
else
LScaleFactor := 1;
FFontSize := Value;
SynEdit.Font.Size := Round(FFontSize * LScaleFactor);
SynEdit.Gutter.Font.Size := SynEdit.Font.Size;
end;
end;
procedure TFrmEditor.ShowSearchDialog;
var
LTextSearchDialog: TTextSearchDialog;
LRect: TRect;
i: integer;
begin
for i := 0 to Screen.FormCount - 1 do
if Screen.Forms[i].ClassType = TTextSearchDialog then
begin
Screen.Forms[i].BringToFront;
exit;
end;
StatusBar.SimpleText := '';
LTextSearchDialog := TTextSearchDialog.Create(Self);
try
LTextSearchDialog.SearchBackwards := gbSearchBackwards;
LTextSearchDialog.SearchCaseSensitive := gbSearchCaseSensitive;
LTextSearchDialog.SearchFromCursor := gbSearchFromCaret;
LTextSearchDialog.SearchInSelectionOnly := gbSearchSelectionOnly;
LTextSearchDialog.SearchText := gsSearchText;
if gbSearchTextAtCaret then
begin
if SynEdit.SelAvail and (SynEdit.BlockBegin.Line = SynEdit.BlockEnd.Line) then
LTextSearchDialog.SearchText := SynEdit.SelText
else
LTextSearchDialog.SearchText := SynEdit.GetWordAtRowCol(SynEdit.CaretXY);
end;
LTextSearchDialog.SearchTextHistory := gsSearchTextHistory;
LTextSearchDialog.SearchWholeWords := gbSearchWholeWords;
if Self.Parent <> nil then
begin
GetWindowRect(Self.Parent.ParentWindow, LRect);
LTextSearchDialog.Left := (LRect.Left + LRect.Right - LTextSearchDialog.Width) div 2;
LTextSearchDialog.Top := (LRect.Top + LRect.Bottom - LTextSearchDialog.Height) div 2;
end;
if LTextSearchDialog.ShowModal() = mrOK then
begin
gbSearchBackwards := LTextSearchDialog.SearchBackwards;
gbSearchCaseSensitive := LTextSearchDialog.SearchCaseSensitive;
gbSearchFromCaret := LTextSearchDialog.SearchFromCursor;
gbSearchSelectionOnly := LTextSearchDialog.SearchInSelectionOnly;
gbSearchWholeWords := LTextSearchDialog.SearchWholeWords;
gbSearchRegex := LTextSearchDialog.SearchRegularExpression;
gsSearchText := LTextSearchDialog.SearchText;
gsSearchTextHistory := LTextSearchDialog.SearchTextHistory;
fSearchFromCaret := gbSearchFromCaret;
if gsSearchText <> '' then
begin
DoSearchText(gbSearchBackwards);
fSearchFromCaret := True;
end;
end;
finally
LTextSearchDialog.Free;
end;
end;
procedure TFrmEditor.SplitterMoved(Sender: TObject);
begin
FSettings.SplitterPos := splitter.Top * 100 div
(Self.Height - Toolbar.Height);
SaveSettings;
end;
procedure TFrmEditor.ToolButtonShowTextClick(Sender: TObject);
begin
PanelEditor.Visible := not PanelEditor.Visible;
UpdateGUI;
SaveSettings;
end;
procedure TFrmEditor.ToolButtonAboutClick(Sender: TObject);
var
LFrm: TFrmAbout;
LRect: TRect;
i: integer;
begin
for i := 0 to Screen.FormCount - 1 do
if Screen.Forms[i].ClassType = TFrmAbout then
begin
Screen.Forms[i].BringToFront;
exit;
end;
LFrm := TFrmAbout.Create(nil);
try
if Self.Parent <> nil then
begin
GetWindowRect(Self.Parent.ParentWindow, LRect);
LFrm.Left := (LRect.Left + LRect.Right - LFrm.Width) div 2;
LFrm.Top := (LRect.Top + LRect.Bottom - LFrm.Height) div 2;
end;
LFrm.ShowModal();
finally
LFrm.Free;
end;
end;
procedure TFrmEditor.ToolButtonMouseEnter(Sender: TObject);
begin
StatusBar.SimpleText := (Sender as TToolButton).Hint;
end;
procedure TFrmEditor.ToolButtonMouseLeave(Sender: TObject);
begin
StatusBar.SimpleText := FSimpleText;
end;
procedure TFrmEditor.ToolButtonReformatClick(Sender: TObject);
begin
SynEdit.Lines.Text := Xml.XMLDoc.FormatXMLData(SynEdit.Lines.Text);
end;
procedure TFrmEditor.UpdateFromSettings;
begin
FSettings.ReadSettings;
if FSettings.FontSize >= MinfontSize then
EditorFontSize := FSettings.FontSize
else
EditorFontSize := MinfontSize;
SynEdit.Font.Name := FSettings.FontName;
PanelEditor.Visible := FSettings.ShowEditor;
UpdateGUI;
end;
procedure TFrmEditor.ToolButtonFontClick(Sender: TObject);
begin
FontDialog.Font.Assign(SynEdit.Font);
FontDialog.Font.Size := EditorFontSize;
if FontDialog.Execute then
begin
FSettings.FontName := FontDialog.Font.Name;
FSettings.FontSize := FontDialog.Font.Size;
FSettings.WriteSettings;
UpdateFromSettings;
end;
end;
procedure TFrmEditor.ToolButtonSearchClick(Sender: TObject);
begin
ShowSearchDialog();
end;
procedure TFrmEditor.ToolButtonSelectModeClick(Sender: TObject);
begin
TToolButton(Sender).CheckMenuDropdown;
end;
procedure TFrmEditor.ToolButtonZommOutClick(Sender: TObject);
begin
EditorFontSize := EditorFontSize - 1;
SaveSettings;
end;
procedure TFrmEditor.ToolButtonZoomInClick(Sender: TObject);
begin
EditorFontSize := EditorFontSize + 1;
SaveSettings;
end;
end.
|
unit InfraValueTypeEvent;
{$I InfraTypes.Inc}
interface
uses
InfraValueTypeIntf, InfraNotify;
type
TInfraChangedEvent = class(TInfraEvent, IInfraChangedEvent);
TInfraAddItemEvent = class(TInfraEvent, IInfraAddItemEvent)
private
FItemIndex: Integer;
FNewItem: IInfraType;
protected
function GetItemIndex: Integer;
function GetNewItem: IInfraType;
procedure SetItemIndex(Value: Integer);
property ItemIndex: Integer read GetItemIndex write SetItemIndex;
property NewItem: IInfraType read GetNewItem;
public
constructor Create(const Src: IInfraType; const NewItem: IInfraType;
ItemIndex: Integer);
end;
TInfraClearListEvent = class(TInfraEvent, IInfraClearListEvent);
TInfraRemoveItemEvent = class(TInfraEvent, IInfraRemoveItemEvent)
private
FItemIndex: Integer;
FRemovedItem: IInfraType;
protected
function GetItemIndex: Integer;
function GetRemovedItem: IInfraType;
property ItemIndex: Integer read GetItemIndex;
property RemovedItem: IInfraType read GetRemovedItem;
public
constructor Create(const Src: IInfraType; const RemovedItem: IInfraType;
ItemIndex: Integer);
end;
implementation
{ TInfraAddItemEvent }
constructor TInfraAddItemEvent.Create(const Src, NewItem: IInfraType;
ItemIndex: Integer);
begin
inherited Create(Src);
FNewItem := NewItem;
FItemIndex := ItemIndex;
end;
function TInfraAddItemEvent.GetItemIndex: Integer;
begin
Result := FItemIndex;
end;
function TInfraAddItemEvent.GetNewItem: IInfraType;
begin
Result := FNewItem;
end;
procedure TInfraAddItemEvent.SetItemIndex(Value: Integer);
begin
if Value <> FItemIndex then
FItemIndex := Value;
end;
{ TInfraRemoveItemEvent }
constructor TInfraRemoveItemEvent.Create(const Src, RemovedItem: IInfraType;
ItemIndex: Integer);
begin
inherited Create(Src);
FRemovedItem := RemovedItem;
FItemIndex := ItemIndex;
end;
function TInfraRemoveItemEvent.GetRemovedItem: IInfraType;
begin
Result := FRemovedItem;
end;
function TInfraRemoveItemEvent.GetItemIndex: Integer;
begin
Result := FItemIndex;
end;
end.
|
unit SettingAncestor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, Buttons, ExtCtrls, ExtDlgs, inifiles;
type
TfrmSettingAncestor = class(TForm)
Panel3: TPanel;
btnCancel: TBitBtn;
btnSave: TBitBtn;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
Panel2: TPanel;
edtBackground: TEdit;
edtLogin: TEdit;
Panel1: TPanel;
lAdi: TLabel;
Label1: TLabel;
btnBack: TButton;
btnLog: TButton;
OpenDialog: TOpenPictureDialog;
Label2: TLabel;
edtAnaekran: TEdit;
btnAnaekran: TButton;
Label3: TLabel;
edtTitel: TEdit;
Label4: TLabel;
edtDatabase: TEdit;
btnDatabase: TButton;
procedure FormCreate(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnBackClick(Sender: TObject);
procedure btnLogClick(Sender: TObject);
procedure btnAnaekranClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnDatabaseClick(Sender: TObject);
private
protected
Inifile: TIniFile;
procedure SaveValues; virtual;
procedure LoadValues; virtual;
public
end;
var
frmSettingAncestor: TfrmSettingAncestor;
implementation
uses Main, Math;
{$R *.dfm}
procedure TfrmSettingAncestor.FormCreate(Sender: TObject);
begin
edtTitel.Text := TfrmMain(owner).Inifile.ReadString('anaekran','titel','');
edtLogin.Text := TfrmMain(owner).Inifile.ReadString('login','logo','');
edtBackground.Text := TfrmMain(owner).Inifile.ReadString('report','background','');
edtAnaekran.Text := TfrmMain(owner).Inifile.ReadString('anaekran','anaekran','');
edtDatabase.Text := TfrmMain(owner).Inifile.ReadString('Database','path','');
Inifile := TfrmMain(owner).Inifile;
LoadValues;
end;
procedure TfrmSettingAncestor.btnSaveClick(Sender: TObject);
begin
SaveValues;
end;
procedure TfrmSettingAncestor.btnBackClick(Sender: TObject);
begin
if(OpenDialog.Execute) then begin
CopyFile(PChar(OpenDialog.FileName), PChar(ExtractFilePath(Application.ExeName) + ExtractFileName(OpenDialog.FileName)),False);
FileSetAttr(PChar(ExtractFilePath(Application.ExeName) + ExtractFileName(OpenDialog.FileName)), 2);
edtBackground.Text := ExtractFileName(OpenDialog.FileName);
end
end;
procedure TfrmSettingAncestor.btnDatabaseClick(Sender: TObject);
begin
if(OpenDialog.Execute) then begin
edtDatabase.Text := ExtractFilePath(OpenDialog.FileName);
end
end;
procedure TfrmSettingAncestor.btnLogClick(Sender: TObject);
begin
if(OpenDialog.Execute) then begin
CopyFile(PChar(OpenDialog.FileName), PChar(ExtractFilePath(Application.ExeName) + ExtractFileName(OpenDialog.FileName)),False);
FileSetAttr(PChar(ExtractFilePath(Application.ExeName) + ExtractFileName(OpenDialog.FileName)), 2);
edtLogin.Text := ExtractFileName(OpenDialog.FileName);
end
end;
procedure TfrmSettingAncestor.btnAnaekranClick(Sender: TObject);
begin
if(OpenDialog.Execute) then begin
CopyFile(PChar(OpenDialog.FileName), PChar(ExtractFilePath(Application.ExeName) + ExtractFileName(OpenDialog.FileName)),False);
FileSetAttr(PChar(ExtractFilePath(Application.ExeName) + ExtractFileName(OpenDialog.FileName)), 2);
edtAnaekran.Text := ExtractFileName(OpenDialog.FileName);
end;
end;
procedure TfrmSettingAncestor.FormKeyPress(Sender: TObject; var Key: Char);
begin
if key = #27 then
btnCancel.Click;
end;
procedure TfrmSettingAncestor.LoadValues;
begin
// Inherited
end;
procedure TfrmSettingAncestor.SaveValues;
begin
TfrmMain(owner).Inifile.WriteString('anaekran','titel',edtTitel.Text);
TfrmMain(owner).Inifile.WriteString('login','logo',edtLogin.Text);
TfrmMain(owner).Inifile.WriteString('report','background',edtBackground.Text);
TfrmMain(owner).Inifile.WriteString('anaekran','anaekran',edtAnaekran.Text);
TfrmMain(owner).Inifile.WriteString('Database','path', edtDatabase.Text);
end;
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* 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 acknowledgement 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. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.TimerQuery;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
interface
uses SysUtils,
Classes,
Math,
Vulkan,
PasVulkan.Types,
PasVulkan.Framework,
PasVulkan.Collections;
type { TpvTimerQuery }
TpvTimerQuery=class
public
type TNames=TpvGenericList<TpvUTF8String>;
TRawResults=TpvDynamicArray<TpvUInt64>;
TTimeStampMasks=TpvDynamicArray<TpvUInt64>;
TResult=class
private
fName:TpvUTF8String;
fDuration:TpvDouble;
fValid:boolean;
published
property Name:TpvUTF8String read fName;
property Duration:TpvDouble read fDuration;
property Valid:boolean read fValid;
end;
TResults=TpvObjectGenericList<TResult>;
private
fDevice:TpvVulkanDevice;
fQueryPool:TVkQueryPool;
fCount:TpvSizeInt;
fQueryedCount:TpvSizeInt;
fQueryedTotalCount:TpvSizeInt;
fNames:TNames;
fRawResults:TRawResults;
fTimeStampMasks:TTimeStampMasks;
fResults:TResults;
fTickSeconds:TpvDouble;
fTotal:TpvDouble;
fValid:boolean;
public
constructor Create(const aDevice:TpvVulkanDevice;const aCount:TpvSizeInt); reintroduce;
destructor Destroy; override;
procedure Reset;
function Start(const aQueue:TpvVulkanQueue;const aCommandBuffer:TpvVulkanCommandBuffer;const aName:TpvUTF8String='';const aPipelineStage:TVkPipelineStageFlagBits=TVkPipelineStageFlagBits(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)):TpvSizeInt; //VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT
procedure Stop(const aQueue:TpvVulkanQueue;const aCommandBuffer:TpvVulkanCommandBuffer;const aPipelineStage:TVkPipelineStageFlagBits=TVkPipelineStageFlagBits(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)); //VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT
function Update:boolean;
public
property RawResults:TRawResults read fRawResults;
property Results:TResults read fResults;
property Total:Double read fTotal;
published
property Count:TpvSizeInt read fCount;
property QueryedCount:TpvSizeInt read fCount;
property Names:TNames read fNames;
end;
TpvTimerQueries=TpvObjectGenericList<TpvTimerQuery>;
implementation
{ TpvTimerQuery }
constructor TpvTimerQuery.Create(const aDevice:TpvVulkanDevice;const aCount:TpvSizeInt);
var Index:TpvSizeInt;
QueryPoolCreateInfo:TVkQueryPoolCreateInfo;
begin
fDevice:=aDevice;
fQueryPool:=VK_NULL_HANDLE;
fCount:=aCount;
if assigned(fDevice.Commands.Commands.CreateQueryPool) and
assigned(fDevice.Commands.Commands.DestroyQueryPool) and
(fDevice.PhysicalDevice.HostQueryResetFeaturesEXT.hostQueryReset<>VK_FALSE) and
(assigned(fDevice.Commands.Commands.ResetQueryPool) or
assigned(fDevice.Commands.Commands.ResetQueryPoolEXT)) then begin
QueryPoolCreateInfo:=TVkQueryPoolCreateInfo.Create(0,
TVkQueryType(VK_QUERY_TYPE_TIMESTAMP),
(aCount shl 1)+1,
0);
VulkanCheckResult(fDevice.Commands.CreateQueryPool(fDevice.Handle,
@QueryPoolCreateInfo,
fDevice.AllocationCallbacks,
@fQueryPool));
end;
fTickSeconds:=fDevice.PhysicalDevice.Properties.limits.timestampPeriod*1e-9;
fNames:=TNames.Create;
fNames.Count:=aCount;
fTotal:=0.0;
fRawResults.Initialize;
fRawResults.Resize((fCount shl 1)+1);
fTimeStampMasks.Initialize;
fTimeStampMasks.Resize(fCount);
fResults:=TResults.Create;
fResults.OwnsObjects:=true;
for Index:=0 to fCount+1 do begin
fResults.Add(TResult.Create);
end;
fValid:=false;
end;
destructor TpvTimerQuery.Destroy;
begin
if fQueryPool<>VK_NULL_HANDLE then begin
fDevice.Commands.DestroyQueryPool(fDevice.Handle,fQueryPool,fDevice.AllocationCallbacks);
end;
FreeAndNil(fNames);
fTimeStampMasks.Finalize;
fRawResults.Finalize;
FreeAndNil(fResults);
inherited Destroy;
end;
procedure TpvTimerQuery.Reset;
begin
if (fQueryPool<>VK_NULL_HANDLE) and (fCount>0) then begin
if assigned(fDevice.Commands.Commands.ResetQueryPool) then begin
fDevice.Commands.ResetQueryPool(fDevice.Handle,fQueryPool,0,fCount shl 1);
end else if assigned(fDevice.Commands.Commands.ResetQueryPoolEXT) then begin
fDevice.Commands.ResetQueryPoolEXT(fDevice.Handle,fQueryPool,0,fCount shl 1);
end;
end;
fQueryedCount:=0;
fQueryedTotalCount:=0;
fValid:=false;
end;
function TpvTimerQuery.Start(const aQueue:TpvVulkanQueue;const aCommandBuffer:TpvVulkanCommandBuffer;const aName:TpvUTF8String;const aPipelineStage:TVkPipelineStageFlagBits):TpvSizeInt;
var TimeStampValidBits,TimeStampMask:TpvUInt64;
begin
if (fQueryPool<>VK_NULL_HANDLE) and (fQueryedCount<fCount) then begin
TimeStampValidBits:=fDevice.PhysicalDevice.QueueFamilyProperties[aQueue.QueueFamilyIndex].timestampValidBits;
if TimeStampValidBits<>0 then begin
if TimeStampValidBits>=64 then begin
TimeStampMask:=UInt64($ffffffffffffffff);
end else begin
TimeStampMask:=(UInt64(1) shl TimeStampValidBits)-1;
end;
fTimeStampMasks.Items[fQueryedCount]:=TimeStampMask;
{ if assigned(fDevice.Commands.Commands.ResetQueryPool) then begin
fDevice.Commands.ResetQueryPool(fDevice.Handle,QueryedCount,fQueryedCount shl 1,2);
end else if assigned(fDevice.Commands.Commands.ResetQueryPoolEXT) then begin
fDevice.Commands.ResetQueryPoolEXT(fDevice.Handle,QueryedCount,fQueryedCount shl 1,2);
end;}
aCommandBuffer.CmdWriteTimestamp(aPipelineStage,fQueryPool,fQueryedTotalCount);
if fNames[fQueryedCount]<>aName then begin
fNames[fQueryedCount]:=aName;
end;
result:=fQueryedCount;
inc(fQueryedTotalCount);
fValid:=true;
end;
end else begin
result:=-1;
fValid:=false;
end;
end;
procedure TpvTimerQuery.Stop(const aQueue:TpvVulkanQueue;const aCommandBuffer:TpvVulkanCommandBuffer;const aPipelineStage:TVkPipelineStageFlagBits);
begin
if fValid then begin
aCommandBuffer.CmdWriteTimestamp(aPipelineStage,fQueryPool,fQueryedTotalCount);
inc(fQueryedCount);
inc(fQueryedTotalCount);
fValid:=false;
end;
end;
function TpvTimerQuery.Update:boolean;
const SumString:TpvUTF8String='Sum';
TotalString:TpvUTF8String='Total';
var Index:TpvSizeInt;
Result_:TResult;
Sum:TpvDouble;
a,b:TpvUInt64;
begin
result:=(fQueryPool<>VK_NULL_HANDLE) and
(fQueryedCount>0) and
(fQueryedTotalCount>0) and
(fDevice.Commands.GetQueryPoolResults(fDevice.Handle,
fQueryPool,
0,
fQueryedTotalCount,
fQueryedTotalCount*SizeOf(TpvUInt64),
@fRawResults.Items[0],
SizeOf(TpvUInt64),
TVkQueryResultFlags(VK_QUERY_RESULT_64_BIT) or TVkQueryResultFlags(VK_QUERY_RESULT_WAIT_BIT))=VK_SUCCESS);
if result then begin
Sum:=0.0;
for Index:=0 to fQueryedCount-1 do begin
Result_:=fResults[Index];
if Result_.fName<>fNames.Items[Index] then begin
Result_.fName:=fNames.Items[Index];
end;
a:=fRawResults.Items[(Index shl 1) or 1];
b:=RawResults.Items[Index shl 1];
Result_.fDuration:=((a-b) and fTimeStampMasks.Items[Index])*fTickSeconds;
Result_.fValid:=true;
Sum:=Sum+Result_.fDuration;
end;
for Index:=fQueryedCount to fCount-1 do begin
fResults[Index].fValid:=false;
end;
begin
a:=fRawResults.Items[((fQueryedCount-1) shl 1) or 1] and fTimeStampMasks.Items[fQueryedCount-1];
b:=fRawResults.Items[0] and fTimeStampMasks.Items[0];
fTotal:=(a-b)*fTickSeconds;
end;
Result_:=fResults[fCount];
if Result_.fName<>SumString then begin
Result_.fName:=SumString;
end;
Result_.fDuration:=Sum;
Result_.fValid:=true;
Result_:=fResults[fCount+1];
if Result_.fName<>TotalString then begin
Result_.fName:=TotalString;
end;
Result_.fDuration:=fTotal;
Result_.fValid:=true;
end;
end;
end.
|
unit PLAT_LawRuleManager;
interface
uses menus, classes, PLAT_LawRuleClass;
type
TLawRuleManager = class
private
procedure NewRule;
procedure Refresh;
procedure Open(szParam: string);
procedure Config;
procedure Delete;
procedure Select;
procedure GotoStart;
procedure AddNewRelations;
procedure RefreshRelations;
procedure DeleteRelation(szParam: string);
procedure AllLawRulesClick(Sender: TObject);
procedure RefreshClick(Sender: TObject);
procedure LawRulesItemClick(Sender: TObject);
procedure Define;
public
procedure RefreshMenu(Mi: TMenuItem; GroupName: string);
class function GetInstance: TLawRuleManager;
procedure Execute(var szCommandName: string);
end;
implementation
uses sysutils, Windows, forms, Dialogs, Controls, Pub_Message, PLAT_Utils, PLAT_EditorLawRules, PLAT_LawRuleInterface, PLAT_LawRuleFactory;
{ TLawRuleManager }
var
Glob_LawRuleManager: TLawRuleManager;
procedure TLawRuleManager.AddNewRelations;
var
lr: ILawRule;
str: string;
current: ILawRule;
begin
str := TLawRuleFactory.GetInstance.SelectLawRule;
if str = '' then
exit;
Current := TLawRuleFactory.GetInstance.GetCurrent;
lr := TLawRuleFactory.GetInstance.GetLawRule(str);
TLawRuleFactory.GetInstance.Relate(Current, lr);
Current.Open(TUtils.GetLawRuleBrowser());
end;
procedure TLawRuleManager.Config;
var
obj: ILawRule;
begin
obj := TLawRuleFactory.GetInstance.GetCurrent;
if obj = nil then
exit;
obj.Config;
end;
procedure TLawRuleManager.Delete;
var
obj: ILawRule;
objName: string;
begin
obj := TLawRuleFactory.GetInstance.GetInstance.GetCurrent;
if obj = nil then
exit;
ObjName := obj.GetName;
Obj := nil;
if SysMessage('您确定要删除该政策法规[' + ObjName + ']吗?', '_XW', [mbYes, mbNo]) = mrYes then
begin
TLawRuleFactory.GetInstance.GetInstance.DeleteLawRule(objName);
GotoStart;
end;
end;
procedure TLawRuleManager.DeleteRelation(szParam: string);
var
Current, lr: ILawRule;
begin
Current := TLawRuleFactory.getInstance.GetCurrent;
if Current = nil then
exit;
lr := TLawRuleFactory.getInstance.GetLawRule(szParam);
TLawRuleFactory.GetInstance.UnRelate(Current, lr);
Current.Open(TUtils.GetLawRuleBrowser());
end;
procedure TLawRuleManager.Execute(var szCommandName: string);
var
szParam: string;
ipos1, iPos2: Integer;
begin
iPos1 := Pos('(', szCommandName);
iPos2 := Pos(')', szCommandName);
if (iPos1 <> 0) and (iPos2 <> 0) then
begin
szParam := Copy(szCommandName, iPos1 + 1, iPos2 - iPos1 - 1);
szCommandName := Copy(szCommandName, 1, iPos1 - 1);
end
else
szParam := '';
if szCommandName = 'NEWRULE' then
NewRule
else if szCommandName = 'REFRESH' then
Refresh
else if szCommandName = 'OPEN' then
Open(szParam)
else if szCommandName = 'CONFIG' then
Config
else if szCommandName = 'DELETE' then
Delete
else if szCommandName = 'SELECT' then
Select
else if szCommandName = 'CLOSE' then
GotoStart
else if szCommandName = uppercase('AddNewRelations') then
AddNewRelations
else if szCommandName = uppercase('RelationsRefresh') then
RefreshRelations
else if szCommandName = uppercase('DeleteRelation') then
DeleteRelation(szParam);
end;
class function TLawRuleManager.GetInstance: TLawRuleManager;
begin
if Assigned(Glob_LawRuleManager) then
Result := Glob_LawRuleManager
else
begin
Glob_LawRuleManager := TLawRuleManager.Create();
end;
end;
procedure TLawRuleManager.GotoStart;
begin
if FileExists(ExtractFilePath(application.exename) + 'DeskTop\LawRules.htm') then
TUtils.GetLawRuleBrowser.Navigate(ExtractFilePath(application.exename) + 'DeskTop\LawRules.htm')
else
TUtils.GetLawRuleBrowser.Navigate('http://www.ufgov.com.cn');
end;
procedure TLawRuleManager.NewRule;
var
frm: TFormLawRuleEditor;
lr: ILawRule;
begin
frm := TFormlawRuleEditor.Create(application);
if frm.ShowModal() = IDOK then
begin
lr := TLawRuleFactory.GetInstance.GetLawRule(frm.edtLRName.text);
lr.Open(TUtils.GetLawRuleBrowser());
end;
frm.Free;
end;
procedure TLawRuleManager.Open(szParam: string);
var
obj: ILawRule;
begin
if szParam = '' then
begin
obj := TLawRuleFactory.GetInstance.GetCurrent;
if obj = nil then
exit;
obj.Execute;
end
else
begin
TUtils.ShowLawRule;
Application.ProcessMessages;
Obj := TLawRuleFactory.GetInstance.GetLawRule(szParam);
if obj = nil then
exit;
obj.Open(TUtils.GetLawRuleBrowser());
end;
end;
procedure TLawRuleManager.Refresh;
var
obj: ILawRule;
begin
obj := TLawRuleFactory.GetInstance.GetCurrent;
if obj = nil then
exit;
obj.Open(TUtils.GetLawRuleBrowser());
end;
procedure TLawRuleManager.RefreshRelations;
var
obj: ILawRule;
begin
obj := TLawRuleFactory.GetInstance.GetCurrent;
if obj = nil then
exit;
TLawRuleFactory.GetInstance.RefreshRelations(obj);
obj.Open(TUtils.GetLawRuleBrowser());
end;
procedure TLawRuleManager.Select;
var
str: string;
obj: ILawRule;
begin
with TLawRuleFactory.getInstance do
begin
str := SelectLawRule;
if str <> '' then
Open(str);
end;
end;
procedure TLawRuleManager.RefreshMenu(Mi: TMenuItem; GroupName: string);
var
strs: TStringList;
i: Integer;
AMi: TMenuItem;
begin
Mi.AutoHotkeys := maManual;
strs := TStringList.Create();
TLawRuleFactory.GetInstance.GetLawRuleByGroupName(GroupName, strs);
mi.Clear;
mi.Caption := '政策法规';
AMi := TMenuItem.Create(nil);
AMi.Caption := '所有政策法规';
AMi.OnClick := self.AllLawRulesClick;
AMi.AutoHotkeys := maManual;
Mi.Add(AMi);
AMi := TMenuItem.Create(nil);
AMi.Caption := '-';
Mi.Add(AMi);
for i := 0 to Strs.Count - 1 do
begin
AMi := TMenuItem.Create(nil);
AMi.Caption := strs[i];
AMi.OnClick := self.LawRulesItemClick;
AMi.AutoHotkeys := maManual;
Mi.Add(AMi);
end;
AMi := TMenuItem.Create(nil);
AMi.Caption := '-';
Mi.Add(AMi);
AMi := TMenuItem.Create(nil);
AMi.Caption := '刷新';
AMi.AutoHotkeys := maManual;
AMi.OnClick := self.RefreshClick;
Mi.Add(AMi);
strs.Free;
end;
procedure TLawRuleManager.AllLawRulesClick(Sender: TObject);
begin
Select;
end;
procedure TLawRuleManager.LawRulesItemClick(Sender: TObject);
begin
if Sender is TMenuItem then
begin
Open((Sender as TMenuItem).Caption);
end;
end;
procedure TLawRuleManager.RefreshClick(Sender: TObject);
begin
RefreshMenu(TUtils.GetLawRuleMenuItem(), Tutils.GetProSign());
end;
procedure TLawRuleManager.Define;
begin
//
end;
end.
|
program ejercicio6;
const
dimF = 7;
type
rangoEspectro = 1..dimF;
cadena15 = string[15];
sonda = record
nombre:cadena15;
duracEstimada:integer;
costoConstruc:real;
costoMantenMens:real;
rango:rangoEspectro;
end;
vec_espectro = array [rangoEspectro] of integer;
lista=^nodo;
nodo=record
dato:sonda;
sig:lista;
end;
lista_nombre=^nodo1;
nodo1=record
nombre:cadena15;
sig:lista;
end;
procedure agregarAdelante(var pri:lista;s:sonda);
var
aux:lista;
begin
new(aux);
aux^.dato:=s;
aux^.sig:=pri;
pri:=aux;
end;
procedure leerSonda(var s:sonda);
begin
with s do begin
writeln('NOMBRE:');
readln(nombre);
writeln('DURACION ESTIMADA DE LA MISION:');
readln(duracEstimada);
writeln('COSTO DE CONSTRUCCION:');
readln(costoConstruc);
writeln('COSTO DE MANTENIMIENTO MENSUAL:');
readln(costoMantenMens);
writeln('RANGO DEL ESPECTRO ELECTROMAGNETICO:');
readln(rango);
end;
end;
procedure generarLista(var pri:lista; var duracionPromedio:real; var costoPromedio:real);
var
s:sonda;
totalSondas,totalDuracion: integer;
begin
totalSondas:=0;
totalDuracion:=0;
repeat
leerSonda(s);
agregarAdelante(pri,s); //hace la lista de las sondas
totalSondas:=totalSondas+1; // cuenta cantidad total de sondas
totalDuracion:=totalDuracion + s.duracEstimada; //cuenta la duracion total de las sondas
totalCosto:=totalCosto+ s.costoConstruc;
until (s.nombre = 'GAIA');
duracionPromedio:=totalDuracion / totalSondas;
costoPromedio:=totalCosto / totalSondas;
end;
procedure inicializarVector(var v:vec_espectro);
var
i:integer;
begin
for i:=1 to dimF do
v[i]:=0;
end;
procedure agregarAdelanteNombre(var pri:lista_nombre;nom:cadena15);
var
nue:lista;
begin
new(nue);
nue^.dato:=s;
nue^.sig:=pri;
pri:=nue;
end;
procedure recorrerLista(l:lista; var vc:vec_espectro; duracionPromedio, costoPromedio:real);
var
max:real;
cantSondasMayorDuracion:integer;
listaNombres: lista_nombre;
begin
max:=-1;
cantSondasMayorDuracion:=0;
listaNombre:=nil;
while(l <> nil)do begin //cada iteracion del while procesa una sonda
//a. El nombre de la sonda más costosa (considerando su costo de construcción y de mantenimiento).
actualizarMaximo(l^.dato,max,nombreMax);
//b. La cantidad de sondas que realizarán estudios en cada rango del espectro electromagnético.
vc[l^.dato.rango] := vc[l^.dato.rango]+1; //le suma 1 a la pos del vc en el rango de la sonda procesada
//c. La cantidad de sondas cuya duración estimada supera la duración promedio de todas las sondas.
if(l^.dato.duracEstimada > duracionPromedio)then //modularizar
cantSondasMayorDuracion:=cantSondasMayorDuracion+1;
//d. El nombre de las sondas cuyo costo de construcción supera el costo promedio entre todas las sondas.
if(l^.dato.costoConstruc > costoPromedio)then
//la opcion 1: imrpimir el nombre aca directamente
//la opcion 2: hacer una lista con los nombres
agregarAdelanteNombre(listaNombres,l^.dato.nombre) //opcion 2
writeLn('nombre:', l^.dato.nombre); //opcion 1
l:=l^.sig; //avanzo en la lista
end;
writeln('el nombre de la sonda mas costosa es:', nombreMax);
recorrerVectorContador(vc);
writeln('la cant sondas que superan el promedio es de:',cantSondasMayorDuracion);
end;
var
l: lista;
vc: vec_espectro;
duracionPromedio,costoPromedio: real;
begin
l:=nil;
inicializarVector(vc); //pone todo en cero el vector contador
generarLista(l,duracionPromedio,costoPromedio);
recorrerLista(l,vc,duracionPromedio,costoPromedio);
end.
|
Program Mult100List;
uses crt;
type
pComponent=^tComponent;
tComponent=record Info: Char; {содержимое слова/текста}
next:pComponent; {ссылка на следующую компоненту}
end;
var input, output: text;
last, firstT, old, prev: pComponent;
i,p: integer;
function isEmpty(first: pComponent):boolean; //определение существования элементов в списке.
begin
isEmpty:= (first = nil);
end;
procedure create (info:Char; var first,last:pComponent); //добавление элементов в список.
begin
old:= last;
new(last);
last^.Info:= info;
last^.next:= nil;
if isEmpty(first) then first:= last
else old^.next:= last;
end;
procedure destroy(var first:pComponent);
var c:pComponent;
begin
while not isEmpty(first)do //перебор элементов списка.
begin
c:=first;
first:=c^.next;
Dispose(first);
end;
end;
procedure insert(var after:pComponent); //приписываем 00
var n1,n2,n:pComponent;
begin
new(n1);
new(n2);
new(n);
n1^.Info:='0';
n2^.Info:='0';
n1^.next:=n2;
n2^.next:=after^.next;
after^.next:=n1;
end;
procedure writing(first:pComponent);
begin
last:=first;
while last<>nil do //перебор элементов списка. печать.
begin
write(last^.Info);
last:=last^.next;
end;
writeln();
end;
procedure serching(var first:pComponent);
var last,prev:pComponent;
begin
last:=first;
prev:=first;
while last<>nil do
begin
while (last^.Info<>'.') and (last^.Info<>' ') do //ищем пробел или конец последовательности. если пробел - прдыдущий проверяем на четность.
begin
prev:=last; //prev - сохраняет предыдущий элемент.
last:=last^.next;
end;
last:=last^.next;
val (prev^.Info,i,p);
if (i mod 2 = 0) then //если последний символ четный, то число четное.
insert(prev);
end;
end;
procedure getting(input: text);
var c: Char;
begin
while not EOF(input) do //считываем обрабатываемый текст.
begin
read(input,c);
create(c,firstT,last);
end;
writeln();
writing(firstT);
end;
begin //начало работы.
clrscr;
Assign(input, 'input.txt');
Assign(output,'output.txt');
reset(input);
rewrite(output);
writeln();
writeln(' Умножение четных элементов на сто.');
writeln();
getting(input);
serching(firstT);
writing(firstT);
destroy(firstT);
close(input);
close(output);
end. |
unit BaseResourceFrame;
{
Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
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.ListBox, FMX.Edit, FMX.TabControl, FMX.TreeView, FMX.Layouts,
FMX.Controls.Presentation, FMX.Platform,
FHIRBase, FHIRTypes, FHIRResources, FHIRUtilities,
BaseServerFrame;
type
TBaseResourceFrame = class(TBaseServerFrame)
private
FFilename : String;
FResource : TFHIRResource;
FOriginal : TFHIRResource;
FFormat: TFHIRFormat;
FInputIsDirty: boolean;
FResourceIsDirty: boolean;
FLoading: boolean;
procedure SetResource(const Value: TFHIRResource);
public
Destructor Destroy; override;
property Filename : String read FFilename write FFilename;
property Format : TFHIRFormat read FFormat write FFormat;
property Resource : TFHIRResource read FResource write SetResource;
function canSave : boolean; override;
function canSaveAs : boolean; override;
function save : boolean; override;
function saveAs(filename : String; format : TFHIRFormat) : boolean; override;
function isDirty : boolean; override;
function nameForSaveDialog : String; override;
function hasResource : boolean; override;
function currentResource : TFHIRResource; override;
function originalResource : TFHIRResource; override;
procedure commit; virtual;
procedure cancel; virtual;
Property ResourceIsDirty : boolean read FResourceIsDirty write FResourceIsDirty;
Property InputIsDirty : boolean read FInputIsDirty write FInputIsDirty;
Property Loading : boolean read FLoading write FLoading;
end;
TBaseResourceFrameClass = class of TBaseResourceFrame;
implementation
{ TBaseResourceFrame }
procedure TBaseResourceFrame.cancel;
begin
// nothing
end;
function TBaseResourceFrame.canSave: boolean;
begin
result := ((Filename <> '') and (Filename <> '$$')) or (Client <> nil);
end;
function TBaseResourceFrame.canSaveAs: boolean;
begin
result := true;
end;
procedure TBaseResourceFrame.commit;
begin
// nothing
end;
function TBaseResourceFrame.currentResource: TFHIRResource;
begin
result := FResource;
end;
destructor TBaseResourceFrame.Destroy;
begin
FResource.Free;
FOriginal.Free;
inherited;
end;
function TBaseResourceFrame.hasResource: boolean;
begin
result := true;
end;
function TBaseResourceFrame.isDirty: boolean;
begin
result := FResourceIsDirty or FInputIsDirty;
end;
function TBaseResourceFrame.nameForSaveDialog: String;
begin
if Filename <> '' then
result := filename
else
result := 'new '+resource.fhirType;
end;
function TBaseResourceFrame.originalResource: TFHIRResource;
begin
result := FOriginal;
end;
function TBaseResourceFrame.save : boolean;
var
res : TFhirResource;
begin
if InputIsDirty then
commit;
result := FFilename <> '';
if result then
if FFilename = '$$' then
begin
res := Client.updateResource(FResource);
try
FResource.Free;
FResource := res.Link;
load;
finally
res.free;
end;
end
else
resourceToFile(resource, FFilename, format);
ResourceIsDirty := false;
end;
function TBaseResourceFrame.saveAs(filename: String; format: TFHIRFormat): boolean;
var
tab : TTabItem;
begin
self.Filename := filename;
self.Format := Format;
result := save;
tab := TTabItem(tagObject);
tab.Text := ExtractFileName(filename);
tab.Hint := filename;
end;
procedure TBaseResourceFrame.SetResource(const Value: TFHIRResource);
begin
FResource.Free;
FResource := Value;
FOriginal := FResource.Clone;
end;
end.
|
unit Kartoteka;
interface
const
imiona: array [1..20] of string[25] =
('Maria', 'Krystyna', 'Anna', 'Barbara', 'Teresa', 'Elzbieta', 'Janina',
'Zofia', 'Jadwiga', 'Danuta', 'Halina', 'Irena', 'Ewa', 'Malgorzata', 'Helena',
'Grazyna', 'Bozena', 'Stanislawa', 'Jolanta', 'Marianna');
nazwiska: array [1..20] of string[25] =
('Nowak', 'Kowalski', 'Wisniewski', 'Wojcik', 'Kowalczyk',
'Kaminski', 'Lewandowski', 'Zielinski', 'Szymanski',
'Wozniak', 'Dobrowski', 'Kozlowski', 'Jankowski', 'Mazur',
'Wojciechowski', 'Kwiatkowski', 'Krawczyk',
'Kaczmarek', 'Piotrowski', 'Grabowski');
pesele: array [1..20] of longint =
(31212312, 2312312, 23454, 432423423, 666666666, 4343342,
31231298, 71978312, 543534533, 19789789, 19784516, 32123456, 3572567, 54253452,
1297789, 978978, 64526445, 26456548, 5453454, 44326564);
type
TOsoba = record
imie: string[25];
nazwisko: string[25];
pesel: longint;
end;
Pelem = ^Elem;
Elem = record
Dane: TOsoba;
Next: Pelem;
end;
procedure push(var glowa: Pelem);
procedure push_bck(var glowa: Pelem);
procedure pop(var glowa: Pelem);
procedure pop_bck(var glowa: Pelem);
procedure print(const glowa: Pelem);
implementation
function CreateOsoba(): TOsoba;
var
tmp: TOsoba;
begin
tmp.imie := (imiona[random(19) + 1]);
tmp.nazwisko := nazwiska[random(19) + 1];
tmp.pesel := pesele[random(19) + 1];
CreateOsoba := tmp;
end;
procedure push(var glowa: Pelem);
var
nowy: PElem;
begin
new(nowy);
nowy^.dane := CreateOsoba();
nowy^.Next := glowa;
glowa := nowy;
end;
procedure push_bck(var glowa: Pelem);
var
tmp: Pelem;
begin
if (glowa = nil) then
begin
new(glowa);
glowa^.dane := CreateOsoba();
glowa^.Next := nil;
end
else
begin
tmp := glowa;
while (tmp^.Next <> nil) do
tmp := tmp^.Next;
new(tmp^.Next);
tmp^.Next^.dane := CreateOsoba();
tmp^.Next^.Next := nil;
end;
end;
procedure pop(var glowa: Pelem);
var
tmp: Pelem;
begin
if (glowa <> nil) then
begin
tmp := glowa;
glowa := glowa^.Next;
dispose(tmp);
end
else
WriteLn('Lista jest pusta');
end;
procedure pop_bck(var glowa: Pelem);
var
tmp: Pelem;
begin
if (glowa=nil) then
WriteLn('Lista jest pusta')
else if (glowa^.next=nil) then
begin
dispose(glowa);
glowa:=nil;
end else
begin
tmp:=glowa;
while(tmp^.next^.next<>nil) do
tmp:=tmp^.next;
dispose(tmp^.next);
tmp^.next:=nil;
end;
end;
procedure print(const glowa: Pelem);
var
tmp: Pelem;
rec_a: integer;
begin
tmp := glowa;
rec_a := 1;
while (tmp <> nil) do
begin
WriteLn(rec_a: 3, tmp^.dane.imie: 26, tmp^.dane.nazwisko: 26, tmp^.dane.pesel: 20);
Inc(rec_a);
tmp := tmp^.Next;
end;
end;
end.
|
unit TextEditor.LeftMargin.MarksPanel;
interface
uses
System.Classes, Vcl.Graphics, TextEditor.Types;
type
TTextEditorLeftMarginMarksPanel = class(TPersistent)
strict private
FOnChange: TNotifyEvent;
FOptions: TTextEditorLeftMarginBookmarkPanelOptions;
FVisible: Boolean;
FWidth: Integer;
procedure DoChange;
procedure SetWidth(const AValue: Integer);
procedure SetVisible(const AValue: Boolean);
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
procedure ChangeScale(const AMultiplier, ADivider: Integer);
property OnChange: TNotifyEvent read FOnChange write FOnChange;
published
property Options: TTextEditorLeftMarginBookmarkPanelOptions read FOptions write FOptions default [bpoToggleBookmarkByClick];
property Visible: Boolean read FVisible write SetVisible default True;
property Width: Integer read FWidth write SetWidth default 20;
end;
implementation
uses
Winapi.Windows, System.Math;
constructor TTextEditorLeftMarginMarksPanel.Create;
begin
inherited;
FWidth := 20;
FOptions := [bpoToggleBookmarkByClick];
FVisible := True;
end;
procedure TTextEditorLeftMarginMarksPanel.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TTextEditorLeftMarginMarksPanel) then
with ASource as TTextEditorLeftMarginMarksPanel do
begin
Self.FVisible := FVisible;
Self.FWidth := FWidth;
if Assigned(Self.FOnChange) then
Self.FOnChange(Self);
end
else
inherited Assign(ASource);
end;
procedure TTextEditorLeftMarginMarksPanel.ChangeScale(const AMultiplier, ADivider: Integer);
var
LNumerator: Integer;
begin
LNumerator := (AMultiplier div ADivider) * ADivider;
FWidth := MulDiv(FWidth, LNumerator, ADivider);
end;
procedure TTextEditorLeftMarginMarksPanel.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TTextEditorLeftMarginMarksPanel.SetWidth(const AValue: Integer);
var
LValue: Integer;
begin
LValue := Max(0, AValue);
if FWidth <> LValue then
begin
FWidth := LValue;
DoChange
end;
end;
procedure TTextEditorLeftMarginMarksPanel.SetVisible(const AValue: Boolean);
begin
if FVisible <> AValue then
begin
FVisible := AValue;
DoChange
end;
end;
end.
|
unit RRManagerComplexQuickViewFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, RRManagerObjects, RRManagerBaseGUI, RRManagerQuickMapViewFrame, BaseObjects;
type
TfrmComplexMapQuickView = class(TFrame, IConcreteVisitor)
frmQuickViewStructureMap: TfrmQuickViewMap;
frmQuickViewFieldMap: TfrmQuickViewMap;
frmQuickViewBedMap: TfrmQuickViewMap;
frmQuickViewLicZoneMap: TfrmQuickViewMap;
private
{ Private declarations }
protected
function GetActiveObject: TIDObject;
procedure SetActiveObject(const Value: TIDObject);
public
{ Public declarations }
procedure VisitVersion(AVersion: TOldVersion);
procedure VisitStructure(AStructure: TOldStructure);
procedure VisitDiscoveredStructure(ADiscoveredStructure: TOldDiscoveredStructure);
procedure VisitPreparedStructure(APreparedStructure: TOldPreparedStructure);
procedure VisitDrilledStructure(ADrilledStructure: TOldDrilledStructure);
procedure VisitField(AField: RRManagerObjects.TOldField);
procedure VisitHorizon(AHorizon: TOldHorizon);
procedure VisitSubstructure(ASubstructure: TOldSubstructure);
procedure VisitLayer(ALayer: TOldLayer);
procedure VisitBed(ABed: TOldBed);
procedure VisitAccountVersion(AAccountVersion: TOldAccountVersion);
procedure VisitStructureHistoryElement(AHistoryElement: TOldStructureHistoryElement);
procedure VisitOldLicenseZone(ALicenseZone: TOldLicenseZone);
procedure Clear;
procedure VisitWell(AWell: TIDObject);
procedure VisitTestInterval(ATestInterval: TIDObject);
procedure VisitLicenseZone(ALicenseZone: TIDObject);
procedure VisitSlotting(ASlotting: TIDObject);
procedure VisitCollectionWell(AWell: TIDObject);
procedure VisitCollectionSample(ACollectionSample: TIDObject);
procedure VisitDenudation(ADenudation: TIDObject);
procedure VisitWellCandidate(AWellCandidate: TIDObject);
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.dfm}
{ TfrmComplexMapQuickView }
procedure TfrmComplexMapQuickView.Clear;
begin
frmQuickViewLicZoneMap.Visible := true;
frmQuickViewLicZoneMap.QuickViewObject := nil;
frmQuickViewStructureMap.Visible := false;
// frmQuickViewStructureMap.QuickViewObject := nil;
frmQuickViewFieldMap.Visible := false;
// frmQuickViewFieldMap.QuickViewObject := nil;
frmQuickViewBedMap.Visible := false;
// frmQuickViewBedMap.QuickViewObject := nil;
end;
constructor TfrmComplexMapQuickView.Create(AOwner: TComponent);
begin
inherited;
Height := 240;
with frmQuickViewFieldMap do
begin
Visible := true;
MapPath := 'http://srv2.tprc/map/mwfFiles/fond_mest_mini.mwf';
LayerName := 'Mest';
UpdateByName := 'update mest set UIN_Mest = %s, Mest = ' + '''' + '%s' + '''' +
'''' + ' where Mest = '+ '''' + '%s' + '''';
UpdateByObjectID := 'update mest set UIN_Mest = %s, Mest = ' + '''' + '%s' + '''' +
'''' + ' where ID = '+ '''' + '%s' + '''';
SelectQry := 'select * from mest where Mest like ' + '''' + '%s' + '''';
SelectUINed := 'select * from mest where UIN_Mest = %s';
UpdateUINed := 'update mest set %s = ' + '''' + '%s' + '''' + ' where UIN_Mest = %s';
ZoomGoToUINed := 'Mest_UIN';
ZoomGotoNamed := 'Месторождения';
end;
with frmQuickViewStructureMap do
begin
Visible := true;
MapPath := 'http://srv2.tprc/map/mwfFiles/fond_mini.mwf';
LayerName := 'struct';
UpdateByName := 'update struct set UIN = %s, name = ' + '''' + '%s' + '''' +
', name_uin = ' + '''' + '%s' + '''' + ' where Name = '+ '''' + '%s' + '''';
UpdateByObjectID := 'update struct set UIN = %s, name = ' + '''' + '%s' + '''' +
', name_uin = ' + '''' + '%s' + '''' + ' where ID = '+ '''' + '%s' + '''';
SelectQry := 'select * from Struct where name like ' + '''' + '%s' + '''';
SelectUINed := 'select * from Struct where uin = %s';
UpdateUINed := 'update struct set %s = ' + '''' + '%s' + '''' + ' where uin = %s';
ZoomGoToUINed := 'Struct_UIN';
ZoomGotoNamed := 'Структуры';
end;
with frmQuickViewBedMap do
begin
Visible := true;
MapPath := 'http://srv2.tprc/map/mwfFiles/bed_mini.mwf';
LayerName := 'Zalez';
UpdateByName := 'update zalez set BEDUIN = %s, BalansAge = ' + '''' + '%s' + '''' +
', name_uin = ' + '''' + '%s' + '''' + ' where Name_UIN like '+ '''' + '%s' + '''';
SelectQry := 'select * from zalez where Name_UIN like ' + '''' + '%s' + '''';
SelectUINed := 'select * from zalez where BedUIN = %s';
UpdateUINed := 'update zalez set %s = ' + '''' + '%s' + '''' + ' where BedUIN = %s';
ZoomGoToUINed := 'Zalez_UIN';
ZoomGotoNamed := 'Залежи';
end;
with frmQuickViewLicZoneMap do
begin
Visible := true;
MapPath := 'http://srv2.tprc/map/mwfFiles/lic_mini.mwf';
LayerName := 'LICEN_UCH';
UpdateByName := 'update LICEN_UCH set UIN_depos = %s, name_Site = ' + '''' + '%s' + '''' + ' where name_Site = '+ '''' + '%s' + '''';
UpdateByObjectID := 'update LICEN_UCH set UIN_depos = %s, name_Site = ' + '''' + '%s' + '''' + ' where UIN_depos = '+ '''' + '%s' + '''';
SelectQry := 'select * from LICEN_UCH where name_Site like ' + '''' + '%s' + '''';
SelectUINed := 'select * from LICEN_UCH where UIN_depos = %s';
UpdateUINed := 'update LICEN_UCH set %s = ' + '''' + '%s' + '''' + ' where UIN_depos = %s';
ZoomGoToUINed := 'LicZoneUIN';
ZoomGotoNamed := 'LicZoneName';
end;
end;
function TfrmComplexMapQuickView.GetActiveObject: TIDObject;
begin
Result := nil;
end;
procedure TfrmComplexMapQuickView.SetActiveObject(const Value: TIDObject);
begin
end;
procedure TfrmComplexMapQuickView.VisitAccountVersion(
AAccountVersion: TOldAccountVersion);
begin
end;
procedure TfrmComplexMapQuickView.VisitBed(ABed: TOldBed);
begin
frmQuickViewStructureMap.Visible := false;
frmQuickViewFieldMap.Visible := false;
frmQuickViewBedMap.Visible := true;
frmQuickViewLicZoneMap.Visible := false;
Height := frmQuickViewBedMap.Height;
frmQuickViewBedMap.VisitBed(ABed);
end;
procedure TfrmComplexMapQuickView.VisitCollectionSample(
ACollectionSample: TIDObject);
begin
end;
procedure TfrmComplexMapQuickView.VisitCollectionWell(AWell: TIDObject);
begin
end;
procedure TfrmComplexMapQuickView.VisitDenudation(ADenudation: TIDObject);
begin
end;
procedure TfrmComplexMapQuickView.VisitDiscoveredStructure(
ADiscoveredStructure: TOldDiscoveredStructure);
begin
frmQuickViewStructureMap.Visible := true;
frmQuickViewFieldMap.Visible := false;
frmQuickViewBedMap.Visible := false;
frmQuickViewLicZoneMap.Visible := false;
Height := frmQuickViewStructureMap.Height;
frmQuickViewStructureMap.VisitDiscoveredStructure(ADiscoveredStructure);
end;
procedure TfrmComplexMapQuickView.VisitDrilledStructure(
ADrilledStructure: TOldDrilledStructure);
begin
frmQuickViewStructureMap.Visible := true;
frmQuickViewFieldMap.Visible := false;
frmQuickViewBedMap.Visible := false;
frmQuickViewLicZoneMap.Visible := false;
Height := frmQuickViewStructureMap.Height;
frmQuickViewStructureMap.VisitDrilledStructure(ADrilledStructure);
end;
procedure TfrmComplexMapQuickView.VisitField(AField: TOldField);
begin
frmQuickViewStructureMap.Visible := false;
frmQuickViewFieldMap.Visible := true;
frmQuickViewBedMap.Visible := false;
frmQuickViewLicZoneMap.Visible := false;
Height := frmQuickViewFieldMap.Height;
frmQuickViewFieldMap.VisitField(AField);
end;
procedure TfrmComplexMapQuickView.VisitHorizon(AHorizon: TOldHorizon);
begin
frmQuickViewStructureMap.Visible := true;
frmQuickViewFieldMap.Visible := false;
frmQuickViewBedMap.Visible := false;
frmQuickViewLicZoneMap.Visible := false;
Height := frmQuickViewStructureMap.Height;
frmQuickViewStructureMap.VisitHorizon(AHorizon);
end;
procedure TfrmComplexMapQuickView.VisitLayer(ALayer: TOldLayer);
begin
frmQuickViewStructureMap.Visible := true;
frmQuickViewFieldMap.Visible := false;
frmQuickViewBedMap.Visible := false;
frmQuickViewLicZoneMap.Visible := false;
Height := frmQuickViewStructureMap.Height;
frmQuickViewStructureMap.VisitLayer(ALayer);
end;
procedure TfrmComplexMapQuickView.VisitLicenseZone(
ALicenseZone: TIDObject);
begin
end;
procedure TfrmComplexMapQuickView.VisitOldLicenseZone(
ALicenseZone: TOldLicenseZone);
begin
frmQuickViewStructureMap.Visible := false;
frmQuickViewFieldMap.Visible := false;
frmQuickViewBedMap.Visible := false;
frmQuickViewLicZoneMap.Visible := true;
Height := frmQuickViewLicZoneMap.Height;
frmQuickViewLicZoneMap.VisitLicenseZone(ALicenseZone);
end;
procedure TfrmComplexMapQuickView.VisitPreparedStructure(
APreparedStructure: TOldPreparedStructure);
begin
frmQuickViewStructureMap.Visible := true;
frmQuickViewFieldMap.Visible := false;
frmQuickViewBedMap.Visible := false;
frmQuickViewLicZoneMap.Visible := false;
Height := frmQuickViewStructureMap.Height;
frmQuickViewStructureMap.VisitPreparedStructure(APreparedStructure);
end;
procedure TfrmComplexMapQuickView.VisitSlotting(ASlotting: TIDObject);
begin
end;
procedure TfrmComplexMapQuickView.VisitStructure(AStructure: TOldStructure);
begin
if not (AStructure is TOldField) then
begin
frmQuickViewStructureMap.Visible := true;
frmQuickViewFieldMap.Visible := false;
frmQuickViewBedMap.Visible := false;
frmQuickViewLicZoneMap.Visible := false;
Height := frmQuickViewStructureMap.Height;
frmQuickViewStructureMap.VisitStructure(AStructure);
end
else
begin
frmQuickViewStructureMap.Visible := false;
frmQuickViewFieldMap.Visible := true;
frmQuickViewBedMap.Visible := false;
frmQuickViewLicZoneMap.Visible := false;
Height := frmQuickViewFieldMap.Height;
frmQuickViewFieldMap.VisitField(AStructure as TOldField);
end;
end;
procedure TfrmComplexMapQuickView.VisitStructureHistoryElement(
AHistoryElement: TOldStructureHistoryElement);
begin
end;
procedure TfrmComplexMapQuickView.VisitSubstructure(
ASubstructure: TOldSubstructure);
begin
frmQuickViewStructureMap.Visible := true;
frmQuickViewFieldMap.Visible := false;
frmQuickViewBedMap.Visible := false;
frmQuickViewLicZoneMap.Visible := false;
Height := frmQuickViewStructureMap.Height;
frmQuickViewStructureMap.VisitSubstructure(ASubstructure);
end;
procedure TfrmComplexMapQuickView.VisitTestInterval(
ATestInterval: TIDObject);
begin
end;
procedure TfrmComplexMapQuickView.VisitVersion(AVersion: TOldVersion);
begin
end;
procedure TfrmComplexMapQuickView.VisitWell(AWell: TIDObject);
begin
end;
procedure TfrmComplexMapQuickView.VisitWellCandidate(
AWellCandidate: TIDObject);
begin
end;
end.
|
unit UDisplacement;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Math;
type
TFloatPoint = record
x: extended;
y: extended;
end;
TDisplacement = class
public
AZoom: extended;
DPoint: TFloatPoint;
MainFormSize: TFloatPoint;
CenterDisplace: TFloatPoint;
MaxFloatPoint, MinFloatPoint: TFloatPoint;
function ToIntCoords(Point: TFloatPoint): TPoint;
function ToFloatCoords(Point: TPoint): TFloatPoint;
procedure ToShift(x, y: extended);
procedure ShowAll(Width, Height: double);
procedure ComboBoxZoom(Zoom: extended);
end;
var
Displacement: TDisplacement;
implementation
function TDisplacement.ToIntCoords(Point: TFloatPoint): TPoint;
begin
Result.X := round((point.X - CenterDisplace.X) * AZoom + MainFormSize.X);
Result.Y := round((point.Y - CenterDisplace.Y) * AZoom + MainFormSize.Y);
end;
procedure TDisplacement.ShowAll(Width, Height: double);
begin
ToShift(CenterDisplace.x - (MaxFloatPoint.x + MinFloatPoint.x) / 2,
CenterDisplace.y - (MaxFloatPoint.y + MinFloatPoint.y) / 2);
Azoom := min(Width / (MaxFloatPoint.x - MinFloatPoint.x), Height /
(MaxFloatPoint.y - MinFloatPoint.y));
end;
function TDisplacement.ToFloatCoords(Point: TPoint): TFloatPoint;
begin
Result.X := (point.X - MainFormSize.X) / AZoom + CenterDisplace.X;
Result.Y := (point.Y - MainFormSize.Y) / AZoom + CenterDisplace.y;
end;
procedure TDisplacement.ToShift(x, y: extended);
begin
CenterDisplace.x := CenterDisplace.x - x;
CenterDisplace.y := CenterDisplace.y - y;
end;
procedure TDisplacement.ComboBoxZoom(Zoom: extended);
begin
AZoom := zoom;
ToShift(CenterDisplace.x - (MaxFloatPoint.x + MinFloatPoint.x) / 2,
CenterDisplace.y - (MaxFloatPoint.y + MinFloatPoint.y) / 2);
end;
initialization
Displacement := TDisplacement.Create();
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.