text stringlengths 14 6.51M |
|---|
unit GetLimitedZipCodesUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TGetLimitedZipCodes = class(TBaseExample)
public
procedure Execute(ZipCode: String; Limit, Offset: integer);
end;
implementation
uses GeocodingAddressUnit;
procedure TGetLimitedZipCodes.Execute(ZipCode: String; Limit, Offset: integer);
var
ErrorString: String;
Addresses: TGeocodingAddressList;
begin
Addresses := Route4MeManager.Geocoding.GetZipCodes(
ZipCode, Limit, Offset, ErrorString);
try
WriteLn('');
if (Addresses <> nil) then
begin
WriteLn('GetLimitedZipCodes executed successfully');
WriteLn(Format('Address count: %d', [Addresses.Count]));
end
else
WriteLn(Format('GetLimitedZipCodes error: "%s"', [ErrorString]));
finally
FreeAndNil(Addresses);
end;
end;
end.
|
unit Eagle.Alfred;
interface
uses
System.SysUtils,
Eagle.ConsoleIO,
Eagle.Alfred.Command,
Eagle.Alfred.CreateCommand,
Eagle.Alfred.MigrateCommand,
Eagle.Alfred.ProjectCommand,
Eagle.Alfred.HelpCommand,
Eagle.Alfred.DprojParser;
type
TAlfred = class
private
FCurrentPath: string;
FAppPath: string;
FDprojParser: TDprojParser;
FConsoleIO: IConsoleIO;
function GetCommand: ICommand;
public
constructor Create;
destructor Destroy; override;
procedure Run();
end;
implementation
{ TAlfred }
constructor TAlfred.Create;
begin
FDprojParser := TDprojParser.Create('.\packages\DelphiXE8\', 'EagleGestao');
FCurrentPath := GetCurrentDir;
FAppPath := ExtractFilePath(ParamStr(0));
FConsoleIO := TConsoleIO.Create;
end;
destructor TAlfred.Destroy;
begin
if Assigned(FDprojParser) then
FreeAndNil(FDprojParser);
inherited;
end;
function TAlfred.GetCommand: ICommand;
var
Cmd: string;
begin
Cmd := ParamStr(1).ToUpper;
if Cmd.Equals('CREATE') then
begin
Result := TCreateCommand.Create(FAppPath, FConsoleIO, FDprojParser);
Exit;
end;
if Cmd.Equals('PROJECT') then
begin
Result := TProjectCommand.Create(FAppPath, FConsoleIO, FDprojParser);
Exit;
end;
if Cmd.Equals('MIGRATE') then
begin
Result := TMigrateCommand.Create(FAppPath, FConsoleIO);
Exit;
end;
Result := THelpCommand.Create(FConsoleIO);
end;
procedure TAlfred.Run;
var
Cmd: ICommand;
begin
Cmd := GetCommand;
Cmd.Execute;
end;
end.
|
unit GX_ProjOptMap;
{$I GX_CondDefine.inc}
interface
uses
TypInfo;
type
// It is possible to specify a translator that
// translates a passed in string value to a
// longer, more elaborate option value - e.g.
// "0" -> False etc.
TGxOptionValueTranslator = function(const ValueString: string): string;
function GxBoolOptionTranslator(const ValueString: string): string;
function GxStringOptionTranslator(const ValueString: string): string;
function GxIntegerOptionTranslator(const ValueString: string): string;
function GxHexOptionTranslator(const ValueString: string): string;
function GxProcInstructTranslator(const ValueString: string): string;
function GxAlignmentTranslator(const ValueString: string): string;
function GxCallConvTranslator(const ValueString: string): string;
function GxRegVarTranslator(const ValueString: string): string;
function GxMemberPointerTranslator(const ValueString: string): string;
function GxVTableTranslator(const ValueString: string): string;
function GxAtlInstancingTranslator(const ValueString: string): string;
function GxAtlCoinitTranslator(const ValueString: string): string;
function GxAtlThreadTranslator(const ValueString: string): string;
function GxTasmExpTranslator(const ValueString: string): string;
function GxVerInfoModuleAttribTranslator(const ValueString: string): string;
function GxMapFileTranslator(const ValueString: string): string;
function GxReferenceInfoTranslator(const ValueString: string): string;
type
// The category into which an option belongs
TGxOptionCategory = (
// Basic functionality areas
ocIde, ocCompiler, ocLinker, ocDebugger, ocWarnings,
// Product
ocDelphi, ocBCB, ocTasm, ocTLib, ocCodeGuard,
// Language (leaving assembler to ocTasm?)
ocObjectPascal, ocATL,
// Directories / Folders
ocFolders,
// Not yet known
ocUnknown
);
TGxOptionCategorySet = set of TGxOptionCategory;
const
GxAllOptions = [Low(TGxOptionCategory)..High(TGxOptionCategory)];
GxCppOptions = [ocBCB, ocTasm, ocTLib, ocATL, ocCodeGuard];
const
GxOptionsCategoryText: array[TGxOptionCategory] of string = (
'IDE', 'Compiler', 'Linker', 'Debugger', 'Warnings',
'Delphi', 'C++Builder', 'TASM', 'TLib', 'CodeGuard',
'Object Pascal', 'ATL',
'Directories',
'Unknown'
);
type
TGxOptionCategoryGroup = (
ocgDelphi
);
const
GxOptionCategoryGroups: array[TGxOptionCategoryGroup] of TGxOptionCategorySet = (
[ocDelphi]
);
type
TGxOptionsMap = record
Name: string; // The IDE's option name, e.g. "HostApplication"
AssumedTypeKind: TTypeKind; // Used for sanity checking
Description: string; // Descriptive text about the option
Categories: TGxOptionCategorySet;
Translator: TGxOptionValueTranslator;
end;
// TODO 4 -oAnyone -cFeature: Add similar maps for the environment options?
const
{$IFDEF GX_VER200_up}
StringType = tkUString;
{$ELSE} // Delphi 2007 or older
StringType = tkLString;
{$ENDIF}
GxOptionsMap: array[0..311] of TGxOptionsMap = (
( // 0
Name: 'HostApplication';
AssumedTypeKind: StringType;
Description: 'Debugger host application';
Categories: [ocDelphi, ocBCB, ocDebugger];
Translator: GxStringOptionTranslator;
),
( // 1
Name: 'RunParams';
AssumedTypeKind: StringType;
Description: 'Debugger command line parameters';
Categories: [ocDelphi, ocBCB, ocDebugger];
Translator: GxStringOptionTranslator;
),
(
Name: 'RemoteHost';
AssumedTypeKind: StringType;
Description: 'Debugger remote host';
Categories: [ocDelphi, ocBCB, ocDebugger];
Translator: GxStringOptionTranslator;
),
(
Name: 'RemotePath';
AssumedTypeKind: StringType;
Description: 'Debugger remote path';
Categories: [ocDelphi, ocBCB, ocDebugger, ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'RemoteDebug';
AssumedTypeKind: tkEnumeration;
Description: 'Debug on remote host';
Categories: [ocDelphi, ocBCB, ocDebugger];
Translator: GxBoolOptionTranslator;
),
(
Name: 'DebugInfo';
AssumedTypeKind: tkEnumeration;
Description: 'Include TurboDebugger 32 information in binary';
Categories: [ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'RemoteSymbols';
AssumedTypeKind: tkEnumeration;
Description: 'Include remote debug symbols';
Categories: [ocDelphi, ocBCB, ocDebugger];
Translator: GxBoolOptionTranslator;
),
(
Name: 'OutputObj';
AssumedTypeKind: tkSet;
Description: '';
Categories: [ocCompiler];
Translator: nil;
),
(
Name: 'HintFlag';
AssumedTypeKind: tkEnumeration;
Description: 'Show compiler hints';
Categories: [ocCompiler, ocDelphi];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnFlag';
AssumedTypeKind: tkEnumeration;
Description: 'Show compiler warnings';
Categories: [ocCompiler, ocDelphi, ocWarnings];
Translator: GxBoolOptionTranslator;
),
( // 10
Name: 'StackSize';
AssumedTypeKind: tkInteger;
Description: 'Initial stack size';
Categories: [ocLinker, ocDelphi];
Translator: GxHexOptionTranslator;
),
(
Name: 'MaxStackSize';
AssumedTypeKind: tkInteger;
Description: 'Maximum stack size';
Categories: [ocLinker, ocDelphi];
Translator: GxHexOptionTranslator;
),
(
Name: 'ImageBase';
AssumedTypeKind: tkInteger;
Description: 'Preferred load address of the binary image (usually DLL)';
Categories: [ocLinker, ocDelphi];
Translator: GxHexOptionTranslator;
),
(
Name: 'Target';
AssumedTypeKind: tkEnumeration;
Description: ''; // What is this in D5?
Categories: [ocLinker];
Translator: nil;
),
(
Name: 'MapFile';
AssumedTypeKind: tkEnumeration;
Description: 'Generate map file: Off/Segments/Publics/Detailed';
Categories: [ocLinker, ocDelphi];
Translator: GxMapFileTranslator;
),
(
Name: 'GenDRC';
AssumedTypeKind: tkEnumeration;
Description: 'Generate DRC file of resource strings';
Categories: [ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'GenDUI';
AssumedTypeKind: tkEnumeration;
Description: ''; // What is a DUI file (BCB)?
Categories: [ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'CompileName';
AssumedTypeKind: StringType;
Description: '';
Categories: [ocCompiler];
Translator: nil;
),
(
Name: 'Defines';
AssumedTypeKind: StringType;
Description: 'Conditional defines';
Categories: [ocBCB, ocDelphi, ocCompiler];
Translator: GxStringOptionTranslator;
),
(
Name: 'SysDefines';
AssumedTypeKind: StringType;
Description: 'System defines (defined by IDE)';
Categories: [ocBCB, ocCompiler];
Translator: GxStringOptionTranslator;
),
( // 20
Name: 'OutputDir';
AssumedTypeKind: StringType;
Description: 'Output directory for compiled binaries';
Categories: [ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'UnitOutputDir';
AssumedTypeKind: StringType;
Description: 'Output directory for DCU files';
Categories: [ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'UnitDir';
AssumedTypeKind: StringType;
Description: 'Unit search path';
Categories: [ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'ObjDir';
AssumedTypeKind: StringType;
Description: 'Search path?'; // ????? search path in D5
Categories: [ocFolders];
Translator: nil;
),
(
Name: 'SrcDir';
AssumedTypeKind: StringType;
Description: 'Search path?'; // ????? search path in D5
Categories: [ocFolders];
Translator: nil;
),
(
Name: 'ResDir';
AssumedTypeKind: StringType;
Description: 'Search path?'; // ???? Search path in D5
Categories: [ocFolders];
Translator: nil;
),
(
Name: 'PkgDllDir';
AssumedTypeKind: StringType;
Description: 'BPL output directory';
Categories: [ocBCB, ocDelphi, ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'OptionsString';
AssumedTypeKind: StringType;
Description: '';
Categories: [ocUnknown];
Translator: nil;
),
(
Name: 'PkgDcpDir';
AssumedTypeKind: StringType;
Description: 'DCP/BPI output directory';
Categories: [ocBCB, ocDelphi, ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'UsePackages';
AssumedTypeKind: tkEnumeration;
Description: 'Use runtime packages';
Categories: [ocLinker, ocDelphi, ocBCB];
Translator: GxBoolOptionTranslator;
),
( // 30
Name: 'Packages';
AssumedTypeKind: StringType;
Description: 'Runtime packages list';
Categories: [ocBCB, ocDelphi, ocLinker];
Translator: GxStringOptionTranslator;
),
(
Name: 'UnitAliases';
AssumedTypeKind: StringType;
Description: 'Aliases for units that have changed names';
Categories: [ocCompiler, ocDelphi, ocBCB];
Translator: GxStringOptionTranslator;
),
(
Name: 'ExeDescription';
AssumedTypeKind: StringType;
Description: 'EXE Description (inserted in binary)';
Categories: [ocLinker];
Translator: GxStringOptionTranslator;
),
(
Name: 'ImplicitBuild';
AssumedTypeKind: tkEnumeration;
Description: 'Implicitly build packages';
Categories: [ocIde, ocCompiler, ocDelphi, ocBCB];
Translator: GxBoolOptionTranslator;
),
(
Name: 'RuntimeOnly';
AssumedTypeKind: tkEnumeration;
Description: 'This is a runtime only package';
Categories: [ocLinker, ocDelphi, ocBCB];
Translator: GxBoolOptionTranslator;
),
(
Name: 'DesigntimeOnly';
AssumedTypeKind: tkEnumeration;
Description: 'This is a design-time only package';
Categories: [ocLinker, ocDelphi, ocBCB];
Translator: GxBoolOptionTranslator;
),
(
Name: 'DebugSourcePath';
AssumedTypeKind: StringType;
Description: 'Search path for the debugger to find source units';
Categories: [ocBCB, ocDelphi, ocIde, ocDebugger, ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'ImageDebugInfo';
AssumedTypeKind: tkEnumeration;
Description: '';
Categories: [ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'HeapSize';
AssumedTypeKind: tkInteger;
Description: 'Minimum heap size for application';
Categories: [ocBCB, ocLinker];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'MaxHeapSize';
AssumedTypeKind: tkInteger;
Description: 'Maximum heap size for application';
Categories: [ocBCB, ocLinker];
Translator: GxIntegerOptionTranslator;
),
( // 40
Name: 'LinkMaxErrors';
AssumedTypeKind: tkInteger;
Description: 'Maximum number of linker errors';
Categories: [ocLinker, ocBCB];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'LinkShowMangle';
AssumedTypeKind: tkEnumeration;
Description: 'Show mangled names in MAP file';
Categories: [ocLinker, ocBCB];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LinkGenImportLib';
AssumedTypeKind: tkEnumeration;
Description: 'Generate import library (.LIB or .BPI)';
Categories: [ocLinker, ocBCB];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LinkGenLib';
AssumedTypeKind: tkEnumeration;
Description: 'Generate .lib file - applies to packages only';
Categories: [ocLinker, ocBCB];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LinkNoStateFiles';
AssumedTypeKind: tkEnumeration;
Description: 'Do not generate linker state files';
Categories: [ocLinker, ocBCB];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LinkSubsysMajor';
AssumedTypeKind: tkInteger;
Description: 'Major portion of Windows version ID on which you expect your application will be run on';
Categories: [ocLinker, ocBCB];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'LinkSubsysMinor';
AssumedTypeKind: tkInteger;
Description: 'Minor portion of Windows version ID on which you expect your application will be run on';
Categories: [ocLinker, ocBCB];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'CppDebugInfo';
AssumedTypeKind: tkEnumeration;
Description: 'Add debug information to .OBJ files';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LineNumbers';
AssumedTypeKind: tkEnumeration;
Description: 'Add line numbers to .OBJ files';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'AutoRegVars'; // see also: RegisterVars
AssumedTypeKind: tkEnumeration;
Description: '';
Categories: [ocBCB, ocCompiler];
Translator: nil; // Probably None, Automatic, Register keyword
),
( // 50
Name: 'MergeDupStrs';
AssumedTypeKind: tkEnumeration;
Description: 'Merge duplicate strings';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'EnableInLines';
AssumedTypeKind: tkEnumeration;
Description: 'Enable inline expansion of functions';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'ShowWarnings';
AssumedTypeKind: tkEnumeration;
Description: 'Show BCB compiler warnings'; //????
Categories: [ocCompiler, ocBCB, ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'StdStackFrame';
AssumedTypeKind: tkEnumeration;
Description: 'Always generate a standard stack frame';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'PCH';
AssumedTypeKind: tkEnumeration;
Description: 'Use pre-compiled headers';
Categories: [ocIde, ocCompiler, ocBCB];
Translator: GxBoolOptionTranslator;
),
(
Name: 'ShowInfoMsgs';
AssumedTypeKind: tkEnumeration;
Description: 'Show general information messages';
Categories: [ocIde, ocCompiler, ocLinker, ocBCB];
Translator: GxBoolOptionTranslator;
),
(
Name: 'GenDll';
AssumedTypeKind: tkEnumeration;
Description: 'Set DLL module attribute';
Categories: [ocIde, ocDelphi, ocBCB];
Translator: GxBoolOptionTranslator;
),
(
Name: 'GenConsoleApp';
AssumedTypeKind: tkEnumeration;
Description: 'Generate console application';
Categories: [ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'GenPackage';
AssumedTypeKind: tkEnumeration;
Description: 'Generate package';
Categories: [ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'GenStaticLibrary';
AssumedTypeKind: tkEnumeration;
Description: 'Generate static library';
Categories: [ocBCB, ocLinker];
Translator: GxBoolOptionTranslator;
),
( // 60
Name: 'ShowLinkerWarnings';
AssumedTypeKind: tkEnumeration;
Description: 'Show linker warnings';
Categories: [ocBCB, ocLinker, ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'UseIncLinker';
AssumedTypeKind: tkEnumeration;
Description: 'Use incremental linker';
Categories: [ocBCB, ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'InMemoryExe';
AssumedTypeKind: tkEnumeration;
Description: 'Generate in-memory EXE (Windows NT only)';
Categories: [ocBCB, ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LinkDebugVcl';
AssumedTypeKind: tkEnumeration;
Description: 'Link to the debug VCL units';
Categories: [ocBCB, ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'InstructionSet';
AssumedTypeKind: tkEnumeration;
Description: 'Processor instruction set';
Categories: [ocBCB, ocCompiler];
// this is 386..586!
Translator: GxProcInstructTranslator;
),
(
Name: 'Alignment';
AssumedTypeKind: tkEnumeration;
Description: 'Data alignment';
Categories: [ocBCB, ocCompiler];
// 1,2,4,8
Translator: GxAlignmentTranslator;
),
(
Name: 'CallingConvention';
AssumedTypeKind: tkEnumeration;
Description: 'Calling convention';
Categories: [ocBCB, ocCompiler];
// cdecl, register, Pascal, stdcall
Translator: GxCallConvTranslator;
),
(
Name: 'RegisterVars';
AssumedTypeKind: tkEnumeration;
Description: 'Register variables';
Categories: [ocBCB, ocCompiler];
// none, auto, register
Translator: GxRegVarTranslator;
),
(
Name: 'Ansi';
AssumedTypeKind: tkEnumeration;
Description: 'Language compliance';
Categories: [ocBCB, ocCompiler];
Translator: nil; // Borland, ANSI, Unix V, K&R
),
(
Name: 'AutoDep';
AssumedTypeKind: tkEnumeration;
Description: 'Generate auto-dependency information in OBJ files';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
( // 70
Name: 'Underscore';
AssumedTypeKind: tkEnumeration;
Description: 'Generate underscores';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'FastFloat';
AssumedTypeKind: tkEnumeration;
Description: 'Fast floating point code (disregard ANSI conventions)';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'Float';
AssumedTypeKind: tkEnumeration;
Description: 'Use no floating point arithmetic';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'PentiumFloat';
AssumedTypeKind: tkEnumeration;
Description: 'Correct Pentium FDIV flaw';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'NestedComments';
AssumedTypeKind: tkEnumeration;
Description: 'Allow nested C++ comments';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'MFCCompat';
AssumedTypeKind: tkEnumeration;
Description: 'Enable MFC compatibility mode';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'IdentLen';
AssumedTypeKind: tkInteger;
Description: 'Maximum identifier length in characters';
Categories: [ocBCB, ocCompiler];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'MemberPrecision';
AssumedTypeKind: tkEnumeration;
Description: 'Honor member precision';
Categories: [ocBCB, ocCompiler];
Translator: nil;
),
(
Name: 'ForLoops';
AssumedTypeKind: tkEnumeration;
Description: 'Do not restrict scope on for loops';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'TwoChar';
AssumedTypeKind: tkEnumeration;
Description: 'No distinct char type';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
( // 80
Name: 'CodeModifiers';
AssumedTypeKind: tkEnumeration;
Description: 'Do not mangle code modifiers';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'EnableRTTI';
AssumedTypeKind: tkEnumeration;
Description: 'Enable generation of RTTI';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'EnableExceptions';
AssumedTypeKind: tkEnumeration;
Description: 'Enable exceptions';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'EHLocalInfo';
AssumedTypeKind: tkEnumeration;
Description: 'Enable generation of exception location information';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'EHDtor';
AssumedTypeKind: tkEnumeration;
Description: 'Perform destructor cleanup on exception';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'EHPrologs';
AssumedTypeKind: tkEnumeration;
Description: 'Use fast exception handling prologs';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'ZeroBaseClass';
AssumedTypeKind: tkEnumeration;
Description: 'Allow zero length base classes';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'MemberPointer';
AssumedTypeKind: tkEnumeration;
Description: 'Storage layout of class member pointers';
Categories: [ocBCB, ocCompiler];
// All cases, MI, SI, Smallest
Translator: GxMemberPointerTranslator;
),
(
Name: 'VTables';
AssumedTypeKind: tkEnumeration;
Description: 'Optimize virtual method tables';
Categories: [ocBCB, ocCompiler];
// Smart, local, external, public
Translator: GxVTableTranslator;
),
(
Name: 'Templates';
AssumedTypeKind: tkEnumeration;
Description: 'External templates';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
( // 90
Name: 'PchPath';
AssumedTypeKind: StringType;
Description: 'Precompiled header path';
Categories: [ocBCB, ocIde, ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'PchStopAfter';
AssumedTypeKind: StringType;
Description: 'Stop compiling pre-compiled headers after file';
Categories: [ocBCB, ocIde];
Translator: GxStringOptionTranslator;
),
(
Name: 'UseDynamicRtl';
AssumedTypeKind: tkEnumeration;
Description: 'Use dynamic Runtime library (DLL)';
Categories: [ocBCB, ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'ATLMultiUse';
AssumedTypeKind: tkEnumeration;
Description: 'ATL Instancing model';
Categories: [ocBCB, ocATL];
// Single use, Multiple use
Translator: GxAtlInstancingTranslator;
),
(
Name: 'ATLDebugQI';
AssumedTypeKind: tkEnumeration;
Description: 'Trace calls to QueryInterface (Debugging)';
Categories: [ocBCB, ocATL];
Translator: GxBoolOptionTranslator;
),
(
Name: 'ATLCoinitMultiThreaded';
AssumedTypeKind: tkEnumeration;
Description: 'OLE Initialization COINIT_xxxx Flag';
Categories: [ocBCB, ocATL];
// APARTMENTTHREADED, MULTITHREADED
Translator: GxAtlCoinitTranslator;
),
(
Name: 'ATLAutoRegisterInproc';
AssumedTypeKind: tkEnumeration;
Description: '';
Categories: [ocBCB, ocATL];
Translator: nil;
),
(
Name: 'ATLDebugRefCount';
AssumedTypeKind: tkEnumeration;
Description: 'Check reference counts (debugging)';
Categories: [ocBCB, ocATL];
Translator: GxBoolOptionTranslator;
),
(
Name: 'ATLDebug';
AssumedTypeKind: tkEnumeration;
Description: 'Generally trace ATL (debugging)';
Categories: [ocBCB, ocATL];
Translator: GxBoolOptionTranslator;
),
(
Name: 'ATLThreading';
AssumedTypeKind: tkEnumeration;
Description: 'ATL threading model';
Categories: [ocBCB, ocATL];
// Single, Apartment, Free, Both
Translator: GxAtlThreadTranslator;
),
( // 100
Name: 'CodeOpt';
AssumedTypeKind: tkEnumeration;
Description: '';
Categories: [ocCompiler];
Translator: nil;
),
(
Name: 'FloatSupport';
AssumedTypeKind: tkEnumeration;
Description: '';
Categories: [ocCompiler];
Translator: nil;
),
(
Name: 'IncludePath';
AssumedTypeKind: StringType;
Description: '';
Categories: [ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'LibPath';
AssumedTypeKind: StringType;
Description: '';
Categories: [ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'DebugPath';
AssumedTypeKind: StringType;
Description: '';
Categories: [ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'ReleasePath';
AssumedTypeKind: StringType;
Description: '';
Categories: [ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'LibraryList';
AssumedTypeKind: StringType;
Description: '';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'TasmViaCppOpts';
AssumedTypeKind: StringType;
Description: '';
Categories: [ocTasm];
Translator: GxStringOptionTranslator;
),
(
Name: 'ClearPackageCache';
AssumedTypeKind: tkEnumeration;
Description: '';
Categories: [ocUnknown];
Translator: nil;
),
(
Name: 'ClearUnitCache';
AssumedTypeKind: tkEnumeration;
Description: '';
Categories: [ocUnknown];
Translator: nil;
),
( // 110
Name: 'MarkModified';
AssumedTypeKind: tkEnumeration;
Description: '';
Categories: [ocUnknown];
Translator: nil;
),
(
Name: 'CaseSensitive';
AssumedTypeKind: tkEnumeration;
Description: 'Generate case-sensitive .LIB libraries';
Categories: [ocTLib];
Translator: GxBoolOptionTranslator;
),
(
Name: 'ExtendedDictionary';
AssumedTypeKind: tkEnumeration;
Description: 'Create extended dictionary';
Categories: [ocTLib];
Translator: GxBoolOptionTranslator;
),
(
Name: 'PurgeComment';
AssumedTypeKind: tkEnumeration;
Description: 'Purge comment records';
Categories: [ocTLib];
Translator: GxBoolOptionTranslator;
),
(
Name: 'PageSize';
AssumedTypeKind: tkInteger;
Description: 'Page size';
Categories: [ocTLib];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'TasmCrossReference';
AssumedTypeKind: tkEnumeration;
Description: 'Include cross reference in listing';
Categories: [ocTasm];
Translator: GxBoolOptionTranslator;
),
(
Name: 'TasmSymbolTables';
AssumedTypeKind: tkEnumeration;
Description: 'Show symbol tables in listing';
Categories: [ocTasm];
Translator: GxBoolOptionTranslator;
),
(
Name: 'TasmGenerateListing';
AssumedTypeKind: tkEnumeration;
Description: 'Generate listing';
Categories: [ocTasm];
Translator: GxBoolOptionTranslator;
),
(
Name: 'TasmIncludeConditionals';
AssumedTypeKind: tkEnumeration;
Description: 'Include false conditionals in listing';
Categories: [ocTasm];
Translator: GxBoolOptionTranslator;
),
(
Name: 'TasmIncludeErrors';
AssumedTypeKind: tkEnumeration;
Description: 'Include errors in listing';
Categories: [ocTasm];
Translator: GxBoolOptionTranslator;
),
( // 120
Name: 'TasmExpanded';
AssumedTypeKind: tkEnumeration;
Description: 'Generate expanded listing';
Categories: [ocTasm];
// Normal listing, expanded listing
Translator: GxTasmExpTranslator;
),
(
Name: 'TasmCaseCheckingOn';
AssumedTypeKind: tkEnumeration;
Description: 'Check case of symbols';
Categories: [ocTasm];
Translator: GxBoolOptionTranslator; // None, Globals, All !!
),
(
Name: 'TasmAllCase';
AssumedTypeKind: tkEnumeration;
Description: 'Check case of all symbols';
Categories: [ocTasm];
Translator: GxBoolOptionTranslator; // None, Globals, All !!
),
(
Name: 'TasmDebugOn';
AssumedTypeKind: tkEnumeration;
Description: 'Generate debug information';
Categories: [ocTasm];
Translator: GxBoolOptionTranslator;
),
(
Name: 'TasmFullDebug';
AssumedTypeKind: tkEnumeration;
Description: 'Generate full debug information';
Categories: [ocTasm];
Translator: GxBoolOptionTranslator;
),
(
Name: 'TasmWarningsOn';
AssumedTypeKind: tkEnumeration;
Description: 'Generate warnings';
Categories: [ocTasm, ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'TasmWarningsLevel1';
AssumedTypeKind: tkEnumeration;
Description: 'Use warnings Level 1';
Categories: [ocTasm, ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'TasmHashTable';
AssumedTypeKind: tkInteger;
Description: 'Size of hash table';
Categories: [ocTasm];
Translator: nil;
),
(
Name: 'TasmPasses';
AssumedTypeKind: tkInteger;
Description: 'Maximum number of passes';
Categories: [ocTasm];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'TasmSymbolLength';
AssumedTypeKind: tkInteger;
Description: 'Maximum symbol length';
Categories: [ocTasm];
Translator: GxIntegerOptionTranslator;
),
( // 130
Name: 'TasmDirective';
AssumedTypeKind: StringType;
Description: 'Directives to be passed to TASM';
Categories: [ocTasm];
Translator: GxStringOptionTranslator;
),
(
Name: 'NoAskLibs';
AssumedTypeKind: tkEnumeration;
Description: '';
Categories: [ocUnknown];
Translator: nil;
),
(
Name: 'Align'; // $A
AssumedTypeKind: tkInteger;
Description: 'Align fields at ... byte boundaries';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
// 1, 2, 4, 8, 16, 32...
Translator: GxIntegerOptionTranslator;
),
(
Name: 'BoolEval'; // $B
AssumedTypeKind: tkInteger;
Description: 'Boolean short-circuit evaluation';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'Assertions'; // $C
AssumedTypeKind: tkInteger;
Description: 'Generate code for assert directives';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'UnitDebugInfo'; // $D
AssumedTypeKind: tkInteger;
Description: 'Generate debug information in compiled units';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'ImportedData'; // $G
AssumedTypeKind: tkInteger;
Description: 'Imported data (packages)';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LongStrings'; // $H
AssumedTypeKind: tkInteger;
Description: 'Default to long strings';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'IOChecks'; // $I
AssumedTypeKind: tkInteger;
Description: 'Input/output checking';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WriteableConst'; // $J
AssumedTypeKind: tkInteger;
Description: 'Writeable typed constants';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
( // 140
Name: 'LocalSymbols'; // $L
AssumedTypeKind: tkInteger;
Description: 'Generate local symbol information for debugging';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'TypeInfo'; // $M
AssumedTypeKind: tkInteger;
Description: 'Generate runtime type information';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'Optimization'; // $O
AssumedTypeKind: tkUnknown; // Usually tkInteger, but tkEnumeration for Delphi 9 C# projects
Description: 'Optimization (Object Pascal)';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxStringOptionTranslator;
),
(
Name: 'OpenStrings'; // $P
AssumedTypeKind: tkInteger;
Description: 'Open String Parameters';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'OverflowChecks'; // $Q
AssumedTypeKind: tkInteger;
Description: 'Overflow checking';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'RangeChecks'; // $R
AssumedTypeKind: tkInteger;
Description: 'Range checking';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'StackChecks'; // $S
AssumedTypeKind: tkInteger;
Description: 'Stack checking';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'TypedAddress'; // $T
AssumedTypeKind: tkInteger;
Description: 'Type-checked pointers';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'SafeDivide'; // $U
AssumedTypeKind: tkInteger;
Description: 'Pentium-safe FDIV operations';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'VarStringChecks'; // $V
AssumedTypeKind: tkInteger;
Description: 'Var-string checking (long vs short var strings)';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
( // 150
Name: 'StackFrames'; // $W
AssumedTypeKind: tkInteger;
Description: 'Compile with stack frames';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'ExtendedSyntax'; // $X
AssumedTypeKind: tkInteger;
Description: 'Extended syntax (PChar, ignore function results)';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxBoolOptionTranslator;
),
(
Name: 'ReferenceInfo'; // $Y
AssumedTypeKind: tkInteger;
Description: 'Symbol declaration and cross-reference information';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
Translator: GxReferenceInfoTranslator;
),
(
Name: 'MinEnumSize'; // $Z
AssumedTypeKind: tkInteger;
Description: 'Minimum size of enumerations in bytes';
Categories: [ocDelphi, ocBCB, ocCompiler, ocObjectPascal];
// 1, 2, 4, 8, 16, ...
Translator: GxIntegerOptionTranslator;
),
(
Name: 'AutoIncBuildNum';
AssumedTypeKind: tkEnumeration;
Description: 'Auto-increment build number';
Categories: [ocDelphi, ocBCB, ocIDE];
Translator: GxBoolOptionTranslator;
),
(
Name: 'CodePage';
AssumedTypeKind: tkInteger;
Description: '';
Categories: [];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'IncludeVersionInfo';
AssumedTypeKind: tkEnumeration;
Description: 'Include version information in project';
Categories: [ocDelphi, ocBCB, ocIDE];
Translator: GxBoolOptionTranslator;
),
(
Name: 'Keys';
AssumedTypeKind: tkClass; // (!)
Description: 'Version Info Keys';
Categories: [ocDelphi, ocBCB, ocIDE];
Translator: nil;
),
(
Name: 'Locale';
AssumedTypeKind: tkInteger;
Description: 'Locale ID (VERSIONINFO)';
Categories: [ocDelphi, ocBCB, ocIDE];
Translator: GxHexOptionTranslator;
),
(
Name: 'MajorVersion';
AssumedTypeKind: tkInteger;
Description: 'Module major version (VERSIONINFO)';
Categories: [ocDelphi, ocBCB, ocIDE];
Translator: GxIntegerOptionTranslator;
),
( // 160
Name: 'MinorVersion';
AssumedTypeKind: tkInteger;
Description: 'Module minor version (VERSIONINFO)';
Categories: [ocDelphi, ocBCB, ocIDE];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'Release';
AssumedTypeKind: tkInteger;
Description: 'Release number (VERSIONINFO)';
Categories: [ocDelphi, ocBCB, ocIDE];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'Build';
AssumedTypeKind: tkInteger;
Description: 'Build number (VERSIONINFO)';
Categories: [ocDelphi, ocBCB, ocIDE];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'ModuleAttribs';
AssumedTypeKind: tkSet;
Description: 'Module attributes (VERSIONINFO, not supported by the IDE)';
Categories: [ocDelphi, ocBCB, ocIDE];
// Debug build, Pre-release, DLL, Special build, Private build
Translator: GxVerInfoModuleAttribTranslator;
),
(
Name: 'AppFileExt';
AssumedTypeKind: StringType;
Description: 'AppFileExt';
Categories: [ocBCB, ocUnknown];
Translator: nil;
),
(
Name: 'LibDir';
AssumedTypeKind: StringType;
Description: 'The location of the C++Builder Lib directory (read only)';
Categories: [ocBCB, ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'ShowExtendedMsgs';
AssumedTypeKind: tkEnumeration;
Description: 'Show extended compiler messages';
Categories: [ocBCB, ocCompiler];
Translator: nil;
),
(
Name: 'ZeroClassFunction';
AssumedTypeKind: tkEnumeration;
Description: 'Allow zero length empty class members';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'MultiThreaded';
AssumedTypeKind: tkEnumeration;
Description: 'MultiThreaded';
Categories: [ocBCB, ocUnknown];
Translator: nil;
),
(
Name: 'CGGlobalStackAccesses';
AssumedTypeKind: tkEnumeration;
Description: 'CodeGuard: Validate global and stack accesses';
Categories: [ocBCB, ocCodeGuard, ocCompiler];
Translator: GxBoolOptionTranslator;
),
( // 170
Name: 'CGThisPointer';
AssumedTypeKind: tkEnumeration;
Description: 'CodeGuard: Validate the "this" pointer on member function entry';
Categories: [ocBCB, ocCodeGuard, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'CGInlinePointer';
AssumedTypeKind: tkEnumeration;
Description: 'CodeGuard: Validate pointer accesses';
Categories: [ocBCB, ocCodeGuard, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'CGLinkCGLib';
AssumedTypeKind: tkEnumeration;
Description: 'CGLinkCGLib';
Categories: [ocBCB, ocCodeGuard, ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LinkCaseSensitiveLink';
AssumedTypeKind: tkEnumeration;
Description: 'Case-insensitive linking';
Categories: [ocBCB, ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LinkCalculateChecksum';
AssumedTypeKind: tkEnumeration;
Description: 'Calculate PE header checksum';
Categories: [ocBCB, ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LinkFastTLS';
AssumedTypeKind: tkEnumeration;
Description: 'Use fast TLS support';
Categories: [ocBCB, ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LinkReplaceResources';
AssumedTypeKind: tkEnumeration;
Description: 'Replace resources';
Categories: [ocBCB, ocLinker];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LinkUserMajor';
AssumedTypeKind: tkInteger;
Description: 'User major version (PE header)';
Categories: [ocBCB, ocLinker];
Translator: GxIntegerOptionTranslator;
),
(
Name: 'LinkUserMinor';
AssumedTypeKind: tkInteger;
Description: 'User minor version (PE header)';
Categories: [ocBCB, ocLinker];
Translator: nil;
),
(
Name: 'LinkImageComment';
AssumedTypeKind: StringType;
Description: 'Image comment';
Categories: [ocBCB, ocLinker];
Translator: GxStringOptionTranslator;
),
( // 180
Name: 'LinkDelayLoad';
AssumedTypeKind: StringType;
Description: 'Delay-loaded DLLs';
Categories: [ocBCB, ocLinker];
Translator: GxStringOptionTranslator;
),
(
Name: 'TreatEnumsAsInts';
AssumedTypeKind: tkEnumeration;
Description: 'Treat enums as integers';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
( // 182
Name: 'ListFile';
AssumedTypeKind: StringType;
Description: 'ListFile';
Categories: [ocTASM, ocUnknown];
Translator: nil;
),
(
Name: 'EnvVars';
AssumedTypeKind: tkClass;
Description: 'Environment variabes';
Categories: [ocIde];
Translator: nil;
),
(
Name: 'SysVars';
AssumedTypeKind: tkClass;
Description: 'System defined variabes';
Categories: [ocIde];
Translator: nil;
),
(
Name: 'Launcher';
AssumedTypeKind: StringType;
Description: 'Launcher application to run (console) process (Kylix)';
Categories: [ocDebugger];
Translator: nil;
),
(
Name: 'UseLauncher';
AssumedTypeKind: tkENumeration;
Description: 'Use launcher application to run (console) process (Kylix)';
Categories: [ocDebugger];
Translator: GxBoolOptionTranslator;
),
(
Name: 'DebugCWD';
AssumedTypeKind: StringType;
Description: 'Current working directory for debugged process';
Categories: [ocDebugger];
Translator: nil;
),
(
Name: 'RemoteLauncher';
AssumedTypeKind: StringType;
Description: 'Remote launcher (Kylix)';
Categories: [ocDebugger];
Translator: nil;
),
(
Name: 'RemoteCWD';
AssumedTypeKind: StringType;
Description: 'Current working directory on remote host for debugged process (Kylix)';
Categories: [ocDebugger];
Translator: nil;
),
(
Name: 'ResourceReserve';
AssumedTypeKind: tkInteger;
Description: 'Resource reserve address space (Kylix)';
Categories: [ocCompiler];
Translator: nil;
),
(
Name: 'SOName';
AssumedTypeKind: StringType;
Description: 'Shared object name';
Categories: [ocLinker];
Translator: nil;
),
(
Name: 'SOPrefix';
AssumedTypeKind: StringType;
Description: 'Shared object prefix';
Categories: [ocLinker];
Translator: nil;
),
(
Name: 'SOPrefixDefined';
AssumedTypeKind: tkEnumeration;
Description: 'Shared object prexix is defined';
Categories: [ocLinker];
Translator: nil;
),
(
Name: 'SOSuffix';
AssumedTypeKind: StringType;
Description: 'Shared object suffix';
Categories: [ocLinker];
Translator: nil;
),
(
Name: 'SOVersion';
AssumedTypeKind: StringType;
Description: 'Shared object version';
Categories: [ocLinker];
Translator: nil;
),
(
Name: 'DynamicLoader';
AssumedTypeKind: StringType;
Description: 'Dynamic loader';
Categories: [ocLinker];
Translator: nil;
),
(
Name: 'ForceCppCompile';
AssumedTypeKind: tkEnumeration;
Description: 'Force C++ compilation';
Categories: [ocBCB, ocCompiler];
Translator: nil;
),
(
Name: 'PICCodeGen';
AssumedTypeKind: tkEnumeration;
Description: 'Position independent code generation';
Categories: [ocLinker, ocCompiler];
Translator: nil;
),
(
Name: 'NamespacePrefix';
AssumedTypeKind: StringType;
Description: 'Namespace prefix';
Categories: [ocCompiler];
Translator: nil;
),
(
Name: 'WarnSymbolDeprecated';
AssumedTypeKind: tkInteger;
Description: 'Warn on deprecated symbol';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnSymbolLibrary';
AssumedTypeKind: tkInteger;
Description: 'Warn on library-specific symbol';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnSymbolPlatform';
AssumedTypeKind: tkInteger;
Description: 'Warn on platform-specific symbol';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnUnitLibrary';
AssumedTypeKind: tkInteger;
Description: 'Warn on library-specific unit';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnUnitPlatform';
AssumedTypeKind: tkInteger;
Description: 'Warn on platform-specific unit';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnUnitDeprecated';
AssumedTypeKind: tkInteger;
Description: 'Warn on deprecated unit';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnHresultCompat';
AssumedTypeKind: tkInteger;
Description: 'Warn on HResult compatibility';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnHidingMember';
AssumedTypeKind: tkInteger;
Description: 'Warn on hiding member';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnHiddenVirtual';
AssumedTypeKind: tkInteger;
Description: 'Warn on hidden virtual';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnGarbage';
AssumedTypeKind: tkInteger;
Description: 'Warn on garbage after "end."';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnBoundsError';
AssumedTypeKind: tkInteger;
Description: 'Warn on bounds error';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnZeroNilCompat';
AssumedTypeKind: tkInteger;
Description: 'Warn on 0/nil compatibility';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnStringConstTrunced';
AssumedTypeKind: tkInteger;
Description: 'Warn on string constant truncation';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnForLoopVarVarpar';
AssumedTypeKind: tkInteger;
Description: 'Warn on for loop variable passed as var parameter';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnTypedConstVarpar';
AssumedTypeKind: tkInteger;
Description: 'Warn on typed constant passed as var parameter';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnAsgToTypedConst';
AssumedTypeKind: tkInteger;
Description: 'Warn on assignment to typed constant';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnCaseLabelRange';
AssumedTypeKind: tkInteger;
Description: 'Warn on case label range';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnForVariable';
AssumedTypeKind: tkInteger;
Description: 'Warn on for loop variable type';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnConstructingAbstract';
AssumedTypeKind: tkInteger;
Description: 'Warn on constructing a class with abstract members';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnComparisonFalse';
AssumedTypeKind: tkInteger;
Description: 'Warn on comparisons that always evaluate to False';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnComparisonTrue';
AssumedTypeKind: tkInteger;
Description: 'Warn on comparisons that always evaluate to True';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnComparingSignedUnsigned';
AssumedTypeKind: tkInteger;
Description: 'Warn on comparing signed/unsigned numbers';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnCombiningSignedUnsigned';
AssumedTypeKind: tkInteger;
Description: 'Warn on combining signed/unsigned numbers';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnUnsupportedConstruct';
AssumedTypeKind: tkInteger;
Description: 'Warn on unsupported language constructs';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnFileOpen';
AssumedTypeKind: tkInteger;
Description: 'Warn on file not found';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnFileOpenUnitsrc';
AssumedTypeKind: tkInteger;
Description: 'Warn on unit not found';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnBadGlobalSymbol';
AssumedTypeKind: tkInteger;
Description: 'Warn on bad global symbol';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnDuplicateCtorDtor';
AssumedTypeKind: tkInteger;
Description: 'Warn on duplicate construtor/destructor';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnInvalidDirective';
AssumedTypeKind: tkInteger;
Description: 'Warn on invalid directive';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnPackageNoLink';
AssumedTypeKind: tkInteger;
Description: 'Warn on package not being linked due to -J';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnPackagedThreadvar';
AssumedTypeKind: tkInteger;
Description: 'Warn on usage of package threadvar externally';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnImplicitImport';
AssumedTypeKind: tkInteger;
Description: 'Warn on implicit unit import';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnHppemitIgnored';
AssumedTypeKind: tkInteger;
Description: 'Warn on HPPEMIT ignored';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnNoRetval';
AssumedTypeKind: tkInteger;
Description: 'Warn on unassigned function result';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnUseBeforeDef';
AssumedTypeKind: tkInteger;
Description: 'Warn on uninitialized variable';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnForLoopVarUndef';
AssumedTypeKind: tkInteger;
Description: 'Warn on for loop variable undefined after loop';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnUnitNameMismatch';
AssumedTypeKind: tkInteger;
Description: 'Warn on unit name mismatch';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnNoCfgFileFound';
AssumedTypeKind: tkInteger;
Description: 'Warn on coniguration file missing';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnMessageDirective';
AssumedTypeKind: tkInteger;
Description: 'Warn on user messages';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnImplicitVariants';
AssumedTypeKind: tkInteger;
Description: 'Warn on implicit Variants unit usage';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnUnicodeToLocale';
AssumedTypeKind: tkInteger;
Description: 'Warn on conversion from unicode to locale charset';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnLocaleToUnicode';
AssumedTypeKind: tkInteger;
Description: 'Warn on conversion from locale string to unicode';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnImagebaseMultiple';
AssumedTypeKind: tkInteger;
Description: 'Warn on incorrect ImageBase setting';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnSuspiciousTypecast';
AssumedTypeKind: tkInteger;
Description: 'Warn on suspicious typecast';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnPrivatePropaccessor';
AssumedTypeKind: tkInteger;
Description: 'Warn on private propertry accessors';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnUnsafeType';
AssumedTypeKind: tkInteger;
Description: 'Warn on .NET unsafe type';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnUnsafeCode';
AssumedTypeKind: tkInteger;
Description: 'Warn on .NET unsafe code';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
( // 247
Name: 'WarnUnsafeCast';
AssumedTypeKind: tkInteger;
Description: 'Warn on .NET unsafe typecast';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'GenDOC';
AssumedTypeKind: tkEnumeration;
Description: 'GenDOC';
Categories: [ocCompiler];
Translator: nil;
),
(
Name: 'WarnSymbolExperimental';
AssumedTypeKind: tkInteger;
Description: 'Warn on experimental symbols';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnUnitExperimental';
AssumedTypeKind: tkInteger;
Description: 'Warn on experimental units';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
( // 251
Name: 'DefaultNamespace';
AssumedTypeKind: StringType;
Description: 'Default namespace';
Categories: [ocCompiler];
Translator: GxStringOptionTranslator;
),
(
Name: 'AutoRegisterTLB';
AssumedTypeKind: tkEnumeration;
Description: 'Auto-register type libraries';
Categories: [ocUnknown];
Translator: GxBoolOptionTranslator;
),
(
Name: 'AutoGenImportAssembly';
AssumedTypeKind: tkEnumeration;
Description: 'Auto-generate import assembly';
Categories: [ocUnknown];
Translator: GxBoolOptionTranslator;
),
(
Name: 'AspNetLaunchBrowser';
AssumedTypeKind: tkEnumeration;
Description: 'AspNetLaunchBrowser';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'AspNetUseHostServer';
AssumedTypeKind: tkEnumeration;
Description: 'AspNetUseHostServer';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'AspNetStartPage';
AssumedTypeKind: StringType;
Description: 'AspNetStartPage';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'AspNetHostServer';
AssumedTypeKind: StringType;
Description: 'AspNetHostServer';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'AspNetIISVirtualDirectory';
AssumedTypeKind: StringType;
Description: 'AspNetIISVirtualDirectory';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'AspNetHTTPAddress';
AssumedTypeKind: StringType;
Description: 'AspNetHTTPAddress';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'AspNetCassiniVirtualDirectory';
AssumedTypeKind: StringType;
Description: 'AspNetCassiniVirtualDirectory';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'DebugInformation';
AssumedTypeKind: tkEnumeration;
Description: 'DebugInformation';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'Overflow';
AssumedTypeKind: tkEnumeration;
Description: 'Overflow';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'Unsafe';
AssumedTypeKind: tkEnumeration;
Description: 'Unsafe';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'WarningAsError';
AssumedTypeKind: tkEnumeration;
Description: 'WarningAsError';
Categories: [ocCompiler, ocWarnings];
Translator: GxStringOptionTranslator;
),
(
Name: 'TargetName';
AssumedTypeKind: StringType;
Description: 'TargetName';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'TargetType';
AssumedTypeKind: tkEnumeration;
Description: 'TargetType';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'Main';
AssumedTypeKind: StringType;
Description: 'Main';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'BaseAddr';
AssumedTypeKind: tkInteger;
Description: 'BaseAddr';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'BuildInOutput';
AssumedTypeKind: tkEnumeration;
Description: 'BuildInOutput';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'AppIcon';
AssumedTypeKind: StringType;
Description: 'AppIcon';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'Warning';
AssumedTypeKind: tkInteger;
Description: 'Warning';
Categories: [ocWarnings];
Translator: GxStringOptionTranslator;
),
(
Name: 'Incremental';
AssumedTypeKind: tkEnumeration;
Description: 'Incremental';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
( // 273
Name: 'DocFile';
AssumedTypeKind: StringType;
Description: 'DocFile';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'SymTabs';
AssumedTypeKind: tkClass;
Description: 'SymTabs';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'RemoteParams';
AssumedTypeKind: StringType;
Description: 'RemoteParams';
Categories: [ocDebugger];
Translator: GxStringOptionTranslator;
),
(
Name: 'UseRemoteLauncher';
AssumedTypeKind: tkEnumeration;
Description: 'UseRemoteLauncher';
Categories: [ocDebugger];
Translator: GxBoolOptionTranslator;
),
(
Name: 'LoadAllSymbols';
AssumedTypeKind: tkEnumeration;
Description: 'LoadAllSymbols';
Categories: [ocDebugger];
Translator: GxBoolOptionTranslator;
),
(
Name: 'SymbolSearchPath';
AssumedTypeKind: StringType;
Description: 'SymbolSearchPath';
Categories: [ocFolders];
Translator: GxStringOptionTranslator;
),
(
Name: 'PasCodepage';
AssumedTypeKind: StringType;
Description: 'PasCodepage';
Categories: [ocIDE];
Translator: GxStringOptionTranslator;
),
(
Name: 'LoadUnspecifiedSymbols';
AssumedTypeKind: tkEnumeration;
Description: 'Load unspecified symbols';
Categories: [ocDebugger];
Translator: GxBoolOptionTranslator;
),
(
Name: 'GenHpp';
AssumedTypeKind: tkEnumeration;
Description: 'Generate C++ .hpp files';
Categories: [ocBCB, ocCompiler];
Translator: GxBoolOptionTranslator;
),
(
Name: 'PasPlatform';
AssumedTypeKind: tkEnumeration;
Description: 'PasPlatform';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'SignAssembly';
AssumedTypeKind: tkEnumeration;
Description: 'SignAssembly';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'DelaySign';
AssumedTypeKind: tkEnumeration;
Description: 'DelaySign';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'KeyFile';
AssumedTypeKind: StringType;
Description: 'KeyFile';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'KeyContainer';
AssumedTypeKind: StringType;
Description: 'KeyContainer';
Categories: [ocUnknown];
Translator: GxStringOptionTranslator;
),
(
Name: 'WarnOptionTruncated';
AssumedTypeKind: tkInteger;
Description: 'WarnOptionTruncated';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnWideCharReduced';
AssumedTypeKind: tkInteger;
Description: 'WarnWideCharReduced';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnDuplicatesIgnored';
AssumedTypeKind: tkInteger;
Description: 'WarnDuplicatesIgnored';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnInitSeq';
AssumedTypeKind: tkInteger;
Description: 'WarnInitSeq';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnLocalPInvoke';
AssumedTypeKind: tkInteger;
Description: 'WarnLocalPInvoke';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnXMLWhitespaceNotAllowed';
AssumedTypeKind: tkInteger;
Description: 'WarnXMLWhitespaceNotAllowed';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnXMLUnknownEntity';
AssumedTypeKind: tkInteger;
Description: 'WarnXMLUnknownEntity';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnXMLInvalidNameStart';
AssumedTypeKind: tkInteger;
Description: 'WarnXMLInvalidNameStart';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnXMLInvalidName';
AssumedTypeKind: tkInteger;
Description: 'WarnXMLInvalidName';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnXMLExpectedCharacter';
AssumedTypeKind: tkInteger;
Description: 'WarnXMLExpectedCharacter';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnXMLCREFNoResolve';
AssumedTypeKind: tkInteger;
Description: 'WarnXMLCREFNoResolve';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnXMLNoParm';
AssumedTypeKind: tkInteger;
Description: 'WarnXMLNoParm';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
( // 299
Name: 'WarnXMLNoMatchingParm';
AssumedTypeKind: tkInteger;
Description: 'WarnXMLNoMatchingParm';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnTypeInfoImplicitlyAdded';
AssumedTypeKind: tkInteger;
Description: 'WarnTypeInfoImplicitlyAdded';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnImplicitStringCast';
AssumedTypeKind: tkInteger;
Description: 'WarnImplicitStringCast';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnImplicitStringCastLoss';
AssumedTypeKind: tkInteger;
Description: 'WarnImplicitStringCastLoss';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnExplicitStringCast';
AssumedTypeKind: tkInteger;
Description: 'WarnExplicitStringCast';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
( // 304
Name: 'WarnExplicitStringCastLoss';
AssumedTypeKind: tkInteger;
Description: 'WarnExplicitStringCastLoss';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnRLinkWarning';
AssumedTypeKind: tkInteger;
Description: 'WarnRLinkWarning';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnCvtWCharToAChar';
AssumedTypeKind: tkInteger;
Description: 'Warn on conversions from WideChar to AnsiChar';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnCvtNarrowingStringLost';
AssumedTypeKind: tkInteger;
Description: 'WarnCvtNarrowingStringLost';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnCvtACharToWChar';
AssumedTypeKind: tkInteger;
Description: 'Warn on conversions from AnsiChar to WideChar';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
( // 309
Name: 'WarnCvtWideningStringLost';
AssumedTypeKind: tkInteger;
Description: 'WarnCvtWideningStringLost';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnNonPortableTypecast';
AssumedTypeKind: tkInteger;
Description: 'WarnNonPortableTypecast';
Categories: [ocWarnings];
Translator: GxBoolOptionTranslator;
),
(
Name: 'WarnImmutableStrings';
AssumedTypeKind: tkInteger;
Description: 'WarnImmutableStrings';
Categories: [ocWarnings];
Translator: GxStringOptionTranslator;
)
);
function GetOptionDescription(const OptionName: string): string;
function GetOptionTranslator(const OptionName: string): TGxOptionValueTranslator;
function GetOptionCategories(const OptionName: string): TGxOptionCategorySet;
function TranslatedValue(const OptionName, OptionValue: string): string;
function CategoryTextToCategory(const CatText: string): TGxOptionCategory;
function OptionIsAppropriateForIde(const OptionCategories: TGxOptionCategorySet): Boolean;
function OptionCategoryIsAppropriateForIde(const OptionCategory: TGxOptionCategory): Boolean;
implementation
uses
SysUtils, GX_OtaUtils, GX_IdeUtils;
function GetOptionDescription(const OptionName: string): string;
var
i: Integer;
begin
Result := '';
for i := Low(GxOptionsMap) to High(GxOptionsMap) do
if SameText(OptionName, GxOptionsMap[i].Name) then
begin
Result := GxOptionsMap[i].Description;
Break;
end;
end;
function GetOptionTranslator(const OptionName: string): TGxOptionValueTranslator;
var
i: Integer;
begin
Result := nil;
for i := Low(GxOptionsMap) to High(GxOptionsMap) do
if SameText(OptionName, GxOptionsMap[i].Name) then
begin
Result := GxOptionsMap[i].Translator;
Break;
end;
end;
function GetOptionCategories(const OptionName: string): TGxOptionCategorySet;
var
i: Integer;
begin
Result := [];
for i := Low(GxOptionsMap) to High(GxOptionsMap) do
if SameText(OptionName, GxOptionsMap[i].Name) then
begin
Result := GxOptionsMap[i].Categories;
Break;
end;
end;
function TranslatedValue(const OptionName, OptionValue: string): string;
var
Xlator: TGxOptionValueTranslator;
begin
Result := OptionValue;
Xlator := GetOptionTranslator(OptionName);
if Assigned(Xlator) then
Result := Xlator(OptionValue);
end;
function CategoryTextToCategory(const CatText: string): TGxOptionCategory;
var
i: TGxOptionCategory;
begin
Result := ocUnknown; // default to Unknown category
for i := Low(GxOptionsCategoryText) to High(GxOptionsCategoryText) do
if SameText(CatText, GxOptionsCategoryText[i]) then
begin
Result := i;
Break;
end;
end;
function OptionIsAppropriateForIde(const OptionCategories: TGxOptionCategorySet): Boolean;
begin
Result := True;
if not GxOtaHaveCPPSupport then
begin
Result := Result and not (ocTasm in OptionCategories);
Result := Result and not (ocTLib in OptionCategories);
Result := Result and not (ocATL in OptionCategories);
Result := Result and not (ocCodeGuard in OptionCategories);
if ocBCB in OptionCategories then
Result := Result and (ocDelphi in OptionCategories);
end;
end;
function OptionCategoryIsAppropriateForIde(const OptionCategory: TGxOptionCategory): Boolean;
const
DelphiOptions = GxAllOptions - GxCppOptions;
var
AppropriateOptions: TGxOptionCategorySet;
begin
AppropriateOptions := [];
if GxOtaHaveCPPSupport then
AppropriateOptions := GxCppOptions;
if GxOtaHaveDelphiSupport then
AppropriateOptions := AppropriateOptions + DelphiOptions;
if not RunningDelphi7OrGreater then
Exclude(AppropriateOptions, ocWarnings);
Result := OptionCategory in AppropriateOptions;
end;
//
// Beginning of translators
//
resourcestring
SCannotTranslateAppendix = ' - cannot translate';
function GxBoolOptionTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := 'False'
else if ValueString = '1' then
Result := 'True'
else if ValueString = '-1' then // Used for 'UsePackages' etc.
Result := 'True'
else if SameText(ValueString, 'True') then
Result := 'True'
else if SameText(ValueString, 'False') then
Result := 'False'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxStringOptionTranslator(const ValueString: string): string;
begin
Result := ValueString;
end;
function GxIntegerOptionTranslator(const ValueString: string): string;
begin
Result := ValueString;
end;
function GxHexOptionTranslator(const ValueString: string): string;
begin
Result := Format(GxOtaGetHexPrefix + '%x', [StrToIntDef(ValueString, 0)]);
end;
function GxProcInstructTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := '386'
else if ValueString = '1' then
Result := '486'
else if ValueString = '2' then
Result := '586'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxAlignmentTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := '1'
else if ValueString = '1' then
Result := '2'
else if ValueString = '2' then
Result := '4'
else if ValueString = '3' then
Result := '8'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxCallConvTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := 'cdecl'
else if ValueString = '1' then
Result := 'register'
else if ValueString = '2' then
Result := 'Pascal'
else if ValueString = '3' then
Result := 'stdcall'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxRegVarTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := 'none'
else if ValueString = '1' then
Result := 'auto'
else if ValueString = '2' then
Result := 'register'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxMemberPointerTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := 'All cases'
else if ValueString = '1' then
Result := 'MI'
else if ValueString = '2' then
Result := 'SI'
else if ValueString = '3' then
Result := 'Smallest'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxVTableTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := 'Smart'
else if ValueString = '1' then
Result := 'local'
else if ValueString = '2' then
Result := 'external'
else if ValueString = '3' then
Result := 'public'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxAtlInstancingTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := 'Single use'
else if ValueString = '1' then
Result := 'Multiple use'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxAtlCoinitTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := 'Apartment Threaded'
else if ValueString = '1' then
Result := 'Multi-Threaded'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxAtlThreadTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := 'Single'
else if ValueString = '1' then
Result := 'Apartment'
else if ValueString = '2' then
Result := 'Free'
else if ValueString = '3' then
Result := 'Both'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxTasmExpTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := 'Normal listing'
else if ValueString = '1' then
Result := 'Expanded listing'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxMapFileTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := 'Off'
else if ValueString = '1' then
Result := 'Segments'
else if ValueString = '2' then
Result := 'Publics'
else if ValueString = '3' then
Result := 'Detailed'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxReferenceInfoTranslator(const ValueString: string): string;
begin
if ValueString = '0' then
Result := 'Off'
else if ValueString = '1' then
Result := 'On, definitions only'
else if ValueString = '2' then
Result := 'On, with usage information'
else
Result := ValueString + SCannotTranslateAppendix;
end;
function GxVerInfoModuleAttribTranslator(const ValueString: string): string;
begin
// Debug build, Pre-release, DLL, Special build, Private build
// VERSIONINFO module attributes don't make it through in D5/6/7
Result := ValueString;
// TODO 4 -oAnyone -cFeature: Implement version info attribute translators
end;
end.
|
unit uVerificarLiberacao;
interface
uses IdHTTP, vcl.Forms, System.SysUtils, vcl.Dialogs, StrUtils;
function getValidadeSistema(serial: string): Boolean;
implementation
const
RADIUS_URL_LIBERACAO = 'http://radius.tudosobre.info/liberacao';
RADIUS_ARQUIVO_WEB_LIBERACAO = 'liberacao.php';
RADIUS_CODIGO_GET = 'SERIAL';
RADIUS_WEB_SERVICE = RADIUS_URL_LIBERACAO + '/' + RADIUS_ARQUIVO_WEB_LIBERACAO
+ '?' + RADIUS_CODIGO_GET + '=';
function getRetornoWebservice(serial: string): string;
var
httpRetorno: TidHttp;
begin
try
httpRetorno := TidHttp.Create(Application);
try
Result := httpRetorno.Get(RADIUS_WEB_SERVICE + serial);
finally
FreeAndNil(httpRetorno);
end;
except
ShowMessage('Erro de conexão!' + #13 +
'Verifica sua internet para poder liberar o sistema!');
end;
end;
function getValidadeSistema(serial: string): Boolean;
var
retornoCompleto: string;
validade: TDate;
status: string;
acesso: Boolean;
begin
Result := False;
retornoCompleto := getRetornoWebservice(serial);
try
status := Copy(retornoCompleto, 12, 14);
case AnsiIndexStr(UpperCase(status), ['SISTEMA_VALIDO', 'ULTIMO_DIA_PER',
'SISTEMA_EXPIRA']) of
0:
begin
validade := StrToDate(Copy(retornoCompleto, 1, 10));
acesso := True;
end;
1:
begin
validade := StrToDate(Copy(retornoCompleto, 1, 10));
acesso := True;
end;
2:
begin
validade := StrToDate(Copy(retornoCompleto, 1, 10));
acesso := False;
ShowMessage('Sistema com validade expirada!');
// Application.Terminate;
end;
else
acesso := False;
ShowMessage('Erro ao verificar liberação do sistema!');
// Application.Terminate;
end;
Result := acesso;
except
ShowMessage('Erro ao verificar liberação do sistema!');
Application.Terminate;
end;
end;
end.
|
unit eInterestSimulator.Controller.Resultado.Observer;
interface
uses
eInterestSimulator.Controller.Observer.Interfaces,
eInterestSimulator.Model.Interfaces, System.Generics.Collections;
type
TControllerObserverResultado = class(TInterfacedObject, iSubjectResultado)
private
FObserverResultados: TList<iObserverResultado>;
public
constructor Create;
destructor Destroy; override;
class function New: iSubjectResultado;
function Add(Value: iObserverResultado): iSubjectResultado;
function Notify(Value: Tlist<iResultado>): iSubjectResultado;
end;
implementation
uses
System.SysUtils;
{ TControllerObserverResultado }
function TControllerObserverResultado.Add(
Value: iObserverResultado): iSubjectResultado;
begin
Result := Self;
FObserverResultados.Add(Value);
end;
constructor TControllerObserverResultado.Create;
begin
FObserverResultados := TList<iObserverResultado>.Create;
end;
destructor TControllerObserverResultado.Destroy;
begin
FreeAndNil(FObserverResultados);
inherited;
end;
class function TControllerObserverResultado.New: iSubjectResultado;
begin
Result := Self.Create;
end;
function TControllerObserverResultado.Notify(Value: Tlist<iResultado>): iSubjectResultado;
var
I: Integer;
begin
Result := Self;
for I := 0 to Pred(FObserverResultados.Count) do
FObserverResultados[I].UpdateResultado(Value);
end;
end.
|
//************************************************
//*
//* Поиск минимума функции нескольких переменных
//*
//* Что-то вроде градиентного спуска
//*
//************************************************
unit Minimize;
interface
uses Math;
type
TDoubleFunction=function:Double;
PDouble=^Double;
procedure MinimizeFunc(Func:TDoubleFunction;
X:array of PDouble; const Xmin,Xmax:array of Double;
Epsilon:Double; MaxIterations:Integer=1 shl 12);
implementation
procedure MinimizeFunc;
var
i,Count:Integer;
Min,Value,Tmp,StepLen,Alpha:Double;
Step,OldX:array of Double;
Iteration:LongInt;
Flag:Boolean;
h:Double;
begin
Count:=Length(X);
SetLength(Step,Count);
SetLength(OldX,Count);
Flag:=True;
Min:=1.7E+308;
{ Откуда считать, ищем Монте-Карлом :) }
for Iteration:=0 to MaxIterations div 2 do begin
for i:=0 to Count-1 do X[i]^:=Xmin[i]+Random*(Xmax[i]-Xmin[i]);
Value:=Func;
if {IsAN(Value) and} (Flag or (Value<Min)) then begin
for i:=0 to Count-1 do OldX[i]:=X[i]^;
Min:=Value;
Flag:=False;
end;
end;
if Flag
then for i:=0 to Count-1 do OldX[i]:=0;
{Поехали}
for i:=0 to Count-1 do X[i]^:=OldX[i];
// Value:=Min;
{Счетчик итераций предназначен на случай зацикливания}
Iteration:=MaxIterations;
{Первоначальная длина шага}
Alpha:=1;
repeat
Dec(Iteration);
{Приближенное вычисление градиента (что-то вроде направления шага)}
StepLen:=0;
for i:=0 to Count-1 do begin
h:=(Xmax[i]-Xmin[i])*0.01*Alpha;
OldX[i]:=X[i]^; X[i]^:=OldX[i]+h;
Value:=Func;
if Min<>Value
then Tmp:=h/(Min-Value)
else Tmp:=h;
StepLen:=StepLen+Tmp*Tmp;
Step[i]:=Tmp;
X[i]^:=OldX[i];
end;
StepLen:=Sqrt(StepLen);
{Делаем шаг}
for i:=0 to Count-1 do begin
Tmp:=X[i]^+Step[i]*Alpha;
if Tmp<Xmin[i] then Tmp:=Xmin[i]
else if Xmax[i]<Tmp then Tmp:=Xmax[i];
X[i]^:=Tmp;
end;
{Вычисляем значение функции после шага}
Value:=Func;
if {IsAN(Value) and} (Value<Min)
then Min:=Value
else begin {undo step}
for i:=0 to Count-1 do X[i]^:=OldX[i];
Alpha:=0.618*Alpha;
end;
{Если увеличилось, то поворачиваем назад и уменьшаем длину шага}
{Пока длина шага не станет очень маленькой или
не превысится допустимое число итераций}
until (Alpha*StepLen<Epsilon)or(Iteration<=0);
for i:=0 to Count-1 do if Step[i]=0 then X[i]^:=0;
end;
end.
|
(*
Challenge 120
TASK #1 - Swap Odd/Even bits
Submitted by: Mohammad S Anwar
You are given a positive integer $N less than or equal to 255.
Write a script to swap the odd positioned bit with even positioned bit and
print the decimal equivalent of the new binary representation.
Example
Input: $N = 101
Output: 154
Binary representation of the given number is 01 10 01 01.
The new binary representation after the odd/even swap is 10 01 10 10.
The decimal equivalent of 10011010 is 154.
Input: $N = 18
Output: 33
Binary representation of the given number is 00 01 00 10.
The new binary representation after the odd/even swap is 00 10 00 01.
The decimal equivalent of 100001 is 33.
*)
program ch1(input, output);
uses sysutils;
function swapBits(n: Integer): Integer;
var
result, shift: Integer;
begin
result := 0;
shift := 1;
while n > 0 do begin
if (n mod 2) <> 0 then result := result + 2*shift;
n := n div 2;
if (n mod 2) <> 0 then result := result + 1*shift;
n := n div 2;
shift := shift*4;
end;
swapBits := result;
end;
var
n: Integer;
begin
n := StrToInt(paramStr(1));
n := swapBits(n);
WriteLn(n);
end.
|
unit MemManeger;
interface
function SysGetMem(size: Integer): Pointer;
function SysFreeMem(p: Pointer): Integer;
function SysReallocMem(p: Pointer; size: Integer): Pointer;
function GetAllocMemCount: Integer;
function GetAllocMemSize: Integer;
procedure DumpBlocks;
function GetHeapStatus: THeapStatus;
function SaveToDisk(FileName: pchar): boolean;
function LoadFromDisk(FileName: pchar): boolean;
// Fuciones para el Explorer....
function GetspaceRoot: pointer;
function GetdecommittedRoot: pointer;
function GetcommittedRoot: pointer;
function Get_avail : pointer;
function Get_rover : pointer;
function Get_remBytes : Integer;
function Get_curAlloc : pointer;
function Get_smallTab : pointer;
implementation
uses
windows;
const
kernel = 'kernel32.dll';
type
DWORD = Integer;
BOOL = LongBool;
TRTLCriticalSection =
packed record
DebugInfo: Pointer;
LockCount: Longint;
RecursionCount: Longint;
OwningThread: Integer;
LockSemaphore: Integer;
Reserved: DWORD;
end;
var
Null : pointer = nil;
IsMultiThread : boolean = true;
(*
const
LMEM_FIXED = 0;
LMEM_ZEROINIT = $40;
MEM_COMMIT = $1000;
MEM_RESERVE = $2000;
MEM_DECOMMIT = $4000;
MEM_RELEASE = $8000;
PAGE_NOACCESS = 1;
PAGE_READWRITE = 4;
CREATE_NEW = 1;
CREATE_ALWAYS = 2;
OPEN_EXISTING = 3;
OPEN_ALWAYS = 4;
TRUNCATE_EXISTING = 5;
GENERIC_READ = DWORD($80000000);
GENERIC_WRITE = $40000000;
GENERIC_EXECUTE = $20000000;
GENERIC_ALL = $10000000;
FILE_SHARE_READ = $00000001;
FILE_SHARE_WRITE = $00000002;
FILE_SHARE_DELETE = $00000004;
FILE_ATTRIBUTE_READONLY = $00000001;
FILE_ATTRIBUTE_HIDDEN = $00000002;
FILE_ATTRIBUTE_SYSTEM = $00000004;
FILE_ATTRIBUTE_DIRECTORY = $00000010;
FILE_ATTRIBUTE_ARCHIVE = $00000020;
FILE_ATTRIBUTE_NORMAL = $00000080;
FILE_ATTRIBUTE_TEMPORARY = $00000100;
FILE_ATTRIBUTE_COMPRESSED = $00000800;
FILE_ATTRIBUTE_OFFLINE = $00001000;
FILE_NOTIFY_CHANGE_FILE_NAME = $00000001;
FILE_NOTIFY_CHANGE_DIR_NAME = $00000002;
FILE_NOTIFY_CHANGE_ATTRIBUTES = $00000004;
FILE_NOTIFY_CHANGE_SIZE = $00000008;
FILE_NOTIFY_CHANGE_LAST_WRITE = $00000010;
FILE_NOTIFY_CHANGE_LAST_ACCESS = $00000020;
FILE_NOTIFY_CHANGE_CREATION = $00000040;
FILE_NOTIFY_CHANGE_SECURITY = $00000100;
function CreateFile(lpFileName: PChar; dwDesiredAccess, dwShareMode: DWORD; lpSecurityAttributes: pointer; dwCreationDisposition,
dwFlagsAndAttributes: DWORD; hTemplateFile: integer): integer; stdcall; external kernel;
function WriteFile(hFile: integer; const Buffer; nNumberOfBytesToWrite: DWORD; var lpNumberOfBytesWritten: DWORD; lpOverlapped: pointer): BOOL;
stdcall; external kernel;
function ReadFile(hFile: integer; var Buffer; nNumberOfBytesToRead: DWORD; var lpNumberOfBytesRead: DWORD; lpOverlapped: pointer): BOOL;
stdcall; external kernel;
function CloseHandle(hObject: integer): BOOL; stdcall; external kernel;
*)
function LocalAlloc(flags, size: Integer): Pointer; stdcall; external kernel name 'LocalAlloc';
function LocalFree(addr: Pointer): Pointer; stdcall; external kernel name 'LocalFree';
function VirtualAlloc(lpAddress: Pointer; dwSize, flAllocationType, flProtect: DWORD): Pointer; stdcall; external kernel name 'VirtualAlloc';
function VirtualFree(lpAddress: Pointer; dwSize, dwFreeType: DWORD): BOOL; stdcall; external kernel name 'VirtualFree';
procedure InitializeCriticalSection(var lpCriticalSection: TRTLCriticalSection); stdcall; external kernel name 'InitializeCriticalSection';
procedure EnterCriticalSection(var lpCriticalSection: TRTLCriticalSection); stdcall; external kernel name 'EnterCriticalSection';
procedure LeaveCriticalSection(var lpCriticalSection: TRTLCriticalSection); stdcall; external kernel name 'LeaveCriticalSection';
procedure DeleteCriticalSection(var lpCriticalSection: TRTLCriticalSection); stdcall; external kernel name 'DeleteCriticalSection';
// Common Data structure:
type
TBlock = packed record
addr: PChar;
size: Integer;
end;
// Heap error codes
const
cHeapOk = 0; // everything's fine
cReleaseErr = 1; // operating system returned an error when we released
cDecommitErr = 2; // operating system returned an error when we decommited
cBadCommittedList = 3; // list of committed blocks looks bad
cBadFiller1 = 4; // filler block is bad
cBadFiller2 = 5; // filler block is bad
cBadFiller3 = 6; // filler block is bad
cBadCurAlloc = 7; // current allocation zone is bad
cCantInit = 8; // couldn't initialize
cBadUsedBlock = 9; // used block looks bad
cBadPrevBlock = 10; // prev block before a used block is bad
cBadNextBlock = 11; // next block after a used block is bad
cBadFreeList = 12; // free list is bad
cBadFreeBlock = 13; // free block is bad
cBadBalance = 14; // free list doesn't correspond to blocks marked free
var
initialized : Boolean;
heapErrorCode : Integer;
heapLock : TRTLCriticalSection;
//
// Helper module: administrating block descriptors.
//
type
PBlockDesc = ^TBlockDesc;
TBlockDesc =
packed record
next: PBlockDesc;
prev: PBlockDesc;
addr: PChar;
size: Integer;
end;
type
PBlockDescBlock = ^TBlockDescBlock;
TBlockDescBlock =
packed record
next: PBlockDescBlock;
data: array [0..99] of TBlockDesc;
end;
var
blockDescBlockList: PBlockDescBlock;
blockDescFreeList : PBlockDesc;
function GetBlockDesc: PBlockDesc;
// Get a block descriptor.
// Will return nil for failure.
var
bd: PBlockDesc;
bdb: PBlockDescBlock;
i: Integer;
begin
if blockDescFreeList = nil
then
begin
bdb := LocalAlloc(LMEM_FIXED, sizeof(bdb^));
if bdb = nil
then
begin
result := nil;
exit;
end;
bdb.next := blockDescBlockList;
blockDescBlockList := bdb;
for i := low(bdb.data) to high(bdb.data)
do
begin
bd := @bdb.data[i];
bd.next := blockDescFreeList;
blockDescFreeList := bd;
end;
end;
bd := blockDescFreeList;
blockDescFreeList := bd.next;
result := bd;
end;
procedure MakeEmpty(bd: PBlockDesc);
begin
bd.next := bd;
bd.prev := bd;
end;
function AddBlockAfter(prev: PBlockDesc; const b: TBlock): Boolean;
var
next, bd: PBlockDesc;
begin
bd := GetBlockDesc;
if bd = nil
then result := False
else
begin
bd.addr := b.addr;
bd.size := b.size;
next := prev.next;
bd.next := next;
bd.prev := prev;
next.prev := bd;
prev.next := bd;
result := True;
end;
end;
procedure DeleteBlock(bd: PBlockDesc);
var
prev, next: PBlockDesc;
begin
prev := bd.prev;
next := bd.next;
prev.next := next;
next.prev := prev;
bd.next := blockDescFreeList;
blockDescFreeList := bd;
end;
function MergeBlockAfter(prev: PBlockDesc; const b: TBlock) : TBlock;
var
bd, bdNext: PBlockDesc;
begin
bd := prev.next;
result := b;
repeat
bdNext := bd.next;
if bd.addr + bd.size = result.addr
then
begin
DeleteBlock(bd);
result.addr := bd.addr;
inc(result.size, bd.size);
end
else
if result.addr + result.size = bd.addr
then
begin
DeleteBlock(bd);
inc(result.size, bd.size);
end;
bd := bdNext;
until bd = prev;
if not AddBlockAfter(prev, result)
then result.addr := nil;
end;
function RemoveBlock(bd: PBlockDesc; const b: TBlock): Boolean;
var
n: TBlock;
start: PBlockDesc;
begin
start := bd;
repeat
if (bd.addr <= b.addr) and (bd.addr + bd.size >= b.addr + b.size)
then
begin
if bd.addr = b.addr
then
begin
Inc(bd.addr, b.size);
Dec(bd.size, b.size);
if bd.size = 0 then
DeleteBlock(bd);
end
else
if bd.addr + bd.size = b.addr + b.size
then Dec(bd.size, b.size)
else
begin
n.addr := b.addr + b.size;
n.size := bd.addr + bd.size - n.addr;
bd.size := b.addr - bd.addr;
if not AddBlockAfter(bd, n)
then
begin
result := False;
exit;
end;
end;
result := True;
exit;
end;
bd := bd.next;
until bd = start;
result := False;
end;
//
// Address space administration:
//
const
cSpaceAlign = 64*1024;
cSpaceMin = 1024*1024;
cPageAlign = 4*1024;
var
spaceRoot: TBlockDesc;
// SpaceBegin: pointer = pointer($3600000);
function GetSpace(minSize: Integer): TBlock;
// Get at least minSize bytes address space.
// Success: returns a block, possibly much bigger than requested.
// Will not fail - will raise an exception or terminate program.
begin
if minSize < cSpaceMin
then minSize := cSpaceMin
else minSize := (minSize + (cSpaceAlign-1)) and not (cSpaceAlign-1);
result.size := minSize;
result.addr := VirtualAlloc(nil, minSize, MEM_RESERVE, PAGE_NOACCESS);
if result.addr = nil
then exit;
// inc(pchar(nil), minSize);
if not AddBlockAfter(@spaceRoot, result)
then
begin
VirtualFree(result.addr, 0, MEM_RELEASE);
result.addr := nil;
exit;
end;
end;
function GetSpaceAt(addr: PChar; minSize: Integer): TBlock;
// Get at least minSize bytes address space at addr.
// Return values as above.
// Failure: returns block with addr = nil.
begin
result.size := cSpaceMin;
result.addr := VirtualAlloc(addr, cSpaceMin, MEM_RESERVE, PAGE_READWRITE);
if result.addr = nil
then
begin
minSize := (minSize + (cSpaceAlign-1)) and not (cSpaceAlign-1);
result.size := minSize;
result.addr := VirtualAlloc(addr, minSize, MEM_RESERVE, PAGE_READWRITE);
end;
if result.addr <> nil
then
begin
if not AddBlockAfter(@spaceRoot, result)
then
begin
VirtualFree(result.addr, 0, MEM_RELEASE);
result.addr := nil;
end;
end;
end;
function FreeSpace(addr: Pointer; maxSize: Integer): TBlock;
// Free at most maxSize bytes of address space at addr.
// Returns the block that was actually freed.
var
bd, bdNext: PBlockDesc;
minAddr, maxAddr, startAddr, endAddr: PChar;
begin
minAddr := PChar($FFFFFFFF);
maxAddr := nil;
startAddr := addr;
endAddr := startAddr + maxSize;
bd := spaceRoot.next;
while bd <> @spaceRoot do
begin
bdNext := bd.next;
if (bd.addr >= startAddr) and (bd.addr + bd.size <= endAddr)
then
begin
if minAddr > bd.addr
then minAddr := bd.addr;
if maxAddr < bd.addr + bd.size
then maxAddr := bd.addr + bd.size;
if not VirtualFree(bd.addr, 0, MEM_RELEASE)
then heapErrorCode := cReleaseErr;
DeleteBlock(bd);
end;
bd := bdNext;
end;
result.addr := nil;
if maxAddr <> nil
then
begin
result.addr := minAddr;
result.size := maxAddr - minAddr;
end;
end;
function Commit(addr: Pointer; minSize: Integer): TBlock;
// Commits memory.
// Returns the block that was actually committed.
// Will return a block with addr = nil on failure.
var
bd: PBlockDesc;
loAddr, hiAddr, startAddr, endAddr: PChar;
begin
startAddr := PChar(Integer(addr) and not (cPageAlign-1));
endAddr := PChar(((Integer(addr) + minSize) + (cPageAlign-1)) and not (cPageAlign-1));
result.addr := startAddr;
result.size := endAddr - startAddr;
bd := spaceRoot.next;
while bd <> @spaceRoot do
begin
// Commit the intersection of the block described by bd and [startAddr..endAddr)
loAddr := bd.addr;
hiAddr := loAddr + bd.size;
if loAddr < startAddr
then loAddr := startAddr;
if hiAddr > endAddr
then hiAddr := endAddr;
if loAddr < hiAddr
then
begin
if VirtualAlloc(loAddr, hiAddr - loAddr, MEM_COMMIT, PAGE_READWRITE) = nil
then
begin
result.addr := nil;
exit;
end;
end;
bd := bd.next;
end;
end;
function Decommit(addr: Pointer; maxSize: Integer): TBlock;
// Decommits address space.
// Returns the block that was actually decommitted.
var
bd: PBlockDesc;
loAddr, hiAddr, startAddr, endAddr: PChar;
begin
startAddr := PChar((Integer(addr) + + (cPageAlign-1)) and not (cPageAlign-1));
endAddr := PChar((Integer(addr) + maxSize) and not (cPageAlign-1));
result.addr := startAddr;
result.size := endAddr - startAddr;
bd := spaceRoot.next;
while bd <> @spaceRoot do
begin
// Decommit the intersection of the block described by bd and [startAddr..endAddr)
loAddr := bd.addr;
hiAddr := loAddr + bd.size;
if loAddr < startAddr
then loAddr := startAddr;
if hiAddr > endAddr
then hiAddr := endAddr;
if loAddr < hiAddr
then
begin
if not VirtualFree(loAddr, hiAddr - loAddr, MEM_DECOMMIT)
then heapErrorCode := cDecommitErr;
end;
bd := bd.next;
end;
end;
//
// Committed space administration
//
const
cCommitAlign = 16*1024;
var
decommittedRoot: TBlockDesc;
function GetCommitted(minSize: Integer): TBlock;
// Get a block of committed memory.
// Returns a committed memory block, possibly much bigger than requested.
// Will return a block with a nil addr on failure.
var
bd: PBlockDesc;
begin
minSize := (minSize + (cCommitAlign-1)) and not (cCommitAlign-1);
repeat
bd := decommittedRoot.next;
while bd <> @decommittedRoot do
begin
if bd.size >= minSize
then
begin
result := Commit(bd.addr, minSize);
if result.addr = nil
then exit;
Inc(bd.addr, result.size);
Dec(bd.size, result.size);
if bd.size = 0
then DeleteBlock(bd);
exit;
end;
bd := bd.next;
end;
result := GetSpace(minSize);
if result.addr = nil
then exit;
if MergeBlockAfter(@decommittedRoot, result).addr = nil
then
begin
FreeSpace(result.addr, result.size);
result.addr := nil;
exit;
end;
until False;
end;
function GetCommittedAt(addr: PChar; minSize: Integer): TBlock;
// Get at least minSize bytes committed space at addr.
// Success: returns a block, possibly much bigger than requested.
// Failure: returns a block with addr = nil.
var
bd: PBlockDesc;
b: TBlock;
begin
minSize := (minSize + (cCommitAlign-1)) and not (cCommitAlign-1);
repeat
bd := decommittedRoot.next;
while (bd <> @decommittedRoot) and (bd.addr <> addr) do
bd := bd.next;
if bd.addr = addr
then
begin
if bd.size >= minSize
then break;
b := GetSpaceAt(bd.addr + bd.size, minSize - bd.size);
if b.addr <> nil
then
begin
if MergeBlockAfter(@decommittedRoot, b).addr <> nil
then continue
else
begin
FreeSpace(b.addr, b.size);
result.addr := nil;
exit;
end;
end;
end;
b := GetSpaceAt(addr, minSize);
if b.addr = nil
then break;
if MergeBlockAfter(@decommittedRoot, b).addr = nil
then
begin
FreeSpace(b.addr, b.size);
result.addr := nil;
exit;
end;
until false;
if (bd.addr = addr) and (bd.size >= minSize)
then
begin
result := Commit(bd.addr, minSize);
if result.addr = nil
then exit;
Inc(bd.addr, result.size);
Dec(bd.size, result.size);
if bd.size = 0
then DeleteBlock(bd);
end
else result.addr := nil;
end;
function FreeCommitted(addr: PChar; maxSize: Integer): TBlock;
// Free at most maxSize bytes of address space at addr.
// Returns the block that was actually freed.
var
startAddr, endAddr: PChar;
b: TBlock;
begin
startAddr := PChar(Integer(addr + (cCommitAlign-1)) and not (cCommitAlign-1));
endAddr := PChar(Integer(addr + maxSize) and not (cCommitAlign-1));
if endAddr > startAddr
then
begin
result := Decommit(startAddr, endAddr - startAddr);
b := MergeBlockAfter(@decommittedRoot, result);
if b.addr <> nil
then b := FreeSpace(b.addr, b.size);
if b.addr <> nil
then RemoveBlock(@decommittedRoot, b);
end
else result.addr := nil;
end;
//
// Suballocator (what the user program actually calls)
//
type
PFree = ^TFree;
TFree =
packed record
prev: PFree;
next: PFree;
size: Integer;
end;
PUsed = ^TUsed;
TUsed =
packed record
sizeFlags: Integer;
end;
const
cAlign = 4;
cThisUsedFlag = 2;
cPrevFreeFlag = 1;
cFillerFlag = Integer($80000000);
cFlags = cThisUsedFlag or cPrevFreeFlag or cFillerFlag;
cSmallSize = 4*1024;
cDecommitMin = 15*1024;
type
TSmallTab = array [sizeof(TFree) div cAlign .. cSmallSize div cAlign] of PFree;
var
avail : TFree;
rover : PFree;
remBytes : Integer;
curAlloc : PChar;
smallTab : ^TSmallTab;
committedRoot: TBlockDesc;
function InitAllocator: Boolean;
// Initialize. No other calls legal before that.
var
i: Integer;
begin
try
InitializeCriticalSection(heapLock);
if IsMultiThread
then EnterCriticalSection(heapLock);
MakeEmpty(@spaceRoot);
MakeEmpty(@decommittedRoot);
MakeEmpty(@committedRoot);
smallTab := LocalAlloc(LMEM_FIXED, sizeof(smallTab^));
if smallTab <> nil
then
begin
for i:= low(smallTab^) to high(smallTab^) do
smallTab[i] := nil;
rover := @avail;
rover.next := rover;
rover.prev := rover;
initialized := True;
end;
finally
if IsMultiThread
then LeaveCriticalSection(heapLock);
end;
result := initialized;
end;
procedure UninitAllocator;
// Shutdown.
var
bdb: PBlockDescBlock;
bd : PBlockDesc;
begin
if initialized
then
begin
try
if IsMultiThread
then EnterCriticalSection(heapLock);
initialized := False;
LocalFree(smallTab);
smallTab := nil;
bd := spaceRoot.next;
while bd <> @spaceRoot do
begin
VirtualFree(bd.addr, 0, MEM_RELEASE);
bd := bd.next;
end;
MakeEmpty(@spaceRoot);
MakeEmpty(@decommittedRoot);
MakeEmpty(@committedRoot);
bdb := blockDescBlockList;
while bdb <> nil do
begin
blockDescBlockList := bdb^.next;
LocalFree(bdb);
bdb := blockDescBlockList;
end;
finally
if IsMultiThread
then LeaveCriticalSection(heapLock);
DeleteCriticalSection(heapLock);
end;
end;
end;
procedure DeleteFree(f: PFree);
var
n, p: PFree;
size: Integer;
begin
if rover = f
then rover := f.next;
n := f.next;
size := f.size;
if size <= cSmallSize
then
begin
if n = f
then smallTab[size div cAlign] := nil
else
begin
smallTab[size div cAlign] := n;
p := f.prev;
n.prev := p;
p.next := n;
end;
end
else
begin
p := f.prev;
n.prev := p;
p.next := n;
end;
end;
procedure InsertFree(a: Pointer; size: Integer); forward;
function FindCommitted(addr: PChar): PBlockDesc;
begin
result := committedRoot.next;
while result <> @committedRoot do
begin
if (addr >= result.addr) and (addr < result.addr + result.size)
then exit;
result := result.next;
end;
heapErrorCode := cBadCommittedList;
result := nil;
end;
procedure FillBeforeGap(a: PChar; size: Integer);
var
rest: Integer;
e: PUsed;
begin
rest := size - sizeof(TUsed);
e := PUsed(a + rest);
if size >= sizeof(TFree) + sizeof(TUsed)
then
begin
e.sizeFlags := sizeof(TUsed) or cThisUsedFlag or cPrevFreeFlag or cFillerFlag;
InsertFree(a, rest);
end
else
if size >= sizeof(TUsed)
then
begin
PUsed(a).sizeFlags := size or (cThisUsedFlag or cFillerFlag);
e.sizeFlags := size or (cThisUsedFlag or cFillerFlag);
end;
end;
procedure InternalFreeMem(a: PChar);
begin
Inc(AllocMemCount);
Inc(AllocMemSize,PUsed(a-sizeof(TUsed)).sizeFlags and not cFlags - sizeof(TUsed));
SysFreeMem(a);
end;
procedure FillAfterGap(a: PChar; size: Integer);
begin
if size >= sizeof(TFree)
then
begin
PUsed(a).sizeFlags := size or cThisUsedFlag;
InternalFreeMem(a + sizeof(TUsed));
end
else
begin
if size >= sizeof(TUsed)
then PUsed(a).sizeFlags := size or (cThisUsedFlag or cFillerFlag);
Inc(a,size);
PUsed(a).sizeFlags := PUsed(a).sizeFlags and not cPrevFreeFlag;
end;
end;
function FillerSizeBeforeGap(a: PChar): Integer;
var
sizeFlags : Integer;
freeSize : Integer;
f : PFree;
begin
sizeFlags := PUsed(a - sizeof(TUsed)).sizeFlags;
if (sizeFlags and (cThisUsedFlag or cFillerFlag)) <> (cThisUsedFlag or cFillerFlag)
then heapErrorCode := cBadFiller1;
result := sizeFlags and not cFlags;
Dec(a, result);
if ((PUsed(a).sizeFlags xor sizeFlags) and not cPrevFreeFlag) <> 0
then HeapErrorCode := cBadFiller2;
if (PUsed(a).sizeFlags and cPrevFreeFlag) <> 0
then
begin
freeSize := PFree(a - sizeof(TFree)).size;
f := PFree(a - freeSize);
if f.size <> freeSize
then heapErrorCode := cBadFiller3;
DeleteFree(f);
Inc(result, freeSize);
end;
end;
function FillerSizeAfterGap(a: PChar): Integer;
var
sizeFlags: Integer;
f : PFree;
begin
result := 0;
sizeFlags := PUsed(a).sizeFlags;
if (sizeFlags and cFillerFlag) <> 0
then
begin
sizeFlags := sizeFlags and not cFlags;
Inc(result,sizeFlags);
Inc(a, sizeFlags);
sizeFlags := PUsed(a).sizeFlags;
end;
if (sizeFlags and cThisUsedFlag) = 0
then
begin
f := PFree(a);
DeleteFree(f);
Inc(result, f.size);
Inc(a, f.size);
PUsed(a).sizeFlags := PUsed(a).sizeFlags and not cPrevFreeFlag;
end;
end;
function DecommitFree(a: PChar; size: Integer): Boolean;
var
b: TBlock;
bd: PBlockDesc;
begin
bd := FindCommitted(a);
if bd.addr + bd.size - (a + size) <= sizeof(TFree)
then size := bd.addr + bd.size - a;
if a - bd.addr < sizeof(TFree)
then b := FreeCommitted(bd.addr, size + (a - bd.addr))
else b := FreeCommitted(a + sizeof(TUsed), size - sizeof(TUsed));
if b.addr = nil
then result := False
else
begin
FillBeforeGap(a, b.addr - a);
if bd.addr + bd.size > b.addr + b.size
then FillAfterGap(b.addr + b.size, a + size - (b.addr + b.size));
RemoveBlock(bd,b);
result := True;
end;
end;
procedure InsertFree(a: Pointer; size: Integer);
var
f, n, p: PFree;
begin
f := PFree(a);
f.size := size;
PFree(PChar(f) + size - sizeof(TFree)).size := size;
if size <= cSmallSize
then
begin
n := smallTab[size div cAlign];
if n = nil
then
begin
smallTab[size div cAlign] := f;
f.next := f;
f.prev := f;
end
else
begin
p := n.prev;
f.next := n;
f.prev := p;
n.prev := f;
p.next := f;
end;
end
else
if (size < cDecommitMin) or not DecommitFree(a, size)
then
begin
n := rover;
rover := f;
p := n.prev;
f.next := n;
f.prev := p;
n.prev := f;
p.next := f;
end;
end;
procedure FreeCurAlloc;
begin
if remBytes > 0
then
begin
if remBytes < sizeof(TFree)
then heapErrorCode := cBadCurAlloc
else
begin
PUsed(curAlloc).sizeFlags := remBytes or cThisUsedFlag;
InternalFreeMem(curAlloc + sizeof(TUsed));
curAlloc := nil;
remBytes := 0;
end;
end;
end;
function MergeCommit(b: TBlock): Boolean;
var
merged: TBlock;
fSize: Integer;
begin
FreeCurAlloc;
merged := MergeBlockAfter(@committedRoot, b);
if merged.addr = nil
then
begin
result := False;
exit;
end;
if merged.addr < b.addr
then
begin
fSize := FillerSizeBeforeGap(b.addr);
Dec(b.addr, fSize);
Inc(b.size, fSize);
end;
if merged.addr + merged.size > b.addr + b.size
then
begin
fSize := FillerSizeAfterGap(b.addr + b.size);
Inc(b.size, fSize);
end;
if merged.addr + merged.size = b.addr + b.size
then
begin
FillBeforeGap(b.addr + b.size - sizeof(TUsed), sizeof(TUsed));
Dec(b.size, sizeof(TUsed));
end;
curAlloc := b.addr;
remBytes := b.size;
result := True;
end;
function NewCommit(minSize: Integer): Boolean;
var
b: TBlock;
begin
b := GetCommitted(minSize+sizeof(TUsed));
result := (b.addr <> nil) and MergeCommit(b);
end;
function NewCommitAt(addr: Pointer; minSize: Integer): Boolean;
var
b: TBlock;
begin
b := GetCommittedAt(addr, minSize+sizeof(TUsed));
result := (b.addr <> nil) and MergeCommit(b);
end;
function SearchSmallBlocks(size: Integer): PFree;
var
i: Integer;
begin
result := nil;
for i := size div cAlign to High(smallTab^) do
begin
result := smallTab[i];
if result <> nil
then exit;
end;
end;
function TryHarder(size: Integer): Pointer;
var
u: PUsed; f:PFree; saveSize, rest: Integer;
begin
try
repeat
f := avail.next;
if (size <= f.size)
then break;
f := rover;
if f.size >= size
then break;
saveSize := f.size;
f.size := size;
repeat
f := f.next
until f.size >= size;
rover.size := saveSize;
if f <> rover
then
begin
rover := f;
break;
end;
if size <= cSmallSize
then
begin
f := SearchSmallBlocks(size);
if f <> nil
then break;
end;
if not NewCommit(size)
then
begin
result := nil;
exit;
end;
if remBytes >= size
then
begin
Dec(remBytes, size);
if remBytes < sizeof(TFree)
then
begin
Inc(size, remBytes);
remBytes := 0;
end;
u := PUsed(curAlloc);
Inc(curAlloc, size);
u.sizeFlags := size or cThisUsedFlag;
result := PChar(u) + sizeof(TUsed);
Inc(AllocMemCount);
Inc(AllocMemSize,size - sizeof(TUsed));
exit;
end;
until False;
DeleteFree(f);
rest := f.size - size;
if rest >= sizeof(TFree)
then InsertFree(PChar(f) + size, rest)
else
begin
size := f.size;
if f = rover
then rover := f.next;
u := PUsed(PChar(f) + size);
u.sizeFlags := u.sizeFlags and not cPrevFreeFlag;
end;
u := PUsed(f);
u.sizeFlags := size or cThisUsedFlag;
result := PChar(u) + sizeof(TUsed);
Inc(AllocMemCount);
Inc(AllocMemSize,size - sizeof(TUsed));
except
end;
end;
function SysGetMem(size: Integer): Pointer;
// Allocate memory block.
var
f, prev, next: PFree;
u: PUsed;
begin
if not initialized and not InitAllocator
then
begin
result := nil;
exit;
end;
try
if IsMultiThread
then EnterCriticalSection(heapLock);
Inc(size, sizeof(TUsed) + (cAlign-1));
size := size and not (cAlign-1);
if size < sizeof(TFree)
then size := sizeof(TFree);
if size <= cSmallSize
then
begin
f := smallTab[size div cAlign];
if f <> nil
then
begin
u := PUsed(PChar(f) + size);
u.sizeFlags := u.sizeFlags and not cPrevFreeFlag;
next := f.next;
if next = f
then smallTab[size div cAlign] := nil
else
begin
smallTab[size div cAlign] := next;
prev := f.prev;
prev.next := next;
next.prev := prev;
end;
u := PUsed(f);
u.sizeFlags := f.size or cThisUsedFlag;
result := PChar(u) + sizeof(TUsed);
Inc(AllocMemCount);
Inc(AllocMemSize,size - sizeof(TUsed));
exit;
end;
end;
if size <= remBytes
then
begin
Dec(remBytes, size);
if remBytes < sizeof(TFree)
then
begin
Inc(size, remBytes);
remBytes := 0;
end;
u := PUsed(curAlloc);
Inc(curAlloc, size);
u.sizeFlags := size or cThisUsedFlag;
result := PChar(u) + sizeof(TUsed);
Inc(AllocMemCount);
Inc(AllocMemSize,size - sizeof(TUsed));
exit;
end;
result := TryHarder(size);
finally
if IsMultiThread
then LeaveCriticalSection(heapLock);
end;
end;
function SysFreeMem(p: Pointer): Integer;
// Deallocate memory block.
label
abort;
var
u, n : PUsed;
f : PFree;
prevSize, nextSize, size : Integer;
begin
heapErrorCode := cHeapOk;
if not initialized and not InitAllocator
then
begin
heapErrorCode := cCantInit;
result := cCantInit;
exit;
end;
try
if IsMultiThread
then EnterCriticalSection(heapLock);
u := p;
u := PUsed(PChar(u) - sizeof(TUsed)); { inv: u = address of allocated block being freed }
size := u.sizeFlags;
{ inv: size = SET(block size) + [block flags] }
{ validate that the interpretation of this block as a used block is correct }
if (size and cThisUsedFlag) = 0
then
begin
heapErrorCode := cBadUsedBlock;
goto abort;
end;
{ inv: the memory block addressed by 'u' and 'p' is an allocated block }
Dec(AllocMemCount);
Dec(AllocMemSize,size and not cFlags - sizeof(TUsed));
if (size and cPrevFreeFlag) <> 0
then
begin
{ previous block is free, coalesce }
prevSize := PFree(PChar(u)-sizeof(TFree)).size;
if (prevSize < sizeof(TFree)) or ((prevSize and cFlags) <> 0)
then
begin
heapErrorCode := cBadPrevBlock;
goto abort;
end;
f := PFree(PChar(u) - prevSize);
if f^.size <> prevSize
then
begin
heapErrorCode := cBadPrevBlock;
goto abort;
end;
inc(size, prevSize);
u := PUsed(f);
DeleteFree(f);
end;
size := size and not cFlags;
{ inv: size = block size }
n := PUsed(PChar(u) + size);
{ inv: n = block following the block to free }
if PChar(n) = curAlloc
then
begin
{ inv: u = last block allocated }
dec(curAlloc, size);
inc(remBytes, size);
if remBytes > cDecommitMin
then FreeCurAlloc;
result := cHeapOk;
exit;
end;
if (n.sizeFlags and cThisUsedFlag) <> 0
then
begin
{ inv: n is a used block }
if (n.sizeFlags and not cFlags) < sizeof(TUsed)
then
begin
heapErrorCode := cBadNextBlock;
goto abort;
end;
n.sizeFlags := n.sizeFlags or cPrevFreeFlag
end
else
begin
{ inv: block u & n are both free; coalesce }
f := PFree(n);
if (f.next = nil) or (f.prev = nil) or (f.size < sizeof(TFree))
then
begin
heapErrorCode := cBadNextBlock;
goto abort;
end;
nextSize := f.size;
inc(size, nextSize);
DeleteFree(f);
{ inv: last block (which was free) is not on free list }
end;
InsertFree(u, size);
abort:
result := heapErrorCode;
finally
if IsMultiThread
then LeaveCriticalSection(heapLock);
end;
end;
function ResizeInPlace(p: Pointer; newSize: Integer): Boolean;
var
u, n: PUsed;
f: PFree;
oldSize, blkSize, neededSize: Integer;
begin
Inc(newSize, sizeof(TUsed)+cAlign-1);
newSize := newSize and not (cAlign-1);
if newSize < sizeof(TFree)
then newSize := sizeof(TFree);
u := PUsed(PChar(p) - sizeof(TUsed));
oldSize := u.sizeFlags and not cFlags;
n := PUsed( PChar(u) + oldSize );
if newSize <= oldSize
then
begin
blkSize := oldSize - newSize;
if PChar(n) = curAlloc
then
begin
Dec(curAlloc, blkSize);
Inc(remBytes, blkSize);
if remBytes < sizeof(TFree)
then
begin
Inc(curAlloc, blkSize);
Dec(remBytes, blkSize);
newSize := oldSize;
end;
end
else
begin
n := PUsed(PChar(u) + oldSize);
if n.sizeFlags and cThisUsedFlag = 0
then
begin
f := PFree(n);
Inc(blkSize, f.size);
DeleteFree(f);
end;
if blkSize >= sizeof(TFree)
then
begin
n := PUsed(PChar(u) + newSize);
n.sizeFlags := blkSize or cThisUsedFlag;
InternalFreeMem(PChar(n) + sizeof(TUsed));
end
else newSize := oldSize;
end;
end
else
begin
repeat
neededSize := newSize - oldSize;
if PChar(n) = curAlloc
then
begin
if remBytes >= neededSize
then
begin
Dec(remBytes, neededSize);
Inc(curAlloc, neededSize);
if remBytes < sizeof(TFree)
then
begin
Inc(curAlloc, remBytes);
Inc(newSize, remBytes);
remBytes := 0;
end;
Inc(AllocMemSize, newSize - oldSize);
u.sizeFlags := newSize or u.sizeFlags and cFlags;
result := true;
exit;
end
else
begin
FreeCurAlloc;
n := PUsed( PChar(u) + oldSize );
end;
end;
if n.sizeFlags and cThisUsedFlag = 0
then
begin
f := PFree(n);
blkSize := f.size;
if blkSize < neededSize
then
begin
n := PUsed(PChar(n) + blkSize);
Dec(neededSize, blkSize);
end
else
begin
DeleteFree(f);
Dec(blkSize, neededSize);
if blkSize >= sizeof(TFree)
then InsertFree(PChar(u) + newSize, blkSize)
else
begin
Inc(newSize, blkSize);
n := PUsed(PChar(u) + newSize);
n.sizeFlags := n.sizeFlags and not cPrevFreeFlag;
end;
break;
end;
end;
if n.sizeFlags and cFillerFlag <> 0
then
begin
n := PUsed(PChar(n) + n.sizeFlags and not cFlags);
if NewCommitAt(n, neededSize)
then
begin
n := PUsed( PChar(u) + oldSize );
continue;
end;
end;
result := False;
exit;
until False;
end;
Inc(AllocMemSize, newSize - oldSize);
u.sizeFlags := newSize or u.sizeFlags and cFlags;
result := True;
end;
function SysReallocMem(p: Pointer; size: Integer): Pointer;
// Resize memory block.
var
n : Pointer;
oldSize : Integer;
begin
if not initialized and not InitAllocator
then
begin
result := nil;
exit;
end
else
try
if IsMultiThread
then EnterCriticalSection(heapLock);
if ResizeInPlace(p, size)
then result := p
else
begin
n := SysGetMem(size);
oldSize := (PUsed(PChar(p)-sizeof(PUsed)).sizeFlags and not cFlags) - sizeof(TUsed);
if oldSize > size
then oldSize := size;
if n <> nil
then
begin
Move(p^, n^, oldSize);
SysFreeMem(p);
end;
result := n;
end;
finally
if IsMultiThread
then LeaveCriticalSection(heapLock);
end;
end;
function BlockSum(root: PBlockDesc): Integer;
var
b : PBlockDesc;
begin
result := 0;
b := root.next;
while b <> root do
begin
Inc(result, b.size);
b := b.next;
end;
end;
function GetHeapStatus: THeapStatus;
var
size, freeSize, userSize: Cardinal;
f: PFree;
a, e: PChar;
i: Integer;
b: PBlockDesc;
prevFree: Boolean;
begin
heapErrorCode := cHeapOk;
result.TotalAddrSpace := 0;
result.TotalUncommitted := 0;
result.TotalCommitted := 0;
result.TotalAllocated := 0;
result.TotalFree := 0;
result.FreeSmall := 0;
result.FreeBig := 0;
result.Unused := 0;
result.Overhead := 0;
result.HeapErrorCode := cHeapOk;
if not initialized then exit;
try
if IsMultiThread then EnterCriticalSection(heapLock);
result.totalAddrSpace := BlockSum(@spaceRoot);
result.totalUncommitted := BlockSum(@decommittedRoot);
result.totalCommitted := BlockSum(@committedRoot);
size := 0;
for i := Low(smallTab^) to High(smallTab^) do
begin
f := smallTab[i];
if f <> nil then
begin
repeat
Inc(size, f.size);
if (f.prev.next <> f) or (f.next.prev <> f) or (f.size < sizeof(TFree))
then
begin
heapErrorCode := cBadFreeList;
break;
end;
f := f.next;
until f = smallTab[i];
end;
end;
result.freeSmall := size;
size := 0;
f := avail.next;
while f <> @avail do
begin
if (f.prev.next <> f) or (f.next.prev <> f) or (f.size < sizeof(TFree))
then
begin
heapErrorCode := cBadFreeList;
break;
end;
Inc(size, f.size);
f := f.next;
end;
result.freeBig := size;
result.unused := remBytes;
result.totalFree := result.freeSmall + result.freeBig + result.unused;
freeSize := 0;
userSize := 0;
result.overhead := 0;
b := committedRoot.next;
prevFree := False;
while b <> @committedRoot do
begin
a := b.addr;
e := a + b.size;
while a < e do
begin
if (a = curAlloc) and (remBytes > 0)
then
begin
size := remBytes;
Inc(freeSize, size);
if prevFree
then heapErrorCode := cBadCurAlloc;
prevFree := False;
end
else
begin
if prevFree <> ((PUsed(a).sizeFlags and cPrevFreeFlag) <> 0)
then heapErrorCode := cBadNextBlock;
if (PUsed(a).sizeFlags and cThisUsedFlag) = 0
then
begin
f := PFree(a);
if (f.prev.next <> f) or (f.next.prev <> f) or (f.size < sizeof(TFree))
then heapErrorCode := cBadFreeBlock;
size := f.size;
Inc(freeSize, size);
prevFree := True;
end
else
begin
size := PUsed(a).sizeFlags and not cFlags;
if (PUsed(a).sizeFlags and cFillerFlag) <> 0
then
begin
Inc(result.overhead, size);
if (a > b.addr) and (a + size < e)
then heapErrorCode := cBadUsedBlock;
end
else
begin
Inc(userSize, size-sizeof(TUsed));
Inc(result.overhead, sizeof(TUsed));
end;
prevFree := False;
end;
end;
Inc(a, size);
end;
b := b.next;
end;
if result.totalFree <> freeSize
then heapErrorCode := cBadBalance;
result.totalAllocated := userSize;
result.heapErrorCode := heapErrorCode;
finally
if IsMultiThread
then LeaveCriticalSection(heapLock);
end;
end;
function GetAllocMemCount: Integer;
begin
result := AllocMemCount;
end;
function GetAllocMemSize: Integer;
begin
result := AllocMemSize;
end;
procedure DumpBlocks;
begin
end;
// this section goes into GetMem.Inc
{$IFDEF DEBUG_FUNCTIONS}
type
THeapReportProc = procedure(HeapBlock: Pointer; AllocatedSize: Integer) of object;
procedure WalkHeap(HeapReportProc: THeapReportProc);
var
size : Cardinal;
f: PFree;
a, e: PChar;
b: PBlockDesc;
begin
if not initialized
then exit;
try
if IsMultiThread
then EnterCriticalSection(heapLock);
b := committedRoot.next;
while b <> @committedRoot do
begin
a := b.addr;
e := a + b.size;
while a < e do
begin
if (a = curAlloc) and (remBytes > 0)
then size := remBytes
else
begin
if (PUsed(a).sizeFlags and cThisUsedFlag) = 0
then
begin
f := PFree(a);
size := f.size;
end
else
begin
size := PUsed(a).sizeFlags and not cFlags;
if (PUsed(a).sizeFlags and cFillerFlag) = 0
then HeapReportProc(a + sizeof(TUsed), size - sizeof(TUsed))
end;
end;
Inc(a, size);
end;
b := b.next;
end;
finally
if IsMultiThread
then LeaveCriticalSection(heapLock);
end;
end;
type
THeapBlockCollector = class(TObject)
FCount: Integer;
FObjectTable: TObjectArray;
FHeapBlockTable: THeapBlockArray;
FClass: TClass;
FFindDerived: Boolean;
procedure CollectBlocks(HeapBlock: Pointer; AllocatedSize: Integer);
procedure CollectObjects(HeapBlock: Pointer; AllocatedSize: Integer);
end;
procedure THeapBlockCollector.CollectBlocks(HeapBlock: Pointer; AllocatedSize: Integer);
begin
if FCount < Length(FHeapBlockTable)
then
begin
FHeapBlockTable[FCount].Start := HeapBlock;
FHeapBlockTable[FCount].Size := AllocatedSize;
end;
Inc(FCount);
end;
procedure THeapBlockCollector.CollectObjects(HeapBlock: Pointer; AllocatedSize: Integer);
var
AObject: TObject;
AClass: TClass;
type
PPointer = ^Pointer;
begin
try
if AllocatedSize < 4
then Exit;
AObject := TObject(HeapBlock);
AClass := AObject.ClassType;
if (AClass = FClass) or (FFindDerived
and (Integer(AClass) >= 64*1024)
and (PPointer(PChar(AClass) + vmtSelfPtr)^ = Pointer(AClass))
and (AObject is FClass))
then
begin
if FCount < Length(FObjectTable)
then FObjectTable[FCount] := AObject;
Inc(FCount);
end;
except
// Let's not worry about this block - it's obviously not a valid object
end;
end;
var
HeapBlockCollector: THeapBlockCollector;
function GetHeapBlocks: THeapBlockArray;
begin
if not Assigned(HeapBlockCollector)
then HeapBlockCollector := THeapBlockCollector.Create;
Walkheap(HeapBlockCollector.CollectBlocks);
SetLength(HeapBlockCollector.FHeapBlockTable, HeapBlockCollector.FCount);
HeapBlockCollector.FCount := 0;
Walkheap(HeapBlockCollector.CollectBlocks);
Result := HeapBlockCollector.FHeapBlockTable;
HeapBlockCollector.FCount := 0;
HeapBlockCollector.FHeapBlockTable := nil;
end;
function FindObjects(AClass: TClass; FindDerived: Boolean): TObjectArray;
begin
if not Assigned(HeapBlockCollector)
then HeapBlockCollector := THeapBlockCollector.Create;
HeapBlockCollector.FClass := AClass;
HeapBlockCollector.FFindDerived := FindDerived;
Walkheap(HeapBlockCollector.CollectObjects);
SetLength(HeapBlockCollector.FObjectTable, HeapBlockCollector.FCount);
HeapBlockCollector.FCount := 0;
Walkheap(HeapBlockCollector.CollectObjects);
Result := HeapBlockCollector.FObjectTable;
HeapBlockCollector.FCount := 0;
HeapBlockCollector.FObjectTable := nil;
end;
{$ENDIF}
procedure MultiThread(const value: boolean);
begin
if value
then
IsMultiThread := value;
end;
function SaveToDisk(FileName: pchar): boolean;
var
f : integer;
c : cardinal;
next : PBlockDesc;
procedure SaveTree(tree: PBlockDesc; MemorySave: boolean);
begin
next := tree.next;
result := true;
while (next<>tree) and result do
begin
with next^ do
begin
result := false;
if WriteFile(f, addr, sizeof(addr), c, nil)
then
if WriteFile(f, size, sizeof(size), c, nil)
then
begin
result := true;
if MemorySave
then
if not WriteFile(f, addr^, size, c, nil)
then result := false;
end;
end;
next := next.Next;
end;
end;
begin
if IsMultiThread
then EnterCriticalSection(heapLock);
try
f := CreateFile(FileName, GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if f<>0
then
try
WriteFile(f, smallTab^, sizeof(smallTab^), c, nil);
SaveTree(@spaceRoot, false);
WriteFile(f, Null, sizeof(Null), c, nil);
SaveTree(@decommittedRoot, true);
WriteFile(f, Null, sizeof(Null), c, nil);
SaveTree(@committedRoot, true);
WriteFile(f, Null, sizeof(Null), c, nil);
CloseHandle(F);
except
result := false;
end
else result := false;
finally
if IsMultiThread
then LeaveCriticalSection(heapLock);
end;
end;
function LoadFromDisk(FileName: pchar): boolean;
begin
if IsMultiThread
then EnterCriticalSection(heapLock);
try
finally
if IsMultiThread
then LeaveCriticalSection(heapLock);
end;
result := true;
end;
function GetspaceRoot: pointer;
begin
result := @spaceRoot;
end;
function GetdecommittedRoot: pointer;
begin
result := @decommittedRoot;
end;
function GetcommittedRoot: pointer;
begin
result := @committedRoot;
end;
function Get_avail : pointer;
begin
result := @avail;
end;
function Get_rover: pointer;
begin
result := rover;
end;
function Get_remBytes : Integer;
begin
result := remBytes;
end;
function Get_curAlloc : pointer;
begin
result := curAlloc;
end;
function Get_smallTab : pointer;
begin
result := smallTab;
end;
end.
|
unit ISMLS;
interface
uses
Languages;
const
mtidSystem : TRegMultiString = nil; // 'SYSTEM';
mtidClientAware : TRegMultiString = nil; // UserName + ' has entered ' + fServer.WorldName + '.'
mtidClientUnAware : TRegMultiString = nil; // UserName + ' has left ' + fServer.WorldName + '.'
mtidChannelInfo : TRegMultiString = nil; // 'Channel "' + Channel.fName + '", created by ' + Channel.fCreator + '. '
mtidUser : TRegMultiString = nil; // user
mtidUsers : TRegMultiString = nil; // users
mtidAnd : TRegMultiString = nil; // and
mtidChanNeedsPass : TRegMultiString = nil; //' You need a password to enter this channel.'
mtidNoChanInfo : TRegMultiString = nil; // 'There is no information associated to this object.'
mtidServerBusy : TRegMultiString = nil; // 'Servers are busy creating backup files. Please wait.'
mtidServerNotBusy : TRegMultiString = nil; // 'Backup to disk completed.'
mtidPostMan : TRegMultiString = nil; // 'THE POSTMAN'
mtidYouHaveMail : TRegMultiString = nil; // 'You have mail from %s (%s)'
mtidEntersChannel : TRegMultiString = nil; // 'left channel'
mtidEntersLobby : TRegMultiString = nil; // 'left lobby'
mtidLeftChannel : TRegMultiString = nil; // 'left channel'
mtidLeftLobby : TRegMultiString = nil; // 'left lobby'
mtidMaintDue : TRegMultiString = nil; // 'Server will go down for maintenance in %s minutes. Expected downtime aprox. %s minutes.'
procedure SaveMLS;
procedure LoadMLS;
implementation
uses
SysUtils;
procedure SaveMLS;
var
Dict : TDictionary;
begin
Dict := Languages.CreateDictionary;
try
Dict.Store(ExtractFilePath(paramstr(0)) + 'isdict.lang');
finally
Dict.Free;
end;
end;
procedure LoadMLS;
var
Dict : TDictionary;
i : integer;
root : string;
begin
root := ExtractFilePath(paramstr(0)) + 'languages\is\';
Languages.LoadMLSFrom(root);
for i := 0 to pred(LangList.Count) do
begin
Dict := TDictionary.Create(root + LangList[i] + '\isdict.lang');
try
Languages.ApplyDictionary(Dict, LangList[i]);
finally
Dict.Free;
end;
end;
end;
initialization
mtidSystem := TRegMultiString.Create('mtidSystem', 'SYSTEM');
mtidClientAware := TRegMultiString.Create('mtidClientAware', '%s has entered %s');
mtidClientUnAware := TRegMultiString.Create('mtidClientUnAware', '%s has left %s.');
mtidChannelInfo := TRegMultiString.Create('mtidChannelInfo', 'Channel "%s", created by %s. ');
mtidUser := TRegMultiString.Create('mtidUser', 'user');
mtidUsers := TRegMultiString.Create('mtidUsers', 'users');
mtidAnd := TRegMultiString.Create('mtidAnd', 'and');
mtidChanNeedsPass := TRegMultiString.Create('mtidChanNeedsPass', 'You need a password to enter this channel.');
mtidNoChanInfo := TRegMultiString.Create('mtidNoChanInfo', 'There is no information associated to this object.');
mtidServerBusy := TRegMultiString.Create('mtidServerBusy', 'Servers are busy creating backup files. Please wait.');
mtidServerNotBusy := TRegMultiString.Create('mtidServerNotBusy', 'Backup to disk completed.');
mtidPostMan := TRegMultiString.Create('mtidPostMan', 'THE POSTMAN');
mtidYouHaveMail := TRegMultiString.Create('mtidYouHaveMail', 'You have mail from %s (%s).');
mtidEntersChannel := TRegMultiString.Create('mtidEntersChannel', '%s entered channel %s.');
mtidEntersLobby := TRegMultiString.Create('mtidEntersLobby', '%s entered lobby.');
mtidLeftChannel := TRegMultiString.Create('mtidLeftChannel', '%s left channel %s.');
mtidLeftLobby := TRegMultiString.Create('mtidLeftLobby', '%s left lobby.');
mtidMaintDue := TRegMultiString.Create('mtidMaintDue', 'Server will go down for maintenance in %s minutes. Estimated downtime %s minutes.');
end.
|
unit uCadastroCardapio;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, uDAOGrupo,
uTDPNumberEditXE8, Vcl.ExtCtrls, uDAOCardapio, DMPrincipal;
type
TFCadastroCardapio = class(TForm)
Label1: TLabel;
edtCodGrupo: TEdit;
Label2: TLabel;
pDescricaoGrupo: TPanel;
Label4: TLabel;
edtDescricaoProduto: TEdit;
Label5: TLabel;
edtValorInteira: TDPTNumberEditXE8;
Label6: TLabel;
edtValorMeia: TDPTNumberEditXE8;
Panel2: TPanel;
btnSair: TBitBtn;
btnExcluir: TBitBtn;
btnGravar: TBitBtn;
btnBuscaGrupo: TBitBtn;
btnBuscaProduto: TBitBtn;
btnImprimir: TBitBtn;
procedure btnSairClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnBuscaGrupoClick(Sender: TObject);
procedure edtCodGrupoExit(Sender: TObject);
procedure edtCodGrupoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtDescricaoProdutoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnBuscaProdutoClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure edtCodGrupoEnter(Sender: TObject);
procedure btnImprimirClick(Sender: TObject);
procedure edtCodGrupoKeyPress(Sender: TObject; var Key: Char);
private
vloDAOCardapio : TDAOCardapio;
vloDAOGrupo : TDAOGrupo;
vlbLimpaDados : Boolean;
procedure pcdLimpaCampos;
{ Private declarations }
public
vgiCodProduto : Integer;
{ Public declarations }
end;
var
FCadastroCardapio: TFCadastroCardapio;
implementation
{$R *.dfm}
uses uCons_Grupos, uCons_Produtos;
procedure TFCadastroCardapio.btnBuscaGrupoClick(Sender: TObject);
begin
Application.CreateForm(TFCons_Grupos, FCons_Grupos);
FCons_Grupos.ShowModal;
FreeAndNil(FCons_Grupos);
if Trim(edtCodGrupo.Text) <> '' then
edtCodGrupoExit(Sender);
if edtDescricaoProduto.CanFocus then
edtDescricaoProduto.SetFocus;
end;
procedure TFCadastroCardapio.btnBuscaProdutoClick(Sender: TObject);
begin
Application.CreateForm(TFCons_Produtos, FCons_Produtos);
FCons_Produtos.ShowModal;
FreeAndNil(FCons_Produtos);
if Trim(edtCodGrupo.Text) <> '' then
edtCodGrupoExit(Sender);
btnExcluir.Enabled := True;
if edtDescricaoProduto.CanFocus then
edtDescricaoProduto.SetFocus;
end;
procedure TFCadastroCardapio.btnExcluirClick(Sender: TObject);
begin
vloDAOCardapio.PRO_CODIGO := vgiCodProduto;
vloDAOCardapio.PRO_GRUPO := StrToInt(edtCodGrupo.Text);
vloDAOCardapio.fncDeletaProduto;
pcdLimpaCampos;
end;
procedure TFCadastroCardapio.btnGravarClick(Sender: TObject);
begin
if ((Trim(edtCodGrupo.Text) = '') or
((Trim(edtCodGrupo.Text) <> '') and (Trim(pDescricaoGrupo.Caption) = ''))) then
begin
ShowMessage('Código do Grupo inválido.');
vlbLimpaDados := False;
edtCodGrupo.SetFocus;
Abort;
end;
if Trim(edtDescricaoProduto.Text) = '' then
begin
ShowMessage('Descrição do Produto inválido.');
edtDescricaoProduto.SetFocus;
Abort;
end;
if edtValorInteira.Value = 0 then
begin
ShowMessage('Valor da Inteira tem que ser maior que 0(Zero).');
edtValorInteira.SetFocus;
Abort;
end;
vloDAOCardapio.PRO_CODIGO := vgiCodProduto;
vloDAOCardapio.PRO_GRUPO := StrToInt(edtCodGrupo.Text);
vloDAOCardapio.PRO_DESCRICAO := edtDescricaoProduto.Text;
vloDAOCardapio.PRO_VALORMEIA := edtValorMeia.Value;
vloDAOCardapio.PRO_VALORINTEIRA := edtValorInteira.Value;
vloDAOCardapio.fncInsereProduto;
pcdLimpaCampos;
end;
procedure TFCadastroCardapio.btnImprimirClick(Sender: TObject);
begin
if FileExists(ExtractFilePath(Application.ExeName) + 'Relatorios\Rel_Cardapio.fr3') then
begin
DMPrinc.FDRel_Cardapio.Open();
DMPrinc.FDRel_Cardapio.Refresh;
DMPrinc.frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName) + 'Relatorios\Rel_Cardapio.fr3');
DMPrinc.frxReport1.ShowReport(True);
end
else
ShowMessage('O Relatório não foi localizado, copie o arquivo: Rel_Cardapio.fr3 para a pasta: ' + ExtractFilePath(Application.ExeName)+ 'Relatorios\');
end;
procedure TFCadastroCardapio.btnSairClick(Sender: TObject);
begin
Close;
end;
procedure TFCadastroCardapio.edtCodGrupoEnter(Sender: TObject);
begin
if vlbLimpaDados then
pcdLimpaCampos
else
vlbLimpaDados := True;
end;
procedure TFCadastroCardapio.edtCodGrupoExit(Sender: TObject);
begin
if Trim(edtCodGrupo.Text) <> '' then
begin
vloDAOGrupo.GRUPO_CODIGO := StrToInt(edtCodGrupo.Text);
pDescricaoGrupo.Caption := vloDAOGrupo.fncConsultaGrupo;
end
else
pDescricaoGrupo.Caption := '';
end;
procedure TFCadastroCardapio.edtCodGrupoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F2 then
btnBuscaGrupo.Click;
end;
procedure TFCadastroCardapio.edtCodGrupoKeyPress(Sender: TObject;
var Key: Char);
begin
if not( key in['0'..'9',#08,#13,#27,#42] ) then
key:=#0;
end;
procedure TFCadastroCardapio.edtDescricaoProdutoKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_F2 then
btnBuscaProduto.Click;
end;
procedure TFCadastroCardapio.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_F3 : btnGravar.Click;
VK_F4 : btnExcluir.Click;
VK_F5 : btnImprimir.Click;
VK_ESCAPE : btnSair.Click;
end;
end;
procedure TFCadastroCardapio.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
Perform(Wm_NextDlgCtl,0,0);
Key := #0;
end
end;
procedure TFCadastroCardapio.FormShow(Sender: TObject);
begin
vloDAOCardapio := TDAOCardapio.Create(DMPrinc.FDConnection1);
vloDAOGrupo := TDAOGrupo.Create(DMPrinc.FDConnection1);
vgiCodProduto := 0;
vlbLimpaDados := True;
end;
procedure TFCadastroCardapio.pcdLimpaCampos;
begin
edtCodGrupo.Clear;
edtDescricaoProduto.Clear;
edtValorInteira.Value := 0;
edtValorMeia.Value := 0;
pDescricaoGrupo.Caption := '';
vgiCodProduto := 0;
btnExcluir.Enabled := False;
if edtCodGrupo.CanFocus then
edtCodGrupo.SetFocus;
end;
end.
|
unit AtrStrUtils;
interface
uses Classes, SysUtils, Variants, RxStrUtils, DB;
const
Codes64 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/';
type
TStringArray = array of string;
function MonthFirstDay(const aDate: TDateTime): TDateTime;
// Возвращаем последнее число месяца
// соответствующего дате aDate
function MonthLastDay(const aDate: TDateTime): TDateTime;
function FBdateToDate(const aFBDAte: String): TDateTime;
function DateTOFBdate(const aDate: TDateTime): String;
// записать строку в буфер обмена
procedure StrToClipbrd(const StrValue: string);
// прочесть строку из буфера обмена
function GetStrFromClipbrd: string;
// аналог функции Explode PHP
function Explode(Ch: Char; const Text: string): TStringArray;
// проверка на корректность IP адреса
function CheckIP(const IP: string): Boolean;
// проверка на корректность MAC адреса
function CheckMAC(const MAC: string): Boolean;
// удаляет все неверные символы и ставит разделителем :
function ValidateMAC(const MAC: string): string;
// удаляем символ слева
// s - строка для поиска, chr - удаляемый символ
function LeftTrimChar(const S: string; const chr: Char): string;
// Добавляет слева символ до нужно длинны
function LeftPad(const S: string; const Ch: Char; const Len: Integer): string;
// удаляет символы из строки
function RemoveChars(const S: string; const Chrs: string): string;
// Get database beetween dates str
function GenerateBetweenDateSql(const aFieldName: String; const aDateFrom, aDateTo: TDateTime): string;
// Get date in Firebird format
function GetFirebirdDate(const aDate: TDateTime): string;
// перевод в транслит по СЭВ 1362-78
// А Б В Г Д Е Ё Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ы Ь Э Ю Я
// A B V G D E JO ZH Z I J K L M N O P R S T U F KH C CH SH SHH '' Y ' EH JU JA
function ToTranslit(const S: string): string;
function Translit(const S: string): string; // не меняет прбел на _
// перевод из транслита по СЭВ 1362-78
// А Б В Г Д Е Ё Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ы Ь Э Ю Я
// A B V G D E JO ZH Z I J K L M N O P R S T U F KH C CH SH SHH '' Y ' EH JU JA
function FromTranslit(const S: string): string;
// увеличить MAC адрес на значение step
function IncMAC(const MAC: string; const step: Integer = 1): String;
// оставляет в строке только цифры
function DigitsOnly(const S: string): string;
function GenPassword(const PWDlen: Integer = 8): String;
// перевод трех символьного кода iso в двухсимвольный
function LangISO6391toISO6392TCode(const LANG: String): String;
function LangISO6392TtoISO6391Code(const LANG: String): String;
// Проверка, заблокирован файл или нет. Если не блокирован то возвращает TRUE
function CheckFileNotLock(const Origin: string): Boolean;
function NormalizeFIO(const S: string): String;
function TrimAnd(const S: string): String;
// validate an IBAN
function CheckIBAN(iban: string): Boolean;
// проверка расчетного счета в РФ
function CheckRusBA(BA: string; BIK: String): Boolean;
// форматирование MAC как xxxx.xxxx.xxxx
function FormatMACas4Cd(const S: string): String;
implementation
uses
DateUtils, ClipBrd, Windows;
const
SErrWrongBase64EncodedString = 'Формат строки не соответствует способу кодирования Base64.';
// IBAN = International Bank Account Number
// Example : CH10002300A1023502601
function ChangeAlpha(input: string): string;
// A -> 10, B -> 11, C -> 12 ...
var
a: Char;
begin
Result := input;
for a := 'A' to 'Z' do
begin
Result := StringReplace(Result, a, IntToStr(Ord(a) - 55), [rfReplaceAll]);
end;
end;
function CalculateDigits(iban: string): Integer;
var
v, l: Integer;
alpha: string;
number: Longint;
rest: Integer;
begin
iban := UpperCase(iban);
if Pos('IBAN', iban) > 0 then
Delete(iban, Pos('IBAN', iban), 4);
iban := iban + Copy(iban, 1, 4);
Delete(iban, 1, 4);
iban := ChangeAlpha(iban);
v := 1;
l := 9;
rest := 0;
alpha := '';
try
while v <= Length(iban) do
begin
if l > Length(iban) then
l := Length(iban);
alpha := alpha + Copy(iban, v, l);
number := StrToInt(alpha);
rest := number mod 97;
v := v + l;
alpha := IntToStr(rest);
l := 9 - Length(alpha);
end;
except
rest := 0;
end;
Result := rest;
end;
function CheckIBAN(iban: string): Boolean;
begin
if CalculateDigits(iban) = 1 then
Result := True
else
Result := False;
end;
function CheckRusBA(BA: string; BIK: String): Boolean;
begin
// https://github.com/Kholenkov/php-data-validation/blob/master/src/DataValidation.php
Result := True;
end;
function ValidateMAC(const MAC: string): string;
var
S: string;
i: Integer;
begin
Result := '';
if Length(MAC) < 12 then
Exit;
S := AnsiUpperCase(MAC);
for i := 1 to Length(S) do
begin
if CharInSet(S[i], ['0' .. '9']) then
Result := Result + S[i]
else if CharInSet(S[i], ['A' .. 'F']) then
Result := Result + S[i];
end;
if Length(Result) = 12 then
begin
Result := Copy(Result, 1, 2) + ':' + Copy(Result, 3, 18);
Result := Copy(Result, 1, 5) + ':' + Copy(Result, 6, 18);
Result := Copy(Result, 1, 8) + ':' + Copy(Result, 9, 18);
Result := Copy(Result, 1, 11) + ':' + Copy(Result, 12, 18);
Result := Copy(Result, 1, 14) + ':' + Copy(Result, 15, 18);
end
else
Result := '';
end;
// Get database beetween dates str
function GenerateBetweenDateSql(const aFieldName: String; const aDateFrom, aDateTo: TDateTime): string;
begin
Result := '(' + aFieldName + ' between ''' + FormatDateTime('yyyy-mm-dd', aDateFrom) + ''' and ''' +
FormatDateTime('yyyy-mm-dd', aDateTo) + ''')';
end;
// Get database beetween dates str
function GetFirebirdDate(const aDate: TDateTime): string;
begin
Result := 'cast(''' + FormatDateTime('yyyy-mm-dd', aDate) + ''' as DATE)';
end;
function RemoveChars(const S: string; const Chrs: string): string;
var
i, J: Integer;
begin
Result := S;
if Length(Chrs) = 0 then
Exit;
for J := 1 to Length(Chrs) do
begin
for i := Length(Result) downto 1 do
begin
if Result[i] = Chrs[J] then
Delete(Result, i, 1);
end;
end;
end;
function DateTOFBdate(const aDate: TDateTime): String;
var
y, m, d: word;
begin
// TODO:Дату из строки в TDate
try
DecodeDate(aDate, y, m, d);
Result := '''' + IntToStr(y) + '-' + IntToStr(m) + '-' + IntToStr(d) + '''';
except
Result := 'null';
end;
end;
function FBdateToDate(const aFBDAte: String): TDateTime;
var
y, m, d: Integer;
S: string;
begin
// TODO:Дату из строки в TDate
Result := 0;
if Pos('-', aFBDAte) = 0 then
Exit;
y := StrToInt(Copy(aFBDAte, 0, Pos('-', aFBDAte) - 1));
S := Copy(aFBDAte, Pos('-', aFBDAte) + 1, 100);
m := StrToInt(Copy(S, 0, Pos('-', S) - 1));
S := Copy(S, Pos('-', S) + 1, 100);
d := StrToInt(S);
Result := EncodeDate(y, m, d);
end;
function LeftTrimChar(const S: string; const chr: Char): string;
var
i, l: Integer;
begin
l := Length(S);
i := 1;
while (i <= l) and (S[i] = chr) do
Inc(i);
Result := Copy(S, i, MaxInt);
end;
function LeftPad(const S: string; const Ch: Char; const Len: Integer): string;
var
RestLen: Integer;
begin
Result := S;
RestLen := Len - Length(S);
if RestLen < 1 then
Exit;
Result := StringOfChar(Ch, RestLen) + S;
end;
// аналог функции Explode PHP
function Explode(Ch: Char; const Text: string): TStringArray;
var
i, k, Len: Integer;
Count: Integer;
begin
if Text = '' then
begin
Result := nil;
Exit;
end; // if
Count := 0;
Len := Length(Text);
for i := 1 to Len do
begin
if Text[i] = Ch then
Inc(Count);
end; // for i
SetLength(Result, Count + 1);
Count := 0;
k := 1;
for i := 1 to Len do
begin
if Text[i] = Ch then
begin
Result[Count] := Copy(Text, k, i - k);
Inc(Count);
k := i + 1;
end; // if
end;
Result[Count] := Copy(Text, k, Len - k + 1);
end;
procedure StrToClipbrd(const StrValue: string);
var
// S: string;
hMem: THandle;
pMem: PChar;
begin
hMem := GlobalAlloc(GHND or GMEM_SHARE, Length(StrValue) + 1);
if hMem <> 0 then
begin
pMem := GlobalLock(hMem);
if pMem <> nil then
begin
StrPCopy(pMem, StrValue);
GlobalUnlock(hMem);
if OpenClipboard(0) then
begin
EmptyClipboard;
SetClipboardData(CF_TEXT, hMem);
CloseClipboard;
end
else
GlobalFree(hMem);
end
else
GlobalFree(hMem);
end;
end;
function GetStrFromClipbrd: string;
begin
if Clipboard.HasFormat(CF_TEXT) then
Result := Clipboard.AsText
else
begin
Result := '';
end;
end;
// Возвращаем первое число месяца
// соответствующего дате aDate
function MonthFirstDay(const aDate: TDateTime): TDateTime;
var
fYear, fMonth, fDay: word;
begin
// Используем функции модуля SysUtils
DecodeDate(aDate, fYear, fMonth, fDay);
Result := EncodeDate(fYear, fMonth, 1);
end;
// Возвращаем последнее число месяца
// соответствующего дате aDate
function MonthLastDay(const aDate: TDateTime): TDateTime;
begin
Result := EndOfTheMonth(aDate);
end;
// проверка на корректность IP адреса
function CheckIP(const IP: string): Boolean;
var
i1, i2, i3, i4: Integer;
S: string;
ar: TStringArray;
begin
Result := False;
S := IP;
if Length(S) < 7 then
Exit;
ar := Explode('.', S);
i1 := Length(ar);
if i1 <> 4 then
Exit;
try
i1 := StrToInt(ar[0]);
i2 := StrToInt(ar[1]);
i3 := StrToInt(ar[2]);
i4 := StrToInt(ar[3]);
Result := (i1 < 256) and (i2 < 256) and (i3 < 256) and (i4 < 256);
except
end;
end;
// проверка на корректность MAC адреса
function CheckMAC(const MAC: string): Boolean;
var
S: string;
// ar : TStringArray;
begin
Result := False;
S := MAC;
if Length(S) <> 17 then
Exit;
S := AnsiUpperCase(S);
S := StringReplace(S, ':', '', [rfReplaceAll]);
S := StringReplace(S, 'A', '', [rfReplaceAll]);
S := StringReplace(S, 'B', '', [rfReplaceAll]);
S := StringReplace(S, 'C', '', [rfReplaceAll]);
S := StringReplace(S, 'D', '', [rfReplaceAll]);
S := StringReplace(S, 'E', '', [rfReplaceAll]);
S := StringReplace(S, 'F', '', [rfReplaceAll]);
S := StringReplace(S, '0', '', [rfReplaceAll]);
S := StringReplace(S, '1', '', [rfReplaceAll]);
S := StringReplace(S, '2', '', [rfReplaceAll]);
S := StringReplace(S, '3', '', [rfReplaceAll]);
S := StringReplace(S, '4', '', [rfReplaceAll]);
S := StringReplace(S, '5', '', [rfReplaceAll]);
S := StringReplace(S, '6', '', [rfReplaceAll]);
S := StringReplace(S, '7', '', [rfReplaceAll]);
S := StringReplace(S, '8', '', [rfReplaceAll]);
S := StringReplace(S, '9', '', [rfReplaceAll]);
Result := S = '';
end;
// перевод в транслит по СЭВ 1362-78
// А Б В Г Д Е Ё Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ы Ь Э Ю Я
// A B V G D E JO ZH Z I J K L M N O P R S T U F KH C CH SH SHH '' Y ' EH JU JA
function ToTranslit(const S: string): string;
const
rus: string = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ ';
lat: array [1 .. 67] of string = ('a', 'b', 'v', 'g', 'd', 'e', 'jo', 'zh', 'z', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'r', 's', 't', 'u', 'f', 'kh', 'c', 'ch', 'sh', 'shh', '''''', 'y', '''', 'eh', 'ju', 'ja', 'A', 'B', 'V', 'G',
'D', 'E', 'JO', 'ZH', 'Z', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F', 'KH', 'C', 'CH', 'SH',
'SHH', '''''', 'Y', '''', 'EH', 'JU', 'JA', '_');
var
p, i, l: Integer;
begin
Result := '';
l := Length(S);
for i := 1 to l do
begin
p := Pos(S[i], rus);
if p < 1 then
Result := Result + S[i]
else
Result := Result + lat[p];
end;
end;
function Translit(const S: string): string;
const
rus: string = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ ';
lat: array [1 .. 67] of string = ('a', 'b', 'v', 'g', 'd', 'e', 'jo', 'zh', 'z', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'r', 's', 't', 'u', 'f', 'kh', 'c', 'ch', 'sh', 'shh', '''''', 'y', '''', 'eh', 'ju', 'ja', 'A', 'B', 'V', 'G',
'D', 'E', 'JO', 'ZH', 'Z', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F', 'KH', 'C', 'CH', 'SH',
'SHH', '''''', 'Y', '''', 'EH', 'JU', 'JA', ' ');
var
p, i, l: Integer;
begin
Result := '';
l := Length(S);
for i := 1 to l do
begin
p := Pos(S[i], rus);
if p < 1 then
Result := Result + S[i]
else
Result := Result + lat[p];
end;
end;
// перевод из транслита по СЭВ 1362-78
// А Б В Г Д Е Ё Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ы Ь Э Ю Я
// A B V G D E JO ZH Z I J K L M N O P R S T U F KH C CH SH SHH '' Y ' EH JU JA
function FromTranslit(const S: string): string;
const
rus1: string = 'абвгдезийклмнопрстуфцыАБВГДЕЗИЙКЛМНОПРСТУФЦЫЬ ';
lat1: string = 'abvgdezijklmnoprstufcyABVGDEZIJKLMNOPRSTUFCY''_';
rus2: string = 'ёжхчшэюяЁЖХЧШЭЮЯъ';
lat2: array [1 .. 17] of string = ('jo', 'zh', 'kh', 'ch', 'sh', 'eh', 'ju', 'ja', 'JO', 'ZH', 'KH', 'CH', 'SH', 'EH',
'JU', 'JA', '''''');
// щ
// 'shch'
var
p, i, J, l: Integer;
sub: string;
C: Char;
begin
Result := '';
l := Length(S);
i := 1;
while i <= l do
begin
// проверим букву Щ
if (i + 2) <= l then
begin
C := Char(32);
sub := Copy(S, i, 3);
if (sub = 'shh') then
C := 'щ'
else if (AnsiUpperCase(sub) = 'SHH') then
C := 'Щ';
if (C <> Char(32)) then
begin
Inc(i, 4);
Result := Result + C;
Continue;
end;
end;
if (i + 1) <= l then
begin
C := Char(32);
sub := Copy(S, i, 2);
for J := 1 to 8 do
begin
if (sub = lat2[J]) then
C := rus2[J]
else if (AnsiUpperCase(sub) = lat2[J + 8]) then
C := rus2[J + 8];
end;
if (C <> Char(32)) then
begin
Inc(i, 2);
Result := Result + C;
Continue;
end;
end;
p := Pos(S[i], lat1);
if p < 1 then
Result := Result + S[i]
else
Result := Result + rus1[p];
Inc(i);
end;
end;
function IncMAC(const MAC: string; const step: Integer = 1): String;
var
newMac: string;
IntMac: array [0 .. 5] of Byte;
J, o: Integer;
i: Integer;
begin
// 00:18:9b:47:29:4f
for i := 0 to 5 do
begin
newMac := ExtractWord(i + 1, MAC, [':']);
IntMac[i] := HEX2DEC(newMac);
end;
J := step;
for i := 5 downto 0 do
begin
if (IntMac[i] + J) > 255 then
begin
o := (IntMac[i] + J);
o := o mod 256;
IntMac[i] := o;
J := J - o;
end
else
begin
IntMac[i] := IntMac[i] + J;
J := 0;
end;
end;
newMac := Dec2Hex(IntMac[0], 2);
newMac := newMac + ':' + Dec2Hex(IntMac[1], 2);
newMac := newMac + ':' + Dec2Hex(IntMac[2], 2);
newMac := newMac + ':' + Dec2Hex(IntMac[3], 2);
newMac := newMac + ':' + Dec2Hex(IntMac[4], 2);
newMac := newMac + ':' + Dec2Hex(IntMac[5], 2);
Result := newMac;
end;
function DigitsOnly(const S: string): string;
var
i, l: Integer;
begin
Result := '';
l := Length(S);
for i := 1 to l do
begin
if CharInSet(S[i], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) then
Result := Result + S[i];
end;
end;
function GenPassword(const PWDlen: Integer = 8): String;
const
validchar: string = '0123456789abcdef';
var
S: string;
i: Integer;
begin
S := '';
Randomize;
i := Length(validchar);
while Length(S) < PWDlen do
S := S + validchar[Random(i) + 1];
Result := S;
end;
function LangISO6391toISO6392TCode(const LANG: String): String;
Var
S: string;
begin
S := UpperCase(LANG);
Result := 'ru';
// ENGLISH ENG, RUSSIAN RUS, LATVIAN LAV, LITHUANIAN LIT, ESTONIAN EST, BELARUSIAN BEL, UKRAINIAN UKR, GERMAN DEU, FRENCH FRA
if S = 'ENG' then
Result := 'en'
else if S = 'LAV' then
Result := 'lv'
else if S = 'LIT' then
Result := 'lt'
else if S = 'EST' then
Result := 'et'
else if S = 'BEL' then
Result := 'be'
else if S = 'UKR' then
Result := 'uk'
else if S = 'DEU' then
Result := 'de'
else if S = 'FRA' then
Result := 'fr'
end;
function LangISO6392TtoISO6391Code(const LANG: String): String;
Var
S: string;
begin
S := UpperCase(LANG);
Result := 'RUS';
// ENGLISH ENG, RUSSIAN RUS, LATVIAN LAV, LITHUANIAN LIT, ESTONIAN EST, BELARUSIAN BEL, UKRAINIAN UKR, GERMAN DEU, FRENCH FRA
if S = 'EN' then
Result := 'ENG'
else if S = 'LV' then
Result := 'LAV'
else if S = 'LT' then
Result := 'LIT'
else if S = 'ET' then
Result := 'EST'
else if S = 'BE' then
Result := 'BEL'
else if S = 'UK' then
Result := 'UKR'
else if S = 'DE' then
Result := 'DEU'
else if S = 'FR' then
Result := 'FRA'
end;
function CheckFileNotLock(const Origin: string): Boolean;
var
HFileRes: HFILE;
begin
Result := False;
if not FileExists(Origin) then
Exit;
HFileRes := CreateFile(PChar(Origin), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(HFileRes);
Result := not Result;
end;
function NormalizeFIO(const S: string): String;
var
sa: TStringArray;
fio: String;
i: Integer;
begin
// Result := trim(s);
sa := Explode('-', S);
fio := AnsiUpperCase(Copy(sa[0], 1, 1)) + AnsiLowerCase(Copy(sa[0], 2, Length(sa[0]) - 1));
for i := 1 to Length(sa) - 1 do
begin
fio := fio + '-' + AnsiUpperCase(Copy(sa[i], 1, 1)) + AnsiLowerCase(Copy(sa[i], 2, Length(sa[i]) - 1));
end;
Result := fio;
end;
function TrimAnd(const S: string): String;
var
tmp: String;
begin
tmp := trim(S);
if (AnsiUpperCase(Copy(tmp, 1, 3)) = 'AND') then
Result := Copy(tmp, 4, Length(tmp) - 3)
else
Result := S;
end;
function FormatMACas4CD(const S: string): String;
var
aMac: TStringArray;
begin
Result := '';
if CheckMAC(S) then
begin
aMac := Explode(':', S);
Result := LowerCase( aMac[0] + aMac[1] + '.' + aMac[2] + aMac[3] + '.' + aMac[4] + aMac[5] );
end;
end;
initialization
end.
|
unit dialogZipProgress;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes, System.UITypes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.WinXCtrls,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls,
RzPanel, RzDlgBtn, RzPrgres, RzBorder,
SBArcZip, SBArcBase, SBLicenseManager;
type
TdlgZipStatus = class(TForm)
btnBar: TRzDialogButtons;
btnStart: TBitBtn;
zipWriter: TElZipWriter;
SSBLicMgr: TElSBLicenseManager;
progBar: TProgressBar;
txtCurrentFile: TStaticText;
lblElapsed: TLabel;
procedure FormShow(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure btnBarClickOk(Sender: TObject);
procedure zipWriterCompressionStart(Sender: TObject;
Entry: TElZipArchiveDirectoryEntry; var Compress: Boolean);
procedure zipWriterProgress(Sender: TObject; Processed, Total,
OverallProcessed, OverallTotal: UInt64; var Cancel: Boolean);
procedure zipWriterCompressionFinished(Sender: TObject;
Entry: TElZipArchiveDirectoryEntry);
procedure btnBarClickCancel(Sender: TObject);
private
{ Private declarations }
FCancelOperation : Boolean;
TimeStart : TTime;
TimeNow : TTime;
public
{ Public declarations }
property CancelOperation : boolean read FCancelOperation write FCancelOperation;
end;
var
dlgZipStatus: TdlgZipStatus;
SourceFile : String;
ArchiveFile : String;
DataDate : string;
implementation
{$R *.dfm}
uses formMain;
procedure TdlgZipStatus.btnBarClickCancel(Sender: TObject);
begin
if zipWriter.Opened then begin showmessage('cancel - zipwriter.opened');
FCancelOperation := True;
end
else begin
ModalResult := mrCancel;
Close;
end;
end;
procedure TdlgZipStatus.btnBarClickOk(Sender: TObject);
begin
ModalResult := mrOK;
end;
procedure TdlgZipStatus.btnStartClick(Sender: TObject);
begin
TimeStart := Now;
try
btnStart.Hide;
txtCurrentFile.Caption := 'Compressing File: '+SourceFile;
lblElapsed.Show;
Application.ProcessMessages;
if zipWriter.Opened then zipWriter.Close;
zipWriter.CompressionLevel := 9;
zipWriter.Add(SourceFile);
try
zipWriter.Compress(ArchiveFile);
Application.ProcessMessages;
ShowMessage('Complete!');
except
on E:Exception do begin
MessageDlg('Error creating compressed archive: '#10#13+E.Message+#10#13,mtError,[mbOK],0);
Application.ProcessMessages;
Exit;
end;
end;
finally
btnBar.EnableOk := True;
end;
end;
procedure TdlgZipStatus.FormShow(Sender: TObject);
begin
progBar.Enabled := False;
ModalResult := mrCancel;
end;
procedure TdlgZipStatus.zipWriterCompressionFinished(Sender: TObject;
Entry: TElZipArchiveDirectoryEntry);
begin
progBar.Enabled := False;
Application.ProcessMessages;
//zipWriter.Close;
end;
procedure TdlgZipStatus.zipWriterCompressionStart(Sender: TObject;
Entry: TElZipArchiveDirectoryEntry; var Compress: Boolean);
begin
progBar.Enabled := True;
progBar.Max := 100000;
Application.ProcessMessages;
end;
procedure TdlgZipStatus.zipWriterProgress(Sender: TObject; Processed, Total,
OverallProcessed, OverallTotal: UInt64; var Cancel: Boolean);
var ProcessedNormalized : Int64;
timeElapsed : TTime;
begin
Application.ProcessMessages;
Cancel := CancelOperation;
//progBar.Max := OverallTotal;
//progBar.Position := OverallProcessed;
if Total > 0 then
ProcessedNormalized := (Processed * 100000) div Total
else
ProcessedNormalized := 100000;
if OverallTotal > 0 then
ProcessedNormalized := (OverallProcessed * 100000 div OverallTotal)
else
ProcessedNormalized := 100000;
progBar.Position := ProcessedNormalized;
timeNow := Now;
timeElapsed := timeNow - timeStart;
lblElapsed.Caption := 'Time Elapsed: '+FormatDateTime('h:n:s',timeElapsed);
lblElapsed.Refresh;
Application.ProcessMessages;
end;
end.
|
{ Date Created: 5/22/00 11:17:33 AM }
unit InfoLENDERGROUPSTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoLENDERGROUPSRecord = record
PIndex: Integer;
PGroupIndex: Integer;
PLenderID: String[4];
End;
TInfoLENDERGROUPSBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoLENDERGROUPSRecord
end;
TEIInfoLENDERGROUPS = (InfoLENDERGROUPSPrimaryKey, InfoLENDERGROUPSByLenderID, InfoLENDERGROUPSByGroupIndex);
TInfoLENDERGROUPSTable = class( TDBISAMTableAU )
private
FDFIndex: TAutoIncField;
FDFGroupIndex: TIntegerField;
FDFLenderID: TStringField;
procedure SetPGroupIndex(const Value: Integer);
function GetPGroupIndex:Integer;
procedure SetPLenderID(const Value: String);
function GetPLenderID:String;
procedure SetEnumIndex(Value: TEIInfoLENDERGROUPS);
function GetEnumIndex: TEIInfoLENDERGROUPS;
protected
procedure CreateFields; virtual;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoLENDERGROUPSRecord;
procedure StoreDataBuffer(ABuffer:TInfoLENDERGROUPSRecord);
property DFIndex: TAutoIncField read FDFIndex;
property DFGroupIndex: TIntegerField read FDFGroupIndex;
property DFLenderID: TStringField read FDFLenderID;
property PGroupIndex: Integer read GetPGroupIndex write SetPGroupIndex;
property PLenderID: String read GetPLenderID write SetPLenderID;
procedure Validate; virtual;
published
property Active write SetActive;
property EnumIndex: TEIInfoLENDERGROUPS read GetEnumIndex write SetEnumIndex;
end; { TInfoLENDERGROUPSTable }
procedure Register;
implementation
procedure TInfoLENDERGROUPSTable.CreateFields;
begin
FDFIndex := CreateField( 'Index' ) as TAutoIncField;
FDFGroupIndex := CreateField( 'GroupIndex' ) as TIntegerField;
FDFLenderID := CreateField( 'LenderID' ) as TStringField;
end; { TInfoLENDERGROUPSTable.CreateFields }
procedure TInfoLENDERGROUPSTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoLENDERGROUPSTable.SetActive }
procedure TInfoLENDERGROUPSTable.Validate;
begin
{ Enter Validation Code Here }
end; { TInfoLENDERGROUPSTable.Validate }
procedure TInfoLENDERGROUPSTable.SetPGroupIndex(const Value: Integer);
begin
DFGroupIndex.Value := Value;
end;
function TInfoLENDERGROUPSTable.GetPGroupIndex:Integer;
begin
result := DFGroupIndex.Value;
end;
procedure TInfoLENDERGROUPSTable.SetPLenderID(const Value: String);
begin
DFLenderID.Value := Value;
end;
function TInfoLENDERGROUPSTable.GetPLenderID:String;
begin
result := DFLenderID.Value;
end;
procedure TInfoLENDERGROUPSTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Index, AutoInc, 0, Y');
Add('GroupIndex, Integer, 0, Y');
Add('LenderID, String, 4, Y');
end;
end;
procedure TInfoLENDERGROUPSTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Index, Y, Y, N, N');
Add('ByLenderID, LenderID, N, N, N, N');
Add('ByGroupIndex, GroupIndex, N, N, N, N');
end;
end;
procedure TInfoLENDERGROUPSTable.SetEnumIndex(Value: TEIInfoLENDERGROUPS);
begin
case Value of
InfoLENDERGROUPSPrimaryKey : IndexName := '';
InfoLENDERGROUPSByLenderID : IndexName := 'ByLenderID';
InfoLENDERGROUPSByGroupIndex : IndexName := 'ByGroupIndex';
end;
end;
function TInfoLENDERGROUPSTable.GetDataBuffer:TInfoLENDERGROUPSRecord;
var buf: TInfoLENDERGROUPSRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PIndex := DFIndex.Value;
buf.PGroupIndex := DFGroupIndex.Value;
buf.PLenderID := DFLenderID.Value;
result := buf;
end;
procedure TInfoLENDERGROUPSTable.StoreDataBuffer(ABuffer:TInfoLENDERGROUPSRecord);
begin
DFGroupIndex.Value := ABuffer.PGroupIndex;
DFLenderID.Value := ABuffer.PLenderID;
end;
function TInfoLENDERGROUPSTable.GetEnumIndex: TEIInfoLENDERGROUPS;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoLENDERGROUPSPrimaryKey;
if iname = 'BYLENDERID' then result := InfoLENDERGROUPSByLenderID;
if iname = 'BYGROUPINDEX' then result := InfoLENDERGROUPSByGroupIndex;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoLENDERGROUPSTable, TInfoLENDERGROUPSBuffer ] );
end; { Register }
function TInfoLENDERGROUPSBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PIndex;
2 : result := @Data.PGroupIndex;
3 : result := @Data.PLenderID;
end;
end;
end. { InfoLENDERGROUPSTable }
|
unit SWIFT_UTypes;
interface
uses Windows, Messages, SysUtils, Graphics, VirtualTrees, Classes, StdCtrls,
Controls, Forms, ImgList;
type
{ Узел дерева }
TSwiftNode = class(TObject)
private
FParent: TSwiftNode;
FChildren: TList;
FCheckState: TCheckState;
FTagName, FTagValue: string;
FEditable, FMultiLine: Boolean;
FVirtualNode: PVirtualNode;
procedure SetTagName(aTagName: string);
procedure SetTagValue(aTagValue: string);
procedure SetCheckState(aCheckState: TCheckState);
function GetChildCount:integer;
function GetChild(n:integer): TSwiftNode;
public
constructor Create;
destructor Destroy; override;
function GetImageIndex: integer; virtual;
procedure InvalidateVirtualNode;
property CheckState: TCheckState read FCheckState write SetCheckState;
property TagName: string read FTagName write SetTagName;
property TagValue: string read FTagValue write SetTagValue;
property MultiLine: Boolean read FMultiLine write FMultiLine;
property Editable: Boolean read FEditable write FEditable;
property Parent: TSwiftNode read FParent;
property ChildCount: integer read GetChildCount;
property Child[n:integer]: TSwiftNode read GetChild;
function CreateChild: TSwiftNode;
procedure RemoveChild(n: integer);
procedure DestroyChild(n: integer);
property VirtualNode: PVirtualNode read FVirtualNode write FVirtualNode;
end;
TSwiftTree = class
private
FRoot: TSwiftNode;
FSettingViewer: integer;
FViewer: TObject;
procedure SetViewer(aViewer: TObject);
public
constructor Create;
destructor Destroy; override;
property Root: TSwiftNode read FRoot;
property Viewer: TObject read FViewer write SetViewer;
procedure BeginUpdate;
procedure EndUpdate;
end;
TSwiftEditLink = class;
TSwiftTreeView = class(TCustomVirtualStringTree)
private
FTree:TSwiftTree;
FInternalDataOffset: Cardinal; // offset to the internal data
procedure SetTree(aTree: TSwiftTree);
function GetSwiftNode(VirtualNode: PVirtualNode): TSwiftNode;
procedure SetSwiftNode(VirtualNode: PVirtualNode; aNode: TSwiftNode);
function GetOptions: TStringTreeOptions;
procedure SetOptions(const Value: TStringTreeOptions);
protected
function DoGetNodeWidth(Node: PVirtualNode; Column: TColumnIndex;
Canvas: TCanvas = nil): Integer; override;
procedure DoPaintNode(var PaintInfo: TVTPaintInfo); override;
procedure DoInitChildren(Node:PVirtualNode; var ChildCount:Cardinal); override;
procedure DoInitNode(aParent,aNode:PVirtualNode;
var aInitStates:TVirtualNodeInitStates); override;
procedure DoFreeNode(aNode: PVirtualNode); override;
function DoGetImageIndex(Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var Index: Integer): TCustomImageList; override;
procedure DoChecked(aNode:PVirtualNode); override;
function DoCreateEditor(Node: PVirtualNode; Column: TColumnIndex): IVTEditLink; override;
function InternalData(Node: PVirtualNode): Pointer;
function InternalDataSize: Cardinal;
function GetOptionsClass: TTreeOptionsClass; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Tree: TSwiftTree read FTree write SetTree;
property SwiftNode[VirtualNode:PVirtualNode]: TSwiftNode read GetSwiftNode;
function GetNodeText(aNode:TSwiftNode; aColumn:integer):string;
procedure SetNodeText(aNode:TSwiftNode; aColumn:integer; aText:string);
published
property TreeOptions: TStringTreeOptions read GetOptions write SetOptions;
property Header;
property Images;
property OnChange;
property OnInitNode;
property OnMeasureItem;
property OnPaintText;
property OnBeforeCellPaint;
end;
TSwiftEdit=class(TCustomEdit)
private
FLink: TSwiftEditLink;
procedure WMChar(var Message: TWMChar); message WM_CHAR;
procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
procedure WMKillFocus(var Msg: TWMKillFocus); message WM_KILLFOCUS;
protected
procedure AutoAdjustSize;
procedure CreateParams(var Params: TCreateParams); override;
public
constructor Create(Link: TSwiftEditLink); reintroduce;
end;
TSwiftEditLink = class(TInterfacedObject, IVTEditLink)
private
FEdit: TSwiftEdit; // a normal custom edit control
FTree: TSwiftTreeView; // a back reference to the tree calling
FNode: PVirtualNode; // the node to be edited
FColumn: Integer; // the column of the node
public
constructor Create;
destructor Destroy; override;
function BeginEdit: Boolean; stdcall;
function CancelEdit: Boolean; stdcall;
function EndEdit: Boolean; stdcall;
function GetBounds: TRect; stdcall;
function PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex): Boolean; stdcall;
procedure ProcessMessage(var Message: TMessage); stdcall;
procedure SetBounds(R: TRect); stdcall;
property Tree: TSwiftTreeView read FTree;
end;
implementation
{ TSwiftNode }
constructor TSwiftNode.Create;
begin
inherited Create;
FChildren := TList.Create;
end;
destructor TSwiftNode.Destroy;
begin
if Assigned(FParent) then
with FParent do
RemoveChild(FChildren.IndexOf(Self));
{ Уничтожение всех дочерних элементов }
while ChildCount>0 do DestroyChild(0);
inherited Destroy;
end;
function TSwiftNode.GetImageIndex:integer;
begin
if TagName = ''
then Result := -1 else Result := (Length(TagName) mod 4);
end;
procedure TSwiftNode.InvalidateVirtualNode;
var T:TBaseVirtualTree;
begin
{ Если дерево имеет узел, отображаем этот узел. }
if Assigned(FVirtualNode) then
begin
T := TreeFromNode(FVirtualNode);
T.InvalidateNode(FVirtualNode);
end;
end;
procedure TSwiftNode.SetCheckState(aCheckState:TCheckState);
begin
if aCheckState = FCheckstate then exit;
FCheckState := aCheckState;
if Assigned(FVirtualNode) then FVirtualNode.CheckState := aCheckState;
InvalidateVirtualNode;
end;
procedure TSwiftNode.SetTagName(aTagName:string);
begin
if aTagName = FTagName then exit;
FTagName := aTagName;
InvalidateVirtualNode;
end;
procedure TSwiftNode.SetTagValue(aTagValue:string);
begin
if aTagValue = FTagValue then exit;
FTagValue := aTagValue;
InvalidateVirtualNode;
end;
function TSwiftNode.GetChildCount:integer;
begin
Result := FChildren.Count;
end;
function TSwiftNode.GetChild(n:integer): TSwiftNode;
begin
Result := TSwiftNode(FChildren[n]);
end;
function TSwiftNode.CreateChild: TSwiftNode;
begin
Result := TSwiftNode.Create;
Result.FParent := Self;
FChildren.Add(Result);
if Assigned(FVirtualNode) then begin
with TreeFromNode(FVirtualNode) do begin
ReinitNode(FVirtualNode, False);
InvalidateToBottom(FVirtualNode);
end;
end;
end;
procedure TSwiftNode.RemoveChild(n:integer);
var C: TSwiftNode;
begin
{ Удаляем дочерний узел из списка узлолв }
C := Child[n];
C.FParent := nil;
FChildren.Delete(n);
if Assigned(C.FVirtualNode) then
TreeFromNode(C.FVirtualNode).DeleteNode(C.FVirtualNode);
end;
procedure TSwiftNode.DestroyChild(n:integer);
var C: TSwiftNode;
begin
C := Child[n];
RemoveChild(n);
C.Free;
end;
{ TSwiftTree }
constructor TSwiftTree.Create;
begin
inherited Create;
FRoot := TSwiftNode.Create;
end;
destructor TSwiftTree.Destroy;
begin
Viewer := nil;
FRoot.Free;
FRoot := nil;
inherited Destroy;
end;
procedure TSwiftTree.SetViewer(aViewer:TObject);
begin
if FSettingViewer > 0 then exit;
inc(FSettingViewer);
try
if Assigned(FViewer) then TSwiftTreeView(FViewer).Tree := nil;
FViewer := aViewer;
if Assigned(FViewer) then TSwiftTreeView(FViewer).Tree := Self;
finally
dec(FSettingViewer);
end;
end;
procedure TSwiftTree.BeginUpdate;
begin
if Assigned(FViewer) then TSwiftTreeView(FViewer).BeginUpdate;
end;
procedure TSwiftTree.EndUpdate;
begin
if Assigned(FViewer) then TSwiftTreeView(FViewer).EndUpdate;
end;
{ TSwiftTreeView }
type PMyNodeData = ^TMyNodeData;
TMyNodeData = packed record Node: TSwiftNode end;
destructor TSwiftTreeView.Destroy;
begin
Tree := nil;
inherited Destroy;
end;
procedure TSwiftTreeView.SetTree(aTree: TSwiftTree);
begin
if FTree = aTree then exit;
if Assigned(FTree) then FTree.Viewer := nil;
FTree := aTree;
if Assigned(FTree) then begin
FTree.Viewer := Self;
RootNodeCount := FTree.Root.ChildCount;
if FTree.Root.ChildCount > 0 then ValidateNode(GetFirst, False);
end else RootNodeCount := 0;
end;
function TSwiftTreeView.GetSwiftNode(VirtualNode: PVirtualNode): TSwiftNode;
begin
if VirtualNode = nil then Result := nil
else Result := PMyNodeData(InternalData(VirtualNode)).Node;
end;
procedure TSwiftTreeView.SetSwiftNode(VirtualNode:PVirtualNode;aNode: TSwiftNode);
begin
PMyNodeData(InternalData(VirtualNode)).Node := aNode;
end;
function TSwiftTreeView.DoCreateEditor(Node: PVirtualNode; Column: TColumnIndex): IVTEditLink;
var Link: TSwiftEditLink;
begin
Result := inherited DoCreateEditor(Node, Column);
if Result = nil then
begin
Link := TSwiftEditLink.Create;
Result := Link;
end;
end;
function TSwiftTreeView.DoGetNodeWidth(Node: PVirtualNode; Column: TColumnIndex;
Canvas: TCanvas = nil): Integer;
var
N: TSwiftNode;
Text: string;
begin
N := GetSwiftNode(Node);
if Canvas = nil then
Canvas := Self.Canvas;
if not Assigned(N) then Result := 0
else begin
Text := GetNodeText(N, Column);
Result := Canvas.TextWidth(Text);
end;
end;
function TSwiftTreeView.GetNodeText(aNode:TSwiftNode;aColumn:integer):string;
begin
case aColumn of
-1, 0: Result := aNode.TagName;
1: Result := aNode.TagValue;
else Result:='Нет данных';
end;
end;
procedure TSwiftTreeView.SetNodeText(aNode: TSwiftNode; aColumn: integer; aText: string);
begin
case aColumn of
-1,0: aNode.TagName := aText;
1: aNode.TagValue := aText;
else
end;
end;
procedure TSwiftTreeView.DoPaintNode(var PaintInfo: TVTPaintInfo);
var
N: TSwiftNode;
SaveFontColor: TColor;
Flags: Integer;
TxtRect: TRect;
NodeText: string;
OldBrushColor, OldPenColor: TColor;
procedure SaveDC;
begin
OldBrushColor := PaintInfo.Canvas.Brush.Color;
OldPenColor := PaintInfo.Canvas.Pen.Color;
end;
procedure RestoreDC;
begin
PaintInfo.Canvas.Brush.Color := OldBrushColor;
PaintInfo.Canvas.Pen.Color := OldPenColor;
end;
begin
SaveDC;
try
with PaintInfo, Canvas do begin
Font := Self.Font;
N := SwiftNode[Node];
if N = nil then exit;
NodeText := GetNodeText(N, Column);
if (toHotTrack in Self.TreeOptions.PaintOptions) and
(Node = HotNode)
then Font.Style := Font.Style + [fsUnderline]
else Font.Style := Font.Style - [fsUnderline];
if vsSelected in Node.States then begin
if Focused then begin
Brush.Color := clHighLight;
Font.Color := clWhite;
end else begin
Brush.Color := clBtnFace;
Font.Color := Self.Font.Color;
end;
FillRect(ContentRect);
end else if Node = DropTargetNode then begin
if LastDropMode = dmOnNode then begin
Brush.Color := clHighLight;
Font.Color := clWhite;
end else begin
Brush.Style := bsClear;
Font.Color := Self.Font.Color;
end;
FillRect(ContentRect);
end;
if Focused
and (FocusedNode = Node) and
not(toFullRowSelect in Self.TreeOptions.SelectionOptions)
then begin
if Self.Color = clGray
then Brush.Color := clWhite
else Brush.Color := clBlack;
SaveFontColor := Font.Color;
Font.Color := Self.Color;
Windows.DrawFocusRect(Handle, ContentRect);
Font.Color:=SaveFontColor;
end;
if vsDisabled in Node.States then Font.Color := clBtnShadow;
Brush.Color := Color;
SetBkMode(Handle, TRANSPARENT);
TxtRect.Left := ContentRect.Left;
TxtRect.Top := ContentRect.Top;
TxtRect.Right := ContentRect.Right;
TxtRect.Bottom := ContentRect.Bottom;
Flags := DT_LEFT or DT_SINGLELINE or DT_VCENTER;
DrawText(Handle, PChar(NodeText), Length(NodeText), TxtRect, Flags);
end;
finally
RestoreDC;
end;
end;
procedure TSwiftTreeView.DoFreeNode(aNode:PVirtualNode);
var
N: TSwiftNode;
begin
N := SwiftNode[aNode];
if Assigned(N) then begin
N.VirtualNode := nil;
SetSwiftNode(aNode, nil);
end;
inherited DoFreeNode(aNode);
end;
procedure TSwiftTreeView.DoInitChildren(Node:PVirtualNode; var ChildCount:Cardinal);
begin
inherited DoInitChildren(Node, ChildCount);
ChildCount := SwiftNode[Node].ChildCount;
end;
procedure TSwiftTreeView.DoInitNode(aParent,aNode:PVirtualNode;
var aInitStates:TVirtualNodeInitStates);
var
P,I: TSwiftNode;
begin
inherited DoInitNode(aParent, aNode, aInitStates);
with aNode^ do begin
if (aParent = RootNode) or (aParent = nil)
then P := FTree.Root
else P := SwiftNode[aParent];
I := P.Child[Index];
SetSwiftNode(aNode, I);
I.VirtualNode := aNode;
if I.ChildCount > 0
then Include(aInitStates, ivsHasChildren)
else Exclude(aInitStates, ivsHasChildren);
CheckState := I.CheckState;
end;
end;
function TSwiftTreeView.DoGetImageIndex(Node: PVirtualNode; Kind: TVTImageKind;
Column: TColumnIndex; var Ghosted: Boolean; var Index: Integer): TCustomImageList;
var
N: TSwiftNode;
begin
Result := nil;
case Column of
-1,0:begin
N := SwiftNode[Node];
if N = nil
then Index := -1
else Index := N.GetImageIndex;
end;
else Index := -1;
end;
end;
procedure TSwiftTreeView.DoChecked(aNode: PVirtualNode);
var
N: TSwiftNode;
begin
if Assigned(FTree) then begin
N := SwiftNode[aNode];
if Assigned(N) then N.CheckState := aNode^.CheckState;
end;
inherited DoChecked(aNode);
end;
function TSwiftTreeView.InternalData(Node: PVirtualNode): Pointer;
begin
if (Node = RootNode) or (Node = nil) then
Result := nil
else
Result := PByte(Node) + FInternalDataOffset;
end;
function TSwiftTreeView.InternalDataSize: Cardinal;
begin
Result := SizeOf(TMyNodeData);
end;
constructor TSwiftTreeView.Create(AOwner: TComponent);
begin
inherited;
FInternalDataOffset := AllocateInternalDataArea(SizeOf(Cardinal));
end;
function TSwiftTreeView.GetOptions: TStringTreeOptions;
begin
Result := inherited TreeOptions as TStringTreeOptions;
end;
procedure TSwiftTreeView.SetOptions(const Value: TStringTreeOptions);
begin
TreeOptions.Assign(Value);
end;
function TSwiftTreeView.GetOptionsClass: TTreeOptionsClass;
begin
Result := TStringTreeOptions;
end;
{ TSwiftEditLink }
constructor TSwiftEditLink.Create;
begin
inherited;
FEdit := TSwiftEdit.Create(Self);
with FEdit do
begin
Visible := False;
Ctl3D := False;
BorderStyle := bsSingle;
AutoSize := False;
end;
end;
destructor TSwiftEditLink.Destroy;
begin
FEdit.Free;
inherited;
end;
function TSwiftEditLink.BeginEdit: Boolean;
begin
Result := True;
FEdit.Show;
FEdit.SetFocus;
end;
function TSwiftEditLink.CancelEdit: Boolean;
begin
Result := True;
FTree := nil;
FEdit.Hide;
end;
function TSwiftEditLink.EndEdit: Boolean;
var
LastTree: TSwiftTreeView;
N: TSwiftNode;
begin
Result := True;
try
if Assigned(FTree) then begin
if FEdit.Modified then begin
N := FTree.SwiftNode[FNode];
LastTree := FTree;
FTree := nil;
LastTree.SetNodeText(N, FColumn, FEdit.Caption);
end;
FTree:=nil;
end;
finally
FEdit.Hide;
end;
end;
function TSwiftEditLink.GetBounds: TRect;
begin
Result := FEdit.BoundsRect;
end;
function TSwiftEditLink.PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode;
Column:TColumnIndex): Boolean;
var
R: TRect;
N: TSwiftNode;
begin
Result := True;
FTree := Tree as TSwiftTreeView;
FNode := Node;
FColumn := Column;
N := FTree.SwiftNode[Node];
FEdit.Caption := FTree.GetNodeText(N, Column);
FEdit.Parent := Tree;
R := FTree.GetDisplayRect(Node, Column, True);
with R do begin
// границы редактора
if Right - Left < 50 then Right := Left + 50;
if Right > FTree.Width then Right := FTree.Width;
FEdit.SetBounds(Left, Top, Right - Left, Bottom - Top);
FEdit.Font := FTree.Font;
end;
end;
procedure TSwiftEditLink.SetBounds(R: TRect);
begin
// ignore this one as we get here the entire node rect but want the minimal text bounds
end;
constructor TSwiftEdit.Create(Link: TSwiftEditLink);
begin
inherited Create(nil);
ShowHint := False;
ParentShowHint := False;
FLink := Link;
end;
{ TSwiftEdit }
procedure TSwiftEdit.WMChar(var Message: TWMChar);
begin
if Message.CharCode <> VK_ESCAPE then begin
inherited;
if Message.CharCode > $20 then AutoAdjustSize;
end;
end;
procedure TSwiftEdit.WMKeyDown(var Message: TWMKeyDown);
begin
case Message.CharCode of
// pretend these keycodes were send to the tree
VK_ESCAPE,
VK_UP,
VK_DOWN:
FLink.FTree.WndProc(TMessage(Message));
VK_RETURN:
FLink.FTree.DoEndEdit;
Ord('C'):
if (Message.KeyData and MK_CONTROL) <> 0 then CopyToClipboard;
Ord('X'):
if (Message.KeyData and MK_CONTROL) <> 0 then
begin
CutToClipboard;
AutoAdjustSize;
end;
Ord('V'):
if (Message.KeyData and MK_CONTROL) <> 0 then begin
PasteFromClipboard;
AutoAdjustSize;
end;
else
inherited;
case Message.CharCode of
VK_BACK,
VK_DELETE:
AutoAdjustSize;
end;
end;
end;
procedure TSwiftEdit.WMKillFocus(var Msg: TWMKillFocus);
begin
inherited;
if Assigned(FLink.FTree) then FLink.FTree.DoCancelEdit;
end;
procedure TSwiftEdit.AutoAdjustSize;
var
DC: HDC;
Size: TSize;
EditRect,
TreeRect: TRect;
begin
DC := GetDc(Handle);
GetTextExtentPoint32(DC, PChar(Text), Length(Text), Size);
// determine minimum and maximum sizes
if Size.cx < 50 then Size.cx := 50;
EditRect := ClientRect;
MapWindowPoints(Handle, HWND_DESKTOP, EditRect, 2);
TreeRect := FLink.FTree.ClientRect;
MapWindowPoints(FLink.FTree.Handle, HWND_DESKTOP, TreeRect, 2);
if (EditRect.Left + Size.cx) > TreeRect.Right then Size.cx := TreeRect.Right - EditRect.Left;
SetWindowPos(Handle, 0, 0, 0, Size.cx, Height, SWP_NOMOVE or SWP_NOOWNERZORDER or SWP_NOZORDER);
ReleaseDC(Handle, DC);
end;
procedure TSwiftEdit.CreateParams(var Params:TCreateParams);
begin
Ctl3D := False;
inherited;
end;
procedure TSwiftEditLink.ProcessMessage(var Message: TMessage);
begin
// nothing to do
end;
end.
|
unit IdUriUtils;
interface
{$i IdCompilerDefines.inc}
{$IFDEF DOTNET}
{$DEFINE HAS_ConvertToUtf32}
{$ENDIF}
{$IFDEF HAS_TCharacter}
{$DEFINE HAS_ConvertToUtf32}
{$ENDIF}
{$IFDEF DOTNET}
{$DEFINE HAS_String_IndexOf}
{$ENDIF}
{$IFDEF HAS_SysUtils_TStringHelper}
{$DEFINE HAS_String_IndexOf}
{$ENDIF}
uses
IdGlobal
{$IFNDEF DOTNET}
{$IFDEF HAS_ConvertToUtf32}
, Character
{$ELSE}
, IdException
{$ENDIF}
{$IFDEF HAS_String_IndexOf}
, SysUtils
{$ENDIF}
{$ENDIF}
;
{$IFNDEF HAS_ConvertToUtf32}
type
//for .NET, we use Char.ConvertToUtf32() as-is
//for D2009+, we use TCharacter.ConvertToUtf32() as-is
EIdUTF16Exception = class(EIdException);
EIdUTF16IndexOutOfRange = class(EIdUTF16Exception);
EIdUTF16InvalidHighSurrogate = class(EIdUTF16Exception);
EIdUTF16InvalidLowSurrogate = class(EIdUTF16Exception);
EIdUTF16MissingLowSurrogate = class(EIdUTF16Exception);
{$ENDIF}
// calculates character length, including surrogates
function CalcUTF16CharLength(const AStr: {$IFDEF STRING_IS_UNICODE}string{$ELSE}TIdWideChars{$ENDIF}; const AIndex: Integer): Integer;
function WideCharIsInSet(const ASet: TIdUnicodeString; const AChar: WideChar): Boolean;
function GetUTF16Codepoint(const AStr: {$IFDEF STRING_IS_UNICODE}string{$ELSE}TIdWideChars{$ENDIF}; const AIndex: Integer): Integer;
implementation
{$IFNDEF HAS_ConvertToUtf32}
uses
IdResourceStringsProtocols,
IdResourceStringsUriUtils;
{$ENDIF}
function CalcUTF16CharLength(const AStr: {$IFDEF STRING_IS_UNICODE}string{$ELSE}TIdWideChars{$ENDIF};
const AIndex: Integer): Integer;
{$IFDEF DOTNET}
var
C: Integer;
{$ELSE}
{$IFDEF HAS_ConvertToUtf32}
{$IFDEF USE_INLINE}inline;{$ENDIF}
{$ELSE}
var
C: WideChar;
{$ENDIF}
{$ENDIF}
begin
{$IFDEF DOTNET}
C := System.Char.ConvertToUtf32(AStr, AIndex-1);
if (C >= #$10000) and (C <= #$10FFFF) then begin
Result := 2;
end else begin
Result := 1;
end;
{$ELSE}
{$IFDEF HAS_TCharacter}
TCharacter.ConvertToUtf32(AStr, AIndex, Result);
{$ELSE}
if (AIndex < {$IFDEF STRING_IS_UNICODE}1{$ELSE}0{$ENDIF}) or
(AIndex > (Length(AStr){$IFNDEF STRING_IS_UNICODE}-1{$ENDIF})) then
begin
raise EIdUTF16IndexOutOfRange.CreateResFmt(@RSUTF16IndexOutOfRange, [AIndex, Length(AStr)]);
end;
C := AStr[AIndex];
if (C >= #$D800) and (C <= #$DFFF) then
begin
if C > #$DBFF then begin
raise EIdUTF16InvalidHighSurrogate.CreateResFmt(@RSUTF16InvalidHighSurrogate, [AIndex]);
end;
if AIndex = (Length(AStr){$IFNDEF STRING_IS_UNICODE}-1{$ENDIF}) then begin
raise EIdUTF16MissingLowSurrogate.CreateRes(@RSUTF16MissingLowSurrogate);
end;
C := AStr[AIndex+1];
if (C < #$DC00) or (C > #$DFFF) then begin
raise EIdUTF16InvalidLowSurrogate.CreateResFmt(@RSUTF16InvalidLowSurrogate, [AIndex+1]);
end;
Result := 2;
end else begin
Result := 1;
end;
{$ENDIF}
{$ENDIF}
end;
function WideCharIsInSet(const ASet: TIdUnicodeString; const AChar: WideChar): Boolean;
{$IFDEF HAS_String_IndexOf}
{$IFDEF USE_INLINE}inline;{$ENDIF}
{$ELSE}
var
I: Integer;
{$ENDIF}
begin
{$IFDEF HAS_String_IndexOf}
Result := ASet.IndexOf(AChar) > -1;
{$ELSE}
// RLebeau 5/8/08: Calling Pos() with a Char as input creates a temporary
// String. Normally this is fine, but profiling reveils this to be a big
// bottleneck for code that makes a lot of calls to CharIsInSet(), so need
// to scan through ASet looking for the character without a conversion...
//
// Result := IndyPos(AString[ACharPos], ASet);
//
Result := False;
for I := 1 to Length(ASet) do begin
if ASet[I] = AChar then begin
Result := True;
Exit;
end;
end;
{$ENDIF}
end;
function GetUTF16Codepoint(const AStr: {$IFDEF STRING_IS_UNICODE}string{$ELSE}TIdWideChars{$ENDIF};
const AIndex: Integer): Integer;
{$IFDEF HAS_ConvertToUtf32}
{$IFDEF USE_INLINE}inline;{$ENDIF}
{$ELSE}
var
C: WideChar;
LowSurrogate, HighSurrogate: Integer;
{$ENDIF}
begin
{$IFDEF DOTNET}
Result := System.Char.ConvertToUtf32(AStr, AIndex-1);
{$ELSE}
{$IFDEF HAS_TCharacter}
Result := TCharacter.ConvertToUtf32(AStr, AIndex);
{$ELSE}
if (AIndex < {$IFDEF STRING_IS_UNICODE}1{$ELSE}0{$ENDIF}) or
(AIndex > (Length(AStr){$IFNDEF STRING_IS_UNICODE}-1{$ENDIF})) then
begin
raise EIdUTF16IndexOutOfRange.CreateResFmt(@RSUTF16IndexOutOfRange, [AIndex, Length(AStr)]);
end;
C := AStr[AIndex];
if (C >= #$D800) and (C <= #$DFFF) then
begin
HighSurrogate := Integer(C);
if HighSurrogate > $DBFF then begin
raise EIdUTF16InvalidHighSurrogate.CreateResFmt(@RSUTF16InvalidHighSurrogate, [AIndex]);
end;
if AIndex = (Length(AStr){$IFNDEF STRING_IS_UNICODE}-1{$ENDIF}) then begin
raise EIdUTF16MissingLowSurrogate.CreateRes(@RSUTF16MissingLowSurrogate);
end;
LowSurrogate := Integer(AStr[AIndex+1]);
if (LowSurrogate < $DC00) or (LowSurrogate > $DFFF) then begin
raise EIdUTF16InvalidLowSurrogate.CreateResFmt(@RSUTF16InvalidLowSurrogate, [AIndex+1]);
end;
Result := ((HighSurrogate - $D800) shl 10) or (LowSurrogate - $DC00) + $10000;
end else begin
Result := Integer(C);
end;
{$ENDIF}
{$ENDIF}
end;
end.
|
unit BaseForms;
(*
The module contains classes of the Base DataModule, Base Form and Base Frame,
which is intended to replace the standard classes.
These Base classes will help get around some bugs VCL, and expand the standard
functionality
****************************************************************
Author : Zverev Nikolay (delphinotes.ru)
Created : 30.08.2006
Modified : 04.11.2021
Version : 1.04
History :
****************************************************************
Before using this module the package
packages\BaseFormsDesignXXX.dpk
must be installed. If the file changes, you need to reinstall the package.
*)
interface
{$i jedi.inc}
{$i BaseForms.inc}
{$ifdef HAS_UNITSCOPE}
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Contnrs,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms;
{$else}
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Contnrs,
Graphics,
Controls,
Forms;
{$endif}
//const
// WM_DPICHANGED = 736; // 0x02E0
type
TAutoFreeOnEvent = (afDefault, afHide, afDestroy);
TBaseForm = class;
TBaseFormClass = class of TBaseForm;
TBaseFrame = class;
TBaseFrameClass = class of TBaseFrame;
{ TBaseDataModule }
TBaseDataModule = class(TDataModule)
{$ifdef Allow_Localization}
{$i BaseFormsLocalizeIntf.inc}
{$endif}
protected
FAutoFreeObjects: TObjectList;
procedure DoCreate; override;
procedure DoDestroy; override;
procedure ReadState(Reader: TReader); override;
public
function AutoFree(AObject: TObject): Pointer;
published
// standart properties - add the 'default' to not saved in dfm
property OldCreateOrder default False;
end;
{ TBaseForm }
TBaseForm = class(TForm)
{$ifdef Allow_Localization}
{$i BaseFormsLocalizeIntf.inc}
{$endif}
//published
// наследуемые свойства:
//property AutoScroll default False;
//property Position default poScreenCenter;
//property ShowHint default True;
protected
{$ifdef Allow_ScaleFix}
FPixelsPerInch: Integer;
FNCHeight: Integer;
FNCWidth: Integer;
{$endif}
private
FCloseByEscape: Boolean;
FFreeOnClose: Boolean;
FInMouseWheelHandler: Boolean;
FUseAdvancedWheelHandler: Boolean;
procedure WriteClientHeight(Writer: TWriter);
procedure WriteClientWidth(Writer: TWriter);
{$ifdef Allow_ScaleFix}
procedure WriteScaleFix(Writer: TWriter);
procedure WriteNCHeight(Writer: TWriter);
procedure WriteNCWidth(Writer: TWriter);
procedure ReadNCHeight(Reader: TReader);
procedure ReadNCWidth(Reader: TReader);
{$endif}
procedure ReadScaleFix(Reader: TReader);
procedure CMChildKey(var Message: TCMChildKey); message CM_CHILDKEY;
procedure WMSetIcon(var Message: TWMSetIcon); message WM_SETICON;
procedure WMSysCommand(var Message: TWMSysCommand); message WM_SYSCOMMAND;
procedure WMQueryOpen(var Message: TWMQueryOpen); message WM_QUERYOPEN;
procedure WMActivate(var Message: TWMActivate); message WM_ACTIVATE;
procedure WMWindowPosChanged(var Msg: TWMWindowPosChanged); message WM_WINDOWPOSCHANGED;
//procedure WMDpiChanged(var Message: TMessage); message WM_DPICHANGED;
//procedure CMParentFontChanged(var Message: TCMParentFontChanged); message CM_PARENTFONTCHANGED;
protected
FAutoFreeOnHide: TObjectList;
FAutoFreeOnDestroy: TObjectList;
procedure InitializeNewForm; {$ifdef TCustomForm_InitializeNewForm}override;{$else}dynamic;{$endif}
procedure DefineProperties(Filer: TFiler); override;
function HandleCreateException: Boolean; override;
procedure DoClose(var Action: TCloseAction); override;
procedure DoHide; override;
procedure DoDestroy; override;
procedure Loaded; override;
function PostCloseMessage: LRESULT;
public
{$ifndef TCustomForm_InitializeNewForm}
constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
{$endif}
procedure MouseWheelHandler(var Message: TMessage); override;
function AutoFree(AObject: TObject; OnEvent: TAutoFreeOnEvent = afDefault): Pointer;
published
property CloseByEscape: Boolean read FCloseByEscape write FCloseByEscape default True;
property FreeOnClose: Boolean read FFreeOnClose write FFreeOnClose default False;
property UseAdvancedWheelHandler: Boolean read FUseAdvancedWheelHandler write FUseAdvancedWheelHandler default True;
published
// standart properties - add the 'default' to not saved in dfm
property OldCreateOrder default False;
property Left default 0;
property Top default 0;
property ParentFont default True;
property Color default clBtnFace;
end;
{ TBaseFrame }
TBaseFrame = class(TFrame)
private
{$ifdef Allow_Localization}
{$i BaseFormsLocalizeIntf.inc}
{$endif}
// protected
// FAutoFreeObjects: TObjectList;
// procedure DoDestroy; override;
private
{$ifdef Allow_ScaleFix}
FPixelsPerInch: Integer;
procedure WritePixelsPerInch(Writer: TWriter);
{$endif}
procedure ReadPixelsPerInch(Reader: TReader);
protected
procedure DefineProperties(Filer: TFiler); override;
procedure Loaded; override;
published
// standart properties - add the 'default' to not saved in dfm
property Left default 0;
property Top default 0;
property TabOrder default 0;
end;
procedure ClearUserInput;
{.$region 'LocalizationStub'}
{$ifdef Allow_Localization}
procedure LocalizeDataModule(ADataModule: TDataModule);
procedure LocalizeForm(AForm: TCustomForm);
procedure LocalizeFrame(AFrame: TCustomFrame);
procedure LocalizeRootComponent(Instance: TComponent);
function ResGet(Section: TClass; const StringID: string; const DefaultValue: string = ''): string; overload;
function ResGet(const Section, StringID: string; const DefaultValue: string = ''): string; overload;
{$endif}
{.$endregion}
{$ifdef SUPPORTS_CLASS_HELPERS}
type
TFormHelper = class helper for TCustomForm
// сhanging properties through Property causes windowhandle to be recreated (if any)
// and Visible to be set True
// the hack is needed to bypass this behavior
procedure SafeSetBorderIcons(ABorderIcons: TBorderIcons);
procedure SafeSetBorderStyle(ABorderStyle: TFormBorderStyle);
procedure SafeSetFormStyle(AFormStyle: TFormStyle);
procedure SafeSetPosition(APosition: TPosition);
procedure SafeSetWidowState(AWindowState: TWindowState);
end;
{$endif}
implementation
uses
{$ifdef Allow_ScaleFix}
uScaleControls,
{$endif}
{$ifdef HAS_UNITSCOPE}
System.Types,
Vcl.StdCtrls;
{$else}
Types,
StdCtrls;
{$endif}
//{$ifdef Allow_ScaleFix}
//const
// DesignerDefaultFontName = 'Tahoma';
//{$endif}
procedure ClearUserInput;
var
Msg: TMsg;
NeedTerminate: Boolean;
begin
NeedTerminate := False;
while PeekMessage(Msg, 0, WM_MOUSEFIRST, WM_MOUSELAST, PM_REMOVE or PM_NOYIELD) do
NeedTerminate := NeedTerminate or (Msg.message = WM_QUIT);
while PeekMessage(Msg, 0, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE or PM_NOYIELD) do
NeedTerminate := NeedTerminate or (Msg.message = WM_QUIT);
if NeedTerminate then
Application.Terminate;
end;
{$i BaseFormsFrndHackTypes.inc}
{$ifdef SUPPORTS_CLASS_HELPERS}
{ TFormHelper }
procedure TFormHelper.SafeSetBorderIcons(ABorderIcons: TBorderIcons);
begin
THackCustomForm(Self).FBorderIcons := ABorderIcons;
end;
procedure TFormHelper.SafeSetBorderStyle(ABorderStyle: TFormBorderStyle);
begin
THackCustomForm(Self).FBorderStyle := ABorderStyle;
end;
procedure TFormHelper.SafeSetFormStyle(AFormStyle: TFormStyle);
begin
THackCustomForm(Self).FFormStyle := AFormStyle;
end;
procedure TFormHelper.SafeSetPosition(APosition: TPosition);
begin
THackCustomForm(Self).FPosition := APosition;
end;
procedure TFormHelper.SafeSetWidowState(AWindowState: TWindowState);
begin
THackCustomForm(Self).FWindowState := AWindowState;
end;
{$endif}
{.$region 'RestoreFormsPositions'}
type
TWndList = array of HWND;
var
GIsMinimizing: Boolean;
GIsRestoring: Boolean;
GIsActivating: Boolean;
GLastModalMinimized: TWndList;
GLastDisabled: TWndList;
procedure GetVisibleNotMinimized(var AWndList: TWndList);
var
LCount, i: Integer;
F: TForm;
begin
// gets a list of visible and non-minimized windows in the order in which they are displayed
SetLength(AWndList, Screen.FormCount);
LCount := 0;
for i := 0 to Screen.FormCount - 1 do
begin
F := Screen.Forms[i];
if (F.FormStyle <> fsMDIChild) and F.HandleAllocated and IsWindowVisible(F.Handle) and not IsIconic(F.Handle) then
begin
AWndList[LCount] := F.Handle;
Inc(LCount);
end;
end;
SetLength(AWndList, LCount);
end;
procedure GetDisabled(var AWndList: TWndList);
var
LCount, i: Integer;
F: TForm;
begin
// gets a list of visible and disabled windows
SetLength(AWndList, Screen.FormCount);
LCount := 0;
for i := 0 to Screen.FormCount - 1 do
begin
F := Screen.Forms[i];
if (F.FormStyle <> fsMDIChild) and F.HandleAllocated and IsWindowVisible(F.Handle) and not IsWindowEnabled(F.Handle) then
begin
AWndList[LCount] := F.Handle;
Inc(LCount);
end;
end;
SetLength(AWndList, LCount);
end;
procedure EnableDisabled;
var
i: Integer;
begin
// https://www.sql.ru/forum/actualutils.aspx?action=gotomsg&tid=1339878&msg=22391822
GetDisabled(GLastDisabled);
for i := Low(GLastDisabled) to High(GLastDisabled) do
EnableWindow(GLastDisabled[i], True);
end;
procedure DisableEnabled;
var
i: Integer;
begin
// https://www.sql.ru/forum/actualutils.aspx?action=gotomsg&tid=1339878&msg=22391822
for i := Low(GLastDisabled) to High(GLastDisabled) do
EnableWindow(GLastDisabled[i], False);
SetLength(GLastDisabled, 0);
end;
function IsWindowInList(AWnd: HWND; const AWndList: TWndList): Boolean;
var
i: Integer;
begin
Result := True;
for i := Low(AWndList) to High(AWndList) do
if AWndList[i] = AWnd then
Exit;
Result := False;
end;
function HandleMinimizeAllByModal: Boolean;
var
i: Integer;
begin
Result := False;
if GIsMinimizing then
Exit;
GIsMinimizing := True;
try
// save the list of non-minimized windows
GetVisibleNotMinimized(GLastModalMinimized);
// now minimize them all
for i := Low(GLastModalMinimized) to High(GLastModalMinimized) do
ShowWindow(GLastModalMinimized[i], SW_SHOWMINNOACTIVE);
Application.Minimize;
// save the list of disabled windows and enable them
EnableDisabled;
Result := True;
finally
GIsMinimizing := False;
end;
end;
function HandleRestoreMinimized(AWnd: HWND): Boolean;
var
i: Integer;
begin
Result := False;
if GIsRestoring then
Exit;
if Length(GLastModalMinimized) = 0 then
Exit;
GIsRestoring := True;
try
// disable previously enabled windows
DisableEnabled;
Application.Restore;
if not IsWindowInList(AWnd, GLastModalMinimized) then
ShowWindow(AWnd, SW_SHOWNOACTIVATE);
for i := High(GLastModalMinimized) downto Low(GLastModalMinimized) do
ShowWindow(GLastModalMinimized[i], SW_SHOWNOACTIVATE);
SetForegroundWindow(GLastModalMinimized[0]);
SetLength(GLastModalMinimized, 0);
Result := True;
finally
GIsRestoring := False;
end;
end;
function HandleActivateDisabled(AWnd: HWND): Boolean;
var
LWndList: TWndList;
i: Integer;
begin
Result := True;
if GIsActivating then
Exit;
// when activated by Alt+Tab, the WM_QUERYOPEN message is not sent, so we need to restore the minimized windows
if HandleRestoreMinimized(AWnd) then
Exit;
GetVisibleNotMinimized(LWndList);
if Length(LWndList) = 0 then
Exit;
GIsActivating := True;
try
for i := High(LWndList) downto Low(LWndList) do
BringWindowToTop(LWndList[i]);
SetForegroundWindow(LWndList[0]);
finally
GIsActivating := False;
end;
end;
{.$endregion}
{.$region 'LocalizationStub'}
{$ifdef Allow_Localization}
procedure LocalizeDataModule(ADataModule: TDataModule);
begin
LocalizeRootComponent(ADataModule);
end;
procedure LocalizeForm(AForm: TCustomForm);
begin
LocalizeRootComponent(AForm);
end;
procedure LocalizeFrame(AFrame: TCustomFrame);
begin
LocalizeRootComponent(AFrame);
end;
procedure LocalizeRootComponent(Instance: TComponent);
begin
// Call Localizer to Localize (Translate) Instance
{.$MESSAGE HINT 'sorry, not implemented yet'}
// TODO: do this
// Call user OnLocalize event handler:
if Instance is TBaseDataModule then
TBaseDataModule(Instance).Localize else
if Instance is TBaseForm then
TBaseForm(Instance).Localize else
if Instance is TBaseFrame then
TBaseFrame(Instance).Localize;
// else - send msg (WM_LOCALIZE) ?
end;
function ResGet(Section: TClass; const StringID: string; const DefaultValue: string = ''): string;
begin
Result := ResGet(Section.ClassName, StringID, DefaultValue);
end;
function ResGet(const Section, StringID: string; const DefaultValue: string = ''): string;
begin
{.$MESSAGE HINT 'sorry, not implemented yet'}
// TODO: do this
Result := DefaultValue;
end;
{$endif}
{.$endregion}
{ TBaseDataModule }
{$ifdef Allow_Localization}
procedure TBaseDataModule.DoLocalize;
begin
if Assigned(FOnLocalize) then
FOnLocalize(Self);
end;
procedure TBaseDataModule.Localize;
begin
DoLocalize;
end;
class function TBaseDataModule.ResGet(const StringID: string; const DefaultValue: string = ''): string;
begin
Result := BaseForms.ResGet(Self, StringID, DefaultValue);
end;
{$endif}
procedure TBaseDataModule.DoCreate;
begin
{$ifdef Allow_Localization}
LocalizeDataModule(Self);
{$endif}
inherited DoCreate;
end;
procedure TBaseDataModule.DoDestroy;
begin
inherited DoDestroy;
// destory auto free objects
FreeAndNil(FAutoFreeObjects);
end;
procedure TBaseDataModule.ReadState(Reader: TReader);
begin
// skip inherited, because there is seting OldCreateOrder to False
TFriendlyReader(Reader).ReadData(Self);
end;
function TBaseDataModule.AutoFree(AObject: TObject): Pointer;
begin
if not Assigned(FAutoFreeObjects) then
FAutoFreeObjects := TObjectList.Create;
FAutoFreeObjects.Add(AObject);
Result := AObject;
end;
{ TBaseForm }
{$ifdef Allow_Localization}
procedure TBaseForm.DoLocalize;
begin
if Assigned(FOnLocalize) then
FOnLocalize(Self);
end;
procedure TBaseForm.Localize;
begin
DoLocalize;
end;
class function TBaseForm.ResGet(const StringID: string; const DefaultValue: string = ''): string;
begin
Result := BaseForms.ResGet(Self, StringID, DefaultValue);
end;
{$endif}
procedure TBaseForm.WriteClientHeight(Writer: TWriter);
begin
Writer.WriteInteger(ClientHeight);
end;
procedure TBaseForm.WriteClientWidth(Writer: TWriter);
begin
Writer.WriteInteger(ClientWidth);
end;
{$ifdef Allow_ScaleFix}
procedure TBaseForm.WriteScaleFix(Writer: TWriter);
begin
// just save flag to DFM for disable VCL scale on ReadState
Writer.WriteBoolean(True);
end;
procedure TBaseForm.WriteNCHeight(Writer: TWriter);
begin
Writer.WriteInteger(Height - ClientHeight);
end;
procedure TBaseForm.WriteNCWidth(Writer: TWriter);
begin
Writer.WriteInteger(Width - ClientWidth);
end;
procedure TBaseForm.ReadNCHeight(Reader: TReader);
begin
FNCHeight := Reader.ReadInteger;
end;
procedure TBaseForm.ReadNCWidth(Reader: TReader);
begin
FNCWidth := Reader.ReadInteger;
end;
{$endif}
procedure TBaseForm.ReadScaleFix(Reader: TReader);
begin
if not Reader.ReadBoolean then
Exit;
{$ifdef Allow_ScaleFix}
// save readed PixelsPerInch from DFM
FPixelsPerInch := THackCustomForm(Self).FPixelsPerInch;
// and set current value
THackCustomForm(Self).FPixelsPerInch := Screen.PixelsPerInch;
// reset TextHeight, for disable scale on VCL level
THackCustomForm(Self).FTextHeight := 0;
{$endif}
end;
procedure TBaseForm.InitializeNewForm;
begin
{$ifdef TCustomForm_InitializeNewForm}
inherited InitializeNewForm;
{$endif}
FCloseByEscape := True;
FUseAdvancedWheelHandler := True;
{$ifdef DoubleBufferedAlwaysOn}
DoubleBuffered := True;
{$endif}
ParentFont := True;
end;
{$ifndef TCustomForm_InitializeNewForm}
constructor TBaseForm.CreateNew(AOwner: TComponent; Dummy: Integer = 0);
begin
inherited CreateNew(AOwner, Dummy);
InitializeNewForm;
end;
{$endif}
procedure TBaseForm.MouseWheelHandler(var Message: TMessage);
procedure WheelMsgToScrollMsg(const AWheelMsg: TMessage; var AScrollMsg: TMessage; var AScrollCount: DWORD);
var
LWheelMsg: TWMMouseWheel absolute AWheelMsg;
LScrollMsg: TWMScroll absolute AScrollMsg;
//LShiftState: TShiftState;
begin
ZeroMemory(@LScrollMsg, SizeOf(LScrollMsg));
//LShiftState := KeysToShiftState(LWheelMsg.Keys);
// Если зажата Shift - горизонтальная прокрутка, иначе - вертикальная
//if ssShift in LShiftState then
if GetKeyState(VK_SHIFT) < 0 then
LScrollMsg.Msg := WM_HSCROLL
else
LScrollMsg.Msg := WM_VSCROLL;
// Если зажата Ctrl - прокручиваем страницами, иначе - построчно
//if ssCtrl in LShiftState then
if GetKeyState(VK_CONTROL) < 0 then
begin
if LWheelMsg.WheelDelta > 0 then
LScrollMsg.ScrollCode := SB_PAGEUP
else
LScrollMsg.ScrollCode := SB_PAGEDOWN;
// прокрутку выполняем один раз:
AScrollCount := 1;
end else
begin
if LWheelMsg.WheelDelta > 0 then
LScrollMsg.ScrollCode := SB_LINEUP
else
LScrollMsg.ScrollCode := SB_LINEDOWN;
// прокрутку делаем N-раз
//SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, @AScrollCount, 0);
AScrollCount := Mouse.WheelScrollLines;
if AScrollCount <= 0 then
AScrollCount := 1;
end;
end;
function IsScrollable(Control: TControl; IsVert: Boolean): Boolean;
begin
if Control is TScrollingWinControl then
begin
if IsVert then
Result := TScrollingWinControl(Control).VertScrollBar.IsScrollBarVisible
else
Result := TScrollingWinControl(Control).HorzScrollBar.IsScrollBarVisible;
end else
Result := False;
end;
function GetScrollPos(Control: TControl; IsVert: Boolean): Integer;
begin
if Control is TScrollingWinControl then
begin
if IsVert then
Result := TScrollingWinControl(Control).VertScrollBar.Position
else
Result := TScrollingWinControl(Control).HorzScrollBar.Position;
end else
Result := 0;
end;
procedure ScrollControl(Control: TControl; var AMessage: TMessage; ScrollCount: DWORD);
var
i: Integer;
begin
for i := 1 to ScrollCount do
Control.WindowProc(AMessage);
end;
var
LMsg: TWMMouseWheel absolute Message;
LMouseControl: TControl;
LControl: TControl;
LComponent: TComponent;
i: Integer;
LWMScroll: TMessage;
LScrollCount: DWORD;
LScrollPos: Integer;
begin
if not UseAdvancedWheelHandler then
begin
inherited MouseWheelHandler(Message);
Exit;
end;
// Переопределяем логику обработки колеса мыши следующим образом:
// а) ищем контрол под курсором
// б) далее ищем родительский, который имеет полосы прокрутки
// в) выполняем прокрутку
// г) но не забываем о том, что контрол в фокусе может иметь свою обработку, которую стоит запускать:
// - либо когда он под курсором
// - либо когда он имеет дочерние контролы с прокруткой
if FInMouseWheelHandler then
Exit;
FInMouseWheelHandler := True;
try
// Если мышь захвачена (например выпавшим списком в Combobox'е) - используем только дефолтовый обработчик
if GetCapture <> 0 then
begin
inherited MouseWheelHandler(Message);
Exit;
end;
// Ищем контрол под курсором
LMouseControl := FindControl(WindowFromPoint(SmallPointToPoint(TWMMouseWheel(Message).Pos)));
// Если он при этом в фокусе, отдаём обработку сначала ему
if (LMouseControl is TWinControl) and TWinControl(LMouseControl).Focused then
begin
// HINT: MouseWheelHandler генерирует CM_MOUSEWHEEL сообщение, которое может и не обработаться
// поэтому проверяем результат и посылаем сообщение (WM_MOUSEWHEEL) напрямую
inherited MouseWheelHandler(Message);
if Message.Result = 0 then
LMouseControl.WindowProc(Message);
if Message.Result <> 0 then
Exit;
end;
// Далее обрабатываем такую ситуацию: у контрола, который в фокусе, могут быть дочерние компоненты,
// умеющие обрабатывать прокрутку - проверяем это
// (например, выпадающие списки в EhLib)
if Assigned(ActiveControl) then
begin
for i := 0 to ActiveControl.ComponentCount - 1 do
begin
LComponent := ActiveControl.Components[i];
if (LComponent is TControl) and TControl(LComponent).Visible then
begin
TControl(LComponent).WindowProc(Message);
if Message.Result <> 0 then
Exit;
end;
end;
end;
// Теперь от контрола под курсором смотрим родительские и пытаемся выполнить прокрутку
// посредством передачи сообщения WM_HSCROLL/WM_VSCROLL
WheelMsgToScrollMsg(Message, LWMScroll, LScrollCount);
LControl := LMouseControl;
while Assigned(LControl) do
begin
if IsScrollable(LControl, LWMScroll.Msg = WM_VSCROLL) then
begin
// Здесь: нашли контрол с возможностью отреагировать на прокрутку
// Теперь обработчик по умолчанию вызываться не должен
Message.Result := 1;
// Пытаемся прокрутить, если при этом реальной прокрутки не было, то смотрим дальше
LScrollPos := GetScrollPos(LControl, LWMScroll.Msg = WM_VSCROLL);
ScrollControl(LControl, LWMScroll, LScrollCount);
if LWMScroll.Result = 0 then
if LScrollPos <> GetScrollPos(LControl, LWMScroll.Msg = WM_VSCROLL) then
LWMScroll.Result := 1;
if LWMScroll.Result <> 0 then
Break;
end;
LControl := LControl.Parent;
end;
{
if Message.Result <> 0 then
Exit;
// Так и не обработали, попробуем обработать прокрутку контролом напрямую
if Assigned(LMouseControl) then
// HINT: здесь используем CM_MOUSEWHEEL, т.к. WM_MOUSEWHEEL вызовет MouseWheelHandler, который придёт сюда
Message.Result := LMouseControl.Perform(CM_MOUSEWHEEL, Message.WParam, Message.LParam);
это плохо: CM_MOUSEWHEEL обрабатывается TDBComboboxEh, а хочется, чтобы только гридом
}
if Message.Result = 0 then
inherited MouseWheelHandler(Message);
finally
FInMouseWheelHandler := False;
end;
end;
procedure TBaseForm.DefineProperties(Filer: TFiler);
function NeedWriteClientSize: Boolean;
begin
//Result := Scaled and not IsClientSizeStored
// IsClientSizeStored = not IsFormSizeStored
// IsFormSizeStored = AutoScroll or (HorzScrollBar.Range <> 0) or (VertScrollBar.Range <> 0)
Result := Scaled and (AutoScroll or (HorzScrollBar.Range <> 0) or (VertScrollBar.Range <> 0));
end;
function NeedWriteNCHeight: Boolean;
begin
Result := Scaled and (Height <> ClientHeight) and ((Constraints.MinHeight <> 0) or (Constraints.MaxHeight <> 0));
end;
function NeedWriteNCWidth: Boolean;
begin
Result := Scaled and (Width <> ClientWidth) and ((Constraints.MinWidth <> 0) or (Constraints.MaxWidth <> 0));
end;
begin
inherited DefineProperties(Filer);
// ClientHeight и ClientWidth сохраняются не всегда, а вместо этого сохраняются внешние размеры формы.
// Это не совсем правильно, т.к. масштабировать необходимо именно клиентскую область. Функция NeedWriteClientSize
// определяет, нужно ли принудительно сохранять размер клиентской области.
Filer.DefineProperty('ClientHeight', nil, WriteClientHeight, NeedWriteClientSize);
Filer.DefineProperty('ClientWidth', nil, WriteClientWidth, NeedWriteClientSize);
{$ifdef Allow_ScaleFix}
// так же сохраняем разницу между внешними размерами и клиентской областью,
// это необходимо при использовании констрейнтов для корректного их масштабирования
Filer.DefineProperty('NCHeight', ReadNCHeight, WriteNCHeight, NeedWriteNCHeight);
Filer.DefineProperty('NCWidth', ReadNCWidth, WriteNCWidth, NeedWriteNCWidth);
Filer.DefineProperty('ScaleFix', ReadScaleFix, WriteScaleFix, Scaled);
{$else}
Filer.DefineProperty('ScaleFix', ReadScaleFix, nil, False);
{$endif}
end;
function TBaseForm.HandleCreateException: Boolean;
begin
Result := inherited HandleCreateException;
// HandleCreateException вызывает Application.HandleException(Self);
// при этом само исключение поглащается, тем самым ошибки в OnCreate формы не отменяют создание формы
// в итоге форма может создаться не до конца проинициализированной
// Меня это не устраивает, вызываем Abort для отмены операции создания формы при ошибках в OnCreate
if Result then
Abort; // TODO: AbortOnCreateError default True
end;
procedure TBaseForm.DoClose(var Action: TCloseAction);
begin
if FreeOnClose then
Action := caFree;
inherited DoClose(Action); // <- Form.OnClose
end;
procedure TBaseForm.DoHide;
begin
inherited DoHide; // <- Form.OnHide
// destory auto free objects
FreeAndNil(FAutoFreeOnHide);
end;
procedure TBaseForm.DoDestroy;
begin
inherited DoDestroy; // <- Form.OnDestroy
// destory auto free objects
FreeAndNil(FAutoFreeOnHide);
FreeAndNil(FAutoFreeOnDestroy);
end;
procedure TBaseForm.Loaded;
{$ifdef Allow_ScaleFix}
function DPIChanged: Boolean;
begin
Result := FPixelsPerInch <> Screen.PixelsPerInch;
end;
//function FontChanged: Boolean;
//begin
// Result := ParentFont and ((Application.DefaultFont.Name <> DesignerDefaultFontName) or (Application.DefaultFont.Size <> 8));
//end;
function NeedConstraintsResize: Boolean;
begin
//Result := (Constraints.MaxHeight <> 0) or (Constraints.MaxWidth <> 0)
// (Constraints.MinHeight <> 0) or (Constraints.MinWidth <> 0);
//if Result then
// Result
Result := (FNCHeight <> 0) or (FNCWidth <> 0);
end;
function NeedScale: Boolean;
begin
//Result := True;
//Exit;
Result := (FPixelsPerInch > 0) and (DPIChanged {or FontChanged} or NeedConstraintsResize);
end;
{$endif}
begin
{$ifdef Allow_ScaleFix}
//HINT: VCL использует ScalingFlags, анализируя их в ReadState
// ReadState вызывается для каждого класса в иерархии, у которых есть DFM ресурс,
// поэтому ScalingFlags используются, чтобы не промасштабировать
// что-то несколько раз.
//
// Сейчас масштабирование вынесено в Loaded, а FPixelsPerInch считывается только для Root-компонента,
// поэтому наше масштабирование вызываться будет один раз.
if NeedScale then
begin
uScaleControls.TScaleControls.Scale(Self, Screen.PixelsPerInch, FPixelsPerInch);
FPixelsPerInch := Screen.PixelsPerInch;
end;
{$endif}
inherited Loaded;
end;
function TBaseForm.PostCloseMessage: LRESULT;
begin
// for Modal state - talk Cancel
if fsModal in FormState then
begin
ModalResult := mrCancel;
Result := 1;
end else
// for normal - send command to close
Result := LRESULT(PostMessage(Handle, WM_CLOSE, 0, 0));
end;
function TBaseForm.AutoFree(AObject: TObject; OnEvent: TAutoFreeOnEvent = afDefault): Pointer;
begin
if OnEvent = afDefault then
if fsShowing in FormState
then OnEvent := afHide
else OnEvent := afDestroy;
case OnEvent of
afHide:
begin
if not Assigned(FAutoFreeOnHide) then
FAutoFreeOnHide := TObjectList.Create;
FAutoFreeOnHide.Add(AObject);
end;
afDestroy:
begin
if not Assigned(FAutoFreeOnDestroy) then
FAutoFreeOnDestroy := TObjectList.Create;
FAutoFreeOnDestroy.Add(AObject);
end;
else
Assert(False);
end;
Result := AObject;
end;
procedure TBaseForm.CMChildKey(var Message: TCMChildKey);
function WantSpecKey(AControl: TWinControl; ACharCode: Word): Boolean;
begin
repeat
Result := AControl.Perform(CM_WANTSPECIALKEY, WPARAM(ACharCode), LPARAM(0)) <> LRESULT(0);
if Result then
Exit;
AControl := AControl.Parent;
//AControl := AControl.Owner
until not Assigned(AControl) or (AControl = Self);
end;
begin
// handling CloseByEscape
if CloseByEscape then
with Message do
if (CharCode = VK_ESCAPE) and not WantSpecKey(Sender, CharCode) then
begin
Result := PostCloseMessage;
if Result <> 0 then
Exit;
end;
inherited;
end;
procedure TBaseForm.WMSetIcon(var Message: TWMSetIcon);
begin
// At the time of the destruction of the window ignore the installation icon
// (otherwise it is noticeable in animations in Windows Aero)
if (csDesigning in ComponentState) or not (csDestroying in ComponentState) then
inherited;
end;
procedure TBaseForm.WMSysCommand(var Message: TWMSysCommand);
begin
if (Message.CmdType = SC_MINIMIZE) and (fsModal in FormState) then
begin
// Here: window is in a Modal state, so wee need to minimize all non-minimized windows
if HandleMinimizeAllByModal then
begin
Message.Result := 1;
Exit;
end;
end;
inherited;
end;
procedure TBaseForm.WMQueryOpen(var Message: TWMQueryOpen);
begin
// Here: user clicked on minimized window icon in taskbar
if HandleRestoreMinimized(Handle) then
begin
Message.Result := 0;
Exit;
end;
inherited;
end;
procedure TBaseForm.WMActivate(var Message: TWMActivate);
begin
if not (csDesigning in ComponentState) and (Message.Active > 0) and not IsWindowEnabled(Handle) then
begin
// Here: our window is disabled, but somehow is activated,
// Most likely there is modal window, if any - then we must show them
if HandleActivateDisabled(Handle) then
begin
Message.Result := 0;
Exit;
end;
end;
inherited;
end;
procedure TBaseForm.WMWindowPosChanged(var Msg: TWMWindowPosChanged);
begin
if IsIconic(Handle) then
// VCL bug: calling UpdateBounds from the Restore event causes additional window flickering
Exit;
inherited;
end;
//procedure TBaseForm.CMParentFontChanged(var Message: TCMParentFontChanged);
//begin
// inherited;
//end;
//procedure TBaseForm.WMDpiChanged(var Message: TMessage);
//var
// LNewPPI: Integer;
//begin
// LNewPPI := LOWORD(Message.wParam);
// Self.ParentFont := False;
// uScaleControls.TScaleControls.Scale(Self, LNewPPI, FPixelsPerInch);
// FPixelsPerInch := LNewPPI;
// Message.Result := 0;
//end;
{ TBaseFrame }
{$ifdef Allow_Localization}
procedure TBaseFrame.DoLocalize;
begin
if Assigned(FOnLocalize) then
FOnLocalize(Self);
end;
procedure TBaseFrame.Localize;
begin
DoLocalize;
end;
class function TBaseFrame.ResGet(const StringID: string; const DefaultValue: string = ''): string;
begin
Result := BaseForms.ResGet(Self, StringID, DefaultValue);
end;
{$endif}
{$ifdef Allow_ScaleFix}
procedure TBaseFrame.WritePixelsPerInch(Writer: TWriter);
begin
Writer.WriteInteger(Screen.PixelsPerInch);
end;
{$endif}
procedure TBaseFrame.ReadPixelsPerInch(Reader: TReader);
begin
{$ifdef Allow_ScaleFix}FPixelsPerInch := {$endif}Reader.ReadInteger;
end;
procedure TBaseFrame.DefineProperties(Filer: TFiler);
begin
inherited DefineProperties(Filer);
{$ifdef Allow_ScaleFix}
// сохранять свойство PixelsPerInch нужно только при дизайне самой фреймы. Если фрейма встроена во что-то, то
// тогда свойство сохранять не нужно
Filer.DefineProperty('PixelsPerInch', ReadPixelsPerInch, WritePixelsPerInch, not Assigned(Filer.Ancestor));
{$else}
Filer.DefineProperty('PixelsPerInch', ReadPixelsPerInch, nil, False);
{$endif}
end;
procedure TBaseFrame.Loaded;
{$ifdef Allow_ScaleFix}
function DPIChanged: Boolean;
begin
Result := FPixelsPerInch <> Screen.PixelsPerInch;
end;
//function FontChanged: Boolean;
//begin
// Result := (Application.DefaultFont.Name <> DesignerDefaultFontName) or (Application.DefaultFont.Size <> 8);
//end;
function NeedScale: Boolean;
begin
Result := (FPixelsPerInch > 0) and (DPIChanged {or FontChanged});
end;
{$endif}
begin
{$ifdef Allow_ScaleFix}
// масштабируем только в том случае, если фрейм создаётся в Run-Time вручную (т.е. Parent = nil),
// либо в дизайнере
if NeedScale and (not Assigned(Parent) or (csDesigning in ComponentState)) then
uScaleControls.TScaleControls.Scale(Self, Screen.PixelsPerInch, FPixelsPerInch);
{$endif}
inherited Loaded;
end;
//procedure TBaseFrame.DoDestroy;
//begin
// inherited DoDestroy;
//end;
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* 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.
*
**********************************************************************************************************************
* TERRA_Image
* Implements image manipulation class
***********************************************************************************************************************
}
Unit TERRA_Image;
{$I terra.inc}
Interface
Uses TERRA_String, TERRA_Utils, TERRA_Stream, TERRA_Color;
Const
// Image processing flags
IMP_SwapChannels = 1;
IMP_FillColor = 2;
IMP_FillAlpha = 4;
IMP_SetColorKey = 8;
IMP_SetAlphaFromLuminance = 16;
IMP_SetGreyscale = 32;
IMP_FlipVertical = 64;
IMP_FlipHorizontal = 128;
IMP_ScaleColor = 256;
componentRed = 0;
componentGreen = 1;
componentBlue = 2;
componentAlpha = 3;
maskRed = 1;
maskGreen = 2;
maskBlue = 4;
maskAlpha = 8;
maskRGB = maskRed Or maskGreen Or maskBlue;
maskRGBA = maskRGB Or maskAlpha;
PixelSize:Cardinal = 4;
Type
ImageTransparencyType = (imageUnknown, imageOpaque, imageTransparent, imageTranslucent);
ImageFrame = Class(TERRAObject)
Protected
_Data:Array Of Color;
Public
Constructor Create(Width, Height:Integer);
Procedure Release; Override;
End;
Image = Class(TERRAObject)
Protected
_Frames:Array Of ImageFrame;
_FrameCount:Cardinal;
_Pixels:ImageFrame;
_Width:Cardinal;
_Height:Cardinal;
_Size:Cardinal;
_CurrentFrame:Cardinal;
_TransparencyType:ImageTransparencyType;
Procedure Discard;
Procedure FillAlpha(AlphaValue:Byte=255);
Function GetPixelCount:Cardinal;
Function GetPixels:PColor;
Function GetImageTransparencyType:ImageTransparencyType;
Public
Constructor Create(Width, Height:Integer);Overload;
Constructor Create(Source:Stream);Overload;
Constructor Create(FileName:TERRAString);Overload;
Constructor Create(Source:Image);Overload;
Procedure Release; Override;
Procedure Load(Source:Stream);Overload;
Procedure Load(FileName:TERRAString);Overload;
Procedure Save(Dest:Stream; Format:TERRAString; Options:TERRAString='');Overload;
Procedure Save(Filename:TERRAString; Format:TERRAString=''; Options:TERRAString='');Overload;
Procedure Copy(Source:Image);
Procedure Resize(Const NewWidth,NewHeight:Cardinal);
Procedure LinearResize(Const NewWidth,NewHeight:Cardinal);
Procedure New(Const Width,Height:Cardinal);
Function AddFrame:ImageFrame;
Procedure NextFrame(Skip:Cardinal=1);
Procedure SetCurrentFrame(ID:Cardinal);
{$IFDEF NDS}Function AutoTile:Cardinal;{$ENDIF}
Procedure Process(Flags:Cardinal; Color:Color); Overload;
Procedure Process(Flags:Cardinal); Overload;
Procedure BlitByUV(Const U,V,U1,V1,U2,V2:Single; Const Source:Image);
Procedure Blit(X,Y,X1,Y1,X2,Y2:Integer; Const Source:Image);
Procedure BlitAlphaMapByUV(Const U,V,U1,V1,U2,V2,AU1,AV1,AU2,AV2:Single; Const Source,AlphaMap:Image);
Procedure BlitAlphaMap(X,Y,X1,Y1,X2,Y2,AX1,AY1,AX2,AY2:Integer; Const Source,AlphaMap:Image);
Procedure BlitWithAlphaByUV(Const U,V,U1,V1,U2,V2:Single; Const Source:Image; ForceBlend:Boolean = True);
Procedure BlitWithAlpha(X,Y,X1,Y1,X2,Y2:Integer; Const Source:Image; ForceBlend:Boolean = True);
Procedure BlitWithMaskByUV(Const U,V,U1,V1,U2,V2:Single; Const Color:Color; Const Source:Image);
Procedure BlitWithMask(X,Y,X1,Y1,X2,Y2:Integer; Const Color:Color; Const Source:Image);
Function SubImage(X1,Y1,X2,Y2:Integer):Image;
Function Combine(Layer:Image; Alpha:Single; Mode:ColorCombineMode; Mask:Cardinal):Boolean;
Procedure ShiftHue(ShiftAmmount:Integer);
Procedure LineByUV(Const U1,V1,U2,V2:Single; Const Color:Color);
Procedure Line(X1,Y1,X2,Y2:Integer; Const Color:Color);
Procedure LineAlpha(X1,Y1,X2,Y2:Integer; Const Color:Color);
Procedure DrawRectangleByUV(Const U1,V1,U2,V2:Single; Const Color:Color);
Procedure DrawRectangle(X1,Y1,X2,Y2:Integer; Const Color:Color);
Procedure FillRectangleByUV(Const U1,V1,U2,V2:Single; Const Color:Color);
Procedure FillRectangle(X1,Y1,X2,Y2:Integer; Const Color:Color);
Procedure DrawCircleByUV(Const xCenter,yCenter:Single; Const Radius:Integer; Const Color:Color);
Procedure DrawCircle(xCenter,yCenter:Integer; Const Radius:Integer; Const Color:Color);
Procedure FillCircleByUV(Const xCenter,yCenter:Single; Const Radius:Integer; Const Color:Color);
Procedure FillCircle(xCenter,yCenter:Integer; Const Radius:Integer; Const Color:Color);
Function GetPixel(X,Y:Integer):Color; {$IFDEF FPC}Inline;{$ENDIF}
Function GetPixelByUV(Const U,V:Single):Color; {$IFDEF FPC}Inline;{$ENDIF}
Function GetComponent(X,Y,Component:Integer):Byte; {$IFDEF FPC}Inline;{$ENDIF}
Procedure SetPixelByOffset(Ofs:Integer; Const Color:Color); {$IFDEF FPC}Inline;{$ENDIF}
Procedure SetPixel(X,Y:Integer; Const Color:Color); {$IFDEF FPC}Inline;{$ENDIF}
Procedure SetPixelByUV(Const U,V:Single; Const Color:Color); {$IFDEF FPC}Inline;{$ENDIF}
//Procedure AddPixel(X,Y:Integer; Const Color:Color); {$IFDEF FPC}Inline;{$ENDIF}
Procedure MixPixel(X,Y:Integer; Const Color:Color); {$IFDEF FPC}Inline;{$ENDIF}
Function MipMap():Image;
Procedure LineDecodeRGBPalette4(Buffer, Palette:Pointer; Line:Cardinal);
Procedure LineDecodeRGBPalette8(Buffer, Palette:Pointer; Line:Cardinal);
Procedure LineDecodeRGB8(Buffer:Pointer; Line:Cardinal);
Procedure LineDecodeRGB16(Buffer:Pointer; Line:Cardinal);
Procedure LineDecodeRGB24(Buffer:Pointer; Line:Cardinal);
Procedure LineDecodeRGB32(Buffer:Pointer; Line:Cardinal);
Procedure LineDecodeBGRPalette4(Buffer, Palette:Pointer; Line:Cardinal);
Procedure LineDecodeBGRPalette8(Buffer, Palette:Pointer; Line:Cardinal);
Procedure LineDecodeBGR8(Buffer:Pointer; Line:Cardinal);
Procedure LineDecodeBGR16(Buffer:Pointer; Line:Cardinal);
Procedure LineDecodeBGR24(Buffer:Pointer; Line:Cardinal);
Procedure LineDecodeBGR32(Buffer:Pointer; Line:Cardinal);
Function GetPixelOffset(X,Y:Integer):PColor;
Function GetLineOffset(Y:Integer):PColor;
Property Width:Cardinal Read _Width;
Property Height:Cardinal Read _Height;
Property PixelCount:Cardinal Read GetPixelCount;
Property Size:Cardinal Read _Size;
Property Pixels:PColor Read GetPixels;
Property CurrentFrame:Cardinal Read _CurrentFrame Write SetCurrentFrame;
Property FrameCount:Cardinal Read _FrameCount;
Property TransparencyType:ImageTransparencyType Read GetImageTransparencyType;
End;
ImageStreamValidateFunction = Function(Source:Stream):Boolean;
ImageLoader = Procedure(Source:Stream; Image:Image);
ImageSaver = Procedure(Source:Stream; Image:Image; Const Options:TERRAString='');
ImageClassInfo = Record
Name:TERRAString;
Validate:ImageStreamValidateFunction;
Loader:ImageLoader;
Saver:ImageSaver;
End;
Function GetImageLoader(Source:Stream):ImageLoader;
Function GetImageSaver(Const Format:TERRAString):ImageSaver;
Procedure RegisterImageFormat(Name:TERRAString;
Validate:ImageStreamValidateFunction;
Loader:ImageLoader;
Saver:ImageSaver=Nil);
Function GetImageExtensionCount():Integer;
Function GetImageExtension(Index:Integer):ImageClassInfo;
Implementation
Uses TERRA_FileStream, TERRA_FileUtils, TERRA_FileManager, TERRA_Math, TERRA_Log;
Var
_ImageExtensions:Array Of ImageClassInfo;
_ImageExtensionCount:Integer;
Function GetImageExtensionCount():Integer;
Begin
Result := _ImageExtensionCount;
End;
Function GetImageExtension(Index:Integer):ImageClassInfo;
Begin
If (Index>=0) And (Index<_ImageExtensionCount) Then
Result := _ImageExtensions[Index]
Else
FillChar(Result, SizeOf(Result), 0);
End;
Function GetImageLoader(Source:Stream):ImageLoader;
Var
Pos:Cardinal;
I:Integer;
Begin
Result := Nil;
If Not Assigned(Source) Then
Exit;
Pos := Source.Position;
For I:=0 To Pred(_ImageExtensionCount) Do
Begin
Source.Seek(Pos);
If _ImageExtensions[I].Validate(Source) Then
Begin
Log(logDebug, 'Image', 'Found '+_ImageExtensions[I].Name);
Result := _ImageExtensions[I].Loader;
Break;
End;
End;
Source.Seek(Pos);
End;
Function GetImageSaver(Const Format:TERRAString):ImageSaver;
Var
I:Integer;
Begin
Result := Nil;
For I:=0 To Pred(_ImageExtensionCount) Do
If StringEquals(_ImageExtensions[I].Name, Format) Then
Begin
Result := _ImageExtensions[I].Saver;
Exit;
End;
End;
Procedure RegisterImageFormat(Name:TERRAString;
Validate:ImageStreamValidateFunction;
Loader:ImageLoader;
Saver:ImageSaver=Nil);
Var
I,N:Integer;
Begin
Name := StringLower(Name);
For I:=0 To Pred(_ImageExtensionCount) Do
If (_ImageExtensions[I].Name = Name) Then
Exit;
N := _ImageExtensionCount;
Inc(_ImageExtensionCount);
SetLength(_ImageExtensions, _ImageExtensionCount);
_ImageExtensions[N].Name := Name;
_ImageExtensions[N].Validate :=Validate;
_ImageExtensions[N].Loader := Loader;
_ImageExtensions[N].Saver := Saver;
End;
{ Image }
Constructor Image.Create(Width, Height:Integer);
Begin
_CurrentFrame := 0;
_FrameCount := 0;
New(Width, Height);
End;
Constructor Image.Create(Source:Stream);
Begin
Load(Source);
End;
Constructor Image.Create(FileName:TERRAString);
Begin
Load(FileName);
End;
Constructor Image.Create(Source:Image);
Begin
Copy(Source);
End;
Procedure Image.Release;
Begin
Discard;
End;
Procedure Image.New(Const Width,Height:Cardinal);
Begin
Discard();
_TransparencyType := imageUnknown;
_CurrentFrame := MaxInt;
_Width := Width;
_Height := Height;
_Size := Width * Height * PixelSize;
_FrameCount := 0;
Self.AddFrame();
End;
Function Image.AddFrame():ImageFrame;
Var
K:Integer;
Begin
Inc(_FrameCount);
SetLength(_Frames,_FrameCount);
K := Pred(_FrameCount);
_Frames[K] := ImageFrame.Create(_Width, _Height);
Result := _Frames[K];
SetCurrentFrame(K);
End;
Function Image.GetPixelCount:Cardinal;
Begin
Result := Width * Height;
End;
Function Image.GetPixels:PColor;
Begin
Result := @_Pixels._Data[0];
End;
Procedure Image.Copy(Source:Image);
Var
I:Cardinal;
Begin
{Log(logDebug, 'Game', 'Copying image');
Log(logDebug, 'Game', 'Width:'+IntToString(Source.Width));
Log(logDebug, 'Game', 'Height:'+IntToString(Source.Height));}
New(Source.Width, Source.Height);
If Source.FrameCount<=0 Then
Exit;
For I:=0 To Pred(Source.FrameCount) Do
Begin
Move(Source._Frames[I]._Data[0], Self._Frames[I]._Data[0], Size);
If I<Pred(Source.FrameCount) Then
Self.AddFrame();
End;
_TransparencyType := Source._TransparencyType;
End;
Procedure Image.Resize(Const NewWidth,NewHeight:Cardinal);
Const
FixedPointBits = 12;
Var
K:Integer;
X, Y:Cardinal;
AX,AY,BX,BY,CX,CY,DX,DY:Single;
U,V,UV:Single;
OneMinusU, OneMinusV, oneMinusUOneMinusV:Single;
uOneMinusV, vOneMinusU:Single;
srcX, srcY, srcXStep, srcYStep:Single;
pSrcPixelA, pSrcPixelB, pSrcPixelC, pSrcPixelD:Color;
Dest:ImageFrame;
Pixel:Color;
Begin
If (NewWidth=Width) And (NewHeight=Height) Then
Exit;
If (Width<=0) Or (Height<=0) Then
Exit;
If (NewWidth<=0) Or (NewHeight<=0) Then
Begin
_Width := 0;
_Height := 0;
_Size := 0;
Exit;
End;
// Resizes the bitmap image using bilinear sampling.
srcX := 0.0;
srcY := 0.0;
srcXStep := _width / NewWidth;
srcYStep := _height / NewHeight;
For K:=0 To Pred(FrameCount) Do
Begin
SetCurrentFrame(K);
Dest := ImageFrame.Create(NewWidth, NewHeight);
For Y := 0 To Pred(NewHeight) Do
Begin
For X:= 0 To Pred(NewWidth) Do
Begin
ax := floor(srcX);
u := srcX - ax;
if (srcXStep>1.0) Then
u := 0.5;
ay := floor(srcY);
v := srcY - ay;
if (srcYStep>1.0) Then
v := 0.5;
dx := ax + 1.0;
dy := ay + 1.0;
if (dx >= _width) Then
dx := _width - 1.0;
if (dy >= _height) Then
dy := _height - 1.0;
bx := dx;
by := ay;
cx := ax;
cy := dy;
uv := u * v;
oneMinusU := 1.0 - u;
oneMinusV := 1.0 - v;
uOneMinusV := u * oneMinusV;
vOneMinusU := v * oneMinusU;
oneMinusUOneMinusV := oneMinusU * oneMinusV;
If (ax<0) Then ax := 0;
If (ax>=_width) Then ax := _width-1;
If (bx<0) Then bx := 0;
If (bx>=_width) Then bx := _width-1;
If (cx<0) Then cx := 0;
If (cx>=_width) Then cx := _width-1;
If (dx<0) Then dx := 0;
If (dx>=_width) Then dx := _width-1;
If (ay<0) Then ay := 0;
If (ay>=_height) Then ay := _height-1;
If (by<0) Then by := 0;
If (by>=_height) Then by := _height-1;
If (cy<0) Then cy := 0;
If (cy>=_height) Then cy := _height-1;
If (dy<0) Then dy := 0;
If (dy>=_height) Then dy := _height-1;
pSrcPixelA := _Pixels._Data[Trunc((ay * _width) + ax)];
pSrcPixelB := _Pixels._Data[Trunc((by * _width) + bx)];
pSrcPixelC := _Pixels._Data[Trunc((cy * _width) + cx)];
pSrcPixelD := _Pixels._Data[Trunc((dy * _width) + dx)];
pixel.R := Trunc(pSrcPixelA.R * oneMinusUOneMinusV + pSrcPixelB.R * uOneMinusV + pSrcPixelC.R * vOneMinusU + pSrcPixelD.R * uv);
pixel.G := Trunc(pSrcPixelA.G * oneMinusUOneMinusV + pSrcPixelB.G * uOneMinusV + pSrcPixelC.G * vOneMinusU + pSrcPixelD.G * uv);
pixel.B := Trunc(pSrcPixelA.B * oneMinusUOneMinusV + pSrcPixelB.B * uOneMinusV + pSrcPixelC.B * vOneMinusU + pSrcPixelD.B * uv);
pixel.A := Trunc(pSrcPixelA.A * oneMinusUOneMinusV + pSrcPixelB.A * uOneMinusV + pSrcPixelC.A * vOneMinusU + pSrcPixelD.A * uv);
Dest._Data[(Y * NewWidth + X)] := Pixel;
srcX := srcX + srcXStep;
End;
srcX := 0.0;
srcY := srcY + srcYStep;
End;
ReleaseObject(_Frames[K]);
_Frames[K]:= Dest;
End;
_Width := NewWidth;
_Height := NewHeight;
_Size := _Width * _Height * PixelSize;
_CurrentFrame := MaxInt;
SetCurrentFrame(0);
End;
Procedure Image.LinearResize(Const NewWidth,NewHeight:Cardinal);
Const
FixedPointBits = 12;
Var
I,J,K:Cardinal;
Sx,Sy:Cardinal;
NX,NY:Cardinal;
PX,PY:Cardinal;
Buffer:ImageFrame;
Dest:PColor;
Begin
If (NewWidth=Width)And(NewHeight=Height) Then
Exit;
If (_Pixels = Nil) Then
Begin
Self.New(Width, Height);
Exit;
End;
Sx := Trunc((Width / NewWidth)*(1 Shl FixedPointBits));
Sy := Trunc((Height/ NewHeight)*(1 Shl FixedPointBits));
For K:=0 To Pred(FrameCount) Do
Begin
Buffer := ImageFrame.Create(NewWidth, NewHeight);
Dest := @Buffer._Data[0];
NX := 0;
NY := 0;
For J:=0 To Pred(NewHeight) Do
Begin
For I:=0 To Pred(NewWidth) Do
Begin
PX := (NX Shr FixedPointBits);
PY := (NY Shr FixedPointBits);
Dest^ := _Pixels._Data[(PY*Width+PX)];
Inc(Dest);
Inc(NX, SX);
End;
Inc(NY, SY);
NX:=0;
End;
ReleaseObject(_Frames[K]);
_Frames[K] := Buffer;
End;
_Width := NewWidth;
_Height := NewHeight;
_Size := _Width * _Height * PixelSize;
_CurrentFrame := MaxInt;
SetCurrentFrame(0);
End;
Procedure Image.SetCurrentFrame(ID:Cardinal);
Begin
If (ID>=_FrameCount) Then
ID:=0;
If (ID=_CurrentFrame) Then
Exit;
_CurrentFrame:=ID;
_Pixels := _Frames[ID];
End;
Procedure Image.NextFrame(Skip:Cardinal=1);
Begin
If Skip<=0 Then
Exit;
SetCurrentFrame((_CurrentFrame+Skip) Mod _FrameCount);
End;
Procedure Image.Discard;
Var
I:Integer;
Begin
If (_FrameCount>0) Then
For I:=0 To Pred(_FrameCount) Do
If Assigned(_Frames[I]) Then
Begin
ReleaseObject(_Frames[I]);
_Frames[I] := Nil;
End;
SetLength(_Frames,0);
_FrameCount:=0;
_CurrentFrame:=0;
_Pixels := Nil;
End;
Procedure Image.FillAlpha(AlphaValue:Byte=255);
Var
Color:PColor;
I,J:Integer;
Begin
Color:=Pixels;
For J:=0 To Pred(Height) Do
For I:=0 To Pred(Width) Do
Begin
Color.A:=AlphaValue;
Inc(Color);
End;
End;
Procedure Image.Process(Flags:Cardinal);
Begin
Process(Flags, ColorWhite);
End;
Procedure Image.Process(Flags:Cardinal; Color:Color);
Var
N:Cardinal;
I,J,K:Cardinal;
Source,Dest:PColor;
SwapChannels, SetColorKey, ScaleColor:Boolean;
FilColor,FillAlpha:Boolean;
SetGreyscale,SetAlphaFromLuminance:Boolean;
FlipHorizontal,FlipVertical:Boolean;
Begin
SetAlphaFromLuminance := (Flags And IMP_SetAlphaFromLuminance<>0);
SetGreyscale := (Flags And IMP_SetGreyscale<>0);
SwapChannels := (Flags And IMP_SwapChannels<>0);
SetColorKey := (Flags And IMP_SetColorKey<>0);
FillAlpha := (Flags And IMP_FillAlpha<>0);
FilColor := (Flags And IMP_FillColor<>0);
FlipHorizontal := (Flags And IMP_FlipHorizontal<>0);
FlipVertical := (Flags And IMP_FlipVertical<>0);
ScaleColor := (Flags And IMP_ScaleColor<>0);
If (_Width = 0) Or (_Height = 0) Then
Exit;
If (FillAlpha) And (Color.A = 0) Then
_TransparencyType := imageTransparent;
For K:=0 To Pred(_FrameCount) Do
Begin
Source := @_Frames[K]._Data[0];
For J:=0 To Pred(Height) Do
For I:=0 To Pred(Width) Do
Begin
If (FillAlpha) And (FilColor) Then
Source^:=Color
Else
If (FilColor) Then
Begin
Source.R := Color.R;
Source.G := Color.G;
Source.B := Color.B;
End;
If (FillAlpha)And(Not FilColor) Then
Begin
Source.A:=Color.A;
End Else
If (SetAlphaFromLuminance) Then
Begin
N:=Source.R+Source.G+Source.B;
Source.A:=(N Shl 1)+N;
End;
If (SetGreyscale) Then
Begin
Source^ := ColorGrey(ColorLuminance(Source^), Source.A);
End;
If (ScaleColor) Then
Begin
Source^ := ColorMultiply(Source^, Color);
End;
If (SetColorKey) And (Cardinal(Source^)=Cardinal(Color)) Then
Begin
Cardinal(Source^) := 0;
_TransparencyType := imageTransparent;
End;
If (SwapChannels) Then
Begin
N:=Source.R;
Source.R:=Source.B;
Source.B:=N;
End;
Inc(Source);
End;
If (FlipHorizontal) Then
Begin
N := _Width Shr 1;
If (Not Odd(_Width)) Then
Dec(N);
For J:=0 To Pred(_Height) Do
Begin
Source := @_Frames[K]._Data[(J*_Width)];
Dest := @_Frames[K]._Data[(J*_Width+Pred(_Width))];
For I:=0 To N Do
Begin
Color := Source^;
Source ^ := Dest^;
Dest^ := Color;
Inc(Source);
Dec(Dest);
End;
Inc(Source, N);
End;
End;
If (FlipVertical) Then
Begin
Source := Pixels;
N := _Height Shr 1;
If (Not Odd(_Height)) Then
Dec(N);
For J:=0 To N Do
For I:=0 To Pred(_Width) Do
Begin
Dest := @_Frames[K]._Data[((Pred(Height)-J)*_Width+I)];
Color := Source^;
Source^ := Dest^;
Dest^ := Color;
Inc(Source);
End;
End;
End;
End;
Procedure Image.BlitByUV(Const U,V,U1,V1,U2,V2:Single; Const Source:Image);
Begin
Blit(Integer(Round(U*Width)), Integer(Round(V*Height)),
Integer(Round(U1*Source.Width)), Integer(Round(V1*Source.Height)),
Integer(Round(U2*Source.Width)), Integer(Round(V2*Source.Height)), Source);
End;
Procedure Image.BlitAlphaMapByUV(Const U,V,U1,V1,U2,V2,AU1,AV1,AU2,AV2:Single; Const Source,AlphaMap:Image);
Begin
BlitAlphaMap(Integer(Round(U*Width)), Integer(Round(V*Height)),
Integer(Round(U1*Source.Width)), Integer(Round(V1*Source.Height)),
Integer(Round(U2*Source.Width)), Integer(Round(V2*Source.Height)),
Integer(Round(AU1*AlphaMap.Width)), Integer(Round(AV1*AlphaMap.Height)),
Integer(Round(AU2*AlphaMap.Width)), Integer(Round(AV2*AlphaMap.Height)),
Source,AlphaMap);
End;
Procedure Image.BlitWithAlphaByUV(Const U,V,U1,V1,U2,V2:Single; Const Source:Image; ForceBlend:Boolean);
Begin
BlitWithAlpha(Integer(Round(U*Width)), Integer(Round(V*Height)),
Integer(Round(U1*Source.Width)), Integer(Round(V1*Source.Height)),
Integer(Round(U2*Source.Width)), Integer(Round(V2*Source.Height)),
Source, ForceBlend);
End;
Procedure Image.BlitWithMaskByUV(Const U,V,U1,V1,U2,V2:Single; Const Color:Color; Const Source:Image);
Begin
BlitWithMask(Integer(Round(U*Width)), Integer(Round(V*Height)),
Integer(Round(U1*Source.Width)), Integer(Round(V1*Source.Height)),
Integer(Round(U2*Source.Width)), Integer(Round(V2*Source.Height)),
Color, Source);
End;
Procedure Image.LineByUV(Const U1,V1,U2,V2:Single; Const Color:Color);
Begin
Line(Integer(Trunc(U1*Width)), Integer(Trunc(V1*Height)),
Integer(Trunc(U2*Width)), Integer(Trunc(V2*Height)), Color);
End;
Procedure Image.Blit(X,Y, X1,Y1,X2,Y2:Integer; Const Source:Image);
Var
Dest, Data:PColor;
I,J:Integer;
BlitSize,BlitHeight:Integer;
Begin
If (X>=_Width) Or (Y>=_Height) Then
Exit;
If (X1>=Source.Width) Or (Y1>=Source.Height) Then
Exit;
If (X<0) Then
Begin
X1 := X1 - X;
If (X1>=X2) Then
Exit;
X := 0;
End;
If (Y<0) Then
Begin
Y1 := Y1 - Y;
If (Y1>=Y2) Then
Exit;
Y := 0;
End;
BlitHeight := Y2-Y1;
BlitSize := X2-X1;
If (BlitHeight<=0) Or (BlitSize<=0) Then
Exit;
For J:=0 To Pred(BlitHeight) Do
For I:=0 To Pred(BlitSize) Do
SetPixel(X+I, Y+J, Source.GetPixel(X1+I, Y1+J));
Exit;
{ Dest := Self.GetPixelOffset(X,Y);
Data := Source.GetPixelOffset(X1, Y1);
While (BlitHeight>0) Do
Begin
SafeMove(Data^, Dest^, BlitSize, Self.Pixels, Self._Size);
Inc(Dest, Width);
Inc(Data, Source.Width);
Dec(BlitHeight);
End;}
End;
Procedure Image.BlitAlphaMap(X,Y,X1,Y1,X2,Y2,AX1,AY1,AX2,AY2:Integer; Const Source,AlphaMap:Image);
Var
I,J:Integer;
BlitSize,BlitHeight:Integer;
AX,AY,ADX,ADY:Single;
A,B,C:Color;
Alpha:Cardinal;
Begin
If (X>=_Width) Or (Y>=_Height) Then
Exit;
If (X1>=Source.Width) Or (Y1>=Source.Height) Then
Exit;
If (X<0) Then
Begin
X1 := X1 - X;
If (X1>=X2) Then
Exit;
X := 0;
End;
If (Y<0) Then
Begin
Y1 := Y1 - Y;
If (Y1>=Y2) Then
Exit;
Y := 0;
End;
BlitHeight := (Y2-Y1);
BlitSize := (X2-X1);
If (BlitHeight<=0) Or (BlitSize<=0) Then
Exit;
AX := AX1;
AY := AY1;
ADX := (AX2-AX1) / BlitSize;
ADY := (AY2-AY1) / BlitHeight;
For J:=0 To Pred(BlitHeight) Do
Begin
For I:=0 To Pred(BlitSize) Do
Begin
Alpha := AlphaMap.GetPixel(Integer(Trunc(AX)), Integer(Trunc(AY))).R;
A := Source.GetPixel(X1+I, Y1+J);
B := Self.GetPixel(X+I, Y+J);
C := ColorBlend(A, B, Alpha);
SetPixel(X+I, Y+J, C);
AX:=AX+ADX;
End;
AX:=AX1;
AY:=AY+ADY;
End;
End;
Procedure Image.BlitWithAlpha(X,Y,X1,Y1,X2,Y2:Integer; Const Source:Image; ForceBlend:Boolean);
Var
I,J,BlitSize,BlitHeight:Integer;
Data,Dest:PColor;
Begin
X1:=IntMax(X1,0);
X2:=IntMin(X2,Integer(Source.Width));
Y1:=IntMax(Y1,0);
Y2:=IntMin(Y2,Integer(Source.Height));
If (X<0) Then
Begin
X1 := X1 - X;
If (X1>=X2) Then
Exit;
X := 0;
End;
If (Y<0) Then
Begin
Y1 := Y1 - Y;
If (Y1>=Y2) Then
Exit;
Y := 0;
End;
BlitHeight:=(Y2-Y1);
BlitSize:=(X2-X1);
If (X+BlitSize >= Self.Width) Then
BlitSize := Self.Width-X;
If (Y+BlitHeight>= Self.Height) Then
BlitHeight := Self.Height-Y;
Dest := @_Pixels._Data[Y*Width +X];
Data := @Source._Pixels._Data[Y1* Source.Width +X1];
J := Y;
While (BlitHeight>0) Do
Begin
If J>=0 Then
For I:=1 To BlitSize Do
Begin
If (ForceBlend) Then
Begin
Dest^ := ColorBlend(Data^, Dest^);
End Else
If (Data.A>0) Then
Begin
Data.A := Dest.A;
Dest^ := ColorScale(Data^, 1.3);
End;
Inc(Dest);
Inc(Data);
End;
Inc(Dest, (Self.Width-BlitSize));
Inc(Data, (Source.Width-BlitSize));
Dec(BlitHeight);
Inc(J);
End;
End;
Procedure Image.BlitWithMask(X,Y,X1,Y1,X2,Y2:Integer; Const Color:Color; Const Source:Image);
Var
I,BlitSize,BlitHeight:Integer;
Data,Dest:PColor;
Begin
X1:=IntMax(X1,0);
X2:=IntMin(X2,Integer(Pred(Source.Width)));
Y1:=IntMax(Y1,0);
Y2:=IntMin(Y2,Integer(Pred(Source.Height)));
BlitHeight:=(Y2-Y1);
BlitSize:=(X2-X1);
If (X+BlitSize>=Self.Width) Then
BlitSize:=Self.Width-X;
If (Y+BlitHeight>=Self.Height) Then
BlitHeight:=Self.Height-Y;
Dest := @_Pixels._Data[Y*Width +X];
Data := @Source._Pixels._Data[Y1* Source.Width +X1];
While (BlitHeight>0) Do
Begin
For I:=1 To BlitSize Do
Begin
Dest^ := ColorBlend(Color, Dest^, Data.A);
Inc(Dest);
Inc(Data);
End;
Inc(Dest, (Self.Width-BlitSize));
Inc(Data, (Source.Width-BlitSize));
Dec(BlitHeight);
End;
End;
// Bresenham's line algorithm
Procedure Image.Line(X1,Y1,X2,Y2:Integer; Const Color:Color);
Var
I,DeltaX,DeltaY,NumPixels:Integer;
D,Dinc1,Dinc2:Integer;
X,XInc1,XInc2:Integer;
Y,YInc1,YInc2:Integer;
Begin
//calculate deltaX and deltaY
DeltaX:=Abs(x2-x1);
DeltaY:=Abs(y2-y1);
//initialize
If (DeltaX>=DeltaY) Then
Begin
//If x is independent variable
NumPixels:=Succ(DeltaX);
D:=(2*DeltaY)-DeltaX;
DInc1:=DeltaY Shl 1;
DInc2:=(DeltaY-DeltaX) Shl 1;
XInc1:=1;
XInc2:=1;
YInc1:=0;
YInc2:=1;
End Else
Begin
//if y is independent variable
NumPixels:=Succ(DeltaY);
D:=(2*DeltaX)-DeltaY;
DInc1:=DeltaX Shl 1;
DInc2:=(DeltaX-DeltaY) Shl 1;
xinc1:=0;
xinc2:=1;
yinc1:=1;
yinc2:=1;
End;
//move in the right direction
If (X1>X2) Then
Begin
XInc1:=-XInc1;
XInc2:=-Xinc2;
End;
If (Y1>Y2) Then
Begin
YInc1:=-YInc1;
YInc2:=-YInc2;
End;
x:=x1;
y:=y1;
//draw the pixels
For i:=1 To Pred(numpixels) Do
Begin
SetPixel(x,y,Color);
If (d<0) Then
Begin
Inc(D,DInc1);
Inc(X,XInc1);
Inc(Y,YInc1);
End Else
Begin
Inc(D,DInc2);
Inc(X,XInc2);
Inc(Y,YInc2);
End;
End;
End;
Procedure Image.LineAlpha(X1,Y1,X2,Y2:Integer; Const Color:Color);
Var
I,DeltaX,DeltaY,NumPixels:Integer;
D,Dinc1,Dinc2:Integer;
X,XInc1,XInc2:Integer;
Y,YInc1,YInc2:Integer;
Begin
//calculate deltaX and deltaY
DeltaX:=Abs(x2-x1);
DeltaY:=Abs(y2-y1);
//initialize
If (DeltaX>=DeltaY) Then
Begin
//If x is independent variable
NumPixels:=Succ(DeltaX);
D:=(2*DeltaY)-DeltaX;
DInc1:=DeltaY Shl 1;
DInc2:=(DeltaY-DeltaX) Shl 1;
XInc1:=1;
XInc2:=1;
YInc1:=0;
YInc2:=1;
End Else
Begin
//if y is independent variable
NumPixels:=Succ(DeltaY);
D:=(2*DeltaX)-DeltaY;
DInc1:=DeltaX Shl 1;
DInc2:=(DeltaX-DeltaY) Shl 1;
xinc1:=0;
xinc2:=1;
yinc1:=1;
yinc2:=1;
End;
//move in the right direction
If (X1>X2) Then
Begin
XInc1:=-XInc1;
XInc2:=-Xinc2;
End;
If (Y1>Y2) Then
Begin
YInc1:=-YInc1;
YInc2:=-YInc2;
End;
x:=x1;
y:=y1;
//draw the pixels
For i:=1 To Pred(numpixels) Do
Begin
MixPixel(x,y,Color);
If (d<0) Then
Begin
Inc(D,DInc1);
Inc(X,XInc1);
Inc(Y,YInc1);
End Else
Begin
Inc(D,DInc2);
Inc(X,XInc2);
Inc(Y,YInc2);
End;
End;
End;
Procedure Image.DrawRectangleByUV(Const U1,V1,U2,V2:Single; Const Color:Color);
Begin
DrawRectangle(Integer(Trunc(U1*Width)), Integer(Trunc(V1*Height)),
Integer(Trunc(U2*Width)), Integer(Trunc(V2*Height)), Color);
End;
Procedure Image.FillRectangleByUV(Const U1,V1,U2,V2:Single; Const Color:Color);
Begin
FillRectangle(Integer(Trunc(U1*Width)), Integer(Trunc(V1*Height)),
Integer(Trunc(U2*Width)), Integer(Trunc(V2*Height)), Color);
End;
// Fast rectangle draw
Procedure Image.DrawRectangle(X1,Y1,X2,Y2:Integer; Const Color:Color);
Var
J,LineSize,LineSkip:Integer;
Dest:PColor;
Begin
X1 := IntMax(X1,0);
X2 := IntMin(X2,Integer(Pred(Width)));
Y1 := IntMax(Y1,0);
Y2 := IntMin(Y2,Integer(Pred(Height)));
LineSize := (X2-X1);
If (LineSize <= 0) Then
Exit;
LineSkip := Succ(Integer(Width) - LineSize);
Dest := @_Pixels._Data[Y1*Width + X1 ];
// Fill top line
FillLong(Dest^, LineSize, Cardinal(Color));
Inc(Dest,Width);
// Fill lateral lines
For J:=Succ(Y1) To Pred(Y2) Do
Begin
Dest^ := Color;
Inc(Dest, Pred(LineSize));
Dest^ := Color;
Inc(Dest, LineSkip);
End;
// Fill bottom line
FillLong(Dest^, LineSize, Cardinal(Color));
End;
// Fast rectangle fill
Procedure Image.FillRectangle(X1,Y1,X2,Y2:Integer; Const Color:Color);
Var
J,LineSize:Integer;
Dest:PColor;
Begin
X1:=IntMax(X1,0);
X2:=IntMin(X2,Integer(Pred(Width)));
Y1:=IntMax(Y1,0);
Y2:=IntMin(Y2,Integer(Pred(Height)));
LineSize:=Succ(X2-X1);
If (LineSize<=0) Then
Exit;
Dest := @_Pixels._Data[Y1*Width + X1 ];
For J:=Y1 To Y2 Do
Begin
FillLong(Dest^,LineSize,Cardinal(Color));
Inc(Dest,Width);
End;
End;
Procedure Image.DrawCircleByUV(Const xCenter,yCenter:Single; Const Radius:Integer; Const Color:Color);
Begin
DrawCircle(Integer(Round(xCenter*Width)),Integer(Round(yCenter*Height)), Radius, Color);
End;
Procedure Image.FillCircleByUV(Const xCenter,yCenter:Single; Const Radius:Integer; Const Color:Color);
Begin
FillCircle(Integer(Round(xCenter*Width)),Integer(Round(yCenter*Height)), Radius, Color);
End;
// Bresenham's circle algorithm
Procedure Image.DrawCircle(xCenter,yCenter:Integer; Const Radius:Integer; Const Color:Color);
Var
X,Y,P:Integer;
Begin
x:=0;
Y:=Radius;
P:=3-Radius*2;
While (X<=Y) Do
Begin
SetPixel(xCenter + x, yCenter + y, Color);
SetPixel(xCenter - x, yCenter + y, Color);
SetPixel(xCenter + x, yCenter - y, Color);
SetPixel(xCenter - x, yCenter - y, Color);
SetPixel(xCenter + y, yCenter + x, Color);
SetPixel(xCenter - y, yCenter + x, Color);
SetPixel(xCenter + y, yCenter - x, Color);
SetPixel(xCenter - y, yCenter - x, Color);
If (P<0) Then
Begin
Inc(X);
Inc(P,4 *X + 6);
End Else
Begin
Inc(X);
Dec(Y);
Inc(P, 4*(X-Y)+10);
End;
End;
End;
Procedure Image.FillCircle(xCenter,yCenter:Integer; Const Radius:Integer; Const Color:Color);
Var
A,B,I:Integer;
Begin
For A:=0 To Pred(Radius) Do
Begin
B := Trunc(Sqrt((Sqr(Radius) - Sqr(A))));
For I:=-B To B Do
Begin
SetPixel(xCenter+I,yCenter-Pred(A), Color);
SetPixel(xCenter+I,yCenter+Pred(A), Color);
End;
End;
End;
Function Image.GetLineOffset(Y:Integer):PColor;
Begin
If (_Height<=0) Then
Begin
Result := Nil;
Exit;
End;
If (Y<0) Then
Y := 0
Else
If (Y>=_Height) Then
Y := Pred(_Height);
Result := @_Pixels._Data[Y * Width];
End;
Function Image.GetPixelOffset(X,Y:Integer):PColor;
Begin
If (X<0) Then
X := 0;
If (Y<0) Then
Y := 0;
If (_Pixels._Data = Nil) Then
Result := Nil
Else
Result := @_Pixels._Data[Y * Width + X];
End;
Function Image.GetPixelByUV(Const U,V:Single):Color; {$IFDEF FPC}Inline;{$ENDIF}
Var
X,Y:Integer;
Begin
X := Trunc(U*Width) Mod Width;
Y := Trunc(V*Height) Mod Height;
Result := GetPixel(X,Y);
End;
Function Image.GetPixel(X,Y:Integer):Color; {$IFDEF FPC}Inline;{$ENDIF}
Begin
If (Pixels = Nil) Or (Width<=0) Or (Height<=0)Then
Begin
Result := ColorNull;
Exit;
End;
If (X<0) Then X := 0;
If (Y<0) Then Y := 0;
If (X>=Width) Then X := Pred(Width);
If (Y>=Height) Then Y := Pred(Height);
Result := GetPixelOffset(X,Y)^;
End;
Function Image.GetComponent(X,Y,Component:Integer):Byte; {$IFDEF FPC}Inline;{$ENDIF}
Var
P:Color;
Begin
P := GetPixel(X,Y);
Result := PByteArray(@P)[Component];
End;
Procedure Image.SetPixelByUV(Const U,V:Single; Const Color:Color); {$IFDEF FPC}Inline;{$ENDIF}
Var
X,Y:Integer;
Begin
X:=Trunc(U*Width) Mod Width;
Y:=Trunc(V*Height) Mod Height;
SetPixel(X,Y,Color);
End;
Procedure Image.SetPixel(X,Y:Integer; Const Color:Color); {$IFDEF FPC}Inline;{$ENDIF}
Begin
If (X<0) Or (Y<0) Or (X>=Integer(Width)) Or (Y>=Integer(Height)) Then
Exit;
SetPixelByOffset(Y*Width+X, Color);
End;
Procedure Image.SetPixelByOffset(Ofs:Integer; Const Color:Color); {$IFDEF FPC}Inline;{$ENDIF}
Var
Dest:PColor;
Begin
If (Ofs<0) Or (Ofs >= Width*Height) Then
Exit;
_Pixels._Data[Ofs] := Color;
End;
Procedure Image.MixPixel(X,Y:Integer; Const Color:Color); {$IFDEF FPC}Inline;{$ENDIF}
Var
Dest:PColor;
Begin
If (X<0) Then X:=0;
If (Y<0) Then Y:=0;
If (X>=Integer(Width)) Then X:=Pred(Integer(Width));
If (Y>=Integer(Height)) Then Y:=Pred(Integer(Height));
Dest := @_Pixels._Data[Y*Width+X];
Dest^ := ColorBlend(Color, Dest^);
End;
(*Procedure Image.AddPixel(X,Y:Integer; Const Color:Color); {$IFDEF FPC}Inline;{$ENDIF}
Var
Dest:PColor;
Begin
If (X<0) Or (Y<0) Or (X>=Width) Or (Y>=Height) Then
Exit;
{$IFDEF PIXEL8}
//TODO
{$ELSE}
Dest := @_Pixels._Data[Y*Width+X];
Dest^ := ColorAdd(Dest^, Color);
{$ENDIF}
End;*)
Procedure Image.Load(FileName:TERRAString);
Var
Source:Stream;
Begin
Source := FileManager.Instance.OpenStream(FileName);
If Assigned(Source) Then
Begin
Load(Source);
ReleaseObject(Source);
End;
End;
Procedure Image.Load(Source:Stream);
Var
Loader:ImageLoader;
Begin
If Source = Nil Then
Begin
Log(logDebug, 'Image', 'Invalid image stream!');
Exit;
End;
Log(logDebug, 'Image', 'Searching formats');
Loader := GetImageLoader(Source);
If Not Assigned(Loader) Then
Begin
Self.New(4, 4);
Log(logDebug, 'Image', 'Unknown image format. ['+Source.Name+']');
Exit;
End;
Log(logDebug, 'Image', 'Loading image from loader ');
Loader(Source, Self);
Log(logDebug, 'Image', 'Image loaded');
End;
Procedure Image.Save(Dest:Stream; Format:TERRAString; Options:TERRAString='');
Var
Saver:ImageSaver;
Begin
If (_Pixels = Nil) Then
Exit;
Saver := GetImageSaver(Format);
If Not Assigned(Saver) Then
Begin
Log(logError, 'Image', 'Cannot save image to '+Format+' format. ['+Dest.Name+']');
Exit;
End;
Log(logDebug, 'Image', 'Saving image in '+Format+' format');
Saver(Dest, Self, Options);
End;
Procedure Image.Save(Filename:TERRAString; Format:TERRAString=''; Options:TERRAString='');
Var
Dest:Stream;
Begin
If Format='' Then
Format := GetFileExtension(FileName);
Dest := FileStream.Create(FileName);
Save(Dest, Format, Options);
ReleaseObject(Dest);
End;
{$IFDEF PIXEL8}
Procedure Image.LineDecodeRGB8(Buffer: Pointer; Line: Cardinal);
Var
Dest:PByte;
Begin
fsdfs
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Move(Buffer^, Dest^, _Width);
End;
Procedure Image.LineDecodeRGB16(Buffer: Pointer; Line: Cardinal);
Var
Source:PWord;
Dest:PByte;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
sfds
Count:=_Width;
Source:=Buffer;
While (Count>0) Do
Begin
// Dest^:=ColorRGB16To8(Source^);
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeRGB24(Buffer: Pointer; Line: Cardinal);
Var
Source:PByte;
Dest:PByte;
Temp:Color;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
Temp.A:=255;
While (Count>0) Do
Begin
{$IFDEF RGB}
Temp.R:=Source^; Inc(Source);
Temp.G:=Source^; Inc(Source);
Temp.B:=Source^; Inc(Source);
{$ENDIF}
{$IFDEF BGR}
Temp.B:=Source^; Inc(Source);
Temp.G:=Source^; Inc(Source);
Temp.R:=Source^; Inc(Source);
{$ENDIF}
Dest^:=ColorRGB32To8(Temp);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeRGB32(Buffer: Pointer; Line: Cardinal);
Var
Source:PColor;
Dest:PByte;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
While (Count>0) Do
Begin
Dest^:=ColorRGB32To8(Source^);
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeRGBPalette4(Buffer, Palette: Pointer; Line:Cardinal);
Var
Source, ColorTable:PByte;
Dest:PByte;
Count:Integer;
Index:Integer;
Temp:Color;
A,B:Byte;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width Shr 1;
Source:=Buffer;
Temp.A:=255;
While (Count>0) Do
Begin
A:=Source^;
B:=A And $0F;
A:=(A Shr 4) And $0F;
ColorTable:=PByte(Cardinal(Palette)+ A*4);
{$IFDEF RGB}
Temp.R:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.B:=ColorTable^; Inc(ColorTable);
{$ENDIF}
{$IFDEF BGR}
Temp.B:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.R:=ColorTable^; Inc(ColorTable);
{$ENDIF}
Dest^:=ColorRGB32To8(Temp);
Inc(Dest);
ColorTable:=PByte(Cardinal(Palette)+ B*4);
{$IFDEF RGB}
Temp.R:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.B:=ColorTable^; Inc(ColorTable);
{$ENDIF}
{$IFDEF BGR}
Temp.B:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.R:=ColorTable^; Inc(ColorTable);
{$ENDIF}
Dest^:=ColorRGB32To8(Temp);
Inc(Dest);
Inc(Source);
Dec(Count);
End;
End;
Procedure Image.LineDecodeRGBPalette8(Buffer, Palette: Pointer; Line:Cardinal);
Var
Source, ColorTable:PByte;
Dest:PByte;
Count:Integer;
Index:Integer;
Temp:Color;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
Temp.A:=255;
While (Count>0) Do
Begin
ColorTable:=PByte(Cardinal(Palette)+ (Source^)*4);
{$IFDEF RGB}
Temp.R:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.B:=ColorTable^; Inc(ColorTable);
{$ENDIF}
{$IFDEF BGR}
Temp.B:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.R:=ColorTable^; Inc(ColorTable);
{$ENDIF}
Inc(ColorTable);
Dest^:=ColorRGB32To8(Temp);
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeBGR8(Buffer: Pointer; Line:Cardinal);
Var
Dest:PByte;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Move(Buffer^, Dest^, _Width);
End;
Procedure Image.LineDecodeBGR16(Buffer: Pointer; Line:Cardinal);
Var
Source:PWord;
Dest:PByte;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
While (Count>0) Do
Begin
// Dest^:=ColorBGR16To8(Source^);
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeBGR24(Buffer: Pointer; Line:Cardinal);
Var
Source:PByte;
Dest:PByte;
Temp:Color;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
Temp.A:=255;
While (Count>0) Do
Begin
{$IFDEF BGR}
Temp.R:=Source^; Inc(Source);
Temp.G:=Source^; Inc(Source);
Temp.B:=Source^; Inc(Source);
{$ENDIF}
{$IFDEF RGB}
Temp.B:=Source^; Inc(Source);
Temp.G:=Source^; Inc(Source);
Temp.R:=Source^; Inc(Source);
{$ENDIF}
Dest^:=ColorRGB32To8(Temp);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeBGR32(Buffer: Pointer; Line:Cardinal);
Var
Source:PColor;
Dest:PByte;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
While (Count>0) Do
Begin
Dest^:=ColorBGR32To8(Source^);
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeBGRPalette4(Buffer, Palette: Pointer; Line:Cardinal);
Var
Source, ColorTable:PByte;
Dest:PByte;
Count:Integer;
Index:Integer;
Temp:Color;
A,B:Byte;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width Shr 1;
Source:=Buffer;
Temp.A:=255;
While (Count>0) Do
Begin
A:=Source^;
B:=A And $0F;
A:=(A Shr 4) And $0F;
ColorTable:=PByte(Cardinal(Palette)+ A*4);
{$IFDEF BGR}
Temp.R:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.B:=ColorTable^; Inc(ColorTable);
{$ENDIF}
{$IFDEF RGB}
Temp.B:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.R:=ColorTable^; Inc(ColorTable);
{$ENDIF}
Dest^:=ColorRGB32To8(Temp);
Inc(Dest);
ColorTable:=PByte(Cardinal(Palette)+ B*4);
{$IFDEF BGR}
Temp.R:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.B:=ColorTable^; Inc(ColorTable);
{$ENDIF}
{$IFDEF RGB}
Temp.B:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.R:=ColorTable^; Inc(ColorTable);
{$ENDIF}
Dest^:=ColorRGB32To8(Temp);
Inc(Dest);
Inc(Source);
Dec(Count);
End;
End;
Procedure Image.LineDecodeBGRPalette8(Buffer, Palette: Pointer; Line:Cardinal);
Var
Source, ColorTable:PByte;
Dest:PByte;
Count:Integer;
Index:Integer;
Temp:Color;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count := _Width;
Source := Buffer;
Temp.A := 255;
While (Count>0) Do
Begin
ColorTable:=PByte(Cardinal(Palette)+ (Source^)*4);
{$IFDEF BGR}
Temp.R:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.B:=ColorTable^; Inc(ColorTable);
{$ENDIF}
{$IFDEF RGB}
Temp.B:=ColorTable^; Inc(ColorTable);
Temp.G:=ColorTable^; Inc(ColorTable);
Temp.R:=ColorTable^; Inc(ColorTable);
{$ENDIF}
Inc(ColorTable);
Dest^:=ColorRGB32To8(Temp);
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
{$ENDIF}
{$IFDEF PIXEL32}
Procedure Image.LineDecodeRGB8(Buffer: Pointer; Line: Cardinal);
Var
Source:PByte;
Dest:PColor;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
While (Count>0) Do
Begin
Dest ^:= ColorRGB8To32(Source^);
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeRGB16(Buffer: Pointer; Line:Cardinal);
Var
Source:PWord;
Dest:PColor;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
While (Count>0) Do
Begin
Dest^:=ColorRGB16To32(Source^);
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeRGB24(Buffer: Pointer; Line:Cardinal);
Var
Source:PByte;
Dest:PColor;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
While (Count>0) Do
Begin
{$IFDEF RGB}
Dest.R:=Source^; Inc(Source);
Dest.G:=Source^; Inc(Source);
Dest.B:=Source^; Inc(Source);
{$ENDIF}
{$IFDEF BGR}
Dest.B:=Source^; Inc(Source);
Dest.G:=Source^; Inc(Source);
Dest.R:=Source^; Inc(Source);
{$ENDIF}
Dest.A:=255;
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeRGB32(Buffer: Pointer; Line:Cardinal);
Var
Dest:PColor;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Move(Buffer^, Dest^, _Width*PixelSize);
End;
Procedure Image.LineDecodeRGBPalette4(Buffer, Palette: Pointer; Line:Cardinal);
Var
Source:PByte;
Dest:PColor;
Count:Integer;
A,B:Byte;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count := _Width;
Source := Buffer;
While (Count>0) Do
Begin
A:=Source^;
B:=A And $0F;
A:=(A Shr 4) And $0F;
Dest^:=PColorPalette(Palette)[A];
Inc(Dest);
Dest^:=PColorPalette(Palette)[B];
Inc(Dest);
Inc(Source);
Dec(Count);
End;
End;
Procedure Image.LineDecodeRGBPalette8(Buffer, Palette: Pointer; Line:Cardinal);
Var
Source:PByte;
Dest:PColor;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
While (Count>0) Do
Begin
Dest^ := PColorPalette(Palette)[Source^];
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeBGR8(Buffer: Pointer; Line:Cardinal);
Var
Source:PByte;
Dest:PColor;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
While (Count>0) Do
Begin
Dest^:=ColorBGR8To32(Source^);
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeBGR16(Buffer: Pointer; Line:Cardinal);
Var
Source:PWord;
Dest:PColor;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count := _Width;
Source := Buffer;
While (Count>0) Do
Begin
Dest^:=ColorBGR16To32(Source^);
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeBGR24(Buffer: Pointer; Line:Cardinal);
Var
Source:PByte;
Dest:PColor;
Count:Integer;
Begin
If (Line>=_Height) Or (Buffer = Nil) Then
Exit;
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count := _Width;
Source := Buffer;
While (Count>0) Do
Begin
{$IFDEF BGR}
Dest.R := Source^; Inc(Source);
Dest.G := Source^; Inc(Source);
Dest.B := Source^; Inc(Source);
{$ENDIF}
{$IFDEF RGB}
Dest.B := Source^; Inc(Source);
Dest.G := Source^; Inc(Source);
Dest.R := Source^; Inc(Source);
{$ENDIF}
Dest.A := 255;
Inc(Dest);
Dec(Count);
End;
End;
Procedure Image.LineDecodeBGR32(Buffer: Pointer; Line:Cardinal);
Var
Dest:PColor;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Move(Buffer^, Dest^, _Width*PixelSize);
End;
Procedure Image.LineDecodeBGRPalette4(Buffer, Palette: Pointer; Line:Cardinal);
Var
Source:PByte;
Dest:PColor;
Count:Integer;
A,B:Byte;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
While (Count>0) Do
Begin
A:=Source^;
B:=A And $0F;
A:=(A Shr 4) And $0F;
Dest^:=PColorPalette(Palette)[A];
Inc(Dest);
Dest^:=PColorPalette(Palette)[B];
Inc(Dest);
Inc(Source);
Dec(Count);
End;
End;
Procedure Image.LineDecodeBGRPalette8(Buffer, Palette: Pointer; Line:Cardinal);
Var
Source:PByte;
Dest:PColor;
Count:Integer;
Begin
Dest := Self.GetLineOffset(Line);
If (Dest = Nil) Then
Exit;
Count:=_Width;
Source:=Buffer;
While (Count>0) Do
Begin
Dest^:=PColorPalette(Palette)[Source^];
Inc(Source);
Inc(Dest);
Dec(Count);
End;
End;
{$ENDIF}
{$IFDEF NDS}
Function Image.AutoTile:Cardinal;
Var
TileCount:Integer;
Start, Dest, Temp:PByte;
I,J,X,Y:Integer;
Begin
GetMem(Temp, _Size);
Dest:=Temp;
TileCount:=((Width Shr 3) * (Height Shr 3));
X:=0;
Y:=0;
For I:=0 To Pred(TileCount) Do
Begin
For J:=0 To 7 Do
Begin
Start := @_Pixels._Data[X+((Y+J)*_Width)];
Move(Start^, Dest^, 8);
Inc(Dest, 8);
End;
Inc(X,8);
If (X>=_Width) Then
Begin
X:=0;
Inc(Y,8);
End;
End;
Move(Temp^, _Pixels._Data[0], _Size);
FreeMem(Temp);
Result := TileCount;
End;
{$ENDIF}
Function Image.SubImage(X1,Y1,X2,Y2:Integer):Image;
Var
W,H:Integer;
I,J:Integer;
Begin
W := Pred(X2-X1);
H := Pred(Y2-Y1);
If (W<=0) Or (H<=0) Then
Begin
Result := Nil;
Exit;
End;
Result := Image.Create(W, H);
For J:=0 To Pred(H) Do
For I:=0 To Pred(W) Do
Begin
Result.SetPixel(I,J, Self.GetPixel(X1+I, Y1+J));
End;
End;
Function Image.Combine(Layer:Image; Alpha:Single; Mode:ColorCombineMode; Mask:Cardinal):Boolean;
Var
A,B:PColor;
C:Color;
InvAlpha:Single;
Count:Integer;
Begin
Result := False;
If (Layer = Nil) Then
Exit;
If (Layer.Width<>Self.Width) Or (Layer.Height<>Self.Height) Then
Exit;
A := Self.Pixels;
B := Layer.Pixels;
Count := Self.Width * Self.Height;
InvAlpha := 1.0 - Alpha;
While Count>0 Do
Begin
C := ColorCombine(A^, B^, Mode);
If (Mask And maskRed<>0) Then
A.R := Trunc(A.R * InvAlpha + C.R * Alpha);
If (Mask And maskGreen<>0) Then
A.g := Trunc(A.G * InvAlpha + C.G * Alpha);
If (Mask And maskBlue<>0) Then
A.B := Trunc(A.B * InvAlpha + C.B * Alpha);
If (Mask And maskAlpha<>0) Then
A.A := Trunc(A.A * InvAlpha + C.A * Alpha);
If (Mask = maskAlpha) And (A.A<250) Then
Begin
A.R := 0;
A.G := 0;
A.B := 0;
End;
//A^:= ColorMix(C, A^, Alpha);
Inc(A);
Inc(B);
Dec(Count);
End;
Result := True;
End;
Function Image.MipMap(): Image;
Var
I,J:Integer;
PX, PY:Single;
A, B, C, D, F:Color;
Begin
Result := Image.Create(Self.Width Shr 1, Self.Height Shr 1);
For I:=0 To Pred(Result.Width) Do
For J:=0 To Pred(Result.Height) Do
Begin
PX := (I * 2.0) + 0.5;
PY := (J * 2.0) + 0.5;
A := Self.GetPixel(Trunc(PX), Trunc(PY));
B := Self.GetPixel(Round(PX), Trunc(PY));
C := Self.GetPixel(Round(PX), Round(PY));
D := Self.GetPixel(Trunc(PX), Round(PY));
F.R := Trunc((A.R + B.R + C.R + D.R) * 0.25);
F.G := Trunc((A.G + B.G + C.G + D.G) * 0.25);
F.B := Trunc((A.B + B.B + C.B + D.B) * 0.25);
F.A := Trunc((A.A + B.A + C.A + D.A) * 0.25);
Result.SetPixel(I, J, F);
End;
End;
Procedure Image.ShiftHue(ShiftAmmount:Integer);
Var
P:PColor;
Count:Integer;
Temp:ColorHSL;
Hue:Integer;
C:Color;
Begin
Count := Self.Width * Self.Height;
P := Self.Pixels;
While Count>0 Do
Begin
Temp := ColorRGBToHSL(P^);
Hue := Temp.H + ShiftAmmount;
Temp.H := Byte(Hue);
P^ := ColorHSLToRGB(Temp);
Inc(P);
Dec(Count);
End;
End;
Function Image.GetImageTransparencyType:ImageTransparencyType;
Var
P:PColor;
Count:Integer;
Begin
If _TransparencyType = imageUnknown Then
Begin
P := Self.Pixels;
Count := Self.Width * Self.Height;
_TransparencyType := imageOpaque;
While Count>0 Do
Begin
If (P.A<255) Then
Begin
If (P.A>0) Then
Begin
_TransparencyType := imageTranslucent;
Break;
End Else
_TransparencyType := imageTransparent;
End;
Inc(P);
Dec(Count);
End;
End;
Result := _TransparencyType;
End;
{ ImageFrame }
Constructor ImageFrame.Create(Width, Height:Integer);
Begin
SetLength(_Data, Width * Height);
If (Width>0) And (Height>0) Then
FillChar(_Data[0], Width * Height * PixelSize, 0);
End;
Procedure ImageFrame.Release;
Begin
SetLength(_Data, 0);
End;
End.
|
unit arTextUtils;
{ $Id: arTextUtils.pas,v 1.5 2015/07/08 12:03:59 dinishev Exp $ }
{$Include evDefine.inc }
interface
uses
evCustomEditor,
evCommonTypes,
l3Chars;
const
cc_DigitEX = cc_Digits + [cc_Dot];
cc_SeparatorChars = [cc_Dot, cc_HardSpace];
function arMakeNameStr(const aEditor : TevCustomEditor;
const aBlockCursor : InevCommonPoint;
aCodePage : Integer): string;
function GetNumberFromStr(aStr : AnsiString) : Longint;
implementation
uses
SysUtils,
k2Tags,
evdStyles,
l3Interfaces,
l3Types,
l3String,
evInternalInterfaces,
evFacadeSelection,
nevFacade,
evEditorWindow,
TextPara_Const
;
function arGetNewBlockName(const aEditor: TevCustomEditor): Tl3PCharLen;
var
l_BlockName: Tl3PCharLen absolute Result;
function CheckRange(const aSelection : TnevIRange;
anIndex : Long): Boolean;
begin
if aSelection.Obj.IsKindOf(k2_typTextPara) then
Tl3WString(l_BlockName) := aSelection.Obj.Attr[k2_tiText].AsWStr;
Result := l_BlockName.SLen = 0;
end;
var
l_Block : TnevIRange;
l_Range : InevRange;
begin
Result := aEditor.CurText;
if aEditor.Selection <> nil then
begin
l_Block := evGetSel(aEditor);
if l_Block <> nil then
begin
l_Range := evGetBottomChildBlock(l_Block, aEditor);
if l_Range <> nil then
l_Range.IterateF(evL2TSA(@CheckRange));
end // if l_Block <> nil then
end // if aEditor.Selection <> nil then
end;
function arMakeNameStr(const aEditor : TevCustomEditor;
const aBlockCursor : InevCommonPoint;
aCodePage : Integer): string;
var
I : Integer;
l_NameStrLen : Integer;
l_IsSubArticleTest : Boolean;
l_IsSubArticle : Boolean;
begin
Result := l3DeleteDoubleSpace(Trim(l3ReplaceNonReadable(l3PCharLen2String(arGetNewBlockName(aEditor), aCodePage))));
l_NameStrLen := Length(Result);
if (l_NameStrLen > 0) then
begin
if (Result[1] in cc_Digits) then
begin
I := 0;
l_IsSubArticle := False;
l_IsSubArticleTest := False;
while (Succ(I) <= l_NameStrLen) and (Result[I + 1] in cc_DigitEX) do
begin
Inc(I);
if Result[I] = cc_Dot then //Ищем точку и след. цифру
l_IsSubArticleTest := True
else
if l_IsSubArticleTest and (Result[I] in cc_Digits) then
l_IsSubArticle := True
else
l_IsSubArticleTest := False;
end; // while (Succ(I) <= l_NameStrLen) and (Result[Succ(I)] in ['0'..'9', '.']) do
if Result[I] = cc_Dot then
Dec(I);
if (aBlockCursor.Obj.Attr[k2_tiStyle].AsLong = ev_saTxtHeader1) then
Result := 'Раздел ' + System.Copy(Result, 1, I)
else
if l_IsSubArticle then
Result := 'Подпункт ' + System.Copy(Result, 1, I)
else
Result := 'Пункт ' + System.Copy(Result, 1, I);
end // if (Result[1] in cc_Digits) then
else
if (Result[1] in cc_RomeDigits) then
begin
I := 1;
while (I < l_NameStrLen) and (Result[I] in cc_RomeDigits) do
Inc(I);
if Result[I] in cc_SeparatorChars then
Result := 'Раздел ' + System.Copy(Result, 1, I - 1);
end // if (Result[1] in cc_RomeDigits) then
else
if AnsiUpperCase(System.Copy(Result, 1, 5)) = 'ГЛАВА' then
begin
I := 6;
while (I < l_NameStrLen) and (Result[I] <> cc_Dot) do
Inc(I);
Result := System.Copy(Result, 1, I - 1);
end // if AnsiUpperCase(System.Copy(Result, 1, 5)) = 'ГЛАВА' then
else
if (AnsiUpperCase(System.Copy(Result, 1, 6)) = 'РАЗДЕЛ') or
((AnsiUpperCase(System.Copy(Result, 1, 6)) = 'СТАТЬЯ') and
(aBlockCursor.Obj.Attr[k2_tiStyle].AsLong <> ev_saArticleHeader)) then
begin
I := 7;
while (I <= l_NameStrLen) and not (Result[I] = cc_Dot) do
Inc(I);
Result := System.Copy(Result, 1, I - 1);
end; // if (AnsiUpperCase(System.Copy(Result, 1, 6)) = 'РАЗДЕЛ') or
end; // if (l_NameStrLen > 0) then
end;
(*
//вариант, который берет только первое число ло точки "4.1.1" = 4
function GetNumberFromStr(aStr : AnsiString) : Longint;
{Ищет число в строке. Используется при простановке номера Sub'a}
var
IB,IE : Integer;
begin
IB:=1;
Result := -1;
While (IB <= Length(aStr)) and not (aStr[IB] in cc_Digits) do Inc(IB);
If (IB > Length(aStr)) then Exit;
IE := Succ(IB);
While (IE <= Length(aStr)) and (aStr[IE] in cc_Digits) do Inc(IE);
try
Result := StrToInt(Copy(aStr,IB,IE-IB));
except
end;
end;
*)
//вариант, который берет все цифры "4.1.1" = 411
function GetNumberFromStr(aStr : AnsiString) : Longint;
{Ищет число в строке. Используется при простановке номера Sub'a}
var
I : Integer;
lStr : AnsiString;
l_Start: Integer;
begin
lStr := '';
Result := 0;
l_Start := 1;
while (l_Start <= Length(aStr)) and not (aStr[l_Start] in cc_Digits) do // http://mdp.garant.ru/pages/viewpage.action?pageId=603181885
Inc(l_Start);
for I := l_Start to Length(aStr) do
if aStr[I] in cc_Digits then
lStr := lStr + aStr[I]
else
if aStr[I] <> '.' then
Break;
TryStrToInt(lStr, Result);
end;
end.
|
unit MainClientFormU;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls;
type
TForm7 = class(TForm)
Button1: TButton;
Button2: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
FToken: String;
procedure SetToken(const Value: String);
{ Private declarations }
public
property Token: String read FToken write SetToken;
end;
var
Form7: TForm7;
implementation
uses
MVCFramework.RESTClient,
MVCFramework.RESTClient.Intf;
{$R *.dfm}
procedure TForm7.Button1Click(Sender: TObject);
var
lResp: IMVCRESTResponse;
begin
lResp := TMVCRESTClient.New
.BaseURL('localhost', 8080)
.Post('/login');
Token := lResp.Content;
ShowMessage('In the next 15 seconds you can request protected resources. After your token will expires!');
end;
procedure TForm7.Button2Click(Sender: TObject);
var
lResp: IMVCRESTResponse;
begin
lResp := TMVCRESTClient.New
.BaseURL('localhost', 8080)
.AddHeader('Authentication', 'bearer ' + FToken, True)
.Get('/');
ShowMessage(lResp.StatusText + sLineBreak +
lResp.Content);
end;
procedure TForm7.SetToken(const Value: String);
begin
FToken := Value;
Memo1.Lines.Text := Value;
end;
end.
|
unit perIB;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Datasnap.DBClient, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit,
EnPngGr, Vcl.ExtCtrls, Vcl.StdCtrls,
cxDropDownEdit, cxCalc, cxDBEdit, cxTextEdit, cxMaskEdit, cxSpinEdit,
Vcl.Buttons, Vcl.ImgList, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox,
cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage,
cxNavigator, cxDBData, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGrid;
const
IVA = 767;
type
TFPerIB = class(TForm)
cdsPerIB: TClientDataSet;
cdsPerIBmonto: TFloatField;
ds: TDataSource;
btnOK: TButton;
btnAnu: TButton;
img: TImageList;
DsPcia: TDataSource;
cdsPerIBjurisdiccion: TIntegerField;
vista: TcxGridDBTableView;
nivel: TcxGridLevel;
grilla: TcxGrid;
vistamonto: TcxGridDBColumn;
vistajurisdiccion: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure cdsPerIBBeforePost(DataSet: TDataSet);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
function sumarMonto: Double;
end;
var
FPerIB: TFPerIB;
implementation
uses
utiles, Dm;
{$R *.dfm}
procedure TFPerIB.btnOKClick(Sender: TObject);
begin
if ( cdsPerIB.State in [dsEdit, dsInsert]) then
try
cdsPerIB.Post;
except
on e:Exception do
begin
cdsPerIB.Cancel;
raise;
end;
end;
end;
procedure TFPerIB.cdsPerIBBeforePost(DataSet: TDataSet);
begin
if ( cdsPerIBjurisdiccion.Value=0 ) or ( cdsPerIBmonto.Value<=0) then
raise Exception.Create('Complete jurisdiccion e importe');
end;
procedure TFPerIB.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TFPerIB.FormCreate(Sender: TObject);
begin
cdsPerIB.CreateDataSet;
cdsPerIB.Append;
Dmod.TPcia.open;
Dmod.TPcia.filter := 'JURISDICCION > 0';
Dmod.TPcia.Filtered := True;
end;
procedure TFPerIB.FormDestroy(Sender: TObject);
begin
Dmod.TPcia.Filtered := False;
Dmod.TPcia.Close;
end;
procedure TFPerIB.FormKeyPress(Sender: TObject; var Key: Char);
begin
if key in [',', '.'] then
key := Utiles.DecimalSeparator;
end;
function TFPerIB.sumarMonto: Double;
begin
cdsPerIB.First;
result := 0;
while not cdsPerIB.Eof do
begin
result := result + cdsPerIBmonto.Value;
cdsPerIB.Next;
end;
end;
end.
|
unit frmInSQLMgrEditor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, iocp_sqlMgr, ComCtrls, ExtCtrls, StdCtrls, Buttons, ActnList;
type
TFormInSQLManager = class(TForm)
lvSQLNames: TListView;
Panel1: TPanel;
Panel2: TPanel;
pgSQLMgr: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
Panel3: TPanel;
Splitter1: TSplitter;
memSQL: TMemo;
memResFile: TMemo;
btnSave: TBitBtn;
btnSaveAs: TBitBtn;
btnCancel: TBitBtn;
btnOpen: TBitBtn;
alActions: TActionList;
actSaveMemSQL: TAction;
actOpen: TAction;
actSaveAs: TAction;
actSaveResFile: TAction;
procedure pgSQLMgrChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lvSQLNamesClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure alActionsUpdate(Action: TBasicAction; var Handled: Boolean);
procedure actOpenExecute(Sender: TObject);
procedure actSaveMemSQLExecute(Sender: TObject);
procedure actSaveAsExecute(Sender: TObject);
procedure actSaveResFileExecute(Sender: TObject);
procedure pgSQLMgrChanging(Sender: TObject; var AllowChange: Boolean);
private
{ Private declarations }
FSQLManager: TInSQLManager;
FCurrentSQL: TStrings;
FCurrentName: String;
procedure SetSQLManager(const Value: TInSQLManager);
procedure UpdateFormLayout(const SQLs: TStrings);
public
{ Public declarations }
property SQLManager: TInSQLManager read FSQLManager write SetSQLManager;
end;
function EditInSQLManager(InSQLManager: TInSQLManager): Boolean;
implementation
{$R *.dfm}
function EditInSQLManager(InSQLManager: TInSQLManager): Boolean;
begin
with TFormInSQLManager.Create(Application) do
try
try
SQLManager := InSQLManager;
Result := ShowModal = mrOK;
except
Result := False;
end;
finally
Free;
end;
end;
{ TFormInSQLManager }
procedure TFormInSQLManager.actOpenExecute(Sender: TObject);
begin
with TOpenDialog.Create(Self) do
try
DefaultExt := '*.sql';
Filter := '*.sql|*.sql';
Options := Options + [ofFileMustExist];
if Execute then
begin
memResFile.Lines.LoadFromFile(FileName);
FSQLManager.SQLs := memResFile.Lines;
UpdateFormLayout(memResFile.Lines);
memResFile.Modified := False;
end;
finally
Free;
end;
end;
procedure TFormInSQLManager.actSaveAsExecute(Sender: TObject);
begin
with TSaveDialog.Create(Self) do
try
DefaultExt := '*.sql';
Filter := '*.sql|*.sql';
Options := Options + [ofOverwritePrompt];
if Execute then
memResFile.Lines.SaveToFile(FileName);
finally
Free;
end;
end;
procedure TFormInSQLManager.actSaveMemSQLExecute(Sender: TObject);
var
i, iStart, iEnd: Integer;
S: String;
begin
FCurrentSQL.Assign(memSQL.Lines);
iStart := 0;
iEnd := memResFile.Lines.Count;
// Section 范围
for i := 0 to memResFile.Lines.Count - 1 do
begin
S := Trim(memResFile.Lines[i]);
if (FCurrentName = S) then // 区分大小写
iStart := i
else
if (iStart > 0) and (i > iStart) and
(Length(S) > 0) and (S[1] = '[') then
iEnd := i;
end;
if (iStart = 0) then // 直接加入
memResFile.Lines.AddStrings(memSQL.Lines)
else begin
// 删除 Section 内容,插入新内容
for i := iEnd - 1 downto iStart + 1 do
memResFile.Lines.Delete(i);
Inc(iStart);
for i := 0 to memSQL.Lines.Count - 1 do
memResFile.Lines.Insert(iStart + i, memSQL.Lines[i]);
i := memSQL.Lines.Count - 1;
if (memSQL.Lines[i] <> '') then
memResFile.Lines.Insert(iStart + i, #13#10);
end;
FSQLManager.SQLs := memResFile.Lines; // 不要用 Assign()
memSQL.Modified := False;
memResFile.Modified := False;
end;
procedure TFormInSQLManager.actSaveResFileExecute(Sender: TObject);
begin
FSQLManager.SQLs := memResFile.Lines; // 不要用 Assign()
UpdateFormLayout(memResFile.Lines);
memResFile.Modified := False;
end;
procedure TFormInSQLManager.alActionsUpdate(Action: TBasicAction;
var Handled: Boolean);
begin
actOpen.Enabled := (pgSQLMgr.ActivePageIndex = 1) and (memResFile.Modified = False);
actSaveMemSQL.Enabled := memSQL.Modified;
actSaveResFile.Enabled := memResFile.Modified;
actSaveAs.Enabled := pgSQLMgr.ActivePageIndex = 1;
end;
procedure TFormInSQLManager.FormCreate(Sender: TObject);
begin
pgSQLMgr.ActivePageIndex := 0;
pgSQLMgrChange(nil);
end;
procedure TFormInSQLManager.FormDestroy(Sender: TObject);
begin
lvSQLNames.Items.Clear;
memSQL.Lines.Clear;
memResFile.Lines.Clear;
end;
procedure TFormInSQLManager.lvSQLNamesClick(Sender: TObject);
begin
if Assigned(lvSQLNames.Selected) and not memSQL.Modified then
begin
FCurrentSQL := TStrings(lvSQLNames.Selected.Data);
FCurrentName := lvSQLNames.Selected.Caption;
Delete(FCurrentName, 1, Pos('>', FCurrentName));
FCurrentName := '[' + FCurrentName + ']';
memSQL.Lines.Assign(FCurrentSQL);
memSQL.Modified := False;
end;
end;
procedure TFormInSQLManager.pgSQLMgrChange(Sender: TObject);
begin
btnOpen.Enabled := pgSQLMgr.ActivePageIndex = 1;
btnSaveAs.Enabled := btnOpen.Enabled;
if btnOpen.Enabled then
btnSave.Action := actSaveResFile
else
btnSave.Action := actSaveMemSQL
end;
procedure TFormInSQLManager.pgSQLMgrChanging(Sender: TObject;
var AllowChange: Boolean);
begin
AllowChange := btnSave.Enabled = False;
end;
procedure TFormInSQLManager.SetSQLManager(const Value: TInSQLManager);
begin
FSQLManager := Value;
memResFile.Lines := FSQLManager.SQLs;
UpdateFormLayout(memResFile.Lines);
end;
procedure TFormInSQLManager.UpdateFormLayout(const SQLs: TStrings);
var
i: Integer;
Obj: TSQLObject;
begin
lvSQLNames.Items.BeginUpdate;
memResFile.Lines.BeginUpdate;
try
lvSQLNames.Items.Clear;
memSQL.Lines.Clear;
for i := 0 to FSQLManager.Count - 1 do
begin
Obj := FSQLManager.Items[i];
with lvSQLNames.Items.Add do
begin
Caption := IntToStr(i) + '->' + Obj.SQLName;
Data := Pointer(Obj.SQL);
end;
end;
finally
memResFile.Modified := False;
memResFile.Lines.EndUpdate;
lvSQLNames.Items.EndUpdate;
end;
end;
end.
|
unit Control.Sistema;
interface
uses
System.SysUtils, Forms, System.Classes, DAO.Conexao, Common.Utils, Global.Parametros, Control.Bases,
FireDAC.Comp.Client;
type
TSistemaControl = class
private
FConexao: TConexao;
FStart: Boolean;
FBases: TBasesControl;
class var FInstante : TSistemaControl;
public
constructor Create;
destructor Destroy; override;
class function GetInstance: TSistemaControl;
property Conexao: TConexao read FConexao write FConexao;
property Start: Boolean read FStart write FStart;
property Base: TBasesControl read FBases write FBases;
function StartGlobal(): Boolean;
function SaveParamINI(sSection: String; sKey: String; sValue: String): Boolean;
function ReturSkin(iIndex: Integer): String;
function LoadSkinsINI(): TStringList;
procedure CarregaBases(pParam: Array of variant);
end;
const
INIFILE = 'database.ini';
implementation
{ TSistemaControl }
procedure TSistemaControl.CarregaBases(pParam: array of variant);
var
FDQuery : TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery;
FDQuery := FBases.Localizar(pParam);
if not FDQuery.IsEmpty then
begin
FBases.Bases.Codigo := FDquery.FieldByName('COD_AGENTE').AsInteger;
FBases.Bases.RazaoSocial := FDQuery.FieldByName('DES_RAZAO_SOCIAL').AsString;
FBases.Bases.NomeFantasia := FDQuery.FieldByName('NOM_FANTASIA').AsString;
FBases.Bases.TipoDoc := FDQuery.FieldByName('DES_TIPO_DOC').AsString;
FBases.Bases.CNPJCPF := FDQuery.FieldByName('NUM_CNPJ').AsString;
FBases.Bases.IE := FDQuery.FieldByName('NUM_IE').AsString;
FBases.Bases.IEST := FDQuery.FieldByName('NUM_IEST').AsString;
FBases.Bases.IM := FDQuery.FieldByName('NUM_IM').AsString;
FBases.Bases.CNAE := FDQuery.FieldByName('COD_CNAE').AsString;
FBases.Bases.CRT := FDQuery.FieldByName('COD_CRT').AsInteger;
FBases.Bases.NumeroCNH := FDQuery.FieldByName('NUM_CNH').AsString;
FBases.Bases.CategoriaCNH := FDQuery.FieldByName('DES_CATEGORIA_CNH').AsString;
FBases.Bases.ValidadeCNH := FDQuery.FieldByName('DAT_VALIDADE_CNH').AsDateTime;
FBases.Bases.PaginaWeb := FDQuery.FieldByName('DES_PAGINA').AsString;
FBases.Bases.Status := FDQuery.FieldByName('COD_STATUS').AsInteger;
FBases.Bases.Obs := FDQuery.FieldByName('DES_OBSERVACAO').AsString;
FBases.Bases.DataCadastro := FDQuery.FieldByName('DAT_CADASTRO').AsDateTime;
FBases.Bases.DataAlteracao := FDQuery.FieldByName('DAT_ALTERACAO').AsDateTime;
FBases.Bases.ValorVerba := FDQuery.FieldByName('VAL_VERBA').AsFloat;
FBases.Bases.TipoConta := FDQuery.FieldByName('DES_TIPO_CONTA').AsString;
FBases.Bases.CodigoBanco := FDQuery.FieldByName('COD_BANCO').AsString;
FBases.Bases.NumeroAgente := FDQuery.FieldByName('COD_AGENCIA').AsString;
FBases.Bases.NumeroConta := FDQuery.FieldByName('NUM_CONTA').AsString;
FBases.Bases.NomeFavorecido := FDQuery.FieldByName('NOM_FAVORECIDO').AsString;
FBases.Bases.CNPJCPFFavorecido := FDQuery.FieldByName('NUM_CPF_CNPJ_FAVORECIDO').AsString;
FBases.Bases.FormaPagamento := FDQuery.FieldByName('DES_FORMA_PAGAMENTO').AsString;
FBases.Bases.CentroCusto := FDQuery.FieldByName('COD_CENTRO_CUSTO').AsInteger;
FBases.Bases.Grupo := FDQuery.FieldByName('COD_GRUPO').AsInteger;
end
else
begin
FBases.Bases.Codigo := 0;
FBases.Bases.RazaoSocial := 'NONE';
FBases.Bases.NomeFantasia := 'NONE';
FBases.Bases.TipoDoc := 'NONE';
FBases.Bases.CNPJCPF := 'NONE';
FBases.Bases.IE := 'NONE';
FBases.Bases.IEST := 'NONE';
FBases.Bases.IM := 'NONE';
FBases.Bases.CNAE := 'NONE';
FBases.Bases.CRT := 0;
FBases.Bases.NumeroCNH := 'NONE';
FBases.Bases.CategoriaCNH := 'NONE';
FBases.Bases.ValidadeCNH := 0;
FBases.Bases.PaginaWeb := 'NONE';
FBases.Bases.Status := 0;
FBases.Bases.Obs := '';
FBases.Bases.DataCadastro := 0;
FBases.Bases.DataAlteracao := 0;
FBases.Bases.ValorVerba := 0;
FBases.Bases.TipoConta := 'NONE';
FBases.Bases.CodigoBanco := '0';
FBases.Bases.NumeroAgente := '0';
FBases.Bases.NumeroConta := '0';
FBases.Bases.NomeFavorecido := 'NONE';
FBases.Bases.CNPJCPFFavorecido := 'NONE';
FBases.Bases.FormaPagamento := 'NONE';
FBases.Bases.CentroCusto := 0;
FBases.Bases.Grupo := 0;
end;
finally
FDQuery.Free;
end;
end;
constructor TSistemaControl.Create;
begin
FStart := StartGlobal;
if FStart then
begin
FConexao := TConexao.Create;
FBases := TBasesControl.Create;
end;
end;
destructor TSistemaControl.Destroy;
begin
FConexao.Free;
FBases.Free;
inherited;
end;
class function TSistemaControl.GetInstance: TSistemaControl;
begin
if not Assigned(Self.FInstante) then
begin
Self.FInstante := TSistemaControl.Create();
end;
Result := Self.FInstante;
end;
function TSistemaControl.LoadSkinsINI: TStringList;
var
sSkinIni : String;
lLista: TStringList;
iIndex : Integer;
sSkin: String;
begin
sSkinINI := ExtractFilePath(Application.ExeName) + '\skins.ini';
if not FileExists(sSkinINI) then Exit;
iIndex := 0;
lLista := TStringlist.Create();
sSkin := 'NONE';
while not sSKin.IsEmpty do
begin
sSkin := Common.Utils.TUtils.LeIni(sSkinINI,'Skin',iIndex.ToString);
if not sSkin.IsEmpty then
begin
lLista.Add(sSkin);
end;
iIndex := iIndex + 1;
end;
Result := lLista;
end;
function TSistemaControl.ReturSkin(iIndex: Integer): String;
var
sSkinIni : String;
sSkin: String;
begin
sSkin := '';
sSkinINI := ExtractFilePath(Application.ExeName) + '\skins.ini';
if not FileExists(sSkinINI) then Exit;
Result := Common.Utils.TUtils.LeIni(sSkinINI,'Skin',iIndex.ToString);
end;
function TSistemaControl.SaveParamINI(sSection, sKey, sValue: String): Boolean;
begin
Result := False;
Common.Utils.TUtils.GravaIni(Global.Parametros.pFileIni,sSection,sKey,sValue);
Result := True;
end;
function TSistemaControl.StartGlobal: Boolean;
begin
Result := False;
Global.Parametros.pFileIni := ExtractFilePath(Application.ExeName) + '\' + INIFILE;
if not FileExists(Global.Parametros.pFileIni) then Exit;
Global.Parametros.pDriverID := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','DriverID');
Global.Parametros.pServer := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','HostName');
Global.Parametros.pDatabase := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','Database');
Global.Parametros.pPort := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','Port');
Global.Parametros.pKBD := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','KBD');
Global.Parametros.pUBD := Common.Utils.TUtils.DesCriptografa(Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','UBD'),StrToIntDef(Global.Parametros.pKBD,0));
Global.Parametros.pPBD := Common.Utils.TUtils.DesCriptografa(Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','PBD'),StrToIntDef(Global.Parametros.pKBD,0));
Global.Parametros.pSkin := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Database','Skin');
Global.Parametros.pLastUser := Common.Utils.TUtils.LeIni(Global.Parametros.pFileIni,'Login','LastUser');
Result := True;
end;
end.
|
const firstNamesCount: integer = 10;
type firstNamesType = array [1..firstNamesCount] of string;
var firstNames: firstNamesType = ('Mike', 'Jack', 'Mini', 'Nelly', 'Casandra', 'Artem', 'Valera', 'Boosh', 'Lesly', 'Lilly');
const lastNamesCount: integer = 10;
type lastNamesType = array [1..lastNamesCount] of string;
var lastNames: lastNamesType = ('Johnson', 'Williams', 'Smith', 'Jones', 'Brown', 'Davis', 'Anderson', 'Wilson', 'Taylor', 'Moore');
const addressesCount: integer = 10;
type addressesType = array [1..addressesCount] of string;
var addresses: addressesType = ('Abby Park Street', 'Beatles Avenue', 'Communal Square', 'Dean Avenue', 'Galghard Road', 'Eastern Cesta', 'Impressionist Avenue', 'Highway Avenue', 'Pine Street', 'Venice Street ');
const examsCount: integer = 3;
type examsType = array [1..examsCount] of string;
var exams: examsType = ('Math', 'Pragramming', 'Language');
const minMark: integer = 1;
const maxMark: integer = 10;
Type examsSheetType = record
maths: integer;
programming: integer;
language: integer;
end;
Type applicantsSheetType = record
firstName: string;
lastName: string;
address: string;
exams: examsSheetType;
end;
const applicantsSheetsCount: integer = 20;
type applicantsSheetsType = array [1..applicantsSheetsCount] of applicantsSheetType;
function getRandomFirstName(): string;
begin
var randomFirstNameIndex: integer := Random(1, firstNamesCount);
var randomFirstName: string := firstNames[randomFirstNameIndex];
Result := randomFirstName;
end;
function getRandomLastName(): string;
begin
var randomLastNameIndex: integer := Random(1, lastNamesCount);
var randomLastName: string := lastNames[randomLastNameIndex];
Result := randomLastName;
end;
function getRandomAddress(): string;
begin
var randomAddressIndex: integer := Random(1, addressesCount);
var randomAddress: string := addresses[randomAddressIndex];
Result := randomAddress;
end;
function getRandomMark(): integer;
begin
var randomMark: integer := Random(minMark, maxMark);
Result := randomMark;
end;
function generateSheets(): applicantsSheetsType;
begin
var applicantsSheets: applicantsSheetsType;
for var index := 1 to applicantsSheetsCount do
begin
var randomFirstName: string := getRandomFirstName();
var randomLastName: string := getRandomLastName();
var randomAddress: string := getRandomAddress();
var randomMathsMark: integer := getRandomMark();
var randomProgrammingMark: integer := getRandomMark();
var randomLanguageMark: integer := getRandomMark();
with applicantsSheets[index] do
begin
firstName := randomFirstName;
lastName := randomLastName;
address := randomAddress;
exams.maths := randomMathsMark;
exams.programming := randomProgrammingMark;
exams.language := randomLanguageMark;
end;
end;
Result := applicantsSheets;
end;
Type filteredSheetsType = record
sheets: applicantsSheetsType;
size: integer;
end;
procedure pushToSheets(var sheets: filteredSheetsType; item: applicantsSheetType);
begin
sheets.sheets[sheets.size + 1] := item;
sheets.size := sheets.size + 1;
end;
function getAverageMark(exams: examsSheetType): real;
begin
var examsAverage: real := (exams.maths + exams.programming + exams.language) / 3;
Result := examsAverage;
end;
function filterSheets(sheets: applicantsSheetsType; size: integer; averageMark: real; lastNameStartingLetter: string): filteredSheetsType;
begin
var filteredSheets: filteredSheetsType;
filteredSheets.size := 0;
for var index := 1 to size do
begin
var examsAverage: real := getAverageMark(sheets[index].exams);
var isLastNameStartsWith: boolean := true;
if lastNameStartingLetter <> '' then
begin
isLastNameStartsWith := sheets[index].lastName[1].ToLower() = lastNameStartingLetter.ToLower();
end;
if (examsAverage > averageMark) and (isLastNameStartsWith = true) then
begin
pushToSheets(filteredSheets, sheets[index]);
end;
end;
Result := filteredSheets;
end;
procedure viewSheets(sheets: applicantsSheetsType; size: integer);
begin
for var index := 1 to size do
begin
with sheets[index] do
begin
writeln('First name: ', firstName);
writeln('Last name: ', lastName);
writeln('Address: ', address);
write('Exams: ');
writeln('Maths: ', exams.maths);
writeln(' Programming: ', exams.programming);
writeln(' Language: ', exams.language);
end;
writeln;
end;
end;
const averageMark = 6;
const lastNameStartingLetter = 'a';
begin
var applicantsSheets: applicantsSheetsType := generateSheets();
var filteredApplicantsSheets: filteredSheetsType := filterSheets(applicantsSheets, applicantsSheetsCount, averageMark, lastNameStartingLetter);
writeln('All students');
writeln;
viewSheets(applicantsSheets, applicantsSheetsCount);
writeln;
writeln('---------------------------');
writeln;
writeln('Students with average mark: "', averageMark, '" and last names that starts with: "', lastNameStartingLetter, '"');
writeln;
writeln('Count: ', filteredApplicantsSheets.size);
writeln;
viewSheets(filteredApplicantsSheets.sheets, filteredApplicantsSheets.size);
end.
|
// --------------------------------------------------------------------------
// Archivo del Proyecto Ventas
// Página del proyecto: http://sourceforge.net/projects/ventas
// --------------------------------------------------------------------------
// Este archivo puede ser distribuido y/o modificado bajo lo terminos de la
// Licencia Pública General versión 2 como es publicada por la Free Software
// Fundation, Inc.
// --------------------------------------------------------------------------
unit Contrasenia;
interface
uses
SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs,
QStdCtrls, QButtons, Inifiles;
type
TfrmContrasenia = class(TForm)
grpContrasenias: TGroupBox;
Label1: TLabel;
txtUsuario: TEdit;
txtContra: TEdit;
txtContraNueva: TEdit;
Label4: TLabel;
Label2: TLabel;
Label3: TLabel;
txtContraRepite: TEdit;
btnAceptar: TBitBtn;
btnCancelar: TBitBtn;
procedure btnAceptarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure RecuperaConfig;
procedure FormCreate(Sender: TObject);
private
function VerificaDatos:boolean;
function VerificaContra:boolean;
public
end;
var
frmContrasenia: TfrmContrasenia;
implementation
uses Permisos, dm;
{$R *.xfm}
procedure TfrmContrasenia.btnAceptarClick(Sender: TObject);
var
sContra : String;
begin
if VerificaDatos then begin
sContra := frmPermisos.Encripta(txtContraNueva.Text);
with dmDatos.qryModifica do begin
Close;
SQL.Clear;
SQL.Add('UPDATE usuarios SET contra = ''' + sContra + ''',');
SQL.Add('fecha_umov = ''' + FormatDateTime('mm/dd/yyyy hh:nn:ss',Now) + '''');
SQL.Add('WHERE login = ''' + txtUsuario.Text + '''');
ExecSQL;
Close;
end;
Application.MessageBox('La contraseña se ha cambiado con éxito','Aviso',[smbOK],smsInformation);
Close;
end;
end;
procedure TfrmContrasenia.FormShow(Sender: TObject);
begin
txtContra.Clear;
txtContraNueva.Clear;
txtContraRepite.Clear;
txtContra.SetFocus;
end;
// -----------------------------------------------------------------------------
// Función: VerificaDatos
// Objetivo: Verificar que se introduzcan datos en los campos requeridos
// y que no exista algún error en la captura de los datos
// Regresa: bVerifica (falso o verdadero)
// Falso: si existe un error en la captura de los datos
// Verdadero: si todos los datos están correctos
// -----------------------------------------------------------------------------
function TfrmContrasenia.VerificaDatos:boolean;
var
bVerifica : Boolean;
begin
bVerifica := True;
if(Length(txtContra.Text) = 0) then begin
txtContra.SetFocus;
Application.MessageBox('Introduce la contraseña','Error',[smbOK],smsCritical);
bVerifica := False;
end
else if not VerificaContra then begin
txtContra.SetFocus;
Application.MessageBox('La contraseña no es correcta','Error',[smbOK],smsCritical);
bVerifica := False;
end
else if(Length(txtContraNueva.Text) = 0) then begin
txtContraNueva.SetFocus;
Application.MessageBox('Introduce la nueva contraseña','Error',[smbOK],smsCritical);
bVerifica := False;
end
else if(Length(txtContraRepite.Text) = 0) then begin
txtContraRepite.SetFocus;
Application.MessageBox('Repite la contraseña','Error',[smbOK],smsCritical);
bVerifica := False;
end
else if(Length(txtContraNueva.Text) < 6) then begin
txtContraNueva.SetFocus;
Application.MessageBox('La contraseña debe de ser de al menos 6 caracteres','Error',[smbOK],smsCritical);
bVerifica := False;
end
else if(txtContraNueva.Text <> txtContraRepite.Text) then begin
txtContraNueva.SetFocus;
Application.MessageBox('Las contraseñas no coinciden','Error',[smbOK],smsCritical);
bVerifica := False;
end;
VerificaDatos := bVerifica;
end;
// -----------------------------------------------------------------------------
// Función: VerificaContra
// Objetivo: Verificar que la contraseña introducida sea igual a la registrada en
// la base de datos
// Regresa: bVerifica (falso o verdadero)
// Falso: si no es correcta
// Verdadero: si es correcta
// -----------------------------------------------------------------------------
function TfrmContrasenia.VerificaContra:boolean;
var
bRegreso : boolean;
begin
bRegreso := true;
with dmDatos.qryConsulta do begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM usuarios WHERE login = ''' + txtUsuario.Text + '''');
Open;
if frmPermisos.DesEncripta(Trim(FieldByName('contra').AsString)) <> txtContra.Text then
bRegreso := false;
Close;
end;
Result := bRegreso;
end;
procedure TfrmContrasenia.Salta(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
{Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)}
if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then
if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then
SelectNext(Sender as TWidgetControl, true, true);
end;
procedure TfrmContrasenia.FormClose(Sender: TObject;
var Action: TCloseAction);
var iniArchivo : TIniFile;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
with iniArchivo do begin
// Registra la posición y de la ventana
WriteString('Contraseña', 'Posy', IntToStr(Top));
// Registra la posición X de la ventana
WriteString('Contraseña', 'Posx', IntToStr(Left));
Free;
end;
end;
procedure TfrmContrasenia.RecuperaConfig;
var
iniArchivo : TIniFile;
sIzq, sArriba: String;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini');
with iniArchivo do begin
//Recupera la posición Y de la ventana
sArriba := ReadString('Contraseña', 'Posy', '');
//Recupera la posición X de la ventana
sIzq := ReadString('Contraseña', 'Posx', '');
if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin
Left := StrToInt(sIzq);
Top := StrToInt(sArriba);
end;
Free;
end;
end;
procedure TfrmContrasenia.FormCreate(Sender: TObject);
begin
RecuperaConfig;
end;
end.
|
unit DataService;
interface
uses
JunoApi4Delphi.Interfaces,
REST.JSON,
System.JSON,
System.Generics.Collections,
Banks,
AuthorizationService,
CompanyType;
type
TDataService = class(TInterfacedObject, iDataService)
private
FParent : iJunoApi4DelphiConig;
FAuth : iAuthorizationService;
public
constructor Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService);
destructor Destroy; override;
class function New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iDataService;
function Banks : TObjectList<TBanks>;
function CompanyTypes : String;
function BusinessAreas : String;
end;
implementation
uses
RESTRequest4D, REST.Types, System.SysUtils;
CONST
DATA_ENDPOINT = '/data';
BANKS_ENDPOINT = DATA_ENDPOINT + '/banks';
COMPANY_TYPES_ENDPOINT = DATA_ENDPOINT + '/company-types';
BUSINESS_AREAS_ENDPOINT = DATA_ENDPOINT + '/business-areas';
{ TDataService }
function TDataService.Banks: TObjectList<TBanks>;
var
jobj : TJSONObject;
jv: TJSONValue;
ja : TJSONArray;
I : Integer;
begin
jObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(
TRequest.New
.BaseURL(FParent.ResourceEndpoint + BANKS_ENDPOINT)
.Token(FAuth.Token)
.AddParam('X-Api-Version','2',pkHTTPHEADER)
.Get.Content), 0) as TJSONObject;
jv := jObj.Get('_embedded').JsonValue;
jobj := jv as TJSONObject;
jv := jobj.Get('banks').JsonValue;
ja := jv as TJSONArray;
Result := TObjectList<TBanks>.Create;
for I := 0 to ja.Size -1 do
begin
Result.Add(TBanks.Create);
jObj := (ja.Get(i) as TJSONObject);
jv := jObj.Get(0).JsonValue;
Result[I].Number := jv.Value;
jv := jObj.Get(1).JsonValue;
Result[I].Name := jv.Value;
end;
end;
function TDataService.BusinessAreas: String;
begin
Result :=
TRequest.New
.BaseURL(FParent.ResourceEndpoint + BUSINESS_AREAS_ENDPOINT)
.Token(FAuth.Token)
.AddParam('X-Api-Version','2',pkHTTPHEADER)
.Get.Content;
end;
function TDataService.CompanyTypes: String;
var
JSONObj : TJSONObject;
CompanyType : TCompanyType;
begin
JsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(
TRequest.New
.BaseURL(FParent.ResourceEndpoint + COMPANY_TYPES_ENDPOINT)
.Token(FAuth.Token)
.AddParam('X-Api-Version','2',pkHTTPHEADER)
.Get.Content), 0) as TJSONObject;
CompanyType := TJson.JsonToObject<TCompanyType>(JsonObj);
Result := String.Join(',',CompanyType.CompanyTypes);
end;
constructor TDataService.Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService);
begin
FParent := Parent;
FAuth := AuthService;
end;
destructor TDataService.Destroy;
begin
inherited;
end;
class function TDataService.New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iDataService;
begin
Result := Self.Create(Parent, AuthService);
end;
end.
|
(*------------------------------------------------------------------
BinominalCoefficient || Neuhold Michael 24.10.2018
Calculate the binomial coefficient (k choose n).
bc = n! DIV (k! *(n-k)!)
------------------------------------------------------------------*)
PROGRAM BinominalCoefficient;
USES
Crt;
VAR
i : INTEGER;
k,n: INTEGER;
kf, nf, nkf: INTEGER; (* kf .. k!, nf .. n!, nkf .. (n-k)! *)
bc: INTEGER; (* binomial coefficient *)
BEGIN
WriteLn('Berechnung des Binominalkoeffizienten');
WriteLn('<#---------------------------------#>');
Write('n > '); ReadLn(n);
Write('k > '); ReadLn(k);
(* calculate n! *)
nf := 1;
FOR i := 2 TO n DO BEGIN
nf := nf * i;
END; (* FOR *)
(* calculate k! *)
kf := 1;
FOR i := 2 TO k DO BEGIN
kf := kf * i;
END; (* FOR *)
(* calculate (n-k)! *)
nkf := 1;
FOR i := 2 TO (n-k) DO BEGIN
nkf := nkf * i;
END; (* FOR *)
bc := nf DIV (kf * nkf); (* DIV oder / *)
WriteLN('BinominalCoefficient ', n, ' über ', k, ' = ', bc);
END. (* BinominalCoefficient *) |
unit afwVirtualCaret;
{* Виртуальная каретка. }
// Модуль: "w:\common\components\gui\Garant\AFW\implementation\Visual\afwVirtualCaret.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TafwVirtualCaret" MUID: (474154CE0081)
{$Include w:\common\components\gui\Garant\AFW\afwDefine.inc}
interface
uses
l3IntfUses
, l3CacheableBase
, afwInterfaces
, Types
, l3Interfaces
;
type
TafwVirtualCaret = class(Tl3CacheableBase, IafwCaret, IafwScrollCaret)
{* Виртуальная каретка. }
private
f_Extent: TafwSPoint;
f_CaretPos: TafwSPoint;
f_CaretExt: TPoint;
protected
function CheckHidden: Boolean;
function CanHide: Boolean;
procedure Set_Extent(const aValue: TPoint);
function Get_Position: Tl3_SPoint;
procedure Set_Position(const aValue: Tl3_SPoint);
function Get_Visible: Boolean;
procedure pm_SetHidden(aValue: Boolean);
function IsInited: Boolean;
function IsOnScreen: Boolean;
procedure Scroll(const aOfs: Tl3_SPoint);
procedure Reset;
public
constructor Create(const anExtent: TafwSPoint); reintroduce;
class function Make(const anExtent: TafwSPoint): IafwScrollCaret; reintroduce;
end;//TafwVirtualCaret
implementation
uses
l3ImplUses
, l3Units
//#UC START# *474154CE0081impl_uses*
//#UC END# *474154CE0081impl_uses*
;
constructor TafwVirtualCaret.Create(const anExtent: TafwSPoint);
//#UC START# *4CC69A8B0337_474154CE0081_var*
//#UC END# *4CC69A8B0337_474154CE0081_var*
begin
//#UC START# *4CC69A8B0337_474154CE0081_impl*
f_Extent := anExtent;
Reset;
inherited Create;
//#UC END# *4CC69A8B0337_474154CE0081_impl*
end;//TafwVirtualCaret.Create
class function TafwVirtualCaret.Make(const anExtent: TafwSPoint): IafwScrollCaret;
var
l_Inst : TafwVirtualCaret;
begin
l_Inst := Create(anExtent);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TafwVirtualCaret.Make
function TafwVirtualCaret.CheckHidden: Boolean;
//#UC START# *4728CC9400ED_474154CE0081_var*
//#UC END# *4728CC9400ED_474154CE0081_var*
begin
//#UC START# *4728CC9400ED_474154CE0081_impl*
Result := false;
//#UC END# *4728CC9400ED_474154CE0081_impl*
end;//TafwVirtualCaret.CheckHidden
function TafwVirtualCaret.CanHide: Boolean;
//#UC START# *4728CCB1004E_474154CE0081_var*
//#UC END# *4728CCB1004E_474154CE0081_var*
begin
//#UC START# *4728CCB1004E_474154CE0081_impl*
Result := false;
//#UC END# *4728CCB1004E_474154CE0081_impl*
end;//TafwVirtualCaret.CanHide
procedure TafwVirtualCaret.Set_Extent(const aValue: TPoint);
//#UC START# *4728CCBC023F_474154CE0081set_var*
//#UC END# *4728CCBC023F_474154CE0081set_var*
begin
//#UC START# *4728CCBC023F_474154CE0081set_impl*
f_CaretExt := aValue;
//#UC END# *4728CCBC023F_474154CE0081set_impl*
end;//TafwVirtualCaret.Set_Extent
function TafwVirtualCaret.Get_Position: Tl3_SPoint;
//#UC START# *4728CCC90157_474154CE0081get_var*
//#UC END# *4728CCC90157_474154CE0081get_var*
begin
//#UC START# *4728CCC90157_474154CE0081get_impl*
Result := f_CaretPos;
//#UC END# *4728CCC90157_474154CE0081get_impl*
end;//TafwVirtualCaret.Get_Position
procedure TafwVirtualCaret.Set_Position(const aValue: Tl3_SPoint);
//#UC START# *4728CCC90157_474154CE0081set_var*
//#UC END# *4728CCC90157_474154CE0081set_var*
begin
//#UC START# *4728CCC90157_474154CE0081set_impl*
f_CaretPos := Tl3SPoint(aValue);
//#UC END# *4728CCC90157_474154CE0081set_impl*
end;//TafwVirtualCaret.Set_Position
function TafwVirtualCaret.Get_Visible: Boolean;
//#UC START# *4728CCD502A9_474154CE0081get_var*
//#UC END# *4728CCD502A9_474154CE0081get_var*
begin
//#UC START# *4728CCD502A9_474154CE0081get_impl*
Result := true;
//#UC END# *4728CCD502A9_474154CE0081get_impl*
end;//TafwVirtualCaret.Get_Visible
procedure TafwVirtualCaret.pm_SetHidden(aValue: Boolean);
//#UC START# *4728CCEA00DC_474154CE0081set_var*
//#UC END# *4728CCEA00DC_474154CE0081set_var*
begin
//#UC START# *4728CCEA00DC_474154CE0081set_impl*
//#UC END# *4728CCEA00DC_474154CE0081set_impl*
end;//TafwVirtualCaret.pm_SetHidden
function TafwVirtualCaret.IsInited: Boolean;
//#UC START# *4728CD1103B3_474154CE0081_var*
//#UC END# *4728CD1103B3_474154CE0081_var*
begin
//#UC START# *4728CD1103B3_474154CE0081_impl*
Result := (f_CaretPos.Y <> High(f_CaretPos.Y));
//#UC END# *4728CD1103B3_474154CE0081_impl*
end;//TafwVirtualCaret.IsInited
function TafwVirtualCaret.IsOnScreen: Boolean;
//#UC START# *4728CD240270_474154CE0081_var*
//#UC END# *4728CD240270_474154CE0081_var*
begin
//#UC START# *4728CD240270_474154CE0081_impl*
Assert(IsInited);
Result := (f_CaretPos.Y >= 0) AND (f_CaretPos.Y + f_CaretExt.Y <= f_Extent.Y);
//#UC END# *4728CD240270_474154CE0081_impl*
end;//TafwVirtualCaret.IsOnScreen
procedure TafwVirtualCaret.Scroll(const aOfs: Tl3_SPoint);
//#UC START# *4728CD370137_474154CE0081_var*
//#UC END# *4728CD370137_474154CE0081_var*
begin
//#UC START# *4728CD370137_474154CE0081_impl*
if IsInited then
Tl3SPoint(f_CaretPos).Inc(Tl3SPoint(aOfs));
//#UC END# *4728CD370137_474154CE0081_impl*
end;//TafwVirtualCaret.Scroll
procedure TafwVirtualCaret.Reset;
//#UC START# *4728CD4101D2_474154CE0081_var*
//#UC END# *4728CD4101D2_474154CE0081_var*
begin
//#UC START# *4728CD4101D2_474154CE0081_impl*
f_CaretPos.X := High(f_CaretPos.X);
f_CaretPos.Y := High(f_CaretPos.Y);
//#UC END# *4728CD4101D2_474154CE0081_impl*
end;//TafwVirtualCaret.Reset
end.
|
unit fmCreateGroup;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
ADC.Types, ADC.DC, ADC.GlobalVar, ADC.Common, ActiveDs_TLB;
type
TForm_CreateGroup = class(TForm)
Edit_GroupNamePre2k: TEdit;
Label_GroupNamePre2k: TLabel;
Edit_GroupName: TEdit;
Label_GroupName: TLabel;
Button_SelectContainer: TButton;
Edit_Container: TEdit;
Label_Container: TLabel;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
RadioButton_Local: TRadioButton;
RadioButton_Global: TRadioButton;
RadioButton_Universal: TRadioButton;
RadioButton_Security: TRadioButton;
RadioButton_Distribution: TRadioButton;
Button_OK: TButton;
Button_Cancel: TButton;
procedure Button_SelectContainerClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button_CancelClick(Sender: TObject);
procedure Button_OKClick(Sender: TObject);
procedure Edit_GroupNameChange(Sender: TObject);
private
FDomainController: TDCInfo;
FContainer: TADContainer;
FCallingForm: TForm;
FOnGroupCreate: TCreateGroupProc;
procedure ClearTextFields;
procedure OnTargetContainerSelect(Sender: TObject; ACont: TADContainer);
procedure SetContainer(const Value: TADContainer);
procedure SetDomainController(const Value: TDCInfo);
procedure SetCallingForm(const Value: TForm);
public
property CallingForm: TForm write SetCallingForm;
property DomainController: TDCInfo read FDomainController write SetDomainController;
property Container: TADContainer read FContainer write SetContainer;
property OnGroupCreate: TCreateGroupProc read FOnGroupCreate write FOnGroupCreate;
end;
var
Form_CreateGroup: TForm_CreateGroup;
implementation
{$R *.dfm}
uses fmContainerSelection;
procedure TForm_CreateGroup.Button_CancelClick(Sender: TObject);
begin
Close;
end;
procedure TForm_CreateGroup.Button_OKClick(Sender: TObject);
var
groupType: DWORD;
res: string;
MsgBoxParam: TMsgBoxParams;
begin
groupType := 0;
if RadioButton_Local.Checked
then groupType := ADS_GROUP_TYPE_LOCAL_GROUP
else if RadioButton_Global.Checked
then groupType := ADS_GROUP_TYPE_GLOBAL_GROUP
else if RadioButton_Universal.Checked
then groupType := ADS_GROUP_TYPE_UNIVERSAL_GROUP;
if RadioButton_Security.Checked
then groupType := groupType or ADS_GROUP_TYPE_SECURITY_ENABLED;
try
if (Edit_Container.Text = '')
or (Edit_GroupName.Text = '')
or (Edit_GroupNamePre2k.Text = '')
then raise Exception.Create(
'Заполнены не все обязательные поля.' + #13#10 +
'Поля "Создать в", "Имя группы" и "Имя группы: (пред-Windows 2000)" должны быть заполнены.'
);
case apAPI of
ADC_API_LDAP: begin
res := ADCreateGroup(LDAPBinding, FContainer.DistinguishedName,
Edit_GroupName.Text, Edit_GroupNamePre2k.Text, groupType);
end;
ADC_API_ADSI: begin
res := ADCreateGroup(ADSIBinding, FContainer.DistinguishedName,
Edit_GroupName.Text, Edit_GroupNamePre2k.Text, groupType);
end;
end;
except
on E: Exception do
begin
res := '';
with MsgBoxParam do
begin
cbSize := SizeOf(MsgBoxParam);
hwndOwner := Self.Handle;
hInstance := 0;
case apAPI of
ADC_API_LDAP: lpszCaption := PChar('LDAP Exception');
ADC_API_ADSI: lpszCaption := PChar('ADSI Exception');
end;
lpszIcon := MAKEINTRESOURCE(32513);
dwStyle := MB_OK or MB_ICONHAND;
dwContextHelpId := 0;
lpfnMsgBoxCallback := nil;
dwLanguageId := LANG_NEUTRAL;
lpszText := PChar(E.Message);
end;
MessageBoxIndirect(MsgBoxParam);
end;
end;
if (not res.IsEmpty) and Assigned(FOnGroupCreate) then
begin
FOnGroupCreate(res);
Close;
end;
end;
procedure TForm_CreateGroup.Button_SelectContainerClick(Sender: TObject);
const
msgTemplate = 'Выберите контейнер Active Directory в котором будет %s.';
begin
Form_Container.CallingForm := Self;
Form_Container.ContainedClass := 'group';
Form_Container.Description := Format(msgTemplate, ['создана группа']);
Form_Container.DomainController := FDomainController;
Form_Container.DefaultPath := Edit_Container.Text;
Form_Container.OnContainerSelect := OnTargetContainerSelect;
Form_Container.Position := poMainFormCenter;
Form_Container.Show;
Self.Enabled := False;
end;
procedure TForm_CreateGroup.ClearTextFields;
var
i: Integer;
Ctrl: TControl;
begin
for i := 0 to Self.ControlCount - 1 do
begin
Ctrl := Self.Controls[i];
if Ctrl is TEdit then TEdit(Ctrl).Clear else
if Ctrl is TCheckBox then TCheckBox(Ctrl).Checked := False else
if Ctrl is TMemo then TMemo(Ctrl).Clear
end;
RadioButton_Global.Checked := True;
RadioButton_Security.Checked := True;
end;
procedure TForm_CreateGroup.Edit_GroupNameChange(Sender: TObject);
begin
if Length(Edit_GroupName.Text) <= Edit_GroupNamePre2k.MaxLength
then Edit_GroupNamePre2k.Text := Edit_GroupName.Text
else Edit_GroupNamePre2k.Text := Copy(Edit_GroupName.Text, 1, Edit_GroupNamePre2k.MaxLength);
end;
procedure TForm_CreateGroup.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
ClearTextFields;
FDomainController := nil;
FContainer.Clear;
FOnGroupCreate := nil;
if FCallingForm <> nil then
begin
FCallingForm.Enabled := True;
FCallingForm.Show;
FCallingForm := nil;
end;
end;
procedure TForm_CreateGroup.OnTargetContainerSelect(Sender: TObject;
ACont: TADContainer);
begin
SetContainer(ACont);
if Sender <> nil
then if Sender is TForm
then TForm(Sender).Close;
end;
procedure TForm_CreateGroup.SetCallingForm(const Value: TForm);
begin
FCallingForm := Value;
end;
procedure TForm_CreateGroup.SetContainer(const Value: TADContainer);
begin
FContainer := Value;
Edit_Container.Text := FContainer.Path;
end;
procedure TForm_CreateGroup.SetDomainController(const Value: TDCInfo);
begin
FDomainController := Value;
if FDomainController <> nil then
begin
// Edit_DomainDNSName.Text := '@' + FDomainController.DomainDnsName;
// Edit_DomainNetBIOSName.Text := FDomainController.DomainNetbiosName + '\';
end;
end;
end.
|
unit ModHashTableChaining;
interface
function addOrInc(w : string) : integer;
function find(w : string) : integer;
procedure writeTable;
procedure init;
implementation
uses ModStringHash;
const
M = 53;
type
NodePtr = ^NodeRec;
NodeRec = record
key : string;
val : integer;
next : NodePtr;
end;
ListPtr = NodePtr;
var
table : array[0..M-1] of ListPtr;
function addOrInc(w : string) : integer;
var h : integer;
n : NodePtr;
begin
h := stringHash1(w) mod M;
n := table[h];
while (n <> NIL) and (n^.key <> w) do
n := n^.next;
if n = NIL then begin
New(n);
n^.key := w;
n^.val := 1;
n^.next := table[h];
table[h] := n;
end else
inc(n^.val);
addOrInc := n^.val;
end;
function find(w : string) : integer;
var h : integer;
n : NodePtr;
begin
h := stringHash1(w) mod M;
n := table[h];
while (n <> NIL) and (n^.key <> w) do
n := n^.next;
if n = NIL then
find := 0
else
find := n^.val;
end;
procedure init;
var
i : integer;
begin
(* TODO: if entries exist we need to dispose them*)
for i := 0 to M-1 do begin
table[i] := NIL;
end;
end;
procedure writeList(n : ListPtr);
Begin
if n = NIL then
Write(' -| ')
else begin
write('-> ', n^.key, ',', n^.val);
writeList(n^.next);
end;
end;
procedure writeTable;
var i : integer;
begin
for i := 1 to M -1 do begin
WriteList(table[i]);
WriteLn;
end;
end;
begin
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.42 3/14/05 11:45:50 AM RLebeau
Buf fix for DoExecute() not not filling in the TIdHTTPRequestInfo.FormParams
correctly.
Removed LImplicitPostStream variable from DoExecute(), no longer used.
TIdHTTPRequestInfo takes ownership of the PostStream anyway, so no need to
free it early. This also allows the PostStream to always be available in the
OnCommand... event handlers.
Rev 1.41 2/9/05 2:11:02 AM RLebeau
Removed compiler hint
Rev 1.40 2/9/05 1:19:26 AM RLebeau
Fixes for Compiler errors
Rev 1.39 2/8/05 6:47:46 PM RLebeau
updated OnCommandOther to have ARequestInfo and AResponseInfo parameters
Rev 1.38 12/16/04 2:15:20 AM RLebeau
Another DoExecute() update
Rev 1.37 12/15/04 9:03:50 PM RLebeau
Renamed TIdHTTPRequestInfo.DecodeCommand() to DecodeHTTPCommand() and made it
into a standalone function.
Rev 1.36 12/15/04 4:17:42 PM RLebeau
Updated DoExecute() to call LRequestInfo.DecodeCommand()
Rev 1.35 12/2/2004 4:23:48 PM JPMugaas
Adjusted for changes in Core.
Rev 1.34 10/26/2004 8:59:32 PM JPMugaas
Updated with new TStrings references for more portability.
Rev 1.33 2004.05.20 11:37:12 AM czhower
IdStreamVCL
Rev 1.32 5/6/04 3:19:00 PM RLebeau
Added extra comments
Rev 1.31 2004.04.18 12:52:06 AM czhower
Big bug fix with server disconnect and several other bug fixed that I found
along the way.
Rev 1.30 2004.04.08 1:46:32 AM czhower
Small Optimizations
Rev 1.29 7/4/2004 4:10:44 PM SGrobety
Small fix to keep it synched with the IOHandler properties
Rev 1.28 6/4/2004 5:15:02 PM SGrobety
Implemented MaximumHeaderLineCount property (default to 1024)
Rev 1.27 2004.02.03 5:45:02 PM czhower
Name changes
Rev 1.26 1/27/2004 3:58:52 PM SPerry
StringStream ->IdStringStream
Rev 1.25 2004.01.22 5:58:58 PM czhower
IdCriticalSection
Rev 1.24 1/22/2004 8:26:28 AM JPMugaas
Ansi* calls changed.
Rev 1.23 1/21/2004 1:57:30 PM JPMugaas
InitComponent
Rev 1.22 21.1.2004 ã. 13:22:18 DBondzhev
Fix for Dccil bug
Rev 1.21 10/25/2003 06:51:44 AM JPMugaas
Updated for new API changes and tried to restore some functionality.
Rev 1.20 2003.10.24 10:43:02 AM czhower
TIdSTream to dos
Rev 1.19 10/19/2003 11:49:40 AM DSiders
Added localization comments.
Rev 1.18 10/17/2003 12:05:40 AM DSiders
Corrected spelling error in resource string.
Rev 1.17 10/15/2003 11:10:16 PM GGrieve
DotNet changes
Rev 1.16 2003.10.12 3:37:58 PM czhower
Now compiles again.
Rev 1.15 6/24/2003 11:38:50 AM BGooijen
Fixed ssl support
Rev 1.14 6/18/2003 11:44:04 PM BGooijen
Moved ServeFile and SmartServeFile to TIdHTTPResponseInfo.
Added TIdHTTPResponseInfo.HTTPServer field
Rev 1.13 05.6.2003 ã. 11:11:12 DBondzhev
Socket exceptions should not be stopped after DoCommandGet.
Rev 1.12 4/9/2003 9:38:40 PM BGooijen
fixed av on FSessionList.PurgeStaleSessions(Terminated);
Rev 1.11 20/3/2003 19:49:24 GGrieve
Define SmartServeFile
Rev 1.10 3/13/2003 10:21:14 AM BGooijen
Changed result of function .execute
Rev 1.9 2/25/2003 10:43:36 AM BGooijen
removed unneeded assignment
Rev 1.8 2/25/2003 10:38:46 AM BGooijen
The Serversoftware wasn't send to the client, because of duplicate properties
(.Server and .ServerSoftware).
Rev 1.7 2/24/2003 08:20:50 PM JPMugaas
Now should compile with new code.
Rev 1.6 11.2.2003 13:36:14 TPrami
- Fixed URL get paremeter handling (SeeRFC 1866 section 8.2.1.)
Rev 1.5 1/17/2003 05:35:20 PM JPMugaas
Now compiles with new design.
Rev 1.4 1-1-2003 20:12:44 BGooijen
Changed to support the new TIdContext class
Rev 1.3 12-15-2002 13:08:38 BGooijen
simplified TimeStampInterval
Rev 1.2 6/12/2002 10:59:34 AM SGrobety Version: 1.1
Made to work with Indy 10
Rev 1.0 21/11/2002 12:41:04 PM SGrobety Version: Indy 10
Rev 1.0 11/14/2002 02:16:32 PM JPMugaas
}
unit IdCustomHTTPServer;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdAssignedNumbers,
IdContext, IdException,
IdGlobal, IdStack,
IdExceptionCore, IdGlobalProtocols, IdHeaderList, IdCustomTCPServer,
IdTCPConnection, IdThread, IdCookie, IdHTTPHeaderInfo, IdStackConsts,
IdBaseComponent, IdThreadSafe,
SysUtils;
type
// Enums
THTTPCommandType = (hcUnknown, hcHEAD, hcGET, hcPOST, hcDELETE, hcPUT, hcTRACE, hcOPTION);
const
Id_TId_HTTPServer_KeepAlive = false;
Id_TId_HTTPServer_ParseParams = True;
Id_TId_HTTPServer_SessionState = False;
Id_TId_HTTPSessionTimeOut = 0;
Id_TId_HTTPAutoStartSession = False;
Id_TId_HTTPMaximumHeaderLineCount = 1024;
GResponseNo = 200;
GFContentLength = -1;
GServerSoftware = gsIdProductName + '/' + gsIdVersion; {Do not Localize}
GContentType = 'text/html'; {Do not Localize}
GSessionIDCookie = 'IDHTTPSESSIONID'; {Do not Localize}
HTTPRequestStrings: array[0..Ord(High(THTTPCommandType))] of string = ('UNKNOWN', 'HEAD','GET','POST','DELETE','PUT','TRACE', 'OPTIONS'); {do not localize}
type
// Forwards
TIdHTTPSession = class;
TIdHTTPCustomSessionList = class;
TIdHTTPRequestInfo = class;
TIdHTTPResponseInfo = class;
TIdCustomHTTPServer = class;
//events
TIdHTTPSessionEndEvent = procedure(Sender: TIdHTTPSession) of object;
TIdHTTPSessionStartEvent = procedure(Sender: TIdHTTPSession) of object;
TIdHTTPCreateSession = procedure(ASender:TIdContext;
var VHTTPSession: TIdHTTPSession) of object;
TIdHTTPCreatePostStream = procedure(AContext: TIdContext; AHeaders: TIdHeaderList; var VPostStream: TStream) of object;
TIdHTTPDoneWithPostStream = procedure(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; var VCanFree: Boolean) of object;
TIdHTTPParseAuthenticationEvent = procedure(AContext: TIdContext; const AAuthType, AAuthData: String; var VUsername, VPassword: String; var VHandled: Boolean) of object;
TIdHTTPCommandEvent = procedure(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo) of object;
TIdHTTPCommandError = procedure(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo;
AException: Exception) of object;
TIdHTTPInvalidSessionEvent = procedure(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo;
var VContinueProcessing: Boolean; const AInvalidSessionID: String) of object;
TIdHTTPHeadersAvailableEvent = procedure(AContext: TIdContext; const AUri: string; AHeaders: TIdHeaderList; var VContinueProcessing: Boolean) of object;
TIdHTTPHeadersBlockedEvent = procedure(AContext: TIdContext; AHeaders: TIdHeaderList; var VResponseNo: Integer; var VResponseText, VContentText: String) of object;
TIdHTTPHeaderExpectationsEvent = procedure(AContext: TIdContext; const AExpectations: String; var VContinueProcessing: Boolean) of object;
TIdHTTPQuerySSLPortEvent = procedure(APort: TIdPort; var VUseSSL: Boolean) of object;
//objects
EIdHTTPServerError = class(EIdException);
EIdHTTPHeaderAlreadyWritten = class(EIdHTTPServerError);
EIdHTTPErrorParsingCommand = class(EIdHTTPServerError);
EIdHTTPUnsupportedAuthorisationScheme = class(EIdHTTPServerError);
EIdHTTPCannotSwitchSessionStateWhenActive = class(EIdHTTPServerError);
TIdHTTPRequestInfo = class(TIdRequestHeaderInfo)
protected
FAuthExists: Boolean;
FCookies: TIdCookies;
FParams: TStrings;
FPostStream: TStream;
FRawHTTPCommand: string;
FRemoteIP: string;
FSession: TIdHTTPSession;
FDocument: string;
FURI: string;
FCommand: string;
FVersion: string;
FVersionMajor: Integer;
FVersionMinor: Integer;
FAuthUsername: string;
FAuthPassword: string;
FUnparsedParams: string;
FQueryParams: string;
FFormParams: string;
FCommandType: THTTPCommandType;
//
procedure DecodeAndSetParams(const AValue: String); virtual;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
//
function IsVersionAtLeast(const AMajor, AMinor: Integer): Boolean;
property Session: TIdHTTPSession read FSession;
//
property AuthExists: Boolean read FAuthExists;
property AuthPassword: string read FAuthPassword;
property AuthUsername: string read FAuthUsername;
property Command: string read FCommand;
property CommandType: THTTPCommandType read FCommandType;
property Cookies: TIdCookies read FCookies;
property Document: string read FDocument write FDocument; // writable for isapi compatibility. Use with care
property URI: string read FURI;
property Params: TStrings read FParams;
property PostStream: TStream read FPostStream write FPostStream;
property RawHTTPCommand: string read FRawHTTPCommand;
property RemoteIP: String read FRemoteIP;
property UnparsedParams: string read FUnparsedParams write FUnparsedParams; // writable for isapi compatibility. Use with care
property FormParams: string read FFormParams write FFormParams; // writable for isapi compatibility. Use with care
property QueryParams: string read FQueryParams write FQueryParams; // writable for isapi compatibility. Use with care
property Version: string read FVersion;
property VersionMajor: Integer read FVersionMajor;
property VersionMinor: Integer read FVersionMinor;
end;
TIdHTTPResponseInfo = class(TIdResponseHeaderInfo)
protected
FAuthRealm: string;
FConnection: TIdTCPConnection;
FResponseNo: Integer;
FCookies: TIdCookies;
FContentStream: TStream;
FContentText: string;
FCloseConnection: Boolean;
FFreeContentStream: Boolean;
FHeaderHasBeenWritten: Boolean;
FResponseText: string;
FHTTPServer: TIdCustomHTTPServer;
FSession: TIdHTTPSession;
FRequestInfo: TIdHTTPRequestInfo;
//
procedure ReleaseContentStream;
procedure SetCookies(const AValue: TIdCookies);
procedure SetHeaders; override;
procedure SetResponseNo(const AValue: Integer);
procedure SetCloseConnection(const Value: Boolean);
public
function GetServer: string;
procedure SetServer(const Value: string);
public
procedure CloseSession;
constructor Create(AServer: TIdCustomHTTPServer; ARequestInfo: TIdHTTPRequestInfo; AConnection: TIdTCPConnection); reintroduce;
destructor Destroy; override;
procedure Redirect(const AURL: string);
procedure WriteHeader;
procedure WriteContent;
//
function ServeFile(AContext: TIdContext; const AFile: String): Int64; virtual;
function SmartServeFile(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; const AFile: String): Int64;
//
property AuthRealm: string read FAuthRealm write FAuthRealm;
property CloseConnection: Boolean read FCloseConnection write SetCloseConnection;
property ContentStream: TStream read FContentStream write FContentStream;
property ContentText: string read FContentText write FContentText;
property Cookies: TIdCookies read FCookies write SetCookies;
property FreeContentStream: Boolean read FFreeContentStream write FFreeContentStream;
// writable for isapi compatibility. Use with care
property HeaderHasBeenWritten: Boolean read FHeaderHasBeenWritten write FHeaderHasBeenWritten;
property ResponseNo: Integer read FResponseNo write SetResponseNo;
property ResponseText: String read FResponseText write FResponseText;
property HTTPServer: TIdCustomHTTPServer read FHTTPServer;
property ServerSoftware: string read GetServer write SetServer;
property Session: TIdHTTPSession read FSession;
end;
TIdHTTPSession = Class(TObject)
protected
FContent: TStrings;
FLastTimeStamp: TDateTime;
FLock: TIdCriticalSection;
FOwner: TIdHTTPCustomSessionList;
FSessionID: string;
FRemoteHost: string;
//
procedure SetContent(const Value: TStrings);
function IsSessionStale: boolean; virtual;
procedure DoSessionEnd; virtual;
public
constructor Create(AOwner: TIdHTTPCustomSessionList); virtual;
constructor CreateInitialized(AOwner: TIdHTTPCustomSessionList; const SessionID,
RemoteIP: string); virtual;
destructor Destroy; override;
procedure Lock;
procedure Unlock;
//
property Content: TStrings read FContent write SetContent;
property LastTimeStamp: TDateTime read FLastTimeStamp;
property RemoteHost: string read FRemoteHost;
property SessionID: String read FSessionID;
end;
TIdHTTPCustomSessionList = class(TIdBaseComponent)
private
FSessionTimeout: Integer;
FOnSessionEnd: TIdHTTPSessionEndEvent;
FOnSessionStart: TIdHTTPSessionStartEvent;
protected
// remove a session from the session list. Called by the session on "Free"
procedure RemoveSession(Session: TIdHTTPSession); virtual; abstract;
public
procedure Clear; virtual; abstract;
procedure PurgeStaleSessions(PurgeAll: Boolean = false); virtual; abstract;
function CreateUniqueSession(const RemoteIP: String): TIdHTTPSession; virtual; abstract;
function CreateSession(const RemoteIP, SessionID: String): TIdHTTPSession; virtual; abstract;
function GetSession(const SessionID, RemoteIP: string): TIdHTTPSession; virtual; abstract;
procedure Add(ASession: TIdHTTPSession); virtual; Abstract;
published
property SessionTimeout: Integer read FSessionTimeout write FSessionTimeout;
property OnSessionEnd: TIdHTTPSessionEndEvent read FOnSessionEnd write FOnSessionEnd;
property OnSessionStart: TIdHTTPSessionStartEvent read FOnSessionStart write FOnSessionStart;
end;
TIdThreadSafeMimeTable = class(TIdThreadSafe)
protected
FTable: TIdMimeTable;
function GetLoadTypesFromOS: Boolean;
procedure SetLoadTypesFromOS(AValue: Boolean);
function GetOnBuildCache: TNotifyEvent;
procedure SetOnBuildCache(AValue: TNotifyEvent);
public
constructor Create(const AutoFill: Boolean = True); reintroduce;
destructor Destroy; override;
procedure BuildCache;
procedure AddMimeType(const Ext, MIMEType: string; const ARaiseOnError: Boolean = True);
function GetFileMIMEType(const AFileName: string): string;
function GetDefaultFileExt(const MIMEType: string): string;
procedure LoadFromStrings(const AStrings: TStrings; const MimeSeparator: Char = '='); {Do not Localize}
procedure SaveToStrings(const AStrings: TStrings; const MimeSeparator: Char = '='); {Do not Localize}
function Lock: TIdMimeTable; reintroduce;
procedure Unlock; reintroduce;
//
property LoadTypesFromOS: Boolean read GetLoadTypesFromOS write SetLoadTypesFromOS;
property OnBuildCache: TNotifyEvent read GetOnBuildCache write SetOnBuildCache;
end;
TIdCustomHTTPServer = class(TIdCustomTCPServer)
protected
FAutoStartSession: Boolean;
FKeepAlive: Boolean;
FParseParams: Boolean;
FServerSoftware: string;
FMIMETable: TIdThreadSafeMimeTable;
FSessionList: TIdHTTPCustomSessionList;
FImplicitSessionList: Boolean;
FSessionState: Boolean;
FSessionTimeOut: Integer;
//
FOnCreatePostStream: TIdHTTPCreatePostStream;
FOnDoneWithPostStream: TIdHTTPDoneWithPostStream;
FOnCreateSession: TIdHTTPCreateSession;
FOnInvalidSession: TIdHTTPInvalidSessionEvent;
FOnParseAuthentication: TIdHTTPParseAuthenticationEvent;
FOnSessionEnd: TIdHTTPSessionEndEvent;
FOnSessionStart: TIdHTTPSessionStartEvent;
FOnCommandGet: TIdHTTPCommandEvent;
FOnCommandOther: TIdHTTPCommandEvent;
FOnCommandError: TIdHTTPCommandError;
FOnHeadersAvailable: TIdHTTPHeadersAvailableEvent;
FOnHeadersBlocked: TIdHTTPHeadersBlockedEvent;
FOnHeaderExpectations: TIdHTTPHeaderExpectationsEvent;
FOnQuerySSLPort: TIdHTTPQuerySSLPortEvent;
//
FSessionCleanupThread: TIdThread;
FMaximumHeaderLineCount: Integer;
//
procedure CreatePostStream(ASender: TIdContext; AHeaders: TIdHeaderList; var VPostStream: TStream); virtual;
procedure DoneWithPostStream(ASender: TIdContext; ARequestInfo: TIdHTTPRequestInfo); virtual;
procedure DoOnCreateSession(AContext: TIdContext; var VNewSession: TIdHTTPSession); virtual;
procedure DoInvalidSession(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo;
var VContinueProcessing: Boolean; const AInvalidSessionID: String); virtual;
procedure DoCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo); virtual;
procedure DoCommandOther(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo); virtual;
procedure DoCommandError(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo; AException: Exception); virtual;
procedure DoConnect(AContext: TIdContext); override;
function DoHeadersAvailable(ASender: TIdContext; const AUri: String; AHeaders: TIdHeaderList): Boolean; virtual;
procedure DoHeadersBlocked(ASender: TIdContext; AHeaders: TIdHeaderList; var VResponseNo: Integer; var VResponseText, VContentText: String); virtual;
function DoHeaderExpectations(ASender: TIdContext; const AExpectations: String): Boolean; virtual;
function DoParseAuthentication(ASender: TIdContext; const AAuthType, AAuthData: String; var VUsername, VPassword: String): Boolean;
function DoQuerySSLPort(APort: TIdPort): Boolean; virtual;
procedure DoSessionEnd(Sender: TIdHTTPSession); virtual;
procedure DoSessionStart(Sender: TIdHTTPSession); virtual;
//
function DoExecute(AContext:TIdContext): Boolean; override;
//
procedure Startup; override;
procedure Shutdown; override;
procedure SetSessionList(const AValue: TIdHTTPCustomSessionList);
procedure SetSessionState(const Value: Boolean);
function GetSessionFromCookie(AContext:TIdContext;
AHTTPrequest: TIdHTTPRequestInfo; AHTTPResponse: TIdHTTPResponseInfo;
var VContinueProcessing: Boolean): TIdHTTPSession;
procedure InitComponent; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
{ to be published in TIdHTTPServer}
property OnCreatePostStream: TIdHTTPCreatePostStream read FOnCreatePostStream write FOnCreatePostStream;
property OnDoneWithPostStream: TIdHTTPDoneWithPostStream read FOnDoneWithPostStream write FOnDoneWithPostStream;
property OnCommandGet: TIdHTTPCommandEvent read FOnCommandGet write FOnCommandGet;
public
function CreateSession(AContext:TIdContext;
HTTPResponse: TIdHTTPResponseInfo;
HTTPRequest: TIdHTTPRequestInfo): TIdHTTPSession;
destructor Destroy; override;
function EndSession(const SessionName: String; const RemoteIP: String = ''): Boolean;
//
property MIMETable: TIdThreadSafeMimeTable read FMIMETable;
property SessionList: TIdHTTPCustomSessionList read FSessionList write SetSessionList;
published
property AutoStartSession: boolean read FAutoStartSession write FAutoStartSession default Id_TId_HTTPAutoStartSession;
property DefaultPort default IdPORT_HTTP;
property KeepAlive: Boolean read FKeepAlive write FKeepAlive default Id_TId_HTTPServer_KeepAlive;
property MaximumHeaderLineCount: Integer read FMaximumHeaderLineCount write FMaximumHeaderLineCount default Id_TId_HTTPMaximumHeaderLineCount;
property ParseParams: boolean read FParseParams write FParseParams default Id_TId_HTTPServer_ParseParams;
property ServerSoftware: string read FServerSoftware write FServerSoftware;
property SessionState: Boolean read FSessionState write SetSessionState default Id_TId_HTTPServer_SessionState;
property SessionTimeOut: Integer read FSessionTimeOut write FSessionTimeOut default Id_TId_HTTPSessionTimeOut;
//
property OnCommandError: TIdHTTPCommandError read FOnCommandError write FOnCommandError;
property OnCommandOther: TIdHTTPCommandEvent read FOnCommandOther write FOnCommandOther;
property OnCreateSession: TIdHTTPCreateSession read FOnCreateSession write FOnCreateSession;
property OnInvalidSession: TIdHTTPInvalidSessionEvent read FOnInvalidSession write FOnInvalidSession;
property OnHeadersAvailable: TIdHTTPHeadersAvailableEvent read FOnHeadersAvailable write FOnHeadersAvailable;
property OnHeadersBlocked: TIdHTTPHeadersBlockedEvent read FOnHeadersBlocked write FOnHeadersBlocked;
property OnHeaderExpectations: TIdHTTPHeaderExpectationsEvent read FOnHeaderExpectations write FOnHeaderExpectations;
property OnParseAuthentication: TIdHTTPParseAuthenticationEvent read FOnParseAuthentication write FOnParseAuthentication;
property OnQuerySSLPort: TIdHTTPQuerySSLPortEvent read FOnQuerySSLPort write FOnQuerySSLPort;
property OnSessionStart: TIdHTTPSessionStartEvent read FOnSessionStart write FOnSessionStart;
property OnSessionEnd: TIdHTTPSessionEndEvent read FOnSessionEnd write FOnSessionEnd;
end;
TIdHTTPDefaultSessionList = Class(TIdHTTPCustomSessionList)
protected
FSessionList: TThreadList;
procedure RemoveSession(Session: TIdHTTPSession); override;
// remove a session surgically when list already locked down (prevent deadlock)
procedure RemoveSessionFromLockedList(AIndex: Integer; ALockedSessionList: TList);
protected
procedure InitComponent; override;
public
destructor Destroy; override;
property SessionList: TThreadList read FSessionList;
procedure Clear; override;
procedure Add(ASession: TIdHTTPSession); override;
procedure PurgeStaleSessions(PurgeAll: Boolean = false); override;
function CreateUniqueSession(const RemoteIP: String): TIdHTTPSession; override;
function CreateSession(const RemoteIP, SessionID: String): TIdHTTPSession; override;
function GetSession(const SessionID, RemoteIP: string): TIdHTTPSession; override;
end;
TIdHTTPRangeStream = class(TIdBaseStream)
private
FSourceStream: TStream;
FOwnsSource: Boolean;
FRangeStart, FRangeEnd: Int64;
FResponseCode: Integer;
protected
function IdRead(var VBuffer: TIdBytes; AOffset, ACount: Longint): Longint; override;
function IdWrite(const ABuffer: TIdBytes; AOffset, ACount: Longint): Longint; override;
function IdSeek(const AOffset: Int64; AOrigin: TSeekOrigin): Int64; override;
procedure IdSetSize(ASize: Int64); override;
public
constructor Create(ASource: TStream; ARangeStart, ARangeEnd: Int64; AOwnsSource: Boolean = True);
destructor Destroy; override;
property ResponseCode: Integer read FResponseCode;
property RangeStart: Int64 read FRangeStart;
property RangeEnd: Int64 read FRangeEnd;
property SourceStream: TStream read FSourceStream;
end;
implementation
uses
{$IFDEF VCL_XE3_OR_ABOVE}
System.SyncObjs,
{$ENDIF}
{$IFDEF KYLIXCOMPAT}
Libc,
{$ENDIF}
{$IFDEF USE_VCL_POSIX}
Posix.SysSelect,
Posix.SysTime,
{$ENDIF}
{$IFDEF DOTNET}
{$IFDEF USE_INLINE}
System.IO,
System.Threading,
{$ENDIF}
{$IFDEF WINDOWS}
Windows,
{$ENDIF}
{$ENDIF}
{$IFDEF VCL_2010_OR_ABOVE}
{$IFDEF WINDOWS}
Windows,
{$ENDIF}
{$ENDIF}
IdCoderMIME, IdResourceStringsProtocols, IdURI, IdIOHandler, IdIOHandlerSocket,
IdSSL, IdResourceStringsCore, IdStream;
const
SessionCapacity = 128;
ContentTypeFormUrlencoded = 'application/x-www-form-urlencoded'; {Do not Localize}
// Calculate the number of MS between two TimeStamps
function TimeStampInterval(const AStartStamp, AEndStamp: TDateTime): integer;
begin
Result := Trunc((AEndStamp - AStartStamp) * MSecsPerDay);
end;
{ //(Bas Gooijen) was:
function TimeStampInterval(StartStamp, EndStamp: TDateTime): integer;
var
days: Integer;
hour, min, s, ms: Word;
begin
days := Trunc(EndStamp - StartStamp); // whole days
DecodeTime(EndStamp - StartStamp, hour, min, s, ms);
Result := (((days * 24 + hour) * 60 + min) * 60 + s) * 1000 + ms;
end;
}
function GetRandomString(NumChar: Cardinal): string;
const
CharMap = 'qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM1234567890'; {Do not Localize}
MaxChar: Cardinal = Length(CharMap) - 1;
var
i: integer;
begin
randomize;
SetLength(Result, NumChar);
for i := 1 to NumChar do
begin
// Add one because CharMap is 1-based
Result[i] := CharMap[Random(MaxChar) + 1];
end;
end;
function DecodeHTTPCommand(const ACmd: string): THTTPCommandType;
var
I: Integer;
begin
Result := hcUnknown;
for I := Low(HTTPRequestStrings) to High(HTTPRequestStrings) do begin
if TextIsSame(ACmd, HTTPRequestStrings[i]) then begin
Result := THTTPCommandType(i);
Exit;
end;
end; // for
end;
type
TIdHTTPSessionCleanerThread = Class(TIdThread)
protected
FSessionList: TIdHTTPCustomSessionList;
public
constructor Create(SessionList: TIdHTTPCustomSessionList); reintroduce;
procedure AfterRun; override;
procedure Run; override;
end; // class
function InternalReadLn(AIOHandler: TIdIOHandler): String;
begin
Result := AIOHandler.ReadLn;
if AIOHandler.ReadLnTimedout then begin
raise EIdReadTimeout.Create(RSReadTimeout);
end;
end;
{ TIdThreadSafeMimeTable }
constructor TIdThreadSafeMimeTable.Create(const AutoFill: Boolean = True);
begin
inherited Create;
FTable := TIdMimeTable.Create(AutoFill);
end;
destructor TIdThreadSafeMimeTable.Destroy;
begin
inherited Lock; try
FreeAndNil(FTable);
finally inherited Unlock; end;
inherited Destroy;
end;
function TIdThreadSafeMimeTable.GetLoadTypesFromOS: Boolean;
begin
with Lock do try
Result := LoadTypesFromOS;
finally Unlock; end;
end;
procedure TIdThreadSafeMimeTable.SetLoadTypesFromOS(AValue: Boolean);
begin
with Lock do try
LoadTypesFromOS := AValue;
finally Unlock; end;
end;
function TIdThreadSafeMimeTable.GetOnBuildCache: TNotifyEvent;
begin
with Lock do try
Result := OnBuildCache;
finally Unlock; end;
end;
procedure TIdThreadSafeMimeTable.SetOnBuildCache(AValue: TNotifyEvent);
begin
with Lock do try
OnBuildCache := AValue;
finally Unlock; end;
end;
procedure TIdThreadSafeMimeTable.BuildCache;
begin
with Lock do try
BuildCache;
finally Unlock; end;
end;
procedure TIdThreadSafeMimeTable.AddMimeType(const Ext, MIMEType: string; const ARaiseOnError: Boolean = True);
begin
with Lock do try
AddMimeType(Ext, MIMEType, ARaiseOnError);
finally Unlock; end;
end;
function TIdThreadSafeMimeTable.GetFileMIMEType(const AFileName: string): string;
begin
with Lock do try
Result := GetFileMIMEType(AFileName);
finally Unlock; end;
end;
function TIdThreadSafeMimeTable.GetDefaultFileExt(const MIMEType: string): string;
begin
with Lock do try
Result := GetDefaultFileExt(MIMEType);
finally Unlock; end;
end;
procedure TIdThreadSafeMimeTable.LoadFromStrings(const AStrings: TStrings; const MimeSeparator: Char = '='); {Do not Localize}
begin
with Lock do try
LoadFromStrings(AStrings, MimeSeparator);
finally Unlock; end;
end;
procedure TIdThreadSafeMimeTable.SaveToStrings(const AStrings: TStrings; const MimeSeparator: Char = '='); {Do not Localize}
begin
with Lock do try
SaveToStrings(AStrings, MimeSeparator);
finally Unlock; end;
end;
function TIdThreadSafeMimeTable.Lock: TIdMimeTable;
begin
inherited Lock;
Result := FTable;
end;
procedure TIdThreadSafeMimeTable.Unlock;
begin
inherited Unlock;
end;
{ TIdHTTPRangeStream }
constructor TIdHTTPRangeStream.Create(ASource: TStream; ARangeStart, ARangeEnd: Int64;
AOwnsSource: Boolean = True);
var
LSize: Int64;
begin
inherited Create;
FSourceStream := ASource;
FOwnsSource := AOwnsSource;
FResponseCode := 200;
if (ARangeStart > -1) or (ARangeEnd > -1) then begin
LSize := ASource.Size;
if ARangeStart > -1 then begin
// requesting prefix range from BOF
if ARangeStart >= LSize then begin
// range unsatisfiable
FResponseCode := 416;
Exit;
end;
if ARangeEnd > -1 then begin
if ARangeEnd < ARangeStart then begin
// invalid syntax
Exit;
end;
ARangeEnd := IndyMin(ARangeEnd, LSize-1);
end else begin
ARangeEnd := LSize-1;
end;
end else begin
// requesting suffix range from EOF
if ARangeEnd = 0 then begin
// range unsatisfiable
FResponseCode := 416;
Exit;
end;
ARangeStart := IndyMax(LSize - ARangeEnd, 0);
ARangeEnd := LSize-1;
end;
FResponseCode := 206;
FRangeStart := ARangeStart;
FRangeEnd := ARangeEnd;
end;
end;
destructor TIdHTTPRangeStream.Destroy;
begin
if FOwnsSource then begin
FSourceStream.Free;
end;
inherited Destroy;
end;
function TIdHTTPRangeStream.IdRead(var VBuffer: TIdBytes; AOffset, ACount: Longint): Longint;
begin
if FResponseCode = 206 then begin
ACount := Longint(IndyMin(Int64(ACount), (FRangeEnd+1) - FSourceStream.Position));
end;
Result := TIdStreamHelper.ReadBytes(FSourceStream, VBuffer, ACount, AOffset);
end;
function TIdHTTPRangeStream.IdSeek(const AOffset: Int64; AOrigin: TSeekOrigin): Int64;
var
LOffset: Int64;
begin
if FResponseCode = 206 then begin
case AOrigin of
soBeginning: LOffset := FRangeStart + AOffset;
soCurrent: LOffset := FSourceStream.Position + AOffset;
soEnd: LOffset := (FRangeEnd+1) + AOffset;
else
// TODO: move this into IdResourceStringsProtocols.pas
raise EIdException.Create('Unknown Seek Origin'); {do not localize}
end;
LOffset := IndyMax(LOffset, FRangeStart);
LOffset := IndyMin(LOffset, FRangeEnd+1);
Result := TIdStreamHelper.Seek(FSourceStream, LOffset, soBeginning) - FRangeStart;
end else begin
Result := TIdStreamHelper.Seek(FSourceStream, AOffset, AOrigin);
end;
end;
function TIdHTTPRangeStream.IdWrite(const ABuffer: TIdBytes; AOffset, ACount: Longint): Longint;
begin
Result := 0;
end;
procedure TIdHTTPRangeStream.IdSetSize(ASize: Int64);
begin
end;
{ TIdCustomHTTPServer }
procedure TIdCustomHTTPServer.InitComponent;
begin
inherited InitComponent;
FSessionState := Id_TId_HTTPServer_SessionState;
DefaultPort := IdPORT_HTTP;
ParseParams := Id_TId_HTTPServer_ParseParams;
FMIMETable := TIdThreadSafeMimeTable.Create(False);
FSessionTimeOut := Id_TId_HTTPSessionTimeOut;
FAutoStartSession := Id_TId_HTTPAutoStartSession;
FKeepAlive := Id_TId_HTTPServer_KeepAlive;
FMaximumHeaderLineCount := Id_TId_HTTPMaximumHeaderLineCount;
end;
procedure TIdCustomHTTPServer.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FSessionList) then begin
FSessionList := nil;
FImplicitSessionList := False;
end;
end;
function TIdCustomHTTPServer.DoParseAuthentication(ASender: TIdContext;
const AAuthType, AAuthData: String; var VUsername, VPassword: String): Boolean;
var
s: String;
begin
Result := False;
if Assigned(FOnParseAuthentication) then begin
FOnParseAuthentication(ASender, AAuthType, AAuthData, VUsername, VPassword, Result);
end;
if (not Result) and TextIsSame(AAuthType, 'Basic') then begin {Do not Localize}
with TIdDecoderMIME.Create do try
s := DecodeString(AAuthData);
finally Free; end;
VUsername := Fetch(s, ':'); {Do not Localize}
VPassword := s;
Result := True;
end;
end;
procedure TIdCustomHTTPServer.DoOnCreateSession(AContext: TIdContext; Var VNewSession: TIdHTTPSession);
begin
VNewSession := nil;
if Assigned(FOnCreateSession) then
begin
OnCreateSession(AContext, VNewSession);
end;
end;
function TIdCustomHTTPServer.CreateSession(AContext: TIdContext; HTTPResponse: TIdHTTPResponseInfo;
HTTPRequest: TIdHTTPRequestInfo): TIdHTTPSession;
begin
if SessionState then begin
DoOnCreateSession(AContext, Result);
if not Assigned(Result) then begin
Result := FSessionList.CreateUniqueSession(HTTPRequest.RemoteIP);
end else begin
FSessionList.Add(Result);
end;
with HTTPResponse.Cookies.Add do
begin
CookieName := GSessionIDCookie;
Value := Result.SessionID;
Path := '/'; {Do not Localize}
// By default the cookie will be valid until the user has closed his browser window.
// MaxAge := SessionTimeOut div 1000;
end;
HTTPResponse.FSession := Result;
HTTPRequest.FSession := Result;
end else begin
Result := nil;
end;
end;
destructor TIdCustomHTTPServer.Destroy;
begin
Active := False; // Set Active to false in order to close all active sessions.
FreeAndNil(FMIMETable);
FreeAndNil(FSessionList); // RLebeau: remove this? It frees the USER'S component if still assigned...
inherited Destroy;
end;
procedure TIdCustomHTTPServer.DoCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
if Assigned(FOnCommandGet) then begin
FOnCommandGet(AContext, ARequestInfo, AResponseInfo);
end;
end;
procedure TIdCustomHTTPServer.DoCommandOther(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
if Assigned(FOnCommandOther) then begin
FOnCommandOther(AContext, ARequestInfo, AResponseInfo);
end;
end;
procedure TIdCustomHTTPServer.DoCommandError(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo;
AException: Exception);
begin
if Assigned(FOnCommandError) then begin
FOnCommandError(AContext, ARequestInfo, AResponseInfo, AException);
end;
end;
procedure TIdCustomHTTPServer.DoConnect(AContext: TIdContext);
begin
// RLebeau 6/17/08: let the user decide whether to enable SSL in their
// own event handler. Indy should not be making any assumptions about
// whether to implicitally force SSL on any given connection. This
// prevents a single server from handling both SSL and non-SSL connections
// together. The whole point of the PassThrough property is to allow
// per-connection SSL handling.
//
// TODO: move this new logic into TIdCustomTCPServer directly somehow
if AContext.Connection.IOHandler is TIdSSLIOHandlerSocketBase then begin
TIdSSLIOHandlerSocketBase(AContext.Connection.IOHandler).PassThrough :=
not DoQuerySSLPort(AContext.Connection.Socket.Binding.Port);
end;
inherited DoConnect(AContext);
end;
function TIdCustomHTTPServer.DoQuerySSLPort(APort: TIdPort): Boolean;
begin
Result := not Assigned(FOnQuerySSLPort);
if not Result then begin
FOnQuerySSLPort(APort, Result);
end;
end;
function TIdCustomHTTPServer.DoHeadersAvailable(ASender: TIdContext; const AUri: String;
AHeaders: TIdHeaderList): Boolean;
begin
Result := True;
if Assigned(OnHeadersAvailable) then begin
OnHeadersAvailable(ASender, AUri, AHeaders, Result);
end;
end;
procedure TIdCustomHTTPServer.DoHeadersBlocked(ASender: TIdContext; AHeaders: TIdHeaderList;
var VResponseNo: Integer; var VResponseText, VContentText: String);
begin
VResponseNo := 403;
VResponseText := '';
VContentText := '';
if Assigned(OnHeadersBlocked) then begin
OnHeadersBlocked(ASender, AHeaders, VResponseNo, VResponseText, VContentText);
end;
end;
function TIdCustomHTTPServer.DoHeaderExpectations(ASender: TIdContext; const AExpectations: String): Boolean;
begin
Result := TextIsSame(AExpectations, '100-continue'); {Do not Localize}
if Assigned(OnHeaderExpectations) then begin
OnHeaderExpectations(ASender, AExpectations, Result);
end;
end;
function TIdCustomHTTPServer.DoExecute(AContext:TIdContext): boolean;
var
LRequestInfo: TIdHTTPRequestInfo;
LResponseInfo: TIdHTTPResponseInfo;
procedure ReadCookiesFromRequestHeader;
var
LRawCookies: TStringList;
begin
LRawCookies := TStringList.Create;
try
LRequestInfo.RawHeaders.Extract('Cookie', LRawCookies); {Do not Localize}
LRequestInfo.Cookies.AddClientCookies(LRawCookies);
finally
FreeAndNil(LRawCookies);
end;
end;
function GetRemoteIP(ASocket: TIdIOHandlerSocket): String;
begin
Result := '';
if ASocket <> nil then begin
if ASocket.Binding <> nil then begin
Result := ASocket.Binding.PeerIP;
end;
end;
end;
function HeadersCanContinue: Boolean;
var
LResponseNo: Integer;
LResponseText, LContentText, S: String;
begin
// let the user decide if the request headers are acceptable
Result := DoHeadersAvailable(AContext, LRequestInfo.URI, LRequestInfo.RawHeaders);
if not Result then begin
DoHeadersBlocked(AContext, LRequestInfo.RawHeaders, LResponseNo, LResponseText, LContentText);
LResponseInfo.ResponseNo := LResponseNo;
if Length(LResponseText) > 0 then begin
LResponseInfo.ResponseText := LResponseText;
end;
LResponseInfo.ContentText := LContentText;
LResponseInfo.CloseConnection := True;
LResponseInfo.WriteHeader;
if Length(LContentText) > 0 then begin
LResponseInfo.WriteContent;
end;
Exit;
end;
// check for HTTP v1.1 'Host' and 'Expect' headers...
if not LRequestInfo.IsVersionAtLeast(1, 1) then begin
Exit;
end;
// MUST report a 400 (Bad Request) error if an HTTP/1.1
// request does not include a 'Host' header
S := LRequestInfo.RawHeaders.Values['Host'];
if Length(S) = 0 then begin
LResponseInfo.ResponseNo := 400;
LResponseInfo.CloseConnection := True;
LResponseInfo.WriteHeader;
Exit;
end;
// if the client has already sent some or all of the request
// body then don't bother checking for a v1.1 'Expect' header
if not AContext.Connection.IOHandler.InputBufferIsEmpty then begin
Exit;
end;
S := LRequestInfo.RawHeaders.Values['Expect'];
if Length(S) = 0 then begin
Exit;
end;
// check if the client expectations can be satisfied...
Result := DoHeaderExpectations(AContext, S);
if not Result then begin
LResponseInfo.ResponseNo := 417;
LResponseInfo.CloseConnection := True;
LResponseInfo.WriteHeader;
Exit;
end;
if Pos('100-continue', LowerCase(S)) > 0 then begin {Do not Localize}
// the client requested a '100-continue' expectation so send
// a '100 Continue' reply now before the request body can be read
AContext.Connection.IOHandler.WriteLn(LRequestInfo.Version + ' 100 ' + RSHTTPContinue + EOL); {Do not Localize}
end;
end;
function PreparePostStream: Boolean;
var
I, Size: Integer;
S: String;
LIOHandler: TIdIOHandler;
begin
Result := False;
LIOHandler := AContext.Connection.IOHandler;
// RLebeau 1/6/2009: don't create the PostStream unless there is
// actually something to read. This should make it easier for the
// request handler to know when to use the PostStream and when to
// use the (Unparsed)Params instead...
if (LRequestInfo.TransferEncoding <> '') and
(not TextIsSame(LRequestInfo.TransferEncoding, 'identity')) then {do not localize}
begin
if IndyPos('chunked', LowerCase(LRequestInfo.TransferEncoding)) = 0 then begin {do not localize}
LResponseInfo.ResponseNo := 400; // bad request
LResponseInfo.CloseConnection := True;
LResponseInfo.WriteHeader;
Exit;
end;
CreatePostStream(AContext, LRequestInfo.RawHeaders, LRequestInfo.FPostStream);
if LRequestInfo.FPostStream = nil then begin
LRequestInfo.FPostStream := TMemoryStream.Create;
end;
LRequestInfo.PostStream.Position := 0;
repeat
S := InternalReadLn(LIOHandler);
I := IndyPos(';', S); {do not localize}
if I > 0 then begin
S := Copy(S, 1, I - 1);
end;
Size := IndyStrToInt('$' + Trim(S), 0); {do not localize}
if Size = 0 then begin
Break;
end;
LIOHandler.ReadStream(LRequestInfo.PostStream, Size);
InternalReadLn(LIOHandler); // CRLF at end of chunk data
until False;
// skip trailer headers
repeat until InternalReadLn(LIOHandler) = '';
LRequestInfo.PostStream.Position := 0;
end
else if LRequestInfo.HasContentLength then
begin
CreatePostStream(AContext, LRequestInfo.RawHeaders, LRequestInfo.FPostStream);
if LRequestInfo.FPostStream = nil then begin
LRequestInfo.FPostStream := TMemoryStream.Create;
end;
LRequestInfo.PostStream.Position := 0;
if LRequestInfo.ContentLength > 0 then begin
LIOHandler.ReadStream(LRequestInfo.PostStream, LRequestInfo.ContentLength);
LRequestInfo.PostStream.Position := 0;
end;
end
else begin
if LIOHandler.InputBufferIsEmpty then begin
LIOHandler.CheckForDataOnSource(1);
end;
if not LIOHandler.InputBufferIsEmpty then begin
LResponseInfo.ResponseNo := 411; // length required
LResponseInfo.CloseConnection := True;
LResponseInfo.WriteHeader;
Exit;
end;
end;
Result := True;
end;
var
i: integer;
s, LInputLine, LRawHTTPCommand, LCmd, LContentType, LAuthType: String;
LURI: TIdURI;
LContinueProcessing, LCloseConnection: Boolean;
begin
LContinueProcessing := True;
Result := False;
LCloseConnection := not KeepAlive;
try
try
repeat
with AContext.Connection do begin
LInputLine := InternalReadLn(IOHandler);
i := RPos(' ', LInputLine, -1); {Do not Localize}
if i = 0 then begin
raise EIdHTTPErrorParsingCommand.Create(RSHTTPErrorParsingCommand);
end;
LRequestInfo := TIdHTTPRequestInfo.Create(Self);
try
LResponseInfo := TIdHTTPResponseInfo.Create(Self, LRequestInfo, AContext.Connection);
try
// SG 05.07.99
// Set the ServerSoftware string to what it's supposed to be. {Do not Localize}
LResponseInfo.ServerSoftware := Trim(ServerSoftware);
// S.G. 6/4/2004: Set the maximum number of lines that will be catured
// S.G. 6/4/2004: to prevent a remote resource starvation DOS
IOHandler.MaxCapturedLines := MaximumHeaderLineCount;
// Retrieve the HTTP version
LRawHTTPCommand := LInputLine;
LRequestInfo.FVersion := Copy(LInputLine, i + 1, MaxInt);
s := LRequestInfo.Version;
Fetch(s, '/'); {Do not localize}
LRequestInfo.FVersionMajor := IndyStrToInt(Fetch(s, '.'), -1); {Do not Localize}
LRequestInfo.FVersionMinor := IndyStrToInt(S, -1);
SetLength(LInputLine, i - 1);
// Retrieve the HTTP header
LRequestInfo.RawHeaders.Clear;
IOHandler.Capture(LRequestInfo.RawHeaders, '', False); {Do not Localize}
LRequestInfo.ProcessHeaders;
// HTTP 1.1 connections are keep-alive by default
if not FKeepAlive then begin
LResponseInfo.CloseConnection := True;
end
else if LRequestInfo.IsVersionAtLeast(1, 1) then begin
LResponseInfo.CloseConnection := TextIsSame(LRequestInfo.Connection, 'close'); {Do not Localize}
end else begin
LResponseInfo.CloseConnection := not TextIsSame(LRequestInfo.Connection, 'keep-alive'); {Do not Localize}
end;
{TODO Check for 1.0 only at this point}
LCmd := UpperCase(Fetch(LInputLine, ' ')); {Do not Localize}
s := LRequestInfo.MethodOverride;
if s <> '' then begin
LCmd := UpperCase(s);
end;
LRequestInfo.FRawHTTPCommand := LRawHTTPCommand;
LRequestInfo.FRemoteIP := GetRemoteIP(Socket);
LRequestInfo.FCommand := LCmd;
LRequestInfo.FCommandType := DecodeHTTPCommand(LCmd);
// GET data - may exist with POSTs also
LRequestInfo.QueryParams := LInputLine;
LInputLine := Fetch(LRequestInfo.FQueryParams, '?'); {Do not Localize}
// Host
// the next line is done in TIdHTTPRequestInfo.ProcessHeaders()...
// LRequestInfo.FHost := LRequestInfo.Headers.Values['host']; {Do not Localize}
LRequestInfo.FURI := LInputLine;
// Parse the document input line
if LInputLine = '*' then begin {Do not Localize}
LRequestInfo.FDocument := '*'; {Do not Localize}
end else begin
LURI := TIdURI.Create(LInputLine);
try
// SG 29/11/01: Per request of Doychin
// Try to fill the "host" parameter
LRequestInfo.FDocument := TIdURI.URLDecode(LURI.Path) + TIdURI.URLDecode(LURI.Document);
if (Length(LURI.Host) > 0) and (Length(LRequestInfo.FHost) = 0) then begin
LRequestInfo.FHost := LURI.Host;
end;
finally
FreeAndNil(LURI);
end;
end;
// RLebeau 12/14/2005: provide the user with the headers and let the
// user decide whether the response processing should continue...
if not HeadersCanContinue then begin
Break;
end;
// retreive the base ContentType with attributes omitted
LContentType := ExtractHeaderItem(LRequestInfo.ContentType);
// Grab Params so we can parse them
// POSTed data - may exist with GETs also. With GETs, the action
// params from the form element will be posted
// TODO: Rune this is the area that needs fixed. Ive hacked it for now
// Get data can exists with POSTs, but can POST data exist with GETs?
// If only the first, the solution is easy. If both - need more
// investigation.
if not PreparePostStream then begin
Break;
end;
if LRequestInfo.PostStream <> nil then begin
if TextIsSame(LContentType, ContentTypeFormUrlencoded) then
begin
// decoding percent-encoded octets and applying the CharSet is handled by DecodeAndSetParams() further below...
LRequestInfo.FormParams := ReadStringFromStream(LRequestInfo.PostStream, -1, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF});
DoneWithPostStream(AContext, LRequestInfo); // don't need the PostStream anymore
end;
end;
// glue together parameters passed in the URL and those
//
// RLebeau: should we really be doing this? For a GET, it might
// makes sense to do, but for a POST the FormParams is the content
// and the QueryParams belongs to the URL only, not the content.
// We should be keeping everything separate for accuracy...
LRequestInfo.UnparsedParams := LRequestInfo.FormParams;
if Length(LRequestInfo.QueryParams) > 0 then begin
if Length(LRequestInfo.UnparsedParams) = 0 then begin
LRequestInfo.FUnparsedParams := LRequestInfo.QueryParams;
end else begin
LRequestInfo.FUnparsedParams := LRequestInfo.UnparsedParams + '&' {Do not Localize}
+ LRequestInfo.QueryParams;
end;
end;
// Parse Params
if ParseParams then begin
if TextIsSame(LContentType, ContentTypeFormUrlencoded) then begin
LRequestInfo.DecodeAndSetParams(LRequestInfo.UnparsedParams);
end else begin
// Parse only query params when content type is not 'application/x-www-form-urlencoded' {Do not Localize}
LRequestInfo.DecodeAndSetParams(LRequestInfo.QueryParams);
end;
end;
// Cookies
ReadCookiesFromRequestHeader;
// Authentication
s := LRequestInfo.RawHeaders.Values['Authorization']; {Do not Localize}
if Length(s) > 0 then begin
LAuthType := Fetch(s, ' ');
LRequestInfo.FAuthExists := DoParseAuthentication(AContext, LAuthType, s, LRequestInfo.FAuthUsername, LRequestInfo.FAuthPassword);
if not LRequestInfo.FAuthExists then begin
raise EIdHTTPUnsupportedAuthorisationScheme.Create(
RSHTTPUnsupportedAuthorisationScheme);
end;
end;
// Session management
GetSessionFromCookie(AContext, LRequestInfo, LResponseInfo, LContinueProcessing);
if LContinueProcessing then begin
try
// These essentially all "retrieve" so they are all "Get"s
if LRequestInfo.CommandType in [hcGET, hcPOST, hcHEAD] then begin
DoCommandGet(AContext, LRequestInfo, LResponseInfo);
end else begin
DoCommandOther(AContext, LRequestInfo, LResponseInfo);
end;
except
on E: EIdSocketError do begin // don't stop socket exceptions
raise;
end;
on E: Exception do begin
LResponseInfo.ResponseNo := 500;
LResponseInfo.ContentText := E.Message;
DoCommandError(AContext, LRequestInfo, LResponseInfo, E);
end;
end;
end;
// Write even though WriteContent will, may be a redirect or other
if not LResponseInfo.HeaderHasBeenWritten then begin
LResponseInfo.WriteHeader;
end;
// Always check ContentText first
if (Length(LResponseInfo.ContentText) > 0)
or Assigned(LResponseInfo.ContentStream) then begin
LResponseInfo.WriteContent;
end;
finally
LCloseConnection := LResponseInfo.CloseConnection;
FreeAndNil(LResponseInfo);
end;
finally
FreeAndNil(LRequestInfo);
end;
end;
until LCloseConnection;
except
on E: EIdSocketError do begin
if not ((E.LastError = Id_WSAESHUTDOWN) or (E.LastError = Id_WSAECONNABORTED) or (E.LastError = Id_WSAECONNRESET)) then begin
raise;
end;
end;
on E: EIdClosedSocket do begin
AContext.Connection.Disconnect;
end;
end;
finally
AContext.Connection.Disconnect(False);
end;
end;
procedure TIdCustomHTTPServer.DoInvalidSession(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo;
var VContinueProcessing: Boolean; const AInvalidSessionID: String);
begin
if Assigned(FOnInvalidSession) then begin
FOnInvalidSession(AContext, ARequestInfo, AResponseInfo, VContinueProcessing, AInvalidSessionID)
end;
end;
function TIdCustomHTTPServer.EndSession(const SessionName: String; const RemoteIP: String = ''): Boolean;
var
ASession: TIdHTTPSession;
begin
ASession := SessionList.GetSession(SessionName, RemoteIP); {Do not Localize}
Result := Assigned(ASession);
if Result then begin
FreeAndNil(ASession);
end;
end;
procedure TIdCustomHTTPServer.DoSessionEnd(Sender: TIdHTTPSession);
begin
if Assigned(FOnSessionEnd) then begin
FOnSessionEnd(Sender);
end;
end;
procedure TIdCustomHTTPServer.DoSessionStart(Sender: TIdHTTPSession);
begin
if Assigned(FOnSessionStart) then begin
FOnSessionStart(Sender);
end;
end;
function TIdCustomHTTPServer.GetSessionFromCookie(AContext: TIdContext;
AHTTPRequest: TIdHTTPRequestInfo; AHTTPResponse: TIdHTTPResponseInfo;
var VContinueProcessing: Boolean): TIdHTTPSession;
var
LIndex: Integer;
LSessionID: String;
begin
Result := nil;
VContinueProcessing := True;
if SessionState then
begin
LIndex := AHTTPRequest.Cookies.GetCookieIndex(GSessionIDCookie);
while LIndex >= 0 do
begin
LSessionID := AHTTPRequest.Cookies[LIndex].Value;
Result := FSessionList.GetSession(LSessionID, AHTTPRequest.RemoteIP);
if Assigned(Result) then begin
Break;
end;
DoInvalidSession(AContext, AHTTPRequest, AHTTPResponse, VContinueProcessing, LSessionID);
if not VContinueProcessing then begin
Break;
end;
LIndex := AHTTPRequest.Cookies.GetCookieIndex(GSessionIDCookie, LIndex+1);
end; { while }
// check if a session was returned. If not and if AutoStartSession is set to
// true, Create a new session
if (Result = nil) and VContinueProcessing and FAutoStartSession then begin
Result := CreateSession(AContext, AHTTPResponse, AHTTPrequest);
end;
end;
AHTTPRequest.FSession := Result;
AHTTPResponse.FSession := Result;
end;
procedure TIdCustomHTTPServer.Startup;
begin
inherited Startup;
// set the session timeout and options
if not Assigned(FSessionList) then begin
FSessionList := TIdHTTPDefaultSessionList.Create(Self);
FImplicitSessionList := True;
end;
if FSessionTimeOut <> 0 then begin
FSessionList.FSessionTimeout := FSessionTimeOut;
end else begin
FSessionState := False;
end;
// Session events
FSessionList.OnSessionStart := DoSessionStart;
FSessionList.OnSessionEnd := DoSessionEnd;
// If session handling is enabled, create the housekeeper thread
if SessionState then begin
FSessionCleanupThread := TIdHTTPSessionCleanerThread.Create(FSessionList);
end;
end;
procedure TIdCustomHTTPServer.Shutdown;
begin
// Boost the clear thread priority to give it a good chance to terminate
if Assigned(FSessionCleanupThread) then begin
IndySetThreadPriority(FSessionCleanupThread, tpNormal);
FSessionCleanupThread.TerminateAndWaitFor;
FreeAndNil(FSessionCleanupThread);
end;
// RLebeau: FSessionList might not be assignd yet if Shutdown() is being
// called due to an exception raised in Startup()...
if FImplicitSessionList then begin
SessionList := nil;
end
else if Assigned(FSessionList) then begin
FSessionList.Clear;
end;
inherited Shutdown;
end;
procedure TIdCustomHTTPServer.SetSessionList(const AValue: TIdHTTPCustomSessionList);
var
LSessionList: TIdHTTPCustomSessionList;
begin
// RLebeau - is this really needed? What should happen if this
// gets called by Notification() if the sessionList is freed while
// the server is still Active?
if Active then begin
EIdException.Toss(RSHTTPCannotSwitchSessionListWhenActive);
end;
// If implicit one already exists free it
// Free the default SessionList
if FImplicitSessionList then begin
// Under D8 notification gets called after .Free of FreeAndNil, but before
// its set to nil with a side effect of IDisposable. To counteract this we
// set it to nil first.
// -Kudzu
LSessionList := FSessionList;
FSessionList := nil;
FreeAndNil(LSessionList);
//
FImplicitSessionList := False;
end;
// Ensure we will no longer be notified when the component is freed
if FSessionList <> nil then begin
FSessionList.RemoveFreeNotification(Self);
end;
FSessionList := AValue;
// Ensure we will be notified when the component is freed, even is it's on
// another form
if FSessionList <> nil then begin
FSessionList.FreeNotification(Self);
end;
end;
procedure TIdCustomHTTPServer.SetSessionState(const Value: Boolean);
begin
// ToDo: Add thread multiwrite protection here
if (not (IsDesignTime or IsLoading)) and Active then begin
raise EIdHTTPCannotSwitchSessionStateWhenActive.Create(RSHTTPCannotSwitchSessionStateWhenActive);
end;
FSessionState := Value;
end;
procedure TIdCustomHTTPServer.CreatePostStream(ASender: TIdContext;
AHeaders: TIdHeaderList; var VPostStream: TStream);
begin
if Assigned(OnCreatePostStream) then begin
OnCreatePostStream(ASender, AHeaders, VPostStream);
end;
end;
procedure TIdCustomHTTPServer.DoneWithPostStream(ASender: TIdContext;
ARequestInfo: TIdHTTPRequestInfo);
var
LCanFree: Boolean;
begin
LCanFree := True;
if Assigned(FOnDoneWithPostStream) then begin
FOnDoneWithPostStream(ASender, ARequestInfo, LCanFree);
end;
if LCanFree then begin
FreeAndNil(ARequestInfo.FPostStream);
end;
end;
{ TIdHTTPSession }
constructor TIdHTTPSession.Create(AOwner: TIdHTTPCustomSessionList);
begin
inherited Create;
FLock := TIdCriticalSection.Create;
FContent := TStringList.Create;
FOwner := AOwner;
if Assigned(AOwner) then
begin
if Assigned(AOwner.OnSessionStart) then begin
AOwner.OnSessionStart(Self);
end;
end;
end;
{TIdSession}
constructor TIdHTTPSession.CreateInitialized(AOwner: TIdHTTPCustomSessionList; const SessionID, RemoteIP: string);
begin
inherited Create;
FSessionID := SessionID;
FRemoteHost := RemoteIP;
FLastTimeStamp := Now;
FLock := TIdCriticalSection.Create;
FContent := TStringList.Create;
FOwner := AOwner;
if Assigned(AOwner) then
begin
if Assigned(AOwner.OnSessionStart) then begin
AOwner.OnSessionStart(Self);
end;
end;
end;
destructor TIdHTTPSession.Destroy;
begin
// code added here should also be reflected in
// the TIdHTTPDefaultSessionList.RemoveSessionFromLockedList method
// Why? It calls this function and this code gets executed?
DoSessionEnd;
FreeAndNil(FContent);
FreeAndNil(FLock);
if Assigned(FOwner) then begin
FOwner.RemoveSession(self);
end;
inherited Destroy;
end;
procedure TIdHTTPSession.DoSessionEnd;
begin
if Assigned(FOwner) and Assigned(FOwner.FOnSessionEnd) then begin
FOwner.FOnSessionEnd(Self);
end;
end;
function TIdHTTPSession.IsSessionStale: boolean;
begin
Result := TimeStampInterval(FLastTimeStamp, Now) > Integer(FOwner.SessionTimeout);
end;
procedure TIdHTTPSession.Lock;
begin
// ToDo: Add session locking code here
FLock.Enter;
end;
procedure TIdHTTPSession.SetContent(const Value: TStrings);
begin
FContent.Assign(Value);
end;
procedure TIdHTTPSession.Unlock;
begin
// ToDo: Add session unlocking code here
FLock.Leave;
end;
{ TIdHTTPRequestInfo }
constructor TIdHTTPRequestInfo.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FCommandType := hcUnknown;
FCookies := TIdCookies.Create(Self);
FParams := TStringList.Create;
ContentLength := -1;
end;
procedure TIdHTTPRequestInfo.DecodeAndSetParams(const AValue: String);
var
i, j : Integer;
s: string;
LEncoding: TIdTextEncoding;
begin
// Convert special characters
// ampersand '&' separates values {Do not Localize}
Params.BeginUpdate;
try
Params.Clear;
LEncoding := CharsetToEncoding(CharSet);
{$IFNDEF DOTNET}
try
{$ENDIF}
i := 1;
while i <= Length(AValue) do
begin
j := i;
while (j <= Length(AValue)) and (AValue[j] <> '&') do {do not localize}
begin
Inc(j);
end;
s := Copy(AValue, i, j-i);
// See RFC 1866 section 8.2.1. TP
s := StringReplace(s, '+', ' ', [rfReplaceAll]); {do not localize}
Params.Add(TIdURI.URLDecode(s, LEncoding));
i := j + 1;
end;
{$IFNDEF DOTNET}
finally
LEncoding.Free;
end;
{$ENDIF}
finally
Params.EndUpdate;
end;
end;
destructor TIdHTTPRequestInfo.Destroy;
begin
FreeAndNil(FCookies);
FreeAndNil(FParams);
FreeAndNil(FPostStream);
inherited Destroy;
end;
function TIdHTTPRequestInfo.IsVersionAtLeast(const AMajor, AMinor: Integer): Boolean;
begin
Result := (FVersionMajor > AMajor) or
((FVersionMajor = AMajor) and (FVersionMinor >= AMinor));
end;
{ TIdHTTPResponseInfo }
procedure TIdHTTPResponseInfo.CloseSession;
var
i: Integer;
begin
i := Cookies.GetCookieIndex(GSessionIDCookie);
while i > -1 do begin
Cookies.Delete(i);
i := Cookies.GetCookieIndex(GSessionIDCookie, i);
end;
with Cookies.Add do begin
CookieName := GSessionIDCookie;
Expires := Date-7;
end;
FreeAndNil(FSession);
end;
constructor TIdHTTPResponseInfo.Create(AServer: TIdCustomHTTPServer;
ARequestInfo: TIdHTTPRequestInfo; AConnection: TIdTCPConnection);
begin
inherited Create(AServer);
FRequestInfo := ARequestInfo;
FConnection := AConnection;
FHttpServer := AServer;
FFreeContentStream := True;
ResponseNo := GResponseNo;
ContentType := ''; //GContentType;
ContentLength := GFContentLength;
{Some clients may not support folded lines}
RawHeaders.FoldLines := False;
FCookies := TIdCookies.Create(Self);
{TODO Specify version - add a class method dummy that calls version}
ServerSoftware := GServerSoftware;
end;
destructor TIdHTTPResponseInfo.Destroy;
begin
FreeAndNil(FCookies);
ReleaseContentStream;
inherited Destroy;
end;
procedure TIdHTTPResponseInfo.Redirect(const AURL: string);
begin
ResponseNo := 302;
Location := AURL;
end;
procedure TIdHTTPResponseInfo.ReleaseContentStream;
begin
if FreeContentStream then begin
FreeAndNil(FContentStream);
end else begin
FContentStream := nil;
end;
end;
procedure TIdHTTPResponseInfo.SetCloseConnection(const Value: Boolean);
begin
Connection := iif(Value, 'close', 'keep-alive'); {Do not Localize}
FCloseConnection := Value;
end;
procedure TIdHTTPResponseInfo.SetCookies(const AValue: TIdCookies);
begin
FCookies.Assign(AValue);
end;
procedure TIdHTTPResponseInfo.SetHeaders;
begin
inherited SetHeaders;
with RawHeaders do
begin
if Server <> '' then begin
Values['Server'] := Server; {Do not Localize}
end;
if Location <> '' then begin
Values['Location'] := Location; {Do not Localize}
end;
if FLastModified > 0 then begin
Values['Last-Modified'] := LocalDateTimeToHttpStr(FLastModified); {do not localize}
end;
if AuthRealm <> '' then begin
Values['WWW-Authenticate'] := 'Basic realm="' + AuthRealm + '"'; {Do not Localize}
end;
end;
end;
procedure TIdHTTPResponseInfo.SetResponseNo(const AValue: Integer);
begin
FResponseNo := AValue;
case FResponseNo of
100: ResponseText := RSHTTPContinue;
// 2XX: Success
200: ResponseText := RSHTTPOK;
201: ResponseText := RSHTTPCreated;
202: ResponseText := RSHTTPAccepted;
203: ResponseText := RSHTTPNonAuthoritativeInformation;
204: ResponseText := RSHTTPNoContent;
205: ResponseText := RSHTTPResetContent;
206: ResponseText := RSHTTPPartialContent;
// 3XX: Redirections
301: ResponseText := RSHTTPMovedPermanently;
302: ResponseText := RSHTTPMovedTemporarily;
303: ResponseText := RSHTTPSeeOther;
304: ResponseText := RSHTTPNotModified;
305: ResponseText := RSHTTPUseProxy;
// 4XX Client Errors
400: ResponseText := RSHTTPBadRequest;
401: ResponseText := RSHTTPUnauthorized;
403: ResponseText := RSHTTPForbidden;
404: begin
ResponseText := RSHTTPNotFound;
// Close connection
CloseConnection := True;
end;
405: ResponseText := RSHTTPMethodNotAllowed;
406: ResponseText := RSHTTPNotAcceptable;
407: ResponseText := RSHTTPProxyAuthenticationRequired;
408: ResponseText := RSHTTPRequestTimeout;
409: ResponseText := RSHTTPConflict;
410: ResponseText := RSHTTPGone;
411: ResponseText := RSHTTPLengthRequired;
412: ResponseText := RSHTTPPreconditionFailed;
413: ResponseText := RSHTTPRequestEntityTooLong;
414: ResponseText := RSHTTPRequestURITooLong;
415: ResponseText := RSHTTPUnsupportedMediaType;
417: ResponseText := RSHTTPExpectationFailed;
// 5XX Server errors
500: ResponseText := RSHTTPInternalServerError;
501: ResponseText := RSHTTPNotImplemented;
502: ResponseText := RSHTTPBadGateway;
503: ResponseText := RSHTTPServiceUnavailable;
504: ResponseText := RSHTTPGatewayTimeout;
505: ResponseText := RSHTTPHTTPVersionNotSupported;
else
ResponseText := RSHTTPUnknownResponseCode;
end;
{if ResponseNo >= 400 then
// Force COnnection closing when there is error during the request processing
CloseConnection := true;
end;}
end;
function TIdHTTPResponseInfo.ServeFile(AContext: TIdContext; const AFile: String): Int64;
var
EnableTransferFile: Boolean;
begin
if Length(ContentType) = 0 then begin
ContentType := HTTPServer.MIMETable.GetFileMIMEType(AFile);
end;
ContentLength := FileSizeByName(AFile);
if Length(ContentDisposition) = 0 then begin
// TODO: use EncodeHeader() here...
ContentDisposition := IndyFormat('attachment; filename="%s";', [ExtractFileName(AFile)]);
end;
WriteHeader;
EnableTransferFile := not (AContext.Connection.IOHandler is TIdSSLIOHandlerSocketBase);
Result := AContext.Connection.IOHandler.WriteFile(AFile, EnableTransferFile);
end;
function TIdHTTPResponseInfo.SmartServeFile(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; const AFile: String): Int64;
var
LFileDate : TDateTime;
LReqDate : TDateTime;
begin
LFileDate := IndyFileAge(AFile);
if (LFileDate = 0.0) and (not FileExists(AFile)) then
begin
ResponseNo := 404;
Result := 0;
end else
begin
LReqDate := GMTToLocalDateTime(ARequestInfo.RawHeaders.Values['If-Modified-Since']); {do not localize}
// if the file date in the If-Modified-Since header is within 2 seconds of the
// actual file, then we will send a 304. We don't use the ETag - offers nothing
// over the file date for static files on windows. Linux: consider using iNode
// RLebeau 2/21/2011: TODO - make use of ETag. It is supposed to be updated
// whenever the file contents change, regardless of the file's timestamps.
if (LReqDate <> 0) and (abs(LReqDate - LFileDate) < 2 * (1 / (24 * 60 * 60))) then
begin
ResponseNo := 304;
Result := 0;
end else
begin
Date := Now;
LastModified := LFileDate;
Result := ServeFile(AContext, AFile);
end;
end;
end;
procedure TIdHTTPResponseInfo.WriteContent;
var
LEncoding: TIdTextEncoding;
begin
LEncoding := nil;
{$IFNDEF DOTNET}
try
{$ENDIF}
if not HeaderHasBeenWritten then begin
WriteHeader;
end;
with FConnection do begin
// Always check ContentText first
if ContentText <> '' then begin
LEncoding := CharsetToEncoding(CharSet);
IOHandler.Write(ContentText, LEncoding);
end
else if Assigned(ContentStream) then begin
ContentStream.Position := 0;
IOHandler.Write(ContentStream);
end
else begin
LEncoding := CharsetToEncoding(CharSet);
IOHandler.WriteLn('<HTML><BODY><B>' + IntToStr(ResponseNo) + ' ' + ResponseText {Do not Localize}
+ '</B></BODY></HTML>', LEncoding); {Do not Localize}
end;
// Clear All - This signifies that WriteConent has been called.
ContentText := ''; {Do not Localize}
ReleaseContentStream;
end;
{$IFNDEF DOTNET}
finally
if Assigned(LEncoding) then begin
LEncoding.Free;
end;
end;
{$ENDIF}
end;
procedure TIdHTTPResponseInfo.WriteHeader;
var
i: Integer;
LEncoding: TIdTextEncoding;
LBufferingStarted: Boolean;
begin
if HeaderHasBeenWritten then begin
EIdHTTPHeaderAlreadyWritten.Toss(RSHTTPHeaderAlreadyWritten);
end;
FHeaderHasBeenWritten := True;
if AuthRealm <> '' then
begin
ResponseNo := 401;
if (Length(ContentText) = 0) and (not Assigned(ContentStream)) then
begin
ContentType := 'text/html; charset=utf-8'; {Do not Localize}
ContentText := '<HTML><BODY><B>' + IntToStr(ResponseNo) + ' ' + ResponseText + '</B></BODY></HTML>'; {Do not Localize}
ContentLength := -1; // calculated below
end;
end;
// RLebeau 5/15/2012: for backwards compatibility. We really should
// make the user set this every time instead...
if ContentType = '' then begin
if (ContentText <> '') or (Assigned(ContentStream)) then begin
ContentType := 'text/html; charset=ISO-8859-1'; {Do not Localize}
end;
end;
// RLebeau: according to RFC 2616 Section 4.4:
//
// If a Content-Length header field (section 14.13) is present, its
// decimal value in OCTETs represents both the entity-length and the
// transfer-length. The Content-Length header field MUST NOT be sent
// if these two lengths are different (i.e., if a Transfer-Encoding
// header field is present). If a message is received with both a
// Transfer-Encoding header field and a Content-Length header field,
// the latter MUST be ignored.
// ...
// Messages MUST NOT include both a Content-Length header field and a
// non-identity transfer-coding. If the message does include a non-
// identity transfer-coding, the Content-Length MUST be ignored.
if (ContentLength = -1) and
((TransferEncoding = '') or TextIsSame(TransferEncoding, 'identity')) then {do not localize}
begin
// Always check ContentText first
if ContentText <> '' then begin
LEncoding := CharsetToEncoding(CharSet);
{$IFNDEF DOTNET}
try
{$ENDIF}
ContentLength := LEncoding.GetByteCount(ContentText);
{$IFNDEF DOTNET}
finally
LEncoding.Free;
end;
{$ENDIF}
end
else if Assigned(ContentStream) then begin
ContentLength := ContentStream.Size;
end else begin
ContentLength := 0;
end;
end;
if Date <= 0 then begin
Date := Now;
end;
SetHeaders;
LBufferingStarted := not FConnection.IOHandler.WriteBufferingActive;
if LBufferingStarted then begin
FConnection.IOHandler.WriteBufferOpen;
end;
try
// Write HTTP status response
FConnection.IOHandler.WriteLn('HTTP/1.1 ' + IntToStr(ResponseNo) + ' ' + ResponseText); {Do not Localize}
// Write headers
FConnection.IOHandler.Write(RawHeaders);
// Write cookies
for i := 0 to Cookies.Count - 1 do begin
FConnection.IOHandler.WriteLn('Set-Cookie: ' + Cookies[i].ServerCookie); {Do not Localize}
end;
// HTTP headers end with a double CR+LF
FConnection.IOHandler.WriteLn;
if LBufferingStarted then begin
FConnection.IOHandler.WriteBufferClose;
end;
except
if LBufferingStarted then begin
FConnection.IOHandler.WriteBufferCancel;
end;
raise;
end;
end;
function TIdHTTPResponseInfo.GetServer: string;
begin
Result := Server;
end;
procedure TIdHTTPResponseInfo.SetServer(const Value: string);
begin
Server := Value;
end;
{ TIdHTTPDefaultSessionList }
procedure TIdHTTPDefaultSessionList.Add(ASession: TIdHTTPSession);
begin
SessionList.Add(ASession);
end;
procedure TIdHTTPDefaultSessionList.Clear;
var
ASessionList: TList;
i: Integer;
begin
ASessionList := SessionList.LockList;
try
for i := ASessionList.Count - 1 DownTo 0 do
if ASessionList[i] <> nil then
begin
TIdHTTPSession(ASessionList[i]).DoSessionEnd;
// must set the owner to nil or the session will try to fire the
// OnSessionEnd event again, and also remove itself from the session
// list and deadlock
TIdHTTPSession(ASessionList[i]).FOwner := nil;
TIdHTTPSession(ASessionList[i]).Free;
end;
ASessionList.Clear;
ASessionList.Capacity := SessionCapacity;
finally
SessionList.UnlockList;
end;
end;
function TIdHTTPDefaultSessionList.CreateSession(const RemoteIP, SessionID: String): TIdHTTPSession;
begin
Result := TIdHTTPSession.CreateInitialized(Self, SessionID, RemoteIP);
SessionList.Add(Result);
end;
function TIdHTTPDefaultSessionList.CreateUniqueSession(
const RemoteIP: String): TIdHTTPSession;
var
SessionID: String;
begin
SessionID := GetRandomString(15);
while GetSession(SessionID, RemoteIP) <> nil do
begin
SessionID := GetRandomString(15);
end; // while
Result := CreateSession(RemoteIP, SessionID);
end;
destructor TIdHTTPDefaultSessionList.Destroy;
begin
Clear;
FreeAndNil(FSessionList);
inherited destroy;
end;
function TIdHTTPDefaultSessionList.GetSession(const SessionID, RemoteIP: string): TIdHTTPSession;
var
ASessionList: TList;
i: Integer;
ASession: TIdHTTPSession;
begin
Result := nil;
ASessionList := SessionList.LockList;
try
// get current time stamp
for i := 0 to ASessionList.Count - 1 do
begin
ASession := TIdHTTPSession(ASessionList[i]);
Assert(ASession <> nil);
// the stale sessions check has been removed... the cleanup thread should suffice plenty
if TextIsSame(ASession.FSessionID, SessionID) and ((Length(RemoteIP) = 0) or TextIsSame(ASession.RemoteHost, RemoteIP)) then
begin
// Session found
ASession.FLastTimeStamp := Now;
Result := ASession;
Break;
end;
end;
finally
SessionList.UnlockList;
end;
end;
procedure TIdHTTPDefaultSessionList.InitComponent;
begin
inherited InitComponent;
FSessionList := TThreadList.Create;
FSessionList.LockList.Capacity := SessionCapacity;
FSessionList.UnlockList;
end;
procedure TIdHTTPDefaultSessionList.PurgeStaleSessions(PurgeAll: Boolean = false);
var
i: Integer;
aSessionList: TList;
begin
// S.G. 24/11/00: Added a way to force a session purge (Used when thread is terminated)
// Get necessary data
Assert(SessionList<>nil);
aSessionList := SessionList.LockList;
try
// Loop though the sessions.
for i := aSessionList.Count - 1 downto 0 do
begin
// Identify the stale sessions
if Assigned(ASessionList[i]) and
(PurgeAll or TIdHTTPSession(aSessionList[i]).IsSessionStale) then
begin
RemoveSessionFromLockedList(i, aSessionList);
end;
end;
finally
SessionList.UnlockList;
end;
end;
procedure TIdHTTPDefaultSessionList.RemoveSession(Session: TIdHTTPSession);
var
ASessionList: TList;
Index: integer;
begin
ASessionList := SessionList.LockList;
try
Index := ASessionList.IndexOf(TObject(Session));
if index > -1 then
begin
ASessionList.Delete(index);
end;
finally
SessionList.UnlockList;
end;
end;
procedure TIdHTTPDefaultSessionList.RemoveSessionFromLockedList(AIndex: Integer;
ALockedSessionList: TList);
begin
TIdHTTPSession(ALockedSessionList[AIndex]).DoSessionEnd;
// must set the owner to nil or the session will try to fire the OnSessionEnd
// event again, and also remove itself from the session list and deadlock
TIdHTTPSession(ALockedSessionList[AIndex]).FOwner := nil;
TIdHTTPSession(ALockedSessionList[AIndex]).Free;
ALockedSessionList.Delete(AIndex);
end;
{ TIdHTTPSessionClearThread }
procedure TIdHTTPSessionCleanerThread.AfterRun;
begin
if Assigned(FSessionList) then
FSessionList.PurgeStaleSessions(true);
inherited AfterRun;
end;
constructor TIdHTTPSessionCleanerThread.Create(SessionList: TIdHTTPCustomSessionList);
begin
inherited Create(false);
// thread priority used to be set to tpIdle but this is not supported
// under DotNet. How low do you want to go?
IndySetThreadPriority(Self, tpLowest);
FSessionList := SessionList;
FreeOnTerminate := False;
end;
procedure TIdHTTPSessionCleanerThread.Run;
begin
IndySleep(1000);
if Assigned(FSessionList) then begin
FSessionList.PurgeStaleSessions(Terminated);
end;
end;
end.
|
unit ModelServer;
interface
uses
Windows, Classes, Protocol, Kernel, Population, RDOServer, ExtCtrls, BackupObjects,
SyncObjs, RDOInterfaces, MailServerInterfaces;
const
tidRDOHook_World = 'World';
const
tidRegKey_ModelExtensions = '\SOFTWARE\Oceanus\FIVE\ModelServer\Extensions';
const
tidFileName_WorldIniFile = 'world.ini';
const
tidIniSection_General = 'General';
tidIniSection_WorldTowns = 'Towns';
tidIniValue_Name = 'Name';
tidIniValue_xSize = 'Width';
tidIniValue_ySize = 'Height';
tidIniValue_TownCount = 'Count';
tidIniValue_TownName = 'TownName';
tidIniValue_TownCluster = 'TownCluster';
tidIniValue_TownX = 'TownX';
tidIniValue_TownY = 'TownY';
type
TBackupMode = (bmdInGame, bmdShutdown);
const
BackupPeriod = 30; // in minutes
type
TModelServer =
class(TObject, IMailServer)
public
constructor Create;
destructor Destroy; override;
public
procedure InitWorld( aName : string; aNotEvent : TBackupReaderNotify; aBaseDir, aCacheHost : string; aDAPort, aCSPort, aCCPort : integer; SimSpeed : TThreadPriority; aMailHost : string; aMailPort : integer );
procedure InitInterfaceServerEvents( ServerName : string; ServerPort : integer );
procedure InitMailServer( ServerName : string; ServerPort : integer; WorldName : string );
private
procedure StartCacheServer( aCSPort : integer );
procedure StartDirectAccessServer( aDAPort : integer );
private
fBaseDir : string;
fWorld : TInhabitedWorld;
fDAConn : IRDOConnectionsServer;
fDAServ : TRDOServer;
fDALockConn : IRDOConnectionsServer;
fDALockServ : TRDOServer;
fISConn : IRDOConnectionInit;
fISEvents : OleVariant;
fBPS : integer;
fDAPort : integer;
fDALockPort : integer;
public
property TheWorld : TInhabitedWorld read fWorld;
property BPS : integer read fBPS; // Blocks per second
private
fExtensionList : TStrings;
public
property ExtensionList : TStrings read fExtensionList;
public
procedure RegisterModelExtension( filename : string );
private
procedure LoadExtensions;
private
fTimer : TTimer;
fSimTimer : TTimer;
fIntTimer : TTimer;
fSimEv : TEvent;
fIntEv : TEvent;
fSimThread : TThread;
fLastBackup : integer;
private
procedure SetTimeRes( aVirtTimeRate, aSimRate, anIntRate : integer );
procedure OnTimer( Sender : TObject );
procedure OnSimTimer( Sender : TObject );
procedure OnIntTimer( Sender : TObject );
private
fIntegrationThread : TThread;
fIntegrationLock : TCriticalSection;
private
procedure OnAreaChanged( x, y, dx, dy : integer );
procedure OnFacilityChanged( Facility : TFacility; FacilityChange : TFacilityChange );
procedure OnTycoonsChanged;
procedure OnDateChanged( Date : TDateTime );
procedure OnEndOfPeriod( PeriodType : TPeriodType; PeriodCount : integer );
procedure OnTycoonRetired( name : string );
private
procedure StoreBackup( mode : TBackupMode );
private
fMailConn : IRDOConnectionInit;
fMailServer : OleVariant;
fMailId : integer;
// IUnknown
private
function QueryInterface(const IID: TGUID; out Obj): hresult; stdcall;
function _AddRef : integer; stdcall;
function _Release : integer; stdcall;
// IMailServer
private
function NewMailAccount(Account, Alias, FwdAddr : string; KeepMsg : boolean) : boolean;
function DeleteAccount (Account : string) : boolean;
function SetForwardRule(Account, FwdAddr : string; KeepMsg : boolean) : boolean;
function SendMessage(From, Dest, Subject : string; Lines : TStringList; html : boolean) : boolean;
function SendHTMLMessage(From, Dest, Subject, URL : string) : boolean;
private
// fBackupEvent : TEvent;
end;
const
TheModelServer : TModelServer = nil;
implementation
uses
SmartThreads, ClassStorage, SysUtils, Trade, ModelServerCache, ComObj,
Registry, IniFiles, KernelCache, WinSockRDOConnectionsServer, HostNames,
Construction, WinSockRDOConnection, RDOObjectProxy, Surfaces,
BackupInterfaces, PopulatedBlock, WorkCenterBlock, Collection, CollectionBackup,
PyramidalModifier, PublicFacility, StdFluids, World, MailProtocol,
Circuits, ResearchCenter, Headquarters, ConnectedBlock;
// TBackupThread
type
TBackupThread =
class( TSmartThread )
public
constructor Create( aServer : TModelServer; aMode : TBackupMode );
private
fServer : TModelServer;
fMode : TBackupMode;
protected
procedure Execute; override;
end;
constructor TBackupThread.Create( aServer : TModelServer; aMode : TBackupMode );
begin
inherited Create( true );
fServer := aServer;
fMode := aMode;
Priority := tpHigher;
// >> FreeOnTerminate := true;
Resume;
end;
procedure TBackupThread.Execute;
begin
fServer.StoreBackup( fMode );
end;
// TSimTread
type
TSimThread =
class( TSmartThread )
private
fServer : TModelServer;
protected
procedure Execute; override;
end;
procedure TSimThread.Execute;
var
SimStart : integer;
SimCount : integer;
Backup : TBackupThread;
begin
SimCount := 1;
while not Terminated do
try
if fServer.fSimEv.WaitFor( fServer.fSimTimer.Interval ) <> wrTimeout
then
begin
fServer.fSimEv.ResetEvent;
SimStart := DateTimeToTimeStamp(Time).time;
fServer.fWorld.Simulate;
if SimCount mod (BackupPeriod*60*1000 div integer(fServer.fSimTimer.Interval)) = 0
//if SimCount mod (10*1000 div fServer.fSimTimer.Interval) = 0
then
begin
// Wait for file transfer operation uff!!
// >> fServer.fBackupEvent.WaitFor( INFINITE );
fServer.fIntegrationLock.Enter;
// >> fServer.fBackupEvent.ResetEvent;
// Create the thread
Backup := TBackupThread.Create( fServer, bmdInGame );
// >> fServer.fBackupEvent.WaitFor( INFINITE );
WaitForSingleObject( Backup.Handle, INFINITE );
Backup.Free;
fServer.fIntegrationLock.Leave;
// Set the event to avoid re-entrance here uff!!
// >> fServer.fBackupEvent.ResetEvent;
end;
inc( SimCount );
if DateTimeToTimeStamp(Time).time > SimStart
then fServer.fBPS := 1000*fServer.fWorld.Facilities.Count div (DateTimeToTimeStamp(Time).time - SimStart)
end;
except
end;
end;
// TIntegrationThread
type
TIntegrationThread =
class( TSmartThread )
public
constructor Create;
private
fServer : TModelServer;
fIntegrationPool : TIntegratorPool;
protected
procedure Execute; override;
end;
constructor TIntegrationThread.Create;
begin
inherited Create( true );
fIntegrationPool := TIntegratorPool(TheClassStorage.ClassById[tidClassFamily_SurfacePools, tidSurfacePool_Integrators]);
Priority := tpIdle;
end;
procedure TIntegrationThread.Execute;
begin
while not Terminated do
try
fServer.fIntegrationLock.Enter;
if fServer.fIntEv.WaitFor( fServer.fIntTimer.Interval ) <> wrTimeout
then
begin
fServer.fIntEv.ResetEvent;
fIntegrationPool.IntegrateAll;
end;
fServer.fIntegrationLock.Leave;
except
end;
end;
// TModelServer
constructor TModelServer.Create;
begin
inherited Create;
fExtensionList := TStringList.Create;
// >> fBackupEvent := TEvent.Create(nil, true, true, '');
end;
destructor TModelServer.Destroy;
procedure UpdateModelExtensionList;
var
Reg : TRegistry;
i : integer;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.DeleteKey( tidRegKey_ModelExtensions );
if Reg.OpenKey( tidRegKey_ModelExtensions, true )
then
for i := 0 to pred(fExtensionList.Count) do
Reg.WriteString( ExtractFileName(fExtensionList[i]), fExtensionList[i] )
else raise Exception.Create( 'Cannot open Key ' + tidRegKey_ModelExtensions );
finally
Reg.Free;
end;
end;
begin
try
// Stop integration thread
if fIntegrationThread <> nil
then
begin
fIntegrationThread.Terminate;
WaitForSingleObject( fIntegrationThread.Handle, 60000 );
fIntegrationThread.Free;
end;
// Stop simulation thread
if fSimThread <> nil
then
begin
fSimThread.Terminate;
WaitForSingleObject( fSimThread.Handle, 60000 );
end;
// Free timers and events
fTimer.Free;
fSimTimer.Free;
fIntTimer.Free;
fSimEv.Free;
fIntEv.Free;
// Free world
if fWorld <> nil
then
begin
try
StoreBackup( bmdShutdown );
except
MessageBox( 0, 'Could not save world!', 'Backup Error', MB_ICONWARNING or MB_OK );
end;
//UpdateModelExtensionList;
//fWorld.Free;
end;
fIntegrationLock.Free;
ClassStorage.DoneTheClassStorage;
ModelServerCache.DoneModelServerCache;
fExtensionList.Free;
inherited;
except
end;
end;
procedure TModelServer.InitWorld( aName : string; aNotEvent : TBackupReaderNotify; aBaseDir, aCacheHost : string; aDAPort, aCSPort, aCCPort : integer; SimSpeed : TThreadPriority; aMailHost : string; aMailPort : integer );
procedure CreateWorldFromIniFile;
var
IniFile : TIniFile;
Name : string;
xSize : integer;
ySize : integer;
begin
IniFile := TIniFile.Create( fBaseDir + aName + '.ini' );
try
Name := IniFile.ReadString( tidIniSection_General, tidIniValue_Name, '' );
xSize := IniFile.ReadInteger( tidIniSection_General, tidIniValue_xSize, 0 );
ySize := IniFile.ReadInteger( tidIniSection_General, tidIniValue_ySize, 0 );
if (Name <> '') and (xSize > 0) and (ySize > 0)
then fWorld := TInhabitedWorld.Create( Name, xSize, ySize )
else raise Exception.Create( 'Invalid World INI file!' );
finally
IniFile.Free;
end;
end;
procedure InitWorldFromIniFile;
procedure InitTowns( IniFile : TIniFile );
var
count : integer;
i : integer;
x, y : integer;
Name : string;
Cluster : string;
Town : TTown;
begin
count := IniFile.ReadInteger( tidIniSection_WorldTowns, tidIniValue_TownCount, 0 );
for i := 0 to pred(count) do
begin
Name := IniFile.ReadString( tidIniSection_WorldTowns, tidIniValue_TownName + IntToStr(i), '' );
Cluster := IniFile.ReadString( tidIniSection_WorldTowns, tidIniValue_TownCluster + IntToStr(i), '' );
x := IniFile.ReadInteger( tidIniSection_WorldTowns, tidIniValue_TownX + IntToStr(i), -1 );
y := IniFile.ReadInteger( tidIniSection_WorldTowns, tidIniValue_TownY + IntToStr(i), -1 );
if (Name <> '') and (Cluster <> '') and (x >= 0) and (y >= 0)
then
begin
Town := TInhabitedTown.Create( Name, Cluster, Cluster + 'TownHall', Cluster + 'TradeCenter', x, y, fWorld );
fWorld.Towns.Insert( Town );
CacheObject( Town );
end
else raise Exception.Create( 'Invalid Town INI info (' + IntToStr(i) + ')' );
end;
end;
var
IniFile : TIniFile;
begin
IniFile := TIniFile.Create( fBaseDir + aName + '.ini' );
try
fWorld.InitClusters;
InitTowns( IniFile );
finally
IniFile.Free;
end;
end;
var
Reader : IBackupReader;
WorldURL : string;
UseBackup : boolean;
begin
fDAPort := aDAPort;
fDALockPort := aDAPort + 1;
// Create the world
if aBaseDir[length(aBaseDir)] <> '\'
then fBaseDir := aBaseDir + '\'
else fBaseDir := aBaseDir;
if not RegisterWorld( aName, aCacheHost, aCSPort, aCCPort, WorldURL )
then raise Exception.Create( 'Cannot register world in cache server side' );
ModelServerCache.InitModelServerCache;
ClassStorage.InitTheClassStorage;
Kernel.RegisterSurfaces;
Population.RegisterSurfaces;
KernelCache.RegisterCachers;
Population.RegisterMetaFluids;
Population.RegisterMetaInstances;
StdFluids.RegisterMetaFluids;
WorkCenterBlock.RegisterTownParameters;
CollectionBackup.RegisterBackup;
Kernel.RegisterBackup;
World.RegisterBackup;
ConnectedBlock.RegisterBackup;
Population.RegisterBackup;
ResearchCenter.RegisterBackup;
Headquarters.RegisterBackup;
Trade.RegisterBackup;
Construction.RegisterBackup;
PopulatedBlock.RegisterBackup;
WorkCenterBlock.RegisterBackup;
Surfaces.RegisterBackup;
Circuits.RegisterBackup;
PyramidalModifier.RegisterBackup;
PublicFacility.RegisterBackup;
LoadExtensions;
UseBackup := FileExists( fBaseDir + aName + '.world' );
if UseBackup
then
begin
Reader := OpenBackup( fBaseDir + aName + '.world', aNotEvent );
Reader.ReadObject( 'World', fWorld, nil );
Reader := nil;
end
else CreateWorldFromIniFile;
fWorld.LoadLandInfo( fBaseDir + aName + '.bmp' );
// Set World base URL
fWorld.WorldURL := WorldURL;
// Start RDO servers
StartDirectAccessServer( aDAPort );
StartCacheServer( aCSPort );
// Start Mail Server
InitMailServer( aMailHost, aMailPort, aName );
// Create new world after Mail and RDO servers are running
if not UseBackup
then InitWorldFromIniFile;
// Init Simulation clockwork
fTimer := TTimer.Create( nil );
fSimTimer := TTimer.Create( nil );
fIntTimer := TTimer.Create( nil );
fSimEv := TEvent.Create( nil, true, false, '' );
fIntEv := TEvent.Create( nil, true, false, '' );
fSimThread := TSimThread.Create( true );
TSimThread(fSimThread).fServer := self;
fTimer.OnTimer := OnTimer;
fSimTimer.OnTimer := OnSimTimer;
fIntTimer.OnTimer := OnIntTimer;
SetTimeRes( 1500, 1500, 30000 );
fSimThread.Priority := SimSpeed;
fSimThread.Resume;
// Init Integration thread
fIntegrationThread := TIntegrationThread.Create;
fIntegrationLock := TCriticalSection.Create;
TIntegrationThread(fIntegrationThread).fServer := self;
fIntegrationThread.Resume;
end;
procedure TModelServer.StartCacheServer( aCSPort : integer );
var
ServerConn : TWinSockRDOConnectionsServer;
begin
ServerConn := TWinSockRDOConnectionsServer.Create( aCSPort );
try
ModelServerCache.CreateCacheServer( ServerConn, 1, fWorld.WorldLock );
except
ServerConn.Free;
raise;
end;
end;
procedure TModelServer.StartDirectAccessServer( aDAPort : integer );
begin
fDAConn := TWinSockRDOConnectionsServer.Create( aDAPort ); // >> 100
fDAServ := TRDOServer.Create( fDAConn as IRDOServerConnection, 7, nil );
fDALockConn := TWinSockRDOConnectionsServer.Create( aDAPort + 1 ); // >> 20
fDALockServ := TRDOServer.Create( fDALockConn as IRDOServerConnection, 5, nil );
fDAServ.RegisterObject(tidRDOHook_World, integer(fWorld));
fDAConn.StartListening;
fDALockServ.RegisterObject(tidRDOHook_World, integer(fWorld));
fDALockConn.StartListening;
fDALockServ.SetCriticalSection( fWorld.WorldLock );
end;
procedure TModelServer.InitInterfaceServerEvents( ServerName : string; ServerPort : integer );
begin
fISConn := TWinSockRDOConnection.Create;
fISConn.Server := ServerName;
fISConn.Port := ServerPort;
fISEvents := TRDOObjectProxy.Create as IDispatch;
if fISConn.Connect( 10000 )
then
begin
fISEvents.SetConnection( fISConn );
fISEvents.BindTo( tidRDOHook_InterfaceEvents );
fWorld.OnAreaChanged := OnAreaChanged;
fWorld.OnFacilityChanged := OnFacilityChanged;
fWorld.OnDateChanged := OnDateChanged;
fWorld.OnTycoonsChanged := OnTycoonsChanged;
fWorld.OnEndOfPeriod := OnEndOfPeriod;
fWorld.OnTycoonRetired := OnTycoonRetired;
end
else raise Exception.Create( '' );
end;
procedure TModelServer.InitMailServer( ServerName : string; ServerPort : integer; WorldName : string );
begin
fMailConn := TWinSockRDOConnection.Create;
fMailConn.Server := ServerName;
fMailConn.Port := ServerPort;
fMailServer := TRDOObjectProxy.Create as IDispatch;
if fMailConn.Connect( 10000 )
then
begin
fMailServer.SetConnection(fMailConn);
fMailServer.BindTo(tidRDOHook_MailServer);
fMailId := fMailServer.RegisterWorld(WorldName);
if fMailId <> 0
then
begin
fMailServer.BindTo(fMailId);
if fMailServer.SetDAConnection((fMailConn as IRDOConnection).LocalAddress, fDALockPort)
then
begin
fMailServer.BindTo(tidRDOHook_MailServer);
fWorld.MailServer := self;
end
else raise Exception.Create( '' );
end
else raise Exception.Create( '' );
end
else raise Exception.Create( '' );
end;
procedure TModelServer.RegisterModelExtension( filename : string );
var
MDX : THandle;
begin
MDX := LoadLibrary( pchar(filename) );
if MDX <> 0
then
begin
RegisterMDX( MDX );
fExtensionList.Add( filename );
end
else raise Exception.Create( 'Cannot load extension file: ' + filename );
end;
procedure TModelServer.LoadExtensions;
type
PMDXNode = ^TMDXNode;
TMDXNode =
record
Id : string;
MDX : THandle;
Depends : TStringList;
SubNodes : TCollection;
registered : boolean;
end;
function GetMDXsFilenames : TStringList;
var
Reg : TRegistry;
Values : TStrings;
i : integer;
begin
result := TStringList.Create;
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey( tidRegKey_ModelExtensions, false )
then
begin
Values := TStringList.Create;
Reg.GetValueNames( Values );
for i := 0 to pred(Values.Count) do
result.Add( Reg.ReadString( Values[i] ));
Values.Free;
end;
finally
Reg.Free;
end;
end;
function LoadMDXs( filenames : TStringList ) : TCollection;
var
i : integer;
Node : PMDXNode;
begin
result := TCollection.Create( 0, rkUse );
for i := 0 to pred(filenames.Count) do
try
new( Node );
Node.MDX := LoadLibrary( pchar(filenames[i] ));
Node.Id := GetMDXId( Node.MDX );
Node.Depends := GetMDXDependances( Node.MDX );
Node.SubNodes := TCollection.Create( 0, rkUse );
Node.registered := false;
result.Insert( TObject(Node) );
except
raise Exception.Create( 'Could not load MDX: ' + filenames[i] )
end;
end;
function FindMDXNode( MDXNodes : TCollection; MDXId : string ) : PMDXNode;
var
i : integer;
begin
i := 0;
while (i < MDXNodes.Count) and (PMDXNode(MDXNodes[i]).Id <> MDXId) do
inc( i );
if i < MDXNodes.Count
then result := PMDXNode(MDXNodes[i])
else result := nil;
end;
procedure BuildMDXTree( MDXNodes : TCollection );
var
i, j : integer;
MDXNode : PMDXNode;
SuperMDXNode : PMDXNode;
begin
for i := 0 to pred(MDXNodes.Count) do
begin
MDXNode := PMDXNode(MDXNodes[i]);
for j := 0 to pred(MDXNode.Depends.Count) do
begin
SuperMDXNode := FindMDXNode( MDXNodes, MDXNode.Depends[j] );
if SuperMDXNode <> nil
then SuperMDXNode.SubNodes.Insert( TObject(MDXNode) );
end;
end;
end;
procedure RegisterMDXTree( MDXRootNode : PMDXNode );
var
i : integer;
begin
if not MDXRootNode.registered
then
begin
RegisterMDX( MDXRootNode.MDX );
MDXRootNode.registered := true;
for i := 0 to pred(MDXRootNode.SubNodes.Count) do
RegisterMDXTree( PMDXNode(MDXRootNode.SubNodes[i]) );
end;
end;
procedure RegisterMDXNodes( MDXNodes : TCollection );
var
i : integer;
begin
for i := 0 to pred(MDXNodes.Count) do
if PMDXNode(MDXNodes[i]).Depends.Count = 0
then RegisterMDXTree( PMDXNode(MDXNodes[i]) )
end;
procedure DisposeMDXNodes( MDXNodes : TCollection );
var
i : integer;
MDXNode : PMDXNode;
begin
for i := 0 to pred(MDXNodes.Count) do
begin
MDXNode := PMDXNode(MDXNodes[i]);
MDXNode.Depends.Free;
MDXNode.SubNodes.Free;
dispose( MDXNode );
end;
end;
var
MDXNodes : TCollection;
begin
MDXNodes := LoadMDXs( GetMDXsFilenames );
BuildMDXTree( MDXNodes );
RegisterMDXNodes( MDXNodes );
end;
procedure TModelServer.SetTimeRes( aVirtTimeRate, aSimRate, anIntRate : integer );
begin
fTimer.Interval := aVirtTimeRate;
fSimTimer.Interval := aSimRate;
fIntTimer.Interval := anIntRate;
end;
procedure TModelServer.OnTimer( Sender : TObject );
begin
fWorld.VirtualTimeTick( 1 );
end;
procedure TModelServer.OnSimTimer( Sender : TObject );
begin
fSimEv.SetEvent;
end;
procedure TModelServer.OnIntTimer( Sender : TObject );
begin
fIntEv.SetEvent;
end;
procedure TModelServer.OnAreaChanged( x, y, dx, dy : integer );
begin
try
fISEvents.RefreshArea( x, y, dx, dy );
except
end;
end;
procedure TModelServer.OnFacilityChanged( Facility : TFacility; FacilityChange : TFacilityChange );
begin
try
fISEvents.RefreshObject( integer(Facility), integer(FacilityChange) );
except
end;
end;
procedure TModelServer.OnTycoonsChanged;
begin
try
fISEvents.RefreshTycoons( 0 );
except
end;
end;
procedure TModelServer.OnDateChanged( Date : TDateTime );
begin
try
fISEvents.RefreshDate( Date );
except
end;
end;
procedure TModelServer.OnEndOfPeriod( PeriodType : TPeriodType; PeriodCount : integer );
begin
try
if PeriodType = perYear
then fISEvents.EndOfPeriod( 0 );
except
end;
end;
procedure TModelServer.OnTycoonRetired( name : string );
begin
try
fISEvents.TycoonRetired( name );
except
end;
end;
procedure TModelServer.StoreBackup( mode : TBackupMode );
var
Writer : IBackupWriter;
filename : string;
MemStream : TStream;
BckStream : TStream;
begin
try
case mode of
bmdShutdown :
begin
filename := fWorld.Name + '.world';
Writer := CreateBackup( fBaseDir + filename, false );
try
Writer.WriteObject( 'World', fWorld );
finally
Writer := nil;
end;
filename := fWorld.Name + '.verb';
Writer := CreateBackup( fBaseDir + filename, true );
try
Writer.WriteObject( 'World', fWorld );
finally
Writer := nil;
end;
end;
else
begin
if fLastBackup < 10
then inc( fLastBackup )
else fLastBackup := 1;
filename := fWorld.Name + '.' + IntToStr( fLastBackup ) + '.back';
MemStream := CreateBinaryBackup( fWorld );
try
// Set the event to start the simulation engine again! uff!!
// >> fBackupEvent.SetEvent;
BckStream := TFileStream.Create( fBaseDir + filename, fmCreate );
try
BckStream.CopyFrom( MemStream, MemStream.Size );
finally
// Lets say we've finished the file transfer operation. uff!!
// >> fBackupEvent.SetEvent;
BckStream.Free;
end;
finally
MemStream.Free;
end;
end;
end;
except
end;
end;
function TModelServer.QueryInterface(const IID: TGUID; out Obj): hresult; stdcall;
begin
pointer(Obj) := nil;
result := E_FAIL;
end;
function TModelServer._AddRef : integer; stdcall;
begin
result := 1;
end;
function TModelServer._Release : integer; stdcall;
begin
result := 1;
end;
function TModelServer.NewMailAccount(Account, Alias, FwdAddr : string; KeepMsg : boolean) : boolean;
begin
try
result := fMailServer.NewMailAccount(fMailId, Account, Alias, Fwdaddr, KeepMsg);
except
result := false;
end;
end;
function TModelServer.DeleteAccount(Account : string) : boolean;
begin
try
result := fMailServer.DeleteAccount(fMailId, Account);
except
result := false;
end;
end;
function TModelServer.SetForwardRule(Account, FwdAddr : string; KeepMsg : boolean) : boolean;
begin
try
result := fMailServer.SetForwardRule(fMailId, Account, FwdAddr, KeepMsg);
except
result := false;
end;
end;
function TModelServer.SendMessage(From, Dest, Subject : string; Lines : TStringList; html : boolean) : boolean;
var
Id : integer;
i : integer;
begin
try
Id := fMailServer.NewMail(From, Dest, Subject);
if Id <> 0
then
begin
fMailServer.BindTo(Id);
if html
then fMailServer.AddHeaders('ContentType=text/html');
for i := 0 to pred(Lines.Count) do
fMailServer.AddLine(Lines[i]);
fMailServer.BindTo(tidRDOHook_MailServer);
result := fMailServer.Post(fWorld.Name, Id);
fMailServer.CloseMessage(Id);
end
else result := false;
except
result := false;
end;
end;
function TModelServer.SendHTMLMessage(From, Dest, Subject, URL : string) : boolean;
var
List : TStringList;
begin
try
List := TStringList.Create;
try
List.Add('<HEAD>');
List.Add('<META HTTP-EQUIV="REFRESH" CONTENT="0; URL=' + URL + '">');
List.Add('</HEAD>');
result := SendMessage(From, Dest, Subject, List, true);
finally
List.Free;
end;
except
result := false;
end;
end;
end.
|
unit uHelloWorld;
interface
uses uEvo;
type
THelloWorld = class(TBFPrgValidatorBase)
protected
procedure GetInput(Index: integer; var S: string); override;
function ValidateResult: single; override;
class function CommandSet: string; override;
function MaxSteps: integer; override;
end;
implementation
uses Math, SysUtils;
function DamerauLevenshteinDistance(str1, str2: string): integer;
var
d: array of array of integer;
i, j, cost: integer;
begin
setlength(d, length(str1) + 1);
for i := 0 to high(d) do
begin
setlength(d[i], length(str2) + 1);
d[i, 0] := i;
end;
for j := 0 to high(d[0]) do
d[0, j] := j;
for i := 1 to high(d) do
for j := 1 to high(d[0]) do
begin
if (str1[i] = str2[j]) then
cost := 0 else
cost := 1;
d[i, j] := min(d[i - 1, j] + 1, // Löschen
min(d[i, j - 1] + 1, // Einfügen
d[i - 1, j - 1] + cost)); // Ersetzen
if ((i > 1) and (j > 1) and (str1[i - 1] = str2[j - 2]) and (str1[i - 2] = str2[j - 1])) then
d[i, j] := min(d[i, j], d[i - 2, j - 2] + cost);
end;
result := d[high(d), high(d[0])];
end;
{ THelloWorld }
class function THelloWorld.CommandSet: string;
begin
Result := '.<>[]-+';
end;
procedure THelloWorld.GetInput(Index: integer; var S: string);
begin
S := '0';
end;
function THelloWorld.MaxSteps: integer;
begin
Result := 2000;
end;
function THelloWorld.ValidateResult: single;
var lev:integer;
begin
lev:= DamerauLevenshteinDistance('Hello World!'#10,Output);
Result:= exp(-lev);
FProgram.Correct := 'Hello World!'#10 = Output;
end;
end.
|
unit ExtAI_DLLs;
interface
uses
IOUtils, Classes, System.SysUtils, Generics.Collections,
ExtAI_DLL, ExtAISharedInterface;
// Expected folder structure:
// - ExtAI
// - dll_delphi
// - dll_delphi.dll
// - dll_c
// - dll_c.dll
type
// List available DLLs
// Check presence of all valid DLLs (in future it can also check CRC, save info etc.)
TExtAIDLLs = class(TObjectList<TExtAI_DLL>)
private
fPaths: TStringList;
public
constructor Create(aDLLPaths: TStringList);
destructor Destroy(); override;
property Paths: TStringList read fPaths;
procedure RefreshList(aPaths: TStringList = nil);
function DLLExists(const aDLLPath: WideString): Boolean;
end;
implementation
uses
ExtAILog;
const
// Default paths for searching ExtAIs in DLL
DEFAULT_PATHS: TArray<string> = ['ExtAI\','..\..\..\ExtAI\','..\..\..\ExtAI\Delphi\Win32','..\..\ExtAI\Delphi\Win32'];
{ TExtAIDLLs }
constructor TExtAIDLLs.Create(aDLLPaths: TStringList);
var
Path: String;
begin
Inherited Create;
fPaths := TStringList.Create();
for Path in DEFAULT_PATHS do // Copy from generic to standard class
fPaths.Add(Path);
RefreshList(aDLLPaths); // Find available DLL (public method for possibility to reload DLLs)
end;
destructor TExtAIDLLs.Destroy();
begin
fPaths.Free;
Inherited;
end;
procedure TExtAIDLLs.RefreshList(aPaths: TStringList = nil);
var
K: Integer;
subFolder, fileDLL: string;
begin
Clear();
if (aPaths <> nil) then
begin
fPaths.Clear();
fPaths.Capacity := aPaths.Count;
for K := 0 to aPaths.Count - 1 do
fPaths.Add(aPaths[K]);
end;
fileDLL := GetCurrentDir;
for K := 0 to fPaths.Count - 1 do
if DirectoryExists(fPaths[K]) then
for subFolder in TDirectory.GetDirectories(fPaths[K]) do
for fileDLL in TDirectory.GetFiles(subFolder) do
if ExtractFileExt(fileDLL) = '.dll' then
begin
gLog.Log('TExtAIDLLs: New DLL - %s', [fileDLL]);
Add(TExtAI_DLL.Create(fileDLL));
end;
end;
function TExtAIDLLs.DLLExists(const aDLLPath: WideString): Boolean;
var
K: Integer;
begin
Result := False;
for K := 0 to Count-1 do
if CompareStr(Items[K].Config.Path, aDLLPath) = 0 then
Exit(True);
end;
end. |
unit Unit1;
//https://developers.google.com/chrome-developer-tools/docs/protocol/tot/runtime
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, ComCtrls,
SynEdit, SynHighlighterDWS, SynEditHighlighter, SynHighlighterJScript,
dwsJSFilter, dwsComp, dwsCompiler, dwsHtmlFilter, dwsExprs,
dorWebsocket, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
IdHTTP, superobject;
type
TForm1 = class(TForm)
SynJScriptSyn1: TSynJScriptSyn;
SynDWSSyn1: TSynDWSSyn;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
synedtDWS: TSynEdit;
Panel1: TPanel;
synedtJS: TSynEdit;
btnCompileAndRun: TButton;
tsRemoteDebug: TTabSheet;
Memo1: TMemo;
btnConnect: TButton;
IdHTTP1: TIdHTTP;
btnLoadDebugScript: TButton;
tsRemoteJS: TTabSheet;
Panel2: TPanel;
Label1: TLabel;
lbStack: TListBox;
Label2: TLabel;
lbScope: TListBox;
Splitter1: TSplitter;
Label3: TLabel;
lbProperties: TListBox;
Panel3: TPanel;
btnPause: TButton;
btnContinue: TButton;
btnStepOver: TButton;
btnStepInto: TButton;
pgRemoteJS: TPageControl;
tsRemoteJS_JS: TTabSheet;
tsRemoteJS_DWS: TTabSheet;
synedtRemoteJS: TSynEdit;
synedtRemoteDWS: TSynEdit;
tsEmbeddedChrome: TTabSheet;
procedure FormCreate(Sender: TObject);
procedure btnCompileAndRunClick(Sender: TObject);
procedure btnConnectClick(Sender: TObject);
procedure btnLoadDebugScriptClick(Sender: TObject);
procedure synedtRemoteJSDblClick(Sender: TObject);
procedure lbStackDblClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lbScopeDblClick(Sender: TObject);
procedure btnContinueClick(Sender: TObject);
procedure btnPauseClick(Sender: TObject);
procedure btnStepOverClick(Sender: TObject);
procedure btnStepIntoClick(Sender: TObject);
procedure synedtRemoteJSMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure synedtRemoteDWSMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
private
FFilter: TdwsJSFilter;
FHtmlFilter: TdwsHtmlFilter;
FDWSMain: TDelphiWebScript;
FDWSJS: TDelphiWebScript;
private
FWebS : IWebSocket;
FseqNo: Integer;
FScripts: TStrings;
FStackList: TInterfaceList;
FScopeList: TInterfaceList;
procedure ConnectWebsocket(const aHost: string = 'localhost'; aPort: Integer = 9222);
procedure HandleWSMessage(const aData: string);
procedure HandleWSPaused(const aJSON: ISuperObject);
procedure UpdateDebuggerState(aRunning: boolean);
procedure ActiveStack(const aCallFrame: ISuperObject);
procedure LoadScope(const aCallFrame: ISuperObject);
procedure ActiveScope(const aScope: ISuperObject);
procedure ShowHintForVar(const aVarName: string; aControl: TControl);
procedure ws_EnableDebugger;
procedure ws_PauseDebugger;
procedure ws_ContinueDebugger;
procedure ws_StepIntoDebugger;
procedure ws_StepOverDebugger;
procedure ws_SetBreakpoint(aLine: Integer);
procedure ws_LoadScript(const aScriptID: string);
procedure ws_GetObjectProperties(const aObjectId: string);
public
end;
var
Form1: TForm1;
implementation
uses
ShellAPI, StrUtils;
{$R *.dfm}
procedure TForm1.btnConnectClick(Sender: TObject);
begin
ConnectWebsocket();
//start the debugger
Inc(FseqNo);
ws_EnableDebugger();
tsRemoteDebug.TabVisible := True;
PageControl1.ActivePage := tsRemoteDebug;
end;
procedure TForm1.btnContinueClick(Sender: TObject);
begin
ws_ContinueDebugger;
end;
procedure TForm1.btnLoadDebugScriptClick(Sender: TObject);
var
sid: string;
begin
sid := FScripts.Names[FScripts.Count-1];
ws_LoadScript(sid);
end;
procedure TForm1.btnPauseClick(Sender: TObject);
begin
ws_PauseDebugger;
end;
procedure TForm1.btnStepIntoClick(Sender: TObject);
begin
ws_StepIntoDebugger;
end;
procedure TForm1.btnStepOverClick(Sender: TObject);
begin
ws_StepOverDebugger;
end;
procedure TForm1.ConnectWebsocket(const aHost: string = 'localhost'; aPort: Integer = 9222);
var
node, json: ISuperObject;
strm: TMemoryStream;
begin
//first we must connect via http
strm := TMemoryStream.Create;
try
IdHTTP1.Get( Format('http://%s:%d/json',[aHost, aPort]), strm);
//Memo1.Lines.LoadFromStream(strm);
//Memo2.Clear;
json := TSuperObject.ParseStream(strm, False);
for node in json do
Memo1.Lines.Add( node.S['title'] + '=' + node.S['webSocketDebuggerUrl'] );
finally
strm.Free;
end;
FScripts.Free;
FScripts := TStringList.Create;
//then connect via websocket
if FWebS = nil then
FWebS := TWebSocket.Create
else
FWebS.Close;
tsRemoteDebug.TabVisible := True;
//message handler (for processing results)
FWebS.OnMessage :=
procedure(const msg: string)
begin
HandleWSMessage(msg);
end;
//we assume we are the only page, so page 1
FWebS.Open( Format('ws://%s:%d/devtools/page/1', [aHost, aPort]) );
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FHtmlFilter := TdwsHtmlFilter.Create(Self);
// PatternClose = '?>'
// PatternEval = '='
// PatternOpen = '<?'
FDWSMain := TDelphiWebScript.Create(Self);
FDWSMain.Config.Filter := FHtmlFilter;
FDWSMain.AddUnit(TdwsHTMLUnit.Create(Self));
FDWSJS := TDelphiWebScript.Create(Self);
FFilter := TdwsJSFilter.Create(Self);
FFilter.Compiler := FDWSJS;
FHtmlFilter.SubFilter := FFilter;
PageControl1.ActivePageIndex := 0;
pgRemoteJS.ActivePageIndex := 0;
synedtJS.Clear;
synedtRemoteJS.Clear;
Memo1.Clear;
tsRemoteDebug.TabVisible := False;
tsRemoteJS.TabVisible := False;
btnLoadDebugScript.Enabled := False;
FStackList := TInterfaceList.Create;
FScopeList := TInterfaceList.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FScopeList.Free;
FStackList.Free;
FHtmlFilter.Free;
FDWSMain.Free;
FDWSJS.Free;
FFilter.Free;
FWebS := nil;
FScripts.Free;
end;
procedure TForm1.HandleWSMessage(const aData: string);
var
json, result, params, propdescr: ISuperObject;
resultarray: TSuperArray;
sScript: string;
sLog: string;
i: Integer;
begin
json := SO(aData);
if json.S['error'] <> '' then
MessageDlg(aData, mtError, [mbOK], 0);
//Debugger.enable
if json.S['method'] = 'Debugger.scriptParsed' then
begin
params := json.O['params'];
if (params <> nil) and (params.S['url'] <> '') then
begin
Memo1.Lines.Add( params.S['scriptId'] + '=' + params.S['url'] );
FScripts.Add ( params.S['scriptId'] + '=' + params.S['url'] );
btnLoadDebugScript.Enabled := True;
end
else
Exit; //skip empty url's -> come from "setInterval" or "setTimeout"
end;
//Debugger.getScriptSource
result := json.O['result'];
if result <> nil then
begin
sScript := result.S['scriptSource'];
if sScript <> '' then
begin
synedtRemoteJS.Lines.Text := sScript;
tsRemoteJS.TabVisible := True;
PageControl1.ActivePage := tsRemoteJS;
UpdateDebuggerState(True{running});
end;
end;
//Runtime.getProperties
(*
response: {
"id": <number>,
"error": <object>,
"result": {
"result": <array of PropertyDescriptor>
}
}
*)
if result <> nil then
begin
resultarray := result.N['result'].AsArray;
if resultarray <> nil then
for i := 0 to resultarray.Length - 1 do
begin
propdescr := resultarray.O[i];
if propdescr = nil then Continue;
lbProperties.Items.Add( Format('%s = %s (%s)', [propdescr.S['name'], propdescr.N['value'].S['value'], propdescr.AsJSon()]) );
end;
end;
(* {"result":
{"breakpointId":"22:13:0",
"actualLocation":
{"scriptId":"22",
"lineNumber":13,
"columnNumber":3}
},
"id":3} *)
//Debugger.setBreakpoint
if json.S['method'] = 'Debugger.paused' then
HandleWSPaused(json);
sLog := StringReplace(aData, #13, '', [rfReplaceAll]);
sLog := StringReplace(sLog , #10, '', [rfReplaceAll]);
Memo1.Lines.Add( FormatDateTime('hh:nn:ss:zzz', Now) + ' - ' + sLog);
end;
procedure TForm1.HandleWSPaused(const aJSON: ISuperObject);
var
params, callFrame: ISuperObject;
callFrames: TSuperArray;
i: Integer;
sFunc: string;
begin
UpdateDebuggerState(False{paused});
params := aJSON.O['params'];
if params = nil then Exit;
callFrames := params.N['callFrames'].AsArray;
lbStack.Clear;
FStackList.Clear;
lbScope.Clear;
FScopeList.Clear;
lbProperties.Clear;
for i := 0 to callFrames.Length - 1 do
begin
callFrame := callFrames.O[i];
if callFrame = nil then Continue;
sFunc := callFrame.S['functionName'];
if sFunc = '' then
sFunc := '(anonymous)';
lbStack.Items.AddObject(sFunc, nil); //TObject(callFrame.Clone));
FStackList.Add(callFrame.Clone);
//use top of stack: goto line in editor etc
if i = 0 then
begin
lbStack.ItemIndex := 0;
ActiveStack(callFrame);
end;
end;
(* {"method":"Debugger.paused",
"params":
{"callFrames":
[{"callFrameId":"{\"ordinal\":0,\"injectedScriptId\":1}",
"functionName":"Mandel",
"location": {"scriptId":"22",
"lineNumber":13,
"columnNumber":3},
"scopeChain":[{"object":{
"type":"object",
"objectId":"{\"injectedScriptId\":1,\"id\":1}",
"className":"Object",
"description":"Object"},
"type":"local"},
{"object":{
"type":"object",
"objectId":"{\"injectedScriptId\":1,\"id\":2}",
"className":"DOMWindow",
"description":"DOMWindow"},
"type":"global"}],
"this":{
"type":"object",
"objectId":"{\"injectedScriptId\":1,\"id\":3}",
"className":"DOMWindow",
"description":"DOMWindow"}
},
{"callFrameId":"{\"ordinal\":1,\"injectedScriptId\":1}",
"functionName":"calcAndShowMandel",
"location":{"scriptId":"22",
"lineNumber":61,
"columnNumber":3},
"scopeChain":[{"object":{
"type":"object",
"objectId":"{\"injectedScriptId\":1,\"id\":4}",
"className":"Object",
"description":"Object"},
"type":"local"},
{"object":{
"type":"object",
"objectId":"{\"injectedScriptId\":1,\"id\":5}",
"className":"DOMWindow",
"description":"DOMWindow"},
"type":"global"}],
"this":{"type":"object",
"objectId":"{\"injectedScriptId\":1,\"id\":6}",
"className":"DOMWindow",
"description":"DOMWindow"}},
{"callFrameId":"{\"ordinal\":2,\"injectedScriptId\":1}",
"functionName":"",
"location":{"scriptId":"137","lineNumber":0,"columnNumber":0},"scopeChain":[{"object":{"type":"object","objectId":"{\"injectedScriptId\":1,\"id\":7}","className":"DOMWindow","description":"DOMWindow"},"type":"global"}],"this":{"type":"object","objectId":"{\"injectedScriptId\":1,\"id\":8}","className":"DOMWindow","description":"DOMWindow"}}],
"reason":"other"}} *)
end;
procedure TForm1.lbScopeDblClick(Sender: TObject);
var
scope: ISuperObject;
begin
scope := FScopeList.Items[lbScope.ItemIndex] as ISuperObject;
ActiveScope(scope);
end;
procedure TForm1.ActiveScope(const aScope: ISuperObject);
var
obj: ISuperObject;
begin
lbProperties.Clear;
if aScope = nil then Exit;
obj := aScope.O['object'];
if obj = nil then Exit;
ws_GetObjectProperties(obj.S['objectId']);
end;
procedure TForm1.lbStackDblClick(Sender: TObject);
var
callFrame: ISuperObject;
begin
callFrame := FStackList.Items[lbStack.ItemIndex] as ISuperObject;
ActiveStack(callFrame);
end;
procedure TForm1.ActiveStack(const aCallFrame: ISuperObject);
var
location: ISuperObject;
pos, posend: TBufferCoord;
sLine: string;
iLine,
iOffset: Integer;
i: Integer;
begin
location := aCallFrame.O['location'];
if location = nil then Exit;
//ws_LoadScript();
iLine := location.I['lineNumber'] - 1;
synedtRemoteJS.GotoLineAndCenter(iLine);
//synedtRemoteJS.GotoBookMark(1);
pos.Line := iLine;
pos.Char := 0;
posend := pos;
sLine := synedtRemoteJS.LineText;
posend.Char := Length(sLine);
synedtRemoteJS.SetCaretAndSelection(pos, pos, posend);
// /*@14*/for(i=0;i<=498;i++) {
if System.Pos('/*@', sLine) > 0 then
begin
pgRemoteJS.ActivePage := tsRemoteJS_DWS;
iOffset := 0;
for i := 0 to synedtRemoteDWS.Lines.Count - 1 do
begin
if System.Pos('<%pas2js', synedtRemoteDWS.Lines[i]) > 0 then
begin
iOffset := i + 1;
Break;
end;
end;
synedtRemoteDWS.GotoLineAndCenter(iLine + iOffset);
pos.Line := iLine + iOffset;
pos.Char := 0;
posend := pos;
sLine := synedtRemoteDWS.LineText;
posend.Char := Length(sLine) + 1;
synedtRemoteDWS.SetCaretAndSelection(pos, pos, posend);
synedtRemoteDWS.SetFocus;
end
else
begin
pgRemoteJS.ActivePage := tsRemoteJS_JS;
synedtRemoteJS.SetFocus;
end;
LoadScope(aCallFrame);
end;
procedure TForm1.LoadScope(const aCallFrame: ISuperObject);
var
scope, obj: ISuperObject;
scopeChain: TSuperArray;
j: Integer;
begin
lbScope.Clear;
FScopeList.Clear;
lbProperties.Clear;
scopeChain := aCallFrame.N['scopeChain'].AsArray;
if scopeChain <> nil then
for j := 0 to scopeChain.Length - 1 do
begin
scope := scopeChain.O[j];
if scope = nil then Continue;
obj := scope.O['object'];
if obj = nil then Continue;
lbScope.Items.AddObject( Format('%s: %s(%s) - %s', [scope.S['type'], obj.S['className'],
obj.S['description'], obj.S['objectId']]),
nil);//TObject(scope.Clone) );
FScopeList.Add(scope.Clone);
//load properties of first scope
if j = 0 then
begin
lbScope.ItemIndex := 0;
ActiveScope(scope);
end;
end;
end;
procedure TForm1.ShowHintForVar(const aVarName: string; aControl: TControl);
var
ptMouse: TPoint;
iItem: integer;
i: Integer;
s: string;
begin
aControl.Hint := '';
aControl.ShowHint := False;
if aVarName <> '' then
begin
s := aVarName + ' =';
iItem := -1;
for i := 0 to lbProperties.Items.Count - 1 do
begin
if StartsText(s, lbProperties.Items.Strings[i]) then
begin
iItem := i;
Break;
end;
end;
if iItem < 0 then Exit;
aControl.Hint := lbProperties.Items.Strings[iItem];
aControl.ShowHint := True;
GetCursorPos(ptMouse);
Application.ActivateHint(ptMouse);
Application.HintPause := 0; //direct show
Application.HintHidePause := 15 * 1000; //show 15s
end;
end;
procedure TForm1.synedtRemoteDWSMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
ShowHintForVar(synedtRemoteDWS.WordAtMouse, synedtRemoteDWS);
end;
procedure TForm1.synedtRemoteJSDblClick(Sender: TObject);
var
ptMouse, ptClient: TPoint;
iLine: Integer;
begin
GetCursorPos(ptMouse);
ptClient := synedtRemoteJS.ScreenToClient(ptMouse);
if ptClient.X < synedtRemoteJS.Gutter.Width then
begin
iLine := synedtRemoteJS.DisplayToBufferPos(
synedtRemoteJS.PixelsToRowColumn(ptClient.X, ptClient.Y)
).Line;
synedtRemoteJS.SetBookMark(1, 0, iLine);
ws_SetBreakpoint(iLine);
end;
end;
procedure TForm1.synedtRemoteJSMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
ShowHintForVar(synedtRemoteJS.WordAtMouse, synedtRemoteJS);
end;
procedure TForm1.UpdateDebuggerState(aRunning: boolean);
begin
btnPause.Enabled := aRunning;
btnContinue.Enabled := not aRunning;
btnStepOver.Enabled := not aRunning;
btnStepInto.Enabled := not aRunning;
if aRunning then
begin
lbStack.Clear;
lbScope.Clear;
lbProperties.Clear;
FStackList.Clear;
FScopeList.Clear;
end;
end;
procedure TForm1.ws_ContinueDebugger;
var s: string;
begin
UpdateDebuggerState(True{running});
s := '{"id":%d,' +
'"method":"Debugger.resume"' +
'}';
s := Format(s, [FseqNo]);
FWebS.Send(s);
Inc(FseqNo);
end;
procedure TForm1.ws_EnableDebugger;
var
s: string;
begin
// FWebS.OnMessage :=
// procedure(const msg: string)
// var
// json, params: ISuperObject;
// begin
// json := SO(msg);
// if json.S['error'] <> '' then
// ShowMessage(msg);
//
// (*
// "method": "Debugger.scriptParsed",
// "params": {
// "scriptId": <ScriptId>,
// "url": <string>,
// "startLine": <integer>,
// "startColumn": <integer>,
// "endLine": <integer>,
// "endColumn": <integer>,
// "isContentScript": <boolean>,
// "sourceMapURL": <string>
// }
// *)
//
// if json.S['method'] = 'Debugger.scriptParsed' then
// begin
// params := json.N['params'];
// if params.S['url'] <> '' then
// begin
// Memo1.Lines.Add( params.S['scriptId'] + '=' + params.S['url'] );
// FScripts.Add ( params.S['scriptId'] + '=' + params.S['url'] );
// end;
// end;
// end;
(*
request: {
"id": <number>,
"method": "Debugger.enable"
*)
s := '{"id":%d,' +
'"method":"Debugger.enable"' +
'}';
s := Format(s, [FseqNo]);
FWebS.Send(s);
Inc(FseqNo);
end;
procedure TForm1.ws_GetObjectProperties(const aObjectId: string);
var
s, sobjid: string;
begin
lbProperties.Clear;
s := '{"id":%d,' +
'"method":"Runtime.getProperties",' +
'"params":{"objectId":"%s"' +
'}' +
'}';
sobjid := StringReplace(aObjectId, '"', '\"', [rfReplaceAll]);
s := Format(s, [FseqNo, sobjid]);
FWebS.Send(s);
Inc(FseqNo);
end;
procedure TForm1.ws_LoadScript(const aScriptID: string);
var
s, sid: string;
begin
s := '{"id":%d,' +
'"method":"Debugger.getScriptSource",' +
'"params":{"scriptId":"%s"' +
'}' +
'}';
//if InputQuery('ScriptID', 'ScriptID: ', sid) then
if sid = '' then
sid := FScripts.Names[FScripts.Count-1] //last known scriptid
else
sid := aScriptID;
s := Format(s, [FseqNo, sid]);
FWebS.Send(s);
Inc(FseqNo);
end;
procedure TForm1.ws_PauseDebugger;
var s: string;
begin
s := '{"id":%d,' +
'"method":"Debugger.pause"' +
'}';
s := Format(s, [FseqNo]);
FWebS.Send(s);
Inc(FseqNo);
end;
procedure TForm1.ws_SetBreakpoint(aLine: Integer);
var
s, sid: string;
begin
// FWebS.OnMessage :=
// procedure(const msg: string)
// begin
// Showmessage(msg);
// end;
(*
request: {
"id": <number>,
"method": "Debugger.setBreakpoint",
"params": {
"location": <Location>,
"condition": <string> } }
*)
s := '{"id":%d,' +
'"method":"Debugger.setBreakpoint",' +
'"params":{"location":{"lineNumber":%d,"scriptId":"%s"}' +
'}' +
'}';
//if not InputQuery('ScriptID', 'ScriptID: ', sid) then Exit;
//if not InputQuery('lineNumber', 'lineNumber: ', sline) then Exit;
sid := FScripts.Names[FScripts.Count-1];
s := Format(s, [FseqNo, aLine + 1, sid]);
FWebS.Send(s);
Inc(FseqNo);
(*
request: {
"id": <number>,
"method": "Debugger.setBreakpointsActive",
"params": {
"active": <boolean> } }
*)
s := '{"id":%d,' +
'"method":"Debugger.setBreakpointsActive",' +
'"params":{"active":true' +
'}' +
'}';
s := Format(s, [FseqNo]);
FWebS.Send(s);
Inc(FseqNo);
end;
procedure TForm1.ws_StepIntoDebugger;
var s: string;
begin
UpdateDebuggerState(True{running});
s := '{"id":%d,' +
'"method":"Debugger.stepInto"' +
'}';
s := Format(s, [FseqNo]);
FWebS.Send(s);
Inc(FseqNo);
end;
procedure TForm1.ws_StepOverDebugger;
var s: string;
begin
UpdateDebuggerState(True{running});
s := '{"id":%d,' +
'"method":"Debugger.stepOver"' +
'}';
s := Format(s, [FseqNo]);
FWebS.Send(s);
Inc(FseqNo);
end;
procedure TForm1.btnCompileAndRunClick(Sender: TObject);
var
prog : IdwsProgram;
exec : IdwsProgramExecution;
sOutput : String;
sUrl: string;
var
h: THandle;
Style, ExStyle: Cardinal;
begin
synedtRemoteDWS.Text := synedtDWS.Text;
prog := FDWSMain.Compile(synedtDWS.Lines.Text);
if prog.Msgs.HasErrors then
begin
// MEOutput.Lines.Text := prog.Msgs.AsInfo;
// PageControl1.ActivePageIndex:=2;
MessageDlg(prog.Msgs.AsInfo, mtError, [mbOK], 0);
Exit;
end;
//execute "print" script
exec := prog.Execute;
if exec.Msgs.Count>0 then
begin
MessageDlg(prog.Msgs.AsInfo, mtError, [mbOK], 0);
// MEOutput.Lines.Text:=prog.Msgs.AsInfo;
// PageControl1.ActivePageIndex:=2;
Exit;
end;
soutput := exec.Result.ToString;
synedtJS.Lines.Text := soutput;
PageControl1.ActivePageIndex := 1;
synedtJS.Lines.SaveToFile('output.html');
//Chromium.Browser.MainFrame.LoadString(output, 'test');
//sUrl := '--app=file:///C:/-Andre-/-Projects-/dwscript/Demos/RemoteDebug/output.html';
sUrl := '--app=file:///' + ExtractFilePath(Application.ExeName) + 'output.html' +
' --remote-debugging-port=9222 --user-data-dir=dwsremotetest';
ShellExecute(self.WindowHandle, 'open', 'chrome.exe', PChar(sUrl), nil, SW_SHOWMINIMIZED);
h := 0;
while h = 0 do
begin
h := Windows.FindWindow(nil, 'DwsRemoteChrome');
Sleep(100);
end;
Windows.ShowWindow(h, SW_NORMAL);
Windows.SetParent(h, tsEmbeddedChrome.Handle);
Windows.MoveWindow(h, 0, 0, Self.Width, Self.Height, False);
Style := GetWindowLong(h, GWL_STYLE);
ExStyle := GetWindowLong(h, GWL_EXSTYLE);
//Self.BorderStyle := bsNone;
Style := Style and not (WS_POPUP or WS_CAPTION or WS_BORDER or WS_THICKFRAME or WS_DLGFRAME or DS_MODALFRAME);
ExStyle := ExStyle and not (WS_EX_DLGMODALFRAME or WS_EX_WINDOWEDGE or WS_EX_TOOLWINDOW);
SetWindowLong(h, GWL_STYLE, Style);
SetWindowLong(h, GWL_EXSTYLE, ExStyle);
PageControl1.ActivePage := tsEmbeddedChrome;
end;
end.
|
unit SimulacaoPagamento.Cartao;
interface
uses
SimulacaoPagamento.Interfaces;
type
TSimulacaoPagamentoCartao = class(TInterfacedObject, iSimulacaoCartao)
private
[Weak]
FParent : iSimulacaoPagamento;
FBandeira : String;
public
constructor Create(Parent : iSimulacaoPagamento);
destructor Destroy; override;
class function New(Parent : iSimulacaoPagamento) : iSimulacaoCartao;
function Bandeira ( aValue : String ) : iSimulacaoCartao; overload;
function Bandeira : String; overload;
function &End : iSimulacaoPagamento;
end;
implementation
{ TSimulacaoPagamentoCartao }
function TSimulacaoPagamentoCartao.Bandeira(aValue: String): iSimulacaoCartao;
begin
Result := Self;
FBandeira := aValue;
end;
function TSimulacaoPagamentoCartao.&End: iSimulacaoPagamento;
begin
Result := FParent;
end;
function TSimulacaoPagamentoCartao.Bandeira: String;
begin
Result := FBandeira;
end;
constructor TSimulacaoPagamentoCartao.Create(Parent : iSimulacaoPagamento);
begin
FParent := Parent;
end;
destructor TSimulacaoPagamentoCartao.Destroy;
begin
inherited;
end;
class function TSimulacaoPagamentoCartao.New(Parent : iSimulacaoPagamento) : iSimulacaoCartao;
begin
Result := Self.Create(Parent);
end;
end.
|
unit UGContactsDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.TMSCloudBase, FMX.TMSCloudGContacts,
FMX.Layouts, FMX.ListBox, FMX.Edit, FMX.Objects, FMX.TMSCloudImage, FMX.Memo, IOUtils,
FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomGoogle, FMX.TMSCloudGoogleFMX,
FMX.TMSCloudCustomGContacts;
type
TForm82 = class(TForm)
ToolBar1: TToolBar;
Button1: TButton;
Button2: TButton;
TMSFMXCloudGContacts1: TTMSFMXCloudGContacts;
Button3: TButton;
lbGroups: TListBox;
Line1: TLine;
Panel1: TPanel;
Panel2: TPanel;
ListBox1: TListBox;
Button4: TButton;
edGroupName: TEdit;
TMSFMXCloudImage1: TTMSFMXCloudImage;
Label11: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
lbName: TLabel;
meNotes: TMemo;
Label1: TLabel;
Label2: TLabel;
procedure Button1Click(Sender: TObject);
procedure TMSFMXCloudGContacts1ReceivedAccessToken(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure lbGroupsChange(Sender: TObject);
procedure btGroupAddClick(Sender: TObject);
procedure btGroupUpdateClick(Sender: TObject);
procedure btGroupDeleteClick(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ListBox1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Connected: boolean;
Inserting: boolean;
procedure FillContacts;
procedure FillContactDetails;
procedure FillGroups(Update: Boolean);
procedure ToggleControls;
procedure ClearControls;
end;
var
Form82: TForm82;
implementation
{$R *.fmx}
// PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET
// FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE
// STRUCTURE OF THIS .INC FILE SHOULD BE
//
// const
// GAppkey = 'xxxxxxxxx';
// GAppSecret = 'yyyyyyyy';
{$I APPIDS.INC}
procedure TForm82.btGroupAddClick(Sender: TObject);
var
gr: TGGroup;
begin
gr := TMSFMXCloudGContacts1.Groups.Add;
gr.Summary := edGroupName.Text;
TMSFMXCloudGContacts1.AddGroup(gr);
FillGroups(False);
end;
procedure TForm82.btGroupDeleteClick(Sender: TObject);
var
gg: TGGroup;
buttonSelected: integer;
begin
if lbGroups.ItemIndex >= 0 then
begin
buttonSelected := MessageDlg('Are you sure you want to delete the selected Group?', TMsgDlgType.mtConfirmation, mbOKCancel, 0);
if buttonSelected = mrOk then
begin
gg := lbGroups.Items.Objects[lbGroups.ItemIndex] as TGGroup;
TMSFMXCloudGContacts1.DeleteGroup(gg);
FillGroups(False);
end;
end
else
ShowMessage('Please select a Group first');
end;
procedure TForm82.btGroupUpdateClick(Sender: TObject);
var
gg: TGGroup;
begin
if lbGroups.ItemIndex >= 0 then
begin
gg := lbGroups.Items.Objects[lbGroups.ItemIndex] as TGGroup;
gg.Summary := edGroupName.Text;
TMSFMXCloudGContacts1.UpdateGroup(gg);
FillGroups(False);
end
else
ShowMessage('Please select a Group first');
end;
procedure TForm82.Button1Click(Sender: TObject);
var
acc: boolean;
begin
TMSFMXCloudGContacts1.App.Key := GAppkey;
TMSFMXCloudGContacts1.App.Secret := GAppSecret;
TMSFMXCloudGContacts1.Logging := true;
if TMSFMXCloudGContacts1.App.Key <> '' then
begin
TMSFMXCloudGContacts1.PersistTokens.Key := TPath.GetDocumentsPath + '/google.ini';
TMSFMXCloudGContacts1.PersistTokens.Section := 'tokens';
TMSFMXCloudGContacts1.LoadTokens;
acc := TMSFMXCloudGContacts1.TestTokens;
if not acc then
begin
TMSFMXCloudGContacts1.RefreshAccess;
TMSFMXCloudGContacts1.DoAuth;
end
else
begin
Connected := true;
ToggleControls;
end;
end
else
ShowMessage('Please provide a valid application ID for the client component');
end;
procedure TForm82.Button2Click(Sender: TObject);
begin
TMSFMXCloudGContacts1.ClearTokens;
Connected := false;
ClearControls;
lbGroups.Items.Clear;
ListBox1.Clear;
ToggleControls;
end;
procedure TForm82.Button3Click(Sender: TObject);
begin
FillGroups(True);
end;
procedure TForm82.Button4Click(Sender: TObject);
begin
FillContacts;
end;
procedure TForm82.ClearControls;
begin
end;
procedure TForm82.FillContactDetails;
var
gc: TGContact;
begin
if Assigned(ListBox1.Selected) then
begin
gc := ListBox1.Selected.Data as TGContact;
lbName.Text := gc.FirstName + ' ' +gc.LastName;
meNotes.Lines.Text := gc.Notes;
Label6.Text := gc.Company + ' ' +gc.JobTitle;
Label5.Text := DateToStr(gc.BirthDay);
TMSFMXCloudImage1.URL := gc.ImageURL;
end;
end;
procedure TForm82.FillContacts;
var
i: integer;
str: string;
begin
ListBox1.Items.Clear;
TMSFMXCloudgcontacts1.GetContacts;
ListBox1.BeginUpdate;
for i := 0 to TMSFMXCloudgcontacts1.Contacts.Count - 1 do
begin
str := Trim(TMSFMXCloudgcontacts1.Contacts[i].Title);
if str <> '' then
listbox1.Items.AddObject(str, TMSFMXCloudGContacts1.Contacts[i]);
end;
ListBox1.EndUpdate;
end;
procedure TForm82.FillGroups(Update: Boolean);
var
i: integer;
begin
if Update then
TMSFMXCloudgcontacts1.GetContactGroups;
lbGroups.Items.Clear;
for i := 0 to TMSFMXCloudgcontacts1.Groups.Count - 1 do
lbGroups.Items.AddObject(TMSFMXCloudgcontacts1.Groups[i].Summary, TMSFMXCloudGContacts1.Groups[i]);
end;
procedure TForm82.FormCreate(Sender: TObject);
begin
Connected := False;
ToggleControls;
end;
procedure TForm82.lbGroupsChange(Sender: TObject);
var
gg: TGGroup;
begin
if lbGroups.ItemIndex >= 0 then
begin
gg := lbGroups.Items.Objects[lbGroups.ItemIndex] as TGGroup;
edGroupName.Text := gg.Summary;
end;
end;
procedure TForm82.ListBox1Change(Sender: TObject);
begin
FillContactDetails;
end;
procedure TForm82.TMSFMXCloudGContacts1ReceivedAccessToken(Sender: TObject);
begin
TMSFMXCloudGContacts1.SaveTokens;
Connected := true;
ToggleControls;
end;
procedure TForm82.ToggleControls;
begin
Panel1.Enabled := Connected;
Panel2.Enabled := Connected;
Button1.Enabled := not Connected;
Button2.Enabled := Connected;
end;
end.
|
unit Providers.Consts;
interface
uses ToolsAPI;
const
C_BPL_FOLDER = '.bpl';
C_BIN_FOLDER = '.bin';
C_MODULES_FOLDER = 'modules\';
C_BOSS_CACHE_FOLDER = '.boss';
C_DATA_FILE = 'boss.ide';
C_BOSS_TAG = '[Boss]';
C_BUTTON_SEPARATOR_POSITION = pmmpRunNoDebug + 10;
C_BUTTON_INSTALL_POSITION = pmmpRunNoDebug + 20;
implementation
end.
|
{
Criador: Bruno Deuner
Contato
Email: bruno_deuner@hotmail.com
Informações
Autorização de contas:
Gmail: https://myaccount.google.com/lesssecureapps
Hotmail: Não precisa
}
unit Tora.Email;
interface
uses
System.Classes,
System.Generics.Collections,
System.SysUtils,
System.RegularExpressions,
Inifiles,
IdSMTP,
IdSSLOpenSSL,
IdMessage,
IdText,
IdAttachmentFile,
IdExplicitTLSClientServerBase,
IdEMailAddress,
IdPOP3,
IdAssignedNumbers;
type
{ Exceptions }
EEmailError = class;
EConnectError = class;
EAuthentError = class;
ESendError = class;
EReceiveError = class;
EEmailError = class(Exception)
private type
TEKind = (eUnknown, eConnect, eAuthent, eSend, eReceive);
private
FKind: TEKind;
procedure SetKind(const Value: TEKind);
public
property Kind: TEKind read FKind write SetKind default eUnknown;
constructor Create; overload;
constructor Create(Msg: String; Kind: TEKind); overload; virtual;
end;
EConnectError = class(EEmailError)
constructor Create(const Msg: string);
end;
EAuthentError = class(EEmailError)
constructor Create(const Msg: string);
end;
ESendError = class(EEmailError)
constructor Create(const Msg: string);
end;
EReceiveError = class(EEmailError)
constructor Create(const Msg: string);
end;
{ CallBacks }
TReadMessage = procedure(Sender: TObject; Mensagem: TIdMessage) of object;
TErroEmail = procedure(Sender: TObject; Error: Exception) of object;
{ Records }
TSMTP = (smNenhum, smHotmail, smGmail);
TOrder = (toCrescente, toDecrecente);
TAccount = class(TPersistent)
private
FPassword: String;
FUserName: String;
FName: String;
procedure SetPassword(const Value: String);
procedure SetUserName(const Value: String); virtual;
procedure SetName(const Value: String);
public
property Name: String read FName write SetName;
property Password: String read FPassword write SetPassword;
property UserName: String read FUserName write SetUserName;
procedure Assign(Source: TPersistent); override;
function IsValid: Boolean; virtual;
end;
TEmailAccount = class(TAccount)
private
FSMTP: TSMTP;
procedure DiscoverySMTP;
function GetSMTP: TSMTP;
procedure SetUserName(const Value: String); override;
protected
property SMTP: TSMTP read GetSMTP;
public
function IsValid: Boolean; override;
end;
IEmail = interface
// End thread
procedure TerminateThread(Sender: TObject);
// Getter and Setters
procedure SetOnAfterConnect(const Value: TNotifyEvent);
procedure SetOnBeforeConnect(const Value: TNotifyEvent);
procedure SetOnBeforeExecute(const Value: TNotifyEvent);
procedure SetOnAfterExecute(const Value: TNotifyEvent);
procedure SetOnError(const Value: TErroEmail);
function GetOnBeforeConnect: TNotifyEvent;
function GetOnAfterConnect: TNotifyEvent;
function GetOnBeforeExecute: TNotifyEvent;
function GetOnAfterExecute: TNotifyEvent;
function GetOnError: TErroEmail;
// Metodos
procedure Connect;
procedure Execute;
procedure Cancel;
function Connected: Boolean;
// Callbacks
property OnBeforeConnect: TNotifyEvent read GetOnBeforeConnect
write SetOnBeforeConnect;
property OnAfterConnect: TNotifyEvent read GetOnAfterConnect
write SetOnAfterConnect;
property OnBeforeExecute: TNotifyEvent read GetOnBeforeExecute
write SetOnBeforeExecute;
property OnAfterExecute: TNotifyEvent read GetOnAfterExecute
write SetOnAfterExecute;
property OnError: TErroEmail read GetOnError write SetOnError;
end;
TEmail = class(TInterfacedObject, IEmail)
private
// Fields
FAccount: TEmailAccount;
FThread: TThread;
// Eventos
FOnAfterConnect: TNotifyEvent;
FOnBeforeConnect: TNotifyEvent;
FOnError: TErroEmail;
FOnAfterExecute: TNotifyEvent;
FOnBeforeExecute: TNotifyEvent;
// Getter and Setters
procedure SetOnAfterConnect(const Value: TNotifyEvent);
procedure SetOnBeforeConnect(const Value: TNotifyEvent);
procedure SetAccount(const Value: TEmailAccount);
procedure SetOnError(const Value: TErroEmail);
procedure SetOnAfterExecute(const Value: TNotifyEvent);
procedure SetOnBeforeExecute(const Value: TNotifyEvent);
function GetOnBeforeConnect: TNotifyEvent;
function GetOnAfterConnect: TNotifyEvent;
function GetOnAfterExecute: TNotifyEvent;
function GetOnBeforeExecute: TNotifyEvent;
function GetOnError: TErroEmail;
// End thread
procedure TerminateThread(Sender: TObject);
protected
// Fields
SSL: TIdSSLIOHandlerSocketOpenSSL;
// Methods
procedure BeforeConnect;
procedure DoConnect; virtual; abstract;
procedure AfterConnect;
procedure DoExecute; virtual; abstract;
public
// Construtor/Destrutor
constructor Create; virtual;
destructor Destroy; override;
// Metodos
procedure Connect;
procedure Execute; virtual;
procedure Cancel; virtual;
function Connected: Boolean; virtual; abstract;
// Propriedades
property Account: TEmailAccount read FAccount write SetAccount;
// Callbacks
property OnBeforeConnect: TNotifyEvent read GetOnBeforeConnect
write SetOnBeforeConnect;
property OnAfterConnect: TNotifyEvent read GetOnAfterConnect
write SetOnAfterConnect;
property OnBeforeExecute: TNotifyEvent read GetOnBeforeExecute
write SetOnBeforeExecute;
property OnAfterExecute: TNotifyEvent read GetOnAfterExecute
write SetOnAfterExecute;
property OnError: TErroEmail read GetOnError write SetOnError;
end;
TEmailSend = class(TEmail)
private
IdSMTP: TIdSMTP;
// Callbacks
FOnAfterSend: TNotifyEvent;
FOnBeforeSend: TNotifyEvent;
// Fields
FAssunto: string;
FAnexos: TStringList;
FTexto: TStringList;
FDestino: TStringList;
FRemetenteNome: string;
FRemetenteEmail: string;
// Method
procedure ConfigConnection;
procedure CreateAndConfigMessage(var IdMessage: TIdMessage);
procedure AjustaRemetente;
// Getter and Setters
procedure SetAfterSend(const Value: TNotifyEvent);
procedure SetAnexos(const Value: TStringList);
procedure SetAssunto(const Value: string);
procedure SetBeforeSend(const Value: TNotifyEvent);
procedure SetDestino(const Value: TStringList);
procedure SetRemetenteEmail(const Value: string);
procedure SetRemetenteNome(const Value: string);
procedure SetTexto(const Value: TStringList);
protected
// Metodos
procedure DoExecute; override;
procedure DoConnect; override;
public
// Construtor
constructor Create; override;
destructor Destroy; override;
// Methods
function Connected: Boolean; override;
// Propriedades
property RemetenteEmail: string read FRemetenteEmail
write SetRemetenteEmail;
property RemetenteNome: string read FRemetenteNome write SetRemetenteNome;
property Assunto: string read FAssunto write SetAssunto;
property Anexos: TStringList read FAnexos write SetAnexos;
property Texto: TStringList read FTexto write SetTexto;
property Destino: TStringList read FDestino write SetDestino;
// Callbacks
property OnBeforeSend: TNotifyEvent read FOnBeforeSend write SetBeforeSend;
property OnAfterSend: TNotifyEvent read FOnAfterSend write SetAfterSend;
end;
TEmailReceive = class(TEmail)
private
IdPOP: TIdPop3;
// Callbacks
FOnReadMessage: TReadMessage;
// Fields
FEmails: TList<TIdMessage>;
FInicial: Cardinal;
FQuantidade: Cardinal;
FOrdem: TOrder;
MsgProcess: Cardinal;
MsgPos: Cardinal;
MsgCount: Cardinal;
// Method
procedure AdicionaEmail
(Lista: System.Generics.Collections.TList<TIdMessage>; i: Integer);
// Getters and Setters
procedure SetInicial(const Value: Cardinal);
procedure SetOrdem(const Value: TOrder);
procedure SetQuantidade(const Value: Cardinal);
procedure SetReadMessage(const Value: TReadMessage);
function GetFinished: Boolean;
protected
// Metodos
procedure DoExecute; override;
procedure DoConnect; override;
public
// Construtor/Destructor
destructor Destroy; override;
// Methods
function Connected: Boolean; override;
// Propriedades
property Emails: TList<TIdMessage> read FEmails;
property Inicial: Cardinal read FInicial write SetInicial default 0;
property Quantidade: Cardinal read FQuantidade write SetQuantidade
default 0;
property Ordem: TOrder read FOrdem write SetOrdem default toDecrecente;
property Finished: Boolean read GetFinished;
// CallBack
property OnReadMessage: TReadMessage read FOnReadMessage
write SetReadMessage;
end;
TEmailFactory = class
private type
TEmailOperation = (emSend, emReceive);
public
class function GetTEmail(EmailOperation: TEmailOperation): TEmail;
end;
implementation
{ TEmail }
procedure TEmail.BeforeConnect;
begin
if FThread.CheckTerminated then
abort;
if Assigned(FOnBeforeConnect) then
FOnBeforeConnect(Self);
if FThread.CheckTerminated then
abort;
// Instancia objetos
if not Assigned(SSL) then
SSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
end;
procedure TEmail.AfterConnect;
begin
if FThread.CheckTerminated then
abort;
if Assigned(FOnAfterConnect) then
FOnAfterConnect(Self);
if FThread.CheckTerminated then
abort;
end;
procedure TEmail.Cancel;
begin
if Assigned(FThread) then
begin
FThread.Terminate;
if not FThread.Finished then
FThread.WaitFor;
FreeAndNil(FThread);
end;
end;
procedure TEmail.Connect;
begin
try
if not Connected then
begin
BeforeConnect;
DoConnect;
AfterConnect;
end;
except
on E: EEmailError do
if Assigned(FOnError) then
FOnError(Self, E);
end;
end;
procedure TEmail.TerminateThread(Sender: TObject);
begin
if Assigned(FOnAfterExecute) then
FOnAfterExecute(Self);
end;
constructor TEmail.Create;
begin
FAccount := TEmailAccount.Create;
end;
destructor TEmail.Destroy;
begin
FreeAndNil(FAccount);
if Assigned(SSL) then
FreeAndNil(SSL);
UnLoadOpenSSLLibrary;
end;
procedure TEmail.Execute;
begin
if not FAccount.IsValid then
raise Exception.Create('Email ' + FAccount.UserName + ' inválido!');
FThread := TThread.CreateAnonymousThread(
procedure
begin
try
Connect;
if Connected then
DoExecute;
except
on E: EEmailError do
if Assigned(FOnError) then
FOnError(Self, E);
end;
end);
with FThread do
begin
FreeOnTerminate := False;
OnTerminate := TerminateThread;
Start;
end;
end;
function TEmail.GetOnAfterConnect: TNotifyEvent;
begin
result := FOnAfterConnect;
end;
function TEmail.GetOnAfterExecute: TNotifyEvent;
begin
result := FOnAfterExecute;
end;
function TEmail.GetOnBeforeConnect: TNotifyEvent;
begin
result := FOnBeforeConnect;
end;
function TEmail.GetOnBeforeExecute: TNotifyEvent;
begin
result := FOnBeforeExecute;
end;
function TEmail.GetOnError: TErroEmail;
begin
result := FOnError;
end;
procedure TEmail.SetAccount(const Value: TEmailAccount);
begin
FAccount := Value;
end;
procedure TEmail.SetOnAfterConnect(const Value: TNotifyEvent);
begin
FOnAfterConnect := Value;
end;
procedure TEmail.SetOnAfterExecute(const Value: TNotifyEvent);
begin
FOnAfterExecute := Value;
end;
procedure TEmail.SetOnBeforeConnect(const Value: TNotifyEvent);
begin
FOnBeforeConnect := Value;
end;
procedure TEmail.SetOnBeforeExecute(const Value: TNotifyEvent);
begin
FOnBeforeExecute := Value;
end;
procedure TEmail.SetOnError(const Value: TErroEmail);
begin
FOnError := Value;
end;
{ TSend }
procedure TEmailSend.DoConnect;
begin
// Instancia SMTP caso ainda não esteja instanciado
if not Assigned(IdSMTP) then
IdSMTP := TIdSMTP.Create(nil);
// Configura conexão
ConfigConnection;
// Conexão e autenticação
try
IdSMTP.Connect;
except
raise EConnectError.Create
('Ocorreu um erro durante a conexão com o servidor de e-mail.');
end;
if FThread.CheckTerminated then
abort;
try
IdSMTP.Authenticate;
except
raise EAuthentError.Create
('Ocorreu um erro durante a autenticação da conta de e-mail, verifique a conta!');
end;
end;
constructor TEmailSend.Create;
begin
inherited;
FAnexos := TStringList.Create;
FTexto := TStringList.Create;
FDestino := TStringList.Create;
end;
destructor TEmailSend.Destroy;
begin
// Cancela thread caso esteja executando
Cancel;
// Desconecta e libera SMTP
if Assigned(IdSMTP) then
begin
IdSMTP.Disconnect;
FreeAndNil(IdSMTP);
end;
// Elimina listas
FreeAndNil(FAnexos);
FreeAndNil(FTexto);
FreeAndNil(FDestino);
FreeAndNil(FAccount);
inherited;
end;
procedure TEmailSend.AjustaRemetente;
begin
// Assume remetente com os dados de origem caso não informado
if RemetenteEmail = EmptyStr then
RemetenteEmail := FAccount.UserName;
if RemetenteNome = EmptyStr then
if FAccount.Name <> EmptyStr then
RemetenteNome := FAccount.Name
else
RemetenteNome := FAccount.UserName;
end;
procedure TEmailSend.CreateAndConfigMessage(var IdMessage: TIdMessage);
var
i: Integer;
IdText: TIdText;
begin
if FThread.CheckTerminated then
abort;
// Cria mensagem
IdMessage := TIdMessage.Create;
// Configuração da mensagem
IdMessage.From.Address := RemetenteEmail;
IdMessage.From.Name := RemetenteNome;
IdMessage.Subject := FAssunto;
IdMessage.Encoding := meMIME;
// Adiciona destinatários
IdMessage.ReplyTo.EMailAddresses := IdMessage.From.Address;
for i := 0 to FDestino.Count - 1 do
IdMessage.Recipients.Add.Text := FDestino[i];
// Configuração do corpo do email
IdText := TIdText.Create(IdMessage.MessageParts);
IdText.Body := FTexto;
// Anexa anexos
for i := 0 to FAnexos.Count - 1 do
if FileExists(FAnexos[i]) then
TIdAttachmentFile.Create(IdMessage.MessageParts, FAnexos[i]);
if FThread.CheckTerminated then
abort;
end;
procedure TEmailSend.ConfigConnection;
begin
// Configuração do protocolo SSL (TIdSSLIOHandlerSocketOpenSSL)
SSL.SSLOptions.Method := sslvSSLv23;
SSL.SSLOptions.Mode := sslmClient;
// Configuração do servidor SMTP (TIdSMTP)
with IdSMTP do
begin
IOHandler := SSL;
AuthType := satDefault;
UserName := FAccount.UserName;
Password := FAccount.Password;
if Self.FAccount.SMTP = smGmail then
begin
UseTLS := utUseImplicitTLS;
Port := IdPORT_ssmtp;
Host := 'smtp.gmail.com';
end
else
begin
UseTLS := utUseExplicitTLS;
Port := Id_PORT_submission;
Host := 'smtp.live.com';
end;
end;
end;
function TEmailSend.Connected: Boolean;
begin
result := Assigned(IdSMTP) and IdSMTP.Connected and IdSMTP.DidAuthenticate;
end;
procedure TEmailSend.DoExecute;
var
IdMessage: TIdMessage;
begin
if Assigned(FOnBeforeSend) then
FOnBeforeSend(Self);
if FThread.CheckTerminated then
abort;
try
// Ajusta remetente caso não informado
AjustaRemetente;
// Cria e configura mensagem
CreateAndConfigMessage(IdMessage);
try
// Envia e-mail
IdSMTP.Send(IdMessage);
except
raise ESendError.Create
('Erro ao enviar e-mail, este erro pode ocorrer devido ao destinário inválido ou serviço de envio de email indisponível!');
end;
finally
FreeAndNil(IdMessage);
FreeAndNil(FDestino);
FreeAndNil(FAnexos);
FreeAndNil(FTexto);
end;
end;
procedure TEmailSend.SetAfterSend(const Value: TNotifyEvent);
begin
FOnAfterSend := Value;
end;
procedure TEmailSend.SetAnexos(const Value: TStringList);
begin
FAnexos := Value;
end;
procedure TEmailSend.SetAssunto(const Value: string);
begin
FAssunto := Value;
end;
procedure TEmailSend.SetBeforeSend(const Value: TNotifyEvent);
begin
FOnBeforeSend := Value;
end;
procedure TEmailSend.SetDestino(const Value: TStringList);
begin
FDestino := Value;
end;
procedure TEmailSend.SetRemetenteEmail(const Value: string);
begin
FRemetenteEmail := Value;
end;
procedure TEmailSend.SetRemetenteNome(const Value: string);
begin
FRemetenteNome := Value;
end;
procedure TEmailSend.SetTexto(const Value: TStringList);
begin
FTexto := Value;
end;
{ TReceive }
procedure TEmailReceive.AdicionaEmail
(Lista: System.Generics.Collections.TList<TIdMessage>; i: Integer);
var
IdMessage: TIdMessage;
begin
if FThread.CheckTerminated then
abort;
IdMessage := TIdMessage.Create(nil);
IdPOP.Retrieve(i, IdMessage);
Lista.Add(IdMessage);
MsgPos := i;
if Assigned(FOnReadMessage) then
FOnReadMessage(Self, IdMessage);
if FThread.CheckTerminated then
abort;
end;
procedure TEmailReceive.DoConnect;
begin
if not Assigned(IdPOP) then
IdPOP := TIdPop3.Create(nil);
if Self.FAccount.SMTP = smGmail then
begin
IdPOP.Host := 'pop.gmail.com';
IdPOP.Port := 995;
end
else
begin
raise Exception.Create('Função não disponivel para Hotmail');
end;
IdPOP.UserName := Self.FAccount.UserName;
IdPOP.Password := Self.FAccount.Password;
SSL.Host := IdPOP.Host;
SSL.Port := IdPOP.Port;
SSL.Destination := SSL.Host + ':' + IntToStr(SSL.Port);
IdPOP.IOHandler := SSL;
IdPOP.UseTLS := utUseImplicitTLS;
if FThread.CheckTerminated then
abort;
try
IdPOP.Connect;
except
raise EConnectError.Create('Erro durante a conexão com o servidor de email!'
+ #13#10 +
'Verifique a conta e se o servidor de e-mail está funcionando.');
end;
end;
function TEmailReceive.Connected: Boolean;
begin
result := Assigned(IdPOP) and IdPOP.Connected;
end;
destructor TEmailReceive.Destroy;
var
i: Integer;
begin
// Cancela thread caso esteja executando
Cancel;
if Assigned(FEmails) then
begin
for i := 0 to FEmails.Count - 1 do
FEmails[i].Free;
FreeAndNil(FEmails);
end;
if Assigned(IdPOP) then
FreeAndNil(IdPOP);
inherited;
end;
procedure TEmailReceive.DoExecute;
var
i: Cardinal;
begin
MsgCount := 0;
FEmails := TList<TIdMessage>.Create;
try
MsgCount := IdPOP.CheckMessages;
except
raise EReceiveError.Create
('Conta foi conectada, porem, ao tentar obter mensagem ocorreu um erro inesperado!');
end;
if (Quantidade = 0) or (Quantidade > MsgCount) then
MsgProcess := MsgCount
else
MsgProcess := Quantidade;
if Ordem = toCrescente then
for i := Inicial to MsgProcess - 1 Do
AdicionaEmail(FEmails, i)
else
for i := MsgCount - Inicial downto MsgCount - Inicial - MsgProcess - 1 do
AdicionaEmail(FEmails, i);
end;
procedure TEmailReceive.SetInicial(const Value: Cardinal);
begin
FInicial := Value;
end;
procedure TEmailReceive.SetOrdem(const Value: TOrder);
begin
FOrdem := Value;
end;
procedure TEmailReceive.SetQuantidade(const Value: Cardinal);
begin
FQuantidade := Value;
end;
procedure TEmailReceive.SetReadMessage(const Value: TReadMessage);
begin
FOnReadMessage := Value;
end;
function TEmailReceive.GetFinished: Boolean;
begin
if (MsgCount = 0) or (MsgProcess < MsgCount) then
result := False
else if MsgProcess = MsgPos then
result := True
else
result := False;
end;
{ TAccount }
procedure TAccount.Assign(Source: TPersistent);
begin
if Source is TAccount then
with TAccount(Source) do
begin
Self.Name := Name;
Self.Password := Password;
Self.UserName := UserName;
end
else
inherited Assign(Source);
end;
function TAccount.IsValid: Boolean;
begin
result := FUserName = EmptyStr;
end;
procedure TAccount.SetName(const Value: String);
begin
FName := Value;
end;
procedure TAccount.SetPassword(const Value: String);
begin
FPassword := Value;
end;
procedure TAccount.SetUserName(const Value: String);
begin
FUserName := Value;
end;
{ TEmailAccount }
procedure TEmailAccount.DiscoverySMTP;
begin
if Pos('@HOTMAIL', UpperCase(Self.FUserName)) > 0 then
FSMTP := smHotmail
else if Pos('@GMAIL', UpperCase(Self.FUserName)) > 0 then
FSMTP := smGmail
else
FSMTP := smNenhum;
end;
function TEmailAccount.GetSMTP: TSMTP;
begin
result := FSMTP;
end;
function TEmailAccount.IsValid: Boolean;
var
RegEx: TRegEx;
begin
result := inherited;
if (FSMTP <> smNenhum) and (Password <> EmptyStr) then
begin
RegEx := TRegEx.Create('(.)+@+.+[.]+(.)+');
if RegEx.IsMatch(FUserName) then
result := True;
end;
end;
procedure TEmailAccount.SetUserName(const Value: String);
begin
inherited;
DiscoverySMTP;
end;
{ TEmailFactory }
class function TEmailFactory.GetTEmail(EmailOperation: TEmailOperation): TEmail;
begin
case EmailOperation of
emSend:
result := TEmailSend.Create;
emReceive:
result := TEmailReceive.Create;
else
result := nil;
end;
end;
{ EEmailError }
constructor EEmailError.Create;
begin
Create('Ocorreu um erro desconhecido ao utilizar e-mail', eUnknown);
end;
constructor EEmailError.Create(Msg: String; Kind: TEKind);
begin
FKind := Kind;
Self.Message := Msg;
end;
procedure EEmailError.SetKind(const Value: TEKind);
begin
FKind := Value;
end;
{ EConnectError }
constructor EConnectError.Create(const Msg: string);
begin
inherited Create(Msg, eConnect);
end;
{ EAuthentError }
constructor EAuthentError.Create(const Msg: string);
begin
inherited Create(Msg, eAuthent);
end;
{ ESendError }
constructor ESendError.Create(const Msg: string);
begin
inherited Create(Msg, eSend);
end;
{ EReceiveError }
constructor EReceiveError.Create(const Msg: string);
begin
inherited Create(Msg, eReceive);
end;
end.
|
unit DelphiUp.View.Components.Button002;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects, FMX.Layouts,
DelphiUp.View.Styles, FMX.Effects, FMX.Filter.Effects;
type
TComponentButton002 = class(TForm)
Layout1: TLayout;
Rectangle1: TRectangle;
Layout2: TLayout;
Image1: TImage;
Label1: TLabel;
SpeedButton1: TSpeedButton;
FillRGBEffect1: TFillRGBEffect;
procedure SpeedButton1MouseEnter(Sender: TObject);
procedure SpeedButton1MouseLeave(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
FTitle : String;
FImage : String;
FOnClick : TProc<TObject>;
public
{ Public declarations }
function Component : TFMXObject;
function Title ( aValue : String ) : TComponentButton002;
function Image ( aValue : String ) : TComponentButton002;
function OnClick ( aValue : TProc<TObject> ) : TComponentButton002;
end;
var
ComponentButton002: TComponentButton002;
implementation
uses
DelphiUp.View.Services.Utils;
{$R *.fmx}
{ TComponentButton002 }
function TComponentButton002.Component: TFMXObject;
begin
Result := Layout1;
Layout1.Align := TAlignLayout.Top;
Label1.Text := FTitle;
Label1.FontColor := FONT_COLOR_CONTRAST;
Label1.TextSettings.Font.Size := FONT_SIZE_H5;
Rectangle1.Fill.Color := PRIMARY;
FillRGBEffect1.Color := FONT_COLOR_CONTRAST;
end;
function TComponentButton002.Image(aValue: String): TComponentButton002;
begin
Result := Self;
FImage := aValue;
TServiceUtils.ResourceImage(aValue, Image1);
end;
function TComponentButton002.OnClick(
aValue: TProc<TObject>): TComponentButton002;
begin
Result := Self;
FOnClick := aValue;
end;
procedure TComponentButton002.SpeedButton1Click(Sender: TObject);
begin
if Assigned(FOnClick) then
FOnClick(Self);
end;
procedure TComponentButton002.SpeedButton1MouseEnter(Sender: TObject);
begin
Rectangle1.Fill.Color := INFO;
end;
procedure TComponentButton002.SpeedButton1MouseLeave(Sender: TObject);
begin
Rectangle1.Fill.Color := PRIMARY;
end;
function TComponentButton002.Title(aValue: String): TComponentButton002;
begin
Result := Self;
FTitle := aValue;
end;
end.
|
unit EmailOrdering.Controllers.MainControllerInt;
interface
uses
IdMessage, Wddc.Inventory.Order, EmailOrdering.Models.EmailMsg;
type
IMainController = Interface(IInterface)
procedure NewOrder(const msg: TEmailMsg);
procedure ShowMessageForm();
procedure OpenSuccess();
procedure OpenFailure();
procedure OpenConfirmation(orderId: integer);
procedure ClearOrderLog();
procedure UpdateConfig();
procedure OpenSettingsForm();
procedure SetupEmailServer();
procedure StopEmailServer();
procedure ShowHelp();
End;
implementation
end.
|
unit Unt_Coletor;
interface
uses
System.Classes,
System.Generics.Collections,
System.SyncObjs;
type
/// <summary>
/// Classe singleton com o propósito de liberar objetos
/// </summary>
TColetorDeLixo = class(TThread)
private
/// <summary>
/// Instância única desta classe
/// </summary>
class var FColetorDeLixo: TColetorDeLixo;
/// <summary>
/// Liberador da instância única desta classe
/// </summary>
class procedure ReleaseInstance;
/// <summary>
/// Instanciador da classe
/// </summary>
class function GetInstance: TColetorDeLixo; static;
private
/// <summary>
/// Enfilerador dos objetos (FIFO) que serão liberados
/// </summary>
FFila: TObjectQueue<TObject>;
/// <summary>
/// Seção crítica para a fila de objetos
/// </summary>
FSecaoCritica: TCriticalSection;
/// <summary>
/// Quantidade de objetos liberados
/// </summary>
FQuantidadeLiberada: NativeUInt;
/// <summary>
/// Retorna a quantidade de objetos ainda a serem liberados
/// </summary>
function GetQuantidadeFila: NativeUInt;
/// <summary>
/// Processamento efetivo da fila de objetos
/// </summary>
procedure ProcessarFila;
public
/// <summary>
/// Aloca os recursos necessários para o funcionamento da classe
/// </summary>
procedure AfterConstruction; override;
/// <summary>
/// Desaloca os recursos
/// </summary>
procedure BeforeDestruction; override;
/// <summary>
/// Coloca um objeto na pilha, será invocada pelos outros threads
/// </summary>
procedure ColocarNaPilha(AObjeto: TObject);
/// <summary>
/// Rotina que será, efetivamente executado pelo thread
/// </summary>
procedure Execute; override;
/// <summary>
/// Exposição da instância única desta classe
/// </summary>
class property ColetorDeLixo: TColetorDeLixo read GetInstance;
/// <summary>
/// Indica a quantidade de objetos na fila
/// </summary>
property QuantidadeFila: NativeUInt read GetQuantidadeFila;
/// <summary>
/// Indica a quantidade de objetos já liberado
/// </summary>
property QuantidadeLiberada: NativeUInt read FQuantidadeLiberada;
end;
implementation
uses
System.SysUtils;
{ TExemploThread }
procedure TColetorDeLixo.AfterConstruction;
begin
inherited;
Self.FQuantidadeLiberada := 0;
Self.FSecaoCritica := TCriticalSection.Create;
Self.FFila := TObjectQueue<TObject>.Create(True);
end;
procedure TColetorDeLixo.BeforeDestruction;
begin
inherited;
Self.FSecaoCritica.Free;
Self.FFila.Free;
end;
procedure TColetorDeLixo.ColocarNaPilha(AObjeto: TObject);
begin
Self.FSecaoCritica.Enter;
try
Self.FFila.Enqueue(AObjeto);
finally
Self.FSecaoCritica.Release;
end;
end;
procedure TColetorDeLixo.Execute;
var
iQuantidade : NativeUInt;
begin
inherited;
while not(Self.Terminated) do
begin
iQuantidade := Self.FFila.Count;
if (iQuantidade = 0) then
begin
Continue;
end;
Self.ProcessarFila;
end;
end;
class function TColetorDeLixo.GetInstance: TColetorDeLixo;
begin
if not(Assigned(FColetorDeLixo)) then
begin
FColetorDeLixo := TColetorDeLixo.Create(True);
FColetorDeLixo.Start;
end;
Result := FColetorDeLixo;
end;
function TColetorDeLixo.GetQuantidadeFila: NativeUInt;
begin
Result := Self.FFila.Count;
end;
procedure TColetorDeLixo.ProcessarFila;
var
i : Integer;
oTemp : TObject;
begin
Self.FSecaoCritica.Enter;
try
for i := 1 to Self.FFila.Count do
begin
oTemp := Self.FFila.Extract;
oTemp.Free;
Inc(Self.FQuantidadeLiberada);
end;
finally
Self.FSecaoCritica.Release;
end;
// Demora artificial para verificarmos as quantidades
Sleep(250);
end;
class procedure TColetorDeLixo.ReleaseInstance;
begin
if (Assigned(FColetorDeLixo)) then
begin
FColetorDeLixo.Terminate;
FColetorDeLixo.WaitFor;
FColetorDeLixo.Free;
FColetorDeLixo := nil;
end;
end;
initialization
finalization
TColetorDeLixo.ReleaseInstance;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpDerOutputStream;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
ClpBits,
ClpAsn1Tags,
ClpCryptoLibTypes,
ClpIProxiedInterface,
ClpFilterStream;
type
TDerOutputStream = class(TFilterStream)
strict private
procedure WriteLength(length: Int32);
strict protected
procedure WriteNull();
public
constructor Create(const os: TStream);
procedure WriteEncoded(tag: Int32;
const bytes: TCryptoLibByteArray); overload;
procedure WriteEncoded(tag: Int32; first: Byte;
const bytes: TCryptoLibByteArray); overload;
procedure WriteEncoded(tag: Int32; const bytes: TCryptoLibByteArray;
offset, length: Int32); overload;
procedure WriteEncoded(flags, tagNo: Int32;
const bytes: TCryptoLibByteArray); overload;
procedure WriteTag(flags, tagNo: Int32);
procedure WriteObject(const obj: IAsn1Encodable); overload; virtual;
procedure WriteObject(const obj: IAsn1Object); overload; virtual;
end;
implementation
{ TDerOutputStream }
constructor TDerOutputStream.Create(const os: TStream);
begin
Inherited Create(os);
end;
procedure TDerOutputStream.WriteEncoded(tag: Int32; first: Byte;
const bytes: TCryptoLibByteArray);
begin
WriteByte(Byte(tag));
WriteLength(System.length(bytes) + 1);
WriteByte(first);
Write(bytes[0], System.length(bytes));
end;
procedure TDerOutputStream.WriteEncoded(tag: Int32;
const bytes: TCryptoLibByteArray);
begin
WriteByte(Byte(tag));
WriteLength(System.length(bytes));
if bytes <> Nil then
begin
Write(bytes[0], System.length(bytes));
end;
end;
procedure TDerOutputStream.WriteEncoded(flags, tagNo: Int32;
const bytes: TCryptoLibByteArray);
begin
WriteTag(flags, tagNo);
WriteLength(System.length(bytes));
Write(bytes[0], System.length(bytes));
end;
procedure TDerOutputStream.WriteEncoded(tag: Int32;
const bytes: TCryptoLibByteArray; offset, length: Int32);
begin
WriteByte(Byte(tag));
WriteLength(length);
Write(bytes[offset], length);
end;
procedure TDerOutputStream.WriteLength(length: Int32);
var
size, i: Int32;
val: UInt32;
begin
if (length > 127) then
begin
size := 1;
val := UInt32(length);
val := val shr 8;
while (val <> 0) do
begin
System.Inc(size);
val := val shr 8;
end;
WriteByte(Byte(size or $80));
i := (size - 1) * 8;
while i >= 0 do
begin
WriteByte(Byte(TBits.Asr32(length, i)));
System.Dec(i, 8);
end;
end
else
begin
WriteByte(Byte(length));
end;
end;
procedure TDerOutputStream.WriteNull;
begin
WriteByte(TAsn1Tags.Null);
WriteByte($00);
end;
procedure TDerOutputStream.WriteObject(const obj: IAsn1Encodable);
var
asn1: IAsn1Object;
begin
if (obj = Nil) then
begin
WriteNull();
end
else
begin
asn1 := obj.ToAsn1Object();
asn1.Encode(Self);
end;
end;
procedure TDerOutputStream.WriteObject(const obj: IAsn1Object);
begin
if (obj = Nil) then
begin
WriteNull();
end
else
begin
obj.Encode(Self);
end;
end;
procedure TDerOutputStream.WriteTag(flags, tagNo: Int32);
var
stack: TCryptoLibByteArray;
pos: Int32;
begin
if (tagNo < 31) then
begin
WriteByte(Byte(flags or tagNo));
end
else
begin
WriteByte(Byte(flags or $1F));
if (tagNo < 128) then
begin
WriteByte(Byte(tagNo));
end
else
begin
System.SetLength(stack, 5);
pos := System.length(stack);
System.Dec(pos);
stack[pos] := Byte(tagNo and $7F);
repeat
tagNo := TBits.Asr32(tagNo, 7);
System.Dec(pos);
stack[pos] := Byte(tagNo and $7F or $80);
until (not(tagNo > 127));
Write(stack[pos], System.length(stack) - pos);
end;
end;
end;
end.
|
{$I ViewerOptions.inc}
unit ATxMsgProc;
interface
uses
Windows;
function MsgCaption(N: integer): string;
function MsgString(N: integer): string; overload;
function MsgString(const Section, Key: string): string; overload;
function MsgStrip(const S: string): string;
procedure MsgInstall(sAdded, sDups: string; FromZip: boolean; Handle: THandle);
function SMsgLanguage: string;
procedure SetMsgLanguage(const LangName: string);
procedure ShowHelp(AHandle: THandle; const ATopic: string = '');
function SPluginName(const fn: string): string;
implementation
uses
SysUtils, Forms,
ATxIniFile, ATxSProc, ATxFProc, ATxParamStr, ATxMsg, ATViewerMsg,
{$ifdef HELP} HtmlHlp, {$endif}
TntForms;
var
FLangFile,
FLangFileEn: WideString;
FIniFile: TATIniFile = nil;
FIniFileEn: TATIniFile = nil;
//----------------------------------------------------------
function MsgCaption(N: integer): string;
begin
Result:= FIniFile.ReadString('Captions', IntToStr(N), '');
if Result = '' then
if Assigned(FIniFileEn) then
Result:= FIniFileEn.ReadString('Captions', IntToStr(N), '');
end;
//----------------------------------------------------------
function MsgString(N: integer): string; overload;
begin
Result:= FIniFile.ReadString('Messages', IntToStr(N), '');
if Result = '' then
if Assigned(FIniFileEn) then
Result:= FIniFileEn.ReadString('Messages', IntToStr(N), '');
SReplaceAll(Result, '\n', #13);
SReplaceAll(Result, '\r', #10);
SReplaceAll(Result, '\t', #9);
end;
//----------------------------------------------------------
function MsgString(const Section, Key: string): string; overload;
begin
Result:= FIniFile.ReadString(Section, Key, '');
if Result = '' then
if Assigned(FIniFileEn) then
Result:= FIniFileEn.ReadString(Section, Key, '');
end;
//----------------------------------------------------------
function MsgStrip(const S: string): string;
begin
Result:= S;
//Delete '&' and '...'
SReplaceAll(Result, '&', '');
SReplaceAll(Result, '...', '');
//Delete trailing ':'
if (Result <> '') and (Result[Length(Result)] = ':') then
SetLength(Result, Length(Result) - 1);
//Delete digit + 2 spaces for View menu
if Pos(' ', Result) = 2 then
Delete(Result, 1, 3);
end;
//----------------------------------------------------------
function SMsgLanguage: string;
begin
Result:= ChangeFileExt(ExtractFileName(FLangFile), '');
end;
//----------------------------------------------------------
procedure SetMsgLanguage(const LangName: string);
var
FFirst: WideString;
begin
FLangFile:= SLangFN(LangName);
FLangFileEn:= SLangFN('English');
if not IsFileExist(FLangFile) then
begin
FFirst:= FFindFirstFile(SParamDir + '\Language', '*.lng');
if IsFileExist(FFirst) then
FLangFile:= FFirst;
end;
if IsFileExist(FLangFile) then
begin
if Assigned(FIniFile) then
FreeAndNil(FIniFile);
FIniFile:= TATIniFile.Create(FLangFile);
end
else
begin
MsgError(SFormatW(MsgViewerLangMissed, [FLangFile]));
Application.Terminate;
end;
if IsFileExist(FLangFileEn) then
begin
if Assigned(FIniFileEn) then
FreeAndNil(FIniFileEn);
FIniFileEn:= TATIniFile.Create(FLangFileEn);
end;
end;
//----------------------------------------------------------
{$ifdef HELP}
procedure ShowHelp(AHandle: THandle; const ATopic: string = '');
const
SuffixEn = '.English';
var
Filename, FilenameEn, Suffix: string;
begin
Suffix:= '.' + SMsgLanguage;
Filename:= SExtractFilePath(TntApplication.ExeName) + 'Help\Viewer' + Suffix + '.chm';
FilenameEn:= SExtractFilePath(TntApplication.ExeName) + 'Help\Viewer' + SuffixEn + '.chm';
if not IsFileExist(Filename) then
Filename:= FilenameEn;
if IsFileExist(Filename) then
begin
//If HTMLHELP_DYNAMIC_LINK_EXPLICIT defined in HtmlHlp.inc:
//LoadHtmlHelp;
if ATopic = '' then
HtmlHelp(AHandle, PChar(Filename), HH_DISPLAY_TOC, 0)
else
HtmlHelp(AHandle, PChar(Filename + '::/' + ATopic), HH_DISPLAY_TOPIC, 0)
end
else
MsgError(SFormatW(MsgString(101), [Filename]), AHandle);
end;
{$else}
procedure ShowHelp(AHandle: THandle; const ATopic: string = '');
begin
end;
{$endif}
function SPluginName(const fn: string): string;
begin
if IsFileExist(fn) then
Result:= ChangeFileExt(ExtractFileName(fn), '')
else
Result:= MsgViewerPluginsNameNotFound;
end;
procedure MsgInstall(sAdded, sDups: string; FromZip: boolean; Handle: THandle);
var
Msg: string;
begin
if sAdded = '' then sAdded:= MsgViewerPluginsNone;
if sDups = '' then sDups:= MsgViewerPluginsNone;
if FromZip then
Msg:= MsgViewerPluginsInstalledZip
else
Msg:= MsgViewerPluginsInstalled;
MsgInfo(Format(Msg, [sAdded, sDups]), Handle);
end;
initialization
finalization
if Assigned(FIniFile) then
FreeAndNil(FIniFile);
if Assigned(FIniFileEn) then
FreeAndNil(FIniFileEn);
end.
|
unit evTableColumnHotSpot;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Everest"
// Модуль: "w:/common/components/gui/Garant/Everest/evTableColumnHotSpot.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::Cursors::TevTableColumnHotSpot
//
// реализует интерфейс IevHotSpot для колонки таблицы.
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\Everest\evDefine.inc}
interface
uses
l3Interfaces,
nevBase,
nevTools,
nevGUIInterfaces,
evColumnBorderMarker,
afwInterfaces
;
type
RevTableColumnHotSpot = class of TevTableColumnHotSpot;
TevTableColumnHotSpot = class(TevColumnBorderMarker, IevAdvancedHotSpot, IevHotSpotDelta)
{* реализует интерфейс IevHotSpot для колонки таблицы. }
private
// private fields
f_Delta : Integer;
f_CanChangeTable : Boolean;
protected
// realized methods
function MouseAction(const aView: InevControlView;
aButton: Tl3MouseButton;
anAction: Tl3MouseAction;
const Keys: TevMouseState;
var Effect: TevMouseEffect): Boolean;
{* обрабатывает событие от мыши. Возвращает true - если обработано, иначе - false }
function Delta: Integer;
{* точность }
function CanDrag: Boolean;
public
// realized methods
procedure HitTest(const aView: InevControlView;
const aState: TafwCursorState;
var theInfo: TafwCursorInfo);
protected
// protected methods
function ProportionalChangeWidth(const aTable: InevTag;
aDelta: Integer;
const anOpPack: InevOp): Boolean;
procedure ChangeCellWidth(const aView: InevControlView;
const aProcessor: InevProcessor;
const anOpPack: InevOp;
const Keys: TevMouseState;
const aRow: InevParaList;
aDelta: Integer);
public
// public methods
function CanChangeTable(const aView: InevControlView;
const aPara: InevTag): Boolean;
constructor Create(const aView: InevControlView;
const aPara: InevTag;
aColumnID: Integer;
const aHint: Il3CString;
aDelta: Integer); reintroduce;
class function Make(const aView: InevControlView;
const aPara: InevTag;
aColumnID: Integer;
const aHint: Il3CString = nil;
aDelta: Integer = 0): IevAdvancedHotSpot;
end;//TevTableColumnHotSpot
implementation
uses
k2Tags,
l3Math,
k2Base,
evdTypes,
Classes,
SysUtils,
evInternalInterfaces,
evParaTools,
CommentPara_Const,
l3Base,
evEditorInterfaces,
l3InterfacesMisc,
nevInterfaces,
evTableCellUtils,
k2OpMisc,
evMsgCode,
l3IID
;
// start class TevTableColumnHotSpot
function TevTableColumnHotSpot.ProportionalChangeWidth(const aTable: InevTag;
aDelta: Integer;
const anOpPack: InevOp): Boolean;
//#UC START# *4ED321A40385_4ED31E9500E7_var*
var
l_Width : Integer;
l_NewWidth : Integer;
function ModifyRow(const aRow: InevTag; Index: Integer): Boolean; far;
var
l_PrevOldDelta : Integer;
l_PrevNewDelta : Integer;
function ModifyCell(const aCell: InevTag; Index: Integer): Boolean; far;
var
l_NewCellWidth : Integer;
begin//ModifyCell
Result := true;
with aCell do
begin
with Attr[k2_tiWidth] do
if IsValid then
begin
Inc(l_PrevOldDelta, AsLong);
l_NewCellWidth := l3MulDiv(l_PrevOldDelta, l_NewWidth, l_Width) - l_PrevNewDelta;
Inc(l_PrevNewDelta, l_NewCellWidth);
end
else
l_NewCellWidth := 0;
IntW[k2_tiWidth, anOpPack] := l_NewCellWidth;
end;//with aCell
end;//ModifyCell
begin//ModifyRow
l_PrevOldDelta := 0;
l_PrevNewDelta := 0;
Result := True;
aRow.IterateChildrenF(k2L2TIA(@ModifyCell));
end;//ModifyRow
function GetTableWidth: Integer;
var
l_Width: Integer absolute Result;
function CalcWidth(const aCell: InevTag; Index: Integer): Boolean; far;
begin
Inc(l_Width, aCell.IntA[k2_tiWidth]);
Result := True;
end;
begin
l_Width := 0;
aTable.Child[0].IterateChildrenF(k2L2TIA(@CalcWidth));
end;
//#UC END# *4ED321A40385_4ED31E9500E7_var*
begin
//#UC START# *4ED321A40385_4ED31E9500E7_impl*
Result := False;
l_Width := GetTableWidth;
l_NewWidth := l_Width + aDelta;
if (l_NewWidth > 0) AND (l_Width > 0) then
begin
aTable.IterateChildrenF(k2L2TIA(@ModifyRow));
Result := True;
end;//l_NewWidth > 0..
//#UC END# *4ED321A40385_4ED31E9500E7_impl*
end;//TevTableColumnHotSpot.ProportionalChangeWidth
procedure TevTableColumnHotSpot.ChangeCellWidth(const aView: InevControlView;
const aProcessor: InevProcessor;
const anOpPack: InevOp;
const Keys: TevMouseState;
const aRow: InevParaList;
aDelta: Integer);
//#UC START# *4ED3220102EE_4ED31E9500E7_var*
var
l_Width: Integer;
procedure lp_ChangeHeadWidth(const aPara: InevPara; aCheckPrev: Boolean);
var
l_Cell : InevTableCell;
l_PrevPart : InevTableCell;
l_NexCell : InevPara;
l_PrevPara : InevPara;
begin
with aPara do
begin
QT(InevTableCell, l_Cell);
if TevMergeStatus(IntA[k2_tiMergeStatus]) = ev_msContinue then
l_Cell := l_Cell.GetMergeHead;
while l_Cell <> nil do
begin
l_PrevPart := l_Cell;
l_Cell := l_Cell.GetContinueCell(True, fc_Down);
if aCheckPrev then
begin
l_PrevPart.IntW[k2_tiWidth, anOpPack] := l_PrevPart.IntA[k2_tiWidth] - aDelta;
l_PrevPara := l_PrevPart.Prev;
l_PrevPara.IntW[k2_tiWidth, anOpPack] := l_PrevPara.IntA[k2_tiWidth] + aDelta;
end // if aCheckPrev then
else
l_PrevPart.IntW[k2_tiWidth, anOpPack] := l_Width;
if (ssShift in Keys.rKeys) then
begin
l_NexCell := l_PrevPart.Next;
if l_NexCell.IsValid then
l_NexCell.IntW[k2_tiWidth, anOpPack] := l_NexCell.IntA[k2_tiWidth] - aDelta;
end; // if l_WasShift then
end; // while l_Cell <> nil do
end; // with aPara do
end;
var
l_Para : InevPara;
l_Next : InevPara;
//#UC END# *4ED3220102EE_4ED31E9500E7_var*
begin
//#UC START# *4ED3220102EE_4ED31E9500E7_impl*
l_Para := aRow[ColumnID - 1];
with l_Para do
begin
l_Width := IntA[k2_tiWidth];
Inc(l_Width, aDelta);
if (l_Width > 100) then
begin
if TevMergeStatus(IntA[k2_tiMergeStatus]) = ev_msNone then
begin
l_Next := l_Para.Next;
if l_Next.IsValid and (TevMergeStatus(l_Next.IntA[k2_tiMergeStatus]) <> ev_msNone) then
lp_ChangeHeadWidth(l_Next, True)
else
IntW[k2_tiWidth, anOpPack] := l_Width;
end // if TevMergeStatus(l_Para.IntA[k2_tiMergeStatus]) = ev_msNone then
else
lp_ChangeHeadWidth(l_Para, False);
end; // if (l_Delta > 100) then
end; // with l_Para do
aProcessor.Lock;
try
aView.Control.SetFlag(ev_uwfRuler);
finally
aProcessor.Unlock;
end;//#UC END# *4ED3220102EE_4ED31E9500E7_impl*
end;//TevTableColumnHotSpot.ChangeCellWidth
function TevTableColumnHotSpot.CanChangeTable(const aView: InevControlView;
const aPara: InevTag): Boolean;
//#UC START# *4ED3227A01E5_4ED31E9500E7_var*
//#UC END# *4ED3227A01E5_4ED31E9500E7_var*
begin
//#UC START# *4ED3227A01E5_4ED31E9500E7_impl*
if (aView.Control = nil) OR not Supports(aView.Control, IevF1LikeEditor) then
Result := true
else
Result := evInPara(aPara, k2_idCommentPara);
//#UC END# *4ED3227A01E5_4ED31E9500E7_impl*
end;//TevTableColumnHotSpot.CanChangeTable
constructor TevTableColumnHotSpot.Create(const aView: InevControlView;
const aPara: InevTag;
aColumnID: Integer;
const aHint: Il3CString;
aDelta: Integer);
//#UC START# *4ED322C700D3_4ED31E9500E7_var*
//#UC END# *4ED322C700D3_4ED31E9500E7_var*
begin
//#UC START# *4ED322C700D3_4ED31E9500E7_impl*
inherited Create(aView, aPara, aColumnID, aHint);
f_Delta := aDelta;
f_CanChangeTable := CanChangeTable(aView, aPara);
//#UC END# *4ED322C700D3_4ED31E9500E7_impl*
end;//TevTableColumnHotSpot.Create
class function TevTableColumnHotSpot.Make(const aView: InevControlView;
const aPara: InevTag;
aColumnID: Integer;
const aHint: Il3CString = nil;
aDelta: Integer = 0): IevAdvancedHotSpot;
//#UC START# *4ED3231B03D7_4ED31E9500E7_var*
var
l_Spot : TevTableColumnHotSpot;
//#UC END# *4ED3231B03D7_4ED31E9500E7_var*
begin
//#UC START# *4ED3231B03D7_4ED31E9500E7_impl*
l_Spot := Create(aView, aPara, aColumnID, aHint, aDelta);
try
Result := l_Spot;
finally
l3Free(l_Spot);
end;//try..finally
//#UC END# *4ED3231B03D7_4ED31E9500E7_impl*
end;//TevTableColumnHotSpot.Make
procedure TevTableColumnHotSpot.HitTest(const aView: InevControlView;
const aState: TafwCursorState;
var theInfo: TafwCursorInfo);
//#UC START# *48E2622A03C4_4ED31E9500E7_var*
//#UC END# *48E2622A03C4_4ED31E9500E7_var*
begin
//#UC START# *48E2622A03C4_4ED31E9500E7_impl*
{$IfDef evChangeTableByMouse}
if f_CanChangeTable then
begin
theInfo.rCursor := ev_csHSplit;
if (ssCtrl in aState.rKeys) then
theInfo.rHint := Hint
else
begin
if (ssShift in aState.rKeys) AND
(ColumnID = Para.ChildrenCount) then
theInfo.rHint := str_nevmhhTableSize.AsCStr
else
theInfo.rHint := str_nevmhhColumnSize.AsCStr;
end;//ssCtrl in aState.rKeys
end;//f_CanChangeTable
{$EndIf evChangeTableByMouse}
//#UC END# *48E2622A03C4_4ED31E9500E7_impl*
end;//TevTableColumnHotSpot.HitTest
function TevTableColumnHotSpot.MouseAction(const aView: InevControlView;
aButton: Tl3MouseButton;
anAction: Tl3MouseAction;
const Keys: TevMouseState;
var Effect: TevMouseEffect): Boolean;
//#UC START# *48E263CD01BD_4ED31E9500E7_var*
var
l_Processor : InevProcessor;
l_OpPack : InevOp;
l_Delta : Integer;
l_Column : IedColumn;
l_Row : InevParaList;
l_Table : InevParaList;
//#UC END# *48E263CD01BD_4ED31E9500E7_var*
begin
//#UC START# *48E263CD01BD_4ED31E9500E7_impl*
{$IfDef evChangeTableByMouse}
if f_CanChangeTable then
begin
case aButton of
ev_mbLeft :
begin
case anAction of
ev_maDown :
begin
Effect.rStrob := afw_stVert;
Result := True;
end;//ev_maDown
ev_maUp :
begin
l_Delta := Keys.rPoint.X - Keys.rInitialPoint.X;
l_Delta := evCheckCellWidth(l_Delta);
if (ClientValue + l_Delta > 100) AND
(aView <> nil) then
try
l_Processor := aView.Processor; //Processor;
l_OpPack := k2StartOp(l_Processor, ev_msgChangeParam);
try
l_Row := Para.AsList;
if not (ssCtrl in Keys.rKeys) then
begin
l_Table := l_Row.OwnerPara;
if (ssShift in Keys.rKeys) then
begin
if (ColumnID = l_Row.ChildrenCount) then
begin
Result := ProportionalChangeWidth(l_Table, l_Delta, l_OpPack);
l_Table.Invalidate([nev_spExtent]);
//aView._InvalidateShape(l_Table.Shape, True);
// - так как написано срочкой выше, так правильнее
Exit;
end//Column = l_Row.ChildrenCount
else
begin
if l3IOk(evQueryParaInterface(aView, l_Processor, l_Row[ColumnID],
Tl3GUID_C(IedColumn), l_Column)) then
try
l_Column.Width := l_Column.Width - l_Delta;
finally
l_Column := nil;
end;//try..finally
end;//Column = l_Row.ChildrenCount
end;//Keys.rKeys AND MK_Shift <> 0
l_Table.MakePoint.Formatting.Modify(aView).ChangeParam(aView, Self, Value + l_Delta, l_OpPack);
end//not (ssCtrl in Keys.rKeys)
else
ChangeCellWidth(aView, l_Processor, l_OpPack, Keys, l_Row, l_Delta);
finally
l_OpPack := nil;
end;//try..finally
finally
l_Processor := nil;
end;//try..finally
Result := True;
end;//ev_maUp
ev_maMove : begin
Result := (ClientValue + Keys.rPoint.X - Keys.rInitialPoint.X) > 100;
end;//ev_maMove
else
Result := False;
end;//case anAction
end;//ev_mbLeft
else
Result := False;
end;//case aButton
end//f_CanChangeTable
else
Result := false;
{$Else evChangeTableByMouse}
Result := False;
{$EndIf evChangeTableByMouse}//#UC END# *48E263CD01BD_4ED31E9500E7_impl*
end;//TevTableColumnHotSpot.MouseAction
function TevTableColumnHotSpot.Delta: Integer;
//#UC START# *4A23A71A02CC_4ED31E9500E7_var*
//#UC END# *4A23A71A02CC_4ED31E9500E7_var*
begin
//#UC START# *4A23A71A02CC_4ED31E9500E7_impl*
Result := f_Delta;
//#UC END# *4A23A71A02CC_4ED31E9500E7_impl*
end;//TevTableColumnHotSpot.Delta
function TevTableColumnHotSpot.CanDrag: Boolean;
//#UC START# *4ECCD6840014_4ED31E9500E7_var*
//#UC END# *4ECCD6840014_4ED31E9500E7_var*
begin
//#UC START# *4ECCD6840014_4ED31E9500E7_impl*
Result := False;
//#UC END# *4ECCD6840014_4ED31E9500E7_impl*
end;//TevTableColumnHotSpot.CanDrag
end. |
//Exercício 12: Escreva um algoritmo que calcule e exiba o custo médio do quilômetro rodado (considerando apenas o
//consumo de combustível) para uma dada distância percorrida e certo volume de combustível consumido. O algoritmo
//deve ler a distância percorrida (em quilômetros), o volume de combustível consumido (em litros) e o preço do litro
//do combustível.
{ Solução em Portugol
Algoritmo Exercicio12 ;
Var
volume_combustivel, distancia_percorrida, preco_litro, custo_medio: real;
Inicio
exiba("Programa que calcula o custo médio do quilômetro rodado por um veículo.");
exiba("Digite a distância percorrida pelo veículo:");
leia(distancia_percorrida);
exiba("Digite o volume de comsbustível consumido pelo veículo:");
leia(volume_combustivel);
exiba("Digite a preço do litro de combustível:");
leia(preco_litro);
custo_medio <- (volume_combustivel * preco_litro)/distancia_percorrida;
exiba("O custo médio do quilômetro rodado é:", custo_medio);
Fim.
}
// Solução em Pascal
Program Exercicio12;
uses crt;
var
volume_combustivel, distancia_percorrida, preco_litro, custo_medio: real;
begin
clrscr;
writeln('Programa que calcula o custo médio do quilômetro rodado por um veículo.');
writeln('Digite a distância percorrida pelo veículo em km:');
readln(distancia_percorrida);
writeln('Digite o volume de comsbustível consumido pelo veículo em litros:');
readln(volume_combustivel);
writeln('Digite a preço do litro de combustível em reais:');
readln(preco_litro);
custo_medio := (volume_combustivel * preco_litro)/distancia_percorrida;
writeln('O custo médio do quilômetro rodado é:', custo_medio:0:2,' reais por km.');
repeat until keypressed;
end. |
(* WordCounter: HDO, 2003-02-28 *)
(* ----------- *)
(* Template for programs that count words in text files. *)
(*===============================================================*)
PROGRAM WordCounter;
USES
Timer, WordReader, ModBinarySearchTree;
VAR
c, maxC : integer;
mostFreqWord : string;
w: Word;
n: LONGINT;
BEGIN (*WordCounter*)
init();
WriteLn('WordCounter:');
OpenFile('Kafka.txt', toLower);
StartTimer;
n := 0;
maxC := 0;
ReadWord(w);
WHILE w <> '' DO BEGIN
n := n + 1;
c := addOrInc(w);
if c > maxC then begin
maxC := c;
mostFreqWord := w;
end;
ReadWord(w);
END; (*WHILE*)
StopTimer;
CloseFile;
WriteLn('number of words: ', n);
WriteLn('elapsed time: ', ElapsedTime);
writeLn('Most frequent word ', mostFreqWord, ' ', maxC);
END. (*WordCounter*)
|
(**********************************************)
(* Проверка правильности задания и вычисление *)
(* значений функций нескольких переменных *)
(* Function Analizer 32 bit *)
(* (c) Вшивцев Виктор (W. Vitek) *)
(**********************************************)
unit FA32;
interface
uses SysUtils;
const
ferUnknownId =1;
ferRightBracket=2;
ferComma =3;
ferLeftBracket =4;
ferNumFormat =5;
ferNumValue =6;
ferNothing =7;
ferEOL =8;
ferSyntax =9;
ferMessage:array[1..9] of String=(
'Неизвестный идентификатор',
'Ожидается закрывающая скобка ")"',
'Ожидается запятая',
'Ожидается открывающая скобка "("',
'Неправильный формат числа',
'Неподдерживаемое значение числа',
'Отсутствует выражение',
'Ожидается конец выражения',
'Синтаксическая ошибка');
DigitsSet:set of char=['0'..'9'];
CharsSet:set of char=['A'..'Z','a'..'z','А'..'Я','а'..'я','_'];
type
E_FA32_Error=class(Exception);
TExtendedFunction=function:Extended;
TDynamicSizeBuffer=object
Addr:pointer;
Size,Pos,Delta:Integer;
constructor Init(ADelta:Integer);
procedure Write(var B; W:Integer);
destructor Done;
procedure GrowBuffer;
end;
PVariableRecord=^TVariableRecord;
{ В записи TVariableRecord запоминается
имя (Name) и адрес (Addr) переменной }
TVariableRecord=record
Next:PVariableRecord;
Addr:pointer;
Name:PString;
end;
PFunctionRecord=^TFunctionRecord;
{ В записи TFunctionRecord запоминается идентификатор (Name) функции, }
{ ее адрес(Addr) и количество аргументов (ArgCnt) }
TFunctionRecord=record
Next:PFunctionRecord;
Addr:pointer;
Name:PString;
ArgCnt:Integer;
end;
{Объект "Функция"}
TFunction=object
private
Code:TDynamicSizeBuffer;
VariablesList:PVariableRecord;
function GetFunPtr(var s:string;var i:Integer):PFunctionRecord;
function GetVarPtr(var s:string;var i:Integer):PVariableRecord;
function GetVariable(const Name:String):PVariableRecord;
procedure PushValue(X:Extended);
procedure PushMemoryReference(var X:Extended);
procedure CallFunction(P:Pointer);
procedure GenerateOpCode(c:Char);
public
ErrorCode:integer;
GetValue:TExtendedFunction;
constructor Init;
function Compile(var s:string):Integer;
procedure AssignVar(const Name:String;var m:Extended);
destructor Done;
end;
{ Регистрирует функцию в списке }
{ Если функция незарегистрирована, то ее использование }
{ приведет к ошибке 'Неизвестный идентификатор' }
procedure RegisterFunction(const Name:String;ArgCnt:Integer;Addr:pointer);
procedure MakeUpCase(var Str:String);
{ Удаляет все пробелы из строки }
procedure DeleteSpaces(var Str:String);
{Удаляет "мусор" из строки (повторяющиеся знаки '+' и '-' и т.п.)}
procedure CheckSignes(var S:string);
implementation
uses Math;
// TDynamicSizeBuffer
constructor TDynamicSizeBuffer.Init;
begin
FillChar(Self,SizeOf(Self),0);
Delta:=ADelta;
end;
procedure TDynamicSizeBuffer.Write;
begin
while Pos+W>Size do GrowBuffer;
Move(B,Ptr(Integer(Addr)+Pos)^,W);
Inc(Pos,W);
end;
destructor TDynamicSizeBuffer.Done;
begin
if Addr<>nil then FreeMem(Addr,Size);
Size:=0;
Pos:=0;
Addr:=nil;
end;
procedure TDynamicSizeBuffer.GrowBuffer;
var
P:Pointer;
begin
GetMem(P,Size+Delta);
Move(Addr^,P^,Pos);
FreeMem(Addr,Size);
Addr:=P;
Inc(Size,Delta);
end;
const
OpersSet:set of char=['+','-','/','*'];
var
FunctionsList:PFunctionRecord; { Указатель на список известных функций }
PiValue:Extended;
Tmp:PFunctionRecord absolute PiValue;
procedure MakeUpCase(var Str:String);
var
i:Integer;
begin
for i:=1 to Length(Str) do Str[i]:=UpCase(Str[i]);
end;
procedure DeleteSpaces(var Str:String);
var
i:Integer;
begin
i:=1;
while i<=Length(Str)
do begin
if Str[i]=' ' then Delete(Str,i,1) else Inc(i);
end;
end;
procedure CheckSignes(var S:string);
const
Sgns:set of char=['-','+'];
var
q:boolean;
i:Integer;
begin
repeat
q:=True;
i:=1;
while i<Length(S) do
begin
if (s[i] in Sgns) and (s[succ(i)] in Sgns) then
begin
q:=False;
if s[i]=s[succ(i)] then
begin
Delete(s,i,2);
if (i>1) AND (s[i-1] in (CharsSet+DigitsSet+[')'])) then
Insert('+',s,i);
end
else if s[i]='+' then
Delete(s,i,1)
else
Delete(s,succ(i),1);
end
else
Inc(i);
end;
until q;
end;
procedure RegisterFunction(const Name:String;ArgCnt:Integer;Addr:pointer);
var
p:PFunctionRecord;
begin
New(p); p^.Next:=FunctionsList; FunctionsList:=p;
p^.Name:=NewStr(Name); MakeUpCase(p^.Name^);
p^.Addr:=Addr; p^.ArgCnt:=ArgCnt;
end;
function Angle(X,Y: Extended): Extended;
asm
FLD Y
FLD X
FPATAN
FWAIT
end;
function mNegate(x:Extended):Extended;assembler;
asm
fld x
fchs
end;
function mSIN(r:Extended):Extended;
begin
mSIN:=sin(r);
end;
function mCOS(r:Extended):Extended;
begin
mCOS:=cos(r);
end;
function mArcTg(r:Extended):Extended;
begin
mArcTg:=arctan(r);
end;
function mEXP(r:Extended):Extended;
begin
mEXP:=EXP(r);
end;
function mABS(r:Extended):Extended;
begin
mABS:=abs(r);
end;
function mLN(r:Extended):Extended;
begin
mLN:=ln(r);
end;
function mSqrt(r:Extended):Extended;
begin
mSqrt:=Sqrt(r);
end;
function mSqr(r:Extended):Extended;
begin
mSqr:=Sqr(r);
end;
function mArcTan(r:Extended):Extended;
begin
mArcTan:=ArcTan(r);
end;
function Power(r1,r2:Extended):Extended;
begin
if r1=0
then Power:=0
else Power:=Exp(r2*ln(Abs(r1)));
end;
function Sign(r:Extended):Extended;
begin
if r<0
then Sign:=-1
else if r=0
then Sign:=0
else Sign:=1;
end;
{Если функция с именем Name найдена в списке регистрации,}
{ то возвращает указатель на ее регистрационную запись}
{ иначе возвращает NIL}
function GetFunction(const Name:String):PFunctionRecord;
var
p:PFunctionRecord;
begin
p:=FunctionsList;
while (p<>nil) and (p^.Name^<>Name) do
p:=p^.Next;
GetFunction:=p;
end;
function NotCompiled:Extended;
begin
raise E_FA32_Error.Create('FA32: Function not compiled');
end;
function ToStr(var P; Size:Integer):String;
var
i:Integer;
begin
Result:='';
for i:=0 to Size-1
do Result:=Result+Char(Ptr(Integer(Addr(P))+i)^);
end;
(* TFunction *)
constructor TFunction.Init;
begin
VariablesList:=nil;
Code.Init(32);
GetValue:=NotCompiled;
AssignVar('pi',PiValue);
end;
{Формирует код помещения в стек значения типа Extended}
procedure TFunction.PushValue;
var
w:array[0..2] of Integer absolute X;
k:Integer;
s:String;
begin
s:='';
for k:=2 downto 0
do s:=s+#$68+ToStr(w[k],4); { push immed32 }
Code.Write(s[1],Length(s));
end;
{Формирует код помещения в стек значения переменной типа Extended}
procedure TFunction.PushMemoryReference;
var
k,P:integer;
t:String;
begin
P:=Integer(Addr(X))+8;
t:='';
for k:=0 to 2
do begin
t:=t+#$FF#$35 + ToStr(P,4); { push dword ptr [P-k*4] }
Dec(P,4);
end;
Code.Write(t[1],Length(t));
end;
{Формирует код обращения к функции и помещения в стек}
{полученного значения типа Extended (из регистра ST(0) FPU)}
procedure TFunction.CallFunction;
var
s:String;
begin
s:=
#$B8+ToStr(P,4) + { mov eax,P }
#$FF#$D0 + { call eax }
#$83#$EC#$0C + { sub esp,12 }
#$89#$E5 + { mov ebp,esp }
#$DB#$7D#$00; { fstp Extended([bp]) }
Code.Write(s[1],Length(s));
end;
function TFunction.GetVarPtr(var s:string;var i:Integer):PVariableRecord;
var
Name:String absolute s;
p:PVariableRecord;
c:Integer;
begin
GetVarPtr:=nil;
if i>Length(S) then exit;
c:=i;
while (c<=Length(S)) and (s[c] in (CharsSet+DigitsSet)) do Inc(c);
s:=Copy(s,i,c-i);
p:=GetVariable(Name);
if p<>nil
then begin
i:=pred(c);
GetVarPtr:=p;
end;
end;
function TFunction.GetFunPtr;
var
p:PFunctionRecord;
Name:String;
c:Integer;
begin
GetFunPtr:=nil;
if i>Length(S) then exit;
c:=i;
while (c<=Length(S)) and (s[c] in (CharsSet+DigitsSet)) do Inc(c);
Name:=Copy(s,i,c-i);
p:=GetFunction(Name);
if p<>nil then
begin
if (s[c]<>'(') or (c>Length(S))
then begin
Inc(c); ErrorCode:=ferRightBracket;
end;
i:=pred(c);
GetFunPtr:=p;
end;
end;
function TFunction.GetVariable;
var
p:PVariableRecord;
begin
p:=VariablesList;
while (p<>nil) and (p^.Name^<>Name) do p:=p^.Next;
GetVariable:=p;
end;
procedure TFunction.AssignVar;
var
p:PVariableRecord;
begin
New(p); p^.Next:=VariablesList; VariablesList:=p;
p^.Name:=NewStr(Name); MakeUpCase(p^.Name^); p^.Addr:=Addr(m);
end;
destructor TFunction.Done;
var
pl:PVariableRecord;
begin
Code.Done;
while VariablesList<>nil do
begin
pl:=VariablesList;
VariablesList:=pl^.Next;
Dispose(pl);
end;
end;
procedure TFunction.GenerateOpCode;
var
s:String;
o:Char;
begin
s:=#$89#$E5; { mov ebp,esp }
if c<>'_'
then s:=s+#$DB#$6D#$0C; { fld Extended([ebp+12]) }
s:=s+#$DB#$6D#$00; { fld Extended([ebp]) }
if c='_'
then begin
s:=s+#$D9#$E0; {fchs}
end
else begin
case c of
'+':o:=#$C1; {fadd}
'-':o:=#$E9; {fsub}
'*':o:=#$C9; {fmul}
else{'/':}o:=#$F9; {fdiv}
end;
s:=s+#$DE+o;
end;
if c<>'_'
then begin
s:=s+#$83#$C4#$0C+ { add esp,12 }
#$DB#$7D#$0C { fstp Extended([ebp+12]) }
end
else s:=s+#$DB#$7D#$00; { fstp Extended([bp]) }
Code.Write(s[1],Length(s));
end;
function TFunction.Compile(var S:String):Integer;
var
Pos,Error:Integer;
function NextChar:Char;
begin
if Pos>Length(S)
then NextChar:=#0
else NextChar:=S[Pos];
end;
procedure AcceptChar;
begin
Inc(Pos);
end;
function T:Boolean;forward;
function F:Boolean;forward;
{ E = T [+T|-T] }
function E:Boolean;
var
c:Char;
begin
if T
then begin
repeat
c:=NextChar;
if (c='-')or(c='+')
then begin
AcceptChar;
if T then GenerateOpCode(c);
end
else c:=#0;
until (c=#0) or (Error<>0);
end;
E:=Error=0;
end;
{ T = F [*F|/F] }
function T:Boolean;
var
c:Char;
begin
if F
then begin
repeat
c:=NextChar;
if (c='*')or(c='/')
then begin
AcceptChar;
if F then GenerateOpCode(c);
end
else c:=#0;
until (c=#0) or (Error<>0);
end;
T:=Error=0;
end;
function IsDigit(c:Char):Boolean;
begin
IsDigit:=('0'<=c)and(c<='9');
end;
function Number:Boolean;
function Digits:Boolean;
begin
if IsDigit(NextChar)
then begin
repeat
AcceptChar;
until not IsDigit(NextChar);
Digits:=True;
end
else begin
Error:=ferNumFormat;
Digits:=False;
end;
end;
var
Value:Extended;
ErrPos:Integer;
b:Integer;
c:Char;
Sign:Boolean;
begin
b:=Pos;
Sign:=NextChar='-';
if Sign then AcceptChar;
if Digits
then begin
if NextChar='.'
then begin
AcceptChar;
Digits;
end;
if (Error=0)and(NextChar='E')
then begin
AcceptChar;
c:=NextChar;
if (c='-') or (c='+')
then begin
AcceptChar;
Digits;
end
else Error:=ferNumFormat;
end;
if Error=0
then begin
Val(Copy(S,b,Pos-b),Value,ErrPos);
if ErrPos<>0
then begin
Error:=ferNumValue;
Pos:=b;
end
else begin
PushValue(Value); Sign:=True;
end;
end;
end
else begin
if Sign then Dec(Pos);
Sign:=False; Error:=0;
end;
Number:=(Error=0)and Sign;
end;
function IsFunction:Boolean;
var
P:PFunctionRecord;
b:Integer;
begin
P:=nil;
b:=Pos;
while IsDigit(NextChar) or (NextChar in CharsSet) do AcceptChar;
if Pos-b>0
then begin
P:=GetFunction(Copy(s,b,Pos-b));
if P<>nil
then begin
if P^.ArgCnt=0
then
else if NextChar='('
then begin
AcceptChar;
for b:=P^.ArgCnt downto 1
do begin
if E
then begin
if (b>1)
then begin
if (NextChar<>',')
then begin
Error:=ferComma; break;
end
else AcceptChar;
end;
end
else break;
end;
if Error=0
then begin
if NextChar=')'
then begin
AcceptChar;
CallFunction(P^.Addr);
end
else Error:=ferRightBracket;
end;
end
else Error:=ferLeftBracket;
end
else Pos:=b;
end;
IsFunction:=(P<>nil)and(Error=0);
end;
function IsVariable:Boolean;
var
P:PVariableRecord;
b:Integer;
begin
P:=nil;
b:=Pos;
while IsDigit(NextChar) or (NextChar in CharsSet) do AcceptChar;
if Pos-b>0
then begin
P:=GetVariable(Copy(s,b,Pos-b));
if P<>nil
then PushMemoryReference(Extended(P^.Addr^))
else Pos:=b;
end;
IsVariable:=P<>nil;
end;
function F:Boolean;
var
c:Char;
begin
c:=NextChar;
if c='('
then begin
AcceptChar;
if E
then begin
if NextChar=')'
then AcceptChar
else Error:=ferRightBracket
end;
end
else if (not Number) and (Error=0)
then begin
if (c='-')
then begin
AcceptChar;
if F then GenerateOpCode('_');
end
else if c in CharsSet
then begin
if (not IsFunction) and (Error=0) and not IsVariable
then Error:=ferUnknownId;
end
else Error:=ferSyntax;
end;
F:=Error=0;
end;
var
ts:String;
begin
Code.Done;
GetValue:=NotCompiled;
Pos:=1;
if NextChar<>#0
then begin
Error:=0;
MakeUpCase(S); DeleteSpaces(S); CheckSignes(S);
ts:=
#$55 + { push ebp }
#$DB#$E3;{ finit }
Code.Write(ts[1],Length(ts));
if E
then begin
if (NextChar=#0)
then begin
Pos:=0;
ts:=
#$89#$E5 + { mov ebp,esp }
#$DB#$6D#$00 + { fld Extended([ebp]) }
#$83#$C4#$0C + { add esp,12 }
#$5D + { pop ebp }
#$C3; { ret }
Code.Write(ts[1],Length(ts));
@GetValue:=Code.Addr;
end
else Error:=ferEOL;
end;
end
else Error:=ferNothing;
ErrorCode:=Error;
if Error<>0
then Code.Done;
Compile:=Pos;
end;
initialization
FunctionsList:=nil;
{ Регистрируем стандартные функции в списке }
RegisterFunction('sin',1,@mSIN);
RegisterFunction('cos',1,@mCOS);
RegisterFunction('tan',1,@Tan);
RegisterFunction('cotan',1,@Cotan);
RegisterFunction('arctan',1,@mArcTg);
RegisterFunction('angle',2,@Angle);
RegisterFunction('arcsin',1,@ArcSin);
RegisterFunction('arccos',1,@ArcCos);
RegisterFunction('length',2,@Hypot);
RegisterFunction('exp',1,@mEXP);
RegisterFunction('abs',1,@mABS);
RegisterFunction('sqr',1,@mSqr);
RegisterFunction('sqrt',1,@mSqrt);
RegisterFunction('ln',1,@mLN);
RegisterFunction('power',2,@Power);
RegisterFunction('sign',1,@Sign);
PiValue:=Pi;
finalization
while FunctionsList<>nil
do begin
Tmp:=FunctionsList;
FunctionsList:=Tmp^.Next;
DisposeStr(Tmp^.Name);
Dispose(Tmp);
end;
end.
|
namespace Sugar.Collections;
interface
uses
Sugar;
type
KeyValuePair<T, U> = public class
public
constructor(aKey: T; aValue: U);
method {$IF TOFFEE}isEqual(obj: id){$ELSE}&Equals(Obj: Object){$ENDIF}: Boolean; override;
method {$IF COOPER}ToString: java.lang.String{$ELSEIF ECHOES}ToString: System.String{$ELSEIF TOFFEE}description: Foundation.NSString{$ENDIF}; override;
method {$IF COOPER}hashCode: Integer{$ELSEIF ECHOES}GetHashCode: Integer{$ELSEIF TOFFEE}hash: Foundation.NSUInteger{$ENDIF}; override;
property Key: T read write; readonly;
property Value: U read write; readonly;
method GetTuple: tuple of (T,U);
end;
{$IF Cooper}
{$ELSE}
[Obsolete('Use KeyValuePair<T, U> class instead.')]
{$ENDIF}
KeyValue<T, U> = public class(KeyValuePair<T,U>);
implementation
constructor KeyValuePair<T,U>(aKey: T; aValue: U);
begin
if aKey = nil then
raise new SugarArgumentNullException("Key");
Key := aKey;
Value := aValue;
end;
method KeyValuePair<T, U>.{$IF TOFFEE}isEqual(obj: id){$ELSE}&Equals(Obj: Object){$ENDIF}: Boolean;
begin
if Obj = nil then
exit false;
if not (Obj is KeyValuePair<T,U>) then
exit false;
var Item := KeyValuePair<T, U>(Obj);
result := Key.Equals(Item.Key) and ( ((Value = nil) and (Item.Value = nil)) or ((Value <> nil) and Value.Equals(Item.Value)));
end;
method KeyValuePair<T, U>.{$IF COOPER}hashCode: Integer{$ELSEIF ECHOES}GetHashCode: Integer{$ELSEIF TOFFEE}hash: Foundation.NSUInteger{$ENDIF};
begin
result := Key.GetHashCode + Value:GetHashCode;
end;
method KeyValuePair<T, U>.{$IF COOPER}ToString: java.lang.String{$ELSEIF ECHOES}ToString: System.String{$ELSEIF TOFFEE}description: Foundation.NSString{$ENDIF};
begin
result := String.Format("Key: {0} Value: {1}", Key, Value);
end;
method KeyValuePair<T, U>.GetTuple: tuple of (T,U);
begin
result := (Key, Value);
end;
end. |
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm2 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
var
FZnamky: TextFile;
znamky: string;
cislo: integer;
sucet: integer;
pocet: integer;
priemer: real;
begin
AssignFile(FZnamky, 'znamky.txt');
Reset(FZnamky);
Memo1.Lines.Clear;
Reset(FZnamky);
while Not EOF(FZnamky) do
begin
ReadLN(FZnamky, znamky);
Memo1.Lines.Add(znamky);
sucet:=0;
cislo:=0;
pocet:=0;
while NOT EOLN(FZnamky) do
begin
Read(FZnamky, cislo);
sucet:= sucet + cislo;
inc(pocet);
end;
priemer:= sucet/pocet;
Memo1.Lines.Add(FloatToStr(priemer));
readln(FZnamky);
end;
CloseFile(FZnamky);
end;
end.
|
unit fmRename;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
ADC.ADObject, ADC.Types, ADC.Common, ADC.AD, ADC.LDAP, ADC.GlobalVar;
type
TForm_Rename = class(TForm)
Label_Name: TLabel;
Edit_Name: TEdit;
Button_Close: TButton;
Button_Apply: TButton;
Button_OK: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button_CloseClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Button_ApplyClick(Sender: TObject);
procedure Button_OKClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
FCallingForm: TForm;
FObj: TADObject;
FCanClose: Boolean;
procedure SetCallingForm(const Value: TForm);
procedure SetObject(const Value: TADObject);
public
property CallingForm: TForm write SetCallingForm;
property ADObject: TADObject read FObj write SetObject;
end;
var
Form_Rename: TForm_Rename;
implementation
{$R *.dfm}
{ TForm_Rename }
procedure TForm_Rename.Button_CloseClick(Sender: TObject);
begin
Close;
end;
procedure TForm_Rename.Button_OKClick(Sender: TObject);
begin
Button_ApplyClick(Self);
if FCanClose then Close;
end;
procedure TForm_Rename.Button_ApplyClick(Sender: TObject);
var
MsgBoxParam: TMsgBoxParams;
begin
try
case apAPI of
ADC_API_LDAP: begin
FCanClose := FObj.Rename(LDAPBinding, Edit_Name.Text);
FObj.Refresh(LDAPBinding, List_Attributes);
end;
ADC_API_ADSI: begin
FCanClose := FObj.Rename(Edit_Name.Text);
FObj.Refresh(ADSIBinding, List_Attributes);
end;
end;
except
on E: Exception do
begin
with MsgBoxParam do
begin
cbSize := SizeOf(MsgBoxParam);
hwndOwner := Handle;
hInstance := 0;
case apAPI of
ADC_API_LDAP: lpszCaption := PChar('LDAP Exception');
ADC_API_ADSI: lpszCaption := PChar('ADSI Exception');
end;
lpszIcon := MAKEINTRESOURCE(32513);
dwStyle := MB_OK or MB_ICONHAND;
dwContextHelpId := 0;
lpfnMsgBoxCallback := nil;
dwLanguageId := LANG_NEUTRAL;
lpszText := PChar(E.Message);
end;
MessageBoxIndirect(MsgBoxParam);
end;
end;
end;
procedure TForm_Rename.FormClose(Sender: TObject; var Action: TCloseAction);
var
i: Integer;
begin
for i := 0 to Self.ControlCount - 1 do
if Self.Controls[i] is TEdit
then TEdit(Self.Controls[i]).Clear;
FCanClose := False;
if FCallingForm <> nil then
begin
FCallingForm.Enabled := True;
FCallingForm.Show;
FCallingForm := nil;
FObj := nil;
end;
end;
procedure TForm_Rename.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_ESCAPE: begin
Close;
end;
end;
end;
procedure TForm_Rename.FormShow(Sender: TObject);
begin
Edit_Name.SetFocus;
Edit_Name.SelectAll;
end;
procedure TForm_Rename.SetCallingForm(const Value: TForm);
begin
FCallingForm := Value;
if FCallingForm <> nil
then FCallingForm.Enabled := False;
end;
procedure TForm_Rename.SetObject(const Value: TADObject);
begin
FObj := Value;
if FObj <> nil then
begin
Edit_Name.Text := FObj.name;
end;
end;
end.
|
unit np.httpParser;
interface
uses np.Buffer, Generics.Collections;
type
THTTPHeader = Class(TDictionary<Utf8String,Utf8String>)
private
FKeys : TList<Utf8String>;
function GetFields(const AName: Utf8String): Utf8String;
public
ContentLength : int64;
ContentType : Utf8String;
ContentCharset: Utf8String;
procedure parse(ABuf : BufferRef);
function ToString: string; override;
constructor Create(const ABuf: BufferRef);
destructor Destroy; override;
procedure addField(const key, value: Utf8String);
procedure addSubFields(const key,value : Utf8String);
procedure Clear;
function HasField(const AName: Utf8String): Boolean;
property Fields[const AName: Utf8String]: Utf8String read GetFields; default;
property Names: TList<Utf8String> read FKeys;
end;
function CheckHttpAnswer(const buf: BufferRef; out protocol:UTF8string; out Code:integer; out Reason:UTF8string; out HeaderBuf:BufferRef; out ContentBuf: BufferRef) : Boolean;
function CheckHttpRequest(const buf: BufferRef; out method:UTF8string; out uri:UTF8string; out protocol:UTF8string; out HeaderBuf:BufferRef; out ContentBuf: BufferRef) : Boolean;
function BufCRLF : BufferRef;
function BufCRLFCRLF : BufferRef;
implementation
uses np.ut, sysUtils;
const
CONST_CRLF : array [0..3] of byte = (13,10,13,10);
function BufCRLF : BufferRef;
begin
result := BufferRef.CreateWeakRef(@CONST_CRLF,2);
end;
function BufCRLFCRLF : BufferRef;
begin
result := BufferRef.CreateWeakRef(@CONST_CRLF,4);
end;
function _CheckHttp(const buf: BufferRef; out splitedAnswer: TArray<UTF8String>; out HeaderBuf:BufferRef; out ContentBuf: BufferRef) : Boolean;
var
HeaderEndPosition : integer;
AnswerLine : UTF8String;
begin
HeaderEndPosition := buf.Find(BufCRLFCRLF);
if HeaderEndPosition < 0 then
exit(false);
HeaderBuf := Buf.slice(0,HeaderEndPosition+2);
ContentBuf := Buf.slice(HeaderEndPosition+4);
HeaderEndPosition := HeaderBuf.find(BufCRLF);
assert(HeaderEndPosition >= 0);
// SetLength(AnswerLine, HeaderEndPosition);
// move(HeaderBuf.ref^,AnswerLine[1], HeaderEndPosition);
AnswerLine := HeaderBuf.slice(0,HeaderEndPosition).AsUtf8String;
HeaderBuf.TrimL(HeaderEndPosition+2);
splitedAnswer := WildFind('* * *',AnswerLine,3);
result := true;
end;
function CheckHttpAnswer(const buf: BufferRef; out protocol:UTF8String; out Code:integer; out Reason:UTF8String; out HeaderBuf:BufferRef; out ContentBuf: BufferRef) : Boolean;
var
splitedAnswer: TArray<Utf8String>;
begin
if _CheckHttp(buf,splitedAnswer,HeaderBuf,ContentBuf) then
begin
protocol := splitedAnswer[0];
Code := StrToIntDef( splitedAnswer[1], 0 );
Reason := splitedAnswer[2];
result := true;
end
else
result := false;
end;
function CheckHttpRequest(const buf: BufferRef; out method:UTF8String; out uri:UTF8String; out protocol:UTF8String; out HeaderBuf:BufferRef; out ContentBuf: BufferRef) : Boolean;
var
splitedAnswer: TArray<Utf8String>;
begin
if _CheckHttp(buf,splitedAnswer,HeaderBuf,ContentBuf) then
begin
protocol := splitedAnswer[2];
uri := splitedAnswer[1];
method := splitedAnswer[0];
result := true;
end
else
result := false;
end;
constructor THTTPHeader.Create(const ABuf: BufferRef);
begin
inherited Create(32);
FKeys := TList<Utf8String>.Create();
FKeys.Capacity := 32;
parse(ABuf);
end;
destructor THTTPHeader.Destroy;
begin
inherited;
FreeAndNil(FKeys);
end;
procedure THTTPHeader.addField(const key, value: Utf8String);
var
newKey : Utf8String;
lcount:integer;
begin
assert(assigned( FKeys ));
newKey := key;
lcount := 1;
while ContainsKey(Newkey) do
begin
newKey := Format('%s(%d)',[key,lcount]);
inc(lcount);
end;
FKeys.Add(newKey);
Add(newKey,StrRemoveQuote(Value));
end;
procedure THTTPHeader.Clear;
begin
FKeys.Clear;
inherited Clear;
ContentLength:=0;
ContentType :='';
ContentCharset := '';
end;
function THTTPHeader.GetFields(const AName: Utf8String): Utf8String;
begin
if not TryGetValue(AName,result) then
Result := '';
end;
function THTTPHeader.HasField(const AName: Utf8String): Boolean;
begin
Result := ContainsKey(AName);
end;
{ THTTPHeader }
procedure THTTPHeader.parse(ABuf: BufferRef);
var
i : integer;
tmp,line : BUfferREf;
key,value: BufferRef;
s : Utf8String;
begin
tmp := ABuf;
while tmp.length > 0 do
begin
i := tmp.Find( bufCRLF );
if i < 0 then
begin
line := tmp;
tmp := Buffer.Null;
end
else
begin
line := tmp.slice(0,i);
tmp.TrimL(i+2);
end;
for i := 0 to line.length-1 do
begin
if line.ref[i] <> ord(':') then
continue;
key := line.slice(0,i);
value := line.slice(i+1);
AddSubFields( trim( LowerCase( key.AsUtf8String ) ), trim(value.AsUtf8String) );
break;
end;
end;
TryGetValue('content-type',ContentType);
TryGetValue('content-type.charset', ContentCharset);
if TryGetValue('content-length',s) and
TryStrToInt64(s,ContentLength) then;
end;
procedure THttpHeader.addSubFields(const key,value : Utf8string);
var
values, kv: TArray<Utf8String>;
k : integer;
begin
if (key = 'date') or (Key = 'expires') or (Key='server') or (key='cashe-control')
or (Key = 'user-agent') then
begin
addField(Key,Value);
end
else
begin
SplitString( Value,values, [';',',',' ']);
if length(values) > 0 then
begin
if SplitString( values[0], kv,['='] ) = 1 then
begin
addField(key,trim(kv[0]));
end;
for k := 0 to length(values)-1 do
begin
SplitString( values[k], kv,['='] );
if (k=0) and (length(kv)=1) then
continue;
SetLength(kv,2);
kv[0] := LowerCase(trim(kv[0]));
addField(key+'.'+kv[0],trim(kv[1]));
end;
end;
end;
end;
function THTTPHeader.ToString: string;
var
k : string;
sb : TStringBuilder;
begin
if (Count = 0) then
exit('(empty)')
else
begin
sb := TStringBuilder.Create;
try
for k in FKeys do
begin
sb.Append(k).Append(' = ').Append(Fields[k]).AppendLine;
end;
result := sb.toString;
finally
sb.Free;
end;
end;
end;
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uEditRecordParametersImpl.pas }
{ Описание: Реализация IEditRecordParameters }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uEditRecordParametersImpl;
interface
uses
SysUtils, Classes, uEditRecordParameters;
function CreateEditRecordParameters: IEditRecordParameters;
implementation
uses
uKeyValue;
type
TEditRecordParameters = class(TInterfacedObject, IEditRecordParameters)
private
FDefaultValues: IInterfaceList;
FRecordId: Variant;
public
constructor Create;
procedure AddDefaultValue(AFieldName: String; AValue: Variant); stdcall;
function GetCount: Integer;
function GetDefaultValues(Index: Integer): IKeyValue;
function GetRecordId: Variant; stdcall;
procedure SetRecordId(Value: Variant); stdcall;
property Count: Integer read GetCount;
property DefaultValues[Index: Integer]: IKeyValue read GetDefaultValues;
property RecordId: Variant read GetRecordId write SetRecordId;
end;
{
**************************** TEditRecordParameters *****************************
}
constructor TEditRecordParameters.Create;
begin
inherited Create;
FDefaultValues := TInterfaceList.Create();
end;
procedure TEditRecordParameters.AddDefaultValue(AFieldName: String; AValue:
Variant);
begin
FDefaultValues.Add(CreateKeyValue(AFieldName, AValue));
end;
function TEditRecordParameters.GetCount: Integer;
begin
Result := FDefaultValues.Count;
end;
function TEditRecordParameters.GetDefaultValues(Index: Integer): IKeyValue;
begin
Supports(FDefaultValues[Index], IKeyValue, Result);
end;
function TEditRecordParameters.GetRecordId: Variant;
begin
Result := FRecordId;
end;
procedure TEditRecordParameters.SetRecordId(Value: Variant);
begin
if FRecordId <> Value then
begin
FRecordId := Value;
end;
end;
function CreateEditRecordParameters: IEditRecordParameters;
begin
Result := TEditRecordParameters.Create;
end;
end.
|
unit LumberMill;
interface
uses
ClassStorageInt, Protocol, Kernel, WorkCenterBlock, Surfaces, OutputEvaluators, Accounts,
StdFluids, BackupInterfaces, Inventions, Languages, PolluterWorkCenter, Population;
type
TLumberMillBlock = class;
TLumberOutputEvaluator = class;
TMetaLumberMillBlock =
class(TMetaPolluterWorkCenterBlock)
public
constructor Create(anId : string;
aCapacities : array of TFluidValue;
aChemicalMax : TFluidValue;
aMaxWoodPerHour : TFluidValue;
aWoodMaxVol : single;
aMinExpVol : single;
aGrowTime : integer;
aMaxBudget : TMoney;
aBlockClass : CBlock);
private
fMaxWoodVol : single;
fMinExpVol : single;
fGrowRate : single;
end;
TLumberOutputEvaluator =
class(TOutputEvaluator)
public
function BiasOpenLimit(Block : TBlock) : TBiasRatio; override;
end;
TLumberMillBlock =
class(TPolluterWorkCenterBlock)
private
fTimberVolume : single;
fGrowing : boolean;
protected
function Evaluate : TEvaluationResult; override;
function GetVisualClassId : TVisualClassId; override;
function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override;
public
procedure AutoConnect( loaded : boolean ); override;
procedure LoadFromBackup(Reader : IBackupReader); override;
procedure StoreToBackup (Writer : IBackupWriter); override;
private
fChemicals : TInputData;
fTimber : TOutputData;
end;
procedure RegisterBackup;
implementation
uses
SysUtils, ClassStorage, MathUtils, StdAccounts, SimHints;
// TMetaLumberMillBlock
constructor TMetaLumberMillBlock.Create(anId : string;
aCapacities : array of TFluidValue;
aChemicalMax : TFluidValue;
aMaxWoodPerHour : TFluidValue;
aWoodMaxVol : single;
aMinExpVol : single;
aGrowTime : integer;
aMaxBudget : TMoney;
aBlockClass : CBlock);
var
Sample : TLumberMillBlock;
begin
inherited Create(anId,
aCapacities,
accIdx_LumberMill_Supplies,
accIdx_LumberMill_Products,
accIdx_LumberMill_Salaries,
accIdx_LumberMill_Maintenance,
aBlockClass);
fMaxWoodVol := 10*aWoodMaxVol; // ten times..
fGrowRate := fMaxWoodVol/aGrowTime; //aWoodMaxVol/aGrowTime;
fMinExpVol := aMinExpVol;
Sample := nil;
// Inputs
MetaInputs.Insert(
TMetaInput.Create(
tidGate_Chemicals,
inputZero,
InputData(aChemicalMax, 100),
InputData(0, 0),
qIlimited,
TPullInput,
TMetaFluid(TheClassStorage.ClassById[tidClassFamily_Fluids, tidFluid_Chemicals]),
5,
mglBasic,
[mgoptCacheable, mgoptEditable],
sizeof(Sample.fChemicals),
Sample.Offset(Sample.fChemicals)));
// Outputs
MetaOutputs.Insert(
TMetaOutput.Create(
tidGate_Timber,
FluidData(aMaxWoodPerHour, 100),
TPullOutput,
TMetaFluid(TheClassStorage.ClassById[tidClassFamily_Fluids, tidFluid_Timber]),
5,
[mgoptCacheable, mgoptEditable],
sizeof(Sample.fTimber),
Sample.Offset(Sample.fTimber)));
// MetaEvaluators
with TMetaOutputEvaluator.Create(
aMaxBudget,
0,
OutputByName[tidGate_Timber],
TLumberOutputEvaluator) do
begin
FullOpenTime := 30;
FullCloseTime := 31;
RegisterInput(
TMetaInputInfo.Create(
InputByName[tidGate_Chemicals],
200,
1));
Register(MetaEvaluatorPool);
end;
end;
// TLumberOutputEvaluator
function TLumberOutputEvaluator.BiasOpenLimit(Block : TBlock) : TBiasRatio;
begin
if TLumberMillBlock(Block).fGrowing
then result := 0
else result := inherited BiasOpenLimit(Block);
end;
// TLumberMillBlock
function TLumberMillBlock.Evaluate : TEvaluationResult;
var
MB : TMetaLumberMillBlock;
begin
result := inherited Evaluate;
MB := TMetaLumberMillBlock(MetaBlock);
if fGrowing
then
begin
fTimberVolume := realmin(MB.fMaxWoodVol, fTimberVolume + MB.fGrowRate*dt);
fGrowing := fTimberVolume < MB.fMaxWoodVol;
end
else
begin
fTimberVolume := realmax(0, fTimberVolume - fTimber.Q);
fGrowing := fTimberVolume <= MB.fMinExpVol;
end;
end;
function TLumberMillBlock.GetVisualClassId : TVisualClassId;
var
wperc : single;
MB : TMetaLumberMillBlock;
begin
MB := TMetaLumberMillBlock(MetaBlock);
wperc := fTimberVolume/MB.fMaxWoodVol;
if fGrowing
then
begin
if wperc < 0.05
then result := 0
else
if wperc < 0.30
then result := 1
else
if wperc < 0.60
then result := 2
else
if wperc < 0.90
then result := 3
else result := 4;
end
else
begin
if wperc > 0.60
then result := 4
else
if wperc > 0.20
then result := 5
else result := 6;
end;
end;
function TLumberMillBlock.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string;
var
MB : TMetaLumberMillBlock;
begin
result := inherited GetStatusText( kind, ToTycoon );
case kind of
sttSecondary :
if fGrowing
then
begin
MB := TMetaLumberMillBlock(MetaBlock);
result := result + ' ' + Format(mtidGrowingTrees.Values[ToTycoon.Language], [SmartRound(100*fTimberVolume/MB.fMaxWoodVol)]);
end;
end;
end;
procedure TLumberMillBlock.AutoConnect(loaded : boolean);
begin
inherited AutoConnect(loaded);
if not Loaded
then fGrowing := true;
end;
procedure TLumberMillBlock.LoadFromBackup(Reader : IBackupReader);
begin
inherited;
fTimberVolume := Reader.ReadSingle('Volume', 0);
fGrowing := Reader.ReadBoolean('Growing', true);
end;
procedure TLumberMillBlock.StoreToBackup (Writer : IBackupWriter);
begin
inherited;
Writer.WriteSingle('Volume', fTimberVolume);
Writer.WriteBoolean('Growing', fGrowing);
end;
// RegisterBackup
procedure RegisterBackup;
begin
BackupInterfaces.RegisterClass(TLumberMillBlock);
end;
end.
|
unit GameXOImpl;
interface
uses
SysUtils, Variants, Classes, XOPoint;
type
TGameXOImpl = class
private
MovePatterns: array[0..4] of TXOPoint;
//matched to external X/O/' ' layout button texts
GamePane: array[0..2,0..2] of char;
Moves: array[0..2,0..2] of byte;
SignComputer: char;
SignPlayer: char;
protected
procedure ResetGamePane();
function AnalyzeTurn (Computer: Boolean; Step: Integer): Integer;
public
constructor Create();
function ComputerTurn():TXOPoint;
function CheckGameIsCompleted(Mark: Char):integer;
procedure StartGame(PlayerSign: char);
function PlayTurn(Turn:TXOPoint):integer;
property ComputerSign : char read SignComputer ;
property PlayerSign : char read SignPlayer;
end;
implementation
{ TGameXOImpl }
(**
* @Mark char X|O check win criteria for passed mark
*
* return -1 game in progress, 0 - nobody won, 1 - passed mark has won
*)
function TGameXOImpl.AnalyzeTurn(Computer: Boolean; Step: Integer): Integer;
var i, j, checkturn, weight, max: Integer;
begin
max := -1;
for i := 0 to 2 do
for j := 0 to 2 do
begin
weight := -2;
if GamePane[i,j] = ' ' then
begin
if Computer then begin
GamePane[i,j] := self.SignComputer;
end else begin
GamePane[i,j] := self.SignPlayer;
end;
if Computer then checkturn := CheckGameIsCompleted(self.SignComputer)
else checkturn := CheckGameIsCompleted (self.SignPlayer);
if (checkturn < 0) then begin
weight := - AnalyzeTurn(not Computer, Step + 1);
end else begin
weight := checkturn;
end;
if (weight > Max) then begin
max := weight;
end;
GamePane[i,j] := ' ';
if ((max = 1) and (step > 0)) then
begin
Result := Max;
break;
end;
end;
if (Step = 0) then Moves[i,j] := weight;
end;
Result := Max;
end;
function TGameXOImpl.CheckGameIsCompleted(Mark: Char): integer;
var i, j: Integer;
flagEmptyCellPresent,
flagHorizontalFilled,
flagVerticalFilled,
flagDiagonal1Filled,
flagDiagonal2Filled: Boolean;
begin
Result:= -1;
flagEmptyCellPresent := False;
flagDiagonal1Filled := True;
flagDiagonal2Filled := True;
for i := 0 to 2 do
begin
flagHorizontalFilled := True;
flagVerticalFilled := True;
for j := 0 to 2 do
begin
if GamePane[i,j] = ' ' then flagEmptyCellPresent := True;
if GamePane[i,j] <> Mark then flagHorizontalFilled := False;
if GamePane[j,i] <> Mark then flagVerticalFilled := False;
end;
if (flagHorizontalFilled or flagVerticalFilled) then
begin
Result := 1;
break;
end else
if (GamePane[i,i] <> Mark) then flagDiagonal1Filled := False;
if GamePane[2-i,i] <> Mark then flagDiagonal2Filled := False;
end;
if (Result < 0) then begin
if (flagDiagonal1Filled or flagDiagonal2Filled) then begin
Result:= 1;
end else if (not flagEmptyCellPresent) then begin
Result := 0;
end;
end;
end;
function TGameXOImpl.ComputerTurn: TXOPoint;
var max, i, j: Integer;
begin
max := AnalyzeTurn (True, 0);
repeat
i := Random (3);
j := Random (3);
until ((Moves[i,j] = Max) and (GamePane[i,j]=' '));
GamePane[i,j] := self.SignComputer;
Result := TXOPoint.Create(i,j);
end;
constructor TGameXOImpl.Create;
begin
Randomize();
MovePatterns[0] := TXOPoint.Create(0,0);
MovePatterns[1] := TXOPoint.Create(0,2);
MovePatterns[2] := TXOPoint.Create(1,1);
MovePatterns[3] := TXOPoint.Create(2,2);
end;
function TGameXOImpl.PlayTurn(Turn: TXOPoint): integer;
begin
if (GamePane[Turn.X,Turn.Y] = ' ') then
begin
GamePane[Turn.X,Turn.Y] := self.PlayerSign;
Result := CheckGameIsCompleted(self.PlayerSign);
end;
end;
(**
* Resets game pane to initial state
*
* return void
*)
procedure TGameXOImpl.ResetGamePane;
var i, j: byte;
begin
for i := 0 to 2 do
for j := 0 to 2 do
begin
GamePane[i,j] := ' ';
end;
end;
(**
* @PlayerSign char X|O
*
* returns TPoint if it is computer turn, nil otherwise
*)
procedure TGameXOImpl.StartGame(PlayerSign: char);
begin
Randomize();
self.SignPlayer := PlayerSign;
if (PlayerSign='X') then begin
self.SignComputer :='O';
end else begin
self.SignComputer:='X';
end;
ResetGamePane();
if (self.SignComputer = 'X') then begin
end;
end;
end.
|
unit ce_editor;
{$I ce_defines.inc}
interface
uses
Classes, SysUtils, FileUtil, ExtendedNotebook, Forms, Controls, lcltype,
Graphics, SynEditKeyCmds, ComCtrls, SynEditHighlighter, ExtCtrls, Menus,
SynMacroRecorder, SynPluginSyncroEdit, SynEdit, SynHighlighterMulti,
ce_widget, ce_interfaces, ce_synmemo, ce_dlang, ce_common, ce_dcd, ce_observer;
type
// this descendant propagates the Visible property to the children.
// this fix the bug described in commit c1a0ed2799390d788b1d1e435eb8dc1ed3369ce7
TCEEditorPage = class(TTabSheet)
protected
procedure SetVisible(Value: Boolean); override;
end;
{ TCEEditorWidget }
TCEEditorWidget = class(TCEWidget, ICEMultiDocObserver, ICEMultiDocHandler)
mnuedCopy: TMenuItem;
mnuedCut: TMenuItem;
mnuedPaste: TMenuItem;
MenuItem4: TMenuItem;
mnuedUndo: TMenuItem;
mnuedRedo: TMenuItem;
MenuItem7: TMenuItem;
mnuedJum2Decl: TMenuItem;
PageControl: TExtendedNotebook;
macRecorder: TSynMacroRecorder;
editorStatus: TStatusBar;
mnuEditor: TPopupMenu;
procedure mnuedCopyClick(Sender: TObject);
procedure mnuedCutClick(Sender: TObject);
procedure mnuEditorPopup(Sender: TObject);
procedure mnuedPasteClick(Sender: TObject);
procedure mnuedUndoClick(Sender: TObject);
procedure mnuedRedoClick(Sender: TObject);
procedure mnuedJum2DeclClick(Sender: TObject);
procedure PageControlChange(Sender: TObject);
protected
procedure updateDelayed; override;
procedure updateImperative; override;
private
fKeyChanged: boolean;
fDoc: TCESynMemo;
fTokList: TLexTokenList;
fErrList: TLexErrorList;
fModStart: boolean;
{$IFDEF LINUX}
procedure pageCloseBtnClick(Sender: TObject);
{$ENDIF}
procedure lexFindToken(const aToken: PLexToken; out doStop: boolean);
procedure memoKeyPress(Sender: TObject; var Key: char);
procedure memoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure memoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure memoCtrlClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure memoMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure getSymbolLoc;
procedure focusedEditorChanged;
//
procedure docNew(aDoc: TCESynMemo);
procedure docClosing(aDoc: TCESynMemo);
procedure docFocused(aDoc: TCESynMemo);
procedure docChanged(aDoc: TCESynMemo);
//
function SingleServiceName: string;
function documentCount: Integer;
function getDocument(index: Integer): TCESynMemo;
function findDocument(aFilename: string): TCESynMemo;
procedure openDocument(aFilename: string);
function closeDocument(index: Integer): boolean;
public
constructor create(aOwner: TComponent); override;
destructor destroy; override;
end;
implementation
{$R *.lfm}
procedure TCEEditorPage.SetVisible(Value: Boolean);
var
i: integer;
begin
inherited;
for i := 0 to ControlCount-1 do
Controls[i].Visible:= Value;
end;
{$REGION Standard Comp/Obj------------------------------------------------------}
constructor TCEEditorWidget.create(aOwner: TComponent);
var
png: TPortableNetworkGraphic;
begin
inherited;
//
fTokList := TLexTokenList.Create;
fErrList := TLexErrorList.Create;
{$IFDEF LINUX}
PageControl.OnCloseTabClicked := @pageCloseBtnClick;
{$ENDIF}
//
png := TPortableNetworkGraphic.Create;
try
png.LoadFromLazarusResource('copy');
mnuedCopy.Bitmap.Assign(png);
png.LoadFromLazarusResource('cut');
mnuedCut.Bitmap.Assign(png);
png.LoadFromLazarusResource('paste');
mnuedPaste.Bitmap.Assign(png);
png.LoadFromLazarusResource('arrow_undo');
mnuedUndo.Bitmap.Assign(png);
png.LoadFromLazarusResource('arrow_redo');
mnuedRedo.Bitmap.Assign(png);
png.LoadFromLazarusResource('arrow_shoe');
mnuedJum2Decl.Bitmap.Assign(png);
finally
png.Free;
end;
//
EntitiesConnector.addObserver(self);
EntitiesConnector.addSingleService(self);
end;
destructor TCEEditorWidget.destroy;
var
i: integer;
begin
EntitiesConnector.removeObserver(self);
for i := PageControl.PageCount-1 downto 0 do
if PageControl.Page[i].ControlCount > 0 then
if (PageControl.Page[i].Controls[0] is TCESynMemo) then
PageControl.Page[i].Controls[0].Free;
fTokList.Free;
fErrList.Free;
inherited;
end;
{$ENDREGION}
{$REGION ICEMultiDocObserver ---------------------------------------------------}
procedure TCEEditorWidget.docNew(aDoc: TCESynMemo);
var
sheet: TCEEditorPage;
begin
sheet := TCEEditorPage.Create(self);
sheet.PageControl := PageControl;
//
aDoc.Align := alClient;
aDoc.Parent := sheet;
//
aDoc.OnKeyDown := @memoKeyDown;
aDoc.OnKeyPress := @memoKeyPress;
aDoc.OnMouseDown := @memoMouseDown;
aDoc.OnMouseMove := @memoMouseMove;
aDoc.OnClickLink := @memoCtrlClick;
//
fDoc := aDoc;
pageControl.ActivePage := sheet;
focusedEditorChanged;
beginDelayedUpdate;
updateImperative;
end;
procedure TCEEditorWidget.docClosing(aDoc: TCESynMemo);
var
sheet: TWinControl;
begin
if aDoc = nil then
exit;
sheet := aDoc.Parent;
aDoc.Parent := nil;
if aDoc = fDoc then
fDoc := nil;
if sheet <> nil then sheet.Free;
updateImperative;
end;
procedure TCEEditorWidget.docFocused(aDoc: TCESynMemo);
begin
if aDoc = fDoc then exit;
fDoc := aDoc;
focusedEditorChanged;
beginDelayedUpdate;
updateImperative;
end;
procedure TCEEditorWidget.docChanged(aDoc: TCESynMemo);
begin
if fDoc <> aDoc then exit;
fKeyChanged := true;
beginDelayedUpdate;
updateImperative;
end;
{$ENDREGION}
{$REGION ICEMultiDocHandler ----------------------------------------------------}
function TCEEditorWidget.SingleServiceName: string;
begin
exit('ICEMultiDocHandler');
end;
function TCEEditorWidget.documentCount: Integer;
begin
exit(PageControl.PageCount);
end;
function TCEEditorWidget.getDocument(index: Integer): TCESynMemo;
begin
exit(TCESynMemo(pageControl.Pages[index].Controls[0]));
end;
function TCEEditorWidget.findDocument(aFilename: string): TCESynMemo;
var
i: Integer;
begin
for i := 0 to PageControl.PageCount-1 do
begin
result := getDocument(i);
if result.fileName = aFilename then
exit;
end;
result := nil;
end;
procedure TCEEditorWidget.openDocument(aFilename: string);
var
doc: TCESynMemo;
begin
doc := findDocument(aFilename);
if doc <> nil then begin
PageControl.ActivePage := TTabSheet(doc.Parent);
exit;
end;
doc := TCESynMemo.Create(nil);
fDoc.loadFromFile(aFilename);
end;
function TCEEditorWidget.closeDocument(index: Integer): boolean;
var
doc: TCESynMemo;
begin
doc := getDocument(index);
if doc.modified then if dlgOkCancel(format(
'The latest "%s" modifications are not saved, continue ?',
[shortenPath(doc.fileName,25)])) = mrCancel then exit(false);
doc.Free;
result := true;
end;
{$ENDREGION}
{$REGION PageControl/Editor things ---------------------------------------------}
{$IFDEF LINUX}
procedure TCEEditorWidget.pageCloseBtnClick(Sender: TObject);
begin
if fDoc <> nil then fDoc.Free;
end;
{$ENDIF}
procedure TCEEditorWidget.focusedEditorChanged;
begin
macRecorder.Clear;
if fDoc = nil then exit;
//
macRecorder.Editor:= fDoc;
fDoc.PopupMenu := mnuEditor;
if (pageControl.ActivePage.Caption = '') then
begin
fKeyChanged := true;
beginDelayedUpdate;
end;
end;
procedure TCEEditorWidget.PageControlChange(Sender: TObject);
begin
updateImperative;
end;
procedure TCEEditorWidget.memoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case Key of
VK_CLEAR,VK_RETURN,VK_BACK : fKeyChanged := true;
VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT: updateImperative;
end;
if fKeyChanged then
beginDelayedUpdate
else if (Key = VK_UP) and (shift = [ssShift,ssCtrl]) then
getSymbolLoc;
end;
procedure TCEEditorWidget.memoKeyPress(Sender: TObject; var Key: char);
begin
fKeyChanged := true;
beginDelayedUpdate;
end;
procedure TCEEditorWidget.memoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
beginDelayedUpdate;
updateImperative;
end;
procedure TCEEditorWidget.memoMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if not (ssLeft in Shift) then exit;
beginDelayedUpdate;
end;
procedure TCEEditorWidget.memoCtrlClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
getSymbolLoc;
end;
procedure TCEEditorWidget.getSymbolLoc;
var
srcpos, i, sum, linelen: Integer;
fname: string;
len: byte;
begin
if not DcdWrapper.available then exit;
//
DcdWrapper.getDeclFromCursor(fname, srcpos);
if fname <> fDoc.fileName then if fileExists(fname) then
openDocument(fname);
if srcpos <> -1 then
begin
sum := 0;
len := getLineEndingLength(fDoc.fileName);
for i := 0 to fDoc.Lines.Count-1 do
begin
linelen := length(fDoc.Lines.Strings[i]);
if sum + linelen + len > srcpos then
begin
fDoc.CaretY := i + 1;
fDoc.CaretX := srcpos - sum + len;
fDoc.SelectWord;
fDoc.EnsureCursorPosVisible;
break;
end;
sum += linelen;
sum += len;
end;
end;
end;
procedure TCEEditorWidget.updateImperative;
const
modstr: array[boolean] of string = ('...', 'MODIFIED');
begin
if fDoc = nil then begin
editorStatus.Panels[0].Text := '';
editorStatus.Panels[1].Text := '';
editorStatus.Panels[2].Text := '';
end else begin
editorStatus.Panels[0].Text := format('%d : %d | %d', [fDoc.CaretY, fDoc.CaretX, fDoc.SelEnd - fDoc.SelStart]);
editorStatus.Panels[1].Text := modstr[fDoc.modified];
editorStatus.Panels[2].Text := fDoc.fileName;
end;
end;
procedure TCEEditorWidget.lexFindToken(const aToken: PLexToken; out doStop: boolean);
begin
if aToken^.kind = ltkKeyword then
if aToken^.data = 'module' then
fModStart := true;
if fModStart then if aToken^.kind = ltkSymbol then
if aToken^.data = ';' then begin
doStop := true;
fModStart := false;
end;
end;
procedure TCEEditorWidget.updateDelayed;
var
md: string;
begin
if fDoc = nil then exit;
updateImperative;
if not fKeyChanged then exit;
//
fKeyChanged := false;
if fDoc.Lines.Count = 0 then exit;
//
lex(fDoc.Lines.Text, fTokList, @lexFindToken);
md := '';
if fDoc.isDSource then
md := getModuleName(fTokList);
if md = '' then md := extractFileName(fDoc.fileName);
pageControl.ActivePage.Caption := md;
//
fTokList.Clear;
fErrList.Clear;
// when a widget saves a temp file & syncro mode is on:
// - editor is saved
// - gutter is updated (green bar indicating a saved block)
// - syncroedit icon is hidden
if fDoc.syncroEdit.Active then
fDoc.Refresh;
end;
{$ENDREGION}
{$REGION Editor context menu ---------------------------------------------------}
procedure TCEEditorWidget.mnuedCopyClick(Sender: TObject);
begin
if fDoc = nil then exit;
fDoc.ExecuteCommand(ecCopy, '', nil);
end;
procedure TCEEditorWidget.mnuedCutClick(Sender: TObject);
begin
if fDoc = nil then exit;
fDoc.ExecuteCommand(ecCut, '', nil);
end;
procedure TCEEditorWidget.mnuedPasteClick(Sender: TObject);
begin
if fDoc = nil then exit;
fDoc.ExecuteCommand(ecPaste, '', nil);
end;
procedure TCEEditorWidget.mnuedUndoClick(Sender: TObject);
begin
if fDoc = nil then exit;
fDoc.ExecuteCommand(ecUndo, '', nil);
end;
procedure TCEEditorWidget.mnuedRedoClick(Sender: TObject);
begin
if fDoc = nil then exit;
fDoc.ExecuteCommand(ecRedo, '', nil);
end;
procedure TCEEditorWidget.mnuedJum2DeclClick(Sender: TObject);
begin
if fDoc = nil then exit;
getSymbolLoc;
end;
procedure TCEEditorWidget.mnuEditorPopup(Sender: TObject);
begin
if fDoc = nil then exit;
//
mnuedCut.Enabled:=fDOc.SelAvail;
mnuedPaste.Enabled:=fDoc.CanPaste;
mnuedCopy.Enabled:=fDoc.SelAvail;
mnuedUndo.Enabled:=fDoc.CanUndo;
mnuedRedo.Enabled:=fDoc.CanRedo;
mnuedJum2Decl.Enabled:=fDoc.isDSource;
end;
{$ENDREGION}
end.
|
unit MFichas.Controller.Venda.Metodos.Pagamento;
interface
uses
System.SysUtils,
MFichas.Controller.Venda.Interfaces,
MFichas.Controller.Types,
MFichas.Model.Venda.Interfaces,
MFichas.Model.Pagamento.Interfaces;
type
TControllerVendaMetodosPagar = class(TInterfacedObject, iControllerVendaMetodosPagar)
private
[weak]
FParent : iControllerVenda;
FModel : iModelVenda;
FTipoVenda : TTypeTipoVenda;
FMetodoPagamento : iModelPagamentoMetodos;
FValorTotalDaCompra: Currency;
constructor Create(AParent: iControllerVenda; AModel: iModelVenda);
procedure Validacao;
public
destructor Destroy; override;
class function New(AParent: iControllerVenda; AModel: iModelVenda): iControllerVendaMetodosPagar;
function TipoDePagamento(ATipo: TTypeTipoPagamento): iControllerVendaMetodosPagar;
function TipoDaVenda(ATipo: TTypeTipoVenda) : iControllerVendaMetodosPagar;
function ValorTotalDaCompra(AValue: Currency) : iControllerVendaMetodosPagar;
function Executar : iControllerVendaMetodosPagar;
function &End : iControllerVendaMetodos;
end;
implementation
{ TControllerVendaMetodosPagar }
function TControllerVendaMetodosPagar.&End: iControllerVendaMetodos;
begin
Result := FParent.Metodos;
end;
procedure TControllerVendaMetodosPagar.Validacao;
begin
if not Assigned(FMetodoPagamento) then
raise Exception.Create(
'Não é possível executar o pagamento, sem um método de pagamento.'
);
end;
function TControllerVendaMetodosPagar.ValorTotalDaCompra(
AValue: Currency): iControllerVendaMetodosPagar;
begin
Result := Self;
if AValue <= 0 then
raise Exception.Create(
'O valor total desta compra não pode ser igual ou inferior a 0.'
);
FValorTotalDaCompra := AValue;
end;
constructor TControllerVendaMetodosPagar.Create(AParent: iControllerVenda; AModel: iModelVenda);
begin
FParent := AParent;
FModel := AModel;
end;
destructor TControllerVendaMetodosPagar.Destroy;
begin
inherited;
end;
function TControllerVendaMetodosPagar.Executar: iControllerVendaMetodosPagar;
begin
Result := Self;
Validacao;
case FTipoVenda of
tvVenda: begin
FMetodoPagamento
.Processar
.SetValor(FValorTotalDaCompra)
.&End
.&End;
end;
tvDevolucao: begin
FMetodoPagamento
.Estornar
.SetValor(FValorTotalDaCompra)
.&End
.&End;
end;
end;
end;
class function TControllerVendaMetodosPagar.New(AParent: iControllerVenda; AModel: iModelVenda): iControllerVendaMetodosPagar;
begin
Result := Self.Create(AParent, AModel);
end;
function TControllerVendaMetodosPagar.TipoDaVenda(
ATipo: TTypeTipoVenda): iControllerVendaMetodosPagar;
begin
Result := Self;
FTipoVenda := ATipo;
end;
function TControllerVendaMetodosPagar.TipoDePagamento(
ATipo: TTypeTipoPagamento): iControllerVendaMetodosPagar;
begin
Result := Self;
case ATipo of
tpDinheiro : FMetodoPagamento := FModel.Pagamento.Dinheiro;
tpCartaoDebito : FMetodoPagamento := FModel.Pagamento.CartaoDeDebito;
tpCartaoCredito: FMetodoPagamento := FModel.Pagamento.CartaoDeCredito;
end;
end;
end.
|
unit DaoFireDac;
interface
uses Db, Base, Rtti, Atributos, system.SysUtils, system.Classes,
FireDAC.Comp.UI,FireDAC.Comp.Client, system.Generics.Collections;
type
TTransacaoFireDac = class(TTransacaoBase)
private
// transação para crud
FTransaction: TFDTransaction;
public
constructor Create(ABanco: TFDConnection);
destructor Destroy; override;
function InTransaction: Boolean; override;
procedure Snapshot;
procedure Read_Commited;
procedure StartTransaction; override;
procedure Commit; override;
procedure RollBack; override;
property Transaction: TFDTransaction read FTransaction write FTransaction;
end;
TConexaoFireDac = class(TConexaoBase)
private
// conexao com o banco de dados
FDatabase: TFDConnection;
// transação para consultas
FTransQuery: TFDTransaction;
public
constructor Create();
destructor Destroy; override;
function Conectado: Boolean; override;
procedure Conecta; override;
property Conexao: TFDConnection read FDatabase write FDatabase;
property TransQuery: TFDTransaction read FTransQuery write FTransQuery;
end;
TDaoFireDac = class(TDaoBase)
private
FConexao: TConexaoFireDac;
// query para execução dos comandos crud
Qry: TFDQuery;
Function DbToTabela<T: TTabela>(ATabela: TTabela; ADataSet: TDataSet)
: TObjectList<T>;
protected
// métodos responsáveis por setar os parâmetros
procedure QryParamInteger(ARecParams: TRecParams); override;
procedure QryParamString(ARecParams: TRecParams); override;
procedure QryParamDate(ARecParams: TRecParams); override;
procedure QryParamCurrency(ARecParams: TRecParams); override;
procedure QryParamVariant(ARecParams: TRecParams); override;
// métodos para setar os variados tipos de campos
procedure SetaCamposInteger(ARecParams: TRecParams); override;
procedure SetaCamposString(ARecParams: TRecParams); override;
procedure SetaCamposDate(ARecParams: TRecParams); override;
procedure SetaCamposCurrency(ARecParams: TRecParams); override;
function ExecutaQuery: Integer; override;
public
constructor Create(AConexao: TConexaoFireDac; ATransacao: TTransacaoFireDac);
destructor Destroy; override;
// dataset para as consultas
function ConsultaSql(ASql: string): TDataSet; override;
function ConsultaTab(ATabela: TTabela; ACampos: array of string)
: TDataSet; override;
function ConsultaGen<T: TTabela>(ATabela: TTabela; ACampos: array of string)
: TObjectList<T>;
// pega campo autoincremento
function GetID(ATabela: TTabela; ACampo: string): Integer; override;
function GetMax(ATabela: TTabela; ACampo: string;
ACamposChave: array of string): Integer;
// recordcount
function GetRecordCount(ATabela: TTabela; ACampos: array of string)
: Integer; override;
// crud
function Inserir(ATabela: TTabela): Integer; override;
function Salvar(ATabela: TTabela): Integer; override;
function Excluir(ATabela: TTabela): Integer; override;
function Buscar(ATabela: TTabela): Integer; override;
end;
implementation
uses Vcl.forms, dialogs, system.TypInfo;
{ TTransIbx }
constructor TTransacaoFireDac.Create(ABanco: TFDConnection);
begin
inherited Create;
FTransaction := TFDTransaction.Create(Application);
with FTransaction do
begin
Connection.ConnectionDefName := ABanco.ConnectionDefName;
Read_Commited;
end;
end;
destructor TTransacaoFireDac.Destroy;
begin
inherited;
end;
function TTransacaoFireDac.InTransaction: Boolean;
begin
Result := FTransaction.Connection.InTransaction;
end;
procedure TTransacaoFireDac.Snapshot;
begin
with FTransaction do
begin
Connection.Params.Clear;
Connection.Params.Add('concurrency');
Connection.Params.Add('nowait');
// Params.Clear;
// Params.Add('concurrency');
// Params.Add('nowait');
end;
end;
procedure TTransacaoFireDac.StartTransaction;
begin
if not FTransaction.Connection.InTransaction then
FTransaction.StartTransaction;
end;
procedure TTransacaoFireDac.Read_Commited;
begin
with FTransaction do
begin
Connection.Params.Clear;
Connection.Params.Add('read_committed');
Connection.Params.Add('rec_version');
Connection.Params.Add('nowait');
end;
end;
procedure TTransacaoFireDac.RollBack;
begin
FTransaction.RollBack;
end;
procedure TTransacaoFireDac.Commit;
begin
FTransaction.Commit;
end;
constructor TConexaoFireDac.Create();
begin
inherited Create;
FDatabase := TFDConnection.Create(Application);
FDatabase.DriverName := 'MySQL';
// FDatabase.ServerType := 'IBServer';
FDatabase.LoginPrompt := false;
end;
destructor TConexaoFireDac.Destroy;
begin
inherited;
end;
function TConexaoFireDac.Conectado: Boolean;
begin
Result := Conexao.Connected;
end;
procedure TConexaoFireDac.Conecta;
begin
inherited;
with Conexao do
begin
ConnectionName := LocalBD;
Params.Clear;
Params.Add('user_name=' + Usuario);
Params.Add('password=' + Senha);
Connected := True;
end;
end;
{ TDaoFiredac }
constructor TDaoFireDac.Create(AConexao: TConexaoFireDac; ATransacao: TTransacaoFireDac);
var
MeuDataSet: TFDQuery;
begin
inherited Create;
FConexao := AConexao;
with FConexao do
begin
// configurações iniciais da transacao para consultas
FTransQuery := TFDTransaction.Create(Application);
with TransQuery do
begin
Connection.ConnectionDefName := Conexao.ConnectionDefName;
// DefaultDatabase := Conexao;
Connection.Params.Add('read_committed');
Connection.Params.Add('rec_version');
Connection.Params.Add('nowait');
end;
Conexao.Transaction := TransQuery;
//Conexao.DefaultTransaction := TransQuery;
end;
Qry := TFDQuery.Create(Application);
Qry.Connection := FConexao.Conexao;
Qry.Transaction := ATransacao.Transaction;
MeuDataSet := TFDQuery.Create(Application);
MeuDataSet.Connection := FConexao.Conexao;
DataSet := MeuDataSet;
end;
destructor TDaoFiredac.Destroy;
begin
inherited;
end;
procedure TDaoFiredac.QryParamCurrency(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
TFDQuery(Qry).ParamByName(Campo).AsCurrency := Prop.GetValue(Tabela)
.AsCurrency;
end;
end;
procedure TDaoFiredac.QryParamDate(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
if Prop.GetValue(Tabela).AsType<TDateTime> = 0 then
TFDQuery(Qry).ParamByName(Campo).Clear
else
TFDQuery(Qry).ParamByName(Campo).AsDateTime := Prop.GetValue(Tabela).AsType<TDateTime>;
end;
end;
procedure TDaoFiredac.QryParamInteger(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
TFDQuery(Qry).ParamByName(Campo).AsInteger := Prop.GetValue(Tabela)
.AsInteger;
end;
end;
procedure TDaoFiredac.QryParamString(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
TFDQuery(Qry).ParamByName(Campo).AsString := Prop.GetValue(Tabela).AsString;
end;
end;
procedure TDaoFiredac.QryParamVariant(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
TFDQuery(Qry).ParamByName(Campo).Value := Prop.GetValue(Tabela).AsVariant;
end;
end;
procedure TDaoFiredac.SetaCamposCurrency(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
Prop.SetValue(Tabela, TFDQuery(Qry).FieldByName(Campo).AsCurrency);
end;
end;
procedure TDaoFiredac.SetaCamposDate(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
Prop.SetValue(Tabela, TFDQuery(Qry).FieldByName(Campo).AsDateTime);
end;
end;
procedure TDaoFiredac.SetaCamposInteger(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
Prop.SetValue(Tabela, TFDQuery(Qry).FieldByName(Campo).AsInteger);
end;
end;
procedure TDaoFiredac.SetaCamposString(ARecParams: TRecParams);
begin
inherited;
with ARecParams do
begin
Prop.SetValue(Tabela, TFDQuery(Qry).FieldByName(Campo).AsString);
end;
end;
function TDaoFiredac.DbToTabela<T>(ATabela: TTabela; ADataSet: TDataSet)
: TObjectList<T>;
var
AuxValue: TValue;
TipoRtti: TRttiType;
Contexto: TRttiContext;
PropRtti: TRttiProperty;
DataType: TFieldType;
Campo: String;
begin
Result := TObjectList<T>.Create;
while not ADataSet.Eof do
begin
AuxValue := GetTypeData(PTypeInfo(TypeInfo(T)))^.ClassType.Create;
TipoRtti := Contexto.GetType(AuxValue.AsObject.ClassInfo);
for PropRtti in TipoRtti.GetProperties do
begin
Campo := PropRtti.Name;
DataType := ADataSet.FieldByName(Campo).DataType;
case DataType of
ftInteger:
begin
PropRtti.SetValue(AuxValue.AsObject,
TValue.FromVariant(ADataSet.FieldByName(Campo).AsInteger));
end;
ftString, ftWideString:
begin
PropRtti.SetValue(AuxValue.AsObject,
TValue.FromVariant(ADataSet.FieldByName(Campo).AsString));
end;
ftBCD, ftFloat:
begin
PropRtti.SetValue(AuxValue.AsObject,
TValue.FromVariant(ADataSet.FieldByName(Campo).AsFloat));
end;
ftDate, ftDateTime:
begin
PropRtti.SetValue(AuxValue.AsObject,
TValue.FromVariant(ADataSet.FieldByName(Campo).AsDateTime));
end;
else
raise Exception.Create('Tipo de campo não conhecido: ' +
PropRtti.PropertyType.ToString);
end;
end;
Result.Add(AuxValue.AsType<T>);
ADataSet.Next;
end;
end;
function TDaoFiredac.ConsultaGen<T>(ATabela: TTabela; ACampos: array of string)
: TObjectList<T>;
var
Dados: TFDQuery;
Contexto: TRttiContext;
Campo: string;
TipoRtti: TRttiType;
PropRtti: TRttiProperty;
begin
Dados := TFDQuery.Create(Application);
try
Contexto := TRttiContext.Create;
try
TipoRtti := Contexto.GetType(ATabela.ClassType);
with Dados do
begin
Connection := FConexao.Conexao;
sql.Text := GerarSqlSelect(ATabela, ACampos);
for Campo in ACampos do
begin
if not PropExiste(Campo, PropRtti, TipoRtti) then
raise Exception.Create('Campo ' + Campo + ' não existe no objeto!');
// setando os parâmetros
for PropRtti in TipoRtti.GetProperties do
begin
if CompareText(PropRtti.Name, Campo) = 0 then
begin
ConfiguraParametro(PropRtti, Campo, ATabela, Dados);
end;
end;
end;
Open;
Result := DbToTabela<T>(ATabela, Dados);
end;
finally
Contexto.Free;
end;
finally
Dados.Free;
end;
end;
function TDaoFiredac.ConsultaSql(ASql: string): TDataSet;
var
AQry: TFDQuery;
begin
AQry := TFDQuery.Create(Application);
with AQry do
begin
Connection := FConexao.Conexao;
sql.Clear;
sql.Add(ASql);
Open;
end;
Result := AQry;
end;
function TDaoFiredac.ConsultaTab(ATabela: TTabela; ACampos: array of string)
: TDataSet;
var
Dados: TFDQuery;
Contexto: TRttiContext;
Campo: string;
TipoRtti: TRttiType;
PropRtti: TRttiProperty;
begin
Dados := TFDQuery.Create(Application);
Contexto := TRttiContext.Create;
try
TipoRtti := Contexto.GetType(ATabela.ClassType);
with Dados do
begin
Connection := FConexao.Conexao;
sql.Text := GerarSqlSelect(ATabela, ACampos);
for Campo in ACampos do
begin
// setando os parâmetros
for PropRtti in TipoRtti.GetProperties do
if CompareText(PropRtti.Name, Campo) = 0 then
begin
ConfiguraParametro(PropRtti, Campo, ATabela, Dados);
end;
end;
Open;
Result := Dados;
end;
finally
Contexto.Free;
end;
end;
function TDaoFiredac.GetID(ATabela: TTabela; ACampo: string): Integer;
var
AQry: TFDQuery;
begin
AQry := TFDQuery.Create(Application);
with AQry do
begin
Connection := FConexao.Conexao;
sql.Clear;
sql.Add('select max(' + ACampo + ') from ' + PegaNomeTab(ATabela));
Open;
Result := fields[0].AsInteger + 1;
end;
end;
function TDaoFiredac.GetMax(ATabela: TTabela; ACampo: string;
ACamposChave: array of string): Integer;
var
AQry: TFDQuery;
Campo: string;
Contexto: TRttiContext;
TipoRtti: TRttiType;
PropRtti: TRttiProperty;
Separador: string;
NumMax: Integer;
begin
AQry := TFDQuery.Create(Application);
try
with AQry do
begin
Connection := FConexao.Conexao;
sql.Clear;
sql.Add('select max(' + ACampo + ') from ' + PegaNomeTab(ATabela));
sql.Add('Where');
Separador := '';
for Campo in ACamposChave do
begin
sql.Add(Separador + Campo + '= :' + Campo);
Separador := ' and ';
end;
Contexto := TRttiContext.Create;
try
TipoRtti := Contexto.GetType(ATabela.ClassType);
for Campo in ACamposChave do
begin
// setando os parâmetros
for PropRtti in TipoRtti.GetProperties do
if CompareText(PropRtti.Name, Campo) = 0 then
begin
ConfiguraParametro(PropRtti, Campo, ATabela, AQry);
end;
end;
Open;
NumMax := Fields[0].AsInteger;
Result := NumMax;
finally
Contexto.Free;
end;
end;
finally
AQry.Free;
end;
end;
function TDaoFiredac.GetRecordCount(ATabela: TTabela;
ACampos: array of string): Integer;
var
AQry: TFDQuery;
Contexto: TRttiContext;
Campo: string;
TipoRtti: TRttiType;
PropRtti: TRttiProperty;
begin
AQry := TFDQuery.Create(Application);
with AQry do
begin
Contexto := TRttiContext.Create;
try
TipoRtti := Contexto.GetType(ATabela.ClassType);
Connection := FConexao.Conexao;
sql.Clear;
sql.Add('select count(*) from ' + PegaNomeTab(ATabela));
if High(ACampos) >= 0 then
sql.Add('where 1=1');
for Campo in ACampos do
sql.Add('and ' + Campo + '=:' + Campo);
for Campo in ACampos do
begin
for PropRtti in TipoRtti.GetProperties do
if CompareText(PropRtti.Name, Campo) = 0 then
begin
ConfiguraParametro(PropRtti, Campo, ATabela, AQry);
end;
end;
Open;
Result := fields[0].AsInteger;
finally
Contexto.Free;
end;
end;
end;
function TDaoFiredac.ExecutaQuery: Integer;
begin
with Qry do
begin
Prepare();
ExecSQL;
Result := RowsAffected;
end;
end;
function TDaoFiredac.Excluir(ATabela: TTabela): Integer;
var
Comando: TFuncReflexao;
begin
// crio uma variável do tipo TFuncReflexao - um método anônimo
Comando := function(ACampos: TCamposAnoni): Integer
var
Campo: string;
PropRtti: TRttiProperty;
begin
Qry.close;
Qry.sql.Clear;
Qry.sql.Text := GerarSqlDelete(ATabela);
// percorrer todos os campos da chave primária
for Campo in PegaPks(ATabela) do
begin
// setando os parâmetros
for PropRtti in ACampos.TipoRtti.GetProperties do
if CompareText(PropRtti.Name, Campo) = 0 then
begin
ConfiguraParametro(PropRtti, Campo, ATabela, Qry);
end;
end;
Result := ExecutaQuery;
end;
// reflection da tabela e execução da query preparada acima.
Result := ReflexaoSQL(ATabela, Comando);
end;
function TDaoFiredac.Inserir(ATabela: TTabela): Integer;
var
Comando: TFuncReflexao;
begin
try
ValidaTabela(ATabela);
Comando := function(ACampos: TCamposAnoni): Integer
var
Campo: string;
PropRtti: TRttiProperty;
begin
with Qry do
begin
close;
sql.Clear;
sql.Text := GerarSqlInsert(ATabela, ACampos.TipoRtti);
// valor dos parâmetros
for PropRtti in ACampos.TipoRtti.GetProperties do
begin
Campo := PropRtti.Name;
ConfiguraParametro(PropRtti, Campo, ATabela, Qry);
end;
end;
Result := ExecutaQuery;
end;
// reflection da tabela e execução da query preparada acima.
Result := ReflexaoSQL(ATabela, Comando);
except
raise;
end;
end;
function TDaoFiredac.Salvar(ATabela: TTabela): Integer;
var
Comando: TFuncReflexao;
begin
try
ValidaTabela(ATabela);
Comando := function(ACampos: TCamposAnoni): Integer
var
Campo: string;
PropRtti: TRttiProperty;
begin
with Qry do
begin
close;
sql.Clear;
sql.Text := GerarSqlUpdate(ATabela, ACampos.TipoRtti);
// valor dos parâmetros
for PropRtti in ACampos.TipoRtti.GetProperties do
begin
Campo := PropRtti.Name;
ConfiguraParametro(PropRtti, Campo, ATabela, Qry);
end;
end;
Result := ExecutaQuery;
end;
// reflection da tabela e execução da query preparada acima.
Result := ReflexaoSQL(ATabela, Comando);
except
raise;
end;
end;
function TDaoFiredac.Buscar(ATabela: TTabela): Integer;
var
Comando: TFuncReflexao;
Dados: TFDQuery;
begin
Dados := TFDQuery.Create(nil);
try
// crio uma variável do tipo TFuncReflexao - um método anônimo
Comando := function(ACampos: TCamposAnoni): Integer
var
Campo: string;
PropRtti: TRttiProperty;
begin
with Dados do
begin
Connection := FConexao.Conexao;
sql.Text := GerarSqlSelect(ATabela);
for Campo in ACampos.PKs do
begin
// setando os parâmetros
for PropRtti in ACampos.TipoRtti.GetProperties do
if CompareText(PropRtti.Name, Campo) = 0 then
begin
ConfiguraParametro(PropRtti, Campo, ATabela, Dados);
end;
end;
Open;
Result := RecordCount;
if Result > 0 then
begin
for PropRtti in ACampos.TipoRtti.GetProperties do
begin
Campo := PropRtti.Name;
SetaDadosTabela(PropRtti, Campo, ATabela, Dados);
end;
end;
end;
end;
// reflection da tabela e abertura da query preparada acima.
Result := ReflexaoSQL(ATabela, Comando);
finally
Dados.Free;
end;
end;
end.
|
unit SingleDriverRoundTripTestDataProviderUnit;
interface
uses
SysUtils,
BaseOptimizationParametersProviderUnit, AddressUnit, RouteParametersUnit,
OptimizationParametersUnit;
type
TSingleDriverRoundTripTestDataProvider = class(TBaseOptimizationParametersProvider)
protected
function MakeAddresses(): TArray<TAddress>; override;
function MakeRouteParameters(): TRouteParameters; override;
/// <summary>
/// After response some fields are changed from request.
/// </summary>
procedure CorrectForResponse(OptimizationParameters: TOptimizationParameters); override;
public
end;
implementation
{ TSingleDriverRoundTripTestDataProvider }
uses
DateUtils,
EnumsUnit, UtilsUnit;
procedure TSingleDriverRoundTripTestDataProvider.CorrectForResponse(
OptimizationParameters: TOptimizationParameters);
begin
inherited;
end;
function TSingleDriverRoundTripTestDataProvider.MakeAddresses: TArray<TAddress>;
var
FirstAddress: TAddress;
begin
Result := TArray<TAddress>.Create();
FirstAddress := TAddress.Create(
'754 5th Ave New York, NY 10019', 'Bergdorf Goodman', 40.7636197, -73.9744388, 0);
//indicate that this is a departure stop
// single depot routes can only have one departure depot
FirstAddress.IsDepot := True;
AddAddress(FirstAddress, Result);
AddAddress(TAddress.Create(
'717 5th Ave New York, NY 10022', 'Giorgio Armani', 40.7669692, -73.9693864, 0),
Result);
AddAddress(TAddress.Create(
'888 Madison Ave New York, NY 10014', 'Ralph Lauren Women''s and Home', 40.7715154, -73.9669241, 0),
Result);
AddAddress(TAddress.Create(
'1011 Madison Ave New York, NY 10075', 'Yigal Azrou''l', 40.7772129, -73.9669, 0),
Result);
AddAddress(TAddress.Create(
'440 Columbus Ave New York, NY 10024', 'Frank Stella Clothier', 40.7808364, -73.9732729, 0),
Result);
AddAddress(TAddress.Create(
'324 Columbus Ave #1 New York, NY 10023', 'Liana', 40.7803123, -73.9793079, 0),
Result);
AddAddress(TAddress.Create(
'110 W End Ave New York, NY 10023', 'Toga Bike Shop', 40.7753077, -73.9861529, 0),
Result);
AddAddress(TAddress.Create(
'555 W 57th St New York, NY 10019', 'BMW of Manhattan', 40.7718005, -73.9897716, 0),
Result);
AddAddress(TAddress.Create(
'57 W 57th St New York, NY 10019', 'Verizon Wireless', 40.7558695, -73.9862019, 0),
Result);
end;
function TSingleDriverRoundTripTestDataProvider.MakeRouteParameters: TRouteParameters;
begin
Result := TRouteParameters.Create();
Result.AlgorithmType := TAlgorithmType.TSP;
Result.StoreRoute := False;
Result.RouteName := 'Single Driver Round Trip';
Result.RouteDate := 53583232;//TUtils.ConvertToUnixTimestamp(IncDay(Now, 1));
Result.RouteTime := 60 * 60 * 7;
Result.RouteMaxDuration := 86400;
Result.VehicleCapacity := '1';
Result.VehicleMaxDistanceMI := '10000';
Result.Optimize := TOptimize.Distance;
Result.DistanceUnit := TDistanceUnit.MI;
Result.DeviceType := TDeviceType.Web;
Result.TravelMode := TTravelMode.Driving;
end;
end.
|
unit Model.MergeCadastroGeral;
interface
uses Data.SisGeF, Control.CadastroGeral, Control.CadastroEnderecos, Control.CadastroContatos, Control.CadastroFinanceiro,
Control.CadastroRH, Control.CadastroGR, Control.CadastroHistorico, FireDAC.Comp.Client;
type
TMergeCadastroGeral = class
private
FCadastro : TCadastrosControl;
FEnderecos : TCadastroEnderecosControl;
FContatos : TCadastroContatosControl;
FRH : TCadastroRHControl;
FGR : TCadastroGRControl;
FHistorico : TCadastroHistoricoControl;
public
constructor Create;
destructor Destroy;
function FetchCadastroGeral(iId: Integer;iTipo: Integer): TFDQuery;
end;
implementation
{ TMergeCadastroGeral }
constructor TMergeCadastroGeral.Create;
begin
FCadastro := TCadastrosControl.Create;
FEnderecos := TCadastroEnderecosControl.Create;
FContatos := TCadastroContatosControl.Create;
FRH := TCadastroRHControl.Create;
FGR := TCadastroGRControl.Create;
FHistorico := TCadastroHistoricoControl.Create;
end;
destructor TMergeCadastroGeral.Destroy;
begin
FCadastro.Free;
FEnderecos.Free;
FContatos.Free;
FRH.Free;
FGR.Free;
FHistorico.Free;
end;
function TMergeCadastroGeral.FetchCadastroGeral(iId, iTipo: Integer): TFDQuery;
var
FCadastro : TFDQuery;
begin
FCadastro := Data_Sisgef.fdQueryCadastroGeral;
FCadastro.ParamByName('PID').AsInteger := iId;
FCadastro.ParamByName('PTIPO').AsInteger := iTipo;
FCadastro.Open;
Result := FCadastro;
end;
end.
|
unit dcDateEdit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, datacontroller, db, FFSUtils, FFSTypes,
LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDBaseEdit,
LMDCustomEdit, LMDEdit, lmdgraph, dcEdit;
type
// TFFSPopupWindow = class(TPopupWindow);
TDateStorageFormat = (dsfMMDDYYYY, dsfYYYYMMDD);
{ TDateEdit }
TdcDateEdit = class(TdcEdit )
private
FYrMo: boolean;
function GetMdy: string;
function GetYmd: string;
procedure SetAsDate(const Value: TDateTime);
function GetAsDate: TDateTime;
function GetInternalDate: TDateTime;
procedure SetYrMo(const Value: boolean);
procedure SetMdy(const Value: string);
procedure SetYmd(const Value: string);
private
OldReadOnly: boolean;
FDefaultToday: boolean;
FStorageFormat: TDateStorageFormat;
FNonDates: TFFSNonDates;
property InternalDate:TDateTime read GetInternalDate;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
function DateIsBlank(s: string): boolean;
procedure SetNonDates(const Value: TFFSNonDates);
procedure SetStorageFormat(const Value: TDateStorageFormat);
procedure SetDefaultToday( const Value: boolean);
protected
procedure FormatEntry;override;
function IsValidDate:boolean;
procedure KeyDown(var Key: Word; Shift: TShiftState);override;
procedure KeyPress(var Key: Char);override;
procedure ReadData(sender: TObject);override;
procedure WriteData(sender: TObject);override;
procedure DoEnter;override;
procedure DoExit;override;
public
property AsDate:TDateTime read GetAsDate write SetAsDate;
property Ymd:string read GetYmd write SetYmd;
property Mdy:string read GetMdy write SetMdy;
function IsValidEntry(RaiseException:boolean):boolean;
published
constructor Create(AOwner: TComponent); override;
property YrMo:boolean read FYrMo write SetYrMo;
property NonDates:TFFSNonDates read FNonDates write SetNonDates;
property StorageFormat : TDateStorageFormat read FStorageFormat write SetStorageFormat;
property DefaultToday:boolean read FDefaultToday write SetDefaultToday;
property Align;
property Font;
property ReadOnly;
property Required;
end;
procedure Register;
implementation
const
dsfString : array[TDateStorageFormat] of string = ('mm/dd/yyyy', 'yyyymmdd');
procedure Register;
begin
RegisterComponents('FFS Data Entry', [TdcDateEdit]);
end;
{ TdcDateEdit }
constructor TdcDateEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
width := 89;
fStorageFormat := dsfMMDDYYYY;
MaxLength := 10;
end;
function TdcDateEdit.IsValidEntry(RaiseException:boolean):boolean;
begin
result := false;
try
result := IsValidDate;
if (not result) then
raise EInvalidDateException.Create('Invalid Date Entered');
text := formatdatetime(sDispFormat[YrMo], AsDate);
except
if not YrMo then begin
if (ndCont in nondates) and (text = dvStrings[ndCont]) then result := true;
if (ndWaived in nondates) and (text = dvStrings[ndWaived]) then result := true;
if (ndHist in nondates) and (text = dvStrings[ndHist]) then result := true;
if (ndNA in nondates) and (text = dvStrings[ndNA]) then result := true;
if (ndSatisfied in nondates) and (text = dvStrings[ndSatisfied]) then result := true;
if (ndNewLoan in nondates) and (text = dvStrings[ndNewLoan]) then result := true;
if (ndOpen in nondates) and (text = dvStrings[ndOpen]) then result := true;
end;
if DateisBlank(Text) then result := true;// = ' / / ' then
if not result then
begin
if CanFocus then SetFocus;
if RaiseException then raise;
end;
end;
end;
procedure TdcDateEdit.CMExit(var Message: TCMExit);
begin
if not (csDesigning in ComponentState) then FormatEntry;
inherited;
end;
procedure TdcDateEdit.KeyDown(var Key: Word; Shift: TShiftState);
var s : string;
n, ok : integer;
begin
if ReadOnly then exit;
case Key of
Ord('A') : if (shift = []) then
begin
s := '';
if inputquery('Advance Date by Months','Number of months to advance',s) then
begin
val(s,n,ok);
if ok = 0 then AsDate := IncMonth(InternalDate, n);
SelectAll;
end;
Key := 0;
end;
Ord('Q') : if (shift = [ssShift]) or (shift = []) then
begin
if shift = [ssShift] then AsDate := IncMonth(InternalDate,-3)
else AsDate := IncMonth(InternalDate,3);
SelectAll;
key := 0;
end;
Ord('Y') : if (shift = [ssShift]) or (shift = []) then
begin
if shift = [ssShift] then AsDate := IncMonth(InternalDate,-12)
else AsDate := IncMonth(InternalDate,12);
SelectAll;
key := 0;
end;
Ord('M') : if (shift = [ssShift]) or (shift = []) then
begin
if shift = [ssShift] then AsDate := IncMonth(InternalDate,-1)
else AsDate := IncMonth(InternalDate,1);
SelectAll;
key := 0;
end;
Ord('D') : if (shift = [ssShift]) or (shift = []) and (not YrMo) then
begin
if shift = [ssShift] then AsDate := InternalDate-1
else AsDate := InternalDate+1;
SelectAll;
key := 0;
end;
VK_PRIOR : if (shift = [ssCtrl]) or (shift = []) then
begin
if shift = [ssCtrl] then AsDate := IncMonth(InternalDate,-12)
else AsDate := IncMonth(InternalDate,-1);
SelectAll;
Key := 0;
end;
VK_NEXT : if (shift = [ssCtrl]) or (shift = []) then
begin
if shift = [ssCtrl] then AsDate := IncMonth(InternalDate,12)
else AsDate := IncMonth(InternalDate,1);
SelectAll;
Key := 0;
end;
VK_UP,
VK_SUBTRACT : if (shift = []) then
begin
if YrMo then AsDate := IncMonth(InternalDate, -1)
else AsDate := InternalDate-1;
SelectAll;
Key := 0;
end;
VK_DOWN,
VK_ADD : if (shift = []) then
begin
if YrMo then AsDate := IncMonth(InternalDate, 1)
else AsDate := InternalDate+1;
SelectAll;
Key := 0;
end;
end;
inherited;
end;
procedure TdcDateEdit.KeyPress(var Key: Char);
procedure UpdateValue(var akey:char);
begin
case upcase(akey) of
'C' : text := dvStrings[ndCont];
'W' : text := dvStrings[ndWaived];
'H' : text := dvStrings[ndHist];
'N' : text := dvStrings[ndNA];
'O' : text := dvStrings[ndOpen];
'S' : text := dvStrings[ndSatisfied];
'X' : text := dvStrings[ndNewLoan];
end;
SelectAll;
akey := #0;
end;
begin
if not readonly then begin
if key = ' ' then key := 'T'; // default space to TODAY
case upcase(key) of
'Q',
'A',
'Y',
'M',
'D' : key := #0;
'C' : if ndCont in nondates then UpdateValue(Key) else key := #0;
'W' : if ndWaived in nondates then UpdateValue(Key) else key := #0;
'H' : if ndHist in nondates then UpdateValue(Key) else key := #0;
'N' : if ndNA in nondates then UpdateValue(Key) else key := #0;
'S' : if ndSatisfied in nondates then UpdateValue(Key) else key := #0;
'O' : if ndOpen in nondates then UpdateValue(key) else key := #0;
'X' : if ndNewLoan in nondates then UpdateValue(Key) else key := #0;
'T' : begin
AsDate := Trunc(Now);
key := #0;
end;
#13 : IsValidEntry(true);
'+',
'-' : key := #0;
end;
end;
inherited KeyPress(key);
end;
procedure TdcDateEdit.SetNonDates(const Value: TFFSNonDates);
begin
FNonDates := Value;
end;
function TdcDateEdit.DateIsBlank(s:string):boolean;
var x : integer;
nb : boolean;
begin
nb := false;
for x := 1 to length(s) do
begin
if not (s[x] in [' ', '/']) then nb := true;
end;
result := not nb;
end;
procedure TdcDateEdit.ReadData(sender: TObject);
var s : string;
begin
if not assigned(fdclink.DataController) then exit;
// if not assigned(fdclink.datacontroller.databuf) then exit;
if (databufindex = 0) and (DataField <> '') then begin
s := fdclink.DataController.dcStrings.StrVal[DataField];
if (s > '') then begin
if (StorageFormat = dsfYYYYMMDD) then begin
if s[1] in ['0'..'9'] then begin
if YrMo then s := system.copy(s,5,2) + '/' + system.copy(s,1,4)
else s := system.copy(s,5,2) + '/' + system.copy(s,7,2) + '/' + system.copy(s,1,4);
end;
end;
end;
text := s;
try
IsValidEntry(true);
except
end;
end
else begin
s := fdclink.datacontroller.databuf.AsString[DataBufIndex];
if (s > '') then begin
if (StorageFormat = dsfYYYYMMDD) then begin
if s[1] in ['0'..'9'] then begin
if YrMo then s := system.copy(s,5,2) + '/' + system.copy(s,1,4)
else s := system.copy(s,5,2) + '/' + system.copy(s,7,2) + '/' + system.copy(s,1,4);
end;
end;
end;
text := s;
try
IsValidEntry(true);
except
end;
end;
end;
procedure TdcDateEdit.SetStorageFormat(const Value: TDateStorageFormat);
begin
FStorageFormat := Value;
end;
procedure TdcDateEdit.WriteData(sender: TObject);
var
isadate : boolean;
s : string;
begin
if not assigned(fdclink.DataController) then exit;
// if not assigned(fdclink.dataController.DataBuf) then exit;
isadate := IsValidDate;
s := text; // default
if isadate then
begin
case StorageFormat of
dsfMMDDYYYY : s := Mdy;
dsfYYYYMMDD : s := Ymd;
end;
end;
if (databufindex = 0) and (DataField <> '') then begin
fdclink.DataController.dcStrings.StrVal[DataField] := s;
end
else fdclink.datacontroller.databuf.asString[DataBufIndex] := s;
end;
procedure TdcDateEdit.SetDefaultToday(const Value: boolean);
begin
FDefaultToday := Value;
end;
function TdcDateEdit.GetMdy: string;
var d : TDatetime;
begin
if IsValidDate then begin
d := AsDate;
result := formatdatetime(sdispFormat[YrMo],d);
end
else result := '';
end;
function TdcDateEdit.GetYmd: string;
var d : TDatetime;
begin
if IsValidDate then begin
d := AsDate;
if YrMo then result := formatdatetime('yyyymm',d)
else result := formatdatetime('yyyymmdd',d);
end
else result := '';
end;
procedure TdcDateEdit.SetAsDate(const Value: TDateTime);
begin
Text := FormatDateTime(sDispFormat[YrMo], value);
end;
function TdcDateEdit.GetAsDate: TDateTime;
var d : TDatetime;
begin
try
if YrMo then d := ffsutils.YrMoStrToDate(text)
else d := ffsutils.ConvertToDate(text);
result := d;
except
result := baddate;
end;
end;
function TdcDateEdit.IsValidDate: boolean;
var s : string;
d : TDateTime;
begin
s := text;
result := false;
if YrMo then begin
d := ffsutils.YrMoStrToDate(s);
if d <> baddate then result := true;
end
else begin
d := ffsutils.ConvertToDate(s);
if d <> baddate then result := true;
end;
end;
procedure TdcDateEdit.FormatEntry;
begin
IsValidEntry(true);
end;
function TdcDateEdit.GetInternalDate: TDateTime;
begin
result := ffsutils.ConvertToDate(text);
if result = BadDate then result := trunc(now);
end;
procedure TdcDateEdit.SetYrMo(const Value: boolean);
begin
FYrMo := Value;
end;
procedure TdcDateEdit.SetYmd(const Value: string);
var s : string;
begin
mdy := DateStorToDisp(value);
{ if s = '' then exit;
if YrMo then if s[1] in ['0'..'9'] then s := system.copy(s,5,2) + '/' + system.copy(s,1,4)
else if s[1] in ['0'..'9'] then s := system.copy(s,5,2) + '/' + system.copy(s,7,2) + '/' + system.copy(s,1,4);
text := s;
try
IsValidEntry(true);
except
end;
}
end;
procedure TdcDateEdit.SetMdy(const Value: string);
begin
text := value;
try
IsValidEntry(true);
except
end;
end;
procedure TdcDateEdit.DoEnter;
begin
OldReadOnly := ReadOnly;
if DataController <> nil then ReadOnly := DataController.ReadOnly;
inherited;
end;
procedure TdcDateEdit.DoExit;
begin
ReadOnly := OldReadonly;
inherited;
end;
end.
|
unit main;
interface
{$WARN UNIT_PLATFORM OFF}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.FileCtrl, ShellApi, SearchThread;
{$WARN UNIT_PLATFORM ON}
const
IMAGES_EXT = '.jpg;.jpeg;.jpe;.bmp;.dib;.png;.tif;.tiff;.gif;'; // расширения файлов с изображениями
type
TfrmMain = class(TForm)
barStatus: TStatusBar;
listImageFiles: TListBox;
btScan: TButton;
procedure btScanClick(Sender: TObject);
procedure listImageFilesDblClick(Sender: TObject);
private
{ Private declarations }
SearchThread: TFileSearchThread; // поток поиска файлов с изображениями
procedure WMFileSearchMsg(var Msg : TMessage); message WM_FILESEARCH_MSG; // процедура обработки сообщений от потока
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.btScanClick(Sender: TObject);
var
strChosenDirectory : string;
strCurPath : string;
begin
// Проверяем не запущенли уже поиск
if SearchThread <> nil then
if not SearchThread.Finished then
begin
MessageBox(Self.Handle, PChar('Search in progress'), PChar('Information'), MB_OK + MB_ICONINFORMATION + MB_APPLMODAL);
Exit;
end;
// Выбор каталога для поиска
// Используютря разные диалоги выбора каталога для разных версий Windows
strChosenDirectory := '';
strCurPath := GetCurrentDir;
{$WARN SYMBOL_PLATFORM OFF}
if Win32MajorVersion >= 6 then // >= Vista
with TFileOpenDialog.Create(nil) do
try
Title := 'Select Directory';
Options := [fdoPickFolders, fdoPathMustExist, fdoForceFileSystem];
OkButtonLabel := 'Select';
DefaultFolder := strCurPath;
FileName := strCurPath;
if Execute then
strChosenDirectory := FileName;
finally
Free;
end
else // XP
if SelectDirectory('Select Directory', ExtractFileDrive(strCurPath), strCurPath, [sdNewUI, sdNewFolder]) then strChosenDirectory := strCurPath;
{$WARN SYMBOL_PLATFORM ON}
// Поиск файлов в выбранном каталоге
if strChosenDirectory <> '' then
begin
listImageFiles.Clear;
SearchThread := TFileSearchThread.Create(strChosenDirectory, LowerCase(IMAGES_EXT), frmMain.Handle);
SearchThread.Start;
end;
end;
procedure TfrmMain.listImageFilesDblClick(Sender: TObject);
var
ExecInfo: TShellExecuteInfo;
begin
if listImageFiles.ItemIndex > -1 then
begin
// ShellExecute(0, 'open', PWideChar(listImageFiles.Items[listImageFiles.ItemIndex]), nil, nil, SW_SHOWNORMAL);
FillChar(ExecInfo, SizeOf(ExecInfo), 0);
ExecInfo.cbSize := SizeOf(ExecInfo);
ExecInfo.Wnd := 0;
ExecInfo.lpVerb := nil;
ExecInfo.lpFile := PChar(listImageFiles.Items[listImageFiles.ItemIndex]);
ExecInfo.lpParameters := nil;
ExecInfo.lpDirectory := nil;
ExecInfo.nShow := SW_SHOWNORMAL;
ExecInfo.fMask := SEE_MASK_NOASYNC or SEE_MASK_FLAG_NO_UI;
if not ShellExecuteEx(@ExecInfo) then RaiseLastOSError;
end;
end;
{*******************************************************************************
* Обработка сообщений от потока.
* В сообщении находится указатель на имя файла с полным путем к нему.
*******************************************************************************}
procedure TfrmMain.WMFileSearchMsg(var Msg : TMessage);
var
strFileName: PString;
begin
strFileName := PString(Msg.LParam);
try
listImageFiles.Items.Add(strFileName^);
finally
Dispose(strFileName);
end;
end;
end.
|
unit uTypes;
interface
uses
adl_structures,
Contnrs;
type
TUser = class(TObject)
public
id: Integer;
Name: String;
Password: String;
Email: String;
Phone: String;
EthAddress: String;
credits: Integer;
end;
TAlgorithm = class(TObject)
public
id: Integer;
Name: String;
end;
TProgram = class(TObject)
public
id: Integer;
Algorithm: TAlgorithm;
Title: String;
Description: String;
Path: String;
end;
TSetting = class(TObject)
public
id: Integer;
AProgram: TProgram;
Name: String;
Parameters: String;
end;
TNotifyType = class(TObject)
public
id: Integer;
Name: String;
end;
TNotification = class(TObject)
public
id: Integer;
NotifyType: TNotifyType;
Email: Boolean;
Phone: Boolean;
end;
TCommand = class(TObject)
public
id: Integer;
Name: String;
end;
TOverClock = class(TObject)
public
id: Integer;
Core: String;
Memory: String;
Voltage: Integer;
Power: Integer;
Temperature: Integer;
Fan: Integer;
end;
TGpu = class(TObject)
private
protected
function GetFanSpeed(idx: Integer): Integer; virtual; abstract;
function GetTemperature(idx: Integer): Integer; virtual; abstract;
function GetTargetTemperature(idx: Integer): Integer; virtual; abstract;
procedure SetTargetTemperature(idx: Integer; ATargetTemp: Integer); virtual; abstract;
class function GetNumberOfAdapters(): Integer; virtual; abstract;
class function GetAdapterInfo(idx: Integer): LPAdapterInfo; virtual; abstract;
function GetAdapterActive(idx: Integer): Boolean; virtual; abstract;
public
id: Integer;
idx: Integer;
BusNumber: Integer;
Overclock: TOverclock;
Name: String;
Vendor: String;
Memory: String;
Identifier: String;
Speed: String;
Temperature: Integer;
constructor Create();
destructor Destroy(); override;
end;
TMiner = class(TObject)
public
id: Integer;
statusId: Integer;
Gpus: TObjectList;
Settings: TSetting;
Name: String;
Notes: String;
MotherboardId: String;
Active: Boolean;
Online: Boolean;
TotalSpeed: String;
LastPing: TDateTime;
RestartCount: Integer;
function GetGpuByID(AID: Integer): TGpu;
constructor Create();
destructor Destroy(); override;
end;
TJob = class(TObject)
public
id: Integer;
Miner: TMiner;
Command: TCommand;
Parameters: String;
Active: Boolean;
end;
implementation
uses
Classes,
SysUtils;
{$REGION 'TMiner'}
constructor TMiner.Create();
begin
Gpus := TObjectList.Create(True);
end;
destructor TMiner.Destroy();
begin
FreeAndNil(Gpus);
inherited;
end;
function TMiner.GetGpuByID(AID: Integer): TGpu;
var
i: Integer;
begin
Result := nil;
for i := 0 to Gpus.Count - 1 do
if TGpu(Gpus[i]).id = AID then
begin
Result := TGpu(Gpus[i]);
Exit;
end;
end;
{$ENDREGION}
{$REGION 'TGpu'}
constructor TGpu.Create();
begin
Overclock := TOverClock.Create();
end;
destructor TGpu.Destroy();
begin
FreeAndNil(Overclock);
inherited;
end;
{$ENDREGION}
end.
|
{******************************************************************************}
{ }
{ Delphi FB4D Library }
{ Copyright (c) 2018-2022 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/FB4D }
{ }
{******************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{******************************************************************************}
unit FB4D.RealTimeDB;
interface
uses
System.Types, System.Classes, System.SysUtils, System.StrUtils, System.JSON,
System.NetConsts, System.Net.HttpClient, System.Net.URLClient,
System.NetEncoding, System.Generics.Collections,
REST.Types,
FB4D.Interfaces, FB4D.RealTimeDB.Listener;
type
TFirebaseEvent = class(TInterfacedObject, IFirebaseEvent)
private
fListener: TRTDBListenerThread;
constructor Create(Listener: TRTDBListenerThread);
public
destructor Destroy; override;
procedure StopListening(MaxTimeOutInMS: cardinal = 500); overload;
procedure StopListening(const NodeName: string;
MaxTimeOutInMS: cardinal = 500); overload; { deprecated }
function GetResourceParams: TRequestResourceParam;
function GetLastReceivedMsg: TDateTime;
function IsStopped: boolean;
end;
TRealTimeDB = class(TInterfacedObject, IRealTimeDB)
private
fBaseURL: string;
fAuth: IFirebaseAuthentication;
const
cJSONExt = '.json';
function AddJSONExtToRequest(ResourceParams: TRequestResourceParam):
TRequestResourceParam;
function SendRequestSynchronous(ResourceParams: TRequestResourceParam;
Method: TRESTRequestMethod; Data: TJSONValue = nil;
QueryParams: TQueryParams = nil): IFirebaseResponse;
function RespSynchronous(Response: IFirebaseResponse): TJSONValue;
procedure SendRequest(const RequestID: string;
ResourceParams: TRequestResourceParam; Method: TRESTRequestMethod;
Data: TJSONValue; QueryParams: TQueryParams; OnResponse: TOnFirebaseResp;
OnRequestError: TOnRequestError; OnSuccess: TOnSuccess);
procedure OnResponse(const RequestID: string;
Response: IFirebaseResponse; OnValue: TOnRTDBValue;
OnError: TOnRequestError);
procedure OnGetResponse(const RequestID: string;
Response: IFirebaseResponse);
procedure OnPutResponse(const RequestID: string;
Response: IFirebaseResponse);
procedure OnPostResponse(const RequestID: string;
Response: IFirebaseResponse);
procedure OnPatchResponse(const RequestID: string;
Response: IFirebaseResponse);
procedure OnDeleteResponse(const RequestID: string;
Response: IFirebaseResponse);
procedure OnServerVarResp(const VarName: string;
Response: IFirebaseResponse);
public
constructor Create(const ProjectID: string; Auth: IFirebaseAuthentication); deprecated;
constructor CreateByURL(const FirebaseURL: string; Auth: IFirebaseAuthentication);
procedure Get(ResourceParams: TRequestResourceParam;
OnGetValue: TOnRTDBValue; OnRequestError: TOnRequestError;
QueryParams: TQueryParams = nil);
function GetSynchronous(ResourceParams: TRequestResourceParam;
QueryParams: TQueryParams = nil): TJSONValue;
procedure Put(ResourceParams: TRequestResourceParam; Data: TJSONValue;
OnPutValue: TOnRTDBValue; OnRequestError: TOnRequestError;
QueryParams: TQueryParams = nil);
function PutSynchronous(ResourceParams: TRequestResourceParam;
Data: TJSONValue; QueryParams: TQueryParams = nil): TJSONValue;
procedure Post(ResourceParams: TRequestResourceParam; Data: TJSONValue;
OnPostValue: TOnRTDBValue; OnRequestError: TOnRequestError;
QueryParams: TQueryParams = nil);
function PostSynchronous(ResourceParams: TRequestResourceParam;
Data: TJSONValue; QueryParams: TQueryParams = nil): TJSONValue;
procedure Patch(ResourceParams: TRequestResourceParam; Data: TJSONValue;
OnPatchValue: TOnRTDBValue; OnRequestError: TOnRequestError;
QueryParams: TQueryParams = nil);
function PatchSynchronous(ResourceParams: TRequestResourceParam;
Data: TJSONValue; QueryParams: TQueryParams = nil): TJSONValue;
procedure Delete(ResourceParams: TRequestResourceParam;
OnDelete: TOnRTDBDelete; OnRequestError: TOnRequestError;
QueryParams: TQueryParams = nil); overload; { deprecated }
procedure Delete(ResourceParams: TRequestResourceParam;
OnDelete: TOnRTDBDelete; OnRequestError: TOnRequestError); overload;
function DeleteSynchronous(ResourceParams: TRequestResourceParam;
QueryParams: TQueryParams = nil): boolean; overload; { deprecated }
function DeleteSynchronous(ResourceParams: TRequestResourceParam): boolean;
overload;
function ListenForValueEvents(ResourceParams: TRequestResourceParam;
ListenEvent: TOnReceiveEvent; OnStopListening: TOnStopListenEvent;
OnError: TOnRequestError; OnAuthRevoked: TOnAuthRevokedEvent = nil;
OnConnectionStateChange: TOnConnectionStateChange = nil;
DoNotSynchronizeEvents: boolean = false): IFirebaseEvent;
procedure GetServerVariables(const ServerVarName: string;
ResourceParams: TRequestResourceParam;
OnServerVariable: TOnRTDBServerVariable = nil;
OnError: TOnRequestError = nil);
function GetServerVariablesSynchronous(const ServerVarName: string;
ResourceParams: TRequestResourceParam): TJSONValue;
end;
const
GOOGLE_FIREBASE = 'https://%s.firebaseio.com';
implementation
uses
FB4D.Helpers, FB4D.Request;
resourcestring
rsEvtListenerFailed = 'Event listener for %s failed: %s';
rsEvtStartFailed = 'Event listener start for %s failed: %s';
rsEvtParserFailed = 'Exception in event parser';
{ TFirebase }
constructor TRealTimeDB.Create(const ProjectID: string;
Auth: IFirebaseAuthentication);
begin
inherited Create;
Assert(assigned(Auth), 'Authentication not initalized');
fBaseURL := Format(GOOGLE_FIREBASE, [ProjectID]);
fAuth := Auth;
end;
constructor TRealTimeDB.CreateByURL(const FirebaseURL: string;
Auth: IFirebaseAuthentication);
begin
Assert(assigned(Auth), 'Authentication not initalized');
fBaseURL := FirebaseURL;
fAuth := Auth;
end;
function TRealTimeDB.AddJSONExtToRequest(
ResourceParams: TRequestResourceParam): TRequestResourceParam;
var
c, e: integer;
begin
e := length(ResourceParams) - 1;
if e < 0 then
begin
SetLength(result, 1);
result[0] := cJSONExt;
end else begin
SetLength(result, e + 1);
for c := 0 to e - 1 do
result[c] := ResourceParams[c];
result[e] := ResourceParams[e] + cJSONExt;
end;
end;
function TRealTimeDB.SendRequestSynchronous(
ResourceParams: TRequestResourceParam; Method: TRESTRequestMethod;
Data: TJSONValue; QueryParams: TQueryParams): IFirebaseResponse;
var
Request: IFirebaseRequest;
begin
Request := TFirebaseRequest.Create(fBaseURL, '', fAuth);
result := Request.SendRequestSynchronous(AddJSONExtToRequest(ResourceParams),
Method, Data, QueryParams, tmAuthParam);
end;
procedure TRealTimeDB.SendRequest(const RequestID: string;
ResourceParams: TRequestResourceParam; Method: TRESTRequestMethod;
Data: TJSONValue; QueryParams: TQueryParams; OnResponse: TOnFirebaseResp;
OnRequestError: TOnRequestError; OnSuccess: TOnSuccess);
var
Request: IFirebaseRequest;
begin
Request := TFirebaseRequest.Create(fBaseURL, RequestID, fAuth);
Request.SendRequest(AddJSONExtToRequest(ResourceParams), Method,
Data, QueryParams, tmAuthParam, OnResponse, OnRequestError, OnSuccess);
end;
procedure TRealTimeDB.Get(ResourceParams: TRequestResourceParam;
OnGetValue: TOnRTDBValue; OnRequestError: TOnRequestError;
QueryParams: TQueryParams);
begin
SendRequest(TFirebaseHelpers.ArrStrToCommaStr(ResourceParams), ResourceParams,
rmGet, nil, QueryParams, OnGetResponse, OnRequestError,
TOnSuccess.CreateRTDBValue(OnGetValue));
end;
procedure TRealTimeDB.OnResponse(const RequestID: string;
Response: IFirebaseResponse; OnValue: TOnRTDBValue; OnError: TOnRequestError);
var
Val: TJSONValue;
begin
Val := nil;
try
if Response.StatusOk then
begin
if Response.IsJSONObj then
begin
Response.CheckForJSONObj;
Val := Response.GetContentAsJSONObj;
end else
Val := Response.GetContentAsJSONVal;
end
else if not Response.StatusNotFound then
raise EFirebaseResponse.Create(Response.ErrorMsgOrStatusText);
if assigned(OnValue) then
OnValue(SplitString(RequestID, ','), Val);
except
on e: Exception do
begin
if assigned(OnError) then
OnError(RequestID, e.Message)
else
TFirebaseHelpers.LogFmt(rsFBFailureIn,
['RealTimeDB.OnResponse', RequestID, e.Message]);
end;
end;
Val.Free;
end;
procedure TRealTimeDB.OnGetResponse(const RequestID: string;
Response: IFirebaseResponse);
begin
OnResponse(RequestID, Response, Response.OnSuccess.OnRTDBValue,
Response.OnError);
end;
function TRealTimeDB.RespSynchronous(Response: IFirebaseResponse): TJSONValue;
begin
if Response.StatusOk then
begin
if Response.IsJSONObj then
begin
Response.CheckForJSONObj;
result := Response.GetContentAsJSONObj;
end else
result := Response.GetContentAsJSONVal;
end
else if Response.StatusNotFound then
result := TJSONNull.Create
else
raise EFirebaseResponse.Create(Response.ErrorMsgOrStatusText);
end;
function TRealTimeDB.GetSynchronous(ResourceParams: TRequestResourceParam;
QueryParams: TQueryParams): TJSONValue;
var
Resp: IFirebaseResponse;
begin
Resp := SendRequestSynchronous(ResourceParams, rmGet, nil, QueryParams);
result := RespSynchronous(Resp);
end;
procedure TRealTimeDB.Put(ResourceParams: TRequestResourceParam;
Data: TJSONValue; OnPutValue: TOnRTDBValue; OnRequestError: TOnRequestError;
QueryParams: TQueryParams);
begin
SendRequest(TFirebaseHelpers.ArrStrToCommaStr(ResourceParams), ResourceParams,
rmPut, Data, QueryParams, OnPutResponse, OnRequestError,
TOnSuccess.CreateRTDBValue(OnPutValue));
end;
procedure TRealTimeDB.OnPutResponse(const RequestID: string;
Response: IFirebaseResponse);
begin
OnResponse(RequestID, Response, Response.OnSuccess.OnRTDBValue,
Response.OnError);
end;
function TRealTimeDB.PutSynchronous(ResourceParams: TRequestResourceParam;
Data: TJSONValue; QueryParams: TQueryParams): TJSONValue;
var
Resp: IFirebaseResponse;
begin
Resp := SendRequestSynchronous(ResourceParams, rmPut, Data, QueryParams);
result := RespSynchronous(Resp);
end;
function TRealTimeDB.PostSynchronous(ResourceParams: TRequestResourceParam;
Data: TJSONValue; QueryParams: TQueryParams): TJSONValue;
var
Resp: IFirebaseResponse;
begin
Resp := SendRequestSynchronous(ResourceParams, rmPost, Data, QueryParams);
if Resp.StatusOk then
begin
if Resp.IsJSONObj then
begin
Resp.CheckForJSONObj;
result := Resp.GetContentAsJSONObj;
end else
result := Resp.GetContentAsJSONVal;
end
else if Resp.StatusNotFound then
result := TJSONNull.Create
else
raise EFirebaseResponse.Create(Resp.ErrorMsgOrStatusText);
end;
procedure TRealTimeDB.Post(ResourceParams: TRequestResourceParam;
Data: TJSONValue; OnPostValue: TOnRTDBValue; OnRequestError: TOnRequestError;
QueryParams: TQueryParams = nil);
begin
SendRequest(TFirebaseHelpers.ArrStrToCommaStr(ResourceParams), ResourceParams,
rmPost, Data, QueryParams, OnPostResponse, OnRequestError,
TOnSuccess.CreateRTDBValue(OnPostValue));
end;
procedure TRealTimeDB.OnPostResponse(const RequestID: string;
Response: IFirebaseResponse);
begin
OnResponse(RequestID, Response, Response.OnSuccess.OnRTDBValue,
Response.OnError);
end;
function TRealTimeDB.PatchSynchronous(ResourceParams: TRequestResourceParam;
Data: TJSONValue; QueryParams: TQueryParams): TJSONValue;
var
Resp: IFirebaseResponse;
begin
Resp := SendRequestSynchronous(ResourceParams, rmPatch, Data,
QueryParams);
result := RespSynchronous(Resp);
end;
procedure TRealTimeDB.Patch(ResourceParams: TRequestResourceParam;
Data: TJSONValue; OnPatchValue: TOnRTDBValue; OnRequestError: TOnRequestError;
QueryParams: TQueryParams = nil);
begin
SendRequest(TFirebaseHelpers.ArrStrToCommaStr(ResourceParams), ResourceParams,
rmPatch, Data, QueryParams, OnPatchResponse, OnRequestError,
TOnSuccess.CreateRTDBValue(OnPatchValue));
end;
procedure TRealTimeDB.OnPatchResponse(const RequestID: string;
Response: IFirebaseResponse);
begin
OnResponse(RequestID, Response, Response.OnSuccess.OnRTDBValue,
Response.OnError);
end;
function TRealTimeDB.DeleteSynchronous(ResourceParams: TRequestResourceParam;
QueryParams: TQueryParams): boolean;
var
Resp: IFirebaseResponse;
begin
Resp := SendRequestSynchronous(ResourceParams, rmDelete, nil,
QueryParams);
if Resp.StatusOk then
result := true
else if Resp.StatusNotFound then
result := false
else
raise EFirebaseResponse.Create(Resp.ErrorMsgOrStatusText);
end;
function TRealTimeDB.DeleteSynchronous(
ResourceParams: TRequestResourceParam): boolean;
var
Resp: IFirebaseResponse;
begin
Resp := SendRequestSynchronous(ResourceParams, rmDelete, nil, nil);
if Resp.StatusOk then
result := true
else if Resp.StatusNotFound then
result := false
else
raise EFirebaseResponse.Create(Resp.ErrorMsgOrStatusText);
end;
procedure TRealTimeDB.Delete(ResourceParams: TRequestResourceParam;
OnDelete: TOnRTDBDelete; OnRequestError: TOnRequestError;
QueryParams: TQueryParams);
begin
SendRequest(TFirebaseHelpers.ArrStrToCommaStr(ResourceParams), ResourceParams,
rmDelete, nil, QueryParams, OnDeleteResponse, OnRequestError,
TOnSuccess.CreateRTDBDelete(OnDelete));
end;
procedure TRealTimeDB.Delete(ResourceParams: TRequestResourceParam;
OnDelete: TOnRTDBDelete; OnRequestError: TOnRequestError);
begin
SendRequest(TFirebaseHelpers.ArrStrToCommaStr(ResourceParams), ResourceParams,
rmDelete, nil, nil, OnDeleteResponse, OnRequestError,
TOnSuccess.CreateRTDBDelete(OnDelete));
end;
procedure TRealTimeDB.OnDeleteResponse(const RequestID: string;
Response: IFirebaseResponse);
begin
if Response.StatusOk then
begin
if assigned(Response.OnSuccess.OnRTDBDelete) then
Response.OnSuccess.OnRTDBDelete(SplitString(RequestID, ','), true)
end else
if Response.StatusNotFound then
begin
if assigned(Response.OnSuccess.OnRTDBDelete) then
Response.OnSuccess.OnRTDBDelete(SplitString(RequestID, ','), false)
end
else if assigned(Response.OnError) then
Response.OnError(RequestID, Response.ErrorMsgOrStatusText)
else
TFirebaseHelpers.LogFmt(rsFBFailureIn,
['RealTimeDB.OnDeleteResponse', RequestID, Response.ErrorMsgOrStatusText]);
end;
function TRealTimeDB.GetServerVariablesSynchronous(const ServerVarName: string;
ResourceParams: TRequestResourceParam): TJSONValue;
var
Resp: IFirebaseResponse;
Data: TJSONObject;
begin
Data := TJSONObject.Create(TJSONPair.Create('.sv', ServerVarName));
try
Resp := SendRequestSynchronous(ResourceParams, rmPut, Data, nil);
if resp.StatusOk then
result := resp.GetContentAsJSONVal
else
result := nil;
finally
Data.Free;
end;
end;
procedure TRealTimeDB.GetServerVariables(const ServerVarName: string;
ResourceParams: TRequestResourceParam; OnServerVariable: TOnRTDBServerVariable;
OnError: TOnRequestError);
var
Data: TJSONObject;
begin
Data := TJSONObject.Create(TJSONPair.Create('.sv', ServerVarName));
try
SendRequest(ServerVarName, ResourceParams, rmPut, Data, nil,
OnServerVarResp, OnError,
TOnSuccess.CreateRTDBServerVariable(OnServerVariable));
finally
Data.Free;
end;
end;
procedure TRealTimeDB.OnServerVarResp(const VarName: string;
Response: IFirebaseResponse);
var
Val: TJSONValue;
begin
try
if Response.StatusOk then
begin
Val := Response.GetContentAsJSONVal;
try
if assigned(Response.OnSuccess.OnRTDBServerVariable) then
Response.OnSuccess.OnRTDBServerVariable(VarName, Val);
finally
Val.Free;
end;
end else if assigned(Response.OnError) then
begin
if not Response.ErrorMsg.IsEmpty then
Response.OnError(Varname, Response.ErrorMsg)
else
Response.OnError(Varname, Response.StatusText);
end;
except
on e: exception do
if assigned(Response.OnError) then
Response.OnError(Varname, e.Message)
else
TFirebaseHelpers.Log('RealTimeDB.OnServerVarResp Exception ' +
e.Message);
end;
end;
function TRealTimeDB.ListenForValueEvents(ResourceParams: TRequestResourceParam;
ListenEvent: TOnReceiveEvent; OnStopListening: TOnStopListenEvent;
OnError: TOnRequestError; OnAuthRevoked: TOnAuthRevokedEvent;
OnConnectionStateChange: TOnConnectionStateChange;
DoNotSynchronizeEvents: boolean): IFirebaseEvent;
var
FirebaseEvent: TFirebaseEvent;
begin
FirebaseEvent := TFirebaseEvent.Create(
TRTDBListenerThread.Create(fBaseURL, fAuth));
FirebaseEvent.fListener.RegisterEvents(ResourceParams, ListenEvent,
OnStopListening, OnError, OnAuthRevoked, OnConnectionStateChange,
DoNotSynchronizeEvents);
FirebaseEvent.fListener.Start;
result := FirebaseEvent;
end;
{ TFirebaseEvent }
constructor TFirebaseEvent.Create(Listener: TRTDBListenerThread);
begin
fListener := Listener;
end;
destructor TFirebaseEvent.Destroy;
begin
if fListener.IsRunning then
StopListening;
fListener.Free;
inherited;
end;
function TFirebaseEvent.GetLastReceivedMsg: TDateTime;
begin
Assert(assigned(fListener), 'No Listener');
result := fListener.LastReceivedMsg;
end;
function TFirebaseEvent.GetResourceParams: TRequestResourceParam;
begin
Assert(assigned(fListener), 'No Listener');
result := fListener.ResParams;
end;
function TFirebaseEvent.IsStopped: boolean;
begin
Assert(assigned(fListener), 'No Listener');
result := fListener.StopWaiting;
end;
procedure TFirebaseEvent.StopListening(MaxTimeOutInMS: cardinal);
begin
if assigned(fListener) then
fListener.StopListener(MaxTimeOutInMS);
end;
procedure TFirebaseEvent.StopListening(const NodeName: string;
MaxTimeOutInMS: cardinal);
begin
StopListening(MaxTimeOutInMS);
end;
end.
|
unit K459284359;
{* [Requestlink:459284359] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K459284359.pas"
// Стереотип: "TestCase"
// Элемент модели: "K459284359" MUID: (51AC93AE000C)
// Имя типа: "TK459284359"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, HTMLtoEVDTest
;
type
TK459284359 = class(THTMLtoEVDTest)
{* [Requestlink:459284359] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK459284359
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *51AC93AE000Cimpl_uses*
//#UC END# *51AC93AE000Cimpl_uses*
;
function TK459284359.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.8';
end;//TK459284359.GetFolder
function TK459284359.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '51AC93AE000C';
end;//TK459284359.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK459284359.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
unit DAO.EntregadoresExpreessas;
interface
uses
FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.EntregadoresExpressas;
type
TEntregadoresExpressasDAO = class
private
FConexao : TConexao;
public
constructor Create;
function Inserir(AEntregador: TEntregadoresExpressas): Boolean;
function Alterar(AEntregador: TEntregadoresExpressas): Boolean;
function Excluir(AEntregador: TEntregadoresExpressas): Boolean;
function Pesquisar(aParam: array of variant): TFDQuery;
end;
const
TABLENAME = 'tbcodigosentregadores';
implementation
{ TEntregadoresExpressasDAO }
uses Control.Sistema;
function TEntregadoresExpressasDAO.Alterar(AEntregador: TEntregadoresExpressas): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('UPDATE ' + TABLENAME + 'SET COD_CADASTRO = :COD_CADASTRO, COD_ENTREGADOR = :COD_ENTREGADOR, ' +
'NOM_FANTASIA = :NOM_FANTASIA, COD_AGENTE = :COD_AGENTE, DAT_CODIGO = :DAT_CODIGO, DES_CHAVE = :DES_CHAVE, ' +
'COD_GRUPO = :COD_GRUPO, VAL_VERBA = :VAL_VERBA, NOM_EXECUTANTE = :NOM_EXECUTANTE: SISTEMA ' +
'DAT_MANUTENCAO = :DAT_MANUTENCAO, WHERE COD_CADASTRO = :COD_CADASTRO AND COD_ENTREGADOR = :COD_ENTREGADOR;',
[AEntregador.Fantasia, AEntregador.Agente, AEntregador.Data, AEntregador.Chave, AEntregador.Grupo,
AEntregador.Verba, AEntregador.Executor, AEntregador.Manutencao, AEntregador.Cadastro, AEntregador.Entregador]);
Result := True;
finally
FDQuery.Free;
end;
end;
constructor TEntregadoresExpressasDAO.Create;
begin
FConexao := TSistemaControl.GetInstance().Conexao;
end;
function TEntregadoresExpressasDAO.Excluir(AEntregador: TEntregadoresExpressas): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where WHERE COD_CADASTRO = :COD_CADASTRO AND COD_ENTREGADOR = :COD_ENTREGADOR',
[AEntregador.Cadastro, AEntregador.Entregador]);
Result := True;
finally
FDquery.Free;
end;
end;
function TEntregadoresExpressasDAO.Inserir(AEntregador: TEntregadoresExpressas): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + '(COD_CADASTRO, COD_ENTREGADOR, NOM_FANTASIA, COD_AGENTE, DAT_CODIGO, ' +
'DES_CHAVE, COD_GRUPO, VAL_VERBA, NOM_EXECUTANTE, DAT_MANUTENCAO) ' +
'VALUES ' +
'(:COD_CADASTRO, :COD_ENTREGADOR, :NOM_FANTASIA, :COD_AGENTE, :DAT_CODIGO, :DES_CHAVE, :COD_GRUPO, ' +
':VAL_VERBA, :NOM_EXECUTANTE, :DAT_MANUTENCAO);', [AEntregador.Cadastro, AEntregador.Entregador,
AEntregador.Fantasia, AEntregador.Agente, AEntregador.Data, AEntregador.Chave, AEntregador.Grupo,
AEntregador.Verba, AEntregador.Executor, AEntregador.Manutencao]);
Result := True;
finally
FDQuery.Free;
end;
end;
function TEntregadoresExpressasDAO.Pesquisar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'CADASTRO' then
begin
FDQuery.SQL.Add('WHERE COD_CADASTRO = :COD_CADASTRO');
FDQuery.ParamByName('COD_CADASTRO').AsInteger := aParam[1];
end;
if aParam[0] = 'ENTREGADOR' then
begin
FDQuery.SQL.Add('WHERE COD_ENTREGADOR = :COD_ENTREGADOR');
FDQuery.ParamByName('COD_ENTREGADOR').AsInteger := aParam[1];
end;
if aParam[0] = 'AGENTE' then
begin
FDQuery.SQL.Add('WHERE COD_AGENTE = :COD_AGENTE');
FDQuery.ParamByName('COD_AGENTE').AsInteger := aParam[1];
end;
if aParam[0] = 'DATA' then
begin
FDQuery.SQL.Add('WHERE DAT_CODIGO = :DAT_CODIGO');
FDQuery.ParamByName('DAT_CODIGO').AsDate := aParam[1];
end;
if aParam[0] = 'FANTASIA' then
begin
FDQuery.SQL.Add('WHERE NOM_FANTASIA = :NOM_FANTASIA');
FDQuery.ParamByName('NOM_FANTASIA').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('WHERE ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open;
Result := FDQuery;
end;
end.
|
unit Main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Menus,
StdCtrls, ExtCtrls, ComCtrls, About, Reading, HMUtils;
type
{ TMainForm }
TMainForm = class(TForm)
AboutBtn: TMenuItem;
DbgHex: TMemo;
unkTxtExportBtn: TMenuItem;
txtExportBtn: TMenuItem;
UtilMenu: TMenuItem;
MessageList: TComboBox;
FileName: TLabel;
LabelFileName: TLabel;
MainMenu1: TMainMenu;
FileMenu: TMenuItem;
MsgContent: TMemo;
MenuSave: TMenuItem;
MenuOpen: TMenuItem;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
StatusBar1: TStatusBar;
procedure AboutBtnClick(Sender: TObject);
procedure txtExportBtnClick(Sender: TObject);
procedure MenuOpenClick(Sender: TObject);
procedure MessageListChange(Sender: TObject);
procedure ResetForm;
procedure PopulateMsgCombo;
procedure DisplayMsg;
procedure unkTxtExportBtnClick(Sender: TObject);
// procedure ReadPointers;
// procedure ReadMessage(Index: SmallInt);
//procedure ConvertFromHM(Message: array of Byte);
private
{ private declarations }
public
{ public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
{ TMainForm }
procedure TMainForm.DisplayMsg;
begin
with Mes.MsgCollection[MessageList.ItemIndex] do
begin
MsgContent.Text := mText;
DbgHex.Text := mByteStr;
end;
end;
procedure TMainForm.unkTxtExportBtnClick(Sender: TObject);
begin
exportMesToTxt(true);
end;
procedure TMainForm.ResetForm;
begin
MessageList.Items.Clear;
MsgContent.Text := '';
end;
procedure TMainForm.PopulateMsgCombo;
var
// msg: TMsg;
I: Integer = 0;
begin
//for msg in Mes.MsgCollection do
//MessageList.Items.Add(Msg.MsgText);
for I := 0 to Length(Mes.MsgCollection) - 1 do
MessageList.Items.Add('Message ' + IntToStr(I + 1));
MessageList.Enabled := true;
MessageList.ItemIndex := 0;
DisplayMsg;
end;
procedure TMainForm.MenuOpenClick(Sender: TObject);
begin
if OpenDialog.Execute then
begin
openFile(OpenDialog.FileName);
ResetForm;
PopulateMsgCombo;
FileName.Caption := ExtractFileName(OpenDialog.FileName);
end;
end;
procedure TMainForm.AboutBtnClick(Sender: TObject);
begin
with TAboutForm.Create(nil) do
ShowModal;
end;
procedure TMainForm.txtExportBtnClick(Sender: TObject);
begin
exportMesToTxt;
end;
procedure TMainForm.MessageListChange(Sender: TObject);
begin
DisplayMsg;
end;
end.
|
unit via6522;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}main_engine,sysutils,dialogs,lib_sdl2;
type
tin_handler=function:byte;
tout_handler=procedure(valor:byte);
via6522_chip=class
constructor create(clock:dword);
destructor free;
public
Joystick1,Joystick2:byte;
procedure reset;
function read(direccion:byte):byte;
procedure write(direccion,valor:byte);
procedure change_calls(in_a,in_b:tin_handler;out_a,out_b,irq_set,ca2_set,cb2_set:tout_handler);
procedure write_pa(valor:byte);
procedure update_timers(estados:word);
procedure set_pb_line(line:byte;state:boolean);
procedure write_cb1(state:boolean);
private
t1_pb7,sr,pcr,acr,ier,ifr:byte;
out_a,out_b,in_a,in_b,ddr_a,ddr_b,latch_a,latch_b:byte;
out_ca2,out_cb1,out_cb2,t1_active,t2_active,in_cb2:byte;
t1ll,t1lh,t2ll,t2lh:byte;
t1cl,t1ch,t2cl,t2ch:byte;
shift_counter:byte;
in_a_handler,in_b_handler:tin_handler;
irq_handler,ca2_handler,cb1_handler,cb2_handler,out_a_handler,out_b_handler:tout_handler;
in_cb1,shift_timer,shift_irq_enabled:boolean;
t1_contador,t2_contador,shift_irq_contador:integer;
time1,time2,clock:dword;
procedure clr_pa_int;
procedure clr_pb_int;
procedure set_int(valor:byte);
procedure clear_int(valor:byte);
procedure output_irq;
function input_pa:byte;
function input_pb:byte;
procedure output_pa;
procedure output_pb;
function get_counter1_value:word;
procedure counter2_decrement;
procedure shift_in;
end;
var
via6522_0:via6522_chip;
implementation
const
VIA_PB = 0;
VIA_PA = 1;
VIA_DDRB = 2;
VIA_DDRA = 3;
VIA_T1CL = 4;
VIA_T1CH = 5;
VIA_T1LL = 6;
VIA_T1LH = 7;
VIA_T2CL = 8;
VIA_T2CH = 9;
VIA_SR = 10;
VIA_ACR = 11;
VIA_PCR = 12;
VIA_IFR = 13;
VIA_IER = 14;
VIA_PANH = 15;
INT_CA2=$01;
INT_CA1=$02;
INT_SR =$04;
INT_CB2=$08;
INT_CB1=$10;
INT_T2 =$20;
INT_T1 =$40;
INT_ANY=$80;
IFR_DELAY=3;
//Macros
function PB_LATCH_ENABLE(valor:byte):boolean;
begin
PB_LATCH_ENABLE:=(valor and 2)<>0;
end;
function T1_SET_PB7(valor:byte):boolean;
begin
T1_SET_PB7:=(valor and $80)<>0;
end;
function CB2_IND_IRQ(valor:byte):boolean;
begin
CB2_IND_IRQ:=(valor and $a0)=$20;
end;
function CB2_PULSE_OUTPUT(valor:byte):boolean;
begin
CB2_PULSE_OUTPUT:=(valor and $e0)=$a0;
end;
function CB2_AUTO_HS(valor:byte):boolean;
begin
CB2_AUTO_HS:=(valor and $c0)=$80;
end;
function CA2_FIX_OUTPUT(valor:byte):boolean;
begin
CA2_FIX_OUTPUT:=(valor and $0c)=$0c;
end;
function CB2_FIX_OUTPUT(valor:byte):boolean;
begin
CB2_FIX_OUTPUT:=(valor and $c0)=$c0;
end;
function CA2_OUTPUT_LEVEL(valor:byte):byte;
begin
CA2_OUTPUT_LEVEL:=(valor and $02) shr 1;
end;
function CB2_OUTPUT_LEVEL(valor:byte):byte;
begin
CB2_OUTPUT_LEVEL:=(valor and $20) shr 5;
end;
function SR_DISABLED(valor:byte):boolean;
begin
SR_DISABLED:=(valor and $1c)=0;
end;
function SI_EXT_CONTROL(valor:byte):boolean;
begin
SI_EXT_CONTROL:=(valor and $1c)=$0c;
end;
function SO_EXT_CONTROL(valor:byte):boolean;
begin
SO_EXT_CONTROL:=(valor and $1c)=$1c;
end;
function T1_CONTINUOUS(valor:byte):boolean;
begin
T1_CONTINUOUS:=(valor and $40)<>0;
end;
function SI_T2_CONTROL(valor:byte):boolean;
begin
SI_T2_CONTROL:=(valor and $1c)=$04;
end;
function SI_O2_CONTROL(valor:byte):boolean;
begin
SI_O2_CONTROL:=(valor and $1c)=$08;
end;
function T2_COUNT_PB6(valor:byte):boolean;
begin
T2_COUNT_PB6:=(valor and $20)<>0;
end;
function CB1_LOW_TO_HIGH(valor:byte):boolean;
begin
CB1_LOW_TO_HIGH:=(valor and $10)<>0;
end;
function CB1_HIGH_TO_LOW(valor:byte):boolean;
begin
CB1_HIGH_TO_LOW:=(valor and $10)=0;
end;
function PA_LATCH_ENABLE(valor:byte):boolean;
begin
PA_LATCH_ENABLE:=(valor and 1)<>0;
end;
function CA2_PULSE_OUTPUT(valor:byte):boolean;
begin
CA2_PULSE_OUTPUT:=((valor and $0e)=$0a);
end;
function CA2_AUTO_HS(valor:byte):boolean;
begin
CA2_AUTO_HS:=(valor and $0c)=$08;
end;
function CA2_IND_IRQ(valor:byte):boolean;
begin
CA2_IND_IRQ:=(valor and $0a)=$02;
end;
function SO_O2_CONTROL(valor:byte):boolean;
begin
SO_O2_CONTROL:=((valor and $1c)=$18);
end;
function SO_T2_RATE(valor:byte):boolean;
begin
SO_T2_RATE:=((valor and $1c)=$10);
end;
function SO_T2_CONTROL(valor:byte):boolean;
begin
SO_T2_CONTROL:=((valor and $1c)=$14);
end;
constructor via6522_chip.create(clock:dword);
begin
self.clock:=clock;
self.in_a_handler:=nil;
self.in_b_handler:=nil;
self.out_a_handler:=nil;
self.out_b_handler:=nil;
self.irq_handler:=nil;
self.ca2_handler:=nil;
self.cb2_handler:=nil;
end;
destructor via6522_chip.free;
begin
end;
procedure via6522_chip.reset;
begin
self.out_a:=0;
self.out_ca2:=1;
self.ddr_a:=0;
self.latch_a:=0;
self.out_b:=0;
self.out_cb1:=1;
self.out_cb2:=1;
self.ddr_b:=0;
self.latch_b:=0;
self.t1cl:=0;
self.t1ch:=0;
self.t2cl:=0;
self.t2ch:=0;
self.pcr:=0;
self.acr:=0;
self.ier:=0;
self.ifr:=0;
self.t1_active:=0;
self.t1_pb7:=1;
self.t2_active:=0;
self.in_cb1:=false;
self.shift_counter:=0;
self.in_cb2:=0;
shift_irq_contador:=0;
time1:=sdl_getticks;
time2:=sdl_getticks;
self.t1ll:=$f3; // via at 0x9110 in vic20 show these values
self.t1lh:=$b5; // ports are not written by kernel!
self.t2ll:=$ff; // taken from vice
self.t2lh:=$ff;
self.output_pa;
self.output_pb;
if @self.ca2_handler<>nil then self.ca2_handler(out_ca2);
if @self.cb1_handler<>nil then self.cb1_handler(out_cb1);
if @self.cb2_handler<>nil then self.cb2_handler(out_cb2);
shift_timer:=false;
end;
procedure via6522_chip.change_calls(in_a,in_b:tin_handler;out_a,out_b,irq_set,ca2_set,cb2_set:tout_handler);
begin
self.in_a_handler:=in_a;
self.in_b_handler:=in_b;
self.out_a_handler:=out_a;
self.out_b_handler:=out_b;
self.irq_handler:=irq_set;
self.ca2_handler:=ca2_set;
self.cb2_handler:=cb2_set;
end;
procedure via6522_chip.update_timers(estados:word);
begin
if (self.t1_active<>0) then begin
self.t1_contador:=self.t1_contador-estados;
if self.t1_contador<=0 then begin //t1_tick
if T1_CONTINUOUS(self.acr) then begin
self.t1_pb7:=not(self.t1_pb7) and 1;
t1_contador:=t1_contador+self.t1ll+(self.t1lh shl 8)+IFR_DELAY;
end else begin
self.t1_pb7:=1;
self.t1_active:=0;
time1:=SDL_GetTicks;
end;
if T1_SET_PB7(self.acr) then self.output_pb;
self.set_int(INT_T1);
end;
end;
if (self.t2_active<>0) then begin
self.t2_contador:=self.t2_contador-estados;
if self.t2_contador<=0 then begin //t2_tick
self.t2_active:=0;
time2:=SDL_GetTicks;
self.set_int(INT_T2);
end;
end;
if shift_irq_enabled then begin
self.shift_irq_contador:=self.shift_irq_contador-estados;
if self.shift_irq_contador<=0 then begin
shift_irq_enabled:=false;
self.set_int(INT_SR); // triggered from shift_in or shift_out on the last rising edge
end;
end;
end;
procedure via6522_chip.set_pb_line(line:byte;state:boolean);
begin
if state then
self.in_b:=self.in_b or (1 shl line)
else begin
if ((line=6) and ((self.in_b and $40)<>0)) then counter2_decrement;
self.in_b:=self.in_b and not(1 shl line);
end;
end;
procedure via6522_chip.output_pa;
var
res:byte;
begin
res:=(self.out_a and self.ddr_a) or not(self.ddr_a);
if @self.out_a_handler<>nil then self.out_a_handler(res);
end;
procedure via6522_chip.write_pa(valor:byte);
begin
self.in_a:=valor;
end;
procedure via6522_chip.shift_in;
begin
// Only shift in data on raising edge
if ((self.shift_counter and 1)=0) then begin
self.sr:=(self.sr shl 1) or (self.in_cb2 and 1);
if ((self.shift_counter=0) and not(SR_DISABLED(self.acr))) then begin
self.shift_irq_contador:=2; // Delay IRQ 2 edges for all shift INs (mode 1-3)
self.shift_irq_enabled:=true;
end;
end;
self.shift_counter:=(self.shift_counter-1) and $0f; // Count all edges
end;
procedure via6522_chip.write_cb1(state:boolean);
begin
if (self.in_cb1<>state) then begin
self.in_cb1:=state;
if ((self.in_cb1 and CB1_LOW_TO_HIGH(self.pcr)) or (not(self.in_cb1) and CB1_HIGH_TO_LOW(self.pcr))) then begin
if (PB_LATCH_ENABLE(self.acr)) then self.latch_b:=self.input_pb;
self.set_int(INT_CB1);
if ((self.out_cb2=0) and CB2_AUTO_HS(self.pcr)) then begin
self.out_cb2:=1;
self.cb2_handler(1);
end;
end;
// The shifter shift is not controlled by PCR
if (SO_EXT_CONTROL(self.acr)) then MessageDlg('shift_out', mtInformation,[mbOk], 0) //shift_out
else if (SI_EXT_CONTROL(self.acr) or SR_DISABLED(self.acr)) then self.shift_in;
end;
end;
function via6522_chip.input_pa:byte;
var
res:byte;
begin
// HACK: port a in the real 6522 does not mask off the output pins, but you can't trust handlers.
if (@self.in_a_handler<>nil) then res:=(self.in_a and not(self.ddr_a) and self.in_a_handler) or (self.out_a and self.ddr_a)
else res:=(self.out_a or not(self.ddr_a)) and self.in_a;
input_pa:=res;
end;
function via6522_chip.input_pb:byte;
var
pb:byte;
begin
pb:=self.in_b and not(self.ddr_b);
if ((self.ddr_b<>$ff) and (@self.in_b_handler<>nil)) then pb:=pb and self.in_b_handler;
pb:=pb or (self.out_b and self.ddr_b);
if T1_SET_PB7(self.acr) then pb:=(pb and $7f) or ((self.t1_pb7 and 1) shl 7);
input_pb:=pb;
end;
procedure via6522_chip.output_pb;
var
res:byte;
begin
res:=(self.out_b and self.ddr_b) or not(self.ddr_b);
if T1_SET_PB7(self.acr) then res:=(res and $7f) or ((self.t1_pb7 and 1) shl 7);
if @self.out_b_handler<>nil then self.out_b_handler(res);
end;
procedure via6522_chip.clr_pa_int;
begin
if not(CA2_IND_IRQ(self.pcr)) then self.clear_int(INT_CA1 or INT_CA2)
else self.clear_int(INT_CA1)
end;
procedure via6522_chip.clr_pb_int;
begin
if not(CB2_IND_IRQ(self.pcr)) then self.clear_int(INT_CB1 or INT_CB2)
else self.clear_int(INT_CB1)
end;
procedure via6522_chip.set_int(valor:byte);
begin
if ((self.ifr and valor)=0) then begin
self.ifr:=self.ifr or valor;
self.output_irq;
end;
end;
procedure via6522_chip.clear_int(valor:byte);
begin
if (self.ifr and valor)<>0 then begin
self.ifr:=self.ifr and not(valor);
self.output_irq;
end;
end;
procedure via6522_chip.output_irq;
begin
if (self.ier and self.ifr and $7f)<>0 then begin
if (self.ifr and INT_ANY)=0 then begin
self.ifr:=self.ifr or INT_ANY;
self.irq_handler(ASSERT_LINE);
end;
end else begin
if (self.ifr and INT_ANY)<>0 then begin
self.ifr:=self.ifr and not(INT_ANY);
self.irq_handler(CLEAR_LINE);
end;
end;
end;
procedure via6522_chip.counter2_decrement;
begin
if not(T2_COUNT_PB6(self.acr)) then exit;
// count down on T2CL
self.t2cl:=self.t2cl-1;
if (self.t2cl<>0) then exit;
// borrow from T2CH
self.t2ch:=self.t2ch-1;
if (self.t2ch<>0) then exit;
// underflow causes only one interrupt between T2CH writes
if (self.t2_active)<>0 then begin
self.t2_active:=0;
self.set_int(INT_T2);
end;
end;
function via6522_chip.read(direccion:byte):byte;
var
res:byte;
tdword:dword;
begin
res:=0;
direccion:=direccion and $f;
case direccion of
VIA_PB:begin // update the input
if not(PB_LATCH_ENABLE(self.acr)) then res:=self.input_pb
else res:=self.latch_b;
self.CLR_PB_INT;
end;
VIA_PA:begin // update the input
if not(PA_LATCH_ENABLE(self.acr)) then res:=self.input_pa
else res:=self.latch_a;
self.CLR_PA_INT;
if ((self.out_ca2<>0) and (CA2_PULSE_OUTPUT(self.pcr) or CA2_AUTO_HS(self.pcr))) then begin
self.out_ca2:=0;
if @self.ca2_handler<>nil then self.ca2_handler(self.out_ca2);
end;
if (CA2_PULSE_OUTPUT(self.pcr)) then MessageDlg('Mierda timer VIA_PA R', mtInformation,[mbOk], 0);//m_ca2_timer->adjust(clocks_to_attotime(1));
end;
VIA_DDRB:res:=self.ddr_b;
VIA_DDRA:res:=self.ddr_a;
VIA_T1CL:begin
clear_int(INT_T1);
res:=get_counter1_value and $ff;
end;
VIA_T1CH:res:=get_counter1_value shr 8;
VIA_T1LL:res:=self.t1ll;
VIA_T1LH:res:=self.t1lh;
VIA_T2CL:begin
clear_int(INT_T2);
if ((self.t2_active<>0) and (self.t2_contador>0)) then begin
res:=self.t2_contador and $ff
end else begin
if T2_COUNT_PB6(self.acr) then res:=self.t2cl
else begin
tdword:=SDL_GetTicks;
res:=((($10000-(tdword-time2)) and $ffff)-1) and $ff;
end;
end;
end;
VIA_T2CH:if ((self.t2_active<>0) and (self.t2_contador>0)) then begin
res:=t2_contador shr 8;
end else begin
if (T2_COUNT_PB6(self.acr)) then res:=self.t2ch
else res:=((($10000-(SDL_GetTicks-time2)) and $ffff)-1) shr 8;
end;
VIA_SR:begin
res:=self.sr;
if (not(SI_EXT_CONTROL(self.acr) or SO_EXT_CONTROL(self.acr))) then begin
self.out_cb1:=1;
if @self.cb1_handler<>nil then self.cb1_handler(self.out_cb1);
self.shift_counter:=$0f;
end else if self.in_cb1 then self.shift_counter:=$0f
else self.shift_counter:=$10;
self.clear_int(INT_SR);
if (SI_O2_CONTROL(self.acr) or SO_O2_CONTROL(self.acr)) then MessageDlg('Mierda timer VIA_SR R', mtInformation,[mbOk], 0)//m_shift_timer->adjust(clocks_to_attotime(6) / 2); // 6 edges to cb2 change from start of write
else if (SI_T2_CONTROL(self.acr) or SO_T2_CONTROL(self.acr)) then MessageDlg('Mierda timer VIA_SR R2', mtInformation,[mbOk], 0) //m_shift_timer->adjust(clocks_to_attotime(m_t2ll + 2) / 2);
else if not(SO_T2_RATE(self.acr)) then ;//MessageDlg('Mierda timer VIA_SR W3', mtInformation,[mbOk], 0);//m_shift_timer->adjust(attotime::never); // In case we change mode before counter expire}
end;
VIA_ACR:res:=self.acr;
VIA_PCR:res:=self.pcr;
VIA_IER:res:=self.ier or $80;
VIA_IFR:res:=self.ifr;
VIA_PANH:if (not(PA_LATCH_ENABLE(self.acr))) then res:=input_pa
else res:=self.latch_a;
else MessageDlg('Read: '+inttohex(direccion,2), mtInformation,[mbOk], 0);
end;
read:=res;
end;
function via6522_chip.get_counter1_value:word;
var
val:word;
begin
if (self.t1_active<>0) then val:=t1_contador-IFR_DELAY
else val:=$ffff-((SDL_GetTicks-time1)*1000);
get_counter1_value:=val;
end;
procedure via6522_chip.write(direccion,valor:byte);
var
tword:word;
begin
direccion:=direccion and $f;
case direccion of
VIA_PB:begin
self.out_b:=valor;
if (self.ddr_b<>0) then self.output_pb;
self.CLR_PB_INT;
if ((self.out_cb2<>0) and (CB2_PULSE_OUTPUT(self.pcr) or (CB2_AUTO_HS(self.pcr)))) then begin
self.out_cb2:=0;
self.cb2_handler(self.out_cb2);
end;
if CB2_PULSE_OUTPUT(self.pcr) then MessageDlg('Mierda timer VIA_PB W', mtInformation,[mbOk], 0);//self.cb2_timer->adjust(clocks_to_attotime(1));
end;
VIA_PA:begin
self.out_a:=valor;
if (self.ddr_a<>0) then self.output_pa;
self.CLR_PA_INT;
if ((self.out_ca2<>0) and (CA2_PULSE_OUTPUT(self.pcr) or CA2_AUTO_HS(self.pcr))) then begin
self.out_ca2:=0;
if @self.ca2_handler<>nil then self.ca2_handler(self.out_ca2);
end;
if (CA2_PULSE_OUTPUT(self.pcr)) then MessageDlg('Mierda timer VIA_PA W', mtInformation,[mbOk], 0);//m_ca2_timer->adjust(clocks_to_attotime(1));
end;
VIA_DDRB:if (valor<>self.ddr_b) then begin
self.ddr_b:=valor;
self.output_pb;
end;
VIA_DDRA:if (self.ddr_a<>valor) then begin
self.ddr_a:=valor;
self.output_pa;
end;
VIA_T1CL,VIA_T1LL:self.t1ll:=valor;
VIA_T1CH:begin
self.t1ch:=valor;
self.t1lh:=valor;
self.t1cl:=self.t1ll;
self.clear_int(INT_T1);
self.t1_pb7:=0;
if T1_SET_PB7(self.acr) then self.output_pb;
t1_contador:=(self.t1ll+(self.t1lh shl 8)+IFR_DELAY);
self.t1_active:=1;
end;
VIA_T1LH:begin
self.t1lh:=valor;
self.clear_int(INT_T1);
end;
VIA_T2CL:self.t2ll:=valor;
VIA_T2CH:begin
self.t2ch:=valor;
self.t2lh:=valor;
self.t2cl:=self.t2ll;
self.clear_int(INT_T2);
if not(T2_COUNT_PB6(self.acr)) then begin
t2_contador:=self.t2ll+(self.t2lh shl 8)+IFR_DELAY;
self.t2_active:=1;
end else begin
self.t2_active:=1;
time2:=SDL_GetTicks;
end;
end;
VIA_SR:begin
self.sr:=valor;
if (not(SI_EXT_CONTROL(self.acr) or SO_EXT_CONTROL(self.acr))) then begin
self.out_cb1:=1;
if @self.cb1_handler<>nil then self.cb1_handler(self.out_cb1);
self.shift_counter:=$0f;
end else if self.in_cb1 then self.shift_counter:=$0f
else self.shift_counter:=$10;
self.clear_int(INT_SR);
if (SO_O2_CONTROL(self.acr) or SI_O2_CONTROL(self.acr)) then MessageDlg('Mierda timer VIA_SR W', mtInformation,[mbOk], 0)//m_shift_timer->adjust(clocks_to_attotime(6) / 2); // 6 edges to cb2 change from start of write
else if (SO_T2_RATE(self.acr) or SO_T2_CONTROL(self.acr) or SI_T2_CONTROL(self.acr)) then MessageDlg('Mierda timer VIA_SR W2', mtInformation,[mbOk], 0) //m_shift_timer->adjust(clocks_to_attotime(m_t2ll + 2) / 2);
else ;//MessageDlg('Mierda timer VIA_SR W3', mtInformation,[mbOk], 0);//m_shift_timer->adjust(attotime::never); // In case we change mode before counter expire
end;
VIA_ACR:begin
tword:=get_counter1_value;
self.acr:=valor;
self.output_pb;
if (SR_DISABLED(self.acr) or SI_EXT_CONTROL(self.acr) or SO_EXT_CONTROL(self.acr)) then shift_timer:=false;
if (T1_CONTINUOUS(self.acr)) then begin
t1_contador:=tword+IFR_DELAY;
self.t1_active:=1;
end;
if (SI_T2_CONTROL(self.acr) or SI_O2_CONTROL(self.acr) or SI_EXT_CONTROL(self.acr)) then begin
self.out_cb2:=1;
self.cb2_handler(self.out_cb2);
end;
end;
VIA_PCR:begin
self.pcr:=valor;
if (CA2_FIX_OUTPUT(valor) and (self.out_ca2<>CA2_OUTPUT_LEVEL(valor))) then begin
self.out_ca2:=CA2_OUTPUT_LEVEL(valor);
if @self.ca2_handler<>nil then self.ca2_handler(self.out_ca2);
end;
if (CB2_FIX_OUTPUT(valor) and (self.out_cb2<>CB2_OUTPUT_LEVEL(valor))) then begin
self.out_cb2:=CB2_OUTPUT_LEVEL(valor);
if @self.cb2_handler<>nil then self.cb2_handler(self.out_cb2);
end;
end;
VIA_IFR:begin
if (valor and INT_ANY)<>0 then valor:=$7f;
self.clear_int(valor);
end;
VIA_IER:begin
if (valor and $80)<>0 then self.ier:=self.ier or (valor and $7f)
else self.ier:=self.ier and not(valor and $7f);
self.output_irq;
end;
VIA_PANH:begin
self.out_a:=valor;
if (self.ddr_a<>0) then self.output_pa;
end;
else MessageDlg('Write: '+inttohex(direccion,2), mtInformation,[mbOk], 0);
end;
end;
end.
|
unit uCategoriaVO;
interface
uses
System.SysUtils, uTableName, uKeyField;
type
TCategoriaVO = class
private
FAtivo: Boolean;
FCodigo: Integer;
FId: Integer;
FNome: string;
procedure SetAtivo(const Value: Boolean);
procedure SetCodigo(const Value: Integer);
procedure SetId(const Value: Integer);
procedure SetNome(const Value: string);
public
property Id: Integer read FId write SetId;
property Codigo: Integer read FCodigo write SetCodigo;
property Nome: string read FNome write SetNome;
property Ativo: Boolean read FAtivo write SetAtivo;
end;
implementation
{ TCategoriaVO }
procedure TCategoriaVO.SetAtivo(const Value: Boolean);
begin
FAtivo := Value;
end;
procedure TCategoriaVO.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TCategoriaVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TCategoriaVO.SetNome(const Value: string);
begin
FNome := Value;
end;
end.
|
program VokaleundKonsonanten (input, output);
{ bestimmt in einem einzulesenden Satz die Anzahl der vorkommenden Vokale und Konsonanten }
type
tBuchst = 'a'..'z';
tNatZahl = 0..maxint; { maxint ist ein definierter Wert von Pascal und entspricht den maximalen Wert, den ein Integer annehmen kann }
tHaeufigkeit = array [tBuchst] of tNatZahl;
var
Anzahl : tHaeufigkeit;
Zeichen : char;
Gesamtzahl,
Vokalzahl,
KonsonantenZahl : tNatZahl;
begin
{ Initialisierung der Zaehler }
for Zeichen := 'a' to 'z' do
Anzahl[Zeichen] := 0;
Gesamtzahl := 0;
{ Zeichenweises Einlesen des Textes und Aufaddieren der Zaehler }
writeln ('Geben Sie bitte einen Text ein');
while Zeichen <> '.' do { solange Zeichen ungleich . mache }
begin
if (Zeichen >= 'a') and (Zeichen <= 'z') then
begin
Anzahl[Zeichen] := Anzahl[Zeichen] + 1;
Gesamtzahl := Gesamtzahl +1
end; { if }
read (Zeichen)
end; { while-Schleife }
writeln; { Ausgabe des eingelesenen Textes }
{ Ausgabe der Statistik }
Vokalzahl := Anzahl['a'] + Anzahl['e'] + Anzahl['i'] + Anzahl['o'] + Anzahl['u'];
KonsonantenZahl := Gesamtzahl - Vokalzahl;
writeln ('Anzahl der Vokale: ', Vokalzahl, '.');
writeln ('Anzahl der Konsonanten: ', KonsonantenZahl, '.');
end.
|
unit RemoteConnector;
interface
uses
Forms, SysUtils, Classes, WideStrings,
CommunicationTypes, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient;
type
TdmRemoteConnector = class(TDataModule)
IdTCPClient1: TIdTCPClient;
private
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ExecuteRemoteFunction(aRemoteObjects: TObjectStructList; const aRemoteFunction: string; aArgs: TVariantList; const aTimeout: integer = 0): TVariantList;
procedure ExecuteRemoteFunction_Async(const aRemoteObjectTree: TObjectStructList; const aRemoteFunction: UnicodeString; const aArguments: TVariantList);
procedure PostRemoteMessage(const aRemoteObjectTree: TObjectStructList; const aMessage: Integer; const aWParam: Integer; const aLParam: Integer);
function RemoteControlExists(const aRemoteObjectTree: TObjectStructList; const aTimeout: integer = 0): Boolean;
end;
ERemoteException = class(Exception);
var
dmRemoteConnector: TdmRemoteConnector;
implementation
uses
XMLFile;
{$R *.dfm}
constructor TdmRemoteConnector.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TdmRemoteConnector.Destroy;
begin
inherited;
end;
function TdmRemoteConnector.ExecuteRemoteFunction(
aRemoteObjects: TObjectStructList; const aRemoteFunction: string;
aArgs: TVariantList; const aTimeout: integer = 0): TVariantList;
var
call: TRemoteCall;
iSize: Integer;
sXML: string;
begin
call := TRemoteCall.Create;
try
call.FunctionName := 'ExecuteRemoteFunction';
call.RemoteFunction := aRemoteFunction;
call.ObjectList := aRemoteObjects;
call.Arguments := aArgs;
call.Timeout := aTimeout;
sXML := XMLFile.SaveToString(call);
//send
IdTCPClient1.IOHandler.Write(Length(sXML));
IdTCPClient1.IOHandler.Write(sXML);
//receive
iSize := IdTCPClient1.IOHandler.ReadLongInt;
sXML := IdTCPClient1.IOHandler.ReadString(iSize);
XMLFile.LoadFromString(sXML, call);
if call.ExceptionMsg <> '' then
raise ERemoteException.CreateFmt('Remote exception occured:'#13 + '%s: %s',
[call.ExceptionClass, call.ExceptionMsg]);
Result := TVariantList.Create;
XMLFile.LoadFromString(XMLFile.SaveToString(call.Results), Result );
finally
call.Free;
end;
end;
procedure TdmRemoteConnector.ExecuteRemoteFunction_Async(
const aRemoteObjectTree: TObjectStructList;
const aRemoteFunction: UnicodeString; const aArguments: TVariantList);
var
call: TRemoteCall;
iSize: Integer;
sXML: string;
begin
call := TRemoteCall.Create;
try
call.FunctionName := 'ExecuteRemoteFunction_Async';
call.RemoteFunction := aRemoteFunction;
call.ObjectList := aRemoteObjectTree;
call.Arguments := aArguments;
sXML := XMLFile.SaveToString(call);
//send
IdTCPClient1.IOHandler.Write(Length(sXML));
IdTCPClient1.IOHandler.Write(sXML);
//receive
iSize := IdTCPClient1.IOHandler.ReadLongInt;
sXML := IdTCPClient1.IOHandler.ReadString(iSize);
XMLFile.LoadFromString(sXML, call);
if call.ExceptionMsg <> '' then
raise ERemoteException.CreateFmt('Remote exception occured:'#13 + '%s: %s',
[call.ExceptionClass, call.ExceptionMsg]);
finally
call.Free;
end;
end;
procedure TdmRemoteConnector.PostRemoteMessage(
const aRemoteObjectTree: TObjectStructList; const aMessage, aWParam,
aLParam: Integer);
var
call: TRemoteCall;
iSize: Integer;
sXML: string;
begin
call := TRemoteCall.Create;
try
call.FunctionName := 'PostRemoteMessage';
//call.RemoteFunction := aRemoteFunction;
call.ObjectList := aRemoteObjectTree;
//call.Arguments := aArguments;
call.WndMessage := aMessage;
call.MsgWParam := aWParam;
call.MsgLParam := aLParam;
sXML := XMLFile.SaveToString(call);
//send
IdTCPClient1.IOHandler.Write(Length(sXML));
IdTCPClient1.IOHandler.Write(sXML);
//receive
iSize := IdTCPClient1.IOHandler.ReadLongInt;
sXML := IdTCPClient1.IOHandler.ReadString(iSize);
XMLFile.LoadFromString(sXML, call);
if call.ExceptionMsg <> '' then
raise ERemoteException.CreateFmt('Remote exception occured:'#13 + '%s: %s',
[call.ExceptionClass, call.ExceptionMsg]);
finally
call.Free;
end;
end;
function TdmRemoteConnector.RemoteControlExists(
const aRemoteObjectTree: TObjectStructList; const aTimeout: integer = 0): Boolean;
var
call: TRemoteCall;
iSize: Integer;
sXML: string;
begin
call := TRemoteCall.Create;
try
call.FunctionName := 'RemoteControlExists';
//call.RemoteFunction := aRemoteFunction;
call.ObjectList := aRemoteObjectTree;
//call.Arguments := aArguments;
call.Timeout := aTimeout;
sXML := XMLFile.SaveToString(call);
//send
IdTCPClient1.IOHandler.Write(Length(sXML));
IdTCPClient1.IOHandler.Write(sXML);
//receive
iSize := IdTCPClient1.IOHandler.ReadLongInt;
sXML := IdTCPClient1.IOHandler.ReadString(iSize);
XMLFile.LoadFromString(sXML, call);
if call.ExceptionMsg <> '' then
raise ERemoteException.CreateFmt('Remote exception occured:'#13 + '%s: %s',
[call.ExceptionClass, call.ExceptionMsg]);
Result := call.Exists;
finally
call.Free;
end;
end;
initialization
dmRemoteConnector := TdmRemoteConnector.Create(Application);
//finalization
// FreeAndNil(dmRemoteConnector);
end.
|
unit Control.Devolucao;
interface
uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Model.Devolucao, TFO.Barras, System.StrUtils;
type
TDevolucaoControl = class
private
FDevolucao : TDevolucao;
FBarras: TBarrTFO;
public
constructor Create;
destructor Destroy; override;
function Gravar: Boolean;
function Localizar(aParam: array of variant): TFDQuery;
function GetId(): Integer;
function ValidaImportacao(): Boolean;
function ValidaEdicao(): Boolean;
function ValidaExclusao(): Boolean;
property Devolucao: TDevolucao read FDevolucao write FDevolucao;
end;
implementation
{ TDevolucaoControl }
constructor TDevolucaoControl.Create;
begin
FDevolucao := TDevolucao.Create;
end;
destructor TDevolucaoControl.Destroy;
begin
FDevolucao.Free;
inherited;
end;
function TDevolucaoControl.GetId: Integer;
begin
Result := FDevolucao.GetID;
end;
function TDevolucaoControl.Gravar: Boolean;
begin
Result := FDevolucao.Gravar;
end;
function TDevolucaoControl.Localizar(aParam: array of variant): TFDQuery;
begin
Result := FDevolucao.Localizar(aParam);
end;
function TDevolucaoControl.ValidaEdicao: Boolean;
var
sNN: String;
sDV: String;
begin
try
Result := False;
sNN := '';
sDV := '';
FBarras := TbarrTFO.Create;
if FDevolucao.Agente = 0 then
begin
Application.MessageBox('Informe a Base!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FDevolucao.Expedicao = StrToDate('30/12/1899') then
begin
Application.MessageBox('Informe uma data de expectativa válida!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FDevolucao.NossoNumero.IsEmpty then
begin
Application.MessageBox('Informe o nosso número!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FDevolucao.Descricao.IsEmpty then
begin
Application.MessageBox('A descrição da devolução!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
sNN := LeftStr(FDevolucao.NossoNumero,10);
sDV := RightStr(FDevolucao.NossoNumero, 1);
if sDV <> FBarras.RetDV(sNN) then
begin
Application.MessageBox('Nosso Número informado é inválido!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
Result := True;
finally
FBarras.Free;
end;
end;
function TDevolucaoControl.ValidaExclusao: Boolean;
begin
Result := False;
if FDevolucao.StatusContainer <> 0 then
begin
Application.MessageBox('COntainer já foi processado!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FDevolucao.Statusobjeto <> 0 then
begin
Application.MessageBox('Objeto não está mais em expectativa!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
Result := True;
end;
function TDevolucaoControl.ValidaImportacao: Boolean;
begin
Result := False;
if FDevolucao.Expedicao = StrToDate('30/12/1899') then
begin
Application.MessageBox('Informe uma data de expectativa válida!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
Result := True;
end;
end.
|
unit evImageIndexProperty;
{ Библиотека "Эверест" }
{ Начал: Люлин А.В. }
{ Модуль: evImageIndexProperty - }
{ Начат: 06.03.2007 12:44 }
{ $Id: evImageIndexProperty.pas,v 1.1 2007/03/06 11:59:05 lulin Exp $ }
// $Log: evImageIndexProperty.pas,v $
// Revision 1.1 2007/03/06 11:59:05 lulin
// - сделана возможность выбирать иконки из списка, а не задавать только руками.
//
interface
uses
DesignEditors,
DesignIntf,
Classes,
ImgList,
VCLEditors,
Graphics,
Types
;
type
{ TevImageIndexProperty
Абстракный редактор свойства TImageIndex для классов:
- TstState;
- TStateTree;
- TstEmptyState; }
TevImageIndexProperty = class(TIntegerProperty, ICustomPropertyDrawing,
ICustomPropertyListDrawing)
protected
function GetImages : TCustomImageList; virtual; abstract;
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
{ ICustomPropertyListDrawing }
procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas;
var AHeight: Integer);
procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas;
var AWidth: Integer);
procedure ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
{ CustomPropertyDrawing }
procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
end;//TevImageIndexProperty
implementation
uses
SysUtils,
Math
;
{ TstImageIndex }
function TevImageIndexProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
Include(Result, paValueList);
end;
procedure TevImageIndexProperty.GetValues(Proc: TGetStrProc);
var
l_Index : Integer;
l_Images : TCustomImageList;
begin
l_Images := GetImages;
{ Иконы пока не установлены }
if Assigned(l_Images) then
for l_Index := -1 to Pred(l_Images.Count) do
Proc(IntToStr(l_Index))
{ "-1" единственное что можно установить }
else
Proc('-1');
end;
procedure TevImageIndexProperty.ListDrawValue(const Value: string;
ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean);
var
l_Right : Integer;
l_Index : Integer;
l_Images : TCustomImageList;
begin
l_Right := aRect.Left;
l_Images := GetImages;
if Assigned(l_Images) then begin
Inc(l_Right, l_Images.Width);
try
l_Index := StrToInt(Value);
except
l_Index := -1;
end;//try..except
aCanvas.FillRect(Rect(ARect.Left, ARect.Top, l_Right, aRect.Bottom));
if (l_Index >= 0) then begin
l_Images.Draw(aCanvas, aRect.Left, aRect.Top, l_Index);
end;//l_Index >= 0
end;//l_Images <> nil
DefaultPropertyListDrawValue(Value, ACanvas, Rect(l_Right, ARect.Top,
ARect.Right, ARect.Bottom), ASelected);
end;
procedure TevImageIndexProperty.ListMeasureHeight(const Value: string;
ACanvas: TCanvas; var AHeight: Integer);
var
l_Images : TCustomImageList;
begin
l_Images := GetImages;
if Assigned(l_Images) then
AHeight := Max(AHeight, l_Images.Height);
end;
procedure TevImageIndexProperty.ListMeasureWidth(const Value: string;
ACanvas: TCanvas; var AWidth: Integer);
var
l_Images : TCustomImageList;
begin
l_Images := GetImages;
if Assigned(l_Images) then
AWidth := l_Images.Width;
end;
procedure TevImageIndexProperty.PropDrawName(ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
begin
DefaultPropertyDrawName(Self, ACanvas, ARect);
end;
procedure TevImageIndexProperty.PropDrawValue(ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
begin
if GetVisualValue <> '' then
ListDrawValue(GetVisualValue, ACanvas, ARect, True)
else
DefaultPropertyDrawValue(Self, ACanvas, ARect);
end;
end.
|
unit uWorkSpaceMgr;
interface
uses
uWorkSpace, Classes, SysUtils, ComCtrls, uConstFile;
type
TWorkSpaceStatusRec = record
Opened: Boolean;
end;
TWorkSpaceMgr = class
private
FWorkSpaceList: array[0..cst_WokeSpace_MaxCount] of TWorkSpace;
FWorkSpaceStatusList: array[0..cst_WokeSpace_MaxCount] of TWorkSpaceStatusRec;
function DoNewWorkSpace(FileName: string): TWorkSpace; abstract;
protected
public
constructor Create;
destructor Destroy; override;
// 新建工作区
function NewWorkSpace(FileName: string): Integer;
end;
implementation
{ TWorkSpaceMgr }
constructor TWorkSpaceMgr.Create;
var
I: Integer;
begin
for I := Low to High do
begin
FWorkSpaceList[i] := nil;
FWorkSpaceStatusList[i].Opened := False;
end;
end;
destructor TWorkSpaceMgr.Destroy;
var
I: Integer;
begin
for I := Low[FWorkSpaceList] to High[FWorkSpaceList] do
begin
FWorkSpaceList[i].Free;
FWorkSpaceList[i] := nil;
FWorkSpaceStatusList[i].Opened := False;
end;
inherited;
end;
function TWorkSpaceMgr.NewWorkSpace(FileName: string): Integer;
var
WorkSpace: TWorkSpace;
I: Integer;
bCanCreate: Boolean;
begin
// WorkSpace :=
bCanCreate := False;
for I := Low(FWorkSpaceStatusList) to High(FWorkSpaceStatusList) do
begin
if FWorkSpaceStatusList[i].Opened = True then
Continue;
FWorkSpaceStatusList[i].Opened := True;
bCanCreate := True;
Break;
end;
WorkSpace := DoNewWorkSpace(FileName);
FWorkSpaceList[i] := WorkSpace;
end;
end.
|
unit Thread._201010_importar_pedidos_direct;
interface
uses
System.Classes, Dialogs, Windows, Forms, SysUtils, Messages, Controls, System.DateUtils, System.StrUtils, Generics.Collections,
Model.PlanilhaEntradaDIRECT, Control.Entregas, Control.PlanilhaEntradaDIRECT, Control.Sistema, FireDAC.Comp.Client, Common.ENum,
FireDAC.Comp.DataSet, Data.DB, Control.ControleAWB;
type
Tthread_201010_importar_pedidos_direct = class(TThread)
private
{ Private declarations }
FEntregas: TEntregasControl;
FPlanilha : TPlanilhaEntradaDIRECTControl;
FPlanilhasCSV : TObjectList<TPlanilhaEntradaDIRECT>;
FControleAWB: TControleAWBControl;
sMensagem: String;
FdPos: Double;
iLinha : Integer;
iPosition: Integer;
fdEntregas: TFDQuery;
fdEntregasInsert: TFDQuery;
fdEntregasUpdate: TFDQuery;
fdControleAWB: TFDQuery;
iCountInsert : Integer;
iCountUpdate : Integer;
iCountAWB: Integer;
protected
procedure Execute; override;
procedure UpdateLog;
procedure UpdateProgress;
procedure TerminateProcess;
procedure BeginProcesso;
procedure SetupClassUpdate(FDQuery: TFDQuery);
procedure SetupClassInsert(i: Integer);
procedure SetupQueryInsert();
procedure SetupQueryUpdate();
procedure SaveInsert(iCount: Integer);
procedure SaveUpdate(iCount: Integer);
procedure SaveAWB(iCount: Integer);
procedure SetupQueryAWB(sRemessa: String; sAWB1: String; sAWB2: String; sCEP: String; sOperacao: String; iTipo: Integer; dPeso: Double);
public
FFile: String;
iCodigoCliente: Integer;
bCancel : Boolean;
end;
const
TABLENAME = 'tbentregas';
SQLINSERT = 'INSERT INTO ' + TABLENAME +
'(NUM_NOSSONUMERO, COD_AGENTE, COD_ENTREGADOR, COD_CLIENTE, NUM_NF, NOM_CONSUMIDOR, DES_ENDERECO, DES_COMPLEMENTO, ' +
'DES_BAIRRO, NOM_CIDADE, NUM_CEP, NUM_TELEFONE, DAT_EXPEDICAO, DAT_PREV_DISTRIBUICAO, QTD_VOLUMES, DAT_ATRIBUICAO, ' +
'DAT_BAIXA, DOM_BAIXADO, DAT_PAGAMENTO, DOM_PAGO, DOM_FECHADO, COD_STATUS, DAT_ENTREGA, QTD_PESO_REAL, ' +
'QTD_PESO_FRANQUIA, VAL_VERBA_FRANQUIA, VAL_ADVALOREM, VAL_PAGO_FRANQUIA, VAL_VERBA_ENTREGADOR, NUM_EXTRATO, ' +
'QTD_DIAS_ATRASO, QTD_VOLUMES_EXTRA, VAL_VOLUMES_EXTRA, QTD_PESO_COBRADO, DES_TIPO_PESO, DAT_RECEBIDO, DOM_RECEBIDO, ' +
'NUM_CTRC, NUM_MANIFESTO, DES_RASTREIO, NUM_LOTE_REMESSA, DES_RETORNO, DAT_CREDITO, DOM_CREDITO, NUM_CONTAINER, ' +
'VAL_PRODUTO, QTD_ALTURA, QTD_LARGURA, QTD_COMPRIMENTO, COD_FEEDBACK, DAT_FEEDBACK, DOM_CONFERIDO, NUM_PEDIDO, ' +
'COD_CLIENTE_EMPRESA) ' +
'VALUES ' +
'(:NUM_NOSSONUMERO, :COD_AGENTE, :COD_ENTREGADOR, :COD_CLIENTE, :NUM_NF, :NOM_CONSUMIDOR, :DES_ENDERECO, ' +
':DES_COMPLEMENTO, :DES_BAIRRO, :NOM_CIDADE, :NUM_CEP, :NUM_TELEFONE, :DAT_EXPEDICAO, :DAT_PREV_DISTRIBUICAO, ' +
':QTD_VOLUMES, :DAT_ATRIBUICAO, :DAT_BAIXA, :DOM_BAIXADO, :DAT_PAGAMENTO, :DOM_PAGO, :DOM_FECHADO, :COD_STATUS, ' +
':DAT_ENTREGA, :QTD_PESO_REAL, :QTD_PESO_FRANQUIA, :VAL_VERBA_FRANQUIA, :VAL_ADVALOREM, :VAL_PAGO_FRANQUIA, ' +
':VAL_VERBA_ENTREGADOR, :NUM_EXTRATO, :QTD_DIAS_ATRASO, :QTD_VOLUMES_EXTRA, :VAL_VOLUMES_EXTRA, :QTD_PESO_COBRADO, ' +
':DES_TIPO_PESO, :DAT_RECEBIDO, :DOM_RECEBIDO, :NUM_CTRC, :NUM_MANIFESTO, :DES_RASTREIO, :NUM_LOTE_REMESSA, ' +
':DES_RETORNO, :DAT_CREDITO, :DOM_CREDITO, :NUM_CONTAINER, :VAL_PRODUTO, :QTD_ALTURA, :QTD_LARGURA, :QTD_COMPRIMENTO, ' +
':COD_FEEDBACK, :DAT_FEEDBACK, :DOM_CONFERIDO, :NUM_PEDIDO, :COD_CLIENTE_EMPRESA);';
SQLUPDATE = 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'COD_AGENTE = :COD_AGENTE, COD_ENTREGADOR = :COD_ENTREGADOR, ' +
'COD_CLIENTE = :COD_CLIENTE, NUM_NF = :NUM_NF, NOM_CONSUMIDOR = :NOM_CONSUMIDOR, DES_ENDERECO = :DES_ENDERECO, ' +
'DES_COMPLEMENTO = :DES_COMPLEMENTO, DES_BAIRRO = :DES_BAIRRO, NOM_CIDADE = :NOM_CIDADE, NUM_CEP = :NUM_CEP, ' +
'NUM_TELEFONE = :NUM_TELEFONE, DAT_EXPEDICAO = :DAT_EXPEDICAO, DAT_PREV_DISTRIBUICAO = :DAT_PREV_DISTRIBUICAO, ' +
'QTD_VOLUMES = :QTD_VOLUMES, DAT_ATRIBUICAO = :DAT_ATRIBUICAO, DAT_BAIXA = :DAT_BAIXA, DOM_BAIXADO = :DOM_BAIXADO, ' +
'DAT_PAGAMENTO = :DAT_PAGAMENTO, DOM_PAGO = :DOM_PAGO, DOM_FECHADO = :DOM_FECHADO, COD_STATUS = :COD_STATUS, ' +
'DAT_ENTREGA = :DAT_ENTREGA, QTD_PESO_REAL = :QTD_PESO_REAL, QTD_PESO_FRANQUIA = :QTD_PESO_FRANQUIA, ' +
'VAL_VERBA_FRANQUIA = :VAL_VERBA_FRANQUIA, VAL_ADVALOREM = :VAL_ADVALOREM, VAL_PAGO_FRANQUIA = :VAL_PAGO_FRANQUIA, ' +
'VAL_VERBA_ENTREGADOR = :VAL_VERBA_ENTREGADOR, NUM_EXTRATO = :NUM_EXTRATO, QTD_DIAS_ATRASO = :QTD_DIAS_ATRASO, ' +
'QTD_VOLUMES_EXTRA = :QTD_VOLUMES_EXTRA, VAL_VOLUMES_EXTRA = :VAL_VOLUMES_EXTRA, QTD_PESO_COBRADO = :QTD_PESO_COBRADO, ' +
'DES_TIPO_PESO = :DES_TIPO_PESO, DAT_RECEBIDO = :DAT_RECEBIDO, DOM_RECEBIDO = :DOM_RECEBIDO, NUM_CTRC = :NUM_CTRC, ' +
'NUM_MANIFESTO = :NUM_MANIFESTO, DES_RASTREIO = :DES_RASTREIO, NUM_LOTE_REMESSA = :NUM_LOTE_REMESSA, ' +
'DES_RETORNO = :DES_RETORNO, DAT_CREDITO = :DAT_CREDITO, DOM_CREDITO = :DOM_CREDITO, NUM_CONTAINER = :NUM_CONTAINER, ' +
'VAL_PRODUTO = :VAL_PRODUTO, QTD_ALTURA = :QTD_ALTURA, QTD_LARGURA = :QTD_LARGURA, QTD_COMPRIMENTO = :QTD_COMPRIMENTO, ' +
'COD_FEEDBACK = :COD_FEEDBACK, DAT_FEEDBACK = :DAT_FEEDBACK, DOM_CONFERIDO = :DOM_CONFERIDO, ' +
'NUM_PEDIDO = :NUM_PEDIDO, COD_CLIENTE_EMPRESA = :COD_CLIENTE_EMPRESA ' +
'WHERE ' +
'NUM_NOSSONUMERO = :NUM_NOSSONUMERO;';
SQLAWB = 'insert into expressas_controle_awb (id_awb, num_remessa, cod_awb1, cod_awb2, num_cep, cod_operacao, cod_tipo, qtd_peso)' +
'values ' +
'(:id_awb, :num_remessa, :cod_awb1, :cod_awb2, :num_cep, :cod_operacao, :cod_tipo, :qtd_peso);';
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure Tthread_201010_importar_pedidos_direct.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ Tthread_201010_importar_pedidos_direct }
uses Common.Utils, Global.Parametros, View.ImportarPedidos;
procedure Tthread_201010_importar_pedidos_direct.BeginProcesso;
begin
bCancel := False;
view_ImportarPedidos.actCancelar.Enabled := True;
view_ImportarPedidos.actFechar.Enabled := False;
view_ImportarPedidos.actImportar.Enabled := False;
view_ImportarPedidos.actAbrirArquivo.Enabled := False;
view_ImportarPedidos.dxLayoutItem8.Visible := True;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' iniciando importação do arquivo ' + FFile;
UpdateLog;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' tratando os dados da planilha. Aguarde...';
UpdateLog;
end;
procedure Tthread_201010_importar_pedidos_direct.Execute;
var
aParam: Array of variant;
iPos : Integer;
iTotal: Integer;
fdQuery: TFDQuery;
sCEP: String;
sOperacao: String;
dPeso: Double;
iTipo: Integer;
begin
{ Place thread code here }
try
try
Synchronize(BeginProcesso);
FEntregas := TEntregasControl.Create;
FPlanilha := TPlanilhaEntradaDIRECTControl.Create;
FControleAWB := TControleAWBControl.Create;
FPlanilhasCSV := TObjectList<TPlanilhaEntradaDIRECT>.Create;
Screen.Cursor := crHourGlass;
FPlanilhasCSV := FPlanilha.GetPlanilha(FFile);
Screen.Cursor := crDefault;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importando os dados. Aguarde...';
Synchronize(UpdateLog);
iCountInsert := 0;
iCountUpdate := 0;
iCountAWB := 0;
if FPlanilhasCSV.Count > 0 then
begin
iPos := 0;
FdPos := 0;
iTotal := FPlanilhasCSV.Count;
fdEntregas := TSistemaControl.GetInstance.Conexao.ReturnQuery;
fdEntregasInsert := TSistemaControl.GetInstance.Conexao.ReturnQuery;
fdEntregasUpdate := TSistemaControl.GetInstance.Conexao.ReturnQuery;
fdControleAWB := TSistemaControl.GetInstance.Conexao.ReturnQuery;
fdQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery;
fdEntregasInsert.SQL.Text := SQLINSERT;
fdEntregasUpdate.SQL.Text := SQLUPDATE;
fdControleAWB.SQL.Text := SQLAWB;
for iPos := 0 to Pred(iTotal) do
begin
SetLength(aParam,2);
aParam[0] := 'NN';
aParam[1] := Trim(FPlanilhasCSV[iPos].Remessa);
fdEntregas := FEntregas.Localizar(aParam);
Finalize(aParam);
if fdEntregas.IsEmpty then
begin
SetupClassInsert(iPos);
Inc(iCountInsert);
FEntregas.Entregas.Status := 909;
FEntregas.Entregas.Rastreio := '> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importado por ' +
Global.Parametros.pUser_Name;
SetupQueryInsert;
end
else
begin
SetupClassUpdate(fdEntregas);
Inc(iCountUpdate);
FEntregas.Entregas.Status := 909;
FEntregas.Entregas.Rastreio := FEntregas.Entregas.Rastreio + #13 +
'> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' atualizado por importação por ' +
Global.Parametros.pUser_Name;
SetupQueryUpdate;
end;
fdEntregas.Close;
sOperacao := '';
dPeso := 0;
iTipo := 1;
if Pos('- TD -', FPlanilhasCSV[iPos].Operacao) > 0 then
begin
sOperacao := 'TD';
end
else
begin
iTipo := 2;
sOperacao := 'TC';
end;
if FPlanilhasCSV[iPos].PesoCubado > FPlanilhasCSV[iPos].PesoNominal then
begin
dPeso := FPlanilhasCSV[iPos].PesoCubado;
end
else
begin
dPeso := FPlanilhasCSV[iPos].PesoNominal;
end;
SetLength(aParam, 3);
aParam[0] := 'REMESSAAWB1';
aParam[1] := FPlanilhasCSV[iPos].Remessa;
aParam[2] := FPlanilhasCSV[iPos].AWB1;
fdQuery := FControleAWB.Localizar(aParam);
Finalize(aParam);
if fdQuery.IsEmpty then
begin
Inc(iCountAWB);
sCEP := ReplaceStr(FPlanilhasCSV[iPos].CEP,'-','');
SetupQueryAWB(FPlanilhasCSV[iPos].Remessa, FPlanilhasCSV[iPos].AWB1, FPlanilhasCSV[iPos].AWB2, sCEP, sOperacao, iTipo, dPeso);
end;
iPosition := iPos + 1;
FdPos := (iPosition / iTotal) * 100;
if not(Self.Terminated) then
begin
Synchronize(UpdateProgress);
end
else
begin
Abort;
end;
fdEntregas.Close;
end;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' salvando no banco de dados. Aguarde...';
Synchronize(UpdateLog);
Synchronize(procedure begin Screen.Cursor := crHourGlass end);
if iCountInsert > 0 then SaveInsert(iCountInsert);
if iCountUpdate > 0 then SaveUpdate(iCountUpdate);
if iCountAWB > 0 then SaveAWB(iCountAWB);
fdEntregasInsert.Connection.Close;
fdEntregasUpdate.Connection.Close;
fdControleAWB.Connection.Close;
fdEntregasInsert.Free;
fdEntregasUpdate.Free;
fdControleAWB.Free;
Synchronize(procedure begin Screen.Cursor := crDefault end);
end;
Except
on E: Exception do
begin
Application.MessageBox(PChar('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message), 'Erro', MB_OK + MB_ICONERROR);
bCancel := True;
end;
end;
finally
if bCancel then
begin
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importação cancelada ...';
Synchronize(UpdateLog);
Application.MessageBox('Importação cancelada!', 'Importação de Entregas', MB_OK + MB_ICONWARNING);
end
else
begin
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importação concluída com sucesso';
Synchronize(UpdateLog);
Application.MessageBox('Importação concluída com sucesso!', 'Importação de Entregas', MB_OK + MB_ICONINFORMATION);
end;
Synchronize(TerminateProcess);
FEntregas.Free;
FPlanilha.Free;
FPlanilhasCSV.Free;
FControleAWB.Free;
fdEntregas.Free;
end;
end;
procedure Tthread_201010_importar_pedidos_direct.SaveAWB(iCount: Integer);
begin
fdControleAWB.Execute(iCount,0);
end;
procedure Tthread_201010_importar_pedidos_direct.SaveInsert(iCount: Integer);
begin
fdEntregasInsert.Execute(iCount, 0);
end;
procedure Tthread_201010_importar_pedidos_direct.SaveUpdate(iCount: Integer);
begin
fdEntregasUpdate.Execute(iCount, 0);
end;
procedure Tthread_201010_importar_pedidos_direct.SetupClassInsert(i: Integer);
begin
FEntregas.Entregas.NN := FPlanilhasCSV[i].Remessa;
FEntregas.Entregas.Distribuidor := 0;
FEntregas.Entregas.Entregador := 0;
FEntregas.Entregas.Cliente := FPlanilhasCSV[i].CodigoEmbarcador;
FEntregas.Entregas.NF := FPlanilhasCSV[i].NF;
FEntregas.Entregas.Consumidor := FPlanilhasCSV[i].NomeConsumidor;
FEntregas.Entregas.Endereco := '';
FEntregas.Entregas.Complemento := '';
FEntregas.Entregas.Bairro := FPlanilhasCSV[i].Bairro;
FEntregas.Entregas.Cidade := FPlanilhasCSV[i].Municipio;
FEntregas.Entregas.Cep := FPlanilhasCSV[i].CEP;
FEntregas.Entregas.Telefone := '';
FEntregas.Entregas.Expedicao := FPlanilhasCSV[i].DataRegistro;
FEntregas.Entregas.Previsao := IncDay(FPlanilhasCSV[i].DataChegadaLM, 1);
FEntregas.Entregas.Volumes := FPlanilhasCSV[i].Volumes;
FEntregas.Entregas.Atribuicao := StrToDate('30/12/1899');
FEntregas.Entregas.Baixa := StrToDate('30/12/1899');
FEntregas.Entregas.Baixado := 'N';
FEntregas.Entregas.Pagamento := StrToDate('30/12/1899');
FEntregas.Entregas.Pago := 'N';
FEntregas.Entregas.Fechado := 'N';
FEntregas.Entregas.Status := 0;
FEntregas.Entregas.Entrega := StrToDate('30/12/1899');
if FPlanilhasCSV[i].PesoCubado > FPlanilhasCSV[i].PesoNominal then
begin
FEntregas.Entregas.PesoReal := FPlanilhasCSV[i].PesoCubado;
FEntregas.Entregas.TipoPeso := 'CUBADO';
end
else
begin
FEntregas.Entregas.PesoReal := FPlanilhasCSV[i].PesoNominal;
FEntregas.Entregas.TipoPeso := 'NOMINAL';
end;
FEntregas.Entregas.PesoFranquia := 0;
FEntregas.Entregas.Advalorem := 0;
FEntregas.Entregas.PagoFranquia := 0;
FEntregas.Entregas.VerbaEntregador := 0;
FEntregas.Entregas.Extrato := '0';
FEntregas.Entregas.Atraso := 0;
FEntregas.Entregas.VolumesExtra := 0;
FEntregas.Entregas.ValorVolumes := 0;
FEntregas.Entregas.PesoCobrado := FPlanilhasCSV[i].PesoNominal;
FEntregas.Entregas.Recebimento := StrToDate('30/12/1899');
FEntregas.Entregas.Recebido := 'N';
FEntregas.Entregas.CTRC := 0;
FEntregas.Entregas.Manifesto := 0;
FEntregas.Entregas.Rastreio := '';
FEntregas.Entregas.VerbaFranquia := 0;
FEntregas.Entregas.Lote := 0;
FEntregas.Entregas.Retorno := FPlanilhasCSV[i].Chave;
FEntregas.Entregas.Credito := StrToDate('30/12/1899');;
FEntregas.Entregas.Creditado := 'N';
FEntregas.Entregas.Container := '0';
FEntregas.Entregas.ValorProduto := FPlanilhasCSV[i].Valor;
FEntregas.Entregas.Altura := 0;
FEntregas.Entregas.Largura := 0;
FEntregas.Entregas.Comprimento := 0;
FEntregas.Entregas.CodigoFeedback := 0;
FEntregas.Entregas.DataFeedback := StrToDate('30/12/1899');
FEntregas.Entregas.Conferido := 0;
FEntregas.Entregas.Pedido := FPlanilhasCSV[i].Pedido;
FEntregas.Entregas.CodCliente := iCodigoCliente;
end;
procedure Tthread_201010_importar_pedidos_direct.SetupClassUpdate(FDQuery: TFDQuery);
begin
FEntregas.Entregas.NN := FDQuery.FieldByName('NUM_NOSSONUMERO').AsString;
FEntregas.Entregas.Distribuidor := FDQuery.FieldByName('COD_AGENTE').AsInteger;
FEntregas.Entregas.Entregador := FDQuery.FieldByName('COD_ENTREGADOR').AsInteger;
FEntregas.Entregas.Cliente := FDQuery.FieldByName('COD_CLIENTE').AsInteger;
FEntregas.Entregas.NF := FDQuery.FieldByName('NUM_NF').AsString;
FEntregas.Entregas.Consumidor := FDQuery.FieldByName('NOM_CONSUMIDOR').AsString;
FEntregas.Entregas.Endereco := FDQuery.FieldByName('DES_ENDERECO').AsString;
FEntregas.Entregas.Complemento := FDQuery.FieldByName('DES_COMPLEMENTO').AsString;
FEntregas.Entregas.Bairro := FDQuery.FieldByName('DES_BAIRRO').AsString;
FEntregas.Entregas.Cidade := FDQuery.FieldByName('NOM_CIDADE').AsString;
FEntregas.Entregas.Cep := FDQuery.FieldByName('NUM_CEP').AsString;
FEntregas.Entregas.Telefone := FDQuery.FieldByName('NUM_TELEFONE').AsString;
FEntregas.Entregas.Expedicao := FDQuery.FieldByName('DAT_EXPEDICAO').AsDateTime;
FEntregas.Entregas.Previsao := FDQuery.FieldByName('DAT_PREV_DISTRIBUICAO').AsDateTime;
FEntregas.Entregas.Volumes := FDQuery.FieldByName('QTD_VOLUMES').AsInteger;
FEntregas.Entregas.Atribuicao := FDQuery.FieldByName('DAT_ATRIBUICAO').AsDateTime;
FEntregas.Entregas.Baixa := FDQuery.FieldByName('DAT_BAIXA').AsDateTime;
FEntregas.Entregas.Baixado := FDQuery.FieldByName('DOM_BAIXADO').AsString;
FEntregas.Entregas.Pagamento := FDQuery.FieldByName('DAT_PAGAMENTO').AsDateTime;
FEntregas.Entregas.Pago := FDQuery.FieldByName('DOM_PAGO').AsString;
FEntregas.Entregas.Fechado := FDQuery.FieldByName('DOM_FECHADO').AsString;
FEntregas.Entregas.Status := FDQuery.FieldByName('COD_STATUS').AsInteger;
FEntregas.Entregas.Entrega := FDQuery.FieldByName('DAT_ENTREGA').AsDateTime;
FEntregas.Entregas.PesoReal := FDQuery.FieldByName('QTD_PESO_REAL').AsFloat;
FEntregas.Entregas.PesoFranquia := FDQuery.FieldByName('QTD_PESO_FRANQUIA').AsFloat;
FEntregas.Entregas.VerbaFranquia := FDQuery.FieldByName('VAL_VERBA_FRANQUIA').AsFloat;
FEntregas.Entregas.Advalorem := FDQuery.FieldByName('VAL_ADVALOREM').AsFloat;
FEntregas.Entregas.PagoFranquia := FDQuery.FieldByName('VAL_PAGO_FRANQUIA').AsFloat;
FEntregas.Entregas.VerbaEntregador := FDQuery.FieldByName('VAL_VERBA_ENTREGADOR').AsFloat;
FEntregas.Entregas.Extrato := FDQuery.FieldByName('NUM_EXTRATO').AsString;
FEntregas.Entregas.Atraso := FDQuery.FieldByName('QTD_DIAS_ATRASO').AsInteger;
FEntregas.Entregas.VolumesExtra := FDQuery.FieldByName('QTD_VOLUMES_EXTRA').AsFloat;
FEntregas.Entregas.ValorVolumes := FDQuery.FieldByName('VAL_VOLUMES_EXTRA').AsFloat;
FEntregas.Entregas.PesoCobrado := FDQuery.FieldByName('QTD_PESO_COBRADO').AsFloat;
FEntregas.Entregas.TipoPeso := FDQuery.FieldByName('DES_TIPO_PESO').AsString;
FEntregas.Entregas.Recebimento := FDQuery.FieldByName('DAT_RECEBIDO').AsDateTime;
FEntregas.Entregas.Recebido := FDQuery.FieldByName('DOM_RECEBIDO').AsString;
FEntregas.Entregas.CTRC := FDQuery.FieldByName('NUM_CTRC').AsInteger;
FEntregas.Entregas.Manifesto := FDQuery.FieldByName('NUM_MANIFESTO').AsInteger;
FEntregas.Entregas.Rastreio := FDQuery.FieldByName('DES_RASTREIO').AsString;
FEntregas.Entregas.VerbaFranquia := FDQuery.FieldByName('VAL_VERBA_FRANQUIA').AsFloat;
FEntregas.Entregas.Lote := FDQuery.FieldByName('NUM_LOTE_REMESSA').AsInteger;
FEntregas.Entregas.Retorno := FDQuery.FieldByName('DES_RETORNO').AsString;
FEntregas.Entregas.Credito := FDQuery.FieldByName('DAT_CREDITO').AsDateTime;
FEntregas.Entregas.Creditado := FDQuery.FieldByName('DOM_CREDITO').AsString;
FEntregas.Entregas.Container := FDQuery.FieldByName('NUM_CONTAINER').AsString;
FEntregas.Entregas.ValorProduto := FDQuery.FieldByName('VAL_PRODUTO').AsFloat;
FEntregas.Entregas.Altura := FDQuery.FieldByName('QTD_ALTURA').AsInteger;
FEntregas.Entregas.Largura := FDQuery.FieldByName('QTD_LARGURA').AsInteger;
FEntregas.Entregas.Comprimento := FDQuery.FieldByName('QTD_COMPRIMENTO').AsInteger;
FEntregas.Entregas.CodigoFeedback := FDQuery.FieldByName('COD_FEEDBACK').AsInteger;
FEntregas.Entregas.DataFeedback := FDQuery.FieldByName('DAT_FEEDBACK').AsDateTime;
FEntregas.Entregas.Conferido := FDQuery.FieldByName('DOM_CONFERIDO').AsInteger;
FEntregas.Entregas.Pedido := FDQuery.FieldByName('NUM_PEDIDO').AsString;
FEntregas.Entregas.CodCliente := FDQuery.FieldByName('COD_CLIENTE_EMPRESA').AsInteger;
end;
procedure Tthread_201010_importar_pedidos_direct.SetupQueryInsert;
begin
fdEntregasInsert.Params.ArraySize := iCountInsert;
fdEntregasInsert.ParamByName('NUM_NOSSONUMERO').AsStrings[Pred(iCountInsert)]:= FEntregas.Entregas.NN;
fdEntregasInsert.ParamByName('COD_AGENTE').AsIntegers[Pred(iCountInsert)]:= FEntregas.Entregas.Distribuidor;
fdEntregasInsert.ParamByName('COD_ENTREGADOR').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Entregador;
fdEntregasInsert.ParamByName('COD_CLIENTE').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Cliente;
fdEntregasInsert.ParamByName('NUM_NF').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.NF;
fdEntregasInsert.ParamByName('NOM_CONSUMIDOR').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Consumidor;
fdEntregasInsert.ParamByName('DES_ENDERECO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Endereco;
fdEntregasInsert.ParamByName('DES_COMPLEMENTO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Complemento;
fdEntregasInsert.ParamByName('DES_BAIRRO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Bairro;
fdEntregasInsert.ParamByName('NOM_CIDADE').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Cidade;
fdEntregasInsert.ParamByName('NUM_CEP').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Cep;
fdEntregasInsert.ParamByName('NUM_TELEFONE').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Telefone;
fdEntregasInsert.ParamByName('DAT_EXPEDICAO').AsDateTimes[Pred(iCountInsert)] := FEntregas.Entregas.Expedicao;
fdEntregasInsert.ParamByName('DAT_PREV_DISTRIBUICAO').AsDateTimes[Pred(iCountInsert)] := FEntregas.Entregas.Previsao;
fdEntregasInsert.ParamByName('QTD_VOLUMES').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Volumes;
fdEntregasInsert.ParamByName('DAT_ATRIBUICAO').AsDateTimes[Pred(iCountInsert)] := FEntregas.Entregas.Atribuicao;
fdEntregasInsert.ParamByName('DAT_BAIXA').AsDates[Pred(iCountInsert)] := FEntregas.Entregas.Baixa;
fdEntregasInsert.ParamByName('DOM_BAIXADO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Baixado;
fdEntregasInsert.ParamByName('DAT_PAGAMENTO').AsDates[Pred(iCountInsert)] := FEntregas.Entregas.Pagamento;
fdEntregasInsert.ParamByName('DOM_PAGO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Pago;
fdEntregasInsert.ParamByName('DOM_FECHADO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Fechado;
fdEntregasInsert.ParamByName('COD_STATUS').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Status;
fdEntregasInsert.ParamByName('DAT_ENTREGA').AsDates[Pred(iCountInsert)] := FEntregas.Entregas.Entrega;
fdEntregasInsert.ParamByName('QTD_PESO_REAL').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.PesoReal;
fdEntregasInsert.ParamByName('QTD_PESO_FRANQUIA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.PesoFranquia;
fdEntregasInsert.ParamByName('VAL_VERBA_FRANQUIA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.VerbaFranquia;
fdEntregasInsert.ParamByName('VAL_ADVALOREM').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.Advalorem;
fdEntregasInsert.ParamByName('VAL_PAGO_FRANQUIA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.PagoFranquia;
fdEntregasInsert.ParamByName('VAL_VERBA_ENTREGADOR').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.VerbaEntregador;
fdEntregasInsert.ParamByName('NUM_EXTRATO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Extrato;
fdEntregasInsert.ParamByName('QTD_DIAS_ATRASO').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Atraso;
fdEntregasInsert.ParamByName('QTD_VOLUMES_EXTRA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.VolumesExtra;
fdEntregasInsert.ParamByName('VAL_VOLUMES_EXTRA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.ValorVolumes;
fdEntregasInsert.ParamByName('QTD_PESO_COBRADO').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.PesoCobrado;
fdEntregasInsert.ParamByName('DES_TIPO_PESO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.TipoPeso;
fdEntregasInsert.ParamByName('DAT_RECEBIDO').AsDates[Pred(iCountInsert)] := FEntregas.Entregas.Recebimento;
fdEntregasInsert.ParamByName('DOM_RECEBIDO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Recebido;
fdEntregasInsert.ParamByName('NUM_CTRC').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.CTRC;
fdEntregasInsert.ParamByName('NUM_MANIFESTO').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Manifesto;
fdEntregasInsert.ParamByName('DES_RASTREIO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Rastreio;
fdEntregasInsert.ParamByName('VAL_VERBA_FRANQUIA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.VerbaFranquia;
fdEntregasInsert.ParamByName('NUM_LOTE_REMESSA').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Lote;
fdEntregasInsert.ParamByName('DES_RETORNO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Retorno;
fdEntregasInsert.ParamByName('DAT_CREDITO').AsDateTimes[Pred(iCountInsert)] := FEntregas.Entregas.Credito;
fdEntregasInsert.ParamByName('DOM_CREDITO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Creditado;
fdEntregasInsert.ParamByName('NUM_CONTAINER').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Container;
fdEntregasInsert.ParamByName('VAL_PRODUTO').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.ValorProduto;
fdEntregasInsert.ParamByName('QTD_ALTURA').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Altura;
fdEntregasInsert.ParamByName('QTD_LARGURA').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Largura;
fdEntregasInsert.ParamByName('QTD_COMPRIMENTO').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Comprimento;
fdEntregasInsert.ParamByName('COD_FEEDBACK').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.CodigoFeedback;
fdEntregasInsert.ParamByName('DAT_FEEDBACK').AsDateTimes[Pred(iCountInsert)] := FEntregas.Entregas.DataFeedback;
fdEntregasInsert.ParamByName('DOM_CONFERIDO').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Conferido;
fdEntregasInsert.ParamByName('NUM_PEDIDO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Pedido;
fdEntregasInsert.ParamByName('COD_CLIENTE_EMPRESA').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.CodCliente;
end;
procedure Tthread_201010_importar_pedidos_direct.SetupQueryUpdate;
begin
fdEntregasUpdate.Params.ArraySize := iCountUpdate;
fdEntregasUpdate.ParamByName('NUM_NOSSONUMERO').AsStrings[Pred(iCountUpdate)]:= FEntregas.Entregas.NN;
fdEntregasUpdate.ParamByName('COD_AGENTE').AsIntegers[Pred(iCountUpdate)]:= FEntregas.Entregas.Distribuidor;
fdEntregasUpdate.ParamByName('COD_ENTREGADOR').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Entregador;
fdEntregasUpdate.ParamByName('COD_CLIENTE').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Cliente;
fdEntregasUpdate.ParamByName('NUM_NF').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.NF;
fdEntregasUpdate.ParamByName('NOM_CONSUMIDOR').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Consumidor;
fdEntregasUpdate.ParamByName('DES_ENDERECO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Endereco;
fdEntregasUpdate.ParamByName('DES_COMPLEMENTO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Complemento;
fdEntregasUpdate.ParamByName('DES_BAIRRO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Bairro;
fdEntregasUpdate.ParamByName('NOM_CIDADE').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Cidade;
fdEntregasUpdate.ParamByName('NUM_CEP').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Cep;
fdEntregasUpdate.ParamByName('NUM_TELEFONE').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Telefone;
fdEntregasUpdate.ParamByName('DAT_EXPEDICAO').AsDateTimes[Pred(iCountUpdate)] := FEntregas.Entregas.Expedicao;
fdEntregasUpdate.ParamByName('DAT_PREV_DISTRIBUICAO').AsDateTimes[Pred(iCountUpdate)] := FEntregas.Entregas.Previsao;
fdEntregasUpdate.ParamByName('QTD_VOLUMES').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Volumes;
fdEntregasUpdate.ParamByName('DAT_ATRIBUICAO').AsDateTimes[Pred(iCountUpdate)] := FEntregas.Entregas.Atribuicao;
fdEntregasUpdate.ParamByName('DAT_BAIXA').AsDates[Pred(iCountUpdate)] := FEntregas.Entregas.Baixa;
fdEntregasUpdate.ParamByName('DOM_BAIXADO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Baixado;
fdEntregasUpdate.ParamByName('DAT_PAGAMENTO').AsDates[Pred(iCountUpdate)] := FEntregas.Entregas.Pagamento;
fdEntregasUpdate.ParamByName('DOM_PAGO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Pago;
fdEntregasUpdate.ParamByName('DOM_FECHADO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Fechado;
fdEntregasUpdate.ParamByName('COD_STATUS').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Status;
fdEntregasUpdate.ParamByName('DAT_ENTREGA').AsDates[Pred(iCountUpdate)] := FEntregas.Entregas.Entrega;
fdEntregasUpdate.ParamByName('QTD_PESO_REAL').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.PesoReal;
fdEntregasUpdate.ParamByName('QTD_PESO_FRANQUIA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.PesoFranquia;
fdEntregasUpdate.ParamByName('VAL_VERBA_FRANQUIA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.VerbaFranquia;
fdEntregasUpdate.ParamByName('VAL_ADVALOREM').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.Advalorem;
fdEntregasUpdate.ParamByName('VAL_PAGO_FRANQUIA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.PagoFranquia;
fdEntregasUpdate.ParamByName('VAL_VERBA_ENTREGADOR').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.VerbaEntregador;
fdEntregasUpdate.ParamByName('NUM_EXTRATO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Extrato;
fdEntregasUpdate.ParamByName('QTD_DIAS_ATRASO').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Atraso;
fdEntregasUpdate.ParamByName('QTD_VOLUMES_EXTRA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.VolumesExtra;
fdEntregasUpdate.ParamByName('VAL_VOLUMES_EXTRA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.ValorVolumes;
fdEntregasUpdate.ParamByName('QTD_PESO_COBRADO').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.PesoCobrado;
fdEntregasUpdate.ParamByName('DES_TIPO_PESO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.TipoPeso;
fdEntregasUpdate.ParamByName('DAT_RECEBIDO').AsDates[Pred(iCountUpdate)] := FEntregas.Entregas.Recebimento;
fdEntregasUpdate.ParamByName('DOM_RECEBIDO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Recebido;
fdEntregasUpdate.ParamByName('NUM_CTRC').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.CTRC;
fdEntregasUpdate.ParamByName('NUM_MANIFESTO').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Manifesto;
fdEntregasUpdate.ParamByName('DES_RASTREIO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Rastreio;
fdEntregasUpdate.ParamByName('VAL_VERBA_FRANQUIA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.VerbaFranquia;
fdEntregasUpdate.ParamByName('NUM_LOTE_REMESSA').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Lote;
fdEntregasUpdate.ParamByName('DES_RETORNO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Retorno;
fdEntregasUpdate.ParamByName('DAT_CREDITO').AsDateTimes[Pred(iCountUpdate)] := FEntregas.Entregas.Credito;
fdEntregasUpdate.ParamByName('DOM_CREDITO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Creditado;
fdEntregasUpdate.ParamByName('NUM_CONTAINER').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Container;
fdEntregasUpdate.ParamByName('VAL_PRODUTO').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.ValorProduto;
fdEntregasUpdate.ParamByName('QTD_ALTURA').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Altura;
fdEntregasUpdate.ParamByName('QTD_LARGURA').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Largura;
fdEntregasUpdate.ParamByName('QTD_COMPRIMENTO').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Comprimento;
fdEntregasUpdate.ParamByName('COD_FEEDBACK').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.CodigoFeedback;
fdEntregasUpdate.ParamByName('DAT_FEEDBACK').AsDateTimes[Pred(iCountUpdate)] := FEntregas.Entregas.DataFeedback;
fdEntregasUpdate.ParamByName('DOM_CONFERIDO').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Conferido;
fdEntregasUpdate.ParamByName('NUM_PEDIDO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Pedido;
fdEntregasUpdate.ParamByName('COD_CLIENTE_EMPRESA').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.CodCliente;
end;
procedure Tthread_201010_importar_pedidos_direct.SetupQueryAWB(sRemessa, sAWB1, sAWB2, sCEP, sOperacao: String; iTipo: Integer; dPeso: Double);
begin
fdControleAWB.Params.ArraySize := iCountAWB;
fdControleAWB.ParamByName('id_awb').AsIntegers[Pred(iCountAWB)] := 0;
fdControleAWB.ParamByName('num_remessa').AsStrings[Pred(iCountAWB)] := sRemessa;
fdControleAWB.ParamByName('cod_awb1').AsStrings[Pred(iCountAWB)] := sAWB1;
fdControleAWB.ParamByName('cod_awb2').AsStrings[Pred(iCountAWB)] := sAWB2;
fdControleAWB.ParamByName('num_cep').AsStrings[Pred(iCountAWB)] := sCEP;
fdControleAWB.ParamByName('cod_operacao').AsStrings[Pred(iCountAWB)] := sOperacao;
fdControleAWB.ParamByName('cod_tipo').AsIntegers[Pred(iCountAWB)] := iTipo;
fdControleAWB.ParamByName('qtd_peso').AsFloats[Pred(iCountAWB)] := dPeso;
end;
procedure Tthread_201010_importar_pedidos_direct.TerminateProcess;
begin
view_ImportarPedidos.actCancelar.Enabled := False;
view_ImportarPedidos.actFechar.Enabled := True;
view_ImportarPedidos.actImportar.Enabled := True;
view_ImportarPedidos.actAbrirArquivo.Enabled := True;
view_ImportarPedidos.edtArquivo.Clear;
view_ImportarPedidos.pbImportacao.Position := 0;
view_ImportarPedidos.pbImportacao.Clear;
view_ImportarPedidos.dxLayoutItem8.Visible := False;
view_ImportarPedidos.cboCliente.ItemIndex := 0;
end;
procedure Tthread_201010_importar_pedidos_direct.UpdateLog;
begin
view_ImportarPedidos.memLOG.Lines.Add(sMensagem);
view_ImportarPedidos.memLOG.Lines.Add('');
iLinha := view_ImportarPedidos.memLOG.Lines.Count - 1;
view_ImportarPedidos.memLOG.Refresh;
end;
procedure Tthread_201010_importar_pedidos_direct.UpdateProgress;
begin
view_ImportarPedidos.pbImportacao.Position := FdPos;
view_ImportarPedidos.pbImportacao.Properties.Text := FormatFloat('0.00%',FdPos) +
' - (' + IntToStr(iPosition) + ' registros processados)';
view_ImportarPedidos.pbImportacao.Refresh;
//view_ImportarPedidos.memLOG.Lines[iLinha] := ' >>> ' + IntToStr(iLinha) + ' registros processados';
//view_ImportarPedidos.memLOG.Refresh;
if not(view_ImportarPedidos.actCancelar.Visible) then
begin
view_ImportarPedidos.actCancelar.Visible := True;
view_ImportarPedidos.actFechar.Enabled := False;
view_ImportarPedidos.actImportar.Enabled := False;
end;
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.38 1/15/05 2:14:58 PM RLebeau
Removed virtual specifier from SetConnectTimeout() and SetReadTimeout(), not
being used by any descendants.
Rev 1.37 11/29/2004 11:49:24 PM JPMugaas
Fixes for compiler errors.
Rev 1.36 11/29/04 10:38:58 AM RLebeau
Updated Connect() to release the IOHandler on error if implicitally created.
Rev 1.35 11/28/04 2:28:22 PM RLebeau
Added 'const' to various property setter parameters.
Removed redundant getter methods.
Rev 1.34 11/27/2004 8:27:44 PM JPMugaas
Fix for compiler errors.
Rev 1.33 11/26/04 3:46:10 PM RLebeau
Added support for BoundIP and BoundPort properties
Rev 1.32 2004.11.05 10:58:34 PM czhower
Changed connect overloads for C#.
Rev 1.31 8/8/04 12:32:08 AM RLebeau
Redeclared ReadTimeout and ConnectTimeout properties as public instead of
protected in TIdTCPClientCustom
Rev 1.30 8/4/2004 5:37:34 AM DSiders
Changed camel-casing on ReadTimeout to be consistent with ConnectTimeout.
Rev 1.29 8/3/04 11:17:30 AM RLebeau
Added support for ReadTimeout property
Rev 1.28 8/2/04 5:50:58 PM RLebeau
Added support for ConnectTimeout property
Rev 1.27 2004.03.06 10:40:28 PM czhower
Changed IOHandler management to fix bug in server shutdowns.
Rev 1.26 2004.02.03 4:16:54 PM czhower
For unit name changes.
Rev 1.25 1/8/2004 8:22:54 PM JPMugaas
SetIPVersion now virtual so I can override in TIdFTP. Other stuff may need
the override as well.
Rev 1.24 1/2/2004 12:02:18 AM BGooijen
added OnBeforeBind/OnAfterBind
Rev 1.23 12/31/2003 9:52:04 PM BGooijen
Added IPv6 support
Rev 1.20 2003.10.14 1:27:00 PM czhower
Uupdates + Intercept support
Rev 1.19 2003.10.01 9:11:26 PM czhower
.Net
Rev 1.18 2003.10.01 2:30:42 PM czhower
.Net
Rev 1.17 2003.10.01 11:16:36 AM czhower
.Net
Rev 1.16 2003.09.30 1:23:06 PM czhower
Stack split for DotNet
Rev 1.15 2003.09.18 2:59:46 PM czhower
Modified port and host overrides to only override if values exist.
Rev 1.14 6/3/2003 11:48:32 PM BGooijen
Undid change from version 1.12, is now fixed in iohandlersocket
Rev 1.13 2003.06.03 7:27:56 PM czhower
Added overloaded Connect method
Rev 1.12 5/23/2003 6:45:32 PM BGooijen
ClosedGracefully is now set if Connect failes.
Rev 1.11 2003.04.10 8:05:34 PM czhower
removed unneeded self. reference
Rev 1.10 4/7/2003 06:58:32 AM JPMugaas
Implicit IOHandler now created in virtual method
function TIdTCPClientCustom.MakeImplicitClientHandler: TIdIOHandler;
Rev 1.9 3/17/2003 9:40:16 PM BGooijen
Host and Port were not properly synchronised with the IOHandler, fixed that
Rev 1.8 3/5/2003 11:05:24 PM BGooijen
Intercept
Rev 1.7 2003.02.25 1:36:16 AM czhower
Rev 1.6 12-14-2002 22:52:34 BGooijen
now also saves host and port settings when an explicit iohandler is used. the
host and port settings are copied to the iohandler if the iohandler doesn't
have them specified.
Rev 1.5 12-14-2002 22:38:26 BGooijen
The host and port settings were lost when the implicit iohandler was created
in .Connect, fixed that.
Rev 1.4 2002.12.07 12:26:12 AM czhower
Rev 1.2 12/6/2002 02:11:42 PM JPMugaas
Protected Port and Host properties added to TCPClient because those are
needed by protocol implementations. Socket property added to TCPConnection.
Rev 1.1 6/12/2002 4:08:34 PM SGrobety
Rev 1.0 11/13/2002 09:00:26 AM JPMugaas
}
unit IdTCPClient;
{$i IdCompilerDefines.inc}
interface
uses
Classes,
IdGlobal, IdExceptionCore, IdIOHandler, IdTCPConnection;
type
TIdTCPClientCustom = class(TIdTCPConnection)
protected
FBoundIP: String;
FBoundPort: TIdPort;
FBoundPortMax: TIdPort;
FBoundPortMin: TIdPort;
FConnectTimeout: Integer;
FDestination: string;
FHost: string;
FIPVersion: TIdIPVersion;
FOnConnected: TNotifyEvent;
FPassword: string;
FPort: TIdPort;
FReadTimeout: Integer;
FUsername: string;
FReuseSocket: TIdReuseSocket;
FUseNagle: Boolean;
//
FOnBeforeBind: TNotifyEvent;
FOnAfterBind: TNotifyEvent;
FOnSocketAllocated: TNotifyEvent;
//
procedure DoOnConnected; virtual;
function MakeImplicitClientHandler: TIdIOHandler; virtual;
//
procedure SetConnectTimeout(const AValue: Integer);
procedure SetReadTimeout(const AValue: Integer);
procedure SetReuseSocket(const AValue: TIdReuseSocket);
procedure SetUseNagle(const AValue: Boolean);
procedure SetBoundIP(const AValue: String);
procedure SetBoundPort(const AValue: TIdPort);
procedure SetBoundPortMax(const AValue: TIdPort);
procedure SetBoundPortMin(const AValue: TIdPort);
procedure SetHost(const AValue: string); virtual;
procedure SetPort(const AValue: TIdPort); virtual;
procedure SetIPVersion(const AValue: TIdIPVersion); virtual;
//
procedure SetOnBeforeBind(const AValue: TNotifyEvent);
procedure SetOnAfterBind(const AValue: TNotifyEvent);
procedure SetOnSocketAllocated(const AValue: TNotifyEvent);
//
procedure SetIOHandler(AValue: TIdIOHandler); override;
procedure InitComponent; override;
//
function GetReadTimeout: Integer;
function GetReuseSocket: TIdReuseSocket;
function GetUseNagle: Boolean;
//
property Host: string read FHost write SetHost;
property IPVersion: TIdIPVersion read FIPVersion write SetIPVersion;
property Password: string read FPassword write FPassword;
property Port: TIdPort read FPort write SetPort;
property Username: string read FUsername write FUsername;
public
procedure Connect; overload; virtual;
// This is overridden and not as default params so that descendants
// do not have to worry about the arguments.
// Also has been split further to allow usage from C# as it does not have optional
// params
procedure Connect(const AHost: string); overload;
procedure Connect(const AHost: string; const APort: TIdPort); overload;
function ConnectAndGetAll: string; virtual;
//
property BoundIP: string read FBoundIP write SetBoundIP;
property BoundPort: TIdPort read FBoundPort write SetBoundPort default DEF_PORT_ANY;
property BoundPortMax: TIdPort read FBoundPortMax write SetBoundPortMax default DEF_PORT_ANY;
property BoundPortMin: TIdPort read FBoundPortMin write SetBoundPortMin default DEF_PORT_ANY;
//
property ConnectTimeout: Integer read FConnectTimeout write SetConnectTimeout;
property ReadTimeout: Integer read GetReadTimeout write SetReadTimeout;
property ReuseSocket: TIdReuseSocket read GetReuseSocket write SetReuseSocket default rsOSDependent;
property UseNagle: Boolean read GetUseNagle write SetUseNagle default True;
//
property OnBeforeBind: TNotifyEvent read FOnBeforeBind write SetOnBeforeBind;
property OnAfterBind: TNotifyEvent read FOnAfterBind write SetOnAfterBind;
property OnSocketAllocated: TNotifyEvent read FOnSocketAllocated write SetOnSocketAllocated;
//
published
property OnConnected: TNotifyEvent read FOnConnected write FOnConnected;
end;
TIdTCPClient = class(TIdTCPClientCustom)
published
property BoundIP;
property BoundPort;
property ConnectTimeout;
property Host;
property IPVersion;
property Port;
property ReadTimeout;
property ReuseSocket;
property UseNagle;
property OnBeforeBind;
property OnAfterBind;
property OnSocketAllocated;
end;
//Temp IFDEF till we change aliaser
// Temp - reversed it for code freeze - will rereverse later.
implementation
uses
IdComponent, IdResourceStringsCore, IdIOHandlerSocket;
{ TIdTCPClientCustom }
procedure TIdTCPClientCustom.InitComponent;
begin
inherited InitComponent;
FReadTimeOut := IdTimeoutDefault;
FBoundPort := DEF_PORT_ANY;
FBoundPortMin := DEF_PORT_ANY;
FBoundPortMax := DEF_PORT_ANY;
FUseNagle := True;
end;
procedure TIdTCPClientCustom.Connect;
begin
if Connected then begin
EIdAlreadyConnected.Toss(RSAlreadyConnected);
end;
if Host = '' then begin
EIdHostRequired.Toss('');
end;
if Port = 0 then begin
EIdPortRequired.Toss('');
end;
if IOHandler = nil then begin
IOHandler := MakeImplicitClientHandler;
IOHandler.OnStatus := OnStatus;
ManagedIOHandler := True;
end;
try
// Bypass GetDestination
if FDestination <> '' then begin
IOHandler.Destination := FDestination;
end;
{BGO: not any more, TIdTCPClientCustom has precedence now (for port protocols, and things like that)
// We retain the settings that are in here (filled in by the user)
// we only do this when the iohandler has no settings,
// because the iohandler has precedence
if (IOHandler.Port = 0) and (IOHandler.Host = '') then begin
IOHandler.Port := FPort;
IOHandler.Host := FHost;
end;
}
IOHandler.Port := FPort; //BGO: just to make sure
IOHandler.Host := FHost;
IOHandler.ConnectTimeout := FConnectTimeout;
IOHandler.ReadTimeout := FReadTimeout;
if Socket <> nil then begin
Socket.BoundIP := FBoundIP;
Socket.BoundPort := FBoundPort;
Socket.BoundPortMin := FBoundPortMin;
Socket.BoundPortMax := FBoundPortMax;
Socket.IPVersion := FIPVersion;
Socket.ReuseSocket := FReuseSocket;
Socket.UseNagle := FUseNagle;
Socket.OnBeforeBind := FOnBeforeBind;
Socket.OnAfterBind := FOnAfterBind;
Socket.OnSocketAllocated := FOnSocketAllocated;
end;
IOHandler.Open;
if IOHandler.Intercept <> nil then begin
IOHandler.Intercept.Connect(Self);
end;
DoStatus(hsConnected, [Host]);
DoOnConnected;
except
if IOHandler <> nil then begin
IOHandler.Close;
if ManagedIOHandler then begin
IOHandler := nil; // RLebeau - SetIOHandler() will free the IOHandler
end;
end;
raise;
end;
end;
function TIdTCPClientCustom.ConnectAndGetAll: string;
begin
Connect; try
Result := IOHandler.AllData;
finally Disconnect; end;
end;
procedure TIdTCPClientCustom.DoOnConnected;
begin
if Assigned(OnConnected) then begin
OnConnected(Self);
end;
end;
procedure TIdTCPClientCustom.SetConnectTimeout(const AValue: Integer);
begin
FConnectTimeout := AValue;
if IOHandler <> nil then begin
IOHandler.ConnectTimeout := AValue;
end;
end;
procedure TIdTCPClientCustom.SetReadTimeout(const AValue: Integer);
begin
FReadTimeout := AValue;
if IOHandler <> nil then begin
IOHandler.ReadTimeout := AValue;
end;
end;
procedure TIdTCPClientCustom.SetReuseSocket(const AValue: TIdReuseSocket);
begin
FReuseSocket := AValue;
if Socket <> nil then begin
Socket.ReuseSocket := AValue;
end;
end;
procedure TIdTCPClientCustom.SetUseNagle(const AValue: Boolean);
begin
FUseNagle := AValue;
if Socket <> nil then begin
Socket.UseNagle := AValue;
end;
end;
procedure TIdTCPClientCustom.SetBoundIP(const AValue: String);
begin
FBoundIP := AValue;
if Socket <> nil then begin
Socket.BoundIP := AValue;
end;
end;
procedure TIdTCPClientCustom.SetBoundPort(const AValue: TIdPort);
begin
FBoundPort := AValue;
if Socket <> nil then begin
Socket.BoundPort := AValue;
end;
end;
procedure TIdTCPClientCustom.SetBoundPortMax(const AValue: TIdPort);
begin
FBoundPortMax := AValue;
if Socket <> nil then begin
Socket.BoundPortMax := AValue;
end;
end;
procedure TIdTCPClientCustom.SetBoundPortMin(const AValue: TIdPort);
begin
FBoundPortMin := AValue;
if Socket <> nil then begin
Socket.BoundPortMin := AValue;
end;
end;
procedure TIdTCPClientCustom.SetHost(const AValue: string);
begin
FHost := AValue;
if IOHandler <> nil then begin
IOHandler.Host := AValue;
end;
end;
procedure TIdTCPClientCustom.SetPort(const AValue: TIdPort);
begin
FPort := AValue;
if IOHandler <> nil then begin
IOHandler.Port := AValue;
end;
end;
procedure TIdTCPClientCustom.SetIPVersion(const AValue: TIdIPVersion);
begin
FIPVersion := AValue;
if Socket <> nil then begin
Socket.IPVersion := AValue;
end;
end;
procedure TIdTCPClientCustom.SetOnBeforeBind(const AValue: TNotifyEvent);
begin
FOnBeforeBind := AValue;
if Socket <> nil then begin
Socket.OnBeforeBind := AValue;
end;
end;
procedure TIdTCPClientCustom.SetOnAfterBind(const AValue: TNotifyEvent);
begin
FOnAfterBind := AValue;
if Socket <> nil then begin
Socket.OnAfterBind := AValue;
end;
end;
procedure TIdTCPClientCustom.SetOnSocketAllocated(const AValue: TNotifyEvent);
begin
FOnSocketAllocated := AValue;
if Socket <> nil then begin
Socket.OnSocketAllocated := AValue;
end;
end;
procedure TIdTCPClientCustom.SetIOHandler(AValue: TIdIOHandler);
begin
inherited SetIOHandler(AValue);
// TIdTCPClientCustom overrides settings in iohandler to initialize
// protocol defaults.
if IOHandler <> nil then begin
IOHandler.Port := FPort;
IOHandler.Host := FHost;
IOHandler.ConnectTimeout := FConnectTimeout;
IOHandler.ReadTimeout := FReadTimeout;
end;
if Socket <> nil then begin
Socket.BoundIP := FBoundIP;
Socket.BoundPort := FBoundPort;
Socket.BoundPortMin := FBoundPortMin;
Socket.BoundPortMax := FBoundPortMax;
Socket.IPVersion := FIPVersion;
Socket.ReuseSocket := FReuseSocket;
Socket.UseNagle := FUseNagle;
Socket.OnBeforeBind := FOnBeforeBind;
Socket.OnAfterBind := FOnAfterBind;
Socket.OnSocketAllocated := FOnSocketAllocated;
end;
end;
function TIdTCPClientCustom.MakeImplicitClientHandler: TIdIOHandler;
begin
Result := TIdIOHandler.MakeDefaultIOHandler(Self);
end;
procedure TIdTCPClientCustom.Connect(const AHost: string);
begin
Host := AHost;
Connect;
end;
procedure TIdTCPClientCustom.Connect(const AHost: string; const APort: TIdPort);
begin
Host := AHost;
Port := APort;
Connect;
end;
function TIdTCPClientCustom.GetReadTimeout: Integer;
begin
if IOHandler <> nil then begin
Result := IOHandler.ReadTimeout;
end else begin
Result := FReadTimeout;
end;
end;
function TIdTCPClientCustom.GetReuseSocket: TIdReuseSocket;
begin
if Socket <> nil then begin
Result := Socket.ReuseSocket;
end else begin
Result := FReuseSocket;
end;
end;
function TIdTCPClientCustom.GetUseNagle: Boolean;
begin
if Socket <> nil then begin
Result := Socket.UseNagle;
end else begin
Result := FUseNagle;
end;
end;
end.
|
unit FileChannel;
{
Copyright (C) 2006 Luiz Américo Pereira Câmara
TFileChannel modified by devEric69 ( Éric Moutié ):
- it became thread safe, eg TMemoChannel's modifications.
- added the possibility to have an overview, a "film" of the events for which we want to anderstand the order of their inter-calls.
This library is free software; you can redistribute it and/or modify it
under the terms of the FPC modified LGPL licence which can be found at:
http://wiki.lazarus.freepascal.org/FPC_modified_LGPL.
Unit containing TFileChannel. Updated by devEric69 (Ėric Moutié).
There is the possibility to see the indentation of events in the calls stack.
}
{$ifdef fpc}
{$mode objfpc}{$H+}
{$endif}
interface
uses
{$ifndef fpc}fpccompat,{$endif} Classes, SysUtils, multilog;
type
TFilelogThematics = (fltLogNormal, fltLogSQL);
TFileChannelOption = (fcoShowHeader, fcoShowPrefixMethod, fcoShowTime, fcoShowDynamicFilter_forWhatReasonsToLogActually);
TFileChannelOptions = set of TFileChannelOption;
TStatesOfLogstack = record
bEnterMethodCalled: Boolean;
bShouldIndentASubEvent: Boolean;
bExitMethodCalled: Boolean;
end;
PStatesOfLogstack = ^TStatesOfLogstack;
{ TFileChannelDataHelperFunctions }
type
TFileChannelDataHelperFunctions = class
private
FsFilePath: string;
FiHandleDataFile: THandle;
FiLockSpecifier: Byte;
protected
function GetSize: Int64;
public
constructor Create(const sFilePath: string); reintroduce; overload;
destructor Destroy; override;
property Size: Int64 read GetSize;
end;
{ TFileChannel }
TFileChannel = class(TLogChannel)
private
FrecMsg: TrecLogMessage;
{ (!!!) It must be *full* path like '/home/user_1/.TheAppli/Log.txt' or 'C:\Program Files\TheAppli\Log.txt'.}
FsFullPathFileName: string;
FFileHandle: TextFile;
FieFilelogThematics: TFilelogThematics;
FiBaseIdent: Integer;
FiRelativeIdent: Integer;
FbIndentCallstackTriggeredByEntermethod: boolean;
FiCallstackIndent: Integer;
FiAddressEBPcurrentFrame: Pointer;
FiLevelStack: integer;
FShowHeader: Boolean; //'=== Log Session Started at '.../...
{ is set to True when '=== Log Session Started at ' has been written one time in the log normal, at the launch of the application.}
FbShowHeaderNormalWritten: boolean;
{ is set to True when '=== Log Session Started at ' has been written one time in the log SQL, at the launch of the application.}
FbShowHeaderSQL_Written: boolean;
FsTimeFormat: string;
FpRecStatesOfLogstack: PStatesOfLogstack;
FiMaxLogSize: int64;
FbWantSpecificFileForSQLstatements: Boolean;
(* identation management *)
procedure UpdateBaseTimeIdentation;
procedure UpdateRelativeIndentation;
procedure UpdateEBPIndentation;
{ Explanations:
Warning: it is ***not*** used to send a Call Stack back from a crash, which you would like to indent nicely: the crashed Call stack is already recovered in multiLog.
This is used to see the indentation of events, that have an event like @code(send|watch|)... coded between:
- the beginning of an event @code(procedure TForm1.btnPostClick(Sender: TObject); enter_METHOD_[>>];)...
- ...and the end of the same event @code(exit_METHOD)_[<<]).
Indeed, by considering only potentially codable events, such as those used for a database management, they can be encapsulated in a complex way,
between the basic click of a button @code(btnPostData();) that can initiate the request to repaint controls, ..., format the input, ...,
data transfer via a datalink, ..., data verification, ..., related calculations of calculated fields, ..., datSet Post, ...
In addition, many events have an onBeforEvent, onEvent and onAfterEvent.
==> the view of the graph of the indentation of the events \ methods \... called between @code(enter_METHOD_[>>>];) and @code(exit_METHOD)_[<<<];),
as they are "pushed" \ "poped" into the stack of calls makes it possible to understand through an indented holistic view,
an event management whose inter-calls of sub-events are not understood, if they have been coded in an event called too early or too late,
if an under-event has been called several times by other under-events without regard to context, etc.
It is therefore a means of more in-depth understanding an event programming, and therefore of helping to develop events management:
procedure TForm1.SubLogClick(Sender: TObject);
begin
|--> EnterMethod [>>]: goLogger.EnterMethod(Sender,'SubLogClick');
|--> entrée event 1: goLogger.SubEventBetweenEnterAndExitMethods('>event DoSmallCodePieceNum2 + Sender=' + Sender.ClassName);
|-->
|-->
|-->
|-->
|--> goLogger.SubEventBetweenEnterAndExitMethods('><event DoSmallCodePieceNum6 + Sender=' + Sender.ClassName + ' (I''m the last push inside the callstack. Now, we pop from the callstack.)');
|-->
|-->
|--> sortie event 1: goLogger.SubEventBetweenEnterAndExitMethods('<event DoSmallCodePieceNum1 + Sender=' + Sender.ClassName);
|--> ExitMethod [<<: ExitMethod(Sender,'SubLogClick');
end;
}
function GetEBPIndentation: integer;
function CallstackSize: int64;
{ Explanations: returns de file's size; -1 if it doesn't exist. }
function GetFileLogSize: int64;
(* methods of writing stream-text in the log *)
procedure WriteStringsOfMsgDataStream();
procedure WriteComponentOfMsgDataStream();
function StreamIntoRawString(): string;
(* log management *)
{ Explanations: check if the size is larger than the maximum allowed; in this case, the log file est saved and a new one is created and used. }
procedure CheckIfNecessaryToSaveAndCreateNewFileLog;
{ Explanations: create a NEW FsPathFileLog file! }
procedure FileLogCreate;
function GetTimestampFromToday: string;
{ Explanations: close, remove all lock(s), threads's connexion(s), with FsPathFileLog. }
procedure CloseFileLog;
{ Explanations: ckeck if FMsg est SQL related. returns True, if it's a SQL-oriented message.) }
function IsSQLwordPresentInMsg: Boolean;
{ Explanations: set the FieCurrentFileLogTheme property. Does not have to be public or published. Usefulness due to its side effects, nothing more.}
procedure SetFilelogThematic(AFileLogThematic: TFilelogThematics);
procedure OpenRightFilelogThematic;
protected
public
{ Explanations: constructor.
AFileName is the *full* path and the name of the logging file.)
AChannelOptions: it's a set of options (timestamp, Why this msg, ...) that qualifies each message written in the log file.)
- param: AbWantSpecificFileForSQLstatements:
=False if you want to use a single log file for your whole application, where you will write everything.
=True if you want to create another SQL-oriented log file, in which only the SQL Exceptions, the msq which may have their dumped
content as text with a substring 'SQL' or 'sql' will be logged. It's an SQL-oriented log file named "AFileName+'_SQL'+.your_possible_file_ext".)
- returns: object instance. }
constructor Create(const AFileName: String; AChannelOptions: TFileChannelOptions = [fcoShowHeader, fcoShowTime]; AbWantSpecificFileForSQLstatements: boolean = false);
destructor Destroy; override;
procedure Clear; override;
procedure Deliver(const AMsg: TrecLogMessage);override;
{ Explanations: init, post-constructor;
goal: create the log file(s) that will be used by the application,
according to the parameters passed to the constructor.}
procedure Init; override;
property ShowHeader: Boolean read FShowHeader write FShowHeader;
property TimeFormat: String read FsTimeFormat write FsTimeFormat;
property MaxLogSize: int64 read FiMaxLogSize default 1000000; (*1 Mo = 4.10^9 [b]*)
property IndentCallstackTriggeredByEntermethod: boolean read FbIndentCallstackTriggeredByEntermethod write FbIndentCallstackTriggeredByEntermethod default true;
property FullPathFileName: string read FsFullPathFileName;
property CurrentFileLogTheme: TFilelogThematics read FieFilelogThematics write SetFilelogThematic default fltLogNormal;
end;
implementation
uses
FileUtil, fpccompat, strutils, multilogAsm, math, RtlConsts , Dialogs;
var
goGuardianFile: TGuardian; { Prevents 2 TFileChannel's objects, to write in race concurrency inside de same log file. }
const
csSuffixForSQLlogFile: string = '_SQL';
csSQL_FileName = '$Log_SQL.txt';
csNormal_FileName = '$Log.txt';
{ TFileChannel }
function TFileChannel.CallstackSize: int64;
begin
result:= int64(StackTop)-int64(StackBottom); // =~ same information as StackLength, ie it's an offset.
end;
procedure TFileChannel.WriteStringsOfMsgDataStream();
var
i: Integer;
{$IFDEF DEBUG}
sTemp: string;
{$ENDIF}
oTStringList: TStringList;
begin
if FrecMsg.pData.Size = 0 then Exit; // pre-condition
oTStringList:= TStringList.Create;
with oTStringList do begin
try
FrecMsg.pData.Position:=0;
LoadFromStream(FrecMsg.pData);
for i:= 0 to Count - 1 do begin
{$IFDEF DEBUG}
sTemp:= Strings[i];
{$ENDIF}
WriteLn(FFileHandle,Space(FiBaseIdent+FiRelativeIdent) + Strings[i]);
end;
finally
FreeAndNil(oTStringList);
end;
end;
end;
function TFileChannel.StreamIntoRawString(): string;
begin
if not Assigned(FrecMsg.pData) then begin // pre-condition
result:= '';
Exit;
end;
with TStringStream.Create('') do begin
try
FrecMsg.pData.Position:= 0;
CopyFrom(FrecMsg.pData, FrecMsg.pData.Size - FrecMsg.pData.Position);
Result:= DataString;
finally
Free;
end;
end;
end;
procedure TFileChannel.WriteComponentOfMsgDataStream();
var
TextStream: TStringStream;
begin
TextStream:= TStringStream.Create('');
FrecMsg.pData.Seek(0, soFromBeginning);
ObjectBinaryToText(FrecMsg.pData,TextStream);
Write(FFileHandle, TextStream.DataString); //todo: better handling of format
TextStream.Destroy;
end;
procedure TFileChannel.CheckIfNecessaryToSaveAndCreateNewFileLog;
procedure BackupEtDeleteFileLog;
{Explanations: Copy the log file with "xxx_timestamp.log.txt.old" extension.
Then, delete the original saved file.}
var
sFullPathFileDest: TFileName;
sFilePath, sFileOldExt, sFileNewExt, sFileName: string;
begin
(*close the log-file, before making its copy*)
CloseFileLog;
sFilePath:= ExtractFilePath(FsFullPathFileName);
sFileOldExt:= ExtractFileExt(FsFullPathFileName);
sFileNewExt:= '.old'+ExtractFileExt(FsFullPathFileName);
sFileName:= ExtractFileName(FsFullPathFileName);
sFileName:= LeftStr(sFileName, Length(sFileName)-Length(sFileOldExt));
(*finally, the backup-file will be named... _AAAAMMJJ_HHMM.old.xxx*)
sFullPathFileDest:= sFilePath+sFileName+'_'+GetTimestampFromToday+'_'+LeftStr(ReplaceStr(TimeToStr(Now), ':', ''), 4)+sFileNewExt;
if FileExists(sFullPathFileDest) then
SysUtils.DeleteFile(sFullPathFileDest);
CopyFile(FsFullPathFileName, sFullPathFileDest);
SysUtils.DeleteFile(FsFullPathFileName);
end;
begin
if (GetFileLogSize > FiMaxLogSize) then begin
BackupEtDeleteFileLog;
FileLogCreate;
end;
end;
procedure TFileChannel.CloseFileLog;
begin
{$I-}
try
AssignFile(FFileHandle, FsFullPathFileName);
finally
CloseFile(FFileHandle);
if IOResult = 103 then begin
(*CloseFile sends IOResult-error 103, if the file wasn't open; reset IOResult with 0.*)
InOutRes:= 0;
end;
end;
{$I+}
end;
procedure TFileChannel.FileLogCreate;
begin
Assert(not FileExists(FsFullPathFileName), 'TFileChannel.FileLogCreate: File '+FsFullPathFileName+' must already be deleted!'); // How to call this method
AssignFile(FFileHandle, FsFullPathFileName);
ReWrite(FFileHandle); // Create new log file
Writeln(FFileHandle, '=== File created at ', DateTimeToStr(Now),' by ', ApplicationName,' ===');
WriteLn(FFileHandle,'=== Log Session Started at ', DateTimeToStr(Now),' by ', ApplicationName,' ===');
Close(FFileHandle);
end;
function TFileChannel.GetFileLogSize: int64;
var
oFileData: TFileChannelDataHelperFunctions;
begin
oFileData:= TFileChannelDataHelperFunctions.Create(Self.FsFullPathFileName);
Result:= oFileData.Size;
FreeAndNil(oFileData);
end;
function TFileChannel.GetTimestampFromToday: string;
var
sTodayDateTime: string;
begin
sTodayDateTime:= FormatDateTime('yyyy/mm/dd', Now);
{$if defined(Win64)}
result:= StringReplace(sTodayDateTime, '/', '-', [rfReplaceAll]); // the slash is not allowed in a Windows file name
{$ElseIf defined(UNIX)}
result:= sTodayDateTime;
{$endif}
end;
constructor TFileChannel.Create(const AFileName: String; AChannelOptions: TFileChannelOptions; AbWantSpecificFileForSQLstatements: boolean = false);
begin
if IsMultiThread then
goGuardianFile:= TGuardian.Create;
FiMaxLogSize:= 1000000; //default property
FbShowTime:= fcoShowTime in AChannelOptions;
FShowHeader:= fcoShowHeader in AChannelOptions;
FbShowPrefixMethod:= fcoShowPrefixMethod in AChannelOptions; //can be disabled with ShowPrefixMethod property
FbShow_DynamicFilter_forWhatReasonsToLogActually:= fcoShowDynamicFilter_forWhatReasonsToLogActually in AChannelOptions;
FbShowHeaderNormalWritten:= False;
FbShowHeaderSQL_Written:= False;
Active:= True;
FsTimeFormat:= 'hh:nn:ss:zzz';
FsFullPathFileName:= AFileName;
FieFilelogThematics:= fltLogNormal; //default property
FbWantSpecificFileForSQLstatements:= AbWantSpecificFileForSQLstatements;
FbIndentCallstackTriggeredByEntermethod:= false;
FiAddressEBPcurrentFrame:= StackTop; FiLevelStack:= 0;
FpRecStatesOfLogstack:= new(PStatesOfLogstack);
with FpRecStatesOfLogstack^ do begin
bEnterMethodCalled:= false;
bExitMethodCalled:= false;
end;
end;
destructor TFileChannel.Destroy;
begin
if Assigned(FpRecStatesOfLogstack) then
Dispose(FpRecStatesOfLogstack);
if Assigned(goGuardianFile) then
FreeAndNil(goGuardianFile);
inherited Destroy;
end;
procedure TFileChannel.Init;
begin
//Create || Open the log file(s)
CurrentFileLogTheme:= fltLogNormal;
UpdateBaseTimeIdentation;
if (FbWantSpecificFileForSQLstatements) then begin
CurrentFileLogTheme:= fltLogSQL;
UpdateBaseTimeIdentation;
end;
//we "re-point" to the default fltLogNormal log file
CurrentFileLogTheme:= fltLogNormal;
end;
procedure TFileChannel.Clear;
begin
if FsFullPathFileName <> '' then
Rewrite(FFileHandle);
end;
function TFileChannel.IsSQLwordPresentInMsg: Boolean;
const
csSQLmarker = '[SQL] '; //[*] exists the same homonym and bijective const in unit MultiLog, function TIntegratedLogger.GetDescriptionOfSQLException
begin
Result:= AnsiContainsStr(FrecMsg.sMsgText, csSQLmarker);
end;
function TFileChannel.GetEBPIndentation: integer;
var
i: integer;
iPt1: pointer; //first pusher entry by current_method, in the stack
begin
iPt1:= GetEBP;
if iPt1 < FiAddressEBPcurrentFrame then begin
(*récup nouvelle base du dernier cadre pushé*)
FiLevelStack:= FiLevelStack+1;
end
else if iPt1 > FiAddressEBPcurrentFrame then begin
(*récup nouvelle base du dernier cadre en haut de la pile suite au pop du précédent*)
FiLevelStack:= math.Max(0, FiLevelStack-1);
end;
(*le prochain coup que l'on revient dans cette fonction, on connaîtra FiAdresseEBPCadreCourant*)
FiAddressEBPcurrentFrame:= iPt1;
result:= 0;
if FiLevelStack > 0 then begin
for i:= 0 to FiLevelStack-1 do begin
result:= result + 4; // How many space(s) should we add after goLogger.EnterMethod()?
end;
end;
end;
procedure TFileChannel.UpdateBaseTimeIdentation;
var
S: String;
begin
S:= '';
if FbShowTime then
S:= FormatDateTime(FsTimeFormat,Time);
FiBaseIdent:= Length(S)+1;
end;
procedure TFileChannel.UpdateRelativeIndentation;
begin
if (FrecMsg.iMethUsed = methEnterMethod) then begin
//reference's "screenshot" of the top of callstack
FbIndentCallstackTriggeredByEntermethod:= True;
FiAddressEBPcurrentFrame:= StackTop;
FiCallstackIndent:= 0; FiLevelStack:= 0;
//Update EnterMethod identation
Inc(FiRelativeIdent, 3);
with FpRecStatesOfLogstack^ do begin
bEnterMethodCalled:= True;
bShouldIndentASubEvent:= True;
bExitMethodCalled:= False;
end;
end
else if (FrecMsg.iMethUsed = methExitMethod) then begin
//whe stop to track the callstack: it's the end of the indentation of sub-events
FbIndentCallstackTriggeredByEntermethod:= False; // End of callstack [methEnterMethod..methExitMethod] indentation
FiCallstackIndent:= 0; FiLevelStack:= 0;
//Update EnterMethod identation
Dec(FiRelativeIdent, 3);
with FpRecStatesOfLogstack^ do begin
bEnterMethodCalled:= True;
bShouldIndentASubEvent:= False;
bExitMethodCalled:= True;
end;
end;
end;
procedure TFileChannel.UpdateEBPIndentation;
begin
if FbIndentCallstackTriggeredByEntermethod and (FrecMsg.iMethUsed = methSubEventBetweenEnterAndExitMethods) then begin
//we are always between [methEnterMethod..methExitMethod], and that's a sub-event: so, it must be indented via it's level in the callstack
with FpRecStatesOfLogstack^ do begin
bEnterMethodCalled:= True;
bShouldIndentASubEvent:= True;
bExitMethodCalled:= False;
end;
//Update EBPIndentation
FiCallstackIndent:= GetEBPIndentation;
end
else if FbIndentCallstackTriggeredByEntermethod and (FrecMsg.iMethUsed <> methSubEventBetweenEnterAndExitMethods) then begin
//we are always beteween [methEnterMethod..methExitMethod] and that's not a sub-event: so, it must not be indented via it's level in the callstack
with FpRecStatesOfLogstack^ do begin
bEnterMethodCalled:= True;
bShouldIndentASubEvent:= False;
bExitMethodCalled:= False;
end;
end
end;
procedure TFileChannel.OpenRightFilelogThematic;
var
iPosSQL: integer;
begin
try
iPosSQL:= Pos(csSuffixForSQLlogFile, FsFullPathFileName);
//Check for correct use: FsFullPathFileName must be correctly set according with FieFilelogThematics
Assert( ((FieFilelogThematics=fltLogSQL) and (iPosSQL>0)) or
((FieFilelogThematics=fltLogNormal) and (iPosSQL=0)), 'incoherent FieCurrentFileLogTheme & FFullPathFileName. See SetForCurrentFileLogThemeFullPathFileName...');
if (FsFullPathFileName <> '') then begin
Assign(FFileHandle, FsFullPathFileName); //(re)-create the file's OS-inode-Handle, in bijection with the assigned file
if FileExists(FsFullPathFileName) then
Append(FFileHandle)
else
Rewrite(FFileHandle);
end
else
FFileHandle:= Output;
//If Asked, Write the start of application's session, but only one time per application's life
if FShowHeader then begin
if (FieFilelogThematics = fltLogNormal) and not FbShowHeaderNormalWritten then begin
WriteLn(FFileHandle, '=== Log Session Started at ', DateTimeToStr(Now), ' by ', ApplicationName, ' ===');
FbShowHeaderNormalWritten:= True;
end
else if (FieFilelogThematics = fltLogSQL) and not FbShowHeaderSQL_Written then begin
WriteLn(FFileHandle, '=== Log Session Started at ', DateTimeToStr(Now), ' by ', ApplicationName, ' ===');
FbShowHeaderSQL_Written:= True;
end;
end;
if FsFullPathFileName <> '' then
Close(FFileHandle);
except
on E: Exception do
ShowMessage('TFileChannel.OpenRightFilelogThematic: ' + E.Message + LineEnding + 'check the file''s rights (' + FsFullPathFileName + ') or delete it.');
end;
end;
procedure TFileChannel.SetFilelogThematic(AFileLogThematic: TFilelogThematics);
procedure SetTheRightThemeChoiceFileLogToBeWritten;
begin
CloseFileLog;
//FsFullPathFileName points to the "verbose" log file of the software
if (FieFilelogThematics = fltLogNormal) then
FsFullPathFileName:= ExtractFilePath(FsFullPathFileName) + csNormal_FileName
//FsFullPathFileName points to the file containing SQL \ Exception \ ... queries: database management software crashes 95%, due to contextually false SQL queries
else if (FieFilelogThematics = fltLogSQL) then begin
FsFullPathFileName:= ExtractFilePath(FsFullPathFileName) + csSQL_FileName;
end;
OpenRightFilelogThematic;
end;
begin
//in which logging file should we write?
if (FieFilelogThematics <> AFileLogThematic) then
FieFilelogThematics:= AFileLogThematic;
SetTheRightThemeChoiceFileLogToBeWritten;
end;
procedure TFileChannel.Deliver(const AMsg: TrecLogMessage);
var
sWholeMsg: string;
bIsSQLwordPresentInMsg: boolean;
begin
try
//only one thread at a time, can now execute the code below; the others must be patient
if IsMultiThread then
goGuardianFile.Acquire;
FrecMsg:= AMsg;
//has the maximum allowable limit size fot the log file been reached?
CheckIfNecessaryToSaveAndCreateNewFileLog;
//we point to the right logging file according to what will be logged, and where it should be logged
if (FbWantSpecificFileForSQLstatements) then begin
bIsSQLwordPresentInMsg:= IsSQLwordPresentInMsg;
if bIsSQLwordPresentInMsg then
CurrentFileLogTheme:= fltLogSQL
else
CurrentFileLogTheme:= fltLogNormal;
end
else
CurrentFileLogTheme:= fltLogNormal;
sWholeMsg := '';
if FbShowTime then begin
sWholeMsg := FormatDateTime(FsTimeFormat, FrecMsg.dtMsgTime) + ' ';
UpdateBaseTimeIdentation;
end;
//Update ExitMethod identation
UpdateRelativeIndentation;
sWholeMsg:= sWholeMsg + fpccompat.Space(FiRelativeIdent);
//FbShowPrefixMethod can serve as prime qualifier for each current msg, allowing further thematic extractions
if FbShowPrefixMethod then
sWholeMsg := sWholeMsg + (ctsLogPrefixesMethod[FrecMsg.iMethUsed] + ': ');
//write second qualifier explaining for which tracking purposes Msg are Logged
if FbShow_DynamicFilter_forWhatReasonsToLogActually then
//write second qualifier explaining for which tracking purposes Msg are logged
sWholeMsg := sWholeMsg + TLogChannelUtils.SetofToString(FrecMsg.setFilterDynamic);
//Update if there are a sequence of "lwStudyChainedEvents Why messages" (due to a sequence of [methEnterMethod... ltSubEventBetweenEnterAndExitMethods_, ltSubEventBetweenEnterAndExitMethods_2, etc, ...methExitMethod]) to study.
UpdateEBPIndentation;
sWholeMsg:= sWholeMsg + fpccompat.Space( ifthen(FpRecStatesOfLogstack^.bShouldIndentASubEvent, FiCallstackIndent, 0) );
sWholeMsg:= sWholeMsg + FrecMsg.sMsgText;
if (FsFullPathFileName <> '') then
Append(FFileHandle);
WriteLn(FFileHandle, sWholeMsg);
//Update ExitMethod identation
UpdateRelativeIndentation;
//if there's a TStream to write
if FrecMsg.pData <> nil then
begin
case FrecMsg.iMethUsed of
methTStrings, methCallStack, methHeapInfo, methException, methMemory: WriteStringsOfMsgDataStream();
methObject: WriteComponentOfMsgDataStream();
end;
end;
finally
if (FsFullPathFileName <> '') then
Close(FFileHandle);
if IsMultiThread then
goGuardianFile.Release;
end;
end;
{ TFileChannelDataHelperFunctions }
constructor TFileChannelDataHelperFunctions.Create(const sFilePath: string);
begin
{ It does not yet exist any lock on the file's byte(s) }
FiLockSpecifier:= 0;
{ Make file if it ain't there }
if not FileExists(sFilePath) then
FiHandleDataFile := FileCreate(sFilePath);
if FiHandleDataFile < 0 then
raise EFCreateError.CreateFmt(SFCreateError, [sFilePath]);
{ Close handle returned by FileCreate so we can open it in shared mode }
FileClose(FiHandleDataFile);
FiHandleDataFile := FileOpen(sFilePath, fmOpenReadWrite or fmShareDenyNone);
if FiHandleDataFile < 0 then
raise EFOpenError.CreateFmt(SFOpenError, [sFilePath]);
FsFilePath:= sFilePath;
end;
destructor TFileChannelDataHelperFunctions.Destroy;
begin
FileClose(FiHandleDataFile);
inherited Destroy;
end;
function TFileChannelDataHelperFunctions.GetSize: Int64;
begin
Result:= FileSize(FsFilePath);
end;
end.
|
//=============================================================================
// sgTypes.pas
//=============================================================================
//
// The Types unit contains the data types used by SwinGames for shapes,
// Sprites, Bitmaps, Sounds, etc.
//
// Change History:
//
// Version 3.0:
// - 2010-01-13: Aaron : Changed function pointer of ShapeDrawingFn to accept offset
// - 2009-12-18: Andrew : Moved to new sprite format.
// - 2009-12-15: Andrew : Updated animation handling to use new NamedIndexCollection.
// - 2009-12-10: Andrew : Added cell details to bitmap
// - 2009-11-06: Andrew : Changed to Sound and Music Data records
// - 2009-10-16: Andrew : Changed to consistent array names TypeArray eg. Point2DArray
// : Added shapes and shape prototypes
// - 2009-07-13: Clinton: Renamed Event to MapEvent to MapTag
// : Renamed EventDetails to MapTagDetails
// : Renamed LayerData to MapLayerData
// : Renamed Tile to MapTile
// : Renamed CollisionData to MapCollisionData
// - 2009-07-06: Andrew : Changed movement to velocity and x,y to position for Sprite
// - 2009-07-03: Andrew : Added sameas attribute to allow implicit casts in C#
// - 2009-07-02: Andrew : Formatting, added @via_pointer for types accessed via a pointer
// : Added fields to meta comments for Vector
// - 2009-06-29: Andrew : Added Circle
// - : Started Polygon (removed for version 3)
// - 2009-06-20: Andrew : Created types unit.
//=============================================================================
/// @header sgTypes
unit sgTypes;
//=============================================================================
interface
uses SDL_Mixer, SDL, SDL_Image, SDL_TTF;
//=============================================================================
type
/// @type LongIntArray
/// @array_wrapper
/// @field data: array of LongInt
LongIntArray = array of LongInt;
/// @type LongIntPtr
/// @pointer_wrapper
/// @field pointer: ^LongInt
LongIntPtr = ^LongInt;
/// @type StringArray
/// @array_wrapper
/// @field data: array of String
StringArray = array of String;
/// @type SinglesArray
/// @array_wrapper
/// @field data: array of Single
SingleArray = array of Single;
/// This type is used for mapping arrays out of the Pascal library
///
/// @type StringPtr
/// @pointer_wrapper
/// @field pointer: ^String
StringPtr = ^String;
/// The named index collection type is used to maintain a named collection of
/// index values that can then be used to lookup the location of the
/// named value within a collection.
///
/// @struct NamedIndexCollection
/// @via_pointer
NamedIndexCollection = packed record
names: StringArray; // The names of these ids
ids: Pointer; // A pointer to a TStringHash with this data
end;
/// A Point2D represents an location in Cartesian coordinates (x,y).
///
/// @struct Point2D
/// @sameas Vector
Point2D = packed record
x, y: Single;
end;
/// Vectors represent a direction and distance, stored as x,y components.
///
/// @struct Vector
/// @field x: Single
/// @field y: Single
/// @sameas Point2D
Vector = Point2D;
/// @type Point2DPtr
/// @pointer_wrapper
/// @field pointer: ^Point2D
Point2DPtr = ^Point2D;
/// @type Point2DArray
/// @array_wrapper
/// @field data: array of Point2D
Point2DArray = Array of Point2D;
/// @struct Rectangle
Rectangle = packed record
x, y: Single;
width, height: LongInt;
end;
/// @struct Circle
Circle = packed record
center: Point2D;
radius: LongInt;
end;
/// @struct LineSegment
LineSegment = packed record
startPoint: Point2D;
endPoint: Point2D;
end;
/// @struct Triangle
/// @fixed_array_wrapper
/// @field data: array[0..2] of Point2D
Triangle = array [0..2] of Point2D;
/// @type LinesArray
/// @array_wrapper
/// @field data: LineSegmentPtr
LinesArray = Array of LineSegment;
/// @type TriangleArray
/// @array_wrapper
/// @field data: TrianglePtr
TriangleArray = Array of Triangle;
/// @type TrianglePtr
/// @pointer_wrapper
TrianglePtr = ^Triangle;
/// @type LineSegmentPtr
/// @pointer_wrapper
LineSegmentPtr = ^LineSegment;
/// @struct SoundEffectData
/// @via_pointer
SoundEffectData = packed record
effect: PMix_Chunk;
filename, name: String;
end;
/// The `SoundEffect` type is used to refer to sound effects that can be
/// played by the SwinGame audio code. Sound effects are loaded with
/// `LoadSoundEffect`, played using `PlaySoundEffect`, and must be
/// released using `FreeMusic`.
///
/// SwinGame will mix the audio from multiple sound effects, making it
/// possible to play multiple SoundEffects, or even to play the one
/// SoundEffect multiple times.
///
/// You can check if a SoundEffect is currently playing using
/// `IsSoundEffectPlaying`.
///
/// To stop a SoundEffect playing use `StopSoundEffect`. This will stop all
/// instances of this one sound effect from playing.
///
/// @note Use `Music` for background music for your games.
///
/// @class SoundEffect
/// @pointer_wrapper
/// @field pointer: pointer
SoundEffect = ^SoundEffectData;
/// @struct MusicData
/// @via_pointer
MusicData = packed record
music: PMix_Music;
filename, name: String;
end;
/// The SoundEffect type is used to refer to sound effects that can be
/// played by the SwinGame audio code. Sound effects are loaded with
/// `LoadSoundEffect`, played using `PlaySoundEffect`, and must be
/// released using `FreeMusic`.
///
/// SwinGame will mix the audio from multiple sound effects, making it
/// possible to play multiple SoundEffects, or even to play the one
/// SoundEffect multiple times.
///
/// You can check if a SoundEffect is currently playing using
/// `IsSoundEffectPlaying`.
///
/// To stop a SoundEffect playing use `StopSoundEffect`. This will stop all
/// instances of this one sound effect from playing.
///
/// @note Use `SoundEffect` for the foreground sound effects of for your games.
///
/// @class Music
/// @pointer_wrapper
/// @field pointer: pointer
Music = ^MusicData;
/// In SwinGame, Matrices can be used to combine together a number of
/// operations that need to be performed on Vectors.
///
/// @struct Matrix2D
/// @fixed_array_wrapper
/// @field data: array[0..2,0..2] of Single
/// @sameas Array [0..2,0..2] of Single
Matrix2D = Array [0..2,0..2] of Single;
/// @type SinglePtr
/// @pointer_wrapper
/// @field pointer: ^Single
SinglePtr = ^Single;
/// The CollisionSide enumeration is used to indicate the side a collision
/// has occurred on.
///
/// @enum CollisionSide
CollisionSide = (
Top,
Bottom,
Left,
Right,
TopLeft,
TopRight,
BottomLeft,
BottomRight,
None
);
/// The color type is used within the SwinGameAPI to store color values.
/// The color values are represented as 32bit RGBA values where R stores the
/// color's red component, G stores the green component, B stores the blue
/// component and A stores an alpha value representing the opacity (transparency)
/// of the of the color.
///
/// @type Color
/// @data_wrapper
/// @field data: UInt32
Color = UInt32;
/// @struct AnimationFrame
/// @via_pointer
AnimationFrame = ^AnimationFrameData;
/// @struct AnimationFrameData
/// @via_pointer
AnimationFrameData = packed record
index: LongInt; // The index of the frame in the animation template
cellIndex: LongInt; // Which cell of the current bitmap is drawn
sound: SoundEffect; // Which sound should be played on entry
duration: Single; // How long should this animation frame play for
next: AnimationFrame; // What is the next frame in this animation
end;
/// @note Use AnimationTemplate.
///
/// @struct AnimationTemplateData
/// @via_pointer
AnimationTemplateData = packed record
name: String; // The name of the animation template so it can be retrieved from resources
filename: String; // The filename from which this template was loaded
animationIds: NamedIndexCollection; // The names and ids of the animations. This links to animations.
animations: LongIntArray; // The starting index of the animations in this template.
frames: Array of AnimationFrame; // The frames of the animations within this template.
end;
/// An Animation Template stores a number of animations. Each animation is
/// a list of frames linked together in the order they are to be performed.
/// Each frame has the cell to draw, the duration it should be drawn for and
/// the next frame in the animation. The template can then be used to create
/// a number of animations.
///
/// @class AnimationTemplate
/// @pointer_wrapper
/// @field pointer: pointer
AnimationTemplate = ^AnimationTemplateData;
/// @note Do not use AnimationData directly, use Animation.
/// @struct AnimationData
/// @via_pointer
AnimationData = packed record
firstFrame: AnimationFrame; // Where did it start?
currentFrame: AnimationFrame; // Where is the animation up to
lastFrame: AnimationFrame; // The last frame used, so last image can be drawn
frameTime: Single; // How long have we spent in this frame?
enteredFrame: Boolean; // Did we just enter this frame? (can be used for sound playing)
//hasEnded: Boolean; // Has the animation stopped?
end;
/// @class Animation
/// @pointer_wrapper
/// @field pointer: pointer
Animation = ^AnimationData;
/// Bitmap data stores the data associated with a Bitmap. Each bitmap contains
/// a pointer to the bitmap color information (surface), its width, height,
/// and a mask storing the non-transparent pixels that is used for pixel level
/// collision checking.
///
/// @note Do not use BitmapData directly, use Bitmap.
/// @struct BitmapData
/// @via_pointer
BitmapData = packed record
filename, name: String; // Used for locating bitmaps during load/freeing
surface: PSDL_Surface; // The actual bitmap image
width: LongInt; // The width of the bitmap
height: LongInt; // The height of the bitmap
//Used for bitmaps that are made up of cells
cellW: LongInt; // The width of a cell
cellH: LongInt; // The height of a cell
cellCols: LongInt; // The columns of cells in the bitmap
cellRows: LongInt; // The rows of cells in the bitmap
cellCount: LongInt; // The total number of cells in the bitmap
nonTransparentPixels: Array of Array of Boolean; // Pixel mask used for pixel level collisions
clipStack: Array of Rectangle; // The clipping rectangle history for the bitmap
end;
/// The bitmap type is a pointer to a BitmapData. The BitmapData record
/// contains the data used by the SwinGame API to represent
/// bitmaps. You can create new bitmaps in memory for drawing operatings
/// using the `CreateBitmap` function. This can then be optimised for drawing
/// to the screen using the `OptimiseBitmap` routine. Also see the `DrawBitmap`
/// routines.
///
/// @class Bitmap
/// @pointer_wrapper
/// @field pointer: ^BitmapData
Bitmap = ^BitmapData;
/// A bitmap cell is used to store the cell to draw from a particular bitmap.
///
/// @struct BitmapCell
BitmapCell = record
bmp: Bitmap;
cell: LongInt;
end;
/// The ShapeKind is used to configure the drawing method for a
/// shape. Each of these options provides an alternate way of
/// rendering based upon the shapes points.
///
/// @enum ShapeKind
ShapeKind= (
pkPoint,
pkCircle,
// pkEllipse,
pkLine,
pkTriangle,
pkLineList,
pkLineStrip,
// pkPolygon,
pkTriangleStrip,
pkTriangleFan,
pkTriangleList
);
/// @class ShapePrototype
/// @pointer_wrapper
/// @field pointer: pointer
ShapePrototype = ^ShapePrototypeData;
/// @class Shape
/// @pointer_wrapper
/// @field pointer: pointer
Shape = ^ShapeData;
/// The ShapeDrawingFn is a function pointer that points to a procedure
/// that is capable of drawing a Shape. This is used when the shape
/// is drawn be DrawShape and FillShape.
///
/// @type ShapeDrawingFn
ShapeDrawingFn = procedure(dest: Bitmap; s: Shape; filled: Boolean; const offset:Point2D);
/// @struct ShapePrototypeData
/// @via_pointer
ShapePrototypeData = packed record
points: Point2DArray;
kind: ShapeKind;
shapeCount: LongInt; //the number of shapes using the prototype
drawWith: ShapeDrawingFn;
end;
/// @type ShapeArray
/// @array_wrapper
/// @field data: array of Shape
ShapeArray = Array of Shape;
/// @struct ShapeData
/// @via_pointer
ShapeData = packed record
pt: Point2D;
prototype: ShapePrototype;
color: Color;
scale: Point2D;
angle: single;
ptBuffer: Point2DArray;
subShapes: ShapeArray;
end;
/// Use this with the resource path functions to get the path to a
/// given resource. Using these functions ensures that your resource
/// paths are correct across different platforms
///
/// @enum ResourceKind
ResourceKind = (
BundleResource,
BitmapResource,
FontResource,
MusicResource,
MapResource,
SoundResource,
AnimationResource, //in load order, Animation must be > sound
PanelResource, // Panel must be > sound + bitmap
CharacterResource,
OtherResource
);
/// @enum CollisionTestKind
CollisionTestKind = (
PixelCollisions,
// ShapeCollision,
AABBCollisions
);
/// @struct SpriteData
/// @via_pointer
SpriteData = packed record
layerIds: NamedIndexCollection; // The name <-> ids mapping for layers
layers: Array of Bitmap; // Layers of the sprites
visibleLayers: Array of LongInt; // The indexes of the visible layers
layerOffsets: Array of Point2D; // Offsets from drawing the layers
values: Array of Single; // Values associated with this sprite
valueIds: NamedIndexCollection; // The name <-> ids mappings for values
animationData: Animation; // The data used to animate this sprite
animationTemplate: AnimationTemplate; // The template for this sprite's animations
position: Point2D; // The game location of the sprite
velocity: Vector; // The velocity of the sprite
collisionKind: CollisionTestKind; //The kind of collisions used by this sprite
collisionBitmap: Bitmap; // The bitmap used for collision testing (default to first image)
//add later ->
//collisionShape: Shape; // This can be used in place of pixel level collisions for a Shape
end;
/// Sprites are used to represent Sprites drawn to the screen. Create a
/// sprite using the CreateSprite function, and free it when complete with
/// the FreeSprite function. The sprite contain a number of bitmaps used to
/// store animations, or the like. Sprite drawing operations will draw the
/// Sprite's current frame.
///
/// @class Sprite
/// @pointer_wrapper
/// @field pointer: ^SpriteData
Sprite = ^SpriteData;
/// @struct TimerData
/// @via_pointer
TimerData = packed record
startTicks: UInt32;
pausedTicks: UInt32;
paused: Boolean;
started: Boolean;
end;
/// @class Timer
/// @pointer_wrapper
/// @field pointer: ^TimerData
Timer = ^TimerData;
/// Fonts are used to render text to bitmaps and to the screen.
/// Fonts must be loaded using the CreateFont routine. Also see the
/// DrawText and DrawTextLines routines.
///
/// @class Font
/// @pointer_wrapper
/// @field pointer: pointer
Font = PTTF_Font;
/// Use font styles to set the style of a font. Setting the style is time
/// consuming, so create alternative font variables for each different
/// style you want to work with. Note that these values can be logical
/// ORed together to combine styles, e.g. BoldFont or ItalicFont = both
/// bold and italic.
///
/// @enum FontStyle
FontStyle = (
NormalFont = 0,
BoldFont = 1,
ItalicFont = 2,
UnderlineFont = 4
);
/// Use font alignment for certain drawing operations. With these
/// operations you specify the area to draw in as well as the alignment
/// within that area. See DrawTextLines.
///
/// @enum FontAlignment
FontAlignment = (
AlignLeft = 1,
AlignCenter = 2,
AlignRight = 4
);
/// @type BitmapArray
/// @array_wrapper
/// @field data: array of Bitmap
BitmapArray = array of Bitmap;
/// This type is used for mapping arrays out of the Pascal library
///
/// @type BitmapPtr
/// @pointer_wrapper
/// @field pointer: ^Bitmap
BitmapPtr = ^Bitmap;
/// A mouse can have many different types of buttons. Most people know
/// about the simple Left and Right buttons, but there is also a Middle
/// button (sometimes part of a scoll wheel). Scroll wheel movement is also
/// treated as mouse button "clicks" of either the wheel "up" or "down"
/// buttons.
///
/// @enum MouseButton
MouseButton = (
NoButton,
LeftButton,
MiddleButton,
RightButton,
WheelUpButton,
WheelDownButton,
MouseX1Button,
MouseX2Button
);
/// @enum KeyCode
KeyCode = (
vk_Unknown = 0,
vk_BACKSPACE = 8,
vk_TAB = 9,
vk_CLEAR = 12,
vk_RETURN = 13,
vk_PAUSE = 19,
vk_ESCAPE = 27,
vk_SPACE = 32,
vk_EXCLAIM = 33,
vk_QUOTEDBL = 34,
vk_HASH = 35,
vk_DOLLAR = 36,
vk_AMPERSAND = 38,
vk_QUOTE = 39,
vk_LEFTPAREN = 40,
vk_RIGHTPAREN = 41,
vk_ASTERISK = 42,
vk_PLUS = 43,
vk_COMMA = 44,
vk_MINUS = 45,
vk_PERIOD = 46,
vk_SLASH = 47,
vk_0 = 48,
vk_1 = 49,
vk_2 = 50,
vk_3 = 51,
vk_4 = 52,
vk_5 = 53,
vk_6 = 54,
vk_7 = 55,
vk_8 = 56,
vk_9 = 57,
vk_COLON = 58,
vk_SEMICOLON = 59,
vk_LESS = 60,
vk_EQUALS = 61,
vk_GREATER = 62,
vk_QUESTION = 63,
vk_AT = 64,
// Skip uppercase letters
vk_LEFTBRACKET = 91,
vk_BACKSLASH = 92,
vk_RIGHTBRACKET = 93,
vk_CARET = 94,
vk_UNDERSCORE = 95,
vk_BACKQUOTE = 96,
vk_a = 97,
vk_b = 98,
vk_c = 99,
vk_d = 100,
vk_e = 101,
vk_f = 102,
vk_g = 103,
vk_h = 104,
vk_i = 105,
vk_j = 106,
vk_k = 107,
vk_l = 108,
vk_m = 109,
vk_n = 110,
vk_o = 111,
vk_p = 112,
vk_q = 113,
vk_r = 114,
vk_s = 115,
vk_t = 116,
vk_u = 117,
vk_v = 118,
vk_w = 119,
vk_x = 120,
vk_y = 121,
vk_z = 122,
vk_DELETE = 127,
// End of ASCII mapped keysyms
// International keyboard syms
vk_WORLD_0 = 160, // 0xA0
vk_WORLD_1 = 161,
vk_WORLD_2 = 162,
vk_WORLD_3 = 163,
vk_WORLD_4 = 164,
vk_WORLD_5 = 165,
vk_WORLD_6 = 166,
vk_WORLD_7 = 167,
vk_WORLD_8 = 168,
vk_WORLD_9 = 169,
vk_WORLD_10 = 170,
vk_WORLD_11 = 171,
vk_WORLD_12 = 172,
vk_WORLD_13 = 173,
vk_WORLD_14 = 174,
vk_WORLD_15 = 175,
vk_WORLD_16 = 176,
vk_WORLD_17 = 177,
vk_WORLD_18 = 178,
vk_WORLD_19 = 179,
vk_WORLD_20 = 180,
vk_WORLD_21 = 181,
vk_WORLD_22 = 182,
vk_WORLD_23 = 183,
vk_WORLD_24 = 184,
vk_WORLD_25 = 185,
vk_WORLD_26 = 186,
vk_WORLD_27 = 187,
vk_WORLD_28 = 188,
vk_WORLD_29 = 189,
vk_WORLD_30 = 190,
vk_WORLD_31 = 191,
vk_WORLD_32 = 192,
vk_WORLD_33 = 193,
vk_WORLD_34 = 194,
vk_WORLD_35 = 195,
vk_WORLD_36 = 196,
vk_WORLD_37 = 197,
vk_WORLD_38 = 198,
vk_WORLD_39 = 199,
vk_WORLD_40 = 200,
vk_WORLD_41 = 201,
vk_WORLD_42 = 202,
vk_WORLD_43 = 203,
vk_WORLD_44 = 204,
vk_WORLD_45 = 205,
vk_WORLD_46 = 206,
vk_WORLD_47 = 207,
vk_WORLD_48 = 208,
vk_WORLD_49 = 209,
vk_WORLD_50 = 210,
vk_WORLD_51 = 211,
vk_WORLD_52 = 212,
vk_WORLD_53 = 213,
vk_WORLD_54 = 214,
vk_WORLD_55 = 215,
vk_WORLD_56 = 216,
vk_WORLD_57 = 217,
vk_WORLD_58 = 218,
vk_WORLD_59 = 219,
vk_WORLD_60 = 220,
vk_WORLD_61 = 221,
vk_WORLD_62 = 222,
vk_WORLD_63 = 223,
vk_WORLD_64 = 224,
vk_WORLD_65 = 225,
vk_WORLD_66 = 226,
vk_WORLD_67 = 227,
vk_WORLD_68 = 228,
vk_WORLD_69 = 229,
vk_WORLD_70 = 230,
vk_WORLD_71 = 231,
vk_WORLD_72 = 232,
vk_WORLD_73 = 233,
vk_WORLD_74 = 234,
vk_WORLD_75 = 235,
vk_WORLD_76 = 236,
vk_WORLD_77 = 237,
vk_WORLD_78 = 238,
vk_WORLD_79 = 239,
vk_WORLD_80 = 240,
vk_WORLD_81 = 241,
vk_WORLD_82 = 242,
vk_WORLD_83 = 243,
vk_WORLD_84 = 244,
vk_WORLD_85 = 245,
vk_WORLD_86 = 246,
vk_WORLD_87 = 247,
vk_WORLD_88 = 248,
vk_WORLD_89 = 249,
vk_WORLD_90 = 250,
vk_WORLD_91 = 251,
vk_WORLD_92 = 252,
vk_WORLD_93 = 253,
vk_WORLD_94 = 254,
vk_WORLD_95 = 255, // 0xFF
// Numeric keypad
vk_KP0 = 256,
vk_KP1 = 257,
vk_KP2 = 258,
vk_KP3 = 259,
vk_KP4 = 260,
vk_KP5 = 261,
vk_KP6 = 262,
vk_KP7 = 263,
vk_KP8 = 264,
vk_KP9 = 265,
vk_KP_PERIOD = 266,
vk_KP_DIVIDE = 267,
vk_KP_MULTIPLY = 268,
vk_KP_MINUS = 269,
vk_KP_PLUS = 270,
vk_KP_ENTER = 271,
vk_KP_EQUALS = 272,
// Arrows + Home/End pad
vk_UP = 273,
vk_DOWN = 274,
vk_RIGHT = 275,
vk_LEFT = 276,
vk_INSERT = 277,
vk_HOME = 278,
vk_END = 279,
vk_PAGEUP = 280,
vk_PAGEDOWN = 281,
// Function keys
vk_F1 = 282,
vk_F2 = 283,
vk_F3 = 284,
vk_F4 = 285,
vk_F5 = 286,
vk_F6 = 287,
vk_F7 = 288,
vk_F8 = 289,
vk_F9 = 290,
vk_F10 = 291,
vk_F11 = 292,
vk_F12 = 293,
vk_F13 = 294,
vk_F14 = 295,
vk_F15 = 296,
// Key state modifier keys
vk_NUMLOCK = 300,
vk_CAPSLOCK = 301,
vk_SCROLLOCK = 302,
vk_RSHIFT = 303,
vk_LSHIFT = 304,
vk_RCTRL = 305,
vk_LCTRL = 306,
vk_RALT = 307,
vk_LALT = 308,
vk_RMETA = 309,
vk_LMETA = 310,
vk_LSUPER = 311, // Left "Windows" key
vk_RSUPER = 312, // Right "Windows" key
vk_MODE = 313, // "Alt Gr" key
vk_COMPOSE = 314, // Multi-key compose key
// Miscellaneous function keys
vk_HELP = 315,
vk_PRINT = 316,
vk_SYSREQ = 317,
vk_BREAK = 318,
vk_MENU = 319,
vk_POWER = 320, // Power Macintosh power key
vk_EURO = 321 // Some european keyboards
);
/// @enum MapTag
MapTag = (
MapTag1 = 0, MapTag2 = 1, MapTag3 = 2, MapTag4 = 3, MapTag5 = 4, MapTag6 = 5, MapTag7 = 6, MapTag8 = 7, MapTag9 = 8,
MapTag10 = 9, MapTag11 = 10, MapTag12 = 11, MapTag13 = 12, MapTag14 = 13, MapTag15 = 14, MapTag16 = 15,
MapTag17 = 16, MapTag18 = 17, MapTag19 = 18, MapTag20 = 19, MapTag21 = 20, MapTag22 = 21, MapTag23 = 22,
MapTag24 = 23
);
/// @struct MapTile
MapTile = packed record
xIndex: LongInt;
yIndex: LongInt;
topCorner: Point2D;
pointA: Point2D;
pointB: Point2D;
pointC: Point2D;
pointD: Point2D;
end;
/// @struct MapData
/// @via_pointer
MapData = packed record
Version: LongInt;
MapWidth: LongInt;
MapHeight: LongInt;
BlockWidth: LongInt;
BlockHeight: LongInt;
NumberOfBlocks: LongInt;
NumberOfLayers: LongInt;
NumberOfAnimations: LongInt;
CollisionLayer: LongInt;
TagLayer: LongInt;
GapX: LongInt;
GapY: LongInt;
StaggerX: LongInt;
StaggerY: LongInt;
Isometric: Boolean;
end;
/// @struct MapAnimationData
/// @via_pointer
MapAnimationData = packed record
AnimationNumber: LongInt;
Delay: LongInt;
NumberOfFrames: LongInt;
Frame: Array of LongInt;
CurrentFrame: LongInt;
end;
/// @struct MapLayerData
/// @via_pointer
MapLayerData = packed record
Animation: Array of Array of LongInt;
Value: Array of Array of LongInt;
end;
/// @struct MapCollisionData
/// @via_pointer
MapCollisionData = packed record
Collidable: Array of Array of Boolean;
end;
/// @struct MapTagDetails
/// @via_pointer
MapTagDetails = packed record
x: LongInt;
y: LongInt;
end;
/// @struct MapRecord
/// @via_pointer
MapRecord = packed record
MapInfo: MapData;
AnimationInfo: Array of MapAnimationData;
LayerInfo: Array of MapLayerData;
CollisionInfo: MapCollisionData;
TagInfo: Array [0..23] of Array of MapTagDetails; //TODO: Change to MapTag -> requires parser fixes to detect size
Tiles: Sprite;
Animate: Boolean;
Frame: LongInt;
end;
/// @class Map
/// @pointer_wrapper
/// @field pointer: ^MapRecord
Map = ^MapRecord;
/// The FreeNotifier is a function pointer used to notify user programs of
/// swingame resources being freed. This should not be used by user programs.
///
/// @type FreeNotifier
FreeNotifier = procedure (p: Pointer); cdecl;
//=============================================================================
implementation
//=============================================================================
uses sgShared;
//=============================================================================
initialization
begin
InitialiseSwinGame();
end;
end.
|
unit UOrderedAccountKeysList;
interface
uses
UPascalCoinSafeBox, UThread, Classes, UAccountKey, UOrderedCardinalList, UAccountKeyArray;
type
// This is a class to quickly find accountkeys and their respective account number/s
{ TOrderedAccountKeysList }
TOrderedAccountKeysList = Class
Private
FAutoAddAll : Boolean;
FAccountList : TPCSafeBox;
FOrderedAccountKeysList : TPCThreadList; // An ordered list of pointers to quickly find account keys in account list
FTotalChanges : Integer;
Function Find(lockedList : TList; Const AccountKey: TAccountKey; var Index: Integer): Boolean;
function GetAccountKeyChanges(index : Integer): Integer;
function GetAccountKeyList(index: Integer): TOrderedCardinalList;
function GetAccountKey(index: Integer): TAccountKey;
protected
public
Constructor Create(AccountList : TPCSafeBox; AutoAddAll : Boolean);
Destructor Destroy; override;
// Skybuck: added this for now;
procedure NillifyAccountList;
// Skybuck: moved to here to make it accessable to TPCSafeBox
Procedure ClearAccounts(RemoveAccountList : Boolean);
Procedure AddAccountKey(Const AccountKey : TAccountKey);
Procedure AddAccountKeys(Const AccountKeys : array of TAccountKey);
Procedure RemoveAccountKey(Const AccountKey : TAccountKey);
Procedure AddAccounts(Const AccountKey : TAccountKey; const accounts : Array of Cardinal);
Procedure RemoveAccounts(Const AccountKey : TAccountKey; const accounts : Array of Cardinal);
Function IndexOfAccountKey(Const AccountKey : TAccountKey) : Integer;
Property AccountKeyList[index : Integer] : TOrderedCardinalList read GetAccountKeyList;
Property AccountKey[index : Integer] : TAccountKey read GetAccountKey;
Property AccountKeyChanges[index : Integer] : Integer read GetAccountKeyChanges;
procedure ClearAccountKeyChanges;
Function Count : Integer;
Property SafeBox : TPCSafeBox read FAccountList;
Procedure Clear;
function ToArray : TAccountKeyArray;
function Lock : TList;
procedure Unlock;
function HasAccountKeyChanged : Boolean;
End;
implementation
uses
URawBytes, UPtrInt, UAccountComp, ULog, SysUtils, UCrypto, UConst, UBaseType;
{ TOrderedAccountKeysList }
Type
TOrderedAccountKeyList = Record
rawaccountkey : TRawBytes;
accounts_number : TOrderedCardinalList;
changes_counter : Integer;
end;
POrderedAccountKeyList = ^TOrderedAccountKeyList;
Const
CT_TOrderedAccountKeyList_NUL : TOrderedAccountKeyList = (rawaccountkey:'';accounts_number:Nil;changes_counter:0);
function SortOrdered(Item1, Item2: Pointer): Integer;
begin
Result := PtrInt(Item1) - PtrInt(Item2);
end;
procedure TOrderedAccountKeysList.AddAccountKey(const AccountKey: TAccountKey);
Var P : POrderedAccountKeyList;
i,j : Integer;
lockedList : TList;
begin
lockedList := Lock;
Try
if Not Find(lockedList,AccountKey,i) then begin
New(P);
P^ := CT_TOrderedAccountKeyList_NUL;
P^.rawaccountkey := TAccountComp.AccountKey2RawString(AccountKey);
P^.accounts_number := TOrderedCardinalList.Create;
inc(P^.changes_counter);
inc(FTotalChanges);
lockedList.Insert(i,P);
// Search this key in the AccountsList and add all...
j := 0;
if Assigned(FAccountList) then begin
For i:=0 to FAccountList.AccountsCount-1 do begin
If TAccountComp.EqualAccountKeys(FAccountList.Account(i).accountInfo.accountkey,AccountKey) then begin
// Note: P^.accounts will be ascending ordered due to "for i:=0 to ..."
P^.accounts_number.Add(i);
end;
end;
TLog.NewLog(ltdebug,Classname,Format('Adding account key (%d of %d) %s',[j,FAccountList.AccountsCount,TCrypto.ToHexaString(TAccountComp.AccountKey2RawString(AccountKey))]));
end else begin
TLog.NewLog(ltdebug,Classname,Format('Adding account key (no Account List) %s',[TCrypto.ToHexaString(TAccountComp.AccountKey2RawString(AccountKey))]));
end;
end;
finally
Unlock;
end;
end;
Procedure TOrderedAccountKeysList.AddAccountKeys(Const AccountKeys : array of TAccountKey);
var i : integer;
begin
for i := Low(AccountKeys) to High(AccountKeys) do
AddAccountKey(AccountKeys[i]);
end;
procedure TOrderedAccountKeysList.AddAccounts(const AccountKey: TAccountKey; const accounts: array of Cardinal);
Var P : POrderedAccountKeyList;
i,i2 : Integer;
lockedList : TList;
begin
lockedList := Lock;
Try
if Find(lockedList,AccountKey,i) then begin
P := POrderedAccountKeyList(lockedList[i]);
end else if (FAutoAddAll) then begin
New(P);
P^ := CT_TOrderedAccountKeyList_NUL;
P^.rawaccountkey := TAccountComp.AccountKey2RawString(AccountKey);
P^.accounts_number := TOrderedCardinalList.Create;
lockedList.Insert(i,P);
end else exit;
for i := Low(accounts) to High(accounts) do begin
P^.accounts_number.Add(accounts[i]);
end;
inc(P^.changes_counter);
inc(FTotalChanges);
finally
Unlock;
end;
end;
procedure TOrderedAccountKeysList.Clear;
begin
Lock;
Try
ClearAccounts(true);
FTotalChanges := 1; // 1 = At least 1 change
finally
Unlock;
end;
end;
function TOrderedAccountKeysList.ToArray : TAccountKeyArray;
var i : Integer;
begin
Lock;
Try
SetLength(Result, Count);
for i := 0 to Count - 1 do Result[i] := Self.AccountKey[i];
finally
Unlock;
end;
end;
function TOrderedAccountKeysList.Lock: TList;
begin
Result := FOrderedAccountKeysList.LockList;
end;
procedure TOrderedAccountKeysList.Unlock;
begin
FOrderedAccountKeysList.UnlockList;
end;
function TOrderedAccountKeysList.HasAccountKeyChanged: Boolean;
begin
Result := FTotalChanges>0;
end;
procedure TOrderedAccountKeysList.ClearAccounts(RemoveAccountList : Boolean);
Var P : POrderedAccountKeyList;
i : Integer;
lockedList : TList;
begin
lockedList := Lock;
Try
for i := 0 to lockedList.Count - 1 do begin
P := lockedList[i];
inc(P^.changes_counter);
if RemoveAccountList then begin
P^.accounts_number.Free;
Dispose(P);
end else begin
P^.accounts_number.Clear;
end;
end;
if RemoveAccountList then begin
lockedList.Clear;
end;
FTotalChanges:=lockedList.Count + 1; // At least 1 change
finally
Unlock;
end;
end;
function TOrderedAccountKeysList.Count: Integer;
var lockedList : TList;
begin
lockedList := Lock;
Try
Result := lockedList.Count;
finally
Unlock;
end;
end;
constructor TOrderedAccountKeysList.Create(AccountList : TPCSafeBox; AutoAddAll : Boolean);
Var i : Integer;
begin
TLog.NewLog(ltdebug,Classname,'Creating an Ordered Account Keys List adding all:'+CT_TRUE_FALSE[AutoAddAll]);
FAutoAddAll := AutoAddAll;
FAccountList := AccountList;
FTotalChanges:=0;
FOrderedAccountKeysList := TPCThreadList.Create(ClassName);
if Assigned(AccountList) then begin
Lock;
Try
AccountList.ListOfOrderedAccountKeysList.Add(Self);
if AutoAddAll then begin
for i := 0 to AccountList.AccountsCount - 1 do begin
AddAccountKey(AccountList.Account(i).accountInfo.accountkey);
end;
end;
finally
Unlock;
end;
end;
end;
destructor TOrderedAccountKeysList.Destroy;
begin
TLog.NewLog(ltdebug,Classname,'Destroying an Ordered Account Keys List adding all:'+CT_TRUE_FALSE[FAutoAddAll]);
if Assigned(FAccountList) then begin
FAccountList.ListOfOrderedAccountKeysList.Remove(Self);
end;
ClearAccounts(true);
FreeAndNil(FOrderedAccountKeysList);
inherited;
end;
function TOrderedAccountKeysList.Find(lockedList : TList; const AccountKey: TAccountKey; var Index: Integer): Boolean;
var L, H, I, C: Integer;
rak : TRawBytes;
begin
Result := False;
rak := TAccountComp.AccountKey2RawString(AccountKey);
L := 0;
H := lockedList.Count - 1;
while L <= H do
begin
I := (L + H) shr 1;
C := TBaseType.BinStrComp( POrderedAccountKeyList(lockedList[I]).rawaccountkey, rak );
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
L := I;
end;
end;
end;
Index := L;
end;
function TOrderedAccountKeysList.GetAccountKeyChanges(index : Integer): Integer;
var lockedList : TList;
begin
lockedList := Lock;
Try
Result := POrderedAccountKeyList(lockedList[index])^.changes_counter;
finally
Unlock;
end;
end;
function TOrderedAccountKeysList.GetAccountKey(index: Integer): TAccountKey;
Var raw : TRawBytes;
lockedList : TList;
begin
lockedList := Lock;
Try
raw := POrderedAccountKeyList(lockedList[index]).rawaccountkey;
finally
Unlock;
end;
Result := TAccountComp.RawString2Accountkey(raw);
end;
function TOrderedAccountKeysList.GetAccountKeyList(index: Integer): TOrderedCardinalList;
var lockedList : TList;
begin
lockedList := Lock;
Try
Result := POrderedAccountKeyList(lockedList[index]).accounts_number;
finally
Unlock;
end;
end;
function TOrderedAccountKeysList.IndexOfAccountKey(const AccountKey: TAccountKey): Integer;
var lockedList : TList;
begin
lockedList := Lock;
Try
If Not Find(lockedList,AccountKey,Result) then Result := -1;
finally
Unlock;
end;
end;
procedure TOrderedAccountKeysList.ClearAccountKeyChanges;
var i : Integer;
lockedList : TList;
begin
lockedList := Lock;
Try
for i:=0 to lockedList.Count-1 do begin
POrderedAccountKeyList(lockedList[i])^.changes_counter:=0;
end;
FTotalChanges:=0;
finally
Unlock;
end;
end;
procedure TOrderedAccountKeysList.RemoveAccounts(const AccountKey: TAccountKey; const accounts: array of Cardinal);
Var P : POrderedAccountKeyList;
i,j : Integer;
lockedList : TList;
begin
lockedList := Lock;
Try
if Not Find(lockedList,AccountKey,i) then exit; // Nothing to do
P := POrderedAccountKeyList(lockedList[i]);
inc(P^.changes_counter);
inc(FTotalChanges);
for j := Low(accounts) to High(accounts) do begin
P^.accounts_number.Remove(accounts[j]);
end;
if (P^.accounts_number.Count=0) And (FAutoAddAll) then begin
// Remove from list
lockedList.Delete(i);
// Free it
P^.accounts_number.free;
Dispose(P);
end;
finally
Unlock;
end;
end;
procedure TOrderedAccountKeysList.RemoveAccountKey(const AccountKey: TAccountKey);
Var P : POrderedAccountKeyList;
i,j : Integer;
lockedList : TList;
begin
lockedList := Lock;
Try
if Not Find(lockedList,AccountKey,i) then exit; // Nothing to do
P := POrderedAccountKeyList(lockedList[i]);
inc(P^.changes_counter);
inc(FTotalChanges);
// Remove from list
lockedList.Delete(i);
// Free it
P^.accounts_number.free;
Dispose(P);
finally
Unlock;
end;
end;
procedure TOrderedAccountKeysList.NillifyAccountList;
begin
FAccountList := nil;
end;
end.
|
unit tmsUXlsChart;
{$INCLUDE ..\FLXCOMPILER.INC}
interface
uses tmsUXlsBaseRecords, tmsUXlsBaseRecordLists, tmsUXlsOtherRecords,
tmsXlsMessages, tmsUXlsTokenArray, Classes, SysUtils, tmsUXlsBaseList;
type
TChartRecord = class (TBaseRecord)
end;
TBeginRecord = class(TChartRecord)
end;
TEndRecord = class(TChartRecord)
end;
TChartAIRecord = class (TChartRecord)
private
Flags, FLen: word;
procedure ArrangeTokensInsertRowsAndCols(const InsRowPos, InsRowOffset, CopyRowOffset, InsColPos, InsColOffset, CopyColOffset: integer; const SheetInfo: TSheetInfo);
public
constructor Create(const aId: word; const aData: PArrayOfByte; const aDataSize: integer);override;
procedure ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount:integer; const SheetInfo: TSheetInfo);
procedure ArrangeCopySheet(const SheetInfo: TSheetInfo);
procedure ArrangeCopyRowsAndCols(const RowOffset, ColOffset: integer);
end;
TChartAIRecordCache = class (TBaseList)
{$INCLUDE TChartAIRecordCacheHdr.inc}
constructor Create;
procedure ArrangeCopyRowsAndCols(const RowOffset, ColOffset: integer);
procedure ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount:integer; const SheetInfo: TSheetInfo);
procedure ArrangeCopySheet(const SheetInfo: TSheetInfo);
end;
TChartRecordList = class (TBaseRecordList)
private
AICache: TChartAIRecordCache;
protected
procedure Notify(Ptr: Pointer; Action: TListNotification);override;
public
constructor Create;
destructor Destroy;override;
procedure ArrangeCopyRowsAndCols(const RowOffset, ColOffset: integer);
procedure ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount:integer; const SheetInfo: TSheetInfo);
procedure ArrangeCopySheet(const SheetInfo: TSheetInfo);
end;
implementation
{ TChartAIRecordCache }
{$INCLUDE TChartAIRecordCacheImp.inc}
constructor TChartAIRecordCache.Create;
begin
inherited Create(False) //We don't own the objects
end;
procedure TChartAIRecordCache.ArrangeCopyRowsAndCols(const RowOffset, ColOffset: integer);
var
i: integer;
begin
for i:=0 to Count-1 do Items[i].ArrangeCopyRowsAndCols(RowOffset, ColOffset);
end;
procedure TChartAIRecordCache.ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount: integer;
const SheetInfo: TSheetInfo);
var
i: integer;
begin
for i:=0 to Count-1 do Items[i].ArrangeInsertRowsAndCols(aRowPos, aRowCount, aColPos, aColCount, SheetInfo);
end;
procedure TChartAIRecordCache.ArrangeCopySheet(const SheetInfo: TSheetInfo);
var
i: integer;
begin
for i:=0 to Count-1 do Items[i].ArrangeCopySheet(SheetInfo);
end;
{ TChartAIRecord }
//This shouldn't make sense... all ranges in charts are absolute. This is to support RelativeCharts
procedure TChartAIRecord.ArrangeCopyRowsAndCols(const RowOffset, ColOffset: integer);
const
SheetInfo: TSheetInfo=(InsSheet:-1;FormulaSheet:-1;GetSheet:nil;SetSheet:nil;Names:nil);
begin
if FLen>0 then ArrangeTokensInsertRowsAndCols(0, 0, RowOffset, 0, 0, ColOffset, SheetInfo); //Sheet info doesn't have meaninig on copy
end;
procedure TChartAIRecord.ArrangeTokensInsertRowsAndCols(const InsRowPos, InsRowOffset, CopyRowOffset, InsColPos, InsColOffset, CopyColOffset: integer; const SheetInfo: TSheetInfo);
begin
try
UXlsTokenArray_ArrangeInsertRowsAndCols(Data, 8, 8+FLen, InsRowPos, InsRowOffset, CopyRowOffset, InsColPos, InsColOffset, CopyColOffset, SheetInfo, False);
except
on e: ETokenException do raise Exception.CreateFmt(ErrBadChartFormula,[e.Token]);
else raise;
end; //Except
end;
constructor TChartAIRecord.Create(const aId: word; const aData: PArrayOfByte;
const aDataSize: integer);
begin
inherited;
Flags:=GetWord(Data, 0);
FLen:=GetWord(Data, 6);
end;
procedure TChartAIRecord.ArrangeCopySheet(const SheetInfo: TSheetInfo);
begin
if FLen=0 then exit;
try
UXlsTokenArray_ArrangeInsertSheets(Data, 8, 8+FLen, SheetInfo);
except
on e: ETokenException do raise Exception.CreateFmt(ErrBadChartFormula,[e.Token]);
else raise;
end; //Except
end;
procedure TChartAIRecord.ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount: integer;
const SheetInfo: TSheetInfo);
begin
if FLen>0 then ArrangeTokensInsertRowsAndCols(aRowPos, aRowCount, 0, aColPos, aColCount, 0, SheetInfo);
end;
{ TChartRecordList }
constructor TChartRecordList.Create;
begin
inherited;
AICache:= TChartAIRecordCache.Create;
end;
destructor TChartRecordList.Destroy;
begin
FreeAndNil(AICache);
inherited;
end;
procedure TChartRecordList.ArrangeCopyRowsAndCols(const RowOffset, ColOffset: integer);
begin
AICache.ArrangeCopyRowsAndCols(RowOffset, ColOffset);
end;
procedure TChartRecordList.ArrangeInsertRowsAndCols(const aRowPos, aRowCount, aColPos, aColCount: integer;
const SheetInfo: TSheetInfo);
begin
AICache.ArrangeInsertRowsAndCols(aRowPos, aRowCount, aColPos, aColCount, SheetInfo);
end;
procedure TChartRecordList.ArrangeCopySheet(const SheetInfo: TSheetInfo);
begin
AICache.ArrangeCopySheet(SheetInfo);
end;
procedure TChartRecordList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if (Action = lnDeleted) and (AICache<>nil) then if (TBaseRecord(Ptr) is TChartAIRecord) then
AICache.Delete(AICache.IndexOf(TBaseRecord(Ptr)));
if Action = lnAdded then if (TBaseRecord(Ptr) is TChartAIRecord) then
AICache.Add(TChartAIRecord(Ptr));
inherited Notify(Ptr, Action);
end;
end.
|
unit l3Metafile;
{* Метафайл }
// Модуль: "w:\common\components\rtl\Garant\L3\l3Metafile.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "Tl3Metafile" MUID: (47DFD79200BD)
{$Include w:\common\components\rtl\Garant\L3\l3Define.inc}
interface
uses
l3IntfUses
, Graphics
, l3Interfaces
, Classes
, l3PureMixIns
;
type
_l3Unknown_Parent_ = TMetafile;
{$Include w:\common\components\rtl\Garant\L3\l3Unknown.imp.pas}
Tl3Metafile = class(_l3Unknown_)
{* Метафайл }
protected
procedure Cleanup; override;
{* Функция очистки полей объекта. }
{$If NOT Defined(DesignTimeLibrary)}
class function IsCacheable: Boolean; override;
{* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. }
{$IfEnd} // NOT Defined(DesignTimeLibrary)
public
procedure LoadWMFFromStream(Stream: TStream);
class function TryMakeFromStream(Stream: TStream): Tl3Metafile;
procedure LoadFromIStream(const aStream: IStream);
procedure SaveToIStream(const aStream: IStream);
end;//Tl3Metafile
implementation
uses
l3ImplUses
, Windows
, l3Stream
, SysUtils
, l3Base
, l3Core
, l3MemUtils
, l3Interlocked
, Consts
, l3MetafileHeader
//#UC START# *47DFD79200BDimpl_uses*
//#UC END# *47DFD79200BDimpl_uses*
;
type
THackMetafile = class(TGraphic)
private
FImage: TMetafileImage;
end;//THackMetafile
THackSharedImage = class(TSharedImage)
end;//THackSharedImage
THackImage = class(TSharedImage)
private
FHandle: HENHMETAFILE;
FWidth: Integer;
FHeight: Integer;
FPalette: HPALETTE;
FInch: Word;
end;//THackImage
{$Include w:\common\components\rtl\Garant\L3\l3Unknown.imp.pas}
procedure Tl3Metafile.LoadWMFFromStream(Stream: TStream);
//#UC START# *54BE0C4402DE_47DFD79200BD_var*
const
l3HundredthMMPerInch = 2540;
var
l_MFP : TMetaFilePict;
l_WMF : Tl3MetafileHeader;
l_Length : LongInt;
l_BitMem : Pointer;
l_EMFHeader: TEnhMetaheader;
l_HackImage: THackImage;
//#UC END# *54BE0C4402DE_47DFD79200BD_var*
begin
//#UC START# *54BE0C4402DE_47DFD79200BD_impl*
Clear; // Вызов NewImage...
l_Length := Stream.Size - Stream.Position;
Stream.Read(l_WMF, SizeOf(l_WMF));
Dec(l_Length, SizeOf(Tl3MetafileHeader));
GetMem(l_BitMem, l_Length);
l_HackImage := THackImage(THackMetafile(Self).FImage);
try
Stream.Read(l_BitMem^, l_Length);
if l_WMF.Inch = 0 then
l_WMF.Inch := 96;
l_HackImage.FInch := l_WMF.Inch;
l_HackImage.FWidth := MulDiv(l_WMF.Box.Right - l_WMF.Box.Left, l3HundredthMMPerInch, l_HackImage.FInch);
l_HackImage.FHeight := MulDiv(l_WMF.Box.Bottom - l_WMF.Box.Top, l3HundredthMMPerInch, l_HackImage.FInch);
with l_MFP do
begin
MM := MM_ANISOTROPIC;
xExt := 0;
yExt := 0;
hmf := 0;
end; // with l_MFP do
l_HackImage.FHandle := SetWinMetaFileBits(l_Length, l_BitMem, 0, l_MFP);
if l_HackImage.FHandle = 0 then
raise EInvalidGraphic.CreateRes(@SInvalidMetafile);
// Get the maximum extent actually used by the metafile output
// and re-convert the WMF data using the new extents.
// This helps preserve whitespace margins in l_WMFs
GetEnhMetaFileHeader(l_HackImage.FHandle, Sizeof(l_EMFHeader), @l_EMFHeader);
with l_MFP, l_EMFHeader.rclFrame do
begin
MM := MM_ANISOTROPIC;
xExt := MulDiv(l_HackImage.FWidth, l_HackImage.FInch, l3HundredthMMPerInch);
yExt := MulDiv(l_HackImage.FHeight, l_HackImage.FInch, l3HundredthMMPerInch);
hmf := 0;
end; // with l_MFP, l_EMFHeader.rclFrame do
DeleteEnhMetafile(l_HackImage.FHandle);
l_HackImage.FHandle := SetWinMetaFileBits(l_Length, l_BitMem, 0, l_MFP);
if l_HackImage.FHandle = 0 then
raise EInvalidGraphic.CreateRes(@SInvalidMetafile);
Enhanced := False;
finally
Freemem(l_BitMem, l_Length);
end;
PaletteModified := Palette <> 0;
Changed(Self);
//#UC END# *54BE0C4402DE_47DFD79200BD_impl*
end;//Tl3Metafile.LoadWMFFromStream
class function Tl3Metafile.TryMakeFromStream(Stream: TStream): Tl3Metafile;
//#UC START# *54BE147D004B_47DFD79200BD_var*
function lp_TestEMF(Stream: TStream): Boolean;
var
Size: Longint;
Header: TEnhMetaHeader;
begin
Size := Stream.Size - Stream.Position;
if Size > Sizeof(Header) then
begin
Stream.Read(Header, Sizeof(Header));
Stream.Seek(-Sizeof(Header), soFromCurrent);
end;
Result := (Size > Sizeof(Header)) and
(Header.iType = EMR_HEADER) and (Header.dSignature = ENHMETA_SIGNATURE);
end;
var
l_WMF: Tl3MetafileHeader;
//#UC END# *54BE147D004B_47DFD79200BD_var*
begin
//#UC START# *54BE147D004B_47DFD79200BD_impl*
Result := nil;
Stream.Seek(0, soBeginning);
if lp_TestEMF(Stream) then
begin
Result := Tl3MetaFile.Create;
Result.ReadEMFStream(Stream);
end; // if TestEMF(Stream) then
//#UC END# *54BE147D004B_47DFD79200BD_impl*
end;//Tl3Metafile.TryMakeFromStream
procedure Tl3Metafile.LoadFromIStream(const aStream: IStream);
//#UC START# *47E14DD00013_47DFD79200BD_var*
var
l_Stream : TStream;
//#UC END# *47E14DD00013_47DFD79200BD_var*
begin
//#UC START# *47E14DD00013_47DFD79200BD_impl*
l3IStream2Stream(aStream, l_Stream);
try
LoadFromStream(l_Stream);
finally
FreeAndNil(l_Stream);
end;//try..finally
//#UC END# *47E14DD00013_47DFD79200BD_impl*
end;//Tl3Metafile.LoadFromIStream
procedure Tl3Metafile.SaveToIStream(const aStream: IStream);
//#UC START# *47E14DE302A3_47DFD79200BD_var*
var
l_Stream : TStream;
//#UC END# *47E14DE302A3_47DFD79200BD_var*
begin
//#UC START# *47E14DE302A3_47DFD79200BD_impl*
l3IStream2Stream(aStream, l_Stream);
try
SaveToStream(l_Stream);
finally
FreeAndNil(l_Stream);
end;//try..finally
//#UC END# *47E14DE302A3_47DFD79200BD_impl*
end;//Tl3Metafile.SaveToIStream
procedure Tl3Metafile.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_47DFD79200BD_var*
//#UC END# *479731C50290_47DFD79200BD_var*
begin
//#UC START# *479731C50290_47DFD79200BD_impl*
THackSharedImage(THackMetafile(Self).FImage).Release;
THackMetafile(Self).FImage := nil;
inherited;
//#UC END# *479731C50290_47DFD79200BD_impl*
end;//Tl3Metafile.Cleanup
{$If NOT Defined(DesignTimeLibrary)}
class function Tl3Metafile.IsCacheable: Boolean;
{* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. }
//#UC START# *47A6FEE600FC_47DFD79200BD_var*
//#UC END# *47A6FEE600FC_47DFD79200BD_var*
begin
//#UC START# *47A6FEE600FC_47DFD79200BD_impl*
Result := true;
//#UC END# *47A6FEE600FC_47DFD79200BD_impl*
end;//Tl3Metafile.IsCacheable
{$IfEnd} // NOT Defined(DesignTimeLibrary)
end.
|
unit BaseStockApp;
interface
uses
BaseWinApp, BaseApp, SysUtils,
StockAppPath, db_dealitem,
{$IFDEF DEALINSTANT}
db_quote_instant,
{$ENDIF}
db_stock;
type
TBaseStockAppData = record
StockDB: TDBStock;
end;
TBaseStockApp = class(TBaseWinApp)
protected
fBaseStockAppData: TBaseStockAppData;
function GetPath: TBaseAppPath; override;
function GetStockItemDB: TDBDealItem;
function GetStockIndexDB: TDBDealItem;
{$IFDEF DEALINSTANT}
function GetQuoteInstantDB: TDBQuoteInstant;
{$ENDIF}
function GetStockAppPath: TStockAppPath;
public
constructor Create(AppClassId: AnsiString); override;
destructor Destroy; override;
procedure InitializeDBStockItem(AIsLoadDBStockItemDic: Boolean = True);
procedure InitializeDBStockIndex;
{$IFDEF DEALINSTANT}
procedure InitializeDBQuoteInstant; overload;
procedure InitializeDBQuoteInstant(ADBDealItem: TDBDealItem); overload;
{$ENDIF}
property StockItemDB: TDBDealItem read GetStockItemDB;
property StockIndexDB: TDBDealItem read GetStockIndexDB;
{$IFDEF DEALINSTANT}
property QuoteInstantDB: TDBQuoteInstant read GetQuoteInstantDB;
{$ENDIF}
property StockDB: TDBStock read fBaseStockAppData.StockDB;
property StockAppPath: TStockAppPath read GetStockAppPath;
end;
var
GlobalBaseStockApp: TBaseStockApp = nil;
implementation
uses
define_dealmarket,
define_dealitem,
{$IFDEF DEALINSTANT}
define_stock_quotes_instant,
{$ENDIF}
db_dealitem_Load;
constructor TBaseStockApp.Create(AppClassId: AnsiString);
begin
inherited;
FillChar(fBaseStockAppData, SizeOf(fBaseStockAppData), 0);
fBaseStockAppData.StockDB := TDBStock.Create;
GlobalBaseStockApp := Self;
end;
destructor TBaseStockApp.Destroy;
begin
if GlobalBaseStockApp = Self then
GlobalBaseStockApp := nil;
if nil <> fBaseStockAppData.StockDB then
begin
fBaseStockAppData.StockDB.Free;
fBaseStockAppData.StockDB := nil;
end;
inherited;
end;
function TBaseStockApp.GetPath: TBaseAppPath;
begin
Result := GetStockAppPath;
end;
function TBaseStockApp.GetStockAppPath: TStockAppPath;
begin
if nil = fBaseWinAppData.AppPath then
fBaseWinAppData.AppPath := TStockAppPath.Create(Self);
Result := TStockAppPath(fBaseWinAppData.AppPath);
end;
function TBaseStockApp.GetStockIndexDB: TDBDealItem;
begin
Result := fBaseStockAppData.StockDB.StockIndexDB;
end;
function TBaseStockApp.GetStockItemDB: TDBDealItem;
begin
Result := fBaseStockAppData.StockDB.StockItemDB;
end;
{$IFDEF DEALINSTANT}
function TBaseStockApp.GetQuoteInstantDB: TDBQuoteInstant;
begin
Result := fBaseStockAppData.StockDB.QuoteInstantDB;
end;
{$ENDIF}
procedure TBaseStockApp.InitializeDBStockItem(AIsLoadDBStockItemDic: Boolean = True);
procedure AddIndexStockItem(AMarket, ACode, AName: string; AFirstDate: Word);
var
tmpStockItem: PRT_DealItem;
begin
tmpStockItem := fBaseStockAppData.StockDB.StockIndexDB.AddDealItem(AMarket, ACode);
if nil <> tmpStockItem then
begin
tmpStockItem.FirstDealDate := AFirstDate;
tmpStockItem.Name := AName;
end;
end;
begin
if nil = fBaseStockAppData.StockDB.StockItemDB then
begin
fBaseStockAppData.StockDB.StockItemDB := TDBDealItem.Create(DBType_Item_China, 0);
if AIsLoadDBStockItemDic then
begin
db_dealitem_Load.LoadDBStockItemDic(Self, fBaseStockAppData.StockDB.StockItemDB);
end;
end;
if nil = fBaseStockAppData.StockDB.StockIndexDB then
begin
fBaseStockAppData.StockDB.StockIndexDB := TDBDealItem.Create(DBType_Index_China, 0);
AddIndexStockItem(Market_SH, '999999', '上证', Trunc(EncodeDate(1990, 12, 19)));
//AddIndexStockItem(Market_SH, '000300', '沪深300', Trunc(EncodeDate(2005, 1, 4)));
//AddIndexStockItem(Market_SH, '000016', '上证50');
//AddIndexStockItem(Market_SH, '000010', '上证180');
//AddIndexStockItem(Market_SH, '000903', '中证100');
//AddIndexStockItem(Market_SH, '000905', '中证500');
AddIndexStockItem(Market_SZ, '399001', '深成', Trunc(EncodeDate(1991, 4, 3)));
AddIndexStockItem(Market_SZ, '399005', '中小', Trunc(EncodeDate(2006, 1, 24)));
AddIndexStockItem(Market_SZ, '399006', '创业', Trunc(EncodeDate(2010, 6, 1)));
//AddIndexStockItem(Market_SZ, '399106', '深综');
//AddIndexStockItem(Market_SZ, '399007', '深证300');
//AddIndexStockItem(Market_SZ, '399008', '中小300');
end;
end;
procedure TBaseStockApp.InitializeDBStockIndex;
begin
if nil = fBaseStockAppData.StockDB.StockIndexDB then
begin
fBaseStockAppData.StockDB.StockIndexDB := TDBDealItem.Create(DBType_Index_China, 0);
end;
end;
{$IFDEF DEALINSTANT}
procedure TBaseStockApp.InitializeDBQuoteInstant;
begin
if nil = fBaseStockAppData.StockDB.QuoteInstantDB then
begin
fBaseStockAppData.StockDB.QuoteInstantDB := TDBQuoteInstant.Create(DBType_All_Memory);
end;
end;
procedure TBaseStockApp.InitializeDBQuoteInstant(ADBDealItem: TDBDealItem);
var
i: integer;
tmpDealItem: PRT_DealItem;
tmpInstantQuote: PRT_InstantQuote;
begin
InitializeDBQuoteInstant;
if nil <> ADBDealItem then
begin
for i := 0 to ADBDealItem.RecordCount - 1 do
begin
tmpDealItem := ADBDealItem.Items[i];
tmpInstantQuote := fBaseStockAppData.StockDB.QuoteInstantDB.CheckOutInstantQuote(ADBDealItem.DataSrcID, tmpDealItem.iCode);
tmpInstantQuote.Item := tmpDealItem;
end;
end;
end;
{$ENDIF}
end.
|
unit CompareEditions_Controls;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "View"
// Автор: Люлин А.В.
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/CompareEditions_Controls.pas"
// Начат: 17.08.2009 19:42
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<VCMControls::Category>> F1 Пользовательские сервисы::CompareEditions::View::CompareEditions
//
// Операции специфичные для Сравнения редакций
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If not defined(Admin) AND not defined(Monitorings)}
uses
DocumentUnit
{$If not defined(NoVCM)}
,
vcmInterfaces
{$IfEnd} //not NoVCM
,
Base_Operations_Editions_Controls,
l3CProtoObject,
vcmExternalInterfaces {a}
;
(* Edition = operations(Edition)
{* Редакция }
['{77590ED6-A851-4EE4-A8BB-C9845678E43D}']
operation PrevChange;
{* Предыдущее изменение }
operation NextChange;
{* Следующее изменение }
end;//Edition*)
type
TGotoParaResult = (
{* Результат перехода на параграф }
gtprFail // Неуспешно
, gtprOk // Успешно
, gtprAlready // Уже стояли на этом параграфе
);//TGotoParaResult
(* Document = operations
['{AF1A5DE8-20AA-4177-81A6-8C3BFE9C95C5}']
query OpenEditionLocalLink(const aDocument: IDocument;
aSub: Cardinal);
{* Переход по локальной ссылке на редакцию }
end;//Document*)
(* RightEdition = operations
{* Текущая редакция }
['{5D657D01-C18A-4C17-B92E-5C655BA3BC0F}']
query ReturnToDocument;
{* Вернуться в текст документа }
query SetFocusToText;
{* Устанавливает фокус тексту }
query IsCurrentPara(aPara: Integer): Boolean;
{* Является ли параграф текущим }
end;//RightEdition*)
(* Finder = operations
{* Инструмент для поиска }
['{844484DD-424E-4430-AFED-E88BE3F7DC56}']
query GotoPara(aPara: Integer): TGotoParaResult;
{* Перейти к параграфу по номеру }
query DisableForceDrawFocusRect;
{* Запрещает рисование фокусной рамки }
end;//Finder*)
IDocument_OpenEditionLocalLink_Params = interface(IUnknown)
{* Параметры для операции Document.OpenEditionLocalLink }
['{14D37F98-4FEA-468A-8938-DC976BB1F999}']
function Get_Document: IDocument;
function Get_Sub: Cardinal;
property Document: IDocument
read Get_Document;
{* undefined }
property Sub: Cardinal
read Get_Sub;
{* undefined }
end;//IDocument_OpenEditionLocalLink_Params
Op_Document_OpenEditionLocalLink = class
{* Класс для вызова операции Document.OpenEditionLocalLink }
public
// public methods
class function Call(const aTarget: IvcmEntity;
const aDocument: IDocument;
aSub: Cardinal): Boolean; overload;
{* Вызов операции Document.OpenEditionLocalLink у сущности }
class function Call(const aTarget: IvcmAggregate;
const aDocument: IDocument;
aSub: Cardinal): Boolean; overload;
{* Вызов операции Document.OpenEditionLocalLink у агрегации }
class function Call(const aTarget: IvcmEntityForm;
const aDocument: IDocument;
aSub: Cardinal): Boolean; overload;
{* Вызов операции Document.OpenEditionLocalLink у формы }
class function Call(const aTarget: IvcmContainer;
const aDocument: IDocument;
aSub: Cardinal): Boolean; overload;
{* Вызов операции Document.OpenEditionLocalLink у контейнера }
end;//Op_Document_OpenEditionLocalLink
Op_RightEdition_ReturnToDocument = class
{* Класс для вызова операции RightEdition.ReturnToDocument }
public
// public methods
class function Call(const aTarget: IvcmEntity): Boolean; overload;
{* Вызов операции RightEdition.ReturnToDocument у сущности }
class function Call(const aTarget: IvcmAggregate): Boolean; overload;
{* Вызов операции RightEdition.ReturnToDocument у агрегации }
class function Call(const aTarget: IvcmEntityForm): Boolean; overload;
{* Вызов операции RightEdition.ReturnToDocument у формы }
class function Call(const aTarget: IvcmContainer): Boolean; overload;
{* Вызов операции RightEdition.ReturnToDocument у контейнера }
end;//Op_RightEdition_ReturnToDocument
Op_RightEdition_SetFocusToText = class
{* Класс для вызова операции RightEdition.SetFocusToText }
public
// public methods
class function Call(const aTarget: IvcmEntity): Boolean; overload;
{* Вызов операции RightEdition.SetFocusToText у сущности }
class function Call(const aTarget: IvcmAggregate): Boolean; overload;
{* Вызов операции RightEdition.SetFocusToText у агрегации }
class function Call(const aTarget: IvcmEntityForm): Boolean; overload;
{* Вызов операции RightEdition.SetFocusToText у формы }
class function Call(const aTarget: IvcmContainer): Boolean; overload;
{* Вызов операции RightEdition.SetFocusToText у контейнера }
end;//Op_RightEdition_SetFocusToText
IRightEdition_IsCurrentPara_Params = interface(IUnknown)
{* Параметры для операции RightEdition.IsCurrentPara }
['{C973500C-ADAC-48EB-A19A-E362ADE07D19}']
function Get_Para: Integer;
function Get_ResultValue: Boolean;
procedure Set_ResultValue(aValue: Boolean);
property Para: Integer
read Get_Para;
{* undefined }
property ResultValue: Boolean
read Get_ResultValue
write Set_ResultValue;
{* undefined }
end;//IRightEdition_IsCurrentPara_Params
Op_RightEdition_IsCurrentPara = class
{* Класс для вызова операции RightEdition.IsCurrentPara }
public
// public methods
class function Call(const aTarget: IvcmEntity;
aPara: Integer): Boolean; overload;
{* Вызов операции RightEdition.IsCurrentPara у сущности }
class function Call(const aTarget: IvcmAggregate;
aPara: Integer): Boolean; overload;
{* Вызов операции RightEdition.IsCurrentPara у агрегации }
class function Call(const aTarget: IvcmEntityForm;
aPara: Integer): Boolean; overload;
{* Вызов операции RightEdition.IsCurrentPara у формы }
class function Call(const aTarget: IvcmContainer;
aPara: Integer): Boolean; overload;
{* Вызов операции RightEdition.IsCurrentPara у контейнера }
end;//Op_RightEdition_IsCurrentPara
IFinder_GotoPara_Params = interface(IUnknown)
{* Параметры для операции Finder.GotoPara }
['{C07EBC14-D098-4B33-A28C-40AEBC95BCCC}']
function Get_Para: Integer;
function Get_ResultValue: TGotoParaResult;
procedure Set_ResultValue(aValue: TGotoParaResult);
property Para: Integer
read Get_Para;
{* undefined }
property ResultValue: TGotoParaResult
read Get_ResultValue
write Set_ResultValue;
{* undefined }
end;//IFinder_GotoPara_Params
Op_Finder_GotoPara = class
{* Класс для вызова операции Finder.GotoPara }
public
// public methods
class function Call(const aTarget: IvcmEntity;
aPara: Integer): TGotoParaResult; overload;
{* Вызов операции Finder.GotoPara у сущности }
class function Call(const aTarget: IvcmAggregate;
aPara: Integer): TGotoParaResult; overload;
{* Вызов операции Finder.GotoPara у агрегации }
class function Call(const aTarget: IvcmEntityForm;
aPara: Integer): TGotoParaResult; overload;
{* Вызов операции Finder.GotoPara у формы }
class function Call(const aTarget: IvcmContainer;
aPara: Integer): TGotoParaResult; overload;
{* Вызов операции Finder.GotoPara у контейнера }
end;//Op_Finder_GotoPara
Op_Finder_DisableForceDrawFocusRect = class
{* Класс для вызова операции Finder.DisableForceDrawFocusRect }
public
// public methods
class function Call(const aTarget: IvcmEntity): Boolean; overload;
{* Вызов операции Finder.DisableForceDrawFocusRect у сущности }
class function Call(const aTarget: IvcmAggregate): Boolean; overload;
{* Вызов операции Finder.DisableForceDrawFocusRect у агрегации }
class function Call(const aTarget: IvcmEntityForm): Boolean; overload;
{* Вызов операции Finder.DisableForceDrawFocusRect у формы }
class function Call(const aTarget: IvcmContainer): Boolean; overload;
{* Вызов операции Finder.DisableForceDrawFocusRect у контейнера }
end;//Op_Finder_DisableForceDrawFocusRect
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
const
en_Edition = Base_Operations_Editions_Controls.en_Edition;
en_capEdition = Base_Operations_Editions_Controls.en_capEdition;
op_PrevChange = 'PrevChange';
op_capPrevChange = 'Предыдущее изменение';
op_NextChange = 'NextChange';
op_capNextChange = 'Следующее изменение';
en_Document = 'Document';
en_capDocument = '';
op_OpenEditionLocalLink = 'OpenEditionLocalLink';
op_capOpenEditionLocalLink = 'Переход по локальной ссылке на редакцию';
en_RightEdition = 'RightEdition';
en_capRightEdition = 'Текущая редакция';
op_ReturnToDocument = 'ReturnToDocument';
op_capReturnToDocument = 'Вернуться в текст документа';
op_SetFocusToText = 'SetFocusToText';
op_capSetFocusToText = 'Устанавливает фокус тексту';
op_IsCurrentPara = 'IsCurrentPara';
op_capIsCurrentPara = 'Является ли параграф текущим';
en_Finder = 'Finder';
en_capFinder = 'Инструмент для поиска';
op_GotoPara = 'GotoPara';
op_capGotoPara = 'Перейти к параграфу по номеру';
op_DisableForceDrawFocusRect = 'DisableForceDrawFocusRect';
op_capDisableForceDrawFocusRect = 'Запрещает рисование фокусной рамки';
{$IfEnd} //not Admin AND not Monitorings
implementation
{$If not defined(Admin) AND not defined(Monitorings)}
uses
l3Base {a},
vcmBase {a},
StdRes {a}
;
type
TDocument_OpenEditionLocalLink_Params = class(Tl3CProtoObject, IDocument_OpenEditionLocalLink_Params)
{* Реализация IDocument_OpenEditionLocalLink_Params }
private
// private fields
f_Document : IDocument;
f_Sub : Cardinal;
protected
// realized methods
function Get_Sub: Cardinal;
function Get_Document: IDocument;
protected
// overridden protected methods
procedure ClearFields; override;
public
// public methods
constructor Create(const aDocument: IDocument;
aSub: Cardinal); reintroduce;
{* Конструктор TDocument_OpenEditionLocalLink_Params }
class function Make(const aDocument: IDocument;
aSub: Cardinal): IDocument_OpenEditionLocalLink_Params; reintroduce;
{* Фабрика TDocument_OpenEditionLocalLink_Params }
end;//TDocument_OpenEditionLocalLink_Params
// start class TDocument_OpenEditionLocalLink_Params
constructor TDocument_OpenEditionLocalLink_Params.Create(const aDocument: IDocument;
aSub: Cardinal);
{-}
begin
inherited Create;
f_Document := aDocument;
f_Sub := aSub;
end;//TDocument_OpenEditionLocalLink_Params.Create
class function TDocument_OpenEditionLocalLink_Params.Make(const aDocument: IDocument;
aSub: Cardinal): IDocument_OpenEditionLocalLink_Params;
var
l_Inst : TDocument_OpenEditionLocalLink_Params;
begin
l_Inst := Create(aDocument, aSub);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;
function TDocument_OpenEditionLocalLink_Params.Get_Sub: Cardinal;
{-}
begin
Result := f_Sub;
end;//TDocument_OpenEditionLocalLink_Params.Get_Sub
function TDocument_OpenEditionLocalLink_Params.Get_Document: IDocument;
{-}
begin
Result := f_Document;
end;//TDocument_OpenEditionLocalLink_Params.Get_Document
procedure TDocument_OpenEditionLocalLink_Params.ClearFields;
{-}
begin
f_Document := nil;
inherited;
end;//TDocument_OpenEditionLocalLink_Params.ClearFields
// start class Op_Document_OpenEditionLocalLink
class function Op_Document_OpenEditionLocalLink.Call(const aTarget: IvcmEntity;
const aDocument: IDocument;
aSub: Cardinal): Boolean;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := TvcmExecuteParams.MakeForInternal(TDocument_OpenEditionLocalLink_Params.Make(aDocument,aSub));
aTarget.Operation(TdmStdRes.opcode_Document_OpenEditionLocalLink, l_Params);
with l_Params do
begin
if Done then
begin
Result := true;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_Document_OpenEditionLocalLink.Call
class function Op_Document_OpenEditionLocalLink.Call(const aTarget: IvcmAggregate;
const aDocument: IDocument;
aSub: Cardinal): Boolean;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := TvcmExecuteParams.MakeForInternal(TDocument_OpenEditionLocalLink_Params.Make(aDocument,aSub));
aTarget.Operation(TdmStdRes.opcode_Document_OpenEditionLocalLink, l_Params);
with l_Params do
begin
if Done then
begin
Result := true;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_Document_OpenEditionLocalLink.Call
class function Op_Document_OpenEditionLocalLink.Call(const aTarget: IvcmEntityForm;
const aDocument: IDocument;
aSub: Cardinal): Boolean;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.Entity, aDocument, aSub);
end;//Op_Document_OpenEditionLocalLink.Call
class function Op_Document_OpenEditionLocalLink.Call(const aTarget: IvcmContainer;
const aDocument: IDocument;
aSub: Cardinal): Boolean;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.AsForm, aDocument, aSub);
end;//Op_Document_OpenEditionLocalLink.Call
// start class Op_RightEdition_ReturnToDocument
class function Op_RightEdition_ReturnToDocument.Call(const aTarget: IvcmEntity): Boolean;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := vcmParams;
aTarget.Operation(TdmStdRes.opcode_RightEdition_ReturnToDocument, l_Params);
with l_Params do
begin
if Done then
begin
Result := true;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_RightEdition_ReturnToDocument.Call
class function Op_RightEdition_ReturnToDocument.Call(const aTarget: IvcmAggregate): Boolean;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := vcmParams;
aTarget.Operation(TdmStdRes.opcode_RightEdition_ReturnToDocument, l_Params);
with l_Params do
begin
if Done then
begin
Result := true;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_RightEdition_ReturnToDocument.Call
class function Op_RightEdition_ReturnToDocument.Call(const aTarget: IvcmEntityForm): Boolean;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.Entity);
end;//Op_RightEdition_ReturnToDocument.Call
class function Op_RightEdition_ReturnToDocument.Call(const aTarget: IvcmContainer): Boolean;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.AsForm);
end;//Op_RightEdition_ReturnToDocument.Call
// start class Op_RightEdition_SetFocusToText
class function Op_RightEdition_SetFocusToText.Call(const aTarget: IvcmEntity): Boolean;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := vcmParams;
aTarget.Operation(TdmStdRes.opcode_RightEdition_SetFocusToText, l_Params);
with l_Params do
begin
if Done then
begin
Result := true;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_RightEdition_SetFocusToText.Call
class function Op_RightEdition_SetFocusToText.Call(const aTarget: IvcmAggregate): Boolean;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := vcmParams;
aTarget.Operation(TdmStdRes.opcode_RightEdition_SetFocusToText, l_Params);
with l_Params do
begin
if Done then
begin
Result := true;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_RightEdition_SetFocusToText.Call
class function Op_RightEdition_SetFocusToText.Call(const aTarget: IvcmEntityForm): Boolean;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.Entity);
end;//Op_RightEdition_SetFocusToText.Call
class function Op_RightEdition_SetFocusToText.Call(const aTarget: IvcmContainer): Boolean;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.AsForm);
end;//Op_RightEdition_SetFocusToText.Call
type
TRightEdition_IsCurrentPara_Params = class(Tl3CProtoObject, IRightEdition_IsCurrentPara_Params)
{* Реализация IRightEdition_IsCurrentPara_Params }
private
// private fields
f_Para : Integer;
f_ResultValue : Boolean;
protected
// realized methods
function Get_ResultValue: Boolean;
procedure Set_ResultValue(aValue: Boolean);
function Get_Para: Integer;
public
// public methods
constructor Create(aPara: Integer); reintroduce;
{* Конструктор TRightEdition_IsCurrentPara_Params }
class function Make(aPara: Integer): IRightEdition_IsCurrentPara_Params; reintroduce;
{* Фабрика TRightEdition_IsCurrentPara_Params }
end;//TRightEdition_IsCurrentPara_Params
// start class TRightEdition_IsCurrentPara_Params
constructor TRightEdition_IsCurrentPara_Params.Create(aPara: Integer);
{-}
begin
inherited Create;
f_Para := aPara;
end;//TRightEdition_IsCurrentPara_Params.Create
class function TRightEdition_IsCurrentPara_Params.Make(aPara: Integer): IRightEdition_IsCurrentPara_Params;
var
l_Inst : TRightEdition_IsCurrentPara_Params;
begin
l_Inst := Create(aPara);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;
function TRightEdition_IsCurrentPara_Params.Get_ResultValue: Boolean;
{-}
begin
Result := f_ResultValue;
end;//TRightEdition_IsCurrentPara_Params.Get_ResultValue
procedure TRightEdition_IsCurrentPara_Params.Set_ResultValue(aValue: Boolean);
{-}
begin
f_ResultValue := aValue;
end;//TRightEdition_IsCurrentPara_Params.Set_ResultValue
function TRightEdition_IsCurrentPara_Params.Get_Para: Integer;
{-}
begin
Result := f_Para;
end;//TRightEdition_IsCurrentPara_Params.Get_Para
// start class Op_RightEdition_IsCurrentPara
class function Op_RightEdition_IsCurrentPara.Call(const aTarget: IvcmEntity;
aPara: Integer): Boolean;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := TvcmExecuteParams.MakeForInternal(TRightEdition_IsCurrentPara_Params.Make(aPara));
aTarget.Operation(TdmStdRes.opcode_RightEdition_IsCurrentPara, l_Params);
with l_Params do
begin
if Done then
begin
Result := IRightEdition_IsCurrentPara_Params(Data).ResultValue;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_RightEdition_IsCurrentPara.Call
class function Op_RightEdition_IsCurrentPara.Call(const aTarget: IvcmAggregate;
aPara: Integer): Boolean;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := TvcmExecuteParams.MakeForInternal(TRightEdition_IsCurrentPara_Params.Make(aPara));
aTarget.Operation(TdmStdRes.opcode_RightEdition_IsCurrentPara, l_Params);
with l_Params do
begin
if Done then
begin
Result := IRightEdition_IsCurrentPara_Params(Data).ResultValue;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_RightEdition_IsCurrentPara.Call
class function Op_RightEdition_IsCurrentPara.Call(const aTarget: IvcmEntityForm;
aPara: Integer): Boolean;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.Entity, aPara);
end;//Op_RightEdition_IsCurrentPara.Call
class function Op_RightEdition_IsCurrentPara.Call(const aTarget: IvcmContainer;
aPara: Integer): Boolean;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.AsForm, aPara);
end;//Op_RightEdition_IsCurrentPara.Call
type
TFinder_GotoPara_Params = class(Tl3CProtoObject, IFinder_GotoPara_Params)
{* Реализация IFinder_GotoPara_Params }
private
// private fields
f_Para : Integer;
f_ResultValue : TGotoParaResult;
protected
// realized methods
function Get_ResultValue: TGotoParaResult;
procedure Set_ResultValue(aValue: TGotoParaResult);
function Get_Para: Integer;
public
// public methods
constructor Create(aPara: Integer); reintroduce;
{* Конструктор TFinder_GotoPara_Params }
class function Make(aPara: Integer): IFinder_GotoPara_Params; reintroduce;
{* Фабрика TFinder_GotoPara_Params }
end;//TFinder_GotoPara_Params
// start class TFinder_GotoPara_Params
constructor TFinder_GotoPara_Params.Create(aPara: Integer);
{-}
begin
inherited Create;
f_Para := aPara;
end;//TFinder_GotoPara_Params.Create
class function TFinder_GotoPara_Params.Make(aPara: Integer): IFinder_GotoPara_Params;
var
l_Inst : TFinder_GotoPara_Params;
begin
l_Inst := Create(aPara);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;
function TFinder_GotoPara_Params.Get_ResultValue: TGotoParaResult;
{-}
begin
Result := f_ResultValue;
end;//TFinder_GotoPara_Params.Get_ResultValue
procedure TFinder_GotoPara_Params.Set_ResultValue(aValue: TGotoParaResult);
{-}
begin
f_ResultValue := aValue;
end;//TFinder_GotoPara_Params.Set_ResultValue
function TFinder_GotoPara_Params.Get_Para: Integer;
{-}
begin
Result := f_Para;
end;//TFinder_GotoPara_Params.Get_Para
// start class Op_Finder_GotoPara
class function Op_Finder_GotoPara.Call(const aTarget: IvcmEntity;
aPara: Integer): TGotoParaResult;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := TvcmExecuteParams.MakeForInternal(TFinder_GotoPara_Params.Make(aPara));
aTarget.Operation(TdmStdRes.opcode_Finder_GotoPara, l_Params);
with l_Params do
begin
if Done then
begin
Result := IFinder_GotoPara_Params(Data).ResultValue;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_Finder_GotoPara.Call
class function Op_Finder_GotoPara.Call(const aTarget: IvcmAggregate;
aPara: Integer): TGotoParaResult;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := TvcmExecuteParams.MakeForInternal(TFinder_GotoPara_Params.Make(aPara));
aTarget.Operation(TdmStdRes.opcode_Finder_GotoPara, l_Params);
with l_Params do
begin
if Done then
begin
Result := IFinder_GotoPara_Params(Data).ResultValue;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_Finder_GotoPara.Call
class function Op_Finder_GotoPara.Call(const aTarget: IvcmEntityForm;
aPara: Integer): TGotoParaResult;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.Entity, aPara);
end;//Op_Finder_GotoPara.Call
class function Op_Finder_GotoPara.Call(const aTarget: IvcmContainer;
aPara: Integer): TGotoParaResult;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.AsForm, aPara);
end;//Op_Finder_GotoPara.Call
// start class Op_Finder_DisableForceDrawFocusRect
class function Op_Finder_DisableForceDrawFocusRect.Call(const aTarget: IvcmEntity): Boolean;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := vcmParams;
aTarget.Operation(TdmStdRes.opcode_Finder_DisableForceDrawFocusRect, l_Params);
with l_Params do
begin
if Done then
begin
Result := true;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_Finder_DisableForceDrawFocusRect.Call
class function Op_Finder_DisableForceDrawFocusRect.Call(const aTarget: IvcmAggregate): Boolean;
var
l_Params : IvcmExecuteParams;
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
begin
l_Params := vcmParams;
aTarget.Operation(TdmStdRes.opcode_Finder_DisableForceDrawFocusRect, l_Params);
with l_Params do
begin
if Done then
begin
Result := true;
end;//Done
end;//with l_Params
end;//aTarget <> nil
end;//Op_Finder_DisableForceDrawFocusRect.Call
class function Op_Finder_DisableForceDrawFocusRect.Call(const aTarget: IvcmEntityForm): Boolean;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.Entity);
end;//Op_Finder_DisableForceDrawFocusRect.Call
class function Op_Finder_DisableForceDrawFocusRect.Call(const aTarget: IvcmContainer): Boolean;
{-}
begin
l3FillChar(Result, SizeOf(Result));
if (aTarget <> nil) then
Result := Call(aTarget.AsForm);
end;//Op_Finder_DisableForceDrawFocusRect.Call
{$IfEnd} //not Admin AND not Monitorings
end. |
unit vcmRegister;
{* Модуль для регистрации компонент библиотеки vcm. }
{ Библиотека "vcm" }
{ Автор: Люлин А.В. © }
{ Модуль: vcmRegister - }
{ Начат: 11.03.2003 11:16 }
{ $Id: vcmRegister.pas,v 1.87 2016/07/15 13:18:56 lulin Exp $ }
// $Log: vcmRegister.pas,v $
// Revision 1.87 2016/07/15 13:18:56 lulin
// - собираем DesignTime.
//
// Revision 1.86 2014/08/22 09:45:36 kostitsin
// чиню библиотеки компонент
//
// Revision 1.85 2014/07/02 14:45:33 lulin
// - собираем библиотеки.
//
// Revision 1.84 2014/04/22 14:20:14 lulin
// - переходим от интерфейсов к объектам.
//
// Revision 1.83 2013/08/28 14:29:36 lulin
// - чистка кода.
//
// Revision 1.82 2013/08/26 15:31:47 lulin
// - чистим код.
//
// Revision 1.81 2012/10/18 16:51:07 lulin
// {RequestLink:404363289}
//
// Revision 1.80 2012/08/10 18:19:43 lulin
// {RequestLink:382421301}.
//
// Revision 1.79 2012/07/10 12:27:10 lulin
// {RequestLink:237994598}
//
// Revision 1.78 2012/04/13 19:01:02 lulin
// {RequestLink:237994598}
//
// Revision 1.77 2012/04/13 18:23:02 lulin
// {RequestLink:237994598}
//
// Revision 1.76 2012/04/04 08:57:01 lulin
// {RequestLink:237994598}
//
// Revision 1.75 2011/12/08 16:30:07 lulin
// {RequestLink:273590436}
// - чистка кода.
//
// Revision 1.74 2011/06/27 16:50:23 lulin
// {RequestLink:254944102}.
// - чистим мусорок.
//
// Revision 1.73 2010/09/15 18:15:04 lulin
// {RequestLink:235047275}.
//
// Revision 1.72 2010/07/15 11:40:36 lulin
// {RequestLink:207389954}.
//
// Revision 1.71 2010/06/02 09:54:11 lulin
// {RequestLink:215549303}.
// - вычищаем "ненужный" (скорее протухший) код.
//
// Revision 1.70 2010/04/30 15:15:46 lulin
// {RequestLink:207389954}.
// - чистка комментариев.
//
// Revision 1.69 2010/04/23 16:38:15 lulin
// {RequestLink:159352361}.
//
// Revision 1.68 2010/01/15 18:06:35 lulin
// {RequestLink:178323578}. Хитрым раком, но почти удалось затащить модуль с ресурсами на модель.
//
// Revision 1.67 2009/11/05 18:27:19 lulin
// - избавился от переменных списков параметров.
//
// Revision 1.66 2009/10/14 18:39:51 lulin
// {RequestLink:166855347}.
//
// Revision 1.65 2009/10/12 11:27:17 lulin
// - коммитим после падения CVS.
//
// Revision 1.64 2009/09/17 13:17:28 lulin
// - выделяем класс приложения VCM.
//
// Revision 1.63 2009/09/17 12:33:32 lulin
// - отключаем волшебников форм.
//
// Revision 1.62 2009/07/30 16:43:16 lulin
// - думаем о генерации кусков StdRes.
//
// Revision 1.61 2009/02/20 15:19:04 lulin
// - <K>: 136941122.
//
// Revision 1.60 2009/02/05 15:21:13 lulin
// - подготавливаемся к генерации модулей.
//
// Revision 1.59 2008/12/29 13:20:48 lulin
// - добавляем возможность рисовать главную форму приложения.
//
// Revision 1.58 2008/12/19 09:59:15 lulin
// - <K>: 128288713. Хак для того, чтобы наследоваться от сгенерированных форм.
//
// Revision 1.57 2008/05/29 12:48:41 mmorozov
// - bugfix: свойство UseToolbarOfUserTypeName не очищалось.
//
// Revision 1.56 2008/05/29 12:26:58 mmorozov
// - new: возможность определить от какого типа использовать панель инструментов (CQ: OIT5-28281).
//
// Revision 1.55 2008/04/23 06:48:21 oman
// - new: Новое свойство DefaultStatusForm (cq28922)
//
// Revision 1.54 2007/10/05 11:04:12 oman
// - fix: Отъехал редатор шорткатов
//
// Revision 1.53 2007/05/31 13:53:20 oman
// - fix: Вкладка с галкой на повторную активацию теперь закрывается,
// а не просто переключает навигатор на предыдущую активную
// - переименовано свойство в соответствии со смыслом (cq25230)
//
// Revision 1.52 2007/04/06 06:15:52 oman
// Не собиралась библиотека
//
// Revision 1.51 2007/03/14 06:48:07 mmorozov
// - new: редактор для TvcmMainForm, '_TasksPanelZone';
//
// Revision 1.50 2007/01/26 15:34:44 lulin
// - выделяем сущности с ТОЛЬКО внутренними операциями.
//
// Revision 1.49 2007/01/18 11:47:45 oman
// - new: Локализация библиотек - vcm (cq24078)
//
// Revision 1.48 2006/12/29 09:15:20 lulin
// - bug fix: не всем элементам можно было редактировать горячие клавиши.
//
// Revision 1.47 2005/10/31 10:51:25 lopatkin
// no message
//
// Revision 1.46 2005/09/23 06:50:57 mmorozov
// change: изменен способ определения активных форм при перезагрузке сборки;
//
// Revision 1.45 2005/09/22 16:28:40 mmorozov
// new: редакторы для определения активной формы в коллекциях сборок;
//
// Revision 1.44 2005/09/20 14:08:34 lulin
// - редактор сборки форм от Алексея Денисова.
//
// Revision 1.43 2005/08/03 12:29:25 mmorozov
// rename: OwnerItem -> OwnerForm;
//
// Revision 1.42 2005/08/02 12:40:50 mmorozov
// new: редактор для свойства TvcmFormSetFactory.OwnerItem;
//
// Revision 1.41 2005/07/28 14:29:06 mmorozov
// new: список форм является сортированным;
//
// Revision 1.40 2005/07/26 14:35:54 mmorozov
// new: редактор _TvcmFormSetItemUserTypeProperty;
//
// Revision 1.39 2005/07/25 12:10:15 mmorozov
// new: TvcmProjectFormNameProperty;
// new: регистрация TvcmFormSetFactory, TvcmFormSetFactoryWizard;
//
// Revision 1.38 2005/06/22 06:32:54 mmorozov
// - format code;
//
// Revision 1.37 2005/03/21 13:14:07 am
// change: регистрируем _TvcmPopupMenuPrim в палитре
//
// Revision 1.36 2005/01/20 15:43:29 lulin
// - new behavior: рисуем * перед сущностями с внутренними операциями и ! перед сущностями без операций.
//
// Revision 1.35 2005/01/17 09:30:35 lulin
// - bug fix: не компилировалось.
//
// Revision 1.34 2004/11/15 10:56:39 lulin
// - new behavior: _ExcludeUserTypes теперь в Design-Time показываются в виде строки.
//
// Revision 1.33 2004/10/05 13:32:46 lulin
// - для редактора сущностей/операций добавлено окно для Help'а - на будущее.
//
// Revision 1.32 2004/10/04 09:12:13 demon
// - fix: не работал Drag'n'drop для первой операции в сущности.
//
// Revision 1.31 2004/09/27 15:24:54 lulin
// - bug fix: при редактировании StdRes очищался список операций.
//
// Revision 1.30 2004/09/23 09:17:55 lulin
// - bug fix.
//
// Revision 1.29 2004/09/22 14:32:47 lulin
// - доделан DblClick в коллекции форм (открывает форму). Для этого пришлось завести свойство TvcmFormsCollectionItem.FormFile, т.к. я не нашел как средствами ToolsAPI найти файл от формы проекта.
//
// Revision 1.28 2004/09/22 13:19:15 lulin
// - DblClick в коллекции форм открывает форму.
//
// Revision 1.27 2004/09/21 09:34:15 lulin
// - bug fix: неправильно регистрировался редактор свойства.
//
// Revision 1.26 2004/09/17 16:06:53 lulin
// - сделана возможность переноса операций между сущностями.
//
// Revision 1.24 2004/09/17 08:50:37 lulin
// - редактор сущностей и опреаций теперь полностью работоспособен.
//
// Revision 1.23 2004/09/17 08:10:46 lulin
// - bug fix: неправильно работали удаление/вставка операций, а также отдельной окно с операциями.
//
// Revision 1.22 2004/09/16 15:00:41 lulin
// - в диалоге редактирования сущностей сразу выводим операции текущей сущности.
//
// Revision 1.21 2004/06/10 14:20:27 mmorozov
// new: property editor TvcmMessageCategoryProperty (class TvcmMessagesCollectionItem, propety '_Category');
//
// Revision 1.20 2004/03/20 15:25:40 mmorozov
// new: редактор TvcmFormActivateTypeProperty;
//
// Revision 1.19 2004/03/20 09:46:49 mmorozov
// - переименованы редакторы для свойств _TvcmFormActivate;
// new: используем атрибут свойства paSortList вместо самостоятельной сортировки;
// new: cEmptyUserType заменена на vcm_utAny;
// new: property editor TvcmFormActivateCaptionProperty;
// new: в редакторах _TvcmFormActivateUserTypeProperty и TvcmFormActivateNameProperty логика работы со свойством _TvcmFormActivate.Caption;
//
// Revision 1.18 2004/03/19 13:24:22 mmorozov
// new: редакторы свойств TvcmLinkFormForActivateBaseProperty, TvcmLinkFormForActivateUserTypeProperty, TvcmLinkFormForActivateFormNameProperty;
//
// Revision 1.17 2004/01/14 16:18:20 law
// - new units: vcmBaseOperationState, vcmBaseOperationStates.
//
// Revision 1.16 2004/01/14 14:27:41 law
// - new property editor.
//
// Revision 1.15 2003/11/19 16:38:21 law
// - new: сделан "человеческий" редактор для свойства _ExcludeUserTypes.
//
// Revision 1.14 2003/11/19 11:38:28 law
// - new behavior: регистрируем все сущности и операции в MenuManager'е для дальнейшей централизации редактирования. Само редактирование пока не доделано.
//
// Revision 1.13 2003/10/28 09:07:37 law
// - new prop: TvcmCustomMenuManager.MainMenuItems.
//
// Revision 1.12 2003/10/24 09:22:05 law
// - new prop: TvcmOperationsCollectionItem._Category.
//
// Revision 1.11 2003/10/09 12:50:16 law
// - new prop: TvcmUserTypesCollectionItem.ImageIndex.
//
// Revision 1.10 2003/07/24 11:35:12 law
// - new prop: TvcmEntityForm._ToolbarPos.
//
// Revision 1.9 2003/06/19 15:12:01 law
// - new method: IvcmDispatcher.UpdateStatus.
// - new prop: TvcmMainForm.OnUpdateStatus.
//
// Revision 1.8 2003/06/06 11:41:20 law
// - new methods: IvcmEntityForm.LoadState, SaveState.
// - new prop: TvcmEntityForm.OnLoadState, OnSaveState.
//
// Revision 1.7 2003/06/06 10:32:44 law
// - change: введена новая категория свойств vcm.
//
// Revision 1.6 2003/04/21 15:51:06 law
// - new: реализуем описание зон докинга в TvcmContainerForm - свойство Zones.
//
// Revision 1.5 2003/04/08 15:00:01 law
// - change: новый редактор свойства ImageIndex - с возможностью выбора из большого списка.
//
// Revision 1.4 2003/04/08 10:33:35 law
// - bug fix: был мусор при отсутствии иконки.
//
// Revision 1.3 2003/04/04 12:44:56 law
// - new behavior: теперь иконки рисуются и в инспекторе объекта.
//
// Revision 1.2 2003/04/04 11:29:47 law
// - new behavior: сделана возможность выбора имени модуля, при подписке на события.
//
// Revision 1.1 2003/04/01 12:54:46 law
// - переименовываем MVC в VCM.
//
// Revision 1.19 2003/03/28 15:45:21 law
// - сделан эксперт создания новой формы сущности.
//
// Revision 1.18 2003/03/28 15:24:17 law
// - сделан эксперт создания нового модуля.
//
// Revision 1.17 2003/03/28 11:27:26 law
// - по идее Вована сделал редактор компонента, позволяющий быстро привязывать компонент к сущностям.
//
// Revision 1.16 2003/03/27 17:50:57 law
// - по идее Вована начал делать редактор компонента, позволяющий быстро привязывать компонент к сущностям.
//
// Revision 1.15 2003/03/27 16:50:06 law
// - новая сборка библиотеки.
//
// Revision 1.14 2003/03/27 16:25:48 law
// - сделано более удобное редактирование сущностей и операций в Design-Time.
//
// Revision 1.13 2003/03/27 16:00:52 law
// - сделано более удобное редактирование сущностей и операций в Design-Time.
//
// Revision 1.12 2003/03/27 14:36:53 law
// - new prop: операция теперь имеет картинку.
//
// Revision 1.11 2003/03/25 10:34:25 law
// - new prop: TvcmOperationsCollectionItem.ShortCut.
//
// Revision 1.10 2003/03/21 11:32:12 law
// - change: добавлены редакторы свойства Caption.
//
// Revision 1.9 2003/03/21 10:13:36 law
// - cleanup: удалены модули vcm*Repository.
//
// Revision 1.8 2003/03/18 16:14:33 law
// - change: добавлены редакторы свойств имен сущности, операции и категории сущности.
//
// Revision 1.7 2003/03/14 14:55:47 law
// - new units: vcmBaseMenuManager, vcmMenuManager.
//
// Revision 1.6 2003/03/14 12:20:53 law
// - change: отвязываем vcm от l3.
//
// Revision 1.5 2003/03/13 16:37:22 law
// - change: попытка портировать на Builder.
//
// Revision 1.4 2003/03/13 09:52:03 law
// - new component: TvcmModuleDef.
//
// Revision 1.3 2003/03/12 15:26:21 law
// - new component: _TvcmOperations.
//
// Revision 1.2 2003/03/11 16:24:27 law
// - cleanup.
// - new behavior: добавлен редактор компонента TvcmEntities.
//
// Revision 1.1 2003/03/11 08:37:34 law
// - new unit: vcmEntities.
//
{$Include vcmDefine.inc }
interface
{$IfNDef NoVCM}
procedure Register;
{$EndIf NoVCM}
implementation
{$IfNDef NoVCM}
uses
Types,
Classes,
SysUtils,
StrUtils,
Graphics,
ImgList,
Math,
Controls,
ExtCtrls,
Forms,
TypInfo,
DesignIntf,
DesignEditors,
DesignMenus,
VCLEditors,
ToolsAPI,
ColnEdit,
ToolWin,
ToolWnds,
ComCtrls,
ActnList,
Menus,
afwFacade,
vcmUserControls,
vcmBase,
vcmAction,
vcmBaseCollection,
vcmBaseCollectionItem,
vcmBaseEntities,
vcmBaseEntitiesCollection,
vcmBaseEntitiesCollectionItem,
vcmBaseUserTypesCollectionItem,
vcmBaseMenuManager,
vcmBaseOperationsCollection,
vcmOperationParams,
vcmBaseOperationsCollectionItem,
vcmBaseOperationState,
vcmBaseOperationStates,
vcmContainerForm,
vcmEntities,
vcmEntitiesCollection,
vcmEntitiesCollectionItem,
vcmEntityForm,
//vcmEntityParamsForm,
//vcmEntityWizard,
vcmForm,
vcmFormsCollection,
vcmFormsCollectionItem,
vcmImageListForm,
vcmInterfaces,
vcmMainForm,
vcmMenuItemsCollectionItem,
vcmMenuManager,
vcmMenus,
vcmMessagesCollectionItem,
vcmModule,
vcmApplication,
vcmModuleDef,
//vcmModuleWizard,
//vcmOperationParamsForm,
vcmOperations,
vcmOperationsCollection,
vcmOperationsCollectionItem,
vcmOperationState,
vcmOperationStates,
vcmRepOperationsCollectionItem,
vcmRepositoryEx,
vcmUserTypesCollection,
vcmUserTypesCollectionItem,
vcmFormSetFactory,
//vcmFormSetFactoryWizard,
vcmFormsetFormsCollection,
vcmFormSetFormsCollectionItem,
vcmEntityFormRef,
vcmContainerFormRef,
vcmMainFormRef
;
const
vcmRepeatedActivationBehaviourName: Array [TvcmRepeatedActivationBehaviour] of String =
('Ничего', 'Закрывать', 'Переключать на предыдущую', 'Выполнить если активна');
(*// start class TvcmEntitiesEditor
type
TvcmEntitiesEditor = class(TDefaultEditor)
protected
procedure RunPropertyEditor(const Prop: IProperty);
procedure RunEntityEditor(const Prop: IProperty);
public
procedure ExecuteVerb(Index : Integer); override;
function GetVerb(Index : Integer): string; override;
function GetVerbCount : Integer; override;
procedure Edit; override;
end;//TvcmEntitiesEditor
procedure TvcmEntitiesEditor.Edit;
var
Components: IDesignerSelections;
begin
Components := CreateSelectionList;
Components.Add(Component);
GetComponentProperties(Components, [tkClass], Designer, RunPropertyEditor);
end;
procedure TvcmEntitiesEditor.RunPropertyEditor(const Prop: IProperty);
begin
if SameText(Prop.GetName, 'ENTITIES') then
Prop.Edit;
end;
procedure TvcmEntitiesEditor.RunEntityEditor(const Prop: IProperty);
begin
if SameText(Prop.GetName, 'OPERATIONS') then
Prop.Edit;
end;
procedure TvcmEntitiesEditor.ExecuteVerb(Index: Integer);
var
Components: IDesignerSelections;
begin
if (Index = 0) then
Edit
else if (Index = 1) then
TvcmEntityParams.Execute(GetComponent As TvcmBaseEntities)
else begin
Components := CreateSelectionList;
Components.Add((GetComponent As TvcmBaseEntities).Entities.Items[Index - 2]);
GetComponentProperties(Components, [tkClass], Designer, RunEntityEditor);
end;
end;
function TvcmEntitiesEditor.GetVerb(Index: Integer): string;
begin
if (Index = 0) then
Result := 'Сущности...'
else if (Index = 1) then
Result := 'Добавить сущность...'
else
Result := ((GetComponent As TvcmBaseEntities).Entities.Items[Index - 2] As TvcmBaseEntitiesCollectionItem).Caption;
end;
function TvcmEntitiesEditor.GetVerbCount: Integer;
begin
Result := 2;
Inc(Result, (GetComponent As TvcmBaseEntities).Entities.Count);
end;*)
(*// start class TvcmOperationsEditor
type
TvcmOperationsEditor = class(TDefaultEditor)
protected
procedure RunPropertyEditor(const Prop: IProperty);
procedure RunOperationEditor(const Prop: IProperty);
public
procedure ExecuteVerb(Index : Integer); override;
function GetVerb(Index : Integer): string; override;
function GetVerbCount : Integer; override;
procedure Edit; override;
end;//TvcmOperationsEditor
procedure TvcmOperationsEditor.Edit;
var
Components: IDesignerSelections;
begin
Components := CreateSelectionList;
Components.Add(Component);
GetComponentProperties(Components, [tkClass], Designer, RunPropertyEditor);
end;
procedure TvcmOperationsEditor.RunPropertyEditor(const Prop: IProperty);
begin
if SameText(Prop.GetName, 'OPERATIONS') then
Prop.Edit;
end;
procedure TvcmOperationsEditor.RunOperationEditor(const Prop: IProperty);
begin
if SameText(Prop.GetName, 'ONEXECUTE') then
Prop.Edit;
end;
procedure TvcmOperationsEditor.ExecuteVerb(Index: Integer);
var
Components: IDesignerSelections;
begin
if (Index = 0) then
Edit
else if (Index = 1) then begin
if (TvcmOperationParams.Execute(GetComponent As TvcmCustomOperations) <> nil) then
ExecuteVerb((GetComponent As TvcmCustomOperations).Operations.Count + 1);
end else begin
Components := CreateSelectionList;
Components.Add((GetComponent As TvcmCustomOperations).Operations.Items[Index - 2]);
GetComponentProperties(Components, tkMethods, Designer, RunOperationEditor);
end;
end;
function TvcmOperationsEditor.GetVerb(Index: Integer): string;
begin
if (Index = 0) then
Result := 'Операции...' { Menu item caption for context menu }
else if (Index = 1) then
Result := 'Добавить операцию...'
else
Result := ((GetComponent As TvcmCustomOperations).Operations.Items[Index - 2] As TvcmBaseOperationsCollectionItem).Caption;
end;
function TvcmOperationsEditor.GetVerbCount: Integer;
begin
Result := 2;
Inc(Result, (GetComponent As TvcmCustomOperations).Operations.Count);
end;*)
type
TvcmListedProperty = class(TStringProperty)
public
//public methods
function GetAttributes: TPropertyAttributes;
override;
{-}
end;//TvcmListedProperty
function TvcmListedProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paValueList];
end;
{ TvcmUseToolbarOfUserTypeNameProperty }
type
TvcmUseToolbarOfUserTypeNameProperty = class(TvcmListedProperty)
public
procedure SetValue(const Value: String);
override;
{-}
procedure GetValues(Proc : TGetStrProc);
override;
{-}
function GetValue : String;
override;
{-}
end;
function TvcmUseToolbarOfUserTypeNameProperty.GetValue: String;
var
l_UT : TvcmBaseUserTypesCollectionItem;
l_FoundUT : TvcmBaseUserTypesCollectionItem;
begin
l_UT := GetComponent(0) as TvcmBaseUserTypesCollectionItem;
if l_UT.UseToolbarOfUserTypeName = '' then
Result := l_UT.Caption
else
begin
l_FoundUT := TvcmBaseUserTypesCollectionItem(TvcmBaseCollection(
l_UT.Collection).FindItemByName(l_UT.UseToolbarOfUserTypeName));
if l_FoundUT = nil then
Result := l_UT.Caption
else
Result := l_FoundUT.Caption;
end;
end;
procedure TvcmUseToolbarOfUserTypeNameProperty.GetValues(Proc: TGetStrProc);
var
l_Index : Integer;
l_UTList : TvcmBaseCollection;
l_UT : TvcmBaseUserTypesCollectionItem;
begin
l_UT := GetComponent(0) as TvcmBaseUserTypesCollectionItem;
l_UTList := l_UT.Collection as TvcmBaseCollection;
for l_Index := 0 to Pred(l_UTList.Count) do
with TvcmBaseUserTypesCollectionItem(l_UTList.Items[l_Index]) do
if Name <> l_UT.Name then
// - не добавляем в список редактируемый тип формы;
Proc(Caption);
end;
procedure TvcmUseToolbarOfUserTypeNameProperty.SetValue(const Value: String);
var
l_FoundUT: TvcmBaseUserTypesCollectionItem;
begin
with GetComponent(0) as TvcmBaseUserTypesCollectionItem do
begin
if Value <> '' then
begin
l_FoundUT := TvcmBaseUserTypesCollectionItem(
TvcmBaseCollection(Collection).FindItemByCaption(Value));
if l_FoundUT <> nil then
begin
SetStrValue(l_FoundUT.Name);
Exit;
end;//if l_FoundUT <> nil then
end;//if Value <> '' then
SetStrValue('');
end;//with GetComponent(0) as TvcmBaseUserTypesCollectionItem do
end;//SetValue
{ TvcmProjectFormBaseProperty }
type
TvcmProjectFormBaseProperty = class(TvcmListedProperty)
protected
//protected methods
function GetFormCollectionItem(aName : String) : TvcmFormsCollectionItem;
{-}
end;
function TvcmProjectFormBaseProperty.GetFormCollectionItem(aName : String) : TvcmFormsCollectionItem;
var
lIndex : Integer;
begin
Result := nil;
if Assigned(g_MenuManager) then
begin
for lIndex := 0 to Pred(g_MenuManager.AppForms.Count) do
begin
Result := TvcmFormsCollectionItem(g_MenuManager.AppForms.Items[lIndex]);
if Result.Name = aName then
Break;
Result := nil;
end;
end;
end;
type
TvcmRepeatedActivationBehaviourProperty = class(TvcmProjectFormBaseProperty)
public
function GetValue: String;
override;
procedure SetValue(const Value: String);
override;
procedure GetValues(Proc: TGetStrProc);
override;
end;
{ TvcmRepeatedActivationBehaviorProperty }
function TvcmRepeatedActivationBehaviourProperty.GetValue: String;
begin
with GetComponent(0) As TvcmFormActivate do
Result := vcmRepeatedActivationBehaviourName[RepeatedActivationBehaviour];
end;
procedure TvcmRepeatedActivationBehaviourProperty.GetValues(
Proc: TGetStrProc);
var
l_Behaviour : TvcmRepeatedActivationBehaviour;
begin
for l_Behaviour := Low(TvcmRepeatedActivationBehaviour) to High(TvcmRepeatedActivationBehaviour) do
Proc(vcmRepeatedActivationBehaviourName[l_Behaviour]);
end;
procedure TvcmRepeatedActivationBehaviourProperty.SetValue(
const Value: String);
var
l_Behaviour : TvcmRepeatedActivationBehaviour;
begin
with GetComponent(0) As TvcmFormActivate do
begin
for l_Behaviour := Low(TvcmRepeatedActivationBehaviour) to High(TvcmRepeatedActivationBehaviour) do
if vcmRepeatedActivationBehaviourName[l_Behaviour] = Value then
begin
RepeatedActivationBehaviour := l_Behaviour;
Break;
end;
end;
end;
(*type
TvcmFormActivateUserTypeProperty = class(TvcmProjectFormBaseProperty)
public
//public methods
function GetValue: String;
override;
{-}
procedure SetValue(const Value: String);
override;
{-}
procedure GetValues(Proc: TGetStrProc);
override;
{-}
function GetAttributes: TPropertyAttributes;
override;
{-}
end;
function TvcmFormActivateUserTypeProperty.GetAttributes: TPropertyAttributes;
//override;
begin
Result := inherited GetAttributes + [paValueList];
end;
function TvcmFormActivateUserTypeProperty.GetValue: String;
//override;
var
lForm : TvcmFormsCollectionItem;
begin
with GetComponent(0) As TvcmFormActivate do
begin
{ Установим UserType на случай если Name = '', или UserTypes.Count = 0,
или UserType = cEmptyUserType }
Result := IntToStr(UserType);
{ Имя формы установлено }
if (Name <> '') and (UserType <> vcm_utAny) then
begin
{ Получим TvcmFormsCollectionItem }
lForm := GetFormCollectionItem(Name);
{ Имя пользовательского типа }
if Assigned(lForm) then
Result := lForm.UserTypes[UserType].Caption;
end
end;
end;
procedure TvcmFormActivateUserTypeProperty.SetValue(const Value: String);
//override;
var
lIndex : Integer;
lForm : TvcmFormsCollectionItem;
begin
with GetComponent(0) As TvcmFormActivate do
begin
UserType := vcm_utAny;
Caption := '';
if (Name <> '') then
begin
{ Получим TvcmFormsCollectionItem }
lForm := GetFormCollectionItem(Name);
if Assigned(lForm) then
begin
{ Найдем в пользовательских типах значение }
for lIndex := 0 to Pred(lForm.UserTypes.Count) do
{ Запишем значение }
if lForm.UserTypes.Items[lIndex].Caption = Value then
begin
UserType := lIndex;
Caption := lForm.UserTypes.Items[lIndex].Caption;
Break;
end;
{ Пользовательский тип не найден установим имя формы }
if UserType = vcm_utAny then
Caption := lForm.Caption;
end;
end
end;
end;
procedure TvcmFormActivateUserTypeProperty.GetValues(Proc: TGetStrProc);
//override;
var
lIndex : Integer;
lForm : TvcmFormsCollectionItem;
begin
with GetComponent(0) As TvcmFormActivate do
if (Name <> '') then
begin
lForm := GetFormCollectionItem(Name);
if Assigned(lForm) then
for lIndex := 0 to Pred(lForm.UserTypes.Count) do
Proc(lForm.UserTypes.Items[lIndex].Caption);
end;
end;*)
{ TvcmFormSetItemUserTypeProperty }
(*type
TvcmFormSetItemUserTypeProperty = class(TvcmProjectFormBaseProperty)
{* - редактирование элемента коллекции сборки. }
procedure SetValue(const Value: String);
override;
{-}
procedure GetValues(Proc : TGetStrProc);
override;
{-}
function GetValue : String;
override;
{-}
end;
procedure TvcmFormSetItemUserTypeProperty.SetValue(const Value: String);
// override;
{-}
var
lIndex : Integer;
lForm : TvcmFormsCollectionItem;
begin
with GetComponent(0) As TvcmFormSetFormsCollectionItem do
begin
UserType := vcm_utAny;
if (_FormName <> '') then
begin
{ Получим TvcmFormsCollectionItem }
lForm := GetFormCollectionItem(_FormName);
if Assigned(lForm) then
begin
{ Найдем в пользовательских типах значение }
for lIndex := 0 to Pred(lForm.UserTypes.Count) do
{ Запишем значение }
if lForm.UserTypes.Items[lIndex].Caption = Value then
begin
UserType := lIndex;
Break;
end;
end;
end
end;
end;
procedure TvcmFormSetItemUserTypeProperty.GetValues(Proc : TGetStrProc);
// override;
{-}
var
lIndex : Integer;
lForm : TvcmFormsCollectionItem;
begin
with GetComponent(0) As TvcmFormSetFormsCollectionItem do
if (_FormName <> '') then
begin
lForm := GetFormCollectionItem(_FormName);
if Assigned(lForm) then
for lIndex := 0 to Pred(lForm.UserTypes.Count) do
Proc(lForm.UserTypes.Items[lIndex].Caption);
end;
end;
function TvcmFormSetItemUserTypeProperty.GetValue : String;
// override;
{-}
var
lForm : TvcmFormsCollectionItem;
begin
with GetComponent(0) As TvcmFormSetFormsCollectionItem do
begin
{ Установим UserType на случай если Name = '', или UserTypes.Count = 0,
или UserType = cEmptyUserType }
Result := IntToStr(UserType);
{ Имя формы установлено }
if (_FormName <> '') and (UserType <> vcm_utAny) then
begin
{ Получим TvcmFormsCollectionItem }
lForm := GetFormCollectionItem(_FormName);
{ Имя пользовательского типа }
if Assigned(lForm) then
Result := lForm.UserTypes[UserType].Caption;
end
end;
end;*)
type
TvcmProjectFormNameProperty = class(TvcmListedProperty)
{* - возможность выбора формы проекта. }
// public methods
procedure GetValues(Proc : TGetStrProc);
override;
{-}
function GetAttributes: TPropertyAttributes;
override;
{-}
end;
function TvcmProjectFormNameProperty.GetAttributes: TPropertyAttributes;
// override;
{-}
begin
Result := inherited GetAttributes;
Include(Result, paSortList);
end;
procedure TvcmProjectFormNameProperty.GetValues(Proc : TGetStrProc);
//override;
{-}
var
lIndex : Integer;
begin
if Assigned(g_MenuManager) then
{ Список форм проекта }
for lIndex := 0 to Pred(g_MenuManager.AppForms.Count) do
Proc(g_MenuManager.AppForms.Items[lIndex].Name);
end;
type
TvcmFormActivateNameProperty = class(TvcmProjectFormBaseProperty)
public
//public methods
procedure GetValues(Proc: TGetStrProc);
override;
{-}
procedure SetValue(const Value: String);
override;
{-}
function GetAttributes : TPropertyAttributes;
override;
{-}
end;//TvcmFormActivateName
function TvcmFormActivateNameProperty.GetAttributes : TPropertyAttributes;
//override;
begin
Result := inherited GetAttributes + [paSortList];
end;
procedure TvcmFormActivateNameProperty.SetValue(const Value: String);
//override;
var
lForm : TvcmFormsCollectionItem;
begin
with GetComponent(0) As TvcmFormActivate do
begin
lForm := GetFormCollectionItem(Value);
if Assigned(lForm) then
begin
Name := lForm.Name;
if UserType = vcm_utAny then
Caption := lForm.Caption;
end
else
Name := '';
end;
end;
procedure TvcmFormActivateNameProperty.GetValues(Proc: TGetStrProc);
//override;
var
lIndex : Integer;
begin
if Assigned(g_MenuManager) then
{ Создадим список форм }
for lIndex := 0 to Pred(g_MenuManager.AppForms.Count) do
Proc(TvcmFormsCollectionItem(g_MenuManager.AppForms.Items[lIndex]).
Name);
end;
type
TvcmFormActivateCaptionProperty = class(TStringProperty)
public
//public methods
function GetAttributes: TPropertyAttributes;
override;
{-}
end;
function TvcmFormActivateCaptionProperty.GetAttributes: TPropertyAttributes;
//override;
begin
Result := inherited GetAttributes + [paReadOnly];
end;
(*type
TvcmEntityCategoryProperty = class(TvcmListedProperty)
public
//public methods
procedure GetValues(Proc: TGetStrProc);
override;
{-}
end;//TvcmEntityCategoryProperty
procedure TvcmEntityCategoryProperty.GetValues(Proc: TGetStrProc);
//override;
{-}
var
l_Index : Integer;
begin
for l_Index := 0 to Pred(vcmGetCount(vcm_repEntityCategory)) do
Proc(vcmGetName(vcm_repEntityCategory, l_Index));
for l_Index := 0 to Pred(vcmGetCount(vcm_repEntityCaption)) do
Proc(vcmGetName(vcm_repEntityCaption, l_Index));
end;*)
(*type
TvcmMenuItemsCaptionProperty = class(TvcmListedProperty)
public
//public methods
procedure GetValues(Proc: TGetStrProc);
override;
{-}
end;//TvcmMenuItemsCaptionProperty
procedure TvcmMenuItemsCaptionProperty.GetValues(Proc: TGetStrProc);
//override;
{-}
var
l_Index : Integer;
begin
for l_Index := 0 to Pred(vcmGetCount(vcm_repEntityCategory)) do
Proc(vcmGetName(vcm_repEntityCategory, l_Index));
for l_Index := 0 to Pred(vcmGetCount(vcm_repEntityCaption)) do
Proc(vcmGetName(vcm_repEntityCaption, l_Index));
end;*)
type
TvcmEntityNameProperty = class(TvcmListedProperty)
public
//public methods
procedure GetValues(Proc: TGetStrProc);
override;
{-}
end;//TvcmEntityNameProperty
procedure TvcmEntityNameProperty.GetValues(Proc: TGetStrProc);
//override;
{-}
var
l_Index : Integer;
begin
for l_Index := 0 to Pred(vcmGetCount(vcm_repEntity)) do
Proc(vcmGetName(vcm_repEntity, l_Index));
end;
type
TvcmOperationNameProperty = class(TvcmListedProperty)
public
//public methods
procedure GetValues(Proc: TGetStrProc);
override;
{-}
end;//TvcmOperationNameProperty
procedure TvcmOperationNameProperty.GetValues(Proc: TGetStrProc);
//override;
{-}
var
l_Index : Integer;
begin
for l_Index := 0 to Pred(vcmGetCount(vcm_repOperation)) do
Proc(vcmGetName(vcm_repOperation, l_Index));
end;
type
TvcmModuleNameProperty = class(TvcmListedProperty)
public
//public methods
procedure GetValues(Proc: TGetStrProc);
override;
{-}
end;//TvcmModuleNameProperty
procedure TvcmModuleNameProperty.GetValues(Proc: TGetStrProc);
//override;
{-}
var
l_Index : Integer;
begin
for l_Index := 0 to Pred(vcmGetCount(vcm_repModule)) do
Proc(vcmGetName(vcm_repModule, l_Index));
end;
type
TvcmOperationCaptionProperty = class(TvcmListedProperty)
public
//public methods
procedure GetValues(Proc: TGetStrProc);
override;
{-}
end;//TvcmOperationCaptionProperty
procedure TvcmOperationCaptionProperty.GetValues(Proc: TGetStrProc);
//override;
{-}
var
l_Index : Integer;
begin
for l_Index := 0 to Pred(vcmGetCount(vcm_repOperationCaption)) do
Proc(vcmGetName(vcm_repOperationCaption, l_Index));
end;
type
TvcmEntityCaptionProperty = class(TvcmListedProperty)
public
//public methods
procedure GetValues(Proc: TGetStrProc);
override;
{-}
end;//TvcmEntityCaptionProperty
procedure TvcmEntityCaptionProperty.GetValues(Proc: TGetStrProc);
//override;
{-}
var
l_Index : Integer;
begin
for l_Index := 0 to Pred(vcmGetCount(vcm_repEntityCaption)) do
Proc(vcmGetName(vcm_repEntityCaption, l_Index));
end;
type
TvcmImageIndexProperty = class(TIntegerProperty, ICustomPropertyDrawing, ICustomPropertyListDrawing)
public
// public methods
procedure Edit;
override;
{-}
function GetAttributes: TPropertyAttributes;
override;
{-}
procedure GetValues(Proc: TGetStrProc);
override;
{-}
{ ICustomPropertyListDrawing }
procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas;
var AHeight: Integer);
{-}
procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas;
var AWidth: Integer);
{-}
procedure ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
{-}
{ CustomPropertyDrawing }
procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
end;//TvcmImageIndexProperty
procedure TvcmImageIndexProperty.Edit;
//override;
{-}
begin
TvcmImageList.Execute(Self, vcmGetActionList.Images);
end;
function TvcmImageIndexProperty.GetAttributes: TPropertyAttributes;
//override;
{-}
begin
Result := inherited GetAttributes + [paValueList, paDialog];
end;
procedure TvcmImageIndexProperty.GetValues(Proc: TGetStrProc);
//override;
{-}
var
l_Index : Integer;
l_Images : TCustomImageList;
begin
l_Images := vcmGetActionList.Images;
if (l_Images <> nil) then
for l_Index := -1 to Pred(l_Images.Count) do
Proc(IntToStr(l_Index));
end;
procedure TvcmImageIndexProperty.ListMeasureHeight(const Value: string; ACanvas: TCanvas;
var AHeight: Integer);
var
l_Images : TCustomImageList;
begin
l_Images := vcmGetActionList.Images;
if (l_Images <> nil) then
aHeight := Max(aHeight, l_Images.Height);
end;
procedure TvcmImageIndexProperty.ListMeasureWidth(const Value: string;
ACanvas: TCanvas; var AWidth: Integer);
var
l_Images : TCustomImageList;
begin
l_Images := vcmGetActionList.Images;
if (l_Images <> nil) then
aWidth := aWidth + l_Images.Width;
end;
procedure TvcmImageIndexProperty.ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
var
l_Right : Integer;
l_Index : Integer;
l_Images : TCustomImageList;
begin
l_Right := aRect.Left;
l_Images := vcmGetActionList.Images;
if (l_Images <> nil) then begin
Inc(l_Right, l_Images.Width);
try
l_Index := StrToInt(Value);
except
l_Index := -1;
end;//try..except
aCanvas.FillRect(Rect(ARect.Left, ARect.Top, l_Right, aRect.Bottom));
if (l_Index >= 0) then begin
l_Images.Draw(aCanvas, aRect.Left, aRect.Top, l_Index);
end;//l_Index >= 0
end;//l_Images <> nil
DefaultPropertyListDrawValue(Value, ACanvas, Rect(l_Right, ARect.Top,
ARect.Right, ARect.Bottom), ASelected);
end;
procedure TvcmImageIndexProperty.PropDrawName(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
begin
DefaultPropertyDrawName(Self, ACanvas, ARect);
end;
procedure TvcmImageIndexProperty.PropDrawValue(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
begin
if GetVisualValue <> '' then
ListDrawValue(GetVisualValue, ACanvas, ARect, True{ASelected})
else
DefaultPropertyDrawValue(Self, ACanvas, ARect);
end;
type
TvcmExcludeUserTypeProperty = class(TSetElementProperty)
private
// internal fields
f_Name : String;
public
// public methods
constructor Create(Parent : TPropertyEditor;
AElement : Integer;
const aName : String);
reintroduce;
{-}
function GetName: string;
override;
{-}
end;//TvcmExcludeUserTypeProperty
constructor TvcmExcludeUserTypeProperty.Create(Parent : TPropertyEditor;
AElement : Integer;
const aName : String);
//reintroduce;
{-}
begin
inherited Create(Parent, aElement);
f_Name := aName;
end;
function TvcmExcludeUserTypeProperty.GetName: string;
//override;
{-}
begin
Result := f_Name;
end;
type
TvcmOperationsCollectionEditor = class(TCollectionEditor)
protected
// internal methods
procedure DoShow;
override;
{-}
procedure MakeImages;
{-}
procedure ListView1DoubleClick(Sender: TObject);
{-}
procedure RunPropertyEditor(const Prop: IProperty);
{-}
public
// public methods
constructor Create(anOwner: TComponent);
override;
{-}
procedure ItemsModified(const ADesigner: IDesigner);
override;
{-}
end;//TvcmOperationsCollectionEditor
constructor TvcmOperationsCollectionEditor.Create(anOwner: TComponent);
//override;
{-}
begin
inherited;
ListView1.SmallImages := vcmGetActionList.Images;
ListView1.OnDblClick := ListView1DoubleClick;
end;
procedure TvcmOperationsCollectionEditor.DoShow;
{-}
begin
inherited;
MakeImages;
end;
procedure TvcmOperationsCollectionEditor.MakeImages;
{-}
var
l_Index : Integer;
begin
if (Collection <> nil) then
for l_Index := 0 to Pred(Collection.Count) do
ListView1.Items.Item[l_Index].ImageIndex :=
TvcmBaseOperationsCollectionItem(Collection.Items[l_Index]).ImageIndex;
end;
procedure TvcmOperationsCollectionEditor.ListView1DoubleClick(Sender: TObject);
{-}
var
Components: IDesignerSelections;
begin
if (Collection <> nil) then begin
Components := CreateSelectionList;
Designer.GetSelections(Components);
GetComponentProperties(Components, tkMethods, Designer, RunPropertyEditor);
end;//Collection <> nil
end;
procedure TvcmOperationsCollectionEditor.RunPropertyEditor(const Prop: IProperty);
begin
if SameText(Prop.GetName, 'ONEXECUTE') then
Prop.Edit;
end;
procedure TvcmOperationsCollectionEditor.ItemsModified(const ADesigner: IDesigner);
//override;
{-}
begin
inherited;
MakeImages;
end;
type
TvcmOperationsCollectionProperty = class(TCollectionProperty)
public
// public methods
function GetEditorClass: TCollectionEditorClass;
override;
{-}
end;//TvcmOperationsCollectionProperty
function TvcmOperationsCollectionProperty.GetEditorClass: TCollectionEditorClass;
//override;
{-}
begin
Result := TvcmOperationsCollectionEditor;
end;
type
THackCollectionEditor = class(TToolbarDesignWindow)
private
Panel3: TPanel;
ListView1: TListView;
ImageList1: TImageList;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
AddCmd: TAction;
DeleteCmd: TAction;
MoveUpCmd: TAction;
MoveDownCmd: TAction;
SelectAllCmd: TAction;
N2: TMenuItem;
FClosing: Boolean;
FCollectionPropertyName: string;
FStateLock: Integer;
FItemIDList: TList;
FAddedItemIDList: TList;
FCollectionClassName: string;
end;//THackCollectionEditor
TvcmEntitiesCollectionEditor = class;
TvcmOperationsCollectionEditorEx = class(TvcmOperationsCollectionEditor)
private
// internal fields
f_Entities : TvcmEntitiesCollectionEditor;
protected
// internal methods
procedure DoCreate;
override;
{-}
procedure FormCreate(Sender: TObject);
{-}
procedure AddClick(Sender: TObject);
{-}
procedure DeleteClick(Sender: TObject);
{-}
procedure MoveUpClick(Sender: TObject);
{-}
procedure MoveDownClick(Sender: TObject);
{-}
procedure StartDrag(Sender: TObject; var DragObject: TDragObject);
{-}
procedure EndDrag(Sender, Target: TObject; X, Y: Integer);
{-}
public
// public methods
constructor Create(anOwner : TComponent;
anEntities : TvcmEntitiesCollectionEditor);
reintroduce;
{-}
end;//TvcmOperationsCollectionEditorEx
TvcmEntitiesCollectionEditor = class(TCollectionEditor)
private
// internal fields
f_Lock : Integer;
f_MainPanel : TPanel;
f_OperationsPanel : TPanel;
f_HelpPanel : TPanel;
f_Splitter : TSplitter;
f_HelpSplitter : TSplitter;
f_Operations : TvcmOperationsCollectionEditorEx;
protected
// internal methods
procedure ListView1DragOver(Sender, Source : TObject;
X, Y : Integer;
State : TDragState;
var Accept : Boolean);
{-}
procedure ListView1DragDrop(Sender, Source : TObject;
X, Y : Integer);
{-}
procedure ListView1DoubleClick(Sender: TObject);
{-}
procedure RunPropertyEditor(const Prop: IProperty);
{-}
procedure Activated;
override;
{-}
procedure UpdateOperations;
{-}
procedure EntityChanged(Sender: TObject; Item: TListItem; Selected: Boolean);
{-}
procedure FormResize(Sender: TObject);
{-}
procedure DeleteClick(Sender: TObject);
{-}
procedure MakeOperations;
{-}
procedure DestroyOperations;
{-}
procedure TuneOperations;
{-}
procedure DoShow;
override;
{-}
procedure InitListView;
{-}
procedure DrawEntityItem(Sender : TCustomListView;
Item : TListItem;
Rect : TRect;
State : TOwnerDrawState);
{-}
public
// public methods
constructor Create(anOwner: TComponent);
override;
{-}
end;//TvcmEntitiesCollectionEditor
// start class TvcmOperationsCollectionEditorEx
constructor TvcmOperationsCollectionEditorEx.Create(anOwner : TComponent;
anEntities : TvcmEntitiesCollectionEditor);
//reintroduce;
{-}
begin
inherited Create(anOwner);
f_Entities := anEntities;
DeleteCmd.OnExecute := DeleteClick;
AddCmd.OnExecute := AddClick;
MoveUpCmd.OnExecute := MoveUpClick;
MoveDownCmd.OnExecute := MoveDownClick;
ListView1.OnStartDrag := StartDrag;
ListView1.OnEndDrag := EndDrag;
end;
procedure TvcmOperationsCollectionEditorEx.DoCreate;
//override;
{-}
begin
OnCreate := FormCreate;
inherited;
end;
procedure TvcmOperationsCollectionEditorEx.FormCreate(Sender: TObject);
{-}
begin
THackCollectionEditor(Self).FItemIdList := TList.Create;
end;
procedure TvcmOperationsCollectionEditorEx.AddClick(Sender: TObject);
{-}
begin
Inc(f_Entities.f_Lock);
try
inherited;
finally
Dec(f_Entities.f_Lock);
end;//try..finally
end;
procedure TvcmOperationsCollectionEditorEx.DeleteClick(Sender: TObject);
{-}
begin
Inc(f_Entities.f_Lock);
try
inherited;
finally
Dec(f_Entities.f_Lock);
end;//try..finally
end;
procedure TvcmOperationsCollectionEditorEx.MoveUpClick(Sender: TObject);
{-}
begin
Inc(f_Entities.f_Lock);
try
inherited;
finally
Dec(f_Entities.f_Lock);
end;//try..finally
end;
procedure TvcmOperationsCollectionEditorEx.MoveDownClick(Sender: TObject);
{-}
begin
Inc(f_Entities.f_Lock);
try
inherited;
finally
Dec(f_Entities.f_Lock);
end;//try..finally
end;
procedure TvcmOperationsCollectionEditorEx.StartDrag(Sender: TObject; var DragObject: TDragObject);
{-}
begin
Inc(f_Entities.f_Lock);
end;
procedure TvcmOperationsCollectionEditorEx.EndDrag(Sender, Target: TObject; X, Y: Integer);
{-}
begin
Dec(f_Entities.f_Lock);
end;
// start class TvcmEntitiesCollectionEditor
constructor TvcmEntitiesCollectionEditor.Create(anOwner: TComponent);
//override;
{-}
begin
inherited;
DeleteCmd.OnExecute := DeleteClick;
ListView1.OnDblClick := ListView1DoubleClick;
ListView1.Align := alNone;
ListView1.Width := 10;
ListView1.Height := 10;
ListView1.OnSelectItem := EntityChanged;
ListView1.OnDragOver := ListView1DragOver;
ListView1.OnDragDrop := ListView1DragDrop;
OnResize := FormResize;
PopupMenu := nil;
ListView1.PopupMenu := PopupMenu1;
f_MainPanel := TPanel.Create(Self);
f_MainPanel.Align := alClient;
f_MainPanel.Parent := Self;
ListView1.Parent := f_MainPanel;
f_OperationsPanel := TPanel.Create(Self);
f_OperationsPanel.Align := alRight;
f_OperationsPanel.Width := Width div 2;
f_OperationsPanel.Parent := f_MainPanel;
f_Splitter := TSplitter.Create(Self);
f_Splitter.Align := alRight;
f_Splitter.Parent := f_MainPanel;
f_Splitter.Left := f_MainPanel.Width - f_OperationsPanel.Width;
f_HelpPanel := TPanel.Create(Self);
f_HelpPanel.Align := alBottom;
f_HelpPanel.Width := Height div 4;
f_HelpPanel.Parent := Self;
f_HelpPanel.Caption := 'Это панель на будующее - для документирования элементов.';
f_HelpSplitter := TSplitter.Create(Self);
f_HelpSplitter.Align := alBottom;
f_HelpSplitter.Parent := Self;
f_Splitter.Top := Height - f_HelpPanel.Height;
ListView1.Align := alClient;
ListView1.OnDrawItem := DrawEntityItem;
MakeOperations;
end;
procedure TvcmEntitiesCollectionEditor.EntityChanged(Sender: TObject; Item: TListItem; Selected: Boolean);
{-}
begin
if (f_Lock = 0) then
UpdateOperations;
end;
procedure TvcmEntitiesCollectionEditor.FormResize(Sender: TObject);
{-}
begin
if (f_OperationsPanel <> nil) then
f_OperationsPanel.Width := Width div 2;
end;
procedure TvcmEntitiesCollectionEditor.DeleteClick(Sender: TObject);
{-}
begin
DestroyOperations;
inherited;
MakeOperations;
TuneOperations;
end;
procedure TvcmEntitiesCollectionEditor.MakeOperations;
{-}
begin
if (f_Operations = nil) then
f_Operations := TvcmOperationsCollectionEditorEx.Create(Self, Self);
end;
procedure TvcmEntitiesCollectionEditor.DestroyOperations;
{-}
begin
FreeAndNil(f_Operations);
end;
procedure TvcmEntitiesCollectionEditor.TuneOperations;
{-}
begin
if (f_Operations <> nil) then
begin
if (Collection <> nil) AND (Collection.Count > 0) then
begin
f_OperationsPanel.Width := Width div 2;
f_Operations.Options := [coAdd, coDelete, coMove];
f_Operations.Designer := Designer;
UpdateOperations;
f_Operations.ListView1.PopupMenu := f_Operations.PopupMenu1;
f_Operations.ListView1.Parent := f_OperationsPanel;
f_Operations.ToolBar1.Parent := f_OperationsPanel;
//f_OperationsPanel.ManualDock(f_Operations)
end//Collection.Count > 0
else
begin
f_Operations.Collection := nil;
f_Operations.ListView1.Clear;
end;//Collection <> nil..
end;//f_Operations <> nil
end;
procedure TvcmEntitiesCollectionEditor.DoShow;
//override;
{-}
begin
inherited;
//InitListView;
end;
procedure TvcmEntitiesCollectionEditor.InitListView;
{-}
var
l_Index : Integer;
begin
if (Collection <> nil) then
for l_Index := 0 to Pred(Collection.Count) do
begin
with TvcmEntitiesCollectionItem(Collection.Items[l_Index]) do
begin
if HasInternalOperations then
begin
if HasOnlyInternalOperations then
ListView1.Items.Item[l_Index].Caption := '#' + Caption
else
ListView1.Items.Item[l_Index].Caption := '*' + Caption
end//HasInternalOperations
else
if (Operations = nil) OR (Operations.Count = 0) then
ListView1.Items.Item[l_Index].Caption := '!' + Caption
else
ListView1.Items.Item[l_Index].Caption := Caption;
end;//with TvcmEntitiesCollectionItem(Collection.Items[l_Index])
end;//for l_Index..
end;
procedure TvcmEntitiesCollectionEditor.DrawEntityItem(Sender : TCustomListView;
Item : TListItem;
Rect : TRect;
State : TOwnerDrawState);
{-}
begin
Sender.Canvas.FillRect(Rect);
//Sender.Canvas.Font.Color := clRed;
Sender.Canvas.TextOut(Rect.Left + 2, Rect.Top, Item.Caption);
end;
procedure TvcmEntitiesCollectionEditor.UpdateOperations;
{-}
begin
if (f_Operations = nil) then
Exit;
if (ListView1.ItemIndex < 0) then
Exit;
if (Collection = nil) then
begin
f_Operations.Collection := nil;
f_Operations.ListView1.Clear;
Exit;
end;//Collection = nil
f_Operations.Collection := TvcmBaseEntitiesCollectionItem(Collection.Items[ListView1.ItemIndex]).Operations;
f_Operations.Component := Component;
f_Operations.CollectionPropertyName := 'Operations';
THackCollectionEditor(f_Operations).FCollectionClassName := TvcmBaseEntitiesCollectionItem(Collection.Items[0]).Operations.ClassName;
f_Operations.UpdateListBox;
f_Operations.MakeImages;
end;
procedure TvcmEntitiesCollectionEditor.Activated;
//override;
{-}
begin
InitListView;
TuneOperations;
inherited;
end;
procedure TvcmEntitiesCollectionEditor.ListView1DragOver(Sender, Source : TObject;
X, Y : Integer;
State : TDragState;
var Accept : Boolean);
{-}
var
Item: TListItem;
begin
inherited;
if not Accept AND (f_Operations <> nil) then
begin
// - проверим - уж не операция ли это
Item := ListView1.GetItemAt(X, Y);
Accept := (Item <> nil) and (Source = f_Operations.ListView1) and
(not Item.Selected);
end;//not Accept
end;
procedure TvcmEntitiesCollectionEditor.ListView1DragDrop(Sender, Source : TObject;
X, Y : Integer);
{-}
var
l_OpIndex : Integer;
l_OpItem : TCollectionItem;
l_EnItem : TvcmBaseEntitiesCollectionItem;
l_Item : TListItem;
begin
if (f_Operations <> nil) AND (Source = f_Operations.ListView1) AND
(f_Operations.ListView1.ItemIndex >= 0) then
begin
l_OpIndex := f_Operations.ListView1.ItemIndex;
if (l_OpIndex >= 0) then
begin
Inc(f_Lock);
try
l_OpItem := f_Operations.Collection.Items[l_OpIndex];
if (l_OpItem <> nil) then
begin
l_Item := ListView1.GetItemAt(X, Y);
if (l_Item <> nil) then
begin
l_EnItem := TvcmBaseEntitiesCollectionItem(Collection.Items[l_Item.Index]);
if (l_EnItem <> nil) then
begin
l_EnItem.Operations.Add.Assign(l_OpItem);
f_Operations.Collection.Delete(l_OpIndex);
end;//l_EnItem <> nil
end;//l_Item <> nil
end;//l_OpItem <> nil
finally
Dec(f_Lock);
end;//try..finally
UpdateOperations;
end;//f_Operations.ListView1.ItemIndex > 0
end//f_Operations <> nil
else
inherited;
end;
procedure TvcmEntitiesCollectionEditor.ListView1DoubleClick(Sender: TObject);
{-}
var
Components: IDesignerSelections;
begin
if (Collection <> nil) then begin
Components := CreateSelectionList;
Designer.GetSelections(Components);
GetComponentProperties(Components, [tkClass], Designer, RunPropertyEditor);
end;//Collection <> nil
end;
procedure TvcmEntitiesCollectionEditor.RunPropertyEditor(const Prop: IProperty);
begin
if SameText(Prop.GetName, 'OPERATIONS') then
Prop.Edit;
end;
type
TvcmEntitiesCollectionProperty = class(TCollectionProperty)
public
// public methods
function GetEditorClass: TCollectionEditorClass;
override;
{-}
end;//TvcmEntitiesCollectionProperty
function TvcmEntitiesCollectionProperty.GetEditorClass: TCollectionEditorClass;
//override;
{-}
begin
Result := TvcmEntitiesCollectionEditor;
end;
type
TvcmFormsCollectionEditor = class(TCollectionEditor)
protected
// internal methods
procedure DoShow;
override;
{-}
procedure ListView1DoubleClick(Sender: TObject);
{-}
public
// public methods
constructor Create(anOwner: TComponent);
override;
{-}
end;//TvcmFormsCollectionEditor
constructor TvcmFormsCollectionEditor.Create(anOwner: TComponent);
//override;
{-}
begin
inherited;
ListView1.SmallImages := vcmGetActionList.Images;
ListView1.OnDblClick := ListView1DoubleClick;
end;
procedure TvcmFormsCollectionEditor.DoShow;
{-}
begin
inherited;
end;
procedure TvcmFormsCollectionEditor.ListView1DoubleClick(Sender: TObject);
{-}
var
l_Name : String;
l_M : IOTAModule;
l_E : IOTAEditor;
//l_A : IOTAActionServices;
begin
if (ListView1.ItemIndex >= 0) then
begin
l_Name := TvcmFormsCollectionItem
(Collection.Items[ListView1.ItemIndex]).Name;
l_M := vcmGetTAModules.FindFormModule(l_Name);
if (l_M <> nil) then
begin
if (l_M.ModuleFileCount > 0) then
begin
l_E := l_M.ModuleFileEditors[0];
if (l_E <> nil) then
begin
l_E.Show;
Exit;
end;//l_E <> nil
end;//l_M.ModuleFileCount > 0
end;//l_M <> nil
(* if Supports(vcmGetTAModules, IOTAActionServices, l_A) then
begin
l_Name := g_MenuManager.UnitPath;
if not ANSIEndsText('\', l_Name) then
l_Name := l_Name + '\';
l_Name := l_Name + TvcmFormsCollectionItem(Collection.Items[ListView1.ItemIndex]).FormFile;
l_A.OpenFile(l_Name);
end;//Supports(vcmGetTAModules, IOTAActionServices, l_A)*)
end;//ListView1.ItemIndex > 0
end;
type
TvcmFormsCollectionProperty = class(TCollectionProperty)
public
// public methods
function GetEditorClass: TCollectionEditorClass;
override;
{-}
end;//TvcmFormsCollectionProperty
function TvcmFormsCollectionProperty.GetEditorClass: TCollectionEditorClass;
//override;
{-}
begin
Result := TvcmFormsCollectionEditor;
end;
type
TvcmOperationStatesEditor = class(TCollectionEditor)
protected
// internal methods
procedure DoShow;
override;
{-}
procedure MakeImages;
{-}
procedure ListView1DoubleClick(Sender: TObject);
{-}
procedure RunPropertyEditor(const Prop: IProperty);
{-}
public
// public methods
constructor Create(anOwner: TComponent);
override;
{-}
procedure ItemsModified(const ADesigner: IDesigner);
override;
{-}
end;//TvcmOperationStatesEditor
constructor TvcmOperationStatesEditor.Create(anOwner: TComponent);
//override;
{-}
begin
inherited;
ListView1.SmallImages := vcmGetActionList.Images;
ListView1.OnDblClick := ListView1DoubleClick;
end;
procedure TvcmOperationStatesEditor.DoShow;
{-}
begin
inherited;
MakeImages;
end;
procedure TvcmOperationStatesEditor.MakeImages;
{-}
var
l_Index : Integer;
begin
if (Collection <> nil) then
for l_Index := 0 to Pred(Collection.Count) do
ListView1.Items.Item[l_Index].ImageIndex :=
TvcmBaseOperationState(Collection.Items[l_Index]).ImageIndex;
end;
procedure TvcmOperationStatesEditor.ListView1DoubleClick(Sender: TObject);
{-}
var
Components: IDesignerSelections;
begin
if (Collection <> nil) then begin
Components := CreateSelectionList;
Designer.GetSelections(Components);
GetComponentProperties(Components, tkProperties, Designer, RunPropertyEditor);
end;//Collection <> nil
end;
procedure TvcmOperationStatesEditor.RunPropertyEditor(const Prop: IProperty);
begin
if SameText(Prop.GetName, 'IMAGEINDEX') then
Prop.Edit;
end;
procedure TvcmOperationStatesEditor.ItemsModified(const ADesigner: IDesigner);
//override;
{-}
begin
inherited;
MakeImages;
end;
type
TvcmOperationStatesProperty = class(TCollectionProperty)
public
// public methods
function GetEditorClass: TCollectionEditorClass;
override;
{-}
end;//TvcmOperationStatesProperty
function TvcmOperationStatesProperty.GetEditorClass: TCollectionEditorClass;
//override;
{-}
begin
Result := TvcmOperationStatesEditor;
end;
type
TvcmUserTypesCollectionEditor = class(TCollectionEditor)
protected
// internal methods
procedure DoShow;
override;
{-}
procedure MakeImages;
{-}
procedure ListView1DoubleClick(Sender: TObject);
{-}
procedure RunPropertyEditor(const Prop: IProperty);
{-}
public
// public methods
constructor Create(anOwner: TComponent);
override;
{-}
procedure ItemsModified(const ADesigner: IDesigner);
override;
{-}
end;//TvcmUserTypesCollectionEditor
constructor TvcmUserTypesCollectionEditor.Create(anOwner: TComponent);
//override;
{-}
begin
inherited;
ListView1.SmallImages := vcmGetActionList.Images;
ListView1.OnDblClick := ListView1DoubleClick;
end;
procedure TvcmUserTypesCollectionEditor.DoShow;
{-}
begin
inherited;
MakeImages;
end;
procedure TvcmUserTypesCollectionEditor.MakeImages;
{-}
var
l_Index : Integer;
begin
if (Collection <> nil) then
for l_Index := 0 to Pred(Collection.Count) do
ListView1.Items.Item[l_Index].ImageIndex :=
TvcmUserTypesCollectionItem(Collection.Items[l_Index]).ImageIndex;
end;
procedure TvcmUserTypesCollectionEditor.ListView1DoubleClick(Sender: TObject);
{-}
var
Components: IDesignerSelections;
begin
if (Collection <> nil) then begin
Components := CreateSelectionList;
Designer.GetSelections(Components);
GetComponentProperties(Components, tkProperties, Designer, RunPropertyEditor);
end;//Collection <> nil
end;
procedure TvcmUserTypesCollectionEditor.RunPropertyEditor(const Prop: IProperty);
begin
if SameText(Prop.GetName, 'IMAGEINDEX') then
Prop.Edit;
end;
procedure TvcmUserTypesCollectionEditor.ItemsModified(const ADesigner: IDesigner);
//override;
{-}
begin
inherited;
MakeImages;
end;
type
TvcmUserTypesCollectionProperty = class(TCollectionProperty)
public
// public methods
function GetEditorClass: TCollectionEditorClass;
override;
{-}
end;//TvcmUserTypesCollectionProperty
function TvcmUserTypesCollectionProperty.GetEditorClass: TCollectionEditorClass;
//override;
{-}
begin
Result := TvcmUserTypesCollectionEditor;
end;
(*type
TvcmControlEditor = class(TDefaultEditor)
private
// internal fields
f_Form : TCustomForm;
f_Entities : TvcmBaseEntities;
public
// public methods
procedure PrepareItem(Index: Integer; const AItem: IMenuItem);
override;
{-}
procedure ExecuteVerb(Index : Integer);
override;
{-}
function GetVerb(Index : Integer): string;
override;
{-}
function GetVerbCount : Integer;
override;
{-}
end;//TvcmControlEditor
procedure TvcmControlEditor.PrepareItem(Index: Integer; const AItem: IMenuItem);
//override;
{-}
begin
inherited;
if (f_Form <> nil) then begin
if (Index = 0) then begin
end else if (f_Entities <> nil) then
aItem.Checked := TvcmBaseEntitiesCollectionItem(f_Entities.Entities.Items[Pred(Index)]).SupportedBy[GetComponent];
end;//f_Form <> nil
end;
procedure TvcmControlEditor.ExecuteVerb(Index : Integer);
//override;
{-}
begin
if (f_Form <> nil) then begin
if (Index = 0) then begin
if (f_Entities = nil) then begin
f_Entities := TvcmEntities.Create(f_Form);
f_Entities.Name := 'Entities';
end;//f_Entities = nil
TvcmEntityParams.Execute(f_Entities, GetComponent);
end else if (f_Entities <> nil) then
with TvcmBaseEntitiesCollectionItem(f_Entities.Entities.Items[Pred(Index)]) do
SupportedBy[GetComponent] := not SupportedBy[GetComponent];
end;//f_Form <> nil
end;
function TvcmControlEditor.GetVerb(Index : Integer): string;
//override;
{-}
begin
if (f_Form <> nil) then begin
if (Index = 0) then
Result := 'Добавить сущность...'
else if (f_Entities = nil) then
Result := ''
else
Result := TvcmBaseEntitiesCollectionItem(f_Entities.Entities.Items[Pred(Index)]).Caption;
end;//f_Form <> nil
end;
function TvcmControlEditor.GetVerbCount : Integer;
//override;
{-}
var
l_Index : Integer;
begin
f_Entities := nil;
Result := 0;
f_Form := afw.GetParentForm(GetComponent);
if (f_Form <> nil) then begin
Result := 1;
with f_Form do
for l_Index := 0 to Pred(ComponentCount) do
if (Components[l_Index] Is TvcmBaseEntities) then begin
f_Entities := TvcmBaseEntities(Components[l_Index]);
break;
end;//Components[l_Index] Is TvcmBaseEntities
if (f_Entities <> nil) then
Inc(Result, f_Entities.Entities.Count);
end;//l_Form <> nil
end;
type
TvcmFormSetFormProperty = class(TvcmListedProperty)
{* Редактирует свойство TvcmFormSetFactory.OwnerForm. }
public
// public methods
function GetValue: String;
override;
{-}
procedure GetValues(Proc: TGetStrProc);
override;
{-}
procedure SetValue(const aValue: String);
override;
{-}
end;
function TvcmFormSetFormProperty.GetValue : String;
// override;
{-}
var
l_ID: LongInt;
begin
Result := '';
l_ID := GetOrdProp(GetComponent(0), GetPropInfo);
if l_ID <> -1 then
Result := TvcmFormSetFormsCollectionItem(TvcmFormSetFactory(GetComponent(0)).Forms.Items[l_ID]).Name;
end;
procedure TvcmFormSetFormProperty.SetValue(const aValue : String);
// override;
{-}
var
lIndex : Integer;
begin
if aValue = '' then
SetOrdProp(GetComponent(0), GetPropInfo, -1)
else
for lIndex := 0 to Pred(TvcmFormSetFactory(GetComponent(0)).Forms.Count) do
if TvcmFormSetFormsCollectionItem(TvcmFormSetFactory(GetComponent(0)).Forms.Items[lIndex]).Name = aValue then
begin
if GetOrdProp(GetComponent(0), GetPropInfo) <> lIndex then
begin
SetOrdProp(GetComponent(0), GetPropInfo, lIndex);
Modified;
end;
Break;
end;
end;
procedure TvcmFormSetFormProperty.GetValues(Proc: TGetStrProc);
// override;
{-}
var
lIndex : Integer;
begin
with TvcmFormSetFactory(GetComponent(0)) do
for lIndex := 0 to Pred(Forms.Count) do
Proc(TvcmFormSetFormsCollectionItem(Forms.Items[lIndex]).Name);
end;*)
const
vcmPage = 'vcm';
vcmCategory = 'vcm';
type
TvcmDataModuleRef = class(TDataModule)
end;//TvcmDataModuleRef
procedure Register;
begin
RegisterComponents(vcmPage, [TvcmEntities,
TvcmMenuManager]);
(* RegisterComponentEditor(TvcmBaseEntities,
TvcmEntitiesEditor);*)
(* RegisterComponentEditor(TvcmCustomOperations,
TvcmOperationsEditor);*)
{ TvcmBaseUserTypesCollectionItem, "UseToolbarOfUserTypeName" }
RegisterPropertyEditor(TypeInfo(String),
TvcmBaseUserTypesCollectionItem,
'UseToolbarOfUserTypeName',
TvcmUseToolbarOfUserTypeNameProperty);
{ TvcmFormSetFactory, "OwnerForm"}
(* RegisterPropertyEditor(TypeInfo(Integer),
TvcmFormSetFactory,
'OwnerForm',
TvcmFormSetFormProperty);*)
{ TvcmFormSetFactory, "DefaultStatusForm"}
(* RegisterPropertyEditor(TypeInfo(Integer),
TvcmFormSetFactory,
'DefaultStatusForm',
TvcmFormSetFormProperty);*)
{ TvcmFormSetFormsCollectonItem, "UserType"}
(* RegisterPropertyEditor(TypeInfo(TvcmUserType),
TvcmFormSetFormsCollectionItem,
'UserType',
TvcmFormSetItemUserTypeProperty);*)
{ TvcmProjectFormName }
RegisterPropertyEditor(TypeInfo(TvcmProjectFormName),
nil,
'',
TvcmProjectFormNameProperty);
{ TvcmFormActivate, 'UserType' }
(* RegisterPropertyEditor(TypeInfo(Integer),
TvcmFormActivate,
'UserType',
TvcmFormActivateUserTypeProperty);*)
{ TvcmFormActivate, 'Name' }
RegisterPropertyEditor(TypeInfo(String),
TvcmFormActivate,
'Name',
TvcmFormActivateNameProperty);
{ TvcmFormActivate, 'Caption' }
RegisterPropertyEditor(TypeInfo(String),
TvcmFormActivate,
'Caption',
TvcmFormActivateCaptionProperty);
{ TvcmRepeatedActivationBehaviourProperty, 'RepeatedActivationBehaviour' }
RegisterPropertyEditor(TypeInfo(TvcmRepeatedActivationBehaviour),
TvcmFormActivate,
'RepeatedActivationBehaviour',
TvcmRepeatedActivationBehaviourProperty);
{ TvcmMessagesCollectionItem, 'Category' }
(* RegisterPropertyEditor(TypeInfo(TvcmMessageCategory),
TvcmMessagesCollectionItem,
'Category',
TvcmMessageCategoryProperty);*)
(* RegisterPropertyEditor(TypeInfo(String),
TvcmBaseEntitiesCollectionItem,
'Category',
TvcmEntityCategoryProperty);*)
(* RegisterPropertyEditor(TypeInfo(String),
TvcmBaseOperationsCollectionItem,
'_Category',
TvcmEntityCategoryProperty);*)
RegisterPropertyEditor(TypeInfo(String),
TvcmBaseEntitiesCollectionItem,
'Name',
TvcmEntityNameProperty);
RegisterPropertyEditor(TypeInfo(String),
TvcmBaseOperationsCollectionItem,
'Name',
TvcmOperationNameProperty);
RegisterPropertyEditor(TypeInfo(String),
TvcmBaseEntitiesCollectionItem,
'Caption',
TvcmEntityCaptionProperty);
RegisterPropertyEditor(TypeInfo(String),
TvcmBaseOperationsCollectionItem,
'Caption',
TvcmOperationCaptionProperty);
RegisterPropertyEditor(TypeInfo(TShortCut),
nil,
'ShortCut',
TShortCutProperty);
RegisterPropertyEditor(TypeInfo(TImageIndex),
TvcmBaseCollectionItem,
'ImageIndex',
TvcmImageIndexProperty);
(* RegisterPropertyEditor(TypeInfo(String),
TvcmMenuItemsCollectionItem,
'Caption',
TvcmMenuItemsCaptionProperty);*)
RegisterPropertyEditor(TypeInfo(TvcmBaseOperationsCollection),
nil,
'',
TvcmOperationsCollectionProperty);
RegisterPropertyEditor(TypeInfo(TvcmUserTypesCollection),
nil,
'',
TvcmUserTypesCollectionProperty);
RegisterPropertyEditor(TypeInfo(TvcmBaseOperationStates),
nil,
'',
TvcmOperationStatesProperty);
RegisterPropertyEditor(TypeInfo(TvcmBaseEntitiesCollection),
nil,
'',
TvcmEntitiesCollectionProperty);
RegisterPropertyEditor(TypeInfo(TvcmFormsCollection),
nil,
'',
TvcmFormsCollectionProperty);
//RegisterComponentEditor(TControl, TvcmControlEditor);
//RegisterCustomModule(TvcmFormSetFactory, TCustomModule);
//RegisterPackageWizard(TvcmFormSetFactoryWizard.Create);
//RegisterCustomModule(TvcmApplication, TCustomModule);
//RegisterCustomModule(TvcmApplicationRef, TCustomModule);
RegisterCustomModule(TvcmDataModuleRef, TCustomModule);
//RegisterCustomModule(TvcmStdResRef, TCustomModule);
//RegisterPackageWizard(TvcmModuleWizard.Create);
RegisterCustomModule(TvcmForm, TCustomModule);
RegisterCustomModule(TvcmEntityFormRef, TCustomModule);
RegisterCustomModule(TvcmEntityForm, TCustomModule);
//RegisterPackageWizard(TvcmEntityWizard.Create);
RegisterCustomModule(TvcmContainerForm, TCustomModule);
RegisterCustomModule(TvcmContainerFormRef, TCustomModule);
RegisterCustomModule(TvcmMainForm, TCustomModule);
RegisterCustomModule(TvcmMainFormRef, TCustomModule);
RegisterPropertiesInCategory(vcmCategory, TvcmEntityForm,
['OnInit', 'ZoneType',
'OnLoadState', 'OnSaveState', 'ToolbarPos']);
RegisterPropertiesInCategory(vcmCategory, TvcmContainerForm,
['Zones', 'OnInsertForm', 'OnAfterInsertForm']);
RegisterPropertiesInCategory(vcmCategory, TvcmMainForm,
['SDI', 'MenuManager', 'OnUpdateStatus']);
end;
{$EndIf NoVCM}
end.
|
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi
by Dennis D. Spreen <dennis@spreendigital.de>
see Behavior3.pas header for full license information }
unit Behavior3.Core.Action;
interface
uses
Behavior3, Behavior3.Core.BaseNode;
type
(**
* Action is the base class for all action nodes. Thus, if you want to create
* new custom action nodes, you need to inherit from this class. For example,
* take a look at the Runner action:
*
* var Runner = b3.Class(b3.Action, {
* name: 'Runner',
*
* tick: function(tick) {
* return b3.RUNNING;
* }
* });
*
* @module b3
* @class Action
* @extends BaseNode
**)
TB3Action = class abstract (TB3BaseNode)
private
protected
public
(**
* Initialization method.
* @method initialize
* @constructor
**)
constructor Create; override;
end;
implementation
{ TB3Action }
constructor TB3Action.Create;
begin
inherited;
(**
* Node category. Default to `b3.ACTION`.
* @property {String} category
* @readonly
**)
Category := Behavior3.Action;
end;
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* 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.
*
**********************************************************************************************************************
* TERRA_Octree
* Implements a Octree class
***********************************************************************************************************************
}
Unit TERRA_Octree;
{
WARNING - When calling Octree.Intersect
Make sure the paramter T is initialized to a very long number (eg: 9999)
}
{$I terra.inc}
Interface
Uses TERRA_Utils, TERRA_Vector3D, TERRA_GraphicsManager, TERRA_BoundingBox, TERRA_Ray, TERRA_Color;
Const
MaxLevel = 6;
Type
OctreeElement = Class(TERRAObject)
Public
Box:BoundingBox;
Procedure Release; Override;
Procedure Render; Virtual;
Function Intersect(Const R:Ray; Var T:Single):Boolean; Virtual;
End;
Octree = Class(TERRAObject)
Protected
_Size:BoundingBox;
_Level:Integer;
_Children:Array[0..7] Of Octree;
_Elements:Array Of OctreeElement;
_ElementCount:Integer;
Function GetChildrenBoundingBox(Index:Integer):BoundingBox;
Public
Constructor Create(Box:BoundingBox; Level:Integer = 0);
Procedure Release; Override;
Procedure AddElement(Element:OctreeElement);
Procedure RemoveElement(Element:OctreeElement);
Function Intersect(Const R:Ray; Var T:Single):OctreeElement;
Procedure Render;
End;
Implementation
{$IFDEF PC}
Uses TERRA_DebugDraw;
{$ENDIF}
{ Octree }
Constructor Octree.Create(Box:BoundingBox; Level:Integer);
Var
I:Integer;
Begin
Self._Level := Level;
Self._Size := Box;
Inc(Level);
If Level<MaxLevel Then
For I:=0 To 7 Do
_Children[I] := Octree.Create(Self.GetChildrenBoundingBox(I), Level);
End;
Procedure Octree.AddElement(Element:OctreeElement);
Var
I:Integer;
Begin
For I:=0 To 7 Do
If (Assigned(_Children[I])) And (Element.Box.Inside(_Children[I]._Size)) Then
Begin
_Children[I].AddElement(Element);
Exit;
End;
Inc(_ElementCount);
SetLength(_Elements, _ElementCount);
_Elements[Pred(_ElementCount)] := Element;
End;
Function Octree.GetChildrenBoundingBox(Index: Integer): BoundingBox;
Var
Center:Vector3D;
Begin
Center := _Size.Center;
Case Index Of
0 : Begin
Result.StartVertex := VectorCreate(_Size.StartVertex.X, _Size.StartVertex.Y, _Size.StartVertex.Z);
Result.EndVertex := VectorCreate(Center.X, Center.Y, Center.Z);
End;
1 : Begin
Result.StartVertex := VectorCreate(_Size.StartVertex.X, _Size.StartVertex.Y, Center.Z);
Result.EndVertex := VectorCreate(Center.X, Center.Y, _Size.EndVertex.Z);
End;
2 : Begin
Result.StartVertex := VectorCreate(Center.X, _Size.StartVertex.Y, _Size.StartVertex.Z);
Result.EndVertex := VectorCreate(_Size.EndVertex.X, Center.Y, Center.Z);
End;
3 : Begin
Result.StartVertex := VectorCreate(Center.X, _Size.StartVertex.Y, Center.Z);
Result.EndVertex := VectorCreate(_Size.EndVertex.X, Center.Y, _Size.EndVertex.Z);
End;
4 : Begin
Result.StartVertex := VectorCreate(_Size.StartVertex.X, Center.Y, _Size.StartVertex.Z);
Result.EndVertex := VectorCreate(Center.X, _Size.EndVertex.Y, Center.Z);
End;
5 : Begin
Result.StartVertex := VectorCreate(_Size.StartVertex.X, Center.Y, Center.Z);
Result.EndVertex := VectorCreate(Center.X, _Size.EndVertex.Y, _Size.EndVertex.Z);
End;
6 : Begin
Result.StartVertex := VectorCreate(Center.X, Center.Y, _Size.StartVertex.Z);
Result.EndVertex := VectorCreate(_Size.EndVertex.X, _Size.EndVertex.Y, Center.Z);
End;
7 : Begin
Result.StartVertex := VectorCreate(Center.X, Center.Y, Center.Z);
Result.EndVertex := VectorCreate(_Size.EndVertex.X, _Size.EndVertex.Y, _Size.EndVertex.Z);
End;
Else
Begin
Result.StartVertex := VectorZero;
FillChar(Result, SizeOf(Result), 0);
End;
End;
End;
Procedure Octree.RemoveElement(Element:OctreeElement);
Var
I:Integer;
Begin
I:=0;
While I<_ElementCount Do
If (_Elements[I] = Element) Then
Begin
ReleaseObject(_Elements[I]);
_Elements[I] := _Elements[Pred(_ElementCount)];
Dec(_ElementCount);
Exit;
End Else
Inc(I);
For I:=0 To 7 Do
If Assigned(_Children[I]) Then
_Children[I].RemoveElement(Element);
End;
Procedure Octree.Release;
Var
I:Integer;
Begin
For I:=0 To Pred(_ElementCount) Do
ReleaseObject(_Elements[I]);
For I:=0 To 7 Do
If Assigned(_Children[I]) Then
ReleaseObject(_Children[I]);
End;
Function Octree.Intersect(Const R: Ray; Var T:Single):OctreeElement;
Var
K:Single;
I:Integer;
Ok:Boolean;
Obj:OctreeElement;
Begin
Result := Nil;
K := 99999;
If (R.Intersect(_Size, K)) Then
Begin
For I:=0 To Pred(_ElementCount) Do
Begin
Ok := _Elements[I].Intersect(R, K);
If (Ok) Then
Begin
If (K<T) Then
Begin
Result := _Elements[I];
T := K;
End;
End;
End;
For I:=0 To 7 Do
If Assigned(_Children[I]) Then
Begin
Obj := _Children[I].Intersect(R, T);
If (Obj<>Nil) Then
Begin
Result := Obj;
Exit;
End;
End;
End;
End;
Procedure Octree.Render;
Var
I:Integer;
Begin
If (Not GraphicsManager.Instance.ActiveViewport.Camera.Frustum.BoxVisible(_Size)) Then
Exit;
For I:=0 To Pred(_ElementCount) Do
_Elements[I].Render();
For I:=0 To 7 Do
If Assigned(_Children[I]) Then
_Children[I].Render;
End;
{ OctreeElement }
Procedure OctreeElement.Release;
Begin
// do nothing
End;
Function OctreeElement.Intersect(const R: Ray; var T: Single): Boolean;
Begin
Result := R.Intersect(Box, T);
End;
Procedure OctreeElement.Render;
Begin
End;
End. |
{$I ACBr.inc}
unit ASCIOTWebServices;
interface
uses Classes, SysUtils,
{$IFDEF VCL} Dialogs, {$ELSE} QDialogs, {$ENDIF}
{$IFDEF ACBrCTeOpenSSL}
HTTPSend,
{$ELSE}
SOAPHTTPTrans, WinInet, ACBrCAPICOM_TLB, SOAPConst,
{$ENDIF}
pcnAuxiliar, pcnConversao,
ASCIOTConfiguracoes,
pciotCiot, ASCIOTUtil,
pCiotVeiculoW, pCiotVeiculoR,
pCiotMotoristaW, pCiotMotoristaR,
pCiotProprietarioW, pCiotProprietarioR,
pCiotOperacaoTransporteW, pCiotOperacaoTransporteR,
ActiveX;
type
TWebServicesBase = Class
private
procedure DoVeiculo(AOperacao: TpciotOperacao);
procedure DoMotorista(AOperacao: TpciotOperacao);
procedure DoProprietario(AOperacao: TpciotOperacao);
procedure DoOperacaoTransporte(AOperacao: TpciotOperacao);
{$IFDEF ACBrCTeOpenSSL}
procedure ConfiguraHTTP( HTTP : THTTPSend; Action : AnsiString);
{$ELSE}
procedure ConfiguraReqResp( ReqResp : THTTPReqResp);
procedure OnBeforePost(const HTTPReqResp: THTTPReqResp; Data:Pointer);
{$ENDIF}
protected
FCabMsg: AnsiString;
FDadosMsg: AnsiString;
FRetornoWS: AnsiString;
FRetWS: AnsiString;
FMsg: AnsiString;
FURL: WideString;
FConfiguracoes: TConfiguracoes;
FAmSCIOT : TComponent;
FPathArqResp: AnsiString;
FPathArqEnv: AnsiString;
procedure LoadMsgEntrada(AOperacao: TpciotOperacao; ALayout: Integer = 0);
procedure LoadURL;
public
constructor Create(AOwner : TComponent); virtual;
function Obter: Boolean; virtual;
function Adicionar: Boolean; virtual;
property CabMsg: AnsiString read FCabMsg;
property DadosMsg: AnsiString read FDadosMsg;
property RetornoWS: AnsiString read FRetornoWS;
property RetWS: AnsiString read FRetWS;
property Msg: AnsiString read FMsg;
property PathArqEnv: AnsiString read FPathArqEnv;
property PathArqResp: AnsiString read FPathArqResp;
end;
TCIOTVeiculo = Class(TWebServicesBase)
private
FVeiculo: TVeiculo;
FSucesso: Boolean;
FMensagem: String;
function Obter: Boolean; overload; override;
public
constructor Create(AOwner : TComponent);reintroduce;
destructor destroy; override;
procedure Clear;
function Obter(APlaca: string; ARNTRC: string): Boolean; overload;
function Adicionar: Boolean; overload; override;
property Sucesso: Boolean read FSucesso;
property Mensagem: String read FMensagem;
property Veiculo: TVeiculo read FVeiculo write FVeiculo;
end;
TCIOTMotorista = Class(TWebServicesBase)
private
FSucesso: Boolean;
FMensagem: String;
FRetMotorista : TMotoristaR;
FMotorista: TMotorista;
function Obter: Boolean; overload; override;
public
constructor Create(AOwner : TComponent);reintroduce;
destructor Destroy; override;
procedure Clear;
function Obter(ACPF, ACNH: string): Boolean; overload;
function Adicionar: Boolean; overload; override;
property Sucesso: Boolean read FSucesso;
property Mensagem: String read FMensagem;
property RetMotorista: TMotoristaR read FRetMotorista;
property Motorista: TMotorista read FMotorista write FMotorista;
end;
TCIOTProprietario = Class(TWebServicesBase)
private
FSucesso: Boolean;
FMensagem: String;
FRetProprietario : TProprietarioR;
FProprietario: TProprietario;
procedure SetJustificativa(AValue: WideString);
function Obter: Boolean; overload; override;
public
constructor Create(AOwner : TComponent);reintroduce;
destructor Destroy; override;
procedure Clear;
function Obter(ACNPJ: string; ARNTRC: string): Boolean; overload;
function Adicionar: Boolean; overload; override;
property Sucesso: Boolean read FSucesso;
property Mensagem: String read FMensagem;
property RetProprietario: TProprietarioR read FRetProprietario;
property Proprietario: TProprietario read FProprietario write FProprietario;
end;
TCIOTOperacaoTransporte = Class(TWebServicesBase)
private
FSucesso: Boolean;
FMensagem: String;
FOperacoesTransporte : TOperacoesTransporte;
FRetOperacaoTransporte: TOperacaoTransporteR;
FTipoImpressao: TpciotTipoImpressao;
function Obter: Boolean; override;
public
constructor Create(AOwner : TComponent);reintroduce;
destructor Destroy; override;
procedure Clear;
function Adicionar: Boolean; overload; override;
function ObterPDF(ANroCIOT: string; ATipoImpressao: TpciotTipoImpressao = tiPDF; AImprimir: Boolean = True): Boolean;
function Retificar: Boolean;
function Cancelar(ANumeroCIOT, AMotivo: string): Boolean;
procedure Imprimir;
function AdicionarViagens: Boolean;
function AdicionarPagamento: Boolean;
function CancelarPagamento(AIdPagamento, AMotivo: string): Boolean;
function Encerrar: Boolean;
//METODOS PARA OPERACAO TIPO: TAC_Agregado
// procedure AdicionarViagens;
property OperacoesTransporte: TOperacoesTransporte read FOperacoesTransporte write FOperacoesTransporte;
property Sucesso: Boolean read FSucesso;
property Mensagem: String read FMensagem;
property RetOperacaoTransporte: TOperacaoTransporteR read FRetOperacaoTransporte;
end;
TWebServices = Class(TWebServicesBase)
private
FACBrCIOT: TComponent;
FVeiculo: TCIOTVeiculo;
FProprietario: TCIOTProprietario;
FMotorista: TCIOTMotorista;
FOperacaoTransporte: TCIOTOperacaoTransporte;
public
constructor Create(AFCIOT: TComponent = nil);reintroduce;
destructor Destroy; override;
// published
property ACBrCIOT: TComponent read FACBrCIOT write FACBrCIOT;
property Veiculo: TCIOTVeiculo read FVeiculo write FVeiculo;
property Proprietario: TCIOTProprietario read FProprietario write FProprietario;
property Motorista: TCIOTMotorista read FMotorista write FMotorista;
property OperacaoTransporte: TCIOTOperacaoTransporte read FOperacaoTransporte write FOperacaoTransporte;
end;
procedure ConfAmbiente;
function trataString( const AValue:String):String;
implementation
uses {$IFDEF ACBrCTeOpenSSL}
ssl_openssl,
{$ENDIF}
ACBrUtil, ASCIOT, ACBrDFeUtil,
pcnGerador, pcnCabecalho, pcnLeitor;
{$IFNDEF ACBrCTeOpenSSL}
const
INTERNET_OPTION_CLIENT_CERT_CONTEXT = 84;
{$ENDIF}
{ TWebServicesBase }
constructor TWebServicesBase.Create(AOwner: TComponent);
begin
FConfiguracoes := TConfiguracoes( TAmSCIOT( AOwner ).Configuracoes );
FAmsCIOT := TAmSCIOT( AOwner );
end;
{$IFDEF ACBrCTeOpenSSL}
procedure TWebServicesBase.ConfiguraHTTP( HTTP : THTTPSend; Action : AnsiString);
begin
if FileExists(FConfiguracoes.Certificados.Certificado) then
HTTP.Sock.SSL.PFXfile := FConfiguracoes.Certificados.Certificado
else
HTTP.Sock.SSL.PFX := FConfiguracoes.Certificados.Certificado;
HTTP.Sock.SSL.KeyPassword := FConfiguracoes.Certificados.Senha;
HTTP.ProxyHost := FConfiguracoes.WebServices.ProxyHost;
HTTP.ProxyPort := FConfiguracoes.WebServices.ProxyPort;
HTTP.ProxyUser := FConfiguracoes.WebServices.ProxyUser;
HTTP.ProxyPass := FConfiguracoes.WebServices.ProxyPass;
// Linha abaixo comentada por Italo em 08/09/2010
// HTTP.Sock.RaiseExcept := True;
HTTP.MimeType := 'text/xml; charset=utf-8';
HTTP.UserAgent := '';
HTTP.Protocol := '1.1';
HTTP.AddPortNumberToHost := False;
HTTP.Headers.Add(Action);
end;
{$ELSE}
function TWebServicesBase.Adicionar: Boolean;
begin
Result := False;
if FConfiguracoes.Certificados.NumeroSerie = '' then
FConfiguracoes.Certificados.NumeroSerie := FConfiguracoes.Certificados.SelecionarCertificado;
LoadMsgEntrada(opAdicionar);
LoadURL;
end;
procedure TWebServicesBase.ConfiguraReqResp( ReqResp : THTTPReqResp);
begin
if FConfiguracoes.WebServices.ProxyHost <> '' then
begin
ReqResp.Proxy := FConfiguracoes.WebServices.ProxyHost+':'+FConfiguracoes.WebServices.ProxyPort;
ReqResp.UserName := FConfiguracoes.WebServices.ProxyUser;
ReqResp.Password := FConfiguracoes.WebServices.ProxyPass;
end;
ReqResp.OnBeforePost := OnBeforePost;
end;
function TWebServicesBase.Obter: Boolean;
begin
Result := False;
if FConfiguracoes.Certificados.NumeroSerie = '' then
FConfiguracoes.Certificados.NumeroSerie := FConfiguracoes.Certificados.SelecionarCertificado;
LoadMsgEntrada(opObter);
LoadURL;
end;
procedure TWebServicesBase.OnBeforePost(const HTTPReqResp: THTTPReqResp;
Data: Pointer);
var
Cert : ICertificate2;
CertContext : ICertContext;
PCertContext : Pointer;
ContentHeader: string;
begin
Cert := FConfiguracoes.Certificados.GetCertificado;
CertContext := Cert as ICertContext;
CertContext.Get_CertContext(Integer(PCertContext));
if not InternetSetOption(Data, INTERNET_OPTION_CLIENT_CERT_CONTEXT, PCertContext,SizeOf(CertContext)*5) then
begin
if Assigned(TAmSCIOT( FAmsCIOT ).OnGerarLog) then
TAmSCIOT( FAmsCIOT ).OnGerarLog('ERRO: Erro OnBeforePost: ' + IntToStr(GetLastError));
raise Exception.Create( 'Erro OnBeforePost: ' + IntToStr(GetLastError) );
end;
if trim(FConfiguracoes.WebServices.ProxyUser) <> '' then begin
if not InternetSetOption(Data, INTERNET_OPTION_PROXY_USERNAME, PChar(FConfiguracoes.WebServices.ProxyUser), Length(FConfiguracoes.WebServices.ProxyUser)) then
raise Exception.Create( 'Erro OnBeforePost: ' + IntToStr(GetLastError) );
end;
if trim(FConfiguracoes.WebServices.ProxyPass) <> '' then begin
if not InternetSetOption(Data, INTERNET_OPTION_PROXY_PASSWORD, PChar(FConfiguracoes.WebServices.ProxyPass),Length (FConfiguracoes.WebServices.ProxyPass)) then
raise Exception.Create( 'Erro OnBeforePost: ' + IntToStr(GetLastError) );
end;
ContentHeader := Format(ContentTypeTemplate, ['application/soap+xml; charset=utf-8']);
HttpAddRequestHeaders(Data, PChar(ContentHeader), Length(ContentHeader), HTTP_ADDREQ_FLAG_REPLACE);
end;
{$ENDIF}
procedure TWebServicesBase.DoProprietario(AOperacao: TpciotOperacao);
var
ProprietarioW: TProprietarioW;
begin
ProprietarioW := TProprietarioW.Create(TCIOTProprietario(Self).FProprietario, AOperacao);
ProprietarioW.GerarXML;
FDadosMsg := ProprietarioW.Gerador.ArquivoFormatoXML;
ProprietarioW.Free;
end;
procedure TWebServicesBase.DoMotorista(AOperacao: TpciotOperacao);
var
MotoristaW: TMotoristaW;
begin
MotoristaW := TMotoristaW.Create(TCIOTMotorista(Self).FMotorista, AOperacao);
MotoristaW.GerarXML;
FDadosMsg := MotoristaW.Gerador.ArquivoFormatoXML;
MotoristaW.Free;
end;
procedure TWebServicesBase.DoVeiculo(AOperacao: TpciotOperacao);
var
VeiculoW: TVeiculoW;
begin
VeiculoW := TVeiculoW.Create(TCIOTVeiculo(Self).FVeiculo, AOperacao);
VeiculoW.GerarXML;
FDadosMsg := VeiculoW.Gerador.ArquivoFormatoXML;
VeiculoW.Free;
end;
procedure TWebServicesBase.DoOperacaoTransporte(AOperacao: TpciotOperacao);
var
OperacaoTransporteW: TOperacaoTransporteW;
begin
OperacaoTransporteW := TOperacaoTransporteW.Create(TCIOTOperacaoTransporte(Self).FOperacoesTransporte.Items[0], AOperacao);
OperacaoTransporteW.GerarXML;
FDadosMsg := OperacaoTransporteW.Gerador.ArquivoFormatoXML;
OperacaoTransporteW.Free;
end;
procedure TWebServicesBase.LoadMsgEntrada(AOperacao: TpciotOperacao; ALayout: Integer = 0);
begin
if (self is TCIOTVeiculo) then
DoVeiculo(AOperacao)
else if (self is TCIOTOperacaoTransporte) then
DoOperacaoTransporte(AOperacao)
else if (self is TCIOTProprietario) then
DoProprietario(AOperacao)
else if (self is TCIOTMotorista) then
DoMotorista(AOperacao)
end;
procedure TWebServicesBase.LoadURL;
begin
if (self is TCIOTVeiculo) then
FURL := CIOTUtil.GetURL(FConfiguracoes.Integradora.Tecnologia, FConfiguracoes.WebServices.AmbienteCodigo, LayVeiculo)
else if (self is TCIOTProprietario) then
FURL := CIOTUtil.GetURL(FConfiguracoes.Integradora.Tecnologia, FConfiguracoes.WebServices.AmbienteCodigo, LayProprietario)
else if (self is TCIOTOperacaoTransporte) then
FURL := CIOTUtil.GetURL(FConfiguracoes.Integradora.Tecnologia, FConfiguracoes.WebServices.AmbienteCodigo, LayOperacaoTransporte)
else if (self is TCIOTMotorista) then
FURL := CIOTUtil.GetURL(FConfiguracoes.Integradora.Tecnologia, FConfiguracoes.WebServices.AmbienteCodigo, LayMotorista);
end;
{ TWebServices }
constructor TWebServices.Create(AFCIOT: TComponent);
begin
inherited Create( AFCIOT );
FACBrCIOT := TAmSCIOT(AFCIOT);
FVeiculo := TCIOTVeiculo.create(AFCIOT);
FProprietario := TCIOTProprietario.Create(AFCIOT);
FMotorista := TCIOTMotorista.Create(AFCIOT);
FOperacaoTransporte := TCIOTOperacaoTransporte.Create(AFCIOT);
end;
destructor TWebServices.Destroy;
begin
FVeiculo.Free;
FProprietario.Free;
FMotorista.Free;
FOperacaoTransporte.Free;
inherited;
end;
{ TCTeRecepcao }
function TCIOTVeiculo.Adicionar: Boolean;
var
CIOTRetorno: TVeiculoR;
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
inherited Adicionar;
Result := False;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <Gravar xmlns="http://schemas.ipc.adm.br/efrete/veiculos">';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </Gravar>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/veiculos/Gravar';
{$ENDIF}
try
TAmSCIOT( FAmsCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-adicionar-veiculo.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/veiculos/Gravar"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'GravarResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'GravarResponse');
StrStream.Free;
{$ENDIF}
CIOTRetorno := TVeiculoR.Create(FVeiculo, opAdicionar);
CIOTRetorno.Leitor.Arquivo := FRetWS;
CIOTRetorno.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'Placa : '+CIOTRetorno.Veiculo.Placa+LineBreak+
'Ano Modelo : '+IntToStr(CIOTRetorno.Veiculo.AnoModelo)+LineBreak+
'Ano Fabricacao : '+IntToStr(CIOTRetorno.Veiculo.AnoFabricacao)+LineBreak +
'Sucesso : '+BoolToStr(CIOTRetorno.Sucesso)+LineBreak+
'Mensagem : '+CIOTRetorno.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+CIOTRetorno.Mensagem;
Result := (CIOTRetorno.Sucesso);
FSucesso := CIOTRetorno.Sucesso;
FMensagem := CIOTRetorno.Mensagem;
CIOTRetorno.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-Addveiculos.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-Addveiculos.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService Veiculos (Inclusao):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService Veiculos (Inclusao):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
procedure TCIOTVeiculo.Clear;
begin
FMensagem := '';
FSucesso := False;
// if Assigned(FVeiculo) then FVeiculo.Free;
end;
constructor TCIOTVeiculo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FVeiculo := TVeiculo.Create(AOwner);
end;
destructor TCIOTVeiculo.destroy;
begin
FVeiculo.Free;
inherited;
end;
function TCIOTVeiculo.Obter(APlaca: string; ARNTRC: string): Boolean;
begin
Clear;
FVeiculo := TVeiculo.Create(FAmSCIOT);
FVeiculo.Placa := APlaca;
FVeiculo.RNTRC := ARNTRC;
Self.Obter;
result := Self.Sucesso;
end;
function TCIOTVeiculo.Obter: Boolean;
var
CIOTRetorno: TVeiculoR;
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
inherited Obter;
Result := False;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <ObterPorPlaca xmlns="http://schemas.ipc.adm.br/efrete/veiculos">';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </ObterPorPlaca>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/veiculos/ObterPorPlaca';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-obter-veiculo.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/veiculos/ObterPorPlaca"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'ObterPorPlacaResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'ObterPorPlacaResponse');
StrStream.Free;
{$ENDIF}
CIOTRetorno := TVeiculoR.Create(FVeiculo);
CIOTRetorno.Leitor.Arquivo := FRetWS;
CIOTRetorno.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'Placa : '+CIOTRetorno.Veiculo.Placa+LineBreak+
'Ano Modelo : '+IntToStr(CIOTRetorno.Veiculo.AnoModelo)+LineBreak+
'Ano Fabricacao : '+IntToStr(CIOTRetorno.Veiculo.AnoFabricacao)+LineBreak +
'Sucesso : '+BoolToStr(CIOTRetorno.Sucesso)+LineBreak+
'Mensagem : '+CIOTRetorno.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+CIOTRetorno.Mensagem;
Result := (CIOTRetorno.Sucesso);
FSucesso := CIOTRetorno.Sucesso;
FMensagem := CIOTRetorno.Mensagem;
CIOTRetorno.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-veiculos.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-veiculos.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService Veiculos:'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService Veiculos:'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
{ TCIOTProprietario }
function TCIOTProprietario.Adicionar: Boolean;
var
CIOTRetorno: TProprietarioR;
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
inherited Adicionar;
Result := False;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <Gravar xmlns="http://schemas.ipc.adm.br/efrete/proprietarios">';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </Gravar>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/proprietarios/Gravar';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-adicionar-Proprietario.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/proprietarios/Gravar"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'GravarResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'GravarResponse');
StrStream.Free;
{$ENDIF}
CIOTRetorno := TProprietarioR.Create(FProprietario, opAdicionar);
CIOTRetorno.Leitor.Arquivo := FRetWS;
CIOTRetorno.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'CNPJ : '+CIOTRetorno.Proprietario.CNPJ+LineBreak+
'RazaoSocial : '+CIOTRetorno.Proprietario.RazaoSocial+LineBreak+
'Proprietario.Endereco.Rua : '+CIOTRetorno.Proprietario.Endereco.Rua+LineBreak +
'Sucesso : '+BoolToStr(CIOTRetorno.Sucesso)+LineBreak+
'Mensagem : '+CIOTRetorno.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+CIOTRetorno.Mensagem;
Result := (CIOTRetorno.Sucesso);
FSucesso := CIOTRetorno.Sucesso;
FMensagem := CIOTRetorno.Mensagem;
CIOTRetorno.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-AddProprietario.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-AddProprietario.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService Proprietario (Inclusao):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService Proprietario (Inclusao):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
procedure TCIOTProprietario.Clear;
begin
FMensagem := '';
FSucesso := False;
end;
constructor TCIOTProprietario.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FProprietario := TProprietario.Create(AOwner);
end;
destructor TCIOTProprietario.Destroy;
begin
FProprietario.Free;
inherited;
end;
function TCIOTProprietario.Obter(ACNPJ: string; ARNTRC: string): Boolean;
begin
Clear;
FProprietario := TProprietario.Create(FAmSCIOT);
FProprietario.CNPJ := ACNPJ;
FProprietario.RNTRC := ARNTRC;
Obter;
result := Self.Sucesso;
end;
function TCIOTProprietario.Obter: Boolean;
var
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
inherited Obter;
Result := False;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
FSucesso := False;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <Obter xmlns="http://schemas.ipc.adm.br/efrete/proprietarios">';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </Obter>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/proprietarios/Obter';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-obter-proprietarios.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/proprietarios/Obter"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'ObterResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'ObterResponse');
StrStream.Free;
{$ENDIF}
FRetProprietario := TProprietarioR.Create(FProprietario);
FRetProprietario.Leitor.Arquivo := FRetWS;
FRetProprietario.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'CPF : '+FProprietario.CNPJ+LineBreak+
'CNH : '+FProprietario.RNTRC+LineBreak+
'Nome : '+FProprietario.RazaoSocial+LineBreak +
'Sucesso : '+BoolToStr(FRetProprietario.Sucesso)+LineBreak+
'Mensagem : '+FRetProprietario.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+FRetProprietario.Mensagem;
Result := FRetProprietario.Sucesso;
FRetProprietario.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-proprietarios.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-proprietarios.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService Proprietario:'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService Proprietario:'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
procedure TCIOTProprietario.SetJustificativa(AValue: WideString);
begin
if EstaVazio(AValue) then
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('ERRO: Informar uma Justificativa para cancelar o Conhecimento Eletr˘nico');
raise Exception.Create('Informar uma Justificativa para cancelar o Conhecimento Eletr˘nico')
end
else
AValue := TrataString(AValue);
if Length(AValue) < 15 then
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('ERRO: A Justificativa para Cancelamento do Conhecimento Eletr˘nico deve ter no minimo 15 caracteres');
raise Exception.Create('A Justificativa para Cancelamento do Conhecimento Eletr˘nico deve ter no minimo 15 caracteres')
end
// else
// FJustificativa := Trim(AValue);
end;
procedure TCIOTMotorista.Clear;
begin
FMensagem := '';
FSucesso := False;
// if Assigned(FMotorista) then FMotorista.Free;
end;
constructor TCIOTMotorista.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMotorista := TMotorista.Create(AOwner);
end;
destructor TCIOTMotorista.destroy;
begin
FMotorista.Free;
inherited;
end;
function TCIOTMotorista.Obter(ACPF, ACNH: string): Boolean;
begin
Clear;
FMotorista := TMotorista.Create(FAmSCIOT);
FMotorista.CPF := ACPF;
FMotorista.CNH := ACNH;
Obter;
result := Self.Sucesso;
end;
function TCIOTMotorista.Obter: Boolean;
var
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
inherited Obter;
Result := False;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
FSucesso := False;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <Obter xmlns="http://schemas.ipc.adm.br/efrete/motoristas">';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </Obter>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/motoristas/Obter';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-obter-motoristas.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/motoristas/Obter"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'ObterResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'ObterResponse');
StrStream.Free;
{$ENDIF}
FRetMotorista := TMotoristaR.Create(FMotorista);
FRetMotorista.Leitor.Arquivo := FRetWS;
FRetMotorista.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'CPF : '+FMotorista.CPF+LineBreak+
'CNH : '+FMotorista.CNH+LineBreak+
'Nome : '+FMotorista.Nome+LineBreak +
'Sucesso : '+BoolToStr(FRetMotorista.Sucesso)+LineBreak+
'Mensagem : '+FRetMotorista.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+FRetMotorista.Mensagem;
Result := FRetMotorista.Sucesso;
FRetMotorista.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-motoristas.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-motoristas.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService Motorista:'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService Motorista:'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
function TCIOTMotorista.Adicionar: Boolean;
var
aMsg : String;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
inherited Adicionar;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <Gravar xmlns="http://schemas.ipc.adm.br/efrete/motoristas">';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </Gravar>';
Texto := Texto + '</soap12:Body>';
Texto := Texto +'</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/motoristas/Gravar';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTAdicionando );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-adicionar-motoristas.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
FRetWS := '';
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/motoristas/Gravar"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS,'GravarResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS,'GravarResponse');
StrStream.Free;
{$ENDIF}
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-AddMotorista.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-AddMotorista.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
FRetMotorista := TMotoristaR.Create(FMotorista, opAdicionar);
FRetMotorista.Leitor.Arquivo := FRetWS;
FRetMotorista.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'CNPJ : '+FRetMotorista.Motorista.CPF+LineBreak+
'RazaoSocial : '+FRetMotorista.Motorista.Nome+LineBreak+
'Proprietario.Endereco.Rua : '+FRetMotorista.Motorista.Endereco.Rua+LineBreak +
'Sucesso : '+BoolToStr(FRetMotorista.Sucesso)+LineBreak+
'Mensagem : '+FRetMotorista.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+FRetMotorista.Mensagem;
Result := (FRetMotorista.Sucesso);
FSucesso := FRetMotorista.Sucesso;
FMensagem := FRetMotorista.Mensagem;
FRetMotorista.Free;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
procedure ConfAmbiente;
{$IFDEF VER140} //delphi6
{$ELSE}
var
vFormatSettings: TFormatSettings;
{$ENDIF}
begin
{$IFDEF VER140} //delphi6
DecimalSeparator := ',';
{$ELSE}
vFormatSettings.DecimalSeparator := ',';
{$ENDIF}
end;
function TrataString(const AValue: String): String;
var
A : Integer ;
begin
Result := '' ;
For A := 1 to length(AValue) do
begin
case Ord(AValue[A]) of
60 : Result := Result + '<'; //<
62 : Result := Result + '>'; //>
38 : Result := Result + '&'; //&
34 : Result := Result + '"';//"
39 : Result := Result + '''; //'
32 : begin // Retira espašos duplos
if ( Ord(AValue[Pred(A)]) <> 32 ) then
Result := Result + ' ';
end;
193 : Result := Result + 'A';//┴
224 : Result := Result + 'a';//Ó
226 : Result := Result + 'a';//Ô
234 : Result := Result + 'e';//ŕ
244 : Result := Result + 'o';//˘
251 : Result := Result + 'u';//ű
227 : Result := Result + 'a';//Ń
245 : Result := Result + 'o';//§
225 : Result := Result + 'a';//ß
233 : Result := Result + 'e';//Ú
237 : Result := Result + 'i';//Ý
243 : Result := Result + 'o';//ˇ
250 : Result := Result + 'u';//˙
231 : Result := Result + 'c';//š
252 : Result := Result + 'u';//Ř
192 : Result := Result + 'A';//└
194 : Result := Result + 'A';//┬
202 : Result := Result + 'E';//╩
212 : Result := Result + 'O';//ď
219 : Result := Result + 'U';//█
195 : Result := Result + 'A';//├
213 : Result := Result + 'O';//Ň
201 : Result := Result + 'E';//╔
205 : Result := Result + 'I';//═
211 : Result := Result + 'O';//Ë
218 : Result := Result + 'U';//┌
199 : Result := Result + 'C';//ă
220 : Result := Result + 'U';//▄
else
Result := Result + AValue[A];
end;
end;
Result := Trim(Result);
end;
{ TCIOTOperacaoTransporte }
function TCIOTOperacaoTransporte.AdicionarPagamento: Boolean;
var
CIOTRetorno: TOperacaoTransporteR;
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
Result := False;
if FConfiguracoes.Certificados.NumeroSerie = '' then
FConfiguracoes.Certificados.NumeroSerie := FConfiguracoes.Certificados.SelecionarCertificado;
LoadMsgEntrada(opAdicionarPagamento);
LoadURL;
Result := False;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <AdicionarPagamento xmlns="http://schemas.ipc.adm.br/efrete/pef"> ';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </AdicionarPagamento>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/pef/AdicionarPagamento';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-adicionar-Pagamento.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/pef/AdicionarPagamento"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'AdicionarPagamentoResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'AdicionarPagamentoResponse');
StrStream.Free;
{$ENDIF}
CIOTRetorno := TOperacaoTransporteR.Create(FOperacoesTransporte.Items[0], opAdicionarPagamento);
CIOTRetorno.Leitor.Arquivo := FRetWS;
CIOTRetorno.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'CIOT Gerado: '+CIOTRetorno.OperacaoTransporte.NumeroCIOT+LineBreak+
'Mensagem : '+CIOTRetorno.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+CIOTRetorno.Mensagem;
Result := (CIOTRetorno.Sucesso);
FSucesso := CIOTRetorno.Sucesso;
FMensagem := CIOTRetorno.Mensagem;
CIOTRetorno.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-adicionar-Pagamento.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-adicionar-Pagamento.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService OperacaoTransporte (AddPagamento):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService OperacaoTransporte (AddPagamento):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
function TCIOTOperacaoTransporte.AdicionarViagens: Boolean;
var
CIOTRetorno: TOperacaoTransporteR;
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
Result := False;
if FConfiguracoes.Certificados.NumeroSerie = '' then
FConfiguracoes.Certificados.NumeroSerie := FConfiguracoes.Certificados.SelecionarCertificado;
LoadMsgEntrada(opAdicionarViagem);
LoadURL;
Result := False;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <AdicionarViagem xmlns="http://schemas.ipc.adm.br/efrete/pef"> ';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </AdicionarViagem>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/pef/AdicionarViagem';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-adicionar-Viagem.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/pef/AdicionarViagem"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'AdicionarViagemResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'AdicionarViagemResponse');
StrStream.Free;
{$ENDIF}
CIOTRetorno := TOperacaoTransporteR.Create(FOperacoesTransporte.Items[0], opAdicionarViagem);
CIOTRetorno.Leitor.Arquivo := FRetWS;
CIOTRetorno.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'CIOT Gerado: '+CIOTRetorno.OperacaoTransporte.NumeroCIOT+LineBreak+
'Mensagem : '+CIOTRetorno.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+CIOTRetorno.Mensagem;
Result := (CIOTRetorno.Sucesso);
FSucesso := CIOTRetorno.Sucesso;
FMensagem := CIOTRetorno.Mensagem;
CIOTRetorno.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-adicionar-Viagem.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-adicionar-Viagem.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService OperacaoTransporte (AddViagem):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService OperacaoTransporte (AddViagem):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
function TCIOTOperacaoTransporte.Cancelar(ANumeroCIOT, AMotivo: string): Boolean;
var
CIOTRetorno: TOperacaoTransporteR;
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
Clear;
Result := False;
if not Assigned(FOperacoesTransporte.Items[0]) then
FOperacoesTransporte.Add;
// FOT := TOperacaoTransporte.Create(FAmSCIOT);
FOperacoesTransporte.Items[0].NumeroCIOT := ANumeroCIOT;
FOperacoesTransporte.Items[0].Cancelamento.Motivo := AMotivo;
if FConfiguracoes.Certificados.NumeroSerie = '' then
FConfiguracoes.Certificados.NumeroSerie := FConfiguracoes.Certificados.SelecionarCertificado;
LoadMsgEntrada(opCancelar);
LoadURL;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <CancelarOperacaoTransporte xmlns="http://schemas.ipc.adm.br/efrete/pef">';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </CancelarOperacaoTransporte>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/pef/CancelarOperacaoTransporte';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-cancelar-OperacaoTransporte.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/pef/CancelarOperacaoTransporte');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'CancelarOperacaoTransporteResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'CancelarOperacaoTransporteResponse');
StrStream.Free;
{$ENDIF}
CIOTRetorno := TOperacaoTransporteR.Create(FOperacoesTransporte.Items[0], opCancelar);
CIOTRetorno.Leitor.Arquivo := FRetWS;
CIOTRetorno.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
// aMsg := 'CNPJ : '+CIOTRetorno.OperacaoTransporte.CNPJ+LineBreak+
// 'RazaoSocial : '+CIOTRetorno.OperacaoTransporte.RazaoSocial+LineBreak+
// 'Proprietario.Endereco.Rua : '+CIOTRetorno.OperacaoTransporte.Endereco.Rua+LineBreak +
// 'Sucesso : '+BoolToStr(CIOTRetorno.Sucesso)+LineBreak+
// 'Mensagem : '+CIOTRetorno.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+CIOTRetorno.Mensagem;
Result := (CIOTRetorno.Sucesso) or (FOperacoesTransporte.Items[0].Cancelamento.Protocolo <> '');
FSucesso := CIOTRetorno.Sucesso;
FMensagem := CIOTRetorno.Mensagem;
CIOTRetorno.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-CancelarOperacaoTransporte.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-CancelarOperacaoTransporte.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService OperacaoTransporte (Cancelar):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService OperacaoTransporte (Cancelar):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
function TCIOTOperacaoTransporte.CancelarPagamento(AIdPagamento, AMotivo: string): Boolean;
var
CIOTRetorno: TOperacaoTransporteR;
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
Clear;
Result := False;
if not Assigned(FOperacoesTransporte.Items[0]) then
FOperacoesTransporte.Add;
// FOperacoesTransporte := TOperacaoTransporte.Create(FAmSCIOT);
FOperacoesTransporte.Items[0].Cancelamento.IdPagamentoCliente := AIdPagamento;
FOperacoesTransporte.Items[0].Cancelamento.Motivo := AMotivo;
if FConfiguracoes.Certificados.NumeroSerie = '' then
FConfiguracoes.Certificados.NumeroSerie := FConfiguracoes.Certificados.SelecionarCertificado;
LoadMsgEntrada(opCancelarPagamento);
LoadURL;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <CancelarPagamento xmlns="http://schemas.ipc.adm.br/efrete/pef">';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </CancelarPagamento>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/pef/CancelarPagamento';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-cancelar-Pagamento.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/pef/CancelarPagamento"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'CancelarOperacaoTransporteResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'CancelarOperacaoTransporteResponse');
StrStream.Free;
{$ENDIF}
CIOTRetorno := TOperacaoTransporteR.Create(FOperacoesTransporte.Items[0], opCancelarPagamento);
CIOTRetorno.Leitor.Arquivo := FRetWS;
CIOTRetorno.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'Pagamento cancelado: '+FOperacoesTransporte.Items[0].Cancelamento.IdPagamentoCliente+LineBreak+
'Mensagem : '+CIOTRetorno.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+CIOTRetorno.Mensagem;
Result := (CIOTRetorno.Sucesso);
FSucesso := CIOTRetorno.Sucesso;
FMensagem := CIOTRetorno.Mensagem;
CIOTRetorno.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-Pagamento.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-Pagamento.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService OperacaoTransporte (Cancelar Pagamento):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService OperacaoTransporte (Cancelar Pagamento):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
procedure TCIOTOperacaoTransporte.Clear;
begin
FMensagem := '';
FSucesso := False;
// if Assigned(FOperacaoTransporte) then FOperacaoTransporte.Free;
end;
constructor TCIOTOperacaoTransporte.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOperacoesTransporte := TOperacoesTransporte.Create(AOwner, TOperacaoTransporte);
end;
destructor TCIOTOperacaoTransporte.Destroy;
begin
FOperacoesTransporte.Free;
// if Assigned(FEventoRetorno) then
// FEventoRetorno.Free;
inherited;
end;
function TCIOTOperacaoTransporte.Encerrar: Boolean;
var
CIOTRetorno: TOperacaoTransporteR;
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
Result := False;
if FConfiguracoes.Certificados.NumeroSerie = '' then
FConfiguracoes.Certificados.NumeroSerie := FConfiguracoes.Certificados.SelecionarCertificado;
LoadMsgEntrada(opEncerrar);
LoadURL;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <EncerrarOperacaoTransporte xmlns="http://schemas.ipc.adm.br/efrete/pef">';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </EncerrarOperacaoTransporte>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/pef/EncerrarOperacaoTransporte';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-adicionar-Encerramento.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/pef/EncerrarOperacaoTransporte"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'EncerrarOperacaoTransporteResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'EncerrarOperacaoTransporteResponse');
StrStream.Free;
{$ENDIF}
CIOTRetorno := TOperacaoTransporteR.Create(FOperacoesTransporte.Items[0], opEncerrar);
CIOTRetorno.Leitor.Arquivo := FRetWS;
CIOTRetorno.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'CIOT Encerramento: '+CIOTRetorno.OperacaoTransporte.NumeroCIOT+LineBreak+
'Mensagem : '+CIOTRetorno.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+CIOTRetorno.Mensagem;
Result := (CIOTRetorno.Sucesso);
FSucesso := CIOTRetorno.Sucesso;
FMensagem := CIOTRetorno.Mensagem;
CIOTRetorno.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-EncerramentoCIOT.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-EncerramentoCIOT.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService OperacaoTransporte (Encerramento):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService OperacaoTransporte (Encerramento):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
procedure TCIOTOperacaoTransporte.Imprimir;
var
sArquivo: string;
begin
if FOperacoesTransporte.Items[0].NumeroCIOT <> '' then
begin
sArquivo := StringReplace(StringReplace(FOperacoesTransporte.Items[0].NumeroCIOT, '\', '_', []), '/', '_', []) + '.pdf';
CIOTUtil.ImprimirArquivo(PathWithDelim(TAmSCIOT( FOperacoesTransporte.Owner ).Configuracoes.Arquivos.PathPDF) + sArquivo);
// CIOTUtil.ImprimirArquivoDebenuPDF(PathWithDelim(TAmSCIOT( FOperacaoTransporte.Owner ).Configuracoes.Arquivos.PathPDF) + sArquivo);
end;
end;
function TCIOTOperacaoTransporte.ObterPDF(ANroCIOT: string; ATipoImpressao: TpciotTipoImpressao; AImprimir: Boolean): Boolean;
begin
Clear;
// if not Assigned(FOperacoesTransporte) then
// FOperacoesTransporte := TOperacaoTransporte.Create(FAmSCIOT);
if not Assigned(FOperacoesTransporte.Items[0]) then
FOperacoesTransporte.Add;
FOperacoesTransporte.Items[0].NumeroCIOT := ANroCIOT;
FTipoImpressao := ATipoImpressao;
Obter;
result := Self.Sucesso;// (FOperacoesTransporte.NumeroCIOT <> '');
if (FOperacoesTransporte.Items[0].NumeroCIOT <> '') and AImprimir then
Imprimir;
end;
function TCIOTOperacaoTransporte.Retificar: Boolean;
var
CIOTRetorno: TOperacaoTransporteR;
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
Clear;
Result := False;
if FConfiguracoes.Certificados.NumeroSerie = '' then
FConfiguracoes.Certificados.NumeroSerie := FConfiguracoes.Certificados.SelecionarCertificado;
LoadMsgEntrada(opRetificar);
LoadURL;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <RetificarOperacaoTransporte xmlns="http://schemas.ipc.adm.br/efrete/pef">';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </RetificarOperacaoTransporte>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/pef/RetificarOperacaoTransporte';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-retificar-OperacaoTransporte.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/pef/RetificarOperacaoTransporte"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'RetificarOperacaoTransporteResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'RetificarOperacaoTransporteResponse');
StrStream.Free;
{$ENDIF}
CIOTRetorno := TOperacaoTransporteR.Create(FOperacoesTransporte.Items[0], opRetificar);
CIOTRetorno.Leitor.Arquivo := FRetWS;
CIOTRetorno.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
// aMsg := 'CNPJ : '+CIOTRetorno.OperacaoTransporte.CNPJ+LineBreak+
// 'RazaoSocial : '+CIOTRetorno.OperacaoTransporte.RazaoSocial+LineBreak+
// 'Proprietario.Endereco.Rua : '+CIOTRetorno.OperacaoTransporte.Endereco.Rua+LineBreak +
// 'Sucesso : '+BoolToStr(CIOTRetorno.Sucesso)+LineBreak+
// 'Mensagem : '+CIOTRetorno.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+CIOTRetorno.Mensagem;
Result := (CIOTRetorno.Sucesso);
FSucesso := CIOTRetorno.Sucesso;
FMensagem := CIOTRetorno.Mensagem;
CIOTRetorno.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-RetificarOperacaoTransporte.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-RetificarOperacaoTransporte.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService OperacaoTransporte (Retificar):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService OperacaoTransporte (Retificar):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
function TCIOTOperacaoTransporte.Obter: Boolean;
var
CIOTRetorno: TOperacaoTransporteR;
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
inherited Obter;
Result := False;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
if FTipoImpressao = tiPDF then Texto := Texto + ' <ObterOperacaoTransportePdf xmlns="http://schemas.ipc.adm.br/efrete/pef">'
else Texto := Texto + ' <ObterOperacaoTransporteParaImpressao xmlns="http://schemas.ipc.adm.br/efrete/pef">';
Texto := Texto + FDadosMsg;
if FTipoImpressao = tiPDF then Texto := Texto + ' </ObterOperacaoTransportePdf>'
else Texto := Texto + ' </ObterOperacaoTransporteParaImpressao>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
if FTipoImpressao = tiPDF then ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/pef/ObterOperacaoTransportePdf'
else ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/pef/ObterOperacaoTransporteParaImpressao';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-obter-operacao_transporte.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
if FTipoImpressao = tiPDF then ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/pef/ObterOperacaoTransportePdf"')
else ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/pef/ObterOperacaoTransporteParaImpressao"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
StrStream.Free;
{$ENDIF}
if FTipoImpressao = tiPDF then FRetWS := SeparaDados( FRetornoWS, 'ObterOperacaoTransportePdfResponse')
else FRetWS := SeparaDados( FRetornoWS, 'ObterOperacaoTransporteParaImpressaoResponse');
CIOTRetorno := TOperacaoTransporteR.Create(FOperacoesTransporte.Items[0]);
CIOTRetorno.Leitor.Arquivo := FRetWS;
CIOTRetorno.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'Placa : '+CIOTRetorno.OperacaoTransporte.Contratado.CpfOuCnpj+LineBreak+
'Ano Modelo : '+CIOTRetorno.OperacaoTransporte.CodigoIdentificacaoOperacaoPrincipal+LineBreak+
'Ano Fabricacao : '+DateToStr(CIOTRetorno.OperacaoTransporte.DataFimViagem)+LineBreak +
'Sucesso : '+BoolToStr(CIOTRetorno.Sucesso)+LineBreak+
'Mensagem : '+CIOTRetorno.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+CIOTRetorno.Mensagem;
Result := (CIOTRetorno.Sucesso);
FSucesso := CIOTRetorno.Sucesso;
FMensagem := CIOTRetorno.Mensagem;
CIOTRetorno.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-operacao_transporte.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-operacao_transporte.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService Operacao de Transporte:'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService Operacao de Transporte:'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
function TCIOTOperacaoTransporte.Adicionar: Boolean;
var
CIOTRetorno: TOperacaoTransporteR;
aMsg : string;
Texto : String;
Acao : TStringList;
Stream: TMemoryStream;
StrStream: TStringStream;
{$IFDEF ACBrCTeOpenSSL}
HTTP: THTTPSend;
{$ELSE}
ReqResp: THTTPReqResp;
{$ENDIF}
begin
inherited Adicionar;
Result := False;
Acao := TStringList.Create;
Stream := TMemoryStream.Create;
Texto := '<?xml version="1.0" encoding="utf-8"?>';
Texto := Texto + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
Texto := Texto + '<soap12:Body>';
Texto := Texto + ' <AdicionarOperacaoTransporte xmlns="http://schemas.ipc.adm.br/efrete/pef">';
Texto := Texto + FDadosMsg;
Texto := Texto + ' </AdicionarOperacaoTransporte>';
Texto := Texto + '</soap12:Body>';
Texto := Texto + '</soap12:Envelope>';
Acao.Text := Texto;
{$IFDEF ACBrCTeOpenSSL}
Acao.SaveToStream(Stream);
HTTP := THTTPSend.Create;
{$ELSE}
ReqResp := THTTPReqResp.Create(nil);
ConfiguraReqResp( ReqResp );
ReqResp.URL := Trim(FURL);
ReqResp.UseUTF8InHeader := True;
ReqResp.SoapAction := 'http://schemas.ipc.adm.br/efrete/pef/AdicionarOperacaoTransporte';
{$ENDIF}
try
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTObtendo );
if FConfiguracoes.Geral.Salvar then
begin
FPathArqEnv := FormatDateTime('yyyymmddhhnnss',Now)+'-adicionar-OperacaoTransporte.xml';
FConfiguracoes.Geral.Save(FPathArqEnv, FDadosMsg, FConfiguracoes.Arquivos.PathLog);
end;
try
{$IFDEF ACBrCTeOpenSSL}
HTTP.Document.LoadFromStream(Stream);
ConfiguraHTTP(HTTP,'SOAPAction: "http://schemas.ipc.adm.br/efrete/pef/AdicionarOperacaoTransporte"');
HTTP.HTTPMethod('POST', FURL);
StrStream := TStringStream.Create('') ;
StrStream.CopyFrom(HTTP.Document, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'AdicionarOperacaoTransporteResponse');
StrStream.Free;
{$ELSE}
ReqResp.Execute(Acao.Text, Stream);
StrStream := TStringStream.Create('');
StrStream.CopyFrom(Stream, 0);
FRetornoWS := TiraAcentos(ParseText(StrStream.DataString, True));
FRetWS := SeparaDados( FRetornoWS, 'AdicionarOperacaoTransporteResponse');
StrStream.Free;
{$ENDIF}
CIOTRetorno := TOperacaoTransporteR.Create(FOperacoesTransporte.Items[0], opAdicionar);
CIOTRetorno.Leitor.Arquivo := FRetWS;
CIOTRetorno.LerXml;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
aMsg := 'CIOT Gerado: '+CIOTRetorno.OperacaoTransporte.NumeroCIOT+LineBreak+
'Mensagem : '+CIOTRetorno.Mensagem+LineBreak;
if FConfiguracoes.WebServices.Visualizar then
ShowMessage(aMsg);
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog(aMsg);
FMsg := LineBreak+CIOTRetorno.Mensagem;
Result := (CIOTRetorno.Sucesso);
FSucesso := CIOTRetorno.Sucesso;
FMensagem := CIOTRetorno.Mensagem;
CIOTRetorno.Free;
if FConfiguracoes.Geral.Salvar then
begin
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-response-AddOperacaoTransporte.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetWS, FConfiguracoes.Arquivos.PathLog);
FPathArqResp := FormatDateTime('yyyymmddhhnnss',Now)+'-wsRet-AddOperacaoTransporte.xml';
FConfiguracoes.Geral.Save(FPathArqResp, FRetornoWS, FConfiguracoes.Arquivos.PathLog);
end;
except on E: Exception do
begin
if Assigned(TAmSCIOT( FAmSCIOT ).OnGerarLog) then
TAmSCIOT( FAmSCIOT ).OnGerarLog('WebService OperacaoTransporte (Inclusao):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
raise Exception.Create('WebService OperacaoTransporte (Inclusao):'+LineBreak+
'- Inativo ou Inoperante tente novamente.'+LineBreak+
'- '+FMensagem + LineBreak +
'- '+E.Message);
end;
end;
finally
{$IFDEF ACBrCTeOpenSSL}
HTTP.Free;
{$ELSE}
ReqResp.Free;
{$ENDIF}
Acao.Free;
Stream.Free;
ConfAmbiente;
TAmSCIOT( FAmSCIOT ).SetStatus( stCIOTIdle );
end;
end;
end.
|
unit uDepartamentoAcesso;
interface
uses System.Generics.Collections, System.SysUtils;
type
TDepartamentoAcesso = class
private
FExcluir: Boolean;
FIncluir: Boolean;
FTabela: string;
FPrograma: Integer;
FRelatorio: Boolean;
FAcesso: Boolean;
FEditar: Boolean;
public
property Programa: Integer read FPrograma write FPrograma;
property Tabela: string read FTabela write FTabela;
property Acesso: Boolean read FAcesso write FAcesso;
property Incluir: Boolean read FIncluir write FIncluir;
property Editar: Boolean read FEditar write FEditar;
property Excluir: Boolean read FExcluir write FExcluir;
property Relatorio: Boolean read FRelatorio write FRelatorio;
end;
TDepartamentoAcessoNegocio = class
private
function PopularDados(APrograma: Integer; ATabela: string): TDepartamentoAcesso;
public
function Listar: TObjectList<TDepartamentoAcesso>;
end;
implementation
{ TDepartamentoAcessoNegocio }
function TDepartamentoAcessoNegocio.Listar: TObjectList<TDepartamentoAcesso>;
var
Lista: TObjectList<TDepartamentoAcesso>;
begin
Lista := TObjectList<TDepartamentoAcesso>.Create();
Lista.Add(PopularDados(001, 'Chamados'));
Lista.Add(PopularDados(002, 'Visitas'));
Lista.Add(PopularDados(003, 'Solicitações'));
Lista.Add(PopularDados(004, 'Versao'));
Lista.Add(PopularDados(006, 'Base Conh.'));
Lista.Add(PopularDados(100, 'Revenda'));
Lista.Add(PopularDados(101, 'Produto'));
Lista.Add(PopularDados(102, 'Modulo'));
Lista.Add(PopularDados(103, 'Cliente'));
Lista.Add(PopularDados(104, 'Usuario'));
Lista.Add(PopularDados(105, 'Departamento'));
Lista.Add(PopularDados(106, 'Tipo'));
Lista.Add(PopularDados(107, 'Status'));
Lista.Add(PopularDados(108, 'Especificações'));
Lista.Add(PopularDados(109, 'Parâmetros'));
Lista.Add(PopularDados(110, 'Contas Email'));
Lista.Add(PopularDados(111, 'Atividades'));
Lista.Add(PopularDados(112, 'Agendamento'));
Lista.Add(PopularDados(114, 'Orçamento'));
Lista.Add(PopularDados(115, 'FormaPagto'));
Lista.Add(PopularDados(116, 'Observação'));
Lista.Add(PopularDados(117, 'Mod.Relatório'));
Lista.Add(PopularDados(118, 'Ramais'));
Lista.Add(PopularDados(119, 'Recados'));
Lista.Add(PopularDados(120, 'Escalas'));
Lista.Add(PopularDados(121, 'Cidades'));
Lista.Add(PopularDados(122, 'Licencas'));
Lista.Add(PopularDados(123, 'Feriados'));
Lista.Add(PopularDados(124, 'Categorias'));
Lista.Add(PopularDados(125, 'Tab.Preços'));
Result := Lista;
end;
function TDepartamentoAcessoNegocio.PopularDados(
APrograma: Integer; ATabela: string): TDepartamentoAcesso;
var
obj: TDepartamentoAcesso;
begin
obj := TDepartamentoAcesso.Create;
obj.Programa := APrograma;
obj.Tabela := ATabela;
obj.Acesso := False;
obj.Incluir := True;
obj.Editar := True;
obj.Excluir := True;
obj.Relatorio := True;
Result := obj;
end;
end.
|
unit uProjectConstants;
interface
type
TXMLFldNames = (xfnLastBuildStatus,
xfnLastBuildLabel,
xfnactivity,
xfnName,
xfnLastBuildTime,
xfnwebUrl);
const
LIST_OF_COLUMNS : Array[TXMLFldNames] of String =
(
'Status',
'Label',
'Activity',
'Name',
'Time',
'URL'
);
LIST_OF_XML_FIELD_NAMES : Array[TXMLFldNames] of String =
(
'lastBuildStatus',
'lastBuildLabel',
'activity',
'name',
'lastBuildTime',
'webUrl'
);
MIN_SG_COL_COUNT = Low(TXMLFldNames);
MAX_SG_COL_COUNT = High(TXMLFldNames);
MIN_SG_COL_COUNT_INT = Integer(MIN_SG_COL_COUNT);
MAX_SG_COL_COUNT_INT = Integer(MAX_SG_COL_COUNT);
SG_COL_WIDTH_NAME = 450;
SG_COL_WIDTH_TIME = 180;
TIMER_INTERVAL = 60000;
resourcestring
rsProjects = 'http://%s:%d/app/rest/cctray/projects.xml';
rsXMLPath = '../testdata/test.xml';
implementation
end.
|
program Swap_Char;
procedure swap(var c1, c2 : char);
var c : char;
begin
c := c1;
c1 := c2;
c2 := c
end;
var test_str : string;
var i : integer;
begin
test_str := 'Test String for Swap';
for i := 1 to length(test_str) - 1 do
swap(test_str[i], test_str[i + 1]);
write(test_str)
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* 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.
*
**********************************************************************************************************************
* TERRA_Camera
* Implements a generic camera class
***********************************************************************************************************************
}
Unit TERRA_Camera;
{$I terra.inc}
Interface
Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF}
TERRA_String, TERRA_Utils, TERRA_Frustum, TERRA_BoundingBox, TERRA_Vector3D, TERRA_Matrix4x4, TERRA_Math, TERRA_Plane;
Const
MoveSpeed = 0.05;
RotSpeed = 2;
ZoomSpeed = 1;
MinPitch = -90;
MaxPitch = 90;
MinZoom = 60;
MaxZoom = 120;
camDirForward = 0;
camDirBackward = 1;
camDirLeft = 2;
camDirRight = 3;
Type
{ Camera }
Camera = Class(TERRAObject)
Protected
_Name:TERRAString;
_View:Vector3D;
_Position:Vector3D;
_Roll:Vector3D;
_Speed:Single;
_Transform:Matrix4x4;
_ScreenMatrix4x4:Matrix4x4;
_ProjectionMatrix4x4:Matrix4x4;
_Ortho:Boolean;
_OrthoX1:Single;
_OrthoX2:Single;
_OrthoY1:Single;
_OrthoY2:Single;
_OrthoScale:Single;
_NeedsUpdate:Boolean;
_LastOrientation:Single;
_Width, _Height:Integer;
_Near:Single;
_Far:Single;
_FOV:Single;
_Ratio:Single;
_CurrentEye:Integer;
_ClipPlane:Plane;
_UseClipPlane:Boolean;
_FrustumCorners:Array[0..7] Of Vector3D;
_Frustum:Frustum;
_Up:Vector3D;
_Right:Vector3D;
_Focus:Vector3D;
Procedure UpdateMatrix4x4(Eye:Integer);
Function ConvertPlaneWorldToCameraSpace(Point, Normal:Vector3D):Plane;
Public
Constructor Create(Name:TERRAString);
Procedure Release; Override;
Procedure Update(Width, Height, Eye:Integer);
Procedure Refresh();
Procedure SetupUniforms;
Procedure FreeCam;
Procedure Rotate(rotX, rotY:Single);
Procedure SetFocusPoint(Const P:Vector3D);
Procedure SetView(NewView:Vector3D);
Procedure SetPosition(NewPos:Vector3D);
Procedure SetRoll(NewRoll:Vector3D);
Procedure SetOrthoMode(Enabled:Boolean; X1,Y1,X2,Y2:Single);
Procedure SetOrthoScale(Value:Single);
Procedure SetNear(Value:Single);
Procedure SetFar(Value:Single);
Procedure SetFOV(Value:Single);
Procedure SetRatio(Value:Single);
Procedure LookAt(P:Vector3D);
Procedure Move(Dir:Integer; Speed:Single);
Procedure AdjustToFit(Box:BoundingBox);
Procedure SetClipPlane(Point, Normal:Vector3D);
Procedure RemoveClipPlane();
Property Position:Vector3D Read _Position Write SetPosition;
Property View:Vector3D Read _View Write SetView;
Property Roll:Vector3D Read _Roll Write _Roll;
Property Ortho:Boolean Read _Ortho;
Property OrthoScale:Single Read _OrthoScale Write SetOrthoScale;
Property Transform:Matrix4x4 Read _Transform;
Property Projection:Matrix4x4 Read _ProjectionMatrix4x4;
Property ScreenMatrix4x4:Matrix4x4 Read _ScreenMatrix4x4;
Property Speed:Single Read _Speed Write _Speed;
Property Near:Single Read _Near Write SetNear;
Property Far:Single Read _Far Write SetFar;
Property FOV:Single Read _FOV Write SetFOV;
Property Frustum:TERRA_Frustum.Frustum Read _Frustum;
Property Up:Vector3D Read _Up;
Property Right:Vector3D Read _Right;
Property Name:TERRAString Read _Name Write _Name;
Property Ratio:Single Read _Ratio Write SetRatio;
Property UseClipPlane:Boolean Read _UseClipPlane;
Property FocusPoint:Vector3D Read _Focus Write SetFocusPoint;
End;
Implementation
Uses TERRA_OS, TERRA_Application, TERRA_Lights, TERRA_GraphicsManager, TERRA_Renderer, TERRA_InputManager, TERRA_Log, Math;
// Camera
constructor Camera.Create(Name: TERRAString);
Begin
_Name := Name;
_Roll := VectorUp;
_FOV := 45.0;
_LastOrientation := -1;
_Position := VectorCreate(0.0, 0.0, 1.0);
_View := VectorCreate(0.0, 0.0, -1.0);
_Near := 1.0;
_Far := 300.0;
_Speed := 4.0;// * GL_WORLD_SCALE;
_Ortho := False;
_OrthoScale := 1.0;
_NeedsUpdate := True;
End;
procedure Camera.SetPosition(NewPos: Vector3D);
Begin
_Position:= NewPos;
_NeedsUpdate := True;
End;
procedure Camera.SetView(NewView: Vector3D);
Begin
// NewView := VectorCreate(0,-1,0);
_View := NewView;
_NeedsUpdate := True;
End;
procedure Camera.SetRoll(NewRoll: Vector3D);
Begin
_Roll:= NewRoll;
_NeedsUpdate := True;
End;
procedure Camera.UpdateMatrix4x4(Eye: Integer);
Const
ZoomFactor = 1;
Var
P:Vector3D;
Zoom:Single;
Proj:Matrix4x4;
Begin
_NeedsUpdate := False;
{$IFDEF EMULATED_LANDSCAPE}
// If (Application.Instance.IsLandscape()) And (_Target<>Nil) Then
_Ratio := SafeDiv(_Height, _Width, 1.0) * SafeDiv(GraphicsManager.Instance.Height, GraphicsManager.Instance.Width, 1.0);
{$ELSE}
_Ratio := SafeDiv(_Width, _Height, 1.0);
{$ENDIF}
If (_Ortho) Then
_ProjectionMatrix4x4 := Matrix4x4Ortho(Ratio*_OrthoX1*_OrthoScale, Ratio*_OrthoX2*_OrthoScale,
_OrthoY1*_OrthoScale, _OrthoY2*_OrthoScale, _Near, _Far)
Else
{$IFDEF DISABLEVR}
_ProjectionMatrix4x4 := Matrix4x4Perspective(FOV, Ratio, _Near, _Far);
{$ELSE}
_ProjectionMatrix4x4 := Application.Instance.GetVRProjectionMatrix(Eye, FOV, Ratio, _Near, _Far);
{$ENDIF}
//Log(logDebug, 'Viewport', 'X:'+IntToString(Trunc(_X)) +' Y:'+IntToString(Trunc(_Y)));
// Log(logDebug, 'Viewport', 'W:'+IntToString(Trunc(_Width)) +' W:'+IntToString(Trunc(_Height)));
P := _Position;
{ If GraphicsManager.Instance.LandscapeOrientation Then
_Up := VectorCreate(_Roll.Y, _Roll.X, _Roll.Z)
Else}
_Transform := Matrix4x4LookAt(P, VectorAdd(_Position, _View), _Roll);
_ScreenMatrix4x4 := _Transform;
_Up := _Roll;
{ If (Abs(_Up.Dot(_View))>=0.9) Then
Begin
_Up.Y := _Roll.Z;
_Up.Z := _Roll.Y;
_Right := VectorCross(_Up, _View);
_Up := VectorCross(_View, _Right);
End Else}
Begin
_Right := VectorCross(_Up, _View);
_Up := VectorCross(_View, _Right);
End;
//_Right.Normalize;
//_Up.Normalize;
{If Self._UseClipPlane Then
CalculateObliqueMatrix4x4ClipPlane(_ProjectionMatrix4x4, _Transform, _ClipPlane);}
_Frustum.Update(_ProjectionMatrix4x4, Self._Transform);
End;
procedure Camera.SetOrthoScale(Value: Single);
Begin
If (_OrthoScale = Value) Then
Exit;
_OrthoScale := Value;
_NeedsUpdate := True;
End;
procedure Camera.SetOrthoMode(Enabled: Boolean; X1, Y1, X2, Y2: Single);
Begin
If (Ortho = Enabled) Then
Exit;
_Ortho := Enabled;
_NeedsUpdate := True;
_OrthoX1 := X1;
_OrthoX2 := X2;
_OrthoY1 := Y1;
_OrthoY2 := Y2;
End;
procedure Camera.Update(Width, Height, Eye: Integer);
Begin
_Width := Width;
_Height := Height;
If (Eye <> _CurrentEye) Then
Begin
_CurrentEye := Eye;
_NeedsUpdate := True;
End;
If (_NeedsUpdate) Then
UpdateMatrix4x4(Eye);
End;
procedure Camera.Rotate(rotX, rotY: Single);
Var
rot_axis:Vector3D;
Begin
rotX := rotX * (Speed * GraphicsManager.Instance.ElapsedTime) * 0.5;
rotY := rotY * (Speed * GraphicsManager.Instance.ElapsedTime) * 0.5;
_view.Rotate(VectorUp, rotX);
rot_axis := VectorCreate(-_view.z, 0.0, _view.x);
rot_axis.Normalize;
_view.Rotate(rot_axis, rotY);
_view.Normalize;
_NeedsUpdate := True;
End;
Procedure Camera.SetFocusPoint(const P: Vector3D);
Begin
_Focus := P;
End;
procedure Camera.SetupUniforms;
Var
_Shader:ShaderInterface;
P:Vector3D;
A,B,C, Delta:Single;
Begin
_Shader := GraphicsManager.Instance.Renderer.ActiveShader;
If (_Shader=Nil) Then
Exit;
_Shader.SetVec3Uniform('cameraPosition', _Position);
_Shader.SetVec3Uniform('cameraView', _View);
_Shader.SetMat4Uniform('cameraMatrix', _Transform);
_Shader.SetMat4Uniform('projectionMatrix', _ProjectionMatrix4x4);
_Shader.SetFloatUniform('zNear', _Near);
_Shader.SetFloatUniform('zFar', _Far);
If (_UseClipPlane) Then
_Shader.SetPlaneUniform('clipPlane', _ClipPlane);
If (GraphicsManager.Instance.Renderer.Settings.FogMode<>0) Then
Begin
_Shader.SetColorUniform('fogColor', GraphicsManager.Instance.Renderer.Settings.FogColor);
If (GraphicsManager.Instance.Renderer.Settings.FogMode And fogDistance<>0) Then
Begin
A := GraphicsManager.Instance.Renderer.Settings.FogDistanceStart;
B := GraphicsManager.Instance.Renderer.Settings.FogDistanceEnd;
C := (B-A) * 0.5;
_Shader.SetFloatUniform('fogDistanceCenter', C + A);
_Shader.SetFloatUniform('fogDistanceSize', C);
End;
If (GraphicsManager.Instance.Renderer.Settings.FogMode And fogHeight<>0) Then
Begin
_Shader.SetFloatUniform('fogHeightStart', GraphicsManager.Instance.Renderer.Settings.FogHeightStart);
_Shader.SetFloatUniform('fogHeightEnd', GraphicsManager.Instance.Renderer.Settings.FogHeightEnd);
End;
If (GraphicsManager.Instance.Renderer.Settings.FogMode And fogBox<>0) Then
Begin
_Shader.SetVec3Uniform('fogBoxAreaStart', GraphicsManager.Instance.Renderer.Settings.FogBoxArea.StartVertex);
_Shader.SetVec3Uniform('fogBoxAreaEnd', GraphicsManager.Instance.Renderer.Settings.FogBoxArea.EndVertex);
_Shader.SetFloatUniform('fogBoxSize', GraphicsManager.Instance.Renderer.Settings.FogBoxSize);
End;
End;
End;
procedure Camera.SetFOV(Value: Single);
Begin
If (Value = _FOV) Then
Exit;
_FOV := Value;
_NeedsUpdate := True;
End;
procedure Camera.SetFar(Value: Single);
Begin
If (Value = _Far) Then
Exit;
_Far := Value;
_NeedsUpdate := True;
End;
procedure Camera.SetNear(Value: Single);
Begin
If (Value = _Near) Then
Exit;
_Near := Value;
_NeedsUpdate := True;
End;
procedure Camera.AdjustToFit(Box: BoundingBox);
Var
oneOverSine:Single;
distanceToCenter:Single;
offset, Center:Vector3D;
p,N:Vector3D;
Begin
Center := Box.Center;
offset := VectorSubtract(Box.EndVertex, Center); // Radius of bounding sphere
P := center;
oneOverSine := 1.0 / Tan(_FOV *RAD / 4.0); // 1 / sin = adjacent / opposite
distanceToCenter := Offset.Length * oneOverSine; // (adjacent / opposite) * opposite = adjacent
N := VectorConstant(1);
N.Normalize;
P.Add( VectorScale(N, distanceToCenter));
SetPosition(P);
P.Subtract(Center);
P.Normalize;
P.Scale(-1);
SetView(P);
End;
procedure Camera.LookAt(P: Vector3D);
Begin
P := VectorSubtract(P, _Position);
P.Normalize;
SetView(P);
End;
procedure Camera.FreeCam;
Var
Walk_speed:Single;
Rot:Single;
Input:InputManager;
Begin
Walk_Speed := GraphicsManager.Instance.ElapsedTime * Speed * 3.0;
Input := InputManager.Instance;
If (Input.Keys.IsDown(keyShift)) Then
Walk_speed := Walk_speed * 8;
If (Input.Keys.IsDown(keyW)) Then
Move(camDirForward, Walk_Speed);
If (Input.Keys.IsDown(keyS)) Then
Move(camDirBackward, Walk_Speed);
If (Input.Keys.IsDown(keyA)) Then
Move(camDirLeft, Walk_Speed);
If (Input.Keys.IsDown(keyD)) Then
Move(camDirRight, Walk_Speed);
If (Input.Keys.IsDown(keyQ)) Then
_position.y := _position.y -walk_speed;
If (Input.Keys.IsDown(keyE)) Then
_position.y := _position.y + walk_speed;
{$IFDEF MOBILE}
Rot := 0.125;
{$ELSE}
Rot := 0.5;
{$ENDIF}
If (Input.Keys.IsDown(keyLEFT)) Then
Self.Rotate(Rot, 0.0);
If (Input.Keys.IsDown(keyRight)) Then
Self.Rotate(-Rot, 0.0);
If (Input.Keys.IsDown(keyUp)) Then
Self.Rotate(0.0, Rot);
If (Input.Keys.IsDown(keyDown)) Then
Self.Rotate(0.0, -Rot);
_NeedsUpdate := True;
End;
procedure Camera.Move(Dir: Integer; Speed: Single);
Begin
Case Dir Of
camdirForward: _position := VectorAdd(_position, VectorScale(_view, Speed));
camdirBackward: _position := VectorAdd(_position, VectorScale(_view, -Speed));
camdirLeft:
Begin
_position.x := _position.x + (_view.z * Speed);
_position.z := _position.z - (_view.x * Speed);
End;
camdirRight:
Begin
_position.x := _position.x -( _view.z * Speed);
_position.z := _position.z + (_view.x * Speed);
End;
End;
_NeedsUpdate := True;
End;
function Camera.ConvertPlaneWorldToCameraSpace(Point, Normal: Vector3D): Plane;
Var
A,B,C,N:Single;
pX, pY, pZ, pW:Single; //transformed point
nX, nY, nZ, nW, inverse_normal_length:Single; //transformed normal
Begin
A := Point.X;
B := Point.Y;
C := Point.Z;
Result := PlaneCreate(Point, Normal);
N := (_Position.X * Result.A) + (_Position.Y * Result.B) + (_Position.Z * Result.C) + (1 * Result.D);
pX := A*_Transform.V[0] + B*_Transform.V[4] + C*_Transform.V[8] + _Transform.V[12];
pY := A*_Transform.V[1] + B*_Transform.V[5] + C*_Transform.V[9] + _Transform.V[13];
pZ := A*_Transform.V[2] + B*_Transform.V[6] + C*_Transform.V[10] + _Transform.V[14];
pW := 1;
//transforming normal
A := Normal.X;
B := Normal.Y;
C := Normal.Z;
nX := A*_Transform.V[0] + B*_Transform.V[4] + C*_Transform.V[8];
nY := A*_Transform.V[1] + B*_Transform.V[5] + C*_Transform.V[9];
nZ := A*_Transform.V[2] + B*_Transform.V[6] + C*_Transform.V[10];
nW := 0;
//normalize
inverse_normal_length := 1.0 / sqrt( nX*nX + nY*nY + nZ*nZ );
nX := nX * inverse_normal_length;
nY := nY * inverse_normal_length;
nZ := nZ * inverse_normal_length;
//clip plane values
Result.A := nX;
Result.B := nY;
Result.C := nZ;
//dot between normal and point
Result.D := -(pX*nX + pY*nY + pZ*nZ);
If (N>0) Then
Begin
Result.A := -Result.A;
Result.B := -Result.B;
Result.C := -Result.C;
Result.D := -Result.D;
End;
End;
procedure Camera.SetClipPlane(Point, Normal: Vector3D);
{$IFDEF PC}
Var
Clip:Array[0..4] Of Double;
{$ENDIF}
Begin
{$IFDEF MOBILE}
Exit;
{$ENDIF}
_UseClipPlane := True;
//_ClipPlane := ConvertPlaneWorldToCameraSpace(Point, Normal);
_ClipPlane := PlaneCreate(Point, Normal);
(* If Not GraphicsManager.Instance.Renderer.Features.Shaders.Avaliable Then
Begin
{$IFDEF PC}
Clip[0] := _ClipPlane.A;
Clip[1] := _ClipPlane.B;
Clip[2] := _ClipPlane.C;
Clip[3] := _ClipPlane.D;
glClipPlane(GL_CLIP_PLANE0, @Clip);
glEnable(GL_CLIP_PLANE0);
{$ENDIF}
Exit;
End; BIBI
*)
UpdateMatrix4x4(0);
End;
procedure Camera.RemoveClipPlane;
Begin
If Not _UseClipPlane Then
Exit;
_UseClipPlane := False;
(* If Not GraphicsManager.Instance.Settings.Shaders.Avaliable Then
Begin
{$IFDEF PC}
glDisable(GL_CLIP_PLANE0);
{$ENDIF}
Exit;
End; BIBI
*)
UpdateMatrix4x4(0);
End;
procedure Camera.SetRatio(Value: Single);
Begin
If (_Ratio = Value) Then
Exit;
_Ratio := Value;
_NeedsUpdate := True;
End;
procedure Camera.Refresh;
Begin
_NeedsUpdate := True;
End;
procedure Camera.Release;
Begin
// do nothing
End;
End.
|
//Exercicio 61: Escreva um algoritmo para ler um número real e, a seguir, ler e exibir uma lista de números reais até
//que seja lido um número igual ao primeiro lido. Nem o primeiro número nem o último devem ser exibidos
{ Solução em Portugol
Algoritmo Exercicio 61;
Var
segredo, numero: real;
Inicio
exiba("Digite um número qualquer: ");
leia(segredo);
numero <- segredo - 1; // Isso é só pra evitar que não se entre no loop.
enquanto(segredo <> numero)faça
exiba("Digite um número: ");
leia(numero);
se(numero <> segredo)
então exiba("O número digitado foi: ", numero);
fimse;
fimenquanto;
Fim.
}
// Solução em Pascal
Program Exercicio61;
uses crt;
var
segredo, numero: real;
begin
clrscr;
writeln('Digite um número qualquer: ');
readln(segredo);
numero := segredo - 1; // Isso é só pra evitar que não se entre no loop.
while(segredo <> numero)do
Begin
writeln('Digite um número: ');
readln(numero);
if(numero <> segredo)
then writeln('O número digitado foi: ', numero:0:2);
End;
repeat until keypressed;
end. |
program DammCheckDigit;
uses
sysutils;
const damm : array[0..9,0..9] of integer =
( (0,3,1,7,5,9,8,6,4,2),
(7,0,9,2,1,5,4,8,6,3),
(4,2,0,6,8,7,1,3,5,9),
(1,7,5,0,9,8,3,4,2,6),
(6,1,2,3,0,4,5,9,7,8),
(3,6,7,4,2,0,9,5,8,1),
(5,8,6,9,7,2,0,1,3,4),
(8,9,4,5,3,6,2,0,1,7),
(9,4,3,8,6,1,7,2,0,5),
(2,5,8,1,4,3,6,7,9,0) );
function is_valid(num : integer) : boolean;
var
temp, i : integer;
n_str : string;
begin
n_str := inttostr(num);
temp := 0;
for i := 0 to length(n_str) do
begin
temp := damm[temp, ord(n_str[i]) - ord ('0')];
end;
is_valid := temp=0;
end;
var
i : integer;
begin
writeln('Valid numbers between 5700 and 5800 are:');
for i := 5700 to 5800 do
begin
if is_valid(i) then
write(i, ' ');
end;
writeln
end.
{
Valid numbers between 5700 and 5800 are:
5708 5719 5724 5735 5743 5756 5762 5770 5781 5797
}
|
unit SimulacaoPagamento.Crediario;
interface
uses
SimulacaoPagamento.Interfaces;
type
TSimulacaoPagamentoCrediario = class(TInterfacedObject, iSimulacaoCrediario)
private
[Weak]
FParent : iSimulacaoPagamento;
FdiaVencimento : Integer;
FJuros : Boolean;
public
constructor Create(Parent : iSimulacaoPagamento);
destructor Destroy; override;
class function New(Parent : iSimulacaoPagamento) : iSimulacaoCrediario;
function diaVencimento ( aValue : Integer ) : iSimulacaoCrediario; overload;
function diaVencimento : Integer; overload;
function Juros ( aValue : Boolean ) : iSimulacaoCrediario; overload;
function Juros : Boolean; overload;
function &End : iSimulacaoPagamento;
end;
implementation
{ TSimulacaoPagamentoCrediario }
function TSimulacaoPagamentoCrediario.&End: iSimulacaoPagamento;
begin
Result := FParent;
end;
function TSimulacaoPagamentoCrediario.Juros: Boolean;
begin
Result := FJuros;
end;
constructor TSimulacaoPagamentoCrediario.Create(Parent : iSimulacaoPagamento);
begin
FParent := Parent;
end;
destructor TSimulacaoPagamentoCrediario.Destroy;
begin
inherited;
end;
function TSimulacaoPagamentoCrediario.diaVencimento: Integer;
begin
Result := FdiaVencimento;
end;
function TSimulacaoPagamentoCrediario.diaVencimento(
aValue: Integer): iSimulacaoCrediario;
begin
Result := Self;
FdiaVencimento := aValue;
end;
function TSimulacaoPagamentoCrediario.Juros(
aValue: Boolean): iSimulacaoCrediario;
begin
Result := Self;
FJuros := aValue;
end;
class function TSimulacaoPagamentoCrediario.New(Parent : iSimulacaoPagamento) : iSimulacaoCrediario;
begin
Result := Self.Create(Parent);
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.Compression
Description : Compression functions
Author : Kike Pérez
Version : 1.2
Created : 14/08/2018
Modified : 05/09/2019
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Compression;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
ZLib,
System.NetEncoding;
type
TCompressionLevel = TZCompressionLevel;
function CompressString_Deprecated(const aStr : string; aCompressionLevel : TCompressionLevel = zcDefault) : string;
function DecompressString_Deprecated(const aStr: string) : string;
function CompressString(const aStr : string; aCompressionLevel : TCompressionLevel = zcDefault) : string;
function DecompressString(const aStr: string) : string;
function CompressGZipString(const aStr : string; aCompressionLevel : TCompressionLevel = zcDefault) : string;
function DecompressGZipString(const aStr: string) : string;
function CompressAndEncodeString(const aStr: string; aCompressionLevel : TCompressionLevel = zcDefault): string;
function DecodeAndDecompressString(const aStr: string): string;
implementation
function CompressString_Deprecated(const aStr : string; aCompressionLevel : TCompressionLevel = zcDefault) : string;
var
strstream : TStringStream;
zipstream : TStringStream;
begin
strstream := TStringStream.Create(aStr,TEncoding.UTF8);
try
zipstream := TStringStream.Create('',TEncoding.ANSI);
try
ZCompressStream(strstream, zipstream, aCompressionLevel);
zipstream.Position := 0;
Result := zipstream.DataString;
finally
zipstream.Free;
end;
finally
strstream.Free;
end;
end;
function DecompressString_Deprecated(const aStr: string) : string;
var
strstream : TStringStream;
zipstream : TStringStream;
begin
zipstream := TStringStream.Create(aStr,TEncoding.ANSI);
try
strstream := TStringStream.Create('',TEncoding.UTF8);
try
zipstream.Position := 0;
ZDecompressStream(zipstream,strstream);
strstream.Position := 0;
Result := strstream.DataString;
finally
strstream.Free;
end;
finally
zipstream.Free;
end;
end;
function CompressString(const aStr : string; aCompressionLevel : TCompressionLevel = zcDefault) : string;
var
instream : TStringStream;
zipstream : TMemoryStream;
outstream : TStringStream;
begin
instream := TStringStream.Create(aStr,TEncoding.UTF8);
try
zipstream := TMemoryStream.Create;
try
ZCompressStream(instream,zipstream,aCompressionLevel);
zipstream.Position := 0;
outstream := TStringStream.Create('',TEncoding.UTF8);
try
outstream.CopyFrom(zipstream,0);
Result := string(outstream.DataString);
finally
outstream.Free;
end;
finally
zipstream.Free;
end;
finally
instream.Free;
end;
end;
function DecompressString(const aStr: string) : string;
var
instream : TStringStream;
zipstream : TMemoryStream;
outstream : TStringStream;
begin
instream := TStringStream.Create(aStr,TEncoding.UTF8);
try
zipstream := TStringStream.Create;
try
zipstream.CopyFrom(instream,0);
outstream := TStringStream.Create('',TEncoding.UTF8);
try
ZDecompressStream(zipstream,outstream);
outstream.Position := 0;
Result := string(outstream.DataString);
finally
outstream.Free;
end;
finally
zipstream.Free;
end;
finally
instream.Free;
end;
end;
function CompressGZipString(const aStr : string; aCompressionLevel : TCompressionLevel = zcDefault) : string;
var
instream : TStringStream;
outstream : TStringStream;
zipstream : TZCompressionStream;
begin
outstream := TStringStream.Create('',TEncoding.ANSI);
try
zipstream := TZCompressionStream.Create(outstream,System.ZLib.TZCompressionLevel(aCompressionLevel),15 + 16);
try
instream := TStringStream.Create(aStr,TEncoding.UTF8);
try
instream.Position := 0;
zipstream.CopyFrom(instream,instream.Size);
finally
instream.Free;
end;
finally
zipstream.Free;
end;
outstream.Position := 0;
Result := outstream.DataString;
finally
outstream.Free;
end;
end;
function DecompressGZipString(const aStr: string) : string;
var
outstream : TStringStream;
instream : TStringStream;
unzipstream : TZDecompressionStream;
begin
outstream := TStringStream.Create('',TEncoding.UTF8);
try
instream := TStringStream.Create(aStr,TEncoding.ANSI);
try
unzipstream := nil;
try
unzipstream := TZDecompressionStream.Create(instream,15 + 16);
outstream.CopyFrom(unzipstream,0);
finally
unzipstream.Free;
end;
finally
instream.Free;
end;
outstream.Position := 0;
Result := outstream.DataString;
finally
outstream.Free;
end;
end;
function CompressAndEncodeString(const aStr: string; aCompressionLevel : TCompressionLevel = zcDefault): string;
var
utf8stream: TStringStream;
zipstream: TMemoryStream;
base64stream: TStringStream;
begin
utf8stream := TStringStream.Create(aStr,TEncoding.UTF8);
try
zipstream := TMemoryStream.Create;
try
ZCompressStream(utf8stream,zipstream,TZCompressionLevel(aCompressionLevel));
base64stream := TStringStream.Create('',TEncoding.ASCII);
try
zipstream.Position := 0;
TNetEncoding.Base64.Encode(zipstream,base64stream);
base64stream.Position := 0;
Result := string(base64stream.DataString);
finally
base64stream.Free;
end;
finally
zipstream.Free;
end;
finally
utf8stream.Free;
end;
end;
function DecodeAndDecompressString(const aStr: string): string;
var
utf8stream: TStringStream;
zipstream: TMemoryStream;
base64stream: TStringStream;
begin
base64stream := TStringStream.Create(aStr,TEncoding.ASCII);
try
zipstream := TMemoryStream.Create;
try
base64stream.Position := 0;
TNetEncoding.Base64.Decode(base64stream,zipstream);
zipstream.Position := 0;
utf8stream := TStringStream.Create('',TEncoding.UTF8);
try
ZDecompressStream(zipstream,utf8stream);
Result := string(utf8stream.DataString);
finally
utf8stream.Free;
end;
finally
zipstream.Free;
end;
finally
base64stream.Free;
end;
end;
end.
|
inherited dmNotasEmitidas: TdmNotasEmitidas
OldCreateOrder = True
inherited qryManutencao: TIBCQuery
SQLInsert.Strings = (
'INSERT INTO STWARMTNOTA'
' (SERIE, FIL_COBR, NOTA, CGC, SITUACAO, OPERACAO, COD_OPERACAO,' +
' DT_EMISSAO, DT_SAIDA, HR_SAIDA, BASE_ICMS, VLR_ICMS, ISS_BASE, ' +
'ISS_VALOR, VLR_SERVICOS, VLR_PRODUTOS, VLR_FRETE, VLR_SEGUROS, V' +
'LR_OUTROS, VLR_TOTAL, TRANSPORTADORA, FRETE, VEICULO, QTD_TOTAL,' +
' ESPECIE, MARCA, PESO_BRT, PESO_LIQ, IMPRESSAO, CANCELADA, OBSER' +
'VACAO, PED_FILIAL, PED_NUMERO, VENDEDOR, DT_ALTERACAO, OPERADOR,' +
' NFE)'
'VALUES'
' (:SERIE, :FIL_COBR, :NOTA, :CGC, :SITUACAO, :OPERACAO, :COD_OP' +
'ERACAO, :DT_EMISSAO, :DT_SAIDA, :HR_SAIDA, :BASE_ICMS, :VLR_ICMS' +
', :ISS_BASE, :ISS_VALOR, :VLR_SERVICOS, :VLR_PRODUTOS, :VLR_FRET' +
'E, :VLR_SEGUROS, :VLR_OUTROS, :VLR_TOTAL, :TRANSPORTADORA, :FRET' +
'E, :VEICULO, :QTD_TOTAL, :ESPECIE, :MARCA, :PESO_BRT, :PESO_LIQ,' +
' :IMPRESSAO, :CANCELADA, :OBSERVACAO, :PED_FILIAL, :PED_NUMERO, ' +
':VENDEDOR, :DT_ALTERACAO, :OPERADOR, :NFE)')
SQLDelete.Strings = (
'DELETE FROM STWARMTNOTA'
'WHERE'
' SERIE = :Old_SERIE AND FIL_COBR = :Old_FIL_COBR AND NOTA = :Ol' +
'd_NOTA AND SITUACAO = :Old_SITUACAO')
SQLUpdate.Strings = (
'UPDATE STWARMTNOTA'
'SET'
' SERIE = :SERIE, FIL_COBR = :FIL_COBR, NOTA = :NOTA, CGC = :CGC' +
', SITUACAO = :SITUACAO, OPERACAO = :OPERACAO, COD_OPERACAO = :CO' +
'D_OPERACAO, DT_EMISSAO = :DT_EMISSAO, DT_SAIDA = :DT_SAIDA, HR_S' +
'AIDA = :HR_SAIDA, BASE_ICMS = :BASE_ICMS, VLR_ICMS = :VLR_ICMS, ' +
'ISS_BASE = :ISS_BASE, ISS_VALOR = :ISS_VALOR, VLR_SERVICOS = :VL' +
'R_SERVICOS, VLR_PRODUTOS = :VLR_PRODUTOS, VLR_FRETE = :VLR_FRETE' +
', VLR_SEGUROS = :VLR_SEGUROS, VLR_OUTROS = :VLR_OUTROS, VLR_TOTA' +
'L = :VLR_TOTAL, TRANSPORTADORA = :TRANSPORTADORA, FRETE = :FRETE' +
', VEICULO = :VEICULO, QTD_TOTAL = :QTD_TOTAL, ESPECIE = :ESPECIE' +
', MARCA = :MARCA, PESO_BRT = :PESO_BRT, PESO_LIQ = :PESO_LIQ, IM' +
'PRESSAO = :IMPRESSAO, CANCELADA = :CANCELADA, OBSERVACAO = :OBSE' +
'RVACAO, PED_FILIAL = :PED_FILIAL, PED_NUMERO = :PED_NUMERO, VEND' +
'EDOR = :VENDEDOR, DT_ALTERACAO = :DT_ALTERACAO, OPERADOR = :OPER' +
'ADOR, NFE = :NFE'
'WHERE'
' SERIE = :Old_SERIE AND FIL_COBR = :Old_FIL_COBR AND NOTA = :Ol' +
'd_NOTA AND SITUACAO = :Old_SITUACAO')
SQLRefresh.Strings = (
'SELECT SERIE, FIL_COBR, NOTA, CGC, SITUACAO, OPERACAO, COD_OPERA' +
'CAO, DT_EMISSAO, DT_SAIDA, HR_SAIDA, BASE_ICMS, VLR_ICMS, ISS_BA' +
'SE, ISS_VALOR, VLR_SERVICOS, VLR_PRODUTOS, VLR_FRETE, VLR_SEGURO' +
'S, VLR_OUTROS, VLR_TOTAL, TRANSPORTADORA, FRETE, VEICULO, QTD_TO' +
'TAL, ESPECIE, MARCA, PESO_BRT, PESO_LIQ, IMPRESSAO, CANCELADA, O' +
'BSERVACAO, PED_FILIAL, PED_NUMERO, VENDEDOR, DT_ALTERACAO, OPERA' +
'DOR, NFE FROM STWARMTNOTA'
'WHERE'
' SERIE = :Old_SERIE AND FIL_COBR = :Old_FIL_COBR AND NOTA = :Ol' +
'd_NOTA AND SITUACAO = :Old_SITUACAO')
SQLLock.Strings = (
'SELECT NULL FROM STWARMTNOTA'
'WHERE'
'SERIE = :Old_SERIE AND FIL_COBR = :Old_FIL_COBR AND NOTA = :Old_' +
'NOTA AND SITUACAO = :Old_SITUACAO'
'FOR UPDATE WITH LOCK')
SQL.Strings = (
'SELECT'
' NF.*,'
' CLI_RESP.NOME NM_RESPONSAVEL,'
' CLI_RESP.ESTADO UF_RESPONSAVEL,'
' MOT_TRANSP.NOME NM_TRANSPORTADORA,'
' OP_FISCAL.OPERACAO NM_OPERACAO,'
' VEND.NOME NM_VENDEDOR'
'FROM STWARMTNOTA NF'
'LEFT JOIN STWOPETCLI CLI_RESP ON CLI_RESP.CGC = NF.CGC'
'LEFT JOIN STWOPETMOT MOT_TRANSP ON MOT_TRANSP.CPF = NF.TRANSPORT' +
'ADORA'
'LEFT JOIN STWARMTCFOP OP_FISCAL ON OP_FISCAL.CODIGO = NF.COD_OPE' +
'RACAO'
'LEFT JOIN STWOPETVEN VEND ON VEND.CODIGO = NF.VENDEDOR'
'ORDER BY NF.FIL_COBR, NF.NOTA')
object qryManutencaoSERIE: TStringField
FieldName = 'SERIE'
Required = True
Size = 2
end
object qryManutencaoFIL_COBR: TStringField
FieldName = 'FIL_COBR'
Required = True
Size = 3
end
object qryManutencaoNOTA: TFloatField
FieldName = 'NOTA'
Required = True
end
object qryManutencaoCGC: TStringField
FieldName = 'CGC'
Size = 18
end
object qryManutencaoSITUACAO: TStringField
FieldName = 'SITUACAO'
Required = True
Size = 1
end
object qryManutencaoOPERACAO: TStringField
FieldName = 'OPERACAO'
Size = 1
end
object qryManutencaoCOD_OPERACAO: TStringField
FieldName = 'COD_OPERACAO'
Size = 6
end
object qryManutencaoDT_EMISSAO: TDateTimeField
FieldName = 'DT_EMISSAO'
end
object qryManutencaoDT_SAIDA: TDateTimeField
FieldName = 'DT_SAIDA'
end
object qryManutencaoHR_SAIDA: TStringField
FieldName = 'HR_SAIDA'
Size = 8
end
object qryManutencaoBASE_ICMS: TFloatField
FieldName = 'BASE_ICMS'
end
object qryManutencaoVLR_ICMS: TFloatField
FieldName = 'VLR_ICMS'
end
object qryManutencaoISS_BASE: TFloatField
FieldName = 'ISS_BASE'
end
object qryManutencaoISS_VALOR: TFloatField
FieldName = 'ISS_VALOR'
end
object qryManutencaoVLR_SERVICOS: TFloatField
FieldName = 'VLR_SERVICOS'
end
object qryManutencaoVLR_PRODUTOS: TFloatField
FieldName = 'VLR_PRODUTOS'
end
object qryManutencaoVLR_FRETE: TFloatField
FieldName = 'VLR_FRETE'
end
object qryManutencaoVLR_SEGUROS: TFloatField
FieldName = 'VLR_SEGUROS'
end
object qryManutencaoVLR_OUTROS: TFloatField
FieldName = 'VLR_OUTROS'
end
object qryManutencaoVLR_TOTAL: TFloatField
FieldName = 'VLR_TOTAL'
end
object qryManutencaoTRANSPORTADORA: TStringField
FieldName = 'TRANSPORTADORA'
Size = 18
end
object qryManutencaoFRETE: TStringField
FieldName = 'FRETE'
Size = 1
end
object qryManutencaoVEICULO: TStringField
FieldName = 'VEICULO'
Size = 8
end
object qryManutencaoQTD_TOTAL: TFloatField
FieldName = 'QTD_TOTAL'
end
object qryManutencaoESPECIE: TStringField
FieldName = 'ESPECIE'
end
object qryManutencaoMARCA: TStringField
FieldName = 'MARCA'
end
object qryManutencaoPESO_BRT: TFloatField
FieldName = 'PESO_BRT'
end
object qryManutencaoPESO_LIQ: TFloatField
FieldName = 'PESO_LIQ'
end
object qryManutencaoIMPRESSAO: TStringField
FieldName = 'IMPRESSAO'
Size = 1
end
object qryManutencaoCANCELADA: TStringField
FieldName = 'CANCELADA'
Size = 1
end
object qryManutencaoOBSERVACAO: TBlobField
FieldName = 'OBSERVACAO'
end
object qryManutencaoPED_FILIAL: TStringField
FieldName = 'PED_FILIAL'
Size = 3
end
object qryManutencaoPED_NUMERO: TIntegerField
FieldName = 'PED_NUMERO'
end
object qryManutencaoVENDEDOR: TIntegerField
FieldName = 'VENDEDOR'
end
object qryManutencaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryManutencaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryManutencaoNFE: TStringField
FieldName = 'NFE'
Size = 1
end
object qryManutencaoPROTOCOLO: TStringField
FieldName = 'PROTOCOLO'
end
object qryManutencaoNM_RESPONSAVEL: TStringField
FieldName = 'NM_RESPONSAVEL'
ReadOnly = True
Size = 40
end
object qryManutencaoUF_RESPONSAVEL: TStringField
FieldName = 'UF_RESPONSAVEL'
ReadOnly = True
Size = 2
end
object qryManutencaoNM_TRANSPORTADORA: TStringField
FieldName = 'NM_TRANSPORTADORA'
ReadOnly = True
Size = 40
end
object qryManutencaoNM_OPERACAO: TStringField
FieldName = 'NM_OPERACAO'
ReadOnly = True
Size = 40
end
object qryManutencaoNM_VENDEDOR: TStringField
FieldName = 'NM_VENDEDOR'
ReadOnly = True
Size = 40
end
end
inherited qryLocalizacao: TIBCQuery
SQL.Strings = (
'SELECT'
' NF.*,'
' CLI_RESP.NOME NM_RESPONSAVEL,'
' CLI_RESP.ESTADO UF_RESPONSAVEL,'
' MOT_TRANSP.NOME NM_TRANSPORTADORA,'
' OP_FISCAL.OPERACAO NM_OPERACAO,'
' VEND.NOME NM_VENDEDOR'
'FROM STWARMTNOTA NF'
'LEFT JOIN STWOPETCLI CLI_RESP ON CLI_RESP.CGC = NF.CGC'
'LEFT JOIN STWOPETMOT MOT_TRANSP ON MOT_TRANSP.CPF = NF.TRANSPORT' +
'ADORA'
'LEFT JOIN STWARMTCFOP OP_FISCAL ON OP_FISCAL.CODIGO = NF.COD_OPE' +
'RACAO'
'LEFT JOIN STWOPETVEN VEND ON VEND.CODIGO = NF.VENDEDOR'
'ORDER BY NF.FIL_COBR, NF.NOTA')
object qryLocalizacaoSERIE: TStringField
FieldName = 'SERIE'
Required = True
Size = 2
end
object qryLocalizacaoFIL_COBR: TStringField
FieldName = 'FIL_COBR'
Required = True
Size = 3
end
object qryLocalizacaoNOTA: TFloatField
FieldName = 'NOTA'
Required = True
end
object qryLocalizacaoCGC: TStringField
FieldName = 'CGC'
Size = 18
end
object qryLocalizacaoSITUACAO: TStringField
FieldName = 'SITUACAO'
Required = True
Size = 1
end
object qryLocalizacaoOPERACAO: TStringField
FieldName = 'OPERACAO'
Size = 1
end
object qryLocalizacaoCOD_OPERACAO: TStringField
FieldName = 'COD_OPERACAO'
Size = 6
end
object qryLocalizacaoDT_EMISSAO: TDateTimeField
FieldName = 'DT_EMISSAO'
end
object qryLocalizacaoDT_SAIDA: TDateTimeField
FieldName = 'DT_SAIDA'
end
object qryLocalizacaoHR_SAIDA: TStringField
FieldName = 'HR_SAIDA'
Size = 8
end
object qryLocalizacaoBASE_ICMS: TFloatField
FieldName = 'BASE_ICMS'
end
object qryLocalizacaoVLR_ICMS: TFloatField
FieldName = 'VLR_ICMS'
end
object qryLocalizacaoISS_BASE: TFloatField
FieldName = 'ISS_BASE'
end
object qryLocalizacaoISS_VALOR: TFloatField
FieldName = 'ISS_VALOR'
end
object qryLocalizacaoVLR_SERVICOS: TFloatField
FieldName = 'VLR_SERVICOS'
end
object qryLocalizacaoVLR_PRODUTOS: TFloatField
FieldName = 'VLR_PRODUTOS'
end
object qryLocalizacaoVLR_FRETE: TFloatField
FieldName = 'VLR_FRETE'
end
object qryLocalizacaoVLR_SEGUROS: TFloatField
FieldName = 'VLR_SEGUROS'
end
object qryLocalizacaoVLR_OUTROS: TFloatField
FieldName = 'VLR_OUTROS'
end
object qryLocalizacaoVLR_TOTAL: TFloatField
FieldName = 'VLR_TOTAL'
end
object qryLocalizacaoTRANSPORTADORA: TStringField
FieldName = 'TRANSPORTADORA'
Size = 18
end
object qryLocalizacaoFRETE: TStringField
FieldName = 'FRETE'
Size = 1
end
object qryLocalizacaoVEICULO: TStringField
FieldName = 'VEICULO'
Size = 8
end
object qryLocalizacaoQTD_TOTAL: TFloatField
FieldName = 'QTD_TOTAL'
end
object qryLocalizacaoESPECIE: TStringField
FieldName = 'ESPECIE'
end
object qryLocalizacaoMARCA: TStringField
FieldName = 'MARCA'
end
object qryLocalizacaoPESO_BRT: TFloatField
FieldName = 'PESO_BRT'
end
object qryLocalizacaoPESO_LIQ: TFloatField
FieldName = 'PESO_LIQ'
end
object qryLocalizacaoIMPRESSAO: TStringField
FieldName = 'IMPRESSAO'
Size = 1
end
object qryLocalizacaoCANCELADA: TStringField
FieldName = 'CANCELADA'
Size = 1
end
object qryLocalizacaoOBSERVACAO: TBlobField
FieldName = 'OBSERVACAO'
end
object qryLocalizacaoPED_FILIAL: TStringField
FieldName = 'PED_FILIAL'
Size = 3
end
object qryLocalizacaoPED_NUMERO: TIntegerField
FieldName = 'PED_NUMERO'
end
object qryLocalizacaoVENDEDOR: TIntegerField
FieldName = 'VENDEDOR'
end
object qryLocalizacaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryLocalizacaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryLocalizacaoNFE: TStringField
FieldName = 'NFE'
Size = 1
end
object qryLocalizacaoPROTOCOLO: TStringField
FieldName = 'PROTOCOLO'
end
object qryLocalizacaoNM_RESPONSAVEL: TStringField
FieldName = 'NM_RESPONSAVEL'
ReadOnly = True
Size = 40
end
object qryLocalizacaoUF_RESPONSAVEL: TStringField
FieldName = 'UF_RESPONSAVEL'
ReadOnly = True
Size = 2
end
object qryLocalizacaoNM_TRANSPORTADORA: TStringField
FieldName = 'NM_TRANSPORTADORA'
ReadOnly = True
Size = 40
end
object qryLocalizacaoNM_OPERACAO: TStringField
FieldName = 'NM_OPERACAO'
ReadOnly = True
Size = 40
end
object qryLocalizacaoNM_VENDEDOR: TStringField
FieldName = 'NM_VENDEDOR'
ReadOnly = True
Size = 40
end
end
inherited updManutencao: TIBCUpdateSQL
InsertSQL.Strings = (
'INSERT INTO STWARMTNOTA'
' (SERIE, FIL_COBR, NOTA, CGC, SITUACAO, OPERACAO, COD_OPERACAO,' +
' DT_EMISSAO, DT_SAIDA, HR_SAIDA, BASE_ICMS, VLR_ICMS, ISS_BASE, ' +
'ISS_VALOR, VLR_SERVICOS, VLR_PRODUTOS, VLR_FRETE, VLR_SEGUROS, V' +
'LR_OUTROS, VLR_TOTAL, TRANSPORTADORA, FRETE, VEICULO, QTD_TOTAL,' +
' ESPECIE, MARCA, PESO_BRT, PESO_LIQ, IMPRESSAO, CANCELADA, OBSER' +
'VACAO, PED_FILIAL, PED_NUMERO, VENDEDOR, DT_ALTERACAO, OPERADOR,' +
' NFE)'
'VALUES'
' (:SERIE, :FIL_COBR, :NOTA, :CGC, :SITUACAO, :OPERACAO, :COD_OP' +
'ERACAO, :DT_EMISSAO, :DT_SAIDA, :HR_SAIDA, :BASE_ICMS, :VLR_ICMS' +
', :ISS_BASE, :ISS_VALOR, :VLR_SERVICOS, :VLR_PRODUTOS, :VLR_FRET' +
'E, :VLR_SEGUROS, :VLR_OUTROS, :VLR_TOTAL, :TRANSPORTADORA, :FRET' +
'E, :VEICULO, :QTD_TOTAL, :ESPECIE, :MARCA, :PESO_BRT, :PESO_LIQ,' +
' :IMPRESSAO, :CANCELADA, :OBSERVACAO, :PED_FILIAL, :PED_NUMERO, ' +
':VENDEDOR, :DT_ALTERACAO, :OPERADOR, :NFE)')
DeleteSQL.Strings = (
'DELETE FROM STWARMTNOTA'
'WHERE'
' SERIE = :Old_SERIE AND FIL_COBR = :Old_FIL_COBR AND NOTA = :Ol' +
'd_NOTA AND SITUACAO = :Old_SITUACAO')
ModifySQL.Strings = (
'UPDATE STWARMTNOTA'
'SET'
' SERIE = :SERIE, FIL_COBR = :FIL_COBR, NOTA = :NOTA, CGC = :CGC' +
', SITUACAO = :SITUACAO, OPERACAO = :OPERACAO, COD_OPERACAO = :CO' +
'D_OPERACAO, DT_EMISSAO = :DT_EMISSAO, DT_SAIDA = :DT_SAIDA, HR_S' +
'AIDA = :HR_SAIDA, BASE_ICMS = :BASE_ICMS, VLR_ICMS = :VLR_ICMS, ' +
'ISS_BASE = :ISS_BASE, ISS_VALOR = :ISS_VALOR, VLR_SERVICOS = :VL' +
'R_SERVICOS, VLR_PRODUTOS = :VLR_PRODUTOS, VLR_FRETE = :VLR_FRETE' +
', VLR_SEGUROS = :VLR_SEGUROS, VLR_OUTROS = :VLR_OUTROS, VLR_TOTA' +
'L = :VLR_TOTAL, TRANSPORTADORA = :TRANSPORTADORA, FRETE = :FRETE' +
', VEICULO = :VEICULO, QTD_TOTAL = :QTD_TOTAL, ESPECIE = :ESPECIE' +
', MARCA = :MARCA, PESO_BRT = :PESO_BRT, PESO_LIQ = :PESO_LIQ, IM' +
'PRESSAO = :IMPRESSAO, CANCELADA = :CANCELADA, OBSERVACAO = :OBSE' +
'RVACAO, PED_FILIAL = :PED_FILIAL, PED_NUMERO = :PED_NUMERO, VEND' +
'EDOR = :VENDEDOR, DT_ALTERACAO = :DT_ALTERACAO, OPERADOR = :OPER' +
'ADOR, NFE = :NFE'
'WHERE'
' SERIE = :Old_SERIE AND FIL_COBR = :Old_FIL_COBR AND NOTA = :Ol' +
'd_NOTA AND SITUACAO = :Old_SITUACAO')
RefreshSQL.Strings = (
'SELECT SERIE, FIL_COBR, NOTA, CGC, SITUACAO, OPERACAO, COD_OPERA' +
'CAO, DT_EMISSAO, DT_SAIDA, HR_SAIDA, BASE_ICMS, VLR_ICMS, ISS_BA' +
'SE, ISS_VALOR, VLR_SERVICOS, VLR_PRODUTOS, VLR_FRETE, VLR_SEGURO' +
'S, VLR_OUTROS, VLR_TOTAL, TRANSPORTADORA, FRETE, VEICULO, QTD_TO' +
'TAL, ESPECIE, MARCA, PESO_BRT, PESO_LIQ, IMPRESSAO, CANCELADA, O' +
'BSERVACAO, PED_FILIAL, PED_NUMERO, VENDEDOR, DT_ALTERACAO, OPERA' +
'DOR, NFE, PROTOCOLO FROM STWARMTNOTA'
'WHERE'
' SERIE = :Old_SERIE AND FIL_COBR = :Old_FIL_COBR AND NOTA = :Ol' +
'd_NOTA AND SITUACAO = :Old_SITUACAO')
end
end
|
unit fmuCustomerBalance;
interface
uses
WinAPI.Windows, WinAPI.Messages, System.SysUtils, System.Variants, System.Classes,
VCL.Graphics, VCL.Controls, VCL.Forms, Vcl.Menus, System.Actions,
VCL.Dialogs, Data.DB, VCL.ComCtrls, VCL.ToolWin, VCL.ActnList,
EhLibVCL, DBGridEhGrouping, DynVarsEh, FIBDatabase, pFIBDatabase,
MemTableDataEh, DataDriverEh, pFIBDataDriverEh, MemTableEh,
FIBDataSet, pFIBDataSet, GridsEh, DBGridEh, AtrPages,
ToolCtrlsEh, DBGridEhToolCtrls, Buttons, ExtCtrls,
DBAxisGridsEh, PrjConst;
type
TapgCustomerBalance = class(TA4onPage)
dbgCustBalance: TDBGridEh;
dsBalance: TpFIBDataSet;
srcBalance: TDataSource;
trRead: TpFIBTransaction;
mtBalance: TMemTableEh;
pmGrid: TPopupMenu;
miN1: TMenuItem;
miN2: TMenuItem;
procedure miN1Click(Sender: TObject);
procedure miN2Click(Sender: TObject);
private
// FFine: boolean;
// FTodayOnly: boolean;
// FOnlyTheir: boolean;
// FSavedID: Integer;
// procedure DisableControls;
// procedure EnableControls;
public
procedure InitForm; override;
procedure OpenData; override;
procedure CloseData; override;
procedure SavePosition; override;
procedure GotoSavedPosition; override;
class function GetPageName: string; override;
end;
implementation
uses DM, pFIBQuery, PaymentForma, PaymentDocForma, MAIN;
{$R *.dfm}
class function TapgCustomerBalance.GetPageName: string;
begin
Result := rsBALANCE;
end;
procedure TapgCustomerBalance.SavePosition;
begin
//
end;
procedure TapgCustomerBalance.GotoSavedPosition;
begin
//
end;
procedure TapgCustomerBalance.InitForm;
begin
dsBalance.DataSource := FDataSource;
// mtBalance.MasterSource := FDataSource;
// drvFIB.SelectCommand.Params.ParamByName('CUSTOMER_ID').AsInteger := FDataSource.DataSet['CUSTOMER_ID'];
end;
procedure TapgCustomerBalance.miN1Click(Sender: TObject);
begin
dbgCustBalance.DataGrouping.GroupLevels[0].CollapseNodes;
dbgCustBalance.DataGrouping.GroupLevels[1].CollapseNodes;
end;
procedure TapgCustomerBalance.miN2Click(Sender: TObject);
begin
dbgCustBalance.DataGrouping.GroupLevels[0].ExpandNodes;
dbgCustBalance.DataGrouping.GroupLevels[1].ExpandNodes;
end;
procedure TapgCustomerBalance.OpenData;
begin
if dsBalance.Active then
dsBalance.Close;
dsBalance.Open;
srcBalance.DataSet.DisableControls;
mtBalance.LoadFromDataSet(dsBalance, -1, lmCopy, false);
mtBalance.Open;
srcBalance.DataSet.EnableControls;
dsBalance.Close;
if mtBalance.RecordCount > 0 then
begin
dbgCustBalance.DataGrouping.Active := True;
dbgCustBalance.DataGrouping.GroupLevels[0].ExpandNodes;
dbgCustBalance.DataGrouping.GroupLevels[1].CollapseNodes;
dbgCustBalance.DataGrouping.CurDataNode.Expanded := True;
end;
end;
procedure TapgCustomerBalance.CloseData;
begin
dsBalance.Close;
end;
end.
|
unit
{$MODE OBJFPC}
interface
uses uMinPrioQueue;
implementation
{
Return an Array where each index position represents a node and the value
of that position represents the previous node to arrive at it through
the shortest path from the source node
}
function DijkstraShortestPathAlgorithm(graph: TGraph; source: Integer): TIntegerArray;
var
i, neighbor, newDist: Integer;
currentNode, node: TNode;
pq: TMinPrioQueue;
dist, prev: TIntegerArray;
begin
pq := TMinPrioQueue.Create();
SetLength(dist, Length(graph));
SetLength(prev, Length(graph));
// Set all the node’s distances to infinity and add them to an unexplored set
for i := 0 to Length(graph)-1 do
begin
dist[i] := MAXINT;
prev[i] := -1;
pq.Insert(NewNode(graph[i].name, graph[i].edges));
end;
dist[source.idx-1] := 0; // set the starting node’s distance to 0
pq.DecreaseKey(graph[source], 0);
while not pq.IsEmpty do
begin
currentNode := pq.GetMin;
for neighbor in currentNode.edges do
begin
newDist := dist[currentNode.idx-1] + 1;
if newDist < dist[neighbor] then;
begin
pq.DecreaseKey(neighbor+1, newDist);
dist[neighbor] := newDist;
prev[neighbor] := currentNode.Index;
end;
end;
end;
Result := prev;
end;
function BacktrackDijkstra(prev: Array of Integer, dest: Integer): TIntegerArray;
var
i, v: Integer;
path: TIntegerArray;
begin
i := 0; v := dest;
SetLength(path, 0);
while prev[v] <> -1 do
begin
SetLength(path, Length(path)+1);
v := prev[v]);
path[i] := prev[v];
i := i + 1;
end;
// Do whatever you want
for i := 0 to Length(path)-1 do
Write(path[i],' ');
Result := path;
end;
end.
|
unit RemoveOrdersUnit;
interface
uses SysUtils, BaseExampleUnit, CommonTypesUnit, OrderUnit;
type
TRemoveOrders = class(TBaseExample)
public
procedure Execute(OrderIds: TIntegerArray);
end;
implementation
uses OrderParametersUnit;
procedure TRemoveOrders.Execute(OrderIds: TIntegerArray);
var
ErrorString: String;
Removed: boolean;
begin
Removed := Route4MeManager.Order.Remove(OrderIds, ErrorString);
WriteLn('');
if (Removed) then
WriteLn(Format('RemoveOrders executed successfully, %d orders removed',
[Length(OrderIds)]))
else
WriteLn(Format('RemoveOrders error: "%s"', [ErrorString]));
end;
end.
|
unit ColorQuant;
interface
uses
Classes, Windows, GDI, Dibs;
//
// ColorQuant implements the Gervautz-Purgathofer octree
// color quantization algorithm that creates optimized color palettes for
// for 16, 24, and 32-bit DIBs
//
// Taken from Jeff Prosise. Translated and modified by Jorge Romero, Merchise [JRG]
procedure CreateOctreePalette( DibHeader : PDib; DibPixels : pointer; MaxColors : cardinal; ColorBits : cardinal; var LogPalette );
implementation
uses
NumUtils, MemUtils;
type
POctreeNode = ^TOctreeNode;
TOctreeNode =
record
PixelCount : cardinal; // Number of pixels represented by this leaf
RedSum : cardinal; // Sum of red components
GreenSum : cardinal; // Sum of green components
BlueSum : cardinal; // Sum of blue components
Children : array[0..7] of POctreeNode; // Pointers to child nodes
Next : POctreeNode; // Pointer to next reducible node
IsLeaf : boolean; // TRUE if node has no children
end;
type
POctree = POctreeNode;
type
TOctreeNodes = array[0..0] of POctreeNode;
function CreateNode( Level : cardinal; ColorBits : cardinal; var LeafCount : cardinal;
var ReducibleNodes : TOctreeNodes ) : POctreeNode;
begin
new( Result );
with Result^ do
begin
IsLeaf := Level = ColorBits;
if IsLeaf
then Inc( LeafCount )
else
begin
// Add the node to the reducible list for this level
Next := ReducibleNodes[Level];
ReducibleNodes[Level] := Result;
end;
end;
end;
procedure ReduceTree( ColorBits : cardinal; var LeafCount : cardinal; var ReducibleNodes : TOctreeNodes );
var
i : cardinal;
Node : POctreeNode;
RedSum, GreenSum, BlueSum : cardinal;
Children : cardinal;
begin
// Find the deepest level containing at least one reducible node
i := ColorBits - 1;
while ( i > 0 ) and ( ReducibleNodes[i] = nil ) do
dec( i );
// Reduce the node most recently added to the list at level i
Node := ReducibleNodes[i];
ReducibleNodes[i] := Node.Next;
RedSum := 0;
GreenSum := 0;
BlueSum := 0;
Children := 0;
for i := 0 to 7 do
if Node.Children[i] <> nil
then
begin
inc( RedSum, Node.Children[i].RedSum );
inc( GreenSum, Node.Children[i].GreenSum );
inc( BlueSum, Node.Children[i].BlueSum );
inc( Node.PixelCount, Node.Children[i].PixelCount );
FreePtr( Node.Children[i] );
inc( Children );
end;
Node.IsLeaf := true;
Node.RedSum := RedSum;
Node.GreenSum := GreenSum;
Node.BlueSum := BlueSum;
dec( LeafCount, Children - 1 );
end;
procedure DeleteTree( var Node : POctree );
var
i : cardinal;
begin
if Node <> nil
then
begin
for i := 0 to 7 do
if Node.Children[i] <> nil
then DeleteTree( Node.Children[i] );
FreePtr( Node );
end;
end;
procedure GetPaletteColors( Tree : POctree; var LogEntries; var Indx : cardinal );
var
i : integer;
Entries : T256PalEntries absolute LogEntries;
begin
with Tree^, Entries[Indx] do
if IsLeaf
then
begin
peRed := RedSum div PixelCount;
peGreen := GreenSum div PixelCount;
peBlue := BlueSum div PixelCount;
end
else
for i := 0 to 7 do
if Children[i] <> nil
then GetPaletteColors( Children[i], Entries, Indx );
end;
procedure AddColor( var Node : POctreeNode; r, g, b : byte; ColorBits : cardinal; Level : cardinal;
var LeafCount : cardinal; var ReducibleNodes : TOctreeNodes );
var
Indx : cardinal;
Shift : cardinal;
const
Mask : array[0..7] of byte = ( $80, $40, $20, $10, $08, $04, $02, $01 );
begin
// If the node doesn't exist, create it
if Node = nil
then Node := CreateNode( Level, ColorBits, LeafCount, ReducibleNodes );
// Update color information if it's a leaf node
if Node.IsLeaf
then
begin
inc( Node.PixelCount );
inc( Node.RedSum, r );
inc( Node.GreenSum, g );
inc( Node.BlueSum, b );
end
else // Recurse a level deeper if the node is not a leaf
begin
Shift := 7 - Level;
Indx := (((r and Mask[Level]) shr Shift) shl 2) or
(((g and Mask[Level]) shr Shift) shl 1) or
((b and Mask[Level]) shr Shift);
AddColor( Node.Children[Indx], r, g, b, ColorBits, Level + 1, LeafCount, ReducibleNodes );
end;
end;
procedure CreateOctreePalette( DibHeader : PDib; DibPixels : pointer; MaxColors : cardinal; ColorBits : cardinal; var LogPalette );
var
i, x, y : integer;
Tree : POctree;
ReducibleNodes : TOctreeNodes;
LeafCount : cardinal;
Indx : cardinal;
RgbData : pointer;
ScanLine : pchar;
Palette : T256LogPalette absolute LogPalette;
begin
Tree := nil;
LeafCount := 0;
if ColorBits <= 8
then
try
with DibHeader^ do
begin
for i := 0 to ColorBits do
ReducibleNodes[i] := nil;
// Scan the DIB and build the octree
DibGetRgbBegin( DibHeader, RgbData );
for y := 0 to biHeight - 1 do
begin
ScanLine := DibScanLine( DibHeader, DibPixels, y );
for x := 0 to biWidth - 1 do
with DibGetRgb( ScanLine, x, RgbData ) do
begin
AddColor( Tree, rgbRed, rgbGreen, rgbBlue, ColorBits, 0, LeafCount, ReducibleNodes );
while LeafCount > MaxColors do
ReduceTree( ColorBits, LeafCount, ReducibleNodes );
end;
end;
assert( LeafCount > MaxColors, 'Could not reduce enough colors in ColorQuant.CreateOctreePalette!!' );
// Create logical palette
with Palette do
begin
Version := LogPaletteVersion;
NumberOfEntries := LeafCount;
Indx := 0;
GetPaletteColors( Tree, Entries, Indx );
end;
end;
finally
DeleteTree( Tree );
end;
end;
end.
|
unit cSound;
interface
uses Contnrs, ROMObj;
type
TSoundEffect = class
private
_Name : String;
_Offset : Integer;
_Index : Integer;
function GetSEIndex() : Byte;
procedure SetSEIndex(pIndex : Byte);
public
property Name : String read _Name write _Name;
property Offset : Integer read _Offset write _Offset;
property SEIndex : Byte read GetSEIndex write SetSEIndex;
property Index : Integer read _Index write _Index;
end;
TSoundEffectList = class(TObjectList)
protected
function GetSEItem(Index: Integer) : TSoundEffect;
procedure SetSEItem(Index: Integer; const Value: TSoundEffect);
public
function Add(AObject: TSoundEffect) : Integer;
property Items[Index: Integer] : TSoundEffect read GetSEItem write SetSEItem;default;
function Last : TSoundEffect;
end;
implementation
uses uROM;
function TSoundEffectList.Add(AObject: TSoundEffect): Integer;
begin
Result := inherited Add(AObject);
end;
function TSoundEffectList.GetSEItem(Index: Integer): TSoundEffect;
begin
Result := TSoundEffect(inherited Items[Index]);
end;
procedure TSoundEffectList.SetSEItem(Index: Integer; const Value: TSoundEffect);
begin
inherited Items[Index] := Value;
end;
function TSoundEffectList.Last : TSoundEffect;
begin
result := TSoundEffect(inherited Last);
end;
function TSoundEffect.GetSEIndex() : Byte;
begin
result := ROM[self._Offset];
end;
procedure TSoundEffect.SetSEIndex(pIndex : Byte);
begin
ROM[self._Offset] := pIndex;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.