text stringlengths 14 6.51M |
|---|
unit uEXIFDisplayControl;
interface
uses
Winapi.Windows,
System.Classes,
Vcl.Themes,
Vcl.Grids,
Vcl.ValEdit;
type
TEXIFDisplayControl = class(TValueListEditor)
private
procedure CalcRowHeight(Row: Integer);
protected
procedure DrawCell(ACol, ARow: Longint; ARect: TRect;
AState: TGridDrawState); override;
procedure Resize; override;
procedure ColWidthsChanged; override;
public
procedure UpdateRowsHeight;
end;
implementation
type
TValueListStringsEx = class(TValueListStrings);
procedure TEXIFDisplayControl.DrawCell(ACol, ARow: Integer; ARect: TRect;
AState: TGridDrawState);
var
Offset: Integer;
CellText: string;
ItemProp: TItemProp;
CRect, DrawRect: TRect;
begin
if DefaultDrawing then
begin
if (ACol = 0) and (ARow > FixedRows - 1) then
ItemProp := TValueListStringsEx(Strings).FindItemProp(ARow - FixedRows, False)
else
ItemProp := nil;
if (ItemProp <> nil) and (ItemProp.KeyDesc <> '') then
CellText := ItemProp.KeyDesc
else
CellText := Cells[ACol, ARow];
if StyleServices.Enabled then
Offset := 4
else
Offset := 2;
CRect := CellRect(ACol, ARow);
DrawRect := Rect(ARect.Left + Offset, ARect.Top + 2, CRect.Right, CRect.Bottom);
DrawText(Canvas.Handle,
PChar(CellText), Length(CellText), DrawRect,
DT_WORDBREAK or DT_PLOTTER or DT_NOPREFIX);
end;
end;
procedure TEXIFDisplayControl.Resize;
begin
inherited;
UpdateRowsHeight;
end;
procedure TEXIFDisplayControl.UpdateRowsHeight;
var
I: Integer;
begin
for I := 1 to RowCount - 1 do
CalcRowHeight(I);
end;
procedure TEXIFDisplayControl.ColWidthsChanged;
begin
inherited;
UpdateRowsHeight;
end;
procedure TEXIFDisplayControl.CalcRowHeight(Row: Integer);
var
J: Integer;
RowHeight, Offset: Integer;
S: string;
CRect, DrawRect: TRect;
begin
RowHeight := DefaultRowHeight;
for J := 0 to 1 do
begin
S := Cells[J, Row];
if StyleServices.Enabled then
Offset := 4
else
Offset := 2;
CRect := CellRect(J, Row);
DrawRect := Rect(CRect.Left + Offset, CRect.Top + 2, CRect.Right, CRect.Bottom);
DrawText(Canvas.Handle,
PChar(S), Length(S), DrawRect,
DT_WORDBREAK or DT_LEFT or DT_NOPREFIX or DT_CALCRECT );
if DrawRect.Height > RowHeight then
RowHeight := DrawRect.Height + 2 * 2;
end;
RowHeights[Row] := RowHeight;
end;
end.
|
//=============================================================================
// sgUtils.pas
//=============================================================================
//
// Extra String Utilities used for processing parts of SwinGame.
//
//
// Change History:
//
// Version 3.0:
// - 2010-02-17: David : Added ExtractAfterFirstDelim
// - 2010-02-04: Andrew : Renamed unit, added code to process lines of a text file
// - 2010-02-03: Andrew : Added ExtractFileAndPath
// - 2010-02-03: Aaron : Added SingleArrayToRange
// Added ZeroArray
// - 2010-02-02: Aaron : Added LongintArrayToRange
// - Earlier : Andrew : Various changes
//=============================================================================
unit sgSharedUtils;
interface
uses sgTypes, sgBackendTypes;
{$ifndef FPC} // Delphi land
function ExtractDelimited(index: integer; const value: string; delim: TSysCharSet): string;
{$endif}
function ExtractAfterFirstDelim(index: integer; const value: string; delim: Char): string;
function CountDelimiter(const value: String; delim: Char): Longint;
function CountDelimiterWithRanges(const value: String; delim: Char): Longint;
function ExtractDelimitedWithRanges(index: Longint; const value: String): String;
function ProcessRange(const valueIn: String): LongintArray;
function ProcessFloatRange(const valueIn: String): SingleArray;
function MyStrToInt(const str: String): Longint; overload;
function MyStrToInt(const str: String; allowEmpty: Boolean) : Longint; overload;
function MyStrToFloat( const str: String): Extended; overload;
function MyStrToFloat(const str: String; allowEmpty: Boolean) : Extended; overload;
function LongintArrayToRange(ints: LongintArray):String;
function SingleArrayToRange(singles: SingleArray):String;
function ExtractFileAndPath(const fullnameIn: String; out path, filename: String; allowNewFile: Boolean): Boolean;
procedure ZeroArray (var ints : LongintArray); overload;
procedure ZeroArray (var singles : SingleArray); overload;
procedure ZeroArray (var Ints : array of LongintArray); overload;
procedure ZeroArray (var singles : array of SingleArray); overload;
procedure MakeFalse (var visited: Array of Boolean);
function WithinRange(arrayLength : Integer; currentIndex : Integer) : Boolean;
//Checks if pointer is assigned, then raises a warning and exits
function CheckAssigned(const msg : String; ptr : Pointer): Boolean;
type
LineData = record
filename: String;
data: String;
lineNo: Longint;
end;
LineProcessor = procedure(const data: LineData; ptr: Pointer);
// This reads the lines of the passed in file, calling proc for each non comment line.
// the ptr is then passed to each line to allow custom data to be passed into the line processing
// procedure.
procedure ProcessLinesInFile(const filename: String; kind: ResourceKind; proc: LineProcessor; ptr: Pointer);
implementation
uses
SysUtils, Math, Classes, StrUtils,
sgShared, sgResources, sgTrace;
function WithinRange(arrayLength : Integer; currentIndex : Integer) : Boolean;
begin
result := (currentIndex >= 0) and (currentIndex < arrayLength);
end;
procedure ZeroArray (var ints : LongintArray); overload;
var
i: Longint;
begin
for i := low(ints) to high(ints) do
begin
ints[i] := 0;
end;
end;
procedure ZeroArray (var singles : SingleArray); overload;
var
i : Longint;
begin
for i := low(singles) to high(singles) do
begin
singles[i] := 0;
end;
end;
procedure ZeroArray (var singles : array of SingleArray); overload;
var
i : Longint;
begin
for i := low(singles) to high(singles) do
begin
ZeroArray(singles[i]);
end;
end;
procedure ZeroArray (var Ints : array of LongintArray); overload;
var
i : Longint;
begin
for i := low(Ints) to high(Ints) do
begin
ZeroArray(Ints[i]);
end;
end;
function SingleArrayToRange(singles: SingleArray):String;
var
i : Longint;
begin
result := '['+FloatToStr(singles[0]);
for i := low(singles)+1 to high(singles) do
begin
result+=','+FloatToStr(Singles[i]);
end;
result +=']';
end;
function LongintArrayToRange(ints: LongintArray):String;
var
i,temp:longint;
tempChanged : Boolean;
begin
result:= '';
temp :=0;
tempChanged := false;
if not assigned(ints) then exit;
result := '['+IntToStr(ints[0]);
for i := low(ints)+1 to high(ints) do
begin
//writeln(ints[0], ints[1]);
if (ints[i]-1) = (ints[i-1]) then
begin
if not tempChanged then temp := ints[i]
else if tempChanged then temp := ints[i];
tempChanged := true;
end
else if tempChanged then
begin
result += '-'+IntToStr(temp);
result += ','+IntToStr(ints[i]);
tempChanged := false;
temp := 0;
end
else if not tempChanged then result +=','+IntToStr(ints[i]);
end;
if tempChanged then
begin
result += '-'+IntToStr(temp);
tempChanged := false;
temp := 0;
end;
result += ']';
end;
function MyStrToInt(const str: String): Longint; overload;
begin
if Length(str) = 0 then result := 0
else result := StrToInt(Trim(str));
end;
function MyStrToInt(const str: String; allowEmpty: Boolean) : Longint; overload;
begin
if allowEmpty and (Length(str) = 0) then
begin
result := -1;
end
else if not TryStrToInt(str, result) then
begin
result := 0;
RaiseException('Value is not an integer : ' + str);
end
else if result < 0 then
begin
result := 0;
RaiseException('Value is not an integer : ' + str);
end;
end;
function MyStrToFloat(const str: String): Extended; overload;
begin
if Length(str) = 0 then result := 0
else result := StrToFloat(Trim(str));
end;
function MyStrToFloat(const str: String; allowEmpty: Boolean) : Extended; overload;
begin
if allowEmpty and (Length(str) = 0) then
begin
result := 0.0;
end
else if not TryStrToFloat(str, result) then
begin
result := 0;
RaiseException('Value is not a number : ' + str);
end;
end;
{$ifndef FPC}
// Delphi land
function ExtractDelimited(index: integer;const value: string; delim: TSysCharSet): string;
var
strs: TStrings;
begin
// Assumes that delim is [','] and uses simple commatext mode - better check
if delim <> [','] then
raise Exception.create('Internal SG bug using ExtractDelimited');
// okay - let a stringlist do the work
strs := TStringList.Create();
strs.CommaText := value;
if (index >= 0) and (index < strs.Count) then
result := strs.Strings[index - 1]
else
result := '';
// cleanup
strs.Free();
end;
{$else}
// proper ExtractDelimited provided by StrUtils
{$endif}
function ExtractAfterFirstDelim(index: integer;const value: string; delim: Char): string;
var
i: Integer;
begin
result := '';
for i := index+1 to CountDelimiter(value , delim)+1 do
begin
result += ExtractDelimited(i, value, [delim]);
if i <> CountDelimiter(value , delim)+1 then result += delim;
end;
end;
function ExtractDelimitedWithRanges(index: Longint;const value: String): String;
var
i, count, start: Longint;
inRange: Boolean;
begin
//SetLength(result, 0);
inRange := false;
result := '';
count := 1; //1 is the first index... not 0
// Find the start of this delimited range
for i := 1 to Length(value) do
begin
if count = index then break;
if (not inRange) and (value[i] = ',') then
count += 1
else if (inRange) and (value[i] = ']') then
inRange := false
else if (not inRange) and (value[i] = '[') then
inRange := true;
end;
if count <> index then exit;
inRange := false;
start := i;
for i := start to Length(value) do
begin
if (not inRange) and (value[i] = ',') then
break
else if (inRange) and (value[i] = ']') then
inRange := false
else if (not inRange) and (value[i] = '[') then
inRange := true;
result += value[i];
end;
end;
function CountDelimiter(const value: String; delim: Char): Longint;
var
i: Integer;
begin
result := 0;
for i := 1 to Length(value) do
begin
if value[i] = delim then
result := result + 1;
end;
end;
function CountDelimiterWithRanges(const value: String; delim: Char): Longint;
var
i: Integer;
inRange: Boolean;
begin
inRange := false;
result := 0;
for i := 1 to Length(value) do
begin
if (not inRange) and (value[i] = delim) then
result := result + 1
else if (value[i] = '[') then
inRange := true
else if (value[i] = ']') then
inRange := false;
end;
end;
function ProcessRange(const valueIn: String): LongintArray;
var
i, j, count, temp, lowPart, highPart, dashCount: Longint;
part, value: String;
procedure _AddToResult(val: Longint);
begin
SetLength(result, Length(result) + 1);
result[High(result)] := val;
end;
begin
value := Trim(valueIn);
SetLength(result, 0);
if (value[1] <> '[') or (value[Length(value)] <> ']') then
begin
// is number?
if TryStrToInt(value, temp) then
begin
SetLength(result, 1);
result[0] := temp;
end;
exit; //not a range?
end;
value := MidStr(value, 2, Length(value) - 2);
i := 0;
count := CountDelimiter(value, ',');
while i <= count do
begin
part := Trim(ExtractDelimited(i + 1, value, [',']));
if TryStrToInt(part, temp) then
begin
//just "a" so...
_AddToResult(temp);
end
else //Should be range
begin
dashCount := CountDelimiter(part, '-');
if (dashCount = 1) or ((dashCount = 2) and (part[1] <> '-')) then //a-b or a--b
lowPart := MyStrToInt(ExtractDelimited(1, part, ['-']))
else //assume -a...
lowPart := -MyStrToInt(ExtractDelimited(2, part, ['-']));
if (dashCount = 1) then //a-b
highPart := MyStrToInt(ExtractDelimited(2, part, ['-']))
else if (dashCount = 2) and (part[1] = '-') then //-a-b
highPart := MyStrToInt(ExtractDelimited(3, part, ['-']))
else if dashCount = 3 then //assume -a--b
highPart := -MyStrToInt(ExtractDelimited(4, part, ['-'])) //read last string
else if dashCount = 2 then //assume a--b
highPart := -MyStrToInt(ExtractDelimited(3, part, ['-']))
else
begin
RaiseException('Error in range.');
SetLength(result, 0);
exit;
end;
for j := 0 to abs(highPart - lowPart) do
begin
//lowPart + j * (-1 or +1)
_AddToResult(lowPart + (j * sign(highPart - lowPart)));
end;
end;
i := i + 1;
end;
end;
function ProcessFloatRange(const valueIn: String): SingleArray;
var
i, count : Longint;
temp: Extended;
part, value: String;
procedure _AddToResult(val: Single);
begin
SetLength(result, Length(result) + 1);
result[High(result)] := val;
end;
begin
value := Trim(valueIn);
SetLength(result, 0);
if (value[1] <> '[') or (value[Length(value)] <> ']') then
exit; //not a range
// Remove the [ and ]
value := MidStr(value, 2, Length(value) - 2);
i := 0;
count := CountDelimiter(value, ',');
while i <= count do
begin
part := Trim(ExtractDelimited(i + 1, value, [',']));
if TryStrToFloat(part, temp) then
begin
//just "123.45" so...
_AddToResult(temp);
end;
i := i + 1;
end;
end;
function ExtractFileAndPath(const fullnameIn: String; out path, filename: String; allowNewFile: Boolean): Boolean;
var
fullname: String;
begin
result := false;
fullname := ExpandFileName(fullnameIn);
if DirectoryExists(fullname) then
begin
// Directory only
path := IncludeTrailingPathDelimiter(fullname); // ensure it includes a directory delim at end
filename := '';
result := true;
end
else if FileExists(fullname) then
begin
// We have a file...
filename := ExtractFileName(fullname);
path := IncludeTrailingPathDelimiter(ExtractFilePath(fullname));
result := true;
end
else
begin
// Neither an existing file or directory... try new file in directory
if not allowNewFile then exit; // not allowed so exit
path := ExtractFilePath(fullname);
if not DirectoryExists(path) then exit; // directory does not exist
filename := ExtractFileName(fullname);
result := true;
end;
// WriteLn(path, filename);
end;
procedure MakeFalse(var visited: Array of Boolean);
var
i: Longint;
begin
for i := 0 to High(visited) do
begin
visited[i] := false;
end;
end;
procedure ProcessLinesInFile(const filename: String; kind: ResourceKind; proc: LineProcessor; ptr: Pointer);
var
path: String;
input: Text;
line: LineData;
begin
{$IFDEF TRACE}
TraceEnter('sgUtils', 'ProcessLinesInFile');
{$ENDIF}
if not assigned(proc) then exit;
path := FilenameToResource(filename, kind);
line.lineNo := 0;
if not FileExists(path) then begin RaiseWarning('Unable to load bundle.'); exit; end;
Assign(input, path);
Reset(input);
line.filename := filename;
try
try
while not EOF(input) do
begin
line.lineNo := line.lineNo + 1;
ReadLn(input, line.data);
if Length(line.data) = 0 then continue; //skip empty lines
line.data := Trim(line.data);
if MidStr(line.data,1,2) = '//' then continue; //skip lines starting with //
proc(line, ptr);
end;
except on e: Exception do
RaiseException('Error processing ' + filename + ' on line ' + IntToStr(line.lineNo) + ': ' + e.Message);
end;
finally
Close(input);
end;
{$IFDEF TRACE}
TraceExit('sgUtils', 'ProcessLinesInFile');
{$ENDIF}
end;
function CheckAssigned(const msg : String; ptr : Pointer): Boolean;
begin
result := true;
if not Assigned(ptr) then
begin
RaiseWarning(msg);
result := false;
exit;
end;
end;
end.
|
(********************************************************)
(* *)
(* Bare Game Library *)
(* http://www.baregame.org *)
(* 0.5.0.0 Released under the LGPL license 2013 *)
(* *)
(********************************************************)
{ <include docs/bare.animation.txt> }
unit Bare.Animation;
{$i bare.inc}
interface
{TODO: Convert animation and storyboard engine from old code base}
uses
Bare.System,
Bare.Types,
Bare.Geometry;
type
TEasing = function(Percent: Float): Float;
TEasingDefaults = record
public
class function Linear(Percent: Float): Float; static;
class function Easy(Percent: Float): Float; static;
class function EasySlow(Percent: Float): Float; static;
class function Extend(Percent: Float): Float; static;
class function Drop(Percent: Float): Float; static;
class function DropSlow(Percent: Float): Float; static;
class function Snap(Percent: Float): Float; static;
class function Bounce(Percent: Float): Float; static;
class function Bouncy(Percent: Float): Float; static;
class function Rubber(Percent: Float): Float; static;
class function Spring(Percent: Float): Float; static;
class function Boing(Percent: Float): Float; static;
end;
TEasings = class(TDictionary<string, TEasing>)
public
procedure RegisterDefaults;
end;
TEasingItem = TEasings.TKeyValue;
function Easings: TEasings;
function Interpolate(Easing: TEasing; Percent: Float; Reverse: Boolean = False): Float;
{ Dependency property related types and routines }
type
IDependencyProperty = interface
['{E021AD95-9985-48AB-B29F-8D25A7BBE10E}']
function GetCount: Integer;
function GetValue(Index: Integer): Float;
procedure SetValue(Value: Float; Index: Integer);
property Count: Integer read GetCount;
end;
TDependencyChangeNotify = procedure(Prop: IDependencyProperty; Index: Integer) of object;
{ Properties }
TVec1Prop = record
private
function GetValue: TVec1;
procedure SetValue(Value: TVec1);
function GetVec(Index: Integer): TVec1Prop;
procedure SetVec(Index: Integer; const Value: TVec1Prop);
function GetLength: Integer;
function GetProp: IDependencyProperty; inline;
function GetIndex: LongInt;
public
class operator Implicit(const Value: TVec1): TVec1Prop;
class operator Implicit(const Value: TVec1Prop): TVec1;
class operator Negative(const A: TVec1Prop): TVec1;
class operator Positive(const A: TVec1Prop): TVec1;
class operator Equal(const A, B: TVec1Prop) : Boolean;
class operator NotEqual(const A, B: TVec1Prop): Boolean;
class operator GreaterThan(const A, B: TVec1Prop): Boolean;
class operator GreaterThanOrEqual(const A, B: TVec1Prop): Boolean;
class operator LessThan(const A, B: TVec1Prop): Boolean;
class operator LessThanOrEqual(const A, B: TVec1Prop): Boolean;
class operator Add(const A, B: TVec1Prop): TVec1;
class operator Subtract(const A, B: TVec1Prop): TVec1;
class operator Multiply(const A, B: TVec1Prop): TVec1;
class operator Divide(const A, B: TVec1Prop): TVec1;
class function Create(OnChange: TDependencyChangeNotify = nil): TVec1Prop; overload; static;
class function Create(Prop: IDependencyProperty; Index: LongInt): TVec1Prop; static;
function Equals(const A: TVec1Prop): Boolean;
function Same(const A: TVec1Prop): Boolean;
property X: TVec1Prop index 0 read GetVec write SetVec;
property Value: TVec1 read GetValue write SetValue;
property Vec[Index: Integer]: TVec1Prop read GetVec write SetVec;
property Length: LongInt read GetLength;
property Prop: IDependencyProperty read GetProp;
property Index: LongInt read GetIndex;
private
FProp: IDependencyProperty;
case Boolean of
True: (FIndex: LongInt);
False: (FValue: TVec1);
end;
TVec2Prop = record
private
function GetValue: TVec2;
procedure SetValue(const Value: TVec2);
function GetVec(Index: Integer): TVec1Prop;
procedure SetVec(Index: Integer; const Value: TVec1Prop);
function GetLength: Integer;
function GetProp: IDependencyProperty; inline;
function GetIndex: LongInt;
public
class operator Implicit(const Value: TVec2Prop): TVec2;
class operator Implicit(const Value: TVec2): TVec2Prop;
class operator Implicit(const Value: TPoint): TVec2Prop;
class operator Explicit(const Value: TVec2Prop): TPoint;
class operator Implicit(const Value: TPointI): TVec2Prop;
class operator Explicit(const Value: TVec2Prop): TPointI;
class operator Implicit(const Value: TPointF): TVec2Prop;
class operator Implicit(const Value: TVec2Prop): TPointF;
class function Create(OnChange: TDependencyChangeNotify = nil): TVec2Prop; overload; static;
class function Create(Prop: IDependencyProperty; Index: LongInt): TVec2Prop; overload; static;
property X: TVec1Prop index 0 read GetVec write SetVec;
property Y: TVec1Prop index 1 read GetVec write SetVec;
property AsVec1: TVec1Prop index 0 read GetVec write SetVec;
property Value: TVec2 read GetValue write SetValue;
property Vec[Index: Integer]: TVec1Prop read GetVec write SetVec;
property Length: LongInt read GetLength;
property Prop: IDependencyProperty read GetProp;
property Index: LongInt read GetIndex;
private
FProp: IDependencyProperty;
case Boolean of
True: (FIndex: LongInt);
False: (FValue: TVec2);
end;
TVec3Prop = record
private
function GetValue: TVec3;
procedure SetValue(const Value: TVec3);
function GetVec(Index: Integer): TVec1Prop;
procedure SetVec(Index: Integer; const Value: TVec1Prop);
function GetAsVec2: TVec2Prop;
procedure SetAsVec2(const Value: TVec2Prop);
function GetLength: Integer;
function GetProp: IDependencyProperty; inline;
function GetIndex: LongInt;
public
class operator Implicit(const Value: TVec3Prop): TVec3;
class operator Implicit(const Value: TVec3): TVec3Prop;
class function Create(OnChange: TDependencyChangeNotify = nil): TVec3Prop; overload; static;
class function Create(Prop: IDependencyProperty; Index: LongInt): TVec3Prop; overload; static;
property X: TVec1Prop index 0 read GetVec write SetVec;
property Y: TVec1Prop index 1 read GetVec write SetVec;
property Z: TVec1Prop index 2 read GetVec write SetVec;
property Heading: TVec1Prop index 0 read GetVec write SetVec;
property Pitch: TVec1Prop index 1 read GetVec write SetVec;
property Roll: TVec1Prop index 2 read GetVec write SetVec;
property AsVec1: TVec1Prop index 0 read GetVec write SetVec;
property AsVec2: TVec2Prop read GetAsVec2 write SetAsVec2;
property Value: TVec3 read GetValue write SetValue;
property Vec[Index: Integer]: TVec1Prop read GetVec write SetVec;
property Length: LongInt read GetLength;
property Prop: IDependencyProperty read GetProp;
property Index: LongInt read GetIndex;
private
FProp: IDependencyProperty;
case Boolean of
True: (FIndex: LongInt);
False: (FValue: TVec3);
end;
TVec4Prop = record
private
function GetValue: TVec4;
procedure SetValue(const Value: TVec4);
function GetVec(Index: Integer): TVec1Prop;
procedure SetVec(Index: Integer; const Value: TVec1Prop);
function GetAsVec2: TVec2Prop;
procedure SetAsVec2(const Value: TVec2Prop);
function GetAsVec3: TVec3Prop;
procedure SetAsVec3(const Value: TVec3Prop);
function GetLength: Integer;
function GetProp: IDependencyProperty; inline;
function GetIndex: LongInt;
public
class operator Implicit(const Value: TVec4): TVec4Prop;
class operator Implicit(const Value: TVec4Prop): TVec4;
class operator Implicit(Value: TColorB): TVec4Prop;
class operator Explicit(const Value: TVec4Prop): TColorB;
class operator Implicit(const Value: TColorF): TVec4Prop;
class operator Implicit(const Value: TVec4Prop): TColorF;
class function Create(OnChange: TDependencyChangeNotify = nil): TVec4Prop; overload; static;
class function Create(Prop: IDependencyProperty; Index: LongInt): TVec4Prop; overload; static;
property X: TVec1Prop index 0 read GetVec write SetVec;
property Y: TVec1Prop index 1 read GetVec write SetVec;
property Z: TVec1Prop index 2 read GetVec write SetVec;
property W: TVec1Prop index 3 read GetVec write SetVec;
property Blue: TVec1Prop index 0 read GetVec write SetVec;
property Green: TVec1Prop index 1 read GetVec write SetVec;
property Red: TVec1Prop index 2 read GetVec write SetVec;
property Alpha: TVec1Prop index 3 read GetVec write SetVec;
property S0: TVec1Prop index 0 read GetVec write SetVec;
property T0: TVec1Prop index 1 read GetVec write SetVec;
property S1: TVec1Prop index 2 read GetVec write SetVec;
property T1: TVec1Prop index 3 read GetVec write SetVec;
property AsVec1: TVec1Prop index 0 read GetVec write SetVec;
property AsVec2: TVec2Prop read GetAsVec2 write SetAsVec2;
property AsVec3: TVec3Prop read GetAsVec3 write SetAsVec3;
property Value: TVec4 read GetValue write SetValue;
property Vec[Index: Integer]: TVec1Prop read GetVec write SetVec;
property Length: LongInt read GetLength;
property Prop: IDependencyProperty read GetProp;
property Index: LongInt read GetIndex;
private
FProp: IDependencyProperty;
case Boolean of
True: (FIndex: LongInt);
False: (FValue: TVec4);
end;
procedure DependencyLink(var Prop: IDependencyProperty; Count: Integer; OnChange: TDependencyChangeNotify);
procedure DependencyUnlink(var Prop: IDependencyProperty);
implementation
const
NegCosPi = 1.61803398874989; { 2 / -Cos(Pi * 1.2) }
class function TEasingDefaults.Linear(Percent: Float): Float;
begin
Result := Percent;
end;
class function TEasingDefaults.Easy(Percent: Float): Float;
begin
Result := Percent * Percent * (3 - 2 * Percent);
end;
class function TEasingDefaults.EasySlow(Percent: Float): Float;
begin
Percent := Easy(Percent);
Result := Percent * Percent * (3 - 2 * Percent);
end;
class function TEasingDefaults.Extend(Percent: Float): Float;
begin
Percent := (Percent * 1.4) - 0.2;
Result := 0.5 - Cos(Pi * Percent) / NegCosPi;
end;
class function Power(const Base, Exponent: Float): Float;
begin
if Exponent = 0 then
Result := 1
else if (Base = 0) and (Exponent > 0) then
Result := 0
else
Result := Exp(Exponent * Ln(Base));
end;
class function TEasingDefaults.Drop(Percent: Float): Float;
begin
Result := Percent * Percent;
end;
class function TEasingDefaults.DropSlow(Percent: Float): Float;
begin
Result := Percent * Percent * Percent;
end;
class function TEasingDefaults.Snap(Percent: Float): Float;
begin
Percent := Percent * Percent;
Percent := (Percent * 1.4) - 0.2;
Result := 0.5 - Cos(Pi * Percent) / NegCosPi;
end;
class function TEasingDefaults.Bounce(Percent: Float): Float;
begin
if Percent > 0.9 then
begin
Result := Percent - 0.95;
Result := 1 + Result * Result * 20 - (0.05 * 0.05 * 20);
end
else if Percent > 0.75 then
begin
Result := Percent - 0.825;
Result := 1 + Result * Result * 16 - (0.075 * 0.075 * 16);
end
else if Percent > 0.5 then
begin
Result := Percent - 0.625;
Result := 1 + Result * Result * 12 - (0.125 * 0.125 * 12);
end
else
begin
Percent := Percent * 2;
Result := Percent * Percent;
end;
end;
class function TEasingDefaults.Bouncy(Percent: Float): Float;
var
Scale, Start, Step: Float;
begin
Result := 1;
Scale := 5;
Start := 0.5;
Step := 0.2;
if Percent < Start then
begin
Result := Percent / Start;
Result := Result * Result;
end
else
while Step > 0.01 do
if Percent < Start + Step then
begin
Step := Step / 2;
Result := (Percent - (Start + Step)) * Scale;
Result := Result * Result;
Result := Result + 1 - Power(Step * Scale, 2);
Break;
end
else
begin
Start := Start + Step;
Step := Step * 0.6;
end;
end;
class function TEasingDefaults.Rubber(Percent: Float): Float;
begin
if Percent > 0.9 then
begin
Result := Percent - 0.95;
Result := 1 - Result * Result * 20 + (0.05 * 0.05 * 20);
end
else if Percent > 0.75 then
begin
Result := Percent - 0.825;
Result := 1 + Result * Result * 18 - (0.075 * 0.075 * 18);
end
else if Percent > 0.5 then
begin
Result := Percent - 0.625;
Result := 1 - Result * Result * 14 + (0.125 * 0.125 * 14);
end
else
begin
Percent := Percent * 2;
Result := Percent * Percent;
end;
end;
class function TEasingDefaults.Spring(Percent: Float): Float;
begin
Percent := Percent * Percent;
Result := Sin(PI * Percent * Percent * 10 - PI / 2) / 4;
Result := Result * (1 - Percent) + 1;
if Percent < 0.3 then
Result := Result * Easy(Percent / 0.3);
end;
class function TEasingDefaults.Boing(Percent: Float): Float;
begin
Percent := Power(Percent, 1.5);
Result := Sin(PI * Power(Percent, 2) * 20 - PI / 2) / 4;
Result := Result * (1 - Percent) + 1;
if Percent < 0.2 then
Result := Result * Easy(Percent / 0.2);
end;
procedure TEasings.RegisterDefaults;
begin
Self['Linear'] := @TEasingDefaults.Linear;
Self['Easy'] := @TEasingDefaults.Easy;
Self['Easy Slow'] := @TEasingDefaults.EasySlow;
Self['Extend'] := @TEasingDefaults.Extend;
Self['Drop'] := @TEasingDefaults.Drop;
Self['Drop Slow'] := @TEasingDefaults.DropSlow;
Self['Snap'] := @TEasingDefaults.Snap;
Self['Bounce'] := @TEasingDefaults.Bounce;
Self['Bouncy'] := @TEasingDefaults.Bouncy;
Self['Rubber'] := @TEasingDefaults.Rubber;
Self['Spring'] := @TEasingDefaults.Spring;
Self['Boing'] := @TEasingDefaults.Boing;
end;
var
EasingsInstance: TObject;
function EasingKeyCompare(const A, B: AnsiString): Integer;
begin
Result := StrCompare(A, B, True);
end;
function Easings: TEasings;
begin
if EasingsInstance = nil then
begin
EasingsInstance := TEasings.Create;
TEasings(EasingsInstance).Comparer := EasingKeyCompare;
end;
Result := TEasings(EasingsInstance);
end;
function Interpolate(Easing: TEasing; Percent: Float; Reverse: Boolean = False): Float;
begin
if Reverse then
Result := 1 - Easing(1 - Percent)
else
Result := Easing(Percent);
end;
{ TVec1Prop }
class operator TVec1Prop.Implicit(const Value: TVec1Prop): TVec1;
begin
Result := Value.Value;
end;
class operator TVec1Prop.Implicit(const Value: TVec1): TVec1Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FIndex := 0;
Result.FValue := Value;
end;
class operator TVec1Prop.Negative(const A: TVec1Prop): TVec1;
begin
Result := -A.Value;
end;
class operator TVec1Prop.Positive(const A: TVec1Prop): TVec1;
begin
Result := A.Value;
end;
class operator TVec1Prop.Equal(const A, B: TVec1Prop) : Boolean;
begin
Result := A.Value = B.Value;
end;
class operator TVec1Prop.NotEqual(const A, B: TVec1Prop): Boolean;
begin
Result := A.Value <> B.Value;
end;
class operator TVec1Prop.GreaterThan(const A, B: TVec1Prop): Boolean;
begin
Result := A.Value > B.Value;
end;
class operator TVec1Prop.GreaterThanOrEqual(const A, B: TVec1Prop): Boolean;
begin
Result := A.Value >= B.Value;
end;
class operator TVec1Prop.LessThan(const A, B: TVec1Prop): Boolean;
begin
Result := A.Value < B.Value;
end;
class operator TVec1Prop.LessThanOrEqual(const A, B: TVec1Prop): Boolean;
begin
Result := A.Value <= B.Value;
end;
class operator TVec1Prop.Add(const A, B: TVec1Prop): TVec1;
begin
Result := A.Value + B.Value;
end;
class operator TVec1Prop.Subtract(const A, B: TVec1Prop): TVec1;
begin
Result := A.Value - B.Value;
end;
class operator TVec1Prop.Multiply(const A, B: TVec1Prop): TVec1;
begin
Result := A.Value * B.Value;
end;
class operator TVec1Prop.Divide(const A, B: TVec1Prop): TVec1;
begin
Result := A.Value / B.Value;
end;
class function TVec1Prop.Create(OnChange: TDependencyChangeNotify = nil): TVec1Prop;
var
V: TVec1Prop;
begin
UIntPtr(V.FProp) := 0;
DependencyLink(V.FProp, 1, OnChange);
V.FIndex := 0;
Exit(V);
end;
{
var
V: TVec1Prop;
begin
//UIntPtr(V.FProp) := 0;
V.FProp := Prop;
V.FIndex := Index;
Exit(V);
end;
}
class function TVec1Prop.Create(Prop: IDependencyProperty; Index: LongInt): TVec1Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FProp := Prop;
Result.FIndex := Index;
end;
function TVec1Prop.Equals(const A: TVec1Prop): Boolean;
begin
Result := Value = A.Value;
end;
function TVec1Prop.Same(const A: TVec1Prop): Boolean;
begin
if FProp = nil then
Result := False
else if FProp = A.FProp then
Result := FIndex = A.FIndex
else
Result := False;
end;
function TVec1Prop.GetValue: TVec1;
begin
if FProp = nil then
Result := FValue
else
Result := FProp.GetValue(FIndex);
end;
procedure TVec1Prop.SetValue(Value: TVec1);
begin
if FProp = nil then
FValue := Value
else
FProp.SetValue(Value, FIndex);
end;
function TVec1Prop.GetVec(Index: Integer): TVec1Prop;
begin
Exit(Self);
end;
procedure TVec1Prop.SetVec(Index: Integer; const Value: TVec1Prop);
begin
if not Same(Value) then
SetValue(Value.Value);
end;
function TVec1Prop.GetLength: Integer;
begin
Result := 1;
end;
function TVec1Prop.GetProp: IDependencyProperty;
begin
Result := FProp;
end;
function TVec1Prop.GetIndex: LongInt;
begin
if FProp = nil then
Result := FIndex
else
Result := -1;
end;
{ TVec2Prop }
class operator TVec2Prop.Implicit(const Value: TVec2Prop): TVec2;
begin
Result := Value.Value;
end;
class operator TVec2Prop.Implicit(const Value: TVec2): TVec2Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FIndex := 0;
Result.FValue := Value;
end;
class operator TVec2Prop.Implicit(const Value: TPoint): TVec2Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FValue.X := Value.X;
Result.FValue.Y := Value.Y;
end;
class operator TVec2Prop.Explicit(const Value: TVec2Prop): TPoint;
var
V: TVec2;
begin
V := Value.Value;
Result.X := Round(V.X);
Result.Y := Round(V.Y);
end;
class operator TVec2Prop.Implicit(const Value: TPointI): TVec2Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FValue.X := Value.X;
Result.FValue.Y := Value.Y;
end;
class operator TVec2Prop.Explicit(const Value: TVec2Prop): TPointI;
var
V: TVec2;
begin
V := Value.Value;
Result.X := Round(V.X);
Result.Y := Round(V.Y);
end;
class operator TVec2Prop.Implicit(const Value: TPointF): TVec2Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FValue.X := Value.X;
Result.FValue.Y := Value.Y;
end;
class operator TVec2Prop.Implicit(const Value: TVec2Prop): TPointF;
var
V: TVec2;
begin
V := Value.Value;
Result.X := V.X;
Result.Y := V.Y;
end;
class function TVec2Prop.Create(OnChange: TDependencyChangeNotify = nil): TVec2Prop; overload; static;
var
V: TVec2Prop;
begin
UIntPtr(V.FProp) := 0;
DependencyLink(V.FProp, 2, OnChange);
V.FIndex := 0;
Exit(V);
end;
class function TVec2Prop.Create(Prop: IDependencyProperty; Index: LongInt): TVec2Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FProp := Prop;
Result.FIndex := Index;
end;
function TVec2Prop.GetValue: TVec2;
begin
if FProp = nil then
Result := FValue
else
begin
Result.X := FProp.GetValue(FIndex);
Result.Y := FProp.GetValue(FIndex + 1);
end;
end;
procedure TVec2Prop.SetValue(const Value: TVec2);
begin
if FProp = nil then
FValue := Value
else
begin
FProp.SetValue(Value.X, FIndex);
FProp.SetValue(Value.Y, FIndex + 1);
end;
end;
function TVec2Prop.GetVec(Index: Integer): TVec1Prop;
var
V: TVec1Prop;
begin
UIntPtr(V.FProp) := 0;
if FProp = nil then
begin
if Index < 1 then
V.FValue := FValue.X
else
V.FValue := FValue.Y;
end
else
begin
V.FProp := FProp;
if Index < 1 then
V.FIndex := FIndex
else
V.FIndex := FIndex + 1;
end;
Exit(V);
end;
procedure TVec2Prop.SetVec(Index: Integer; const Value: TVec1Prop);
begin
if FProp = nil then
begin
FProp := nil;
if Index < 1 then
FValue.X := Value.Value
else
FValue.Y := Value.Value;
end
else
begin
if Index < 1 then
FProp.SetValue(Value.Value, FIndex)
else
FProp.SetValue(Value.Value, FIndex + 1);
end;
end;
function TVec2Prop.GetLength: Integer;
begin
Result := 2;
end;
function TVec2Prop.GetProp: IDependencyProperty;
begin
Result := FProp;
end;
function TVec2Prop.GetIndex: LongInt;
begin
if FProp = nil then
Result := FIndex
else
Result := -1;
end;
{ TVec3Prop }
class operator TVec3Prop.Implicit(const Value: TVec3): TVec3Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FIndex := 0;
Result.FValue := Value;
end;
class operator TVec3Prop.Implicit(const Value: TVec3Prop): TVec3;
begin
Result := Value.Value;
end;
class function TVec3Prop.Create(OnChange: TDependencyChangeNotify = nil): TVec3Prop;
var
V: TVec3Prop;
begin
UIntPtr(V.FProp) := 0;
DependencyLink(V.FProp, 3, OnChange);
V.FIndex := 0;
Exit(V);
end;
class function TVec3Prop.Create(Prop: IDependencyProperty; Index: LongInt): TVec3Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FProp := Prop;
Result.FIndex := Index;
end;
function TVec3Prop.GetValue: TVec3;
begin
if FProp = nil then
Result := FValue
else
begin
Result.X := FProp.GetValue(FIndex);
Result.Y := FProp.GetValue(FIndex + 1);
Result.Z := FProp.GetValue(FIndex + 2);
end;
end;
procedure TVec3Prop.SetValue(const Value: TVec3);
begin
if FProp = nil then
FValue := Value
else
begin
FProp.SetValue(Value.X, FIndex);
FProp.SetValue(Value.Y, FIndex + 1);
end;
end;
function TVec3Prop.GetVec(Index: Integer): TVec1Prop;
var
V: TVec1Prop;
begin
UIntPtr(V.FProp) := 0;
if FProp = nil then
begin
if Index < 1 then
V.FValue := FValue.X
else if Index < 2 then
V.FValue := FValue.Y
else
V.FValue := FValue.Z;
end
else
begin
V.FProp := FProp;
if Index < 1 then
V.FIndex := FIndex
else if Index < 2 then
V.FIndex := FIndex + 1
else
V.FIndex := FIndex + 2;
end;
Exit(V);
end;
procedure TVec3Prop.SetVec(Index: Integer; const Value: TVec1Prop);
begin
if FProp = nil then
begin
FProp := nil;
if Index < 1 then
FValue.X := Value.Value
else if Index < 2 then
FValue.Y := Value.Value
else
FValue.Z := Value.Value;
end
else
begin
if Index < 1 then
FProp.SetValue(Value.Value, FIndex)
else if Index < 2 then
FProp.SetValue(Value.Value, FIndex + 1)
else
FProp.SetValue(Value.Value, FIndex + 2);
end;
end;
function TVec3Prop.GetAsVec2: TVec2Prop;
begin
Result := TVec2Prop.Create(FProp, 0);
end;
procedure TVec3Prop.SetAsVec2(const Value: TVec2Prop);
var
V: TVec2;
begin
V := Value.Value;
X := V.X;
Y := V.Y;
end;
function TVec3Prop.GetLength: Integer;
begin
Result := 3;
end;
function TVec3Prop.GetProp: IDependencyProperty;
begin
Result := FProp;
end;
function TVec3Prop.GetIndex: LongInt;
begin
if FProp = nil then
Result := FIndex
else
Result := -1;
end;
{ TVec4Prop }
class operator TVec4Prop.Implicit(const Value: TVec4): TVec4Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FIndex := 0;
Result.FValue := Value;
end;
class operator TVec4Prop.Implicit(const Value: TVec4Prop): TVec4;
begin
Result := Value.Value;
end;
class operator TVec4Prop.Implicit(Value: TColorB): TVec4Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FValue := Value;
end;
class operator TVec4Prop.Explicit(const Value: TVec4Prop): TColorB;
begin
Result := TColorB(Value.Value);
end;
class operator TVec4Prop.Implicit(const Value: TColorF): TVec4Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FValue := TVec4(Value);
end;
class operator TVec4Prop.Implicit(const Value: TVec4Prop): TColorF;
begin
Result := TColorF(Value.Value);
end;
class function TVec4Prop.Create(OnChange: TDependencyChangeNotify = nil): TVec4Prop;
var
V: TVec4Prop;
begin
UIntPtr(V.FProp) := 0;
DependencyLink(V.FProp, 4, OnChange);
V.FIndex := 0;
Exit(V);
end;
class function TVec4Prop.Create(Prop: IDependencyProperty; Index: LongInt): TVec4Prop;
begin
UIntPtr(Result.FProp) := 0;
Result.FProp := Prop;
Result.FIndex := Index;
end;
function TVec4Prop.GetValue: TVec4;
begin
if FProp = nil then
Result := FValue
else
begin
Result.X := FProp.GetValue(FIndex);
Result.Y := FProp.GetValue(FIndex + 1);
Result.Z := FProp.GetValue(FIndex + 2);
Result.W := FProp.GetValue(FIndex + 3);
end;
end;
procedure TVec4Prop.SetValue(const Value: TVec4);
begin
if FProp = nil then
FValue := Value
else
begin
FProp.SetValue(Value.X, FIndex);
FProp.SetValue(Value.Y, FIndex + 1);
FProp.SetValue(Value.Z, FIndex + 2);
FProp.SetValue(Value.W, FIndex + 3);
end;
end;
function TVec4Prop.GetVec(Index: Integer): TVec1Prop;
var
V: TVec1Prop;
begin
UIntPtr(V.FProp) := 0;
if FProp = nil then
begin
if Index < 1 then
V.FValue := FValue.X
else if Index < 2 then
V.FValue := FValue.Y
else if Index < 3 then
V.FValue := FValue.Z
else
V.FValue := FValue.W;
end
else
begin
V.FProp := FProp;
if Index < 1 then
V.FIndex := FIndex
else if Index < 2 then
V.FIndex := FIndex + 1
else if Index < 3 then
V.FIndex := FIndex + 2
else
V.FIndex := FIndex + 3;
end;
Exit(V);
end;
procedure TVec4Prop.SetVec(Index: Integer; const Value: TVec1Prop);
begin
if FProp = nil then
begin
FProp := nil;
if Index < 1 then
FValue.X := Value.Value
else if Index < 2 then
FValue.Y := Value.Value
else if Index < 3 then
FValue.Z := Value.Value
else
FValue.W := Value.Value;
end
else
begin
if Index < 1 then
FProp.SetValue(Value.Value, FIndex)
else if Index < 2 then
FProp.SetValue(Value.Value, FIndex + 1)
else if Index < 3 then
FProp.SetValue(Value.Value, FIndex + 2)
else
FProp.SetValue(Value.Value, FIndex + 3);
end;
end;
function TVec4Prop.GetAsVec2: TVec2Prop;
begin
Result := TVec2Prop.Create(FProp, 0);
end;
procedure TVec4Prop.SetAsVec2(const Value: TVec2Prop);
var
V: TVec2;
begin
V := Value.Value;
X := V.X;
Y := V.Y;
end;
function TVec4Prop.GetAsVec3: TVec3Prop;
begin
Result := TVec3Prop.Create(FProp, 0);
end;
procedure TVec4Prop.SetAsVec3(const Value: TVec3Prop);
var
V: TVec3;
begin
V := Value.Value;
X := V.X;
Y := V.Y;
Z := V.Z;
end;
function TVec4Prop.GetLength: Integer;
begin
Result := 4;
end;
function TVec4Prop.GetProp: IDependencyProperty;
begin
Result := FProp;
end;
function TVec4Prop.GetIndex: LongInt;
begin
if FProp = nil then
Result := FIndex
else
Result := -1;
end;
{ TDependencyProperty }
type
TPropertyValues = array of Float;
TDependencyProperty = class(TInterfacedObject, IDependencyProperty)
private
FValues: TPropertyValues;
FOnChange: TDependencyChangeNotify;
public
function GetCount: Integer;
function GetValue(Index: Integer): Float;
procedure SetValue(Value: Float; Index: Integer);
end;
function TDependencyProperty.GetCount: Integer;
begin
Result := Length(FValues);
end;
function TDependencyProperty.GetValue(Index: Integer): Float;
begin
Result := FValues[Index];
end;
procedure TDependencyProperty.SetValue(Value: Float; Index: Integer);
begin
if FValues[Index] <> Value then
begin
FValues[Index] := Value;
if Assigned(FOnChange) then
FOnChange(Self, Index);
end;
end;
procedure DependencyLink(var Prop: IDependencyProperty; Count: Integer; OnChange: TDependencyChangeNotify);
var
Dependency: TDependencyProperty;
begin
if Prop = nil then
Dependency := TDependencyProperty.Create
else
Dependency := Prop as TDependencyProperty;
SetLength(Dependency.FValues, Count);
Dependency.FOnChange := OnChange;
Prop := Dependency;
end;
procedure DependencyUnlink(var Prop: IDependencyProperty);
var
Dependency: TDependencyProperty;
begin
if Prop = nil then
Exit;
Dependency := Prop as TDependencyProperty;
Dependency.FOnChange := nil;
Prop := nil;
end;
finalization
EasingsInstance.Free;
end.
|
unit templateactns;
{$mode objfpc}{$H+}
interface
uses
BrookAction, RUtils, path;
type
{ TTemplateAction }
TTemplateAction = class(TBrookAction)
private
FTitle: string;
public
procedure Show(const AName: string; const AArgs: array of const);
procedure Show(const AName: string);
property Title: string read FTitle write FTitle;
end;
implementation
{ TTemplateAction }
procedure TTemplateAction.Show(const AName: string;
const AArgs: array of const);
begin
Write(RUtils.FileToStr(path.TPL_DIR + 'header.html'), [Title]);
Write(RUtils.FileToStr(path.TPL_DIR + AName + '.html'), AArgs);
Write(RUtils.FileToStr(path.TPL_DIR + 'footer.html'));
end;
procedure TTemplateAction.Show(const AName: string);
begin
Show(AName, []);
end;
end.
|
unit fre_openssl_interface;
{
(§LIC)
(c) Autor,Copyright Dipl.Ing.- Helmut Hartl
FirmOS Business Solutions GmbH
New Style BSD Licence (OSI)
Copyright (c) 2001-2013, FirmOS Business Solutions GmbH
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 the <FirmOS Business Solutions GmbH> 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.
(§LIC_END)
}
interface
{$MODE objfpc} {$H+}
{$interfaces corba}
{$modeswitch nestedprocvars}
{$codepage UTF8}
uses Classes,Sysutils,fre_db_interface,fos_tool_interfaces;
type
TFRE_SSL_RESULT = (sslOK,sslNOK);
RFRE_CA_BASEINFORMATION = record
index : TFRE_DB_RawByteString;
index_attr : TFRE_DB_RawByteString;
serial : TFRE_DB_RawByteString;
crlnumber : TFRE_DB_RawByteString;
crl : TFRE_DB_RawByteString;
crt : TFRE_DB_RawByteString;
key : TFRE_DB_RawByteString;
random : TFRE_DB_RawByteString;
end;
RFRE_CRT_BASEINFORMATION = record
crt : TFRE_DB_RawByteString;
key : TFRE_DB_RawByteString;
end;
{ IFRE_SSL }
IFRE_SSL=interface
function CreateCA (const cn,c,st,l,o,ou,email:string; const ca_pass:string; out ca_base_information:RFRE_CA_BASEINFORMATION) : TFRE_SSL_RESULT;
function CreateCrt (const cn,c,st,l,o,ou,email:string; const ca_pass:string; var ca_base_information:RFRE_CA_BASEINFORMATION; const server:boolean; out crt_base_information: RFRE_CRT_BASEINFORMATION ) : TFRE_SSL_RESULT;
function RevokeCrt (const cn:string;const ca_pass:string; const crt:string; var ca_base_information:RFRE_CA_BASEINFORMATION) : TFRE_SSL_RESULT;
function ReadCrtInformation (const crt: string; out cn,c,st,l,o,ou,email:string; out issued_date,end_date:TFRE_DB_DateTime64) : TFRE_SSL_RESULT;
end;
function GET_SSL_IF : IFRE_SSL;
procedure Setup_SSL_IF(const sslif : IFRE_SSL);
var
SSL_IF_VERSION:string='1.0';
implementation
var
PRIVATE_FRE_SSL : IFRE_SSL;
function GET_SSL_IF: IFRE_SSL;
begin
if not assigned(PRIVATE_FRE_SSL) then
raise EFRE_DB_Exception.Create(edb_ERROR,'no assigned SSL interface');
result := PRIVATE_FRE_SSL;
end;
procedure Setup_SSL_IF(const sslif: IFRE_SSL);
begin
if assigned(sslif) and assigned(PRIVATE_FRE_SSL) then
raise EFRE_DB_Exception.Create(edb_ERROR,'double assigned SSL interface');
PRIVATE_FRE_SSL := sslif;
end;
end.
|
unit Design;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
DesignController, DesignSurface, DesignManager;
type
TDesignForm = class(TForm)
DesignController1: TDesignController;
procedure FormPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure DesignController1Change(Sender: TObject);
procedure DesignController1SelectionChange(Sender: TObject);
procedure DesignController1GetAddClass(Sender: TObject;
var ioClass: String);
private
{ Private declarations }
FOnChange: TNotifyEvent;
protected
function GetActive: Boolean;
procedure CreateParams(var Params: TCreateParams); override;
procedure PropertyChange(Sender: TObject);
procedure ReaderError(Reader: TReader; const Message: string;
var Handled: Boolean);
procedure SelectionChange(Sender: TObject);
procedure SetActive(const Value: Boolean);
procedure SetParent(AParent: TWinControl); override;
public
{ Public declarations }
procedure LoadFromFile(const inFilename: string);
procedure SaveToFile(const inFilename: string);
procedure Change;
procedure SetPageSize(inW, inH: Integer);
procedure UpdateDesigner;
property Active: Boolean read GetActive write SetActive;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
var
DesignForm: TDesignForm;
implementation
uses
LrVclUtils, htPaint;
{$R *.dfm}
procedure TDesignForm.FormCreate(Sender: TObject);
begin
//
end;
procedure TDesignForm.FormPaint(Sender: TObject);
begin
htPaintRules(Canvas, ClientRect);
end;
procedure TDesignForm.CreateParams(var Params: TCreateParams);
begin
inherited;
//Params.Style := Params.Style and not WS_CLIPSIBLINGS;
end;
procedure TDesignForm.SetPageSize(inW, inH: Integer);
begin
if Parent <> nil then
begin
Parent.ClientWidth := inW + 12 + 12;
Parent.ClientHeight := inH + 12 + 12;
SetBounds(12, 12, inW, inH);
end;
end;
procedure TDesignForm.SetParent(AParent: TWinControl);
begin
inherited;
SetPageSize(Width, Height);
{
if Parent <> nil then
begin
Left := 12;
Top := 12;
Parent.ClientWidth := Width + 12 + 12;
Parent.ClientHeight := Height + 12 + 12;
end;
}
end;
function TDesignForm.GetActive: Boolean;
begin
Result := DesignController1.Active;
end;
procedure TDesignForm.SetActive(const Value: Boolean);
begin
if Value then
begin
DesignMgr.SelectionObservers.Add(SelectionChange);
DesignMgr.PropertyObservers.Add(PropertyChange);
end else
begin
DesignMgr.SelectionObservers.Remove(SelectionChange);
DesignMgr.PropertyObservers.Remove(PropertyChange);
end;
DesignController1.Active := Value;
end;
procedure TDesignForm.UpdateDesigner;
begin
DesignController1.UpdateDesigner;
end;
procedure TDesignForm.Change;
begin
if Assigned(OnChange) then
OnChange(Self);
end;
procedure TDesignForm.DesignController1Change(Sender: TObject);
begin
DesignMgr.DesignChange;
end;
procedure TDesignForm.PropertyChange(Sender: TObject);
begin
UpdateDesigner;
end;
procedure TDesignForm.SelectionChange(Sender: TObject);
begin
DesignController1.SetSelected(DesignMgr.Selected);
end;
procedure TDesignForm.DesignController1SelectionChange(Sender: TObject);
begin
if Active then
DesignMgr.ObjectsSelected(Self, DesignController1.Selected);
end;
procedure TDesignForm.DesignController1GetAddClass(Sender: TObject;
var ioClass: String);
begin
ioClass := DesignMgr.AddClass;
end;
procedure TDesignForm.ReaderError(Reader: TReader; const Message: string;
var Handled: Boolean);
begin
Handled := true;
end;
procedure TDesignForm.LoadFromFile(const inFilename: string);
begin
DestroyComponents;
//DesignController1.Free;
LrLoadComponentFromFile(Self, inFilename, ReaderError);
Name := 'DesignSurface';
//DesignController1.Active := true;
DesignController1.OnSelectionChange := DesignController1SelectionChange;
DesignController1.OnGetAddClass := DesignController1GetAddClass
end;
procedure TDesignForm.SaveToFile(const inFilename: string);
begin
Visible := false;
LrSaveComponentToFile(Self, inFilename);
Visible := true;
end;
end.
|
unit mpBlock;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,MasterPaskalForm, fileutil, mpcoin, dialogs, math,
nosotime, mpMN, nosodebug,nosogeneral,nosocrypto, nosounit, strutils;
Procedure CrearBloqueCero();
Procedure BuildNewBlock(Numero,TimeStamp: Int64; TargetHash, Minero, Solucion:String);
Function GetDiffHashrate(bestdiff:String):integer;
Function BestHashReadeable(BestDiff:String):string;
function GetDiffForNextBlock(UltimoBloque,Last20Average,lastblocktime,previous:integer):integer;
function GetLast20Time(LastBlTime:integer):integer;
function GetBlockReward(BlNumber:int64):Int64;
Function GuardarBloque(NombreArchivo:string;Cabezera:BlockHeaderData;Ordenes:array of TOrderData;
PosPay:Int64;PoSnumber:integer;PosAddresses:array of TArrayPos;
MNsPay:int64;MNsNumber:Integer;MNsAddresses:array of TArrayPos):boolean;
function LoadBlockDataHeader(BlockNumber:integer):BlockHeaderData;
function GetBlockTrxs(BlockNumber:integer):TBlockOrdersArray;
Procedure UndoneLastBlock();
Function GetBlockPoSes(BlockNumber:integer): BlockArraysPos;
Function GetBlockMNs(BlockNumber:integer): BlockArraysPos;
Function GEtNSLBlkOrdInfo(LineText:String):String;
implementation
Uses
mpDisk,mpProtocol, mpGui, mpparser, mpRed;
Function CreateDevPaymentOrder(number:integer;timestamp,amount:int64):TOrderData;
Begin
Result := Default(TOrderData);
Result.Block := number;
//Result.OrderID :='';
Result.OrderLines := 1;
Result.OrderType := 'PROJCT';
Result.TimeStamp := timestamp-1;
Result.Reference := 'null';
Result.TrxLine := 1;
Result.sender := 'COINBASE';
Result.Address := 'COINBASE';
Result.Receiver := 'NpryectdevepmentfundsGE';
Result.AmmountFee := 0;
Result.AmmountTrf := amount;
Result.Signature := 'COINBASE';
Result.TrfrID := GetTransferHash(Result.TimeStamp.ToString+'COINBASE'+'NpryectdevepmentfundsGE'+IntToStr(amount)+IntToStr(MyLastblock));
Result.OrderID := {GetOrderHash(}'1'+Result.TrfrID{)};
End;
Function CreateNosoPayOrder(number:integer;AddSend,AddReceive:string;timestamp,amount:int64):TOrderData;
Begin
Result := Default(TOrderData);
Result.Block := number;
Result.OrderLines := 1;
Result.OrderType := 'TRFR';
Result.TimeStamp := timestamp-1;
Result.Reference := 'null';
Result.TrxLine := 1;
Result.sender := AddSend;
Result.Address := AddSend;
Result.Receiver := AddReceive;
Result.AmmountFee := 0;
Result.AmmountTrf := amount;
Result.Signature := 'Directive';
Result.TrfrID := GetTransferHash(Result.TimeStamp.ToString+'TRFR'+AddSend+IntToStr(amount)+IntToStr(MyLastblock));
Result.OrderID := GetOrderHash('1'+Result.TrfrID);
End;
// Build the default block 0
Procedure CrearBloqueCero();
Begin
BuildNewBlock(0,GenesysTimeStamp,'',adminhash,'');
if G_Launching then AddLineToDebugLog('console','Block GENESYS (0) created.'); //'Block 0 created.'
if G_Launching then OutText('✓ Block 0 created',false,1);
End;
// Crea un bloque nuevo con la informacion suministrada
Procedure BuildNewBlock(Numero,TimeStamp: int64; TargetHash, Minero, Solucion:String);
var
BlockHeader : BlockHeaderData;
StartBlockTime : int64 = 0;
MinerFee : int64 = 0;
ListaOrdenes : Array of TOrderData;
IgnoredTrxs : Array of TOrderData;
Filename : String;
Contador : integer = 0;
OperationAddress : string = '';
errored : boolean = false;
PoWTotalReward : int64;
ArrayLastBlockTrxs : TBlockOrdersArray;
ExistsInLastBlock : boolean;
Count2 : integer;
DevsTotalReward : int64 = 0;
DevOrder : TOrderData;
PoScount : integer = 0;
PosRequired, PosReward: int64;
PoSTotalReward : int64 = 0;
PoSAddressess : array of TArrayPos;
MNsCount : integer;
MNsReward : int64;
MNsTotalReward : int64 =0;
MNsAddressess : array of TArrayPos;
ThisParam : String;
MNsFileText : String = '';
GVTsTransfered : integer = 0;
NosoPayData : string = '';
NPDOrder : TOrderData;
NPDBlock : integer;
NPDSource : string;
NPDTarget : string;
NPDAmount : int64;
Begin
if GetNosoCFGString(0) = 'STOP' then
begin
ClearAllPending;
exit;
end;
if AnsiContainsStr(GetNosoCFGString(0),'EMPTY') then ClearAllPending;
BuildingBlock := Numero;
BeginPerformance('BuildNewBlock');
if ((numero>0) and (Timestamp < lastblockdata.TimeEnd)) then
begin
AddLineToDebugLog('console','New block '+IntToStr(numero)+' : Invalid timestamp');
AddLineToDebugLog('console','Blocks can not be added until '+TimestampToDate(GenesysTimeStamp));
errored := true;
end;
if TimeStamp > UTCTime+5 then
begin
AddLineToDebugLog('console','New block '+IntToStr(numero)+' : Invalid timestamp');
AddLineToDebugLog('console','Timestamp '+IntToStr(TimeStamp)+' is '+IntToStr(TimeStamp-UTCTime)+' seconds in the future');
errored := true;
end;
if not errored then
begin
if Numero = 0 then StartBlockTime := 1531896783
else StartBlockTime := LastBlockData.TimeEnd+1;
FileName := BlockDirectory + IntToStr(Numero)+'.blk';
SetLength(ListaOrdenes,0);
SetLength(IgnoredTrxs,0);
// Generate summary copy
EnterCriticalSection(CSSumary);
trydeletefile(SummaryFileName+'.bak');
trycopyfile(SummaryFileName,SummaryFileName+'.bak');
LeaveCriticalSection(CSSumary);
// Generate GVT copy
EnterCriticalSection(CSGVTsArray);
trydeletefile(GVTsFilename+'.bak');
copyfile(GVTsFilename,GVTsFilename+'.bak');
LeaveCriticalSection(CSGVTsArray);
// Processs pending orders
EnterCriticalSection(CSPending);
BeginPerformance('NewBLOCK_PENDING');
ArrayLastBlockTrxs := Default(TBlockOrdersArray);
ArrayLastBlockTrxs := GetBlockTrxs(MyLastBlock);
ResetBlockRecords;
for contador := 0 to length(pendingTXs)-1 do
begin
// Version 0.2.1Ga1 reverification starts
if PendingTXs[contador].TimeStamp < LastBlockData.TimeStart then
continue;
//{
ExistsInLastBlock := false;
for count2 := 0 to length(ArrayLastBlockTrxs)-1 do
begin
if ArrayLastBlockTrxs[count2].TrfrID = PendingTXs[contador].TrfrID then
begin
ExistsInLastBlock := true ;
break;
end;
end;
if ExistsInLastBlock then continue;
if PendingTXs[contador].TimeStamp+60 > TimeStamp then
begin
if PendingTXs[contador].TimeStamp < TimeStamp+600 then
insert(PendingTXs[contador],IgnoredTrxs,length(IgnoredTrxs));
continue;
end;
if PendingTXs[contador].OrderType='CUSTOM' then
begin
OperationAddress := GetAddressFromPublicKey(PendingTXs[contador].sender);
if IsCustomizacionValid(OperationAddress,PendingTXs[contador].Receiver,numero) then
begin
minerfee := minerfee+PendingTXs[contador].AmmountFee;
PendingTXs[contador].Block:=numero;
PendingTXs[contador].sender:=OperationAddress;
insert(PendingTXs[contador],ListaOrdenes,length(listaordenes));
end;
end;
if PendingTXs[contador].OrderType='TRFR' then
begin
OperationAddress := PendingTXs[contador].Address;
if SummaryValidPay(OperationAddress,PendingTXs[contador].AmmountFee+PendingTXs[contador].AmmountTrf,numero) then
begin
minerfee := minerfee+PendingTXs[contador].AmmountFee;
CreditTo(PendingTXs[contador].Receiver,PendingTXs[contador].AmmountTrf,numero);
PendingTXs[contador].Block:=numero;
PendingTXs[contador].sender:=OperationAddress;
insert(PendingTXs[contador],ListaOrdenes,length(listaordenes));
end;
end;
if ( (PendingTXs[contador].OrderType='SNDGVT') and ( PendingTXs[contador].sender = AdminPubKey) ) then
begin
OperationAddress := GetAddressFromPublicKey(PendingTXs[contador].sender);
if GetAddressBalanceIndexed(OperationAddress)< PendingTXs[contador].AmmountFee then continue;
if ChangeGVTOwner(StrToIntDef(PendingTXs[contador].Reference,100),OperationAddress,PendingTXs[contador].Receiver)=0 then
begin
minerfee := minerfee+PendingTXs[contador].AmmountFee;
Inc(GVTsTransfered);
SummaryValidPay(OperationAddress,PendingTXs[contador].AmmountFee,numero);
PendingTXs[contador].Block:=numero;
PendingTXs[contador].sender:=OperationAddress;
insert(PendingTXs[contador],ListaOrdenes,length(listaordenes));
end;
end;
end;
// Proyect payments
if GetNosoCFGString(6) <>'' then
begin
NosoPayData := GetNosoCFGString(6);
NosoPayData :=StringReplace(NosoPayData,':','',[rfReplaceAll, rfIgnoreCase]);
NosoPayData :=StringReplace(NosoPayData,',',' ',[rfReplaceAll, rfIgnoreCase]);
NPDBlock := StrToIntdef(Parameter(NosoPayData,0),0);
if NPDBlock = numero then
begin
NPDSource := Parameter(NosoPayData,1);
NPDTarget := Parameter(NosoPayData,2);
if ( (IsValidHashAddress(NPDTarget)) and (IsValidHashAddress(NPDSource)) ) then
begin
NPDAmount := StrToInt64def(Parameter(NosoPayData,3),0);
if SummaryValidPay(NPDSource,NPDamount,NPDBlock) then
begin
CreditTo(NPDTarget,NPDAmount,NPDBlock);
NPDOrder := CreateNosoPayOrder(NPDBlock,NPDSource,NPDTarget,TimeStamp,NPDAmount);
insert(NPDOrder,ListaOrdenes,length(listaordenes));
RemoveCFGData(GetNosoCFGString(6),6);
end;
end;
end;
end;
// Project funds payment
if numero >= PoSBlockEnd then
begin
DevsTotalReward := ((GetBlockReward(Numero)+MinerFee)*GetDevPercentage(Numero)) div 10000;
DevORder := CreateDevPaymentOrder(numero,TimeStamp,DevsTotalReward);
CreditTo('NpryectdevepmentfundsGE',DevsTotalReward,numero);
insert(DevORder,ListaOrdenes,length(listaordenes));
end;
if GVTsTransfered>0 then
begin
SaveGVTs;
UpdateMyGVTsList;
end;
TRY
SetLength(PendingTXs,0);
PendingTXs := copy(IgnoredTrxs,0,length(IgnoredTrxs));
EXCEPT on E:Exception do
begin
AddLineToDebugLog('exceps',FormatDateTime('dd mm YYYY HH:MM:SS.zzz', Now)+' -> '+'Error asigning pending to Ignored');
end;
END; {TRY}
SetLength(IgnoredTrxs,0);
EndPerformance('NewBLOCK_PENDING');
LeaveCriticalSection(CSPending);
//PoS payment
BeginPerformance('NewBLOCK_PoS');
if numero >= PoSBlockStart then
begin
SetLength(PoSAddressess,0);
PoSReward := 0;
PosCount := 0;
PosTotalReward := 0;
if numero < PosBlockEnd then
begin
PosRequired := (GetSupply(numero)*PosStackCoins) div 10000;
PoScount := length(PoSAddressess);
PosTotalReward := ((GetBlockReward(Numero)+MinerFee)*GetPoSPercentage(Numero)) div 10000;
PosReward := PosTotalReward div PoScount;
PosTotalReward := PoSCount * PosReward;
//pay POS
for contador := 0 to length(PoSAddressess)-1 do
CreditTo(PoSAddressess[contador].address,PosReward,numero);
end;
end;
EndPerformance('NewBLOCK_PoS');
// Masternodes processing
BeginPerformance('NewBLOCK_MNs');
CreditMNVerifications();
MNsFileText := GetMNsAddresses();
SaveMNsFile(MNsFileText);
ClearMNsChecks();
ClearMNsList();
if numero >= MNBlockStart then
begin
SetLength(MNsAddressess,0);
Contador := 1;
Repeat
begin
ThisParam := Parameter(MNsFileText,contador);
if ThisParam<> '' then
begin
ThisParam := StringReplace(ThisParam,':',' ',[rfReplaceAll]);
ThisParam := Parameter(ThisParam,1);
SetLength(MNsAddressess,length(MNsAddressess)+1);
MNsAddressess[length(MNsAddressess)-1].address:=ThisParam;
end;
Inc(contador);
end;
until ThisParam = '';
MNsCount := Length(MNsAddressess);
MNsTotalReward := ((GetBlockReward(Numero)+MinerFee)*GetMNsPercentage(Numero,GetNosoCFGString(0))) div 10000;
if MNsCount>0 then MNsReward := MNsTotalReward div MNsCount
else MNsReward := 0;
MNsTotalReward := MNsCount * MNsReward;
For contador := 0 to length(MNsAddressess)-1 do
begin
CreditTo(MNsAddressess[contador].address,MNsReward,numero);
end;
EndPerformance('NewBLOCK_MNs');
end;// End of MNS payment procecessing
// ***END MASTERNODES PROCESSING***
// Reset Order hashes received
ClearReceivedOrdersIDs;
// Miner payment
PoWTotalReward := (GetBlockReward(Numero)+MinerFee)-PosTotalReward-MNsTotalReward-DevsTotalReward;
CreditTo(Minero,PoWTotalReward,numero);
// Update summary lastblock
CreditTo(AdminHash,0,numero);
// Save summary file
BeginPerformance('NewBLOCK_SaveSum');
UpdateSummaryChanges();
EndPerformance('NewBLOCK_SaveSum');
SummaryLastop := numero;
// Limpiar las pendientes
for contador := 0 to length(ListaDirecciones)-1 do
begin
ListaDirecciones[contador].Pending:=0;
end;
// Definir la cabecera del bloque *****
BlockHeader := Default(BlockHeaderData);
BlockHeader.Number := Numero;
BlockHeader.TimeStart:= StartBlockTime;
BlockHeader.TimeEnd:= timeStamp;
BlockHeader.TimeTotal:= TimeStamp - StartBlockTime;
BlockHeader.TimeLast20:=0;//GetLast20Time(BlockHeader.TimeTotal);
BlockHeader.TrxTotales:=length(ListaOrdenes);
if numero = 0 then BlockHeader.Difficult:= InitialBlockDiff
else if ( (numero>0) and (numero<53000) ) then BlockHeader.Difficult:= 0
else BlockHeader.Difficult := PoSCount;
BlockHeader.TargetHash:=TargetHash;
//if protocolo = 1 then BlockHeader.Solution:= Solucion
BlockHeader.Solution:= Solucion+' '+GetNMSData.Diff+' '+PoWTotalReward.ToString+' '+MNsTotalReward.ToString+' '+PosTotalReward.ToString;
if numero = 0 then BlockHeader.Solution:='';
if numero = 0 then BlockHeader.LastBlockHash:='NOSO GENESYS BLOCK'
else BlockHeader.LastBlockHash:=MyLastBlockHash;
if numero<53000 then BlockHeader.NxtBlkDiff:= 0{MNsReward}//GetDiffForNextBlock(numero,BlockHeader.TimeLast20,BlockHeader.TimeTotal,BlockHeader.Difficult);
else BlockHeader.NxtBlkDiff := MNsCount;
BlockHeader.AccountMiner:=Minero;
BlockHeader.MinerFee:=MinerFee;
BlockHeader.Reward:=GetBlockReward(Numero);
// Fin de la cabecera -----
// Guardar bloque al disco
if not GuardarBloque(FileName,BlockHeader,ListaOrdenes,PosReward,PosCount,PoSAddressess,
MNsReward, MNsCount,MNsAddressess) then
AddLineToDebugLog('exceps',FormatDateTime('dd mm YYYY HH:MM:SS.zzz', Now)+' -> '+'*****CRITICAL*****'+slinebreak+'Error building block: '+numero.ToString);
SetNMSData('','','','','','');
BuildNMSBlock := 0;
ZipSumary;
SetLength(ListaOrdenes,0);
SetLength(PoSAddressess,0);
// Actualizar informacion
MyLastBlock := Numero;
MyLastBlockHash := HashMD5File(BlockDirectory+IntToStr(MyLastBlock)+'.blk');
LastBlockData := LoadBlockDataHeader(MyLastBlock);
MySumarioHash := HashMD5File(SummaryFileName);
MyMNsHash := HashMD5File(MasterNodesFilename);
// Actualizar el arvhivo de cabeceras
AddBlchHead(Numero,MyLastBlockHash,MySumarioHash);
MyResumenHash := HashMD5File(ResumenFilename);
if ( (Numero>0) and (form1.Server.Active) ) then
begin
OutgoingMsjsAdd(ProtocolLine(ping));
end;
CheckForMyPending;
if DIreccionEsMia(Minero)>-1 then showglobo('Miner','Block found!');
U_DirPanel := true;
OutText(format('Block built: %d (%d ms)',[numero,EndPerformance('BuildNewBlock')]),true);
end
else
begin
OutText('Failed to build the block',true);
end;
BuildingBlock := 0;
U_DataPanel := true;
End;
Function GetDiffHashrate(bestdiff:String):integer;
var
counter :integer= 0;
Begin
repeat
counter := counter+1;
until bestdiff[counter]<> '0';
Result := (Counter-1)*100;
if bestdiff[counter]='1' then Result := Result+50;
if bestdiff[counter]='2' then Result := Result+25;
if bestdiff[counter]='3' then Result := Result+12;
if bestdiff[counter]='4' then Result := Result+6;
//if bestdiff[counter]='5' then Result := Result+3;
End;
Function BestHashReadeable(BestDiff:String):string;
var
counter :integer = 0;
Begin
if bestdiff = '' then BestDiff := 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF';
repeat
counter := counter+1;
until bestdiff[counter]<> '0';
Result := (Counter-1).ToString+'.';
if counter<length(BestDiff) then Result := Result+bestdiff[counter];
End;
// Devuelve cuantos caracteres compondran el targethash del siguiente bloque
function GetDiffForNextBlock(UltimoBloque,Last20Average, lastblocktime,previous:integer):integer;
Begin
result := previous;
if UltimoBloque < 21 then result := InitialBlockDiff
else
begin
if Last20Average < SecondsPerBlock then
begin
if lastblocktime<SecondsPerBlock then result := Previous+1
end
else if Last20Average > SecondsPerBlock then
begin
if lastblocktime>SecondsPerBlock then result := Previous-1
end
else result := previous;
end;
End;
// Hace el calculo del tiempo promedio empleado en los ultimos 20 bloques
function GetLast20Time(LastBlTime:integer):integer;
var
Part1, Part2 : integer;
Begin
if LastBlockData.Number<21 then result := SecondsPerBlock
else
begin
Part1 := LastBlockData.TimeLast20 * 19 div 20;
Part2 := LastBlTime div 20;
result := Part1 + Part2;
end;
End;
// RETURNS THE MINING REWARD FOR A BLOCK
function GetBlockReward(BlNumber:int64):Int64;
var
NumHalvings : int64;
Begin
if BlNumber = 0 then result := PremineAmount
else if ((BlNumber > 0) and (blnumber < BlockHalvingInterval*(HalvingSteps+1))) then
begin
numHalvings := BlNumber div BlockHalvingInterval;
result := InitialReward div ( 2**NumHalvings );
end
else result := 0;
End;
// Guarda el archivo de bloque en disco
Function GuardarBloque(NombreArchivo:string;Cabezera:BlockHeaderData;
Ordenes:array of TOrderData;
PosPay:Int64;PoSnumber:integer;PosAddresses:array of TArrayPos;
MNsPay:int64;MNsNumber:Integer;MNsAddresses:array of TArrayPos):boolean;
var
MemStr: TMemoryStream;
NumeroOrdenes : int64;
counter : integer;
Begin
result := true;
BeginPerformance('GuardarBloque');
NumeroOrdenes := Cabezera.TrxTotales;
MemStr := TMemoryStream.Create;
TRY
MemStr.Write(Cabezera,Sizeof(Cabezera));
for counter := 0 to NumeroOrdenes-1 do
MemStr.Write(Ordenes[counter],Sizeof(Ordenes[Counter]));
if Cabezera.Number>=PoSBlockStart then
begin
MemStr.Write(PosPay,Sizeof(PosPay));
MemStr.Write(PoSnumber,Sizeof(PoSnumber));
for counter := 0 to PoSnumber-1 do
MemStr.Write(PosAddresses[counter],Sizeof(PosAddresses[Counter]));
end;
if Cabezera.Number>=MNBlockStart then
begin
MemStr.Write(MNsPay,Sizeof(MNsPay));
MemStr.Write(MNsnumber,Sizeof(MNsnumber));
for counter := 0 to MNsNumber-1 do
begin
MemStr.Write(MNsAddresses[counter],Sizeof(MNsAddresses[Counter]));
end;
end;
MemStr.SaveToFile(NombreArchivo);
EXCEPT On E :Exception do
begin
AddLineToDebugLog('console','Error saving block to disk: '+E.Message);
result := false;
end;
END{Try};
MemStr.Free;
EndPerformance('GuardarBloque');
End;
// Carga la informacion del bloque
function LoadBlockDataHeader(BlockNumber:integer):BlockHeaderData;
var
MemStr: TMemoryStream;
Header : BlockHeaderData;
ArchData : String;
Begin
Header := Default(BlockHeaderData);
ArchData := BlockDirectory+IntToStr(BlockNumber)+'.blk';
MemStr := TMemoryStream.Create;
TRY
MemStr.LoadFromFile(ArchData);
MemStr.Position := 0;
MemStr.Read(Header, SizeOf(Header));
EXCEPT ON E:Exception do
begin
AddLineToDebugLog('console','Error loading Header from block '+IntToStr(BlockNumber)+':'+E.Message);
end;
END{Try};
MemStr.Free;
Result := header;
End;
// Devuelve las transacciones del bloque
function GetBlockTrxs(BlockNumber:integer):TBlockOrdersArray;
var
ArrTrxs : TBlockOrdersArray;
MemStr: TMemoryStream;
Header : BlockHeaderData;
ArchData : String;
counter : integer;
TotalTrxs, totalposes : integer;
posreward : int64;
Begin
Setlength(ArrTrxs,0);
ArchData := BlockDirectory+IntToStr(BlockNumber)+'.blk';
MemStr := TMemoryStream.Create;
try
MemStr.LoadFromFile(ArchData);
MemStr.Position := 0;
MemStr.Read(Header, SizeOf(Header));
TotalTrxs := header.TrxTotales;
SetLength(ArrTrxs,TotalTrxs);
For Counter := 0 to TotalTrxs-1 do
MemStr.Read(ArrTrxs[Counter],Sizeof(ArrTrxs[Counter])); // read each record
Except on E: Exception do // nothing, the block is not founded
end;
MemStr.Free;
Result := ArrTrxs;
End;
Function GetBlockPoSes(BlockNumber:integer): BlockArraysPos;
var
resultado : BlockArraysPos;
ArrTrxs : TBlockOrdersArray;
ArchData : String;
MemStr: TMemoryStream;
Header : BlockHeaderData;
TotalTrxs, totalposes : integer;
posreward : int64;
counter : integer;
Begin
Setlength(resultado,0);
ArchData := BlockDirectory+IntToStr(BlockNumber)+'.blk';
MemStr := TMemoryStream.Create;
try
MemStr.LoadFromFile(ArchData);
MemStr.Position := 0;
MemStr.Read(Header, SizeOf(Header));
TotalTrxs := header.TrxTotales;
SetLength(ArrTrxs,TotalTrxs);
For Counter := 0 to TotalTrxs-1 do
MemStr.Read(ArrTrxs[Counter],Sizeof(ArrTrxs[Counter])); // read each record
MemStr.Read(posreward, SizeOf(int64));
MemStr.Read(totalposes, SizeOf(integer));
SetLength(resultado,totalposes);
For Counter := 0 to totalposes-1 do
MemStr.Read(resultado[Counter].address,Sizeof(resultado[Counter]));
SetLength(resultado,totalposes+1);
resultado[length(resultado)-1].address := IntToStr(posreward);
Except on E: Exception do // nothing, the block is not found
end;
MemStr.Free;
Result := resultado;
end;
Function GetBlockMNs(BlockNumber:integer): BlockArraysPos;
var
resultado : BlockArraysPos;
ArrayPos : BlockArraysPos;
ArrTrxs : TBlockOrdersArray;
ArchData : String;
MemStr: TMemoryStream;
Header : BlockHeaderData;
TotalTrxs, totalposes, totalMNs : integer;
posreward,MNreward : int64;
counter : integer;
Begin
Setlength(resultado,0);
Setlength(ArrayPos,0);
if blocknumber <MNBlockStart then
begin
result := resultado;
exit;
end;
ArchData := BlockDirectory+IntToStr(BlockNumber)+'.blk';
MemStr := TMemoryStream.Create;
TRY
// HEADERS
MemStr.LoadFromFile(ArchData);
MemStr.Position := 0;
MemStr.Read(Header, SizeOf(Header));
// TRXS LIST
TotalTrxs := header.TrxTotales;
SetLength(ArrTrxs,TotalTrxs);
For Counter := 0 to TotalTrxs-1 do
MemStr.Read(ArrTrxs[Counter],Sizeof(ArrTrxs[Counter])); // read each record
// POS INFO
MemStr.Read(posreward, SizeOf(int64));
MemStr.Read(totalposes, SizeOf(integer));
SetLength(ArrayPos,totalposes);
For Counter := 0 to totalposes-1 do
MemStr.Read(ArrayPos[Counter].address,Sizeof(ArrayPos[Counter]));
// MNS INFO
MemStr.Read(MNReward, SizeOf(MNReward));
MemStr.Read(totalMNs, SizeOf(totalMNs));
SetLength(resultado,totalMNs);
For Counter := 0 to totalMNs-1 do
begin
MemStr.Read(resultado[Counter].address,Sizeof(resultado[Counter]));
end;
SetLength(resultado,totalMNs+1);
resultado[length(resultado)-1].address := IntToStr(MNReward);
EXCEPT on E: Exception do // nothing, the block is not founded
AddLineToDebugLog('exceps',FormatDateTime('dd mm YYYY HH:MM:SS.zzz', Now)+' -> '+'EXCEPTION on MNs file data:'+E.Message)
END; {TRY}
MemStr.Free;
Result := resultado;
end;
// Deshacer el ultimo bloque
Procedure UndoneLastBlock();
Const
Highest : integer = 0;
var
blocknumber : integer;
Begin
//if BlockUndoneTime+30>UTCTime then exit;
blocknumber:= MyLastBlock;
if BlockNumber < Highest then
begin
AddLineToDebugLog('Console','Can not undo block '+mylastblock.ToString);
exit;
end
else Highest := BlockNumber;
if BlockNumber = 0 then exit;
if MyConStatus = 3 then
begin
MyConStatus := 2;
//if Form1.Server.Active then Form1.Server.Active := false;
ClearMNsChecks();
ClearMNsList();
SetNMSData('','','','','','');
ClearAllPending;
ClearReceivedOrdersIDs;
end;
// recover summary
EnterCriticalSection(CSSumary);
Trydeletefile(SummaryFileName);
Trycopyfile(SummaryFileName+'.bak',SummaryFileName);
LeaveCriticalSection(CSSumary);
CreateSumaryIndex;
// recover GVTs file
EnterCriticalSection(CSGVTsArray);
trydeletefile(GVTsFilename);
copyfile(GVTsFilename+'.bak',GVTsFilename);
LeaveCriticalSection(CSGVTsArray);
GetGVTsFileData();
UpdateMyGVTsList;
// Actualizar la cartera
UpdateWalletFromSumario();
// actualizar el archivo de cabeceras
DelBlChHeadLast(blocknumber);
// Borrar archivo del ultimo bloque
trydeletefile(BlockDirectory +IntToStr(MyLastBlock)+'.blk');
// Actualizar mi informacion
MyLastBlock := GetMyLastUpdatedBlock;
MyLastBlockHash := HashMD5File(BlockDirectory+IntToStr(MyLastBlock)+'.blk');
LastBlockData := LoadBlockDataHeader(MyLastBlock);
MyResumenHash := HashMD5File(ResumenFilename);
AddLineToDebugLog('console','****************************');
AddLineToDebugLog('console','Block undone: '+IntToStr(blocknumber)); //'Block undone: '
AddLineToDebugLog('console','****************************');
AddLineToDebugLog('events',TimeToStr(now)+'Block Undone: '+IntToStr(blocknumber));
U_DataPanel := true;
BlockUndoneTime := UTCTime;
End;
Function GEtNSLBlkOrdInfo(LineText:String):String;
var
ParamBlock : String;
BlkNumber : integer;
OrdersArray : TBlockOrdersArray;
Cont : integer;
ThisOrder : string = '';
Begin
Result := 'NSLBLKORD ';
ParamBlock := UpperCase(Parameter(LineText,1));
If paramblock = 'LAST' then BlkNumber := MyLastBlock
else BlkNumber := StrToIntDef(ParamBlock,-1);
if ( (BlkNumber<0) or (BlkNumber<MyLastBlock-4000) or (BlkNumber>MyLastBlock) ) then Result := Result+'ERROR'
else
begin
Result := Result+BlkNumber.ToString+' ';
OrdersArray := Default(TBlockOrdersArray);
OrdersArray := GetBlockTrxs(BlkNumber);
if Length(OrdersArray)>0 then
begin
For Cont := 0 to LEngth(OrdersArray)-1 do
begin
if OrdersArray[cont].OrderType='TRFR' then
begin
ThisOrder := ThisOrder+OrdersArray[Cont].sender+':'+OrdersArray[Cont].Receiver+':'+OrdersArray[Cont].AmmountTrf.ToString+':'+
OrdersArray[Cont].Reference+':'+OrdersArray[Cont].OrderID+' ';
end;
end;
end;
Result := Result+ThisOrder;
Result := Trim(Result)
end;
End;
END. // END UNIT
|
{*******************************************************}
{ }
{ Tachyon Unit }
{ Vector Raster Geographic Information Synthesis }
{ VOICE .. Tracer }
{ GRIP ICE .. Tongs }
{ Digital Terrain Mapping }
{ Image Locatable Holographics }
{ SOS MAP }
{ Surreal Object Synthesis Multimedia Analysis Product }
{ Fractal3D Life MOW }
{ Copyright (c) 1995,2006 Ivan Lee Herring }
{ }
{*******************************************************}
unit nLifeFiles;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics,
Controls, Forms, Dialogs,
Math, StdCtrls, FileCtrl, Buttons, ExtCtrls;
type
TLifeFilesForm = class(TForm)
DirectoryListBox1: TDirectoryListBox;
DriveComboBox1: TDriveComboBox;
FileListBox1: TFileListBox;
LifeFileEdit: TEdit;
Memo1: TMemo;
FileLabel: TLabel;
SpokesLabel: TLabel;
LifeCyclesLabel: TLabel;
Panel1: TPanel;
Label1: TLabel;
HelpBtn: TSpeedButton;
LifeFileBtn: TSpeedButton;
Do3DBtn: TSpeedButton;
Do2DBtn: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ReallyClose;
procedure LoadFileBtnClick(Sender: TObject);
procedure DoFileLoader(FileName: string);
procedure HelpBtnClick(Sender: TObject);
procedure Do2DBtnClick(Sender: TObject);
{procedure Do2DCellLoader; }
procedure Do3DBtnClick(Sender: TObject);
procedure Do3DCellLoader;
procedure FormShow(Sender: TObject);
private
MinX, MinY, MaxX, MaxY,
PatternWide, PatternHigh:Integer;
public
end;
var
LifeFilesForm: TLifeFilesForm;
implementation
uses ncLife, nUGlobal, nlife3d;
{$R *.DFM}
procedure TLifeFilesForm.FormCreate(Sender: TObject);
begin
top := LifeFilesFormY;
left := LifeFilesFormX;
PatternWide := 0;
PatternHigh := 0;
end;
procedure TLifeFilesForm.ReallyClose;
begin
Setlength(TempArray, 0, 0);
Close;
end;
procedure TLifeFilesForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
LifeFilesFormY := LifeFilesForm.top;
LifeFilesFormX := LifeFilesForm.left;
if ReallyGone then Action := caFree else Action := caHide;
end;
procedure TLifeFilesForm.FormShow(Sender: TObject);
var driveletter:string;
begin
driveletter:= extractfiledrive(nLifeDir);
DriveComboBox1.Drive:=driveletter[1];
DirectoryListBox1.Directory:=nLifeDir;
end;
procedure TLifeFilesForm.HelpBtnClick(Sender: TObject);
begin
Application.HelpContext(2001);
end;
procedure TLifeFilesForm.LoadFileBtnClick(Sender: TObject);
var {FileListBox1Drive,}FileListBox1Directory:String;
begin
{ FileListBox1Drive := DriveComboBox1.Drive;}
FileListBox1Directory := DirectoryListBox1.Directory;
{ showmessage(FileListBox1Directory +'\'+LifeFileEdit.Text);}
If FileExists(FileListBox1Directory +'\'+LifeFileEdit.Text) then
DoFileLoader(FileListBox1Directory +'\'+LifeFileEdit.Text);
end;
procedure TLifeFilesForm.DoFileLoader(FileName: string);
var
LifeText: TextFile;
{CheckString2,} CheckString, DataString, Instring: string;
{private MinX, MinY, MaxX, MaxY,
PatternWide, PatternHigh:Integer;}
CurrentX, CurrentY,
TotalWidth, {MissingWidth,}
TotalLines, {MissingLines,}
OneY, OneX, {The X,Y read from file for each block of life cells}
CheckCode, {checks that val worked}
Ruler,{flips live or die of / 23/3}
DataCount, {LineCount,} {in processing counts of data}
i,j:Integer;
CellList:Array of TPoint;
begin
nLifeDir:=extractfilepath(FileName);
AssignFile(LifeText, FileName);
Reset(LifeText);
Readln(LifeText, Instring);
if (Instring = '#Life 1.05') then
begin
{showmessage(Instring);}
Memo1.Lines.Append(Instring);
DataString := '';
Memo1.Clear;
Memo1.Lines.Clear;
FileLabel.Caption := FileName;
DataCount := 0;
CurrentX:= 0;
CurrentY:= 0;
OneX:= 0;
OneY:= 0;
Setlength(TempArray, 0, 0);
Setlength(CellList, 0);
MaxX :=0;{ 0 - 2147;}
MaxY :=0; {0 - 2147;}
MinX :=0; {2147;}
MinY :=0; {2147;}
while (not eof(LifeText)) do
begin
Readln(LifeText, Instring);
If Length(Instring)>0 then
begin {skip blank lines}
If Length(Instring)=1 then
begin {cover for single data lines}
begin
if Instring[1] = '*' then
begin
inc(DataCount);
Setlength(CellList, DataCount+1);
CellList[DataCount].X := OneX+CurrentX;
CellList[DataCount].Y := OneY+CurrentY;
inc(CurrentX);
end else inc(CurrentX);
end;
inc(CurrentY);
end else
if (Instring[2] = 'D') then
begin
Instring[1] := ' '; Instring[2] := ' ';
Instring := trim(Instring);
{FileLabel.Caption := Instring;}
Memo1.Lines.Append(Instring);
end else
if ((Instring[2] = 'C')) then
begin
Instring[1] := ' '; Instring[2] := ' '; trim(Instring);
Memo1.Lines.Append(Instring);
end else
if (Instring[2] = 'N') then
begin
Memo1.Lines.Append(Instring+' Means Conway Rule');
{Normal.... 23/3 ...}
alife3dForm.Conway1Click(self);
end else
if (Instring[2] = 'R') then
begin
Memo1.Lines.Append(Instring);
{Rulestring.... ...}
Instring[1] := ' '; Instring[2] := ' ';
Instring := trim(Instring);
for i:= 0 to 26 do Universal[0,i]:=False;
for i:= 0 to 26 do Universal[1,i]:=False;
Ruler:=0;
for i := 1 to Length(Instring) do
begin
If (Instring[i] = '/') then Ruler:=1 else
Universal[Ruler,strtoint(Instring[i])]:=True;
end;
alife3dForm.CellularRulesOff;
alife3dForm.Universes.Checked:=True;
CellularRulesStyle:=1;
alife3dForm.StatusBarred.Panels[0].Text :=
alife3dForm.RunBooleanRules;
end else
if (Instring[2] = 'P') then
begin
{Get the X,Y offsets and read in the next line,
so the other lines can be read incremented}
Instring[1] := ' '; Instring[2] := ' '; trim(Instring);
{Get the X,Y and place the array
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '-'];}
{Checkstring:=Copy(Instring,0,Pos(' ',Instring));}
Checkstring := '';
for i := 1 to Pos(' ', Instring) do
begin
if ((Instring[i] in TDigitsSet)) then
Checkstring := Checkstring + Instring[i];
end;
val(Checkstring, OneX, CheckCode);
Checkstring := Copy(Instring, Pos(' ', Instring),Length(Instring));
val(Checkstring, OneY, CheckCode);
CurrentX:= 0;
CurrentY:= 0;
end else
begin {Read in to the current P Block}
for I := 1 to Length(Instring) do
begin
if Instring[I] = '*' then
begin
inc(DataCount);
Setlength(CellList, DataCount+1);
CellList[DataCount].X := OneX+CurrentX;
CellList[DataCount].Y := OneY+CurrentY;
inc(CurrentX);
end else inc(CurrentX);
end;
inc(CurrentY);
end;
end;
end;
for I := 1 to DataCount do
begin
OneX:=CellList[i].X;
OneY:=CellList[i].Y;
if (MinX > OneX) then MinX := OneX;
if (MinY > OneY) then MinY := OneY;
if (MaxX < OneX) then MaxX := OneX;
if (MaxY < OneY) then MaxY := OneY;
end;
TotalWidth:=(MaxX-MinX);
TotalLines:=(MaxY-MinY);
PatternWide:=TotalWidth;
PatternHigh:=TotalLines;
{showmessage(inttostr(TotalWidth));}
Setlength(TempArray, TotalWidth+1, TotalLines+1);
for j := 0 to TotalLines do
for I := 0 to TotalWidth do
TempArray[I, J]:= 0;
for I := 1 to DataCount do
TempArray[CellList[i].X+MinX, CellList[i].Y+MinY] := 1;
{Display Counts}
str(TotalWidth, CheckString);
SpokesLabel.Caption := CheckString;
Memo1.Lines.Append('Total Width: '+CheckString);
str(TotalLines, CheckString);
LifeCyclesLabel.Caption := CheckString;
Memo1.Lines.Append('Total Lines: '+CheckString);
str(MaxX, CheckString);
Memo1.Lines.Append('MaxX: '+CheckString);
str(MaxY, CheckString);
Memo1.Lines.Append('MaxY: '+CheckString);
str(MinX, CheckString);
Memo1.Lines.Append('MinX: '+CheckString);
str(MinY, CheckString);
Memo1.Lines.Append('MinY: '+CheckString);
{Do2DBtn.Enabled:=True;}
Do3DBtn.Enabled:=True;
end else
begin {Bad file }
FileLabel.Caption := 'FileName';
Memo1.Lines.Clear;
Memo1.Lines.Append(Instring);
Setlength(TempArray, 0, 0);
Setlength(CellList, 0);
end;
CloseFile(LifeText);
{Setlength(TempArray, 0, 0);}
Setlength(CellList, 0);
end; {Procedure}
procedure TLifeFilesForm.Do3DBtnClick(Sender: TObject);
begin
alife3dForm.ShowDown(FileLabel.Caption);
end;
procedure TLifeFilesForm.Do3DCellLoader;
var
OffsetX, OffsetY,
LifeSizeHalf, Sizer, I, J {, II,JJ}: Integer;
begin
{Place the already loaded Life file into the Array}
Sizer:=max(PatternHigh, PatternWide);
If Sizer > 511 then {Error}exit;
Case Sizer of
1..9: If LifeSize < 9 then alife3dForm.lifesize10Click(self){LifeSize:=9} ;
10..24: If LifeSize < 24 then alife3dForm.lifesize25Click(self){LifeSize:=24};
25..49: If LifeSize < 49 then alife3dForm.lifesize50Click(self){LifeSize:=49};
50..99: If LifeSize < 99 then alife3dForm.lifesize100Click(self){LifeSize:=99};
100..149:If LifeSize < 149 then alife3dForm.lifesize150Click(self){LifeSize:=149};
150..199:If LifeSize < 199 then alife3dForm.lifesize200Click(self){LifeSize:=199};
200..254:If LifeSize < 254 then alife3dForm.lifesize256Click(self){LifeSize:=254};
255..299:If LifeSize < 299 then alife3dForm.lifesize300Click(self){LifeSize:=511};
300..399:If LifeSize < 399 then alife3dForm.lifesize400Click(self){LifeSize:=511};
400..511:If LifeSize < 511 then alife3dForm.lifesize512Click(self){LifeSize:=511};
end;
{ JJ := 1; II := 1;}
OffsetX:= (LifeSize-PatternWide)div 2;
OffsetY:= (LifeSize-PatternHigh)div 2;
LifeSizeHalf:=LifeSize div 2;
for J := 0 to PatternHigh-1 do begin
for I := 0 to PatternWide-1 do begin
BeforeaLifeMatrix[I+OffsetX, J+OffsetY, LifeSizeHalf]:=
TempArray[i, j];
{inc(II);}
end; {inc(JJ);}
end;
end;
procedure TLifeFilesForm.Do2DBtnClick(Sender: TObject);
begin {Lif Life 2D 2010}
{ Do2DCellLoader;}
{Use 3D code to paint a GR32 bitmap ... BUT ONLY the area Visible
Speed optimization... ??? the hard part ?}
{Record to store data into a 2*XxY array ... X and Y EXPAND as needed
Thus SWITCH which is Active instead of Replacing ALL data every cycle
Count:Byte or Integer
Geez it is too complicated for ME
Display the Max X-Y and Displayed X-Y
Use the GR32 Zoom and Scroll and IGNORE it
Access like a HTF in DTM ?}
end;
{(LoadFileName:String;InWidth:Integer)}
(*
procedure TLifeFilesForm.Do2DCellLoader;
var I, II, J, JJ: Integer;
begin
{ ChangeRow := ARow; ChangeCol := ACol;}
{Place the already loaded Life file into the Array}
if bEditor39 then
begin
JJ := 1; II := 1;
for J := ChangeRow to PatternHigh do begin
for I := ChangeCol to PatternWide do begin
TV[i{ChangeCol}, j{ChangeRow}] := TempArray[II, JJ];
inc(II);
end; inc(JJ);
end;
end else if bEditor78 then
begin
{TV7848[ChangeCol,ChangeRow]}
JJ := 1; II := 1;
for J := ChangeRow to PatternHigh do begin
for I := ChangeCol to PatternWide do begin
TV7848[i{ChangeCol}, j{ChangeRow}] := TempArray[II, JJ];
inc(II);
end; inc(JJ);
end;
end;
end;
*)
end.
|
unit MyLabel;
interface
uses
Classes,
StdCtrls;
type
TMyLabel = class(TLabel)
private
FDescription: String;
FExcludeMe: String;
published
property Description: String read FDescription write FDescription;
property ExcludeMe: String read FExcludeMe write FExcludeMe;
end;
TMyMemo = class(TMemo)
private
FDescription: String;
FExcludeMe: String;
published
property Description: String read FDescription write FDescription;
property ExcludeMe: String read FExcludeMe write FExcludeMe;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('My controls', [TMyLabel, TMyMemo]);
end;
end.
|
unit LrProjectView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, VirtualTrees, ActiveX,
ImgList, PngImageList,
LrTreeData, LrProject;
type
TLrItemCanEvent = procedure(inItem: TLrProjectItem;
var inAllowed: Boolean) of object;
TLrCanDropEvent = procedure(inDragItem, inDropItem: TLrProjectItem;
inShift: TShiftState; var inAccept: Boolean) of object;
TLrDragDropEvent = procedure(inDragItem, inDropItem: TLrProjectItem;
inShift: TShiftState) of object;
TLrNewTextEvent = procedure(inItem: TLrProjectItem;
const inNewText: WideString) of object;
TLrGetImageIndexEvent = procedure(inItem: TLrProjectItem;
var ImageIndex: Integer) of object;
TLrOpenItemEvent = procedure(inItem: TLrProjectItem) of object;
//
TLrProjectForm = class(TForm)
Tree: TVirtualStringTree;
procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
procedure TreeInitNode(Sender: TBaseVirtualTree;
ParentNode, Node: PVirtualNode;
var InitialStates: TVirtualNodeInitStates);
procedure TreeInitChildren(Sender: TBaseVirtualTree;
Node: PVirtualNode; var ChildCount: Cardinal);
procedure TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
procedure TreeDragAllowed(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; var Allowed: Boolean);
procedure TreeDragOver(Sender: TBaseVirtualTree; Source: TObject;
Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode;
var Effect: Integer; var Accept: Boolean);
procedure TreeDragDrop(Sender: TBaseVirtualTree; Source: TObject;
DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState;
Pt: TPoint; var Effect: Integer; Mode: TDropMode);
procedure TreeEditing(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; var Allowed: Boolean);
procedure TreeNewText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; NewText: WideString);
procedure TreeDblClick(Sender: TObject);
private
{ Private declarations }
FOnCanDrag: TLrItemCanEvent;
FOnCanDrop: TLrCanDropEvent;
FOnCanEdit: TLrItemCanEvent;
FOnDragDrop: TLrDragDropEvent;
FOnGetImageIndex: TLrGetImageIndexEvent;
FOnGetOverlayIndex: TLrGetImageIndexEvent;
FOnNewText: TLrNewTextEvent;
FOnOpenItem: TLrOpenItemEvent;
FProject: TLrProject;
protected
function GetFolderItem(inItem: TLrTreeLeaf): TLrProjectItem;
function GetNodeItem(inNode: PVirtualNode): TLrProjectItem;
function GetNodeItems(inNode: PVirtualNode): TLrProjectItem;
function GetSelectedFolderItem: TLrProjectItem;
function GetSelectedItem: TLrProjectItem;
procedure ProjectChange(inSender: TObject);
procedure SetProject(const Value: TLrProject);
procedure SetSelectedItem(const Value: TLrProjectItem);
public
{ Public declarations }
DragItem: TLrProjectItem;
DropItem: TLrProjectItem;
procedure BuildTree;
property FolderItem[inItem: TLrTreeLeaf]: TLrProjectItem
read GetFolderItem;
property OnCanDrag: TLrItemCanEvent read FOnCanDrag write FOnCanDrag;
property OnCanDrop: TLrCanDropEvent read FOnCanDrop write FOnCanDrop;
property OnCanEdit: TLrItemCanEvent read FOnCanEdit write FOnCanEdit;
property OnDragDrop: TLrDragDropEvent read FOnDragDrop write FOnDragDrop;
property OnGetImageIndex: TLrGetImageIndexEvent read FOnGetImageIndex
write FOnGetImageIndex;
property OnGetOverlayIndex: TLrGetImageIndexEvent read FOnGetOverlayIndex
write FOnGetOverlayIndex;
property OnNewText: TLrNewTextEvent read FOnNewText write FOnNewText;
property OnOpenItem: TLrOpenItemEvent read FOnOpenItem write FOnOpenItem;
property Project: TLrProject read FProject write SetProject;
property SelectedItem: TLrProjectItem read GetSelectedItem
write SetSelectedItem;
property SelectedFolderItem: TLrProjectItem read GetSelectedFolderItem;
end;
var
LrProjectForm: TLrProjectForm;
implementation
{$R *.dfm}
procedure TLrProjectForm.SetProject(const Value: TLrProject);
begin
FProject := Value;
//Project.OnChange := ProjectChange;
BuildTree;
end;
procedure TLrProjectForm.ProjectChange(inSender: TObject);
begin
BuildTree;
end;
procedure TLrProjectForm.BuildTree;
begin
Tree.BeginUpdate;
try
Tree.Clear;
if Project = nil then
Tree.RootNodeCount := 0
else
Tree.RootNodeCount := Project.Items.Count;
Tree.FullExpand;
finally
Tree.EndUpdate;
end;
end;
function TLrProjectForm.GetNodeItems(inNode: PVirtualNode): TLrProjectItem;
begin
if (inNode = nil) or (inNode = Tree.RootNode) then
Result := Project.Items
else
Result := TLrProjectItem(Tree.GetNodeData(inNode)^);
end;
function TLrProjectForm.GetNodeItem(inNode: PVirtualNode): TLrProjectItem;
begin
Result := TLrProjectItem(GetNodeItems(inNode.Parent).Items[inNode.Index])
end;
procedure TLrProjectForm.TreeInitNode(Sender: TBaseVirtualTree;
ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
var
item: Pointer;
begin
with GetNodeItems(ParentNode) do
begin
item := Items[Node.Index];
Move(item, Sender.GetNodeData(Node)^, 4);
if Count > 0 then
Include(InitialStates, ivsHasChildren);
end;
end;
procedure TLrProjectForm.TreeInitChildren(Sender: TBaseVirtualTree;
Node: PVirtualNode; var ChildCount: Cardinal);
begin
ChildCount := GetNodeItem(Node).Count;
end;
procedure TLrProjectForm.TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
begin
with GetNodeItem(Node) do
case Column of
0: CellText := DisplayName;
1: CellText := Source;
end;
end;
procedure TLrProjectForm.TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
begin
case Column of
0:
case Kind of
ikNormal, ikSelected:
begin
ImageIndex := GetNodeItem(Node).ImageIndex;
if Assigned(OnGetImageIndex) then
OnGetImageIndex(GetNodeItem(Node), ImageIndex);
end;
ikOverlay:
begin
if Assigned(OnGetOverlayIndex) then
OnGetOverlayIndex(GetNodeItem(Node), ImageIndex);
end;
end;
end;
end;
function TLrProjectForm.GetSelectedItem: TLrProjectItem;
begin
if Tree.FocusedNode = nil then
Result := nil
else
Result := GetNodeItem(Tree.FocusedNode);
end;
procedure TLrProjectForm.SetSelectedItem(const Value: TLrProjectItem);
begin
//
end;
function TLrProjectForm.GetFolderItem(inItem: TLrTreeLeaf): TLrProjectItem;
begin
if inItem is TLrProjectItem then
Result := TLrProjectItem(inItem)
else
Result := nil;
while (Result <> nil) and not (Result is TLrFolderItem) do
Result := TLrProjectItem(Result.Parent);
if Result = nil then
Result := Project.Items;
end;
function TLrProjectForm.GetSelectedFolderItem: TLrProjectItem;
begin
Result := GetFolderItem(SelectedItem);
end;
procedure TLrProjectForm.TreeDragAllowed(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean);
begin
if Assigned(OnCanDrag) then
begin
DragItem := GetNodeItem(Node);
DragItem.Tag := Node.Index;
OnCanDrag(DragItem, Allowed);
end;
//Allowed := true;
end;
procedure TLrProjectForm.TreeDragOver(Sender: TBaseVirtualTree;
Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint;
Mode: TDropMode; var Effect: Integer; var Accept: Boolean);
begin
if Assigned(OnCanDrop) and ((Mode = dmOnNode) or (Mode = dmNowhere)) then
with Sender do
begin
if (DropTargetNode = nil) then
DropItem := nil
else begin
DropItem := GetNodeItem(DropTargetNode);
DropItem.Tag := DropTargetNode.Index;
end;
if not HasAsParent(DropTargetNode, FocusedNode) then
OnCanDrop(DragItem, DropItem, Shift, Accept);
end;
// Accept := (Tree.DropTargetNode <> nil)
//and GetNodeItem(Tree.DropTargetNode).IsFolder
// and (Mode = dmOnNode);
end;
procedure TLrProjectForm.TreeDragDrop(Sender: TBaseVirtualTree;
Source: TObject; DataObject: IDataObject; Formats: TFormatArray;
Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode);
begin
Effect := DROPEFFECT_NONE;
if Assigned(OnDragDrop) then
OnDragDrop(DragItem, DropItem, Shift);
// if Source = Sender then
// begin
//MoveNode(Tree.FocusedNode, Tree.DropTargetNode);
//BuildTree;
// end;
end;
procedure TLrProjectForm.TreeEditing(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean);
var
item: TLrProjectItem;
begin
if Assigned(OnCanEdit) then
begin
item := GetNodeItem(Node);
item.Tag := Node.Index;
OnCanEdit(item, Allowed);
end;
end;
procedure TLrProjectForm.TreeNewText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; NewText: WideString);
begin
if Assigned(OnNewText) then
OnNewText(GetNodeItem(Node), NewText);
end;
procedure TLrProjectForm.TreeDblClick(Sender: TObject);
begin
if Assigned(OnOpenItem) and (SelectedItem <> nil) then
OnOpenItem(SelectedItem);
end;
end.
|
unit Palette;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ImgList, ComCtrls, ExtCtrls,
DCPalette, dcpalet, DCGen,
LMDCustomComponent, LMDBaseController, LMDCustomContainer,
LMDCustomImageList, LMDImageList, LMDControl, LMDBaseControl,
LMDBaseGraphicControl, LMDBaseLabel, LMDCustomGlyphLabel, LMDGlyphLabel,
LMDGraph,
LrCollapsable;
type
TPaletteForm = class(TForm)
PaletteScroll: TScrollBox;
DCCompPalette1: TDCCompPalette;
LMDImageList1: TLMDImageList;
LrCollapsable1: TLrCollapsable;
LMDGlyphLabel3: TLMDGlyphLabel;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FSelectedLabel: TControl;
procedure PaletteLabelClick(Sender: TObject);
procedure PaletteLabelMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PaletteLabelMouseEnter(Sender: TObject);
procedure PaletteLabelMouseExit(Sender: TObject);
procedure SetSelectedLabel(const Value: TControl);
protected
procedure CreateWnd; override;
public
{ Public declarations }
procedure BuildPalette;
procedure GetAddClass(Sender: TObject; var ioClass: String);
property SelectedLabel: TControl read FSelectedLabel write SetSelectedLabel;
end;
var
PaletteForm: TPaletteForm;
implementation
uses
LrUtils, DesignManager;
{$R *.dfm}
procedure TPaletteForm.FormCreate(Sender: TObject);
begin
BuildPalette;
Width := Width + 1;
DesignMgr.OnGetAddClass := GetAddClass;
end;
procedure TPaletteForm.BuildPalette;
var
i, j: Integer;
l: TLMDGlyphLabel;
// r: TJvRollOut;
// r: TFoldingPanelForm;
// r: TLrGroup;
r: TLrCollapsable;
// r: TPanel;
{
procedure CreateGroup;
begin
r := TJvRollOut.Create(Self);
r.ParentColor := false;
//
r.Colors.ButtonBottom := clBlack;
r.Colors.ButtonColor := $00BEF3CA; //$00FDF9F7;
//r.Colors.ButtonTop := clRed;
r.Colors.FrameBottom := clWhite;
r.Colors.FrameTop := $0094EBA7; //$00F3D1BE;
//r.Colors.HotTrackText := clGray;
r.Colors.Color := clWhite; //$00EFF7F8;
//
r.ChildOffset := 1;
r.Parent := PaletteScroll;
r.Top := 9999;
r.Align := alTop;
r.AutoSize := true;
r.Caption := DCCompPalette1.Tabs[i];
end;
}
{
procedure CreateGroup;
begin
AddForm(r, TFoldingPanelForm, PaletteScroll);
r.Top := 9999;
r.Align := alTop;
end;
}
{
procedure CreateGroup(const inCaption: string);
begin
r := TLrGroup.Create(Self);
r.Caption := inCaption;
r.AutoSize := true;
r.Margin := 2;
r.Special := true;
r.Parent := LrBar1;
r.Top := 9999;
r.Align := alTop;
end;
}
procedure CreateGroup(const inCaption: string);
begin
r := TLrCollapsable.Create(Self);
r.Caption := inCaption;
r.AutoSize := true;
r.Parent := PaletteScroll;
r.Color := $F9F9F9;
r.HeaderColor := $E1E1E1;
r.ParentFont := true;
r.Font.Style := [ fsBold ];
//r.Top := 9999;
r.Align := alTop;
SetBounds(0, 0, 120, 120);
r.Visible := true;
end;
{
procedure CreateGroup(const inCaption: string);
begin
r := TPanel.Create(Self);
r.AutoSize := true;
r.BevelInner := TBevelCut(0);
r.BevelOuter := TBevelCut(0);
with LMDExplorerBar1.Sections.Add do
begin
Caption := inCaption;
HeaderSize := 20;
Style := ebsContainer;
LinkedControl := r;
Height := 120;
end;
end;
}
function AddImage(const inClass: TClass): Integer;
var
b, c: TBitmap;
begin
b := TBitmap.Create;
try
LoadBitmapForClass(b, inClass);
b.Transparent := true;
if (b.Width <> 16) then
begin
c := b;
b := TBitmap.Create;
try
b.Width := c.Width;
b.Height := c.Height;
b.Canvas.Brush.Color := clWhite;
b.Canvas.FillRect(Rect(0, 0, c.Width, c.Height));
b.Canvas.Draw(0, 0, c);
finally
c.Free;
end;
c := b;
b := TBitmap.Create;
try
b.Width := 16;
b.Height := 16;
b.Canvas.StretchDraw(Rect(0,0,15,15), c);
finally
c.Free;
end;
end;
Result := LMDImageList1.Items[0].Add(b, nil);
finally
b.Free;
end;
end;
procedure CreateLabel(inButton: TDCPaletteButton);
begin
l := TLMDGlyphLabel.Create(Self);
//
//l.Caption := TurboClassInfo.DisplayName[inButton.ButtonName];
l.Caption := inButton.ButtonName;
l.Hint := inButton.ButtonName;
//
l.Align := alTop;
l.Cursor := crHandPoint;
l.Bevel.StandardStyle := lsSingle;
l.Alignment.Alignment := agCenterLeft;
l.Color := clLime;
//l.DragMode := dmAutomatic;
//
l.OnMouseEnter := PaletteLabelMouseEnter;
l.OnMouseExit := PaletteLabelMouseExit;
l.OnClick := PaletteLabelClick;
//l.OnStartDrag := PaletteLabelStartDrag;
l.OnMouseDown := PaletteLabelMouseDown;
//
l.ImageList := LMDImageList1;
l.ListIndex := 0;
//l.ImageIndex := inButton.ImageIndex;
l.ImageIndex := AddImage(TDCCompButton(inButton).ComponentClass);
//
l.AutoSize := false;
l.Height := l.Height + 4;
//
l.Parent := r;
l.Font.Style := [];
//l.Parent := r.ContentPanel;
end;
begin
for i := 0 to Pred(DCCompPalette1.PageCount) do
begin
CreateGroup(DCCompPalette1.Tabs[i]);
with DCCompPalette1.ButtonTabs[i] do
begin
//r.Height := ButtonCount * 16 + 20;
for j := Pred(ButtonCount) downto 0 do
CreateLabel(Buttons[j]);
//r.Height := 0;
end;
end;
end;
procedure TPaletteForm.CreateWnd;
begin
inherited;
// if PaletteScroll <> nil then
// PaletteScroll.Realign;
end;
procedure TPaletteForm.FormShow(Sender: TObject);
begin
with PaletteScroll do
Width := Width + 1;
end;
procedure TPaletteForm.SetSelectedLabel(const Value: TControl);
begin
if (SelectedLabel <> nil) then
TLMDGlyphLabel(SelectedLabel).Font.Style := [ ];
FSelectedLabel := Value;
if (SelectedLabel <> nil) then
TLMDGlyphLabel(Value).Font.style := [ fsBold ];
end;
procedure TPaletteForm.PaletteLabelMouseEnter(Sender: TObject);
begin
with TLMDGlyphLabel(Sender) do
Font.Style := Font.Style + [ fsUnderline ];
end;
procedure TPaletteForm.PaletteLabelMouseExit(Sender: TObject);
begin
with TLMDGlyphLabel(Sender) do
Font.Style := Font.Style - [ fsUnderline ];
end;
procedure TPaletteForm.PaletteLabelMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
TControl(Sender).BeginDrag(False);
end;
procedure TPaletteForm.PaletteLabelClick(Sender: TObject);
begin
SelectedLabel := TControl(Sender);
end;
procedure TPaletteForm.GetAddClass(Sender: TObject; var ioClass: String);
begin
if SelectedLabel <> nil then
begin
ioClass := SelectedLabel.Hint;
SelectedLabel := nil;
end;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1999-2001 Borland Software Corp. }
{ }
{ Русификация: 2002 Polaris Software }
{ http://polesoft.da.ru }
{*******************************************************}
unit WbmDCnst;
interface
resourcestring
SFetchParams = 'Загрузить &Пар-ры';
SWebPageEdit = 'Редактор &веб страниц...';
SDeleteColumnsQuestion = 'Удалить созданные компоненты?';
sAddFields = 'Добавить поля...';
sAddAllFields = 'Добавить все поля';
sAddFieldsDlgCaption = 'Добавить поля';
sAddActions = 'Добавить Actions...';
sAddAllActions = 'Добавить все Actions...';
sAddActionsDlgCaption = 'Добавить Actions';
sRestoreDefaults = 'По умолчанию';
sAddParams = 'Все параметры...';
sAddAllParams = 'Добавить все пар-ры';
{$IFDEF MSWINDOWS}
sStylesFileFilter =
'Текстовые файлы (*.txt)|*.txt|Все файлы (*.*)|*.*';
{$ENDIF MSWINDOWS}
{$IFDEF LINUX}
sStylesFileFilter =
'Текстовые файлы (*.txt)|*.txt|Все файлы (*)|*';
{$ENDIF LINUX}
sOpenTransformFileFilter = 'XTR файлы (*.xtr)|*.xtr';
sTransformFileExt = 'xtr';
sOpenTransformFileTitle = 'Открыть файл преобразования';
sOpenXmlFileFilter = 'XML файлы (*.xml)|*.xml';
sXmlFileExt = 'xml';
sOpenXmlFileTitle = 'Открыть Xml файл';
srDAccess = 'Доступ к данным';
implementation
end.
|
program HowToControlTheGameSpeed;
uses
SwinGame, sgTypes;
procedure DoWalking(sprt: Sprite; key: KeyCode;const animationName: String; dx, dy: Single);
begin
if KeyDown(key) then
begin
SpriteStartAnimation(sprt, animationName);
SpriteSetDX(sprt, dx);
SpriteSetDY(sprt, dy);
end;
end;
procedure Main();
var
myFrog: Sprite;
gameTime: Timer;
ticks, lastUpdate: Integer;
fraction: single;
begin
OpenAudio();
OpenGraphicsWindow('Controlling Gamespeed', 800, 600);
LoadResourceBundle('dance_bundle.txt');
myFrog := CreateSprite(BitmapNamed('FrogBmp'), AnimationScriptNamed('WalkingScript'));
SpriteStartAnimation(myFrog, 'StandFront');
SpriteSetX(myFrog, 382);
SpriteSetY(myFrog, 274);
gameTime := CreateTimer();
StartTimer(gameTime);
fraction := 0.0;
lastUpdate := 0;
repeat
ProcessEvents();
ClearScreen(ColorWhite);
DrawSprite(myFrog);
RefreshScreen();
UpdateSprite(myFrog, fraction);
ticks := TimerTicks(gameTime);
fraction := (ticks - lastUpdate) / 10;
lastUpdate := ticks;
if SpriteAnimationHasEnded(myFrog) then
begin
SpriteSetDX(myFrog, 0);
SpriteSetDY(myFrog, 0);
DoWalking(myFrog, UPKey, 'WalkBack', 0, -0.25);
DoWalking(myFrog, DOWNKey, 'WalkFront', 0, +0.25);
DoWalking(myFrog, LEFTKey, 'WalkLeft', -0.25, 0);
DoWalking(myFrog, RIGHTKey, 'WalkRight', +0.25, 0);
DoWalking(myFrog, WKey, 'MoonWalkBack', 0, -0.25);
DoWalking(myFrog, SKey, 'MoonWalkFront', 0, +0.25);
DoWalking(myFrog, AKey, 'MoonWalkLeft', -0.25, 0);
DoWalking(myFrog, DKey, 'MoonWalkRight', +0.25, 0);
end;
until WindowCloseRequested();
FreeSprite(myFrog);
CloseAudio();
ReleaseAllResources();
end;
begin
Main();
end. |
unit Contracts_Periods_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxCurrencyEdit,
cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar,
cxControls, cxGroupBox,
cnConsts,cnConsts_Messages, Dm, ibase;
type
Tfrm_Contracts_Periods_AE = class(TForm)
GroupBox: TcxGroupBox;
Date_End_Label: TLabel;
Date_End_DateEdit: TcxDateEdit;
Date_Beg_Label: TLabel;
Date_Beg_DateEdit: TcxDateEdit;
Date_Opl_Label: TLabel;
Date_Opl_DateEdit: TcxDateEdit;
Summa_Edit: TcxCurrencyEdit;
Summa_Label: TLabel;
OkButton: TcxButton;
CancelButton: TcxButton;
id_payer_ComboBox: TcxComboBox;
id_stud_ComboBox: TcxComboBox;
id_stud_Label: TLabel;
id_payer_Label: TLabel;
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Date_Beg_DateEditKeyPress(Sender: TObject; var Key: Char);
procedure Date_End_DateEditKeyPress(Sender: TObject;
var Key: Char);
procedure Date_Opl_DateEditKeyPress(Sender: TObject; var Key: Char);
procedure Summa_EditKeyPress(Sender: TObject; var Key: Char);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Date_Beg_DateEditPropertiesChange(Sender: TObject);
private
PLanguageIndex, EndMonth:byte;
DateStart : TDate;
DM:TDM_Contracts;
DBHandle:TISC_DB_HANDLE;
procedure FormIniLanguage;
public
CountMonthAE: integer;
SummaAE : Currency;
constructor Create(AOwner:TComponent; LanguageIndex : byte; DBH : TISC_DB_HANDLE);reintroduce;
end;
implementation
uses Contract_Add_Edit;
{$R *.dfm}
constructor Tfrm_Contracts_Periods_AE.Create(AOwner:TComponent; LanguageIndex : byte; DBH : TISC_DB_HANDLE);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
PLanguageIndex:= LanguageIndex;
FormIniLanguage();
DBHandle := DBH;
// проверяем дату старта системы
Dm := TDM_Contracts.Create(self);
Dm.DB.Handle := DBHandle;
Dm.ReadDataSet.SelectSQL.Text := 'select CN_DATE_START from CN_PUB_SYS_DATA_GET_ALL';
Dm.ReadDataSet.Open;
if Dm.ReadDataSet['CN_DATE_START'] <> null then
DateStart:= Dm.ReadDataSet['CN_DATE_START']
else
DateStart:= strtodate('01.01.1900');
Dm.ReadDataSet.Close;
// далее проверяем признак разбивки по 30-е число
Dm.ReadDataSet.SelectSQL.Clear;
Dm.ReadDataSet.SelectSQL.Text := 'select * from CN_GET_END_MONTH';
Dm.ReadDataSet.Open;
if Dm.ReadDataSet['CN_END_MONTH'] <> null then
EndMonth:= Dm.ReadDataSet['CN_END_MONTH']
else
EndMonth:= 0;
Dm.ReadDataSet.Close;
Screen.Cursor:=crDefault;
end;
procedure Tfrm_Contracts_Periods_AE.FormIniLanguage;
begin
Date_Beg_Label.Caption:= cnConsts.cn_Date_Beg_Label[PLanguageIndex];
Date_End_Label.Caption:= cnConsts.cn_Date_End_Label[PLanguageIndex];
Date_Opl_Label.Caption:= cnConsts.cn_Periods_DateOpl[PLanguageIndex];
Summa_Label.Caption:= cnConsts.cn_Summa_Column[PLanguageIndex];
id_stud_Label.Caption:= cnConsts.cn_Studer_Osoba[PLanguageIndex];
id_payer_Label.Caption:= cnConsts.cn_Payer_Osoba[PLanguageIndex];
OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex];
CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex];
end;
procedure Tfrm_Contracts_Periods_AE.OkButtonClick(Sender: TObject);
begin
// проверки на непустые поля заполнения
if Date_Beg_DateEdit.Text = ''
then
begin
showmessage(cnConsts.cn_Periods_Date_Beg_Need[PLanguageIndex]);
Date_Beg_DateEdit.SetFocus;
exit;
end;
if Date_End_DateEdit.Text = ''
then
begin
showmessage(cnConsts.cn_Periods_Date_End_Need[PLanguageIndex]);
Date_End_DateEdit.SetFocus;
exit;
end;
if Date_Opl_DateEdit.Text = ''
then
begin
showmessage(cnConsts.cn_Periods_Date_Pay_Need[PLanguageIndex]);
Date_Opl_DateEdit.SetFocus;
exit;
end;
{if Summa_Edit.Value = 0
then
begin
showmessage(cnConsts.cn_Periods_Date_PaySum_Need[PLanguageIndex]);
Summa_Edit.SetFocus;
exit;
end;
}
// проверяю период- не даю добавлять до даты старта
if ((Date_Beg_DateEdit.Date < DateStart) or (Date_End_DateEdit.Date < DateStart)) then
begin
showmessage(cn_PeriodsLessDateStart[PLanguageIndex]);
exit;
end;
if (Date_Beg_DateEdit.Date >= Date_End_DateEdit.Date ) then
begin
showmessage(cn_DateBegNeedMoreDateEnd[PLanguageIndex]);
Date_End_DateEdit.SetFocus;
exit;
end;
ModalResult:=mrOk;
end;
procedure Tfrm_Contracts_Periods_AE.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure Tfrm_Contracts_Periods_AE.FormShow(Sender: TObject);
begin
Date_Beg_DateEdit.setfocus;
end;
procedure Tfrm_Contracts_Periods_AE.Date_Beg_DateEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then Date_End_DateEdit.SetFocus;
end;
procedure Tfrm_Contracts_Periods_AE.Date_End_DateEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then Date_Opl_DateEdit.SetFocus;
end;
procedure Tfrm_Contracts_Periods_AE.Date_Opl_DateEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then Summa_Edit.SetFocus;
end;
procedure Tfrm_Contracts_Periods_AE.Summa_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then OkButton.SetFocus;
end;
procedure Tfrm_Contracts_Periods_AE.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Dm.Free;
end;
procedure Tfrm_Contracts_Periods_AE.Date_Beg_DateEditPropertiesChange(
Sender: TObject);
begin
if Caption = cnConsts.cn_InsertBtn_Caption[PLanguageIndex] then
if Length(Date_Beg_DateEdit.Text)= 10 then
begin
Date_Beg_DateEdit.Date := strtodate(Date_Beg_DateEdit.Text);
DM.StProc.StoredProcName := 'CN_INC_DATE';
DM.StProc.Transaction.StartTransaction;
DM.StProc.Prepare;
DM.StProc.ParamByName('INDATE').AsDate := Date_Beg_DateEdit.Date;
DM.StProc.ParamByName('CNT_DAY').AsVariant := null;
DM.StProc.ParamByName('CNT_YEAR').AsVariant := null;
DM.StProc.ParamByName('CNT_MONTH').AsInteger := CountMonthAE;
DM.StProc.ExecProc;
Date_End_DateEdit.Date := DM.StProc.ParamByName('OUTDATE').AsDate;
DM.StProc.Transaction.Commit;
if bool(EndMonth) then
begin
DM.StProc.StoredProcName := 'CN_INC_DATE';
DM.StProc.Transaction.StartTransaction;
DM.StProc.Prepare;
DM.StProc.ParamByName('INDATE').AsDate := Date_End_DateEdit.Date;
DM.StProc.ParamByName('CNT_DAY').AsInteger := -1;
DM.StProc.ParamByName('CNT_YEAR').AsVariant := null;
DM.StProc.ParamByName('CNT_MONTH').AsVariant := null;
DM.StProc.ExecProc;
Date_End_DateEdit.Date := DM.StProc.ParamByName('OUTDATE').AsDate;
DM.StProc.Transaction.Commit;
end;
Date_Opl_DateEdit.Date := Date_End_DateEdit.Date;
Summa_Edit.Value := SummaAE;
end;
end;
end.
|
unit UStringList;
(*====================================================================
Better implementation of string list than Delphi provides
in contrast to TStringList
- deallocates also objects, not only strings
- Capacity can be set
- beter reallocation of the array of pointers
======================================================================*)
interface
uses UTypes, SysUtils, Classes;
const
{ Maximum TList size }
{$ifdef DELPHI1}
QMaxListSize = 65520 div SizeOf(Pointer);
{$else}
QMaxListSize = Maxint div SizeOf(Pointer);
{$endif}
type
{ Standard events }
EQListError = class(Exception);
{ TList class }
PQPointerList = ^TQPointerList;
TQPointerList = array[0..QMaxListSize - 1] of Pointer;
TQList = class(TObject)
private
FList: PQPointerList;
FCount: Integer;
FCapacity: Integer;
protected
procedure Error; virtual;
function Get(Index: Integer): Pointer;
procedure Grow; virtual;
procedure Put(Index: Integer; Item: Pointer);
procedure SetCapacity(NewCapacity: Integer);
procedure SetCount(NewCount: Integer);
public
destructor Destroy; override;
function Add(Item: Pointer): Integer;
procedure Clear;
procedure Delete(Index: Integer);
procedure Exchange(Index1, Index2: Integer);
function Expand: TQList;
function First: Pointer;
function IndexOf(Item: Pointer): Integer;
procedure Insert(Index: Integer; Item: Pointer);
function Last: Pointer;
procedure Move(CurIndex, NewIndex: Integer);
function Remove(Item: Pointer): Integer;
procedure Pack;
property Capacity: Integer read FCapacity write SetCapacity;
property Count: Integer read FCount write SetCount;
property Items[Index: Integer]: Pointer read Get write Put; default;
property List: PQPointerList read FList;
end;
{ TStringList class }
TQDuplicates = (qdupIgnore, qdupAccept, qdupError);
TQStringList = class(TObject)
private
FList: TQList;
FSorted: Boolean;
FReversed: Boolean;
FDuplicates: TQDuplicates;
procedure QuickSort(L, R: Integer);
procedure SetSorted(Value: Boolean);
procedure SetReversed(Value: Boolean);
protected
function Get(Index: Integer): ShortString; virtual;
function GetCount: Integer; virtual;
function GetObject(Index: Integer): TObject; virtual;
procedure Put(Index: Integer; const S: ShortString); virtual;
procedure PutObject(Index: Integer; AObject: TObject); virtual;
function GetCapacity: Integer;
procedure SetCapacity(ACapacity: Integer);
public
constructor Create;
destructor Destroy; override;
function Add(const S: ShortString): Integer; virtual;
function AddObject(const S: ShortString; AObject: TObject): Integer; virtual;
procedure Clear; virtual;
procedure Delete(Index: Integer); virtual;
procedure Exchange(Index1, Index2: Integer); virtual;
function Find(const S: ShortString; var Index: Integer): Boolean; virtual;
function IndexOf(const S: ShortString): Integer; virtual;
function IndexOfObject(AObject: TObject): Integer;
procedure Insert(Index: Integer; const S: ShortString); virtual;
procedure InsertObject(Index: Integer; const S: ShortString;
AObject: TObject);
procedure Sort; virtual;
property Duplicates: TQDuplicates read FDuplicates write FDuplicates;
property Sorted: Boolean read FSorted write SetSorted;
property Reversed: Boolean read FReversed write SetReversed;
property Objects[Index: Integer]: TObject read GetObject {write PutObject};
property Strings[Index: Integer]: ShortString read Get write Put; default;
property Count: Integer read GetCount;
property Capacity: Integer read GetCapacity write SetCapacity;
end;
{ StrItem management, shared by TQStringList and TStringSparseList }
type
PQStrItem = ^TQStrItem;
TQStrItem = record
FObject: TObject;
FString: ShortString;
end;
function NewQStrItem (const AString: ShortString; AObject: TObject): PQStrItem;
function ChangeStrInQStrItem(OldQStrItem: PQStrItem; const AString: ShortString): PQStrItem;
procedure DisposeQStrItem(P: PQStrItem);
procedure FreeObjects(List:TStringList);
implementation
///uses Consts;
procedure FreeObjects(List:TStringList);
var
i: integer;
begin
for i := 0 to List.Count - 1 do
List.Objects[i].Free;
end;
//-----------------------------------------------------------------------------
procedure ListError(Ident: String);
begin
raise EQListError.Create(Ident);
end;
//=== TQList ==================================================================
destructor TQList.Destroy;
begin
Clear;
end;
//-----------------------------------------------------------------------------
function TQList.Add(Item: Pointer): Integer;
begin
Result := FCount;
if Result = FCapacity then Grow;
FList^[Result] := Item;
Inc(FCount);
end;
//-----------------------------------------------------------------------------
procedure TQList.Clear;
begin
SetCount(0);
SetCapacity(0);
end;
//-----------------------------------------------------------------------------
procedure TQList.Delete(Index: Integer);
begin
if (Index < 0) or (Index >= FCount) then Error;
Dec(FCount);
if Index < FCount then
System.Move(FList^[Index + 1], FList^[Index],
(FCount - Index) * SizeOf(Pointer));
end;
//-----------------------------------------------------------------------------
procedure TQList.Error;
begin
///ListError(SListIndexError);
ListError('SListIndexError');
end;
//-----------------------------------------------------------------------------
procedure TQList.Exchange(Index1, Index2: Integer);
var
Item: Pointer;
begin
if (Index1 < 0) or (Index1 >= FCount) or
(Index2 < 0) or (Index2 >= FCount) then Error;
Item := FList^[Index1];
FList^[Index1] := FList^[Index2];
FList^[Index2] := Item;
end;
//-----------------------------------------------------------------------------
function TQList.Expand: TQList;
begin
if FCount = FCapacity then Grow;
Result := Self;
end;
//-----------------------------------------------------------------------------
function TQList.First: Pointer;
begin
Result := Get(0);
end;
//-----------------------------------------------------------------------------
function TQList.Get(Index: Integer): Pointer;
begin
if (Index < 0) or (Index >= FCount) then Error;
Result := FList^[Index];
end;
//-----------------------------------------------------------------------------
procedure TQList.Grow;
var
Delta: Integer;
begin
if FCapacity > 16 then Delta := FCapacity div 3 else {add 30%}
if FCapacity > 8 then Delta := 16 else
if FCapacity > 4 then Delta := 8 else
Delta := 4;
if (Delta > (QMaxListSize-FCapacity)) and (FCapacity < QMaxListSize) then
Delta := QMaxListSize - FCapacity;
SetCapacity(FCapacity + Delta);
end;
//-----------------------------------------------------------------------------
function TQList.IndexOf(Item: Pointer): Integer;
begin
Result := 0;
while (Result < FCount) and (FList^[Result] <> Item) do Inc(Result);
if Result = FCount then Result := -1;
end;
//-----------------------------------------------------------------------------
procedure TQList.Insert(Index: Integer; Item: Pointer);
begin
if (Index < 0) or (Index > FCount) then Error;
if FCount = FCapacity then Grow;
if Index < FCount then
System.Move(FList^[Index], FList^[Index + 1],
(FCount - Index) * SizeOf(Pointer));
FList^[Index] := Item;
Inc(FCount);
end;
//-----------------------------------------------------------------------------
function TQList.Last: Pointer;
begin
Result := Get(FCount - 1);
end;
//-----------------------------------------------------------------------------
procedure TQList.Move(CurIndex, NewIndex: Integer);
var
Item: Pointer;
begin
if CurIndex <> NewIndex then
begin
if (NewIndex < 0) or (NewIndex >= FCount) then Error;
Item := Get(CurIndex);
Delete(CurIndex);
Insert(NewIndex, Item);
end;
end;
//-----------------------------------------------------------------------------
procedure TQList.Put(Index: Integer; Item: Pointer);
begin
if (Index < 0) or (Index >= FCount) then Error;
FList^[Index] := Item;
end;
//-----------------------------------------------------------------------------
function TQList.Remove(Item: Pointer): Integer;
begin
Result := IndexOf(Item);
if Result <> -1 then Delete(Result);
end;
//-----------------------------------------------------------------------------
procedure TQList.Pack;
var
I: Integer;
begin
for I := FCount - 1 downto 0 do if Items[I] = nil then Delete(I);
end;
//-----------------------------------------------------------------------------
procedure TQList.SetCapacity(NewCapacity: Integer);
var
NewList: PQPointerList;
begin
if (NewCapacity < FCount) or (NewCapacity > QMaxListSize) then Error;
if NewCapacity <> FCapacity then
begin
if NewCapacity = 0 then NewList := nil else
begin
GetMem(NewList, NewCapacity * SizeOf(Pointer));
if FCount <> 0 then
System.Move(FList^, NewList^, FCount * SizeOf(Pointer));
end;
if FCapacity <> 0 then FreeMem(FList, FCapacity * SizeOf(Pointer));
FList := NewList;
FCapacity := NewCapacity;
end;
end;
//-----------------------------------------------------------------------------
procedure TQList.SetCount(NewCount: Integer);
begin
if (NewCount < 0) or (NewCount > QMaxListSize) then Error;
if NewCount > FCapacity then SetCapacity(NewCount);
if NewCount > FCount then
FillChar(FList^[FCount], (NewCount - FCount) * SizeOf(Pointer), 0);
FCount := NewCount;
end;
//=== TQStringList ============================================================
function NewQStrItem(const AString: ShortString; AObject: TObject): PQStrItem;
begin
GetMem(Result, Length(AString) + 5);
Result^.FObject := AObject;
Result^.FString := AString;
end;
//-----------------------------------------------------------------------------
function ChangeStrInQStrItem(OldQStrItem: PQStrItem; const AString: ShortString): PQStrItem;
begin
GetMem(Result, Length(AString) + 5);
Result^.FObject := OldQStrItem^.FObject;
Result^.FString := AString;
FreeMem(OldQStrItem, Length(OldQStrItem^.FString) + 5);
end;
//-----------------------------------------------------------------------------
procedure DisposeQStrItem(P: PQStrItem);
begin
if P^.FObject <> nil then P^.FObject.Destroy;
FreeMem(P, Length(P^.FString) + 5);
end;
//-----------------------------------------------------------------------------
constructor TQStringList.Create;
begin
FList := TQList.Create;
end;
//-----------------------------------------------------------------------------
destructor TQStringList.Destroy;
begin
if FList <> nil then
begin
Clear;
FList.Free;
end;
end;
//-----------------------------------------------------------------------------
function TQStringList.Add(const S: ShortString): Integer;
begin
if not Sorted then
Result := FList.Count
else
if Find(S, Result) then
case Duplicates of
qdupIgnore: Exit;
///qdupError: ListError(SDuplicateString);
qdupError: ListError('SDuplicateString');
end;
FList.Expand.Insert(Result, NewQStrItem(S, nil));
end;
//-----------------------------------------------------------------------------
function TQStringList.AddObject(const S: ShortString; AObject: TObject): Integer;
begin
Result := Add(S);
PutObject(Result, AObject);
end;
//-----------------------------------------------------------------------------
procedure TQStringList.Clear;
var
I: Integer;
begin
for I := 0 to FList.Count - 1 do DisposeQStrItem(FList[I]);
FList.Clear;
end;
//-----------------------------------------------------------------------------
procedure TQStringList.Delete(Index: Integer);
begin
DisposeQStrItem(FList[Index]);
FList.Delete(Index);
end;
//-----------------------------------------------------------------------------
procedure TQStringList.Exchange(Index1, Index2: Integer);
begin
FList.Exchange(Index1, Index2);
end;
//-----------------------------------------------------------------------------
function TQStringList.Find(const S: ShortString; var Index: Integer): Boolean;
var
L, H, I, C: Integer;
begin
Result := False;
L := 0;
H := Count - 1;
while L <= H do
begin
I := (L + H) shr 1;
if FReversed
then C := AnsiCompareText(S, PQStrItem(FList[I])^.FString)
else C := AnsiCompareText(PQStrItem(FList[I])^.FString, S);
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
if Duplicates <> qdupAccept then L := I;
end;
end;
end;
Index := L;
end;
//-----------------------------------------------------------------------------
function TQStringList.Get(Index: Integer): ShortString;
begin
Result := PQStrItem(FList[Index])^.FString;
end;
//-----------------------------------------------------------------------------
function TQStringList.GetCount: Integer;
begin
Result := FList.Count;
end;
//-----------------------------------------------------------------------------
function TQStringList.GetObject(Index: Integer): TObject;
begin
Result := PQStrItem(FList[Index])^.FObject;
end;
//-----------------------------------------------------------------------------
function TQStringList.IndexOf(const S: ShortString): Integer;
begin
if not Sorted
then
begin
for Result := 0 to GetCount - 1 do
if CompareText(Get(Result), S) = 0 then Exit;
Result := -1;
end
else
if not Find(S, Result) then Result := -1;
end;
//-----------------------------------------------------------------------------
procedure TQStringList.Insert(Index: Integer; const S: ShortString);
begin
///if Sorted then ListError(SSortedListError);
if Sorted then ListError('SSortedListError');
FList.Expand.Insert(Index, NewQStrItem(S, nil));
end;
//-----------------------------------------------------------------------------
procedure TQStringList.InsertObject(Index: Integer; const S: ShortString;
AObject: TObject);
begin
Insert(Index, S);
PutObject(Index, AObject);
end;
//-----------------------------------------------------------------------------
procedure TQStringList.Put(Index: Integer; const S: ShortString);
begin
///if Sorted then ListError(SSortedListError);
if Sorted then ListError('SSortedListError');
FList[Index] := ChangeStrInQStrItem(FList[Index], S);
end;
//-----------------------------------------------------------------------------
procedure TQStringList.PutObject(Index: Integer; AObject: TObject);
begin
PQStrItem(FList[Index])^.FObject := AObject;
end;
//-----------------------------------------------------------------------------
procedure TQStringList.QuickSort(L, R: Integer);
var
I, J: Integer;
P: PQStrItem;
begin
I := L;
J := R;
P := PQStrItem(FList[(L + R) shr 1]);
repeat
if FReversed
then
begin
while AnsiCompareText(PQStrItem(FList[I])^.FString, P^.FString) > 0 do Inc(I);
while AnsiCompareText(PQStrItem(FList[J])^.FString, P^.FString) < 0 do Dec(J);
end
else
begin
while AnsiCompareText(PQStrItem(FList[I])^.FString, P^.FString) < 0 do Inc(I);
while AnsiCompareText(PQStrItem(FList[J])^.FString, P^.FString) > 0 do Dec(J);
end;
if I <= J then
begin
FList.Exchange(I, J);
Inc(I);
Dec(J);
end;
until I > J;
if L < J then QuickSort(L, J);
if I < R then QuickSort(I, R);
end;
//-----------------------------------------------------------------------------
procedure TQStringList.SetSorted(Value: Boolean);
begin
if FSorted <> Value then
begin
if Value then Sort;
FSorted := Value;
end;
end;
//-----------------------------------------------------------------------------
procedure TQStringList.SetReversed(Value: Boolean);
begin
if FReversed <> Value then
begin
FReversed := Value;
if Sorted then Sort;
end;
end;
//-----------------------------------------------------------------------------
procedure TQStringList.Sort;
begin
if not Sorted and (FList.Count > 1) then
QuickSort(0, FList.Count - 1);
end;
//-----------------------------------------------------------------------------
function TQStringList.IndexOfObject(AObject: TObject): Integer;
begin
for Result := 0 to GetCount - 1 do
if GetObject(Result) = AObject then Exit;
Result := -1;
end;
//-----------------------------------------------------------------------------
function TQStringList.GetCapacity: Integer;
begin
Result := FList.Capacity;
end;
//-----------------------------------------------------------------------------
procedure TQStringList.SetCapacity(ACapacity: Integer);
begin
FList.Capacity := ACapacity;
end;
//-----------------------------------------------------------------------------
end.
|
unit DSA.Interfaces.DataStructure;
interface
uses
Classes,
SysUtils,
DSA.Graph.Edge;
type
IStack<T> = interface
['{F4C21C9B-5BB0-446D-BBA0-43343B7E8A04}']
function GetSize: integer;
function IsEmpty: boolean;
procedure Push(e: T);
function Pop: T;
function Peek: T;
end;
IQueue<T> = interface
['{1454F65C-3628-488C-891A-4A4F6EDECCDA}']
function GetSize: integer;
function IsEmpty: boolean;
procedure EnQueue(e: T);
function DeQueue: T;
function Peek: T;
end;
ISet<T> = interface
['{EB3DEBD8-1473-4AD1-90B2-C5CEF2AD2A97}']
procedure Add(e: T);
procedure Remove(e: T);
function Contains(e: T): boolean;
function GetSize: integer;
function IsEmpty: boolean;
end;
TPtr_V<V> = packed record
public
PValue: ^V;
end;
IMap<K, V> = interface
['{4D344A23-A724-4120-80D8-C7F07F33D367}']
function Contains(key: K): boolean;
function Get(key: K): TPtr_V<V>;
function GetSize: integer;
function IsEmpty: boolean;
function Remove(key: K): TPtr_V<V>;
procedure Add(key: K; Value: V);
procedure Set_(key: K; Value: V);
end;
IMerger<T> = interface
['{B417FA36-9603-4CDA-9AAE-1EA445B6E63E}']
function Merge(Left, Right: T): T;
end;
IUnionFind = interface
['{3EFCB11A-32EE-4852-8D5D-AFC6F3665933}']
function GetSize: integer;
function IsConnected(p, q: integer): boolean;
procedure UnionElements(p, q: integer);
end;
IGraph = interface
['{CEBEE316-FBAD-4C3D-A39E-B324AD097827}']
function Vertex: integer;
function Edge: integer;
function HasEdge(V: integer; w: integer): boolean;
procedure AddEdge(V: integer; w: integer);
function AdjIterator(V: integer): TArray<integer>;
procedure Show;
end;
IIterator = interface
['{9D13D226-BE98-4658-B9A4-53513A3E24C7}']
function Start: integer;
function Next: integer;
function Finished: boolean;
end;
TWeightGraph<T> = class abstract
protected type
TEdge_T = TEdge<T>;
TArrEdge = TArray<TEdge_T>;
public
function Vertex: integer; virtual; abstract;
function Edge: integer; virtual; abstract;
function HasEdge(V: integer; w: integer): boolean; virtual; abstract;
function AdjIterator(V: integer): TArrEdge; virtual; abstract;
procedure AddEdge(V, w: integer; weight: T); virtual; abstract;
procedure Show; virtual; abstract;
end;
implementation
end.
|
unit Model;
interface
uses Palette, HierarchyAnimation, Mesh, BasicFunctions, BasicDataTypes, dglOpenGL, LOD,
SysUtils, Graphics, GlConstants, ShaderBank, Histogram;
{$INCLUDE source/Global_Conditionals.inc}
type
PModel = ^TModel;
TModel = class
protected
FOpened : boolean;
FType: integer;
FRequestUpdateWorld: boolean;
// Gets
function GetRequestUpdateWorld: boolean;
public
ID: integer;
Palette : PPalette;
IsVisible : boolean;
// Skeleton:
HA : PHierarchyAnimation;
LOD : array of TLOD;
CurrentLOD : integer;
// Source
Filename : string;
// GUI
IsSelected : boolean;
// Others
ShaderBank : PShaderBank;
// constructors and destructors
constructor Create(const _Filename: string; _ShaderBank : PShaderBank); overload; virtual;
constructor Create(const _Model: TModel); overload; virtual;
destructor Destroy; override;
procedure CommonCreationProcedures;
procedure Initialize(); virtual;
procedure ClearLODs;
procedure Clear; virtual;
procedure Reset;
// I/O
procedure SaveLODToFile(const _Filename, _TexExt: string);
// Gets
function GetNumLODs: longword;
function IsOpened : boolean;
function GetVertexCount: longword;
function GetPolyCount: longword;
function GetVoxelCount: longword; virtual;
// Sets
procedure SetNormalsModeRendering;
procedure SetColourModeRendering;
procedure SetQuality(_value: integer); virtual;
// Rendering methods
procedure Render;
procedure RenderVectorial;
procedure ProcessNextFrame;
// Refresh OpenGL List
procedure RefreshModel;
procedure RefreshMesh(_MeshID: integer);
// Textures
procedure ExportTextures(const _BaseDir, _Ext: string; _previewTextures: boolean);
procedure ExportHeightMap(const _BaseDir, _Ext : string; _previewTextures: boolean);
procedure SetTextureNumMipMaps(_NumMipMaps, _TextureType: integer);
// Transparency methods
procedure ForceTransparency(_level: single);
procedure ForceTransparencyOnMesh(_Level: single; _MeshID: integer);
procedure ForceTransparencyExceptOnAMesh(_Level: single; _MeshID: integer);
// Palette Related
procedure ChangeRemappable (_Colour : TColor); virtual;
procedure ChangePalette(const _Filename: string); virtual;
// GUI
procedure SetSelection(_value: boolean);
// Copies
procedure Assign(const _Model: TModel); virtual;
// Mesh Optimization
procedure RemoveInvisibleFaces;
// Quality Assurance
function GetAspectRatioHistogram(): THistogram;
function GetSkewnessHistogram(): THistogram;
function GetSmoothnessHistogram(): THistogram;
procedure FillAspectRatioHistogram(var _Histogram: THistogram);
procedure FillSkewnessHistogram(var _Histogram: THistogram);
procedure FillSmoothnessHistogram(var _Histogram: THistogram);
// Mesh Plugins
procedure AddNormalsPlugin;
procedure RemoveNormalsPlugin;
property ModelType: integer read FType;
property RequestUpdateWorld: boolean read GetRequestUpdateWorld write FRequestUpdateWorld;
end;
implementation
uses GlobalVars, GenericThread;
constructor TModel.Create(const _Filename: string; _ShaderBank : PShaderBank);
begin
Filename := CopyString(_Filename);
ShaderBank := _ShaderBank;
// Create a new 32 bits palette.
New(Palette);
Palette^ := TPalette.Create;
CommonCreationProcedures;
end;
constructor TModel.Create(const _Model: TModel);
begin
Assign(_Model);
end;
destructor TModel.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TModel.CommonCreationProcedures;
begin
CurrentLOD := 0;
FOpened := false;
HA := nil;
ID := GlobalVars.ModelBank.NextID;
Reset;
end;
procedure TModel.Reset;
begin
ClearLODs;
Initialize;
end;
procedure TModel.ClearLODs;
var
i : integer;
begin
i := High(LOD);
while i >= 0 do
begin
LOD[i].Free;
dec(i);
end;
SetLength(LOD,0);
end;
procedure TModel.Clear;
begin
ClearLODs;
Palette^.Free;
Palette := nil;
if HA <> nil then
begin
HA^.Free;
end;
HA := nil;
end;
procedure TModel.Initialize();
begin
FType := C_MT_STANDARD;
if HA = nil then
begin
new(HA);
if CurrentLOD <= High(LOD) then
begin
if High(LOD[CurrentLOD].Mesh) >= 0 then
begin
HA^ := THierarchyAnimation.Create(High(LOD[CurrentLOD].Mesh)+1, 1);
end
else
begin
HA^ := THierarchyAnimation.Create(1, 1);
end;
end
else
begin
HA^ := THierarchyAnimation.Create(1, 1);
end;
end;
IsVisible := true;
end;
// I/O
procedure TModel.SaveLODToFile(const _Filename, _TexExt: string);
begin
LOD[CurrentLOD].SaveToFile(_Filename,_TexExt);
end;
// Gets
function TModel.GetNumLODs: longword;
begin
Result := High(LOD) + 1;
end;
function TModel.IsOpened : boolean;
begin
Result := FOpened;
end;
function TModel.GetVertexCount: longword;
var
i: integer;
begin
Result := 0;
for i := Low(LOD[CurrentLOD].Mesh) to High(LOD[CurrentLOD].Mesh) do
begin
if LOD[CurrentLOD].Mesh[i].Opened and LOD[CurrentLOD].Mesh[i].IsVisible then
begin
inc(Result, LOD[CurrentLOD].Mesh[i].GetNumVertices);
end;
end;
end;
function TModel.GetPolyCount: longword;
var
i: integer;
begin
Result := 0;
for i := Low(LOD[CurrentLOD].Mesh) to High(LOD[CurrentLOD].Mesh) do
begin
if LOD[CurrentLOD].Mesh[i].Opened and LOD[CurrentLOD].Mesh[i].IsVisible then
begin
inc(Result, LOD[CurrentLOD].Mesh[i].NumFaces);
end;
end;
end;
function TModel.GetVoxelCount: longword;
begin
Result := 0;
end;
function TModel.GetRequestUpdateWorld: boolean;
begin
Result := FRequestUpdateWorld;
FRequestUpdateWorld := false;
end;
// Sets
procedure TModel.SetQuality(_value: integer);
begin
// do nothing.
end;
procedure TModel.SetNormalsModeRendering;
var
i : integer;
begin
for i := Low(LOD) to High(LOD) do
begin
LOD[i].SetNormalsModeRendering;
end;
end;
procedure TModel.SetColourModeRendering;
var
i : integer;
begin
for i := Low(LOD) to High(LOD) do
begin
LOD[i].SetColourModeRendering;
end;
end;
// Rendering methods
procedure TModel.Render;
begin
if IsVisible and FOpened then
begin
if CurrentLOD <= High(LOD) then
begin
LOD[CurrentLOD].Render(HA);
end;
end;
end;
// No render to texture, nor display lists.
procedure TModel.RenderVectorial;
begin
if IsVisible and FOpened then
begin
if CurrentLOD <= High(LOD) then
begin
LOD[CurrentLOD].RenderVectorial(HA);
end;
end;
end;
procedure TModel.ProcessNextFrame;
begin
if IsVisible and FOpened then
begin
if CurrentLOD <= High(LOD) then
begin
if HA^.DetectTransformationAnimationFrame then
begin
FRequestUpdateWorld := true;
end;
end;
end;
end;
// Refresh OpenGL List
procedure TModel.RefreshModel;
begin
LOD[CurrentLOD].RefreshLOD;
end;
procedure TModel.RefreshMesh(_MeshID: integer);
begin
LOD[CurrentLOD].RefreshMesh(_MeshID);
end;
// Textures
procedure TModel.ExportTextures(const _BaseDir, _Ext: string; _previewTextures: boolean);
begin
LOD[CurrentLOD].ExportTextures(_BaseDir,_Ext,_previewTextures);
end;
procedure TModel.ExportHeightMap(const _BaseDir, _Ext : string; _previewTextures: boolean);
begin
LOD[CurrentLOD].ExportHeightMap(_BaseDir,_Ext,_previewTextures);
end;
procedure TModel.SetTextureNumMipMaps(_NumMipMaps, _TextureType: integer);
begin
LOD[CurrentLOD].SetTextureNumMipMaps(_NumMipMaps,_TextureType);
end;
// Transparency methods
procedure TModel.ForceTransparency(_level: single);
begin
LOD[CurrentLOD].ForceTransparency(_Level);
end;
procedure TModel.ForceTransparencyOnMesh(_Level: single; _MeshID: integer);
begin
LOD[CurrentLOD].ForceTransparencyOnMesh(_Level,_MeshID);
end;
procedure TModel.ForceTransparencyExceptOnAMesh(_Level: single; _MeshID: integer);
begin
LOD[CurrentLOD].ForceTransparencyExceptOnAMesh(_Level,_MeshID);
end;
// Palette Related
procedure TModel.ChangeRemappable(_Colour: TColor);
begin
if Palette <> nil then
begin
Palette^.ChangeRemappable(_Colour);
end;
end;
procedure TModel.ChangePalette(const _Filename: string);
begin
if Palette <> nil then
begin
Palette^.LoadPalette(_Filename);
end;
end;
// GUI
procedure TModel.SetSelection(_value: boolean);
var
i : integer;
begin
IsSelected := _value;
for i := Low(LOD) to High(LOD) do
begin
LOD[i].SetSelection(_value);
end;
end;
// Copies
procedure TModel.Assign(const _Model: TModel);
var
i : integer;
begin
New(Palette);
FType := _Model.ModelType;
FRequestUpdateWorld := _Model.FRequestUpdateWorld;
ShaderBank := _Model.ShaderBank;
Palette^ := TPalette.Create(_Model.Palette^);
IsVisible := _Model.IsVisible;
SetLength(LOD,_Model.GetNumLODs);
for i := Low(LOD) to High(LOD) do
begin
LOD[i] := TLOD.Create(_Model.LOD[i]);
end;
CurrentLOD := _Model.CurrentLOD;
Filename := CopyString(_Model.Filename);
if HA <> nil then
begin
HA^.Free;
HA := nil;
end;
new(HA);
HA^ := THierarchyAnimation.Create(_Model.HA^);
IsSelected := _Model.IsSelected;
end;
// Mesh Optimizations
procedure TModel.RemoveInvisibleFaces;
begin
LOD[CurrentLOD].RemoveInvisibleFaces;
end;
// Quality Assurance
function TModel.GetAspectRatioHistogram(): THistogram;
begin
Result := LOD[CurrentLOD].GetAspectRatioHistogram;
end;
function TModel.GetSkewnessHistogram(): THistogram;
begin
Result := LOD[CurrentLOD].GetSkewnessHistogram;
end;
function TModel.GetSmoothnessHistogram(): THistogram;
begin
Result := LOD[CurrentLOD].GetSmoothnessHistogram;
end;
procedure TModel.FillAspectRatioHistogram(var _Histogram: THistogram);
begin
LOD[CurrentLOD].FillAspectRatioHistogram(_Histogram);
end;
procedure TModel.FillSkewnessHistogram(var _Histogram: THistogram);
begin
LOD[CurrentLOD].FillSkewnessHistogram(_Histogram);
end;
procedure TModel.FillSmoothnessHistogram(var _Histogram: THistogram);
begin
LOD[CurrentLOD].FillSmoothnessHistogram(_Histogram);
end;
// Mesh Plugins
procedure TModel.AddNormalsPlugin;
begin
LOD[CurrentLOD].AddNormalsPlugin;
end;
procedure TModel.RemoveNormalsPlugin;
begin
LOD[CurrentLOD].RemoveNormalsPlugin;
end;
end.
|
(*
Category: SWAG Title: DIRECTORY HANDLING ROUTINES
Original name: 0037.PAS
Description: Create Directories
Author: GREG VIGNEAULT
Date: 08-25-94 09:09
*)
{
>Has anyone written a function for creating a pathname ?
>I'm having a problem with putting together a function that you
>can pass a pathname to, such as: C:\WINDOWS\SYSTEM\STUFF
>and have it create the path if it's at all possible.
>the problem I'm having seems to stem from the fact that 'MKDIR()'
>can only handle making one directory which is under the current one.
This is because DOS' MkDir itself will fail if any element of a
path is missing. You'll need to parse and build the path, going
directory by directory.
Here's some example code that you may use to create a MakePath
function...
}
PROGRAM MakePath; { Create a path. July 21,1994 Greg Vigneault }
VAR Try, Slash : BYTE;
Error : WORD;
TmpDir, IncDir, NewDir, OurDir : STRING;
BEGIN
WriteLn;
Try := 0;
NewDir := 'C:\000\111\222'; { an example path to create }
GetDir (0,OurDir); { because we'll use CHDIR to confirm directories }
WHILE NewDir[Length(NewDir)] = '\' DO DEC(NewDir[0]); { clip '\' }
IncDir := ''; { start with empty string }
REPEAT
Slash := Pos('\',NewDir); { check for slash }
IF (Slash <> 0) THEN BEGIN
IncDir := IncDir + Copy( NewDir, 1, Slash ); { get directory }
NewDir := Copy( NewDir, Slash+1, Length(NewDir)-Slash ); END
ELSE
IncDir := IncDir + NewDir;
TmpDir := IncDir;
IF (Length(TmpDir) > 3) THEN { clip any trailing '\' }
WHILE TmpDir[Length(TmpDir)] = '\' DO DEC(TmpDir[0]);
REPEAT
{$I-} ChDir(TmpDir); {$I+} { try to log into the directory... }
Error := IoResult;
IF (Error <> 0) THEN BEGIN { couldn't ChDir, so try MkDir... }
{$I-} MkDir(TmpDir); {$I+}
Error := IoResult;
END;
IF (Error <> 0) THEN INC(Try) ELSE Try := 0;
UNTIL (Error = 0) OR (Try > 3);
IF (Error = 0) THEN WriteLn('"',TmpDir,'" -- okay');
UNTIL (Slash = 0) OR (Error <> 0);
IF (Error <> 0) THEN WriteLn('MkDir ',TmpDir,' failed!',#7);
ChDir(OurDir); { log back into our starting directory }
WriteLn;
END {MakePath}.
|
unit uDlgHolidays;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBASE_DialogForm, Menus, cxLookAndFeelPainters, cxStyles,
cxGraphics, cxSchedulerStorage, cxSchedulerCustomControls,
cxSchedulerDateNavigator, cxControls, cxContainer, cxDateNavigator,
StdCtrls, cxButtons, ExtCtrls, cxEdit, cxGroupBox, cxTextEdit,
cxMaskEdit, cxSpinEdit, cxRadioGroup, uHolidays, DB, ADODB,
dxGDIPlusClasses;
type
TdlgHolidays = class(TBASE_DialogForm)
pnlCaption: TPanel;
pnlClient: TPanel;
dnCalendar: TcxDateNavigator;
cxGroupBox1: TcxGroupBox;
Label1: TLabel;
seYear: TcxSpinEdit;
lblNoDate: TLabel;
lblNewYear: TLabel;
cxGroupBox2: TcxGroupBox;
rbViewOnly: TcxRadioButton;
rbEdit: TcxRadioButton;
pnlHide1: TPanel;
Panel1: TPanel;
lblHeader: TLabel;
lFrameDescription: TLabel;
Image_TopHeader: TImage;
procedure seYearPropertiesChange(Sender: TObject);
procedure dnCalendarCustomDrawDayNumber(Sender: TObject;
ACanvas: TcxCanvas;
AViewInfo: TcxSchedulerDateNavigatorDayNumberViewInfo;
var ADone: Boolean);
procedure lblNewYearClick(Sender: TObject);
procedure dnCalendarCustomDrawHeader(Sender: TObject;
ACanvas: TcxCanvas;
AViewInfo: TcxSchedulerDateNavigatorMonthHeaderViewInfo;
var ADone: Boolean);
procedure dnCalendarSelectionChanged(Sender: TObject; const AStart,
AFinish: TDateTime);
procedure dnCalendarPeriodChanged(Sender: TObject; const AStart,
AFinish: TDateTime);
procedure rbViewOnlyClick(Sender: TObject);
procedure rbEditClick(Sender: TObject);
private
FCalendar: TCalendar;
{ Private declarations }
protected
WasEdit: boolean;
public
property Calendar: TCalendar read FCalendar write FCalendar;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
dlgHolidays: TdlgHolidays;
implementation
uses uMain, uCommonUtils;
{$R *.dfm}
procedure TdlgHolidays.seYearPropertiesChange(Sender: TObject);
var
yi: integer;
begin
inherited;
dnCalendar.FirstDate:=EncodeDate(seYear.Value, 1, 1);
if Calendar.YearExists(seYear.Value, yi) then begin
if not Calendar.Years[yi].LoadedFromDB then
Calendar.Years[yi].LoadFromDB;
Calendar.CurrentYearIndex:=yi;
lblNoDate.Visible:=false;
lblNewYear.Visible:=false;
end
else begin
lblNoDate.Visible:=true;
lblNewYear.Visible:=true;
end;
lblHeader.Caption:=format('Календарь выходных и праздничных дней на %d год', [integer(seYear.Value)]);
end;
procedure TdlgHolidays.dnCalendarCustomDrawDayNumber(Sender: TObject;
ACanvas: TcxCanvas;
AViewInfo: TcxSchedulerDateNavigatorDayNumberViewInfo;
var ADone: Boolean);
var
hi: THolidayItem;
begin
inherited;
if lblNoDate.Visible then begin
ACanvas.Font.Color:=clWhite;
ACanvas.Brush.Color:=clWhite;
ACanvas.Pen.Color:=clWhite;
end
else begin
hi:=Calendar.Years[Calendar.CurrentYearIndex].Holidays.FindItemByDate(AViewInfo.Date);
if Assigned(hi) then begin
ACanvas.Font.Color := clRed;
// if hi.IsHoliday then
// ACanvas.Brush.Color := clYellow;
end;
end;
end;
constructor TdlgHolidays.Create(AOwner: TComponent);
var
y, m, d: word;
begin
inherited;
FCalendar:=TCalendar.Create;
Calendar.Years.LoadFromDB;
DecodeDate(now, y, m, d);
seYear.Value:=y;
WasEdit:=false;
end;
destructor TdlgHolidays.Destroy;
begin
FCalendar.Free;
inherited;
end;
procedure TdlgHolidays.lblNewYearClick(Sender: TObject);
var
year: TYearItem;
begin
inherited;
ScreenCursor.IncCursor;
try
year:=Calendar.Years.Add;
year.Year:=seYear.Value;
year.CreateNewItems;
Calendar.CurrentYearIndex:=year.Index;
lblNoDate.Visible:=false;
lblNewYear.Visible:=false;
dnCalendar.LayoutChanged
finally
ScreenCursor.DecCursor;
end;
end;
procedure TdlgHolidays.dnCalendarCustomDrawHeader(Sender: TObject;
ACanvas: TcxCanvas;
AViewInfo: TcxSchedulerDateNavigatorMonthHeaderViewInfo;
var ADone: Boolean);
const
Monthes: array[1..12] of string = ('Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь');
begin
inherited;
AViewInfo.Text:=Monthes[AViewInfo.Month];
end;
procedure TdlgHolidays.dnCalendarSelectionChanged(Sender: TObject;
const AStart, AFinish: TDateTime);
var
hi: THolidayItem;
begin
inherited;
if rbEdit.Checked then begin
hi:=Calendar.CurrentYear.Holidays.FindItemByDate(AStart);
if Assigned(hi) then
Calendar.CurrentYear.Holidays.Delete(hi.Index)
else begin
hi:=Calendar.CurrentYear.Holidays.Add;
hi.Date:=AStart;
hi.IsRestday:=true;
end;
WasEdit:=true;
end;
end;
procedure TdlgHolidays.dnCalendarPeriodChanged(Sender: TObject;
const AStart, AFinish: TDateTime);
begin
inherited;
if seYear.Value>1900 then
dnCalendar.FirstDate:=EncodeDate(seYear.Value, 1, 1);
end;
procedure TdlgHolidays.rbViewOnlyClick(Sender: TObject);
var
rbEditClick: TNotifyEvent;
begin
inherited;
if WasEdit then begin
case MessageBox(Handle, 'Сохранить изменения?', 'Сохранение', MB_YESNOCANCEL or MB_ICONQUESTION or MB_APPLMODAL) of
IDYES: begin Calendar.CurrentYear.SaveToDB; WasEdit:=false; Calendar.CurrentYear.ApplyEdit; end;
IDNO: begin Calendar.CurrentYear.RollbackEdit; WasEdit:=false; dnCalendar.LayoutChanged; end;
IDCANCEL: begin rbEditClick:=rbEdit.OnClick; rbEdit.OnClick:=nil; rbEdit.Checked:=true; rbEdit.OnClick:=rbEditClick; end;
end;
end;
end;
procedure TdlgHolidays.rbEditClick(Sender: TObject);
begin
inherited;
if rbEdit.Checked then
Calendar.CurrentYear.BeginEdit;
end;
end.
|
unit enumTypes;
interface
type
Integer = Integer;
TEnum = (eOne,
eTwo = 2,
eThree);
TEnumArr = array[TEnum.eOne..TEnum.eThree] of TEnum;
TRec = record
private type
TNestedEnum = (CONST1, CONST2);
end;
implementation
var
Enum: TEnum;
begin
TEnum.eTwo;
eOne;
TEnum.default;
TRec.TNestedEnum.CONST1;
end. |
unit uDadosEmpresa;
interface
uses
System.SysUtils, System.Classes, Data.FMTBcd, Data.DB, Datasnap.DBClient,
Datasnap.Provider, Data.SqlExpr;
type
TdmDadosEmpresa = class(TDataModule)
sqlTblemp: TSQLDataSet;
dspTblemp: TDataSetProvider;
cdsTblemp: TClientDataSet;
cdsTblempempcnpj: TStringField;
cdsTblempemprazaosocial: TStringField;
cdsTblempempie: TStringField;
cdsTblempempender: TStringField;
cdsTblempempnro: TStringField;
cdsTblempempcompl: TStringField;
cdsTblempempbairro: TStringField;
cdsTblempcepcep: TStringField;
sqlTblcep: TSQLDataSet;
dsTblcep: TDataSource;
sqlTblcepcepcep: TStringField;
sqlTblcepcepmunicipio: TStringField;
sqlTblcepcepeuf: TStringField;
cdsTblempempfone: TStringField;
procedure dspTblempUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
procedure cdsTblempempcnpjValidate(Sender: TField);
procedure cdsTblempemprazaosocialValidate(Sender: TField);
procedure cdsTblempempieValidate(Sender: TField);
procedure cdsTblempempenderValidate(Sender: TField);
procedure cdsTblempempnroValidate(Sender: TField);
procedure DataModuleCreate(Sender: TObject);
procedure cdsTblempcepcepValidate(Sender: TField);
procedure cdsTblempAfterOpen(DataSet: TDataSet);
procedure cdsTblempBeforePost(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
procedure FiltrarEmpresas;
procedure EditarEmpresa;
procedure SalvarManutencao;
procedure CalcelarManutencao;
end;
var
dmDadosEmpresa: TdmDadosEmpresa;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
uses uConexao, uDadosGlobal;
{$R *.dfm}
procedure TdmDadosEmpresa.CalcelarManutencao;
begin
if not cdsTblemp.Active then
abort;
if cdsTblemp.State in [dsEdit, dsInsert] then
cdsTblemp.Cancel;
if cdsTblemp.ChangeCount > 0 then
cdsTblemp.CancelUpdates;
end;
procedure TdmDadosEmpresa.cdsTblempAfterOpen(DataSet: TDataSet);
begin
sqlTblcep.Open;
end;
procedure TdmDadosEmpresa.cdsTblempBeforePost(DataSet: TDataSet);
begin
// Faço isso para que, caso não seja informado os telefones,
// para não gravar na base de dados apenas os "( )"
if trim(cdsTblempempfone.AsString) = '( )' then
cdsTblempempfone.AsString := '';
end;
procedure TdmDadosEmpresa.cdsTblempcepcepValidate(Sender: TField);
begin
sqlTblcep.Close;
sqlTblcep.ParamByName('cepcep').AsString := cdsTblempcepcep.AsString;
sqlTblcep.Open;
if sqlTblcep.Eof then
raise Exception.Create('CEP informado não está cadastrado.');
end;
procedure TdmDadosEmpresa.cdsTblempempcnpjValidate(Sender: TField);
begin
// Validar CNPJ
if not dmDadosGlobal.ValidarCNPJ(cdsTblempempcnpj.Value) then
raise Exception.Create('CNPJ inválido.');
end;
procedure TdmDadosEmpresa.cdsTblempempenderValidate(Sender: TField);
begin
if trim(cdsTblempempender.Value) = EmptyStr then
raise Exception.Create('Endereço não pode ser nulo.');
end;
procedure TdmDadosEmpresa.cdsTblempempieValidate(Sender: TField);
begin
if trim(cdsTblempempie.Value) = EmptyStr then
raise Exception.Create('Inscrição Estatual não pode ser nula.');
end;
procedure TdmDadosEmpresa.cdsTblempempnroValidate(Sender: TField);
begin
if trim(cdsTblempempnro.Value) = EmptyStr then
raise Exception.Create('Número da rua não pode ser nulo.');
end;
procedure TdmDadosEmpresa.cdsTblempemprazaosocialValidate(Sender: TField);
begin
if trim(cdsTblempemprazaosocial.Value) = EmptyStr then
raise Exception.Create('Razão Social não pode ser nula.');
end;
procedure TdmDadosEmpresa.DataModuleCreate(Sender: TObject);
begin
FiltrarEmpresas;
end;
procedure TdmDadosEmpresa.dspTblempUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
raise Exception.Create(e.Message);
end;
procedure TdmDadosEmpresa.EditarEmpresa;
begin
if not cdsTblemp.Active then
cdsTblemp.Open;
if cdsTblemp.RecordCount = 0 then
cdsTblemp.Append
else
cdsTblemp.Edit;
end;
procedure TdmDadosEmpresa.FiltrarEmpresas;
begin
cdsTblemp.Close;
cdsTblemp.Open;
end;
procedure TdmDadosEmpresa.SalvarManutencao;
begin
if not cdsTblemp.Active then
abort;
// Força novamente a validação do campos
cdsTblempempcnpj.OnValidate(cdsTblempempcnpj);
cdsTblempemprazaosocial.OnValidate(cdsTblempemprazaosocial);
cdsTblempempie.OnValidate(cdsTblempempie);
cdsTblempempender.OnValidate(cdsTblempempender);
cdsTblempempnro.OnValidate(cdsTblempempnro);
cdsTblempcepcep.OnValidate(cdsTblempcepcep);
try
if cdsTblemp.State in [dsEdit, dsInsert] then
cdsTblemp.Post;
cdsTblemp.ApplyUpdates(0);
except
on E: Exception do
begin
if cdsTblemp.ChangeCount > 0 then
cdsTblemp.Cancel;
if pos('key violation', LowerCase(e.Message)) > 0 then
raise Exception.Create('Empresa informado já está cadastrado.')
else if pos('duplicate entry', LowerCase(e.Message)) > 0 then
raise Exception.Create('Empresa informado já está cadastrado.')
else if pos('foreign key constraint fails', LowerCase(e.Message)) > 0 then
raise Exception.Create('Não é possível excluir esta empresa, pois esta empresa está relacionada a outras tabelas.')
else if pos('changed by another user', LowerCase(e.Message)) > 0 then
raise Exception.Create('Atenção:' + chr(10) + 'O registro que você está tentando modificar acaba de ser modificado por outro usuário.' + chr(10) + 'Cancele a operação e realize uma nova filtragem.')
else
raise Exception.Create(e.Message);
end;
end;
end;
end.
|
unit gateway_protocol.Proto;
// This unit was initially generated by: DelphiGrpc "ProtoBufGenerator.exe"
(* ----------------------------------------------------------
PMM 18.05.2020 The following changes where found necessary:
FILE -> _FILE
type -> _type
Int64 -> UInt64 (as used s far)
Integer -> word (in TActivatedJobs.retries)
Integer -> UInt32 (in TCreateWorkflowInstanceRequest.Version)
removed TTopologyRequest (is empty record)
-------------------------------------------------------------*)
interface
uses
System.SysUtils,
Grijjy.ProtocolBuffers;
type
TStringArray = Array of string;
TResourceType = (
_FILE = 0,
BPMN = 1,
YAML = 2);
TPartitionBrokerRole = (
LEADER = 0,
FOLLOWER = 1);
TActivateJobsRequest = record
[Serialize(1)] _type: string;
[Serialize(2)] worker: string;
[Serialize(3)] timeout: Int64;
[Serialize(4)] maxJobsToActivate: Integer;
[Serialize(5)] fetchVariable: TStringArray;
[Serialize(6)] requestTimeout: Int64;
end;
TActivateJobsRequestArray = Array of TActivateJobsRequest;
TActivatedJob = record
[Serialize(1)] key: UInt64;
[Serialize(2)] _type: string;
[Serialize(3)] workflowInstanceKey: UInt64;
[Serialize(4)] bpmnProcessId: string;
[Serialize(5)] workflowDefinitionVersion: Integer;
[Serialize(6)] workflowKey: UInt64;
[Serialize(7)] elementId: string;
[Serialize(8)] elementInstanceKey: UInt64;
[Serialize(9)] customHeaders: string;
[Serialize(10)] worker: string;
[Serialize(11)] retries: Word;
[Serialize(12)] deadline: UInt64;
[Serialize(13)] variables: string;
end;
TActivatedJobArray = Array of TActivatedJob;
TActivateJobsResponse = record
[Serialize(1)] jobs: TActivatedJobArray;
end;
TActivateJobsResponseArray = Array of TActivateJobsResponse;
TCancelWorkflowInstanceRequest = record
[Serialize(1)] workflowInstanceKey: UInt64;
end;
TCancelWorkflowInstanceRequestArray = Array of TCancelWorkflowInstanceRequest;
TCancelWorkflowInstanceResponse = record
end;
TCancelWorkflowInstanceResponseArray = Array of TCancelWorkflowInstanceResponse;
TCompleteJobRequest = record
[Serialize(1)] jobKey: UInt64;
[Serialize(2)] variables: string;
end;
TCompleteJobRequestArray = Array of TCompleteJobRequest;
TCompleteJobResponse = record
end;
TCompleteJobResponseArray = Array of TCompleteJobResponse;
TCreateWorkflowInstanceRequest = record
[Serialize(1)] workflowKey: UInt64; {PMM for NULL: TUInt64(-1)}
[Serialize(2)] bpmnProcessId: string;
[Serialize(3)] version: UInt32; {PMM for Latest TUInt32(-1)}
[Serialize(4)] variables: string;
end;
TCreateWorkflowInstanceResponse = record
[Serialize(1)] workflowKey: UInt64;
[Serialize(2)] bpmnProcessId: string;
[Serialize(3)] version: Integer;
[Serialize(4)] workflowInstanceKey: UInt64;
end;
TCreateWorkflowInstanceResponseArray = Array of TCreateWorkflowInstanceResponse;
TCreateWorkflowInstanceWithResultRequest = record
[Serialize(1)] request: TCreateWorkflowInstanceRequest;
[Serialize(2)] requestTimeout: Int64;
[Serialize(3)] fetchVariables: TStringArray;
end;
TCreateWorkflowInstanceWithResultRequestArray = Array of TCreateWorkflowInstanceWithResultRequest;
TCreateWorkflowInstanceWithResultResponse = record
[Serialize(1)] workflowKey: Int64;
[Serialize(2)] bpmnProcessId: string;
[Serialize(3)] version: Integer;
[Serialize(4)] workflowInstanceKey: Int64;
[Serialize(5)] variables: string;
end;
TCreateWorkflowInstanceWithResultResponseArray = Array of TCreateWorkflowInstanceWithResultResponse;
TWorkflowRequestObject = record
[Serialize(1)] name: string;
[Serialize(2)] _type: TResourceType;
[Serialize(3)] definition: TBytes;
end;
TWorkflowRequestObjectArray = Array of TWorkflowRequestObject;
TDeployWorkflowRequest = record
[Serialize(1)] workflows: TWorkflowRequestObjectArray;
end;
TDeployWorkflowRequestArray = Array of TDeployWorkflowRequest;
TWorkflowMetadata = record
[Serialize(1)] bpmnProcessId: string;
[Serialize(2)] version: Integer;
[Serialize(3)] workflowKey: UInt64;
[Serialize(4)] resourceName: string;
end;
TWorkflowMetadataArray = Array of TWorkflowMetadata;
TDeployWorkflowResponse = record
[Serialize(1)] key: UInt64;
[Serialize(2)] workflows: TWorkflowMetadataArray;
end;
TDeployWorkflowResponseArray = Array of TDeployWorkflowResponse;
TFailJobRequest = record
[Serialize(1)] jobKey: Int64;
[Serialize(2)] retries: Integer;
[Serialize(3)] errorMessage: string;
end;
TFailJobRequestArray = Array of TFailJobRequest;
TFailJobResponse = record
end;
TFailJobResponseArray = Array of TFailJobResponse;
TPublishMessageRequest = record
[Serialize(1)] name: string;
[Serialize(2)] correlationKey: string;
[Serialize(3)] timeToLive: Int64;
[Serialize(4)] messageId: string;
[Serialize(5)] variables: string;
end;
TPublishMessageRequestArray = Array of TPublishMessageRequest;
TPublishMessageResponse = record
end;
TPublishMessageResponseArray = Array of TPublishMessageResponse;
TResolveIncidentRequest = record
[Serialize(1)] incidentKey: Int64;
end;
TResolveIncidentRequestArray = Array of TResolveIncidentRequest;
TResolveIncidentResponse = record
end;
TResolveIncidentResponseArray = Array of TResolveIncidentResponse;
{PMM 12.12.2019 empty Records are not supported
TTopologyRequest = record
end;
TTopologyRequestArray = Array of TTopologyRequest;
}
TPartition = record
[Serialize(1)] partitionId: Integer;
[Serialize(2)] role: TPartitionBrokerRole;
end;
TPartitionArray = Array of TPartition;
TBrokerInfo = record
[Serialize(1)] nodeId: Integer;
[Serialize(2)] host: string;
[Serialize(3)] port: Integer;
[Serialize(4)] partitions: TPartitionArray;
end;
TBrokerInfoArray = Array of TBrokerInfo;
TTopologyResponse = record
[Serialize(1)] brokers: TBrokerInfoArray;
[Serialize(2)] clusterSize: Integer;
[Serialize(3)] partitionsCount: Integer;
[Serialize(4)] replicationFactor: Integer;
end;
TTopologyResponseArray = Array of TTopologyResponse;
TUpdateJobRetriesRequest = record
[Serialize(1)] jobKey: Int64;
[Serialize(2)] retries: Integer;
end;
TUpdateJobRetriesRequestArray = Array of TUpdateJobRetriesRequest;
TUpdateJobRetriesResponse = record
end;
TUpdateJobRetriesResponseArray = Array of TUpdateJobRetriesResponse;
TSetVariablesRequest = record
[Serialize(1)] elementInstanceKey: UInt64;
[Serialize(2)] variables: string;
[Serialize(3)] local: Boolean;
end;
TSetVariablesRequestArray = Array of TSetVariablesRequest;
TSetVariablesResponse = record
end;
TSetVariablesResponseArray = Array of TSetVariablesResponse;
implementation
end.
|
unit SDUClasses;
interface
uses
Classes, Windows;
type
TSDUMemoryStream = class(TMemoryStream)
private
procedure GotoOffset(offset: int64);
public
function ReadByte(offset: int64 = -1): byte;
procedure WriteByte(x: byte; offset: int64 = -1; cnt: integer = -1);
// Read/write little endian WORD
function ReadWORD_LE(offset: int64 = -1): WORD;
procedure WriteWORD_LE(x: WORD; offset: int64 = -1);
// Read/write big endian WORD
function ReadWORD_BE(offset: int64 = -1): WORD;
procedure WriteWORD_BE(x: WORD; offset: int64 = -1);
// Read/write little endian DWORD
function ReadDWORD_LE(offset: int64 = -1): DWORD;
procedure WriteDWORD_LE(x: DWORD; offset: int64 = -1);
// Read/write big endian DWORD
function ReadDWORD_BE(offset: int64 = -1): DWORD;
procedure WriteDWORD_BE(x: DWORD; offset: int64 = -1);
function ReadString(size: integer; offset: integer = -1): ansistring;
procedure WriteString(data: ansistring; maxChars: integer = -1; offset: integer = -1);
function ReadWideString(size: integer; offset: integer = -1): WideString;
procedure WriteWideString(data: WideString; offset: integer = -1);
end;
TSDUFileStream = class(TFileStream)
private
procedure GotoOffset(offset: int64);
public
function ReadByte(offset: int64 = -1): byte;
procedure WriteByte(x: byte; offset: int64 = -1; cnt: integer = -1);
// Read/write little endian WORD
function ReadWORD_LE(offset: int64 = -1): WORD;
procedure WriteWORD_LE(x: WORD; offset: int64 = -1);
// Read/write big endian WORD
function ReadWORD_BE(offset: int64 = -1): WORD;
procedure WriteWORD_BE(x: WORD; offset: int64 = -1);
// Read/write little endian DWORD
function ReadDWORD_LE(offset: int64 = -1): DWORD;
procedure WriteDWORD_LE(x: DWORD; offset: int64 = -1);
// Read/write big endian DWORD
function ReadDWORD_BE(offset: int64 = -1): DWORD;
procedure WriteDWORD_BE(x: DWORD; offset: int64 = -1);
function ReadString(size: integer; offset: integer = -1): string;
procedure WriteString(data: string; maxChars: integer = -1; offset: integer = -1);
function ReadWideString(size: integer; offset: integer = -1): WideString;
procedure WriteWideString(data: WideString; offset: integer = -1);
end;
implementation
uses
Math,
SDUGeneral;
// ==========================================================================
// ==========================================================================
procedure TSDUMemoryStream.GotoOffset(offset: int64);
begin
if (offset >= 0) then
begin
self.Position := offset;
end;
end;
function TSDUMemoryStream.ReadByte(offset: int64 = -1): byte;
begin
GotoOffset(offset);
self.Read(Result, sizeof(Result));
end;
procedure TSDUMemoryStream.WriteByte(x: byte; offset: int64 = -1; cnt: integer = -1);
var
i: integer;
begin
GotoOffset(offset);
if (cnt < 0) then
begin
cnt := 1;
end;
for i:=1 to cnt do
begin
self.Write(x, sizeof(x));
end;
end;
// Read/write little endian DWORD
function TSDUMemoryStream.ReadDWORD_LE(offset: int64 = -1): DWORD;
begin
GotoOffset(offset);
self.Read(Result, sizeof(Result));
end;
procedure TSDUMemoryStream.WriteDWORD_LE(x: DWORD; offset: int64 = -1);
begin
GotoOffset(offset);
self.Write(x, sizeof(x));
end;
// Read/write big endian DWORD
function TSDUMemoryStream.ReadDWORD_BE(offset: int64 = -1): DWORD;
var
tmpDWORD: DWORD;
begin
GotoOffset(offset);
tmpDWORD := ReadDWORD_LE();
Result := SDUConvertEndian(tmpDWORD);
end;
procedure TSDUMemoryStream.WriteDWORD_BE(x: DWORD; offset: int64 = -1);
var
tmpDWORD: DWORD;
begin
GotoOffset(offset);
tmpDWORD := SDUConvertEndian(x);
WriteDWORD_LE(tmpDWORD);
end;
// Read/write little endian WORD
function TSDUMemoryStream.ReadWORD_LE(offset: int64 = -1): WORD;
begin
GotoOffset(offset);
self.Read(Result, sizeof(Result));
end;
procedure TSDUMemoryStream.WriteWORD_LE(x: WORD; offset: int64 = -1);
begin
GotoOffset(offset);
self.Write(x, sizeof(x));
end;
// Read/write big endian WORD
function TSDUMemoryStream.ReadWORD_BE(offset: int64 = -1): WORD;
var
tmpWORD: WORD;
begin
GotoOffset(offset);
tmpWORD := ReadWORD_LE();
Result := SDUConvertEndian(tmpWORD);
end;
procedure TSDUMemoryStream.WriteWORD_BE(x: WORD; offset: int64 = -1);
var
tmpWORD: WORD;
begin
GotoOffset(offset);
tmpWORD := SDUConvertEndian(x);
WriteWORD_LE(tmpWORD);
end;
function TSDUMemoryStream.ReadString(size: integer; offset: integer = -1): ansistring;
var
i: integer;
begin
Result := '';
GotoOffset(offset);
for i:=0 to (size - 1) do
begin
Result := Result + ansichar(self.ReadByte());
end;
end;
procedure TSDUMemoryStream.WriteString(data: ansistring; maxChars: integer = -1; offset: integer = -1);
begin
GotoOffset(offset);
if (maxChars < 0) then
begin
maxChars := length(data);
end;
maxChars := min(maxChars, length(data));
Write(PansiChar(data)^, maxChars);
end;
// Note: Size here is in *bytes*
function TSDUMemoryStream.ReadWideString(size: integer; offset: integer = -1): WideString;
var
i: integer;
begin
Result := '';
GotoOffset(offset);
for i:=0 to ((size - 2) div 2) do
begin
Result := Result + WideChar(self.ReadWORD_LE());
end;
end;
procedure TSDUMemoryStream.WriteWideString(data: WideString; offset: integer = -1);
begin
GotoOffset(offset);
Write(PWideChar(data)^, (length(data) * sizeof(WideChar)));
end;
// ==========================================================================
// ==========================================================================
procedure TSDUFileStream.GotoOffset(offset: int64);
begin
if (offset >= 0) then
begin
self.Position := offset;
end;
end;
function TSDUFileStream.ReadByte(offset: int64 = -1): byte;
begin
GotoOffset(offset);
self.Read(Result, sizeof(Result));
end;
procedure TSDUFileStream.WriteByte(x: byte; offset: int64 = -1; cnt: integer = -1);
var
i: integer;
begin
GotoOffset(offset);
if (cnt < 0) then
begin
cnt := 1;
end;
for i:=1 to cnt do
begin
self.Write(x, sizeof(x));
end;
end;
// Read/write little endian DWORD
function TSDUFileStream.ReadDWORD_LE(offset: int64 = -1): DWORD;
begin
GotoOffset(offset);
self.Read(Result, sizeof(Result));
end;
procedure TSDUFileStream.WriteDWORD_LE(x: DWORD; offset: int64 = -1);
begin
GotoOffset(offset);
self.Write(x, sizeof(x));
end;
// Read/write big endian DWORD
function TSDUFileStream.ReadDWORD_BE(offset: int64 = -1): DWORD;
var
tmpDWORD: DWORD;
begin
GotoOffset(offset);
tmpDWORD := ReadDWORD_LE();
Result := SDUConvertEndian(tmpDWORD);
end;
procedure TSDUFileStream.WriteDWORD_BE(x: DWORD; offset: int64 = -1);
var
tmpDWORD: DWORD;
begin
GotoOffset(offset);
tmpDWORD := SDUConvertEndian(x);
WriteDWORD_LE(tmpDWORD);
end;
// Read/write little endian WORD
function TSDUFileStream.ReadWORD_LE(offset: int64 = -1): WORD;
begin
GotoOffset(offset);
self.Read(Result, sizeof(Result));
end;
procedure TSDUFileStream.WriteWORD_LE(x: WORD; offset: int64 = -1);
begin
GotoOffset(offset);
self.Write(x, sizeof(x));
end;
// Read/write big endian WORD
function TSDUFileStream.ReadWORD_BE(offset: int64 = -1): WORD;
var
tmpWORD: WORD;
begin
GotoOffset(offset);
tmpWORD := ReadWORD_LE();
Result := SDUConvertEndian(tmpWORD);
end;
procedure TSDUFileStream.WriteWORD_BE(x: WORD; offset: int64 = -1);
var
tmpWORD: WORD;
begin
GotoOffset(offset);
tmpWORD := SDUConvertEndian(x);
WriteWORD_LE(tmpWORD);
end;
function TSDUFileStream.ReadString(size: integer; offset: integer = -1): string;
var
i: integer;
begin
Result := '';
GotoOffset(offset);
for i:=0 to (size - 1) do
begin
Result := Result + chr(self.ReadByte());
end;
end;
procedure TSDUFileStream.WriteString(data: string; maxChars: integer = -1; offset: integer = -1);
begin
GotoOffset(offset);
if (maxChars < 0) then
begin
maxChars := length(data);
end;
maxChars := min(maxChars, length(data));
Write(PChar(data)^, maxChars);
end;
// Note: Size here is in *bytes*
function TSDUFileStream.ReadWideString(size: integer; offset: integer = -1): WideString;
var
i: integer;
begin
Result := '';
GotoOffset(offset);
for i:=0 to ((size - 2) div 2) do
begin
Result := Result + WideChar(self.ReadWORD_LE());
end;
end;
procedure TSDUFileStream.WriteWideString(data: WideString; offset: integer = -1);
begin
GotoOffset(offset);
Write(PWideChar(data)^, (length(data) * sizeof(WideChar)));
end;
// ==========================================================================
// ==========================================================================
// ==========================================================================
END.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit uEditorFileHandler;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Classes, Forms, Dialogs, Controls,
uCommon, uFileHist, FileCtrl, uMultiLanguage, SynEditTextBuffer,
SynEditTypes, JclFileUtils;
type
TEditorFileHandler = class
private
fEditor: TObject;
fSavedMemoCaret: TBufferCoord;
fSavedMemoFirstLine: integer;
fSavedMemoLeftChar: integer;
fTextFormat: TTextFormat;
fEncoding: TEncoding;
function GetBackupFilename: string;
procedure RememberMemoPositions;
procedure RestoreMemoPositions;
public
constructor Create(Editor: TObject);
// todo: move to private
function SaveInFormat(Source: TStrings; Format: TTextFormat; FileName: string): boolean;
procedure SaveToFile(const filename : string; const value : string; Encoding: TEncoding = nil);
function PrepareForSave(var NewFileName: string; const ChangeName: boolean = FALSE): boolean;
function LoadFromStream(Stream: TStream): string;
function LoadNewEncoding(const sInput: string; newEncoding: TEncoding): string;
function BackupFile: boolean;
function Rename(NewFileName: string): boolean;
function RenameEnabled: boolean;
function RevertToSavedEnabled: boolean;
function RevertToBackupEnabled: boolean;
procedure RevertToSaved;
procedure RevertToBackup;
procedure CopyTo;
property TextFormat: TTextFormat read fTextFormat write fTextFormat;
property Encoding: TEncoding read fEncoding write fEncoding;
end;
implementation
uses
fEditor, uEnvOptions;
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
function TEditorFileHandler.LoadFromStream(Stream: TStream): string;
var
iSize: Integer;
initialBuffer: TBytes;
srcEncoding : TEncoding;
convertedBuffer : TBytes;
iPreambleLen : integer;
begin
if (fEncoding = nil) then
fEncoding := TEncoding.Unicode;
srcEncoding := nil;
{ Open the file and check the BOM for an encoding }
iSize := Stream.Size - Stream.Position;
SetLength(initialBuffer, iSize);
stream.Read(initialBuffer[0], iSize);
iPreambleLen := TEncoding.GetBufferEncoding(initialbuffer,srcEncoding);
{ If the encoding found is not the expected encoding (default is unicode), then set the encoding }
if (srcEncoding.ClassType <> fEncoding.ClassType) then
begin
fEncoding := srcEncoding;
{ Load with the correct encoding, but leave non-encoded files alone }
if (iPreambleLen > 0) then
begin
convertedBuffer := TEncoding.Convert(srcEncoding, fEncoding, initialBuffer, iPreambleLen, iSize - iPreambleLen);
initialBuffer := convertedBuffer;
end;
iPreambleLen := TEncoding.GetBufferEncoding(initialBuffer,fEncoding);
end;
{ read the contents out into a string using the correct encoding }
result := fEncoding.GetString(initialBuffer, iPreambleLen, Length(initialBuffer) - iPreambleLen);
{ now set the ConTEXT text format, maybe be ASCII,
but 3 different type of line terminators, Windows, UNIX & Mac }
if fEncoding = TEncoding.Unicode then
fTextFormat := tfUnicode
else
if fEncoding = TEncoding.BigEndianUnicode then
fTextFormat := tfUnicodeBigEndian
else
if fEncoding = TEncoding.UTF8 then
fTextFormat := tfUTF8
else
if (Pos(#13#10, result) > 0) then
fTextFormat := tfNormal
else
if (Pos(#10, result) > 0) then
fTextFormat := tfUnix
else
if (Pos(#13, result) > 0) then
fTextFormat := tfMac;
end;
function TEditorFileHandler.LoadNewEncoding(const sInput: string; newEncoding: TEncoding): string;
var
ssInput: TStringStream;
convertedBuffer: TBytes;
begin
{ load a stream with the initial data }
ssInput := TStringStream.Create;
ssInput.WriteString(sInput);
ssInput.Seek(0, soFromBeginning);
{ Convert the buffer }
convertedBuffer := TEncoding.Convert(FEncoding, newEncoding, ssInput.Bytes);
FEncoding := newEncoding;
{ Write it back to a string }
result := FEncoding.GetString(convertedBuffer, 0, Length(convertedBuffer));
end;
//------------------------------------------------------------------------------------------
function TEditorFileHandler.GetBackupFilename: string;
var
path: string;
bak_fname: string;
fname: string;
begin
fname := TfmEditor(fEditor).FileName;
if (Length(EnvOptions.BackupDir) > 0) then
path := PathAddSeparator(EnvOptions.BackupDir)
else
path := ExtractFilePath(fname);
bak_fname := ExtractFileName(fname);
if EnvOptions.BackupDOSFileName then
SetLength(bak_fname, Length(bak_fname) - Length(ExtractFileExt(bak_fname)));
result := path + bak_fname + '.bak';
end;
//------------------------------------------------------------------------------------------
procedure TEditorFileHandler.RememberMemoPositions;
begin
with TfmEditor(fEditor).memo do
begin
fSavedMemoCaret := CaretXY;
fSavedMemoFirstLine := TopLine;
fSavedMemoLeftChar := LeftChar;
end;
end;
//------------------------------------------------------------------------------------------
procedure TEditorFileHandler.RestoreMemoPositions;
begin
with TfmEditor(fEditor).memo do
begin
CaretXY := fSavedMemoCaret;
TopLine := fSavedMemoFirstLine;
LeftChar := fSavedMemoLeftChar;
end;
end;
//------------------------------------------------------------------------------------------
function TEditorFileHandler.BackupFile: boolean;
var
bak_fname: string;
bak_path: string;
ok: boolean;
attr: word;
fname: string;
begin
ok := TRUE;
fname := TfmEditor(fEditor).FileName;
if EnvOptions.BackupFile and FileExists(fname) then
begin
bak_fname := GetBackupFilename;
bak_path := ExtractFilePath(bak_fname);
if (Length(EnvOptions.BackupDir) > 0) then
ForceDirectories(bak_path);
if FileExists(bak_fname) then
begin
attr := FileGetAttr(bak_fname);
FileSetAttr(bak_fname, attr and not faReadOnly);
DeleteFile(bak_fname);
end;
ok := CopyFile(PChar(fname), PChar(bak_fname), FALSE);
if not ok then
MessageDlg(Format(mlStr(ML_EDIT_ERR_SAVING_BACKUP,
'Error creating backup file: ''%s'''), [bak_fname]),
mtError, [mbOK], 0);
end;
result := ok;
end;
//------------------------------------------------------------------------------------------
function TEditorFileHandler.RenameEnabled: boolean;
var
Editor: TfmEditor;
begin
Editor := TfmEditor(fEditor);
result := not (Editor.NewFile or Editor.Unnamed);
end;
//------------------------------------------------------------------------------------------
function TEditorFileHandler.Rename(NewFileName: string): boolean;
var
old_fname: string;
old_path: string;
new_path: string;
Editor: TfmEditor;
begin
Editor := TfmEditor(fEditor);
old_fname := Editor.FileName;
old_path := ExtractFilePath(Editor.FileName);
new_path := ExtractFilePath(NewFileName);
Delete(NewFileName, 1, Length(new_path));
if (Length(new_path) = 0) then
new_path := old_path;
NewFileName := new_path + NewFileName;
if (not FileExists(NewFileName)) or (UpperCase(NewFileName) =
UpperCase(Editor.FileName)) then
begin
result := RenameFile(Editor.FileName, NewFileName);
if not result then
MessageDlg(Format(mlStr(ML_RENAME_FILE_ERROR,
'Error renaming file ''%s'' to ''%s''.'), [Editor.FileName, NewFileName]),
mtError, [mbOK], 0);
end
else
begin
MessageDlg(mlStr(ML_RENAME_FILE_ERR_EXISTS, 'File already exists!'), mtError,
[mbOK], 0);
result := FALSE;
end;
if result then
Editor.FileName := NewFileName;
end;
//------------------------------------------------------------------------------------------
function TEditorFileHandler.RevertToBackupEnabled: boolean;
begin
result := EnvOptions.BackupFile and FileExists(GetBackupFilename);
end;
//------------------------------------------------------------------------------------------
procedure TEditorFileHandler.RevertToBackup;
var
OldFileName: string;
Editor: TfmEditor;
begin
if (MessageDlg(Format(mlStr(ML_REVERT_TO_BACKUP_QUERY,
'Revert to backup file ''%s''?'), [GetBackupFilename]), mtWarning, [mbOK,
mbCancel], 0) = mrOK) then
begin
Editor := TfmEditor(fEditor);
OldFileName := Editor.FileName;
RememberMemoPositions;
Editor.Open(GetBackupFilename, FALSE);
RestoreMemoPositions;
Editor.FileName := OldFileName;
Editor.Modified := TRUE;
end;
end;
//------------------------------------------------------------------------------------------
function TEditorFileHandler.RevertToSavedEnabled: boolean;
var
Editor: TfmEditor;
begin
Editor := TfmEditor(fEditor);
result := Editor.Modified and not (Editor.NewFile or Editor.Unnamed);
end;
//------------------------------------------------------------------------------------------
procedure TEditorFileHandler.RevertToSaved;
var
Editor: TfmEditor;
begin
Editor := TfmEditor(fEditor);
if (MessageDlg(Format(mlStr(ML_REVERT_TO_SAVED_QUERY,
'Revert ''%s'' to saved?'), [Editor.FileName]), mtWarning, [mbOK, mbCancel], 0)
= mrOK) then
begin
RememberMemoPositions;
Editor.Open(Editor.FileName, FALSE);
RestoreMemoPositions;
end;
end;
//------------------------------------------------------------------------------------------
function TEditorFileHandler.SaveInFormat(Source: TStrings; Format: TTextFormat; FileName: string): boolean;
begin
result := true;
try
case format of
tfNormal:
begin
TSynEditStringList(Source).FileFormat := sffDos;
Source.SaveToFile(FileName);
end;
tfUnix:
begin
TSynEditStringList(Source).FileFormat := sffUnix;
Source.SaveToFile(FileName);
end;
tfMac:
begin
TSynEditStringList(Source).FileFormat := sffMac;
Source.SaveToFile(FileName);
end;
tfUnicode:
SaveToFile(Filename, Source.Text, TEncoding.Unicode);
tfUnicodeBigEndian:
SaveToFile(Filename, Source.Text, TEncoding.BigEndianUnicode);
tfUTF8:
SaveToFile(Filename, Source.Text, TEncoding.UTF8);
end;
except
result := false;
end;
end;
//------------------------------------------------------------------------------------------
procedure TEditorFileHandler.SaveToFile(const filename : string; const value : string; Encoding: TEncoding = nil);
var
fs: TFileStream;
Buffer, Preamble: TBytes;
begin
if Encoding = nil then
Encoding := TEncoding.Unicode;
Preamble := Encoding.GetPreamble;
Buffer := Encoding.GetBytes(value);
fs := TFileStream.Create(filename,fmCreate);
try
if Length(Preamble) > 0 then
fs.WriteBuffer(Preamble[0], Length(Preamble));
fs.WriteBuffer(Buffer[0], Length(Buffer));
finally
fs.Free;
end;
end;
function TEditorFileHandler.PrepareForSave(var NewFileName: string; const
ChangeName: boolean = FALSE): boolean;
var
canceled: boolean;
dlg: TSaveDialog;
s: string;
OldExt: string;
OldFilterIndex: integer;
attr: integer;
Editor: TfmEditor;
label
EXECUTE_DIALOG;
function FirstMask_From_NewFilter: string;
begin
result := GetDefaultExtForFilterIndex(dlg.Filter, dlg.FilterIndex);
end;
begin
Editor := TfmEditor(fEditor);
canceled := FALSE;
NewFileName := Editor.FileName;
dlg := TSaveDialog.Create(nil);
try
dlg.Options := [ofHideReadOnly, ofEnableSizing];
if (Length(Editor.FileName) = 0) or ChangeName or (Editor.NewFile and
Editor.Unnamed) then
begin
PrepareOpenDlgForFileType(dlg, Editor);
if not Editor.NewFile then
begin
s := ExtractFileExt(Editor.FileName);
dlg.FileName := Copy(Editor.FileName, 1, Length(Editor.FileName) -
Length(s));
if (Length(s) > 0) and (s[1] = '.') then
Delete(s, 1, 1);
OldExt := s;
end
else
begin
dlg.FileName := '';
OldExt := '';
end;
dlg.DefaultExt := '';
OldFilterIndex := dlg.FilterIndex;
BringEditorToFront(Editor);
EXECUTE_DIALOG:
canceled := not dlg.Execute;
if not canceled then
begin
s := dlg.FileName;
if (Pos('.', ExtractFileName(dlg.FileName)) = 0) then
begin
if (OldExt <> '') and (OldFilterIndex = dlg.FilterIndex) then
s := s + '.' + OldExt
else if (dlg.FilterIndex <> 1) then
s := s + '.' + FirstMask_From_NewFilter;
end;
if DlgReplaceFile(s) then
NewFileName := s
else
goto EXECUTE_DIALOG;
end;
end;
finally
dlg.Free;
end;
if not canceled then
begin
attr := FileGetAttr(NewFileName);
if (attr <> -1) and ((attr and faReadOnly) > 0) then
begin
canceled := MessageDlg(Format(mlStr(ML_EDIT_READ_ONLY_WARNING,
'File ''%s'' is read-only. Save file anyway?'), [NewFileName]),
mtWarning, [mbOK, mbCancel], 0) = mrCancel;
if not canceled then
FileSetAttr(NewFileName, attr and not faReadOnly);
end;
end;
result := not canceled;
end;
//------------------------------------------------------------------------------------------
procedure TEditorFileHandler.CopyTo;
var
fname: string;
Editor: TfmEditor;
begin
Editor := TfmEditor(fEditor);
if PrepareForSave(fname, TRUE) then
begin
if not SaveInFormat(Editor.memo.Lines, Editor.TextFormat, fname) then
DlgErrorSaveFile(fname);
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Constructor, destructor
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor TEditorFileHandler.Create(Editor: TObject);
begin
fEditor := Editor;
end;
//------------------------------------------------------------------------------------------
end.
|
unit LiteMemo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, uColorTheme;
{
Lite Memo
}
type TLiteMemo = class(TMemo)
private
theme: ColorTheme;
protected
public
constructor Create(AOwner: TComponent); override;
// IThemeSupporter
procedure setTheme(theme: ColorTheme);
function getTheme(): ColorTheme;
procedure updateColors();
published
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Lite', [TLiteMemo]);
end;
// Override
constructor TLiteMemo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
theme := CT_DEFAULT_THEME;
updateColors();
// other
BorderStyle := bsNone;
ParentColor := True;
Font.Size := 12;
Font.Name := 'Consolas';
Width := 184;
Height := 96;
end;
// Override
procedure TLiteMemo.setTheme(theme: ColorTheme);
begin
self.theme := theme; // link
end;
// Override
function TLiteMemo.getTheme(): ColorTheme;
begin
getTheme := theme;
end;
// Override
procedure TLiteMemo.updateColors();
begin
Font.Color := theme.text;
end;
end.
|
unit ExecOnTime;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls;
type
TExecOnTime = class(TComponent)
private
CheckTimer : TTimer;
FDayTimeHour : word;
FDayTimeMinute : word;
FOnDayTimeExecute : TNotifyEvent;
FActive : boolean;
NextTrigger : TDateTime;
procedure TimeCheck(Sender : TObject);
procedure SetActive(value : boolean);
procedure NewTrigger;
{ Private-Deklarationen }
protected
{ Protected-Deklarationen }
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure ForceTimeCheck;
{ Public-Deklarationen }
published
property DayTimeHour : word read FDayTimeHour write FDayTimeHour;
property DayTimeMinute : word read FDayTimeMinute write FDayTimeMinute;
property Active : boolean read FActive write SetActive;
property OnDayTimeExecute : TNotifyEvent read FOnDayTimeExecute write FOnDayTimeExecute;
{ Published-Deklarationen }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('ASS', [TExecOnTime]);
end;
constructor TExecOnTime.Create(AOwner : TComponent);
begin
inherited;
CheckTimer := TTimer.Create(self);
with CheckTimer do
begin
Interval := 500;
Enabled := FActive;
OnTimer := TimeCheck;
end;
end;
destructor TExecOnTime.Destroy;
begin
FreeandNil(CheckTimer);
inherited;
end;
procedure TExecOnTime.ForceTimeCheck;
begin
TimeCheck(self);
end;
procedure TExecOnTime.NewTrigger;
begin
NextTrigger := Date + EncodeTime(DayTimeHour, DayTimeMinute, 0, 0);
if NextTrigger < now then
NextTrigger := NextTrigger + 1;
end;
procedure TExecOnTime.SetActive(value : boolean);
begin
CheckTimer.Enabled := value;
FActive := value;
if Value then NewTrigger;
end;
procedure TExecOnTime.TimeCheck(Sender : TObject);
begin
if (not (Self.ComponentState = [csDesigning])) and Assigned(FOnDayTimeExecute) then
begin
if (NextTrigger < now) and FActive then
begin
FOnDayTimeExecute(self);
NewTrigger;
end;
end;
end;
end.
|
unit EnumEditItem;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, cxLookAndFeelPainters, cxControls, cxContainer,
cxEdit, cxTextEdit, StdCtrls, cxButtons;
type
TfrmEditEnumItem = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
cxButton1: TcxButton;
cxButton2: TcxButton;
Label1: TLabel;
cxTextEdit1: TcxTextEdit;
Panel3: TPanel;
Label2: TLabel;
cxTextEdit2: TcxTextEdit;
cxTextEdit3: TcxTextEdit;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
procedure cxButton1Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
procedure TfrmEditEnumItem.cxButton1Click(Sender: TObject);
begin
ModalResult:=mrYes;
end;
procedure TfrmEditEnumItem.cxButton2Click(Sender: TObject);
begin
ModalResult:=mrNo;
end;
procedure TfrmEditEnumItem.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
end;
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: JvSplitter.PAS, released on 2001-02-28.
The Initial Developer of the Original Code is Sébastien Buysse [sbuysse att buypin dott com]
Portions created by Sébastien Buysse are Copyright (C) 2001 Sébastien Buysse.
All Rights Reserved.
Contributor(s):
Michael Beck [mbeck att bigfoot dott com].
dejoy(dejoy att ynl dott gov dott cn)
You may retrieve the latest version of this file at the Project JEDI's JVCL home page,
located at http://jvcl.sourceforge.net
Known Issues:
-----------------------------------------------------------------------------}
unit pSHNetscapeSplitter;
//dk{$I jvcl.inc}
interface
uses
//dk {$IFDEF UNITVERSIONING}
//dk JclUnitVersioning,
//dk {$ENDIF UNITVERSIONING}
SysUtils, Classes,
Windows, Messages, Graphics, Forms, ExtCtrls, Controls; //dk,
//dk {$IFDEF VisualCLX}
//dk Qt,
//dk {$ENDIF VisualCLX}
//dk JvExExtCtrls;
const
MOVEMENT_TOLERANCE = 5; // See WMLButtonUp message handler.
JvDefaultButtonHighlightColor = TColor($00FFCFCF); // RGB(207,207,255)
type
TJvButtonWidthKind = (btwPixels, btwPercentage);
TJvButtonStyle = (bsNetscape, bsWindows);
TJvWindowsButton = (wbMin, wbMax, wbClose);
TJvWindowsButtons = set of TJvWindowsButton;
TpSHExSplitter = class(TSplitter)//dk, IJvExControl)
private
//dk FAboutJVCL: TJVCLAboutInfo;
FHintColor: TColor;
FMouseOver: Boolean;
//dk {$IFDEF VCL}
FOnMouseEnter: TNotifyEvent;
FOnMouseLeave: TNotifyEvent;
//dk {$ENDIF VCL}
FOnParentColorChanged: TNotifyEvent;
function BaseWndProc(Msg: Integer; WParam: Integer = 0; LParam: Integer = 0): Integer;
protected
procedure WndProc(var Msg: TMessage); override;
procedure FocusChanged(AControl: TWinControl); dynamic;
procedure VisibleChanged; reintroduce; dynamic;
procedure EnabledChanged; reintroduce; dynamic;
procedure TextChanged; reintroduce; virtual;
procedure ColorChanged; reintroduce; dynamic;
procedure FontChanged; reintroduce; dynamic;
procedure ParentFontChanged; reintroduce; dynamic;
procedure ParentColorChanged; reintroduce; dynamic;
procedure ParentShowHintChanged; reintroduce; dynamic;
function WantKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; reintroduce; virtual;
function HintShow(var HintInfo: THintInfo): Boolean; reintroduce; dynamic;
function HitTest(X, Y: Integer): Boolean; reintroduce; virtual;
procedure MouseEnter(AControl: TControl); reintroduce; dynamic;
procedure MouseLeave(AControl: TControl); reintroduce; dynamic;
//dk {$IFDEF COMPILER5}
//dk {$IFNDEF HASAUTOSIZE}
//dk procedure CMSetAutoSize(var Msg: TMessage); message CM_SETAUTOSIZE;
//dk procedure SetAutoSize(Value: Boolean); virtual;
//dk {$ENDIF !HASAUTOSIZE}
//dk {$ENDIF COMPILER5}
property MouseOver: Boolean read FMouseOver write FMouseOver;
property HintColor: TColor read FHintColor write FHintColor default clDefault;
//dk {$IFDEF VCL}
property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
//dk {$ENDIF VCL}
property OnParentColorChange: TNotifyEvent read FOnParentColorChanged write FOnParentColorChanged;
public
constructor Create(AOwner: TComponent); override;
published
//dk property AboutJVCL: TJVCLAboutInfo read FAboutJVCL write FAboutJVCL stored False;
protected
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
end;
TpSHCustomNetscapeSplitter = class(TpSHExSplitter)
private
//dk {$IFDEF VCL}
FBusy: Boolean;
//dk {$ENDIF VCL}
FShowButton: Boolean;
FButtonWidthKind: TJvButtonWidthKind;
FButtonWidth: Integer;
FOnMaximize: TNotifyEvent;
FOnMinimize: TNotifyEvent;
FOnRestore: TNotifyEvent;
FMaximized: Boolean;
FMinimized: Boolean;
// Internal use for "restoring" from "maximized" state
FRestorePos: Integer;
// For internal use to avoid calling GetButtonRect when not necessary
FLastKnownButtonRect: TRect;
// Internal use to avoid unecessary painting
FIsHighlighted: Boolean;
// Internal for detecting real clicks
FGotMouseDown: Boolean;
FButtonColor: TColor;
FButtonHighlightColor: TColor;
FArrowColor: TColor;
FTextureColor1: TColor;
FTextureColor2: TColor;
FAutoHighlightColor: Boolean;
FAllowDrag: Boolean;
FButtonStyle: TJvButtonStyle;
FWindowsButtons: TJvWindowsButtons;
FOnClose: TNotifyEvent;
FButtonCursor: TCursor;
procedure SetShowButton(const Value: Boolean);
procedure SetButtonWidthKind(const Value: TJvButtonWidthKind);
procedure SetButtonWidth(const Value: Integer);
function GetButtonRect: TRect;
procedure SetMaximized(const Value: Boolean);
procedure SetMinimized(const Value: Boolean);
function GetAlign: TAlign;
procedure SetAlign(Value: TAlign);
procedure SetArrowColor(const Value: TColor);
procedure SetButtonColor(const Value: TColor);
procedure SetButtonHighlightColor(const Value: TColor);
procedure SetButtonStyle(const Value: TJvButtonStyle);
procedure SetTextureColor1(const Value: TColor);
procedure SetTextureColor2(const Value: TColor);
procedure SetAutoHighlightColor(const Value: Boolean);
procedure SetAllowDrag(const Value: Boolean);
procedure SetWindowsButtons(const Value: TJvWindowsButtons);
procedure SetButtonCursor(const Value: TCursor);
protected
// Internal use for moving splitter position with FindControl and
// UpdateControlSize
FControl: TControl;
FDownPos: TPoint;
//dk {$IFDEF VCL}
procedure MouseEnter(Control: TControl); override;
procedure MouseLeave(Control: TControl); override;
procedure Paint; override;
procedure WMLButtonDown(var Msg: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMLButtonUp(var Msg: TWMLButtonUp); message WM_LBUTTONUP;
procedure WMMouseMove(var Msg: TWMMouseMove); message WM_MOUSEMOVE;
//dk {$ENDIF VCL}
procedure LoadOtherProperties(Reader: TReader); dynamic;
procedure StoreOtherProperties(Writer: TWriter); dynamic;
procedure DefineProperties(Filer: TFiler); override;
function DoCanResize(var NewSize: Integer): Boolean; override;
procedure Loaded; override;
procedure PaintButton(Highlight: Boolean); dynamic;
function DrawArrow(ACanvas: TCanvas; AvailableRect: TRect; Offset: Integer;
ArrowSize: Integer; Color: TColor): Integer; dynamic;
function WindowButtonHitTest(X, Y: Integer): TJvWindowsButton; dynamic;
function ButtonHitTest(X, Y: Integer): Boolean; dynamic;
procedure DoMaximize; dynamic;
procedure DoMinimize; dynamic;
procedure DoRestore; dynamic;
procedure DoClose; dynamic;
procedure FindControl; dynamic;
procedure UpdateControlSize(NewSize: Integer); dynamic;
function GrabBarColor: TColor;
function VisibleWinButtons: Integer;
public
constructor Create(AOwner: TComponent); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
property ButtonRect: TRect read GetButtonRect;
property RestorePos: Integer read FRestorePos write FRestorePos;
property Maximized: Boolean read FMaximized write SetMaximized;
property Minimized: Boolean read FMinimized write SetMinimized;
property AllowDrag: Boolean read FAllowDrag write SetAllowDrag default True;
property ButtonCursor: TCursor read FButtonCursor write SetButtonCursor;
property ButtonStyle: TJvButtonStyle read FButtonStyle write SetButtonStyle default bsNetscape;
property WindowsButtons: TJvWindowsButtons read FWindowsButtons write SetWindowsButtons
default [wbMin, wbMax, wbClose];
property ButtonWidthKind: TJvButtonWidthKind read FButtonWidthKind write SetButtonWidthKind
default btwPixels;
property ButtonWidth: Integer read FButtonWidth write SetButtonWidth default 100;
property ShowButton: Boolean read FShowButton write SetShowButton default True;
property ButtonColor: TColor read FButtonColor write SetButtonColor default clBtnFace;
property ArrowColor: TColor read FArrowColor write SetArrowColor default clNavy;
property ButtonHighlightColor: TColor read FButtonHighlightColor write SetButtonHighlightColor
default JvDefaultButtonHighlightColor;
property AutoHighlightColor: Boolean read FAutoHighlightColor write SetAutoHighlightColor
default False;
property TextureColor1: TColor read FTextureColor1 write SetTextureColor1 default clWhite;
property TextureColor2: TColor read FTextureColor2 write SetTextureColor2 default clNavy;
property Align: TAlign read GetAlign write SetAlign; // Need to know when it changes to redraw arrows
property Width default 10; // it looks best with 10
property Beveled default False; // it looks best without the bevel
property Enabled;
property HintColor;
property OnClose: TNotifyEvent read FOnClose write FOnClose;
property OnMaximize: TNotifyEvent read FOnMaximize write FOnMaximize;
property OnMinimize: TNotifyEvent read FOnMinimize write FOnMinimize;
property OnRestore: TNotifyEvent read FOnRestore write FOnRestore;
property OnParentColorChange;
end;
TpSHNetscapeSplitter = class(TpSHCustomNetscapeSplitter)
published
property Maximized;
property Minimized;
property AllowDrag;
property ButtonCursor;
property ButtonStyle;
property WindowsButtons;
property ButtonWidthKind;
property ButtonWidth;
property ShowButton;
property ButtonColor;
property ArrowColor;
property ButtonHighlightColor;
property AutoHighlightColor;
property TextureColor1;
property TextureColor2;
property Align;
property Width;
property Beveled;
property Enabled;
property ShowHint;
property HintColor;
property OnClose;
property OnMaximize;
property OnMinimize;
property OnRestore;
property OnMouseEnter;
property OnMouseLeave;
property OnParentColorChange;
end;
//dk{$IFDEF UNITVERSIONING}
//dkconst
//dk UnitVersioning: TUnitVersionInfo = (
//dk RCSfile: '$RCSfile: pSHNetscapeSplitter.pas,v $';
//dk Revision: '$Revision: 1.2 $';
//dk Date: '$Date: 2007/01/03 07:23:17 $';
//dk LogPath: 'JVCL\run'
//dk );
//dk{$ENDIF UNITVERSIONING}
//dk from JvExControls
function ShiftStateToKeyData(Shift: TShiftState): Longint;
procedure GetHintColor(var HintInfo: THintInfo; AControl: TControl; HintColor: TColor);
procedure SplitterMouseDownFix(Splitter: TSplitter);
implementation
//dkuses
//dk JvThemes;
function ShiftStateToKeyData(Shift: TShiftState): Longint;
const
AltMask = $20000000;
CtrlMask = $10000000;
ShiftMask = $08000000;
begin
Result := 0;
if ssAlt in Shift then
Result := Result or AltMask;
if ssCtrl in Shift then
Result := Result or CtrlMask;
if ssShift in Shift then
Result := Result or ShiftMask;
end;
procedure GetHintColor(var HintInfo: THintInfo; AControl: TControl; HintColor: TColor);
var
AHintInfo: THintInfo;
begin
case HintColor of
clNone:
HintInfo.HintColor := Application.HintColor;
clDefault:
begin
if Assigned(AControl) and Assigned(AControl.Parent) then
begin
AHintInfo := HintInfo;
//dk {$IFDEF VCL}
AControl.Parent.Perform(CM_HINTSHOW, 0, Integer(@AHintInfo));
//dk {$ENDIF VCL}
//dk {$IFDEF VisualCLX}
//dk Perform(AControl.Parent, CM_HINTSHOW, 0, Integer(@AHintInfo));
//dk {$ENDIF VisualCLX}
HintInfo.HintColor := AHintInfo.HintColor;
end;
end;
else
HintInfo.HintColor := HintColor;
end;
end;
procedure SetRectEmpty(var R: TRect);
begin
FillChar(R, SizeOf(TRect), #0);
end;
{ TpSHExSplitter }
constructor TpSHExSplitter.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHintColor := clDefault;
end;
function TpSHExSplitter.BaseWndProc(Msg: Integer; WParam: Integer = 0; LParam: Integer = 0): Integer;
var
Mesg: TMessage;
begin
Mesg.Msg := Msg;
Mesg.WParam := WParam;
Mesg.LParam := LParam;
Mesg.Result := 0;
inherited WndProc(Mesg);
Result := Mesg.Result;
end;
procedure TpSHExSplitter.VisibleChanged;
begin
BaseWndProc(CM_VISIBLECHANGED);
end;
procedure TpSHExSplitter.EnabledChanged;
begin
BaseWndProc(CM_ENABLEDCHANGED);
end;
procedure TpSHExSplitter.TextChanged;
begin
BaseWndProc(CM_TEXTCHANGED);
end;
procedure TpSHExSplitter.FontChanged;
begin
BaseWndProc(CM_FONTCHANGED);
end;
procedure TpSHExSplitter.ColorChanged;
begin
BaseWndProc(CM_COLORCHANGED);
end;
procedure TpSHExSplitter.ParentFontChanged;
begin
BaseWndProc(CM_PARENTFONTCHANGED);
end;
procedure TpSHExSplitter.ParentColorChanged;
begin
BaseWndProc(CM_PARENTCOLORCHANGED);
if Assigned(OnParentColorChange) then
OnParentColorChange(Self);
end;
procedure TpSHExSplitter.ParentShowHintChanged;
begin
BaseWndProc(CM_PARENTSHOWHINTCHANGED);
end;
function TpSHExSplitter.WantKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean;
begin
Result := BaseWndProc(CM_DIALOGCHAR, Word(Key), ShiftStateToKeyData(Shift)) <> 0;
end;
function TpSHExSplitter.HitTest(X, Y: Integer): Boolean;
begin
Result := BaseWndProc(CM_HITTEST, 0, Integer(PointToSmallPoint(Point(X, Y)))) <> 0;
end;
function TpSHExSplitter.HintShow(var HintInfo: THintInfo): Boolean;
begin
GetHintColor(HintInfo, Self, FHintColor);
Result := BaseWndProc(CM_HINTSHOW, 0, Integer(@HintInfo)) <> 0;
end;
procedure TpSHExSplitter.MouseEnter(AControl: TControl);
begin
FMouseOver := True;
//dk {$IFDEF VCL}
if Assigned(FOnMouseEnter) then
FOnMouseEnter(Self);
//dk {$ENDIF VCL}
BaseWndProc(CM_MOUSEENTER, 0, Integer(AControl));
end;
procedure TpSHExSplitter.MouseLeave(AControl: TControl);
begin
FMouseOver := False;
BaseWndProc(CM_MOUSELEAVE, 0, Integer(AControl));
//dk {$IFDEF VCL}
if Assigned(FOnMouseLeave) then
FOnMouseLeave(Self);
//dk {$ENDIF VCL}
end;
procedure TpSHExSplitter.FocusChanged(AControl: TWinControl);
begin
BaseWndProc(CM_FOCUSCHANGED, 0, Integer(AControl));
end;
//dk{$IFDEF COMPILER5}
//dk{$IFNDEF HASAUTOSIZE}
//dkprocedure TpSHExSplitter.CMSetAutoSize(var Msg: TMessage);
//dkbegin
//dk SetAutoSize(Msg.WParam <> 0);
//dkend;
//dkprocedure TpSHExSplitter.SetAutoSize(Value: Boolean);
//dkbegin
//dk TOpenControl_SetAutoSize(Self, Value);
//dkend;
//dk{$ENDIF !HASAUTOSIZE}
//dk{$ENDIF COMPILER5}
procedure TpSHExSplitter.WndProc(var Msg: TMessage);
begin
case Msg.Msg of
//dk CM_DENYSUBCLASSING:
//dk Msg.Result := Ord(GetInterfaceEntry(IJvDenySubClassing) <> nil);
CM_DIALOGCHAR:
with TCMDialogChar(Msg) do
Result := Ord(WantKey(CharCode, KeyDataToShiftState(KeyData), WideChar(CharCode)));
CM_HINTSHOW:
with TCMHintShow(Msg) do
Result := Integer(HintShow(HintInfo^));
CM_HITTEST:
with TCMHitTest(Msg) do
Result := Integer(HitTest(XPos, YPos));
CM_MOUSEENTER:
MouseEnter(TControl(Msg.LParam));
CM_MOUSELEAVE:
MouseLeave(TControl(Msg.LParam));
CM_VISIBLECHANGED:
VisibleChanged;
CM_ENABLEDCHANGED:
EnabledChanged;
CM_TEXTCHANGED:
TextChanged;
CM_FONTCHANGED:
FontChanged;
CM_COLORCHANGED:
ColorChanged;
CM_FOCUSCHANGED:
FocusChanged(TWinControl(Msg.LParam));
CM_PARENTFONTCHANGED:
ParentFontChanged;
CM_PARENTCOLORCHANGED:
ParentColorChanged;
CM_PARENTSHOWHINTCHANGED:
ParentShowHintChanged;
else
inherited WndProc(Msg);
end;
end;
//============================================================================
procedure TpSHExSplitter.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
SplitterMouseDownFix(Self);
inherited MouseDown(Button, Shift, X, Y);
end;
// SplitterMouseDownFix fixes a bug in the VCL that causes the splitter to no
// more work with the control in the left/top of it when the control has a size
// of 0. This is actually a TWinControl.AlignControl bug.
procedure SplitterMouseDownFix(Splitter: TSplitter);
var
Control: TControl;
Pt: TPoint;
R: TRect;
I, Size: Integer;
begin
with Splitter do
begin
if Align in [alLeft, alTop] then
begin
Control := nil;
Pt := Point(Left, Top);
if Align = alLeft then
Dec(Pt.X)
else //if Align = alTop then
Dec(Pt.Y);
for I := 0 to Parent.ControlCount - 1 do
begin
Control := Parent.Controls[I];
R := Control.BoundsRect;
if Align = alLeft then
Size := R.Right - R.Left
else //if Align = alTop then
Size := R.Bottom - R.Top;
if Control.Visible and Control.Enabled and (Size = 0) then
begin
if Align = alLeft then
Dec(R.Left)
else // Align = alTop then
Dec(R.Top);
if PtInRect(R, Pt) then
Break;
end;
Control := nil;
end;
if Control = nil then
begin
// Check for the control that is zero-sized but after the splitter.
// TWinControl.AlignControls does not work properly with alLeft/alTop.
if Align = alLeft then
Pt := Point(Left + Width - 1, Top)
else // if Align = alTop then
Pt := Point(Left, Top + Height - 1);
for I := 0 to Parent.ControlCount - 1 do
begin
Control := Parent.Controls[I];
R := Control.BoundsRect;
if Align = alLeft then
Size := R.Right - R.Left
else //if Align = alTop then
Size := R.Bottom - R.Top;
if Control.Visible and Control.Enabled and (Size = 0) then
begin
if Align = alLeft then
Dec(R.Left)
else // Align = alTop then
Dec(R.Top);
if PtInRect(R, Pt) then
Break;
end;
Control := nil;
end;
if Control <> nil then
begin
// realign left/top control
if Align = alLeft then
Control.Left := -1
else // if Align = alTop then
Control.Top := -1;
end;
end;
end;
end;
end;
{ TpSHCustomNetscapeSplitter }
constructor TpSHCustomNetscapeSplitter.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//dk IncludeThemeStyle(Self, [csParentBackground]);
Beveled := False;
FAllowDrag := True;
FButtonStyle := bsNetscape;
FWindowsButtons := [wbMin, wbMax, wbClose];
FButtonWidthKind := btwPixels;
FButtonWidth := 100;
FShowButton := True;
SetRectEmpty(FLastKnownButtonRect);
FIsHighlighted := False;
FGotMouseDown := False;
FControl := nil;
FDownPos := Point(0, 0);
FMaximized := False;
FMinimized := False;
FRestorePos := -1;
Width := 10;
FButtonColor := clBtnFace;
FArrowColor := clNavy;
FButtonHighlightColor := JvDefaultButtonHighlightColor;
FAutoHighlightColor := False;
FTextureColor1 := clWhite;
FTextureColor2 := clNavy;
end;
//dk{$IFDEF VCL}
procedure TpSHCustomNetscapeSplitter.MouseEnter(Control: TControl);
var
Pos: TPoint;
begin
if csDesigning in ComponentState then
Exit;
if not MouseOver then
begin
inherited MouseEnter(Control);
//from dfs
GetCursorPos(Pos); // CM_MOUSEENTER doesn't send mouse pos.
Pos := Self.ScreenToClient(Pos);
// The order is important here. ButtonHitTest must be evaluated before
// the ButtonStyle because it will change the cursor (over button or not).
// If the order were reversed, the cursor would not get set for bsWindows
// style since short-circuit Boolean eval would stop it from ever being
// called in the first place.
if ButtonHitTest(Pos.X, Pos.Y) and (ButtonStyle = bsNetscape) then
begin
if not FIsHighlighted then
PaintButton(True)
end
else
if FIsHighlighted then
PaintButton(False);
end;
end;
procedure TpSHCustomNetscapeSplitter.MouseLeave(Control: TControl);
begin
if MouseOver then
begin
inherited MouseLeave(Control);
//from dfs
if (ButtonStyle = bsNetscape) and FIsHighlighted then
PaintButton(False);
FGotMouseDown := False;
end;
end;
procedure TpSHCustomNetscapeSplitter.Paint;
//dk{$IFDEF JVCLThemesEnabled}
//dkvar
//dk Bmp: TBitmap;
//dk DC: THandle;
//dk{$ENDIF JVCLThemesEnabled}
begin
if FBusy then
Exit;
FBusy := True;
try
// Exclude button rect from update region here for less flicker.
//dk {$IFDEF JVCLThemesEnabled}
//dk if ThemeServices.ThemesEnabled then
//dk begin
//dk // DrawThemedBackground(Self, Canvas, ClientRect, Parent.Brush.Color);
//dk DC := Canvas.Handle;
//dk Bmp := TBitmap.Create;
//dk try
//dk Bmp.Width := ClientWidth;
//dk Bmp.Height := ClientHeight;
//dk Canvas.Handle := Bmp.Canvas.Handle;
//dk try
//dk inherited Paint;
//dk finally
//dk Canvas.Handle := DC;
//dk end;
//dk Bmp.Transparent := True;
//dk Bmp.TransparentColor := Color;
//dk Canvas.Draw(0, 0, Bmp);
//dk finally
//dk Bmp.Free;
//dk end;
//dk end;
//dk {$ELSE}
inherited Paint;
//dk {$ENDIF JVCLThemesEnabled}
// Don't paint while being moved unless ResizeStyle = rsUpdate!!!
// Make rect smaller if Beveled is True.
PaintButton(FIsHighlighted);
finally
FBusy := False;
end;
end;
//dk{$ENDIF VCL}
//dfs
function TpSHCustomNetscapeSplitter.ButtonHitTest(X, Y: Integer): Boolean;
begin
// We use FLastKnownButtonRect here so that we don't have to recalculate the
// button rect with GetButtonRect every time the mouse moved. That would be
// EXTREMELY inefficient.
Result := PtInRect(FLastKnownButtonRect, Point(X, Y));
if Align in [alLeft, alRight] then
begin
if (not AllowDrag) or ((Y >= FLastKnownButtonRect.Top) and
(Y <= FLastKnownButtonRect.Bottom)) then
Windows.SetCursor(Screen.Cursors[ButtonCursor])
else
Windows.SetCursor(Screen.Cursors[Cursor]);
end
else
begin
if (not AllowDrag) or ((X >= FLastKnownButtonRect.Left) and
(X <= FLastKnownButtonRect.Right)) then
Windows.SetCursor(Screen.Cursors[ButtonCursor])
else
Windows.SetCursor(Screen.Cursors[Cursor]);
end;
end;
procedure TpSHCustomNetscapeSplitter.DefineProperties(Filer: TFiler);
begin
inherited DefineProperties(Filer);
Filer.DefineProperty('RestorePos', LoadOtherProperties, StoreOtherProperties,
Minimized or Maximized);
end;
function TpSHCustomNetscapeSplitter.DoCanResize(var NewSize: Integer): Boolean;
begin
Result := inherited DoCanResize(NewSize);
// D4 version has a bug that causes it to not honor MinSize, which causes a
// really nasty problem.
if Result and (NewSize < MinSize) then
NewSize := MinSize;
end;
procedure TpSHCustomNetscapeSplitter.DoClose;
begin
if Assigned(FOnClose) then
FOnClose(Self);
end;
procedure TpSHCustomNetscapeSplitter.DoMaximize;
begin
if Assigned(FOnMaximize) then
FOnMaximize(Self);
end;
procedure TpSHCustomNetscapeSplitter.DoMinimize;
begin
if Assigned(FOnMinimize) then
FOnMinimize(Self);
end;
procedure TpSHCustomNetscapeSplitter.DoRestore;
begin
if Assigned(FOnRestore) then
FOnRestore(Self);
end;
function TpSHCustomNetscapeSplitter.DrawArrow(ACanvas: TCanvas; AvailableRect: TRect;
Offset, ArrowSize: Integer; Color: TColor): Integer;
var
X, Y, Q, I, J: Integer;
ArrowAlign: TAlign;
begin
// STB Nitro drivers have a LineTo bug, so I've opted to use the slower
// SetPixel method to draw the arrows.
if not Odd(ArrowSize) then
Dec(ArrowSize);
if ArrowSize < 1 then
ArrowSize := 1;
if FMaximized then
begin
case Align of
alLeft:
ArrowAlign := alRight;
alRight:
ArrowAlign := alLeft;
alTop:
ArrowAlign := alBottom;
else //alBottom
ArrowAlign := alTop;
end;
end
else
ArrowAlign := Align;
Q := ArrowSize * 2 - 1;
Result := Q;
ACanvas.Pen.Color := Color;
with AvailableRect do
begin
case ArrowAlign of
alLeft:
begin
X := Left + ((Right - Left - ArrowSize) div 2) + 1;
if Offset < 0 then
Y := Bottom + Offset - Q
else
Y := Top + Offset;
for J := X + ArrowSize - 1 downto X do
begin
for I := Y to Y + Q - 1 do
ACanvas.Pixels[J, I] := Color;
Inc(Y);
Dec(Q, 2);
end;
end;
alRight:
begin
X := Left + ((Right - Left - ArrowSize) div 2) + 1;
if Offset < 0 then
Y := Bottom + Offset - Q
else
Y := Top + Offset;
for J := X to X + ArrowSize - 1 do
begin
for I := Y to Y + Q - 1 do
ACanvas.Pixels[J, I] := Color;
Inc(Y);
Dec(Q, 2);
end;
end;
alTop:
begin
if Offset < 0 then
X := Right + Offset - Q
else
X := Left + Offset;
Y := Top + ((Bottom - Top - ArrowSize) div 2) + 1;
for I := Y + ArrowSize - 1 downto Y do
begin
for J := X to X + Q - 1 do
ACanvas.Pixels[J, I] := Color;
Inc(X);
Dec(Q, 2);
end;
end;
else // alBottom
if Offset < 0 then
X := Right + Offset - Q
else
X := Left + Offset;
Y := Top + ((Bottom - Top - ArrowSize) div 2) + 1;
for I := Y to Y + ArrowSize - 1 do
begin
for J := X to X + Q - 1 do
ACanvas.Pixels[J, I] := Color;
Inc(X);
Dec(Q, 2);
end;
end;
end;
end;
procedure TpSHCustomNetscapeSplitter.FindControl;
var
P: TPoint;
I: Integer;
R: TRect;
begin
if Parent = nil then
Exit;
FControl := nil;
P := Point(Left, Top);
case Align of
alLeft:
Dec(P.X);
alRight:
Inc(P.X, Width);
alTop:
Dec(P.Y);
alBottom:
Inc(P.Y, Height);
else
Exit;
end;
for I := 0 to Parent.ControlCount - 1 do
begin
FControl := Parent.Controls[I];
if FControl.Visible and FControl.Enabled then
begin
R := FControl.BoundsRect;
if (R.Right - R.Left) = 0 then
Dec(R.Left);
if (R.Bottom - R.Top) = 0 then
Dec(R.Top);
if PtInRect(R, P) then
Exit;
end;
end;
FControl := nil;
end;
function TpSHCustomNetscapeSplitter.GetAlign: TAlign;
begin
Result := inherited Align;
end;
function TpSHCustomNetscapeSplitter.GetButtonRect: TRect;
var
BW: Integer;
begin
if ButtonStyle = bsWindows then
begin
if Align in [alLeft, alRight] then
BW := (ClientRect.Right - ClientRect.Left) * VisibleWinButtons
else
BW := (ClientRect.Bottom - ClientRect.Top) * VisibleWinButtons;
if BW < 1 then
SetRectEmpty(Result)
else
begin
if Align in [alLeft, alRight] then
Result := Rect(0, 0, ClientRect.Right - ClientRect.Left,
BW - VisibleWinButtons)
else
Result := Rect(ClientRect.Right - BW + VisibleWinButtons, 0,
ClientRect.Right, ClientRect.Bottom - ClientRect.Top);
InflateRect(Result, -1, -1);
end;
end
else
begin
// Calc the rectangle the button goes in
if ButtonWidthKind = btwPercentage then
begin
if Align in [alLeft, alRight] then
BW := ClientRect.Bottom - ClientRect.Top
else
BW := ClientRect.Right - ClientRect.Left;
BW := MulDiv(BW, FButtonWidth, 100);
end
else
BW := FButtonWidth;
if BW < 1 then
SetRectEmpty(Result)
else
begin
Result := ClientRect;
if Align in [alLeft, alRight] then
begin
Result.Top := (ClientRect.Bottom - ClientRect.Top - BW) div 2;
Result.Bottom := Result.Top + BW;
InflateRect(Result, -1, 0);
end
else
begin
Result.Left := (ClientRect.Right - ClientRect.Left - BW) div 2;
Result.Right := Result.Left + BW;
InflateRect(Result, 0, -1);
end;
end;
end;
if not IsRectEmpty(Result) then
begin
if Result.Top < 1 then
Result.Top := 1;
if Result.Left < 1 then
Result.Left := 1;
if Result.Bottom >= ClientRect.Bottom then
Result.Bottom := ClientRect.Bottom - 1;
if Result.Right >= ClientRect.Right then
Result.Right := ClientRect.Right - 1;
// Make smaller if it's beveled
if Beveled then
if Align in [alLeft, alRight] then
InflateRect(Result, -3, 0)
else
InflateRect(Result, 0, -3);
end;
FLastKnownButtonRect := Result;
end;
function TpSHCustomNetscapeSplitter.GrabBarColor: TColor;
var
BeginRGB: array [0..2] of Byte;
RGBDifference: array [0..2] of Integer;
R, G, B: Byte;
BeginColor, EndColor: TColor;
NumberOfColors: Integer;
begin
//Need to figure out how many colors available at runtime
NumberOfColors := 256;
BeginColor := clActiveCaption;
EndColor := clBtnFace;
BeginRGB[0] := GetRValue(ColorToRGB(BeginColor));
BeginRGB[1] := GetGValue(ColorToRGB(BeginColor));
BeginRGB[2] := GetBValue(ColorToRGB(BeginColor));
RGBDifference[0] := GetRValue(ColorToRGB(EndColor)) - BeginRGB[0];
RGBDifference[1] := GetGValue(ColorToRGB(EndColor)) - BeginRGB[1];
RGBDifference[2] := GetBValue(ColorToRGB(EndColor)) - BeginRGB[2];
R := BeginRGB[0] + MulDiv(180, RGBDifference[0], NumberOfColors - 1);
G := BeginRGB[1] + MulDiv(180, RGBDifference[1], NumberOfColors - 1);
B := BeginRGB[2] + MulDiv(180, RGBDifference[2], NumberOfColors - 1);
Result := RGB(R, G, B);
end;
procedure TpSHCustomNetscapeSplitter.Loaded;
begin
inherited Loaded;
if FRestorePos = -1 then
begin
FindControl;
if FControl <> nil then
case Align of
alLeft, alRight:
FRestorePos := FControl.Width;
alTop, alBottom:
FRestorePos := FControl.Height;
end;
end;
end;
procedure TpSHCustomNetscapeSplitter.LoadOtherProperties(Reader: TReader);
begin
RestorePos := Reader.ReadInteger;
end;
procedure TpSHCustomNetscapeSplitter.PaintButton(Highlight: Boolean);
const
TEXTURE_SIZE = 3;
var
BtnRect: TRect;
CaptionBtnRect: TRect;
BW: Integer;
TextureBmp: TBitmap;
X, Y: Integer;
RW, RH: Integer;
OffscreenBmp: TBitmap;
WinButton: array [0..2] of TJvWindowsButton;
B: TJvWindowsButton;
BtnFlag: UINT;
begin
if (not FShowButton) or (not Enabled) or (GetParentForm(Self) = nil) then
Exit;
if FAutoHighlightColor then
FButtonHighlightColor := GrabBarColor;
BtnRect := ButtonRect; // So we don't repeatedly call GetButtonRect
if IsRectEmpty(BtnRect) then
Exit; // nothing to draw
OffscreenBmp := TBitmap.Create;
try
OffsetRect(BtnRect, -BtnRect.Left, -BtnRect.Top);
OffscreenBmp.Width := BtnRect.Right;
OffscreenBmp.Height := BtnRect.Bottom;
if ButtonStyle = bsWindows then
begin
OffscreenBmp.Canvas.Brush.Color := Color;
OffscreenBmp.Canvas.FillRect(BtnRect);
if Align in [alLeft, alRight] then
BW := BtnRect.Right
else
BW := BtnRect.Bottom;
FillChar(WinButton, SizeOf(WinButton), 0);
X := 0;
if Align in [alLeft, alRight] then
begin
for B := High(TJvWindowsButton) downto Low(TJvWindowsButton) do
if B in WindowsButtons then
begin
WinButton[X] := B;
Inc(X);
end;
end
else
begin
for B := Low(TJvWindowsButton) to High(TJvWindowsButton) do
if B in WindowsButtons then
begin
WinButton[X] := B;
Inc(X);
end;
end;
for X := 0 to VisibleWinButtons - 1 do
begin
if Align in [alLeft, alRight] then
CaptionBtnRect := Bounds(0, X * BW, BW, BW)
else
CaptionBtnRect := Bounds(X * BW, 0, BW, BW);
BtnFlag := 0;
case WinButton[X] of
wbMin:
if Minimized then
BtnFlag := DFCS_CAPTIONRESTORE
else
BtnFlag := DFCS_CAPTIONMIN;
wbMax:
if Maximized then
BtnFlag := DFCS_CAPTIONRESTORE
else
BtnFlag := DFCS_CAPTIONMAX;
wbClose:
BtnFlag := DFCS_CAPTIONCLOSE;
end;
DrawFrameControl(OffscreenBmp.Canvas.Handle,
CaptionBtnRect, DFC_CAPTION, BtnFlag);
end;
end
else
begin
// Draw basic button
OffscreenBmp.Canvas.Brush.Color := clGray;
//dk {$IFDEF VCL}
OffscreenBmp.Canvas.FrameRect(BtnRect);
//dk {$ENDIF VCL}
//dk {$IFDEF VisualCLX}
//dk FrameRect(OffscreenBmp.Canvas, BtnRect);
//dk {$ENDIF VisualCLX}
InflateRect(BtnRect, -1, -1);
OffscreenBmp.Canvas.Pen.Color := clWhite;
with BtnRect, OffscreenBmp.Canvas do
begin
// This is not going to work with the STB bug. Have to find workaround.
MoveTo(Left, Bottom - 1);
LineTo(Left, Top);
LineTo(Right, Top);
end;
Inc(BtnRect.Left);
Inc(BtnRect.Top);
if Highlight then
OffscreenBmp.Canvas.Brush.Color := ButtonHighlightColor
else
OffscreenBmp.Canvas.Brush.Color := ButtonColor;
OffscreenBmp.Canvas.FillRect(BtnRect);
FIsHighlighted := Highlight;
Dec(BtnRect.Right);
Dec(BtnRect.Bottom);
// Draw the insides of the button
with BtnRect do
begin
// Draw the arrows
if Align in [alLeft, alRight] then
begin
InflateRect(BtnRect, 0, -4);
BW := BtnRect.Right - BtnRect.Left;
DrawArrow(OffscreenBmp.Canvas, BtnRect, 1, BW, ArrowColor);
BW := DrawArrow(OffscreenBmp.Canvas, BtnRect, -1, BW, ArrowColor);
InflateRect(BtnRect, 0, -(BW + 4));
end
else
begin
InflateRect(BtnRect, -4, 0);
BW := BtnRect.Bottom - BtnRect.Top;
DrawArrow(OffscreenBmp.Canvas, BtnRect, 1, BW, ArrowColor);
BW := DrawArrow(OffscreenBmp.Canvas, BtnRect, -1, BW, ArrowColor);
InflateRect(BtnRect, -(BW + 4), 0);
end;
// Draw the texture
// Note: This is so complex because I'm trying to make as much like the
// Netscape splitter as possible. They use a 3x3 texture pattern, and
// that's harder to tile. If the had used an 8x8 (or smaller
// divisibly, i.e. 2x2 or 4x4), I could have used Brush.Bitmap and
// FillRect and they whole thing would have been about half the size,
// twice as fast, and 1/10th as complex.
RW := BtnRect.Right - BtnRect.Left;
RH := BtnRect.Bottom - BtnRect.Top;
if (RW >= TEXTURE_SIZE) and (RH >= TEXTURE_SIZE) then
begin
TextureBmp := TBitmap.Create;
try
with TextureBmp do
begin
Width := RW;
Height := RH;
// Draw first square
Canvas.Brush.Color := OffscreenBmp.Canvas.Brush.Color;
Canvas.FillRect(Rect(0, 0, RW + 1, RH + 1));
Canvas.Pixels[1, 1] := TextureColor1;
Canvas.Pixels[2, 2] := TextureColor2;
// Tile first square all the way across
for X := 1 to ((RW div TEXTURE_SIZE) + ord(RW mod TEXTURE_SIZE > 0)) do
Canvas.CopyRect(Bounds(X * TEXTURE_SIZE, 0, TEXTURE_SIZE,
TEXTURE_SIZE), Canvas, Rect(0, 0, TEXTURE_SIZE, TEXTURE_SIZE));
// Tile first row all the way down
for Y := 1 to ((RH div TEXTURE_SIZE) + ord(RH mod TEXTURE_SIZE > 0)) do
Canvas.CopyRect(Bounds(0, Y * TEXTURE_SIZE, RW, TEXTURE_SIZE),
Canvas, Rect(0, 0, RW, TEXTURE_SIZE));
// Above could be better if it reversed process when splitter was
// taller than it was wider. Optimized only for horizontal right now.
end;
// Copy texture bitmap to the screen.
OffscreenBmp.Canvas.CopyRect(BtnRect, TextureBmp.Canvas,
Rect(0, 0, RW, RH));
finally
TextureBmp.Free;
end;
end;
end;
end;
(**)
Canvas.CopyRect(ButtonRect, OffscreenBmp.Canvas, Rect(0, 0,
OffscreenBmp.Width, OffscreenBmp.Height));
finally
OffscreenBmp.Free;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetAlign(Value: TAlign);
begin
if Align <> Value then
begin
inherited Align := Value;
Invalidate; // Direction changing, redraw arrows.
end;
end;
procedure TpSHCustomNetscapeSplitter.SetAllowDrag(const Value: Boolean);
var
Pt: TPoint;
begin
if FAllowDrag <> Value then
begin
FAllowDrag := Value;
// Have to reset cursor in case it's on the splitter at the moment
GetCursorPos(Pt);
Pt := ScreenToClient(Pt);
ButtonHitTest(Pt.X, Pt.Y);
end;
end;
procedure TpSHCustomNetscapeSplitter.SetArrowColor(const Value: TColor);
begin
if FArrowColor <> Value then
begin
FArrowColor := Value;
if (ButtonStyle = bsNetscape) and ShowButton then
Invalidate;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetAutoHighlightColor(const Value: Boolean);
begin
if FAutoHighlightColor <> Value then
begin
FAutoHighlightColor := Value;
if FAutoHighlightColor then
FButtonHighlightColor := GrabBarColor
else
FButtonHighlightColor := JvDefaultButtonHighlightColor;
if (ButtonStyle = bsNetscape) and ShowButton then
Invalidate;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetButtonColor(const Value: TColor);
begin
if FButtonColor <> Value then
begin
FButtonColor := Value;
if (ButtonStyle = bsNetscape) and ShowButton then
Invalidate;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetButtonCursor(const Value: TCursor);
begin
FButtonCursor := Value;
end;
procedure TpSHCustomNetscapeSplitter.SetButtonHighlightColor(const Value: TColor);
begin
if FButtonHighlightColor <> Value then
begin
FButtonHighlightColor := Value;
if (ButtonStyle = bsNetscape) and ShowButton then
Invalidate;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetButtonStyle(const Value: TJvButtonStyle);
begin
FButtonStyle := Value;
if ShowButton then
Invalidate;
end;
procedure TpSHCustomNetscapeSplitter.SetButtonWidth(const Value: Integer);
begin
if Value <> FButtonWidth then
begin
FButtonWidth := Value;
if (ButtonWidthKind = btwPercentage) and (FButtonWidth > 100) then
FButtonWidth := 100;
if FButtonWidth < 0 then
FButtonWidth := 0;
if (ButtonStyle = bsNetscape) and ShowButton then
Invalidate;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetButtonWidthKind(const Value: TJvButtonWidthKind);
begin
if Value <> FButtonWidthKind then
begin
FButtonWidthKind := Value;
if (FButtonWidthKind = btwPercentage) and (ButtonWidth > 100) then
FButtonWidth := 100;
if (ButtonStyle = bsNetscape) and ShowButton then
Invalidate;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetMaximized(const Value: Boolean);
begin
if Value <> FMaximized then
begin
if csLoading in ComponentState then
begin
FMaximized := Value;
Exit;
end;
FindControl;
if FControl = nil then
Exit;
if Value then
begin
if FMinimized then
FMinimized := False
else
begin
case Align of
alLeft, alRight:
FRestorePos := FControl.Width;
alTop, alBottom:
FRestorePos := FControl.Height;
else
Exit;
end;
end;
if ButtonStyle = bsNetscape then
UpdateControlSize(-3000)
else
case Align of
alLeft, alBottom:
UpdateControlSize(3000);
alRight, alTop:
UpdateControlSize(-3000);
else
Exit;
end;
FMaximized := Value;
DoMaximize;
end
else
begin
UpdateControlSize(FRestorePos);
FMaximized := Value;
DoRestore;
end;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetMinimized(const Value: Boolean);
begin
if Value <> FMinimized then
begin
if csLoading in ComponentState then
begin
FMinimized := Value;
Exit;
end;
FindControl;
if FControl = nil then
Exit;
if Value then
begin
if FMaximized then
FMaximized := False
else
begin
case Align of
alLeft, alRight:
FRestorePos := FControl.Width;
alTop, alBottom:
FRestorePos := FControl.Height;
else
Exit;
end;
end;
FMinimized := Value;
// Just use something insanely large to get it to move to the other extreme
case Align of
alLeft, alBottom:
UpdateControlSize(-3000);
alRight, alTop:
UpdateControlSize(3000);
else
Exit;
end;
DoMinimize;
end
else
begin
FMinimized := Value;
UpdateControlSize(FRestorePos);
DoRestore;
end;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetShowButton(const Value: Boolean);
begin
if Value <> FShowButton then
begin
FShowButton := Value;
SetRectEmpty(FLastKnownButtonRect);
Invalidate;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetTextureColor1(const Value: TColor);
begin
if FTextureColor1 <> Value then
begin
FTextureColor1 := Value;
if (ButtonStyle = bsNetscape) and ShowButton then
Invalidate;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetTextureColor2(const Value: TColor);
begin
if FTextureColor2 <> Value then
begin
FTextureColor2 := Value;
if (ButtonStyle = bsNetscape) and ShowButton then
Invalidate;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetWindowsButtons(const Value: TJvWindowsButtons);
begin
FWindowsButtons := Value;
if (ButtonStyle = bsWindows) and ShowButton then
Invalidate;
end;
procedure TpSHCustomNetscapeSplitter.StoreOtherProperties(Writer: TWriter);
begin
Writer.WriteInteger(RestorePos);
end;
procedure TpSHCustomNetscapeSplitter.UpdateControlSize(NewSize: Integer);
procedure MoveViaMouse(FromPos, ToPos: Integer; Horizontal: Boolean);
begin
if Horizontal then
begin
MouseDown(mbLeft, [ssLeft], FromPos, 0);
MouseMove([ssLeft], ToPos, 0);
MouseUp(mbLeft, [ssLeft], ToPos, 0);
end
else
begin
MouseDown(mbLeft, [ssLeft], 0, FromPos);
MouseMove([ssLeft], 0, ToPos);
MouseUp(mbLeft, [ssLeft], 0, ToPos);
end;
end;
begin
if FControl <> nil then
begin
{ You'd think that using FControl directly would be the way to change it's
position (and thus the splitter's position), wouldn't you? But, TSplitter
has this nutty idea that the only way a control's size will change is if
the mouse moves the splitter. If you size the control manually, the
splitter has an internal variable (FOldSize) that will not get updated.
Because of this, if you try to then move the newly positioned splitter
back to the old position, it won't go there (NewSize <> OldSize must be
True). Now, what are the odds that the user will move the splitter back
to the exact same pixel it used to be on? Normally, extremely low. But,
if the splitter has been restored from it's minimized position, it then
becomes quite likely: i.e. they drag it back all the way to the min
position. What a pain. }
case Align of
alLeft:
MoveViaMouse(Left, FControl.Left + NewSize, True);
// alLeft: FControl.Width := NewSize;
alTop:
MoveViaMouse(Top, FControl.Top + NewSize, False);
// FControl.Height := NewSize;
alRight:
MoveViaMouse(Left, (FControl.Left + FControl.Width - Width) - NewSize, True);
{begin
Parent.DisableAlign;
try
FControl.Left := FControl.Left + (FControl.Width - NewSize);
FControl.Width := NewSize;
finally
Parent.EnableAlign;
end;
end;}
alBottom:
MoveViaMouse(Top, (FControl.Top + FControl.Height - Height) - NewSize, False);
{begin
Parent.DisableAlign;
try
FControl.Top := FControl.Top + (FControl.Height - NewSize);
FControl.Height := NewSize;
finally
Parent.EnableAlign;
end;
end;}
end;
Update;
end;
end;
function TpSHCustomNetscapeSplitter.VisibleWinButtons: Integer;
var
X: TJvWindowsButton;
begin
Result := 0;
for X := Low(TJvWindowsButton) to High(TJvWindowsButton) do
if X in WindowsButtons then
Inc(Result);
end;
function TpSHCustomNetscapeSplitter.WindowButtonHitTest(X, Y: Integer): TJvWindowsButton;
var
BtnRect: TRect;
I: Integer;
B: TJvWindowsButton;
WinButton: array [0..2] of TJvWindowsButton;
BW: Integer;
BRs: array [0..2] of TRect;
begin
Result := wbMin;
// Figure out which one was hit. This function assumes ButtonHitTest has
// been called and returned True.
BtnRect := ButtonRect; // So we don't repeatedly call GetButtonRect
I := 0;
if Align in [alLeft, alRight] then
begin
for B := High(TJvWindowsButton) downto Low(TJvWindowsButton) do
if B in WindowsButtons then
begin
WinButton[I] := B;
Inc(I);
end;
end
else
for B := Low(TJvWindowsButton) to High(TJvWindowsButton) do
if B in WindowsButtons then
begin
WinButton[I] := B;
Inc(I);
end;
if Align in [alLeft, alRight] then
BW := BtnRect.Right - BtnRect.Left
else
BW := BtnRect.Bottom - BtnRect.Top;
FillChar(BRs, SizeOf(BRs), 0);
for I := 0 to VisibleWinButtons - 1 do
if ((Align in [alLeft, alRight]) and PtInRect(Bounds(BtnRect.Left,
BtnRect.Top + (BW * I), BW, BW), Point(X, Y))) or ((Align in [alTop,
alBottom]) and PtInRect(Bounds(BtnRect.Left + (BW * I), BtnRect.Top, BW,
BW), Point(X, Y))) then
begin
Result := WinButton[I];
break;
end;
end;
procedure TpSHCustomNetscapeSplitter.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
if FRestorePos < 0 then
begin
FindControl;
if FControl <> nil then
case Align of
alLeft, alRight:
FRestorePos := FControl.Width;
alTop, alBottom:
FRestorePos := FControl.Height;
end;
end;
end;
//dk{$IFDEF VCL}
procedure TpSHCustomNetscapeSplitter.WMLButtonDown(var Msg: TWMLButtonDown);
begin
if Enabled then
begin
FGotMouseDown := ButtonHitTest(Msg.XPos, Msg.YPos);
if FGotMouseDown then
begin
FindControl;
FDownPos := ClientToScreen(Point(Msg.XPos, Msg.YPos));
end;
end;
if AllowDrag then
inherited // Let TSplitter have it.
else
// Bypass TSplitter and just let normal handling occur. Prevents drag painting.
DefaultHandler(Msg);
end;
procedure TpSHCustomNetscapeSplitter.WMLButtonUp(var Msg: TWMLButtonUp);
var
CurPos: TPoint;
OldMax: Boolean;
begin
inherited;
if FGotMouseDown then
begin
if ButtonHitTest(Msg.XPos, Msg.YPos) then
begin
CurPos := ClientToScreen(Point(Msg.XPos, Msg.YPos));
// More than a little movement is not a click, but a regular resize.
if ((Align in [alLeft, alRight]) and
(Abs(FDownPos.X - CurPos.X) <= MOVEMENT_TOLERANCE)) or
((Align in [alTop, alBottom]) and
(Abs(FDownPos.Y - CurPos.Y) <= MOVEMENT_TOLERANCE)) then
begin
StopSizing;
if ButtonStyle = bsNetscape then
Maximized := not Maximized
else
case WindowButtonHitTest(Msg.XPos, Msg.YPos) of
wbMin:
Minimized := not Minimized;
wbMax:
Maximized := not Maximized;
wbClose:
DoClose;
end;
end;
end;
FGotMouseDown := False;
end
else
if AllowDrag then
begin
FindControl;
if FControl = nil then
Exit;
OldMax := FMaximized;
case Align of
alLeft, alRight:
FMaximized := FControl.Width <= MinSize;
alTop, alBottom:
FMaximized := FControl.Height <= MinSize;
end;
if FMaximized then
begin
UpdateControlSize(MinSize);
if not OldMax then
DoMaximize;
end
else
begin
case Align of
alLeft, alRight:
FRestorePos := FControl.Width;
alTop, alBottom:
FRestorePos := FControl.Height;
end;
if OldMax then
DoRestore;
end;
end;
Invalidate;
end;
procedure TpSHCustomNetscapeSplitter.WMMouseMove(var Msg: TWMMouseMove);
begin
if AllowDrag then
begin
inherited;
// The order is important here. ButtonHitTest must be evaluated before
// the ButtonStyle because it will change the cursor (over button or not).
// If the order were reversed, the cursor would not get set for bsWindows
// style since short-circuit Boolean eval would stop it from ever being
// called in the first place.
if ButtonHitTest(Msg.XPos, Msg.YPos) and (ButtonStyle = bsNetscape) then
begin
if not FIsHighlighted then
PaintButton(True)
end
else
if FIsHighlighted then
PaintButton(False);
end
else
DefaultHandler(Msg); // Bypass TSplitter and just let normal handling occur.
end;
//dk{$ENDIF VCL}
//dk{$IFDEF UNITVERSIONING}
//dkinitialization
//dk RegisterUnitVersion(HInstance, UnitVersioning);
//dkfinalization
//dk UnregisterUnitVersion(HInstance);
//dk{$ENDIF UNITVERSIONING}
end.
|
unit Demo.Material.LineChart.TopX;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_MaterialLineChart_TopX = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_MaterialLineChart_TopX.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_MATERIAL_LINE_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Day'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Guardians of the Galaxy'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'The Avengers'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Transformers: Age of Extinction')
]);
Chart.Data.AddRow([1, 37.8, 80.8, 41.8]);
Chart.Data.AddRow([2, 30.9, 69.5, 32.4]);
Chart.Data.AddRow([3, 25.4, 57, 25.7]);
Chart.Data.AddRow([4, 11.7, 18.8, 10.5]);
Chart.Data.AddRow([5, 11.9, 17.6, 10.4]);
Chart.Data.AddRow([6, 8.8, 13.6, 7.7]);
Chart.Data.AddRow([7, 7.6, 12.3, 9.6]);
Chart.Data.AddRow([8, 12.3, 29.2, 10.6]);
Chart.Data.AddRow([9, 16.9, 42.9, 14.8]);
Chart.Data.AddRow([10, 12.8, 30.9, 11.6]);
Chart.Data.AddRow([11, 5.3, 7.9, 4.7]);
Chart.Data.AddRow([12, 6.6, 8.4, 5.2]);
Chart.Data.AddRow([13, 4.8, 6.3, 3.6]);
Chart.Data.AddRow([14, 4.2, 6.2, 3.4]);
// Options
Chart.Options.Title('Box Office Earnings in First Two Weeks of Opening');
Chart.Options.Subtitle('in millions of dollars (USD)');
Chart.Options.Axes('x', '{0: {side: ''top''}}');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody(
'<div style="width:80%; height:10%"></div>' +
'<div id="Chart" style="width:80%; height:80%;margin: auto"></div>' +
'<div style="width:80%; height:10%"></div>'
);
GChartsFrame.DocumentGenerate('Chart', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_MaterialLineChart_TopX);
end.
|
unit UDGroupSelection;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeGroupSelectionDlg = class(TForm)
pnlSelection1: TPanel;
lblSelectionText: TLabel;
memoSelection: TMemo;
btnOk: TButton;
btnCancel: TButton;
btnClear: TButton;
btnCheck: TButton;
procedure FormShow(Sender: TObject);
procedure memoSelectionChange(Sender: TObject);
procedure btnCheckClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure UpdateSelection;
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
rFormula : TStringList;
end;
var
CrpeGroupSelectionDlg: TCrpeGroupSelectionDlg;
bGroupSelection : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate Method }
{------------------------------------------------------------------------------}
procedure TCrpeGroupSelectionDlg.FormCreate(Sender: TObject);
begin
bGroupSelection := True;
LoadFormPos(Self);
btnOk.Tag := 1;
btnCancel.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow Method }
{------------------------------------------------------------------------------}
procedure TCrpeGroupSelectionDlg.FormShow(Sender: TObject);
begin
rFormula := TStringList.Create;
rFormula.Assign(Cr.GroupSelection.Formula);
UpdateSelection;
end;
{------------------------------------------------------------------------------}
{ UpdateSelection Method }
{------------------------------------------------------------------------------}
procedure TCrpeGroupSelectionDlg.UpdateSelection;
var
OnOff : boolean;
begin
{Enable/Disable controls}
OnOff := not IsStrEmpty(Cr.ReportName);
InitializeControls(OnOff);
{Update list box}
if OnOff then
begin
memoSelection.OnChange := nil;
memoSelection.Lines.Assign(Cr.GroupSelection.Formula);
memoSelection.OnChange := memoSelectionChange;
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeGroupSelectionDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TMemo then
begin
TMemo(Components[i]).Clear;
TMemo(Components[i]).Color := ColorState(OnOff);
TMemo(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ memoSelectionChange Method }
{------------------------------------------------------------------------------}
procedure TCrpeGroupSelectionDlg.memoSelectionChange(Sender: TObject);
begin
Cr.GroupSelection.Formula.Assign(memoSelection.Lines);
end;
{------------------------------------------------------------------------------}
{ btnCheckClick Method }
{------------------------------------------------------------------------------}
procedure TCrpeGroupSelectionDlg.btnCheckClick(Sender: TObject);
begin
if Cr.GroupSelection.Check then
MessageDlg('GroupSelection Formula is Good!', mtInformation, [mbOk], 0)
else
MessageDlg('GroupSelection Formula has an Error.' + Chr(10) +
Cr.LastErrorString, mtError, [mbOk], 0);
end;
{------------------------------------------------------------------------------}
{ btnClearClick Method }
{------------------------------------------------------------------------------}
procedure TCrpeGroupSelectionDlg.btnClearClick(Sender: TObject);
begin
Cr.GroupSelection.Clear;
UpdateSelection;
end;
{------------------------------------------------------------------------------}
{ btnOkClick Method }
{------------------------------------------------------------------------------}
procedure TCrpeGroupSelectionDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
ModalResult := mrOk;
Close;
end;
{------------------------------------------------------------------------------}
{ btnCancelClick Method }
{------------------------------------------------------------------------------}
procedure TCrpeGroupSelectionDlg.btnCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose Method }
{------------------------------------------------------------------------------}
procedure TCrpeGroupSelectionDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ModalResult = mrCancel then
begin
{Restore Settings}
Cr.GroupSelection.Formula.Assign(rFormula);
end;
rFormula.Free;
bGroupSelection := False;
Release;
end;
end.
|
unit cn_fr_CalcUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cn_DM_Calc,
cn_Common_Types, cn_Common_Funcs, cnConsts, cxRadioGroup, cxControls,
cxGroupBox, ExtCtrls, cxLabel, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxDropDownEdit, cxCalendar, frxExportPDF, frxExportXLS,
frxExportHTML, frxClass, frxExportRTF, ActnList, FIBQuery, pFIBQuery,
pFIBStoredProc, frxDBSet, DB, FIBDataSet, pFIBDataSet, frxDesgn,
FIBDatabase, pFIBDatabase, ComCtrls, cxProgressBar;
type
TfrmCalc = class(TForm)
OkButton: TcxButton;
CancelButton: TcxButton;
cxGroupBox1: TcxGroupBox;
StatusBar1: TStatusBar;
Database: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
frxDesigner1: TfrxDesigner;
pFIBDataSet: TpFIBDataSet;
frxDBDataset1: TfrxDBDataset;
pFIBStoredProc: TpFIBStoredProc;
pFIBDataSet3: TpFIBDataSet;
ActionList1: TActionList;
Action1: TAction;
frxRTFExport1: TfrxRTFExport;
frxHTMLExport1: TfrxHTMLExport;
frxXLSExport1: TfrxXLSExport;
frxPDFExport1: TfrxPDFExport;
cxDateEdit: TcxDateEdit;
cxLabelDate: TcxLabel;
pFIBStoredProcFinal: TpFIBStoredProc;
ProgressBar: TcxProgressBar;
frxReport: TfrxReport;
procedure CancelButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure Action1Execute(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure frxReportPrintReport(Sender: TObject);
private
PLanguageIndex: byte;
DM:TDM_Calc;
ID_DOG: int64;
ID_STUD: int64;
ID_DOG_ROOT: int64;
NUM_DOG : string;
count_print: byte;
procedure FormIniLanguage;
public
constructor Create(AParameter:TcnSimpleParamsEx);reintroduce;
end;
var
count_print:Integer;
ID_TRANSACTION:Variant;
designer_rep:Integer;
implementation
{$R *.dfm}
constructor TfrmCalc.Create(AParameter:TcnSimpleParamsEx);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AParameter.Owner);
count_print := 0;
DM:=TDM_Calc.Create(Self);
DM.ReadDataSet.SQLs.SelectSQL.Text := 'select * from sys_options'; // просто чтобы убить транзакцию галимую
DM.DB.Handle:=AParameter.Db_Handle;
DM.ReadDataSet.Open;
DM.ReadDataSet.Close;
Database.Handle:=DM.DB.Handle;
ID_DOG_ROOT := AParameter.cnParamsToPakage.ID_DOG_ROOT;
ID_DOG := AParameter.cnParamsToPakage.ID_DOG;
ID_STUD := AParameter.cnParamsToPakage.ID_STUD;
NUM_DOG := AParameter.cnParamsToPakage.Num_Doc;
Screen.Cursor:=crDefault;
FormIniLanguage();
end;
procedure TfrmCalc.FormIniLanguage;
begin
PLanguageIndex:= cn_Common_Funcs.cnLanguageIndex();
caption := cnConsts.fr_Reports_PrintSpravkaCalc[PLanguageIndex];
cxLabelDate.Caption:= cnConsts.fr_Reports_CALC_NameREP0[PLanguageIndex];
OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex];
CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex];
end;
procedure TfrmCalc.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmCalc.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
dm.free;
end;
procedure TfrmCalc.FormCreate(Sender: TObject);
begin
cxDateEdit.Date:=Date;
count_print:=0;
designer_rep:=0;
end;
procedure TfrmCalc.Action1Execute(Sender: TObject);
begin
if designer_rep=0 then
begin
designer_rep:=1;
StatusBar1.Panels[0].Text:='Режим отладки отчетов';
end
else
begin
designer_rep:=0;
StatusBar1.Panels[0].Text:='';
end;
end;
procedure TfrmCalc.OkButtonClick(Sender: TObject);
var
numberDoc,ORG,OTD:String;
// dateopl:TDate;
// summa:Variant;
id_session_pay, id_session_calc : int64;
CN_SNEED, CNUPLSUM, DOLG_FINAL : Currency;
CNDATEOPL : TDate;
begin
Screen.Cursor := crHourGlass;
ProgressBar.Position := 1;
ProgressBar.Update;
if (ID_TRANSACTION>0) then
begin
pFIBStoredProc.Database:=Database;
pFIBStoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
pFIBStoredProc.StoredProcName:='CN_TMP_PRINT_CN_CALC_DELETE';
pFIBStoredProc.Prepare;
try
pFIBStoredProc.ExecProc;
except
begin
WriteTransaction.Rollback;
Exit;
end;
end;
WriteTransaction.Commit;
end;
ProgressBar.Position := 10;
ProgressBar.Update;
//получаем идентификатор транзакции
pFIBStoredProc.Database:=Database;
pFIBStoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
pFIBStoredProc.StoredProcName:='CN_FR_GET_ID_SESSION';
pFIBStoredProc.Prepare;
try
pFIBStoredProc.ExecProc;
ID_TRANSACTION:=pFIBStoredProc.FieldByName('ID_SESSION').AsVariant;
WriteTransaction.Commit;
except
begin
WriteTransaction.Rollback;
Exit;
end;
end;
ProgressBar.Position := 20;
ProgressBar.Update;
//отбор данных из базы
pFIBStoredProc.Database:=Database;
pFIBStoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
pFIBStoredProc.StoredProcName:='CN_PRINT_CN_CALC';
WriteTransaction.StartTransaction;
pFIBStoredProc.Prepare;
pFIBStoredProc.ParamByName('ID_STUD').AsInt64:=ID_STUD;
pFIBStoredProc.ParamByName('end_check').AsDate:=cxDateEdit.Date;
pFIBStoredProc.ParamByName('ID_SESSION').AsVariant:=ID_TRANSACTION;
try
pFIBStoredProc.ExecProc;
except
begin
WriteTransaction.Rollback;
Exit;
end;
end;
WriteTransaction.Commit;
with pFIBDataSet3 do
begin
Database:=Database;
Transaction:=ReadTransaction;
Active:=false;
SQLs.SelectSQL.Text:='SELECT FIO_PEOPLE AS FIO from CN_DT_STUDINFO_CALC_SELECT('+VarToStr(ID_STUD)+')';
Active:=true;
end;
ProgressBar.Position := 30;
ProgressBar.Update;
With pFIBStoredProc do
begin
try
StoredProcName:='CN_DT_NUMBER_SPAV_SELECT';
Database:=Database;
Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
Prepare;
ExecProc;
numberDoc:=FieldByName('NUMBER_SPRAV').AsString;
ORG:=FieldByName('OUT_MAIN_DEP').AsString;
OTD:=FieldByName('OUT_CHILD_DEP').AsString;
Transaction.Commit;
except
Transaction.Rollback;
raise;
end;
end;
//забор данных
with pFIBDataSet do
begin
Database:=Database;
Transaction:=ReadTransaction;
Active:=false;
ParamByName('param_id_transaction').AsVariant:=ID_TRANSACTION;
Active:=true;
FetchAll;
end;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Contracts\'+'PeoplePay'+'.fr3');
frxReport.Variables.Clear;
ProgressBar.Position := 50;
ProgressBar.Update;
// определяю общую уже уплаченную сумму
With pFIBStoredProcFinal do
begin
try
StoredProcName := 'CN_PAY';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_STUD').AsInt64 := ID_STUD;
ParamByName('DATE_PROV_CHECK').AsShort := 1;
ParamByName('IS_DOC_GEN').AsShort := 0;
ParamByName('IS_PROV_GEN').AsShort := 0;
ParamByName('IS_SMET_GEN').AsShort := 0;
ParamByName('NOFPROV').AsShort := 1;
ParamByName('DIGNORDOCID').AsShort := 1;
ExecProc;
frxReport.Variables['PLATIL_FINAL']:= '''' + VarToStr(ParamByName('CNUPLSUM').AsCurrency) +'''';
CNUPLSUM := ParamByName('CNUPLSUM').AsCurrency ;
id_session_pay:= ParamByName('ID_SESSION').AsInt64;
Transaction.Commit;
Close;
except
Transaction.Rollback;
raise;
end;
end;
ProgressBar.Position := 60;
ProgressBar.Update;
With pFIBStoredProcFinal do
begin
StoredProcName := 'CN_PAY_TMP_CLEAR';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_SESSION').AsInt64 := id_session_pay;
ExecProc;
Transaction.Commit;
Close;
end;
ProgressBar.Position := 70;
ProgressBar.Update;
// определяю общую сумму необх. для уплаты
With pFIBStoredProcFinal do
begin
try
StoredProcName := 'CN_CALC';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_STUD').AsInt64 := ID_STUD ;
ParamByName('BEG_CHECK').AsVariant := null;
ParamByName('END_CHECK').AsVariant := null;
ParamByName('CNUPLSUM').AsCurrency := CNUPLSUM;
ExecProc;
frxReport.Variables['NADO_FINAL']:= '''' + VarToStr(ParamByName('CN_SNEED').AsCurrency) +'''';
CN_SNEED:= ParamByName('CN_SNEED').AsCurrency;
CNDATEOPL := ParamByName('CNDATEOPL').AsDate;
id_session_calc:= ParamByName('ID_SESSION').AsInt64;
Transaction.Commit;
Close;
except
Transaction.Rollback;
raise;
end;
end;
ProgressBar.Position := 80;
ProgressBar.Update;
With pFIBStoredProcFinal do
begin
StoredProcName := 'CN_CALC_TMP_CLEAR';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_SESSION').AsInt64 := id_session_calc;
ExecProc;
Transaction.Commit;
Close;
end;
ProgressBar.Position := 90;
ProgressBar.Update;
DOLG_FINAL := CN_SNEED - CNUPLSUM;
frxReport.Variables['DOLG_FINAL']:= ''''+ VarToStr(DOLG_FINAL) +'''';
frxReport.Variables['CNDATEOPL_cap']:= ''''+ cnConsts.cn_PayPo_Pay[1]+'''';
frxReport.Variables['CNDATEOPL']:= ''''+ datetostr(CNDATEOPL) +'''';
frxReport.Variables['NAMEREP0']:= ''''+ cnConsts.fr_Reports_CALC_NameREP0[1]+'''';
frxReport.Variables['NAMEREP']:= ''''+ cnConsts.fr_Reports_CALC_NameREP[1]+'''';
frxReport.Variables['NAMEREP1']:= ''''+ cnConsts.fr_Reports_CALC_NameREP1[1]+'''';
frxReport.Variables['NAMEREP2']:= ''''+ cnConsts.fr_Reports_CALC_NameREP2[1]+'''';
frxReport.Variables['OBUCHAEMIY']:= ''''+ cnConsts.fr_Reports_CALC_NameStuder[1]+'''';
frxReport.Variables['BEGDATE']:= ''''+ cnConsts.fr_Reports_CALC_Beg[1]+'''';
frxReport.Variables['ENDDATE']:= ''''+ cnConsts.fr_Reports_CALC_End[1]+'''';
frxReport.Variables['BEGDATE']:= ''''+ cnConsts.fr_Reports_CALC_Beg[1]+'''';
frxReport.Variables['ENDDATE']:= ''''+ cnConsts.fr_Reports_CALC_End[1]+'''';
frxReport.Variables['STOIMOTS']:= ''''+ cnConsts.fr_Reports_CALC_Stoimost[1]+'''';
frxReport.Variables['SUMMA_LG']:= ''''+ cnConsts.fr_Reports_CALC_SummaLg[1]+'''';
frxReport.Variables['PERCENT_LG']:= ''''+ cnConsts.fr_Reports_CALC_PersentLg[1]+'''';
frxReport.Variables['BEG_DOLG']:= ''''+ cnConsts.fr_Reports_CALC_DolgBeg[1]+'''';
frxReport.Variables['ALLPERIOD']:= ''''+ cnConsts.fr_Reports_CALC_AllPeriod[1]+'''';
frxReport.Variables['SUMPAY']:= ''''+ cnConsts.fr_Reports_CALC_SumPay[1]+'''';
frxReport.Variables['SUMDOLG']:= ''''+ cnConsts.fr_Reports_CALC_DolgEnd[1]+'''';
frxReport.Variables['PAYCONF1']:= ''''+ cnConsts.fr_Reports_CALC_PayConf[1]+'''';
frxReport.Variables['PAYCONF2']:= ''''+ cnConsts.fr_Reports_CALC_PayConf1[1]+'''';
frxReport.Variables['BUHG']:= ''''+ cnConsts.fr_Reports_CALC_Buhg[1]+'''';
frxReport.Variables['ORG']:= ''''+ORG+'''';
frxReport.Variables['FIO']:= ''''+StringPrepareToQueryText(pFIBDataSet3.FieldByName('FIO').AsString)+'''';
frxReport.Variables['NUMBER']:= ''''+numberDoc+'''';
frxReport.Variables['SUMOPL']:=''''+VarToStr(0)+'''';
frxReport.Variables['REC']:=''''+VarToStr(pFIBDataSet.RecordCount)+'''';
frxReport.Variables['SP_VIDANA']:= ''''+cnConsts.fr_Reports_CALC_KydaVidana[1]+'''';
frxReport.Variables['VSEGO']:= ''''+cnConsts.fr_Reports_CALC_All[1]+'''';
frxReport.Variables['SUMMA_K_OPLATE']:= '''' + cnConsts.fr_Reports_SUMMA_K_OPLATE[1] + '''';
frxReport.Variables['UGE_OPLACHENO']:= '''' + cnConsts.fr_Reports_UGE_OPLACHENO[1] + '''';
frxReport.Variables['SUMMA_DOLGA']:= '''' + cnConsts.fr_Reports_SUMMA_DOLGA[1] + '''';
frxReport.Variables['NUM_DOG']:='''' + NUM_DOG +'''';
pFIBDataSet.Last;
frxReport.Variables['SUM_DOLG_FINAL']:= '''' + VarToStr(pFIBDataSet['DOLG_KONEZ']) +'''';
ProgressBar.Position := 100;
Screen.Cursor := crDefault;
frxReport.PrepareReport(true);
frxReport.ShowReport;
if designer_rep=1 then
begin
frxReport.DesignReport;
end;
pFIBDataSet.Close;
pFIBDataSet3.Close;
//удаление из БД
pFIBStoredProc.Database:=Database;
pFIBStoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
pFIBStoredProc.StoredProcName:='CN_TMP_PRINT_CN_CALC_DELETE';
pFIBStoredProc.Prepare;
pFIBStoredProc.ParamByName('ID_SESSION').AsInt64:=ID_TRANSACTION;
try
pFIBStoredProc.ExecProc;
except
begin
WriteTransaction.Rollback;
Exit;
end;
end;
WriteTransaction.Commit;
end;
procedure TfrmCalc.frxReportPrintReport(Sender: TObject);
var
numberDoc:String;
begin
if count_print=0 then
begin
With pFIBStoredProc do
begin
try
StoredProcName:='CN_DT_NUMBER_SPAV_UPDATE';
Database:=Database;
Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
Prepare;
ExecProc;
numberDoc:=FieldByName('NUMBER_SPRAV').AsString;
Transaction.Commit;
except
Transaction.Rollback;
raise;
end;
end;
frxReport.Variables['NUMBER']:= ''''+'№'+numberDoc+'''';
frxReport.PrepareReport;
inc(count_print);
end;
end;
end.
|
unit ProdutoOperacaoImportar.Controller;
interface
uses Produto.Controller.interf, Produto.Model.interf, System.SysUtils,
TESTPRODUTO.Entidade.Model;
type
TProdutoOperacaoImportarController = class(TInterfacedObject,
IProdutoOperacaoImportarController)
private
FProdutoController: IProdutoController;
FProdutoModel: IProdutoModel;
FProdutoExiste: Boolean;
FRegistro: TTESTPRODUTO;
FCodigoSinapi: Integer;
FDescricao: string;
FUnidMedida: string;
FOrigemPreco: string;
FPrMedioSinapi: Currency;
public
constructor Create;
destructor Destroy; override;
class function New: IProdutoOperacaoImportarController;
function produtoController(AValue: IProdutoController)
: IProdutoOperacaoImportarController;
function produtoModel(AValue: IProdutoModel)
: IProdutoOperacaoImportarController;
function produtoSelecionado(AValue: TTESTPRODUTO)
: IProdutoOperacaoImportarController;
function codigoSinapi(AValue: Integer)
: IProdutoOperacaoImportarController; overload;
function codigoSinapi(AValue: string)
: IProdutoOperacaoImportarController; overload;
function descricao(AValue: string)
: IProdutoOperacaoImportarController; overload;
function unidMedida(AValue: string)
: IProdutoOperacaoImportarController; overload;
function origemPreco(AValue: string)
: IProdutoOperacaoImportarController; overload;
function prMedioSinapi(AValue: Currency)
: IProdutoOperacaoImportarController; overload;
function prMedioSinapi(AValue: string)
: IProdutoOperacaoImportarController; overload;
function &executar: IProdutoController;
end;
implementation
{ TProdutoOperacaoImportarController }
function TProdutoOperacaoImportarController.codigoSinapi(AValue: Integer)
: IProdutoOperacaoImportarController;
begin
Result := Self;
FCodigoSinapi := AValue;
end;
function TProdutoOperacaoImportarController.codigoSinapi(AValue: string)
: IProdutoOperacaoImportarController;
begin
Result := Self;
FCodigoSinapi := StrToInt(AValue);
end;
constructor TProdutoOperacaoImportarController.Create;
begin
end;
function TProdutoOperacaoImportarController.descricao(AValue: string)
: IProdutoOperacaoImportarController;
begin
Result := Self;
FDescricao := AValue;
end;
destructor TProdutoOperacaoImportarController.Destroy;
begin
inherited;
end;
function TProdutoOperacaoImportarController.executar: IProdutoController;
begin
if FProdutoExiste then
begin
raise Exception.Create(FRegistro.CODIGO);
end;
FRegistro.Free;
Self.Free;
end;
class function TProdutoOperacaoImportarController.New
: IProdutoOperacaoImportarController;
begin
Result := Self.Create;
end;
function TProdutoOperacaoImportarController.origemPreco(AValue: string)
: IProdutoOperacaoImportarController;
begin
Result := Self;
FOrigemPreco := AValue;
end;
function TProdutoOperacaoImportarController.prMedioSinapi(AValue: string)
: IProdutoOperacaoImportarController;
begin
Result := Self;
FPrMedioSinapi := StrToCurr(AValue);
end;
function TProdutoOperacaoImportarController.prMedioSinapi(AValue: Currency)
: IProdutoOperacaoImportarController;
begin
Result := Self;
FPrMedioSinapi := AValue;
end;
function TProdutoOperacaoImportarController.produtoController
(AValue: IProdutoController): IProdutoOperacaoImportarController;
begin
Result := Self;
FProdutoController := AValue;
end;
function TProdutoOperacaoImportarController.produtoModel(AValue: IProdutoModel)
: IProdutoOperacaoImportarController;
begin
Result := Self;
FProdutoModel := AValue;
end;
function TProdutoOperacaoImportarController.produtoSelecionado
(AValue: TTESTPRODUTO): IProdutoOperacaoImportarController;
begin
Result := Self;
FRegistro := AValue;
FProdutoExiste := not(AValue = nil);
end;
function TProdutoOperacaoImportarController.unidMedida(AValue: string)
: IProdutoOperacaoImportarController;
begin
Result := Self;
FUnidMedida := AValue;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Added a toolbar to Delphi IDE.
}
unit VXS.SceneToolbar;
interface
implementation
uses
System.Classes,
System.SysUtils,
FMX.Graphics,
FMX.ImgList,
FMX.Controls,
FMX.ComCtrls,
FMX.ExtCtrls,
FMX.ActnList,
ToolsAPI,
VXS.Scene,
VXS.Generics;
const
cVXSceneViewerToolbar = 'VXSceneViewerToolbar';
type
TVXSToolButtonReceiver = class
protected
FActionList: GList<TBasicAction>;
procedure OnClick(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
end;
var
vReciver: TVXSToolButtonReceiver;
function MsgServices: IOTAMessageServices;
begin
Result := (BorlandIDEServices as IOTAMessageServices);
Assert(Result <> nil, 'IOTAMessageServices not available');
end;
procedure AddGLSceneToolbar;
var
Services: INTAServices;
T: Integer;
GLToolbar: TToolBar;
procedure AddButton(const AHint, AResName: string);
var
Bmp: TBitmap;
Act: TAction;
begin
Act := TAction.Create(nil);
Act.ActionList := Services.ActionList;
vReciver.FActionList.Add(Act);
Bmp := TBitmap.Create;
Bmp.LoadFromResourceName(HInstance, AResName);
Act.ImageIndex := Services.AddMasked(Bmp, Bmp.TransparentColor, 'GLScene.' + AResName);
Bmp.Destroy;
Act.Hint := AHint;
Act.Tag := T;
Act.OnExecute := vReciver.OnClick;
with Services.AddToolButton(cVXSceneViewerToolbar, 'GLSButton' + IntToStr(T), Act) do
Action := Act;
Act.Enabled := True;
Inc(T);
end;
begin
if not Supports(BorlandIDEServices, INTAServices, Services) then
exit;
GLToolbar := Services.ToolBar[cVXSceneViewerToolbar];
vReciver := TVXSToolButtonReceiver.Create;
T := 0;
if not Assigned(GLToolbar) then
begin
GLToolbar := Services.NewToolbar(cVXSceneViewerToolbar, 'VXScene Viewer Control');
if Assigned(GLToolbar) then
with GLToolbar do
begin
AddButton('VXSceneViewer default control mode', 'VXSceneViewerControlToolbarDefault');
AddButton('VXSceneViewer navigation mode', 'VXSceneViewerControlToolbarNavigation');
AddButton('VXSceneViewer gizmo mode', 'VXSceneViewerControlToolbarGizmo');
AddButton('Reset view to VXSceneViewer camera', 'VXSceneViewerControlToolbarCameraReset');
Visible := True;
end;
MsgServices.AddTitleMessage('VXScene Toolbar created');
end
else
begin
for T := 0 to GLToolbar.ButtonCount - 1 do
begin
GLToolbar.Buttons[T].Action.OnExecute := vReciver.OnClick;
vReciver.FActionList.Add(GLToolbar.Buttons[T].Action);
end;
MsgServices.AddTitleMessage('VXScene Toolbar activated');
end;
Services.ToolbarModified(GLToolbar);
end;
constructor TVXSToolButtonReceiver.Create;
begin
FActionList := GList<TBasicAction>.Create;
vVXSceneViewerMode := svmDefault;
end;
destructor TVXSToolButtonReceiver.Destroy;
var
I: Integer;
begin
for I := 0 to FActionList.Count - 1 do
FActionList[I].OnExecute := nil;
FActionList.Destroy;
vVXSceneViewerMode := svmDisabled;
end;
procedure TVXSToolButtonReceiver.OnClick(Sender: TObject);
const
cMode: array [TVXSceneViewerMode] of string = ('', 'default', 'navigation', 'gizmo');
var
T: Integer;
begin
inherited;
T := TComponent(Sender).Tag;
if T < 3 then
begin
vVXSceneViewerMode := TVXSceneViewerMode(T+1);
MsgServices.AddTitleMessage(Format('VXSceneViewer %s mode', [cMode[vVXSceneViewerMode]]));
end
else
vResetDesignView := True;
end;
initialization
AddGLSceneToolbar;
finalization
vReciver.Free;
end.
|
unit myutils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LCLIntf, GR32, GR32_Image, Graphics;
{绘制渐变色,全局背景}
procedure MyGradientBackground(AStart,AEnd:TColor;ABitmap:TBitmap32;AHeight,AWidth:integer;ASteps:integer=100);//绘制垂直渐变色
procedure MyGradientBackGroundH(AStart,AEnd:TColor;ABitmap:TBitmap32;AHeight,AWidth:integer;ASteps:integer=100);//绘制水平渐变色
{部分区域背景}
procedure MyGradientArea(AStart,AEnd:TColor;ABitmap:TBitmap32;ATop,ALeft,AHeight,AWidth:integer;ASteps:integer=100);//绘制垂直渐变色
procedure MyGradientAreaH(AStart,AEnd:TColor;ABitmap:TBitmap32;ATop,ALeft,AHeight,AWidth:integer;ASteps:integer=100);//绘制垂直渐变色
{处理坐标轴标签}
function SmartLabel(AValue:Extended;ADec:integer):string;overload;
function SmartLabel(AValue:int64):string;overload;
function GetFormatStr(ADec:integer):string;
{整数值转换为时分字符串}
function IntTimeToStr(AValue:integer):string;
procedure DrawString(ABitmap:TBitmap32;AX,AY:integer;AString:string;AFontName:ShortString;AFontColor:TColor;AFontStyle:TFontStyles;AFontSize:integer;AlignLeft:boolean=True);
implementation
procedure DrawString(ABitmap:TBitmap32;AX,AY:integer;AString:string;AFontName:ShortString;AFontColor:TColor;AFontStyle:TFontStyles;AFontSize:integer;AlignLeft:boolean=True);
begin
ABitmap.Font.Name:=AFontName;
ABitmap.Font.Style:=AFontStyle;
ABitmap.Font.Size:=AFontSize;
ABitmap.Font.Color:=AFontColor;
if AlignLeft then
ABitmap.Textout(AX,AY,AString)
else
ABitmap.Textout(AX-ABitmap.TextWidth(AString),AY,AString);
end;
procedure MyGradientBackground(AStart, AEnd: TColor; ABitmap: TBitmap32;AHeight,AWidth:integer;ASteps:integer=100);
var
i:integer;
J,K:Real;
Deltas: array [0..2] of Real;
R:TRect;
LStartRGB, lEndRGB:TColor;
LSteps:Word;
BufferWidth,BufferHeight:integer;
begin
LSteps:=ASteps;
LStartRGB:=ColorToRGB(AStart);
LEndRGB:=ColorToRGB(AEnd);
BufferWidth:=AWidth;
BufferHeight:=AHeight;
if LSteps>BufferHeight then
LSteps:=BufferHeight;
if LSteps<1 then
LSteps:=1;
Deltas[0]:=(GetRValue(LEndRGB)-GetRValue(LStartRGB))/LSteps;
Deltas[1]:=(GetGValue(LEndRGB)-GetGValue(LStartRGB))/LSteps;
Deltas[2]:=(GetBValue(LEndRGB)-GetBValue(LStartRGB))/LSteps;
ABitmap.Canvas.Brush.Style:=bsSolid;
J:=BufferHeight/LSteps;
for i:=0 to LSteps do
begin
R.Left:=BufferWidth;
R.Right:=0;
R.Top:=Round(I*J);
R.Bottom:=Round((i+1)*j);
ABitmap.Canvas.Brush.Color:=RGB(
Round(GetRValue(LStartRGB)+i*Deltas[0]),
Round(GetGValue(LStartRGB)+i*Deltas[1]),
Round(GetBValue(LStartRGB)+i*Deltas[2])
);
ABitmap.Canvas.FillRect(R);
end;
end;
procedure MyGradientBackGroundH(AStart, AEnd: TColor; ABitmap: TBitmap32;
AHeight, AWidth: integer; ASteps: integer);
var
i:integer;
J,K:Real;
Deltas: array [0..2] of Real;
R:TRect;
LStartRGB, lEndRGB:TColor;
LSteps:Word;
BufferWidth,BufferHeight:integer;
begin
LSteps:=ASteps;
LStartRGB:=ColorToRGB(AStart);
LEndRGB:=ColorToRGB(AEnd);
BufferWidth:=AWidth;
BufferHeight:=AHeight;
if LSteps>BufferWidth then
LSteps:=BufferWidth;
if LSteps<1 then
LSteps:=1;
Deltas[0]:=(GetRValue(LEndRGB)-GetRValue(LStartRGB))/LSteps;
Deltas[1]:=(GetGValue(LEndRGB)-GetGValue(LStartRGB))/LSteps;
Deltas[2]:=(GetBValue(LEndRGB)-GetBValue(LStartRGB))/LSteps;
ABitmap.Canvas.Brush.Style:=bsSolid;
J:=BufferWidth/LSteps;
for i:=0 to LSteps do
begin
R.Left:=Round(i*j);
R.Right:=Round((i+1)*j);
R.Top:=0;
R.Bottom:=BufferHeight;
ABitmap.Canvas.Brush.Color:=RGB(
Round(GetRValue(LStartRGB)+i*Deltas[0]),
Round(GetGValue(LStartRGB)+i*Deltas[1]),
Round(GetBValue(LStartRGB)+i*Deltas[2])
);
ABitmap.Canvas.FillRect(R);
end;
end;
procedure MyGradientArea(AStart, AEnd: TColor; ABitmap: TBitmap32; ATop, ALeft,
AHeight, AWidth: integer; ASteps: integer);
var
i:integer;
J,K:Real;
Deltas: array [0..2] of Real;
R:TRect;
LStartRGB, lEndRGB:TColor;
LSteps:Word;
BufferWidth,BufferHeight:integer;
begin
LSteps:=ASteps;
LStartRGB:=ColorToRGB(AStart);
LEndRGB:=ColorToRGB(AEnd);
BufferWidth:=AWidth;
BufferHeight:=AHeight;
if LSteps>BufferHeight then
LSteps:=BufferHeight;
if LSteps<1 then
LSteps:=1;
Deltas[0]:=(GetRValue(LEndRGB)-GetRValue(LStartRGB))/LSteps;
Deltas[1]:=(GetGValue(LEndRGB)-GetGValue(LStartRGB))/LSteps;
Deltas[2]:=(GetBValue(LEndRGB)-GetBValue(LStartRGB))/LSteps;
ABitmap.Canvas.Brush.Style:=bsSolid;
J:=BufferHeight/LSteps;
for i:=0 to LSteps do
begin
R.Left:=ALeft+BufferWidth;
R.Right:=ALeft;
R.Top:=ATop+Round(I*J);
R.Bottom:=ATop+Round((i+1)*j);
ABitmap.Canvas.Brush.Color:=RGB(
Round(GetRValue(LStartRGB)+i*Deltas[0]),
Round(GetGValue(LStartRGB)+i*Deltas[1]),
Round(GetBValue(LStartRGB)+i*Deltas[2])
);
ABitmap.Canvas.FillRect(R);
end;
end;
procedure MyGradientAreaH(AStart, AEnd: TColor; ABitmap: TBitmap32; ATop,
ALeft, AHeight, AWidth: integer; ASteps: integer);
var
i:integer;
J,K:Real;
Deltas: array [0..2] of Real;
R:TRect;
LStartRGB, lEndRGB:TColor;
LSteps:Word;
BufferWidth,BufferHeight:integer;
begin
LSteps:=ASteps;
LStartRGB:=ColorToRGB(AStart);
LEndRGB:=ColorToRGB(AEnd);
BufferWidth:=AWidth;
BufferHeight:=AHeight;
if LSteps>BufferWidth then
LSteps:=BufferWidth;
if LSteps<1 then
LSteps:=1;
Deltas[0]:=(GetRValue(LEndRGB)-GetRValue(LStartRGB))/LSteps;
Deltas[1]:=(GetGValue(LEndRGB)-GetGValue(LStartRGB))/LSteps;
Deltas[2]:=(GetBValue(LEndRGB)-GetBValue(LStartRGB))/LSteps;
ABitmap.Canvas.Brush.Style:=bsSolid;
J:=BufferWidth/LSteps;
for i:=0 to LSteps-1 do
begin
R.Left:=ALeft+Round(i*j);
R.Right:=ALeft+Round((i+1)*j);
R.Top:=ATop;
R.Bottom:=ATop+BufferHeight;
ABitmap.Canvas.Brush.Color:=RGB(
Round(GetRValue(LStartRGB)+i*Deltas[0]),
Round(GetGValue(LStartRGB)+i*Deltas[1]),
Round(GetBValue(LStartRGB)+i*Deltas[2])
);
ABitmap.Canvas.FillRect(R);
end;
end;
function SmartLabel(AValue:Extended;ADec:integer):string;
var
mValue:Extended;
mFix:string;
begin
if AValue>=1000000 then
begin
mValue:=AValue/1000000;
mFix:='M';
end
else
if AValue>=1000 then
begin
mValue:=AValue/1000;
mFix:='K';
end
else
begin
mValue:=AValue;
mFix:='';
end;
result:=FormatFloat(GetFormatStr(ADec),mValue)+mFix;
end;
function SmartLabel(AValue:int64):string;
begin
if AValue>=1000 then
result:=SmartLabel(AValue,0)
else
result:=inttostr(AValue);
end;
function GetFormatStr(ADec:integer):string;
var
i:integer;
begin
result:='#0.';
for i:=1 to ADec do
begin
result:=result+'0';
end;
end;
function IntTimeToStr(AValue: integer): string;
var
mH,mM,mS:integer;
begin
mH:=AValue div 10000;
mM:=(AValue mod 10000) div 100;
mS:=(AValue mod 10000) mod 100;
Result:=inttostr(mH)+':'+Format('%.2d:%.2d',[mM,mS]);
end;
end.
|
unit StyleClassProperty;
interface
uses
SysUtils, Classes, Controls,
dcedit, dcfdes, dcsystem, dcdsgnstuff,
ThStyleSheet, ThAnchorStyles;
type
TStyleClassProperty = class(TStringProperty)
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
procedure RegisterStyleClassProperty;
implementation
procedure RegisterStyleClassProperty;
begin
RegisterPropertyEditor(TypeInfo(string), nil, 'StyleClass',
TStyleClassProperty);
RegisterPropertyEditor(TypeInfo(string), TThAnchorStyles, '',
TStyleClassProperty);
end;
{ TStyleClassProperty }
function TStyleClassProperty.GetAttributes: TPropertyAttributes;
begin
Result := [ paMultiSelect, paValueList, paSortList, paRevertable ];
end;
procedure TStyleClassProperty.GetValues(Proc: TGetStrProc);
var
s: TThStyleSheet;
i: Integer;
begin
{$ifdef VER130}
s := ThFindStyleSheet(TControl(Designer.GetRoot));
{$else}
s := ThFindStyleSheet(TControl(Designer.Root));
{$endif}
if (s <> nil) then
for i := 0 to s.Styles.Count - 1 do
Proc(s.Styles.StyleItem[i].Name);
end;
end.
|
unit Main;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, SDUSystemTrayIcon, Menus, ActnList;
type
TForm1 = class(TForm)
SDUSystemTrayIcon1: TSDUSystemTrayIcon;
PopupMenu1: TPopupMenu;
miDisplay: TMenuItem;
miExit: TMenuItem;
pbExit: TButton;
ActionList1: TActionList;
actExit: TAction;
actDisplay: TAction;
GroupBox1: TGroupBox;
pbAppMinimise: TButton;
pbClose: TButton;
pbWSMinimise: TButton;
pbHide: TButton;
GroupBox2: TGroupBox;
ckDisplaySystemTrayIconIcon: TCheckBox;
ckCloseToIcon: TCheckBox;
ckMinToIcon: TCheckBox;
GroupBox3: TGroupBox;
pbChildModal: TButton;
pbChildNonModal: TButton;
procedure UpdateSystemTrayIconSettings(Sender: TObject);
procedure pbCloseClick(Sender: TObject);
procedure pbAppMinimiseClick(Sender: TObject);
procedure actExitExecute(Sender: TObject);
procedure actDisplayExecute(Sender: TObject);
procedure pbWSMinimiseClick(Sender: TObject);
procedure pbHideClick(Sender: TObject);
procedure pbChildNonModalClick(Sender: TObject);
procedure pbChildModalClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCreate(Sender: TObject);
private
// Flag to indicate that the login session is about to end
EndSessionFlag: boolean;
procedure WMEndSession(var msg: TWMEndSession); message WM_ENDSESSION;
procedure WMQueryEndSession(var msg: TWMQueryEndSession); message WM_QUERYENDSESSION;
public
procedure AppMin(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
uses
{$IFDEF GEXPERTS}
DbugIntf,
{$ELSE}
SDULogger_U,
{$ENDIF}
SDUGeneral,
SecondForm;
{$IFNDEF GEXPERTS}
{$IFDEF SDUSystemTrayIcon_DEBUG}
procedure SendDebug(x: string);
var
logObj: TSDULogger;
begin
logObj:= TSDULogger.Create('C:\SDUSystemTrayIconDebug.txt');
try
logObj.LogMessage(x);
finally
logObj.Free();
end;
end;
{$ELSE}
procedure SendDebug(x: string);
begin
// Do nothing
end;
{$ENDIF}
{$ENDIF}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
// Functions required for close/minimize to SystemTrayIcon follow
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
// Function required for close to system tray icon
procedure TForm1.WMQueryEndSession(var msg: TWMQueryEndSession);
begin
SendDebug('MAIN APP WMQueryEndSession');
// Default to allowing shutdown
msg.Result := 1;
EndSessionFlag := (msg.Result = 1);
SendDebug('MAIN APP WMQueryEndSession');
inherited;
EndSessionFlag := (msg.Result = 1);
end;
// Function required for close to system tray icon
procedure TForm1.WMEndSession(var msg: TWMEndSession);
begin
SendDebug('MAIN APP WMEndSession');
EndSessionFlag := msg.EndSession;
end;
// Function required for close to system tray icon
procedure TForm1.FormCreate(Sender: TObject);
begin
EndSessionFlag := FALSE;
// This next lines are *NOT* needed - only used for the test app
self.Caption := Application.Title;
UpdateSystemTrayIconSettings(nil);
Application.OnMinimize := AppMin;
end;
// Function required for close to system tray icon
// Note: This is *only* required in your application is you intend to call
// Close() to hide/close the window. Calling Hide() instead is preferable
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
SendDebug('FormClose');
// This code segment is required to handle the case when Close() is called
// programatically
// Only carry out this action if closing to SystemTrayIcon
// Note the MainForm test; if it was the main form, setting Action would have
// no effect
if (
not(EndSessionFlag) and
SDUSystemTrayIcon1.Active and
ckCloseToIcon.checked and
{$IF CompilerVersion >= 18.5}
(
// If Application.MainFormOnTaskbar is set, use the form name,
// otherwise check exactly
(
Application.MainFormOnTaskbar and
(application.mainform <> nil) and
(application.mainform.name = self.name)
) or
(
not(Application.MainFormOnTaskbar) and
(application.mainform <> self)
)
)
{$ELSE}
(Application.MainForm <> self)
{$ENDIF}
) then
begin
SendDebug('Setting FormClose Action');
Action := caMinimize;
end;
end;
// Function required for close to system tray icon
// Note: This is *only* required in your application is you intend to call
// Close() to hide/close the window. Calling Hide() instead is preferable
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
SendDebug('FormCloseQuery');
// This code segment is required to handle the case when Close() is called
// programatically
// Only carry out this action if closing to SystemTrayIcon
// Note the MainForm test; if it was not the main form, setting Action would
// in FormClose would do the minimise
SendDebug('FormCloseQuery SDUSystemTrayIcon1.Active: '+booltostr(SDUSystemTrayIcon1.Active));
if (
not(EndSessionFlag) and
SDUSystemTrayIcon1.Active and
ckCloseToIcon.checked and
{$IF CompilerVersion >= 18.5}
(
// If Application.MainFormOnTaskbar is set, use the form name,
// otherwise check exactly
(
Application.MainFormOnTaskbar and
(application.mainform <> nil) and
(application.mainform.name = self.name)
) or
(
not(Application.MainFormOnTaskbar) and
(application.mainform = self)
)
)
{$ELSE}
(Application.MainForm = self)
{$ENDIF}
) then
begin
SendDebug('FormCloseQuery setting CanClose to FALSE; minimizing to SystemTrayIcon');
CanClose := FALSE;
SDUSystemTrayIcon1.DoMinimizeToIcon();
end;
end;
// Function required for both close and minimize to system tray icon
// Procedure to display the form after minimize/close
procedure TForm1.actDisplayExecute(Sender: TObject);
begin
SendDebug('actDisplayExecute');
SDUSystemTrayIcon1.DoRestore();
end;
// Function required for both close and minimize to system tray icon
procedure TForm1.actExitExecute(Sender: TObject);
begin
// Either:
// Application.Terminate();
// Or:
SDUSystemTrayIcon1.Active := FALSE;
Close();
end;
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
// Test functions follow
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
procedure TForm1.UpdateSystemTrayIconSettings(Sender: TObject);
begin
SDUSystemTrayIcon1.Active := ckDisplaySystemTrayIconIcon.checked;
SDUSystemTrayIcon1.MinimizeToIcon := ckMinToIcon.checked;
end;
procedure TForm1.pbChildNonModalClick(Sender: TObject);
var
dlg: TForm2;
begin
dlg:= TForm2.Create(nil);
try
dlg.Show();
finally
// Note: We don't free dlg - we just leave it non-modal
end;
end;
procedure TForm1.pbChildModalClick(Sender: TObject);
var
dlg: TForm2;
begin
dlg:= TForm2.Create(nil);
try
dlg.ShowModal();
finally
dlg.Free()
end;
end;
procedure TForm1.pbAppMinimiseClick(Sender: TObject);
begin
Application.Minimize();
end;
procedure TForm1.pbWSMinimiseClick(Sender: TObject);
begin
WindowState := wsminimized;
end;
procedure TForm1.pbHideClick(Sender: TObject);
begin
Hide();
end;
procedure TForm1.pbCloseClick(Sender: TObject);
begin
Close();
end;
procedure TForm1.AppMin(Sender: TObject);
begin
SendDebug('AppMin called');
end;
END.
|
{$UNDEF ITEM_REF_IS_PTR}
{$DEFINE ITEM_FREE_FUNC}
{$UNDEF CMP_FUNC}
{$DEFINE VECTOR_ENABLE_MOVE}
unit ObjVec;
interface
type
TItem = TObject;
{$INCLUDE Vector.inc}
IBaseObjectVector = IBaseVector;
TBaseObjectVector = class(TBaseVector)
private
FIsOwner: Boolean;
public
constructor Create(AIsOwner: Boolean = True);
function GetIsOwner: Boolean;
procedure SetIsOwner(Value: Boolean);
property IsOwner: Boolean read GetIsOwner write SetIsOwner;
end;
IObjectVector = interface(IBaseObjectVector)
function GetAt(I: Integer): TObject;
procedure SetAt(I: Integer; const Item: TObject);
function Peek: TObject;
function GetIsOwner: Boolean;
procedure SetIsOwner(Value: Boolean);
property Items[I: Integer]: TObject read GetAt write SetAt; default;
property IsOwner: Boolean read GetIsOwner write SetIsOwner;
end;
TObjectVector = class(TBaseObjectVector, IObjectVector)
public
function GetAt(I: Integer): TObject;
procedure SetAt(I: Integer; const Item: TObject);
function Peek: TObject;
property Items[I: Integer]: TObject read GetAt write SetAt; default;
end;
implementation
{$DEFINE IMPL}
uses
SysUtils, GUtils;
procedure ItemFree(var Item: TItem; BaseVector: TBaseVector);
begin
if TBaseObjectVector(BaseVector).IsOwner then
FreeAndNil(Item);
end;
constructor TBaseObjectVector.Create(AIsOwner: Boolean = True);
begin
inherited Create;
FIsOwner := AIsOwner;
end;
function TBaseObjectVector.GetIsOwner: Boolean;
begin
Result := FIsOwner;
end;
procedure TBaseObjectVector.SetIsOwner(Value: Boolean);
begin
FIsOwner := Value;
end;
{$include Vector.inc}
function TObjectVector.GetAt(I: Integer): TObject;
begin
CheckIndex(I);
Result := FData[I];
end;
function TObjectVector.Peek: TObject;
begin
if Count <= 0 then
raise EVectorRangeError.CreateFmt(
'%s: Invalid Peek call. Vector is empty.', [Self.ClassName]);
Result := FData[Count - 1];
end;
procedure TObjectVector.SetAt(I: Integer; const Item: TObject);
begin
CheckIndex(I);
if (Item <> FData[I]) and IsOwner then
FreeAndNil(FData[I]);
FData[I] := Item;
end;
end.
|
unit MainSettings;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.FreeOTFE.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Classes, // Required for TShortCut
CommonSettings,
IniFiles,
OTFEFreeOTFEBase_U,
//sdu
sdugeneral;
const
{$IFDEF _NEVER_DEFINED}
// This is just a dummy const to fool dxGetText when extracting message
// information
// This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to
// picks up SDUGeneral.SDUCRLF
SDUCRLF = ''#13#10;
{$ENDIF}
FREEOTFE_REGISTRY_SETTINGS_LOCATION = '\Software\LibreCrypt';
// Command line parameter handled in the .dpr
CMDLINE_MINIMIZE = 'minimize';
resourcestring
RS_PROMPT_USER = 'Prompt user';
RS_DO_NOTHING = 'Do nothing';
type
eOnExitWhenMounted = (oewmDismount, oewmPromptUser, oewmLeaveMounted);
resourcestring
ONEXITWHENMOUNTED_DISMOUNT = 'Lock all containers';
ONEXITWHENMOUNTED_LEAVEMOUNTED = 'Leave containers open';
const
OnExitWhenMountedTitlePtr: array [eOnExitWhenMounted] of Pointer =
(@ONEXITWHENMOUNTED_DISMOUNT, @RS_PROMPT_USER, @ONEXITWHENMOUNTED_LEAVEMOUNTED
);
type
eOnExitWhenPortableMode = (owepPortableOff, oewpPromptUser, oewpDoNothing);
resourcestring
ONEXITWHENPORTABLEMODE_PORTABLEOFF = 'Turn off portable mode';
const
OnExitWhenPortableModeTitlePtr: array [eOnExitWhenPortableMode] of Pointer =
(@ONEXITWHENPORTABLEMODE_PORTABLEOFF, @RS_PROMPT_USER, @RS_DO_NOTHING
);
type
eOnNormalDismountFail = (ondfForceDismount, ondfPromptUser, ondfCancelDismount);
// is app running? used to detect crashes
eAppRunning = (arDontKnow{no settings file}, arRunning{set in InitApp}, arClosed{set in Form.close});
resourcestring
ONNORMALDISMOUNTFAIL_FORCEDISMOUNT = 'Force dismount';
ONNORMALDISMOUNTFAIL_CANCELDISMOUNT = 'Cancel dismount';
const
OnNormalDismountFailTitlePtr: array [eOnNormalDismountFail] of Pointer =
(@ONNORMALDISMOUNTFAIL_FORCEDISMOUNT, @RS_PROMPT_USER,
@ONNORMALDISMOUNTFAIL_CANCELDISMOUNT
);
type
TSystemTrayClickAction = (
stcaDoNothing,
stcaDisplayConsole,
stcaDisplayHideConsoleToggle,
stcaMountFile,
stcaMountPartition,
stcaMountLinuxFile,
stcaMountLinuxPartition,
stcaDismountAll
);
resourcestring
SYSTEMTRAYCLICKACTION_DONOTHING = 'Do nothing';
SYSTEMTRAYCLICKACTION_DISPLAYCONSOLE = 'Display window';
SYSTEMTRAYCLICKACTION_DISPLAYHIDECONSOLETOGGLE = 'Display/hide window toggle';
SYSTEMTRAYCLICKACTION_MOUNTFILE = 'Open LibreCrypt file ...';
SYSTEMTRAYCLICKACTION_MOUNTPARTITION = 'Open LibreCrypt partition...';
SYSTEMTRAYCLICKACTION_MOUNTLINUXFILE = 'Open (Linux) ...';
SYSTEMTRAYCLICKACTION_MOUNTLINUXPARTITION = 'Open partition (Linux) ...';
SYSTEMTRAYCLICKACTION_DISMOUNTALL = 'Lock all';
const
SystemTrayClickActionTitlePtr: array [TSystemTrayClickAction] of Pointer =
(@SYSTEMTRAYCLICKACTION_DONOTHING, @SYSTEMTRAYCLICKACTION_DISPLAYCONSOLE,
@SYSTEMTRAYCLICKACTION_DISPLAYHIDECONSOLETOGGLE, @SYSTEMTRAYCLICKACTION_MOUNTFILE,
@SYSTEMTRAYCLICKACTION_MOUNTPARTITION, @SYSTEMTRAYCLICKACTION_MOUNTLINUXFILE,
@SYSTEMTRAYCLICKACTION_MOUNTLINUXPARTITION, @SYSTEMTRAYCLICKACTION_DISMOUNTALL
);
type
TMainSettings = class (TCommonSettings)
PROTECTED
procedure _Load(iniFile: TCustomINIFile); OVERRIDE;
function _Save(iniFile: TCustomINIFile): Boolean; OVERRIDE;
PUBLIC
// General...
OptDisplayToolbar: Boolean;
OptDisplayToolbarLarge: Boolean;
OptDisplayToolbarCaptions: Boolean;
OptDisplayStatusbar: Boolean;
OptAllowMultipleInstances: Boolean;
OptAutoStartPortable: Boolean;
// OptInstalled: Boolean;// has installer been run?
OptDefaultDriveLetter: DriveLetterChar;
OptDefaultMountAs: TFreeOTFEMountAs;
feAppRunning : eAppRunning;
// Prompts and messages
OptWarnBeforeForcedDismount: Boolean;
OptOnExitWhenMounted: eOnExitWhenMounted;
OptOnExitWhenPortableMode: eOnExitWhenPortableMode;
OptOnNormalDismountFail: eOnNormalDismountFail;
// System tray icon...
OptSystemTrayIconDisplay: Boolean;
OptSystemTrayIconMinTo: Boolean;
OptSystemTrayIconCloseTo: Boolean;
OptSystemTrayIconActionSingleClick: TSystemTrayClickAction;
OptSystemTrayIconActionDoubleClick: TSystemTrayClickAction;
// Hotkey...
OptHKeyEnableDismount: Boolean;
OptHKeyKeyDismount: TShortCut;
OptHKeyEnableDismountEmerg: Boolean;
OptHKeyKeyDismountEmerg: TShortCut;
constructor Create(); OVERRIDE;
destructor Destroy(); OVERRIDE;
function RegistryKey(): String; OVERRIDE;
end;
var
// Global variable
gSettings: TMainSettings;
function OnExitWhenMountedTitle(Value: eOnExitWhenMounted): String;
function OnExitWhenPortableModeTitle(Value: eOnExitWhenPortableMode): String;
function OnNormalDismountFailTitle(Value: eOnNormalDismountFail): String;
function SystemTrayClickActionTitle(Value: TSystemTrayClickAction): String;
implementation
uses
Windows, // Required to get rid of compiler hint re DeleteFile
SysUtils, // Required for ChangeFileExt, DeleteFile
Dialogs,
Menus, Registry,
//sdu
SDUDialogs,
SDUi18n,
// Required for ShortCutToText and TextToShortCut
ShlObj; // Required for CSIDL_PERSONAL
const
SETTINGS_V1 = 1;
SETTINGS_V2 = 2;
// -- General section --
// Note: "Advanced" options are *also* stored within the "General" section
// This is done because some "General" settings were moved to become "Advanced" settings
OPT_DISPLAYTOOLBAR = 'DisplayToolbar';
DFLT_OPT_DISPLAYTOOLBAR = True;
OPT_DISPLAYTOOLBARLARGE = 'DisplayToolbarLarge';
DFLT_OPT_DISPLAYTOOLBARLARGE = True;
OPT_DISPLAYTOOLBARCAPTIONS = 'DisplayToolbarCaptions';
DFLT_OPT_DISPLAYTOOLBARCAPTIONS = True;
OPT_DISPLAYSTATUSBAR = 'DisplayStatusbar';
DFLT_OPT_DISPLAYSTATUSBAR = True;
OPT_ALLOWMULTIPLEINSTANCES = 'AllowMultipleInstances';
DFLT_OPT_ALLOWMULTIPLEINSTANCES = False;
OPT_AUTOSTARTPORTABLE = 'AutoStartPortable';
DFLT_OPT_AUTOSTARTPORTABLE = False;
OPT_DEFAULTMOUNTAS = 'DefaultMountAs';
DFLT_OPT_DEFAULTMOUNTAS = fomaRemovableDisk;
// OPT_OPTINSTALLED = 'Installed';
// DFLT_OPT_OPTINSTALLED = False;
OPT_APPRUNNING = 'AppRunning';
DFLT_OPT_APPRUNNING = arDontKnow;
// -- Prompts and messages --
// Section name defined in parent class's unit
OPT_WARNBEFOREFORCEDISMOUNT = 'WarnBeforeForcedDismount';
DFLT_OPT_WARNBEFOREFORCEDISMOUNT = True;
OPT_ONEXITWHENMOUNTED = 'OnExitWhenMounted';
DFLT_OPT_ONEXITWHENMOUNTED = oewmPromptUser;
OPT_ONEXITWHENPORTABLEMODE = 'OnExitWhenPortableMode';
DFLT_OPT_ONEXITWHENPORTABLEMODE = oewpPromptUser;
OPT_ONNORMALDISMOUNTFAIL = 'OnNormalDismountFail';
DFLT_OPT_ONNORMALDISMOUNTFAIL = oewpPromptUser;
// -- System tray icon section --
SECTION_SYSTEMTRAYICON = 'SystemTrayIcon';
OPT_SYSTEMTRAYICONDISPLAY = 'Display';
DFLT_OPT_SYSTEMTRAYICONDISPLAY = True;
OPT_SYSTEMTRAYICONMINTO = 'MinTo';
DFLT_OPT_SYSTEMTRAYICONMINTO = False;
OPT_SYSTEMTRAYICONCLOSETO = 'CloseTo';
DFLT_OPT_SYSTEMTRAYICONCLOSETO = True;
OPT_SYSTEMTRAYICONACTIONSINGLECLICK = 'ActionSingleClick';
DFLT_OPT_SYSTEMTRAYICONACTIONSINGLECLICK = stcaDisplayConsole;
OPT_SYSTEMTRAYICONACTIONDOUBLECLICK = 'ActionDoubleClick';
DFLT_OPT_SYSTEMTRAYICONACTIONDOUBLECLICK = stcaDisplayConsole;
// -- Hotkey section --
SECTION_HOTKEY = 'Hotkeys';
OPT_HOTKEYENABLEDISMOUNT = 'EnableDismount';
DFLT_OPT_HOTKEYENABLEDISMOUNT = False;
OPT_HOTKEYKEYDISMOUNT = 'KeyDismount';
DFLT_OPT_HOTKEYKEYDISMOUNT = 'Shift+Ctrl+D';
OPT_HOTKEYENABLEDISMOUNTEMERG = 'EnableDismountEmerg';
DFLT_OPT_HOTKEYENABLEDISMOUNTEMERG = False;
OPT_HOTKEYKEYDISMOUNTEMERG = 'KeyDismountEmerg';
DFLT_OPT_HOTKEYKEYDISMOUNTEMERG = 'Shift+Ctrl+Alt+D';
function OnExitWhenMountedTitle(Value: eOnExitWhenMounted): String;
begin
Result := LoadResString(OnExitWhenMountedTitlePtr[Value]);
end;
function OnExitWhenPortableModeTitle(Value: eOnExitWhenPortableMode): String;
begin
Result := LoadResString(OnExitWhenPortableModeTitlePtr[Value]);
end;
function OnNormalDismountFailTitle(Value: eOnNormalDismountFail): String;
begin
Result := LoadResString(OnNormalDismountFailTitlePtr[Value]);
end;
function SystemTrayClickActionTitle(Value: TSystemTrayClickAction): String;
begin
Result := LoadResString(SystemTrayClickActionTitlePtr[Value]);
end;
constructor TMainSettings.Create();
begin
inherited;
Load();
end;
destructor TMainSettings.Destroy();
begin
inherited;
end;
procedure TMainSettings._Load(iniFile: TCustomINIFile);
begin
inherited _Load(iniFile);
// todo -otdk : combine load and save, and/or use rtti
OptDisplayToolbar := iniFile.ReadBool(SECTION_GENERAL, OPT_DISPLAYTOOLBAR,
DFLT_OPT_DISPLAYTOOLBAR);
OptDisplayToolbarLarge := iniFile.ReadBool(SECTION_GENERAL,
OPT_DISPLAYTOOLBARLARGE, DFLT_OPT_DISPLAYTOOLBARLARGE);
OptDisplayToolbarCaptions := iniFile.ReadBool(SECTION_GENERAL,
OPT_DISPLAYTOOLBARCAPTIONS, DFLT_OPT_DISPLAYTOOLBARCAPTIONS);
OptDisplayStatusbar := iniFile.ReadBool(SECTION_GENERAL,
OPT_DISPLAYSTATUSBAR, DFLT_OPT_DISPLAYSTATUSBAR);
OptAllowMultipleInstances := iniFile.ReadBool(SECTION_GENERAL,
OPT_ALLOWMULTIPLEINSTANCES, DFLT_OPT_ALLOWMULTIPLEINSTANCES);
OptAutoStartPortable := iniFile.ReadBool(SECTION_GENERAL, OPT_AUTOSTARTPORTABLE,
DFLT_OPT_AUTOSTARTPORTABLE);
OptDefaultMountAs := TFreeOTFEMountAs(iniFile.ReadInteger(SECTION_GENERAL,
OPT_DEFAULTMOUNTAS, Ord(DFLT_OPT_DEFAULTMOUNTAS)));
feAppRunning :=
eAppRunning(iniFile.ReadInteger(SECTION_GENERAL,
OPT_APPRUNNING, Ord(DFLT_OPT_APPRUNNING)));
OptWarnBeforeForcedDismount := iniFile.ReadBool(SECTION_CONFIRMATION,
OPT_WARNBEFOREFORCEDISMOUNT, DFLT_OPT_WARNBEFOREFORCEDISMOUNT);
OptOnExitWhenMounted :=
eOnExitWhenMounted(iniFile.ReadInteger(SECTION_CONFIRMATION, OPT_ONEXITWHENMOUNTED,
Ord(DFLT_OPT_ONEXITWHENMOUNTED)));
OptOnExitWhenPortableMode :=
eOnExitWhenPortableMode(iniFile.ReadInteger(SECTION_CONFIRMATION,
OPT_ONEXITWHENPORTABLEMODE, Ord(DFLT_OPT_ONEXITWHENPORTABLEMODE)));
OptOnNormalDismountFail :=
eOnNormalDismountFail(iniFile.ReadInteger(SECTION_CONFIRMATION,
OPT_ONNORMALDISMOUNTFAIL, Ord(DFLT_OPT_ONNORMALDISMOUNTFAIL)));
OptSystemTrayIconDisplay :=
iniFile.ReadBool(SECTION_SYSTEMTRAYICON, OPT_SYSTEMTRAYICONDISPLAY,
DFLT_OPT_SYSTEMTRAYICONDISPLAY);
OptSystemTrayIconMinTo :=
iniFile.ReadBool(SECTION_SYSTEMTRAYICON, OPT_SYSTEMTRAYICONMINTO,
DFLT_OPT_SYSTEMTRAYICONMINTO);
OptSystemTrayIconCloseTo :=
iniFile.ReadBool(SECTION_SYSTEMTRAYICON, OPT_SYSTEMTRAYICONCLOSETO,
DFLT_OPT_SYSTEMTRAYICONCLOSETO);
OptSystemTrayIconActionSingleClick :=
TSystemTrayClickAction(iniFile.ReadInteger(SECTION_SYSTEMTRAYICON,
OPT_SYSTEMTRAYICONACTIONSINGLECLICK, Ord(DFLT_OPT_SYSTEMTRAYICONACTIONSINGLECLICK)));
OptSystemTrayIconActionDoubleClick :=
TSystemTrayClickAction(iniFile.ReadInteger(SECTION_SYSTEMTRAYICON,
OPT_SYSTEMTRAYICONACTIONDOUBLECLICK, Ord(DFLT_OPT_SYSTEMTRAYICONACTIONDOUBLECLICK)));
OptHKeyEnableDismount := iniFile.ReadBool(SECTION_HOTKEY,
OPT_HOTKEYENABLEDISMOUNT, DFLT_OPT_HOTKEYENABLEDISMOUNT);
OptHKeyKeyDismount := TextToShortCut(iniFile.ReadString(SECTION_HOTKEY,
OPT_HOTKEYKEYDISMOUNT, DFLT_OPT_HOTKEYKEYDISMOUNT));
OptHKeyEnableDismountEmerg := iniFile.ReadBool(SECTION_HOTKEY,
OPT_HOTKEYENABLEDISMOUNTEMERG, DFLT_OPT_HOTKEYENABLEDISMOUNTEMERG);
OptHKeyKeyDismountEmerg := TextToShortCut(iniFile.ReadString(SECTION_HOTKEY,
OPT_HOTKEYKEYDISMOUNTEMERG, DFLT_OPT_HOTKEYKEYDISMOUNTEMERG));
end;
function TMainSettings._Save(iniFile: TCustomINIFile): Boolean;
begin
Result := inherited _Save(iniFile);
if Result then begin
try
iniFile.WriteBool(SECTION_GENERAL, OPT_DISPLAYTOOLBAR, OptDisplayToolbar);
iniFile.WriteBool(SECTION_GENERAL, OPT_DISPLAYTOOLBARLARGE,
OptDisplayToolbarLarge);
iniFile.WriteBool(SECTION_GENERAL, OPT_DISPLAYTOOLBARCAPTIONS,
OptDisplayToolbarCaptions);
iniFile.WriteBool(SECTION_GENERAL, OPT_DISPLAYSTATUSBAR,
OptDisplayStatusbar);
iniFile.WriteBool(SECTION_GENERAL, OPT_ALLOWMULTIPLEINSTANCES,
OptAllowMultipleInstances);
iniFile.WriteBool(SECTION_GENERAL, OPT_AUTOSTARTPORTABLE,
OptAutoStartPortable);
iniFile.WriteInteger(SECTION_GENERAL, OPT_DEFAULTMOUNTAS,
Ord(OptDefaultMountAs));
iniFile.WriteInteger(SECTION_GENERAL, OPT_APPRUNNING,
Ord(feAppRunning));
iniFile.WriteBool(SECTION_CONFIRMATION, OPT_WARNBEFOREFORCEDISMOUNT,
OptWarnBeforeForcedDismount);
iniFile.WriteInteger(SECTION_CONFIRMATION, OPT_ONEXITWHENMOUNTED,
Ord(OptOnExitWhenMounted));
iniFile.WriteInteger(SECTION_CONFIRMATION, OPT_ONEXITWHENPORTABLEMODE,
Ord(OptOnExitWhenPortableMode));
iniFile.WriteInteger(SECTION_CONFIRMATION, OPT_ONNORMALDISMOUNTFAIL,
Ord(OptOnNormalDismountFail));
iniFile.WriteBool(SECTION_SYSTEMTRAYICON, OPT_SYSTEMTRAYICONDISPLAY,
OptSystemTrayIconDisplay);
iniFile.WriteBool(SECTION_SYSTEMTRAYICON, OPT_SYSTEMTRAYICONMINTO,
OptSystemTrayIconMinTo);
iniFile.WriteBool(SECTION_SYSTEMTRAYICON, OPT_SYSTEMTRAYICONCLOSETO,
OptSystemTrayIconCloseTo);
iniFile.WriteInteger(SECTION_SYSTEMTRAYICON, OPT_SYSTEMTRAYICONACTIONSINGLECLICK,
Ord(OptSystemTrayIconActionSingleClick));
iniFile.WriteInteger(SECTION_SYSTEMTRAYICON, OPT_SYSTEMTRAYICONACTIONDOUBLECLICK,
Ord(OptSystemTrayIconActionDoubleClick));
iniFile.WriteBool(SECTION_HOTKEY, OPT_HOTKEYENABLEDISMOUNT,
OptHKeyEnableDismount);
iniFile.WriteString(SECTION_HOTKEY, OPT_HOTKEYKEYDISMOUNT,
ShortCutToText(OptHKeyKeyDismount));
iniFile.WriteBool(SECTION_HOTKEY, OPT_HOTKEYENABLEDISMOUNTEMERG,
OptHKeyEnableDismountEmerg);
iniFile.WriteString(SECTION_HOTKEY, OPT_HOTKEYKEYDISMOUNTEMERG,
ShortCutToText(OptHKeyKeyDismountEmerg));
except
on E: Exception do begin
Result := False;
end;
end;
end;
end;
function TMainSettings.RegistryKey(): String;
begin
Result := FREEOTFE_REGISTRY_SETTINGS_LOCATION;
end;
end.
|
{Se prueba un medicamento en un conjunto de pacientes y se registran cantidad de pacientes
con resultados positivos, cantidad de pacientes con resultados negativos (empeoraron ) y
cantidad de resultados neutros.
Informe el resultado de la prueba de acuerdo al siguiente criterio
- Exitosa: Si mejoraron más de los que empeoraron y los neutros. Y además los que empeoraron
son menos que los neutros.
- Neutra: Si los que mejoraron son más que los que empeoraron y los neutros.
- Fracasada: En cualquier otro caso.
Además calcule e informe porcentaje de positivos sobre los no negativos.
Determine los datos que se requieren para resolver el ejercicio}
Program TP1eje15;
Var
Positivos,Negativos,Neutros,Suma:integer;
porcentaje:real;
Begin
write('Ingrese la cantidad de pacientes con resultados positivos: ');readln(Positivos);
write('Ingrese la cantidad de pacientes con resultados negativos: ');readln(Negativos);
write('Ingrese la cantidad de pacientes con resultados neutros : ');readln(Neutros);
Suma:= Negativos + Neutros;
writeln(' ');
If (Positivos > Suma) and (Negativos < Neutros) then
writeln('Es una medicina exitosa')
Else
if (Positivos > Suma) then
writeln('Es una medicina neutra')
Else
writeln('Es una medicina fracasada');
If (Positivos <= Neutros ) then
porcentaje:= (Positivos * Neutros) /100
Else
porcentaje:= (Positivos * Negativos) /100;
writeln(' ');
writeln('El porcentaje de positivos sobre los no negativos es del: ',porcentaje:2:0,' %');
end.
|
unit Odontologia.Modelo.Entidades.Pedido;
interface
uses
SimpleAttributes;
type
[Tabela('PEDIDO')]
TPEDIDO = class
private
FFECHA: TDateTime;
FID: Integer;
procedure SetFECHA(const Value: TDateTime);
procedure SetID(const Value: Integer);
published
[Campo('ID'), Pk, AutoInc]
property ID : Integer read FID write SetID;
[Campo('FECHA')]
property FECHA : TDateTime read FFECHA write SetFECHA;
end;
implementation
{ TPEDIDO }
procedure TPEDIDO.SetFECHA(const Value: TDateTime);
begin
FFECHA := Value;
end;
procedure TPEDIDO.SetID(const Value: Integer);
begin
FID := Value;
end;
end.
|
unit LandmarkPathCalculator;
interface
uses
SysUtils,
System.Generics.Collections, System.Generics.Defaults,
Ils.Utils, Geo.Hash, Geo.Pos,
ULPCThread, System.Types,
AStar64.DynImport, AStar64.Typ, AStar64.FileStructs, AStar64.LandMark;
type
TLPCProgressFunc = procedure(
const ACurrent: Integer;
const ATotal: Integer
) of object;
TLandmarkPathCalculator = class
private
FFullPath: string;
FFileName: string;
FLandmarkCoords: TGeoPosArray;
FProgressCB: TLPCProgressFunc;
FThreads: Integer;
public
constructor Create(
const AFullPath: string;
const AFileName: string;
const ALandmarkCoords: TGeoPosArray;
const AProgressCB: TLPCProgressFunc;
const AThreads: Integer
);
procedure CalculateAndSave();
end;
//------------------------------------------------------------------------------
TLocalProgressCBFunc = procedure(
const ACurrent: Integer;
const ATotal: Integer
);
TLPC = class
public
class procedure GenMulti(
const AFullPath: string;
const AFileName: string;
const ALandmarkCoords: TGeoPosArray;
const AAccounts: TIntegerDynArray;
const AProgressCB: TLocalProgressCBFunc;
const AThreads: Integer;
const ATimeout: Integer;
const ARecalcAll: Boolean;
const AResDir: string = ''
);
{ class procedure GetCalcMulti(
const ARootPath: string;
const AAccounts: TIntegerDynArray;
// const ALandmarkCoords: TGeoPosArray;
const AProgressCB: TLocalProgressCBFunc;
const AThreads: Integer;
const ATimeout: Integer;
var ARLandmarkMatrix: TLandMarkMatrix
);}
// class procedure Gen(
// const AFullPath: string;
// const AFileName: string;
// const ALandmarkCoords: TGeoPosArray
// );
class procedure InsertLightsFromGeoPosArray(
const ARLandmarkMatrix: TLandMarkMatrix;
const ALandmarkCoords: TGeoPosArray
);
class procedure InsertLightsFromGeoHashArray(
const ARLandmarkMatrix: TLandMarkMatrix;
const ALandmarkCoords: TArray<Int64>
);
end;
implementation
{ TLPC }
class procedure TLPC.GenMulti(
const AFullPath: string;
const AFileName: string;
const ALandmarkCoords: TGeoPosArray;
const AAccounts: TIntegerDynArray;
const AProgressCB: TLocalProgressCBFunc;
const AThreads: Integer;
const ATimeout: Integer;
const ARecalcAll: Boolean;
const AResDir: string
);
var
LMKeyIter: TLandMarkWayKey;
LandMarkMatrixInput, LandMarkMatrixOutput: TLandMarkMatrix;
Tasks: TTaskQueue;
CntTotal, CntCurrent: Integer;
begin
Log('GENMT started with ' + AFullPath + AFileName);
LandMarkMatrixInput := nil;
LandMarkMatrixOutput := nil;
Tasks := nil;
try
LandMarkMatrixInput := TLandMarkMatrix.Create(AFullPath, AFileName, AAccounts, AResDir);
LandMarkMatrixOutput := TLandMarkMatrix.Create(AFullPath, AFileName, AAccounts, AResDir);
Tasks := TTaskQueue.Create(LandMarkMatrixOutput, AThreads, ATimeout, ARecalcAll);
//
if ARecalcAll then
begin
Log('GenMulti. Full recalc');
InsertLightsFromGeoPosArray(LandMarkMatrixInput, ALandmarkCoords);
CntCurrent := 0;
CntTotal := LandMarkMatrixInput.Count;
Log('GENMT pathways ' + IntToStr(CntTotal));
// расчёт
for LMKeyIter in LandMarkMatrixInput.Keys do
begin
if (LandMarkMatrixInput.Items[LMKeyIter].GeoHash <> '') then
Continue;
Log('GENMT pass ' + IntToStr(CntCurrent) + ' of ' + IntToStr(CntTotal));
if Assigned(AProgressCB) then
AProgressCB(CntCurrent, CntTotal);
Inc(CntCurrent);
Tasks.PushTask(LMKeyIter, ARecalcAll, AAccounts);
end;
end else
begin
Log('GenMulti. Partial recalc');
LandMarkMatrixOutput.LoadIndex;
CntCurrent := 0;
CntTotal := LandMarkMatrixOutput.Count;
for LMKeyIter in LandMarkMatrixOutput.Keys do
begin
if (LandMarkMatrixOutput.Items[LMKeyIter].GeoHash = '') then
begin
if Assigned(AProgressCB) then
AProgressCB(CntCurrent, CntTotal);
Inc(CntCurrent);
Tasks.PushTask(LMKeyIter, False, AAccounts);
end else
if (LandMarkMatrixOutput.Items[LMKeyIter].GeoHash = 'fullcalc') then
begin
if Assigned(AProgressCB) then
AProgressCB(CntCurrent, CntTotal);
Inc(CntCurrent);
Tasks.PushTask(LMKeyIter, true, AAccounts);
end;
end;
end;
Log('GENMT waiting');
Tasks.WaitForAllDone();
Log('GENMT saving');
LandMarkMatrixOutput.Save();
Log('GENMT done');
if Assigned(AProgressCB) then
AProgressCB(CntCurrent, CntTotal);
finally
LandMarkMatrixInput.Free();
LandMarkMatrixOutput.Free();
Tasks.Free();
end;
end;
class procedure TLPC.InsertLightsFromGeoPosArray(
const ARLandmarkMatrix: TLandMarkMatrix;
const ALandmarkCoords: TGeoPosArray
);
var
K: TLandMarkWayKey;
I, J: Integer;
begin
K.z := 0;
for I := Low(ALandmarkCoords) to High(ALandmarkCoords) do
begin
for J := Low(ALandmarkCoords) to High(ALandmarkCoords) do
begin
if (I = J) then
Continue;
K.v.HashFrom := TGeoHash.EncodePointBin(ALandmarkCoords[I].Latitude, ALandmarkCoords[I].Longitude);
K.v.HashTo := TGeoHash.EncodePointBin(ALandmarkCoords[J].Latitude, ALandmarkCoords[J].Longitude);
if not ARLandmarkMatrix.ContainsKey(K) then
ARLandmarkMatrix.Add(K, TLandMarkWay.Create('', 0))
else
ARLandmarkMatrix.Items[K].Clear();
end;
end;
end;
(*
class procedure TLPC.GetCalcMulti(const ARootPath: string;
const AAccounts: TIntegerDynArray;
// const ALandmarkCoords: TGeoPosArray;
const AProgressCB: TLocalProgressCBFunc;
const AThreads: Integer;
const ATimeout: Integer;
var ARLandmarkMatrix: TLandMarkMatrix
);
var
LMKeyIter: TLandMarkWayKey;
// LandMarkMatrixInput: TLandMarkMatrix;
Tasks: TTaskQueue;
CntTotal, CntCurrent: Integer;
begin
Log('TLPC.GetCalcMulti started');
// LandMarkMatrixInput := nil;
Tasks := nil;
try
// LandMarkMatrixInput := TLandMarkMatrix.Create(AFullPath, AFileName);
// LandMarkMatrixOutput := TLandMarkMatrix.Create(AFullPath, AFileName);
// Result := TLandMarkMatrix.Create(ARootPath, '');
Tasks := TTaskQueue.Create(ARLandmarkMatrix, AThreads, ATimeout, False);
// InsertLightsFromGeoPosArray(LandMarkMatrixInput, ALandmarkCoords);
CntCurrent := 0;
CntTotal := ARLandmarkMatrix.Count;
Log('TLPC.GetCalcMulti pathways ' + IntToStr(CntTotal));
// расчёт
for LMKeyIter in ARLandmarkMatrix.Keys do
begin
if (ARLandmarkMatrix.Items[LMKeyIter].GeoHash <> '') then
Continue;
Log('TLPC.GetCalcMulti pass ' + IntToStr(CntCurrent) + ' of ' + IntToStr(CntTotal));
if Assigned(AProgressCB) then
AProgressCB(CntCurrent, CntTotal);
Inc(CntCurrent);
Tasks.PushTask(LMKeyIter, True, AAccounts);
end;
Log('TLPC.GetCalcMulti waiting');
Tasks.WaitForAllDone();
Log('TLPC.GetCalcMulti saving');
// LandMarkMatrixOutput.Save();
Log('TLPC.GetCalcMulti done');
if Assigned(AProgressCB) then
AProgressCB(CntCurrent, CntTotal);
finally
// LandMarkMatrixInput.Free();
// LandMarkMatrixOutput.Free();
Tasks.Free();
end;
end;
*)
class procedure TLPC.InsertLightsFromGeoHashArray(
const ARLandmarkMatrix: TLandMarkMatrix;
const ALandmarkCoords: TArray<Int64>
);
var
K: TLandMarkWayKey;
I, J: Integer;
begin
K.z := 0;
for I := Low(ALandmarkCoords) to High(ALandmarkCoords) do
begin
for J := Low(ALandmarkCoords) to High(ALandmarkCoords) do
begin
if (I = J) then
Continue;
K.v.HashFrom := ALandmarkCoords[I];
K.v.HashTo := ALandmarkCoords[J];
if not ARLandmarkMatrix.ContainsKey(K) then
ARLandmarkMatrix.Add(K, TLandMarkWay.Create('', 0))
else
ARLandmarkMatrix.Items[K].Clear();
end;
end;
end;
{ TLandmarkPathCalculator }
constructor TLandmarkPathCalculator.Create(
const AFullPath: string;
const AFileName: string;
const ALandmarkCoords: TGeoPosArray;
const AProgressCB: TLPCProgressFunc;
const AThreads: Integer
);
begin
inherited Create();
//
FFullPath := AFullPath;
FFileName := AFileName;
FLandmarkCoords := ALandmarkCoords;
FProgressCB := AProgressCB;
FThreads := AThreads;
end;
procedure TLandmarkPathCalculator.CalculateAndSave;
begin
//
end;
end.
|
Unit Sys_Procesos;
{ * Sys_Procesos :
* *
* Implementacion de las llamadas al sistema de los procesos *
* algunas no estan provadas hasta el momento *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* 30 - 03 - 04 :Version Inicial *
* *
**************************************************************
}
interface
{DEFINE DEBUG}
{$I ../include/head/asm.h}
{$I ../include/toro/procesos.inc}
{$I ../include/toro/signal.inc}
{$I ../include/head/procesos.h}
{$I ../include/head/signal.h}
{$I ../include/head/scheduler.h}
{$I ../include/head/read_write.h}
{$I ../include/head/printk_.h}
{$DEFINE Use_Hash}
implementation
{$I ../include/head/list.h}
{ * Sys_Getpid :
* *
* Retorno : Numero de pid de la tarea actual *
* *
* Llamada al sistema que devuelve el pid de la tarea actual *
* *
***************************************************************
}
function sys_getpid:dword;cdecl;[public , alias :'SYS_GETPID'];
begin
exit(Tarea_actual^.pid);
end;
{ * Sys_GetPpid : *
* *
* Retorno : Pid del proceso padre de la tarea actual *
* *
* Llamada al sistema que devuelve el pid de padre del proceso *
* *
***************************************************************
}
function sys_getppid:dword;cdecl;[public , alias :'SYS_GETPPID'];
begin
exit(Tarea_actual^.padre_pid);
end;
{ * Sys_Detener : *
* *
* Pid : Numero Pid de la tarea *
* *
* Llamada al sistema que Detiene la ejecucion de un proceso , enviando *
* la se¤al SIG_DETENER , por ahora el proceso no puede ser despertado *
* *
************************************************************************
}
function sys_detener(Pid:dword):dword;cdecl;[public , alias :'SYS_DETENER'];
var tmp,tarea:p_tarea_struc;
begin
tmp := Hash_Get(Pid);
If tmp = nil then
begin
set_errno := -ESRCH ;
exit(-1);
end;
If tmp^.Padre_Pid=Tarea_Actual^.pid then
Signal_Send(tmp,SIG_DETENER)
else
begin
set_errno := -ECHILD ;
exit(-1);
end;
clear_errno ;
exit(0);
end;
{ * Sys_Fork : *
* *
* Unas de las mas importantes llamadas al sistema , puesto que crea *
* un proceso a partir del proceso padre , es una copia exacta del *
* padre *
* *
* Versiones : *
* 4 / 01 / 2005 : Primera Version *
* *
*********************************************************************
}
function sys_fork:dword;cdecl;[public , alias :'SYS_FORK'];
var hijo:p_tarea_struc;
err:word;
ip_ret,esp_ret,ebp_ret,eflags_ret:dword;
l:dword;
begin
asm
mov eax , [ebp + 44]
mov ip_ret , eax
mov eax , [ebp + 28]
mov ebp_ret , eax
mov eax , [ebp + 56]
mov esp_ret , eax
mov eax , [ebp + 52 ]
mov eflags_ret , eax
end;
Hijo := Proceso_Clonar(Tarea_Actual);
If hijo = nil then exit(0);
Hijo^.reg.eip := pointer(ip_ret) ;
Hijo^.reg.esp := pointer(esp_ret) ;
Hijo^.reg.ebp := pointer(ebp_ret);
Hijo^.reg.eax := 0 ; { Resultado de operacion para el hijo }
add_task (Hijo);
exit(hijo^.pid);
end;
{ * Sys_WaitPid : *
* *
* status : Causa de la terminacion *
* Retorno : Pid del proceso Hijo *
* *
* Llamada al sistema que duerme a un padre que espera por la terminacion *
* de un hijo y devuelve la causa de terminacion *
* *
**************************************************************************
}
function sys_waitpid(var status:dword):dword;cdecl;[public , alias :'SYS_WAITPID'];
var pid:dword;
err:word;
begin
esperar_hijo(Tarea_Actual,Pid,err);
status:=err;
exit(pid);
end;
{ * Sys_Exit : *
* *
* status : Causa de la muerte *
* *
* Llamada al sistema que envia la se¤al de muerte al proceso actual *
* *
*********************************************************************
}
procedure sys_exit(status:word);cdecl;[public , alias :'SYS_EXIT'];
begin
cerrar;
Tarea_actual^.terminacion:= status;
Signal_Send(Tarea_Actual,Sig_Morir);
Signaling;
end;
{ * Sys_Kill : *
* *
* Pid : Numero de proceso *
* Signal : Numero de se¤al a enviar *
* *
* Esta es la implementacion de la llamada al sistema Kill() , que *
* envia la se¤al indicada en Signal , al proceso indicado en Pid , *
* siempre que el pid de la tarea solicitante sea igual al padre_pid *
* de Pid . Las Sig_Alarma y las se¤ales del kernel no pueden ser en *
* viadas por el usuario *
* *
***********************************************************************
}
function sys_kill(Pid:dword;Signal:word):dword;cdecl;[public , alias :'SYS_KILL'];
var tmp:p_tarea_struc;
begin
If Signal > 31 then exit(-1);
If (Signal = Sig_Detener) or (Signal = Sig_Alarm) or (Signal = Sig_Hijo) then
begin
set_errno := -EPERM ;
exit(-1);
end;
tmp := Hash_Get(Pid) ;
If tmp = nil then
begin
set_errno := -ESRCH ;
exit(-1);
end;
If tmp^.padre_pid <> Tarea_Actual^.pid then
begin
set_Errno := -ECHILD ;
exit(-1);
end;
Signal_Send(tmp,Signal);
exit(0);
end;
{ * Sys_Signal : *
* *
* Handler : Puntero al procedimiento *
* Signal : Numero de se¤al *
* *
* Esta es la implementacion de la llamada al sistema Signal() , que *
* coloca el puntero de tratamiento de una se¤al en el array Signals[] *
* *
***********************************************************************
}
function sys_signal(Handler:pointer;Signal:word):dword;cdecl;[public , alias :'SYS_SIGNAL'];
begin
Tarea_Actual^.signals[Signal] := Handler;
exit(0);
end;
{ * Sys_ReadErrno : *
* *
* Retorno : Numero de error *
* *
* Funcion que devuelve el codigo de error generado por la ultima *
* llamada al sistema , luego el campo errno es limpiado *
* *
***********************************************************************
}
function sys_readerrno : dword ; cdecl ; [public , alias : 'SYS_READERRNO'];
var errno : dword ;
begin
errno := set_errno ;
clear_errno ;
exit(errno);
end;
end.
|
unit PromoDiscountFactoryClass;
interface
uses PromoDiscountInterface, PromoDiscountAmountClass, PromoDiscountPercentClass, PromoDiscountQtyClass,
PromoDiscountSaleTotalClass, PromoItemClass, uSystemConst, SysUtils;
type
TPromoDiscountFactory = class
public
function createPromoDiscount(arg_Item: TPromoItem): IPromoDiscount;
end;
implementation
{ TPromoDiscountFactory }
function TPromoDiscountFactory.createPromoDiscount(arg_item: TPromoItem): IPromoDiscount;
begin
case ( arg_item.getDiscountType ) of
PROMO_DISCOUNT_AMOUNT : result := TPromoDiscountAmount.create();
PROMO_DISCOUNT_PERCENT: result := TPromoDiscountPercent.create();
PROMO_DISCOUNT_QTY: result := TPromoDiscountQty.create();
PROMO_DISCOUNT_SALE: result := TPromoDiscountSaleTotal.create();
else begin
raise Exception.Create('Unknown type of Promo Discount');
end;
end;
end;
end.
|
unit ZStageUnit;
// ========================================================================
// MesoScan: Z Stage control module
// (c) J.Dempster, Strathclyde Institute for Pharmacy & Biomedical Sciences
// ========================================================================
// 7/6/12 Supports Prior OptiScan II controller
// 14.5.14 Supports voltage-controlled lens positioner
// 27.0.16 Z stage pressure switch protection implemented
// 11.02.17 .Enabled removed, XPosition, YPosition added
// 16.01.17 ZStage.XScaleFactor and ZStage.YScaleFactor added
// 10.05.17 ZPositionMax,ZPositionMin limits added
// 24.05.17 ProScanEnableZStageTTLAction now executed before first Z stage position
// check because commands fail to work immediatelt after opening of com link to
// ProSCan III stage
// 08.08.17 Prior stage: ProScanEnableZStageTTLAction - stop all movement command added
// to TTL triggered list to abort any move commands in progress.
// Now operates in standard mode to allow 'R' command responses to be returned immediately after command
// Moves can now be changed while in progress.
// 18.10.17 Now reports if COM port cannot be opened and disables send/recieves to controller
// 14.11.17 Conversion to Threaded COM I/O in progress
interface
uses
System.SysUtils, System.Classes, Windows, FMX.Dialogs, math, strutils ;
type
TZStage = class(TDataModule)
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
FStageType : Integer ; // Type of stage
ComHandle : THandle ; // Com port handle
ComPortOpen : Boolean ; // Com port open flag
// FControlPort : DWord ; // Control port number
FBaudRate : DWord ; // Com port baud rate
ControlState : Integer ; // Z stage control state
Status : String ; // Z stage status report
MoveToRequest : Boolean ; // Go to Final flag
MoveToPosition : Double ; // Position (um) to go to
RequestedXPos : Double ; // Intermediate X position
RequestedYPos : Double ; // Intermediate Y position
RequestedZPos : Double ; // Intermediate Z position
StageInitRequired : Boolean ; // Stage needs to be initialised
OverLapStructure : POVERLAPPED ;
procedure OpenCOMPort ;
procedure CloseCOMPort ;
procedure ResetCOMPort ;
function SendCommand( const Line : string ) : Boolean ;
function ReceiveBytes( var EndOfLine : Boolean ) : string ;
procedure SetControlPort( Value : DWord ) ;
procedure SetBaudRate( Value : DWord ) ;
procedure SetStageType( Value : Integer ) ;
procedure UpdateZPositionPrior ;
procedure UpdateZPositionPZ ;
procedure MoveToPrior( X : Double ; // New X pos.
Y : Double ; // NEw Y pos.
Z : Double // New Z pos.
) ;
procedure MoveToPZ( Position : Double ) ;
function GetScaleFactorUnits : string ;
procedure ProScanEnableZStageTTLAction ;
procedure WaitforCompletion ;
function WaitforResponse(
ResponseRequired : string
) : Boolean ;
procedure Wait( Delay : double ) ;
public
{ Public declarations }
XPosition : Double ; // X position (um)
XScaleFactor : Double ; // X step scaling factor
YPosition : Double ; // Y position (um)
YScaleFactor : Double ; // Y step scaling factor
ZPosition : Double ; // Z position (um)
ZPositionMax : Double ; // Z position upper limit (um)
ZPositionMin : Double ; // Z position lower limit (um)
ZScaleFactor : Double ; // Z step scaling factor
ZStepTime : Double ; // Time to perform Z step (s)
FControlPort : DWord ; // Control port number
CommandList : TstringList ; // Light Source command list
ReplyList : TstringList ; // Light source replies
procedure Open ;
procedure Close ;
procedure UpdateZPosition ;
procedure MoveTo( X : Double ; // New X pos.
Y : Double ; // NEw Y pos.
Z : Double // New Z pos.
) ;
procedure GetZStageTypes( List : TStrings ) ;
procedure GetControlPorts( List : TStrings ) ;
published
Property ControlPort : DWORD read FControlPort write SetControlPort ;
Property BaudRate : DWORD read FBaudRate write SetBaudRate ;
Property StageType : Integer read FStageType write SetStageType ;
Property ScaleFactorUnits : string read GetScaleFactorUnits ;
end;
var
ZStage: TZStage;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
uses LabIOUnit, mmsystem;
{$R *.dfm}
const
csIdle = 0 ;
csWaitingForPosition = 1 ;
csWaitingForCompletion = 2 ;
stNone = 0 ;
stOptiscanII = 1 ;
stProscanIII = 2 ;
stPiezo = 3 ;
XMaxStep = 10000.0 ;
YMaxStep = 10000.0 ;
ZMaxStep = 10000.0 ;
procedure TZStage.DataModuleCreate(Sender: TObject);
// ---------------------------------------
// Initialisations when module is created
// ---------------------------------------
begin
FStageType := stNone ;
ComPortOpen := False ;
FControlPort := 0 ;
FBaudRate := 9600 ;
Status := '' ;
ControlState := csIdle ;
XPosition := 0.0 ;
XscaleFactor := 1.0 ;
YPosition := 0.0 ;
YScaleFactor := 1.0 ;
ZPosition := 0.0 ;
ZPositionMax := 10000.0 ;
ZPositionMin := -10000.0 ;
ZScaleFactor := 10.0 ;
RequestedXPos := 0.0 ;
RequestedYPos := 0.0 ;
RequestedZPos := 0.0 ;
MoveToRequest := False ;
StageInitRequired := False ;
end;
procedure TZStage.DataModuleDestroy(Sender: TObject);
// --------------------------------
// Tidy up when module is destroyed
// --------------------------------
begin
if ComPortOpen then CloseComPort ;
end;
procedure TZStage.GetZStageTypes( List : TStrings ) ;
// -----------------------------------
// Get list of supported Z stage types
// -----------------------------------
begin
List.Clear ;
List.Add('None') ;
List.Add('Prior Optiscan II') ;
List.Add('Prior Proscan III') ;
List.Add('Piezo (Voltage Controlled)');
end;
procedure TZStage.GetControlPorts( List : TStrings ) ;
// -----------------------------------
// Get list of available control ports
// -----------------------------------
var
i : Integer ;
iDev: Integer;
begin
List.Clear ;
case FStageType of
stOptiscanII,stProScanIII : begin
// COM ports
for i := 1 to 16 do List.Add(format('COM%d',[i]));
end ;
stPiezo : begin
// Analog outputs
for iDev := 1 to LabIO.NumDevices do
for i := 0 to LabIO.NumDACs[iDev]-1 do begin
List.Add(Format('Dev%d:AO%d',[iDev,i])) ;
end;
end;
else begin
List.Add('None');
end ;
end;
end;
procedure TZStage.Open ;
// ---------------------------
// Open Z stage for operation
// ---------------------------
begin
// Close COM port (if open)
if ComPortOpen then CloseComPort ;
case FStageType of
stOptiscanII :
begin
OpenComPort ;
end ;
stProScanIII :
begin
OpenComPort ;
StageInitRequired := True ;
end ;
stPiezo :
begin
end;
end;
end;
function TZStage.GetScaleFactorUnits : string ;
// -------------------------------
// Return units for Z scale factor
// -------------------------------
begin
case FStageType of
stOptiscanII,stProScanIII : Result := 'steps/um' ;
stPiezo : Result := 'V/um' ;
else Result := '' ;
end;
end;
procedure TZStage.Close ;
// ---------------------------
// Close down Z stage operation
// ---------------------------
begin
if ComPortOpen then CloseComPort ;
end;
procedure TZStage.UpdateZPosition ;
// ---------------------------
// Update position of Z stage
// ---------------------------
begin
case FStageType of
stOptiscanII :
begin
if StageInitRequired then
begin
// Set into standard mode (command responses return immediately)
SendCommand('COMP 0') ;
WaitforResponse('0') ;
end;
UpdateZPositionPrior ;
end;
stProScanIII :
begin
if StageInitRequired then
begin
// Set into standard mode (command responses return immediately)
SendCommand('COMP 0') ;
WaitforResponse('0') ;
// Set up stage protection action
ProScanEnableZStageTTLAction ;
StageInitRequired := False ;
end;
UpdateZPositionPrior ;
end;
stPiezo : UpdateZPositionPZ ;
end;
end;
procedure TZStage.MoveTo( X : Double ; // New X pos.
Y : Double ; // New Y pos.
Z : Double // New Z pos.
) ;
// ----------------
// Go to Z position
// ----------------
begin
// Keep within limits
Z := Min(Max(Z,ZPositionMin),ZPositionMax);
case FStageType of
stOptiscanII,stProScanIII : MoveToPrior( X,Y,Z ) ;
stPiezo : MoveToPZ( Z ) ;
end;
end;
procedure TZStage.OpenCOMPort ;
// ----------------------------------------
// Establish communications with COM port
// ----------------------------------------
var
DCB : TDCB ; { Device control block for COM port }
CommTimeouts : TCommTimeouts ;
begin
ComPortOpen := False ;
{ Open com port }
ComHandle := CreateFile( PCHar(format('COM%d',[ControlPort+1])),
GENERIC_READ or GENERIC_WRITE,
0,
Nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0) ;
if Integer(ComHandle) < 0 then
begin
ShowMessage( format('Z Stage: Unable to open port COM%d',[ControlPort+1]));
Exit ;
end;
{ Get current state of COM port and fill device control block }
GetCommState( ComHandle, DCB ) ;
{ Change settings to those required for 1902 }
DCB.BaudRate := CBR_9600 ;
DCB.ByteSize := 8 ;
DCB.Parity := NOPARITY ;
DCB.StopBits := ONESTOPBIT ;
{ Update COM port }
SetCommState( ComHandle, DCB ) ;
{ Initialise Com port and set size of transmit/receive buffers }
SetupComm( ComHandle, 4096, 4096 ) ;
{ Set Com port timeouts }
GetCommTimeouts( ComHandle, CommTimeouts ) ;
CommTimeouts.ReadIntervalTimeout := $FFFFFFFF ;
CommTimeouts.ReadTotalTimeoutMultiplier := 0 ;
CommTimeouts.ReadTotalTimeoutConstant := 0 ;
CommTimeouts.WriteTotalTimeoutMultiplier := 0 ;
CommTimeouts.WriteTotalTimeoutConstant := 5000 ;
SetCommTimeouts( ComHandle, CommTimeouts ) ;
ComPortOpen := True ;
Status := '' ;
ControlState := csIdle ;
end ;
procedure TZStage.CloseCOMPort ;
// ----------------------
// Close serial COM port
// ----------------------
begin
if ComPortOpen then CloseHandle( ComHandle ) ;
ComPortOpen := False ;
end ;
function TZStage.SendCommand(
const Line : string { Text to be sent to Com port }
) : Boolean ;
{ --------------------------------------
Write a line of ASCII text to Com port
--------------------------------------}
var
i : Integer ;
nWritten,nC : DWORD ;
xBuf : array[0..258] of ansichar ;
Overlapped : Pointer ;
OK : Boolean ;
begin
Result := False ;
if not ComPortOpen then Exit ;
{ Copy command line to be sent to xMit buffer and and a CR character }
nC := Length(Line) ;
for i := 1 to nC do xBuf[i-1] := ANSIChar(Line[i]) ;
xBuf[nC] := #13 ;
Inc(nC) ;
Overlapped := Nil ;
OK := WriteFile( ComHandle, xBuf, nC, nWritten, Overlapped ) ;
if (not OK) or (nWRitten <> nC) then
begin
// ShowMessage( ' Error writing to COM port ' ) ;
Result := False ;
end
else Result := True ;
end ;
procedure TZStage.WaitforCompletion ;
var
Status : string ;
Timeout : Cardinal ;
EndOfLine : Boolean ;
begin
if not ComPortOpen then Exit ;
TimeOut := timegettime + 5000 ;
repeat
Status := ReceiveBytes( EndOfLine ) ;
Until EndOfLine or (timegettime > TimeOut) ;
if not EndOfLine then outputDebugstring(pchar('Time out'));
end ;
function TZStage.WaitforResponse(
ResponseRequired : string
) : Boolean ;
var
Response : string ;
EndOfLine : Boolean ;
Timeout : Cardinal ;
begin
if not ComPortOpen then Exit ;
Response := '' ;
TimeOut := timegettime + 5000 ;
if not ComPortOpen then Exit ;
repeat
Response := Response + ReceiveBytes( EndOfLine ) ;
until EndOfLine or (TimeGetTime > TimeOut) ;
if Response = ResponseRequired then Result := True
else Result := False ;
end ;
function TZStage.ReceiveBytes(
var EndOfLine : Boolean
) : string ; { bytes received }
{ -------------------------------------------------------
Read bytes from Com port until a line has been received
-------------------------------------------------------}
var
Line : string ;
rBuf : array[0..255] of ansichar ;
ComState : TComStat ;
PComState : PComStat ;
NumBytesRead,ComError,NumRead : DWORD ;
begin
if not ComPortOpen then Exit ;
PComState := @ComState ;
Line := '' ;
rBuf[0] := ' ' ;
NumRead := 0 ;
EndOfLine := False ;
Result := '' ;
{ Find out if there are any characters in receive buffer }
ClearCommError( ComHandle, ComError, PComState ) ;
// Read characters until CR is encountered
while (NumRead < ComState.cbInQue) and (RBuf[0] <> #13) do
begin
ReadFile( ComHandle,rBuf,1,NumBytesRead,OverlapStructure ) ;
if rBuf[0] <> #13 then Line := Line + String(rBuf[0])
else EndOfLine := True ;
//outputdebugstring(pwidechar(RBuf[0]));
Inc( NumRead ) ;
end ;
Result := Line ;
end ;
procedure TZStage.UpdateZPositionPrior ;
// ----------------------------------------
// Update position of Z stage (Optoscan II)
// ----------------------------------------
var
EndOfLine : Boolean ;
OK : Boolean ;
i,iNum : Integer ;
c,s : string ;
begin
case ControlState of
csIdle :
begin
if StageInitRequired then begin
ProScanEnableZStageTTLAction ;
StageInitRequired := False ;
end;
if MoveToRequest then
begin
// Stop any stage moves in progress
OK := SendCommand('I');
WaitforResponse('R') ;
// Go to requested X,Y,Z position
// ------------------------------
OK := SendCommand( format('G %d,%d,%d',
[Round(RequestedXPos*XScaleFactor),
Round(RequestedYPos*YScaleFactor),
Round(RequestedZPos*ZScaleFactor)]));
if OK then ControlState := csWaitingForCompletion ;
MoveToRequest := False ;
end
else
begin
// Request stage X,Y,Z position
// ----------------------------
OK := SendCommand( 'P' ) ;
if OK then ControlState := csWaitingForPosition ;
end ;
end;
csWaitingForPosition :
begin
// Decode X,Y,Z stage position
// ---------------------------
XScaleFactor := Max(XScaleFactor,1E-4) ;
YScaleFactor := Max(YScaleFactor,1E-4) ;
ZScaleFactor := Max(ZScaleFactor,1E-4) ;
Status := Status + ReceiveBytes( EndOfLine ) ;
if EndOfLine then
begin
i := 1 ;
s := '' ;
iNum := 0 ;
while i <= Length(Status) do
begin
c := Status[i] ;
if (c = ',') or (i = Length(Status)) then
begin
if c <> ',' then s := s + Status[i] ;
// Remove error flag (if represent)
s := ReplaceText(s,'R','');
if (not ContainsText(s,'R')) and (s<>'') then
begin
case iNum of
0 : XPosition := StrToInt64(s)/XScaleFactor ;
1 : YPosition := StrToInt64(s)/YScaleFactor ;
2 : ZPosition := StrToInt64(s)/ZScaleFactor ;
end ;
end;
Inc(INum) ;
s := '' ;
end
else s := s + Status[i] ;
Inc(i) ;
end;
Status := '' ;
ControlState := csIdle ;
end;
end ;
csWaitingForCompletion :
begin
// Wait for response indicating completion of command
Status := ReceiveBytes( EndOfLine ) ;
if EndOfLine then
begin
outputdebugstring(pchar(status));
Status := '' ;
ControlState := csIdle ;
end;
end;
end;
end;
procedure TZStage.MoveToPrior( X : Double ; // New X pos.
Y : Double ; // New Y pos.
Z : Double // New Z pos.
) ;
// ------------------------------
// Go to Z position (Optoscan II)
// ------------------------------
begin
RequestedXPos := X ;
RequestedYPos := Y ;
RequestedZPos := Z ;
MoveToRequest := True ;
end;
procedure TZStage.SetControlPort( Value : DWord ) ;
// ----------------
// Set Control Port
//-----------------
begin
FControlPort := Max(Value,0) ;
ResetCOMPort ;
end;
procedure TZStage.SetBaudRate( Value : DWord ) ;
// ----------------------
// Set com Port baud rate
//-----------------------
begin
if Value <= 0 then Exit ;
FBaudRate := Value ;
ResetCOMPort ;
end;
procedure TZStage.ResetCOMPort ;
// --------------------------
// Reset COM port (if in use)
// --------------------------
begin
case FStageType of
stOptiscanII,stProScanIII :
begin
if ComPortOpen then
begin
CloseComPort ;
OpenComPort ;
end;
end;
end;
end;
procedure TZStage.SetStageType( Value : Integer ) ;
// ------------------------------
// Set type of Z stage controller
// ------------------------------
begin
// Close existing stage
Close ;
FStageType := Value ;
// Reopen new stage
Open ;
end;
procedure TZStage.UpdateZPositionPZ ;
// ----------------------------------
// Update position of Z stage (Piezo)
// ----------------------------------
begin
end;
procedure TZStage.MoveToPZ( Position : Double ) ;
// -------------------------
// Go to Z position (Piezo)
// -------------------------
var
iPort,iChan,iDev : Integer ;
begin
ZPosition := Position ;
iPort := 0 ;
for iDev := 1 to LabIO.NumDevices do
for iChan := 0 to LabIO.NumDACs[iDev]-1 do
begin
if iPort = FControlPort then
begin
LabIO.WriteDAC(iDev,Position*ZScaleFactor,iChan);
end;
inc(iPort) ;
end;
end ;
procedure TZStage.ProScanEnableZStageTTLAction ;
// ---------------------------------------------------------------
// Enable action to be taken when TTL hard limit trigger activated
// ---------------------------------------------------------------
begin
SendCommand('TTLDEL,1') ;
WaitforResponse('0') ;
SendCommand('TTLTP,1,1') ; // Enable trigger on input #1 going high
WaitforResponse('0') ;
SendCommand('TTLACT,1,70,0,0,0') ; // Stop all movement
WaitforResponse('0') ;
SendCommand('TTLACT,1,31,0,0,0') ; // Move Z axis to zero position
WaitforResponse('0') ;
SendCommand('TTLTRG,1') ; // Enable triggers
WaitforResponse('0') ;
end;
procedure TZStage.Wait( Delay : double ) ;
var
TEndWait,T : Cardinal ;
begin
TEndWait := TimeGetTime + Round(Delay*1000.0) ;
repeat
t := TimeGetTime ;
until t >= TEndWait ;
end;
end.
|
unit Email;
interface
{
Changelog:
13.04.2001 Fixed memory Leak and String problem in adresses (Sendmail - method)
31.08.2000 Some Changes on the TStrings Objects, added SetXXAdr-Methods
}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
{ Introducing a new Type of Event to get the Errorcode }
TMapiErrEvent = procedure(Sender: TObject; ErrCode: Integer) of object;
TEmail = class(TComponent)
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
private
{ Private-Deklarationen }
FSubject: string;
FMailtext: string;
FFromName: string;
FFromAdress: string;
FTOAdr: TStrings;
FCCAdr: TStrings;
FBCCAdr: TStrings;
FAttachedFileName: TStrings;
FDisplayFileName: TStrings;
FShowDialog: Boolean;
FUseAppHandle: Boolean;
{ Error Events: }
FOnUserAbort: TNotifyEvent;
FOnMapiError: TMapiErrEvent;
FOnSuccess: TNotifyEvent;
{ +> Changes by Eugene Mayevski [mailto:Mayevski@eldos.org]}
procedure SetToAddr(newValue: TStrings);
procedure SetCCAddr(newValue: TStrings);
procedure SetBCCAddr(newValue: TStrings);
procedure SetAttachedFileName(newValue: TStrings);
{ +< Changes }
protected
{ Protected-Deklarationen }
public
{ Public-Deklarationen }
ApplicationHandle: THandle;
procedure Sendmail();
procedure Reset();
published
{ Published-Deklarationen }
property Subject: string read FSubject write FSubject;
property Body: string read FMailText write FMailText;
property FromName: string read FFromName write FFromName;
property FromAdress: string read FFromAdress write FFromAdress;
property Recipients: TStrings read FTOAdr write SetTOAddr;
property CopyTo: TStrings read FCCAdr write SetCCAddr;
property BlindCopyTo: TStrings read FBCCAdr write SetBCCAddr;
property AttachedFiles: TStrings read FAttachedFileName write SetAttachedFileName;
property DisplayFileName: TStrings read FDisplayFileName;
property ShowDialog: Boolean read FShowDialog write FShowDialog;
property UseAppHandle: Boolean read FUseAppHandle write FUseAppHandle;
{ Events: }
property OnUserAbort: TNotifyEvent read FOnUserAbort write FOnUserAbort;
property OnMapiError: TMapiErrEvent read FOnMapiError write FOnMapiError;
property OnSuccess: TNotifyEvent read FOnSuccess write FOnSuccess;
end;
procedure Register;
implementation
uses Mapi;
{ Register the component: }
procedure Register;
begin
RegisterComponents('NewPower', [TEmail]);
end;
{ TEmail }
constructor TEmail.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOnUserAbort := nil;
FOnMapiError := nil;
FOnSuccess := nil;
FSubject := '';
FMailtext := '';
FFromName := '';
FFromAdress := '';
FTOAdr := TStringList.Create;
FCCAdr := TStringList.Create;
FBCCAdr := TStringList.Create;
FAttachedFileName := TStringList.Create;
FDisplayFileName := TStringList.Create;
FShowDialog := False;
ApplicationHandle := Application.Handle;
end;
{ +> Changes by Eugene Mayevski [mailto:Mayevski@eldos.org]}
procedure TEmail.SetToAddr(newValue: TStrings);
begin
FToAdr.Assign(newValue);
end;
procedure TEmail.SetCCAddr(newValue: TStrings);
begin
FCCAdr.Assign(newValue);
end;
procedure TEmail.SetBCCAddr(newValue: TStrings);
begin
FBCCAdr.Assign(newValue);
end;
procedure TEmail.SetAttachedFileName(newValue: TStrings);
begin
FAttachedFileName.Assign(newValue);
end;
{ +< Changes }
destructor TEmail.Destroy;
begin
FTOAdr.Free;
FCCAdr.Free;
FBCCAdr.Free;
FAttachedFileName.Free;
FDisplayFileName.Free;
inherited destroy;
end;
{ Reset the fields for re-use}
procedure TEmail.Reset;
begin
FSubject := '';
FMailtext := '';
FFromName := '';
FFromAdress := '';
FTOAdr.Clear;
FCCAdr.Clear;
FBCCAdr.Clear;
FAttachedFileName.Clear;
FDisplayFileName.Clear;
end;
{ Send the Mail via the API, this procedure composes and sends
the Email }
procedure TEmail.Sendmail;
var
MapiMessage: TMapiMessage;
MError: Cardinal;
Sender: TMapiRecipDesc;
PRecip, Recipients: PMapiRecipDesc;
PFiles, Attachments: PMapiFileDesc;
i: Integer;
AppHandle: THandle;
begin
{ First we store the Application Handle, if not
the Component might fail to send the Email or
your calling Program gets locked up. }
AppHandle := Application.Handle;
{ Initialize the Attachment Pointer, to keep Delphi quiet }
PFiles := nil;
{ We need all recipients to alloc the memory }
MapiMessage.nRecipCount := FTOAdr.Count + FCCAdr.Count + FBCCAdr.Count;
GetMem(Recipients, MapiMessage.nRecipCount * sizeof(TMapiRecipDesc));
try
with MapiMessage do
begin
ulReserved := 0;
{ Setting the Subject: }
lpszSubject := PChar(Self.FSubject);
{ ... the Body: }
lpszNoteText := PChar(FMailText);
lpszMessageType := nil;
lpszDateReceived := nil;
lpszConversationID := nil;
flFlags := 0;
{ and the sender: (MAPI_ORIG) }
Sender.ulReserved := 0;
Sender.ulRecipClass := MAPI_ORIG;
Sender.lpszName := PChar(FromName);
Sender.lpszAddress := PChar(FromAdress);
Sender.ulEIDSize := 0;
Sender.lpEntryID := nil;
lpOriginator := @Sender;
PRecip := Recipients;
{ We have multiple recipients: (MAPI_TO)
and setting up each: }
if nRecipCount > 0 then
begin
for i := 1 to FTOAdr.Count do
begin
PRecip^.ulReserved := 0;
PRecip^.ulRecipClass := MAPI_TO;
{ lpszName should carry the Name like in the
contacts or the adress book, I will take the
email adress to keep it short: }
PRecip^.lpszName := PChar(FTOAdr.Strings[i - 1]);
{ If you use this component with Outlook97 or 2000
and not some of Express versions you will have to set
'SMTP:' in front of each (email-) adress. Otherwise
Outlook/Mapi will try to handle the Email on itself.
Sounds strange, just erease the 'SMTP:', compile, compose
a mail and take a look at the resulting email adresses
(right click).
}
{ +> Changes by Andreas Hoerig [mailto:andreas.hoerig@sillner.com] }
PRecip^.lpszAddress := StrNew(PChar('SMTP:' + FTOAdr.Strings[i - 1]));
{ +< Changes }
PRecip^.ulEIDSize := 0;
PRecip^.lpEntryID := nil;
Inc(PRecip);
end;
{ Same with the carbon copy recipients: (CC, MAPI_CC) }
for i := 1 to FCCAdr.Count do
begin
PRecip^.ulReserved := 0;
PRecip^.ulRecipClass := MAPI_CC;
PRecip^.lpszName := PChar(FCCAdr.Strings[i - 1]);
{ +> Changes by Andreas Hoerig [mailto:andreas.hoerig@sillner.com] }
PRecip^.lpszAddress := StrNew(PChar('SMTP:' + FCCAdr.Strings[i - 1]));
{ +< Changes }
PRecip^.ulEIDSize := 0;
PRecip^.lpEntryID := nil;
Inc(PRecip);
end;
{ ... and the blind copy recipients: (BCC, MAPI_BCC) }
for i := 1 to FBCCAdr.Count do
begin
PRecip^.ulReserved := 0;
PRecip^.ulRecipClass := MAPI_BCC;
PRecip^.lpszName := PChar(FBCCAdr.Strings[i - 1]);
{ +> Changes by Andreas Hoerig [mailto:andreas.hoerig@sillner.com] }
PRecip^.lpszAddress := StrNew(PChar('SMTP:' + FBCCAdr.Strings[i - 1]));
{ +< Changes }
PRecip^.ulEIDSize := 0;
PRecip^.lpEntryID := nil;
Inc(PRecip);
end;
end;
lpRecips := Recipients;
{ Now we process the attachments: }
nFileCount := FAttachedFileName.Count;
if nFileCount > 0 then
begin
GetMem(Attachments, nFileCount * sizeof(TMapiFileDesc));
PFiles := Attachments;
{ Fist setting up the display names (without path): }
FDisplayFileName.Clear;
for i := 1 to FAttachedFileName.Count do
FDisplayFileName.Add(ExtractFileName(FAttachedFileName[i - 1]));
if nFileCount > 0 then
begin
{ Now we pass the attached file (their paths) to the
structure: }
for i := 1 to FAttachedFileName.Count do
begin
{ Setting the complete Path }
Attachments^.lpszPathName := PChar(FAttachedFileName.Strings[i - 1]);
{ ... and the displayname: }
Attachments^.lpszFileName := PChar(FDisplayFileName.Strings[i - 1]);
Attachments^.ulReserved := 0;
Attachments^.flFlags := 0;
{ Position has to be -1, please see the WinApi Help
for details. }
Attachments^.nPosition := Cardinal(-1);
Attachments^.lpFileType := nil;
Inc(Attachments);
end;
end;
lpFiles := PFiles;
end
else
begin
nFileCount := 0;
lpFiles := nil;
end;
end;
{ Send the Mail, silent or verbose:
Verbose means in Express a Mail is composed and shown as setup.
In non-Express versions we show the Login-Dialog for a new
session and after we have choosen the profile to use, the
composed email is shown before sending
Silent does currently not work for non-Express version. We have
no Session, no Login Dialog so the system refuses to compose a
new email. In Express Versions the email is sent in the
background.
Please Note: It seems that your success on the delivery depends
on a combination of MAPI-Flags (MAPI_DIALOG, MAPI_LOGON_UI, ...)
and your used OS and Office Version. I am currently using
Win2K SP1 and Office 2K SP2 with no problems at all.
If you experience problems on another versions, please try
a different combination of flags for each purpose (Dialog or not).
I would be glad to setup a table with working flags on
each OS/Office combination, just drop me a line.
Possible combinations are also (with Dialog):
1. MAPI_DIALOG or MAPI_LOGON_UI MAPI_NEW_SESSION or MAPI_USE_DEFAULT
2. MAPI_SIMPLE_DEFAULT
See MAPI.PAS or MAPI.H (SDK) for more...
}
if FShowDialog then
MError := MapiSendMail(0, AppHandle, MapiMessage, MAPI_DIALOG or MAPI_LOGON_UI or MAPI_NEW_SESSION, 0)
else
MError := MapiSendMail(0, AppHandle, MapiMessage, 0, 0);
{ Now we have to process the error messages. There are some
defined in the MAPI unit please take a look at the unit to get
familiar with it.
I decided to handle USER_ABORT and SUCCESS as special and leave
the rest to fire the "new" error event defined at the top (as
generic error)
Not treated as special (constants from mapi.pas):
MAPI_E_FAILURE = 2;
MAPI_E_LOGON_FAILURE = 3;
MAPI_E_LOGIN_FAILURE = MAPI_E_LOGON_FAILURE;
MAPI_E_DISK_FULL = 4;
MAPI_E_INSUFFICIENT_MEMORY = 5;
MAPI_E_ACCESS_DENIED = 6;
MAPI_E_TOO_MANY_SESSIONS = 8;
MAPI_E_TOO_MANY_FILES = 9;
MAPI_E_TOO_MANY_RECIPIENTS = 10;
MAPI_E_ATTACHMENT_NOT_FOUND = 11;
MAPI_E_ATTACHMENT_OPEN_FAILURE = 12;
MAPI_E_ATTACHMENT_WRITE_FAILURE = 13;
MAPI_E_UNKNOWN_RECIPIENT = 14;
MAPI_E_BAD_RECIPTYPE = 15;
MAPI_E_NO_MESSAGES = 16;
MAPI_E_INVALID_MESSAGE = 17;
MAPI_E_TEXT_TOO_LARGE = 18;
MAPI_E_INVALID_SESSION = 19;
MAPI_E_TYPE_NOT_SUPPORTED = 20;
MAPI_E_AMBIGUOUS_RECIPIENT = 21;
MAPI_E_AMBIG_RECIP = MAPI_E_AMBIGUOUS_RECIPIENT;
MAPI_E_MESSAGE_IN_USE = 22;
MAPI_E_NETWORK_FAILURE = 23;
MAPI_E_INVALID_EDITFIELDS = 24;
MAPI_E_INVALID_RECIPS = 25;
MAPI_E_NOT_SUPPORTED = 26;
}
case MError of
MAPI_E_USER_ABORT:
begin
if Assigned(FOnUserAbort) then
FOnUserAbort(Self);
end;
SUCCESS_SUCCESS:
begin
if Assigned(FOnSuccess) then
FOnSuccess(Self);
end
else
begin
if Assigned(FOnMapiError) then
FOnMapiError(Self, MError);
end;
end;
finally
{ Finally we do the cleanups, the message should be on its way }
{ +> Changes by Andreas Hoerig [mailto:andreas.hoerig@sillner.com] }
PRecip := Recipients;
for i := 1 to MapiMessage.nRecipCount do
begin
StrDispose(PRecip^.lpszAddress);
Inc(PRecip)
end;
{ +< Changes }
FreeMem(Recipients, MapiMessage.nRecipCount * sizeof(TMapiRecipDesc));
{ +> Changes due to Ken Halliwell [mailto:kjhalliwell@aol.com] }
if Assigned(PFiles) then
FreeMem(PFiles, MapiMessage.nFileCount * sizeof(TMapiFileDesc));
{ +< Changes }
end;
end;
{
Please treat this as free. If you improve the component
I would be glad to get a copy.
}
end.
|
unit fgrdfuncs; {from GLScene TexTerr}
{A very rudimentary unit to read Arcinfo Grid Ascii format
P.G. Scadden, 26/10/00 P.Scadden@gns.cri.nz}
interface
Type
TGrd = class
pts:array of array of single;
destructor destroy; override;
Public
height,width:integer;
maxz:single;
null:single;
cellsize:single;
originX,OriginY:double;
Procedure Loadfromfile(filename:String);
end;
{
ncols 200
nrows 225
xllcorner 2667000
yllcorner 6033000
cellsize 40
NODATA_value -9999
}
implementation
uses Sysutils, Classes;
Type TCharSet = TSysCharSet;
function WordPosition(const N: Integer; const S: string;
const WordDelims: TCharSet): Integer;
{This function lifted straight out of RXlib}
var
Count, I: Integer;
begin
Count := 0;
I := 1;
Result := 0;
while (I <= Length(S)) and (Count <> N) do begin
{ skip over delimiters }
while (I <= Length(S)) and (S[I] in WordDelims) do Inc(I);
{ if we're not beyond end of S, we're at the start of a word }
if I <= Length(S) then Inc(Count);
{ if not finished, find the end of the current word }
if Count <> N then
while (I <= Length(S)) and not (S[I] in WordDelims) do Inc(I)
else Result := I;
end;
end;
function ExtractWord(N: Integer; const S: string;
const WordDelims: TCharSet): string;
{This function lifted straight out of RXlib}
var
I: Integer;
Len: Integer;
begin
Len := 0;
I := WordPosition(N, S, WordDelims);
if I <> 0 then
{ find the end of the current word }
while (I <= Length(S)) and not(S[I] in WordDelims) do begin
{ add the I'th character to result }
Inc(Len);
SetLength(Result, Len);
Result[Len] := S[I];
Inc(I);
end;
SetLength(Result, Len);
end;
procedure TGrd.Loadfromfile;
var
f:TStringList;
linestring,valstr : String;
row,col:Integer;
i, n:Integer;
function ReadLine : String;
begin
Result:=f[n];
Inc(n);
end;
begin
f := TStringList.create;
f.LoadFromFile(filename);
n:=0;
try
linestring := ReadLine;
width := strtoInt(copy(linestring,6,50));
linestring := ReadLine;
height := strtoInt(copy(linestring,6,50));
linestring := ReadLine;
OriginX := strtofloat(copy(linestring,11,50));
linestring := ReadLine;
{
ncols 200
nrows 225
xllcorner 2667000
yllcorner 6033000
cellsize 40
NODATA_value -9999
}
OriginY := strtofloat(copy(linestring,11,50));
linestring := ReadLine;
cellsize := strtofloat(copy(linestring,11,50));
linestring := ReadLine;
null := strtofloat(copy(linestring,15,50));
setlength(pts,height,width);
row := height - 1;
col := 0;
maxz := -3 * 10E38;
while (n<f.Count) and (row >=0) do
begin
linestring := readline;
i:= 1;
valstr := extractword(i,linestring,[' ']);
while valstr<>'' do
begin
pts [row,col] :=strtofloat(valstr);
if pts[row,col]>maxz then maxz := pts[row,col];
inc(col);
If (col=width) then
begin
dec(row);
col := 0;
end;
inc(i);
valstr := extractword(i,linestring,[' ']);
end;
end;
finally
f.free;
end;
end;
destructor Tgrd.destroy;
begin
pts := nil;
inherited destroy;
end;
end.
|
unit DiscSpec_SpecDiscEdit;
{ Содержит функции:
function AddSpecDisc(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE):Int64;
procedure EditSpecDisc(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AID:Int64);
procedure DeleteSpecDisc(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AID:Int64);
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxTextEdit, cxMaskEdit, cxButtonEdit, cxControls, cxContainer,
cxEdit, cxLabel, cxLookAndFeelPainters, ActnList, StdCtrls, cxButtons,
FIBDatabase, pFIBDatabase, Ibase, FIBQuery, pFIBQuery, pFIBStoredProc, uUO_Resources,
uPrK_Loader, uPrK_Resources, DB,
FIBDataSet, pFIBDataSet, DiscSpec_dmCommonStyles, AArray, uUO_Loader;
type
TfSpecDiscEdit = class(TForm)
SpecLabel: TcxLabel;
SpecBE: TcxButtonEdit;
DiscLabel: TcxLabel;
DiscBE: TcxButtonEdit;
OkButton: TcxButton;
ActionList1: TActionList;
OkAction: TAction;
CancelAction: TAction;
CancelButton: TcxButton;
DB: TpFIBDatabase;
Transaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
StoredProc: TpFIBStoredProc;
DSet: TpFIBDataSet;
procedure SpecBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure DiscBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure OkActionExecute(Sender: TObject);
procedure CancelActionExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
pID_SPEC:Int64;
pID_DISC:Int64;
pID_NAKAZ:Int64;
pRejim:UORejim;
public
{ Public declarations }
pID_DISC_SPEC:Int64;
constructor Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;ARejim:UORejim; AID:Int64 = -1);reintroduce;
end;
function AddSpecDisc(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE):Int64;
procedure EditSpecDisc(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AID:Int64);
procedure DeleteSpecDisc(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AID:Int64);
implementation
{$R *.dfm}
uses uSpecKlassSprav;
function AddSpecDisc(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE):Int64;
var ViewForm:TfSpecDiscEdit;
begin
Result:=-1;
ViewForm:=TfSpecDiscEdit.Create(AOwner,ADB_HANDLE,uoAdd,-1);
if ViewForm.ShowModal=mrOk then
Result:=ViewForm.pID_DISC_SPEC;
ViewForm.Release;
end;
procedure EditSpecDisc(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AID:Int64);
var ViewForm:TfSpecDiscEdit;
begin
ViewForm:=TfSpecDiscEdit.Create(AOwner,ADB_HANDLE,uoEdit,AID);
ViewForm.ShowModal;
ViewForm.Release;
end;
procedure DeleteSpecDisc(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AID:Int64);
var ViewForm:TfSpecDiscEdit;
begin
ViewForm:=TfSpecDiscEdit.Create(AOwner,ADB_HANDLE,uoDelete,AID);
if prkMessageDlg('Видалення','Ви дійсно бажаєте видалити запис?',mtConfirmation,[mbYes,mbNo],0)=mrYes then
ViewForm.OkActionExecute(nil);
ViewForm.Release;
end;
constructor TfSpecDiscEdit.Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;ARejim:UORejim;AID:Int64 = -1);
begin
inherited Create(AOwner);
DB.Handle:=ADB_HANDLE;
Transaction.Active:=True;
pID_DISC_SPEC:=AID;
pRejim:=ARejim;
pID_NAKAZ:=-1;
pID_SPEC:=-1;
pID_DISC:=-1;
Caption:=GetEditCaption(pRejim);
if (pID_DISC_SPEC<>-1) and (pRejim=uoEdit) then
begin
if DSet.Active then DSet.Close;
DSet.SQLs.SelectSQL.Text:='SELECT * FROM UO_SP_DISC_SPEC_S_BY_ID('+IntToStr(pID_DISC_SPEC)+')';
DSet.Open;
pID_SPEC:=DSet['ID_SP_SPEC'];
pID_DISC:=DSet['ID_SP_DISC'];
SpecBE.Text:=DSet['NAME_SPEC'];
DiscBE.Text:=DSet['NAME_DISC'];
pID_NAKAZ:=DSet['ID_SP_DISC_SPEC_NAKAZ'];
end;
end;
procedure TfSpecDiscEdit.SpecBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
{var
AParameter:TcnSimpleParams;
Res :variant;
begin
AParameter := TcnSimpleParams.Create;
AParameter.Owner := self;
AParameter.Db_Handle := DB.Handle;
AParameter.Formstyle := fsNormal;
AParameter.WaitPakageOwner:= self;
AParameter.DontShowGroups := False;
Res:=RunFunctionFromPackage(AParameter, 'Contracts\cn_sp_FacultySpecGroup.bpl','ShowSPFacSpecGroup');
AParameter.Free;
if VarArrayDimCount(res) > 0 then
begin
if ((Res[0]<>Null) and (Res[1]<>Null)) then
begin
pID_SPEC:=Res[1];
SpecBE.Text := Res[4];
end;
end;
end; }
var Res:Variant;
begin
Res:=uSpecKlassSprav.ViewPubSpUspec(Self,DB.Handle,fsNormal);
if VarArrayDimCount(Res) > 0 then
begin
pID_SPEC:=Res[0];
SpecBE.Text:=Res[1];
end;
end;
procedure TfSpecDiscEdit.DiscBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
InputParam : TAArray;
Res:Variant;
begin
InputParam := TAArray.Create;
InputParam['Name_Bpl'].AsString := 'UO_SP_DISC.bpl';
InputParam['Input']['aDBHANDLE'].AsInteger := Integer(DB.Handle);
// InputParam['Input']['id_user'].AsInteger := -1;
InputParam['Input']['aFrmStyle'].AsVariant := fsNormal;
// InputParam['Input']['GodNabora'].AsInt64 := God_Nabora;
// InputParam['Input']['ID_USER_GLOBAL'].AsInt64 := ID_USER_GLOBAL;
{ Res:=}uUO_Loader.ShowAllUOBpl(self, InputParam);
if not VarIsNull(InputParam['OutPut']['ID_SP_DISC'].AsVariant) then
begin
pID_DISC:=InputParam['OutPut']['ID_SP_DISC'].AsInt64;
DiscBE.Text:=InputParam['OutPut']['NAME'].AsString;
end;
end;
procedure TfSpecDiscEdit.OkActionExecute(Sender: TObject);
begin
try
StoredProc.Transaction.StartTransaction;
if (pRejim<>uoDelete) and ((pID_SPEC=-1) or (pID_DISC=-1)) then
begin
prkMessageDlg('Увага','Не всі поля заповнені',mtInformation,[mbOK],0);
Exit;
end;
case pRejim of
uoAdd:begin
StoredProc.StoredProcName:='UO_SP_DISC_SPEC_I';
StoredProc.Prepare;
StoredProc.ParamByName('ID_SP_SPEC').AsInt64:=pID_SPEC;
StoredProc.ParamByName('ID_SP_DISC').AsInt64:=pID_DISC;
StoredProc.ParamByName('ID_SP_DISC_SPEC_NAKAZ').AsInt64:=pID_NAKAZ;
StoredProc.ExecProc;
pID_DISC_SPEC:=StoredProc.FN('ID_OUT').AsInt64;
end;
uoEdit:begin
StoredProc.StoredProcName:='UO_SP_DISC_SPEC_U';
StoredProc.Prepare;
StoredProc.ParamByName('ID_SP_DISC_SPEC').AsInt64:=pID_DISC_SPEC;
StoredProc.ParamByName('ID_SP_SPEC').AsInt64:=pID_SPEC;
StoredProc.ParamByName('ID_SP_DISC').AsInt64:=pID_DISC;
StoredProc.ParamByName('ID_SP_DISC_SPEC_NAKAZ').AsInt64:=pID_NAKAZ;
StoredProc.ExecProc;
end;
uoDelete:begin
StoredProc.StoredProcName:='UO_SP_DISC_SPEC_D';
StoredProc.Prepare;
StoredProc.ParamByName('ID_SP_DISC_SPEC').AsInt64:=pID_DISC_SPEC;
StoredProc.ExecProc;
end;
end;
StoredProc.Transaction.Commit;
ModalResult:=mrOk;
except
on E:Exception do
begin
StoredProc.Transaction.Rollback;
prkMessageDlg('Помилка',E.Message,mtError,[mbOK],0);
end;
end;
end;
procedure TfSpecDiscEdit.CancelActionExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TfSpecDiscEdit.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Transaction.Active:=False;
end;
end.
|
unit Unit1;
{The transparent form effect is done with Regions.
First create a region that encompasses the entire form.
Then, find the client area of the form (Client vs. non-Client) and
combine with the full region with RGN_DIFF to make the borders
and title bar visible. Then create a region for each of the
controls and combine them with the original (FullRgn) region.}
{From various posts in the newsgroups - based on some famous
author I'm sure, but I first saw the post by Kerstin Thaler...}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Panel1: TPanel;
Button2: TButton;
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
procedure DoVisible;
procedure DoInvisible;
public
{ Public declarations }
end;
var
Form1: TForm1;
FullRgn, ClientRgn, CtlRgn : THandle;
implementation
{$R *.DFM}
procedure TForm1.DoInvisible;
var
AControl : TControl;
A, Margin, X, Y, CtlX, CtlY : Integer;
begin
Margin := ( Width - ClientWidth ) div 2;
//First, get form region
FullRgn := CreateRectRgn(0, 0, Width, Height);
//Find client area region
X := Margin;
Y := Height - ClientHeight - Margin;
ClientRgn := CreateRectRgn( X, Y, X + ClientWidth, Y + ClientHeight );
//'Mask' out all but non-client areas
CombineRgn( FullRgn, FullRgn, ClientRgn, RGN_DIFF );
//Now, walk through all the controls on the form and 'OR' them
// into the existing Full region.
for A := 0 to ControlCount - 1 do begin
AControl := Controls[A];
if ( AControl is TWinControl ) or ( AControl is TGraphicControl )
then with AControl do begin
if Visible then begin
CtlX := X + Left;
CtlY := Y + Top;
CtlRgn := CreateRectRgn( CtlX, CtlY, CtlX + Width, CtlY + Height );
CombineRgn( FullRgn, FullRgn, CtlRgn, RGN_OR );
end;
end;
end;
//When the region is all ready, put it into effect:
SetWindowRgn(Handle, FullRgn, TRUE);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
//Clean up the regions we created
DeleteObject(ClientRgn);
DeleteObject(FullRgn);
DeleteObject(CtlRgn);
end;
procedure TForm1.DoVisible;
begin
//To restore complete visibility:
FullRgn := CreateRectRgn(0, 0, Width, Height);
CombineRgn(FullRgn, FullRgn, FullRgn, RGN_COPY);
SetWindowRgn(Handle, FullRgn, TRUE);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
//We start out as a transparent form....
DoInvisible;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
//This button just toggles between transparent and not trans..
if Button1.Caption = 'Show Form' then begin
DoVisible;
Button1.Caption := 'Hide Form';
end
else begin
DoInvisible;
Button1.Caption := 'Show Form';
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Application.Terminate;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
//Need to address the transparency if the form gets re-sized.
//Also, note that Form1 scroll bars are set to VISIBLE/FALSE.
//I did that to save a little coding here....
if Button1.Caption = 'Show Form' then
DoInvisible
else
DoVisible;
end;
end.
|
unit config;
{$include def.mor}
interface
Uses Classes,masks,stuff,Winsock,SysUtils{$ifdef debug},logger{$endif};
Type
Tuser = packed record
Name:string[10];
Mask:string[50];
Logged:Boolean;
end;
TData = packed record
BOT_CHANNAL:STRING[10];
BOT_NICK_PREFIX:String[5];
BOT_COMMAND_PREFIX:Char;
BOT_As_Service,BOT_As_Reg,BOT_LOOKUPADRESSS:Boolean;
BOT_Service_Name:AnsiString;
BOT_Service_Info:AnsiString;
BOT_RemoteIP,BOT_LocalIP:string[15];
FTP_User,FTP_Pass:String[8];
SCAN_TimeOut:smallint;
BOT_NICK:String[50];
Servers:Array of string;
Users:array of Tuser;
dScannerPorts:array of smallint;
end;
Var Data:TData;
WSAData:TWSAData;
Function Find_User(Const User,maskk:string):Smallint;
Procedure Login_User(A:Smallint);
Procedure Logout_User(A:Smallint);
Function IsLogIn_User(A:Smallint):Boolean;
Procedure InitConfig;
implementation
Uses ftp;
Procedure Add_User(const user,maskk:string);
begin
SetLength(Data.Users,Length(Data.Users)+1);
Data.Users[length(Data.Users)-1].Name:=user;
Data.Users[length(Data.Users)-1].Mask:=maskk;
Data.Users[length(Data.Users)-1].Logged:=false;
end;
Procedure Login_User(A:Smallint);
begin
Data.Users[a].Logged:=true;
end;
Procedure Logout_User(A:Smallint);
begin
Data.Users[a].Logged:=false;
end;
Function IsLogIn_User(A:Smallint):Boolean;
begin
Result:=Data.Users[a].Logged;
end;
Function Find_User(Const User,maskk:string):Smallint;
var i:smallint;
begin
Result:=-1;
for i:=0 to length(data.Users)-1 do
if (user = data.Users[i].Name) and MatchesMask(Maskk,Data.users[i].mask) then result:=i;
end;
Procedure Add_Server(Const Address:string;Port:word);
begin
Setlength(Data.Servers,length(Data.servers)+1);
Data.Servers[length(Data.servers)-1]:=Address + #58 + Inttostr(Port);
end;
Procedure InitConfig;
begin
// Users
add_User('god','*');
// Servers
add_server('irc.efnet.nl',6667);
// Main
Data.BOT_NICK_PREFIX:='Mama';
DATA.BOT_CHANNAL:='#joinhere';
Data.BOT_COMMAND_PREFIX:='!';
Data.BOT_As_Service:=false;
Data.BOT_As_Reg:=true;
data.BOT_Service_Name:='IDF';
Data.BOT_Service_Info:='Test Service';
Data.SCAN_TimeOut:=1; // 1000ms
DATA.BOT_LOOKUPADRESSS:=TRUE;
DATA.FTP_User:='Test';
DATA.FTP_Pass:='Test';
Setlength(Data.dScannerPorts,4);
Data.dScannerPorts[0]:=1433;
Data.dScannerPorts[1]:=139;
Data.dScannerPorts[2]:=135;
Data.dScannerPorts[3]:=445;
{$ifdef debug}
AddToMessageLog('[DEBUG] CONFIG INIT <OK>');
{$endif}
// Load WinSock 1.1
if WSAStartup($101, WSAData) = 0 then
begin
{$ifdef debug}
AddToMessageLog('[DEBUG] WINSOCK 1.1 INIT <OK>');
{$endif}
Data.BOT_RemoteIP:='NONE'; // DO NOT CHANGE
Data.BOT_LocalIP:=GetLocalIP;
// INIT FTP
FTP.run;
end
else
begin
{$ifdef debug}
AddToMessageLog('[DEBUG] WINSOCK 1.1 INIT <NOT OK>');
{$endif}
halt;
end
end;
begin
end.
|
unit uEncontro;
interface
uses System.Classes, System.SysUtils;
type
TEncontro = class
private
FNomePessoa: string;
FModelo: string;
FNumeroFicha: Integer;
FAno: Integer;
FLetra: string;
public
property Letra: string read FLetra write FLetra;
property NomePessoa: string read FNomePessoa write FNomePessoa;
property Modelo: string read FModelo write FModelo;
property Ano: Integer read FAno write FAno;
property NumeroFicha: Integer read FNumeroFicha write FNumeroFicha;
end;
implementation
end.
|
unit TrayIconEx;
interface
uses
Windows, Messages, ShellApi, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, Menus;
const
WM_CALLBACK_MESSAGE = WM_USER + 55;
type
TTrayIconEx = class(TComponent)
private
fData: TNotifyIconData;
fIcon: TIcon;
fHint: string;
fPopupMenu: TPopupMenu;
fClicked: Boolean;
fOnClick: TNotifyEvent;
fOnDblClick: TNotifyEvent;
fOnMinimize: TNotifyEvent;
fOnMouseMove: TMouseMoveEvent;
fOnMouseDown: TMouseEvent;
fOnMouseUp: TMouseEvent;
fOnRestore: TNotifyEvent;
protected
procedure SetHint(const Hint: string); virtual;
procedure SetIcon(Icon: TIcon); virtual;
procedure AppMinimize(Sender: TObject);
procedure AppRestore(Sender: TObject);
procedure DoMenu; virtual;
procedure Click; virtual;
procedure DblClick; virtual;
procedure EndSession; virtual;
procedure DoMouseMove(Shift: TShiftState; X, Y: Integer); virtual;
procedure DoMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
virtual;
procedure DoMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
virtual;
procedure OnMessage(var Msg: TMessage); virtual;
procedure Changed; virtual;
property Data: TNotifyIconData read fData;
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
procedure Minimize; virtual;
procedure Restore; virtual;
published
property Hint: string read fHint write SetHint;
property Icon: TIcon read fIcon write SetIcon;
property PopupMenu: TPopupMenu read fPopupMenu write fPopupMenu;
property OnClick: TNotifyEvent read fOnClick write fOnClick;
property OnDblClick: TNotifyEvent read fOnDblClick write fOnDblClick;
property OnMinimize: TNotifyEvent read fOnMinimize write fOnMinimize;
property OnMouseMove: TMouseMoveEvent read fOnMouseMove write fOnMouseMove;
property OnMouseDown: TMouseEvent read fOnMouseDown write fOnMouseDown;
property OnMouseUp: TMouseEvent read fOnMouseUp write fOnMouseUp;
property OnRestore: TNotifyEvent read fOnRestore write fOnRestore;
end;
implementation
{
Create the component. At run-time, automatically add a tray icon
with a callback to a hidden window. Use the application icon and title.
}
constructor TTrayIconEx.Create(Owner: TComponent);
begin
inherited Create(Owner);
fIcon := TIcon.Create;
fIcon.Assign(Application.Icon);
if not (csDesigning in ComponentState) then
begin
FillChar(fData, SizeOf(fData), 0);
fData.cbSize := SizeOf(fData);
fData.Wnd := AllocateHwnd(OnMessage); // handle to get notification message
fData.hIcon := Icon.Handle; // icon to display
StrPLCopy(fData.szTip, Application.Title, SizeOf(fData.szTip) - 1);
fData.uFlags := Nif_Icon or Nif_Message;
if Application.Title <> '' then
fData.uFlags := fData.uFlags or Nif_Tip;
fData.uCallbackMessage := WM_CALLBACK_MESSAGE;
if not Shell_NotifyIcon(NIM_ADD, @fData) then // add it
raise EOutOfResources.Create('Cannot create shell notification icon');
{
Replace the application's minimize and restore handlers with
special ones for the tray. The TrayIconEx component has its own
OnMinimize and OnRestore events that the user can set.
}
Application.OnMinimize := AppMinimize;
Application.OnRestore := AppRestore;
end;
end;
{ Remove the icon from the system tray.}
destructor TTrayIconEx.Destroy;
begin
fIcon.Free;
if not (csDesigning in ComponentState) then
Shell_NotifyIcon(Nim_Delete, @fData);
inherited Destroy;
end;
{ Whenever any information changes, update the system tray. }
procedure TTrayIconEx.Changed;
begin
if not (csDesigning in ComponentState) then
Shell_NotifyIcon(NIM_MODIFY, @fData);
end;
{ When the Application is minimized, minimize to the system tray.}
procedure TTrayIconEx.AppMinimize(Sender: TObject);
begin
Minimize
end;
{ When restoring from the system tray, restore the application. }
procedure TTrayIconEx.AppRestore(Sender: TObject);
begin
Restore
end;
{
Message handler for the hidden shell notification window.
Most messages use Wm_Callback_Message as the Msg ID, with
WParam as the ID of the shell notify icon data. LParam is
a message ID for the actual message, e.g., Wm_MouseMove.
Another important message is Wm_EndSession, telling the
shell notify icon to delete itself, so Windows can shut down.
Send the usual Delphi events for the mouse messages. Also
interpolate the OnClick event when the user clicks the
left button, and popup the menu, if there is one, for
right click events.
}
procedure TTrayIconEx.OnMessage(var Msg: TMessage);
{ Return the state of the shift keys. }
function ShiftState: TShiftState;
begin
Result := [];
if GetKeyState(VK_SHIFT) < 0 then
Include(Result, ssShift);
if GetKeyState(VK_CONTROL) < 0 then
Include(Result, ssCtrl);
if GetKeyState(VK_MENU) < 0 then
Include(Result, ssAlt);
end;
var
Pt: TPoint;
Shift: TShiftState;
begin
case Msg.Msg of
Wm_QueryEndSession:
Msg.Result := 1;
Wm_EndSession:
if TWmEndSession(Msg).EndSession then
EndSession;
Wm_Callback_Message:
case Msg.lParam of
WM_MOUSEMOVE:
begin
Shift := ShiftState;
GetCursorPos(Pt);
DoMouseMove(Shift, Pt.X, Pt.Y);
end;
WM_LBUTTONDOWN:
begin
Shift := ShiftState + [ssLeft];
GetCursorPos(Pt);
DoMouseDown(mbLeft, Shift, Pt.X, Pt.Y);
fClicked := True;
end;
WM_LBUTTONUP:
begin
Shift := ShiftState + [ssLeft];
GetCursorPos(Pt);
if fClicked then
begin
fClicked := False;
Click;
end;
DoMouseUp(mbLeft, Shift, Pt.X, Pt.Y);
end;
WM_LBUTTONDBLCLK:
DblClick;
WM_RBUTTONDOWN:
begin
Shift := ShiftState + [ssRight];
GetCursorPos(Pt);
DoMouseDown(mbRight, Shift, Pt.X, Pt.Y);
DoMenu;
end;
WM_RBUTTONUP:
begin
Shift := ShiftState + [ssRight];
GetCursorPos(Pt);
DoMouseUp(mbRight, Shift, Pt.X, Pt.Y);
end;
WM_RBUTTONDBLCLK:
DblClick;
WM_MBUTTONDOWN:
begin
Shift := ShiftState + [ssMiddle];
GetCursorPos(Pt);
DoMouseDown(mbMiddle, Shift, Pt.X, Pt.Y);
end;
WM_MBUTTONUP:
begin
Shift := ShiftState + [ssMiddle];
GetCursorPos(Pt);
DoMouseUp(mbMiddle, Shift, Pt.X, Pt.Y);
end;
WM_MBUTTONDBLCLK:
DblClick;
end;
end;
end;
{ Set a new hint, which is the tool tip for the shell icon. }
procedure TTrayIconEx.SetHint(const Hint: string);
begin
if fHint <> Hint then
begin
fHint := Hint;
StrPLCopy(fData.szTip, Hint, SizeOf(fData.szTip) - 1);
if Hint <> '' then
fData.uFlags := fData.uFlags or Nif_Tip
else
fData.uFlags := fData.uFlags and not Nif_Tip;
Changed;
end;
end;
{ Set a new icon. Update the system tray. }
procedure TTrayIconEx.SetIcon(Icon: TIcon);
begin
if fIcon <> Icon then
begin
fIcon.Assign(Icon);
fData.hIcon := Icon.Handle;
Changed;
end;
end;
{
When the user right clicks the icon, call DoMenu.
If there is a popup menu, and if the window is minimized,
then popup the menu.
}
procedure TTrayIconEx.DoMenu;
var
Pt: TPoint;
begin
if (fPopupMenu <> nil) and not IsWindowVisible(Application.Handle) then
begin
GetCursorPos(Pt);
fPopupMenu.Popup(Pt.X, Pt.Y);
end;
end;
procedure TTrayIconEx.Click;
begin
if Assigned(fOnClick) then
fOnClick(Self);
end;
procedure TTrayIconEx.DblClick;
begin
if Assigned(fOnDblClick) then
fOnDblClick(Self);
end;
procedure TTrayIconEx.DoMouseMove(Shift: TShiftState; X, Y: Integer);
begin
if Assigned(fOnMouseMove) then
fOnMouseMove(Self, Shift, X, Y);
end;
procedure TTrayIconEx.DoMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Assigned(fOnMouseDown) then
fOnMouseDown(Self, Button, Shift, X, Y);
end;
procedure TTrayIconEx.DoMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Assigned(fOnMouseUp) then
fOnMouseUp(Self, Button, Shift, X, Y);
end;
{
When the application minimizes, hide it, so only the icon
in the system tray is visible.
}
procedure TTrayIconEx.Minimize;
begin
ShowWindow(Application.Handle, SW_HIDE);
if Assigned(fOnMinimize) then
fOnMinimize(Self);
end;
{
Restore the application by making its window visible again,
which is a little weird since its window is invisible, having
no height or width, but that's what determines whether the button
appears on the taskbar.
}
procedure TTrayIconEx.Restore;
begin
ShowWindow(Application.Handle, SW_RESTORE);
if Assigned(fOnRestore) then
fOnRestore(Self);
end;
{ Allow Windows to exit by deleting the shell notify icon. }
procedure TTrayIconEx.EndSession;
begin
Shell_NotifyIcon(Nim_Delete, @fData);
end;
end.
|
{*******************************************************}
{ }
{ hHelperFunc.pas
{ Copyright @2014/5/20 16:06:03 by 姜梁
{ }
{ 功能描述:
{ 函数说明:
{*******************************************************}
unit hHelperFunc;
interface
uses
Windows, Classes,SysUtils,Registry;
function GetAllDiskName():TStrings;
function GetType():TStrings;
function GetSkip():TStrings;
function GetPriorStr(Str,keyStr:string):string;
function GetFileNum(temp:string):Double;
function GetTypeInReg(typeString:string):string;
implementation
/// <summary>
/// 取得所有系统盘符
/// </summary>
/// <returns>返回盘符字符串</returns>
function GetAllDiskName():TStrings;
var
I: integer;
tempString: string;
DiskList:TStrings;
begin
DiskList:= TStringList.Create;
for I := 65 to 90 do
begin
//GetDriveType获取盘符信息
//0 驱动器类型不确定
//1 系统目录不存在
//2 DRIVE_REMOVABLE 是可移动驱动器
//3 DRIVE_FIXED 是固定驱动器
//4 DRIVE_REMOTE 是网络驱动器
//5 DRIVE_CDROM 是CD-ROM驱动器
//6 DRIVE_RAMDISK 是虚拟驱动器
tempString:= chr(I) + ':';
if GetDriveType(Pchar(tempString)) = 3 then DiskList.Add(tempString);
end;
Result:= DiskList;
end;
function GetType():TStrings;
var
typestring: TStrings;
begin
typestring:= TStringList.Create;
typestring.Add('.exe');
typestring.Add('.zip');
typestring.Add('.rar');
typestring.Add('.iso');
typestring.Add('.avi');
typestring.Add('.mpg');
typestring.Add('.mp3');
typestring.Add('.mp4');
typestring.Add('.mov');
typestring.Add('.wav');
typestring.Add('.wma');
typestring.Add('.swf');
typestring.Add('.m3u');
typestring.Add('.jpg');
typestring.Add('.gif');
typestring.Add('.png');
typestring.Add('.bmp');
typestring.Add('.txt');
typestring.Add('.wri');
typestring.Add('.rtf');
typestring.Add('.doc');
typestring.Add('.docx');
typestring.Add('.ppt');
typestring.Add('.pptx');
typestring.Add('.xls');
typestring.Add('.xlsx');
typestring.Add('.pdf');
Result:= typestring;
end;
function GetSkip():TStrings;
var
skipstring:TStrings;
begin
skipstring:= TStringList.Create ;
skipstring.Add('C:\Windows');
//skipstring.Add('C:\Windows\System32');
skipstring.Add('C:\Users\Administrator\AppData\Local\Temp');
skipstring.Add('C:\Users\Administrator\AppData\Roaming');
skipstring.Add('C:\ProgramData');
skipstring.Add('C:\Program Files (x86)');
skipstring.Add('C:\Program Files');
Result:= skipstring;
end;
function GetPriorStr(Str,keyStr:string):string;
var
p:Integer; //p表示关键字keyStr在Str中出现的位置
begin
p:=Pos(keyStr,Str)-1;
if p>0
then result:=copy(str,0,p)
else result:=Str;
end;
function GetFileNum(temp:string):Double;
begin
if Pos('G',temp) > 0 then Result:= strtofloat(GetPriorStr(temp,'GB'))*1000*1000
else if Pos('M',temp) >0 then Result:=strtofloat(GetPriorStr(temp,'MB'))*1000
else Result:= strtofloat(GetPriorStr(temp,'KB'));
end;
function GetTypeInReg(typeString:string):string;
var
Reg: TRegistry;
FileType: string;
begin
Reg := TRegistry.Create();
try
Reg.RootKey := HKey_Classes_Root;
if not Reg.OpenKey(typeString, False) then exit;
FileType := Reg.ReadString(''); // 默认值为文件类型
Reg.CloseKey();
if (FileType='') or (not Reg.OpenKey(FileType, False)) then
begin
Result:= typeString;
Exit;
end;
Result := Reg.ReadString(''); //内容类型的具体描述
Reg.CloseKey();
finally
Reg.Free();
end;
end;
end.
|
unit Optimize.Move;
interface
procedure MoveMMX(const Source; var Dest; Count: Integer);
procedure MoveSSE(const Source; var Dest; Count: Integer);
procedure MoveSSE2(const Source; var Dest; Count: Integer);
procedure MoveSSE3(const Source; var Dest; Count: Integer);
implementation
uses
Windows, SysUtils;
{ SIMD Detection code }
type
TSimdInstructionSupport = (sisMMX, sisSSE, sisSSE2, sisSSE3);
TSimdInstructionSupportSet = set of TSimdInstructionSupport;
var
SimdSupported : TSimdInstructionSupportSet;
function GetSupportedSimdInstructionSets : TSimdInstructionSupportSet;
var
rEDX, rECX : Integer;
begin
Result := [];
{ Request the opcode support }
asm
{ Save registers }
PUSH EAX
PUSH EBX
PUSH ECX
PUSH EDX
{ Set the function 1 and clear others }
MOV EAX, $00000001
XOR EBX, EBX
XOR ECX, ECX
XOR EDX, EDX
{ Call CPUID }
CPUID
{ Store the registers we need }
MOV [rEDX], EDX
MOV [rECX], ECX
{ Restore registers }
POP EDX
POP ECX
POP EBX
POP EAX
end;
if ((rECX and 1) <> 0) then
Result := Result + [sisSSE3];
if ((rEDX and (1 shl 23)) <> 0) then
Result := Result + [sisMMX];
if ((rEDX and (1 shl 25)) <> 0) then
Result := Result + [sisSSE];
if ((rEDX and (1 shl 26)) <> 0) then
Result := Result + [sisSSE2];
{
Check if Windows supports XMM registers - run an instruction and check
for exceptions.
}
try
asm
ORPS XMM0, XMM0
end
except
begin
{ Exclude SSE instructions! }
Result := Result - [sisSSE, sisSSE2, sisSSE3];
end;
end;
end;
function PatchMethod(OldMethod, NewMethod : Pointer) : Boolean;
const
SizeOfJump = 5;
var
OldFlags : Cardinal;
__Jump : ^Byte;
__Addr : ^Integer;
begin
Result := False;
try
{ Change the code protection to write }
VirtualProtect(OldMethod, SizeOfJump, PAGE_READWRITE, OldFlags);
except
begin Exit; end;
end;
try
{ Insert the jump instruction }
__Jump := OldMethod;
__Jump^ := $E9;
{ Insert the jump address = (OLD - NEW - SIZEOFJUMP)}
__Addr := Ptr(Integer(OldMethod) + 1);
__Addr^ := Integer(NewMethod) - Integer(OldMethod) - SizeOfJump;
finally
{ Change the protection back to what it was }
VirtualProtect(OldMethod, SizeOfJump, OldFlags, OldFlags);
end;
{ Set status to success }
Result := True;
end;
const
TINYSIZE = 36;
CacheLimit = 1024 * -512;
procedure SmallForwardMove;
asm
jmp dword ptr [@@FwdJumpTable+ecx*4]
nop {Align Jump Table}
@@FwdJumpTable:
dd @@Done {Removes need to test for zero size move}
dd @@Fwd01, @@Fwd02, @@Fwd03, @@Fwd04, @@Fwd05, @@Fwd06, @@Fwd07, @@Fwd08
dd @@Fwd09, @@Fwd10, @@Fwd11, @@Fwd12, @@Fwd13, @@Fwd14, @@Fwd15, @@Fwd16
dd @@Fwd17, @@Fwd18, @@Fwd19, @@Fwd20, @@Fwd21, @@Fwd22, @@Fwd23, @@Fwd24
dd @@Fwd25, @@Fwd26, @@Fwd27, @@Fwd28, @@Fwd29, @@Fwd30, @@Fwd31, @@Fwd32
dd @@Fwd33, @@Fwd34, @@Fwd35, @@Fwd36
@@Fwd36:
mov ecx, [eax-36]
mov [edx-36], ecx
@@Fwd32:
mov ecx, [eax-32]
mov [edx-32], ecx
@@Fwd28:
mov ecx, [eax-28]
mov [edx-28], ecx
@@Fwd24:
mov ecx, [eax-24]
mov [edx-24], ecx
@@Fwd20:
mov ecx, [eax-20]
mov [edx-20], ecx
@@Fwd16:
mov ecx, [eax-16]
mov [edx-16], ecx
@@Fwd12:
mov ecx, [eax-12]
mov [edx-12], ecx
@@Fwd08:
mov ecx, [eax-8]
mov [edx-8], ecx
@@Fwd04:
mov ecx, [eax-4]
mov [edx-4], ecx
ret
nop
@@Fwd35:
mov ecx, [eax-35]
mov [edx-35], ecx
@@Fwd31:
mov ecx, [eax-31]
mov [edx-31], ecx
@@Fwd27:
mov ecx, [eax-27]
mov [edx-27], ecx
@@Fwd23:
mov ecx, [eax-23]
mov [edx-23], ecx
@@Fwd19:
mov ecx, [eax-19]
mov [edx-19], ecx
@@Fwd15:
mov ecx, [eax-15]
mov [edx-15], ecx
@@Fwd11:
mov ecx, [eax-11]
mov [edx-11], ecx
@@Fwd07:
mov ecx, [eax-7]
mov [edx-7], ecx
mov ecx, [eax-4]
mov [edx-4], ecx
ret
nop
@@Fwd03:
movzx ecx, word ptr [eax-3]
mov [edx-3], cx
movzx ecx, byte ptr [eax-1]
mov [edx-1], cl
ret
@@Fwd34:
mov ecx, [eax-34]
mov [edx-34], ecx
@@Fwd30:
mov ecx, [eax-30]
mov [edx-30], ecx
@@Fwd26:
mov ecx, [eax-26]
mov [edx-26], ecx
@@Fwd22:
mov ecx, [eax-22]
mov [edx-22], ecx
@@Fwd18:
mov ecx, [eax-18]
mov [edx-18], ecx
@@Fwd14:
mov ecx, [eax-14]
mov [edx-14], ecx
@@Fwd10:
mov ecx, [eax-10]
mov [edx-10], ecx
@@Fwd06:
mov ecx, [eax-6]
mov [edx-6], ecx
@@Fwd02:
movzx ecx, word ptr [eax-2]
mov [edx-2], cx
ret
nop
nop
nop
@@Fwd33:
mov ecx, [eax-33]
mov [edx-33], ecx
@@Fwd29:
mov ecx, [eax-29]
mov [edx-29], ecx
@@Fwd25:
mov ecx, [eax-25]
mov [edx-25], ecx
@@Fwd21:
mov ecx, [eax-21]
mov [edx-21], ecx
@@Fwd17:
mov ecx, [eax-17]
mov [edx-17], ecx
@@Fwd13:
mov ecx, [eax-13]
mov [edx-13], ecx
@@Fwd09:
mov ecx, [eax-9]
mov [edx-9], ecx
@@Fwd05:
mov ecx, [eax-5]
mov [edx-5], ecx
@@Fwd01:
movzx ecx, byte ptr [eax-1]
mov [edx-1], cl
ret
@@Done:
end;
{-------------------------------------------------------------------------}
{Perform Backward Move of 0..36 Bytes}
{On Entry, ECX = Count, EAX = Source, EDX = Dest. Destroys ECX}
procedure SmallBackwardMove;
asm
jmp dword ptr [@@BwdJumpTable+ecx*4]
nop {Align Jump Table}
@@BwdJumpTable:
dd @@Done {Removes need to test for zero size move}
dd @@Bwd01, @@Bwd02, @@Bwd03, @@Bwd04, @@Bwd05, @@Bwd06, @@Bwd07, @@Bwd08
dd @@Bwd09, @@Bwd10, @@Bwd11, @@Bwd12, @@Bwd13, @@Bwd14, @@Bwd15, @@Bwd16
dd @@Bwd17, @@Bwd18, @@Bwd19, @@Bwd20, @@Bwd21, @@Bwd22, @@Bwd23, @@Bwd24
dd @@Bwd25, @@Bwd26, @@Bwd27, @@Bwd28, @@Bwd29, @@Bwd30, @@Bwd31, @@Bwd32
dd @@Bwd33, @@Bwd34, @@Bwd35, @@Bwd36
@@Bwd36:
mov ecx, [eax+32]
mov [edx+32], ecx
@@Bwd32:
mov ecx, [eax+28]
mov [edx+28], ecx
@@Bwd28:
mov ecx, [eax+24]
mov [edx+24], ecx
@@Bwd24:
mov ecx, [eax+20]
mov [edx+20], ecx
@@Bwd20:
mov ecx, [eax+16]
mov [edx+16], ecx
@@Bwd16:
mov ecx, [eax+12]
mov [edx+12], ecx
@@Bwd12:
mov ecx, [eax+8]
mov [edx+8], ecx
@@Bwd08:
mov ecx, [eax+4]
mov [edx+4], ecx
@@Bwd04:
mov ecx, [eax]
mov [edx], ecx
ret
nop
nop
nop
@@Bwd35:
mov ecx, [eax+31]
mov [edx+31], ecx
@@Bwd31:
mov ecx, [eax+27]
mov [edx+27], ecx
@@Bwd27:
mov ecx, [eax+23]
mov [edx+23], ecx
@@Bwd23:
mov ecx, [eax+19]
mov [edx+19], ecx
@@Bwd19:
mov ecx, [eax+15]
mov [edx+15], ecx
@@Bwd15:
mov ecx, [eax+11]
mov [edx+11], ecx
@@Bwd11:
mov ecx, [eax+7]
mov [edx+7], ecx
@@Bwd07:
mov ecx, [eax+3]
mov [edx+3], ecx
mov ecx, [eax]
mov [edx], ecx
ret
nop
nop
nop
@@Bwd03:
movzx ecx, word ptr [eax+1]
mov [edx+1], cx
movzx ecx, byte ptr [eax]
mov [edx], cl
ret
nop
nop
@@Bwd34:
mov ecx, [eax+30]
mov [edx+30], ecx
@@Bwd30:
mov ecx, [eax+26]
mov [edx+26], ecx
@@Bwd26:
mov ecx, [eax+22]
mov [edx+22], ecx
@@Bwd22:
mov ecx, [eax+18]
mov [edx+18], ecx
@@Bwd18:
mov ecx, [eax+14]
mov [edx+14], ecx
@@Bwd14:
mov ecx, [eax+10]
mov [edx+10], ecx
@@Bwd10:
mov ecx, [eax+6]
mov [edx+6], ecx
@@Bwd06:
mov ecx, [eax+2]
mov [edx+2], ecx
@@Bwd02:
movzx ecx, word ptr [eax]
mov [edx], cx
ret
nop
@@Bwd33:
mov ecx, [eax+29]
mov [edx+29], ecx
@@Bwd29:
mov ecx, [eax+25]
mov [edx+25], ecx
@@Bwd25:
mov ecx, [eax+21]
mov [edx+21], ecx
@@Bwd21:
mov ecx, [eax+17]
mov [edx+17], ecx
@@Bwd17:
mov ecx, [eax+13]
mov [edx+13], ecx
@@Bwd13:
mov ecx, [eax+9]
mov [edx+9], ecx
@@Bwd09:
mov ecx, [eax+5]
mov [edx+5], ecx
@@Bwd05:
mov ecx, [eax+1]
mov [edx+1], ecx
@@Bwd01:
movzx ecx, byte ptr[eax]
mov [edx], cl
ret
@@Done:
end;
{-------------------------------------------------------------------------}
{Move ECX Bytes from EAX to EDX, where EAX > EDX and ECX > 36 (TINYSIZE)}
procedure Forwards_IA32;
asm
fild qword ptr [eax] {First 8}
lea eax, [eax+ecx-8]
lea ecx, [edx+ecx-8]
push edx
push ecx
fild qword ptr [eax] {Last 8}
neg ecx {QWORD Align Writes}
and edx, -8
lea ecx, [ecx+edx+8]
pop edx
@@Loop:
fild qword ptr [eax+ecx]
fistp qword ptr [edx+ecx]
add ecx, 8
jl @@Loop
pop eax
fistp qword ptr [edx] {Last 8}
fistp qword ptr [eax] {First 8}
end;
{-------------------------------------------------------------------------}
{Move ECX Bytes from EAX to EDX, where EAX < EDX and ECX > 36 (TINYSIZE)}
procedure Backwards_IA32;
asm
sub ecx, 8
fild qword ptr [eax+ecx] {Last 8}
fild qword ptr [eax] {First 8}
add ecx, edx {QWORD Align Writes}
push ecx
and ecx, -8
sub ecx, edx
@@Loop:
fild qword ptr [eax+ecx]
fistp qword ptr [edx+ecx]
sub ecx, 8
jg @@Loop
pop eax
fistp qword ptr [edx] {First 8}
fistp qword ptr [eax] {Last 8}
end;
{-------------------------------------------------------------------------}
{Move ECX Bytes from EAX to EDX, where EAX > EDX and ECX > 36 (TINYSIZE)}
procedure Forwards_MMX;
const
SMALLSIZE = 64;
LARGESIZE = 2048;
asm
cmp ecx, SMALLSIZE {Size at which using MMX becomes worthwhile}
jl Forwards_IA32
cmp ecx, LARGESIZE
jge @@FwdLargeMove
push ebx
mov ebx, edx
movq mm0, [eax] {First 8 Bytes}
add eax, ecx {QWORD Align Writes}
add ecx, edx
and edx, -8
add edx, 40
sub ecx, edx
add edx, ecx
neg ecx
nop {Align Loop}
@@FwdLoopMMX:
movq mm1, [eax+ecx-32]
movq mm2, [eax+ecx-24]
movq mm3, [eax+ecx-16]
movq mm4, [eax+ecx- 8]
movq [edx+ecx-32], mm1
movq [edx+ecx-24], mm2
movq [edx+ecx-16], mm3
movq [edx+ecx- 8], mm4
add ecx, 32
jle @@FwdLoopMMX
movq [ebx], mm0 {First 8 Bytes}
emms
pop ebx
neg ecx
add ecx, 32
jmp SmallForwardMove
nop {Align Loop}
nop
@@FwdLargeMove:
push ebx
mov ebx, ecx
test edx, 15
jz @@FwdAligned
lea ecx, [edx+15] {16 byte Align Destination}
and ecx, -16
sub ecx, edx
add eax, ecx
add edx, ecx
sub ebx, ecx
call SmallForwardMove
@@FwdAligned:
mov ecx, ebx
and ecx, -16
sub ebx, ecx {EBX = Remainder}
push esi
push edi
mov esi, eax {ESI = Source}
mov edi, edx {EDI = Dest}
mov eax, ecx {EAX = Count}
and eax, -64 {EAX = No of Bytes to Blocks Moves}
and ecx, $3F {ECX = Remaining Bytes to Move (0..63)}
add esi, eax
add edi, eax
neg eax
@@MMXcopyloop:
movq mm0, [esi+eax ]
movq mm1, [esi+eax+ 8]
movq mm2, [esi+eax+16]
movq mm3, [esi+eax+24]
movq mm4, [esi+eax+32]
movq mm5, [esi+eax+40]
movq mm6, [esi+eax+48]
movq mm7, [esi+eax+56]
movq [edi+eax ], mm0
movq [edi+eax+ 8], mm1
movq [edi+eax+16], mm2
movq [edi+eax+24], mm3
movq [edi+eax+32], mm4
movq [edi+eax+40], mm5
movq [edi+eax+48], mm6
movq [edi+eax+56], mm7
add eax, 64
jnz @@MMXcopyloop
emms {Empty MMX State}
add ecx, ebx
shr ecx, 2
rep movsd
mov ecx, ebx
and ecx, 3
rep movsb
pop edi
pop esi
pop ebx
end;
{-------------------------------------------------------------------------}
{Move ECX Bytes from EAX to EDX, where EAX < EDX and ECX > 36 (TINYSIZE)}
procedure Backwards_MMX;
const
SMALLSIZE = 64;
asm
cmp ecx, SMALLSIZE {Size at which using MMX becomes worthwhile}
jl Backwards_IA32
push ebx
movq mm0, [eax+ecx-8] {Get Last QWORD}
lea ebx, [edx+ecx] {QWORD Align Writes}
and ebx, 7
sub ecx, ebx
add ebx, ecx
sub ecx, 32
@@BwdLoopMMX:
movq mm1, [eax+ecx ]
movq mm2, [eax+ecx+ 8]
movq mm3, [eax+ecx+16]
movq mm4, [eax+ecx+24]
movq [edx+ecx+24], mm4
movq [edx+ecx+16], mm3
movq [edx+ecx+ 8], mm2
movq [edx+ecx ], mm1
sub ecx, 32
jge @@BwdLoopMMX
movq [edx+ebx-8], mm0 {Last QWORD}
emms
add ecx, 32
pop ebx
jmp SmallBackwardMove
end;
{-------------------------------------------------------------------------}
procedure LargeAlignedSSEMove;
asm
@@Loop:
movaps xmm0, [eax+ecx]
movaps xmm1, [eax+ecx+16]
movaps xmm2, [eax+ecx+32]
movaps xmm3, [eax+ecx+48]
movaps [edx+ecx], xmm0
movaps [edx+ecx+16], xmm1
movaps [edx+ecx+32], xmm2
movaps [edx+ecx+48], xmm3
movaps xmm4, [eax+ecx+64]
movaps xmm5, [eax+ecx+80]
movaps xmm6, [eax+ecx+96]
movaps xmm7, [eax+ecx+112]
movaps [edx+ecx+64], xmm4
movaps [edx+ecx+80], xmm5
movaps [edx+ecx+96], xmm6
movaps [edx+ecx+112], xmm7
add ecx, 128
js @@Loop
end;
{-------------------------------------------------------------------------}
procedure LargeUnalignedSSEMove;
asm
@@Loop:
movups xmm0, [eax+ecx]
movups xmm1, [eax+ecx+16]
movups xmm2, [eax+ecx+32]
movups xmm3, [eax+ecx+48]
movaps [edx+ecx], xmm0
movaps [edx+ecx+16], xmm1
movaps [edx+ecx+32], xmm2
movaps [edx+ecx+48], xmm3
movups xmm4, [eax+ecx+64]
movups xmm5, [eax+ecx+80]
movups xmm6, [eax+ecx+96]
movups xmm7, [eax+ecx+112]
movaps [edx+ecx+64], xmm4
movaps [edx+ecx+80], xmm5
movaps [edx+ecx+96], xmm6
movaps [edx+ecx+112], xmm7
add ecx, 128
js @@Loop
end;
{-------------------------------------------------------------------------}
procedure HugeAlignedSSEMove;
const
Prefetch = 512;
asm
@@Loop:
prefetchnta [eax+ecx+Prefetch]
prefetchnta [eax+ecx+Prefetch+64]
movaps xmm0, [eax+ecx]
movaps xmm1, [eax+ecx+16]
movaps xmm2, [eax+ecx+32]
movaps xmm3, [eax+ecx+48]
movntps [edx+ecx], xmm0
movntps [edx+ecx+16], xmm1
movntps [edx+ecx+32], xmm2
movntps [edx+ecx+48], xmm3
movaps xmm4, [eax+ecx+64]
movaps xmm5, [eax+ecx+80]
movaps xmm6, [eax+ecx+96]
movaps xmm7, [eax+ecx+112]
movntps [edx+ecx+64], xmm4
movntps [edx+ecx+80], xmm5
movntps [edx+ecx+96], xmm6
movntps [edx+ecx+112], xmm7
add ecx, 128
js @@Loop
sfence
end;
{-------------------------------------------------------------------------}
procedure HugeUnalignedSSEMove;
const
Prefetch = 512;
asm
@@Loop:
prefetchnta [eax+ecx+Prefetch]
prefetchnta [eax+ecx+Prefetch+64]
movups xmm0, [eax+ecx]
movups xmm1, [eax+ecx+16]
movups xmm2, [eax+ecx+32]
movups xmm3, [eax+ecx+48]
movntps [edx+ecx], xmm0
movntps [edx+ecx+16], xmm1
movntps [edx+ecx+32], xmm2
movntps [edx+ecx+48], xmm3
movups xmm4, [eax+ecx+64]
movups xmm5, [eax+ecx+80]
movups xmm6, [eax+ecx+96]
movups xmm7, [eax+ecx+112]
movntps [edx+ecx+64], xmm4
movntps [edx+ecx+80], xmm5
movntps [edx+ecx+96], xmm6
movntps [edx+ecx+112], xmm7
add ecx, 128
js @@Loop
sfence
end;
{-------------------------------------------------------------------------}
{Dest MUST be 16-Byes Aligned, Count MUST be multiple of 16 }
procedure LargeSSEMove;
asm
push ebx
mov ebx, ecx
and ecx, -128 {No of Bytes to Block Move (Multiple of 128)}
add eax, ecx {End of Source Blocks}
add edx, ecx {End of Dest Blocks}
neg ecx
cmp ecx, CacheLimit {Count > Limit - Use Prefetch}
jl @@Huge
test eax, 15 {Check if Both Source/Dest are Aligned}
jnz @@LargeUnaligned
call LargeAlignedSSEMove {Both Source and Dest 16-Byte Aligned}
jmp @@Remainder
@@LargeUnaligned: {Source Not 16-Byte Aligned}
call LargeUnalignedSSEMove
jmp @@Remainder
@@Huge:
test eax, 15 {Check if Both Source/Dest Aligned}
jnz @@HugeUnaligned
call HugeAlignedSSEMove {Both Source and Dest 16-Byte Aligned}
jmp @@Remainder
@@HugeUnaligned: {Source Not 16-Byte Aligned}
call HugeUnalignedSSEMove
@@Remainder:
and ebx, $7F {Remainder (0..112 - Multiple of 16)}
jz @@Done
add eax, ebx
add edx, ebx
neg ebx
@@RemainderLoop:
movups xmm0, [eax+ebx]
movaps [edx+ebx], xmm0
add ebx, 16
jnz @@RemainderLoop
@@Done:
pop ebx
end;
{-------------------------------------------------------------------------}
{Move ECX Bytes from EAX to EDX, where EAX > EDX and ECX > 36 (TINYSIZE)}
procedure Forwards_SSE;
const
SMALLSIZE = 64;
LARGESIZE = 2048;
asm
cmp ecx, SMALLSIZE
jle Forwards_IA32
push ebx
cmp ecx, LARGESIZE
jge @@FwdLargeMove
movups xmm0, [eax] {First 16 Bytes}
mov ebx, edx
add eax, ecx {Align Writes}
add ecx, edx
and edx, -16
add edx, 48
sub ecx, edx
add edx, ecx
neg ecx
nop {Align Loop}
@@FwdLoopSSE:
movups xmm1, [eax+ecx-32]
movups xmm2, [eax+ecx-16]
movaps [edx+ecx-32], xmm1
movaps [edx+ecx-16], xmm2
add ecx, 32
jle @@FwdLoopSSE
movups [ebx], xmm0 {First 16 Bytes}
neg ecx
add ecx, 32
pop ebx
jmp SmallForwardMove
@@FwdLargeMove:
mov ebx, ecx
test edx, 15
jz @@FwdLargeAligned
lea ecx, [edx+15] {16 byte Align Destination}
and ecx, -16
sub ecx, edx
add eax, ecx
add edx, ecx
sub ebx, ecx
call SmallForwardMove
mov ecx, ebx
@@FwdLargeAligned:
and ecx, -16
sub ebx, ecx {EBX = Remainder}
push edx
push eax
push ecx
call LargeSSEMove
pop ecx
pop eax
pop edx
add ecx, ebx
add eax, ecx
add edx, ecx
mov ecx, ebx
pop ebx
jmp SmallForwardMove
end;
{-------------------------------------------------------------------------}
{Move ECX Bytes from EAX to EDX, where EAX < EDX and ECX > 36 (TINYSIZE)}
procedure Backwards_SSE;
const
SMALLSIZE = 64;
asm
cmp ecx, SMALLSIZE
jle Backwards_IA32
push ebx
movups xmm0, [eax+ecx-16] {Last 16 Bytes}
lea ebx, [edx+ecx] {Align Writes}
and ebx, 15
sub ecx, ebx
add ebx, ecx
sub ecx, 32
@@BwdLoop:
movups xmm1, [eax+ecx]
movups xmm2, [eax+ecx+16]
movaps [edx+ecx], xmm1
movaps [edx+ecx+16], xmm2
sub ecx, 32
jge @@BwdLoop
movups [edx+ebx-16], xmm0 {Last 16 Bytes}
add ecx, 32
pop ebx
jmp SmallBackwardMove
end;
{-------------------------------------------------------------------------}
procedure LargeAlignedSSE2Move; {Also used in SSE3 Move}
asm
@@Loop:
movdqa xmm0, [eax+ecx]
movdqa xmm1, [eax+ecx+16]
movdqa xmm2, [eax+ecx+32]
movdqa xmm3, [eax+ecx+48]
movdqa [edx+ecx], xmm0
movdqa [edx+ecx+16], xmm1
movdqa [edx+ecx+32], xmm2
movdqa [edx+ecx+48], xmm3
movdqa xmm4, [eax+ecx+64]
movdqa xmm5, [eax+ecx+80]
movdqa xmm6, [eax+ecx+96]
movdqa xmm7, [eax+ecx+112]
movdqa [edx+ecx+64], xmm4
movdqa [edx+ecx+80], xmm5
movdqa [edx+ecx+96], xmm6
movdqa [edx+ecx+112], xmm7
add ecx, 128
js @@Loop
end;
{-------------------------------------------------------------------------}
procedure LargeUnalignedSSE2Move;
asm
@@Loop:
movdqu xmm0, [eax+ecx]
movdqu xmm1, [eax+ecx+16]
movdqu xmm2, [eax+ecx+32]
movdqu xmm3, [eax+ecx+48]
movdqa [edx+ecx], xmm0
movdqa [edx+ecx+16], xmm1
movdqa [edx+ecx+32], xmm2
movdqa [edx+ecx+48], xmm3
movdqu xmm4, [eax+ecx+64]
movdqu xmm5, [eax+ecx+80]
movdqu xmm6, [eax+ecx+96]
movdqu xmm7, [eax+ecx+112]
movdqa [edx+ecx+64], xmm4
movdqa [edx+ecx+80], xmm5
movdqa [edx+ecx+96], xmm6
movdqa [edx+ecx+112], xmm7
add ecx, 128
js @@Loop
end;
{-------------------------------------------------------------------------}
procedure HugeAlignedSSE2Move; {Also used in SSE3 Move}
const
Prefetch = 512;
asm
@@Loop:
prefetchnta [eax+ecx+Prefetch]
prefetchnta [eax+ecx+Prefetch+64]
movdqa xmm0, [eax+ecx]
movdqa xmm1, [eax+ecx+16]
movdqa xmm2, [eax+ecx+32]
movdqa xmm3, [eax+ecx+48]
movntdq [edx+ecx], xmm0
movntdq [edx+ecx+16], xmm1
movntdq [edx+ecx+32], xmm2
movntdq [edx+ecx+48], xmm3
movdqa xmm4, [eax+ecx+64]
movdqa xmm5, [eax+ecx+80]
movdqa xmm6, [eax+ecx+96]
movdqa xmm7, [eax+ecx+112]
movntdq [edx+ecx+64], xmm4
movntdq [edx+ecx+80], xmm5
movntdq [edx+ecx+96], xmm6
movntdq [edx+ecx+112], xmm7
add ecx, 128
js @@Loop
sfence
end;
{-------------------------------------------------------------------------}
procedure HugeUnalignedSSE2Move;
const
Prefetch = 512;
asm
@@Loop:
prefetchnta [eax+ecx+Prefetch]
prefetchnta [eax+ecx+Prefetch+64]
movdqu xmm0, [eax+ecx]
movdqu xmm1, [eax+ecx+16]
movdqu xmm2, [eax+ecx+32]
movdqu xmm3, [eax+ecx+48]
movntdq [edx+ecx], xmm0
movntdq [edx+ecx+16], xmm1
movntdq [edx+ecx+32], xmm2
movntdq [edx+ecx+48], xmm3
movdqu xmm4, [eax+ecx+64]
movdqu xmm5, [eax+ecx+80]
movdqu xmm6, [eax+ecx+96]
movdqu xmm7, [eax+ecx+112]
movntdq [edx+ecx+64], xmm4
movntdq [edx+ecx+80], xmm5
movntdq [edx+ecx+96], xmm6
movntdq [edx+ecx+112], xmm7
add ecx, 128
js @@Loop
sfence
end; {HugeUnalignedSSE2Move}
{-------------------------------------------------------------------------}
{Dest MUST be 16-Byes Aligned, Count MUST be multiple of 16 }
procedure LargeSSE2Move;
asm
push ebx
mov ebx, ecx
and ecx, -128 {No of Bytes to Block Move (Multiple of 128)}
add eax, ecx {End of Source Blocks}
add edx, ecx {End of Dest Blocks}
neg ecx
cmp ecx, CacheLimit {Count > Limit - Use Prefetch}
jl @@Huge
test eax, 15 {Check if Both Source/Dest are Aligned}
jnz @@LargeUnaligned
call LargeAlignedSSE2Move {Both Source and Dest 16-Byte Aligned}
jmp @@Remainder
@@LargeUnaligned: {Source Not 16-Byte Aligned}
call LargeUnalignedSSE2Move
jmp @@Remainder
@@Huge:
test eax, 15 {Check if Both Source/Dest Aligned}
jnz @@HugeUnaligned
call HugeAlignedSSE2Move {Both Source and Dest 16-Byte Aligned}
jmp @@Remainder
@@HugeUnaligned: {Source Not 16-Byte Aligned}
call HugeUnalignedSSE2Move
@@Remainder:
and ebx, $7F {Remainder (0..112 - Multiple of 16)}
jz @@Done
add eax, ebx
add edx, ebx
neg ebx
@@RemainderLoop:
movdqu xmm0, [eax+ebx]
movdqa [edx+ebx], xmm0
add ebx, 16
jnz @@RemainderLoop
@@Done:
pop ebx
end;
{-------------------------------------------------------------------------}
{Move ECX Bytes from EAX to EDX, where EAX > EDX and ECX > 36 (TINYSIZE)}
procedure Forwards_SSE2;
const
SMALLSIZE = 64;
LARGESIZE = 2048;
asm
cmp ecx, SMALLSIZE
jle Forwards_IA32
push ebx
cmp ecx, LARGESIZE
jge @@FwdLargeMove
movdqu xmm0, [eax] {First 16 Bytes}
mov ebx, edx
add eax, ecx {Align Writes}
add ecx, edx
and edx, -16
add edx, 48
sub ecx, edx
add edx, ecx
neg ecx
@@FwdLoopSSE2:
movdqu xmm1, [eax+ecx-32]
movdqu xmm2, [eax+ecx-16]
movdqa [edx+ecx-32], xmm1
movdqa [edx+ecx-16], xmm2
add ecx, 32
jle @@FwdLoopSSE2
movdqu [ebx], xmm0 {First 16 Bytes}
neg ecx
add ecx, 32
pop ebx
jmp SmallForwardMove
@@FwdLargeMove:
mov ebx, ecx
test edx, 15
jz @@FwdLargeAligned
lea ecx, [edx+15] {16 byte Align Destination}
and ecx, -16
sub ecx, edx
add eax, ecx
add edx, ecx
sub ebx, ecx
call SmallForwardMove
mov ecx, ebx
@@FwdLargeAligned:
and ecx, -16
sub ebx, ecx {EBX = Remainder}
push edx
push eax
push ecx
call LargeSSE2Move
pop ecx
pop eax
pop edx
add ecx, ebx
add eax, ecx
add edx, ecx
mov ecx, ebx
pop ebx
jmp SmallForwardMove
end;
{-------------------------------------------------------------------------}
{Move ECX Bytes from EAX to EDX, where EAX < EDX and ECX > 36 (TINYSIZE)}
procedure Backwards_SSE2;
const
SMALLSIZE = 64;
asm
cmp ecx, SMALLSIZE
jle Backwards_IA32
push ebx
movdqu xmm0, [eax+ecx-16] {Last 16 Bytes}
lea ebx, [edx+ecx] {Align Writes}
and ebx, 15
sub ecx, ebx
add ebx, ecx
sub ecx, 32
add edi, 0 {3-Byte NOP Equivalent to Align Loop}
@@BwdLoop:
movdqu xmm1, [eax+ecx]
movdqu xmm2, [eax+ecx+16]
movdqa [edx+ecx], xmm1
movdqa [edx+ecx+16], xmm2
sub ecx, 32
jge @@BwdLoop
movdqu [edx+ebx-16], xmm0 {Last 16 Bytes}
add ecx, 32
pop ebx
jmp SmallBackwardMove
end;
{-------------------------------------------------------------------------}
procedure LargeUnalignedSSE3Move;
asm
@@Loop:
lddqu xmm0, [eax+ecx]
lddqu xmm1, [eax+ecx+16]
lddqu xmm2, [eax+ecx+32]
lddqu xmm3, [eax+ecx+48]
movdqa [edx+ecx], xmm0
movdqa [edx+ecx+16], xmm1
movdqa [edx+ecx+32], xmm2
movdqa [edx+ecx+48], xmm3
lddqu xmm4, [eax+ecx+64]
lddqu xmm5, [eax+ecx+80]
lddqu xmm6, [eax+ecx+96]
lddqu xmm7, [eax+ecx+112]
movdqa [edx+ecx+64], xmm4
movdqa [edx+ecx+80], xmm5
movdqa [edx+ecx+96], xmm6
movdqa [edx+ecx+112], xmm7
add ecx, 128
js @@Loop
end;
{-------------------------------------------------------------------------}
procedure HugeUnalignedSSE3Move;
const
Prefetch = 512;
asm
@@Loop:
prefetchnta [eax+ecx+Prefetch]
prefetchnta [eax+ecx+Prefetch+64]
lddqu xmm0, [eax+ecx]
lddqu xmm1, [eax+ecx+16]
lddqu xmm2, [eax+ecx+32]
lddqu xmm3, [eax+ecx+48]
movntdq [edx+ecx], xmm0
movntdq [edx+ecx+16], xmm1
movntdq [edx+ecx+32], xmm2
movntdq [edx+ecx+48], xmm3
lddqu xmm4, [eax+ecx+64]
lddqu xmm5, [eax+ecx+80]
lddqu xmm6, [eax+ecx+96]
lddqu xmm7, [eax+ecx+112]
movntdq [edx+ecx+64], xmm4
movntdq [edx+ecx+80], xmm5
movntdq [edx+ecx+96], xmm6
movntdq [edx+ecx+112], xmm7
add ecx, 128
js @@Loop
sfence
end;
{-------------------------------------------------------------------------}
{Dest MUST be 16-Byes Aligned, Count MUST be multiple of 16 }
procedure LargeSSE3Move(const Source; var Dest; Count: Integer);
asm
push ebx
mov ebx, ecx
and ecx, -128 {No of Bytes to Block Move (Multiple of 128)}
add eax, ecx {End of Source Blocks}
add edx, ecx {End of Dest Blocks}
neg ecx
cmp ecx, CacheLimit {Count > Limit - Use Prefetch}
jl @@Huge
test eax, 15 {Check if Both Source/Dest are Aligned}
jnz @@LargeUnaligned
call LargeAlignedSSE2Move {Both Source and Dest 16-Byte Aligned}
jmp @@Remainder
@@LargeUnaligned: {Source Not 16-Byte Aligned}
call LargeUnalignedSSE3Move
jmp @@Remainder
@@Huge:
test eax, 15 {Check if Both Source/Dest Aligned}
jnz @@HugeUnaligned
call HugeAlignedSSE2Move {Both Source and Dest 16-Byte Aligned}
jmp @@Remainder
@@HugeUnaligned: {Source Not 16-Byte Aligned}
call HugeUnalignedSSE3Move
@@Remainder:
and ebx, $7F {Remainder (0..112 - Multiple of 16)}
jz @@Done
add eax, ebx
add edx, ebx
neg ebx
@@RemainderLoop:
lddqu xmm0, [eax+ebx]
movdqa [edx+ebx], xmm0
add ebx, 16
jnz @@RemainderLoop
@@Done:
pop ebx
end;
{-------------------------------------------------------------------------}
{Move ECX Bytes from EAX to EDX, where EAX > EDX and ECX > 36 (TINYSIZE)}
procedure Forwards_SSE3;
const
SMALLSIZE = 64;
LARGESIZE = 2048;
asm
cmp ecx, SMALLSIZE
jle Forwards_IA32
push ebx
cmp ecx, LARGESIZE
jge @@FwdLargeMove
lddqu xmm0, [eax] {First 16 Bytes}
mov ebx, edx
add eax, ecx {Align Writes}
add ecx, edx
and edx, -16
add edx, 48
sub ecx, edx
add edx, ecx
neg ecx
@@FwdLoopSSE3:
lddqu xmm1, [eax+ecx-32]
lddqu xmm2, [eax+ecx-16]
movdqa [edx+ecx-32], xmm1
movdqa [edx+ecx-16], xmm2
add ecx, 32
jle @@FwdLoopSSE3
movdqu [ebx], xmm0 {First 16 Bytes}
neg ecx
add ecx, 32
pop ebx
jmp SmallForwardMove
@@FwdLargeMove:
mov ebx, ecx
test edx, 15
jz @@FwdLargeAligned
lea ecx, [edx+15] {16 byte Align Destination}
and ecx, -16
sub ecx, edx
add eax, ecx
add edx, ecx
sub ebx, ecx
call SmallForwardMove
mov ecx, ebx
@@FwdLargeAligned:
and ecx, -16
sub ebx, ecx {EBX = Remainder}
push edx
push eax
push ecx
call LargeSSE3Move
pop ecx
pop eax
pop edx
add ecx, ebx
add eax, ecx
add edx, ecx
mov ecx, ebx
pop ebx
jmp SmallForwardMove
end;
{-------------------------------------------------------------------------}
{Move ECX Bytes from EAX to EDX, where EAX < EDX and ECX > 36 (TINYSIZE)}
procedure Backwards_SSE3;
const
SMALLSIZE = 64;
asm
cmp ecx, SMALLSIZE
jle Backwards_IA32
push ebx
lddqu xmm0, [eax+ecx-16] {Last 16 Bytes}
lea ebx, [edx+ecx] {Align Writes}
and ebx, 15
sub ecx, ebx
add ebx, ecx
sub ecx, 32
add edi, 0 {3-Byte NOP Equivalent to Align Loop}
@@BwdLoop:
lddqu xmm1, [eax+ecx]
lddqu xmm2, [eax+ecx+16]
movdqa [edx+ecx], xmm1
movdqa [edx+ecx+16], xmm2
sub ecx, 32
jge @@BwdLoop
movdqu [edx+ebx-16], xmm0 {Last 16 Bytes}
add ecx, 32
pop ebx
jmp SmallBackwardMove
end;
procedure MoveMMX(const Source; var Dest; Count: Integer);
asm
cmp ecx, TINYSIZE
ja @@Large { Count > TINYSIZE or Count < 0 }
cmp eax, edx
jbe @@SmallCheck
add eax, ecx
add edx, ecx
jmp SmallForwardMove
@@SmallCheck:
jne SmallBackwardMove
ret { For Compatibility with Delphi's move for Source = Dest }
@@Large:
jng @@Done { For Compatibility with Delphi's move for Count < 0 }
cmp eax, edx
ja Forwards_MMX
je @@Done { For Compatibility with Delphi's move for Source = Dest }
sub edx, ecx
cmp eax, edx
lea edx, [edx+ecx]
jna Forwards_MMX
jmp Backwards_MMX { Source/Dest Overlap }
@@Done:
end;
procedure MoveSSE(const Source; var Dest; Count: Integer);
asm
cmp ecx, TINYSIZE
ja @@Large { Count > TINYSIZE or Count < 0 }
cmp eax, edx
jbe @@SmallCheck
add eax, ecx
add edx, ecx
jmp SmallForwardMove
@@SmallCheck:
jne SmallBackwardMove
ret { For Compatibility with Delphi's move for Source = Dest }
@@Large:
jng @@Done { For Compatibility with Delphi's move for Count < 0 }
cmp eax, edx
ja Forwards_SSE
je @@Done { For Compatibility with Delphi's move for Source = Dest }
sub edx, ecx
cmp eax, edx
lea edx, [edx+ecx]
jna Forwards_SSE
jmp Backwards_SSE { Source/Dest Overlap }
@@Done:
end;
procedure MoveSSE2(const Source; var Dest; Count: Integer);
asm
cmp ecx, TINYSIZE
ja @@Large {Count > TINYSIZE or Count < 0}
cmp eax, edx
jbe @@SmallCheck
add eax, ecx
add edx, ecx
jmp SmallForwardMove
@@SmallCheck:
jne SmallBackwardMove
ret {For Compatibility with Delphi's move for Source = Dest}
@@Large:
jng @@Done {For Compatibility with Delphi's move for Count < 0}
cmp eax, edx
ja Forwards_SSE2
je @@Done {For Compatibility with Delphi's move for Source = Dest}
sub edx, ecx
cmp eax, edx
lea edx, [edx+ecx]
jna Forwards_SSE2
jmp Backwards_SSE2 {Source/Dest Overlap}
@@Done:
end;
procedure MoveSSE3(const Source; var Dest; Count: Integer);
asm
cmp ecx, TINYSIZE
ja @@Large { Count > TINYSIZE or Count < 0 }
cmp eax, edx
jbe @@SmallCheck
add eax, ecx
add edx, ecx
jmp SmallForwardMove
@@SmallCheck:
jne SmallBackwardMove
ret { For Compatibility with Delphi's move for Source = Dest }
@@Large:
jng @@Done { For Compatibility with Delphi's move for Count < 0}
cmp eax, edx
ja Forwards_SSE3
je @@Done { For Compatibility with Delphi's move for Source = Dest }
sub edx, ecx
cmp eax, edx
lea edx, [edx+ecx]
jna Forwards_SSE3
jmp Backwards_SSE3 { Source/Dest Overlap }
@@Done:
end;
initialization
{ Detect supported SIMD sets }
SimdSupported := GetSupportedSimdInstructionSets();
if false then
{ Patch the RTL Move method }
if sisMMX in SimdSupported then
PatchMethod(@System.Move, @MoveMMX) { MMX version }
else if sisSSE3 in SimdSupported then
PatchMethod(@System.Move, @MoveSSE3) { SSE3 version }
else if sisSSE2 in SimdSupported then
PatchMethod(@System.Move, @MoveSSE2) { SSE2 version }
else if sisSSE in SimdSupported then
PatchMethod(@System.Move, @MoveSSE); { SSE version }
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
SMD vector file format implementation.
}
unit VXS.FileSMD;
interface
uses
System.Classes,
System.SysUtils,
VXS.VectorFileObjects,
VXS.Texture,
VXS.ApplicationFileIO,
VXS.VectorTypes,
VXS.VectorGeometry,
VXS.Material,
VXS.Utils;
type
{ The SMD vector file is Half-life's skeleton format.
The SMD is a text-based file format. They come in two flavors: one that
old Skeleton and triangle (mesh) data, and animation files that store
Skeleton frames.
This reader curently reads both, but requires that the main file
(the one with mesh data) be read first. }
TVXSMDVectorFile = class(TVXVectorFile)
public
class function Capabilities: TVXDataFileCapabilities; override;
procedure LoadFromStream(aStream: TStream); override;
procedure SaveToStream(aStream: TStream); override;
end;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------
// ------------------ TVXSMDVectorFile ------------------
// ------------------
class function TVXSMDVectorFile.Capabilities: TVXDataFileCapabilities;
begin
Result := [dfcRead, dfcWrite];
end;
procedure TVXSMDVectorFile.LoadFromStream(aStream: TStream);
procedure AllocateMaterial(const name: String);
var
matLib: TVXMaterialLibrary;
begin
if Owner is TVXBaseMesh then
begin
matLib := TVXBaseMesh(GetOwner).MaterialLibrary;
if Assigned(matLib) then
begin
if matLib.Materials.GetLibMaterialByName(name) = nil then
begin
if CompareText(name, 'null.bmp') <> 0 then
begin
try
matLib.AddTextureMaterial(name, name)
except
on E: ETexture do
begin
if not Owner.IgnoreMissingTextures then
raise;
end;
end;
end
else
matLib.AddTextureMaterial(name, '');
end;
end;
end;
end;
var
i, j, k, nVert, nTex, firstFrame: Integer;
nbBones, boneID: Integer;
mesh: TVXSkeletonMeshObject;
sl, tl: TStringList;
bone: TVXSkeletonBone;
frame: TVXSkeletonFrame;
faceGroup: TFGVertexNormalTexIndexList;
v: TAffineVector;
boneIDs: TVertexBoneWeightDynArray;
weightCount: Integer;
begin
sl := TStringList.Create;
tl := TStringList.Create;
try
sl.LoadFromStream(aStream);
if sl[0] <> 'version 1' then
raise Exception.Create('SMD version 1 required');
if sl[1] <> 'nodes' then
raise Exception.Create('nodes not found');
if sl.IndexOf('triangles') >= 0 then
begin
mesh := TVXSkeletonMeshObject.CreateOwned(Owner.MeshObjects);
mesh.Mode := momFaceGroups;
end
else if Owner.MeshObjects.Count > 0 then
mesh := (Owner.MeshObjects[0] as TVXSkeletonMeshObject)
else
raise Exception.Create('SMD is an animation, load model SMD first.');
// read skeleton nodes
i := 2;
if Owner.Skeleton.RootBones.Count = 0 then
begin
// new bone structure
while sl[i] <> 'end' do
begin
tl.CommaText := sl[i];
with Owner.Skeleton do
if (tl[2] <> '-1') then
bone := TVXSkeletonBone.CreateOwned
(RootBones.BoneByID(StrToInt(tl[2])))
else
bone := TVXSkeletonBone.CreateOwned(RootBones);
if Assigned(bone) then
begin
bone.boneID := StrToInt(tl[0]);
bone.name := tl[1];
end;
Inc(i);
end;
end
else
begin
// animation file, skip structure
while sl[i] <> 'end' do
Inc(i);
end;
Inc(i);
if sl[i] <> 'skeleton' then
raise Exception.Create('skeleton not found');
Inc(i);
// read animation time frames
nbBones := Owner.Skeleton.RootBones.BoneCount - 1;
firstFrame := Owner.Skeleton.Frames.Count;
while sl[i] <> 'end' do
begin
if Copy(sl[i], 1, 5) <> 'time ' then
raise Exception.Create('time not found, got: ' + sl[i]);
frame := TVXSkeletonFrame.CreateOwned(Owner.Skeleton.Frames);
frame.name := ResourceName + ' ' + sl[i];
Inc(i);
while Pos(Copy(sl[i], 1, 1), ' 1234567890') > 0 do
begin
tl.CommaText := sl[i];
while StrToInt(tl[0]) > frame.Position.Count do
begin
frame.Position.Add(NullVector);
frame.Rotation.Add(NullVector);
end;
frame.Position.Add(VXS.Utils.StrToFloatDef(tl[1]),
VXS.Utils.StrToFloatDef(tl[2]), VXS.Utils.StrToFloatDef(tl[3]));
v := AffineVectorMake(VXS.Utils.StrToFloatDef(tl[4]),
VXS.Utils.StrToFloatDef(tl[5]), VXS.Utils.StrToFloatDef(tl[6]));
frame.Rotation.Add(v);
Inc(i);
end;
while frame.Position.Count < nbBones do
begin
frame.Position.Add(NullVector);
frame.Rotation.Add(NullVector);
end;
Assert(frame.Position.Count = nbBones, 'Invalid number of bones in frame '
+ IntToStr(Owner.Skeleton.Frames.Count));
end;
if Owner is TVXActor then
with TVXActor(Owner).Animations.Add do
begin
k := Pos('.', ResourceName);
if k > 0 then
Name := Copy(ResourceName, 1, k - 1)
else
Name := ResourceName;
Reference := aarSkeleton;
StartFrame := firstFrame;
EndFrame := Self.Owner.Skeleton.Frames.Count - 1;
end;
Inc(i);
if (i < sl.Count) and (sl[i] = 'triangles') then
begin
// read optional mesh data
Inc(i);
if mesh.BonesPerVertex < 1 then
mesh.BonesPerVertex := 1;
faceGroup := nil;
while sl[i] <> 'end' do
begin
if (faceGroup = nil) or (faceGroup.MaterialName <> sl[i]) then
begin
faceGroup := TFGVertexNormalTexIndexList.CreateOwned(mesh.FaceGroups);
faceGroup.Mode := fgmmTriangles;
faceGroup.MaterialName := sl[i];
AllocateMaterial(sl[i]);
end;
Inc(i);
for k := 1 to 3 do
with mesh do
begin
tl.CommaText := sl[i];
if tl.Count > 9 then
begin
// Half-Life 2 SMD, specifies bones and weights
weightCount := StrToInt(tl[9]);
SetLength(boneIDs, weightCount);
for j := 0 to weightCount - 1 do
begin
boneIDs[j].boneID := StrToInt(tl[10 + j * 2]);
boneIDs[j].Weight := VXS.Utils.StrToFloatDef(tl[11 + j * 2]);
end;
nVert := FindOrAdd(boneIDs,
AffineVectorMake(VXS.Utils.StrToFloatDef(tl[1]),
VXS.Utils.StrToFloatDef(tl[2]), VXS.Utils.StrToFloatDef(tl[3])),
AffineVectorMake(VXS.Utils.StrToFloatDef(tl[4]),
VXS.Utils.StrToFloatDef(tl[5]),
VXS.Utils.StrToFloatDef(tl[6])));
nTex := TexCoords.FindOrAdd
(AffineVectorMake(VXS.Utils.StrToFloatDef(tl[7]),
VXS.Utils.StrToFloatDef(tl[8]), 0));
faceGroup.Add(nVert, nVert, nTex);
Inc(i);
end
else
begin
// Half-Life 1 simple format
boneID := StrToInt(tl[0]);
nVert := FindOrAdd(boneID,
AffineVectorMake(VXS.Utils.StrToFloatDef(tl[1]),
VXS.Utils.StrToFloatDef(tl[2]), VXS.Utils.StrToFloatDef(tl[3])),
AffineVectorMake(VXS.Utils.StrToFloatDef(tl[4]),
VXS.Utils.StrToFloatDef(tl[5]),
VXS.Utils.StrToFloatDef(tl[6])));
nTex := TexCoords.FindOrAdd
(AffineVectorMake(VXS.Utils.StrToFloatDef(tl[7]),
VXS.Utils.StrToFloatDef(tl[8]), 0));
faceGroup.Add(nVert, nVert, nTex);
Inc(i);
end;
end;
end;
Owner.Skeleton.RootBones.PrepareGlobalMatrices;
mesh.PrepareBoneMatrixInvertedMeshes;
end;
finally
tl.Free;
sl.Free;
end;
end;
procedure TVXSMDVectorFile.SaveToStream(aStream: TStream);
var
str, nodes: TStrings;
i, j, k, l, b: Integer;
p, r, v, n, t: TAffineVector;
procedure GetNodesFromBonesRecurs(bone: TVXSkeletonBone; ParentID: Integer;
bl: TStrings);
var
i: Integer;
begin
bl.Add(Format('%3d "%s" %3d', [bone.boneID, bone.name, ParentID]));
for i := 0 to bone.Count - 1 do
GetNodesFromBonesRecurs(bone.Items[i], bone.boneID, bl);
end;
begin
str := TStringList.Create;
nodes := TStringList.Create;
try
str.Add('version 1');
// Add the bones
str.Add('nodes');
for i := 0 to Owner.Skeleton.RootBones.Count - 1 do
begin
GetNodesFromBonesRecurs(Owner.Skeleton.RootBones[i], -1, nodes);
end;
str.AddStrings(nodes);
str.Add('end');
// Now add the relavent frames
if Owner.Skeleton.Frames.Count > 0 then
begin
str.Add('skeleton');
for i := 0 to Owner.Skeleton.Frames.Count - 1 do
begin
str.Add(Format('time %d', [i]));
for j := 0 to Owner.Skeleton.Frames[i].Position.Count - 1 do
begin
p := Owner.Skeleton.Frames[i].Position[j];
r := Owner.Skeleton.Frames[i].Rotation[j];
str.Add(StringReplace(Format('%3d %.6f %.6f %.6f %.6f %.6f %.6f',
[j, p.X, p.Y, p.Z, r.X, r.Y, r.Z]), ',', '.', [rfReplaceAll]));
end;
end;
str.Add('end');
end;
// Add the mesh data
if Owner.MeshObjects.Count > 0 then
begin
str.Add('triangles');
for i := 0 to Owner.MeshObjects.Count - 1 do
if Owner.MeshObjects[i] is TVXSkeletonMeshObject then
with TVXSkeletonMeshObject(Owner.MeshObjects[i]) do
begin
for j := 0 to FaceGroups.Count - 1 do
with TFGVertexNormalTexIndexList(FaceGroups[j]) do
begin
for k := 0 to (VertexIndices.Count div 3) - 1 do
begin
str.Add(MaterialName);
for l := 0 to 2 do
begin
v := Vertices[VertexIndices[3 * k + l]];
n := Normals[NormalIndices[3 * k + l]];
t := TexCoords[TexCoordIndices[3 * k + l]];
b := VerticesBonesWeights^[VertexIndices[3 * k + l]]^
[0].boneID;
str.Add(StringReplace
(Format('%3d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f',
[b, v.X, v.Y, v.Z, n.X, n.Y, n.Z, t.X, t.Y]), ',', '.',
[rfReplaceAll]));
end;
end;
end;
end;
str.Add('end');
end;
str.SaveToStream(aStream);
finally
str.Free;
nodes.Free;
end;
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
RegisterVectorFileFormat('smd', 'Half-Life SMD files', TVXSMDVectorFile);
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections,
VCLTee.TeCanvas, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TMyClass<T> = class
private
FObjeto: T;
public
property Objeto: T read FObjeto write FObjeto;
end;
TPessoa = class
private
FIdade: Integer;
FNome: String;
published
property Nome: String read FNome write FNome;
property Idade: Integer read FIdade write FIdade;
end;
TCachoro = class
private
FColor: TColor;
FRaca: String;
published
property Raca: String read FRaca write FRaca;
property Cor: TColor read FColor write FColor;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TMyClass<T> }
procedure TForm1.Button1Click(Sender: TObject);
var
c1: TMyClass<TPessoa>;
c2: TMyClass<TCachoro>;
begin
c1 := TMyClass<TPessoa>.Create;
c1.Objeto := TPessoa.Create;
c1.Objeto.Nome := 'bruno';
c1.Objeto.Idade := 23;
c2:= TMyClass<TCachoro>.Create;
c2.Objeto := TCachoro.Create;
c2.Objeto.Raca := 'pintcher';
c2.Objeto.Cor := clBlack;
end;
end.
|
unit Horse.Compression.Types;
interface
type
{$SCOPEDENUMS ON}
THorseCompressionType = (DEFLATE, GZIP);
{$SCOPEDENUMS OFF}
THorseCompressionTypeHelper = record helper for THorseCompressionType
function ToString: string;
function WindowsBits: Integer;
end;
implementation
{ THorseCompressionTypeHelper }
function THorseCompressionTypeHelper.ToString: string;
begin
case Self of
THorseCompressionType.DEFLATE:
Result := 'deflate';
THorseCompressionType.GZIP:
Result := 'gzip';
end;
end;
function THorseCompressionTypeHelper.WindowsBits: Integer;
begin
case Self of
THorseCompressionType.DEFLATE:
Result := -15;
else
Result := 31;
end;
end;
end.
|
unit LrCollectionEditor;
interface
uses
DesignIntf, DesignEditors, LrCollection;
type
TLrCollectionEditor = class(TPropertyEditor)
public
function Collection: TLrCustomCollection;
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetName: string; override;
function GetValue: string; override;
end;
procedure Register;
implementation
uses
LrCollectionEditorView;
procedure Register;
begin
RegisterPropertyEditor(
TypeInfo(TLrCustomCollection), nil, '', TLrCollectionEditor);
end;
{ TLrCollectionEditor }
function TLrCollectionEditor.Collection: TLrCustomCollection;
begin
Result := TLrCustomCollection(GetOrdValue);
end;
function TLrCollectionEditor.GetAttributes: TPropertyAttributes;
begin
Result := [ paDialog ];
end;
function TLrCollectionEditor.GetName: string;
begin
Result := inherited GetName;
// Result := Collection.Name;
// Result := 'Items';
end;
procedure TLrCollectionEditor.Edit;
var
n: string;
begin
// inherited;
//n := GetName;
n := Collection.Owner.Name + '.' + GetName;
if Collection.Editor <> nil then
TLrCollectionEditorForm(Collection.Editor).Show
else
with TLrCollectionEditorForm.Create(nil) do
begin
Designer := Self.Designer;
Collection := Self.Collection;
//DisplayName := Self.Collection.Owner.Name + '.' + GetName;
//CollectionName := Self.Collection.ClassName; //'Some Name'; //Self.GetName;
CollectionName := n; //'Some Name'; //Self.GetName;
Show;
end;
end;
function TLrCollectionEditor.GetValue: string;
begin
Result := '(' + Collection.ClassName + ')';
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLFileOCT<p>
Support-code to load OCT Files into TGLFreeForm-Components in GLScene.<br>
(OCT being the format output from FSRad, http://www.fluidstudios.com/fsrad.html).<p>
<b>History : </b><font size=-1><ul>
<li>22/01/10 - Yar - Added GLTextureFormat to uses
<li>31/03/07 - DaStr - Added $I GLScene.inc
<li>19/09/03 - EG - "Lighmap" -> "LightMap"
<li>06/05/03 - mrqzzz - added Gamma and Brightness correction variables (vGLFileOCTLightmapBrightness, vGLFileOCTLightmapGammaCorrection)
<li>02/02/03 - EG - Creation
</ul><p>
}
unit GLFileOCT;
interface
{$I GLScene.inc}
uses Classes, GLVectorFileObjects, GLVectorGeometry, ApplicationFileIO, FileOCT;
type
// TGLOCTVectorFile
//
{: The OCT vector file (FSRad output).<p> }
TGLOCTVectorFile = class(TVectorFile)
public
{ Public Declarations }
class function Capabilities : TDataFileCapabilities; override;
procedure LoadFromStream(aStream: TStream); override;
end;
var
vGLFileOCTLightmapBrightness : Single = 1; // Mrqzzz : scaling factor, 1.0 = unchanged
vGLFileOCTLightmapGammaCorrection : Single = 1; // Mrqzzz : scaling factor, 1.0 = unchanged
vGLFileOCTAllocateMaterials : Boolean = True; // Mrqzzz : Flag to avoid loading materials (useful for IDE Extensions or scene editors)
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses
SysUtils, GLTexture, GLMaterial, GLGraphics, GLCrossPlatform, GLState,
GLUtils, GLTextureFormat;
// ------------------
// ------------------ TGLOCTVectorFile ------------------
// ------------------
// Capabilities
//
class function TGLOCTVectorFile.Capabilities : TDataFileCapabilities;
begin
Result:=[dfcRead];
end;
// LoadFromStream
//
procedure TGLOCTVectorFile.LoadFromStream(aStream : TStream);
var
i, y, n : Integer;
oct : TOCTFile;
octFace : POCTFace;
octLightmap : POCTLightmap;
mo : TMeshObject;
fg : TFGVertexIndexList;
lightmapLib : TGLMaterialLibrary;
lightmapBmp : TGLBitmap;
libMat : TGLLibMaterial;
begin
oct:=TOCTFile.Create(aStream);
try
mo:=TMeshObject.CreateOwned(Owner.MeshObjects);
mo.Mode:=momFaceGroups;
lightmapLib:=Owner.LightmapLibrary;
if (Assigned(lightmapLib)) and (vGLFileOCTAllocateMaterials) then begin
// import lightmaps
n:=oct.Header.numLightmaps;
lightmapBmp:=TGLBitmap.Create;
try
lightmapBmp.PixelFormat:=glpf24bit;
lightmapBmp.Width:=128;
lightmapBmp.Height:=128;
for i:=0 to n-1 do begin
octLightmap:=@oct.Lightmaps[i];
// Brightness correction
if vGLFileOCTLightmapBrightness<>1.0 then
BrightenRGBArray(@octLightmap.map, lightmapBmp.Width*lightmapBmp.Height,
vGLFileOCTLightmapBrightness);
// Gamma correction
if vGLFileOCTLightmapGammaCorrection<>1.0 then
GammaCorrectRGBArray(@octLightmap.map, lightmapBmp.Width*lightmapBmp.Height,
vGLFileOCTLightmapGammaCorrection);
// convert RAW RGB to BMP
for y:=0 to 127 do
Move(octLightmap.map[y*128*3], lightmapBmp.ScanLine[127-y]^, 128*3);
// spawn lightmap
libMat:=lightmapLib.AddTextureMaterial(IntToStr(i), lightmapBmp);
with libMat.Material.Texture do begin
MinFilter:=miLinear;
TextureWrap:=twNone;
TextureFormat:=tfRGB;
end;
end;
finally
lightmapBmp.Free;
end;
end;
// import geometry
n:=oct.Header.numVerts;
mo.Vertices.AdjustCapacityToAtLeast(n);
mo.TexCoords.AdjustCapacityToAtLeast(n);
mo.LightMapTexCoords.AdjustCapacityToAtLeast(n);
for i:=0 to n-1 do with oct.Vertices[i] do begin
mo.Vertices.Add(pos[0], pos[1], pos[2]);
mo.TexCoords.Add(tv.s, tv.t);
mo.LightMapTexCoords.Add(lv.s, lv.t);
end;
// import faces
n:=oct.Header.numFaces;
for i:=0 to n-1 do begin
octFace:=@oct.Faces[i];
fg:=TFGVertexIndexList.CreateOwned(mo.FaceGroups);
fg.Mode:=fgmmTriangleFan;
fg.VertexIndices.AddSerie(octFace.start, 1, octFace.num);
if (Assigned(lightmapLib)) and (vGLFileOCTAllocateMaterials) then
fg.LightMapIndex:=octFace.lid;
end;
finally
oct.Free;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterVectorFileFormat('oct', 'FSRad OCT files', TGLOCTVectorFile);
end.
|
unit Render2Test;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls;
type
TRender2TestForm = class(TForm)
PaintBox: TPaintBox;
procedure PaintBoxPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Render2TestForm: TRender2TestForm;
implementation
uses
Layout, Render3, Nodes;
{$R *.dfm}
function BuildNodeList: TNodeList;
var
node, nd: TNode;
begin
Result := TNodeList.Create;
//
node := TDivNode.Create;
node.Text := 'Hello Top Div!';
Result.Add(node);
//
node.Nodes := TNodeList.Create;
with node.Nodes do
begin
nd := TInlineNode.Create;
nd.Text := 'Inline 1';
nd.Style.BackgroundColor := clLime;
nd.Style.Height := 100;
Add(nd);
//
nd := TInlineNode.Create;
nd.Text := 'Inline 2';
nd.Style.BackgroundColor := clAqua;
nd.Style.Height := 100;
Add(nd);
end;
//
node := TDivNode.Create;
node.Text := 'Hello world. ';
node.Style.BackgroundColor := clFuchsia;
node.Style.Height := 100;
Result.Add(node);
end;
function BuildBoxList(inNodes: TNodeList): TBoxList;
begin
with TLayout.Create do
try
Result := BuildBoxes(inNodes);
finally
Free;
end;
end;
procedure RenderBoxList(inBoxes: TBoxList; inCanvas: TCanvas;
inRect: TRect);
begin
with TRenderer.Create do
try
Render(inBoxes, inCanvas, inRect);
finally
Free;
end;
end;
procedure TestLayoutRenderer(inCanvas: TCanvas; inRect: TRect);
var
n: TNodeList;
b: TBoxList;
begin
n := BuildNodeList;
b := BuildBoxList(n);
RenderBoxList(b, inCanvas, inRect);
b.Free;
n.Free;
end;
procedure TRender2TestForm.FormCreate(Sender: TObject);
begin
Show;
end;
procedure TRender2TestForm.PaintBoxPaint(Sender: TObject);
begin
//TestBlockRenderer(PaintBox.Canvas, PaintBox.ClientRect);
//TestBoxRenderer(PaintBox.Canvas, PaintBox.ClientRect);
TestLayoutRenderer(PaintBox.Canvas, PaintBox.ClientRect);
end;
end.
|
program AnimationTests;
uses SwinGame, sgTypes;
var
explosions: AnimationScript;
boom: Array [0..1] of Animation;
expl: Bitmap;
i, currentAnim: Integer;
//Test animated sprites
s: Sprite;
begin
OpenAudio();
OpenGraphicsWindow('Animation Tests', 640, 480);
LoadResourceBundle('Explosion.txt');
boom[0] := CreateAnimation('explosion', AnimationScriptNamed('explosion_temp'), False);
boom[1] := CreateAnimation('implosion', AnimationScriptNamed('explosion_temp'), False);
expl := BitmapNamed('explosion_bmp');
WriteLn('ID of boom[0] = ', HexStr(boom[0]));
WriteLn('ID of boom[1] = ', HexStr(boom[1]));
WriteLn('ID of expl = ', HexStr(expl));
currentAnim := -1;
s := CreateSprite(BitmapNamed('red_explosion'), AnimationScriptNamed('explosion_temp'));
SpriteAddLayer(s, BitmapNamed('count'), 'count');
SpriteShowLayer(s, 'count');
SpriteSetLayerOffset(s, 'count', PointAt(3,3));
SpriteStartAnimation(s, 'explosion_loop');
SpriteSetPosition(s, PointAt(200,200));
repeat // The game loop...
ProcessEvents();
if MouseClicked(LeftButton) then SpriteToggleLayerVisible(s, 'count');
if MouseClicked(RightButton) then SpriteToggleLayerVisible(s, 'explosion');
if KeyTyped(UpKey) then SpriteBringLayerForward(s, 1);
if KeyTyped(DownKey) then SpriteSendLayerBackward(s, 0);
UpdateSprite(s);
if (currentAnim = -1) or AnimationEnded(boom[currentAnim]) then
begin
currentAnim := (currentAnim + 1) mod Length(boom);
RestartAnimation(boom[currentAnim]);
end
else
UpdateAnimation(boom[currentAnim]);
ClearScreen(ColorBlack);
// if assigned(boom[currentAnim]^.currentFrame) then
// WriteLn(currentAnim, ' - ', boom[currentAnim]^.currentFrame^.cellIndex);
DrawAnimation(boom[currentAnim], expl, 50, 50);
DrawSprite(s);
DrawRectangle(ColorGreen, SpriteLayerRectangle(s, 'count'));
DrawCell(BitmapNamed('red_explosion'), 1, 200, 50);
DrawFramerate(0,0);
RefreshScreen(60);
until WindowCloseRequested();
FreeSprite(s);
ReleaseAllResources();
CloseAudio();
end.
|
namespace org.me.torch;
//Sample app by Brian Long (http://blong.com)
{
This example demonstrates a number of things:
- how to invoke a confirmation dialog
- how to make a 'toast' message
- how to launch another activity
- how to make a full screen activity (no status bar)
- how to remove the activity title bar
- how to use a wake lock to prevent the screen from sleeping
- how to set up an options menu (one that shows when you press the Menu button)
- how to set up a context menu (one that shows after a long press)
}
interface
uses
java.util,
android.os,
android.app,
android.content,
android.view,
android.widget,
android.util;
type
MainActivity = public class(Activity)
private
const CONFIRM_TORCH_DIALOG = 1;
protected
method onCreateDialog(id: Integer): Dialog; override;
public
method onCreate(savedInstanceState: Bundle); override;
method TorchDialog_YesClickedEvent(dialog: DialogInterface; which: Integer);
end;
implementation
method MainActivity.onCreate(savedInstanceState: Bundle);
begin
inherited;
// Set our view from the "main" layout resource
ContentView := R.layout.main;
// Get our button from the layout resource,
// and attach an event to it
var torchButton := findViewById(R.id.torchButton) as Button;
//torchButton.OnClickListener := method begin ShowDialog(CONFIRM_TORCH_DIALOG); end;
torchButton.OnClickListener := -> showDialog(CONFIRM_TORCH_DIALOG);
end;
method MainActivity.onCreateDialog(id: Integer): Dialog;
begin
Result := inherited;
if id = CONFIRM_TORCH_DIALOG then
begin
//Create dialog here and return it
//Note this is called just once regardless of number of invocations, unless you call RemoveDialog()
var builder := new AlertDialog.Builder(Self);
builder.Message := R.string.torchDialog_Message;
builder.setPositiveButton(Android.R.string.yes, @TorchDialog_YesClickedEvent);
builder.setNegativeButton(Android.R.string.no, (dialog, which) -> dialog.cancel);
Result := builder.&create;
end;
end;
method MainActivity.TorchDialog_YesClickedEvent(dialog: DialogInterface; which: Integer);
begin
//Brief popup message aka toast
Toast.makeText(Self, R.string.torchButton_Toast, Toast.LENGTH_SHORT).show;
//Now show the torch screen
//var i := new Intent(self, java.lang.Class.ForName("org.me.torch.TorchActivity"));
var i := new Intent(self, typeOf(TorchActivity));
startActivity(i)
end;
end. |
(*
Category: SWAG Title: DIRECTORY HANDLING ROUTINES
Original name: 0044.PAS
Description: Hidden Directories
Author: SWAG SUPPORT TEAM
Date: 09-04-95 10:51
*)
{Hidden Directory Secrets }
program DirHide;
uses dos;
var f: File;
Attr: Word;
begin
if ParamCount < 1 then
begin
writeln('Usage: DirHide directory');
Halt
end;
Assign(f,ParamStr(1));
GetfAttr(f, Attr);
if (DosError = 0) AND
((Attr AND Directory) = Directory) then
begin { v vvvvvvvvv }
Attr := (Attr - Directory) XOR Hidden; { TOGGLE HIDDEN BIT }
SetfAttr(f, Attr);
if DosError = 0 then
if (Attr AND Hidden) = Hidden then
writeln(ParamStr(1),' hidden')
else
writeln(ParamStr(1),' shown')
end
end.
|
unit uFrmConnection;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, ADODB, Registry, IniFiles, uParamFunctions, DB;
type
TFrmConnection = class(TForm)
Panel1: TPanel;
Bevel1: TBevel;
btnSave: TBitBtn;
btnClose: TBitBtn;
Label1: TLabel;
cbxConnection: TComboBox;
edtDriverName: TLabeledEdit;
edtBlobSize: TLabeledEdit;
edtHostName: TLabeledEdit;
edtDataBase: TLabeledEdit;
edtUser: TLabeledEdit;
edtPassword: TLabeledEdit;
chkUseLib: TCheckBox;
ADODBConnect: TADOConnection;
BtnConnection: TButton;
procedure btnCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure cbxConnectionSelect(Sender: TObject);
procedure BtnConnectionClick(Sender: TObject);
private
fConFile : TIniFile;
Function CheckConnection() : Boolean;
procedure GetConnections;
procedure SetConnection(sCon:String);
procedure GetConnection(sCon:String);
procedure ClearFields;
public
function Start : Boolean;
end;
implementation
uses uMain;
{$R *.dfm}
procedure TFrmConnection.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TFrmConnection.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
FreeAndNil(fConFile);
Action := caFree;
end;
function TFrmConnection.Start: Boolean;
begin
GetConnections;
ShowModal;
Result := (ModalResult = mrOK);
end;
procedure TFrmConnection.FormCreate(Sender: TObject);
begin
fConFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + frmMain.GetConfigFile);
end;
procedure TFrmConnection.GetConnections;
begin
fConFile.ReadSections(cbxConnection.Items);
ClearFields;
end;
procedure TFrmConnection.GetConnection(sCon: String);
begin
with fConFile do
begin
edtDriverName.Text := ReadString(sCon, 'DriverName', '');
edtBlobSize.Text := ReadString(sCon, 'BlobSize', '');
edtHostName.Text := ReadString(sCon, 'HostName', '');
edtDataBase.Text := ReadString(sCon, 'DataBase', '');
chkUseLib.Checked := ReadBool(sCon, 'UseNetLib', False);
edtUser.Text := frmMain.Decode('User', ReadString(sCon, 'User', ''));
edtPassword.Text := frmMain.Decode('PW', ReadString(sCon, 'Password', ''));
end;
end;
procedure TFrmConnection.ClearFields;
begin
edtDriverName.Text := 'SQLOLEDB.1';
edtBlobSize.Text := '-1';
cbxConnection.Text := '';
edtHostName.Clear;
edtDataBase.Clear;
edtUser.Clear;
edtPassword.Clear;
end;
procedure TFrmConnection.SetConnection(sCon:String);
begin
with fConFile do
begin
WriteString(sCon, 'DriverName', edtDriverName.Text);
WriteString(sCon, 'BlobSize', edtBlobSize.Text);
WriteString(sCon, 'HostName', edtHostName.Text);
WriteString(sCon, 'DataBase', edtDataBase.Text);
WriteString(sCon, 'User', frmMain.Encode('User', edtUser.Text));
WriteString(sCon, 'Password', frmMain.Encode('PW', edtPassword.Text));
WriteBool(sCon, 'UseNetLib', chkUseLib.Checked);
end;
end;
procedure TFrmConnection.btnSaveClick(Sender: TObject);
begin
if cbxConnection.Text <> '' then
begin
SetConnection(cbxConnection.Text);
GetConnections;
end;
end;
procedure TFrmConnection.cbxConnectionSelect(Sender: TObject);
begin
if cbxConnection.Text <> '' then
GetConnection(cbxConnection.Text);
end;
Function TFrmConnection.CheckConnection: Boolean;
Var
sDadosDoRegistro : String;
Begin
Try
sDadosDoRegistro := SetConnectionStr(edtUser.Text, edtPassword.Text, edtDataBase.Text, edtHostName.Text);
ADODBConnect.Close();
ADODBConnect.ConnectionString := sDadosDoRegistro;
ADODBConnect.Open;
MessageDlg( 'Connection OK', mtInformation, [mbOk], 0 )
Except
On E:Exception Do Begin
MessageDlg( 'Connection Error "' + E.Message + '"', mtError, [mbOk], 0 )
End;
End;
End;
{
Function TFrmConnection.OpenConnection( psDataBaseAlias : String = '' ) : Boolean;
Var
sDadosDoRegistro : String;
Reg : TRegistry;
buildInfo: String;
Begin
try
if not ADODBConnect.Connected then
begin
//Pega as info local
Reg := TRegistry.Create;
// aponta para a chave CURRENT_USER se Windows 7
if ( getOs(buildInfo) = osW7 ) then
Reg.RootKey := HKEY_CURRENT_USER
else
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.OpenKey('SOFTWARE\AppleNet', True);
sDadosDoRegistro := DecodeServerInfo(Reg.ReadString('ServerInfo'), 'Server', CIPHER_TEXT_STEALING, FMT_UU);
sServer := ParseConnectionParameters( sDadosDoRegistro, '#SRV#=' );
sDBAlias := ParseConnectionParameters( sDadosDoRegistro, '#DB#=' );
sUser := ParseConnectionParameters( sDadosDoRegistro, '#USER#=' );
sPW := ParseConnectionParameters( sDadosDoRegistro, '#PW#=' );
If ( Trim( psDataBaseAlias ) <> '' )
Then sDBAlias := psDataBaseAlias;
sDadosDoRegistro := SetConnectionStr(sUser, sPw, SDBAlias, sServer);
//Fechar o Registry
Reg.CloseKey;
Reg.Free;
ADODBConnect.ConnectionString := sDadosDoRegistro;
ADODBConnect.Open;
end;
except
Result := False;
Exit;
end;
Result := True;
End;
}
procedure TFrmConnection.BtnConnectionClick(Sender: TObject);
begin
CheckConnection();
end;
end.
|
unit HlpBlake2BTreeConfig;
{$I ..\..\Include\HashLib.inc}
interface
uses
HlpIBlake2BTreeConfig,
HlpHashLibTypes;
resourcestring
SInvalidFanOutParameter =
'FanOut Value Should be Between [0 .. 255] for Blake2B';
SInvalidMaxDepthParameter =
'FanOut Value Should be Between [1 .. 255] for Blake2B';
SInvalidNodeDepthParameter =
'NodeDepth Value Should be Between [0 .. 255] for Blake2B';
SInvalidInnerHashSizeParameter =
'InnerHashSize Value Should be Between [0 .. 64] for Blake2B';
type
TBlake2BTreeConfig = class sealed(TInterfacedObject, IBlake2BTreeConfig)
strict private
FFanOut, FMaxDepth, FNodeDepth, FInnerHashSize: Byte;
FLeafSize: UInt32;
FNodeOffset: UInt64;
FIsLastNode: Boolean;
procedure ValidateFanOut(AFanOut: Byte); inline;
procedure ValidateInnerHashSize(AInnerHashSize: Byte); inline;
procedure ValidateMaxDepth(AMaxDepth: Byte); inline;
procedure ValidateNodeDepth(ANodeDepth: Byte); inline;
function GetFanOut: Byte; inline;
procedure SetFanOut(value: Byte); inline;
function GetMaxDepth: Byte; inline;
procedure SetMaxDepth(value: Byte); inline;
function GetNodeDepth: Byte; inline;
procedure SetNodeDepth(value: Byte); inline;
function GetInnerHashSize: Byte; inline;
procedure SetInnerHashSize(value: Byte); inline;
function GetLeafSize: UInt32; inline;
procedure SetLeafSize(value: UInt32); inline;
function GetNodeOffset: UInt64; inline;
procedure SetNodeOffset(value: UInt64); inline;
function GetIsLastNode: Boolean; inline;
procedure SetIsLastNode(value: Boolean); inline;
public
constructor Create();
property FanOut: Byte read GetFanOut write SetFanOut;
property MaxDepth: Byte read GetMaxDepth write SetMaxDepth;
property NodeDepth: Byte read GetNodeDepth write SetNodeDepth;
property InnerHashSize: Byte read GetInnerHashSize write SetInnerHashSize;
property LeafSize: UInt32 read GetLeafSize write SetLeafSize;
property NodeOffset: UInt64 read GetNodeOffset write SetNodeOffset;
property IsLastNode: Boolean read GetIsLastNode write SetIsLastNode;
end;
implementation
{ TBlake2BTreeConfig }
procedure TBlake2BTreeConfig.ValidateFanOut(AFanOut: Byte);
begin
if not(AFanOut in [0 .. 255]) then
begin
raise EArgumentInvalidHashLibException.CreateRes(@SInvalidFanOutParameter);
end;
end;
procedure TBlake2BTreeConfig.ValidateInnerHashSize(AInnerHashSize: Byte);
begin
if not(AInnerHashSize in [0 .. 64]) then
begin
raise EArgumentInvalidHashLibException.CreateRes
(@SInvalidInnerHashSizeParameter);
end;
end;
procedure TBlake2BTreeConfig.ValidateMaxDepth(AMaxDepth: Byte);
begin
if not(AMaxDepth in [1 .. 255]) then
begin
raise EArgumentInvalidHashLibException.CreateRes
(@SInvalidMaxDepthParameter);
end;
end;
procedure TBlake2BTreeConfig.ValidateNodeDepth(ANodeDepth: Byte);
begin
if not(ANodeDepth in [0 .. 255]) then
begin
raise EArgumentInvalidHashLibException.CreateRes
(@SInvalidNodeDepthParameter);
end;
end;
function TBlake2BTreeConfig.GetFanOut: Byte;
begin
result := FFanOut;
end;
function TBlake2BTreeConfig.GetInnerHashSize: Byte;
begin
result := FInnerHashSize;
end;
function TBlake2BTreeConfig.GetIsLastNode: Boolean;
begin
result := FIsLastNode;
end;
function TBlake2BTreeConfig.GetLeafSize: UInt32;
begin
result := FLeafSize;
end;
function TBlake2BTreeConfig.GetMaxDepth: Byte;
begin
result := FMaxDepth;
end;
function TBlake2BTreeConfig.GetNodeDepth: Byte;
begin
result := FNodeDepth;
end;
function TBlake2BTreeConfig.GetNodeOffset: UInt64;
begin
result := FNodeOffset;
end;
procedure TBlake2BTreeConfig.SetFanOut(value: Byte);
begin
ValidateFanOut(value);
FFanOut := value;
end;
procedure TBlake2BTreeConfig.SetInnerHashSize(value: Byte);
begin
ValidateInnerHashSize(value);
FInnerHashSize := value;
end;
procedure TBlake2BTreeConfig.SetIsLastNode(value: Boolean);
begin
FIsLastNode := value;
end;
procedure TBlake2BTreeConfig.SetLeafSize(value: UInt32);
begin
FLeafSize := value;
end;
procedure TBlake2BTreeConfig.SetMaxDepth(value: Byte);
begin
ValidateMaxDepth(value);
FMaxDepth := value;
end;
procedure TBlake2BTreeConfig.SetNodeDepth(value: Byte);
begin
ValidateNodeDepth(value);
FNodeDepth := value;
end;
procedure TBlake2BTreeConfig.SetNodeOffset(value: UInt64);
begin
FNodeOffset := value;
end;
constructor TBlake2BTreeConfig.Create;
begin
Inherited Create();
ValidateInnerHashSize(64);
FInnerHashSize := 64;
end;
end.
|
namespace RemObjects.Elements.EUnit;
interface
uses
Sugar;
type
Assert = public partial static class {$IF NOUGAT}mapped to Object{$ENDIF}
private
method Fail(Actual, Expected: Object; Message: String := nil);
method FailIf(Condition: Boolean; Message: String);
method FailIf(Condition: Boolean; Actual, Expected : Object; Message: String := nil);
method FailIfNot(Condition: Boolean; Message: String);
method FailIfNot(Condition: Boolean; Actual, Expected : Object; Message: String := nil);
public
method Fail(Message: String);
end;
implementation
class method Assert.Fail(Message: String);
begin
if Message = nil then
Message := AssertMessages.Unknown;
raise new AssertException(Message);
end;
class method Assert.Fail(Actual: Object; Expected: Object; Message: String);
begin
if Message = nil then
Message := AssertMessages.Unknown;
Fail(String.Format(Message, coalesce(Actual, "(nil)"), coalesce(Expected, "(nil)")));
end;
class method Assert.FailIf(Condition: Boolean; Message: String);
begin
if Condition then
Fail(Message);
end;
class method Assert.FailIf(Condition: Boolean; Actual: Object; Expected: Object; Message: String := nil);
begin
if Condition then
Fail(Actual, Expected, Message);
end;
class method Assert.FailIfNot(Condition: Boolean; Message: String);
begin
FailIf(not Condition, Message);
end;
class method Assert.FailIfNot(Condition: Boolean; Actual: Object; Expected: Object; Message: String := nil);
begin
FailIf(not Condition, Actual, Expected, Message);
end;
end. |
(*
Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED
Original name: 0054.PAS
Description: POKER Again and Again
Author: LEE BARKER
Date: 11-02-93 10:33
*)
{
LEE BARKER
I'm trying to Write a small Poker game For a grade in my
High School Pascal Class.
While the Array of Strings will work, it is a lot of overhead
for what you want to do. It is also difficult to do the scoring.
The following is a small piece of code I posted a year or two
ago when someone asked a similar question. Offered as a study
guide For your homework.
}
Const
Limit = 5; { Minimum cards before reshuffle }
MaxDecks = 1; { Number of decks in use }
NbrCards = MaxDecks * 52;
Cardvalue : Array [0..12] of String[5] =
('Ace','Two','Three','Four','Five','Six','Seven',
'Eight','Nine','Ten','Jack','Queen','King');
Suit : Array [0..3] of String[8] =
('Hearts','Clubs','Diamonds','Spades');
Type
DeckOfCards = Array [0..Pred(NbrCards)] of Byte;
Var
Count,
NextCard : Integer;
Cards : DeckOfCards;
Procedure shuffle;
Var
i, j,
k, n : Integer;
begin
randomize;
j := 0; { New Decks }
For i := 0 to pred(NbrCards) do
begin
Cards[i] := lo(j);
inc(j);
if j > 51 then
j := 0;
end;
For j := 1 to 3 do { why not ? }
For i := 0 to pred(NbrCards) do
begin { swap }
n := random(NbrCards);
k := Cards[n];
Cards[n] := Cards[i];
Cards[i] := k;
end;
NextCard := NbrCards;
end;
Function CardDealt : Byte;
begin
Dec(NextCard);
CardDealt := Cards[NextCard];
end;
Procedure ShowCard(b : Byte);
Var
c, s : Integer;
begin
c := b mod 13;
s := b div 13;
Writeln('The ', Cardvalue[c], ' of ', Suit[s]);
end;
begin
Shuffle;
Writeln('< The deck is shuffled >');
{ if NextCard <= Limit then shuffle }
For Count := 1 to 5 do
ShowCard(CardDealt);
Readln;
end.
|
unit ExtDirect;
// Generated by ExtToPascal v.0.9.8, at 3/5/2010 11:59:34
// from "C:\Trabalho\ext\docs\output" detected as ExtJS v.3
interface
uses
StrUtils, ExtPascal, ExtPascalUtils, Ext, ExtUtil;
type
TExtDirectProvider = class;
TExtDirectJsonProvider = class;
TExtDirectRemotingProvider = class;
TExtDirectPollingProvider = class;
// Procedural types for events TExtDirectProvider
TExtDirectProviderOnConnect = procedure(Provider : TExtDirectProvider) of object;
TExtDirectProviderOnData = procedure(Provider : TExtDirectProvider; E : TEvent) of object;
TExtDirectProviderOnDisconnect = procedure(Provider : TExtDirectProvider) of object;
TExtDirectProviderOnException = procedure of object;
TExtDirectProvider = class(TExtUtilObservable)
private
FId : String;
FPriority : Integer;
FTypeJS : String;
FConnect : TExtObject;
FDisconnect : TExtObject;
FOnConnect : TExtDirectProviderOnConnect;
FOnData : TExtDirectProviderOnData;
FOnDisconnect : TExtDirectProviderOnDisconnect;
FOnException : TExtDirectProviderOnException;
procedure SetFId(Value : String);
procedure SetFPriority(Value : Integer);
procedure SetFTypeJS(Value : String);
procedure SetFConnect(Value : TExtObject);
procedure SetFDisconnect(Value : TExtObject);
procedure SetFOnConnect(Value : TExtDirectProviderOnConnect);
procedure SetFOnData(Value : TExtDirectProviderOnData);
procedure SetFOnDisconnect(Value : TExtDirectProviderOnDisconnect);
procedure SetFOnException(Value : TExtDirectProviderOnException);
protected
procedure InitDefaults; override;
procedure HandleEvent(const AEvtName: string); override;
public
function JSClassName : string; override;
function IsConnected : TExtFunction;
property Id : String read FId write SetFId;
property Priority : Integer read FPriority write SetFPriority;
property TypeJS : String read FTypeJS write SetFTypeJS;
property Connect : TExtObject read FConnect write SetFConnect;
property Disconnect : TExtObject read FDisconnect write SetFDisconnect;
property OnConnect : TExtDirectProviderOnConnect read FOnConnect write SetFOnConnect;
property OnData : TExtDirectProviderOnData read FOnData write SetFOnData;
property OnDisconnect : TExtDirectProviderOnDisconnect read FOnDisconnect write SetFOnDisconnect;
property OnException : TExtDirectProviderOnException read FOnException write SetFOnException;
end;
TExtDirectJsonProvider = class(TExtDirectProvider)
public
function JSClassName : string; override;
end;
// Procedural types for events TExtDirectRemotingProvider
TExtDirectRemotingProviderOnBeforecall = procedure(Provider : TExtDirectRemotingProvider; Transaction : TExtDirectTransaction) of object;
TExtDirectRemotingProviderOnCall = procedure(Provider : TExtDirectRemotingProvider; Transaction : TExtDirectTransaction) of object;
TExtDirectRemotingProvider = class(TExtDirectJsonProvider)
private
FActions : TExtObject;
FEnableBuffer : Integer; // 10
FEnableBufferBoolean : Boolean;
FEnableUrlEncode : String;
FMaxRetries : Integer;
FNamespace : String;
FNamespaceObject : TExtObject;
FTimeout : Integer;
FUrl : String;
FOnBeforecall : TExtDirectRemotingProviderOnBeforecall;
FOnCall : TExtDirectRemotingProviderOnCall;
procedure SetFActions(Value : TExtObject);
procedure SetFEnableBuffer(Value : Integer);
procedure SetFEnableBufferBoolean(Value : Boolean);
procedure SetFEnableUrlEncode(Value : String);
procedure SetFMaxRetries(Value : Integer);
procedure SetFNamespace(Value : String);
procedure SetFNamespaceObject(Value : TExtObject);
procedure SetFTimeout(Value : Integer);
procedure SetFUrl(Value : String);
procedure SetFOnBeforecall(Value : TExtDirectRemotingProviderOnBeforecall);
procedure SetFOnCall(Value : TExtDirectRemotingProviderOnCall);
protected
procedure InitDefaults; override;
procedure HandleEvent(const AEvtName: string); override;
public
function JSClassName : string; override;
property Actions : TExtObject read FActions write SetFActions;
property EnableBuffer : Integer read FEnableBuffer write SetFEnableBuffer;
property EnableBufferBoolean : Boolean read FEnableBufferBoolean write SetFEnableBufferBoolean;
property EnableUrlEncode : String read FEnableUrlEncode write SetFEnableUrlEncode;
property MaxRetries : Integer read FMaxRetries write SetFMaxRetries;
property Namespace : String read FNamespace write SetFNamespace;
property NamespaceObject : TExtObject read FNamespaceObject write SetFNamespaceObject;
property Timeout : Integer read FTimeout write SetFTimeout;
property Url : String read FUrl write SetFUrl;
property OnBeforecall : TExtDirectRemotingProviderOnBeforecall read FOnBeforecall write SetFOnBeforecall;
property OnCall : TExtDirectRemotingProviderOnCall read FOnCall write SetFOnCall;
end;
// Procedural types for events TExtDirectPollingProvider
TExtDirectPollingProviderOnBeforepoll = procedure(E : TExtDirectPollingProvider) of object;
TExtDirectPollingProviderOnPoll = procedure(E : TExtDirectPollingProvider) of object;
TExtDirectPollingProvider = class(TExtDirectJsonProvider)
private
FBaseParams : TExtObject;
FInterval : Integer; // 3000
FPriority : Integer; // 3
FUrl : String;
FUrlFunction : TExtFunction;
FOnBeforepoll : TExtDirectPollingProviderOnBeforepoll;
FOnPoll : TExtDirectPollingProviderOnPoll;
procedure SetFBaseParams(Value : TExtObject);
procedure SetFInterval(Value : Integer);
procedure SetFPriority(Value : Integer);
procedure SetFUrl(Value : String);
procedure SetFUrlFunction(Value : TExtFunction);
procedure SetFOnBeforepoll(Value : TExtDirectPollingProviderOnBeforepoll);
procedure SetFOnPoll(Value : TExtDirectPollingProviderOnPoll);
protected
procedure InitDefaults; override;
procedure HandleEvent(const AEvtName: string); override;
public
function JSClassName : string; override;
function Connect : TExtFunction;
function Disconnect : TExtFunction;
property BaseParams : TExtObject read FBaseParams write SetFBaseParams;
property Interval : Integer read FInterval write SetFInterval;
property Priority : Integer read FPriority write SetFPriority;
property Url : String read FUrl write SetFUrl;
property UrlFunction : TExtFunction read FUrlFunction write SetFUrlFunction;
property OnBeforepoll : TExtDirectPollingProviderOnBeforepoll read FOnBeforepoll write SetFOnBeforepoll;
property OnPoll : TExtDirectPollingProviderOnPoll read FOnPoll write SetFOnPoll;
end;
implementation
procedure TExtDirectProvider.SetFId(Value : String);
begin
FId := Value;
JSCode('id:' + VarToJSON([Value]));
end;
procedure TExtDirectProvider.SetFPriority(Value : Integer);
begin
FPriority := Value;
JSCode('priority:' + VarToJSON([Value]));
end;
procedure TExtDirectProvider.SetFTypeJS(Value : String);
begin
FTypeJS := Value;
JSCode('typeJS:' + VarToJSON([Value]));
end;
procedure TExtDirectProvider.SetFConnect(Value : TExtObject);
begin
FConnect := Value;
JSCode(JSName + '.connect=' + VarToJSON([Value, false]) + ';');
end;
procedure TExtDirectProvider.SetFDisconnect(Value : TExtObject);
begin
FDisconnect := Value;
JSCode(JSName + '.disconnect=' + VarToJSON([Value, false]) + ';');
end;
procedure TExtDirectProvider.SetFOnConnect(Value : TExtDirectProviderOnConnect);
begin
if Assigned(FOnConnect) then
JSCode(JSName+'.events ["connect"].listeners=[];');
if Assigned(Value) then
On('connect', Ajax('connect', ['Provider', '%0.nm'], true));
FOnConnect := Value;
end;
procedure TExtDirectProvider.SetFOnData(Value : TExtDirectProviderOnData);
begin
if Assigned(FOnData) then
JSCode(JSName+'.events ["data"].listeners=[];');
if Assigned(Value) then
On('data', Ajax('data', ['Provider', '%0.nm','E', '%1.nm'], true));
FOnData := Value;
end;
procedure TExtDirectProvider.SetFOnDisconnect(Value : TExtDirectProviderOnDisconnect);
begin
if Assigned(FOnDisconnect) then
JSCode(JSName+'.events ["disconnect"].listeners=[];');
if Assigned(Value) then
On('disconnect', Ajax('disconnect', ['Provider', '%0.nm'], true));
FOnDisconnect := Value;
end;
procedure TExtDirectProvider.SetFOnException(Value : TExtDirectProviderOnException);
begin
if Assigned(FOnException) then
JSCode(JSName+'.events ["exception"].listeners=[];');
if Assigned(Value) then
On('exception', Ajax('exception', [], true));
FOnException := Value;
end;
function TExtDirectProvider.JSClassName : string;
begin
Result := 'Ext.direct.Provider';
end;
procedure TExtDirectProvider.InitDefaults;
begin
inherited;
FConnect := TExtObject.CreateInternal(Self, 'connect');
FDisconnect := TExtObject.CreateInternal(Self, 'disconnect');
end;
function TExtDirectProvider.IsConnected : TExtFunction;
begin
JSCode(JSName + '.isConnected();', 'TExtDirectProvider');
Result := Self;
end;
procedure TExtDirectProvider.HandleEvent(const AEvtName : string);
begin
inherited;
if (AEvtName = 'connect') and Assigned(FOnConnect) then
FOnConnect(TExtDirectProvider(ParamAsObject('Provider')))
else if (AEvtName = 'data') and Assigned(FOnData) then
FOnData(TExtDirectProvider(ParamAsObject('Provider')), TEvent(ParamAsObject('E')))
else if (AEvtName = 'disconnect') and Assigned(FOnDisconnect) then
FOnDisconnect(TExtDirectProvider(ParamAsObject('Provider')))
else if (AEvtName = 'exception') and Assigned(FOnException) then
FOnException();
end;
function TExtDirectJsonProvider.JSClassName : string;
begin
Result := 'Ext.direct.JsonProvider';
end;
procedure TExtDirectRemotingProvider.SetFActions(Value : TExtObject);
begin
FActions := Value;
JSCode('actions:' + VarToJSON([Value, false]));
end;
procedure TExtDirectRemotingProvider.SetFEnableBuffer(Value : Integer);
begin
FEnableBuffer := Value;
JSCode('enableBuffer:' + VarToJSON([Value]));
end;
procedure TExtDirectRemotingProvider.SetFEnableBufferBoolean(Value : Boolean);
begin
FEnableBufferBoolean := Value;
JSCode('enableBuffer:' + VarToJSON([Value]));
end;
procedure TExtDirectRemotingProvider.SetFEnableUrlEncode(Value : String);
begin
FEnableUrlEncode := Value;
JSCode('enableUrlEncode:' + VarToJSON([Value]));
end;
procedure TExtDirectRemotingProvider.SetFMaxRetries(Value : Integer);
begin
FMaxRetries := Value;
JSCode('maxRetries:' + VarToJSON([Value]));
end;
procedure TExtDirectRemotingProvider.SetFNamespace(Value : String);
begin
FNamespace := Value;
JSCode('namespace:' + VarToJSON([Value]));
end;
procedure TExtDirectRemotingProvider.SetFNamespaceObject(Value : TExtObject);
begin
FNamespaceObject := Value;
JSCode('namespace:' + VarToJSON([Value, false]));
end;
procedure TExtDirectRemotingProvider.SetFTimeout(Value : Integer);
begin
FTimeout := Value;
JSCode('timeout:' + VarToJSON([Value]));
end;
procedure TExtDirectRemotingProvider.SetFUrl(Value : String);
begin
FUrl := Value;
JSCode('url:' + VarToJSON([Value]));
end;
procedure TExtDirectRemotingProvider.SetFOnBeforecall(Value : TExtDirectRemotingProviderOnBeforecall);
begin
if Assigned(FOnBeforecall) then
JSCode(JSName+'.events ["beforecall"].listeners=[];');
if Assigned(Value) then
On('beforecall', Ajax('beforecall', ['Provider', '%0.nm','Transaction', '%1.nm'], true));
FOnBeforecall := Value;
end;
procedure TExtDirectRemotingProvider.SetFOnCall(Value : TExtDirectRemotingProviderOnCall);
begin
if Assigned(FOnCall) then
JSCode(JSName+'.events ["call"].listeners=[];');
if Assigned(Value) then
On('call', Ajax('call', ['Provider', '%0.nm','Transaction', '%1.nm'], true));
FOnCall := Value;
end;
function TExtDirectRemotingProvider.JSClassName : string;
begin
Result := 'Ext.direct.RemotingProvider';
end;
procedure TExtDirectRemotingProvider.InitDefaults;
begin
inherited;
FActions := TExtObject.CreateInternal(Self, 'actions');
FEnableBuffer := 10;
FNamespaceObject := TExtObject.CreateInternal(Self, 'namespace');
end;
procedure TExtDirectRemotingProvider.HandleEvent(const AEvtName : string);
begin
inherited;
if (AEvtName = 'beforecall') and Assigned(FOnBeforecall) then
FOnBeforecall(TExtDirectRemotingProvider(ParamAsObject('Provider')), TExtDirectTransaction(ParamAsObject('Transaction')))
else if (AEvtName = 'call') and Assigned(FOnCall) then
FOnCall(TExtDirectRemotingProvider(ParamAsObject('Provider')), TExtDirectTransaction(ParamAsObject('Transaction')));
end;
procedure TExtDirectPollingProvider.SetFBaseParams(Value : TExtObject);
begin
FBaseParams := Value;
JSCode('baseParams:' + VarToJSON([Value, false]));
end;
procedure TExtDirectPollingProvider.SetFInterval(Value : Integer);
begin
FInterval := Value;
JSCode('interval:' + VarToJSON([Value]));
end;
procedure TExtDirectPollingProvider.SetFPriority(Value : Integer);
begin
FPriority := Value;
JSCode('priority:' + VarToJSON([Value]));
end;
procedure TExtDirectPollingProvider.SetFUrl(Value : String);
begin
FUrl := Value;
JSCode('url:' + VarToJSON([Value]));
end;
procedure TExtDirectPollingProvider.SetFUrlFunction(Value : TExtFunction);
begin
FUrlFunction := Value;
JSCode('url:' + VarToJSON([Value, true]));
end;
procedure TExtDirectPollingProvider.SetFOnBeforepoll(Value : TExtDirectPollingProviderOnBeforepoll);
begin
if Assigned(FOnBeforepoll) then
JSCode(JSName+'.events ["beforepoll"].listeners=[];');
if Assigned(Value) then
On('beforepoll', Ajax('beforepoll', ['E', '%0.nm'], true));
FOnBeforepoll := Value;
end;
procedure TExtDirectPollingProvider.SetFOnPoll(Value : TExtDirectPollingProviderOnPoll);
begin
if Assigned(FOnPoll) then
JSCode(JSName+'.events ["poll"].listeners=[];');
if Assigned(Value) then
On('poll', Ajax('poll', ['E', '%0.nm'], true));
FOnPoll := Value;
end;
function TExtDirectPollingProvider.JSClassName : string;
begin
Result := 'Ext.direct.PollingProvider';
end;
procedure TExtDirectPollingProvider.InitDefaults;
begin
inherited;
FBaseParams := TExtObject.CreateInternal(Self, 'baseParams');
FInterval := 3000;
FPriority := 3;
end;
function TExtDirectPollingProvider.Connect : TExtFunction;
begin
JSCode(JSName + '.connect();', 'TExtDirectPollingProvider');
Result := Self;
end;
function TExtDirectPollingProvider.Disconnect : TExtFunction;
begin
JSCode(JSName + '.disconnect();', 'TExtDirectPollingProvider');
Result := Self;
end;
procedure TExtDirectPollingProvider.HandleEvent(const AEvtName : string);
begin
inherited;
if (AEvtName = 'beforepoll') and Assigned(FOnBeforepoll) then
FOnBeforepoll(TExtDirectPollingProvider(ParamAsObject('E')))
else if (AEvtName = 'poll') and Assigned(FOnPoll) then
FOnPoll(TExtDirectPollingProvider(ParamAsObject('E')));
end;
end. |
namespace com.example.android.basicglsurfaceview;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*}
interface
uses
java.io,
java.nio,
javax.microedition.khronos.egl,
javax.microedition.khronos.opengles,
android.content,
android.graphics,
android.opengl,
android.os,
android.util;
type
GLES20TriangleRenderer = public class(GLSurfaceView.Renderer)
private
const TAG = 'GLES20TriangleRenderer';
const FLOAT_SIZE_BYTES = 4;
const TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
const TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
const TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
const mVertexShader =
'uniform mat4 uMVPMatrix;'#10 +
'attribute vec4 aPosition;'#10 +
'attribute vec2 aTextureCoord;'#10 +
'varying vec2 vTextureCoord;'#10 +
'void main() {'#10 +
' gl_Position = uMVPMatrix * aPosition;'#10 +
' vTextureCoord = aTextureCoord;'#10 +
'}'#10;
const mFragmentShader =
'precision mediump float;'#10 +
'varying vec2 vTextureCoord;'#10 +
'uniform sampler2D sTexture;'#10 +
'void main() {'#10 +
' gl_FragColor = texture2D(sTexture, vTextureCoord);'#10 +
'}'#10;
var mTriangleVerticesData: array of Single := [
// X, Y, Z, U, V
-1.0, -0.5, 0, -0.5, 0.0,
1.0, -0.5, 0, 1.5, -0.0,
0.0, 1.11803399, 0, 0.5, 1.61803399 ]; readonly;
var mTriangleVertices: FloatBuffer;
var mMVPMatrix: array of Single := new Single[16];
var mProjMatrix: array of Single := new Single[16];
var mMMatrix: array of Single := new Single[16];
var mVMatrix: array of Single := new Single[16];
var mProgram: Integer;
var mTextureID: Integer;
var muMVPMatrixHandle: Integer;
var maPositionHandle: Integer;
var maTextureHandle: Integer;
var mContext: Context;
method loadShader(shaderType: Integer; source: String): Integer;
method createProgram(vertexSource, fragmentSource: String): Integer;
method checkGlError(op: String);
public
constructor(ctx: Context);
method onDrawFrame(glUnused: GL10);
method onSurfaceChanged(glUnused: GL10; width, height: Integer);
method onSurfaceCreated(glUnused: GL10; config: javax.microedition.khronos.egl.EGLConfig);
end;
implementation
constructor GLES20TriangleRenderer(ctx: Context);
begin
mContext := ctx;
mTriangleVertices := ByteBuffer.allocateDirect(mTriangleVerticesData.length * FLOAT_SIZE_BYTES).order(ByteOrder.nativeOrder).asFloatBuffer;
mTriangleVertices.put(mTriangleVerticesData).position(0)
end;
method GLES20TriangleRenderer.onDrawFrame(glUnused: GL10);
begin
// Ignore the passed-in GL10 interface, and use the GLES20
// class's static methods instead.
GLES20.glClearColor(0.0, 0.0, 1.0, 1.0);
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT or GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glUseProgram(mProgram);
checkGlError('glUseProgram');
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureID);
mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
checkGlError('glVertexAttribPointer maPosition');
mTriangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
GLES20.glEnableVertexAttribArray(maPositionHandle);
checkGlError('glEnableVertexAttribArray maPositionHandle');
GLES20.glVertexAttribPointer(maTextureHandle, 2, GLES20.GL_FLOAT, false, TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
checkGlError('glVertexAttribPointer maTextureHandle');
GLES20.glEnableVertexAttribArray(maTextureHandle);
checkGlError('glEnableVertexAttribArray maTextureHandle');
var time: Int64 := SystemClock.uptimeMillis mod 4000;
var angle: Single := 0.090 * time;
Matrix.setRotateM(mMMatrix, 0, angle, 0, 0, 1.0);
Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, mMMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);
checkGlError('glDrawArrays')
end;
method GLES20TriangleRenderer.onSurfaceChanged(glUnused: GL10; width, height: Integer);
begin
// Ignore the passed-in GL10 interface, and use the GLES20
// class's static methods instead.
GLES20.glViewport(0, 0, width, height);
var ratio: Single := Single(width) / height;
Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7)
end;
method GLES20TriangleRenderer.onSurfaceCreated(glUnused: GL10; config: javax.microedition.khronos.egl.EGLConfig);
begin
// Ignore the passed-in GL10 interface, and use the GLES20
// class's static methods instead.
mProgram := createProgram(mVertexShader, mFragmentShader);
if mProgram = 0 then
exit;
maPositionHandle := GLES20.glGetAttribLocation(mProgram, 'aPosition');
checkGlError('glGetAttribLocation aPosition');
if maPositionHandle = -1 then
raise new RuntimeException('Could not get attrib location for aPosition');
maTextureHandle := GLES20.glGetAttribLocation(mProgram, 'aTextureCoord');
checkGlError('glGetAttribLocation aTextureCoord');
if maTextureHandle = -1 then
raise new RuntimeException('Could not get attrib location for aTextureCoord');
muMVPMatrixHandle := GLES20.glGetUniformLocation(mProgram, 'uMVPMatrix');
checkGlError('glGetUniformLocation uMVPMatrix');
if muMVPMatrixHandle = -1 then
raise new RuntimeException('Could not get attrib location for uMVPMatrix');
// Create our texture. This has to be done each time the
// surface is created.
var textures: array of Integer := new Integer[1];
GLES20.glGenTextures(1, textures, 0);
mTextureID := textures[0];
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureID);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);
var &is: InputStream := mContext.Resources.openRawResource(R.raw.robot);
var bmp: Bitmap;
try
bmp := BitmapFactory.decodeStream(&is);
finally
try
&is.close;
except
on e: IOException do
;// Ignore.
end;
end;
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bmp, 0);
bmp.recycle;
Matrix.setLookAtM(mVMatrix, 0, 0, 0, -5, 0, 0, 0, 0, 1.0, 0.0);
end;
method GLES20TriangleRenderer.loadShader(shaderType: Integer; source: String): Integer;
begin
var shader: Integer := GLES20.glCreateShader(shaderType);
if shader <> 0 then
begin
GLES20.glShaderSource(shader, source);
GLES20.glCompileShader(shader);
var compiled: array of Integer := new Integer[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if compiled[0] = 0 then
begin
Log.e(TAG, 'Could not compile shader ' + shaderType + ':');
Log.e(TAG, GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader := 0
end
end;
exit shader
end;
method GLES20TriangleRenderer.createProgram(vertexSource, fragmentSource: String): Integer;
begin
var vertexShader: Integer := loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if vertexShader = 0 then
exit 0;
var pixelShader: Integer := loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if pixelShader = 0 then
exit 0;
var program: Integer := GLES20.glCreateProgram;
if program <> 0 then
begin
GLES20.glAttachShader(program, vertexShader);
checkGlError('glAttachShader');
GLES20.glAttachShader(program, pixelShader);
checkGlError('glAttachShader');
GLES20.glLinkProgram(program);
var linkStatus: array of Integer := new Integer[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
if linkStatus[0] <> GLES20.GL_TRUE then
begin
Log.e(TAG, 'Could not link program: ');
Log.e(TAG, GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program := 0
end
end;
exit program
end;
method GLES20TriangleRenderer.checkGlError(op: String);
begin
var error: Integer;
repeat
error := GLES20.glGetError;
if error <> GLES20.GL_NO_ERROR then
begin
Log.e(TAG, op + ': glError ' + error);
raise new RuntimeException(op + ': glError ' + error)
end
until error = GLES20.GL_NO_ERROR
end;
end. |
//------------------------------------------------------------------------------
//Movement UNIT
//------------------------------------------------------------------------------
// What it does-
// An event which will be instantiated when a character requests to move.
//
// Changes -
// January 31st, 2007 - RaX - Created Header.
// [2007/03/28] CR - Cleaned up uses clauses, using Icarus as a guide.
//
//------------------------------------------------------------------------------
unit MovementEvent;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
//none
{Project}
Being,
Event
{3rd Party}
//none
;
type
//------------------------------------------------------------------------------
//TMovementEvent
//------------------------------------------------------------------------------
TMovementEvent = class(TRootEvent)
private
ABeing : TBeing;
public
Procedure Execute; override;
constructor Create(SetExpiryTime : LongWord; Being : TBeing);
end;
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
//Execute UNIT
//------------------------------------------------------------------------------
// What it does-
// The real executing code of the event, actually does whatever the event
// needs to do.
//
// Changes -
// January 31st, 2007 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Procedure TMovementEvent.Execute;
begin
ABeing.Walk;
end;//Execute
//------------------------------------------------------------------------------
constructor TMovementEvent.Create(SetExpiryTime : LongWord; Being : TBeing);
begin
inherited Create(SetExpiryTime);
Self.ABeing := Being;
end;
end. |
unit UFloatEdit;
interface
uses
StdCtrls;
type
TFloatEdit = class
private
FEdit: TEdit;
FValue: double;
FInteiros: boolean;
FCasasDecimais: cardinal;
procedure EditKeyPress(Sender: TObject; var Key: char);
procedure Formatar;
function GetValue: double;
public
property Value: double read GetValue;
constructor Create(Edit: TEdit; const SomenteInteiros: boolean = false; const CasasDecimais: cardinal = 2);
end;
implementation
uses
SysUtils, Math, Windows;
{ TFloatEdit }
constructor TFloatEdit.Create(Edit: TEdit; const SomenteInteiros: boolean = false; const CasasDecimais: cardinal = 2);
begin
FEdit := Edit;
FEdit.OnKeyPress := EditKeyPress;
FInteiros := SomenteInteiros;
FCasasDecimais := CasasDecimais;
GetValue;
Formatar;
end;
procedure TFloatEdit.EditKeyPress(Sender: TObject; var Key: char);
var
Fator: double;
begin
GetValue;
Fator := 1 / Power(10, FCasasDecimais);
if FInteiros or (FCasasDecimais = 0) then begin
Fator := 1;
end;
if Key in ['0'..'9'] then begin
FValue := FValue * 10 + (ord(Key) - Ord('0')) * Fator;
end
else if Ord(key) = VK_BACK then begin
FValue := Trunc(FValue * Power(10, FCasasDecimais-1)) / Power(10, FCasasDecimais);
end;
Formatar;
Key := #0;
end;
procedure TFloatEdit.Formatar;
var
CasasDecimais: cardinal;
begin
CasasDecimais := FCasasDecimais;
if FInteiros then begin
CasasDecimais := 0;
end;
FEdit.Text := Format('%.' + IntToStr(CasasDecimais) + 'f', [FValue]);
FEdit.SelStart := Length(FEdit.Text);
end;
function TFloatEdit.GetValue: double;
var
CasasDecimais: Cardinal;
begin
CasasDecimais := FCasasDecimais;
if FInteiros then begin
CasasDecimais := 0;
end;
FValue := StrToFloatDef(FEdit.Text, 0);
FValue := RoundTo(FValue, -CasasDecimais);
result := FValue;
end;
end.
|
unit Odontologia.Modelo.Pedido;
interface
uses
Data.DB,
SimpleDAO,
SimpleInterface,
SimpleQueryRestDW,
System.SysUtils,
Odontologia.Modelo.Pedido.Interfaces,
Odontologia.Modelo.Entidades.Pedido,
Odontologia.Modelo.Conexion.RestDW;
type
TModelPedido = class(TInterfacedOBject, iModelPedido)
private
FEntidade: TPEDIDO;
FDAO: iSimpleDao<TPEDIDO>;
FDataSource: TDataSource;
FPedidoItem : iModelPedidoItem;
public
constructor Create;
destructor Destroy; override;
class function New: iModelPedido;
function Entidad: TPEDIDO; overload;
function Entidad(aEntidad: TPEDIDO): iModelPedido; overload;
function DAO: iSimpleDao<TPEDIDO>;
function DataSource(aDataSource: TDataSource): iModelPedido;
function Item : iModelPedidoItem;
end;
implementation
uses
Odontologia.Modelo.PedidoItem;
{ TModelPedido }
constructor TModelPedido.Create;
begin
FEntidade := TPEDIDO.Create;
FDAO := TSimpleDAO<TPEDIDO>.New
(TSimpleQueryRestDW<TPEDIDO>.New(ModelConexion.RESTDWDataBase1));
FPedidoItem := TModelPedidoItem.New;
end;
function TModelPedido.DAO: iSimpleDao<TPEDIDO>;
begin
Result := FDAO;
end;
function TModelPedido.DataSource(aDataSource: TDataSource): iModelPedido;
begin
Result := Self;
FDataSource := aDataSource;
FDAO.DataSource(FDataSource);
end;
destructor TModelPedido.Destroy;
begin
FreeAndNil(FEntidade);
inherited;
end;
function TModelPedido.Entidad(aEntidad: TPEDIDO): iModelPedido;
begin
Result := Self;
FEntidade := aEntidad;
end;
function TModelPedido.Item: iModelPedidoItem;
begin
Result := FPedidoItem;
end;
function TModelPedido.Entidad: TPEDIDO;
begin
Result := FEntidade;
end;
class function TModelPedido.New: iModelPedido;
begin
Result := Self.Create;
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 082552
////////////////////////////////////////////////////////////////////////////////
unit android.media.VolumeShaper_Configuration_Builder;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.media.VolumeShaper_Configuration;
type
JVolumeShaper_Configuration_Builder = interface;
JVolumeShaper_Configuration_BuilderClass = interface(JObjectClass)
['{70106A50-AF68-4182-B32B-AFEA95F520C1}']
function build : JVolumeShaper_Configuration; cdecl; // ()Landroid/media/VolumeShaper$Configuration; A: $1
function init : JVolumeShaper_Configuration_Builder; cdecl; overload; // ()V A: $1
function init(configuration : JVolumeShaper_Configuration) : JVolumeShaper_Configuration_Builder; cdecl; overload;// (Landroid/media/VolumeShaper$Configuration;)V A: $1
function invertVolumes : JVolumeShaper_Configuration_Builder; cdecl; // ()Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function reflectTimes : JVolumeShaper_Configuration_Builder; cdecl; // ()Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function scaleToEndVolume(volume : Single) : JVolumeShaper_Configuration_Builder; cdecl;// (F)Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function scaleToStartVolume(volume : Single) : JVolumeShaper_Configuration_Builder; cdecl;// (F)Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function setCurve(times : TJavaArray<Single>; volumes : TJavaArray<Single>) : JVolumeShaper_Configuration_Builder; cdecl;// ([F[F)Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function setDuration(durationMillis : Int64) : JVolumeShaper_Configuration_Builder; cdecl;// (J)Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function setInterpolatorType(interpolatorType : Integer) : JVolumeShaper_Configuration_Builder; cdecl;// (I)Landroid/media/VolumeShaper$Configuration$Builder; A: $1
end;
[JavaSignature('android/media/VolumeShaper_Configuration_Builder')]
JVolumeShaper_Configuration_Builder = interface(JObject)
['{281BDA89-C6C7-47CD-B758-BC5569FAB169}']
function build : JVolumeShaper_Configuration; cdecl; // ()Landroid/media/VolumeShaper$Configuration; A: $1
function invertVolumes : JVolumeShaper_Configuration_Builder; cdecl; // ()Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function reflectTimes : JVolumeShaper_Configuration_Builder; cdecl; // ()Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function scaleToEndVolume(volume : Single) : JVolumeShaper_Configuration_Builder; cdecl;// (F)Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function scaleToStartVolume(volume : Single) : JVolumeShaper_Configuration_Builder; cdecl;// (F)Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function setCurve(times : TJavaArray<Single>; volumes : TJavaArray<Single>) : JVolumeShaper_Configuration_Builder; cdecl;// ([F[F)Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function setDuration(durationMillis : Int64) : JVolumeShaper_Configuration_Builder; cdecl;// (J)Landroid/media/VolumeShaper$Configuration$Builder; A: $1
function setInterpolatorType(interpolatorType : Integer) : JVolumeShaper_Configuration_Builder; cdecl;// (I)Landroid/media/VolumeShaper$Configuration$Builder; A: $1
end;
TJVolumeShaper_Configuration_Builder = class(TJavaGenericImport<JVolumeShaper_Configuration_BuilderClass, JVolumeShaper_Configuration_Builder>)
end;
implementation
end.
|
// -------------------------------------------------------------
// Programa em que o usuário informa os 3 lados de um triângulo
// e ele informa o tipo de triângulo. :~
//
// Autor : Rodrigo Garé Pissarro - Beta Tester
// Contato : rodrigogare@uol.com.br
// -------------------------------------------------------------
Program ExemploPzim ;
Var X, Y, Z: real;
Begin
// Solicita os valores de x, y e z
write('Informe o valor do lado X: ');
readln(x);
write('Informe o valor do lado Y: ');
readln(y);
write('Informe o valor do lado Z: ');
readln(z);
// Imprime o tipo de triângulo
if (x<=0) or (y<=0) or (z<=0) then
begin
writeln('Um triângulo não pode ter lados nulos ou negativos');
end
else if (X>(Y+Z)) or (Y>(X+Z)) or (Z>(X+Y)) then
begin
writeln(X:1:0,', ',Y:1:0,' e ',Z:1:0,' não são lados de um triângulo.');
end
else if (x=y) and (y=z) then
begin
write ('O triângulo é equilátero');
end
else if (x=y) or (x=z) or (y=z) then
begin
write ('O triângulo é isósceles');
end
else
begin
write('O triângulo é escaleno');
end;
End.
|
unit Input_Sum;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls,
cxControls, cxContainer, cxEdit, cxTextEdit, ActnList, cxCheckBox,
cxGroupBox, cxCurrencyEdit;
type
TInput_Sum_Form = class(TForm)
ApplyButton: TcxButton;
CancelButton: TcxButton;
ActionList: TActionList;
Action1: TAction;
GroupBox: TcxGroupBox;
CustGroupBox: TcxGroupBox;
CustEdit: TcxTextEdit;
CustCheckBox: TcxCheckBox;
Label1: TLabel;
fSumCheckBox: TcxCheckBox;
RegNumGroupBox: TcxGroupBox;
RegNumEdit: TcxTextEdit;
RegNumCheckBox: TcxCheckBox;
SumEdit: TcxCurrencyEdit;
procedure SumEditFocusChanged(Sender: TObject);
procedure SumEditKeyPress(Sender: TObject; var Key: Char);
procedure CancelButtonClick(Sender: TObject);
procedure ApplyButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Action1Execute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CustCheckBoxPropertiesChange(Sender: TObject);
procedure CustEditKeyPress(Sender: TObject; var Key: Char);
procedure CustCheckBoxKeyPress(Sender: TObject; var Key: Char);
procedure fSumCheckBoxKeyPress(Sender: TObject; var Key: Char);
procedure RegNumCheckBoxKeyPress(Sender: TObject; var Key: Char);
procedure RegNumEditKeyPress(Sender: TObject; var Key: Char);
procedure RegNumCheckBoxPropertiesChange(Sender: TObject);
private
{ Private declarations }
public
ShowExtras : boolean;
Use_fSum : boolean;
end;
var
Input_Sum_Form: TInput_Sum_Form;
implementation
{$R *.dfm}
function CheckExtended(s : string; Key : Char; Decimal : integer; Position : byte) : boolean;
var
k : integer;
begin
Result := False;
if Key in [#8, #9, #13] then Result := True
else if (Key = #45) then Result := (Position = 0) and (s[1] <> #45) // знак минус
// else if Key = DecimalSeparator then Result := ((Pos(DecimalSeparator, s) = 0) and (Length(s) - Position <= Decimal))
// else if Key = #46 then Result := ((Pos(#46, s) = 0) and (Length(s) - Position <= Decimal))
else if Key = #44 then Result := ((Pos(#44, s) = 0) and (Length(s) - Position <= Decimal))
else if Key in ['0'..'9'] then begin
k := Pos(#46, s);
if (k = 0) or (Position < k) then Result := True
else Result := (Length(s) - k < 2);
end;
end;
procedure TInput_Sum_Form.SumEditFocusChanged(Sender: TObject);
begin
if not SumEdit.Focused and (SumEdit.Text = '') then SumEdit.Text := '0' + DecimalSeparator + '00';
end;
procedure TInput_Sum_Form.SumEditKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then begin
Key := #0;
ApplyButton.SetFocus;
end;
end;
procedure TInput_Sum_Form.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TInput_Sum_Form.ApplyButtonClick(Sender: TObject);
begin
if CustCheckBox.Checked and (CustEdit.Text = '') then begin
ShowMessage('Уведіть назву контрагенту або вимкніть фільтр на нього!');
CustEdit.SetFocus;
Exit;
end;
if RegNumCheckBox.Checked and (RegNumEdit.Text = '') then begin
ShowMessage('Уведіть реєстраційний номер договору або вимкніть фільтр на нього!');
RegNumEdit.SetFocus;
Exit;
end;
ModalResult := mrOk;
end;
procedure TInput_Sum_Form.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TInput_Sum_Form.Action1Execute(Sender: TObject);
begin
CancelButtonClick(Sender);
end;
procedure TInput_Sum_Form.FormShow(Sender: TObject);
begin
if ShowExtras then begin
Height := 302;
CustGroupBox.Visible := True;
ApplyButton.Top := 237;
CancelButton.Top := 237;
end
else begin
Height := 138;
CustGroupBox.Visible := False;
ApplyButton.Top := 72;
CancelButton.Top := 72;
end;
fSumCheckBox.Checked := Use_fSum;
fSumCheckBox.Visible := Use_fSum;
CustCheckBoxPropertiesChange(Sender);
RegNumCheckBoxPropertiesChange(Sender);
{ if SumEdit.Text = '' then SumEdit.Text := '0' + DecimalSeparator + '00';
s := SumEdit.Text;
k := Pos(DecimalSeparator, s);
if k = 0 then s := s + DecimalSeparator + '00'
else if (k > 0) and (Length(SumEdit.Text) - k < 2) then s := s + '0';
SumEdit.Text := s;}
SumEdit.SetFocus;
end;
procedure TInput_Sum_Form.CustCheckBoxPropertiesChange(Sender: TObject);
begin
CustEdit.Enabled := CustCheckBox.Checked;
if CustCheckBox.Checked then CustEdit.SetFocus;
end;
procedure TInput_Sum_Form.CustEditKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then begin
Key := #0;
RegNumCheckBox.SetFocus;
end;
end;
procedure TInput_Sum_Form.CustCheckBoxKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
if CustEdit.Enabled then CustEdit.SetFocus
else RegNumCheckBox.SetFocus;
end;
end;
procedure TInput_Sum_Form.fSumCheckBoxKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
if ShowExtras then CustCheckBox.SetFocus
else ApplyButton.SetFocus;
end;
end;
procedure TInput_Sum_Form.RegNumCheckBoxKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
if RegNumEdit.Enabled then RegNumEdit.SetFocus
else ApplyButton.SetFocus;
end;
end;
procedure TInput_Sum_Form.RegNumEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Key := #0;
ApplyButton.SetFocus;
end;
end;
procedure TInput_Sum_Form.RegNumCheckBoxPropertiesChange(Sender: TObject);
begin
RegNumEdit.Enabled := RegNumCheckBox.Checked;
if RegNumCheckBox.Checked then RegNumEdit.SetFocus;
end;
end.
|
unit uConstants;
interface
{Укр} {Рус}
const nLayoutLang :array[0..1] of PAnsiChar =('00000422','00000419');
const nActiont_OK :array[0..1] of string[5] =('ОК', 'ОК');
const nActiont_Cansel :array[0..1] of string[10] =('Відмінити', '');
const nHintActiont_OK :array[0..1] of string[5] =('ОК', 'ОК');
const nHintActiont_Cansel :array[0..1] of string[10] =('Відмінити', '');
const nMsgDlgOk :array[0..1] of string[5] =('Так', '');
const nMsgDlgCansel :array[0..1] of string[10] =('Ні', '');
const nMsgDlgYes :array[0..1] of string[5] =('Так', '');
const nMsgDlgNo :array[0..1] of string[5] =('Ні', '');
const nMsgDlgAbort :array[0..1] of string[10] =('Відмінити', '');
const nMsgDlgRetry :array[0..1] of string[10] =('Повторити', '');
const nMsgDlgIgnore :array[0..1] of string[15] =('Ігнорувати', '');
const nMsgDlgAll :array[0..1] of string[5] =('Все', '');
const nMsgDlgHelp :array[0..1] of string[10] =('Допомога', '');
const nMsgDlgNoToAll :array[0..1] of string[15] =('Ні для всіх', '');
const nMsgDlgYesToAll :array[0..1] of string[15] =('Так для всіх', '');
const nLabelLogin :array[0..1] of string[10] =('Логін', 'Логин');
const nLabelPassword :array[0..1] of string[10] =('Пароль', 'Пароль');
const nFormLogin_Caption :array[0..1] of string[25] =('Контракти абітурієнтів', 'Контракты абитуриентов');
const nFormAbitCn_Caption :array[0..1] of string[25] =('Контракти абітурієнтів', 'Контракты абитуриентов');
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const nActiont_Obnov :array[0..1] of string[10] =('Оновити', 'Обновить');
const nAction_Exit :array[0..1] of string[10] =('Вийти', 'Выйти');
const nActionAddCN :array[0..1] of string[20] =('Додати договір', 'Добавить договор');
const nActionChangeCN :array[0..1] of string[20] =('Змінити договір', 'Изменить договор');
const nActionDelCN :array[0..1] of string[20] =('Видалити договір', 'Удалить договор');
const nActionChangeCN_Status :array[0..1] of string[20] =('Змінити статус', 'Изменить статус');
const nActiontPrint :array[0..1] of string[10] =('Друк', 'Печать');
const nHintAction_Obnov :array[0..1] of string[10] =('Оновити', 'Обновить');
const nHintAction_Exit :array[0..1] of string[10] =('Вийти', 'Выйти');
const nHintAction_Add :array[0..1] of string[10] =('Додати', 'Добавить');
const nHintAction_Change :array[0..1] of string[10] =('Змінити', 'Изменить');
const nHintAction_Del :array[0..1] of string[10] =('Видалити', 'Удалить');
const nHintActiontPrint :array[0..1] of string[10] =('Друк', 'Печать');
const nHintActionChangeCN_Status :array[0..1] of string[40] =('Змінити статус договору на кандидат', 'Изменить статус договора на кандидат');
const nHintActiontSign :array[0..1] of string[10] =('Підписати', 'Подписать');
const nHintActiontUnsign :array[0..1] of string[15] =('Зняти підпис', 'Снять подпись');
const nHintActiontPriceCurrent :array[0..1] of string[15] =('Прейскурант', 'Прейскурант');
const nStatBarObnov :array[0..1] of string[20] =('F5 - Обновити', '');
const nStatBarExit :array[0..1] of string[20] =('Esc - Вийти', '');
const ncolFIO :array[0..1] of string[5] =('ПІБ', 'ФИО');
const ncolNOMER_DELA :array[0..1] of string[15] =('№ справи', '№ дела');
const ncolNAME_FAK :array[0..1] of string[15] =('Факультет', 'Факультет');
const ncolNAME_SPEC :array[0..1] of string[15] =('Спеціальність', 'Специальность');
const ncolSHORT_NAME_CN_FORM_STUD:array[0..1] of string[15] =('Форма навч.', 'Форма обуч.');
const ncolSHORT_NAME_CN_KAT_STUD :array[0..1] of string[20] =('ОКР','ОКР');
const ncolIS_LOCKED :array[0..1] of string[15] =('Контракт', 'Контракт');
const ncxGroupBoxContracts :array[0..1] of string[30] =('Контракти', 'Контракты');
const ncxGroupBoxFilter :array[0..1] of string[15] =('Фільтр', 'Фильтр');
const nLabelOnToday :array[0..1] of string[15] =('За сьогодні', 'За сегодня');
const nLabelOnAll :array[0..1] of string[15] =('Всі', 'Все');
const nLabelButtonFilter :array[0..1] of string[15] =('Фільтрувати', 'Фильтровать');
const nLabelTIN :array[0..1] of string[20] =('Податковий номер', 'Налоговый номер');
const LabelSpec :array[0..1] of string[15] =('Спеціальність', 'Специальность');
const nLabelFIO :array[0..1] of string[15] =('Прізвище', 'Фамилия');
const nLabelBeg :array[0..1] of string[5] =('Поч.', 'Нач.');
const nLabelEnd :array[0..1] of string[5] =('Кін.', 'Кон.');
const ncolNUM_DOG :array[0..1] of string[5] =('Номер', 'Номер');
const ncolDATE_DOG :array[0..1] of string[5] =('Дата', 'Дата');
const ncolSUMMA :array[0..1] of string[5] =('Сума', 'Сумма');
const nLabelNAME_DOG_STATUS :array[0..1] of string[20] =('Статус', 'Статус');
const nLabelNAME_DOG_TYPE :array[0..1] of string[20] =('Тип', 'Тип');
const nLabelMFO :array[0..1] of string[20] =('МФО', 'МФО');
const nLabelFIO_PAYER :array[0..1] of string[20] =('Платник', 'Плательщик');
const nMsgErrorTransaction:array[0..1] of string[50] =('Неможливо виповнити запит!',
'Невозможно выполнить запрос');
const nMsgTryAgain :array[0..1] of string[20] =('Спробуйте ще раз.','Попробуйте еще');
const nMsgOr :array[0..1] of string[5] =(' Або ',' Или ');
const nMsgBoxTitle :array[0..1] of PAnsiChar =('Увага','Внимание');
const nMsgToAdmin :array[0..1] of string[60] =('Зверніться, будь ласка, до адміністратора',
'Обратитесь к администратору');
const nMsgDelContract :array[0..1] of string[60] =('Ви дійсно бажаєте видалити контракт цього абітуріента',
'Вы действительно хотите удалить контракт этого абитуриента');
const nMsgChangeCN_Status :array[0..1] of string[60] =('Ви дійсно бажаєте змінити статус договору на кандидат',
'Вы действительно хотите изменить статус договора на кандидат');
const nActionLink :array[0..1] of string[15] =('Зв`язяти', 'Связать');
const nActionPrikzObnov3 :array[0..1] of string[15] =('Наказ 3 ПК', 'Приказ 3 ПК');
const nActionPrikzObnov12 :array[0..1] of string[15] =('Наказ 1,2,4 ПК', 'Приказ 1,2,4 ПК');
const nMsgIsSigned :array[0..1] of string[60] =('Цей контракт вже підписан!','Этот контракт уже подписан!');
const nMsgIsNotSigned :array[0..1] of string[60] =('Цей контракт ще не підписан!','Этот контракт еще не подписан!');
const nMsgIsActSigned :array[0..1] of string[60] =('Kонтракт підписан!','Kонтракт подписан!');
const nMsgIsActNotSigned :array[0..1] of string[60] =('З контракту знят підпис!','С контракта снята подпись!');
const nMsgNotHaveRights :array[0..1] of String=('Ви не маєте повноважень для здійснення даної дії!',
'У Вас нет прав для осуществления данного действия!');
const nMsgGoToAdmin :array[0..1] of String=('Зверніться до адміністратора.','Обратитесь к администратору.');
const nMsgActionDenied :array[0..1] of String=('Дія заборонена','Действие запрещено');
const nMsgEditDenied :array[0..1] of String=('Ви не маєте прав редагувати цей контракт','Ви не имеете прав редактировать этот контракт');
const nMsgUnadded :array[0..1] of String=('Спочатку необхідно додати контракт!','Сначала необходимо добавить контракт');
const nMsgSignDeny :array[0..1] of String=('Ви не маєте прав на підпис контрактів абітурієнтів!','Ви не имеете прав на подпись контрактов абитуриентов');
const nMsgUnSignDeny :array[0..1] of String=('Ви не маєте прав на зняття підпису з контрактів абітурієнтів!','Ви не имеете прав на снятие подписи с контрактов абитуриентов!');
const nMsgDeny :array[0..1] of String=('Ви не маєте прав виконувати цю дію!','Ви не имеете прав на віполнение єтого действия!');
implementation
end.
|
unit UnitFormMain;
{===============================================================================
CodeRage 9 - Demo for Threaded Database Access
This code shows how to use database access in such a way that it does not
block or delay the user interface with waits.
The query that takes a long time is wrapped in a TTask.Run and executed in
parallel. The result of this query is then put in a local cache and the
user interface is updated to indicate the data is now available for viewing.
Author: Danny Wind
===============================================================================}
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
System.Rtti, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Fmx.Bind.Grid,
System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.Components,
Data.Bind.Grid, Data.Bind.DBScope, FMX.Layouts, FMX.Grid, FMX.ListView.Types,
FMX.ListView, FMX.Memo, FMX.TabControl, FMX.Gestures, System.Actions,
FMX.ActnList, System.Threading;
type
TFormMain = class(TForm)
ListView1: TListView;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
TabControlMain: TTabControl;
TabItemItem: TTabItem;
TabItemDetail: TTabItem;
MemoDetail: TMemo;
ActionList1: TActionList;
PreviousTabAction: TPreviousTabAction;
NextTabAction: TNextTabAction;
GestureManager1: TGestureManager;
LinkListControlToField1: TLinkListControlToField;
LinkPropertyToFieldSelectedTag: TLinkPropertyToField;
procedure ListView1ItemClick(const Sender: TObject;
const AItem: TListViewItem);
procedure LinkListControlToField1FilledListItem(Sender: TObject;
const AEditor: IBindListEditorItem);
procedure ListView1UpdateObjects(const Sender: TObject;
const AItem: TListViewItem);
procedure FormShow(Sender: TObject);
procedure FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo;
var Handled: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TabControlMainChange(Sender: TObject);
private
{ Private declarations }
TaskArray: array of ITask;
procedure UpdateAccessoryObject(aItem: TListViewItem);
public
{ Public declarations }
procedure RequestContent(aItem: TListViewItem);
function CancelRequestContent(aItem: TListViewItem): Boolean;
end;
var
FormMain: TFormMain;
implementation
{$R *.fmx}
uses System.IOUtils, UnitDataMain, UnitDataThread;
function TFormMain.CancelRequestContent(aItem: TListViewItem): Boolean;
var
lID: Integer;
begin
lID := aItem.Tag;
if (TaskArray[lID] <> nil)
and (TaskArray[lID].Status = TTaskStatus.WaitingToRun) then
begin
TaskArray[lID].Cancel;
{Store content in cache}
DataModuleMain.SetContent(lID, 'Loading canceled...');
Result := true;
end
else
Result := false;
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
SetLength(TaskArray, 10);
end;
procedure TFormMain.FormDestroy(Sender: TObject);
var
i: Integer;
begin
for I := 0 to 9 do
begin
if (TaskArray[i] <> nil) then
TaskArray[i].Cancel;
end;
end;
procedure TFormMain.FormGesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
{$IFDEF ANDROID}
case EventInfo.GestureID of
sgiLeft:
begin
if TabControlMain.ActiveTab <> TabControlMain.Tabs[TabControlMain.TabCount-1] then
TabControlMain.ActiveTab := TabControlMain.Tabs[TabControlMain.TabIndex+1];
Handled := True;
end;
sgiRight:
begin
if TabControlMain.ActiveTab <> TabControlMain.Tabs[0] then
TabControlMain.ActiveTab := TabControlMain.Tabs[TabControlMain.TabIndex-1];
Handled := True;
end;
end;
{$ENDIF}
end;
procedure TFormMain.FormShow(Sender: TObject);
begin
Log.Timestamp('SHOW ThreadedDatabase');
end;
procedure TFormMain.LinkListControlToField1FilledListItem(Sender: TObject;
const AEditor: IBindListEditorItem);
var
lIndex: Integer;
lItem: TListViewItem;
begin
{Fires when ListView Items are loaded or the connected dataset is updated.}
lIndex := AEditor.CurrentIndex;
if lIndex >= 0 then
begin
lItem := ListView1.Items[lIndex];
UpdateAccessoryObject(lItem);
end;
end;
procedure TFormMain.ListView1ItemClick(const Sender: TObject;
const AItem: TListViewItem);
var
lID: Integer;
begin
{Request or Display Content
There is a LiveBinding between the ID field and aItem.Tag}
lID := AItem.Tag;
case DataModuleMain.GetMark(lID) of
TAccessoryType.More:
begin
{Mark as on its way}
DataModuleMain.SetMark(lID, TAccessoryType.Checkmark);
{Update in GUI}
UpdateAccessoryObject(AItem);
{Request content for item}
RequestContent(AItem);
end;
TAccessoryType.CheckMark:
begin {Cancel pending request if possible}
if CancelRequestContent(AItem) then
begin
{Mark as not loaded}
DataModuleMain.SetMark(lID, TAccessoryType.More);
{Update indication in GUI}
UpdateAccessoryObject(AItem);
{Update content as canceled in detail}
DataModuleMain.SetContent(lID, 'Loading canceled...');
end;
end;
TAccessoryType.Detail:
begin {Load content from cache into detail}
MemoDetail.Lines.Clear;
MemoDetail.Lines.Add(DataModuleMain.GetContent(lID));
end;
end;
end;
procedure TFormMain.ListView1UpdateObjects(const Sender: TObject;
const AItem: TListViewItem);
begin
{ListView Resize or SCreen Rotate}
UpdateAccessoryObject(AItem);
end;
procedure TFormMain.RequestContent(aItem: TListViewItem);
var
lID: Integer;
begin
lID := aItem.Tag;
{Mark content is loading in cache}
DataModuleMain.SetContent(lID, 'Loading content....');
TaskArray[lID] := TTask.Run(
procedure
var
lDataModuleThread: TDataModuleThread;
lContent: string;
begin
{Load content}
lDataModuleThread := TDataModuleThread.Create(nil);
try
lContent := lDataModuleThread.GetContent(lID);
finally
lDataModuleThread.Free;
end;
TThread.Synchronize(nil,
procedure
begin
{Store content in cache}
DataModuleMain.SetContent(lID, lContent);
{Mark as loaded}
DataModuleMain.SetMark(lID, TAccessoryType.Detail);
{Update indication in GUI}
UpdateAccessoryObject(AItem);
end);
end)
end;
procedure TFormMain.TabControlMainChange(Sender: TObject);
begin
if (TabControlMain.ActiveTab = TabItemDetail) then
begin
MemoDetail.Lines.Clear;
MemoDetail.Lines.Add(DataModuleMain.GetContent(ListView1.Selected.Tag));
end;
end;
procedure TFormMain.UpdateAccessoryObject(aItem: TListViewItem);
var
lID: Integer;
begin
{There is a LiveBinding between the ID field and aItem.Tag}
lID := aItem.Tag;
if (DataModuleMain.GetMark(lID) = TAccessoryType.More) then
aItem.Objects.AccessoryObject.Visible := False
else
begin
aItem.Objects.AccessoryObject.AccessoryType := DataModuleMain.GetMark(lID);
aItem.Objects.AccessoryObject.Visible := True;
end;
aItem.Objects.AccessoryObject.Invalidate;
end;
end.
|
unit modexlib; {Header fr modexlib.asm}
Interface
Var
Vscreen:Pointer; {Zeiger auf Quellbereich fr p13_2_modex}
vpage:Word; {Offset der aktuell unsichtbaren Seite}
palette:Array[0..256*3-1] of Byte; {VGA - Palette}
Procedure Init_ModeX; {ModeX einschalten}
Procedure Enter400; {von Mode X nach 400-Zeilen schalten}
Procedure Double; {virtuelle horiz. Auflsung von 640 ein}
Procedure P13_2_ModeX(start,pic_size:word); {Bild auf Mode X - Screen kop.}
Procedure CopyScreen(Ziel,Quelle:Word); {Quell-Seite nach Ziel-Seite kop.}
Procedure Copy_Block(Ziel,Quelle,Breite,Hoehe:Word);
{kopiert Block von Quell-Offset nach Ziel}
Procedure ClrX(pmask:byte); {Mode X - Bildschirm lschen}
Procedure Split(Row:Byte); {Screen-Splitting in Zeile Row}
Procedure Squeeze; {Bild zusammenfahren von oben und unten}
Procedure SetStart(t:Word); {Startadresse des sichtbaren Bilds setzen}
Procedure Switch; {zwischen Seite 0 und 1 hin und herschalten}
Procedure WaitRetrace; {wartet auf Vertikal-Retrace}
Procedure SetPal; {kopiert Palette in VGA-DAC}
Procedure GetPal; {liest Palette aus VGA-DAC aus}
Procedure Fade_Out; {blendet Bild aus}
Procedure Fade_To(Zielpal:Array of Byte; Schritt:Byte);
{blendet von Palette nach Zielpal}
Procedure Pal_Rot(Start,Ziel:Word);
{Rotiert Palettenteil um 1,
wenn Start>Ziel nach oben, sonst unten}
{interne Prozeduren:}
Procedure Screen_Off; {schaltet Bildschirm aus}
Procedure Screen_On; {schaltet Bildschirm wieder ein}
Procedure CRTC_Unprotect; {ermglicht Zugriff auf Horizontal-Timing}
Procedure CRTC_Protect; {verbietet Zugriff wieder}
Procedure Init_Mode13; {schaltet Mode 13h ein}
Procedure Show_Pic13; {Kopiert VScreen auf Mode 13h}
Procedure Make_bw(Var WorkPal:Array of Byte); {Palette auf schwarz/weiá}
Implementation
Procedure Init_ModeX;external;
Procedure Enter400;external;
Procedure Double;external;
Procedure P13_2_ModeX;external;
Procedure CopyScreen;external;
Procedure Copy_Block;external;
Procedure ClrX;external;
Procedure Split;external;
Procedure Squeeze;external;
Procedure SetStart;external;
Procedure Switch;external;
Procedure WaitRetrace;external;
Procedure SetPal;external;
Procedure GetPal;external;
Procedure Fade_Out;external;
Procedure Fade_To;external;
Procedure Pal_Rot;external;
{$l modexlib}
Procedure Screen_Off;
Begin
Port[$3c4]:=1; {Register 1 des TS (TS Mode) selektieren}
Port[$3c5]:=Port[$3c5] or 32; {Bit 5 (Screen Off) setzen}
End;
Procedure Screen_On;
Begin
Port[$3c4]:=1; {Register 1 des TS (TS Mode) selektieren}
Port[$3c5]:=Port[$3c5] and not 32; {Bit 5 (Screen Off lschen}
End;
Procedure CRTC_UnProtect;
Begin
Port[$3d4]:=$11; {Register 11h des CRTC (Vertical Sync End)}
Port[$3d5]:=Port[$3d5] and not $80 {Bit 7 (Protection Bit) lschen}
End;
Procedure CRTC_Protect;
Begin
Port[$3d4]:=$11; {Register 11h des CRTC (Vertical Sync End)}
Port[$3d5]:=Port[$3d5] or $80 {Bit 7 (Protection Bit) setzen}
End;
Procedure Init_Mode13;assembler;
asm
mov ax,13h
int 10h
End;
Procedure Show_Pic13; {Kopiert VScreen auf Mode 13h}
Begin
Move(Vscreen^,Ptr($a000,0)^,64000);
End;
Procedure Make_bw; {Palette nach schwarz/weiá reduzieren}
Var i,sum:Word; {Wertung: 30% rot, 59% grn, 11% blau}
Begin
For i:=0 to 255 do Begin
Sum:=Round(WorkPal[i*3]*0.3 + WorkPal[i*3+1]*0.59 + WorkPal[i*3+2]*0.11);
FillChar(WorkPal[i*3],3,Sum); {Werte eintragen}
End;
End;
Begin
End.
|
unit uDMPet;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDMGlobalNTier, SConnect, DB, DBClient, MConnect, ImgList,
siComp, uUserObj, IdBaseComponent, IdComponent;
const
URL_VERSION = 'http://petcenter.360pet.com/2d1d26.html?mv_pc=';
URL_SUP_VERSION = 'http://petcenter.360pet.com/2d1d26supplies.html';
URL_HLP_VERSION = 'http://petcenter.360pet.com/2d1d26help.html';
type
TDMPet = class(TDMGlobalNTier)
PetCenterConn: TSharedConnection;
MaintenanceConn: TSharedConnection;
LookUpMaintenanceConn: TSharedConnection;
LookUpPetConn: TSharedConnection;
SearchPetConn: TSharedConnection;
cdsPropertyDomain: TClientDataSet;
cdsPropertyDomainProperty: TStringField;
cdsPropertyDomainPropertyValue: TStringField;
LookUpInventoryConn: TSharedConnection;
ReportConn: TSharedConnection;
cdsSysModule: TClientDataSet;
cdsSysModuleModuleInfo: TStringField;
cdsSysModuleVersionNo: TIntegerField;
cdsSysModuleBuildNo: TIntegerField;
cdsSysModuleSeats: TStringField;
cdsSysModuleVersionType: TStringField;
cdsSysModuleRestricForms: TMemoField;
cdsParam: TClientDataSet;
cdsParamIDParam: TIntegerField;
cdsParamSrvParameter: TStringField;
cdsParamSrvValue: TStringField;
cdsParamSrvType: TStringField;
cdsParamIDMenu: TIntegerField;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FUser : TUser;
FWebNews : String;
FOnlineHelp : String;
FWebMain : String;
FLocalPath : String;
FMRKey : String;
FClientRpl : Boolean;
FCorpRpl : Boolean;
FPetIntegration : Boolean;
procedure LoadWebInfo;
protected
procedure OnAfterConnect; override;
public
property SystemUser : TUser read FUser write FUser;
property WebNews : String read FWebNews write FWebNews;
property OnlineHelp : String read FOnlineHelp write FOnlineHelp;
property WebMain : String read FWebMain write FWebMain;
property LocalPath : String read FLocalPath write FLocalPath;
property MRKey : String read FMRKey write FMRKey;
property ClientRpl : Boolean read FClientRpl write FClientRpl;
property CorpRpl : Boolean read FCorpRpl write FCorpRpl;
property PetIntegration : Boolean read FPetIntegration write FPetIntegration;
procedure SetPropertyDomain(AProperty: String; AValue : Variant);
function GetPropertyDomain(AProperty: String) : Variant;
procedure ApplyUpdatePropertyDomain;
function Login : Boolean;
end;
var
DMPet: TDMPet;
implementation
uses uDMGlobal, uLoginForm, uMainRetailKeyConst;
{$R *.dfm}
procedure TDMPet.DataModuleCreate(Sender: TObject);
begin
inherited;
CreateControls;
FUser := TUser.Create;
FLocalPath := ExtractFilePath(Application.ExeName);
LoadWebInfo;
end;
procedure TDMPet.DataModuleDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FUser);
end;
function TDMPet.GetPropertyDomain(AProperty: String): Variant;
begin
Result := Null;
with cdsPropertyDomain do
if Active then
begin
if Locate('Property', AProperty, []) then
Result := FieldByName('PropertyValue').Value;
end;
end;
procedure TDMPet.SetPropertyDomain(AProperty: String; AValue: Variant);
begin
with cdsPropertyDomain do
if Active then
begin
if Locate('Property', AProperty, []) then
begin
Edit;
FieldByName('PropertyValue').AsString := VarToStr(AValue);
Post;
end;
end;
end;
procedure TDMPet.LoadWebInfo;
begin
FWebMain := URL_VERSION;
FWebNews := URL_SUP_VERSION;
FOnlineHelp := URL_HLP_VERSION;
end;
procedure TDMPet.OnAfterConnect;
begin
inherited;
with cdsPropertyDomain do
if not Active then
Open;
with cdsSysModule do
if not Active then
begin
Open;
DataSetControl.RestrictForms := FieldByName('RestricForms').AsString;
end;
with cdsParam do
if not Active then
Open;
if cdsParam.Locate('IDParam', 91, []) then
begin
FPetIntegration := (cdsParam.FieldByName('SrvValue').AsString <> '');
end
else
FPetIntegration := False;
FClientRpl := ActiveConnection.AppServer.IsClientServer;
FCorpRpl := ActiveConnection.AppServer.IsCorpServer;
DataSetControl.SoftwareExpired := ActiveConnection.AppServer.SoftwareAccess(SOFTWARE_PC);
DataSetControl.SoftwareExpirationDate := ActiveConnection.AppServer.SoftwareGetExpDate(SOFTWARE_PC);
FMRKey := ActiveConnection.AppServer.SoftwareKey;
end;
procedure TDMPet.ApplyUpdatePropertyDomain;
begin
with cdsPropertyDomain do
if Active then
ApplyUpdates(0);
end;
function TDMPet.Login : Boolean;
begin
if (FUser.ID = 0) then
begin
with TLoginForm.Create(Self) do
try
Result := Start;
finally
Free;
end;
end
else
Result := True;
end;
end.
|
unit sgDriverNetworking;
interface
uses sgShared, sgTypes, sgNamedIndexCollection;
type
//TCP Connection
CreateTCPHostProcedure = function (const aPort : LongInt) : Boolean;
CreateTCPConnectionProcedure = function (const aDestIP : String; const aDestPort : LongInt; aConType : ConnectionType) : Connection;
AcceptTCPConnectionProcedure = function () : LongInt;
//TCP Message
BroadcastTCPMessageProcedure = procedure (const aMsg : String);
SendTCPMessageProcedure = function (const aMsg : String; const aConnection : Connection) : Connection;
TCPMessageReceivedProcedure = function () : Boolean;
//HTTP Message
SendHTTPRequestProcedure = function (const aReq : HTTPRequest; const aConnection : Connection) : Connection;
//UDP Connection
CreateUDPHostProcedure = function (const aPort : LongInt) : LongInt;
CreateUDPConnectionProcedure = function (const aDestIP : String; const aDestPort, aInPort : LongInt) : Connection;
//UDP Message
UDPMessageReceivedProcedure = function () : Boolean;
SendUDPMessageProcedure = function (const aMsg : String; const aConnection : Connection) : Boolean;
BroadcastUDPMessageProcedure = procedure (const aMsg : String);
//Close Sockets
CloseTCPHostSocketProcedure = function (const aPort: LongInt) : Boolean;
CloseConnectionProcedure = function (var aConnection : Connection; const aCloseUDPSocket : Boolean) : Boolean;
CloseUDPSocketProcedure = function (const aPort : LongInt) : Boolean;
CloseAllTCPHostSocketProcedure = procedure();
CloseAllConnectionsProcedure = procedure(const aCloseUDPSockets : Boolean);
CloseAllUDPSocketProcedure = procedure();
FreeAllNetworkingResourcesProcedure = procedure();
MyIPProcedure = function () : String;
ConnectionCountProcedure = function () : LongInt;
RetreiveConnectionProcedure = function (const aConnectionAt : LongInt) : Connection;
NetworkingDriverRecord = record
CreateTCPHost : CreateTCPHostProcedure;
CreateTCPConnection : CreateTCPConnectionProcedure;
AcceptTCPConnection : AcceptTCPConnectionProcedure;
TCPMessageReceived : TCPMessageReceivedProcedure;
BroadcastTCPMessage : BroadcastTCPMessageProcedure;
SendTCPMessage : SendTCPMessageProcedure;
SendHTTPRequest : SendHTTPRequestProcedure;
CreateUDPHost : CreateUDPHostProcedure;
CreateUDPConnection : CreateUDPConnectionProcedure;
UDPMessageReceived : UDPMessageReceivedProcedure;
SendUDPMessage : SendUDPMessageProcedure;
BroadcastUDPMessage : BroadcastUDPMessageProcedure;
CloseTCPHostSocket : CloseTCPHostSocketProcedure;
CloseConnection : CloseConnectionProcedure;
CloseUDPSocket : CloseUDPSocketProcedure;
MyIP : MyIPProcedure;
ConnectionCount : ConnectionCountProcedure;
RetreiveConnection : RetreiveConnectionProcedure;
CloseAllTCPHostSocket : CloseAllTCPHostSocketProcedure;
CloseAllConnections : CloseAllConnectionsProcedure;
CloseAllUDPSocket : CloseAllUDPSocketProcedure;
FreeAllNetworkingResources : FreeAllNetworkingResourcesProcedure;
end;
var
NetworkingDriver : NetworkingDriverRecord;
implementation
uses
{$IFDEF SWINGAME_SDL2}sgDriverNetworkingSDL2{$ELSE}sgDriverNetworkingSDL{$ENDIF};
procedure LoadDefaultNetworkingDriver();
begin
{$IFDEF SWINGAME_SDL13}
LoadSDLNetworkingDriver();
{$ELSE}
LoadSDLNetworkingDriver();
{$ENDIF}
end;
function DefaultMyIPProcedure() : String;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.MyIP();
end;
function DefaultConnectionCountProcedure() : LongInt;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.ConnectionCount();
end;
function DefaultRetreiveConnectionProcedure(const aConnectionAt : LongInt) : Connection;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.RetreiveConnection(aConnectionAt);
end;
//----------------------------------------------------------------------------
// TCP Connection Handling
//----------------------------------------------------------------------------
function DefaultCreateTCPHostProcedure(const aPort : LongInt) : Boolean;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.CreateTCPHost(aPort);
end;
function DefaultCreateTCPConnectionProcedure(const aDestIP : String; const aDestPort : LongInt; aConType : ConnectionType) : Connection;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.CreateTCPConnection(aDestIP, aDestPort, aConType);
end;
function DefaultAcceptTCPConnectionProcedure() : LongInt;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.AcceptTCPConnection();
end;
//----------------------------------------------------------------------------
// TCP Message Handling
//----------------------------------------------------------------------------
function DefaultTCPMessageReceivedProcedure() : Boolean;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.TCPMessageReceived();
end;
function DefaultSendTCPMessageProcedure(const aMsg : String; const aConnection : Connection) : Connection;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.SendTCPMessage(aMsg, aConnection);
end;
procedure DefaultBroadcastTCPMessageProcedure(const aMsg : String);
begin
LoadDefaultNetworkingDriver();
NetworkingDriver.BroadcastTCPMessage(aMsg);
end;
//----------------------------------------------------------------------------
// HTTP Message Handling
//----------------------------------------------------------------------------
function DefaultSendHTTPRequestProcedure(const aReq: HTTPRequest; const aConnection : Connection) : Connection;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.SendHTTPRequest(aReq, aConnection);
end;
//----------------------------------------------------------------------------
// UDP Connections
//----------------------------------------------------------------------------
function DefaultCreateUDPHostProcedure(const aPort : LongInt) : LongInt;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.CreateUDPHost(aPort);
end;
function DefaultCreateUDPConnectionProcedure(const aDestIP : String; const aDestPort, aInPort : LongInt) : Connection;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.CreateUDPConnection(aDestIP, aDestPort, aInPort);
end;
//----------------------------------------------------------------------------
// UDP Message
//----------------------------------------------------------------------------
function DefaultUDPMessageReceivedProcedure() : Boolean;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.UDPMessageReceived();
end;
function DefaultSendUDPMessageProcedure(const aMsg : String; const aConnection : Connection) : Boolean;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.SendUDPMessage(aMsg, aConnection);
end;
procedure DefaultBroadcastUDPMessageProcedure(const aMsg : String);
begin
LoadDefaultNetworkingDriver();
NetworkingDriver.BroadcastUDPMessage(aMsg);
end;
//----------------------------------------------------------------------------
// Close Single
//----------------------------------------------------------------------------
function DefaultCloseTCPHostSocketProcedure(const aPort : LongInt) : Boolean;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.CloseTCPHostSocket(aPort);
end;
function DefaultCloseConnectionProcedure(var aConnection : Connection; const aCloseUDPSocket : Boolean) : Boolean;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.CloseConnection(aConnection, aCloseUDPSocket);
end;
function DefaultCloseUDPSocketProcedure(const aPort : LongInt) : Boolean;
begin
LoadDefaultNetworkingDriver();
result := NetworkingDriver.CloseUDPSocket(aPort);
end;
//----------------------------------------------------------------------------
// Close All
//----------------------------------------------------------------------------
procedure DefaultCloseAllTCPHostSocketProcedure();
begin
LoadDefaultNetworkingDriver();
NetworkingDriver.CloseAllTCPHostSocket();
end;
procedure DefaultCloseAllConnectionsProcedure(const aCloseUDPSockets : Boolean);
begin
LoadDefaultNetworkingDriver();
NetworkingDriver.CloseAllConnections(aCloseUDPSockets);
end;
procedure DefaultCloseAllUDPSocketProcedure();
begin
LoadDefaultNetworkingDriver();
NetworkingDriver.CloseAllUDPSocket();
end;
procedure DefaultFreeAllNetworkingResourcesProcedure();
begin
LoadDefaultNetworkingDriver();
NetworkingDriver.FreeAllNetworkingResources();
end;
initialization
begin
NetworkingDriver.CreateTCPHost := @DefaultCreateTCPHostProcedure;
NetworkingDriver.CreateTCPConnection := @DefaultCreateTCPConnectionProcedure;
NetworkingDriver.AcceptTCPConnection := @DefaultAcceptTCPConnectionProcedure;
NetworkingDriver.TCPMessageReceived := @DefaultTCPMessageReceivedProcedure;
NetworkingDriver.BroadcastTCPMessage := @DefaultBroadcastTCPMessageProcedure;
NetworkingDriver.SendTCPMessage := @DefaultSendTCPMessageProcedure;
NetworkingDriver.SendHTTPRequest := @DefaultSendHTTPRequestProcedure;
NetworkingDriver.CreateUDPHost := @DefaultCreateUDPHostProcedure;
NetworkingDriver.CreateUDPConnection := @DefaultCreateUDPConnectionProcedure;
NetworkingDriver.UDPMessageReceived := @DefaultUDPMessageReceivedProcedure;
NetworkingDriver.SendUDPMessage := @DefaultSendUDPMessageProcedure;
NetworkingDriver.BroadcastUDPMessage := @DefaultBroadcastUDPMessageProcedure;
NetworkingDriver.CloseTCPHostSocket := @DefaultCloseTCPHostSocketProcedure;
NetworkingDriver.CloseConnection := @DefaultCloseConnectionProcedure;
NetworkingDriver.CloseUDPSocket := @DefaultCloseUDPSocketProcedure;
NetworkingDriver.MyIP := @DefaultMyIPProcedure;
NetworkingDriver.ConnectionCount := @DefaultConnectionCountProcedure;
NetworkingDriver.RetreiveConnection := @DefaultRetreiveConnectionProcedure;
NetworkingDriver.CloseAllTCPHostSocket := @DefaultCloseAllTCPHostSocketProcedure;
NetworkingDriver.CloseAllConnections := @DefaultCloseAllConnectionsProcedure;
NetworkingDriver.CloseAllUDPSocket := @DefaultCloseAllUDPSocketProcedure;
NetworkingDriver.FreeAllNetworkingResources := @DefaultFreeAllNetworkingResourcesProcedure;
end;
end. |
(*
Category: SWAG Title: RECORD RELATED ROUTINES
Original name: 0001.PAS
Description: BLOCKRW1.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:55
*)
{
Does anyone have any examples of how to Write Text to a File using
blockWrite?
}
Program DemoBlockWrite;
Const
{ Carriage-return + Line-feed Constant. }
co_CrLf = #13#10;
Var
st_Temp : String;
fi_Temp : File;
wo_BytesWritten : Word;
begin
{ Assign 5 lines of Text to temp String. }
st_Temp := 'Line 1 of Text File' + co_CrLf + 'Line 2 of Text File'
+ co_CrLf + co_CrLf + 'Line 4 of Text File' + co_CrLf +
' My name is MUD ' + co_CrLf;
assign(fi_Temp, 'TEST.TXT');
{$I-}
reWrite(fi_Temp, 1);
{$I+}
if (ioresult <> 0) then
begin
Writeln('Error creating TEST.TXT File');
Halt
end;
{ Write 5 lines of Text to File. }
BlockWrite(fi_Temp, st_Temp[1], length(st_Temp), wo_BytesWritten);
{ Check For errors writing Text to File. }
if (wo_BytesWritten <> length(st_Temp)) then
begin
Writeln('Error writing Text to File!');
Halt
end;
{ Close File. }
Close(fi_Temp);
{ Attempt to open Text File again. }
Assign(fi_Temp, 'TEST.TXT');
{$I-}
Reset(fi_Temp, 1);
{$I+}
if (IOResult <> 0) then
begin
Writeln('Error opening TEST.TXT File');
Halt
end;
st_Temp := 'Guy';
{ Position File-Pointer just before the 'MUD' in Text. }
seek(fi_Temp, 77);
{ Correct my name by overwriting old Text With new. }
blockWrite(fi_Temp, st_Temp[1], length(st_Temp), wo_BytesWritten);
{ Check For errors writing Text to File. }
if (wo_BytesWritten <> length(st_Temp)) then
begin
Writeln('Error writing Text to File!');
Halt
end;
Close(fi_Temp)
end.
|
unit DbProperties;
interface
uses
SysUtils, Classes, Controls, TypInfo,
Db,
dcedit, dcfdes, dcsystem, dcdsgnstuff;
type
TListingProperty = class(TStringProperty)
protected
procedure GetValueList(List: TStrings); virtual; abstract;
public
procedure GetValues(Proc: TGetStrProc); override;
end;
//
TTableNameProperty = class(TListingProperty)
protected
function GetConnectionPropName: string;
procedure GetValueList(List: TStrings); override;
public
function GetAttributes: TPropertyAttributes; override;
end;
//
TFieldNameProperty = class(TListingProperty)
protected
function GetDataSourcePropName: string;
procedure GetValueList(List: TStrings); override;
public
function GetAttributes: TPropertyAttributes; override;
end;
procedure RegisterDbProperties;
implementation
uses
TpDb;
procedure RegisterDbProperties;
begin
RegisterPropertyEditor(TypeInfo(string), nil, 'TableName',
TTableNameProperty);
RegisterPropertyEditor(TypeInfo(string), nil, 'FieldName',
TFieldNameProperty);
end;
{ TListingProperty }
procedure TListingProperty.GetValues(Proc: TGetStrProc);
var
i: Integer;
values: TStringList;
begin
values := TStringList.Create;
try
GetValueList(values);
for i := 0 to Pred(values.Count) do
Proc(values[I]);
finally
values.Free;
end;
end;
{ TTableNameProperty }
function TTableNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [ paValueList ];
end;
function TTableNameProperty.GetConnectionPropName: string;
begin
Result := 'Db';
end;
procedure TTableNameProperty.GetValueList(List: TStrings);
var
db: TTpDb;
begin
try
db := GetObjectProp(GetComponent(0), GetConnectionPropName)
as TTpDb;
if (db <> nil) and (db.DesignConnection.Connected) then
db.DesignConnection.Connection.GetTableNames(List);
except
end;
end;
{ TFieldNameProperty }
function TFieldNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [ paValueList ];
end;
function TFieldNameProperty.GetDataSourcePropName: string;
begin
Result := 'DataSource';
end;
procedure TFieldNameProperty.GetValueList(List: TStrings);
var
ps: TTpDataSource;
begin
try
ps := GetObjectProp(GetComponent(0), GetDataSourcePropName)
as TTpDataSource;
if (ps <> nil) and (ps.DataSet <> nil) then
ps.DataSet.GetFieldNames(List);
except
end;
end;
end.
|
unit Chapter09._08_Solution2;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Math,
DeepStar.Utils;
/// 300. Longest Increasing Subsequence
/// https://leetcode.com/problems/longest-increasing-subsequence/description/
/// 动态规划
/// 时间复杂度: O(n^2)
/// 空间复杂度: O(n)
type
TSolution = class(TObject)
public
function LengthOfLIS(nums: TArr_int): integer;
end;
procedure Main;
implementation
procedure Main;
begin
with TSolution.Create do
begin
WriteLn(LengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18]));
Free;
end;
end;
{ TSolution }
function TSolution.LengthOfLIS(nums: TArr_int): integer;
var
memo: TArr_int;
i, j, res: integer;
begin
if Length(nums) = 0 then Exit(0);
// memo[i] 表示以 nums[i] 为结尾的最长上升子序列的长度
SetLength(memo, Length(nums));
TArrayUtils_int.FillArray(memo, 1);
for i := 1 to High(nums) do
begin
for j := 0 to i - 1 do
begin
if nums[i] > nums[j] then
memo[i] := Max(memo[i], 1 + memo[j]);
end;
end;
res := memo[0];
for i := 1 to High(nums) do
res := Max(res, memo[i]);
Result := res;
end;
end.
|
Program main;
{$mode objfpc}
uses
feli_storage,
feli_file,
feli_logger,
feli_crypto,
feli_validation,
feli_config,
feli_user,
feli_exceptions,
feli_operators,
feli_event,
feli_collection,
feli_document,
feli_user_event,
feli_event_ticket,
feli_event_participant,
feli_response,
feli_middleware,
feli_stack_tracer,
feli_ascii_art,
feli_access_level,
feli_constants,
feli_directions,
sysutils,
fphttpapp,
httpdefs,
httproute,
dateutils,
fpjson;
const
port = 8081;
var
testMode: boolean;
procedure debug();
begin
FeliStorageAPI.debug;
FeliFileAPI.debug;
FeliValidation.debug;
end;
function parseRequestJsonBody(req: TRequest): TJsonObject;
var
bodyContent: ansiString;
begin
FeliStackTrace.trace('begin', 'function parseRequestJsonBody(req: TRequest): TJsonObject;');
bodyContent := req.content;
try
result := TJsonObject(getJson(bodyContent));
except
on E: Exception do
begin
FeliLogger.error(e.message);
result := TJsonObject.create();
end;
end;
FeliStackTrace.trace('end', 'function parseRequestJsonBody(req: TRequest): TJsonObject;');
end;
procedure userAuthMiddleware(var middlewareContent: FeliMiddleware; req: TRequest);
var
username, password: ansiString;
requestJson: TJsonObject;
begin
FeliStackTrace.trace('begin', 'procedure userAuthMiddleware(var middlewareContent: FeliMiddleware; req: TRequest);');
requestJson := parseRequestJsonBody(req);
try
username := requestJson.getPath('auth.username').asString;
password := requestJson.getPath('auth.password').asString;
middlewareContent.user := FeliStorageAPI.getUser(username);
if (middlewareContent.user <> nil) then
begin
middlewareContent.user.password := password;
middlewareContent.authenticated := middlewareContent.user.verify();
end
else
begin
middlewareContent.authenticated := false;
end;
except
on E: Exception do
begin
FeliLogger.error(e.message);
end;
end;
FeliStackTrace.trace('end', 'procedure userAuthMiddleware(var middlewareContent: FeliMiddleware; req: TRequest);');
end;
procedure responseWithJson(var res: TResponse; responseTemplate: FeliResponse);
begin
FeliStackTrace.trace('begin', 'procedure responseWithJson(var res: TResponse; responseTemplate: FeliResponse);');
res.content := responseTemplate.toJson();
res.code := responseTemplate.resCode;
res.contentType := 'application/json;charset=utf-8';
res.SetCustomHeader('access-control-allow-origin', '*');
res.ContentLength := length(res.Content);
res.SendContent;
FeliStackTrace.trace('end', 'procedure responseWithJson(var res: TResponse; responseTemplate: FeliResponse);');
end;
(*
End points begin
*)
procedure error404(req: TRequest; res: TResponse);
var
responseTemplate: FeliResponse;
begin
FeliStackTrace.trace('begin', 'procedure error404(req: TRequest; res: TResponse);');
FeliLogger.error(format('Error 404 "%s" not found', [req.URI]));
try
responseTemplate := FeliResponse.create();
responseTemplate.resCode := 404;
responseTemplate.error := '404 Not Found';
responseWithJson(res, responseTemplate);
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure error404(req: TRequest; res: TResponse);');
end;
procedure pingEndpoint(req: TRequest; res: TResponse);
var
responseTemplate: FeliResponse;
begin
FeliStackTrace.trace('begin', 'procedure pingEndpoint(req: TRequest; res: TResponse);');
try
responseTemplate := FeliResponse.create();
responseTemplate.resCode := 200;
responseTemplate.msg := 'Pong!';
responseWithJson(res, responseTemplate);
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure pingEndpoint(req: TRequest; res: TResponse);');
end;
procedure getUsersEndPoint(req: TRequest; res: TResponse);
var
users: FeliUserCollection;
responseTemplate: FeliResponseDataArray;
begin
FeliStackTrace.trace('begin', 'procedure getUsersEndPoint(req: TRequest; res: TResponse);');
try
users := FeliStorageAPI.getUsers();
users.orderBy(FeliUserKeys.username, FeliDirections.ascending);
responseTemplate := FeliResponseDataArray.create();
responseTemplate.data := users.toSecureTJsonArray();
responseTemplate.resCode := 200;
responseWithJson(res, responseTemplate);
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure getUsersEndPoint(req: TRequest; res: TResponse);');
end;
procedure getEventsEndPoint(req: TRequest; res: TResponse);
var
events: FeliEventCollection;
responseTemplate: FeliResponseDataArray;
begin
FeliStackTrace.trace('begin', 'procedure getEventsEndPoint(req: TRequest; res: TResponse);');
try
events := FeliStorageAPI.getEvents();
events.orderBy(FeliEventKeys.startTime, FeliDirections.ascending);
responseTemplate := FeliResponseDataArray.create();
responseTemplate.data := events.toTJsonArray();
responseTemplate.resCode := 200;
responseWithJson(res, responseTemplate);
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure getEventsEndPoint(req: TRequest; res: TResponse);');
end;
procedure getEventEndPoint(req: TRequest; res: TResponse);
var
eventId: ansiString;
event: FeliEvent;
responseTemplate: FeliResponseDataObject;
begin
FeliStackTrace.trace('begin', 'procedure getEventEndPoint(req: TRequest; res: TResponse);');
try
eventId := req.routeParams['eventId'];
event := FeliStorageAPI.getEvent(eventId);
responseTemplate := FeliResponseDataObject.create();
if (event <> nil) then
begin
responseTemplate.data := event.toTJsonObject();
responseTemplate.resCode := 200;
end
else
begin
responseTemplate.resCode := 404;
end;
responseWithJson(res, responseTemplate);
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure getEventEndPoint(req: TRequest; res: TResponse);');
end;
procedure joinEventEndPoint(req: TRequest; res: TResponse);
var
eventId, ticketId: ansiString;
event: FeliEvent;
responseTemplate: FeliResponseDataObject;
middlewareContent: FeliMiddleware;
requestJson: TJsonObject;
tempCollection: FeliCollection;
begin
FeliStackTrace.trace('begin', 'procedure joinEventEndPoint(req: TRequest; res: TResponse);');
try
eventId := req.routeParams['eventId'];
event := FeliStorageAPI.getEvent(eventId);
responseTemplate := FeliResponseDataObject.create();
middlewareContent := FeliMiddleware.create();
userAuthMiddleware(middlewareContent, req);
requestJson := parseRequestJsonBody(req);
try
ticketId := requestJson.getPath('ticket_id').asString;
except
ticketId := '';
end;
if (event <> nil) then
begin
if (middlewareContent.authenticated) then
begin
responseTemplate.authenticated := middlewareContent.authenticated;
if (FeliValidation.fixedValueCheck(middlewareContent.user.accessLevel, [FeliAccessLevel.admin, FeliAccessLevel.participator])) then
begin
tempCollection := event.tickets.where(FeliEventTicketKeys.id, FeliOperators.equalsTo, ticketId);
if (tempCollection.length >= 1) then
begin
middlewareContent.user.joinEvent(eventId, ticketId);
responseTemplate.resCode := 200;
end
else
begin
responseTemplate.resCode := 404;
responseTemplate.error := 'ticket_not_found';
end;
end
else
begin
responseTemplate.resCode := 404;
responseTemplate.error := 'insufficient_permission';
end;
end
else
begin
responseTemplate.resCode := 404;
responseTemplate.error := 'not_authenticated';
end;
end
else
begin
responseTemplate.resCode := 404;
responseTemplate.error := 'event_not_found';
end;
responseWithJson(res, responseTemplate);
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure joinEventEndPoint(req: TRequest; res: TResponse);');
end;
procedure leaveEventEndPoint(req: TRequest; res: TResponse);
var
eventId: ansiString;
event: FeliEvent;
responseTemplate: FeliResponseDataObject;
middlewareContent: FeliMiddleware;
tempCollection: FeliCollection;
begin
FeliStackTrace.trace('begin', 'procedure leaveEventEndPoint(req: TRequest; res: TResponse);');
try
eventId := req.routeParams['eventId'];
event := FeliStorageAPI.getEvent(eventId);
responseTemplate := FeliResponseDataObject.create();
middlewareContent := FeliMiddleware.create();
userAuthMiddleware(middlewareContent, req);
if (event <> nil) then
begin
if (middlewareContent.authenticated) then
begin
responseTemplate.authenticated := middlewareContent.authenticated;
if (FeliValidation.fixedValueCheck(middlewareContent.user.accessLevel, [FeliAccessLevel.admin, FeliAccessLevel.participator])) then
begin
middlewareContent.user.leaveEvent(eventId);
responseTemplate.resCode := 200;
end
else
begin
responseTemplate.resCode := 401;
responseTemplate.error := 'insufficient_permission';
end;
end
else
begin
responseTemplate.resCode := 403;
responseTemplate.error := 'not_authenticated';
end;
end
else
begin
responseTemplate.resCode := 404;
responseTemplate.error := 'event_not_found';
end;
responseWithJson(res, responseTemplate);
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure leaveEventEndPoint(req: TRequest; res: TResponse);');
end;
procedure removeEventEndPoint(req: TRequest; res: TResponse);
var
eventId: ansiString;
event: FeliEvent;
responseTemplate: FeliResponseDataObject;
middlewareContent: FeliMiddleware;
tempCollection: FeliCollection;
begin
FeliStackTrace.trace('begin', 'procedure removeEventEndPoint(req: TRequest; res: TResponse);');
try
eventId := req.routeParams['eventId'];
event := FeliStorageAPI.getEvent(eventId);
responseTemplate := FeliResponseDataObject.create();
middlewareContent := FeliMiddleware.create();
userAuthMiddleware(middlewareContent, req);
if (event <> nil) then
begin
if (middlewareContent.authenticated) then
begin
responseTemplate.authenticated := middlewareContent.authenticated;
if (FeliValidation.fixedValueCheck(middlewareContent.user.accessLevel, [FeliAccessLevel.admin, FeliAccessLevel.organiser])) then
begin
tempCollection := middlewareContent.user.createdEvents.where(FeliUserEventKeys.eventId, FeliOperators.equalsTo, eventId);
if (tempCollection.length > 0) then
begin
middlewareContent.user.removeCreatedEvent(eventId);
responseTemplate.resCode := 200;
end
else
begin
responseTemplate.resCode := 401;
responseTemplate.error := 'insufficient_permission';
end;
end
else
begin
responseTemplate.resCode := 401;
responseTemplate.error := 'insufficient_permission';
end;
end
else
begin
responseTemplate.resCode := 403;
responseTemplate.error := 'not_authenticated';
end;
end
else
begin
responseTemplate.resCode := 404;
responseTemplate.error := 'event_not_found';
end;
responseWithJson(res, responseTemplate);
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure removeEventEndPoint(req: TRequest; res: TResponse);');
end;
procedure updateEventEndPoint(req: TRequest; res: TResponse);
var
eventId, tempString, error: ansiString;
event: FeliEvent;
responseTemplate: FeliResponseDataObject;
middlewareContent: FeliMiddleware;
tempCollection: FeliCollection;
eventObject, requestJson: TJsonObject;
begin
FeliStackTrace.trace('begin', 'procedure updateEventEndPoint(req: TRequest; res: TResponse);');
try
eventId := req.routeParams['eventId'];
event := FeliStorageAPI.getEvent(eventId);
responseTemplate := FeliResponseDataObject.create();
middlewareContent := FeliMiddleware.create();
userAuthMiddleware(middlewareContent, req);
requestJson := parseRequestJsonBody(req);
if (event <> nil) then
begin
if (middlewareContent.authenticated) then
begin
responseTemplate.authenticated := middlewareContent.authenticated;
if (FeliValidation.fixedValueCheck(middlewareContent.user.accessLevel, [FeliAccessLevel.admin, FeliAccessLevel.organiser])) then
begin
if (event.organiser = middlewareContent.user.username) then
begin
try
eventObject := requestJson.getPath('event') as TJsonObject;
with event do
begin
try name := eventObject.getPath(FeliEventKeys.name).asString; except end;
try description := eventObject.getPath(FeliEventKeys.description).asString; except end;
try venue := eventObject.getPath(FeliEventKeys.venue).asString; except end;
try theme := eventObject.getPath(FeliEventKeys.theme).asString; except end;
try tempString := eventObject.getPath(FeliEventKeys.startTime).asString; except end;
try startTime := StrToInt64(tempString); except end;
tempString := 'err';
try tempString := eventObject.getPath(FeliEventKeys.endTime).asString; except end;
try endTime := StrToInt64(tempString); except end;
tempString := 'err';
try tempString := eventObject.getPath(FeliEventKeys.participantLimit).asString; except end;
try participantLimit := StrToInt64(tempString); except end;
if (event.validate(error)) then
begin
FeliStorageAPI.setEvent(event);
responseTemplate.data := event.toTJsonObject();
responseTemplate.resCode := 200;
end
else
begin
responseTemplate.error := error;
responseTemplate.resCode := 400;
end;
end;
except
on E: Exception do
begin
responseTemplate.resCode := 400;
responseTemplate.error := 'an_error_occurred';
end;
end;
// middlewareContent.user.removeCreatedEvent(eventId);
end
else
begin
responseTemplate.resCode := 401;
responseTemplate.error := 'insufficient_permission';
end;
end
else
begin
responseTemplate.resCode := 401;
responseTemplate.error := 'insufficient_permission';
end;
end
else
begin
responseTemplate.resCode := 403;
responseTemplate.error := 'not_authenticated';
end;
end
else
begin
responseTemplate.resCode := 404;
responseTemplate.error := 'event_not_found';
end;
responseWithJson(res, responseTemplate);
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure updateEventEndPoint(req: TRequest; res: TResponse);');
end;
procedure createEventEndPoint(req: TRequest; res: TResponse);
var
eventId, ticketId: ansiString;
event: FeliEvent;
responseTemplate: FeliResponseDataObject;
middlewareContent: FeliMiddleware;
requestJson, eventObject: TJsonObject;
tempString, error: ansiString;
tempReal: real;
ticket: FeliEventTicket;
ticketsArray: TJsonArray;
ticketI: integer;
ticketObject: TJsonObject;
begin
FeliStackTrace.trace('begin', 'procedure createEventEndPoint(req: TRequest; res: TResponse);');
try
responseTemplate := FeliResponseDataObject.create();
middlewareContent := FeliMiddleware.create();
requestJson := parseRequestJsonBody(req);
try
begin
userAuthMiddleware(middlewareContent, req);
responseTemplate.authenticated := middlewareContent.authenticated;
if middlewareContent.authenticated then
begin
try
eventObject := requestJson.getPath('event') as TJsonObject;
event := FeliEvent.create();
with event do
begin
organiser := middlewareContent.user.username;
name := eventObject.getPath(FeliEventKeys.name).asString;
description := eventObject.getPath(FeliEventKeys.description).asString;
venue := eventObject.getPath(FeliEventKeys.venue).asString;
theme := eventObject.getPath(FeliEventKeys.theme).asString;
begin
ticketsArray := eventObject.getPath(FeliEventKeys.tickets) as TJsonArray;
for ticketI := 0 to (ticketsArray.count - 1) do
begin
ticketObject := ticketsArray[ticketI] as TJsonObject;
ticket := FeliEventTicket.create();
ticket.generateId();
ticket.tType := ticketObject.getPath(FeliEventTicketKeys.tType).asString;
tempString := ticketObject.getPath(FeliEventTicketKeys.fee).asString;
ticket.fee := StrToInt64(tempString);
if (ticket.validate(error)) then
begin
tickets.add(ticket);
end;
end;
end;
tempString := eventObject.getPath(FeliEventKeys.startTime).asString;
startTime := StrToInt64(tempString);
tempString := eventObject.getPath(FeliEventKeys.endTime).asString;
endTime := StrToInt64(tempString);
tempString := eventObject.getPath(FeliEventKeys.participantLimit).asString;
participantLimit := StrToInt64(tempString);
if (event.validate(error)) then
begin
middlewareContent.user.createEvent(event);
responseTemplate.data := event.toTJsonObject();
responseTemplate.resCode := 200;
end
else
begin
responseTemplate.error := error;
responseTemplate.resCode := 400;
end;
end;
except
on E: Exception do
begin
responseTemplate.error := e.message;
responseTemplate.resCode := 400;
end;
end;
end
else
begin
responseTemplate.resCode := 403;
responseTemplate.error := 'not_authenticated';
end;
end;
except
on E: Exception do
begin
responseTemplate.error := e.message;
responseTemplate.resCode := 500;
FeliLogger.error(e.message);
end;
end;
responseWithJson(res, responseTemplate);
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure createEventEndPoint(req: TRequest; res: TResponse);');
end;
procedure loginEndPoint(req: TRequest; res: TResponse);
var
responseTemplate: FeliResponseDataObject;
middlewareContent: FeliMiddleware;
begin
FeliStackTrace.trace('begin', 'procedure loginEndPoint(req: TRequest; res: TResponse);');
responseTemplate := FeliResponseDataObject.create();
middlewareContent := FeliMiddleware.create();
try
begin
userAuthMiddleware(middlewareContent, req);
responseTemplate.authenticated := middlewareContent.authenticated;
if middlewareContent.authenticated then
begin
responseTemplate.data := middlewareContent.user.toTJsonObject(true);
responseTemplate.resCode := 200;
end
else
begin
responseTemplate.resCode := 401;
end;
responseWithJson(res, responseTemplate);
end;
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure loginEndPoint(req: TRequest; res: TResponse);');
end;
procedure registerEndPoint(req: TRequest; res: TResponse);
var
registerUser: FeliUser;
responseTemplate: FeliResponseDataObject;
requestJson, registerUserObject: TJsonObject;
begin
FeliStackTrace.trace('begin', 'procedure registerEndPoint(req: TRequest; res: TResponse);');
try
begin
requestJson := parseRequestJsonBody(req);
responseTemplate := FeliResponseDataObject.create();
registerUserObject := TJsonObject(requestJson.getPath('register'));
registerUser := FeliUser.fromTJsonObject(registerUserObject);
try
registerUser.validate();
registerUser.generateSaltedPassword();
FeliStorageAPI.addUser(registerUser); // Error
responseTemplate.data := registerUser.toTJsonObject(true);
responseTemplate.resCode := 200;
except
on E: Exception do
begin
responseTemplate.resCode := 405;
responseTemplate.error := e.message;
end;
end;
responseWithJson(res, responseTemplate);
end;
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure registerEndPoint(req: TRequest; res: TResponse);');
end;
procedure generateAnalysisEndPoint(req: TRequest; res: TResponse);
var
responseTemplate: FeliResponseDataObject;
middlewareContent: FeliMiddleware;
begin
FeliStackTrace.trace('begin', 'procedure loginEndPoint(req: TRequest; res: TResponse);');
responseTemplate := FeliResponseDataObject.create();
middlewareContent := FeliMiddleware.create();
try
begin
userAuthMiddleware(middlewareContent, req);
responseTemplate.authenticated := middlewareContent.authenticated;
if middlewareContent.authenticated then
begin
responseTemplate.data := middlewareContent.user.generateAnalysis();
responseTemplate.resCode := 200;
end
else
begin
responseTemplate.resCode := 401;
end;
responseWithJson(res, responseTemplate);
end;
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure loginEndPoint(req: TRequest; res: TResponse);');
end;
procedure asciiEndpoint(req: TRequest; res: TResponse);
var
responseTemplate: FeliResponse;
uploadedFile: TUploadedFile;
tempString: ansiString;
height, width: int64;
begin
FeliStackTrace.trace('begin', 'procedure asciiEndpoint(req: TRequest; res: TResponse);');
try
responseTemplate := FeliResponse.create();
responseTemplate.resCode := 202;
tempString := req.QueryFields.ValueFromIndex[0];
if (tempString <> '') then height := StrToInt64(tempString);
tempString := req.QueryFields.ValueFromIndex[1];
if (tempString <> '') then width := StrToInt64(tempString);
// if (height <> nil and width <> nil) then
FeliLogger.debug(format('Request Ascii Art %dx%d', [height, width]));
// req.Query;
// req.QueryString;
// req.QueryFields;
try
uploadedFile := req.Files.First;
FeliLogger.debug(format('File Name %s', [uploadedFile.FileName]));
FeliLogger.debug(format('File size %d', [uploadedFile.Size]));
FeliLogger.debug(format('Content Type %s', [uploadedFile.ContentType]));
FeliLogger.debug(format('Local File Path %s', [uploadedFile.LocalFileName]));
try
responseTemplate.msg := FeliAsciiArt.generate(uploadedFile.LocalFileName, height, width);
except
on E: Exception do
begin
FeliLogger.error(e.message);
end;
end;
except
on E: Exception do
begin
FeliLogger.error(e.message);
responseTemplate.msg := 'error_file_not_found';
end;
end;
responseWithJson(res, responseTemplate);
finally
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure asciiEndpoint(req: TRequest; res: TResponse);');
end;
procedure serverShutdownEndpoint(req: TRequest; res: TResponse);
var
responseTemplate: FeliResponse;
middlewareContent: FeliMiddleware;
begin
FeliStackTrace.trace('begin', 'procedure serverShutdownEndpoint(req: TRequest; res: TResponse);');
middlewareContent := FeliMiddleware.create();
try
userAuthMiddleware(middlewareContent, req);
responseTemplate := FeliResponse.create();
if ((middlewareContent.user <> nil) and (middlewareContent.authenticated) and (FeliValidation.fixedValueCheck(middlewareContent.user.accessLevel, [FeliAccessLevel.admin]))) then
begin
responseTemplate.authenticated := middlewareContent.authenticated;
responseTemplate.resCode := 202;
responseTemplate.msg := 'server_shutting_down';
FeliLogger.info('Shutting down server');
application.terminate();
end
else
begin
responseTemplate.resCode := 401;
responseTemplate.msg := 'insufficient_permission';
end;
responseWithJson(res, responseTemplate);
finally
middlewareContent.free();
responseTemplate.free();
end;
FeliStackTrace.trace('end', 'procedure serverShutdownEndpoint(req: TRequest; res: TResponse);');
end;
(*
End points End
*)
procedure init();
begin
FeliStackTrace.trace('begin', 'procedure init();');
application.port := port;
HTTPRouter.RegisterRoute('/api/users/get', @getUsersEndPoint);
HTTPRouter.RegisterRoute('/api/events/get', @getEventsEndPoint);
HTTPRouter.RegisterRoute('/api/event/:eventId/get', @getEventEndPoint);
HTTPRouter.RegisterRoute('/api/event/:eventId/join', @joinEventEndPoint);
HTTPRouter.RegisterRoute('/api/event/:eventId/leave', @leaveEventEndPoint);
HTTPRouter.RegisterRoute('/api/event/:eventId/remove', @removeEventEndPoint);
HTTPRouter.RegisterRoute('/api/event/:eventId/update', @updateEventEndPoint);
HTTPRouter.RegisterRoute('/api/event/post', @createEventEndPoint);
HTTPRouter.RegisterRoute('/api/login', @loginEndPoint);
HTTPRouter.RegisterRoute('/api/register', @registerEndPoint);
HTTPRouter.RegisterRoute('/api/generateAnalysis', @generateAnalysisEndPoint);
httpRouter.registerRoute('/api/shutdown', @serverShutdownEndpoint);
httpRouter.registerRoute('/api/ascii', @asciiEndpoint);
httpRouter.registerRoute('/api/ping', @pingEndpoint);
httpRouter.registerRoute('/*', @error404, true);
application.threaded := false;
if (not testMode) then begin
application.initialize();
FeliLogger.info(format('HTTP Server listening on port %d', [port]));
application.run();
end;
FeliStackTrace.trace('end', 'procedure init();');
end;
procedure test();
var
// userEvent: FeliUserEvent;
// collection: FeliCollection;
// eventCollection: FeliEventCollection;
// eventArray: TJsonArray;
// eventEnum: TJsonEnum;
// eventObject: TJsonObject;
// eventDocument: FeliEvent;
// ticketDocument: FeliEventTicket;
// document: FeliDocument;
user: FeliUser;
users: FeliUserCollection;
event: FeliEvent;
events: FeliEventCollection;
ticket: FeliEventTicket;
usersTJsonArray: TJsonArray;
eventsTJsonArray: TJsonArray;
i: integer;
debugString: ansiString;
// usersArray: TJsonArray;
// userEnum: TJsonEnum;
// testUsernameString: ansiString;
// testUser: FeliUser;
// users: FeliUserCollection;
// testUser2: FeliUser;
// testUserObject: TJsonObject;
tempVar: boolean;
generatedAnalysis: TJsonObject;
begin
FeliStackTrace.trace('begin', 'procedure test();');
// user := FeliStorageAPI.getUser('FelixNPL');
// generatedAnalysis := user.generateAnalysis();
// writeln(generatedAnalysis.formatJson);
// events := FeliStorageAPI.getEvents();
// events.orderBy(FeliEventKeys.startTime, FeliDirections.ascending);
// eventsTJsonArray := events.toTJsonArray();
// debugString := '';
// for i := 0 to (eventsTJsonArray.count - 1) do
// begin
// event := FeliEvent.fromTJsonObject(eventsTJsonArray[i] as TJsonObject);
// // debugString := debugString + event.id + lineSeparator;
// debugString := debugString + IntToStr(event.startTime) + lineSeparator;
// end;
// writeln(debugString);
// writeln(users.toSecureJson);
// user := FeliStorageAPI.getUser('admin');
// user.removeCreatedEvent('t783fggzf4aRPzMZ0RxNd7JSdQG41rNZ');
// event := FeliEvent.create();
// with event do
// begin
// organiser := user.username;
// name := 'Pascal Generated';
// description := 'A test event from pascal';
// venue := 'Hong Kong';
// theme := 'Fun';
// ticket := FeliEventTicket.create();
// ticket.generateId();
// ticket.tType := 'MVP';
// ticket.fee := 256;
// tickets.add(ticket);
// startTime := DateTimeToUnix(Now()) * 1000 - 8 * 60 * 60 * 1000 + 10000;
// endTime := DateTimeToUnix(Now()) * 1000 - 8 * 60 * 60 * 1000 + 20000;
// participantLimit := 5;
// end;
// user.createEvent(event);
// FeliStorageAPI.removeUser('FelixNPL_NotExist');
// eventCollection := FeliStorageAPI.getEvents();
// writeln(eventCollection.length());
// eventArray := eventCollection.toTJsonArray();
// for eventEnum in eventArray do
// begin
// ticketDocument := FeliEventTicket.create();
// with ticketDocument do
// begin
// id := '25136';
// tType := 'MVP++++++';
// fee := 250;
// end;
// eventObject := eventEnum.value as TJsonObject;
// eventDocument := FeliEvent.fromTJsonObject(eventObject);
// eventDocument.tickets.add(ticketDocument);
// FeliLogger.debug(format('Event name: %s', [eventDocument.name]));
// FeliLogger.debug(format('No. tickets: %d', [eventDocument.tickets.length()]));
// writeln(eventDocument.toJson());
// end;
// eventCollection := FeliEventCollection.create();
// eventCollection.add()
// userEvent := FeliUserEvent.create();
// with userEvent do
// begin
// id := 'event_id';
// createdAt := 1596157198112;
// end;
// writeln(userEvent.toJson());
// document := FeliDocument.create();
// writeln(document.toJson());
// user := FeliStorageAPI.getUser('FelixNPL');
// if (user <> nil) then
// writeln(user.toJson()) else
// writeln('no this user wor');
// Test if code still works (<o/)
// FeliStorageAPI.removeUser('test');
// FeliStorageAPI.removeEvent('0TnpfpamgFEqb5tRUOTeu_DiffHJJB7c');
// FeliStorageAPI.removeEvent('JkV74xTNKUrI_Ser9lIx8qkS6pzLlqgi');
// HaHa still works
// Test type casting
// eventCollection := FeliEventCollection.create();
// collection := eventCollection as FeliCollection;
// collection := FeliCollection.create();
// eventCollection := collection as FeliEventCollection;
// writeln('Success');
// Test events
// event := FeliEvent.create();
// with event do
// begin
// organiser := 'PascalGenerated';
// name := 'Lovely Event';
// description := 'Everyone should join this event, it will be epic';
// venue := 'Space';
// theme := 'Weightless';
// end;
// FeliStorageAPI.addEvent(event);
// event := FeliStorageAPI.getEvent('EB3444FB3A9F183C0');
// if (event <> nil) then
// begin
// writeln('Event Found!');
// end
// else
// begin
// writeln('Oh no, event not found')
// end;
// Test for FeliStorageAPI methods
// FeliStorageAPI.removeUser('add.user.test@example.com');
// testUsernameString := 'FelixNPL';
// testUser := FeliStorageAPI.getUser(testUsernameString);
// FeliLogger.info(format('[User] Username %s', [testUser.username]));
// users := FeliStorageAPI.getUsers();
// users := users.where(FeliUserKeys.username, FeliOperators.equalsTo, testUsernameString);
// usersArray := users.toTJsonArray();
// if (users.length = 0) then
// FeliLogger.debug('[User] No users found')
// else
// for userEnum in usersArray do
// begin
// testUser := FeliUser.fromTJsonObject(TJsonObject(userEnum.value));
// FeliLogger.debug(format('[User] Display name: %s', [testUser.username]));
// end;
// Test for FeliStorageAPI.addUser()
// testUser := FeliUser.create();
// with testUser do begin
// // username := 'FelixNPL';
// // password := '20151529';
// // email := 's20151529@home.npl.edu.hk';
// // firstName := 'Felix';
// // lastName := 'Yeung';
// // displayName := 'Felix NPL';
// // accessLevel := 'admin';
// // salt := 'CD5167D267431D269BA0DA40E692F14B';
// // saltedPassword := '91da52fb59d439167de2a21a87243e29';
// username := 'AddUserTest';
// password := '20151529';
// email := 'test@example.com';
// firstName := 'Test';
// lastName := 'User';
// displayName := 'Add User Test';
// accessLevel := 'organiser';
// end;
// testUser.generateSaltedPassword();
// writeln(testUser.verify());
// try
// FeliStorageAPI.addUser(testUser);
// except
// on e: FeliExceptions.FeliStorageUserExist do writeln('EFeliStorageUserExist', e.message);
// on e: Exception do writeln('oh no', e.message);
// end;
// writeln(testUser.toJson());
// Test for FeliStorageAPI.getUser()
// testUsernameString := 'FelixNPL';
// testUser := FeliStorageAPI.getUser(testUsernameString);
// if (testUser <> nil) then
// begin
// writeln(format('User with username %s has been found', [testUsernameString]));
// writeln(testUser.ToTJsonObject().formatJson);
// end
// else
// writeln(format('User with username %s cannot be found', [testUsernameString]));
// Test for FeliUser
// testUser := FeliUser.create();
// with testUser do
// begin
// username := 'FelixNPL';
// password := '20151529';
// email := 's20151529@home.npl.edu.hk';
// firstName := 'Felix';
// lastName := 'Yeung';
// displayName := 'Felix NPL';
// accessLevel := 'admin';
// salt := 'CD5167D267431D269BA0DA40E692F14B';
// saltedPassword := '91da52fb59d439167de2a21a87243e29';
// end;
// testUserObject := testUser.ToTJsonObject();
// usersArray := FeliStorageAPI.getUsers();
// writeln(usersArray[0].formatJson());
// writeln(testUser.verify());
// testUser2 := FeliUser.fromTJsonObject(TJsonObject(usersArray[0]));
// testUserObject := testUser2.ToTJsonObject();
// writeln(testUserObject.formatJson());
// Test for FeliValidation.emailCheck
// writeln(FeliValidation.emailCheck('info@example.com'));
// writeln(FeliValidation.emailCheck('not.an.email.com'));
// Test for FeliValidation.lengthCheck string inclusively
// writeln(FeliValidation.lengthCheck('123456789', 10, 15, true));
// writeln(FeliValidation.lengthCheck('1234567890', 10, 15, true));
// writeln(FeliValidation.lengthCheck('1234567890123', 10, 15, true));
// writeln(FeliValidation.lengthCheck('123456789012345', 10, 15, true));
// writeln(FeliValidation.lengthCheck('123456789012345678', 10, 15, true));
// Test for FeliValidation.lengthCheck string exclusively
// writeln(FeliValidation.lengthCheck('123456789', 10, 15, false));
// writeln(FeliValidation.lengthCheck('1234567890', 10, 15, false));
// writeln(FeliValidation.lengthCheck('1234567890123', 10, 15, false));
// writeln(FeliValidation.lengthCheck('123456789012345', 10, 15, false));
// writeln(FeliValidation.lengthCheck('123456789012345678', 10, 15, false));
// Test for FeliConfig.getApplicationTerminalLog
// writeln(FeliConfig.getApplicationTerminalLog());
// Test for FeliValidation.rangeCheck integer inclusively
// writeln(FeliValidation.rangeCheck(9, 10, 15, true));
// writeln(FeliValidation.rangeCheck(10, 10, 15, true));
// writeln(FeliValidation.rangeCheck(13, 10, 15, true));
// writeln(FeliValidation.rangeCheck(15, 10, 15, true));
// writeln(FeliValidation.rangeCheck(18, 10, 15, true));
// Test for FeliValidation.rangeCheck integer exclusively
// writeln(FeliValidation.rangeCheck(9, 10, 15, false));
// writeln(FeliValidation.rangeCheck(10, 10, 15, false));
// writeln(FeliValidation.rangeCheck(13, 10, 15, false));
// writeln(FeliValidation.rangeCheck(15, 10, 15, false));
// writeln(FeliValidation.rangeCheck(18, 10, 15, false));
// Test for FeliValidation.rangeCheck float inclusively
// writeln(FeliValidation.rangeCheck(9.5, 10.0, 15.0, true));
// writeln(FeliValidation.rangeCheck(10.0, 10.0, 15.0, true));
// writeln(FeliValidation.rangeCheck(13.3, 10.0, 15.0, true));
// writeln(FeliValidation.rangeCheck(15.0, 10.0, 15.0, true));
// writeln(FeliValidation.rangeCheck(18.5, 10.0, 15.0, true));
// Test for FeliValidation.rangeCheck float exclusively
// writeln(FeliValidation.rangeCheck(9.5, 10.0, 15.0, false));
// writeln(FeliValidation.rangeCheck(10.0, 10.0, 15.0, false));
// writeln(FeliValidation.rangeCheck(13.3, 10.0, 15.0, false));
// writeln(FeliValidation.rangeCheck(15.0, 10.0, 15.0, false));
// writeln(FeliValidation.rangeCheck(18.5, 10.0, 15.0, false));
// Test for FeliCrypto.hashMD5 consistency
// FeliLogger.log(FeliCrypto.hashMD5('test'));
// Test for FeliCrypto.generateSalt salt generation
// FeliLogger.log(FeliCrypto.generateSalt(64));
if (testMode) then begin
FeliLogger.debug('Press <Enter> to continue');
readln;
end;
FeliStackTrace.trace('end', 'procedure test();');
end;
begin
testMode := FeliConfig.getIsDebug();
FeliStackTrace.reset();
FeliStackTrace.trace('begin', 'main');
randomize();
try
if (testMode) then test();
init();
// debug();
except
on err: Exception do FeliLogger.error(err.message);
end;
FeliStackTrace.trace('end', 'main');
end.
|
unit uRptBuildPrintGrid;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ppCtrls, ppBands, ppPrnabl, ppClass, ppVar, ppCache, ppComm, ppRelatv,
ppProd, ppReport, ppDB, ppDBPipe, ppViewr;
type
TFrmRptBuildPrintGrid = class(TForm)
RptGrid: TppReport;
RtpHeader: TppHeaderBand;
RepDetail: TppDetailBand;
RepFooter: TppFooterBand;
ppSystemVariable1: TppSystemVariable;
RtpTitle: TppTitleBand;
ppLabel2: TppLabel;
lbUser: TppLabel;
ppSystemVariable2: TppSystemVariable;
DBPipeline: TppDBPipeline;
RepSummary: TppSummaryBand;
shpDetail: TppShape;
lbTitle: TppLabel;
procedure shpDetailPrint(Sender: TObject);
procedure RptGridPreviewFormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure Start(Print:Boolean);
end;
implementation
{$R *.DFM}
procedure TFrmRptBuildPrintGrid.Start(Print:Boolean);
begin
if Print then
begin
//Print
RptGrid.DeviceType := 'Printer';
end
else
begin
//Preview
RptGrid.DeviceType := 'Screen';
end;
RptGrid.Print;
end;
procedure TFrmRptBuildPrintGrid.shpDetailPrint(Sender: TObject);
begin
if Odd(RptGrid.DetailBand.Count) then
shpDetail.Brush.Color := cl3DLight
else
shpDetail.Brush.Color := clWhite;
end;
procedure TFrmRptBuildPrintGrid.RptGridPreviewFormCreate(Sender: TObject);
begin
RptGrid.PreviewForm.WindowState:= wsMaximized;
TppViewer(RptGrid.PreviewForm.Viewer).ZoomSetting:= zsPageWidth;
end;
end.
|
namespace GLExample;
interface
uses
rtl,
GlHelper,
OpenGL;
type
GL_Example_3 = class(IAppInterface)
private
FLightingShader: Shader;
FRemObjectsVAO: array of VertexArray;
FBox : VertexArray;
FUniformViewPos: GLint;
FUniformLightPosition: GLint;
FUniformLightAmbient: GLint;
FUniformLightDiffuse: GLint;
FUniformLightSpecular: GLint;
FUniformMaterialAmbient: GLint;
FUniformMaterialDiffuse: GLint;
FUniformMaterialSpecular: GLint;
FUniformMaterialShininess: GLint;
FUniformContainerModel: GLint;
FUniformContainerView: GLint;
FUniformContainerProjection: GLint;
FUniformContainerNormalMatrix: GLint;
FmodelRotation : Single;
FLightColor : TVector3;
FFilled : Boolean := true;
Finitilalized : Boolean;
private
method UpdateDrawSettings;
method UpdateViewAndProjection(const width, Height : Single);
method UpdateLight(const LightColor : TVector3);
public
method initialize : Boolean;
method Update(width, Height : Integer; const ATotalTimeSec : Double := 0.3);
method ChangeFillmode;
end;
implementation
method GL_Example_3.initialize: Boolean;
const
BOX_VERTICES: array of Single = [
// Positions // Normals
-0.5, -0.5, -0.5, 0.0, 0.0, -1.0,
0.5, -0.5, -0.5, 0.0, 0.0, -1.0,
0.5, 0.5, -0.5, 0.0, 0.0, -1.0,
-0.5, 0.5, -0.5, 0.0, 0.0, -1.0,
-0.5, -0.5, 0.5, 0.0, 0.0, 1.0,
0.5, -0.5, 0.5, 0.0, 0.0, 1.0,
0.5, 0.5, 0.5, 0.0, 0.0, 1.0,
-0.5, 0.5, 0.5, 0.0, 0.0, 1.0,
-0.5, 0.5, 0.5, -1.0, 0.0, 0.0,
-0.5, 0.5, -0.5, -1.0, 0.0, 0.0,
-0.5, -0.5, -0.5, -1.0, 0.0, 0.0,
-0.5, -0.5, 0.5, -1.0, 0.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0, 0.0,
0.5, 0.5, -0.5, 1.0, 0.0, 0.0,
0.5, -0.5, -0.5, 1.0, 0.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0, 0.0,
-0.5, -0.5, -0.5, 0.0, -1.0, 0.0,
0.5, -0.5, -0.5, 0.0, -1.0, 0.0,
0.5, -0.5, 0.5, 0.0, -1.0, 0.0,
-0.5, -0.5, 0.5, 0.0, -1.0, 0.0,
-0.5, 0.5, -0.5, 0.0, 1.0, 0.0,
0.5, 0.5, -0.5, 0.0, 1.0, 0.0,
0.5, 0.5, 0.5, 0.0, 1.0, 0.0,
-0.5, 0.5, 0.5, 0.0, 1.0, 0.0];
{ The indices define 2 triangles per cube face, 6 faces total }
INDICES: array of UInt16 = [
0, 1, 2, 2, 3, 0,
4, 5, 6, 6, 7, 4,
8, 9, 10, 10, 11, 8,
12, 13, 14, 14, 15, 12,
16, 17, 18, 18, 19, 16,
20, 21, 22, 22, 23, 20];
begin
Finitilalized := true;
{Setup Color}
FLightColor.R := 1;
FLightColor.G := 0;
FLightColor.B :=0;
{ Build and compile our shader programs }
FLightingShader := new Shader('materials.vs', 'materials.fs');
FUniformViewPos := FLightingShader.GetUniformLocation('viewPos');
FUniformLightPosition := FLightingShader.GetUniformLocation('light.position');
FUniformLightAmbient := FLightingShader.GetUniformLocation('light.ambient');
FUniformLightDiffuse := FLightingShader.GetUniformLocation('light.diffuse');
FUniformLightSpecular := FLightingShader.GetUniformLocation('light.specular');
FUniformMaterialAmbient := FLightingShader.GetUniformLocation('material.ambient');
FUniformMaterialDiffuse := FLightingShader.GetUniformLocation('material.diffuse');
FUniformMaterialSpecular := FLightingShader.GetUniformLocation('material.specular');
FUniformMaterialShininess := FLightingShader.GetUniformLocation('material.shininess');
FUniformContainerModel := FLightingShader.GetUniformLocation('model');
FUniformContainerView := FLightingShader.GetUniformLocation('view');
FUniformContainerProjection := FLightingShader.GetUniformLocation('projection');
FUniformContainerNormalMatrix := FLightingShader.GetUniformLocation('normalMatrix');
FLightingShader.Use;
{ Define layout of the attributes in the Lighting shader }
var fVertexLayout := new VertexLayout(FLightingShader._GetHandle)
.Add('position', 3)
.Add('normal', 3)
.Add('texture', 2, false, true); // Ignore the texture Coords if not found in the Shader
var s := new ShapeReader();
var lShape := s.load(Asset.getFullname('remobjects1.Shape'));
if lShape <> nil then
FRemObjectsVAO := lShape.getVecArray(fVertexLayout);
fVertexLayout := new VertexLayout(FLightingShader._GetHandle)
.Add('position', 3)
.Add('normal', 3);
FBox := new VertexArray(fVertexLayout, BOX_VERTICES, INDICES);
end;
method GL_Example_3.UpdateLight(const LightColor : TVector3);
var
DiffuseColor, AmbientColor: TVector3;
NormalMatrix: TMatrix3;
begin
var LIGHT_POS := new TVector3(0.2, 0.2, 8.0);
var VIEW_POS := new TVector3(0.2, 0.0, 3.0);
glUniform3f(FUniformLightPosition, LIGHT_POS.X, LIGHT_POS.Y, LIGHT_POS.Z);
glUniform3f(FUniformViewPos,VIEW_POS.X, VIEW_POS.Y, VIEW_POS.Z);
DiffuseColor := LightColor * 0.5; // Decrease the influence
AmbientColor := DiffuseColor * 0.7; // Low influence
glUniform3f(FUniformLightAmbient, AmbientColor.R, AmbientColor.G, AmbientColor.B);
glUniform3f(FUniformLightDiffuse, DiffuseColor.R, DiffuseColor.G, DiffuseColor.B);
glUniform3f(FUniformLightSpecular, 1.0, 1.0, 1.0);
{ Set material properties }
glUniform3f(FUniformMaterialAmbient, 1.0, 0.5, 0.31);
glUniform3f(FUniformMaterialDiffuse, 1.0, 0.5, 0.31);
glUniform3f(FUniformMaterialSpecular, 0.5, 0.5, 0.5); // Specular doesn't have full effect on this object's material
glUniform1f(FUniformMaterialShininess, 32.0);
{ Create and calculate Normal Matrix }
NormalMatrix.Init;
NormalMatrix := NormalMatrix.Inverse.Transpose;
glUniformMatrix3fv(FUniformContainerNormalMatrix, 1, GL_FALSE,NormalMatrix.getPglMatrix3f);
end;
method GL_Example_3.UpdateDrawSettings;
begin
{ Clear the color and depth buffer }
glClearColor(0.3, 0.3, 0.3, 1.0);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
{ Enable depth testing }
glEnable(GL_DEPTH_TEST);
glCullFace(GL_BACK);
//glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glShadeModel(GL_SMOOTH);
// glPolygonMode(GL_FRONT, GL_LINE); // GL_LINE // GL_POINT //GL_FILL
if FFilled then
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) // GL_LINE // GL_POINT //GL_FILL
else
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
end;
method GL_Example_3.UpdateViewAndProjection(const width, Height : Single);
var Projection, View : TMatrix4;
begin
var rot : Single := 345;
const V : Single = 2.5;
var lAspect : Single := (Height / width);
{ORTHOGNAL VIEW}
Projection.InitOrthoOffCenterLH(-V, V*lAspect, V, -V*lAspect, V, -V);
rot := FmodelRotation;
View.InitRotationYawPitchRoll(Radians(-rot), Radians(rot), Radians(-rot));
{ Pass matrices to shader }
glUniformMatrix4fv(FUniformContainerView, 1, GL_FALSE, View.getPglMatrix4f);
glUniformMatrix4fv(FUniformContainerProjection, 1, GL_FALSE, Projection.getPglMatrix4f);
end;
method GL_Example_3.Update(width, Height : Integer; const ATotalTimeSec : Double := 0.3);
var
Model, Translate, Scale, Rotate: TMatrix4;
begin
if not Finitilalized then Initialize;
{ Use corresponding shader when setting uniforms/drawing objects }
FLightingShader.Use;
{Set the defaults and clear the Buffer}
UpdateDrawSettings;
{Prepare the Ligthing}
FLightColor.R := sin(ATotalTimeSec * 2.0);
FLightColor.G := sin(ATotalTimeSec * 0.7);
FLightColor.B := sin(ATotalTimeSec * 1.3);
UpdateLight(FLightColor);
UpdateViewAndProjection(width, Height);
{ Draw the container 1. Time }
var face : Integer;
// Loop over all 6 Sides
for face := 0 to 5 do
begin
// Rotation of Logo
Model.InitRotationYawPitchRoll(Radians(-FmodelRotation*3), Radians(0), Radians(0));
// Model.Init;
Rotate.Init;
// Prepare Roation for Side
case face of
0 :;
1 : Rotate.InitRotationY(Radians(90));
2 : Rotate.InitRotationY(Radians(180));
3 : Rotate.InitRotationY(Radians(270));
4 : Rotate.InitRotationX(Radians(90));
5 : Rotate.InitRotationX(Radians(270));
end;
// Move left and up
Translate.InitTranslation(-0.40,0,1.10);
// Calculate the finish ModelMatrix
Model := Model * Translate * Rotate ;
glUniformMatrix4fv(FUniformContainerModel, 1, GL_FALSE, Model.getPglMatrix4f);
for lVoa in FRemObjectsVAO do lVoa.Render;
{ Draw the container 2. Time }
Model.InitRotationYawPitchRoll(Radians(FmodelRotation*3), Radians(0), Radians(0));
// Move Right and up
Translate.InitTranslation(0.4,0,1.10);
// Sclae the Logo a little bit in x and y direction
Scale.InitScaling(0.8, 0.8, 1.0);
// Calculate the finish ModelMatrix
Model := Scale * Model * Translate * Rotate;
glUniformMatrix4fv(FUniformContainerModel, 1, GL_FALSE, Model.getPglMatrix4f);
for lVoa in FRemObjectsVAO do lVoa.Render;
end;
{Draw the Box}
Model.InitScaling(2);
glUniformMatrix4fv(FUniformContainerModel, 1, GL_FALSE, Model.getPglMatrix4f);
// glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // GL_LINE // GL_POINT //GL_FILL
var boxcol := new TVector3(0.7,0.7,0.5);
UpdateLight(boxcol);
FBox.Render;
{Change the Rotation in every step}
if FmodelRotation >= 359 then
FmodelRotation := 0 else
FmodelRotation := FmodelRotation + 1.0;
end;
method GL_Example_3.ChangeFillmode;
begin
FFilled := not FFilled;
end;
end. |
unit TrataException;
interface
uses
SysUtils, Forms, System.Classes, Vcl.StdCtrls;
type
IException = interface
['{69C683A9-6388-40F1-9282-42C0DE5ABB70}']
procedure TrataException(Sender: TObject; E: Exception; var Memo: TMemo);
procedure GravarLog(Value: String);
procedure GravarMsg(Value: String);
end;
TException = class(TInterfacedObject, IException)
private
FLogFile: String;
FMsg: TStringList;
FMessage: String;
procedure SetLogFile(const Value: String);
procedure SetMessage(const Value: String);
procedure SetMsg(const Value: TStringList);
function GetMessage: String;
public
constructor Create;
destructor Destroy; override;
procedure TrataException(Sender: TObject; E: Exception;
var Memo: TMemo); overload;
procedure TrataException(Sender: TObject; E: Exception); overload;
procedure GravarLog(Value: String);
procedure GravarMsg(Value: String);
property LogFile: String read FLogFile write SetLogFile;
property Msg: TStringList read FMsg write SetMsg;
property Message: String read GetMessage write SetMessage;
end;
// Exception Exceção genérica, usada apenas como ancestral de todas as outras exceções
// EAbort Exceção silenciosa, pode ser gerada pelo procedimento Abort e não mostra nenhuma mensagem
// EAccessViolation Acesso inválido à memória, geralmente ocorre com objetos não inicializados
// EConvertError Erro de conversão de tipos
// EDivByZero Divisão de inteiro por zero
// EInOutError Erro de Entrada ou Saída reportado pelo sistema operacional
// EIntOverFlow Resultado de um cálculo inteiro excedeu o limite
// EInvalidCast TypeCast inválido com o operador as
// EInvalidOp Operação inválida com número de ponto flutuante
// EOutOfMemory Memória insuficiente
// EOverflow Resultado de um cálculo com número real excedeu o limite
// ERangeError Valor excede o limite do tipo inteiro ao qual foi atribuída
// EUnderflow Resultado de um cálculo com número real é menor que a faixa válida
// EVariantError Erro em operação com variant
// EZeroDivide Divisão de real por zero
// EDatabaseError Erro genérico de banco de dados, geralmente não é usado diretamente
// EDBEngineError Erro da BDE, descende de EDatabaseError e traz dados que podem identificar o erro
//
//
// Read more: http://www.linhadecodigo.com.br/artigo/1258/delphi-tratamento-de-execucoes-robustas.aspx#ixzz6VPojzMWJ
TExceptions = (EUnknown = 0, EException, EEAbort, EEConvertError);
TExceptionsHelper = record helper for TExceptions
function ToString: string;
class function Parse(Value: string): TExceptions; static;
end;
implementation
uses
Vcl.Dialogs;
{ TException }
constructor TException.Create;
begin
FLogFile := ChangeFileExt(ParamStr(0), '.log');
FMsg := TStringList.Create;
Application.OnException := TrataException;
end;
destructor TException.Destroy;
begin
FreeAndNil(FMsg);
end;
function TException.GetMessage: String;
begin
end;
procedure TException.GravarLog(Value: String);
var
txtLog: TextFile;
begin
AssignFile(txtLog, FLogFile);
if FileExists(FLogFile) then
Append(txtLog)
else
Rewrite(txtLog);
Writeln(txtLog, FormatDateTime('dd/mm/YY hh:nn:ss - ', Now) + Value);
CloseFile(txtLog);
end;
procedure TException.GravarMsg(Value: String);
begin
FMsg.Add(Value);
end;
procedure TException.SetLogFile(const Value: String);
begin
FLogFile := Value;
end;
procedure TException.SetMsg(const Value: TStringList);
begin
FMsg := Value;
end;
procedure TException.SetMessage(const Value: String);
begin
FMessage := Value;
end;
procedure TException.TrataException(Sender: TObject; E: Exception;
var Memo: TMemo);
begin
TrataException(Sender, E);
Memo.Lines := FMsg;
end;
procedure TException.TrataException(Sender: TObject; E: Exception);
begin
FMessage := TExceptions.Parse(E.ClassName).ToString;
GravarMsg('=================');
GravarMsg('ClassName: ' + E.ClassName);
GravarMsg('Messagem: ' + E.Message);
end;
{ TExceptionsHelper }
class function TExceptionsHelper.Parse(Value: string): TExceptions;
begin
if Value = 'Exception' then
Result := EException
else if Value = 'EAbort' then
Result := EEAbort
else if Value = 'EConvertError' then
Result := EEConvertError
else
Result := EUnknown;
end;
function TExceptionsHelper.ToString: string;
begin
case self of
EException:
Result := 'Exceção Genérica';
EEAbort:
Result := 'Exceção Abortada';
EEConvertError:
Result := 'Erro de conversão de tipos';
else
Result := '';
end;
end;
var
MinhaException: TException;
initialization
MinhaException := TException.Create;
finalization
MinhaException.Free;
end.
|
unit Testparser;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, System.SysUtils, System.Generics.Collections, parser,
System.Contnrs, System.RegularExpressionsCore, System.StrUtils, Vcl.Dialogs,
System.Classes ;
type
// Test methods for class TDomTree
TestTDomTree = class(TTestCase)
strict private
FDomTree: TDomTree;
public
procedure SetUp; override;
procedure TearDown; override;
end;
// Test methods for class TDomTreeNode
TestTDomTreeNode = class(TTestCase)
strict private
FDomTreeNode: TDomTreeNode;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestRunParse;
procedure TestGetTagName;
procedure TestGetAttrValue;
procedure TestGetTextValue;
procedure TestGetComment;
procedure TestFindNode;
procedure TestFindTagOfIndex;
procedure TestGetXPath;
procedure TestFindXPath;
end;
// Test methods for class TChildList
TestTChildList = class(TTestCase)
strict private
FChildList: TChildList;
public
procedure SetUp; override;
procedure TearDown; override;
end;
// Test methods for class TPrmRecList
TestTPrmRecList = class(TTestCase)
strict private
FPrmRecList: TPrmRecList;
public
procedure SetUp; override;
procedure TearDown; override;
end;
implementation
procedure TestTDomTree.SetUp;
begin
FDomTree := TDomTree.Create;
end;
procedure TestTDomTree.TearDown;
begin
FDomTree.Free;
FDomTree := nil;
end;
procedure TestTDomTreeNode.SetUp;
var
DomTree: TDomTree;
begin
DomTree:=TDomTree.Create ;
FDomTreeNode := DomTree.RootNode;
CheckEquals('Root', FDomTreeNode.Tag);
CheckEquals('', FDomTreeNode.TypeTag);
CheckEquals('', FDomTreeNode.AttributesTxt);
CheckEquals('', FDomTreeNode.Text);
CheckEquals(0, FDomTreeNode.Child.Count);
end;
procedure TestTDomTreeNode.TearDown;
begin
FDomTreeNode.Free;
FDomTreeNode := nil;
end;
procedure TestTDomTreeNode.TestRunParse;
var
ReturnValue: Boolean;
HtmlTxt: TStringList;
tmp: string;
tmpNode: TDomTreeNode;
begin
HtmlTxt:=TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
ReturnValue := FDomTreeNode.RunParse(HtmlTxt.Text);
CheckEquals(true, ReturnValue);
//check <?
CheckEquals('<?xml version="1.0" encoding="UTF-8"?>', FDomTreeNode.Child[0].Tag);
CheckEquals('%s', FDomTreeNode.Child[0].Typetag);
CheckEquals('', FDomTreeNode.Child[0].AttributesTxt);
CheckEquals('', FDomTreeNode.Child[0].Text);
//check multiline comment
tmp:='<!-- <link href="https://ozlotteries.r.worldssl.net/stylesheet/main.css" rel="stylesheet" type="text/css" > 1'#$D#$A'123-->';
CheckEquals(tmp, FDomTreeNode.Child[2].Tag);
//check Exceptions contain any symbols
tmp:='Title "<!-- <'#39'this"/> --> '#39'document';
tmpNode:=FDomTreeNode.Child[3].child[0].child[0].child[0];
CheckEquals(tmp, tmpNode.Text);
tmpNode:=FDomTreeNode.Child[3].child[1].child[1];
CheckEquals('textarea', AnsiLowerCase(tmpNode.Tag));
CheckEquals('This disabled field? don'#39't write here<123/>', tmpNode.child[0].Text);
//check attributes
tmpNode:=FDomTreeNode.Child[3].child[1];
CheckEquals('body', AnsiLowerCase(tmpNode.Tag));
CheckEquals(true, tmpNode.Attributes.ContainsKey('class'));
CheckEquals(true, tmpNode.Attributes.TryGetValue('class',tmp));
CheckEquals('"default"', tmp);
CheckEquals(true, tmpNode.Attributes.ContainsKey('bgcolor'));
CheckEquals(true, tmpNode.Attributes.TryGetValue('bgcolor',tmp));
CheckEquals(#39'blue'#39, tmp);
tmpNode:=FDomTreeNode.Child[3].child[1].child[1];
CheckEquals('textarea', AnsiLowerCase(tmpNode.Tag));
CheckEquals(true, tmpNode.Attributes.ContainsKey('disabled'));
CheckEquals(false, tmpNode.Attributes.TryGetValue('class',tmp));
end;
procedure TestTDomTreeNode.TestGetTagName;
var
ReturnValue: string;
tmpNode : TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt:=TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.RunParse(HtmlTxt.Text);
tmpNode:= FDomTreeNode.Child[3].child[1].child[1];
ReturnValue := tmpNode.GetTagName;
CheckEquals('<textarea disabled cols="30" rows="5">', ReturnValue);
end;
procedure TestTDomTreeNode.TestGetAttrValue;
var
ReturnValue: string;
tmpNode: TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt:=TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.RunParse(HtmlTxt.Text);
tmpNode:= FDomTreeNode.Child[3].child[1].child[3];
ReturnValue := tmpNode.GetAttrValue('id');
CheckEquals('"maincontainer"', ReturnValue);
end;
procedure TestTDomTreeNode.TestGetTextValue;
var
ReturnValue: string;
tmpNode: TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt:=TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.RunParse(HtmlTxt.Text);
tmpNode:= FDomTreeNode.Child[3].child[1].child[3].child[1].child[0].child[0].child[0].child[1].child[0].child[0].child[0].child[0].child[0].child[1].child[1].child[0].child[3].child[1];
ReturnValue := tmpNode.GetTextValue(0);
CheckEquals('Draw 960', ReturnValue);
ReturnValue := tmpNode.GetTextValue(1);
CheckEquals('Draw 960', ReturnValue);
ReturnValue := tmpNode.GetTextValue(2);
CheckEquals('Thursday 9th October 2014', ReturnValue);
// TODO: Validate method results
end;
procedure TestTDomTreeNode.TestGetComment;
var
ReturnValue: string;
tmpNode: TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt:=TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.RunParse(HtmlTxt.Text);
tmpNode:= FDomTreeNode.Child[3].child[1];
ReturnValue := tmpNode.GetComment(0);
CheckEquals('<!-- logo(s) -->', ReturnValue);
ReturnValue := tmpNode.GetComment(1);
CheckEquals('<!-- logo(s) -->', ReturnValue);
end;
procedure TestTDomTreeNode.TestFindNode;
var
ReturnValue: Boolean;
dListNode: TNodeList;
HtmlTxt: TStringList;
begin
HtmlTxt:=TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.RunParse(HtmlTxt.Text);
dListNode:= TNodeList.Create;
//tmpNode:= DomTree.Child[3].child[1].child[3];
ReturnValue := FDomTreeNode.FindNode('', 0, 'id="maincontainer"', True, dListNode);
CheckEquals(true, ReturnValue);
CheckEquals('<div id="maincontainer">', dListNode[0].GetTagName);
dListNode.Clear;
ReturnValue := FDomTreeNode.FindNode('', 0, 'id="maincontainer"', false, dListNode);
CheckEquals(false, ReturnValue);
dListNode.Clear;
ReturnValue := FDomTreeNode.FindNode('div', 0, 'id="TopBox"', True, dListNode);
CheckEquals(true, ReturnValue);
CheckEquals('<div id="TopBox">', dListNode[0].GetTagName);
dListNode.Clear;
ReturnValue := FDomTreeNode.FindNode('h1', 0, '', True, dListNode);
CheckEquals(true, ReturnValue);
CheckEquals('<h1 class="pageTitle logintitle">', dListNode[0].GetTagName);
dListNode.Clear;
end;
procedure TestTDomTreeNode.TestFindTagOfIndex;
var
ReturnValue: Boolean;
dListNode: TNodeList;
tmpNode: TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt:=TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.RunParse(HtmlTxt.Text);
dListNode:= TNodeList.Create;
ReturnValue := FDomTreeNode.FindTagOfIndex('div', 2, false, dListNode);
CheckEquals(false, ReturnValue);
tmpNode:= FDomTreeNode.Child[3].child[1].child[3].child[1].child[0].child[0].child[0].child[1].child[0].child[0].child[0].child[0].child[0].child[1].child[1].child[0].child[3];
ReturnValue := tmpNode.FindTagOfIndex('div', 2, false, dListNode);
CheckEquals(true, ReturnValue);
CheckEquals('<div class="numbers">', dListNode[0].GetTagName);
end;
procedure TestTDomTreeNode.TestGetXPath;
var
ReturnValue: string;
tmpNode: TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt:=TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.RunParse(HtmlTxt.Text);
tmpNode:= FDomTreeNode.Child[3].child[1].child[3].child[1].child[0].child[0].child[0].child[1].child[0].child[0].child[0].child[0].child[0].child[1].child[1].child[0].child[3];
ReturnValue := tmpNode.GetXPath(true);
CheckEquals('//*[@id="TopBox"]/div/div/div/div[1]', ReturnValue);
ReturnValue := tmpNode.GetXPath(false);
CheckEquals('./html/body/div/table/tbody/tr/td/table/tbody/tr/td/div/div/div/div/div/div[1]', ReturnValue);
end;
procedure TestTDomTreeNode.TestFindXPath;
var
ReturnValue: Boolean;
dListValue: TStringList;
dListNode: TNodeList;
HtmlTxt: TStringList;
begin
HtmlTxt:=TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.RunParse(HtmlTxt.Text);
dListNode:= TNodeList.Create;
dListValue:= TStringList.Create;
ReturnValue := FDomTreeNode.FindXPath('//*[@id="TopBox"]/div/div/div/div[1]', dListNode, dListValue);
CheckEquals(true, ReturnValue);
CheckEquals(1, dListNode.Count);
CheckEquals('<div class="result_block result_13">', dListNode[0].GetTagName);
dListNode.Clear;
ReturnValue := FDomTreeNode.FindXPath('//*[@id="TopBox"]/div/div/div/div/div[@class="draw default"]/text()[2]', dListNode, dListValue);
CheckEquals(true, ReturnValue);
CheckEquals(2, dListNode.Count);
CheckEquals(2, dListValue.Count);
CheckEquals('Thursday 9th October 2014', dListValue[0]);
dListNode.Clear;
dListValue.Clear;
ReturnValue := FDomTreeNode.FindXPath('//*[@id="TopBox"]/div/div/div/div/div[@class="numbers"]/table/tbody/tr[2]/td[1]/img[2]/@alt', dListNode, dListValue);
CheckEquals(true, ReturnValue);
CheckEquals(2, dListNode.Count);
CheckEquals(2, dListValue.Count);
CheckEquals('"35"', dListValue[0]);
CheckEquals('"9"', dListValue[1]);
end;
procedure TestTChildList.SetUp;
begin
FChildList := TChildList.Create;
end;
procedure TestTChildList.TearDown;
begin
FChildList.Free;
FChildList := nil;
end;
procedure TestTPrmRecList.SetUp;
begin
FPrmRecList := TPrmRecList.Create;
end;
procedure TestTPrmRecList.TearDown;
begin
FPrmRecList.Free;
FPrmRecList := nil;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTDomTree.Suite);
RegisterTest(TestTDomTreeNode.Suite);
RegisterTest(TestTChildList.Suite);
RegisterTest(TestTPrmRecList.Suite);
end.
|
unit UBullet;
interface
uses
w3system, UPlayer, UPlat, UE;
type TBullet = class(TObject)
Shot : boolean; //True if the bullet is active
Left : boolean; //True if the bullet is going left
Angle : float; //The angle the bullet will travel at
X : float;
Y : float;
Damage : integer; //How much damage the bullet will do
FramesLeft : integer; //How many frames it has left (after hitting something)
//This is so that it does not just disappear, it shows it has hit it
constructor create(isLeft : boolean; newX, newY : float; newDamage : integer; newAngle : float);
procedure update(screenWidth : integer; player : TPlayer; Ais : array of TPlayer;
fixed, rands : array of TPlat);
procedure Move();
function HitPlayer(Player : TPlayer) : boolean;
function HitPlat(Plat : TPlat) : boolean;
function BulletBounds() : array [0 .. 1] of array [0 .. 1] of float;
//First array: 0 = X Axis, 1 = Y Axis
//Second array: 0 = Minimum Bound, 1 = Maximum Bound
end;
const
WIDTH = 15; //The bullet's width
HEIGHT = 5; //The bullet's Height
implementation
constructor TBullet.create(isLeft : boolean; newX, newY : float; newDamage : integer; newAngle : float);
begin
Left := isLeft;
X := newX;
Y := newY;
Shot := True;
FramesLeft := 3;
Damage := newDamage;
Angle := newAngle;
end;
procedure TBullet.update(screenWidth : integer; player : TPlayer; Ais : array of TPlayer;
fixed, rands : array of TPlat);
var
i : integer;
begin
if Shot then //If the bullet is active, it will run code
begin
if (FramesLeft = 3) then //Only check collisions if it has got the maximum frames left, meaning
//it won't hit you through a platform or any other object
begin
while i <= High(fixed) do //iterate through the Fixed Platforms
begin
if HitPlat(fixed[i]) then
begin
//If it has hit the Plat, make the frames left for the bullet to live 2
FramesLeft := 2;
//If the platform will crumble, make it fall
if fixed[i].Crumble then
begin
fixed[i].Crumbling := true;
fixed[i].TimeTillFall := CRUMBLE_DELAY;
end;
end;
i += 1; //Increases 'i' so that it will check the next platfrom
end;
i := 0;
while i <= High(rands) do //iterate through the random platforms
begin
if HitPlat(rands[i]) then
begin
//If it has hit the Plat, make the frames left for the bullet to live 2x
FramesLeft := 2;
//If the platfrom will crumble, make it fall
if rands[i].Crumble then
begin
rands[i].Crumbling := true;
rands[i].TimeTillFall := CRUMBLE_DELAY;
end;
end;
i += 1; //Increases i so that it will check the next platform
end;
end;
if FramesLeft <> 3 then //If the frame is not equal to 3, decrease it
begin
FramesLeft -= 1;
end;
if FramesLeft <= 0 then //If the frame is 0, make the bullet inactive
begin
Shot := False;
end;
while Angle >= 360 do //Make the angle under 360, so a proper angle
begin
Angle -= 360;
end;
Move(); //Moves the bullet
if (FramesLeft =3) then
begin
if HitPlayer(player) then //Checks if the bullet has hit the Player
begin
//If it hit the Player, it will make the frames left for the
//bullet to live 2x as long as it is already at the max frames left
//and also will damage the Player, and activate its knockback
//and make it fly back in the correct direction
player.KnockBackFrame := MAXKNOCKBACKFRAMES;
player.KnockBackLeft := Left;
player.Health -= Damage;
FramesLeft := 2;
end;
i := 0;
while i <= High(Ais) do //Iterate through the Ai Units (to be added)
begin
if HitPlayer(Ais[i]) then //Checks if the bullet has hit the selected Ai Unit
begin
//If It hit the Ai unit, it will make the frames left for the
//bullet to live 2 as long as its already at the max frames left
//and also will damage the Ai, and activate its knockback
//and make it fly back in the correct direction
Ais[i].KnockBackFrame := MAXKNOCKBACKFRAMES;
Ais[i].KnockBackLeft := Left;
Ais[i].Health -= Damage;
FramesLeft := 2;
end;
i += 1; //Increases 'i' so it will check the next ai unit
end;
i := 0;
end;
end;
//If the bullet is not active, it will send itself off screen so it cannot
//get in the way.
if Shot = False then
begin
X := -1000;
Y := -1000;
end;
end;
procedure TBullet.Move();
begin
if Angle = 0 then //Move up if instructed to
Y -= WIDTH
else if Angle = 90 then //Move right if instructed to
X += WIDTH
else if Angle = 180 then //move down if instructed to
Y += WIDTH
else if Angle = 270 then //move left if instructed to
X -= WIDTH
else if Angle < 90 then //work out the x and y movement needed using trigonometry
begin
X += Sin(Angle * (PI / 180)) * WIDTH;
Y -= Cos(Angle * (PI / 180)) * WIDTH;
end
else if Angle < 180 then
begin
X += Cos((Angle - 90) * (PI / 180)) * WIDTH;
Y += Sin((Angle - 90) * (PI / 180)) * WIDTH;
end
else if Angle < 270 then
begin
X -= Sin((Angle - 180) * (PI / 180)) * WIDTH;
Y += Cos((Angle - 180) * (PI / 180)) * WIDTH;
end
else if Angle < 360 then
begin
X -= Cos((Angle - 270) * (PI / 180)) * WIDTH;
Y -= Sin((Angle - 270) * (PI / 180)) * WIDTH;
end;
end;
function TBullet.HitPlayer(Player : TPlayer) : boolean;
var
//If this is false, it won't bother checking the Y collision as it has already
//failed the X collision, so it has not hit. This makes it more efficient.
stillCheck : boolean;
begin
stillCheck := false;
//Sets the maximum and minimum x and y of the player, so it is ready to check
var PlayerLeftX = Player.X;
var PlayerRightX = Player.X + PLAYERHEAD;
var PlayerTopY = Player.Y;
var PlayerBottomY = Player.Y + PLAYERHEIGHT;
//The following variable will contain the array of an array with
//The upper and lower bounds of the x and y axis
var Bounds = BulletBounds();
//Tests the X collision
if (Bounds[0][1] >= PlayerLeftX) and (Bounds[0][0] <= PlayerRightX) then
stillCheck := true; //It it passed the x, it will then bother testing the y
if stillCheck then
begin
//Test the y if the x has collided
if (Bounds[1][0] <= PlayerBottomY) and (Bounds[1][1] >= PlayerTopY) then
//It has collided with both x and y so has hit
Exit(true);
end;
Exit(False); //If both haven't passed, this runs returning false.
end;
function TBullet.HitPlat(Plat : TPlat) : boolean;
var
//If this is false, it won't bother checking the Y collision as it has already
//failed the X collision, so it has not hit. This makes it more efficient.
stillCheck : boolean;
begin
stillCheck := false;
//Sets the platform's minimum and maximum X and Y's
var PlatLeftX = Plat.X;
var PlatRightX = Plat.X + Plat.Width;
var PlatTopY = Plat.Y;
var PlatBottomY = Plat.Y + Plat.Height;
//The following variable will contain the array of an array with
//The upper and lower bounds of the x and y axis
var Bounds = BulletBounds();
//Tests the X collision
if (Bounds[0][1] >= PlatLeftX) and (Bounds[0][0] <= PlatRightX) then
stillCheck := true; //It it passed the x, it will then bother testing the y
if stillCheck then
begin
//Test the y if the x has collided
if (Bounds[1][0] <= PlatBottomY) and (Bounds[1][1] >= PlatTopY) then
//It has collided with both x and y so has hit
Exit(true);
end;
Exit(False); //If both havn't passed, this runs returning false
end;
function TBullet.BulletBounds() : array [0 .. 1] of array [0 .. 1] of float;
var
//Will be used to form the 2D array
BulletLeftX, BulletRightX, BulletTopY, BulletBottomY : float;
//The returned 2D array
Return : array [0 .. 1] of array [0 .. 1] of float;
begin
//Works out the minimum and maximum X and Y of the bullet, depending on the angle
if Angle = 0 then
begin
BulletLeftX := X;
BulletRightX := X + HEIGHT;
BulletTopY := Y;
BulletBottomY := Y + WIDTH;
end
else if Angle = 90 then
begin
BulletLeftX := X;
BulletRightX := X + WIDTH;
BulletTopY := Y;
BulletBottomY := Y + HEIGHT;
end
else if Angle = 180 then
begin
BulletLeftX := X;
BulletRightX := X + HEIGHT;
BulletTopY := Y;
BulletBottomY := Y + WIDTH;
end
else if Angle = 270 then
begin
BulletLeftX := X;
BulletRightX := X + WIDTH;
BulletTopY := Y;
BulletBottomY := Y + HEIGHT;
end
//Uses trigonometry for Angles that are not stright below
//Angles under 90 and angles between 180 and 270
else if (Angle < 90) or ((Angle >= 180) and (Angle < 270)) then
begin
var TempAngle := Angle; //Create a temp angle as it may need to be changed
//So its under 90 degrees
if Angle >= 90 then
TempAngle := Angle - 180;
TempAngle *= (Pi / 180); //Convert the angle from degrees to radians
//as the Pascal trigonetry commands use radians
BulletLeftX := X;
BulletRightX := X + (Sin(TempAngle) * WIDTH) + (Cos(TempAngle) * HEIGHT);
BulletTopY := Y - (Cos(TempAngle) * WIDTH);
BulletBottomY := Y + (Sin(TempAngle) * HEIGHT);
end
else //Angles above 270 and angle between 90 and 180
begin
var TempAngle := Angle - 90; //Create a temp angle as it may need to be changed
//So its under 90 degrees
if Angle >= 180 then
TempAngle := Angle - 270;
TempAngle *= (Pi / 180); //Convert the angle from degrees to radians
//as the Pascal trigonetry commands use radians
BulletLeftX := X;
BulletRightX := X + (Sin(TempAngle) * HEIGHT) + (Cos(TempAngle) * WIDTH);
BulletTopY := Y - (Cos(TempAngle) * HEIGHT);
BulletBottomY := Y + (Sin(TempAngle) * WIDTH);
end;
Return[0][0] := BulletLeftX;
Return[0][1] := BulletRightX;
Return[1][0] := BulletTopY;
Return[1][1] := BulletBottomY;
Exit(Return);
end;
end.
|
{..............................................................................}
{ Summary: Forces rebuild of all internal/split planes }
{ on the current PCB document }
{ }
{ Copyright (c) 2006 by Altium Limited }
{..............................................................................}
{..............................................................................}
Procedure RebuildInternalSplitPlanes;
Var
PCBBoard : IPCB_Board;
TheLayerStack : IPCB_LayerStack;
FoundPlane : Boolean;
LayerObj : IPCB_LayerObject;
L : TLayer;
Begin
PCBBoard := PCBServer.GetCurrentPCBBoard;
If PCBBoard = Nil Then Exit;
TheLayerStack := PCBBoard.LayerStack;
If TheLayerStack = Nil Then Exit;
FoundPlane := False;
LayerObj := TheLayerStack.FirstLayer;
Repeat
If InSet(LayerObj.LayerID, InternalPlanes) Then
Begin
PCBBoard.InvalidatePlane(LayerObj.LayerID);
FoundPlane := True;
End;
LayerObj := TheLayerStack.NextLayer(LayerObj);
Until LayerObj = Nil;
If FoundPlane Then
Begin
PCBBoard.ValidateInvalidPlanes;
PCBBoard.GraphicalView_ZoomRedraw
End
Else ShowInfo('This Board does not contain internal planes');
End;
{..............................................................................}
|
unit DAW.Model.Device.New;
interface
uses
System.SysUtils;
type
{$SCOPEDENUMS ON}
TdawDevice = class
private
FID: string;
FName: string;
FIP: string;
FLastConnected: TDateTime;
FIsConnected: Boolean;
procedure SetIsConnected(const Value: Boolean);
function GetLastConnected: TDateTime;
public
constructor Create(const AName, AId: string);
published
property ID: string read FID write FID;
property Name: string read FName write FName;
property IP: string read FIP write FIP;
property LastConnected: TDateTime read GetLastConnected write FLastConnected;
property IsConnected: Boolean read FIsConnected write SetIsConnected;
end;
implementation
{ TdawDevice }
constructor TdawDevice.Create(const AName, AId: string);
begin
FID := AId;
FName := AName;
end;
function TdawDevice.GetLastConnected: TDateTime;
begin
Result := FLastConnected;
end;
procedure TdawDevice.SetIsConnected(const Value: Boolean);
begin
FIsConnected := Value;
if Value then
FLastConnected := Now;
end;
end.
|
Unit Un_PdfRenderiza;
Interface
Uses Classes,
System.Types,
FMX.Objects,
Un_PdfObjetos,
Un_PdfXRef,
Un_PdfGrafico,
Un_PdfTexto;
Const NUL_CHAR=#0;
FF_CHAR=#12;
//------------------------------------------------------------------------
Type TPdfTipoComando=(com_array,com_numero,com_string,com_colchete,com_nome,com_comando,com_dicionario,com_fim);
//------------------------------------------------------------------------
TPdfCategoriaComando=(cat_grafico,cat_texto,cat_cont_marc,cat_compat);
//------------------------------------------------------------------------
TPdfComando=Class(TObject)
Private
obj_TipoComando:TPdfTipoComando;
obj_CategComando:TPdfCategoriaComando;
str_Comando:String;
Public
Constructor Create(Var stm_Conteudo:TStringStream);
Property Comando:String Read str_Comando;
Property Tipo:TPdfTipoComando Read obj_TipoComando;
Property Categoria:TPdfCategoriaComando Read obj_CategComando;
End;
//------------------------------------------------------------------------
TParam=Class(TObject)
Private
lst_Dados:TList;
int_Tamanho:Integer;
Public
Constructor Create;
Procedure Insere(obj_Dado:TPdfComando);
Function TipoParam:TPdfTipoComando;
Function BuscaReal:Extended;
Function BuscaInteiro:Integer;
Function BuscaString:String;
Function BuscaArrayReal:TList;
Function BuscaArrayString:TStringList;
Procedure LimpaParam;
Property Tamanho:Integer Read int_Tamanho;
End;
//------------------------------------------------------------------------
TPdfRenderiza=Class(TObject)
Private
stl_Comandos:TStringList;
obj_Param:TParam;
obj_Grafico:TPdfGrafico;
obj_Texto:TPdfTexto;
Procedure Comando_W(str_Comando:String);
Procedure Comando_J(str_Comando:String);
Procedure Comando_M(str_Comando:String);
Procedure Comando_D(str_Comando:String);
Procedure Comando_RI;
Procedure Comando_I;
Procedure Comando_GS;
Procedure Comando_Q(str_Comando:String);
Procedure Comando_CM;
Procedure Comando_L;
Procedure Comando_C;
Procedure Comando_V;
Procedure Comando_Y;
Procedure Comando_H;
Procedure Comando_RE;
Procedure Comando_S(str_Comando:String);
Procedure Comando_F(str_Comando:String);
Procedure Comando_B(str_Comando:String);
Procedure Comando_N;
Procedure Comando_CS(str_Comando:String);
Procedure Comando_SC(str_Comando:String);
Procedure Comando_SCN(str_Comando:String);
Procedure Comando_G(str_Comando:String);
Procedure Comando_RG(str_Comando:String);
Procedure Comando_K(str_Comando:String);
Procedure Comando_SH;
Procedure Comando_BI;
Procedure Comando_ID;
Procedure Comando_EI;
Procedure Comando_DO;
Procedure Comando_BT;
Procedure Comando_ET;
Procedure Comando_TC;
Procedure Comando_TW;
Procedure Comando_TZ;
Procedure Comando_TL;
Procedure Comando_TF;
Procedure Comando_TR;
Procedure Comando_TS;
Procedure Comando_TD(str_Comando:String);
Procedure Comando_TM;
Procedure Comando_T;
Procedure Comando_TJ(str_Comando:String);
Procedure Comando_Aspas(str_Comando:String);
Procedure Comando_D0;
Procedure Comando_D1;
Procedure Comando_MP;
Procedure Comando_DP;
Procedure Comando_BMC;
Procedure Comando_BDC;
Procedure Comando_EMC;
Procedure Comando_BX;
Procedure Comando_EX;
Public
Constructor Create(Var obj_Grafico:TPdfGrafico;Var obj_Texto:TPdfTexto);
Procedure TrataConteudo(stm_Conteudo:TStringStream);
End;
Implementation
Uses System.SysUtils,
System.Math,
System.StrUtils,
System.ZLib,
System.UITypes,
FMX.Types,
Un_PdfUtils;
//-----------------------------------------------------------------------------
// TPdfComando
//-----------------------------------------------------------------------------
Constructor TPdfComando.Create(Var stm_Conteudo:TStringStream);
Var chr_Dado:AnsiChar;
int_ContPonto,
int_ContSinal,
int_ContPar:Byte;
Begin
Inherited Create;
Self.str_Comando:='';
If stm_Conteudo.Size-stm_Conteudo.Position-2>0 Then
Begin
Repeat
stm_Conteudo.Read(chr_Dado,1);
If chr_Dado='%' Then
Begin
_BuscaLinha(stm_Conteudo);
stm_Conteudo.Read(chr_Dado,1);
End;
Until ((Not _EhCaractereBranco(chr_Dado)) Or (stm_Conteudo.Size-stm_Conteudo.Position-2<=0));
If (stm_Conteudo.Size-stm_Conteudo.Position-2>0) Or (chr_Dado In ['[','(','{','<','/','.','-','a'..'z','A'..'Z','0'..'9']) Then
Begin
If chr_Dado='[' Then
Begin
Self.obj_TipoComando:=com_array;
int_ContPar:=0;
Repeat
If chr_Dado='[' Then
Inc(int_ContPar);
If chr_Dado=']' Then
Dec(int_ContPar);
Self.str_Comando:=Self.str_Comando+chr_Dado;
stm_Conteudo.Read(chr_Dado,1);
If chr_Dado='%' Then
Begin
_BuscaLinha(stm_Conteudo);
stm_Conteudo.Read(chr_Dado,1);
End;
Until int_ContPar=0;
stm_Conteudo.Position:=stm_Conteudo.Position-1;
End
Else If chr_Dado='(' Then
Begin
Self.obj_TipoComando:=com_string;
int_ContPar:=0;
Repeat
If chr_Dado='(' Then
Inc(int_ContPar);
If chr_Dado=')' Then
Dec(int_ContPar);
Self.str_Comando:=Self.str_Comando+chr_Dado;
stm_Conteudo.Read(chr_Dado,1);
If chr_Dado='%' Then
Begin
_BuscaLinha(stm_Conteudo);
stm_Conteudo.Read(chr_Dado,1);
End;
Until int_ContPar=0;
stm_Conteudo.Position:=stm_Conteudo.Position-1;
End
Else If chr_Dado='{' then
Begin
Self.obj_TipoComando:=com_colchete;
int_ContPar:=0;
Repeat
If chr_Dado='}' Then
Inc(int_ContPar);
If chr_Dado='{' Then
Dec(int_ContPar);
Self.str_Comando:=Self.str_Comando+chr_Dado;
stm_Conteudo.Read(chr_Dado,1);
If chr_Dado='%' Then
Begin
_BuscaLinha(stm_Conteudo);
stm_Conteudo.Read(chr_Dado,1);
End;
Until int_ContPar=0;
stm_Conteudo.Position:=stm_Conteudo.Position-1;
End
Else If chr_Dado='<' then
Begin
int_ContPar:=0;
Repeat
If chr_Dado='>' Then
Inc(int_ContPar);
If chr_Dado='<' Then
Dec(int_ContPar);
Self.str_Comando:=Self.str_Comando+chr_Dado;
stm_Conteudo.Read(chr_Dado,1);
If chr_Dado='%' Then
Begin
_BuscaLinha(stm_Conteudo);
stm_Conteudo.Read(chr_Dado,1);
End;
Until int_ContPar=0;
If Pos('<<',Self.str_Comando)>0 Then
Self.obj_TipoComando:=com_dicionario
Else
Self.obj_TipoComando:=com_array;
stm_Conteudo.Position:=stm_Conteudo.Position-1;
End
Else If chr_Dado='/' then
Begin
Self.obj_TipoComando:=com_nome;
Repeat
Self.str_Comando:=Self.str_Comando+chr_Dado;
stm_Conteudo.Read(chr_Dado,1);
If chr_Dado='%' Then
Begin
_BuscaLinha(stm_Conteudo);
stm_Conteudo.Read(chr_Dado,1);
End;
Until ((chr_Dado<='a') Or (chr_Dado>'z')) And ((chr_Dado<'A') Or (chr_Dado>'Z')) And ((chr_Dado<'0') Or (chr_Dado>'9'));
stm_Conteudo.Position:=stm_Conteudo.Position-1;
End
Else If (chr_Dado='.') Or (chr_Dado='-') Or ((chr_Dado>='0') And (chr_Dado<='9')) Then
Begin
Self.obj_TipoComando:=com_numero;
int_ContPonto:=0;
int_ContSinal:=0;
Repeat
If chr_Dado='.' Then
Inc(int_ContPonto);
If chr_Dado='-' Then
Inc(int_ContSinal);
Self.str_Comando:=Self.str_Comando+chr_Dado;
stm_Conteudo.Read(chr_Dado,1);
If chr_Dado='%' Then
Begin
_BuscaLinha(stm_Conteudo);
stm_Conteudo.Read(chr_Dado,1);
End;
Until (chr_Dado<>'.') And (chr_Dado<>'-') And ((chr_Dado<'0') Or (chr_Dado>'9'));
stm_Conteudo.Position:=stm_Conteudo.Position-1;
If (int_ContPonto>1) Or (int_ContSinal>1) Then
Raise Exception.Create('Valor inválido:"'+Self.str_Comando+'".')
End
Else If ((chr_Dado>='a') And (chr_Dado<='z')) Or ((chr_Dado>='A') And (chr_Dado<='Z')) Or (chr_Dado='\') Or (chr_Dado>='"') Then
Begin
Self.obj_TipoComando:=com_comando;
Repeat
Self.str_Comando:=Self.str_Comando+chr_Dado;
stm_Conteudo.Read(chr_Dado,1);
If chr_Dado='%' Then
Begin
_BuscaLinha(stm_Conteudo);
stm_Conteudo.Read(chr_Dado,1);
End;
Until ((chr_Dado<='a') Or (chr_Dado>'z')) And ((chr_Dado<'A') Or (chr_Dado>'Z')) And (chr_Dado<>'\') And (chr_Dado<>'"') And (chr_Dado<>'*');
stm_Conteudo.Position:=stm_Conteudo.Position-1;
End;
End
Else
Self.obj_TipoComando:=com_fim;
End
Else
Self.obj_TipoComando:=com_fim;
//É comando?
If Self.obj_TipoComando=com_comando Then
//Sim, vmos definir a categoria dele...
Begin
//É comando para manipulação de gráficos?
If (Self.str_Comando='w') Or (Self.str_Comando='J') Or (Self.str_Comando='j') Or (Self.str_Comando='M') Or (Self.str_Comando='d') Or (Self.str_Comando='ri') Or
(Self.str_Comando='i') Or (Self.str_Comando='gs') Or (Self.str_Comando='q') Or (Self.str_Comando='Q') Or (Self.str_Comando='cm') Or (Self.str_Comando='m') Or
(Self.str_Comando='l') Or (Self.str_Comando='c') Or (Self.str_Comando='v') Or (Self.str_Comando='y') Or (Self.str_Comando='h') Or (Self.str_Comando='re') Or
(Self.str_Comando='S') Or (Self.str_Comando='s') Or (Self.str_Comando='f') Or (Self.str_Comando='F') Or (Self.str_Comando='f*') Or (Self.str_Comando='B') Or
(Self.str_Comando='B*') Or (Self.str_Comando='b') Or (Self.str_Comando='b*') Or (Self.str_Comando='n') Or (Self.str_Comando='W') Or (Self.str_Comando='W*') Or
(Self.str_Comando='CS') Or (Self.str_Comando='cs') Or (Self.str_Comando='SC') Or (Self.str_Comando='SCN') Or (Self.str_Comando='sc') Or (Self.str_Comando='scn') Or
(Self.str_Comando='G') Or (Self.str_Comando='g') Or (Self.str_Comando='RG') Or (Self.str_Comando='rg') Or (Self.str_Comando='K') Or (Self.str_Comando='k') Or
(Self.str_Comando='sh') Or (Self.str_Comando='BI') Or (Self.str_Comando='ID') Or (Self.str_Comando='EI') Or (Self.str_Comando='Do')Then
Self.obj_CategComando:=cat_grafico
//É comando para manipulação de textos?
Else If (Self.str_Comando='BT') Or (Self.str_Comando='ET') Or (Self.str_Comando='Tc') Or (Self.str_Comando='Tw') Or (Self.str_Comando='Tz') Or (Self.str_comando='TL') Or
(Self.str_Comando='Tf') Or (Self.str_Comando='Tr') Or (Self.str_Comando='Ts') Or (Self.str_Comando='Td') Or (Self.str_Comando='TD') Or (Self.str_Comando='Tm') Or
(Self.str_Comando='T*') Or (Self.str_Comando='Tj') Or (Self.str_Comando='TJ') Or (Self.str_Comando='''') Or (Self.str_Comando='"') Or (Self.str_Comando='d0') Or
(Self.str_Comando='d1') Then
Self.obj_CategComando:=cat_texto
//É comando para manipulação de conteúdo marcado?
Else If (Self.str_Comando='MP') Or (Self.str_Comando='DP') Or (Self.str_Comando='BMC') Or (Self.str_Comando='BDC') Or (Self.str_Comando='EMC') Then
Self.obj_CategComando:=cat_cont_marc
//É comando para compatibilidade?
Else If (Self.str_Comando='BX') Or (Self.str_Comando='EX') Then
Self.obj_CategComando:=cat_compat
End;
End;
//-----------------------------------------------------------------------------
// TParam
//-----------------------------------------------------------------------------
Constructor TParam.Create;
Begin
Inherited Create;
lst_Dados:=TList.Create;
End;
//-----------------------------------------------------------------------------
Procedure TParam.Insere(obj_Dado:TPdfComando);
Begin
If obj_Dado<>Nil Then
Begin
Self.lst_Dados.Add(obj_Dado);
Self.int_Tamanho:=Self.lst_Dados.Count;
End;
End;
//-----------------------------------------------------------------------------
Function TParam.TipoParam:TPdfTipoComando;
Begin
Result:=TPdfComando(Self.lst_Dados[Self.lst_Dados.Count-1]).Tipo;
End;
//-----------------------------------------------------------------------------
Function TParam.BuscaReal:Extended;
Var obj_Formatos:TFormatSettings;
Begin
If Self.lst_Dados.Count>0 Then
Begin
obj_Formatos:=TFormatSettings.Create;
If TPdfComando(Self.lst_Dados[Self.lst_Dados.Count-1]).Tipo=com_numero Then
Result:=StrToFloat(StringReplace(TPdfComando(Self.lst_Dados[Self.lst_Dados.Count-1]).Comando,'.',obj_Formatos.DecimalSeparator,[rfReplaceAll]))
Else
Raise Exception.Create('Valor inválido:"'+TPdfComando(Self.lst_Dados[Self.lst_Dados.Count-1]).Comando+'".');
Self.lst_Dados.Delete(Self.lst_Dados.Count-1);
Self.int_Tamanho:=Self.lst_Dados.Count;
End
Else
Raise Exception.Create('Pilha vazia.');
End;
//-----------------------------------------------------------------------------
Function TParam.BuscaInteiro:Integer;
Var obj_Formatos:TFormatSettings;
Begin
If Self.lst_Dados.Count>0 Then
Begin
If TPdfComando(Self.lst_Dados[Self.lst_Dados.Count-1]).Tipo=com_numero Then
Begin
If Pos('.',TPdfComando(Self.lst_Dados[Self.lst_Dados.Count-1]).Comando)>0 Then
Result:=Trunc(StrToFloatDef(StringReplace(TPdfComando(Self.lst_Dados[Self.lst_Dados.Count-1]).Comando,'.',obj_Formatos.DecimalSeparator,[rfReplaceAll]),0))
Else
Result:=StrToIntDef(TPdfComando(Self.lst_Dados[Self.lst_Dados.Count-1]).Comando,0);
End
Else
Raise Exception.Create('Valor inválido:"'+TPdfComando(Self.lst_Dados[Self.lst_Dados.Count-1]).Comando+'".');
Self.lst_Dados.Delete(Self.lst_Dados.Count-1);
Self.int_Tamanho:=Self.lst_Dados.Count;
End
Else
Raise Exception.Create('Pilha vazia.');
End;
//-----------------------------------------------------------------------------
Function TParam.BuscaString:String;
Begin
If Self.lst_Dados.Count>0 Then
Begin
Result:=TPdfComando(Self.lst_Dados[Self.lst_Dados.Count-1]).Comando;
Self.lst_Dados.Delete(Self.lst_Dados.Count-1);
Self.int_Tamanho:=Self.lst_Dados.Count;
End
Else
Raise Exception.Create('Pilha vazia.');
End;
//-----------------------------------------------------------------------------
Function TParam.BuscaArrayReal:TList;
Var ptr_Valor:^Real;
str_Conteudo:String;
int_PosIni,
int_PosFim:Integer;
I:Byte;
stl_Result:TStringList;
Begin
Result:=TList.Create;
str_Conteudo:=Trim(Self.BuscaString);
If Length(str_Conteudo)>0 Then
Begin
int_PosIni:=Pos('[',str_Conteudo);
int_PosFim:=Pos(']',str_Conteudo);
If int_PosIni<int_PosFim Then
Begin
str_Conteudo:=Copy(str_Conteudo,1,int_PosFim-1);
str_Conteudo:=Copy(str_Conteudo,int_PosIni+1,Length(str_Conteudo));
str_Conteudo:=Trim(str_Conteudo);
While Pos(' ',str_Conteudo)>0 Do
str_Conteudo:=StringReplace(str_Conteudo,' ',' ',[rfReplaceAll]);
str_Conteudo:='"'+StringReplace(str_Conteudo,' ','","',[rfReplaceAll])+'"';
stl_Result:=TStringList.Create;
stl_Result.CommaText:=str_Conteudo;
If stl_Result.Count>0 Then
Begin
For I:=0 To stl_Result.Count-1 Do
Begin
New(ptr_Valor);
ptr_Valor^:=StrToFloatDef(stl_Result[I],0);
Result.Add(ptr_Valor);
End;
End;
End;
End;
End;
//-----------------------------------------------------------------------------
Function TParam.BuscaArrayString:TStringList;
Var ptr_Valor:^Real;
str_Conteudo:String;
int_PosIni,
int_PosFim:Integer;
I:Byte;
Begin
Result:=TStringList.Create;
str_Conteudo:=Trim(Self.BuscaString);
If Length(str_Conteudo)>0 Then
Begin
int_PosIni:=Pos('(',str_Conteudo);
int_PosFim:=Pos(')',str_Conteudo);
If int_PosIni<int_PosFim Then
Begin
str_Conteudo:=Copy(str_Conteudo,1,int_PosFim-1);
str_Conteudo:=Copy(str_Conteudo,int_PosIni+1,Length(str_Conteudo));
str_Conteudo:=Trim(str_Conteudo);
While Pos(' ',str_Conteudo)>0 Do
str_Conteudo:=StringReplace(str_Conteudo,' ',' ',[rfReplaceAll]);
str_Conteudo:='"'+StringReplace(str_Conteudo,' ','","',[rfReplaceAll])+'"';
Result.CommaText:=str_Conteudo;
End;
End;
End;
//------------------------------------------------------------------------
Procedure TParam.LimpaParam;
Begin
Self.lst_Dados.Clear;
Self.int_Tamanho:=Self.lst_Dados.Count;
End;
//-----------------------------------------------------------------------------
// TPdfRenderiza
//-----------------------------------------------------------------------------
Constructor TPdfRenderiza.Create(Var obj_Grafico:TPdfGrafico;Var obj_Texto:TPdfTexto);
Begin
Inherited Create;
Self.obj_Grafico:=obj_Grafico;
End;
//-----------------------------------------------------------------------------
//Comando para manipulação de gráficos.
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_W(str_Comando:String);
Var flt_Valor:Real;
Begin
If str_Comando='w' Then
Begin
If Self.obj_Param.Tamanho>=1 then
Self.obj_Grafico.DefineLarguraLinha(Self.obj_Param.BuscaReal);
End
Else If str_Comando='W' Then
Begin
End;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_J(str_Comando:String);
Begin
If Self.obj_Param.Tamanho>=1 Then
Begin
If str_Comando='J' Then
Self.obj_Grafico.DefineBordaLinha(Self.obj_Param.BuscaInteiro)
Else If str_Comando='j' Then
Self.obj_Grafico.DefineJuncaoLinha(Self.obj_Param.BuscaInteiro);
End;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_M(str_Comando:String);
Var flt_X,
flt_Y:Real;
Begin
//Inicia um novo caminho
If str_Comando='m' Then
Begin
If Self.obj_Param.Tamanho>=2 then
Begin
flt_Y:=Self.obj_Param.BuscaReal;
flt_X:=Self.obj_Param.BuscaReal;
Self.obj_Grafico.NovoCaminho(flt_X,flt_Y);
End;
End;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_D;
Var int_Inicio:Integer;
lst_Array:TList;
arr_Traco:Array Of Single;
I:Byte;
Begin
If Self.obj_Param.Tamanho>=2 Then
Begin
int_Inicio:=Self.obj_Param.BuscaInteiro;
lst_Array:=Self.obj_Param.BuscaArrayReal;
SetLength(arr_Traco,lst_Array.Count);
For I:=0 To lst_Array.Count-1 Do
arr_Traco[I+1]:=Real(lst_Array[I]^);
Self.obj_Grafico.DefineArrayTracejado(int_Inicio,arr_Traco);
End;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_RI;
Begin
Self.obj_Grafico.PropositoRederizacao;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_I;
Begin
Self.obj_Grafico.DefineMaximoNivelamento;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_GS;
Begin
Self.obj_Grafico.DefineEstadoGrafico;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_Q(str_Comando:String);
Begin
If str_Comando='Q' Then
Self.obj_Grafico.RestauraEstadoGrafico
Else If str_Comando='q' Then
Self.obj_Grafico.SalvaEstadoGrafico;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_CM;
Var flt_A,
flt_B,
flt_C,
flt_D,
flt_E,
flt_F:Double;
Begin
If Self.obj_Param.Tamanho>=6 then
Begin
flt_F:=Self.obj_Param.BuscaReal;
flt_E:=Self.obj_Param.BuscaReal;
flt_D:=Self.obj_Param.BuscaReal;
flt_C:=Self.obj_Param.BuscaReal;
flt_B:=Self.obj_Param.BuscaReal;
flt_A:=Self.obj_Param.BuscaReal;
Self.obj_Grafico.ConcatMatriz(flt_A,flt_B,flt_C,flt_D,flt_E,flt_F);
End;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_L;
Var flt_X,
flt_Y:Double;
Begin
If Self.obj_Param.Tamanho>=2 then
Begin
flt_Y:=Self.obj_Param.BuscaReal;
flt_X:=Self.obj_Param.BuscaReal;
Self.obj_Grafico.Linha(flt_X,flt_Y);
End;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_C;
Var flt_X1,
flt_Y1,
flt_X2,
flt_Y2,
flt_X3,
flt_Y3:Double;
Begin
If Self.obj_Param.Tamanho>=6 then
Begin
flt_X1:=Self.obj_Param.BuscaReal;
flt_Y1:=Self.obj_Param.BuscaReal;
flt_X2:=Self.obj_Param.BuscaReal;
flt_Y2:=Self.obj_Param.BuscaReal;
flt_X3:=Self.obj_Param.BuscaReal;
flt_Y3:=Self.obj_Param.BuscaReal;
Self.obj_Grafico.Curva(flt_X1,flt_Y1,flt_X2,flt_Y2,flt_X3,flt_Y3);
Self.obj_Param.LimpaParam;
End;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_V;
Begin
Self.obj_Grafico.IncluiCurvaInicio;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_Y;
Begin
Self.obj_Grafico.IncluiCurvaFinal;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_H;
Begin
Self.obj_Grafico.FechaSubCaminho;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_RE;
Var flt_X,
flt_Y,
flt_Largura,
flt_Altura:Double;
Begin
If Self.obj_Param.Tamanho>=4 Then
Begin
flt_Altura:=Self.obj_Param.BuscaReal;
flt_Largura:=Self.obj_Param.BuscaReal;
flt_Y:=Self.obj_Param.BuscaReal;
flt_X:=Self.obj_Param.BuscaReal;
Self.obj_Grafico.Retangulo(flt_X,flt_Y,flt_Altura,flt_Largura);;
End;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_S(str_Comando:String);
Begin
If str_Comando='s' Then
Self.obj_Grafico.FechaQuebraCaminho
Else If str_Comando='S' Then
Self.obj_Grafico.QuebraCaminho;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_F(str_Comando:String);
Begin
If str_Comando='f' Then
Self.obj_Grafico.Preenche
Else If str_Comando='F' Then
Self.obj_Grafico.Preenche
Else If str_Comando='f*' Then
Self.obj_Grafico.Preenche;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_B(str_Comando:String);
Begin
If str_Comando='b' Then
Begin
Self.obj_Grafico.Preenche;
End
Else If str_Comando='B' Then
Begin
Self.obj_Grafico.Preenche;
End
Else If str_Comando='b*' Then
Begin
Self.obj_Grafico.Preenche;
End
Else If str_Comando='B*' Then
Begin
Self.obj_Grafico.Preenche;
End;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_N;
Begin
Self.obj_Grafico.FechaCaminho;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_CS(str_Comando:String);
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_SC(str_Comando:String);
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_SCN(str_Comando:String);
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_G(str_Comando:String);
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_RG(str_Comando:String);
Var flt_R,
flt_G,
flt_B:Double;
Begin
If Self.obj_Param.Tamanho>=3 Then
Begin
flt_B:=Self.obj_Param.BuscaReal;
flt_G:=Self.obj_Param.BuscaReal;
flt_R:=Self.obj_Param.BuscaReal;
If str_Comando='RG' Then
Self.obj_Grafico.DefineCorLinhaRGB(flt_R,flt_G,flt_B)
Else If str_Comando='rg' Then
Self.obj_Grafico.DefineCorFundoRGB(flt_R,flt_G,flt_B);
End;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_K(str_Comando:String);
Var int_C,
int_M,
int_Y,
int_K:Integer;
Begin
If Self.obj_Param.Tamanho>=4 Then
Begin
int_K:=Self.obj_Param.BuscaInteiro;
int_Y:=Self.obj_Param.BuscaInteiro;
int_M:=Self.obj_Param.BuscaInteiro;
int_C:=Self.obj_Param.BuscaInteiro;
If str_Comando='K' Then
Self.obj_Grafico.DefineCorLinhaCMYK(int_C,int_M,int_Y,int_K)
Else If str_Comando='k' Then
Self.obj_Grafico.DefineCorFundoCMYK(int_C,int_M,int_Y,int_K);
Self.obj_Param.LimpaParam;
End;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_SH;
Begin
Self.obj_Grafico.Preenche;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_BI;
Begin
Self.obj_Grafico.InicioObjetoInterno;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_ID;
Begin
Self.obj_Grafico.InicioDadoInterno;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_EI;
Begin
Self.obj_Grafico.FimImagemInterna;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_DO;
Begin
Self.obj_Grafico.InvocaObjeto;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
//Comandos para manipulação de textos.
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_BT;
Begin
Self.obj_Texto.InicioTexto;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_ET;
Begin
Self.obj_Texto.FimTexto;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_TC;
Begin
Self.obj_Texto.EspacoCarac;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_TW;
Begin
Self.obj_Texto.EspacoPalavra;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_TZ;
Begin
Self.obj_Texto.EscalaHorizontal;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_TL;
Begin
Self.obj_Texto.EspacoEntreLinhas;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_TF;
Begin
Self.obj_Texto.DefineFonte;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_TR;
Begin
Self.obj_Texto.DefineTipoRederizacao;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_TS;
Begin
Self.obj_Texto.DefinePosVertical;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_TD(str_Comando:String);
Begin
Self.obj_Texto.MoveParaPosicao;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_TM;
Var flt_A,
flt_B,
flt_C,
flt_D,
flt_E,
flt_F:Double;
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_T;
Begin
Self.obj_Texto.ProximaLinha;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_TJ(str_Comando:String);
Var stl_Texto:TStringList;
str_Texto:String;
I:Integer;
flt_Val:Real;
Begin
If str_Comando='Tj' Then
Begin
str_Texto:=Self.obj_Param.BuscaString;
Self.obj_Texto.ProcessaTexto(str_Texto);
End
Else If str_Comando='TJ' Then
Begin
stl_Texto:=Self.obj_Param.BuscaArrayString;
Self.obj_Texto.ProcessaArrayTexto(stl_Texto);
stl_Texto.Free;
End;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_Aspas(str_Comando:String);
Begin
If str_Comando='''' Then
Self.obj_Texto.ProcessaApostrofe
Else If str_Comando='"' Then
Self.obj_Texto.ProcessaAspas;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_D0;
Begin
Self.obj_Texto.DefineFonteTipo3;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_D1;
Begin
Self.obj_Texto.DefineFonteTipo3;
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
//Comandos para manipulação de conteúdo marcado.
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_MP;
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_DP;
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_BMC;
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_BDC;
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_EMC;
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
//Comandos compatibilidade.
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_BX;
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.Comando_EX;
Begin
Self.obj_Param.LimpaParam;
End;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
Procedure TPdfRenderiza.TrataConteudo(stm_Conteudo:TStringStream);
Var obj_Comando:TPdfComando;
chr_Dado:AnsiChar;
int_ContPar:Byte;
flt_X,
flt_Y:Extended;
stl_Comando:TStringList;
str_Linha:String;
Begin
Self.obj_Param:=TParam.Create;
stm_Conteudo.Position:=0;
stl_Comando:=TStringList.Create;
str_Linha:='';
Repeat
obj_Comando:=TPdfComando.Create(stm_Conteudo);
If obj_Comando.Tipo=com_comando Then
Begin
stl_Comando.Add(str_Linha+' '+obj_Comando.Comando);
str_Linha:='';
Case obj_Comando.Categoria Of
cat_grafico:
Begin
//Comandos para manipulação de gráficos.
If (obj_Comando.Comando='w') Or (obj_Comando.Comando='W') Or (obj_Comando.Comando='W*')Then
Self.Comando_W(obj_Comando.Comando)
Else If (obj_Comando.Comando='J') Or (obj_Comando.Comando='j') Then
Self.Comando_J(obj_Comando.Comando)
Else If (obj_Comando.Comando='M') Or (obj_Comando.Comando='m') Then
Self.Comando_M(obj_Comando.Comando)
Else If obj_Comando.Comando='d' Then
Self.Comando_D(obj_Comando.Comando)
Else If obj_Comando.Comando='ri' Then
Self.Comando_RI
Else If obj_Comando.Comando='i' Then
Self.Comando_I
Else If obj_Comando.Comando='gs' Then
Self.Comando_GS
Else If (obj_Comando.Comando='q') Or (obj_Comando.Comando='Q') Then
Self.Comando_Q(obj_Comando.Comando)
Else if obj_Comando.Comando='cm' Then
Self.Comando_CM
Else If obj_Comando.Comando='l' Then
Self.Comando_L
Else If obj_Comando.Comando='c' Then
Self.Comando_C
Else If obj_Comando.Comando='v' Then
Self.Comando_V
Else If obj_Comando.Comando='y' Then
Self.Comando_Y
Else If obj_Comando.Comando='h' Then
Self.Comando_H
Else If obj_Comando.Comando='re' Then
Self.Comando_RE
Else If (obj_Comando.Comando='S') Or (obj_Comando.Comando='s') Then
Self.Comando_S(obj_Comando.Comando)
Else If (obj_Comando.Comando='f') Or (obj_Comando.Comando='f*') Or (obj_Comando.Comando='F') Then
Self.Comando_F(obj_Comando.Comando)
Else If (obj_Comando.Comando='b') Or (obj_Comando.Comando='B') Or (obj_Comando.Comando='b*') Then
Self.Comando_B(obj_Comando.Comando)
Else If obj_Comando.Comando='n' Then
Self.Comando_N
Else If (obj_Comando.Comando='CS') Or (obj_Comando.Comando='cs') Then
Self.Comando_CS(obj_Comando.Comando)
Else If (obj_Comando.Comando='SC') Or (obj_Comando.Comando='sc') Then
Self.Comando_SC(obj_Comando.Comando)
Else If (obj_Comando.Comando='SCN') Or (obj_Comando.Comando='scn') Then
Self.Comando_SCN(obj_Comando.Comando)
Else If (obj_Comando.Comando='G') Or (obj_Comando.Comando='g') Then
Self.Comando_G(obj_Comando.Comando)
Else If (obj_Comando.Comando='RG') Or (obj_Comando.Comando='rg') Then
Self.Comando_RG(obj_Comando.Comando)
Else If (obj_Comando.Comando='K') Or (obj_Comando.Comando='k') Then
Self.Comando_K(obj_Comando.Comando)
Else If obj_Comando.Comando='sh' Then
Self.Comando_SH
Else If obj_Comando.Comando='BI' Then
Self.Comando_BI
Else If obj_Comando.Comando='ID' Then
Self.Comando_ID
Else If obj_Comando.Comando='EI' Then
Self.Comando_EI
Else If obj_Comando.Comando='Do' Then
Self.Comando_DO;
End;
cat_texto:
Begin
//Comando para manipulação de textos.
If obj_Comando.Comando='BT' Then
Comando_BT
Else If obj_Comando.Comando='ET' Then
Comando_ET
Else If obj_Comando.Comando='Tc' Then
Comando_TC
Else If obj_Comando.Comando='Tw' Then
Comando_TW
Else If obj_Comando.Comando='Tz' Then
Comando_TZ
Else If obj_Comando.Comando='TL' Then
Comando_TL
Else If obj_Comando.Comando='Tf' Then
Comando_TF
Else If obj_Comando.Comando='Tr' Then
Comando_TR
Else If obj_Comando.Comando='Ts' Then
Comando_TS
Else If (obj_Comando.Comando='Td') Or (obj_Comando.Comando='TD') Then
Comando_TD(obj_Comando.Comando)
Else If obj_Comando.Comando='Tm' Then
Comando_TM
Else If obj_Comando.Comando='T*' Then
Comando_T
Else If (obj_Comando.Comando='Tj') Or (obj_Comando.Comando='TJ') Then
Comando_TJ(obj_Comando.Comando)
Else If (obj_Comando.Comando='''') Or (obj_Comando.Comando='"') Then
Comando_Aspas(obj_Comando.Comando)
Else If obj_Comando.Comando='d0' Then
Comando_D0
Else If obj_Comando.Comando='d1' Then
Comando_D1
End;
cat_cont_marc:
Begin
//Comandos para manipulação de conteúdo marcado.
If obj_Comando.Comando='MP' Then
Comando_MP
Else If obj_Comando.Comando='DP' Then
Comando_DP
Else If obj_Comando.Comando='BMC' Then
Comando_BMC
Else If obj_Comando.Comando='BDC' Then
Comando_BDC
Else If obj_Comando.Comando='EMC' Then
Comando_EMC
End;
cat_compat:
Begin
//Comandos compatibilidade.
If obj_Comando.Comando='BX'Then
Comando_BX
Else If obj_Comando.Comando='EX'Then
Comando_EX
End;
End
End
Else If obj_Comando.Tipo<>com_fim Then
Begin
Self.obj_Param.Insere(obj_Comando);
str_Linha:=str_Linha+' '+obj_Comando.Comando;
End;
Until obj_Comando.Tipo=com_fim;
//Self.obj_Grafico.Desenha;
stl_Comando.SaveToFile('c:\Temp\'+FormatDateTime('yyyymmddhhnn',Now)+'.txt');
End;
End.
|
unit abDeleteWizard;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, abWizardTemplate, ComCtrls, StdCtrls, ExtCtrls,
nsProcessFrm, nsGlobals, nsTypes;
type
TfrmDeleteWizard = class(TfrmWizardTemplate)
ts1: TTabSheet;
ts2: TTabSheet;
Panel3: TPanel;
Label34: TLabel;
Label35: TLabel;
chkProcessImmediately: TCheckBox;
Panel1: TPanel;
Label7: TLabel;
Label8: TLabel;
pnlProcess: TPanel;
Image1: TImage;
lblCount: TLabel;
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
FProject: TNSProject;
FOldProcess: TfrmProcess;
FIntProcess: TfrmProcess;
FNumberOfProcessed: integer;
FList: TStrings;
procedure InitList(const AList: TStrings);
procedure MarkForDeletion;
public
{ Public declarations }
function GoForward: integer; override;
function GoBack: integer; override;
end;
var
frmDeleteWizard: TfrmDeleteWizard;
function DeleteWizard(const AProject: TNSProject; const AList: TStrings): Boolean;
implementation
uses nsActions;
{$R *.dfm}
function DeleteWizard(const AProject: TNSProject; const AList: TStrings): Boolean;
begin
frmDeleteWizard := TfrmDeleteWizard.Create(Application);
with frmDeleteWizard do
try
FProject := AProject;
InitList(AList);
if FProject <> nil then
begin
FOldProcess := FProject.FProgress;
FProject.FProgress := FIntProcess;
end;
Result := ShowModal = mrOk;
finally
if FProject <> nil then
FProject.FProgress := FOldProcess;
Free;
end;
end;
procedure TfrmDeleteWizard.btnCancelClick(Sender: TObject);
begin
if PageControl.ActivePageIndex = 1 then
begin
g_AbortProcess := True;
Application.ProcessMessages;
ModalResult := mrCancel;
end
else
ModalResult := mrCancel;
end;
procedure TfrmDeleteWizard.FormCreate(Sender: TObject);
begin
inherited;
FIntProcess := TfrmProcess.Create(Self);
with FIntProcess do
begin
Color := clWhite;
Parent := pnlProcess;
BorderStyle := bsNone;
Align := alClient;
pnlBottom.Visible := False;
Visible := True;
end;
end;
function TfrmDeleteWizard.GoBack: integer;
begin
Result := 1;
end;
function TfrmDeleteWizard.GoForward: integer;
begin
Result := 0;
case PageControl.ActivePageIndex of
0:
begin
MarkForDeletion;
end;
end;
end;
procedure TfrmDeleteWizard.InitList(const AList: TStrings);
begin
FList := AList;
lblCount.Caption := Format(sItemsSelectForDel, [FList.Count]);
end;
procedure TfrmDeleteWizard.MarkForDeletion;
var
I: integer;
Item: TNSItem;
NeedRebuild: Boolean;
begin
for I := 0 to FList.Count - 1 do
begin
Item := TNSItem(FList.Objects[I]);
MarkItemForDeletion(FProject, Item, NeedRebuild);
end;
PageControl.ActivePageIndex := 1;
// if chkProcessImmediately.Checked then
begin
Self.Update;
Application.ProcessMessages;
g_AbortProcess := False;
FNumberOfProcessed := ProcessProject(FProject, csDelete);
ModalResult := mrOk;
end;
(*
else
begin
ModalResult := mrOk;
end;
*)
end;
end.
|
unit UDCrossTabs;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32;
type
TCrpeCrossTabsDlg = class(TForm)
pnlCrossTabs: TPanel;
gbObjectFormatting: TGroupBox;
btnBorder: TButton;
btnFormat: TButton;
editTop: TEdit;
lblTop: TLabel;
lblLeft: TLabel;
editLeft: TEdit;
lblSection: TLabel;
editWidth: TEdit;
lblWidth: TLabel;
lblHeight: TLabel;
editHeight: TEdit;
cbSection: TComboBox;
btnOk: TButton;
lblNumber: TLabel;
lbNumbers: TListBox;
editCount: TEdit;
lblCount: TLabel;
gbGridOptions: TGroupBox;
cbShowCellMargins: TCheckBox;
cbShowGridLines: TCheckBox;
cbRepeatRowLabels: TCheckBox;
cbKeepColumnsTogether: TCheckBox;
cbSuppressEmptyRows: TCheckBox;
cbSuppressEmptyColumns: TCheckBox;
cbSuppressRowGrandTotals: TCheckBox;
cbSuppressColumnGrandTotals: TCheckBox;
lblColorRowGrandTotals: TLabel;
cbColorRowGrandTotals: TComboBox;
ColorDialog1: TColorDialog;
lblColorColumnGrandTotals: TLabel;
cbColorColumnGrandTotals: TComboBox;
rgUnits: TRadioGroup;
btnSummaries: TButton;
btnRowGroups: TButton;
btnColumnGroups: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure editSizeEnter(Sender: TObject);
procedure editSizeExit(Sender: TObject);
procedure cbSectionChange(Sender: TObject);
procedure btnBorderClick(Sender: TObject);
procedure btnFormatClick(Sender: TObject);
procedure UpdateCrossTabs;
procedure lbNumbersClick(Sender: TObject);
procedure cbColorRowGrandTotalsDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
procedure cbColorColumnGrandTotalsDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
procedure cbColorRowGrandTotalsChange(Sender: TObject);
procedure cbColorColumnGrandTotalsChange(Sender: TObject);
procedure cbShowCellMarginsClick(Sender: TObject);
procedure cbShowGridLinesClick(Sender: TObject);
procedure cbRepeatRowLabelsClick(Sender: TObject);
procedure cbKeepColumnsTogetherClick(Sender: TObject);
procedure cbSuppressEmptyRowsClick(Sender: TObject);
procedure cbSuppressEmptyColumnsClick(Sender: TObject);
procedure cbSuppressRowGrandTotalsClick(Sender: TObject);
procedure cbSuppressColumnGrandTotalsClick(Sender: TObject);
procedure btnSummariesClick(Sender: TObject);
procedure btnRowGroupsClick(Sender: TObject);
procedure btnColumnGroupsClick(Sender: TObject);
procedure rgUnitsClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
CrossTabIndex : smallint;
PrevSize : string;
CustomRowColor : TColor;
CustomColumnColor : TColor;
end;
var
CrpeCrossTabsDlg: TCrpeCrossTabsDlg;
bCrossTabs : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl, UDBorder, UDFormat, UDCrossTabSummaries, UDCrossTabGroups;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.FormCreate(Sender: TObject);
begin
bCrossTabs := True;
LoadFormPos(Self);
CrossTabIndex := -1;
btnOk.Tag := 1;
CustomRowColor := clNone;
CustomColumnColor := clNone;
{ColorColumnGrandTotals}
with cbColorColumnGrandTotals.Items do
begin
AddObject('clBlack', Pointer(clBlack));
AddObject('clMaroon', Pointer(clMaroon));
AddObject('clGreen', Pointer(clGreen));
AddObject('clOlive', Pointer(clOlive));
AddObject('clNavy', Pointer(clNavy));
AddObject('clPurple', Pointer(clPurple));
AddObject('clTeal', Pointer(clTeal));
AddObject('clGray', Pointer(clGray));
AddObject('clSilver', Pointer(clSilver));
AddObject('clRed', Pointer(clRed));
AddObject('clLime', Pointer(clLime));
AddObject('clYellow', Pointer(clYellow));
AddObject('clBlue', Pointer(clBlue));
AddObject('clFuchsia', Pointer(clFuchsia));
AddObject('clAqua', Pointer(clAqua));
AddObject('clWhite', Pointer(clWhite));
AddObject('clNone', Pointer(clNone));
AddObject('Custom', Pointer(CustomColumnColor));
end;
{ColorRowGrandTotals}
with cbColorRowGrandTotals.Items do
begin
AddObject('clBlack', Pointer(clBlack));
AddObject('clMaroon', Pointer(clMaroon));
AddObject('clGreen', Pointer(clGreen));
AddObject('clOlive', Pointer(clOlive));
AddObject('clNavy', Pointer(clNavy));
AddObject('clPurple', Pointer(clPurple));
AddObject('clTeal', Pointer(clTeal));
AddObject('clGray', Pointer(clGray));
AddObject('clSilver', Pointer(clSilver));
AddObject('clRed', Pointer(clRed));
AddObject('clLime', Pointer(clLime));
AddObject('clYellow', Pointer(clYellow));
AddObject('clBlue', Pointer(clBlue));
AddObject('clFuchsia', Pointer(clFuchsia));
AddObject('clAqua', Pointer(clAqua));
AddObject('clWhite', Pointer(clWhite));
AddObject('clNone', Pointer(clNone));
AddObject('Custom', Pointer(CustomRowColor));
end;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.FormShow(Sender: TObject);
begin
UpdateCrossTabs;
end;
{------------------------------------------------------------------------------}
{ UpdateCrossTabs }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.UpdateCrossTabs;
var
i : integer;
OnOff : boolean;
begin
CrossTabIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
OnOff := False
else
begin
OnOff := (Cr.CrossTabs.Count > 0);
{Get CrossTab Index}
if OnOff then
begin
if Cr.CrossTabs.ItemIndex > -1 then
CrossTabIndex := Cr.CrossTabs.ItemIndex
else
CrossTabIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff = True then
begin
{Fill Section ComboBox}
cbSection.Items.AddStrings(Cr.SectionFormat.Names);
{Fill Numbers ListBox}
for i := 0 to Cr.CrossTabs.Count - 1 do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Cr.CrossTabs.Count);
lbNumbers.ItemIndex := CrossTabIndex;
lbNumbersClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ lbNumbersClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.lbNumbersClick(Sender: TObject);
begin
CrossTabIndex := lbNumbers.ItemIndex;
Cr.CrossTabs[CrossTabIndex];
{CrossTab options}
cbShowCellMargins.Checked := Cr.CrossTabs.Item.ShowCellMargins;
cbShowGridLines.Checked := Cr.CrossTabs.Item.ShowGridLines;
cbRepeatRowLabels.Checked := Cr.CrossTabs.Item.RepeatRowLabels;
cbKeepColumnsTogether.Checked := Cr.CrossTabs.Item.KeepColumnsTogether;
cbSuppressEmptyRows.Checked := Cr.CrossTabs.Item.SuppressEmptyRows;
cbSuppressEmptyColumns.Checked := Cr.CrossTabs.Item.SuppressEmptyColumns;
cbSuppressRowGrandTotals.Checked := Cr.CrossTabs.Item.SuppressRowGrandTotals;
cbSuppressColumnGrandTotals.Checked := Cr.CrossTabs.Item.SuppressColumnGrandTotals;
{ColorColumnGrandTotals}
case Cr.CrossTabs.Item.ColorColumnGrandTotals of
clBlack : cbColorColumnGrandTotals.ItemIndex := 0;
clMaroon : cbColorColumnGrandTotals.ItemIndex := 1;
clGreen : cbColorColumnGrandTotals.ItemIndex := 2;
clOlive : cbColorColumnGrandTotals.ItemIndex := 3;
clNavy : cbColorColumnGrandTotals.ItemIndex := 4;
clPurple : cbColorColumnGrandTotals.ItemIndex := 5;
clTeal : cbColorColumnGrandTotals.ItemIndex := 6;
clGray : cbColorColumnGrandTotals.ItemIndex := 7;
clSilver : cbColorColumnGrandTotals.ItemIndex := 8;
clRed : cbColorColumnGrandTotals.ItemIndex := 9;
clLime : cbColorColumnGrandTotals.ItemIndex := 10;
clYellow : cbColorColumnGrandTotals.ItemIndex := 11;
clBlue : cbColorColumnGrandTotals.ItemIndex := 12;
clFuchsia : cbColorColumnGrandTotals.ItemIndex := 13;
clAqua : cbColorColumnGrandTotals.ItemIndex := 14;
clWhite : cbColorColumnGrandTotals.ItemIndex := 15;
clNone : cbColorColumnGrandTotals.ItemIndex := 16;
else {Custom}
begin
cbColorColumnGrandTotals.ItemIndex := 17;
CustomColumnColor := Cr.CrossTabs.Item.ColorColumnGrandTotals;
cbColorColumnGrandTotals.Items.Objects[17] := Pointer(CustomColumnColor);
end;
end;
{ColorRowGrandTotals}
case Cr.CrossTabs.Item.ColorRowGrandTotals of
clBlack : cbColorRowGrandTotals.ItemIndex := 0;
clMaroon : cbColorRowGrandTotals.ItemIndex := 1;
clGreen : cbColorRowGrandTotals.ItemIndex := 2;
clOlive : cbColorRowGrandTotals.ItemIndex := 3;
clNavy : cbColorRowGrandTotals.ItemIndex := 4;
clPurple : cbColorRowGrandTotals.ItemIndex := 5;
clTeal : cbColorRowGrandTotals.ItemIndex := 6;
clGray : cbColorRowGrandTotals.ItemIndex := 7;
clSilver : cbColorRowGrandTotals.ItemIndex := 8;
clRed : cbColorRowGrandTotals.ItemIndex := 9;
clLime : cbColorRowGrandTotals.ItemIndex := 10;
clYellow : cbColorRowGrandTotals.ItemIndex := 11;
clBlue : cbColorRowGrandTotals.ItemIndex := 12;
clFuchsia : cbColorRowGrandTotals.ItemIndex := 13;
clAqua : cbColorRowGrandTotals.ItemIndex := 14;
clWhite : cbColorRowGrandTotals.ItemIndex := 15;
clNone : cbColorRowGrandTotals.ItemIndex := 16;
else {Custom}
begin
cbColorRowGrandTotals.ItemIndex := 17;
CustomRowColor := Cr.CrossTabs.Item.ColorRowGrandTotals;
cbColorRowGrandTotals.Items.Objects[17] := Pointer(CustomRowColor);
end;
end;
{Size and Position}
cbSection.ItemIndex := Cr.SectionFormat.IndexOf(Cr.CrossTabs.Item.Section);
rgUnitsClick(Self);
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TRadioGroup then
TRadioGroup(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ cbColorRowGrandTotalsDrawItem }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbColorRowGrandTotalsDrawItem(
Control: TWinControl; Index: Integer; Rect: TRect;
State: TOwnerDrawState);
var
ColorR : TRect;
TextR : TRect;
OldColor : TColor;
begin
ColorR.Left := Rect.Left + 1;
ColorR.Top := Rect.Top + 1;
ColorR.Right := Rect.Left + 18{ColorWidth} - 1;
ColorR.Bottom := Rect.Top + cbColorRowGrandTotals.ItemHeight - 1;
TextR.Left := Rect.Left + 18{ColorWidth} + 4;
TextR.Top := Rect.Top + 1;
TextR.Right := Rect.Right;
TextR.Bottom := Rect.Bottom - 1;
with cbColorRowGrandTotals.Canvas do
begin
FillRect(Rect); { clear the rectangle }
OldColor := Brush.Color;
Brush.Color := TColor(cbColorRowGrandTotals.Items.Objects[Index]);
Rectangle(ColorR.Left, ColorR.Top, ColorR.Right, ColorR.Bottom);
Brush.Color := OldColor;
DrawText(Handle, PChar(cbColorRowGrandTotals.Items[Index]), -1, TextR, DT_VCENTER or DT_SINGLELINE);
end;
end;
{------------------------------------------------------------------------------}
{ cbColorColumnGrandTotalsDrawItem }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbColorColumnGrandTotalsDrawItem(
Control: TWinControl; Index: Integer; Rect: TRect;
State: TOwnerDrawState);
var
ColorR : TRect;
TextR : TRect;
OldColor : TColor;
begin
ColorR.Left := Rect.Left + 1;
ColorR.Top := Rect.Top + 1;
ColorR.Right := Rect.Left + 18{ColorWidth} - 1;
ColorR.Bottom := Rect.Top + cbColorColumnGrandTotals.ItemHeight - 1;
TextR.Left := Rect.Left + 18{ColorWidth} + 4;
TextR.Top := Rect.Top + 1;
TextR.Right := Rect.Right;
TextR.Bottom := Rect.Bottom - 1;
with cbColorColumnGrandTotals.Canvas do
begin
FillRect(Rect); { clear the rectangle }
OldColor := Brush.Color;
Brush.Color := TColor(cbColorColumnGrandTotals.Items.Objects[Index]);
Rectangle(ColorR.Left, ColorR.Top, ColorR.Right, ColorR.Bottom);
Brush.Color := OldColor;
DrawText(Handle, PChar(cbColorColumnGrandTotals.Items[Index]), -1, TextR, DT_VCENTER or DT_SINGLELINE);
end;
end;
{------------------------------------------------------------------------------}
{ cbColorRowGrandTotalsChange }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbColorRowGrandTotalsChange(Sender: TObject);
var
xColor : TColor;
i : integer;
begin
i := cbColorRowGrandTotals.ItemIndex;
xColor := TColor(cbColorRowGrandTotals.Items.Objects[i]);
if cbColorRowGrandTotals.Items[i] = 'Custom' then
begin
ColorDialog1.Color := xColor;
if ColorDialog1.Execute then
begin
xColor := ColorDialog1.Color;
CustomRowColor := xColor;
cbColorRowGrandTotals.Items.Objects[i] := Pointer(CustomRowColor);
end;
end;
Cr.CrossTabs[CrossTabIndex].ColorRowGrandTotals := xColor;
end;
{------------------------------------------------------------------------------}
{ cbColorColumnGrandTotalsChange }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbColorColumnGrandTotalsChange(
Sender: TObject);
var
xColor : TColor;
i : integer;
begin
i := cbColorColumnGrandTotals.ItemIndex;
xColor := TColor(cbColorColumnGrandTotals.Items.Objects[i]);
if cbColorColumnGrandTotals.Items[i] = 'Custom' then
begin
ColorDialog1.Color := xColor;
if ColorDialog1.Execute then
begin
xColor := ColorDialog1.Color;
CustomColumnColor := xColor;
cbColorColumnGrandTotals.Items.Objects[i] := Pointer(CustomColumnColor);
end;
end;
Cr.CrossTabs[CrossTabIndex].ColorColumnGrandTotals := xColor;
end;
{------------------------------------------------------------------------------}
{ cbShowCellMarginsClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbShowCellMarginsClick(Sender: TObject);
begin
Cr.CrossTabs.Item.ShowCellMargins := cbShowCellMargins.Checked;
end;
{------------------------------------------------------------------------------}
{ cbShowGridLinesClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbShowGridLinesClick(Sender: TObject);
begin
Cr.CrossTabs.Item.ShowGridLines := cbShowGridLines.Checked;
end;
{------------------------------------------------------------------------------}
{ cbRepeatRowLabelsClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbRepeatRowLabelsClick(Sender: TObject);
begin
Cr.CrossTabs.Item.RepeatRowLabels := cbRepeatRowLabels.Checked;
end;
{------------------------------------------------------------------------------}
{ cbKeepColumnsTogetherClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbKeepColumnsTogetherClick(Sender: TObject);
begin
Cr.CrossTabs.Item.KeepColumnsTogether := cbKeepColumnsTogether.Checked;
end;
{------------------------------------------------------------------------------}
{ cbSuppressEmptyRowsClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbSuppressEmptyRowsClick(Sender: TObject);
begin
Cr.CrossTabs.Item.SuppressEmptyRows := cbSuppressEmptyRows.Checked;
end;
{------------------------------------------------------------------------------}
{ cbSuppressEmptyColumnsClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbSuppressEmptyColumnsClick(Sender: TObject);
begin
Cr.CrossTabs.Item.SuppressEmptyColumns := cbSuppressEmptyColumns.Checked;
end;
{------------------------------------------------------------------------------}
{ cbSuppressRowGrandTotalsClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbSuppressRowGrandTotalsClick(Sender: TObject);
begin
Cr.CrossTabs.Item.SuppressRowGrandTotals := cbSuppressRowGrandTotals.Checked;
end;
{------------------------------------------------------------------------------}
{ cbSuppressColumnGrandTotalsClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbSuppressColumnGrandTotalsClick(
Sender: TObject);
begin
Cr.CrossTabs.Item.SuppressColumnGrandTotals := cbSuppressColumnGrandTotals.Checked;
end;
{------------------------------------------------------------------------------}
{ btnSummariesClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.btnSummariesClick(Sender: TObject);
begin
CrpeCrossTabSummariesDlg := TCrpeCrossTabSummariesDlg.Create(Application);
CrpeCrossTabSummariesDlg.Crs := Cr.CrossTabs[CrossTabIndex].Summaries;
CrpeCrossTabSummariesDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnRowGroupsClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.btnRowGroupsClick(Sender: TObject);
begin
CrpeCrossTabGroupsDlg := TCrpeCrossTabGroupsDlg.Create(Application);
CrpeCrossTabGroupsDlg.Caption := 'CrossTab RowGroups';
CrpeCrossTabGroupsDlg.Crg := Cr.CrossTabs[CrossTabIndex].RowGroups;
CrpeCrossTabGroupsDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnColumnGroupsClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.btnColumnGroupsClick(Sender: TObject);
begin
CrpeCrossTabGroupsDlg := TCrpeCrossTabGroupsDlg.Create(Application);
CrpeCrossTabGroupsDlg.Caption := 'CrossTab ColumnGroups';
CrpeCrossTabGroupsDlg.Crg := Cr.CrossTabs[CrossTabIndex].ColumnGroups;
CrpeCrossTabGroupsDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ rgUnitsClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.rgUnitsClick(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
editTop.Text := TwipsToInchesStr(Cr.CrossTabs[CrossTabIndex].Top);
editLeft.Text := TwipsToInchesStr(Cr.CrossTabs[CrossTabIndex].Left);
editWidth.Text := TwipsToInchesStr(Cr.CrossTabs[CrossTabIndex].Width);
editHeight.Text := TwipsToInchesStr(Cr.CrossTabs[CrossTabIndex].Height);
end
else {twips}
begin
editTop.Text := IntToStr(Cr.CrossTabs[CrossTabIndex].Top);
editLeft.Text := IntToStr(Cr.CrossTabs[CrossTabIndex].Left);
editWidth.Text := IntToStr(Cr.CrossTabs[CrossTabIndex].Width);
editHeight.Text := IntToStr(Cr.CrossTabs[CrossTabIndex].Height);
end;
end;
{------------------------------------------------------------------------------}
{ editSizeEnter }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.editSizeEnter(Sender: TObject);
begin
if Sender is TEdit then
PrevSize := TEdit(Sender).Text;
end;
{------------------------------------------------------------------------------}
{ editSizeExit }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.editSizeExit(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
if not IsFloating(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.CrossTabs[CrossTabIndex].Top := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.CrossTabs[CrossTabIndex].Left := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editWidth' then
Cr.CrossTabs[CrossTabIndex].Width := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editHeight' then
Cr.CrossTabs[CrossTabIndex].Height := InchesStrToTwips(TEdit(Sender).Text);
UpdateCrossTabs; {this will truncate any decimals beyond 3 places}
end;
end
else {twips}
begin
if not IsNumeric(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.CrossTabs[CrossTabIndex].Top := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.CrossTabs[CrossTabIndex].Left := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editWidth' then
Cr.CrossTabs[CrossTabIndex].Width := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editHeight' then
Cr.CrossTabs[CrossTabIndex].Height := StrToInt(TEdit(Sender).Text);
end;
end;
end;
{------------------------------------------------------------------------------}
{ cbSectionChange }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.cbSectionChange(Sender: TObject);
begin
Cr.CrossTabs[CrossTabIndex].Section := cbSection.Items[cbSection.ItemIndex];
end;
{------------------------------------------------------------------------------}
{ btnBorderClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.btnBorderClick(Sender: TObject);
begin
CrpeBorderDlg := TCrpeBorderDlg.Create(Application);
CrpeBorderDlg.Border := Cr.CrossTabs[CrossTabIndex].Border;
CrpeBorderDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnFormatClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.btnFormatClick(Sender: TObject);
begin
CrpeFormatDlg := TCrpeFormatDlg.Create(Application);
CrpeFormatDlg.Format := Cr.CrossTabs[CrossTabIndex].Format;
CrpeFormatDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.btnOkClick(Sender: TObject);
begin
rgUnits.ItemIndex := 1; {change to twips to avoid the Update call}
if (not IsStrEmpty(Cr.ReportName)) and (CrossTabIndex > -1) then
begin
editSizeExit(editTop);
editSizeExit(editLeft);
editSizeExit(editWidth);
editSizeExit(editHeight);
end;
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabsDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bCrossTabs := False;
Release;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{
FMOD based sound-manager (http://www.fmod.org/, free for freeware).
Unsupported feature(s) :
sound source velocity
looping (sounds are played either once or forever)
sound cones
}
unit GLSMFMOD;
interface
{$I GLScene.inc}
uses
System.Classes,
System.SysUtils,
GLSound,
GLScene,
GLVectorGeometry,
FMod,
FmodTypes,
FmodPresets;
type
TGLSMFMOD = class(TGLSoundManager)
private
FActivated: Boolean;
FEAXCapable: Boolean; // not persistent
protected
function DoActivate: Boolean; override;
procedure DoDeActivate; override;
procedure NotifyMasterVolumeChange; override;
procedure Notify3DFactorsChanged; override;
procedure NotifyEnvironmentChanged; override;
procedure KillSource(aSource: TGLBaseSoundSource); override;
procedure UpdateSource(aSource: TGLBaseSoundSource); override;
procedure MuteSource(aSource: TGLBaseSoundSource; muted: Boolean); override;
procedure PauseSource(aSource: TGLBaseSoundSource; paused: Boolean); override;
function GetDefaultFrequency(aSource: TGLBaseSoundSource): Integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure UpdateSources; override;
function CPUUsagePercent: Single; override;
function EAXSupported: Boolean; override;
published
property MaxChannels default 32;
end;
// ---------------------------------------------------------------------
implementation
// ---------------------------------------------------------------------
type
TFMODInfo = record
channel: Integer;
pfs: PFSoundSample;
end;
PFMODInfo = ^TFMODInfo;
procedure VectorToFMODVector(const aVector: TVector; var aFMODVector: TFSoundVector);
begin
aFMODVector.X := aVector.X;
aFMODVector.Y := aVector.Y;
aFMODVector.Z := -aVector.Z;
end;
// ------------------
// ------------------ TGLSMFMOD ------------------
// ------------------
constructor TGLSMFMOD.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
MaxChannels := 32;
end;
destructor TGLSMFMOD.Destroy;
begin
inherited Destroy;
end;
function TGLSMFMOD.DoActivate: Boolean;
var
cap: Cardinal;
begin
FMOD_Load(nil);
{$IFDEF MSWINDOWS}
if not FSOUND_SetOutput(FSOUND_OUTPUT_DSOUND) then
begin
Result := False;
Exit;
end;
{$ENDIF}
{$IFDEF LINUX}
if not FSOUND_SetOutput(FSOUND_OUTPUT_ALSA) then
begin
Result := False;
Exit;
end;
{$ENDIF}
if not FSOUND_SetDriver(0) then
begin
Result := False;
Exit;
end;
cap := 0;
if FSOUND_GetDriverCaps(0, cap) then
FEAXCapable := ((cap and (FSOUND_CAPS_EAX2 or FSOUND_CAPS_EAX3)) > 0)
else
Assert(False, 'Failed to retrieve driver Caps.');
if not FSOUND_Init(OutputFrequency, MaxChannels, 0) then
Assert(False, 'FSOUND_Init failed.');
FActivated := True;
NotifyMasterVolumeChange;
Notify3DFactorsChanged;
if Environment <> seDefault then
NotifyEnvironmentChanged;
Result := True;
end;
procedure TGLSMFMOD.DoDeActivate;
begin
FSOUND_StopSound(FSOUND_ALL);
FSOUND_Close;
FMOD_Unload;
FEAXCapable := False;
end;
procedure TGLSMFMOD.NotifyMasterVolumeChange;
begin
if FActivated then
FSOUND_SetSFXMasterVolume(Round(MasterVolume * 255));
end;
procedure TGLSMFMOD.Notify3DFactorsChanged;
begin
if FActivated then
begin
FSOUND_3D_SetDistanceFactor(DistanceFactor);
FSOUND_3D_SetRolloffFactor(RollOffFactor);
FSOUND_3D_SetDopplerFactor(DopplerFactor);
end;
end;
procedure TGLSMFMOD.NotifyEnvironmentChanged;
var
SoundRevProps: TFSoundReverbProperties;
begin
if FActivated and EAXSupported then
begin
case Environment of
seDefault : SoundRevProps := FSOUND_PRESET_GENERIC;
sePaddedCell : SoundRevProps := FSOUND_PRESET_PADDEDCELL;
seRoom : SoundRevProps := FSOUND_PRESET_ROOM;
seBathroom : SoundRevProps := FSOUND_PRESET_BATHROOM;
seLivingRoom : SoundRevProps := FSOUND_PRESET_LIVINGROOM;
seStoneroom : SoundRevProps := FSOUND_PRESET_STONEROOM;
seAuditorium : SoundRevProps := FSOUND_PRESET_AUDITORIUM;
seConcertHall : SoundRevProps := FSOUND_PRESET_CONCERTHALL;
seCave : SoundRevProps := FSOUND_PRESET_CAVE;
seArena : SoundRevProps := FSOUND_PRESET_ARENA;
seHangar : SoundRevProps := FSOUND_PRESET_HANGAR;
seCarpetedHallway : SoundRevProps := FSOUND_PRESET_CARPETTEDHALLWAY;
seHallway : SoundRevProps := FSOUND_PRESET_HALLWAY;
seStoneCorridor : SoundRevProps := FSOUND_PRESET_STONECORRIDOR;
seAlley : SoundRevProps := FSOUND_PRESET_ALLEY;
seForest : SoundRevProps := FSOUND_PRESET_FOREST;
seCity : SoundRevProps := FSOUND_PRESET_CITY;
seMountains : SoundRevProps := FSOUND_PRESET_MOUNTAINS;
seQuarry : SoundRevProps := FSOUND_PRESET_QUARRY;
sePlain : SoundRevProps := FSOUND_PRESET_PLAIN;
seParkingLot : SoundRevProps := FSOUND_PRESET_PARKINGLOT;
seSewerPipe : SoundRevProps := FSOUND_PRESET_SEWERPIPE;
seUnderWater : SoundRevProps := FSOUND_PRESET_UNDERWATER;
seDrugged : SoundRevProps := FSOUND_PRESET_DRUGGED;
seDizzy : SoundRevProps := FSOUND_PRESET_DIZZY;
sePsychotic : SoundRevProps := FSOUND_PRESET_PSYCHOTIC;
else
Assert(False);
end;
FSOUND_Reverb_SetProperties(SoundRevProps);
end;
end;
procedure TGLSMFMOD.KillSource(aSource: TGLBaseSoundSource);
var
p: PFMODInfo;
begin
if aSource.ManagerTag <> 0 then
begin
p := PFMODInfo(aSource.ManagerTag);
aSource.ManagerTag := 0;
if p.channel <> -1 then
if not FSOUND_StopSound(p.channel) then
Assert(False, IntToStr(Integer(p)));
FSOUND_Sample_Free(p.pfs);
FreeMem(p);
end;
end;
procedure TGLSMFMOD.UpdateSource(aSource: TGLBaseSoundSource);
var
p: PFMODInfo;
objPos, objVel: TVector;
position, velocity: TFSoundVector;
begin
if (sscSample in aSource.Changes) then
begin
KillSource(aSource);
end;
if (aSource.Sample = nil) or (aSource.Sample.Data = nil) or (aSource.Sample.Data.WAVDataSize = 0) then
Exit;
if aSource.ManagerTag <> 0 then
begin
p := PFMODInfo(aSource.ManagerTag);
if not FSOUND_IsPlaying(p.channel) then
begin
p.channel := -1;
aSource.Free;
Exit;
end;
end
else
begin
p := AllocMem(SizeOf(TFMODInfo));
p.channel := -1;
p.pfs := FSOUND_Sample_Load(FSOUND_FREE, aSource.Sample.Data.WAVData, FSOUND_HW3D + FSOUND_LOOP_OFF + FSOUND_LOADMEMORY, 0,
aSource.Sample.Data.WAVDataSize);
if aSource.NbLoops > 1 then
FSOUND_Sample_SetMode(p.pfs, FSOUND_LOOP_NORMAL);
FSOUND_Sample_SetMinMaxDistance(p.pfs, aSource.MinDistance, aSource.MaxDistance);
aSource.ManagerTag := Integer(p);
end;
if aSource.Origin <> nil then
begin
objPos := aSource.Origin.AbsolutePosition;
objVel := NullHmgVector;
end
else
begin
objPos := NullHmgPoint;
objVel := NullHmgVector;
end;
VectorToFMODVector(objPos, position);
VectorToFMODVector(objVel, velocity);
if p.channel = -1 then
p.channel := FSOUND_PlaySound(FSOUND_FREE, p.pfs);
if p.channel <> -1 then
begin
FSOUND_3D_SetAttributes(p.channel, @position, @velocity);
FSOUND_SetVolume(p.channel, Round(aSource.Volume * 255));
FSOUND_SetMute(p.channel, aSource.Mute);
FSOUND_SetPaused(p.channel, aSource.Pause);
FSOUND_SetPriority(p.channel, aSource.Priority);
if aSource.Frequency > 0 then
FSOUND_SetFrequency(p.channel, aSource.Frequency);
end
else
aSource.Free;
inherited UpdateSource(aSource);
end;
procedure TGLSMFMOD.MuteSource(aSource: TGLBaseSoundSource; muted: Boolean);
var
p: PFMODInfo;
begin
if aSource.ManagerTag <> 0 then
begin
p := PFMODInfo(aSource.ManagerTag);
FSOUND_SetMute(p.channel, muted);
end;
end;
procedure TGLSMFMOD.PauseSource(aSource: TGLBaseSoundSource; paused: Boolean);
var
p: PFMODInfo;
begin
if aSource.ManagerTag <> 0 then
begin
p := PFMODInfo(aSource.ManagerTag);
FSOUND_SetPaused(p.channel, paused);
end;
end;
procedure TGLSMFMOD.UpdateSources;
var
objPos, objVel, objDir, objUp: TVector;
position, velocity, fwd, top: TFSoundVector;
begin
// update listener
ListenerCoordinates(objPos, objVel, objDir, objUp);
VectorToFMODVector(objPos, position);
VectorToFMODVector(objVel, velocity);
VectorToFMODVector(objDir, fwd);
VectorToFMODVector(objUp, top);
FSOUND_3D_Listener_SetAttributes(@position, @velocity, fwd.x, fwd.y, fwd.z, top.x, top.y, top.z);
// update sources
inherited;
FSOUND_Update;
end;
function TGLSMFMOD.CPUUsagePercent: Single;
begin
Result := FSOUND_GetCPUUsage;
end;
function TGLSMFMOD.EAXSupported: Boolean;
begin
Result := FEAXCapable;
end;
function TGLSMFMOD.GetDefaultFrequency(aSource: TGLBaseSoundSource): Integer;
var
p: PFMODInfo;
dfreq, dVol, dPan, dPri: Integer;
begin
try
p:=PFMODInfo(aSource.ManagerTag);
FSOUND_Sample_GetDefaults(p.pfs, dFreq, dVol, dPan, dPri);
Result:=dFreq;
except
Result:=-1;
end;
end;
end.
|
unit PaiPreSaleReceive;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Mask, DateBox, DBCtrls, DB, DBTables, Grids, DBGrids,
Buttons, DBCGrids, ComCtrls, ADODB, SuperComboADO, Variants, siComp,
siLangRT, uParentAll, uFrmPayPartial, strUtils;
type
TFrmPaiPreSaleReceive = class(TFrmParentAll)
Panel1: TPanel;
Panel9: TPanel;
Panel3: TPanel;
spTestPayType: TADOStoredProc;
spquPayTypeMin: TADOStoredProc;
spquPayTypeMinDifDay: TIntegerField;
spquPayTypeMinTotalSale: TFloatField;
pgReceive: TPageControl;
tbSingle: TTabSheet;
tbMultiple: TTabSheet;
Panel5: TPanel;
Image2: TImage;
Image8: TImage;
Label5: TLabel;
Label6: TLabel;
pnlPaymentType: TPanel;
Image1: TImage;
Image3: TImage;
spPayCash: TSpeedButton;
spPayVisa: TSpeedButton;
spPayMaster: TSpeedButton;
spPayAmerican: TSpeedButton;
Label4: TLabel;
pnlPayTitle: TPanel;
cmbPaymentType: TSuperComboADO;
pnlDepositDate: TPanel;
lblPreDate: TLabel;
Image6: TImage;
Image7: TImage;
spDep30: TSpeedButton;
spDep60: TSpeedButton;
spDep90: TSpeedButton;
pnlDateTitle: TPanel;
EditDepositDate: TDateBox;
Panel2: TPanel;
Image10: TImage;
Image11: TImage;
Label3: TLabel;
Label7: TLabel;
Label8: TLabel;
EditTotalInvoice: TEdit;
btMulti2: TSpeedButton;
btMulti3: TSpeedButton;
btMulti4: TSpeedButton;
pnlShowCash: TPanel;
lblCashTotal: TLabel;
EditTotalCash: TEdit;
lblPlus: TLabel;
lblReceived: TLabel;
EditReceived: TEdit;
lblMinus: TLabel;
spLine: TShape;
lblChange: TLabel;
EditChange: TEdit;
lblEqual: TLabel;
Label13: TLabel;
EditReceiveDate: TDateBox;
pnlShowAuthorization: TPanel;
Label1: TLabel;
EditAuthorization: TEdit;
btMulti5: TSpeedButton;
pnlMultiParcela: TPanel;
pnlParc1: TPanel;
lblParc1: TLabel;
Label12: TLabel;
cmbPayType1: TSuperComboADO;
lblAuto1: TLabel;
EditAuto1: TEdit;
EditDep1: TDateBox;
lblDep1: TLabel;
Label16: TLabel;
EditValue1: TEdit;
pnlParc2: TPanel;
Label17: TLabel;
Label18: TLabel;
lblAuto2: TLabel;
lblDep2: TLabel;
Label22: TLabel;
cmbPayType2: TSuperComboADO;
EditAuto2: TEdit;
EditDep2: TDateBox;
EditValue2: TEdit;
pnlParc3: TPanel;
Label23: TLabel;
Label24: TLabel;
lblAuto3: TLabel;
lblDep3: TLabel;
Label28: TLabel;
cmbPayType3: TSuperComboADO;
EditAuto3: TEdit;
EditDep3: TDateBox;
EditValue3: TEdit;
pnlParc4: TPanel;
Label29: TLabel;
Label30: TLabel;
lblAuto4: TLabel;
lblDep4: TLabel;
Label33: TLabel;
cmbPayType4: TSuperComboADO;
EditAuto4: TEdit;
EditDep4: TDateBox;
EditValue4: TEdit;
pnlParc5: TPanel;
Label34: TLabel;
Label35: TLabel;
lblAuto5: TLabel;
lblDep5: TLabel;
Label38: TLabel;
cmbPayType5: TSuperComboADO;
EditAuto5: TEdit;
EditDep5: TDateBox;
EditValue5: TEdit;
quPaymentValue: TADOQuery;
quPaymentValueTotal: TFloatField;
cbxCloseLayaway: TCheckBox;
Image4: TImage;
Image5: TImage;
pnlLayway: TPanel;
lblPayment: TLabel;
lblLayaway: TLabel;
lbMenus: TLabel;
Shape1: TShape;
lbIqual: TLabel;
lbBalance: TLabel;
edPayment: TEdit;
edLayaway: TEdit;
edtBalance: TEdit;
spHelp: TSpeedButton;
btOK: TButton;
btCancel: TButton;
spPayCheck: TSpeedButton;
lbPartialInfo: TLabel;
btnPartialPayment: TSpeedButton;
lbPartialInfo2: TLabel;
btnPartialPayment2: TSpeedButton;
spPreSaleDeleteDelayPayment: TADOStoredProc;
procedure btOKClick(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure spPayCashClick(Sender: TObject);
procedure spPayVisaClick(Sender: TObject);
procedure cmbPaymentTypeSelectItem(Sender: TObject);
procedure spDep30Click(Sender: TObject);
procedure spPayMasterClick(Sender: TObject);
procedure spPayAmericanClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EditReceivedChange(Sender: TObject);
procedure SelecionaParcela(Sender: TObject);
procedure cmbPayType1SelectItem(Sender: TObject);
procedure cmbPayType2SelectItem(Sender: TObject);
procedure cmbPayType3SelectItem(Sender: TObject);
procedure cmbPayType4SelectItem(Sender: TObject);
procedure cmbPayType5SelectItem(Sender: TObject);
procedure pgReceiveChange(Sender: TObject);
procedure RecalcTotals(Sender : TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure EditReceivedExit(Sender: TObject);
procedure edPaymentChange(Sender: TObject);
procedure edPaymentExit(Sender: TObject);
procedure spHelpClick(Sender: TObject);
procedure edPaymentKeyPress(Sender: TObject; var Key: Char);
procedure EditValue1KeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure spPayCheckClick(Sender: TObject);
procedure btnPartialPaymentClick(Sender: TObject);
procedure btnPartialPayment2Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
MyIDPreSale,
MyIDCliente,
IDInvoice : Integer;
sRefound,
sTotalRef,
sReceive,
sTotalRec,
sSetDateTo : String;
MyTotInvoice,
TotParcela,
MyLayaway,
MyTotCash,
MyPayment : Currency;
MyquPreSaleInfo : TADOQuery;
MyquPreSaleItem : TADOStoredProc;
MyquPreSaleValue : TADOStoredProc;
MyPaymentTypeID,
MyOtherComID,
MyIDTouristGroup : Integer;
MyDepositDate,
MyPreSaleDate : TDateTime;
MyIsLayaway : Boolean;
IsLayawayToClose : Boolean;
MyIDCashRegMov : Integer;
OldTag : Integer;
nParcela : Integer;
IsOnRecalc : Boolean;
iSolicitacaoTEF : Integer;
FrmPayPartial : TFrmPayPartial;
procedure PushError(ErrorType: Integer; sError: String);
function ValidSinglePaymentType : Boolean;
function ValidateMultiple(IsSaving : Boolean) : Boolean;
function AddPayment:Boolean;
function DoPay:Boolean;
function PrintDocument:Boolean;
procedure StartSingle;
procedure StartMultiple;
procedure PaintPanel(PanelTag : Integer; Color : Integer);
procedure AtuDepositState(PaymentTypeID : Integer);
procedure CreateParams( var Params: TCreateParams ); override;
procedure PreencherCheck(PagTipo:String);
procedure CancelPreDatar;
function GetPayment:Double;
function DeletePayment: Boolean;
public
{ Public declarations }
function Start(quPreSaleInfo: TADOQuery;
quPreSaleValue: TADOStoredProc;
quPreSaleItem: TADOStoredProc;
IDCashRegMov: integer;
IsLayaway: Boolean): Boolean;
end;
implementation
uses uDM, xBase, uPassword, uPrintReceipt, uMsgBox, uMsgConstant, uHandleError,
uNumericFunctions, uDateTimeFunctions, uCharFunctions, uDMGlobal,
uSystemConst, EFiscal, uImpCheq, uFisPersistence;
{$R *.DFM}
procedure TFrmPaiPreSaleReceive.CancelPreDatar;
begin
If FrmPayPartial <> nil then
FrmPayPartial.ClearPaymentList;
lbPartialInfo.Caption := '';
lbPartialInfo2.Caption := '';
end;
procedure TFrmPaiPreSaleReceive.PushError(ErrorType: Integer; sError: String);
begin
DM.SetError(ErrorType, Self.Name, sError);
end;
procedure TFrmPaiPreSaleReceive.PreencherCheck(PagTipo:String);
var
BankCode : String;
begin
if not (MyStrToInt(cmbPaymentType.LookUpValue) = PAY_TYPE_CHECK) then
Exit;
DM.IsCheck(PagTipo, BankCode);
//MyquPreSaleInfo.FieldByName('FirstName').AsString;
//MyquPreSaleInfo.FieldByName('LastName').AsString;
if not DM.fPrintReceipt.PrintCheck then
Exit;
with TFrmImpCheq.Create(self) do
begin
Start(CHECK_VENDA);
free;
end;
end;
function TFrmPaiPreSaleReceive.GetPayment:Double;
begin
if MyIsLayaway then
Result := MyPayment
else
Result := MyTotInvoice;
end;
function TFrmPaiPreSaleReceive.DoPay:Boolean;
var
cCash : Currency;
begin
Try
cCash := 0;
if pnlShowCash.Visible then
cCash := MyStrToMoney(EditReceived.Text);
DM.fPOS.PreSalePay(MyIDPreSale,
MyIDTouristGroup,
MyOtherComID,
MyIDCashRegMov,
DM.fStore.ID,
Now,
EditReceiveDate.Date,
cCash,
IDInvoice);
Result := True;
Except
on E: Exception do
begin
PushError(CRITICAL_ERROR, 'PreSaleReceive.DoPay.Exception' + #13#10 + E.Message);
Result := False;
end;
end;
end;
function TFrmPaiPreSaleReceive.PrintDocument:Boolean;
var
iPrinType : Integer;
begin
try
if MyIsLayaway then
iPrinType := RECEIPT_TYPE_LAYAWAY_RECEIVE
else
iPrinType := RECEIPT_TYPE_HOLD;
if (DM.fPrintReceipt.PrintReceipt) then
with TPrintReceipt.Create(Self) do
Start(MyIDPreSale, iPrinType);
Result := True;
Except
on E: Exception do
begin
PushError(CRITICAL_ERROR, 'PreSaleReceive.PrintDocument.Exception' + #13#10 + E.Message);
Result := False;
end;
end;
end;
function TFrmPaiPreSaleReceive.AddPayment:Boolean;
function GetAuthorization(sAuthorization: String): String;
begin
if sAuthorization = '' Then
Result := Trim(EditAuthorization.Text)
else
Result := sAuthorization;
end;
var
Authorization : String;
sValue : String;
ExprireDate : TDateTime;
i : Integer;
begin
Authorization := '';
DM.OpenCashRegister;
try
Result := True;
btOK.Enabled := False;
btCancel.Enabled := False;
if MyStrToInt(cmbPaymentType.LookUpValue) = 1 then
ExprireDate := Int(EditReceiveDate.Date)
else
ExprireDate := Int(EditDepositDate.Date);
if pnlShowAuthorization.Visible then
Authorization := EditAuthorization.Text;
// Grava nova parcela
if pgReceive.ActivePage = tbSingle then
begin
//Adicionar pagamento pre-datados caso tenha
If (FrmPayPartial <> nil) and FrmPayPartial.HasDeposit then
begin
for i := 0 to FrmPayPartial.tvPartialPay.Items.Count-1 do
begin
DM.fPOS.AddPayment(MyIDPreSale,
DM.fStore.ID,
DM.fUser.ID,
MyIDCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).IDPaymentType,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).IDCashRegMov,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).PreSaleDate,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).ExpireDate,
IntToStr(i+1)+'/'+IntToStr(FrmPayPartial.tvPartialPay.Items.Count),
GetAuthorization(TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).Authorization),
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).Valor,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).NumeroDoc,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).DocCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).NomeCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).Telefone,
MyStrToInt(TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).Banco),
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).OBS,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).PaymentPlace,
True);
end;
end
else
DM.fPOS.AddPayment(MyIDPreSale,
DM.fStore.ID,
DM.fUser.ID,
MyIDCliente,
MyStrToInt(cmbPaymentType.LookUpValue),
MyIDCashRegMov,
EditReceiveDate.Date,
ExprireDate,
'1/1',
Authorization,
GetPayment,
'', '', '', '', 0, '',
0,
False);
end
else
begin
// Usa o validate para incluir
Result := ValidateMultiple(True);
end;
except
on E: Exception do
begin
PushError(CRITICAL_ERROR, 'PreSaleReceive.AddPayment.Exception' + #13#10 + E.Message);
Result := False;
end;
end;
end;
procedure TFrmPaiPreSaleReceive.CreateParams( var Params: TCreateParams );
begin
inherited CreateParams( Params );
Params.Style := WS_THICKFRAME or WS_POPUP;
end;
function TFrmPaiPreSaleReceive.Start( quPreSaleInfo: TADOQuery;
quPreSaleValue: TADOStoredProc;
quPreSaleItem: TADOStoredProc;
IDCashRegMov: integer;
IsLayaway: Boolean): Boolean;
begin
MyIDCashRegMov := IDCashRegMov;
MyIDPreSale := quPreSaleInfo.FieldByName('IDPreSale').AsInteger;
MyIDCliente := quPreSaleInfo.FieldByName('IDCustomer').AsInteger;
MyTotInvoice := quPreSaleValue.FieldByName('TotalInvoice').AsFloat;
MyPaymentTypeID := quPreSaleInfo.FieldByName('IDMeioPag').AsInteger;
MyDepositDate := quPreSaleInfo.FieldByName('DepositDate').AsDateTime;
MyPreSaleDate := quPreSaleInfo.FieldByName('PreSaleDate').AsDateTime;
MyOtherComID := quPreSaleInfo.FieldByName('OtherComissionID').AsInteger;
MyIDTouristGroup := quPreSaleInfo.FieldByName('IDTouristGroup').AsInteger;
MyquPreSaleInfo := quPreSaleInfo;
MyquPreSaleValue := quPreSaleValue;
MyquPreSaleItem := quPreSaleItem;
MyIsLayaway := IsLayaway;
EditReceiveDate.Date := Now;
tbMultiple.TabVisible := not MyIsLayaway;
cbxCloseLayaway.Checked := True;
cbxCloseLayaway.Visible := False;
if MyIsLayaway then
begin
// Mostros os campos do Layaway
lblPayment.Visible := True;
edPayment.Visible := True;
lblLayaway.Visible := True;
edPayment.Visible := True;
edLayaway.Visible := True;
lbMenus.Visible := True;
lbIqual.Visible := True;
lbBalance.Visible := True;
edtBalance.Visible := True;
// Calculo o total de layaway
with quPaymentValue do
begin
Close;
Parameters.ParambyName('IDPreSale').Value := MyIDPreSale;
Open;
MyLayaway := quPaymentValueTotal.AsFloat;
Close;
end;
// Sugiro o valor restante a pagar
MyPayment := MyTotInvoice - MyLayaway;
edLayaway.text := FloatToStrF(MyLayaway, ffCurrency, 20, 2);
edtBalance.text := FloatToStrF(MyPayment, ffCurrency, 20, 2);
IsLayawayToClose := MyPayment=0;
//Verifico se e para fechar o Layaway
if IsLayawayToClose then
begin
pnlPaymentType.Visible := False;
pnlShowCash.Visible := False;
lblPayment.Visible := False;
edPayment.Visible := False;
lbIqual.Visible := False;
cbxCloseLayaway.Visible := True;
cbxCloseLayaway.Enabled := False;
end
else
begin
cbxCloseLayaway.Visible := False;
edPayment.Clear;
end;
end
else
begin
// Sumo com os campos do layaway
lblPayment.Visible := False;
edPayment.Visible := False;
lblLayaway.Visible := False;
edPayment.Visible := False;
edLayaway.Visible := False;
lbMenus.Visible := False;
lbIqual.Visible := False;
lbBalance.Visible := False;
edtBalance.Visible := False;
end;
// Numero de Parcelas
nParcela := 1;
Left := 0;
Top := 102;
Height := Screen.Height - Top;
Result := (ShowModal = mrOK );
end;
procedure TFrmPaiPreSaleReceive.btOKClick(Sender: TObject);
var
bCanExec : Boolean;
AC : Char;
IniFech, CodFiscal : String;
InvoiceDiscount,
TotalReceived : Currency;
begin
// Faz todas as validaçoes aqui e depois chama a rotina correta
if not IsLayawayToClose then
begin
if pgReceive.ActivePage = tbSingle then
begin
if not ValidSinglePaymentType then
Exit;
//Verify the payment Type in Check
PreencherCheck(cmbPaymentType.LookUpValue);
if pnlShowAuthorization.Visible and (EditAuthorization.Text = '') then
begin
EditAuthorization.SetFocus;
MsgBox(MSG_CRT_NO_AUTHORIZANUMBER, vbOKOnly + vbCritical);
Exit;
end;
end
else
begin
// Valida o recebimento Multiple
if not ValidateMultiple(False) then
Exit;
end;
if not TestDate(EditReceiveDate.Text) then
begin
MsgBox(MSG_CRT_INVAL_DATE_RECEIVE, vbCritical + vbOkOnly);
EditReceiveDate.SetFocus;
Exit;
end;
// Testa o troco dado
// Teste se Received > Total PreSale
if MyIsLayaway then
begin
if (spPayCash.Down and (MyRound(MyPayment-MyStrToMoney(EditReceived.Text), 2)>0)) then
begin
EditReceived.SetFocus;
MsgBox(MSG_INF_TOTAL_SMALLER_PRE_SALE, vbOKOnly + vbInformation);
Exit;
end;
//Payment cannot be zero
if MyPayment = 0 then
begin
MsgBox(MSG_CRT_NO_PAYMENT_ZERO, vbCritical + vbOkOnly);
edPayment.SetFocus;
exit;
end;
//Invalid Payment
if MyPayment > (MyTotInvoice - MyLayaway) then
begin
MsgBox(MSG_CRT_NO_VALID_AMOUNT, vbCritical + vbOkOnly);
edPayment.SetFocus;
Exit;
end;
end
else
begin
if ((MyTotCash > 0) and (MyRound(MyTotCash-MyStrToMoney(EditReceived.Text), 2)>0)) then
begin
EditReceived.SetFocus;
MsgBox(MSG_INF_TOTAL_SMALLER_PRE_SALE, vbOKOnly + vbInformation);
Exit;
end;
end;
end;
//Impressora fiscal
if DM.fCashRegister.Fiscal then
begin
if DM.fModuloFiscal.InvoiceDiscount then
InvoiceDiscount := MyquPreSaleValue.FieldByName('ItemDiscount').AsCurrency
else
InvoiceDiscount := 0;
if InvoiceDiscount < 0 then
AC := 'A'
else
AC := 'D';
if MyStrToInt(cmbPaymentType.LookUpValue) = PAY_TYPE_CASH then
TotalReceived := MyStrToMoney(EditReceived.Text)
else
TotalReceived := MyTotInvoice;
if cmbPaymentType.LookUpValue = '' then
CodFiscal := ''
else
CodFiscal := DM.DescCodigo(['IDMeioPag'], [cmbPaymentType.LookUpValue], 'MeioPag', 'CodFiscal');
{pagamento em cinco(5) formas <> para recebimento}
IniFech := FISCAL_FECHA_NOTA_ACRES_DESC + AC + ';' +
FISCAL_FECHA_NOTA_TIPO_ACRES_DESC + '$;' +
FISCAL_FECHA_NOTA_VALOR_ACRES_DESC + MyFormatCur(Abs(InvoiceDiscount),DM.fModuloFiscal.Decimal)+';'+
FISCAL_FECHA_NOTA_TIPO_PAGAMENTO + cmbPaymentType.Text + ';' +
FISCAL_FECHA_NOTA_MSG + MyquPreSaleInfo.FieldByName('Note').AsString + ';' +
FISCAL_FECHA_NOTA_VALOR_PAGO + MyFormatCur(TotalReceived,DM.fModuloFiscal.Decimal) +';'+
FISCAL_ITEM_PONTO_DEC + DM.fModuloFiscal.Decimal+';' +
FISCAL_FECHA_NOTA_IDX_PAGAMENTO + CodFiscal+';';
with DM.EFiscal1 do
begin
if pgReceive.ActivePage = tbSingle then
begin
bCanExec := FechaCupomFiscal(IniFech);
end
else if pgReceive.ActivePage = tbMultiple then
begin
bCanExec := IniFechCupfisc(IniFech);
{if bCanExec then
bCanExec := FechaCupomFiscal(IniFech);}
if cmbPayType1.Text<>'' then
begin
CodFiscal := DM.DescCodigo(['IDMeioPag'], [cmbPayType1.LookUpValue], 'MeioPag', 'CodFiscal');
EfetuaFormaPagamento(cmbPayType1.Text, StrToCurr(EditValue1.Text), CodFiscal);
PreencherCheck(cmbPaymentType.LookUpValue);
if cmbPayType2.Text<>'' then
begin
CodFiscal := DM.DescCodigo(['IDMeioPag'], [cmbPayType2.LookUpValue], 'MeioPag', 'CodFiscal');
EfetuaFormaPagamento(cmbPayType2.Text, StrToCurr(EditValue2.Text), CodFiscal);
PreencherCheck(cmbPaymentType.LookUpValue);
if cmbPayType3.Text<>'' then
begin
CodFiscal := DM.DescCodigo(['IDMeioPag'], [cmbPayType3.LookUpValue], 'MeioPag', 'CodFiscal');
EfetuaFormaPagamento(cmbPayType3.Text, StrToCurr(EditValue3.Text), CodFiscal);
PreencherCheck(cmbPaymentType.LookUpValue);
if cmbPayType4.Text<>'' then
begin
CodFiscal := DM.DescCodigo(['IDMeioPag'], [cmbPayType4.LookUpValue], 'MeioPag', 'CodFiscal');
EfetuaFormaPagamento(cmbPayType4.Text, StrToCurr(EditValue4.Text), CodFiscal);
PreencherCheck(cmbPaymentType.LookUpValue);
if cmbPayType5.Text<>'' then
begin
CodFiscal := DM.DescCodigo(['IDMeioPag'], [cmbPayType5.LookUpValue], 'MeioPag', 'CodFiscal');
EfetuaFormaPagamento(cmbPayType5.Text, StrToCurr(EditValue5.Text), CodFiscal);
PreencherCheck(cmbPaymentType.LookUpValue);
end;
end;
end;
end;
end;
if bCanExec then
bCanExec := TermFechCupFisc(MyquPreSaleInfo.FieldByName('Note').AsString);
end;
end; //end With
if not bCanExec then
Exit;
end; //end IF Fiscal
try
bCanExec := True;
DM.ADODBConnect.BeginTrans;
if not (MyIsLayaway) or (MyIsLayaway and (MyPayment <> 0)) then
begin
If MyIsLayaway Then
bCanexec := DeletePayment;
if bCanexec then
bCanExec := AddPayment;
end;
//Close Payment
if bCanExec then
if not (MyIsLayaway) or ((MyRound(MyTotInvoice-(MyPayment + MyLayaway),2)=0) and (cbxCloseLayaway.Checked)) then
bCanExec := DoPay;
if DM.fCashRegister.Fiscal Then
begin
//Tipo60
if bCanExec and AddTipo60ResumoDiario(Self, IDInvoice) then
AddTipo60ResumoItem(Self, IDInvoice, DM.fPOS.InvoiceItem);
end;
Finally
if bCanExec then
begin
DM.ADODBConnect.CommitTrans;
//Imprime o pagamento
bCanExec := PrintDocument;
if not bCanExec then
MsgBox(MSG_CRT_ERROR_PRINT, vbCritical + vbOkOnly);
btCancel.Enabled := True;
btOK.Enabled := True;
ModalResult := mrOK;
end
else
begin
DM.ADODBConnect.RollbackTrans;
btCancel.Enabled := True;
btOK.Enabled := True;
MsgBox(MSG_INF_NOT_RECEIVE_HOLD, vbInformation + vbOkOnly);
ModalResult := mrNone;
end;
end;
if DM.fCashRegister.Open then
DM.EFiscal1.AbreGaveta;
end;
procedure TFrmPaiPreSaleReceive.btCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
CancelPreDatar;
end;
procedure TFrmPaiPreSaleReceive.FormShow(Sender: TObject);
begin
WindowState := wsNormal;
// Seta Panel so do Cash
// pnlShowCash.Visible := False;
pnlShowCash.Visible := not IsLayawayToClose;
// Carrega valores iniciais do pagamento
EditTotalInvoice.Text := FloatToStrF(MyTotInvoice, ffCurrency, 20, 2);
lblMinus.Visible := MyTotInvoice > 0;
EditChange.Visible := lblMinus.Visible;
lblEqual.Visible := lblMinus.Visible;
lblChange.Visible := lblMinus.Visible;
spLine.Visible := lblMinus.Visible;
if MyTotInvoice < 0 then
begin
btOk.Caption := sRefound;
lblCashTotal.Caption := sTotalRef;
end
else
begin
lblCashTotal.Caption := sTotalRec;
btOk.Caption := sReceive;
end;
StartSingle;
end;
procedure TFrmPaiPreSaleReceive.spPayCashClick(Sender: TObject);
begin
cmbPaymentType.LookUpValue := IntToStr(PAY_TYPE_CASH);
cmbPaymentTypeSelectItem(nil);
if MyIsLayaway then
edPayment.SetFocus
else
begin
if not pnlShowCash.Visible then
pnlShowCash.Visible := True;
EditReceived.SetFocus;
end;
end;
procedure TFrmPaiPreSaleReceive.spPayVisaClick(Sender: TObject);
begin
cmbPaymentType.LookUpValue := IntToStr(PAY_TYPE_VISA);
cmbPaymentTypeSelectItem(nil);
end;
procedure TFrmPaiPreSaleReceive.cmbPaymentTypeSelectItem(Sender: TObject);
begin
MyTotCash := 0;
case MyStrToInt(cmbPaymentType.LookUpValue) of
PAY_TYPE_CASH : begin
spPayCash.Down := True;
MyTotCash := MyTotInvoice;
if MyIsLayaway then
EditTotalCash.Text := FloatToStrF(MyPayment, ffCurrency, 20, 2)
else
EditTotalCash.Text := FloatToStrF(MyTotCash, ffCurrency, 20, 2);
end;
PAY_TYPE_VISA : spPayVisa.Down := True;
PAY_TYPE_AMERICAN : spPayAmerican.Down := True;
PAY_TYPE_MASTER : spPayMaster.Down := True;
PAY_TYPE_CHECK : spPayCheck.Down := True;
else
begin
// nao seleciona
spPayCash.Down := False;
spPayVisa.Down := False;
spPayAmerican.Down := False;
spPayMaster.Down := False;
spPayCheck.Down := False;
end;
end;
// Atualiza estado do Deposit Date
AtuDepositState(MyStrToInt(cmbPaymentType.LookUpValue));
if (MyStrToInt(cmbPaymentType.LookUpValue) > 0) and not ValidSinglePaymentType then
Exit;
if MyStrToInt(cmbPaymentType.LookUpValue) > 1 then
begin
pnlShowAuthorization.Visible := True;
EditAuthorization.Text := '';
EditAuthorization.SetFocus;
end
else
pnlShowAuthorization.Visible := False;
// Mostra o panel de Cash se pagamento for do tipo cash
pnlShowCash.Visible := (MyTotCash > 0);
if pnlShowCash.Visible then
EditReceived.SetFocus;
//Cancela Pre-Datado se trocar de tipo de pago
CancelPreDatar;
end;
procedure TFrmPaiPreSaleReceive.spDep30Click(Sender: TObject);
begin
EditDepositDate.Text := DateToStr(Int(EditReceiveDate.Date) +
MyStrToInt(RightStr(TSpeedButton(Sender).Caption, 1)));
end;
procedure TFrmPaiPreSaleReceive.spPayMasterClick(Sender: TObject);
begin
cmbPaymentType.LookUpValue := IntToStr(PAY_TYPE_MASTER);
cmbPaymentTypeSelectItem(nil);
end;
procedure TFrmPaiPreSaleReceive.spPayAmericanClick(Sender: TObject);
begin
cmbPaymentType.LookUpValue := IntToStr(PAY_TYPE_AMERICAN);
cmbPaymentTypeSelectItem(nil);
end;
procedure TFrmPaiPreSaleReceive.AtuDepositState(PaymentTypeID : Integer);
begin
// Desabilita tudo
spDep30.Down := False;
spDep60.Down := False;
spDep90.Down := False;
spDep30.Visible := False;
spDep60.Visible := False;
spDep90.Visible := False;
lblPreDate.Visible := False;
with spquPayTypeMin do
begin
if Active then Close;
Parameters.ParambyName('@IDMeioPag').Value := PaymentTypeID;
Open;
First;
while not Eof do
begin
if (spquPayTypeMinDifDay.AsInteger > 0) and
(MyTotInvoice >= spquPayTypeMinTotalSale.AsFloat) then
begin
if not spDep30.Visible then
begin
spDep30.Caption := '+&' + Trim(spquPayTypeMinDifDay.AsString);
spDep30.Hint := sSetDateTo + DateToStr(Int(EditReceiveDate.Date) + spquPayTypeMinDifDay.AsInteger);
spDep30.Visible := True;
end
else if not spDep60.Visible then
begin
spDep60.Caption := '+&' + Trim(spquPayTypeMinDifDay.AsString);
spDep60.Hint := sSetDateTo + DateToStr(Int(EditReceiveDate.Date) + spquPayTypeMinDifDay.AsInteger);
spDep60.Visible := True;
end
else if not spDep90.Visible then
begin
spDep90.Caption := '+&' + Trim(spquPayTypeMinDifDay.AsString);
spDep90.Hint := sSetDateTo + DateToStr(Int(EditReceiveDate.Date) + spquPayTypeMinDifDay.AsInteger);
spDep90.Visible := True;
end;
end;
Next;
end;
Close;
// testa se mostra o panel de deposit date
pnlDepositDate.Visible := spDep30.Visible;
lblPreDate.Visible := (not spDep30.Visible) and (not Password.HasFuncRight(17));
if lblPreDate.Visible then
begin
EditDepositDate.Color := clSilver;
EditDepositDate.ReadOnly := True;
end
else
begin
EditDepositDate.Color := clWhite;
EditDepositDate.ReadOnly := False;
end;
end;
end;
procedure TFrmPaiPreSaleReceive.PaintPanel(PanelTag : Integer; Color : Integer);
begin
case PanelTag of
1 : pnlPayTitle.Color := Color;
2 : pnlDateTitle.Color := Color;
end;
end;
procedure TFrmPaiPreSaleReceive.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmPaiPreSaleReceive.EditReceivedChange(Sender: TObject);
var
Code : Integer;
Value : Real;
begin
// Muda o change automatico
if Trim(EditReceived.Text) = '' then
EditChange.Text := FloatToStrF(0, ffCurrency, 20, 2);
Val(EditReceived.Text, Value, Code);
if Code = 0 then
if MyIsLayaway then
EditChange.Text := FloatToStrF(Value-MyPayment, ffCurrency, 20, 2)
else
EditChange.Text := FloatToStrF(Value-MyTotCash, ffCurrency, 20, 2);
end;
procedure TFrmPaiPreSaleReceive.SelecionaParcela(Sender: TObject);
var
i, j : integer;
MyPanel : TPanel;
begin
// Numero de Parcelas
nParcela := TSpeedButton(Sender).Tag;
// Seleciona as parcelas que vao aparecer
with pnlMultiParcela do
begin
for i := 0 to (ControlCount - 1) do
begin
if not (Controls[i] is TPanel) then Continue;
// Mostra as parcelas dependendo do numero selecionado
Controls[i].Visible := (Controls[i].Tag <= TSpeedButton(Sender).Tag);
// Apaga todos os valores dos campos
MyPanel := TPanel(Controls[i]);
try
IsOnRecalc := True;
for j := 0 to (MyPanel.ControlCount - 1) do
begin
if MyPanel.Controls[j] is TSuperComboADO then
begin
TSuperComboADO(MyPanel.Controls[j]).LookUpValue := '';
TSuperComboADO(MyPanel.Controls[j]).OnSelectItem(MyPanel.Controls[j]);
end
else if MyPanel.Controls[j] is TEdit then
TEdit(MyPanel.Controls[j]).Text := ''
else if MyPanel.Controls[j] is TDateBox then
TDateBox(MyPanel.Controls[j]).Date := Int(EditReceiveDate.Date);
end;
finally
IsOnRecalc := False;
end;
end;
end;
RecalcTotals(nil);
end;
procedure TFrmPaiPreSaleReceive.cmbPayType1SelectItem(Sender: TObject);
begin
lblAuto1.Visible := (MyStrToInt(cmbPayType1.LookUpValue) > 1);
EditAuto1.Visible := lblAuto1.Visible;
EditDep1.Visible := lblAuto1.Visible;
lblDep1.Visible := EditDep1.Visible;
RecalcTotals(EditValue1);
btnPartialPayment2.Visible := lblAuto1.Visible;
//Cancela Pre-Datado se trocar de tipo de pago
CancelPreDatar;
end;
procedure TFrmPaiPreSaleReceive.cmbPayType2SelectItem(Sender: TObject);
begin
lblAuto2.Visible := (MyStrToInt(cmbPayType2.LookUpValue) > 1);
EditAuto2.Visible := lblAuto2.Visible;
EditDep2.Visible := lblAuto2.Visible;
lblDep2.Visible := EditDep2.Visible;
RecalcTotals(EditValue2);
end;
procedure TFrmPaiPreSaleReceive.cmbPayType3SelectItem(Sender: TObject);
begin
lblAuto3.Visible := (MyStrToInt(cmbPayType3.LookUpValue) > 1);
EditAuto3.Visible := lblAuto3.Visible;
EditDep3.Visible := lblAuto3.Visible;
lblDep3.Visible := EditDep3.Visible;
RecalcTotals(EditValue3);
end;
procedure TFrmPaiPreSaleReceive.cmbPayType4SelectItem(Sender: TObject);
begin
lblAuto4.Visible := (MyStrToInt(cmbPayType4.LookUpValue) > 1);
EditAuto4.Visible := lblAuto4.Visible;
EditDep4.Visible := lblAuto4.Visible;
lblDep4.Visible := EditDep4.Visible;
RecalcTotals(EditValue4);
end;
procedure TFrmPaiPreSaleReceive.cmbPayType5SelectItem(Sender: TObject);
begin
lblAuto5.Visible := (MyStrToInt(cmbPayType5.LookUpValue) > 1);
EditAuto5.Visible := lblAuto5.Visible;
EditDep5.Visible := lblAuto5.Visible;
lblDep5.Visible := EditDep5.Visible;
RecalcTotals(EditValue5);
end;
procedure TFrmPaiPreSaleReceive.pgReceiveChange(Sender: TObject);
begin
// Ajusta qual modo vai aparecer
case pgReceive.ActivePage.TabIndex of
0 : StartSingle;
1 : StartMultiple;
end;
//Cancela Pre-Datado se trocar de tipo de pago
CancelPreDatar;
end;
procedure TFrmPaiPreSaleReceive.StartSingle;
begin
pgReceive.ActivePage := tbSingle;
spDep30.Down := False;
spDep60.Down := False;
spDep90.Down := False;
cmbPaymentType.LookUpValue := '';
cmbPaymentTypeSelectItem(nil);
EditDepositDate.Date := Int(EditReceiveDate.Date);
// Testa se vendedor fez algum Deposit Date pre setado
if ( MyPaymentTypeID > 0 ) then
begin
// Seleciona a forma de pagamento escolhida pelo vendedor
cmbPaymentType.LookUpValue := IntToStr(MyPaymentTypeID);
cmbPaymentTypeSelectItem(nil);
EditDepositDate.Date := MyDepositDate;
MsgBox(MSG_INF_INVOICE_HAS_SETUP, vbOKOnly + vbInformation);
end;
if not IsLayawayToClose then
cmbPaymentType.SetFocus;
end;
procedure TFrmPaiPreSaleReceive.StartMultiple;
begin
pgReceive.ActivePage := tbMultiple;
IsOnRecalc := False;
pnlShowCash.Visible := False;
btMulti2.Down := True;
SelecionaParcela(btMulti2);
end;
procedure TFrmPaiPreSaleReceive.RecalcTotals(Sender : TObject);
var
SubTotal : Double;
MyEditValue : TEdit;
MycmbPayType : TSuperComboADO;
i : integer;
begin
// Recalcula os totais para que sempre sobre a divisao do numero de parcelas
if IsOnRecalc then Exit;
MyTotCash := 0;
SubTotal := 0;
// Desabilita o Loop do change to text do controle
IsOnRecalc := True;
with pnlMultiParcela do
begin
for i := 0 to (ControlCount - 1) do
begin
if not (Controls[i] is TPanel) then Continue;
if not Controls[i].Visible then Continue;
MyEditValue := TEdit(Self.FindComponent('EditValue' + Trim(IntToStr(Controls[i].Tag))));
MycmbPayType := TSuperComboADO(Self.FindComponent('cmbPayType' + Trim(IntToStr(Controls[i].Tag))));
if Sender = nil then
begin
// Entra quando for todas as parcelas
MyEditValue.Text := MyFloatToStr(MyRound(MyTotInvoice/nParcela, 2));
end
else
begin
// Entra quando estiver editando um field
if Controls[i].Tag > TSpeedButton(Sender).Tag then
begin
// Calcula dividido pelo resto dos outros campos
MyEditValue.Text := MyFloatToStr(MyRound((MyTotInvoice-SubTotal)/(nParcela-TSpeedButton(Sender).Tag), 2));
if MyStrToInt(MycmbPayType.LookUpValue) = 1 then
MyTotCash := MyTotCash + MyStrToMoney(MyEditValue.Text);
end
else
begin
SubTotal := SubTotal + MyStrToMoney(MyEditValue.Text);
if MyStrToInt(MycmbPayType.LookUpValue) = 1 then
MyTotCash := MyTotCash + MyStrToMoney(MyEditValue.Text);
end;
end;
end;
end;
if (MyTotCash > 0) then
begin
pnlShowCash.Visible := True;
EditTotalCash.Text := FloatToStrF(MyTotCash, ffCurrency, 20, 2);
EditReceived.Text := FormatFloat('###0.00', MyTotCash);
EditChange.Text := FloatToStrF(0, ffCurrency, 20, 2);
end
else
pnlShowCash.Visible := False;
IsOnRecalc := False;
end;
procedure TFrmPaiPreSaleReceive.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Shift = [ssAlt] then
begin
if UpperCase(Chr(Key)) = 'S' then
StartSingle
else if UpperCase(Chr(Key)) = 'M' then
StartMultiple;
end;
end;
function TFrmPaiPreSaleReceive.ValidateMultiple(IsSaving : Boolean) : Boolean;
function GetAuthorization(sAuthorization: String): String;
begin
if sAuthorization = '' Then
Result := Trim(EditAuto1.Text)
else
Result := sAuthorization;
end;
var
MyEditValue : TEdit;
MycmbPayType : TSuperComboADO;
MyEditAuto : TEdit;
MyEditDep : TDateBox;
i,j : integer;
Authorization : String;
ExprireDate : TDateTime;
begin
// Valida multiplas parcelas
Result := False;
Authorization := '';
with pnlMultiParcela do
begin
for i := 0 to (ControlCount - 1) do
begin
if not (Controls[i] is TPanel) then Continue;
if not Controls[i].Visible then Continue;
MyEditValue := TEdit(Self.FindComponent('EditValue' + Trim(IntToStr(Controls[i].Tag))));
MycmbPayType := TSuperComboADO(Self.FindComponent('cmbPayType' + Trim(IntToStr(Controls[i].Tag))));
MyEditAuto := TEdit(Self.FindComponent('EditAuto' + Trim(IntToStr(Controls[i].Tag))));
MyEditDep := TDateBox(Self.FindComponent('EditDep' + Trim(IntToStr(Controls[i].Tag))));
if IsSaving then
begin
if MyStrToInt(cmbPaymentType.LookUpValue) = 1 then
ExprireDate := EditReceiveDate.Date
else
ExprireDate := MyEditDep.Date;
if MyEditAuto.Visible then
Authorization := MyEditAuto.Text;
If (FrmPayPartial <> nil) and FrmPayPartial.HasDeposit then
begin
for j := 0 to FrmPayPartial.tvPartialPay.Items.Count-1 do
begin
DM.fPOS.AddPayment(MyIDPreSale,
DM.fStore.ID,
DM.fUser.ID,
MyIDCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).IDPaymentType,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).IDCashRegMov,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).PreSaleDate,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).ExpireDate,
IntToStr(i+1)+'/'+IntToStr(ControlCount-3) + ' - ' +IntToStr(j+1)+'/'+IntToStr(FrmPayPartial.tvPartialPay.Items.Count),
GetAuthorization(TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).Authorization),
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).Valor,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).NumeroDoc,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).DocCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).NomeCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).Telefone,
MyStrToInt(TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).Banco),
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).OBS,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).PaymentPlace,
True);
end;
//Depois que efetuar o Pre-Datado tenho que limpar os valores
CancelPreDatar;
end
else
begin
DM.fPOS.AddPayment(MyIDPreSale,
DM.fStore.ID,
DM.fUser.ID,
MyIDCliente,
MyStrToInt(MycmbPayType.LookUpValue),
MyIDCashRegMov,
EditReceiveDate.Date,
ExprireDate,
IntToStr(i+1)+'/'+IntToStr(ControlCount-3),
Authorization,
MyStrToMoney(MyEditValue.Text),
'', '', '', '', 0, '',
0, False);
end;
Continue; // Passa para o proximo campo
end;
// Testa se authorization e valida
if MycmbPayType.LookUpValue = '' then
begin
MsgBox(MSG_CRT_NO_PAYMENT_TYPE, vbOKOnly + vbInformation);
if MyEditAuto.Visible then
MyEditAuto.SetFocus;
Exit;
end;
// Testa se valor e branco
if MyEditValue.Text = '' then
begin
MsgBox(MSG_CRT_NO_AMOUNT, vbOKOnly + vbInformation);
if MyEditValue.Visible then
MyEditValue.SetFocus;
Exit;
end;
// Testa se authorization e valida
if MyEditAuto.Visible and (MyEditAuto.Text = '') then
begin
MsgBox(MSG_CRT_NO_AUTHORIZANUMBER, vbOKOnly + vbInformation);
if MyEditAuto.Visible then
MyEditAuto.SetFocus;
Exit;
end;
// Teste de Invoice com Special Price com Payment Type diferente de Cash
if (MyquPreSaleInfo.FieldByName('MediaID').AsInteger = MEDIA_TYPE_GUIDE) and
MyquPreSaleValue.FieldByName('TaxIsent').AsBoolean and
(MyStrToInt(MycmbPayType.LookUpValue) <> PAY_TYPE_CASH) then
begin
if Password.HasFuncRight(18) then
begin
if MsgBox(MSG_QST_INVOICE_ONLY_CASH, vbYesNo + vbQuestion) = vbNo then
Exit;
end
else
begin
MycmbPayType.SetFocus;
MsgBox(MSG_INF_INVOICE_REC_ONLY_CASH, vbOKOnly + vbInformation);
Exit;
end;
end;
// teste de data valida
if MyEditDep.visible and not TestDate(MyEditDep.Text) then
begin
if MyEditDep.Visible then
MyEditDep.SetFocus;
MsgBox(MSG_CRT_NO_VALID_DATE, vbOKOnly + vbInformation);
Exit;
end;
// Teste de pre date valido
// testa valor minimo para pagamento em cada tipo
if (MyEditDep.Visible) and (MyTotInvoice > 0) then
with spTestpayType do
begin
Parameters.ParambyName('@IDMeioPag').Value := MyStrToInt(MycmbPayType.LookUpValue);
//#Rod - Round
Parameters.ParambyName('@DifDay').Value := Int(MyEditDep.Date-Int(EditReceiveDate.Date));
Parameters.ParambyName('@Value').Value := MyTotInvoice;
ExecProc;
case Parameters.ParambyName('RETURN_VALUE').Value of
1 : begin
if Password.HasFuncRight(17) then
begin
if MsgBox(MSG_QST_AMOUN_NOT_REACH_MIN, vbYesNo + vbQuestion) = vbNo then
begin
MyEditValue.SetFocus;
Exit;
end;
end
else
begin
MyEditDep.SetFocus;
MsgBox(MSG_INF_INVOICE_NOT_REACH_DATE, vbOKOnly + vbInformation);
Exit;
end;
end;
-1 : begin
if Password.HasFuncRIght(17) then
begin
if MsgBox(MSG_QST_PAYTYPE_NOT_ALLOW_DATE, vbYesNo + vbQuestion) = vbNo then
begin
MyEditValue.SetFocus;
Exit;
end;
end
else
begin
MyEditDep.SetFocus;
MsgBox(MSG_INF_PAYTYPE_NOT_THIS_DATE, vbOKOnly + vbInformation);
Exit;
end;
end;
end;
end;
end;
end;
Result := True;
end;
procedure TFrmPaiPreSaleReceive.EditReceivedExit(Sender: TObject);
begin
EditReceived.Text := FormatFloat('###0.00', MyStrToMoney(EditReceived.Text));
end;
function TFrmPaiPreSaleReceive.ValidSinglePaymentType : Boolean;
begin
Result := False;
// Valida o recebimento single
if cmbPaymentType.LookUpValue = '' then
begin
cmbPaymentType.SetFocus;
MsgBox(MSG_CRT_NO_PAYMENT_TYPE, vbOKOnly + vbCritical);
Exit;
end;
if not TestDate(EditDepositDate.Text) and pnlDepositDate.Visible then
begin
EditDepositdate.SetFocus;
MsgBox(MSG_CRT_NO_VALID_DATE, vbOKOnly + vbCritical);
Exit;
end;
// Teste de Invoice com Special Price com Payment Type diferente de Cash
if (MyquPreSaleInfo.FieldByName('MediaID').AsInteger = MEDIA_TYPE_GUIDE) and
MyquPreSaleValue.FieldByName('TaxIsent').AsBoolean and
(MyStrToInt(cmbPaymentType.LookUpValue) <> PAY_TYPE_CASH) then
begin
if Password.HasFuncRight(18) then
begin
if MsgBox(MSG_QST_INVOICE_ONLY_CASH, vbYesNo + vbQuestion) = vbNo then
Exit;
end
else
begin
cmbPaymentType.SetFocus;
MsgBox(MSG_INF_INVOICE_REC_ONLY_CASH, vbOKOnly + vbInformation);
Exit;
end;
end;
if MyTotInvoice > 0 then
begin
// testa valor minimo para pagamento em cada tipo
with spTestpayType do
begin
Parameters.ParambyName('@IDMeioPag').Value := MyStrToInt(cmbPaymentType.LookUpValue);
Parameters.ParambyName('@DifDay').Value := Int(EditDepositDate.Date-Int(EditReceiveDate.Date));
Parameters.ParambyName('@Value').Value := MyTotInvoice;
ExecProc;
case Parameters.ParambyName('RETURN_VALUE').Value of
1 : begin
if Password.HasFuncRight(17) then
begin
if MsgBox(MSG_QST_AMOUN_NOT_REACH_MIN, vbYesNo + vbQuestion) = vbNo then
Exit;
end
else
begin
if pnlDepositDate.Visible then
EditDepositDate.SetFocus;
MsgBox(MSG_INF_INVOICE_NOT_REACH_DATE, vbOKOnly + vbInformation);
Exit;
end;
end;
-1 : begin
if Password.HasFuncRight(17) then
begin
if MsgBox(MSG_QST_PAYTYPE_NOT_ALLOW_DATE, vbYesNo + vbQuestion) = vbNo then
Exit;
end
else
begin
if pnlDepositDate.Visible then
EditDepositDate.SetFocus;
MsgBox(MSG_INF_PAYTYPE_NOT_THIS_DATE, vbOKOnly + vbInformation);
Exit;
end;
end;
end;
end;
end;
Result := True;
end;
procedure TFrmPaiPreSaleReceive.edPaymentChange(Sender: TObject);
var
Code : Integer;
Value : Real;
cPayment : Currency;
begin
// Muda o change automatico
if Trim(edPayment.Text) = '' then
MyPayment := 0
else
MyPayment := MyStrToMoney(edPayment.Text);
//Val(edPayment.Text, Value, Code);
//if Code = 0 then
// MyPayment := Value;
EditReceived.Text := edPayment.Text;
EditTotalCash.Text := FloatToStrF(MyPayment, ffCurrency, 20, 2);
Try
cPayment := MyStrToCurrency(edPayment.Text);
Except
cPayment := 0
end;
//cbxCloseLayaway.Visible := (MyRound(MyTotInvoice-(MyPayment + MyLayaway),2)=0);
cbxCloseLayaway.Visible := (MyRound(MyTotInvoice-(cPayment + MyLayaway),2)=0);
if cbxCloseLayaway.Visible then
cbxCloseLayaway.Checked := (MsgBox(MSG_QST_CLOSE_LAYAWAY, vbYesNo + vbQuestion) = vbYes);
end;
procedure TFrmPaiPreSaleReceive.edPaymentExit(Sender: TObject);
begin
if cmbPaymentType.Text = '' then
Exit;
edPayment.Text := FormatFloat('###0.00', MyPayment);
if MyPayment = 0 then
begin
MsgBox(MSG_CRT_NO_PAYMENT_ZERO, vbCritical + vbOkOnly);
edPayment.SetFocus;
exit;
end;
if MyPayment > (MyTotInvoice - MyLayaway) then
begin
MsgBox(MSG_CRT_NO_VALID_AMOUNT, vbCritical + vbOkOnly);
edPayment.SetFocus;
Exit;
end;
end;
procedure TFrmPaiPreSaleReceive.spHelpClick(Sender: TObject);
begin
Application.HelpContext(1060);
end;
procedure TFrmPaiPreSaleReceive.edPaymentKeyPress(Sender: TObject;
var Key: Char);
begin
Key := ValidatePositiveCurrency(Key);
end;
procedure TFrmPaiPreSaleReceive.EditValue1KeyPress(Sender: TObject;
var Key: Char);
begin
Key := ValidatePositiveCurrency(Key);
end;
procedure TFrmPaiPreSaleReceive.FormCreate(Sender: TObject);
begin
inherited;
iSolicitacaoTEF := 0;
fLangLoaded := (DMGlobal.IDLanguage = LANG_ENGLISH);
//Load Translation
if (not fLangLoaded) and (siLang.StorageFile <> '') then
begin
if FileExists(DMGlobal.LangFilesPath + siLang.StorageFile) then
siLang.LoadAllFromFile(DMGlobal.LangFilesPath + siLang.StorageFile, True)
else
MsgBox(MSG_INF_DICTIONARI_NOT_FOUND ,vbOKOnly + vbInformation);
fLangLoaded := True;
end;
Case DMGlobal.IDLanguage of
LANG_ENGLISH :
begin
sRefound := '&Refund';
sTotalRef := 'Total Refund :';
sReceive := '&Receive';
sTotalRec := 'Cash Total :';
sSetDateTo := 'Set Date to ';
end;
LANG_PORTUGUESE :
begin
sRefound := '&Reembolso';
sTotalRef := 'Total :';
sReceive := '&Receber';
sTotalRec := 'Total :';
sSetDateTo := 'Colocar data para ';
end;
LANG_SPANISH :
begin
sRefound := '&Reembolso';
sTotalRef := 'Total :';
sReceive := '&Reciber';
sTotalRec := 'Total :';
sSetDateTo := 'Colocar fecha para ';
end;
end;
end;
procedure TFrmPaiPreSaleReceive.spPayCheckClick(Sender: TObject);
begin
cmbPaymentType.LookUpValue := IntToStr(PAY_TYPE_CHECK);
cmbPaymentTypeSelectItem(nil);
end;
procedure TFrmPaiPreSaleReceive.btnPartialPaymentClick(Sender: TObject);
begin
inherited;
if MyTotInvoice <= 0 then
Exit;
If FrmPayPartial = nil then
FrmPayPartial := TFrmPayPartial.Create(Self);
lbPartialInfo.Caption :=
FrmPayPartial.Start(StrToInt(cmbPaymentType.LookUpValue),
MyIDCliente,
MyIDPreSale,
MyIDCashRegMov,
MyTotInvoice,
EditReceiveDate.Date,
EditAuthorization.Text,
0,
0);
end;
procedure TFrmPaiPreSaleReceive.btnPartialPayment2Click(Sender: TObject);
begin
inherited;
if StrToCurr(EditValue1.Text) <= 0 then
Exit;
If FrmPayPartial = nil then
FrmPayPartial := TFrmPayPartial.Create(Self);
lbPartialInfo2.Caption :=
FrmPayPartial.Start(StrToInt(cmbPayType1.LookUpValue),
MyIDCliente,
MyIDPreSale,
MyIDCashRegMov,
StrToCurr(EditValue1.Text),
EditReceiveDate.Date,
EditAuto1.Text,
0,
0);
end;
procedure TFrmPaiPreSaleReceive.FormDestroy(Sender: TObject);
begin
inherited;
If FrmPayPartial <> nil then
FreeAndNil(FrmPayPartial);
end;
function TFrmPaiPreSaleReceive.DeletePayment: Boolean;
begin
Result := True;
If (FrmPayPartial <> nil) Then
if (FrmPayPartial.tvPartialPay.Items.Count > 0) Then
with spPreSaleDeleteDelayPayment do
begin
Parameters.ParamByName('@PreSaleID').Value := MyIDPreSale;
Parameters.ParamByName('@IDUser').Value := DM.fUser.ID;
ExecProc;
end;
end;
end.
|
program poj3274;
const maxn=100000+100;
type
arr=array[1..30] of longint;
tp=record
b:arr;
num:longint;
end;
var i,j,n,m,p,q,l,r,k:longint;
a:array[0..maxn] of tp;
ans:longint;
procedure openfile;
begin
assign(input,'poj3274.in');
assign(output,'poj3274.out');
reset(input);
rewrite(output);
end;
procedure closefile;
begin
close(input); close(output);
end;
procedure work(p:longint;var a:arr);
var i,j,x:longint;
begin
x:=p;
i:=0;
while x>0 do
begin x:=x shr 1; inc(i); end;
x:=p;
for j:=1 to i do
begin
a[j]:=x mod 2; x:=x shr 1;
end;
end;
function compare(p,q:tp):boolean;
var i,j:longint;
begin
for i:=1 to k do
begin
if p.b[i]<q.b[i] then exit(true);
if p.b[i]>q.b[i] then exit(false);
end;
if p.num<q.num then exit(true);
exit(false);
end;
function equal(p,q:tp):boolean;
var i:longint;
begin
for i:=1 to k do
if p.b[i]<>q.b[i] then exit(false);
exit(true);
end;
procedure qsort(l,r:longint);
var i,j:longint; m,t:tp;
begin
i:=l; j:=r; m:=a[(l+r) div 2];
repeat
while compare(a[i],m) do inc(i);
while compare(m,a[j]) do dec(j);
if i<=j then
begin
t:=a[i];
a[i]:=a[j];
a[j]:=t;
inc(i); dec(j);
end;
until i>j;
if l<j then qsort(l,j);
if i<r then qsort(i,r);
end;
begin
//openfile;
readln(n,k);
for i:=1 to n do
begin
a[i].num:=i;
readln(p);
work(p,a[i].b);
end;
for i:=1 to n do
begin
for j:=1 to k do
a[i].b[j]:=a[i-1].b[j]+a[i].b[j];
for j:=k downto 1 do
a[i].b[j]:=a[i].b[j]-a[i].b[1];
end;
qsort(1,n);
i:=1;
while i<=n do
begin
j:=i;
while equal(a[j],a[j+1]) do
inc(j);
if a[j].num-a[i].num>ans then ans:=a[j].num-a[i].num;
i:=j+1;
end;
writeln(Ans);
//closefile;
end.
|
unit HS4Bind.Credential;
interface
uses
HS4bind.Interfaces;
type
THS4BindCredential = class(TInterfacedObject, iHS4BindCredential)
private
[weak]
FParent : iHS4Bind;
FBaseURL : string;
FEndPoint : string;
public
constructor Create(Parent : iHS4Bind);
destructor Destroy; override;
class function New(aParent : iHS4Bind) : iHS4BindCredential;
function BaseURL(const aValue : string) : iHS4BindCredential; overload;
function BaseURL : string; overload;
function &End : iHS4Bind;
end;
implementation
{ THS4BindCredential }
function THS4BindCredential.BaseURL(const aValue : string) : iHS4BindCredential;
begin
Result:= Self;
FBaseURL:= aValue;
end;
function THS4BindCredential.&End: iHS4Bind;
begin
Result:= FParent;
end;
function THS4BindCredential.BaseURL: string;
begin
Result:= FBaseURL;
end;
constructor THS4BindCredential.Create(Parent: iHS4Bind);
begin
FParent:= Parent;
end;
destructor THS4BindCredential.Destroy;
begin
inherited;
end;
class function THS4BindCredential.New(aParent: iHS4Bind): iHS4BindCredential;
begin
result:= Self.Create(aParent);
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [PONTO_MARCACAO]
The MIT License
Copyright: Copyright (C) 2016 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 PontoMarcacaoVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL,
PontoFechamentoJornadaVO;
type
TPontoMarcacaoVO = class(TVO)
private
FID: Integer;
FID_COLABORADOR: Integer;
FID_PONTO_RELOGIO: Integer;
FNSR: Integer;
FDATA_MARCACAO: TDateTime;
FHORA_MARCACAO: String;
FTIPO_MARCACAO: String;
FTIPO_REGISTRO: String;
FPAR_ENTRADA_SAIDA: String;
FJUSTIFICATIVA: String;
//Transientes
//FListaPontoMarcacao: TListaPontoMarcacaoVO;
FListaPontoFechamentoJornada: TListaPontoFechamentoJornadaVO;
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdColaborador: Integer read FID_COLABORADOR write FID_COLABORADOR;
property IdPontoRelogio: Integer read FID_PONTO_RELOGIO write FID_PONTO_RELOGIO;
property Nsr: Integer read FNSR write FNSR;
property DataMarcacao: TDateTime read FDATA_MARCACAO write FDATA_MARCACAO;
property HoraMarcacao: String read FHORA_MARCACAO write FHORA_MARCACAO;
property TipoMarcacao: String read FTIPO_MARCACAO write FTIPO_MARCACAO;
property TipoRegistro: String read FTIPO_REGISTRO write FTIPO_REGISTRO;
property ParEntradaSaida: String read FPAR_ENTRADA_SAIDA write FPAR_ENTRADA_SAIDA;
property Justificativa: String read FJUSTIFICATIVA write FJUSTIFICATIVA;
//Transientes
/// EXERCICIO: Nós precisamos dessa lista, mas ela só será criada logo abaixo, como fazer para utilizá-la?
//property ListaPontoMarcacao: TListaPontoMarcacaoVO read FListaPontoMarcacao write FListaPontoMarcacao;
property ListaPontoFechamentoJornada: TListaPontoFechamentoJornadaVO read FListaPontoFechamentoJornada write FListaPontoFechamentoJornada;
end;
TListaPontoMarcacaoVO = specialize TFPGObjectList<TPontoMarcacaoVO>;
implementation
constructor TPontoMarcacaoVO.Create;
begin
inherited;
//FListaPontoMarcacao := TListaPontoMarcacaoVO.Create;
FListaPontoFechamentoJornada := TListaPontoFechamentoJornadaVO.Create;
end;
destructor TPontoMarcacaoVO.Destroy;
begin
//FreeAndNil(FListaPontoMarcacao);
FreeAndNil(FListaPontoFechamentoJornada);
inherited;
end;
initialization
Classes.RegisterClass(TPontoMarcacaoVO);
finalization
Classes.UnRegisterClass(TPontoMarcacaoVO);
end.
|
unit clsHouse;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
THouse = class
private
fArrParticipants : array[1..3] of string;
fHouse : string;
fGrade : integer;
fScore : integer;
public
constructor Create(sHouse : string; iGrade : integer);
destructor Destroy; override;
procedure setHouse(sHouse : string);
procedure setGrade(iGrade : integer);
procedure setScore(iScore : integer);
procedure setParticipants(p1, p2, p3 : string);
function getHouse : string;
function getGrade : integer;
function getScore : integer;
function toString : string;
function getParticipant(iNo : integer):string;
end;
implementation
{ THouse }
constructor THouse.Create(sHouse: string; iGrade: integer);
var
sPath, sAdd, sLine, sP1, sP2, sP3 : string;
TF: textfile;
begin
sP1 := '';
sP2 := '';
sP3 := '';
sAdd := '';
sPath := '';
fHouse := sHouse;
fGrade := iGrade;
case fGrade of
8: sAdd := 'Grade 8';
9: sAdd := 'Grade 9';
10: sAdd := 'Grade 10';
11: sAdd := 'Grade 11';
12: sAdd := 'Grade 12';
// 13: sAdd := 'Teachers';
end;
sPath := GetCurrentDir()+'\Participants\' + sAdd + '.txt';
if FileExists(sPath) <> true then
begin
ShowMessage('File for ' + sAdd + ' cannot be found!');
Exit;
end;
sHouse := sHouse + ':';
AssignFile(TF, sPath);
Reset(TF);
while not EOF(TF) do
begin
readln(TF, sLine);
if sHouse = sLine then
begin
readln(TF, sP1);
readln(TF, sP2);
readln(TF, sP3);
break;
end;
end;
fArrParticipants[1] := sP1;
fArrParticipants[2] := sP2;
fArrParticipants[3] := sP3;
fScore := 0;
CloseFile(TF);
end;
destructor THouse.Destroy;
begin
inherited;
end;
function THouse.getGrade: integer;
begin
result := fGrade;
end;
function THouse.getHouse: string;
begin
result := fHouse;
end;
function THouse.getParticipant(iNo: integer): string;
begin
result := fArrParticipants[iNo];
end;
function THouse.getScore: integer;
begin
result := fScore;
end;
procedure THouse.setGrade(iGrade: integer);
begin
fGrade := iGrade;
end;
procedure THouse.setHouse(sHouse: string);
begin
fHouse := sHouse;
end;
procedure THouse.setParticipants(p1, p2, p3: string);
begin
fArrParticipants[1] := p1;
fArrParticipants[2] := p2;
fArrParticipants[3] := p3;
end;
procedure THouse.setScore(iScore: integer);
begin
fScore := iScore;
end;
function THouse.toString: string;
var
sParticipants : string;
iLoop : integer;
begin
sParticipants := '';
for iLoop := 1 to 3 do
begin
sParticipants := sParticipants + fArrParticipants[iLoop] + #13;
end;
result := fHouse + #9 + 'Grade ' + inttostr(fGrade) + #13 +
sParticipants;
end;
end.
|
////////////////////////////////////////////////////////////////////////////
// PaxCompiler
// Site: http://www.paxcompiler.com
// Author: Alexander Baranovsky (paxscript@gmail.com)
// ========================================================================
// Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved.
// Code Version: 4.2
// ========================================================================
// Unit: PAXCOMP_TRYLST.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
unit PAXCOMP_TRYLST;
interface
uses {$I uses.def}
SysUtils,
Classes,
PAXCOMP_CONSTANTS,
PAXCOMP_TYPES,
PAXCOMP_SYS,
PAXCOMP_PAUSE;
type
TTryRec = class(TPauseRec)
private
public
TryKind: TTryKind;
ExceptOnInfo: TAssocIntegers;
Level: Integer;
BreakOffset: Integer;
ContinueOffset: Integer;
N: Integer; // not saved into stream
constructor Create;
destructor Destroy; override;
procedure SaveToStream(S: TStream);
procedure LoadFromStream(S: TStream);
function Clone: TTryRec;
end;
TTryList = class(TTypedList)
private
function GetRecord(I: Integer): TTryRec;
public
procedure SaveToStream(S: TStream);
procedure LoadFromStream(S: TStream);
function Add: TTryRec;
property Records[I: Integer]: TTryRec read GetRecord; default;
end;
implementation
//----------- TTryRec ----------------------------------------------------------
constructor TTryRec.Create;
begin
inherited;
ExceptOnInfo := TAssocIntegers.Create;
end;
destructor TTryRec.Destroy;
begin
FreeAndNil(ExceptOnInfo);
inherited;
end;
procedure TTryRec.SaveToStream(S: TStream);
begin
S.Write(TryKind, SizeOf(TryKind));
S.Write(ProgOffset, SizeOf(ProgOffset));
S.Write(Level, SizeOf(Level));
S.Write(BreakOffset, SizeOf(BreakOffset));
S.Write(ContinueOffset, SizeOf(ContinueOffset));
ExceptOnInfo.SaveToStream(S);
end;
procedure TTryRec.LoadFromStream(S: TStream);
begin
S.Read(TryKind, SizeOf(TryKind));
S.Read(ProgOffset, SizeOf(ProgOffset));
S.Read(Level, SizeOf(Level));
S.Read(BreakOffset, SizeOf(BreakOffset));
S.Read(ContinueOffset, SizeOf(ContinueOffset));
ExceptOnInfo.LoadFromStream(S);
end;
function TTryRec.Clone: TTryRec;
begin
result := TTryRec.Create;
result.TryKind := TryKind;
result.Level := Level;
result.N := N;
FreeAndNil(result.ExceptOnInfo);
result.ExceptOnInfo := ExceptOnInfo.Clone;
// TPauseRec
result._EBP := _EBP;
result._ESP := _ESP;
result.ESP0 := ESP0;
result.ProgOffset := ProgOffset;
result.StackFrame := StackFrame;
result.StackFrameSize := StackFrameSize;
end;
//----------- TTryList ---------------------------------------------------------
function TTryList.Add: TTryRec;
begin
result := TTryRec.Create;
L.Add(result);
end;
function TTryList.GetRecord(I: Integer): TTryRec;
begin
result := TTryRec(L[I]);
end;
procedure TTryList.SaveToStream(S: TStream);
var
I, K: Integer;
begin
K := Count;
S.Write(K, SizeOf(Integer));
for I:=0 to K - 1 do
Records[I].SaveToStream(S);
end;
procedure TTryList.LoadFromStream(S: TStream);
var
I, K: Integer;
R: TTryRec;
begin
Clear;
S.Read(K, SizeOf(Integer));
for I:=0 to K - 1 do
begin
R := Add;
R.LoadFromStream(S);
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.