text stringlengths 14 6.51M |
|---|
unit ClipBrd;
{
LLCL - FPC/Lazarus Light LCL
based upon
LVCL - Very LIGHT VCL
----------------------------
This file is a part of the Light LCL (LLCL).
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
This Source Code Form is "Incompatible With Secondary Licenses",
as defined by the Mozilla Public License, v. 2.0.
Copyright (c) 2015-2016 ChrisF
Based upon the Very LIGHT VCL (LVCL):
Copyright (c) 2008 Arnaud Bouchez - http://bouchez.info
Portions Copyright (c) 2001 Paul Toth - http://tothpaul.free.fr
Version 1.02:
* TClipboard: SetAsText fix
Version 1.01:
* File creation.
* TClipboard/Clipboard implemented (only for text)
}
{$IFDEF FPC}
{$define LLCL_FPC_MODESECTION}
{$I LLCLFPCInc.inc} // For mode
{$undef LLCL_FPC_MODESECTION}
{$ENDIF}
{$I LLCLOptions.inc} // Options
//------------------------------------------------------------------------------
interface
uses
Classes;
type
TClipboard = class(TPersistent)
private
fOwnerHandle: THandle;
function OpenClipBrd(): boolean;
procedure CloseClipBrd;
function GetAsText(): string;
procedure SetAsText(const Value: string);
procedure SetBuffer(Format: cardinal; Buffer: pointer; Size: integer);
public
procedure Open;
procedure Close;
procedure Clear;
function HasFormat(Format: cardinal): boolean;
function GetAsHandle(Format: cardinal): THandle;
procedure SetAsHandle(Format: cardinal; Value: THandle);
property AsText: string read GetAsText write SetAsText;
end;
{$IFDEF FPC}
const
CF_TEXT = 1;
CF_BITMAP = 2;
CF_UNICODETEXT = 13;
{$ENDIF}
var
Clipboard: TClipboard;
//------------------------------------------------------------------------------
implementation
uses
LLCLOSInt, Windows,
Forms;
{$IFDEF FPC}
{$PUSH} {$HINTS OFF}
{$ENDIF}
type
TPApplication = class(TApplication); // To access to protected part
//------------------------------------------------------------------------------
{ TClipboard }
function TClipboard.OpenClipBrd(): boolean;
begin
if fOwnerHandle=0 then
fOwnerHandle := TPApplication(Application).AppHandle;
result := LLCL_OpenClipboard(fOwnerHandle);
end;
procedure TClipboard.CloseClipBrd;
begin
LLCL_CloseClipboard();
end;
function TClipboard.GetAsText(): string;
var hData: THandle;
begin
result := '';
if not OpenClipBrd() then exit;
hData := LLCL_GetClipboardData(LLCLS_CLPB_GetTextFormat());
if hData<>0 then
begin
result := LLCLS_CLPB_GetText(LLCL_GlobalLock(hData));
LLCL_GlobalUnlock(hData);
end;
CloseClipBrd;
end;
procedure TClipboard.SetAsText(const Value: string);
var pText: pointer;
var len: cardinal;
begin
pText := LLCLS_CLPB_SetTextPtr(Value, len);
SetBuffer(LLCLS_CLPB_GetTextFormat(), pText, len);
FreeMem(pText);
end;
procedure TClipboard.SetBuffer(Format: cardinal; Buffer: pointer; Size: integer);
var hMem: THandle;
var pMem: pointer;
begin
if not OpenClipBrd() then exit;
Clear;
hMem := LLCL_GlobalAlloc(GMEM_MOVEABLE or GMEM_DDESHARE, Size);
if hMem<>0 then
begin
pMem := LLCL_GlobalLock(hMem);
if Assigned(pMem) then
Move(Buffer^, pMem^, Size);
LLCL_GlobalUnlock(hMem);
LLCL_SetClipboardData(Format, hMem);
// Don't free the allocated memory
end;
CloseClipBrd;
end;
procedure TClipboard.Open;
begin
OpenClipBrd();
end;
procedure TClipboard.Close;
begin
CloseClipBrd;
end;
procedure TClipboard.Clear;
begin
LLCL_EmptyClipboard();
end;
function TClipboard.HasFormat(Format: cardinal): boolean;
begin
result := LLCL_IsClipboardFormatAvailable(Format);
end;
function TClipboard.GetAsHandle(Format: cardinal): THandle;
begin
result := 0;
if not OpenClipBrd() then exit;
result := LLCL_GetClipboardData(Format);
Close;
end;
procedure TClipboard.SetAsHandle(Format: cardinal; Value: THandle);
begin
if not OpenClipBrd() then exit;
Clear;
LLCL_SetClipboardData(Format, Value);
Close;
end;
//------------------------------------------------------------------------------
initialization
Clipboard := TClipboard.Create();
finalization
Clipboard.Free;
{$IFDEF FPC}
{$POP}
{$ENDIF}
end.
|
unit Unlocker;
interface
uses
SysUtils, Generics.Collections,
Device.PhysicalDrive, Device.PhysicalDrive.List, OS.Handle,
Getter.PhysicalDrive.PartitionList;
type
IDriveHandleUnlocker = interface['{8BBD8DB6-A063-4982-8FBA-54051BE87A2A}']
end;
TOSFileUnlockList = TList<IOSFileUnlock>;
TDriveHandleUnlocker = class(TInterfacedObject, IDriveHandleUnlocker)
public
constructor Create(const Letter: String;
const PhysicalDriveList: TPhysicalDriveList;
const SelectedDrive: IPhysicalDrive);
destructor Destroy; override;
private
UnlockList: TOSFileUnlockList;
procedure IfThisDriveUnlock(const CurrentDrive: IPhysicalDrive;
const Letter: string);
end;
implementation
{ TDriveHandleUnlocker }
destructor TDriveHandleUnlocker.Destroy;
begin
UnlockList.Free;
inherited;
end;
procedure TDriveHandleUnlocker.IfThisDriveUnlock(
const CurrentDrive: IPhysicalDrive; const Letter: string);
var
PartitionList: TPartitionList;
const
NotFound = -1;
begin
PartitionList := CurrentDrive.GetPartitionList;
try
if PartitionList.FindEntryByIndex(Letter) > NotFound then
UnlockList.Add(CurrentDrive.Unlock);
finally
PartitionList.Free;
end;
end;
constructor TDriveHandleUnlocker.Create(const Letter: String;
const PhysicalDriveList: TPhysicalDriveList;
const SelectedDrive: IPhysicalDrive);
var
CurrentDrive: IPhysicalDrive;
begin
UnlockList := TOSFileUnlockList.Create;
IfThisDriveUnlock(SelectedDrive, Letter);
for CurrentDrive in PhysicalDriveList do
IfThisDriveUnlock(CurrentDrive, Letter);
end;
end.
|
unit lin_win_compat;
{Unit holding behaviour differences between linux and windows}
{$ifdef fpc}
{$mode objfpc}{$H+}
{$endif}
interface
uses Classes
, SysUtils
;
const K_IP_GENERAL_BROADCAST : string = '255.255.255.255';
procedure GetProxySettings(out bEnabled : boolean; out sServer : string);
procedure LogInSystem (const EventType : TEventType; const Msg : String);
implementation // =============================================================
uses {$ifndef fpc}
windows , // Needed on delphi to define KEY_READ
{$endif}
{$ifdef unix}
SystemLog
, Process
{$else}
EventLog
, Registry
, IdStack
{$endif}
, uIP
;
{$ifndef unix}
var fEventLog : TEventLog;
{$endif}
// ============================================================================
procedure GetProxySettings(out bEnabled: boolean; out sServer: string);
{$ifndef windows}
var sl : TStringList;
s : string;
{$endif}
begin
sServer := '';
bEnabled := false;
{$ifdef windows}
with TRegistry.Create(KEY_READ) do begin
RootKey := HKEY_CURRENT_USER;
if OpenKey('\Software\Microsoft\Windows\CurrentVersion\Internet Settings',False) then begin
bEnabled := (ReadInteger('ProxyEnable') = 1);
sServer := ReadString ('ProxyServer');
end;
free;
end;
{$else}
sl := TStringList.Create;
sl.Delimiter := '/';
sl.DelimitedText := GetEnvironmentVariable('http_proxy'); // may have http://xx.xx.xx.xx:yy/ as input
for s in sl do
if Pos('.',s)<>0 then sServer := s; // Quick & dirty way to extract server ip & port
sl.free;
bEnabled := (sServer<>'');
{$endif}
end;
//=============================================================================
procedure LogInSystem (const EventType : TEventType; const Msg : String);
var logInfo : longint;
begin
{$ifdef unix}
Case EventType of
etCustom : logInfo := LOG_NOTICE;
etDebug : logInfo := LOG_DEBUG;
etInfo : logInfo := LOG_INFO;
etWarning : logInfo := LOG_WARNING;
etError : logInfo := LOG_ERR;
end;
syslog(loginfo,'%s',[pchar(Msg)]);
{$else}
fEventLog.Log(EventType,Msg);
{$endif}
end;
{$ifdef mswindows}
{$R C:/pp/packages/fcl-base/src/win/fclel.res} // Load resource strings for windows event log
{$endif}
initialization // =============================================================
{$ifdef mswindows}
fEventLog := TEventLog.Create(nil);
fEventLog.DefaultEventType:=etInfo;
fEventLog.LogType:=ltSystem;
fEventLog.Identification := GetProductName;
fEventLog.Active:=true;
fEventlog.RegisterMessageFile('');
{$endif}
finalization // ===============================================================
{$ifdef mswindows}
fEventLog.Free;
{$endif}
end.
|
program Exceptions;
{$codepage utf8}
uses
Crt,
Classes,
SysUtils,
HTTPDefs,
fpHTTP,
fpWeb,
fphttpclient,
fpjson,
jsonparser,
httpprotocol;
type
TResponse = record
StatusCode: integer;
Body: TJSONData;
end;
var
GameCode, OrgKey: string;
Teams: TJSONArray;
Team: TJSONData;
IsAuthenticated: boolean;
i: integer;
TeamTable: array of integer;
function QueryAPI(Method, Path: string; State: integer): TResponse;
var
HTTP: TFPHTTPClient;
SS: TStringStream;
begin
try
try
HTTP := TFPHttpClient.Create(nil);
SS := TStringStream.Create('');
HTTP.AddHeader('Authorization', 'JWT ' + OrgKey);
HTTP.AddHeader('Content-Type', 'application/json');
if State <> 0 then
HTTP.RequestBody:=TStringStream.Create('{"state":' + IntToStr(State)+ '}');
HTTP.HTTPMethod(Method, 'https://game-mock.herokuapp.com/games/' +
GameCode + Path, SS, [200, 201, 400, 401, 404, 500, 505]);
//HTTP.RequestHeaders[3]
Result.StatusCode := HTTP.ResponseStatusCode;
Result.Body := GetJSON(SS.Datastring);
except
on E: Exception do
WriteLn(E.Message);
end;
finally
SS.Free;
HTTP.Free;
end;
end;
function AuthenticationCheck(): boolean;
var
Response: TResponse;
begin
Write('Enter gamecode: ');
Readln(GameCode);
GameCode := 'bgi63c';
Write('Enter organizer key: ');
Readln(OrgKey);
OrgKey := 'bti34tbri8t34rtdbiq34tvdri6qb3t4vrdtiu4qv';
Response := QueryAPI('GET', '/teams', 0);
case Response.StatusCode of
200:
begin
WriteLn('Success');
Teams := TJSONArray(Response.Body);
Result := True;
end;
400:
begin
WriteLn('Zadána špatná strategie');
//unallowed status - strategie kterou tým nemůže
Result := False;
end;
401:
begin
WriteLn('Špatný klíč organizátora');
//UNAUTHORIZED
Result := False;
end;
404:
begin
WriteLn('Špatné číslo týmu/ špatný kód hry');
//šppatná adresa in general
Result := False;
end;
500:
begin
WriteLn('Chyba serveru - pracujeme na opravení');
//internal server error
Result := False;
end;
end;
end;
procedure PrintMoves(Moves: TJSONData);
var
Move: TJSONData;
begin
WriteLn('Možné pohyby:');
for i := 0 to Moves.Count - 1 do
begin
Move := Moves.FindPath('[' + i.ToString() + ']');
WriteLn(' ' + IntToStr(Move.FindPath('id').AsQWord) + ') ' + Move.FindPath('name').AsString);
end;
end;
procedure PrintTeam(Team: TJSONData);
var
Number, StateRecord, Name: string;
begin
Number := IntToStr(Team.FindPath('number').AsQWord);
Name := Team.FindPath('name').AsString;
// StateRecord := Team.FindPath('stateRecord').AsString;
WriteLn(Number + '. ' + Name);
// WriteLn(StateRecord);
PrintMoves(Team.FindPath('possibleMoves'));
end;
procedure ReverseMove(Team: TJSONData);
var
Number: string;
Response: TResponse;
begin
Number := Team.FindPath('number').AsString;
Response := QueryAPI('DELETE', '/teams/' + Number + '/state', 0);
if Response.StatusCode <> 200 then
WriteLn('POZOR!: Vrácení pohybu se nezdařilo.')
else
PrintTeam(Response.Body);
end;
procedure CheckMoveId(Team: TJSONData; MoveId: integer);
var
Moves : TJSONData;
Possible : boolean;
begin
Possible := false;
Moves := Team.FindPath('possibleMoves');
for i := 0 to Moves.Count - 1 do
begin
if Moves.FindPath('[' + i.ToString() + '].id').AsInteger = MoveId then
Possible := true;
end;
if not Possible then
Raise EConvertError.Create ('POZOR!: Neplatné číslo pohybu');
end;
procedure MoveTeam(Team: TJSONData; Move: string);
var
Number: string;
Response: TResponse;
MoveId: integer;
begin
Number := Team.FindPath('id').AsString;
try
MoveId := StrToInt(Move);
CheckMoveId(Team, MoveId);
Response := QueryAPI('POST', '/teams/' + Number + '/state', MoveId);
if Response.StatusCode <> 201 then
WriteLn('POZOR!: Zadání pohybu se nezdařilo.')
else
PrintTeam(Response.Body);
except
on E: EConvertError do
Writeln('POZOR!: Neplatné číslo pohybu');
end;
end;
function TeamNumberTranslate(TeamNumber: integer): integer;
begin
Result := -1;
for i := 0 to Length(TeamTable) do
begin
if TeamTable[i] = TeamNumber then
begin
Result := i + 1;
Exit();
end;
end;
end;
procedure ManageMoveInput(Team: TJSONData);
var
MoveInput: string;
begin
while True do
begin
ReadLn();
Write('Zadej číslo pohybu: ');
ReadLn(MoveInput);
MoveInput := Upcase(Trim(MoveInput));
case MoveInput of
'':
Exit;
'R':
ReverseMove(Team);
else
MoveTeam(Team, MoveInput);
end;
end;
end;
procedure ManageInput(Teams: TJSONArray);
var
TeamNumber: integer;
TeamResponse: TResponse;
MoveInput: string;
begin
while True do
begin
Write('Zadej číslo týmu: ');
Read(TeamNumber);
TeamResponse := QueryAPI('GET', '/teams/' + IntToStr(TeamNumberTranslate(TeamNumber)), 0);
if TeamResponse.StatusCode <> 200 then
begin
WriteLn('Neznámý tým');
Continue;
end;
PrintTeam(TeamResponse.Body);
ManageMoveInput(TeamResponse.Body);
end;
end;
begin
IsAuthenticated := False;
while not IsAuthenticated do
IsAuthenticated := AuthenticationCheck();
SetLength(TeamTable, Teams.Count);
for i := 0 to Teams.Count - 1 do
begin
Team := Teams.FindPath('[' + i.ToString() + ']');
WriteLn(Team.FindPath('id').AsString + ' = ' + Team.FindPath('number').AsString);
TeamTable[i] := Team.FindPath('number').AsInteger;
end;
ManageInput(Teams);
// Writeln(IntToStr(TeamNumberTranslate(TeamNumber)));
// WriteLn(QueryAPI('GET', '/teams/' + IntToStr(TeamNumberTranslate(TeamNumber))).Body.FindPath('name').AsString);
Readln;
Readln;
end.
{S := HTTP.ResponseHeaders[3];
Delete(S,1,14);
if Pos('application/json',S)=1 then
begin
GetJSON(Result).FindPath('type').AsString
end;
}
|
unit glslang.Versions;
interface //#################################################################### ■
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//Copyright (C) 2012-2013 LunarG, Inc.
//
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
uses LUX.Code.C;
//
// Help manage multiple profiles, versions, extensions etc.
//
//
// Profiles are set up for masking operations, so queries can be done on multiple
// profiles at the same time.
//
// Don't maintain an ordinal set of enums (0,1,2,3...) to avoid all possible
// defects from mixing the two different forms.
//
type T_EProfile = (
EBadProfile = 0,
ENoProfile = 1 shl 0, // only for desktop, before profiles showed up
ECoreProfile = 1 shl 1,
ECompatibilityProfile = 1 shl 2,
EEsProfile = 1 shl 3
);
//
// Map from profile enum to externally readable text name.
//
function ProfileName( profile:T_EProfile ) :P_char; inline;
//
// The behaviors from the GLSL "#extension extension_name : behavior"
//
type TExtensionBehavior = (
EBhMissing = 0,
EBhRequire,
EBhEnable,
EBhWarn,
EBhDisable,
EBhDisablePartial // use as initial state of an extension that is only partially implemented
);
//
// Symbolic names for extensions. Strings may be directly used when calling the
// functions, but better to have the compiler do spelling checks.
//
const E_GL_OES_texture_3D :P_char = 'GL_OES_texture_3D';
const E_GL_OES_standard_derivatives :P_char = 'GL_OES_standard_derivatives';
const E_GL_EXT_frag_depth :P_char = 'GL_EXT_frag_depth';
const E_GL_OES_EGL_image_external :P_char = 'GL_OES_EGL_image_external';
const E_GL_EXT_shader_texture_lod :P_char = 'GL_EXT_shader_texture_lod';
const E_GL_ARB_texture_rectangle :P_char = 'GL_ARB_texture_rectangle';
const E_GL_3DL_array_objects :P_char = 'GL_3DL_array_objects';
const E_GL_ARB_shading_language_420pack :P_char = 'GL_ARB_shading_language_420pack';
const E_GL_ARB_texture_gather :P_char = 'GL_ARB_texture_gather';
const E_GL_ARB_gpu_shader5 :P_char = 'GL_ARB_gpu_shader5';
const E_GL_ARB_separate_shader_objects :P_char = 'GL_ARB_separate_shader_objects';
const E_GL_ARB_compute_shader :P_char = 'GL_ARB_compute_shader';
const E_GL_ARB_tessellation_shader :P_char = 'GL_ARB_tessellation_shader';
const E_GL_ARB_enhanced_layouts :P_char = 'GL_ARB_enhanced_layouts';
const E_GL_ARB_texture_cube_map_array :P_char = 'GL_ARB_texture_cube_map_array';
const E_GL_ARB_shader_texture_lod :P_char = 'GL_ARB_shader_texture_lod';
const E_GL_ARB_explicit_attrib_location :P_char = 'GL_ARB_explicit_attrib_location';
const E_GL_ARB_shader_image_load_store :P_char = 'GL_ARB_shader_image_load_store';
const E_GL_ARB_shader_atomic_counters :P_char = 'GL_ARB_shader_atomic_counters';
const E_GL_ARB_shader_draw_parameters :P_char = 'GL_ARB_shader_draw_parameters';
const E_GL_ARB_derivative_control :P_char = 'GL_ARB_derivative_control';
const E_GL_ARB_shader_texture_image_samples :P_char = 'GL_ARB_shader_texture_image_samples';
const E_GL_ARB_viewport_array :P_char = 'GL_ARB_viewport_array';
const E_GL_ARB_gl_spirv :P_char = 'GL_ARB_gl_spirv';
const E_GL_ARB_sparse_texture2 :P_char = 'GL_ARB_sparse_texture2';
const E_GL_ARB_sparse_texture_clamp :P_char = 'GL_ARB_sparse_texture_clamp';
//const E_GL_ARB_cull_distance :P_char = 'GL_ARB_cull_distance'; // present for 4.5, but need extension control over block members
// #line and #include
const E_GL_GOOGLE_cpp_style_line_directive :P_char = 'GL_GOOGLE_cpp_style_line_directive';
const E_GL_GOOGLE_include_directive :P_char = 'GL_GOOGLE_include_directive';
// AEP
const E_GL_ANDROID_extension_pack_es31a :P_char = 'GL_ANDROID_extension_pack_es31a';
const E_GL_KHR_blend_equation_advanced :P_char = 'GL_KHR_blend_equation_advanced';
const E_GL_OES_sample_variables :P_char = 'GL_OES_sample_variables';
const E_GL_OES_shader_image_atomic :P_char = 'GL_OES_shader_image_atomic';
const E_GL_OES_shader_multisample_interpolation :P_char = 'GL_OES_shader_multisample_interpolation';
const E_GL_OES_texture_storage_multisample_2d_array :P_char = 'GL_OES_texture_storage_multisample_2d_array';
const E_GL_EXT_geometry_shader :P_char = 'GL_EXT_geometry_shader';
const E_GL_EXT_geometry_point_size :P_char = 'GL_EXT_geometry_point_size';
const E_GL_EXT_gpu_shader5 :P_char = 'GL_EXT_gpu_shader5';
const E_GL_EXT_primitive_bounding_box :P_char = 'GL_EXT_primitive_bounding_box';
const E_GL_EXT_shader_io_blocks :P_char = 'GL_EXT_shader_io_blocks';
const E_GL_EXT_tessellation_shader :P_char = 'GL_EXT_tessellation_shader';
const E_GL_EXT_tessellation_point_size :P_char = 'GL_EXT_tessellation_point_size';
const E_GL_EXT_texture_buffer :P_char = 'GL_EXT_texture_buffer';
const E_GL_EXT_texture_cube_map_array :P_char = 'GL_EXT_texture_cube_map_array';
// OES matching AEP
const E_GL_OES_geometry_shader :P_char = 'GL_OES_geometry_shader';
const E_GL_OES_geometry_point_size :P_char = 'GL_OES_geometry_point_size';
const E_GL_OES_gpu_shader5 :P_char = 'GL_OES_gpu_shader5';
const E_GL_OES_primitive_bounding_box :P_char = 'GL_OES_primitive_bounding_box';
const E_GL_OES_shader_io_blocks :P_char = 'GL_OES_shader_io_blocks';
const E_GL_OES_tessellation_shader :P_char = 'GL_OES_tessellation_shader';
const E_GL_OES_tessellation_point_size :P_char = 'GL_OES_tessellation_point_size';
const E_GL_OES_texture_buffer :P_char = 'GL_OES_texture_buffer';
const E_GL_OES_texture_cube_map_array :P_char = 'GL_OES_texture_cube_map_array';
// Arrays of extensions for the above AEP duplications
const AEP_geometry_shader :array of P_char = [ E_GL_EXT_geometry_shader, E_GL_OES_geometry_shader ];
const Num_AEP_geometry_shader :T_int = SizeOf( AEP_geometry_shader ) div SizeOf( AEP_geometry_shader[0] );
const AEP_geometry_point_size :array of P_char = [ E_GL_EXT_geometry_point_size, E_GL_OES_geometry_point_size ];
const Num_AEP_geometry_point_size :T_int = SizeOf( AEP_geometry_point_size ) div SizeOf( AEP_geometry_point_size[0] );
const AEP_gpu_shader5 :array of P_char = [ E_GL_EXT_gpu_shader5, E_GL_OES_gpu_shader5 ];
const Num_AEP_gpu_shader5 :T_int = SizeOf( AEP_gpu_shader5 ) div SizeOf( AEP_gpu_shader5[0] );
const AEP_primitive_bounding_box :array of P_char = [ E_GL_EXT_primitive_bounding_box, E_GL_OES_primitive_bounding_box ];
const Num_AEP_primitive_bounding_box :T_int = SizeOf( AEP_primitive_bounding_box ) div SizeOf( AEP_primitive_bounding_box[0] );
const AEP_shader_io_blocks :array of P_char = [ E_GL_EXT_shader_io_blocks, E_GL_OES_shader_io_blocks ];
const Num_AEP_shader_io_blocks :T_int = SizeOf( AEP_shader_io_blocks ) div SizeOf( AEP_shader_io_blocks[0] );
const AEP_tessellation_shader :array of P_char = [ E_GL_EXT_tessellation_shader, E_GL_OES_tessellation_shader ];
const Num_AEP_tessellation_shader :T_int = SizeOf( AEP_tessellation_shader ) div SizeOf( AEP_tessellation_shader[0] );
const AEP_tessellation_point_size :array of P_char = [ E_GL_EXT_tessellation_point_size, E_GL_OES_tessellation_point_size ];
const Num_AEP_tessellation_point_size :T_int = SizeOf( AEP_tessellation_point_size ) div SizeOf( AEP_tessellation_point_size[0] );
const AEP_texture_buffer :array of P_char = [ E_GL_EXT_texture_buffer, E_GL_OES_texture_buffer ];
const Num_AEP_texture_buffer :T_int = SizeOf( AEP_texture_buffer ) div SizeOf(AEP_texture_buffer[0] );
const AEP_texture_cube_map_array :array of P_char = [ E_GL_EXT_texture_cube_map_array, E_GL_OES_texture_cube_map_array ];
const Num_AEP_texture_cube_map_array :T_int = SizeOf( AEP_texture_cube_map_array ) div SizeOf( AEP_texture_cube_map_array[0] );
implementation //############################################################### ■
function ProfileName( profile:T_EProfile ) :P_char;
begin
case profile of
ENoProfile : Result := 'none';
ECoreProfile : Result := 'core';
ECompatibilityProfile: Result := 'compatibility';
EEsProfile : Result := 'es';
else Result := 'unknown profile';
end;
end;
end. //######################################################################### ■
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSRESTExpertsCreators;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DSServerWebBrokerExpertsCreators, ExpertsTemplates, ExpertsProject,
ExpertsModules;
type
TDSRESTExpertsCreatorsModule = class(TDSServerWebBrokerExpertsCreatorsModule)
private
procedure AddScriptFiles(const APersonality: string; IncludeOptional: Boolean);
protected
procedure CreateModules(const APersonality: string); override;
procedure UpdateProperties; override;
end;
implementation
{$R *.dfm}
uses DSServerFeatures, DSServerScriptGen, DSServerExpertsTemplateProperties, ToolsAPI,
DCCStrs, CommonOptionStrs;
{ TDSRESTExpertsCreatorsModule }
procedure TDSRESTExpertsCreatorsModule.CreateModules(
const APersonality: string);
begin
inherited;
AddScriptFiles(APersonality, dsSampleWebFiles in Features);
end;
procedure TDSRESTExpertsCreatorsModule.AddScriptFiles(const APersonality: string; IncludeOptional: Boolean);
begin
DSServerScriptGen.AddScriptFiles(Personality);
if IncludeOptional then
DSServerScriptGen.AddSampleScriptFiles(Personality);
end;
procedure TDSRESTExpertsCreatorsModule.UpdateProperties;
begin
inherited;
// Other properties set by ancestor
SetBoolTemplateProperty(sIncludeSampleWebFiles_9, IsFeatureEnabled(dsSampleWebFiles));
SetBoolTemplateProperty(sDataSnapREST_10, True);
SetBoolTemplateProperty(sDataSnapConnectors_16, IsFeatureEnabled(dsConnectors));
end;
end.
|
unit GF_x;
interface
uses G_F, Math,SysUtils;
type
bvec= array of byte;
ivec= array of integer;
GFX=class
private
q, degree : integer;
public
coeffs: array of GF;
Constructor Create; overload;
constructor Create(qvalue: integer); overload;
constructor Create( qvalue, indegree: integer); overload;
constructor Create(qvalue : integer; const invalues : bvec); overload;
constructor Create(qvalue : integer; const invalues : string); overload;
constructor Create(const ingfx: GFX ); overload;
procedure set_field_values(qvalue: integer; const invalues: ivec ); overload;
procedure set_field_values(qvalue: integer; const invalues: string ); overload;
function get_size :integer;
function get_degree:integer ; // Return degree of gf(q)[x]
procedure set_degree(indegree:integer);
function get_true_degree:integer;
procedure clear;
procedure Copy(const ingfx: GFX); //overload;
procedure Add(const ingfx: GFX);
procedure Sub(const ingfx: GFX);
procedure Mul(const ingfx: GFX); overload;
function Count(const ingf:GF):GF;
function toString : string ;
end;
function Add(const op1, op2:GFX):GFX;
function Sub(const op1, op2:GFX):GFX;
function Mul(const op1, op2:GFX):GFX;overload;
function Divv(const c,g: GFX):GFX;overload;
function Modd(const c,g: GFX):GFX;
function Mul(const ingfx: GFX; const ingf:GF):GFX; overload;
function Divv(const ingfx: GFX; const ingf:GF):GFX; overload;
implementation
constructor GFX.Create;
begin
degree:=-1;
q:=0;
end;
constructor GFX.Create(qvalue: integer);
begin
q:=qvalue;
end;
constructor GFX.Create( qvalue, indegree: integer);
var i :integer;
begin
q:=qvalue;
SetLength(coeffs,indegree+1);
degree:=indegree;
for i:=0 to degree do
coeffs[i]:=GF.Create(q,-1);
end;
//Copy
constructor GFX.Create(const ingfx: GFX );
var i,b:integer;
begin
degree:=ingfx.degree;
q:=ingfx.q;
SetLength(coeffs,degree+1);
for i:=0 to degree do
coeffs[i]:=GF.Create(q,ingfx.coeffs[i].get_value);
end;
constructor GFX.Create(qvalue:integer; const invalues: bvec);
var input:ivec;
i,len :integer;
begin
len:= Length(invalues) ;
SetLength(input,len);
for i:=0 to len-1 do
input[i]:= invalues[i] ;
set_field_values(qvalue,input);
end;
constructor GFX.Create( qvalue:integer; const invalues: string);
begin
set_field_values(qvalue,invalues);
end;
procedure GFX.set_field_values(qvalue: integer; const invalues: ivec ) ;
var b,i:integer;
begin
degree:= Length(invalues)-1;
Setlength(coeffs,degree+1);
for i:=0 to degree do
coeffs[i]:=GF.Create(qvalue,invalues[i]);
q:=qvalue;
end;
procedure GFX.set_field_values(qvalue: integer; const invalues: string ) ;
var size:byte;
vec:ivec;
i:integer;
forconvert:GF;
begin
size:=Length(invalues);
Setlength(vec,size);
forconvert:=GF.Create(qvalue);
for i:=1 To size Do
begin
forconvert.set_field_value_by_pol(qvalue,StrToInt(invalues[i]));
vec[i-1]:= forconvert.get_value;
end;
set_field_values(qvalue,vec);
end;
function GFX.get_size :integer;
begin
Result:=q;
end;
function GFX.get_degree:integer ;
begin
Result:=degree;
end;
procedure GFX.set_degree(indegree:integer);
begin
SetLength(coeffs,indegree+1);
degree:=indegree;
end;
function GFX.get_true_degree:integer;
var i:integer;
begin
i:=degree;
while(coeffs[i].get_value=-1) do
begin
i:=i-1;
if (i=-1) then
break;
end;
Result:=i;
end;
procedure GFX.clear;
var i:integer;
begin
for i:=0 to degree do
coeffs[i].set_field_value(q,-1);
end;
procedure GFX.Copy(const ingfx: GFX);
var i,Olddegree:integer;
begin
Olddegree:=degree;
degree:=ingfx.degree;
q:=ingfx.q;
SetLength(coeffs,degree+1);
for i:=0 to degree do
if(i<=Olddegree) then
coeffs[i].set_field_value(q,ingfx.coeffs[i].get_value)
else
coeffs[i]:=GF.Create(q,ingfx.coeffs[i].get_value);
(*for i:=0 to Olddegree-1 do
coeffs[i].set_field_value(q,ingfx.coeffs[i].get_value);
for i:=Olddegree to degree do
coeffs[i]:=GF.Create(q,ingfx.coeffs[i].get_value);
*)
end;
procedure GFX.Add(const ingfx: GFX);
var i,j:integer;
begin
if (q = ingfx.q) then
begin
if (ingfx.degree > degree) then
begin
SetLength(coeffs,ingfx.degree+1);
// set new coefficients to the zeroth element
for j:=degree+1 to ingfx.degree do
coeffs[j]:=GF.create(q,-1);
degree:=ingfx.degree;
end;
for i:=0 to ingfx.degree do
coeffs[i].Add(ingfx.coeffs[i]);
end;
end;
procedure GFX.Sub(const ingfx: GFX);
begin
if (q = ingfx.q) then
Add(ingfx);
end;
procedure GFX.Mul(const ingfx: GFX);
var i,j:integer;
tempcoeffs:array of GF;
begin
if (q = ingfx.q) then
begin
Setlength(tempcoeffs,degree+1);
for i:=0 to degree do
tempcoeffs[i]:=GF.Create(coeffs[i]);
SetLength(coeffs,degree+ingfx.degree+1);
for j:=0 to degree do
coeffs[j].set_field_value(q,-1); // set coefficients to the zeroth element (log(0)=-Inf=-1)
for j:=degree+1 to (degree+ingfx.degree) do // and create new coeffs
coeffs[j]:=GF.Create(q,-1);
for i:=0 to degree do
for j:=0 to ingfx.degree do
coeffs[i+j].Add(G_F.Mul(ingfx.coeffs[j],tempcoeffs[i]));
degree:=degree+ingfx.degree;
end;
end;
function Divv(const c,g: GFX):GFX;
var q_c,q_g,q,tempdegree,gdegree,degreedif,i:integer;
temp,m,divisor:GFX;
Zeroo:GF;
begin
q_c:= c.get_size;
q_g:=g.get_size;
q:=c.get_size;
if (q_c=q_g) then
begin
Zeroo:=GF.Create(q,-1);
temp:=GFX.Create(c);
tempdegree:= temp.get_true_degree;
gdegree:= g.get_true_degree;
if (gdegree=-1) then
Result:=GFX.Create(q_c,0)
else
if (tempdegree>=gdegree) then
begin
degreedif:= tempdegree - gdegree;
m:=GFX.Create(q,degreedif);
divisor:=GFX.Create(q,degreedif);
for i:=0 to c.get_degree-1 do
begin
m.coeffs[degreedif]:= G_F.Divv(temp.coeffs[tempdegree],g.coeffs[gdegree]);
divisor.set_degree(degreedif);
divisor.clear;
divisor.coeffs[degreedif]:= m.coeffs[degreedif];
temp.Sub(Mul(divisor,g));
tempdegree:= temp.get_true_degree;
degreedif:= tempdegree - gdegree;
if ( (degreedif<0) or ((temp.get_true_degree=0) and (Equal(temp.coeffs[0],Zeroo) ) )) then
break;
end;
Result:=GFX.Create(m);
end
else
Result:=GFX.Create(q_c,0);
end
else Result:=GFX.Create;
end;
function Modd(const c,g: GFX):GFX;
var q_c,q_g,q,tempdegree,gdegree,degreedif,i:integer;
temp,m,divisor:GFX;
Zeroo:GF;
begin
q_c:= c.get_size;
q_g:=g.get_size;
q:=q_c;
if (q_c=q_g) then
begin
Zeroo:=GF.Create(q,-1);
gdegree:= g.get_true_degree;
if (gdegree=-1) then
temp:=GFX.Create(q_c,0)
else
begin
temp:=GFX.Create(c);
tempdegree:= temp.get_true_degree;
if (tempdegree>=gdegree) then
begin
degreedif:= tempdegree - gdegree;
m:=GFX.Create(q,degreedif);
divisor:=GFX.Create(q,degreedif);
for i:=0 to c.get_degree-1 do
begin
m.coeffs[degreedif]:= G_F.Divv(temp.coeffs[tempdegree],g.coeffs[gdegree]);
divisor.set_degree(degreedif);
divisor.clear;
divisor.coeffs[degreedif]:= m.coeffs[degreedif];
temp.Sub(Mul(divisor,g));
tempdegree:= temp.get_true_degree;
degreedif:= tempdegree - gdegree;
if ( (degreedif<0) or ((temp.get_true_degree=0) and (Equal(temp.coeffs[0],Zeroo) ) )) then
break;
end;
end;
end;
Result:=GFX.Create(temp);
end
else Result:=GFX.Create;
end;
function Mul(const op1,op2:GFX):GFX;
begin
Result:=GFX.Create(op1);
Result.Mul(op2);
end;
function GFX.Count(const ingf:GF):GF;
var i:integer;
temp,ingfpower:GF;
begin
if (q = ingf.get_size) then
begin
temp:=GF.Create(coeffs[0]);
ingfpower:=GF.Create(ingf);
for i:=1 to degree do
begin
temp.Add(G_F.Mul(coeffs[i],ingfpower));
ingfpower.Mul(ingf);
end;
result:= GF.Create(temp);
end;
//result:=GF.Create;
end;
function GFX.toString : string ;
var i,terms:integer;
Zero0,One:GF;
s:string;
begin
terms:=0;
Zero0:=GF.Create(q,-1);
One:=GF.Create(q,0);
for i:=0 to degree do
if ( NOTEqual(coeffs[i],Zero0) ) then
begin
if (terms<>0) then Result:=Result+'+' else terms:=terms+1;
if (Equal(coeffs[i],One)) then Result:=Result+'x^'+IntToStr(i)
else Result:=Result+coeffs[i].ValueToString+'*x^'+IntToStr(i);
end;
if (terms = 0) then Result:='zero polynom';
end;
function Add(const op1, op2:GFX):GFX;
begin
Result:=GFX.Create(op1);
Result.Add(op2);
end;
function Sub(const op1, op2:GFX):GFX;
begin
Result:=GFX.Create(op1);
Result.Add(op2);
end;
function Mul(const ingfx:GFX; const ingf:GF):GFX;
var temp:GFX;
i:integer;
begin
if (ingf.get_size = ingfx.q) then
begin
temp:=GFX.Create(ingfx);
for i:=0 to ingfx.get_degree do
temp.coeffs[i].Mul(ingf);
Result:=GFX.Create(temp);
end
else Result:=GFX.Create;
end;
function Divv(const ingfx:GFX;const ingf:GF):GFX;
var temp:GFX;
i:integer;
begin
if (ingf.get_size = ingfx.q) then
begin
temp:=GFX.Create(ingfx);
for i:=0 to ingfx.get_degree do
temp.coeffs[i].Divv(ingf);
Result:=GFX.Create(temp);
end
else Result:=GFX.Create;
end;
end.
|
{ *******************************************************************************
Title: Gerenciamento de Memória - Swap - Algoritmos de Listas Encadeadas
Description: Exemplo que simula o gerencimento de memória com Swap utilizando
os algoritmos first fit, best fit e worst fit.
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:
alberteije@gmail.com
@author Albert Eije Barreto Mouta
@version 1.0
******************************************************************************* }
unit U_Principal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, jpeg, math, Grids;
type
TF_Principal = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
BotaoCriarProcessos: TBitBtn;
Bevel2: TBevel;
Label5: TLabel;
Bevel4: TBevel;
Label22: TLabel;
Label23: TLabel;
Bevel5: TBevel;
EditTamanhoProcessoInicial: TEdit;
Label25: TLabel;
EditTamanhoProcessoFinal: TEdit;
Label26: TLabel;
Label27: TLabel;
Label28: TLabel;
EditQuantidadeProcessos: TEdit;
EditMemoriaReal: TEdit;
EditMemoriaSO: TEdit;
Label30: TLabel;
EditTimeCriacaoInicial: TEdit;
EditTimeCriacaoFinal: TEdit;
Label31: TLabel;
Label24: TLabel;
Label32: TLabel;
Label33: TLabel;
Bevel6: TBevel;
BotaoInicia: TBitBtn;
Panel3: TPanel;
Memo2: TMemo;
Panel4: TPanel;
BotaoFecharEspecificacao: TSpeedButton;
ComboBoxAlgoritmoEstrategia: TComboBox;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
EditTimeDuracaoInicial: TEdit;
EditTimeDuracaoFinal: TEdit;
Timer1: TTimer;
BotaoParar: TButton;
Bevel1: TBevel;
BotaoReiniciar: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
BotaoEspecificacao: TBitBtn;
Label6: TLabel;
Label11: TLabel;
Label12: TLabel;
Bevel3: TBevel;
procedure atualizaBuracos;
procedure primeiroBuraco;
procedure melhorBuraco;
procedure piorBuraco;
procedure alocaSO;
procedure alocaProcesso(tam, id, topo: integer);
procedure retiraProcesso(id: integer);
procedure desenhaGrade;
procedure desenhaGradeBuracos(linhas: integer);
procedure desenhaGradeBotoes(linhas: integer);
procedure BotaoFecharEspecificacaoClick(Sender: TObject);
procedure BotaoEspecificacaoClick(Sender: TObject);
procedure EditTamanhoProcessoFinalExit(Sender: TObject);
procedure EditTimeCriacaoFinalExit(Sender: TObject);
procedure BotaoCriarProcessosClick(Sender: TObject);
procedure BotaoIniciaClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure EditMemoriaRealExit(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BotaoPararClick(Sender: TObject);
procedure ordenaGrid(Grid: TStringGrid; SortCol: integer; by: byte);
procedure BotaoReiniciarClick(Sender: TObject);
procedure EditMemoriaSOExit(Sender: TObject);
private
public
end;
var
F_Principal: TF_Principal;
tempoCriacao: integer;
tempoDuracao: integer;
tempoPassado: integer;
tamanhoProcesso: integer;
ultimaPosicao: integer;
ultimaPosicaoSo: integer;
pixelPorMB: integer;
MBPorPixel: integer;
grade: TStringGrid;
gradeBuracos: TStringGrid;
gradeBotoes: TStringGrid;
botoes: array of TPanel;
cores: array [1 .. 20] of TColor;
botaoSO: TPanel;
alturaProcesso: integer;
implementation
{$R *.dfm}
// função para converter horas para segundos
function Hora_Seg(Horas: string): LongInt;
Var
Hor, Min, Seg: LongInt;
begin
Horas[Pos(':', Horas)] := '[';
Horas[Pos(':', Horas)] := ']';
Hor := StrToInt(Copy(Horas, 1, Pos('[', Horas) - 1));
Min := StrToInt(Copy(Horas, Pos('[', Horas) + 1, (Pos(']', Horas) - Pos('[', Horas) - 1)));
if Pos(':', Horas) > 0 then
Seg := StrToInt(Copy(Horas, Pos(']', Horas) + 1, (Pos(':', Horas) - Pos(']', Horas) - 1)))
else
Seg := StrToInt(Copy(Horas, Pos(']', Horas) + 1, 2));
Result := Seg + (Hor * 3600) + (Min * 60);
end;
// verifica se o valor passado para a memoria é válido
function potenciaDeDois(Numero: Double): Boolean;
begin
// pega o tamanho passado para a memória e sai dividindo por 2. Se conseguir
// chegar até 2 é porque o número é válido
while Numero > 1 do
begin
Numero := Numero / 2;
if Numero = 2 then
begin
Result := true;
break;
end
else
Result := false;
end;
end;
// Função para ordernar um vetor (no caso a StringGrid)
procedure TF_Principal.ordenaGrid(Grid: TStringGrid; SortCol: integer; by: byte);
var
i, j: integer;
temp: TStringList;
begin
temp := TStringList.Create;
with Grid do
begin
for i := FixedRows to RowCount - 2 do
begin
for j := i + 1 to RowCount - 1 do
begin
if (by = 0) then
begin // ascendente
if AnsiCompareText(Cells[SortCol, i], Cells[SortCol, j]) < 0 then
begin
temp.assign(rows[j]);
rows[j].assign(rows[i]);
rows[i].assign(temp);
end;
end
else
begin // descendente
if AnsiCompareText(Cells[SortCol, i], Cells[SortCol, j]) > 0 then
begin
temp.assign(rows[j]);
rows[j].assign(rows[i]);
rows[i].assign(temp);
end;
end;
end;
end;
end;
temp.free;
end;
procedure TF_Principal.BotaoFecharEspecificacaoClick(Sender: TObject);
begin
Panel3.Visible := false;
Panel2.Enabled := true;
end;
procedure TF_Principal.BotaoEspecificacaoClick(Sender: TObject);
begin
Panel3.Visible := true;
Panel2.Enabled := false;
Panel3.BringToFront;
end;
procedure TF_Principal.EditMemoriaSOExit(Sender: TObject);
begin
if EditMemoriaSO.Text = '' then
EditMemoriaSO.Text := '128';
if StrToInt(EditMemoriaSO.Text) > StrToInt(EditMemoriaReal.Text) then
begin
ShowMessage('Tamanho do SO maior que o tamanho da memória - corrija.');
EditMemoriaSO.clear;
EditMemoriaSO.SetFocus;
end;
end;
procedure TF_Principal.EditTamanhoProcessoFinalExit(Sender: TObject);
begin
if StrToInt(EditTamanhoProcessoFinal.Text) < StrToInt(EditTamanhoProcessoInicial.Text) then
begin
ShowMessage('Intervalo incorreto - insira novamente');
EditTamanhoProcessoFinal.Text := '0';
EditTamanhoProcessoInicial.Text := '0';
EditTamanhoProcessoInicial.SetFocus;
end;
end;
procedure TF_Principal.EditTimeCriacaoFinalExit(Sender: TObject);
begin
if StrToInt(EditTimeCriacaoFinal.Text) < StrToInt(EditTimeCriacaoInicial.Text) then
begin
ShowMessage('Intervalo incorreto - insira novamente');
EditTimeCriacaoFinal.Text := '0';
EditTimeCriacaoInicial.Text := '0';
EditTimeCriacaoInicial.SetFocus;
end;
end;
procedure TF_Principal.desenhaGrade;
begin
{
Desenha a grade dos processos.
colunas utilizadas:
0 - id do processo
1 - Tamanho do processo
2 - Instante de criação
3 - Duração do processo
4 - Instante de Alocação
5 - Momento em que o processo entrou na fila
6 - Momento em que o processo saiu da fila
7 - Instante de conclusão do processo
8 - Tempo de espera
9 - Status do processo
10 - Posição de início da memória
11 - Posição final da memória
}
grade := TStringGrid.Create(F_Principal);
grade.Parent := F_Principal;
grade.BorderStyle := bsSingle;
grade.ColCount := 12;
grade.FixedCols := 0;
grade.FixedRows := 1;
grade.Height := 340;
grade.Left := 158;
grade.RowCount := StrToInt(EditQuantidadeProcessos.Text) + 1;
grade.ScrollBars := ssBoth;
grade.Top := 30;
grade.Visible := true;
grade.Width := 467;
grade.DefaultColWidth := 52;
grade.DefaultRowHeight := 20;
grade.ColWidths[0] := 30;
grade.ColWidths[5] := 30;
grade.ColWidths[6] := 30;
grade.Cells[0, 0] := 'id';
grade.Cells[1, 0] := 'Tamanho';
grade.Cells[2, 0] := 'Criação';
grade.Cells[3, 0] := 'Duração';
grade.Cells[4, 0] := 'Alocação';
grade.Cells[5, 0] := 'E.Fila';
grade.Cells[6, 0] := 'S.Fila';
grade.Cells[7, 0] := 'Conclusão';
grade.Cells[8, 0] := 'Espera';
grade.Cells[9, 0] := 'Status';
grade.Cells[10, 0] := 'Início';
grade.Cells[11, 0] := 'Fim';
end;
procedure TF_Principal.desenhaGradeBuracos(linhas: integer);
begin
{
Desenha a grade dos buracos.
colunas necessárias:
0 - id do Buraco
1 - Posição inicial
2 - Posição final
3 - Tamanho
}
gradeBuracos := TStringGrid.Create(F_Principal);
gradeBuracos.Parent := F_Principal;
gradeBuracos.BorderStyle := bsSingle;
gradeBuracos.ColCount := 4;
gradeBuracos.FixedCols := 0;
gradeBuracos.FixedRows := 1;
gradeBuracos.Height := 180;
gradeBuracos.Left := 158;
gradeBuracos.RowCount := linhas;
gradeBuracos.ScrollBars := ssBoth;
gradeBuracos.Top := 400;
gradeBuracos.Visible := true;
gradeBuracos.Width := 200;
gradeBuracos.DefaultColWidth := 40;
gradeBuracos.DefaultRowHeight := 20;
gradeBuracos.Cells[0, 0] := 'id';
gradeBuracos.Cells[1, 0] := 'Início';
gradeBuracos.Cells[2, 0] := 'Fim';
gradeBuracos.Cells[3, 0] := 'Tam.';
end;
procedure TF_Principal.desenhaGradeBotoes(linhas: integer);
begin
{
Desenha a grade dos panels (que representa os processos)
É necessário saber em que posição estão os processos para
atualizar a grade dos buracos.
colunas necessárias:
0 - id do Botão (panel)
1 - Posição inicial
2 - Posição final
3 - Tamanho
}
gradeBotoes := TStringGrid.Create(F_Principal);
gradeBotoes.Parent := F_Principal;
gradeBotoes.BorderStyle := bsSingle;
gradeBotoes.ColCount := 4;
gradeBotoes.FixedCols := 0;
gradeBotoes.FixedRows := 1;
gradeBotoes.Height := 180;
gradeBotoes.Left := 425;
gradeBotoes.RowCount := linhas + 1;
gradeBotoes.ScrollBars := ssBoth;
gradeBotoes.Top := 400;
gradeBotoes.Visible := true;
gradeBotoes.Width := 200;
gradeBotoes.DefaultColWidth := 40;
gradeBotoes.DefaultRowHeight := 20;
gradeBotoes.Cells[0, 0] := 'Cod.';
gradeBotoes.Cells[1, 0] := 'Início';
gradeBotoes.Cells[2, 0] := 'Fim';
gradeBotoes.Cells[3, 0] := 'Tam.';
end;
procedure TF_Principal.BotaoCriarProcessosClick(Sender: TObject);
var
i, tempoAnterior: integer;
begin
// seta o tamanho do array de processos para a quantidade de processos informada
// pelo usuário do sistema
SetLength(botoes, StrToInt(EditQuantidadeProcessos.Text));
// desenha a grade de processos
desenhaGrade;
BotaoCriarProcessos.Enabled := false;
tempoAnterior := 0;
for i := 1 to StrToInt(EditQuantidadeProcessos.Text) do
begin
// vai sortear os tempos e o tamanho dos processos
Randomize;
tamanhoProcesso := randomRange(StrToInt(EditTamanhoProcessoInicial.Text), StrToInt(EditTamanhoProcessoFinal.Text));
tempoCriacao := randomRange(StrToInt(EditTimeCriacaoInicial.Text), StrToInt(EditTimeCriacaoFinal.Text)) + tempoAnterior;
tempoDuracao := randomRange(StrToInt(EditTimeDuracaoInicial.Text), StrToInt(EditTimeDuracaoFinal.Text));
grade.Cells[0, i] := IntToStr(i);
grade.Cells[1, i] := IntToStr(tamanhoProcesso);
grade.Cells[2, i] := IntToStr(tempoCriacao);
grade.Cells[3, i] := IntToStr(tempoDuracao);
grade.Cells[5, i] := '0';
grade.Cells[6, i] := '0';
grade.Cells[9, i] := 'Inexistente';
tempoAnterior := tempoCriacao;
end;
BotaoInicia.Enabled := true;
Label6.Visible := true;
end;
procedure TF_Principal.BotaoIniciaClick(Sender: TObject);
begin
Label11.Visible := true;
Label12.Visible := true;
// num primeiro momento desenha-se a grade dos buracos com 2 linhas:
// uma para os títulos e outra para o primeiro buraco
desenhaGradeBuracos(2);
Timer1.Enabled := true;
BotaoInicia.Enabled := false;
// chama o procedimento que aloca o Sistema Operacional
alocaSO;
end;
procedure TF_Principal.Timer1Timer(Sender: TObject);
begin
// este procedimento é executado de 1 em 1 segundo
inc(tempoPassado);
Label23.Caption := IntToStr(tempoPassado);
if ComboBoxAlgoritmoEstrategia.Text = 'First Fit' then
primeiroBuraco
else if ComboBoxAlgoritmoEstrategia.Text = 'Best Fit' then
melhorBuraco
else if ComboBoxAlgoritmoEstrategia.Text = 'Worst Fit' then
piorBuraco;
end;
procedure TF_Principal.alocaSO;
var
cor: integer;
begin
{
Definição das variáveis MBPorPixel e pixelPorMB
A altura real em pixels da área reservada para mostrar a memória é 512.
Se o usuário entrar com um valor até 512, nós podemos representar um
pixel por um MB, de acordo com os valores abaixo. Lembrando que 1 pixel
é sempre um valor inteiro, por isso usa-se a função Trunc.
64MB de Ram Real - Fica 8 Pixels por MB ---> 512/64
128MB de Ram Real - Fica 4 Pixels por MB ---> 512/128
256MB de Ram Real - Fica 2 Pixels por MB ---> 512/256
512MB de Ram Real - Fica 1 Pixels por MB ---> 512/512
Se o usuário entrar com um valor maior que 512 não vai dar pra representar
a memória em pixels, porque a menor unidade de um pixel é 1.
Para isso teremos que usar a variável MBPorPixel para informar ao programa
quantos megas um pixel vai representar.
1024MB de Ram Real - Fica 2 MB sendo representados por 1 pixel ---> 1024/512
2048MB de Ram Real - Fica 4 MB sendo representados por 1 pixel ---> 2048/512
}
if StrToInt(EditMemoriaReal.Text) <= 512 then
begin
pixelPorMB := trunc(512 / StrToInt(EditMemoriaReal.Text));
MBPorPixel := 0;
end
else
begin
MBPorPixel := trunc(StrToInt(EditMemoriaReal.Text) / 512);
pixelPorMB := 0;
end;
{
Alocação do S.O. na memória
Neste momento vamos utilizar as variáveis MBPorPixel ou pixelPorMB.
É um simples cálculo para desenhar o processo dentro da área que foi
definida para representar a memória real.
}
{
se a memória for menor que 512 a ultima posição do SO, ou seja, o primeiro
buracao será calculado com base no tamanho do SO vezes a variável pixelPorMB
senão, a altura do processo será o tamanho do SO dividido pela variavel
MBPorPixel, e então o última posição do SO será a altura do processo.
}
if MBPorPixel = 0 then
ultimaPosicaoSo := (StrToInt(EditMemoriaSO.Text) * pixelPorMB)
else
begin
alturaProcesso := trunc(StrToInt(EditMemoriaSO.Text) / MBPorPixel);
ultimaPosicaoSo := alturaProcesso;
end;
// botaoSO representa um processo especial criado para o SO que se mantém
// fixo até o aplicativo ser finalizado
botaoSO := TPanel.Create(F_Principal);
botaoSO.Parent := F_Principal;
botaoSO.ParentBackground := False;
botaoSO.Top := 1;
botaoSO.Left := 0;
botaoSO.Width := 150;
botaoSO.Height := ultimaPosicaoSo;
botaoSO.Font.Size := 11;
botaoSO.Font.Style := [fsbold];
botaoSO.Font.Name := 'Arial';
botaoSO.Caption := 'Sistema Operacional';
// sorteia a cor para o botão do SO
Randomize;
cor := randomRange(1, 20);
botaoSO.Color := cores[cor];
// chama o procedimento que atualiza a grade dos buracos
atualizaBuracos;
end;
procedure TF_Principal.primeiroBuraco;
var
i, j: integer;
begin
// esse procedimento é chamado a cada segundo pelo método do Timer
// esse primeiro laço verifica os processos a sair
for i := 1 to StrToInt(EditQuantidadeProcessos.Text) do
begin
if grade.Cells[7, i] = Label23.Caption then
begin
retiraProcesso(StrToInt(grade.Cells[0, i]));
grade.Cells[9, i] := 'Concluído';
end;
end;
// esse segundo laço verifica os processos a entrar
for i := 1 to StrToInt(EditQuantidadeProcessos.Text) do
begin
// se o momento de criação do processo é igual ao tempo atual ou o processo está na fila
if (grade.Cells[2, i] = Label23.Caption) or (grade.Cells[9, i] = 'Fila') then
begin
// varre a grade dos buracos
for j := 1 to gradeBuracos.RowCount - 1 do
begin
// se o tamanho do buraco é maior que o tamanho do processo (pegou logo o primeiro buraco)
if (StrToInt(gradeBuracos.Cells[3, j]) >= StrToInt(grade.Cells[1, i])) then
begin
// posição inicial do processo: é o inicio do buraco
grade.Cells[10, i] := gradeBuracos.Cells[1, j];
// posição final do processo: é a posição inicial do buraco + Tamanho do Processo - 1
grade.Cells[11, i] := IntToStr(StrToInt(gradeBuracos.Cells[1, j]) + StrToInt(grade.Cells[1, i]) - 1);
// aloca o processo passando 3 parametros: Tamanho, Id, Inicio que é o topo
alocaProcesso(StrToInt(grade.Cells[1, i]), StrToInt(grade.Cells[0, i]), StrToInt(grade.Cells[10, i]));
// grava na grade de processos o momento da alocação do processo:
// Momento da Criação + (E.Fila - S.Fila)
// faz um teste para verificar se o processo já está na fila
if grade.Cells[5, i] <> '0' then
begin
grade.Cells[6, i] := Label23.Caption;
end;
// Instante de alocação: instante de criação + (Saída da Fila - Entrada na fila)
grade.Cells[4, i] := IntToStr(StrToInt(grade.Cells[2, i]) + (StrToInt(grade.Cells[6, i]) - StrToInt(grade.Cells[5, i])));
// grava na grade de processos o momento da conclusão do processo:
// Tempo de duração + Momento de alocação
grade.Cells[7, i] := IntToStr(StrToInt(grade.Cells[3, i]) + StrToInt(grade.Cells[4, i]));
// grava o status do processo
grade.Cells[9, i] := 'Rodando';
break;
end
// se chegou no final da grade dos buracos e não achou um buraco compatível
// coloca o processo na fila
else if (j = gradeBuracos.RowCount - 1) or (gradeBuracos.Cells[3, j + 1] = '') then
begin
if grade.Cells[5, i] = '0' then
begin
grade.Cells[9, i] := 'Fila';
grade.Cells[5, i] := Label23.Caption;
end;
break;
end;
end;
end;
end;
end;
procedure TF_Principal.melhorBuraco;
var
i, j, escolha, tEscolha: integer;
begin
// para o melhor buraco vamos ter que usar uma variável escolha
escolha := 0;
// laço para verificar processos a sair
for i := 1 to StrToInt(EditQuantidadeProcessos.Text) do
begin
if grade.Cells[7, i] = Label23.Caption then
begin
retiraProcesso(StrToInt(grade.Cells[0, i]));
grade.Cells[9, i] := 'Concluído';
end;
end;
// laço para verificar processoa a entrar
for i := 1 to StrToInt(EditQuantidadeProcessos.Text) do
begin
// tEscolha é setada para o tamanho da memória
tEscolha := StrToInt(EditMemoriaReal.Text);
// se chegou o momento do processo ou ele está na fila
if (grade.Cells[2, i] = Label23.Caption) or (grade.Cells[9, i] = 'Fila') then
begin
// procura pelo melhor buraco
for j := 1 to gradeBuracos.RowCount - 1 do
begin
// se não chegou no final da grade dos buracos
if gradeBuracos.Cells[3, j] <> '' then
begin
// se (tamanho do buraco >= tamanho do processo) e (o tamanho do buraco for menor que tEscolha)
if (StrToInt(gradeBuracos.Cells[3, j]) >= StrToInt(grade.Cells[1, i])) and (StrToInt(gradeBuracos.Cells[3, j]) <= tEscolha) then
begin
// aponta escolha para o índice do melhor buraco
escolha := j;
// atualiza tEscolha para o tamanho do melhor buraco
tEscolha := StrToInt(gradeBuracos.Cells[3, escolha]);
end;
end;
end;
// se achou um buraco para o processo, tEscolha será diferente do tamanho da memória
// e então o programa vai entrar nesse SE
if tEscolha <> StrToInt(EditMemoriaReal.Text) then
begin
// posição inicial: inicio do buraco
grade.Cells[10, i] := gradeBuracos.Cells[1, escolha];
// posição final: posição inicial do buraco + Tamanho do Processo - 1
grade.Cells[11, i] := IntToStr(StrToInt(gradeBuracos.Cells[1, escolha]) + StrToInt(grade.Cells[1, i]) - 1);
// aloca o processo passando 3 parametros: Tamanho, Id, Inicio que é o topo
alocaProcesso(StrToInt(grade.Cells[1, i]), StrToInt(grade.Cells[0, i]), StrToInt(grade.Cells[10, i]));
// grava na grade de processos o momento da alocação do processo:
// Momento da Criação + (E.Fila - S.Fila)
// faz um teste para verificar se o processo já está na fila
if grade.Cells[5, i] <> '0' then
begin
grade.Cells[6, i] := Label23.Caption;
end;
// Instante de alocação: instante de criação + (Saída da Fila - Entrada na fila)
grade.Cells[4, i] := IntToStr(StrToInt(grade.Cells[2, i]) + (StrToInt(grade.Cells[6, i]) - StrToInt(grade.Cells[5, i])));
// grava na grade de processos o momento da conclusão do processo:
// Tempo de duração + Momento de alocação
grade.Cells[7, i] := IntToStr(StrToInt(grade.Cells[3, i]) + StrToInt(grade.Cells[4, i]));
// grava o status do processo
grade.Cells[9, i] := 'Rodando';
// break;
end
// se chegou no final da grade dos buracos e não achou um buraco compatível
// coloca o processo na fila
else
begin
if grade.Cells[5, i] = '0' then
begin
grade.Cells[9, i] := 'Fila';
grade.Cells[5, i] := Label23.Caption;
end;
// break;
end;
end;
end;
end;
procedure TF_Principal.piorBuraco;
var
i, j, escolha, tEscolha: integer;
begin
// para o pior buraco vamos ter que usar uma variável escolha
escolha := 0;
// laço para verificar processos a sair
for i := 1 to StrToInt(EditQuantidadeProcessos.Text) do
begin
if grade.Cells[7, i] = Label23.Caption then
begin
retiraProcesso(StrToInt(grade.Cells[0, i]));
grade.Cells[9, i] := 'Concluído';
end;
end;
// laço para verificar processos a entrar
for i := 1 to StrToInt(EditQuantidadeProcessos.Text) do
begin
// tEscolha é setada para zero
tEscolha := 0;
// se chegou o momento do processo ou ele está na fila
if (grade.Cells[2, i] = Label23.Caption) or (grade.Cells[9, i] = 'Fila') then
begin
// procura pelo pior buraco
for j := 1 to gradeBuracos.RowCount - 1 do
begin
// se não chegou no final da grade dos buracos
if gradeBuracos.Cells[3, j] <> '' then
begin
// se (tamanho do buraco >= tamanho do processo) e (o tamanho do buraco for maior que tEscolha)
if (StrToInt(gradeBuracos.Cells[3, j]) >= StrToInt(grade.Cells[1, i])) and (StrToInt(gradeBuracos.Cells[3, j]) >= tEscolha) then
begin
// aponta escolha para o índice do pior buraco
escolha := j;
// atualiza tEscolha para o tamanho do pior buraco
tEscolha := StrToInt(gradeBuracos.Cells[3, escolha]);
end;
end;
end;
// se achou um buraco para o processo, tEscolha será diferente de zero
// e então o programa vai entrar nesse SE
if tEscolha <> 0 then
begin
// posição inicial: inicio do buraco
grade.Cells[10, i] := gradeBuracos.Cells[1, escolha];
// posição final: posição inicial do buraco + Tamanho do Processo - 1
grade.Cells[11, i] := IntToStr(StrToInt(gradeBuracos.Cells[1, escolha]) + StrToInt(grade.Cells[1, i]) - 1);
// aloca o processo passando 3 parametros: Tamanho, Id, Inicio que é o topo
alocaProcesso(StrToInt(grade.Cells[1, i]), StrToInt(grade.Cells[0, i]), StrToInt(grade.Cells[10, i]));
// grava na grade de processos o momento da alocação do processo:
// Momento da Criação + (E.Fila - S.Fila)
// faz um teste para verificar se o processo já está na fila
if grade.Cells[5, i] <> '0' then
begin
grade.Cells[6, i] := Label23.Caption;
end;
// Instante de alocação: instante de criação + (Saída da Fila - Entrada na fila)
grade.Cells[4, i] := IntToStr(StrToInt(grade.Cells[2, i]) + (StrToInt(grade.Cells[6, i]) - StrToInt(grade.Cells[5, i])));
// grava na grade de processos o momento da conclusão do processo:
// Tempo de duração + Momento de alocação
grade.Cells[7, i] := IntToStr(StrToInt(grade.Cells[3, i]) + StrToInt(grade.Cells[4, i]));
// grava o status do processo
grade.Cells[9, i] := 'Rodando';
// break;
end
// se chegou no final da grade dos buracos e não achou um buraco compatível
// coloca o processo na fila
else
begin
if grade.Cells[5, i] = '0' then
begin
grade.Cells[9, i] := 'Fila';
grade.Cells[5, i] := Label23.Caption;
end;
// break;
end;
end;
end;
end;
procedure TF_Principal.alocaProcesso(tam, id, topo: integer);
var
i, j, cor: integer;
begin
// se ainda não tem processos UltimaPosicao será zero, neste caso será
// atualizada para a Ultima posicão do SO que é o início do primeiro buraco
if ultimaPosicao = 0 then
ultimaPosicao := ultimaPosicaoSo;
// preenchimento do vetor de botões (panels) com os processos
botoes[id] := TPanel.Create(F_Principal);
botoes[id].Parent := F_Principal;
botoes[id].ParentBackground := False;
botoes[id].Left := 0;
botoes[id].Width := 150;
Randomize;
cor := randomRange(1, 20);
botoes[id].Color := cores[cor];
// se a memoria for <= 512
if MBPorPixel = 0 then
begin
alturaProcesso := tam;
ultimaPosicao := ultimaPosicao + tam;
end
// se a memória for maior que 512
else
begin
// se topo for um valor par faz a divisão direta com o trunc e nada será perdido
if topo mod 2 = 0 then
topo := trunc(topo / MBPorPixel)
// se topo for um valor impar faz a divisão e soma com 1
else
topo := trunc(topo / MBPorPixel) + 1;
// altura do processo é o tamanh dividido por MBPorPixel
alturaProcesso := trunc(tam / MBPorPixel);
// ultima posicao será a ultima posicao + altura do processo - serve para saber
// o inicio de um buraco
ultimaPosicao := ultimaPosicao + alturaProcesso;
end;
botoes[id].Top := topo;
botoes[id].Font.Style := [fsbold];
botoes[id].Font.Name := 'Arial';
botoes[id].Height := alturaProcesso;
botoes[id].Caption := 'Processo ' + IntToStr(id);
// atualiza a grade dos buracos
atualizaBuracos;
end;
procedure TF_Principal.retiraProcesso(id: integer);
var
i, somaEspera, processosConcluidos: integer;
begin
somaEspera := 0;
// retira o processo da tela
botoes[id].free;
// Tempo de espera do processo: alocacao - criacao + duracao
grade.Cells[8, id] := IntToStr(StrToInt(grade.Cells[4, id]) - StrToInt(grade.Cells[2, id]) + StrToInt(grade.Cells[3, id]));
// laço para somar os tempos de espera de todos os processos concluídos
for i := 1 to StrToInt(EditQuantidadeProcessos.Text) do
begin
if grade.Cells[8, i] <> '' then
begin
inc(processosConcluidos);
somaEspera := somaEspera + StrToInt(grade.Cells[8, i]);
end;
end;
// atualiza o tempo médio de espera
Label1.Caption := FloatToStr(roundto(somaEspera / processosConcluidos, -2));
// atualiza a grade dos buracos
atualizaBuracos;
end;
procedure TF_Principal.EditMemoriaRealExit(Sender: TObject);
begin
if potenciaDeDois(StrToFloat(EditMemoriaReal.Text)) = false then
begin
ShowMessage('Esse não é um valor válido para o tamanho da memória');
EditMemoriaReal.SetFocus;
end;
end;
procedure TF_Principal.atualizaBuracos;
var
i, j, somaMem: integer;
begin
somaMem := 0;
gradeBotoes.free;
// gera a grade de botões baseada no número de botões que existem na posição
// left=0
j := 0;
for i := 1 to ComponentCount - 1 do
begin
if (Components[i] is TPanel) then
if (Components[i] as TPanel).Left = 0 then
begin
j := j + 1;
end;
end;
// desenha a grade de botões passando o número de linhas
desenhaGradeBotoes(j);
// laço para preencher a grade dos botões
j := 0;
for i := 1 to ComponentCount - 1 do
begin
if (Components[i] is TPanel) then
if (Components[i] as TPanel).Left = 0 then
begin
j := j + 1;
// após testar se é um processo
// insere o indice na grade
gradeBotoes.Cells[0, j] := IntToStr(j);
// se a memória for maior que 512
if MBPorPixel <> 0 then
begin
// posicao inicial do processo ativo: topo do botão * MBPorpixel - 1
gradeBotoes.Cells[1, j] := IntToStr(((Components[i] as TPanel).Top * MBPorPixel) - 1);
// posicao final do processo ativo (: (altura do botão * MBPorPixel) + ((topo do botão - 1)*MBPorPixel)
gradeBotoes.Cells[2, j] := IntToStr(((Components[i] as TPanel).Height * MBPorPixel) + ((Components[i] as TPanel).Top - 1) * MBPorPixel);
end
// se a memória for menor ou igual a 512
else
begin
// posicao inicial: topo do botão
gradeBotoes.Cells[1, j] := IntToStr((Components[i] as TPanel).Top);
// posicao final: (altura do botão + topo do botão - 1)
gradeBotoes.Cells[2, j] := IntToStr((Components[i] as TPanel).Height + (Components[i] as TPanel).Top - 1);
end;
// se memória for <= 512 o tamanho do processo ativo será igual a altura do botão
if MBPorPixel = 0 then
gradeBotoes.Cells[3, j] := IntToStr((Components[i] as TPanel).Height)
// gradeBotoes.Cells[3,j] := IntToStr(trunc((Components[i] as TPanel).Height / PixelPorMB))
// senão será a altura do botão * MBPorPixel
else
gradeBotoes.Cells[3, j] := IntToStr((Components[i] as TPanel).Height * MBPorPixel);
// atualiza a variavel que cacula a quantidade de memória oculpada no momento
somaMem := somaMem + StrToInt(gradeBotoes.Cells[3, j]);
end;
end;
// mostra na tela a % de memória utilizada
Label3.Caption := FloatToStr(roundto(somaMem / StrToInt(EditMemoriaReal.Text), -2) * 100);
// ordena a grade dos processos ativos
ordenaGrid(gradeBotoes, 1, 1);
gradeBuracos.free;
desenhaGradeBuracos(gradeBotoes.RowCount);
// laço para preencher a grade dos buracos
j := 0;
for i := 1 to gradeBotoes.RowCount - 1 do
begin
// se ainda não chegou no último registro
if i <> gradeBotoes.RowCount - 1 then
begin
// se a posição inicial do botão posterior-1 for direfente da posição final do botão atual
// neste caso existe um buraco
if StrToInt(gradeBotoes.Cells[1, i + 1]) - 1 <> StrToInt(gradeBotoes.Cells[2, i]) then
begin
j := j + 1;
// insere o indice na grade
gradeBuracos.Cells[0, j] := IntToStr(j);
// posicao inicial do buraco
gradeBuracos.Cells[1, j] := IntToStr(StrToInt(gradeBotoes.Cells[2, i]) + 1);
// posicao final do buraco
gradeBuracos.Cells[2, j] := IntToStr(StrToInt(gradeBotoes.Cells[1, i + 1]) - 1);
// tamanho do buraco
gradeBuracos.Cells[3, j] := IntToStr((StrToInt(gradeBotoes.Cells[1, i + 1]) - 1) - (StrToInt(gradeBotoes.Cells[2, i])));
end;
end
// se chegou no último registro
else
begin
j := j + 1;
// insere o indice na grade
gradeBuracos.Cells[0, j] := IntToStr(j);
// posicao inicial do buraco
gradeBuracos.Cells[1, j] := IntToStr(StrToInt(gradeBotoes.Cells[2, i]) + 1);
// posicao final do buraco
gradeBuracos.Cells[2, j] := EditMemoriaReal.Text;
// tamanho do buraco será
gradeBuracos.Cells[3, j] := IntToStr(StrToInt(EditMemoriaReal.Text) - (StrToInt(gradeBotoes.Cells[2, i])));
end;
end;
end;
procedure TF_Principal.BotaoPararClick(Sender: TObject);
begin
Timer1.Enabled := false;
end;
procedure TF_Principal.BotaoReiniciarClick(Sender: TObject);
begin
Timer1.Enabled := true;
end;
procedure TF_Principal.FormCreate(Sender: TObject);
begin
// define as cores do array de cores
cores[1] := $0088BCF7;
cores[2] := $0080FFFF;
cores[3] := $0080FF80;
cores[4] := $00FFFF80;
cores[5] := $00FF8000;
cores[6] := $00C080FF;
cores[7] := $00C08000;
cores[8] := $00C08080;
cores[9] := $007C7CBE;
cores[10] := $008CB1FF;
cores[11] := $00FFC6C6;
cores[12] := $0000E8E8;
cores[13] := $00DCFFB9;
cores[14] := $00FF62FF;
cores[15] := $00DFBFFF;
cores[16] := $00CAFFFF;
cores[17] := $00CADBFF;
cores[18] := $00DFBDBD;
cores[19] := $00769771;
cores[20] := $00987093;
ultimaPosicao := 0;
end;
procedure TF_Principal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
botaoSO.free;
grade.free;
gradeBotoes.free;
gradeBuracos.free;
end;
end.
|
unit VarPointer;
interface
uses
SysUtils;
type
TPointer = class(TObject)
private
FPtr: PChar;
procedure SetPointer(const Value: PChar);
public
procedure ReadData(var Buf; Bytes: Integer; OffsetBytes: Integer=0);
function ReadByte(OffsetBytes: Integer=0): Byte;
function ReadWord(OffsetBytes: Integer=0): Word;
function ReadInteger(OffsetBytes: Integer=0): Integer;
procedure WriteData(var Data; Bytes: Integer; OffsetBytes: Integer=0);
procedure WriteInteger(Data: Integer; OffsetBytes: Integer=0);
procedure WriteByte(Data: Byte; OffsetBytes: Integer=0);
procedure WriteWord(Data: Word; OffsetBytes: Integer=0);
procedure SkipBytes(Bytes: Integer);
property Ptr: PChar read FPtr write SetPointer default nil;
end;
implementation
{ TPointer }
function TPointer.ReadByte(OffsetBytes: Integer): Byte;
begin
ReadData(Result, SizeOf(Result), OffsetBytes);
end;
procedure TPointer.ReadData(var Buf; Bytes, OffsetBytes: Integer);
begin
Move((FPtr + OffsetBytes)^, Buf, Bytes);
end;
function TPointer.ReadInteger(OffsetBytes: Integer): Integer;
begin
ReadData(Result, SizeOf(Result), OffsetBytes);
end;
function TPointer.ReadWord(OffsetBytes: Integer): Word;
begin
ReadData(Result, SizeOf(Result), OffsetBytes);
end;
procedure TPointer.SetPointer(const Value: PChar);
begin
FPtr := Value;
end;
procedure TPointer.SkipBytes(Bytes: Integer);
begin
FPtr := FPtr + Bytes;
end;
procedure TPointer.WriteByte(Data: Byte; OffsetBytes: Integer);
begin
WriteData(Data, SizeOf(Data), OffsetBytes);
end;
procedure TPointer.WriteData(var Data; Bytes, OffsetBytes: Integer);
begin
Move(Data, (FPtr + OffsetBytes)^, Bytes);
end;
procedure TPointer.WriteInteger(Data, OffsetBytes: Integer);
begin
WriteData(Data, SizeOf(Data), OffsetBytes);
end;
procedure TPointer.WriteWord(Data: Word; OffsetBytes: Integer);
begin
WriteData(Data, SizeOf(Data), OffsetBytes);
end;
end.
|
{***************************************************************
*
* Project : NewsReader
* Unit Name: ConnectThread
* Purpose : Sub Thread unit
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:30:26
* Author : <unknown>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit ConnectThread;
interface
uses
{$IFDEF Linux}
{$ELSE}
{$ENDIF}
Classes, SysUtils, IdTCPClient;
type
TProc = procedure() of object;
TExcClass = class of exception;
TIdConnectThread = class(TThread)
public
ConnectProc: TProc;
errormsg: string;
done: boolean;
excclass: TExcClass;
procedure Execute; override;
end;
procedure ConnectThreaded(AClient: TIdTCPClient);
implementation
uses IdAntiFreezeBase, windows;
procedure ConnectThreaded(AClient: TIdTCPClient);
begin
with TIdConnectThread.Create(true) do
try
TMethod(ConnectProc).Code := Addr(TIdTCPClient.Connect);
// FConnecting := true; // new property Connecting (readonly)
resume;
repeat
sleep(10);
TIdAntiFreezeBase.DoProcess(true);
until done;
// FConnecting := false;
if assigned(excclass) then
raise excclass.Create(errormsg);
finally
free;
end;
end;
{ TIdConnectThread }
procedure TIdConnectThread.Execute;
begin
inherited;
done := false;
errormsg := '';
excclass := nil;
try
if assigned(connectproc) then
connectproc();
except
on e: exception do
begin
errormsg := e.message;
excclass := TExcClass(e.classtype);
end;
end;
done := true;
end;
end.
|
unit adot.VCL.Log;
interface
uses
adot.Log,
adot.VCL.Tools,
adot.Win.Tools,
Winapi.Messages,
Winapi.Windows,
System.SysUtils,
System.SyncObjs,
System.Classes,
System.StrUtils;
type
// Thread-safe implementation of VCL logger (message based to avoid any
// deadlock posibility).
TVCLDelegatedLog = class(TCustomDelegatedLog)
protected
const
wmLogMessage = wm_user + 1;
var
FLogLines: TStringList;
FLogLinesMsgSent: Boolean;
FLogLinesCS: TCriticalSection;
FMessanger: TMessenger;
FOnBeginUpdate, FOnEndUpdate: TProc;
procedure Send(AData: pointer; ASize: Integer); override;
procedure DoFlush; override;
procedure OnMessage(var AMessage: TMessage); virtual;
public
constructor Create(AOnLogMessage: TCustomDelegatedLog.TOnLogMessage;
AOnBeginUpdate: TProc = nil; AOnEndUpdate: TProc = nil);
destructor Destroy; override;
end;
TVCLStringsLog = class(TVCLDelegatedLog)
protected
FStrings: TStrings;
procedure LogString(const Msg: string);
procedure OnMessage(var AMessage: TMessage); override;
public
constructor Create(AStrings: TStrings);
end;
procedure AddMemoLog(ALines: TStrings);
implementation
{ TVCLDelegatedLog }
constructor TVCLDelegatedLog.Create(AOnLogMessage: TCustomDelegatedLog.TOnLogMessage;
AOnBeginUpdate: TProc = nil; AOnEndUpdate: TProc = nil);
begin
FLogLines := TStringList.Create;
FLogLinesCS := TCriticalSection.Create;
FMessanger := TMessenger.Create(OnMessage);
FOnBeginUpdate := AOnBeginUpdate;
FOnEndUpdate := AOnEndUpdate;
inherited Create(AOnLogMessage);
end;
destructor TVCLDelegatedLog.Destroy;
begin
FreeAndNil(FMessanger);
FreeAndNil(FLogLinesCS);
FreeAndNil(FLogLines);
inherited;
end;
procedure TVCLDelegatedLog.DoFlush;
begin
end;
procedure TVCLDelegatedLog.Send(AData: pointer; ASize: Integer);
var
s: string;
begin
s := DataAsString(Adata, ASize);
FLogLinesCS.Enter;
try
FLogLines.Add(s);
if not FLogLinesMsgSent then
FLogLinesMsgSent := PostMessage(FMessanger.Handle, wmLogMessage, 0,0);
finally
FLogLinesCS.Leave;
end;
end;
procedure TVCLDelegatedLog.OnMessage(var AMessage: TMessage);
var
i: Integer;
begin
if not Assigned(FOnLogMessage) or (AMessage.Msg<>wmLogMessage) then
Exit;
FLogLinesCS.Enter;
try
FLogLinesMsgSent := False;
if Assigned(FOnBeginUpdate) then
FOnBeginUpdate;
try
for i := 0 to FLogLines.Count-1 do
FOnLogMessage(FLogLines[i]);
finally
if Assigned(FOnEndUpdate) then
FOnEndUpdate;
end;
FLogLines.Clear;
finally
FLogLinesCS.Leave;
end;
end;
{ TVCLStringsLog }
constructor TVCLStringsLog.Create(AStrings: TStrings);
begin
FStrings := AStrings;
inherited Create(LogString);
end;
procedure TVCLStringsLog.LogString(const Msg: string);
var
s: string;
begin
s := Msg;
if EndsText(#13#10, s) or EndsText(#10#13, s) then
SetLength(s, Length(s)-2);
FStrings.Add(s);
end;
procedure TVCLStringsLog.OnMessage(var AMessage: TMessage);
begin
FStrings.BeginUpdate;
try
inherited;
finally
FStrings.EndUpdate;
end;
end;
procedure AddMemoLog(ALines: TStrings);
begin
adot.Log.AddLogger(TVCLStringsLog.Create(ALines));
end;
end.
|
unit ASPI;
interface
uses
SPTI,
Windows;
const
SENSE_LEN = 24; { Default sense buffer length}
SRB_DIR_SCSI = $00; { Direction determined by SCSI}
SRB_POSTING = $01; { Enable ASPI posting}
SRB_ENABLE_RESIDUAL_COUNT = $04; { Enable residual byte count reporting}
SRB_DIR_IN = $08; { Transfer from SCSI target to host}
SRB_DIR_OUT = $10; { Transfer from host to SCSI target}
SRB_EVENT_NOTIFY = $40; { Enable ASPI event notification}
RESIDUAL_COUNT_SUPPORTED = $02; { Extended buffer flag}
MAX_SRB_TIMEOUT = 108000; { 30 hour maximum timeout in sec}
DEFAULT_SRB_TIMEOUT = 108000; { Max timeout by default}
{******************************************************************************}
{ ASPI Command Definitions }
{******************************************************************************}
SC_HA_INQUIRY = $00; { Host adapter inquiry}
SC_GET_DEV_TYPE = $01; { Get device type}
SC_EXEC_SCSI_CMD = $02; { Execute SCSI command}
SC_ABORT_SRB = $03; { Abort an SRB}
SC_RESET_DEV = $04; { SCSI bus device reset}
SC_SET_HA_PARMS = $05; { Set HA parameters}
SC_GET_DISK_INFO = $06; { Get Disk information}
SC_RESCAN_SCSI_BUS = $07; { ReBuild SCSI device map}
SC_GETSET_TIMEOUTS = $08; { Get/Set target timeouts}
{******************************************************************************}
{ SRB Status }
{******************************************************************************}
SS_PENDING = $00; { SRB being processed}
SS_COMP = $01; { SRB completed without error}
SS_ABORTED = $02; { SRB aborted}
SS_ABORT_FAIL = $03; { Unable to abort SRB}
SS_ERR = $04; { SRB completed with error}
SS_INVALID_CMD = $80; { Invalid ASPI command}
SS_INVALID_HA = $81; { Invalid host adapter number}
SS_NO_DEVICE = $82; { SCSI device not installed}
SS_INVALID_SRB = $E0; { Invalid parameter set in SRB}
SS_OLD_MANAGER = $E1; { ASPI manager doesn't support Windows}
SS_BUFFER_ALIGN = $E1; { Buffer not aligned (replaces OLD_MANAGER in Win32)}
SS_ILLEGAL_MODE = $E2; { Unsupported Windows mode}
SS_NO_ASPI = $E3; { No ASPI managers resident}
SS_FAILED_INIT = $E4; { ASPI for windows failed init}
SS_ASPI_IS_BUSY = $E5; { No resources available to execute cmd}
SS_BUFFER_TO_BIG = $E6; { Buffer size to big to handle!}
SS_MISMATCHED_COMPONENTS = $E7; { The DLLs/EXEs of ASPI don't version check}
SS_NO_ADAPTERS = $E8; { No host adapters to manage}
SS_INSUFFICIENT_RESOURCES = $E9; { Couldn't allocate resources needed to init}
SS_ASPI_IS_SHUTDOWN = $EA; { Call came to ASPI after PROCESS_DETACH}
SS_BAD_INSTALL = $EB; { The DLL or other components are installed wrong}
{******************************************************************************}
{ Host Adapter Status }
{******************************************************************************}
HASTAT_OK = $00; { Host adapter did not detect an error}
HASTAT_SEL_TO = $11; { Selection Timeout}
HASTAT_DO_DU = $12; { Data overrun data underrun}
HASTAT_BUS_FREE = $13; { Unexpected bus free}
HASTAT_PHASE_ERR = $14; { Target bus phase sequence failure}
HASTAT_TIMEOUT = $09; { Timed out while SRB was waiting to beprocessed.}
HASTAT_COMMAND_TIMEOUT = $0B; { Adapter timed out processing SRB.}
HASTAT_MESSAGE_REJECT = $0D; { While processing SRB, the adapter received a MESSAGE}
HASTAT_BUS_RESET = $0E; { A bus reset was detected.}
HASTAT_PARITY_ERROR = $00; { A parity error was detected.}
HASTAT_REQUEST_SENSE_FAILED = $10; { The adapter failed in issuing}
DTYPE_DASD = $00; { Disk Device }
DTYPE_SEQD = $01; { Tape Device }
DTYPE_PRNT = $02; { Printer }
DTYPE_PROC = $03; { Processor }
DTYPE_WORM = $04; { Write-once read-multiple }
DTYPE_CROM = $05; { CD-ROM device }
DTYPE_CDROM = $05; { CD-ROM device }
DTYPE_SCAN = $06; { Scanner device }
DTYPE_OPTI = $07; { Optical memory device }
DTYPE_JUKE = $08; { Medium Changer device }
DTYPE_COMM = $09; { Communications device }
DTYPE_RESL = $0A; { Reserved (low) }
DTYPE_RESH = $1E; { Reserved (high) }
DTYPE_UNKNOWN = $1F; { Unknown or no device type }
SCSI_INQUIRY = $12;
DEF_SENSE_LEN = 16; { Default Sense Len }
{***************************************************************************}
{ Request Sense Data Format }
{***************************************************************************}
type TSenseArea = packed record
ErrorCode,
SegmentNum,
SenseKey,
InfoByte0,
InfoByte1,
InfoByte2,
InfoByte3,
AddSenLen,
ComSpecInf0,
ComSpecInf1,
ComSpecInf2,
ComSpecInf3,
AddSenseCode,
AddSenQual,
FieldRepUCode,
SenKeySpec15,
SenKeySpec16,
SenKeySpec17: Byte;
AddSenseBytes: Array[18..$20] of byte;
end;
{*****************************************************************************}
{ SRB - HOST ADAPTER INQUIRY - SC_HA_INQUIRY (0) }
{*****************************************************************************}
type
TSRB_HAInquiry = packed record
Command: BYTE;
Status: BYTE;
HaId: BYTE;
Flags: BYTE;
Hdr_Rsvd: LongInt;
HA_Count: BYTE;
HA_SCSI_ID: BYTE;
HA_ManagerId: Array[0..15] of char;
HA_Identifier: Array[0..15] of char;
HA_Unique: Array[0..15] of char;
HA_Rsvd1: Word;
end;
{******************************************************************************}
{ SRB - GET DEVICE TYPE - SC_GET_DEV_TYPE (1) }
{******************************************************************************}
type
TSRB_GDEVBlock = packed record
Command: BYTE;
Status: BYTE;
HaId: BYTE;
Flags: BYTE;
Hdr_Rsvd: LongInt;
Target: BYTE;
Lun: BYTE;
DeviceType: BYTE;
Rsvd1: BYTE;
end;
{*****************************************************************************}
{ SRB - EXECUTE SCSI COMMAND - SC_EXEC_SCSI_CMD (2) }
{*****************************************************************************}
type
TSRB_ExecSCSICmd = packed record
Command: BYTE;
Status: BYTE;
HaId: BYTE;
Flags: BYTE;
Hdr_Rsvd: LongInt;
Target: BYTE;
Lun: BYTE;
Rsvd1: Word;
BufLen: LongInt;
BufPointer: PChar;
SenseLen: BYTE;
CDBLen: BYTE;
HaStat: BYTE;
TargStat: BYTE;
PostProc: THandle;
Rsvd2: array[0..19] of byte;
CDBCmd: Byte;
CDBByte: array[1..15] of byte;
SenseArea: TSenseArea;
end;
{******************************************************************************}
{ SRB - ABORT AN SRB - SC_ABORT_SRB (3) }
{******************************************************************************}
type
TSRB_Abort = packed record
Command: BYTE;
Status: BYTE;
HaId: BYTE;
Flags: BYTE;
Hdr_Rsvd: LongInt;
ToAbort: Pointer;
end;
{*****************************************************************************}
{ SRB - BUS DEVICE RESET - SC_RESET_DEV (4) }
{*****************************************************************************}
type
SRB_BusDeviceReset = packed record
Command: BYTE;
Status: BYTE;
HaId: BYTE;
Flags: BYTE;
Hdr_Rsvd: LongInt;
Target: BYTE;
Lun: BYTE;
Rsvd1: Array[0..12-1] of BYTE;
HaStat: BYTE;
TargStat: BYTE;
PostProc: Pointer;
Rsvd2: Array[0..36-1] of BYTE;
end;
{******************************************************************************}
{ SRB - GET DISK INFORMATION - SC_GET_DISK_INFO }
{******************************************************************************}
type
TSRB_GetDiskInfo = packed record
Command: BYTE;
Status: BYTE;
HaId: BYTE;
Flags: BYTE;
Hdr_Rsvd: LongInt;
Target: BYTE;
Lun: BYTE;
DriveFlags: BYTE;
Int13HDriveInfo: BYTE;
Heads: BYTE;
Sectors: BYTE;
Rsvd1: Array[0..9] of BYTE;
end {SRB_GetDiskInfo};
{******************************************************************************}
{ SRB - RESCAN SCSI BUS(ES) ON SCSIPORT }
{******************************************************************************}
type
SRB_RescanPort = packed record
Command: BYTE;
Status: BYTE;
HaId: BYTE;
Flags: BYTE;
Hdr_Rsvd: LongInt;
end {RescanPort};
{******************************************************************************}
{ SRB - GET/SET TARGET TIMEOUTS }
{******************************************************************************}
type
TSRB_GetSetTimeouts = packed record
Command: BYTE;
Status: BYTE;
HaId: BYTE;
Flags: BYTE;
Hdr_Rsvd: LongInt;
Target: BYTE;
Lun: BYTE;
Timeout: LongInt;
end;
{******************************************************************************}
{ ASPIBUFF - Structure For Controllng I/O Buffers }
{******************************************************************************}
type
tag_ASPI32BUFF = packed record
AB_BufPointer: Pointer;
AB_BufLen: LongInt;
AB_ZeroFill: LongInt;
AB_Reserved: LongInt;
end;
type
TDiscInformation = record
DataLen: Word;
DiscStatus: Byte;
FirstTrack: Byte;
Sessions: Byte;
FirstTrackOfLastSession: Byte;
LastTrackOfLastSession: Byte;
InformationValidity: Byte;
DiscType: Byte;
Resvd: array [0..2] of Byte;
DiscIdentification: array [0..3] of Byte;
Resvd2: array [12..50] of Byte;
end;
type
TTrackInformationBlock = packed record
DataLength: Word;
TrackNumber,
SessionNumber,
Reserved1,
TrackMode,
DataMode,
Reserved2: Byte;
TrackStartAddress,
NextWritableAddress,
FreeBlocks,
FixedPacketSize,
TrackSize,
LastRecordedAddress: LongWord;
TrackNumber2,
SessionNumber2,
Res3, Res4, Res5, Res6, Res7, Res8: Byte;
end;
type
TTOCPMATIP0100 = packed record
DataLength: Word;
FirstSession, LastSession: Byte;
Field0: Byte;
Field1: Byte;
Field2: Byte;
Reserved: Byte;
StMin: Byte;
StSec: Byte;
StFrame: Byte;
Reseved2: Byte;
EdMin: Byte;
EdSec: Byte;
EdFrame: Byte;
Others: array[0..10] of byte;
end;
TModePage05 = packed record
PageCode,
PageLen: byte;
WriteType : Byte;
TrackMode : Byte;
DBType : Byte;
LinkSize: Byte;
Res6: Byte;
Host_App_Code: Byte;
SessionFormat: Byte;
Res9: Byte;
PacketSize: LongWord;
PauseLen: Word;
MediaCatNumber: array[1..16] of char;
ISRC: array[1..14] of char;
sub_header: array[1..4] of char;
vendor_uniq: array[1..4] of char;
end;
TTEST = packed record
Res1: Byte;
Res2: Byte;
Speed: WORD;
end;
TModePage2A = packed record // CD Capabilities
PageCode: Byte; //0
PageLen: Byte; //1
DiscReadCaps: Byte; //2
DiscWriteCaps: Byte; //3
AudioPlay: Byte; //4
CDDASupported: Byte; //5
Lock: Byte; //6
SepChanVol: Byte; //7
MaxReadSpeed: Word; //8-9
NumVolLevels: Word; //10-11
BufferSize:Word; //12-13
CurReadSpeed: Word; //14-15
Reserved16: Byte; //16
BCKF: Byte; //17
MaxWriteSpeed: Word; //18-19
CurWriteSpeed: Word; //20-21
CMRS: WORD; //22-23
RES24: BYTE; RES25: BYTE; RES26: BYTE; //24-26
RCS: BYTE; //27
CWSS: WORD; //28-29
WW: Word; //30-31
WriteSpeeds:array [0..120] of Ttest;
end;
TInquiryData = packed record
PeripheralData: Byte;
RMB: Byte;
Version: Byte;
Byte3: Byte;
AdditionalLen: Byte;
Byte5: Byte;
Byte6: Byte;
Byte7: Byte;
VendorID: array[8..15] of char;
ProductID: array[16..31] of char;
ProductRev: array[32..35] of char;
VendorSpecific: array[36..55] of char;
Byte56: Byte;
Reseverd: Byte;
v1, v2, v3, v4: Word;
OtherVData: array [0..62] of byte;
DeviceType: ShortInt; //PeripheralData
Qulifier: Byte;
end;
type
TTOCData0000 = packed record
DataLength : Word;
FirstTrackNumber: Byte;
LastTrackNumber: Byte;
Res1, Res2: Byte;
TrackNumber: Byte;
Res3: Byte;
TrackStartAddress: Cardinal;
OtherData: array[0..101] of byte;
end;
TTOCData0001 = packed record
DataLength : Word;
FirstTrackNumber: Byte;
LastTrackNumber: Byte;
end;
PSCSI_ADDRESS = ^SCSI_ADDRESS;
SCSI_ADDRESS = packed record
Length: Cardinal;
PortNumber,
PathId,
TargetId,
Lun: Byte;
end;
type
TDisc = record
Capacity: Integer;
DiscStatus,
LastSession
: Byte;
BackgroundFormat: Byte;
Eraseable: Boolean;
end;
var
ASPILayerName: String;
TryInternalASPIFirst: Boolean;
SendASPI32Command: function(LPSRB: Pointer):DWORD; cdecl;
GetASPI32SupportInfo: function: DWORD; cdecl;
ASPIDLLLoaded: Boolean = False;
function _InitializeASPI(InternalFirst: Boolean; AspiPath: String): Boolean;
function _ReInitializeASPI: Boolean;
function _DeInitializeASPI: Boolean;
implementation
var
ASPIDLLHandle: DWORD = 0;
{******************************************************************************}
{ _InitializeASPI }
{******************************************************************************}
function _InitializeASPI(InternalFirst: Boolean; AspiPath: String): Boolean;
var
ErrorMode: DWORD;
begin
ErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
if InternalFirst and (SPTIInit <> 0) then
begin
@GetASPI32SupportInfo := @__GetASPI32SupportInfo;
@SendASPI32Command := @__SendASPI32Command;
ASPIDLLLoaded := True;
ASPILayerName := 'BMASPI32';
end;
if not ASPIDLLLoaded then
begin
ASPIDLLHandle := 0;
try
if (AspiPath <> '')
then ASPIDLLHandle := LoadLibrary(pchar(AspiPath));
if (ASPIDLLHandle = 0)
then ASPIDLLHandle := LoadLibrary('.\WNASPI32.DLL');
if ASPIDLLHandle = 0 then
ASPIDLLHandle := LoadLibrary('WNASPI32.DLL');
except
ASPIDLLHandle := 0;
end;
if ASPIDLLHandle > 31 then
begin
ASPILayerName := 'WNASPI32.DLL';
ASPIDLLLoaded := True;
@GetASPI32SupportInfo := GetProcAddress(ASPIDLLHandle,'GetASPI32SupportInfo');
@SendASPI32Command := GetProcAddress(ASPIDLLHandle,'SendASPI32Command');
Assert(@GetASPI32SupportInfo <> nil);
Assert(@SendASPI32Command <> nil);
end
else
begin
(*
ASPIDLLHandle := LoadLibrary('ASAPI.DLL');
if ASPIDLLHandle > 31 then
begin
ASPILayerName := 'ASAPI.DLL';
ASPIDLLLoaded := True;
@GetASPI32SupportInfo := GetProcAddress(ASPIDLLHandle,'GetASAPI32SupportInfo');
Assert(@GetASPI32SupportInfo <> nil);
@SendASPI32Command := GetProcAddress(ASPIDLLHandle,'SendASAPI32Command');
Assert(@SendASPI32Command <> nil);
end; *)
end;
if (not ASPIDLLLoaded) and (SPTIInit <> 0) then
begin
@GetASPI32SupportInfo := @__GetASPI32SupportInfo;
@SendASPI32Command := @__SendASPI32Command;
ASPIDLLLoaded := True;
ASPILayerName := 'BMASPI32';
end;
end;
if ASPIDLLLoaded then
GetASPI32SupportInfo;
result := ASPIDLLLoaded;
TryInternalASPIFirst := InternalFirst;
SetErrorMode(ErrorMode);
end;
function _ReInitializeASPI: Boolean;
begin
if ASPILayerName = 'BMASPI32' then
begin
ASPIDLLLoaded := False;
SPTIDeInit;
end
else
begin
_DeInitializeASPI;
end;
_InitializeASPI(TryInternalASPIFirst, '');
result := True;
end;
function _DeInitializeASPI: Boolean;
begin
result := true;
if ASPIDLLLoaded and (ASPIDLLHandle <> 0) then
begin
ASPIDLLLoaded := False;
Result := FreeLibrary(ASPIDLLHandle);
ASPIDLLHandle := 0;
end;
end;
initialization
ASPIDLLLoaded := False;
finalization
if ASPIDLLLoaded and (ASPIDLLHandle <> 0) then
FreeLibrary(ASPIDLLHandle);
end.
|
unit MapSetupObjectType;
interface
uses Graphics, Classes, WinUtils, MapObjects2_TLB, Dialogs, SysUtils, GlblCnst,
FileCtrl;
type
LayerRecord = record
LayerName : String;
LayerFileName : String;
LayerPathName : String;
MainLayer : Boolean;
Visible : Boolean;
Transparent : Boolean;
LayerColor : LongInt;
LayerType : String;
FillType : LongInt;
LayerOrder : LongInt;
UseLabelPlacer : Boolean;
UseLabelRenderer : Boolean;
TextField : String;
XOffsetField : String;
YOffsetField : String;
RotationField : String;
SplinedText : Boolean;
Flip : Boolean;
DrawBackground : Boolean;
HeightField : String;
SymbolField : String;
LevelField : String;
PlaceAbove : Boolean;
PlaceBelow : Boolean;
PlaceOn : Boolean;
end;
LayerPointer = ^LayerRecord;
TMapSetupObject = class
private
FLayerList : TList;
public
SetupName : String;
DefaultZoomPercentToDrawDetails : Double;
MapFileKeyField : String;
PASKeyField : String;
PASIndex : String;
LabelColor : LongInt;
LabelType : Integer;
FillColor : LongInt;
FillType : Integer;
DashDotSBLFormat : Boolean;
UseMapParcelIDFormat : Boolean;
AV_SP_Ratio_Decimals : Integer;
Constructor Create;
Function GetLayerCount : Integer;
Procedure AddLayer(_LayerName : String;
_LayerFile : String;
_MainLayer : Boolean;
_LayerColor : LongInt;
_Visible : Boolean;
_Transparent : Boolean;
_LayerType : String;
_FillType : LongInt;
_LayerOrder : LongInt;
_UseLabelPlacer : Boolean;
_UseLabelRenderer : Boolean;
_TextField : String;
_XOffsetField : String;
_YOffsetField : String;
_RotationField : String;
_SplinedText : Boolean;
_Flip : Boolean;
_DrawBackground : Boolean;
_HeightField : String;
_SymbolField : String;
_LevelField : String;
_PlaceAbove : Boolean;
_PlaceBelow : Boolean;
_PlaceOn : Boolean);
Function GetLayerName(I : Integer) : String;
Function GetLayerColor(LayerName : String) : LongInt;
Function GetLayerLocation(LayerName : String) : String;
Function GetLayerType(LayerName : String) : String;
Function GetLayerDatabaseName(LayerName : String) : String;
Function GetLayerFillType(LayerName : String) : LongInt;
Function GetLayerOrder(LayerName : String) : LongInt;
Function GetTextFieldName(LayerName : String) : String;
Function GetXOffsetFieldName(LayerName : String) : String;
Function GetYOffsetFieldName(LayerName : String) : String;
Function GetRotationFieldName(LayerName : String) : String;
Function UseLabelPlacer(LayerName : String) : Boolean;
Function UseLabelRenderer(LayerName : String) : Boolean;
Function IsMainLayer(LayerName : String) : Boolean;
Function MapLayerIsVisible(LayerName : String) : Boolean;
Function MapLayerIsTransparent(LayerName : String) : Boolean;
Procedure SetLayerVisible(LayerName : String;
IsVisible : Boolean);
Procedure SortLayersByLayerOrder;
Procedure Clear;
Destructor Destroy; override;
end;
const
lyMain = -1;
implementation
uses Utilitys;
{=============================================================}
Constructor TMapSetupObject.Create;
begin
inherited Create;
FLayerList := TList.Create;
end; {Create}
{=============================================================}
Function TMapSetupObject.GetLayerCount : Integer;
begin
Result := FLayerList.Count;
end;
{=============================================================}
Procedure TMapSetupObject.AddLayer(_LayerName : String;
_LayerFile : String;
_MainLayer : Boolean;
_LayerColor : LongInt;
_Visible : Boolean;
_Transparent : Boolean;
_LayerType : String;
_FillType : LongInt;
_LayerOrder : LongInt;
_UseLabelPlacer : Boolean;
_UseLabelRenderer : Boolean;
_TextField : String;
_XOffsetField : String;
_YOffsetField : String;
_RotationField : String;
_SplinedText : Boolean;
_Flip : Boolean;
_DrawBackground : Boolean;
_HeightField : String;
_SymbolField : String;
_LevelField : String;
_PlaceAbove : Boolean;
_PlaceBelow : Boolean;
_PlaceOn : Boolean);
var
LayerPtr : LayerPointer;
begin
New(LayerPtr);
with LayerPtr^ do
begin
LayerName := _LayerName;
LayerFileName := StripPath(_LayerFile);
LayerPathName := ReturnPath(_LayerFile);
{FXX04302003-2(2.07): If the directory does not exist, try locally.}
If not DirectoryExists(LayerPathName)
then LayerPathName := ChangeLocationToLocalDrive(LayerPathName);
MainLayer := _MainLayer;
LayerColor := _LayerColor;
Visible := _Visible;
Transparent := _Transparent;
LayerType := _LayerType;
{CHG08052004-1(M1.5): Add fill type and layer order.}
FillType := _FillType;
LayerOrder := _LayerOrder;
{CHG02172005-1(M1.6): Add label \ renderer options t layers.}
UseLabelPlacer := _UseLabelPlacer;
UseLabelRenderer := _UseLabelRenderer;
TextField := _TextField;
XOffsetField := _XOffsetField;
YOffsetField := _YOffsetField;
RotationField := _RotationField;
SplinedText := _SplinedText;
Flip := _Flip;
DrawBackground := _DrawBackground;
HeightField := _HeightField;
SymbolField := _SymbolField;
LevelField := _LevelField;
PlaceAbove := _PlaceAbove;
PlaceBelow := _PlaceBelow;
PlaceOn := _PlaceOn;
end; {with LayerPtr^ do}
{Always make sure the main layer is the first layer in the list.}
If _MainLayer
then FLayerList.Insert(0, LayerPtr)
else FLayerList.Add(LayerPtr);
end; {AddLayer}
{===================================================}
Function TMapSetupObject.GetLayerName(I : Integer) : String;
begin
try
Result := LayerPointer(FLayerList[I])^.LayerName;
except
MessageDlg('Can not get layer name for layer # ' + IntToStr(I) + '.',
mtError, [mbOK], 0);
Abort;
end;
end; {GetLayerName}
{===================================================}
Function TMapSetupObject.GetLayerDatabaseName(LayerName : String) : String;
var
I : Integer;
begin
Result := '';
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.LayerPathName;
end; {GetLayerDatabaseName}
{===================================================}
Function TMapSetupObject.GetLayerLocation(LayerName : String) : String;
var
I : Integer;
begin
Result := '';
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.LayerFileName;
end; {GetLayerLocation}
{===================================================}
Function TMapSetupObject.GetLayerColor(LayerName : String) : LongInt;
var
I : Integer;
begin
Result := moPaleYellow;
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.LayerColor;
end; {GetLayerColor}
{===================================================}
Function TMapSetupObject.GetLayerType(LayerName : String) : String;
var
I : Integer;
begin
Result := '';
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.LayerType;
end; {GetLayerType}
{===================================================}
Function TMapSetupObject.GetLayerFillType(LayerName : String) : LongInt;
var
I : Integer;
begin
Result := moTransparentFill;
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.FillType;
end; {GetLayerFillType}
{===================================================}
Function TMapSetupObject.GetLayerOrder(LayerName : String) : LongInt;
var
I : Integer;
begin
Result := 0;
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.LayerOrder;
end; {GetLayerOrder}
{===================================================}
Function TMapSetupObject.GetTextFieldName(LayerName : String) : String;
var
I : Integer;
begin
Result := '';
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.TextField;
end; {GetTextFieldName}
{===================================================}
Function TMapSetupObject.GetXOffsetFieldName(LayerName : String) : String;
var
I : Integer;
begin
Result := '';
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.XOffsetField;
end; {GetXOffsetFieldName}
{===================================================}
Function TMapSetupObject.GetYOffsetFieldName(LayerName : String) : String;
var
I : Integer;
begin
Result := '';
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.YOffsetField;
end; {GetYOffsetFieldName}
{===================================================}
Function TMapSetupObject.GetRotationFieldName(LayerName : String) : String;
var
I : Integer;
begin
Result := '';
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.RotationField;
end; {GetRotationFieldName}
{===================================================}
Function TMapSetupObject.UseLabelPlacer(LayerName : String) : Boolean;
var
I : Integer;
begin
Result := False;
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.UseLabelPlacer;
end; {UseLabelPlacer}
{===================================================}
Function TMapSetupObject.UseLabelRenderer(LayerName : String) : Boolean;
var
I : Integer;
begin
Result := False;
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) or
((LayerName = 'MAIN') and
LayerPointer(FLayerList[I])^.MainLayer))
then Result := LayerPointer(FLayerList[I])^.UseLabelRenderer;
end; {UseLabelRenderer}
{======================================================}
Function TMapSetupObject.IsMainLayer(LayerName : String) : Boolean;
var
I : Integer;
begin
Result := False;
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) and
LayerPointer(FLayerList[I])^.MainLayer)
then Result := True;
end; {IsMainLayer}
{======================================================}
Function TMapSetupObject.MapLayerIsVisible(LayerName : String) : Boolean;
var
I : Integer;
begin
Result := False;
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) and
(LayerPointer(FLayerList[I])^.Visible or
LayerPointer(FLayerList[I])^.MainLayer))
then Result := True;
end; {MapLayerIsVisible}
{======================================================}
Function TMapSetupObject.MapLayerIsTransparent(LayerName : String) : Boolean;
var
I : Integer;
begin
Result := False;
For I := 0 to (FLayerList.Count - 1) do
If ((LayerPointer(FLayerList[I])^.LayerName = LayerName) and
(LayerPointer(FLayerList[I])^.Transparent or
LayerPointer(FLayerList[I])^.MainLayer))
then Result := True;
end; {MapLayerIsTransparent}
{=======================================================}
Procedure TMapSetupObject.SortLayersByLayerOrder;
var
I, J : Integer;
TempPointer : Pointer;
begin
For I := 0 to (FLayerList.Count - 1) do
For J := (I + 1) to (FLayerList.Count - 1) do
If (LayerPointer(FLayerList[J])^.LayerOrder < LayerPointer(FLayerList[I])^.LayerOrder)
then
begin
TempPointer := FLayerList[I];
FLayerList[I] := FLayerList[J];
FLayerList[J] := TempPointer;
end;
end; {SortLayersByLayerOrder}
{=======================================================}
Procedure TMapSetupObject.SetLayerVisible(LayerName : String;
IsVisible : Boolean);
var
I : Integer;
begin
For I := 0 to (FLayerList.Count - 1) do
If (LayerPointer(FLayerList[I])^.LayerName = LayerName)
then LayerPointer(FLayerList[I])^.Visible := IsVisible;
end; {SetLayerVisible}
{===================================================}
Procedure TMapSetupObject.Clear;
begin
ClearTList(FLayerList, SizeOf(LayerRecord));
end;
{===================================================}
Destructor TMapSetupObject.Destroy;
begin
FreeTList(FLayerList, SizeOf(LayerRecord));
inherited Destroy;
end; {Destroy}
end.
|
unit IdGlobalProtocols;
interface
type
TIdFileName = String;
function FileSizeByName(const AFilename: TIdFileName): Int64;
implementation
uses Classes, SysUtils;
type
TIdReadFileExclusiveStream = class(TFileStream)
public
constructor Create(const AFile : String);
end;
constructor TIdReadFileExclusiveStream.Create(const AFile : String);
begin
inherited Create(AFile, fmOpenRead or fmShareDenyWrite);
end;
// OS-independant version
function FileSizeByName(const AFilename: TIdFileName): Int64;
//Leave in for HTTP Server
{$IFDEF DOTNET}
var
LFile : System.IO.FileInfo;
{$ELSE}
{$IFDEF USE_INLINE} inline; {$ENDIF}
{$IFDEF WINDOWS}
var
LHandle : THandle;
LRec : TWin32FindData;
{$IFDEF WIN32_OR_WIN64}
LOldErrorMode : Integer;
{$ENDIF}
{$ENDIF}
{$IFDEF UNIX}
var
{$IFDEF USE_VCL_POSIX}
LRec : _Stat;
{$IFDEF USE_MARSHALLED_PTRS}
M: TMarshaller;
{$ENDIF}
{$ELSE}
{$IFDEF KYLIXCOMPAT}
LRec : TStatBuf;
{$ELSE}
LRec : TStat;
LU : time_t;
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$IFNDEF NATIVEFILEAPI}
var
LStream: TIdReadFileExclusiveStream;
{$ENDIF}
{$ENDIF}
begin
{$IFDEF DOTNET}
Result := -1;
LFile := System.IO.FileInfo.Create(AFileName);
if LFile.Exists then begin
Result := LFile.Length;
end;
{$ENDIF}
{$IFDEF WINDOWS}
Result := -1;
//check to see if something like "a:\" is specified and fail in that case.
//FindFirstFile would probably succede even though a drive is not a proper
//file.
if not IsVolume(AFileName) then begin
{
IMPORTANT!!!
For servers in Windows, you probably want the API call to fail rather than
get a "Cancel Try Again Continue " dialog-box box if a drive is not
ready or there's some other critical I/O error.
}
{$IFDEF WIN32_OR_WIN64}
LOldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
{$ENDIF}
LHandle := Windows.FindFirstFile(PIdFileNameChar(AFileName), LRec);
if LHandle <> INVALID_HANDLE_VALUE then begin
Windows.FindClose(LHandle);
if (LRec.dwFileAttributes and Windows.FILE_ATTRIBUTE_DIRECTORY) = 0 then begin
Result := (Int64(LRec.nFileSizeHigh) shl 32) + LRec.nFileSizeLow;
end;
end;
{$IFDEF WIN32_OR_WIN64}
finally
SetErrorMode(LOldErrorMode);
end;
{$ENDIF}
end;
{$ENDIF}
{$IFDEF UNIX}
Result := -1;
{$IFDEF USE_VCL_POSIX}
//This is messy with IFDEF's but I want to be able to handle 63 bit file sizes.
if stat(
{$IFDEF USE_MARSHALLED_PTRS}
M.AsAnsi(AFileName).ToPointer
{$ELSE}
PAnsiChar(
{$IFDEF STRING_IS_ANSI}
AFileName
{$ELSE}
AnsiString(AFileName) // explicit convert to Ansi
{$ENDIF}
)
{$ENDIF}
, LRec) = 0 then
begin
Result := LRec.st_size;
end;
{$ELSE}
//Note that we can use stat here because we are only looking at the date.
if {$IFDEF KYLIXCOMPAT}stat{$ELSE}fpstat{$ENDIF}(
PAnsiChar(
{$IFDEF STRING_IS_ANSI}
AFileName
{$ELSE}
AnsiString(AFileName) // explicit convert to Ansi
{$ENDIF}
), LRec) = 0 then
begin
Result := LRec.st_Size;
end;
{$ENDIF}
{$ENDIF}
{$IFNDEF NATIVEFILEAPI}
Result := -1;
if FileExists(AFilename) then begin
LStream := TIdReadFileExclusiveStream.Create(AFilename);
try
Result := LStream.Size;
finally
LStream.Free;
end;
end;
{$ENDIF}
end;
end.
|
unit Financas.Controller.Interfaces;
interface
uses
System.Classes, FMX.Types;
type
iControllerListboxItensDefault = interface;
iControllerListboxDefault = interface;
iControllerListboxItensForm = interface
['{34754E44-2355-460E-811D-DFD01A7CAE45}']
function Show: TFMXObject;
end;
iControllerListboxMenu = interface
['{259EE633-DE95-464C-8A8F-218FBBEBA64A}']
procedure Exibir;
end;
iControllerListboxItensFactory = interface
['{C2594544-AD66-4F60-8BEE-FF43F58210B0}']
function Default: iControllerListboxItensDefault;
function Cliente: iControllerListboxItensForm;
function Produto: iControllerListboxItensForm;
end;
iControllerListboxFactory = interface
['{BD946BB0-3AA0-4F62-8323-3D9995592331}']
function Default(Container: TComponent): iControllerListboxDefault;
function Principal(Container: TComponent): iControllerListboxMenu;
function Produtos(Container: TComponent): iControllerListboxMenu;
function Clientes(Container: TComponent): iControllerListboxMenu;
end;
iControllerListboxItensDefault = interface
['{6D81B601-2E7B-4E92-BF5F-723EBAB09EB5}']
function Name(Value: String): iControllerListboxItensDefault;
function Text(Value: String): iControllerListboxItensDefault;
function StyleLookup(Value: String): iControllerListboxItensDefault;
function OnClick(Value: TNotifyEvent): iControllerListboxItensDefault;
function Item: TFMXObject;
end;
iControllerListboxDefault = interface
['{CB4EA7BB-65B7-4637-B48F-4790AB28F887}']
function Name(Value: String): iControllerListboxDefault;
function Align(Value: TAlignlayout): iControllerListboxDefault;
function ItemHeight(Value: Integer): iControllerListboxDefault;
function AddItem(Value: TFMXobject): iControllerListboxDefault;
function Lista: TFMXObject;
procedure Exibir;
end;
iControllerApplicationInfoFactory = interface
['{CAAF492F-F49F-4E81-96A6-5BAEE1974DC9}']
function CompanyName: String;
function FileDescription: String;
function FileVersion: String;
function InternalName: String;
function LegalCopyRight: String;
function LegalTradeMarks: String;
function OriginalFileName: String;
function ProductName: String;
function ProductVersion: String;
function Comments: String;
end;
iControllerIniFileFactory = interface
['{71ABF879-779C-4012-94EC-422E06133ACF}']
function Database: String;
function UserName: String;
function Password: String;
function DriverID: String;
function Server: String;
function Port: String;
procedure SetDatabase(const Value: String);
procedure SetUserName(const Value: String);
procedure SetPassword(const Value: String);
procedure SetDriverID(const Value: String);
procedure SetServer(const Value: String);
procedure SetPort(const Value: String);
end;
implementation
end.
|
unit ColorShades;
//{$MODE Delphi}
interface
uses
Classes, Graphics;
type
TNrOfLevels = 2..16;
TLevelIndex = 1..16;
TColorShades =
class(TObject)
private
FLeftBlue : Byte;
FRightBlue : Byte;
FDeltaBlue : Byte;
FLeftGreen : Byte;
FRightGreen: Byte;
FDeltaGreen: Byte;
FLeftRed : Byte;
FRightRed : Byte;
FDeltaRed : Byte;
FNrOfLevels: TNrOflevels;
procedure Update;
procedure SetLeftBlue (const Value: Byte);
procedure SetRightBlue (const Value: Byte);
procedure SetLeftGreen (const Value: Byte);
procedure SetRightGreen(const Value: Byte);
procedure SetLeftRed (const Value: Byte);
procedure SetRightRed (const Value: Byte);
procedure SetNrOfLevels(const Value: TNrOfLevels);
procedure SetStandard(AShades: Integer);
public
procedure SetProperties(
ALeftBlue , ARightBlue ,
ALeftGreen, ARightGreen,
ALeftRed , ARightRed: Byte;
ANrOfLevels: TNrOfLevels);
function Level(I: TLevelIndex): TColor;
property LeftBlue : Byte read FLeftBlue write SetLeftBlue ;
property RightBlue : Byte read FRightBlue write SetRightBlue ;
property DeltaBlue : Byte read FDeltaBlue;
property LeftGreen : Byte read FLeftGreen write SetLeftGreen ;
property RightGreen: Byte read FRightGreen write SetRightGreen;
property DeltaGreen: Byte read FDeltaGreen;
property LeftRed : Byte read FLeftRed write SetLeftRed ;
property RightRed : Byte read FRightRed write SetRightRed ;
property DeltaRed : Byte read FDeltaRed;
property NrOfLevels: TNrOfLevels read FNrOfLevels write SetNrOfLevels;
property Standard : Integer write SetStandard;
end;
const
sh4LightGray = 0;
sh4LightBlue = 1;
sh4LightGreen = 2;
sh4LightRed = 3;
sh4LightYellow = 4;
sh4LightViolet = 5;
sh4LightOrange = 6;
var
StandardShadesList: TStrings;
implementation
//{$R *.DFM}
type
TStandardShades =
record
LB, RB, LG, RG, LR, RR: Byte;
NL: TNrOfLevels;
end;
const
StandardShades: array[sh4LightGray..sh4LightOrange] of TStandardShades =
(
(LB: 200; RB: 240; LG: 200; RG:240; LR:200; RR:240; NL:4 ), {sh4LightGray}
(LB: 255; RB: 255; LG: 180; RG:240; LR:180; RR:240; NL:4 ), {sh4LightBlue}
(LB: 180; RB: 240; LG: 255; RG:255; LR:180; RR:240; NL:4 ), {shLightGreen}
(LB: 180; RB: 240; LG: 180; RG:240; LR:255; RR:255; NL:4 ), {sh4LightRed}
(LB: 150; RB: 240; LG: 255; RG:255; LR:255; RR:255; NL:4 ), {sh4LightYellow}
(LB: 255; RB: 255; LG: 180; RG:240; LR:240; RR:240; NL:4 ), {sh4LightViolet}
(LB: 155; RB: 240; LG: 200; RG:240; LR:240; RR:240; NL:4 ) {sh4LightOrange}
);
const
clGrayUnit = $00010101;
clBlueUnit = $00010000;
clGreenUnit = $00000100;
clRedUnit = $00000001;
{ TColorShades }
procedure TColorShades.SetLeftBlue(const Value: Byte);
begin
FLeftBlue := Value;
Update;
end;
procedure TColorShades.SetLeftGreen(const Value: Byte);
begin
FLeftGreen := Value;
Update;
end;
procedure TColorShades.SetLeftRed(const Value: Byte);
begin
FLeftRed := Value;
Update;
end;
procedure TColorShades.SetNrOfLevels(const Value: TNrOfLevels);
begin
FNrOfLevels := Value;
Update;
end;
procedure TColorShades.SetStandard(AShades: Integer);
var
VI: Integer;
begin
if (sh4LightGray <= AShades) and (AShades <= sh4LightOrange)
then VI := AShades
else VI := sh4LightGray;
with StandardShades[VI] do
SetProperties(LB, RB, LG, RG, LR, RR, NL);
end;
procedure TColorShades.SetRightBlue(const Value: Byte);
begin
FRightBlue := Value;
Update;
end;
procedure TColorShades.SetRightGreen(const Value: Byte);
begin
FRightGreen := Value;
Update;
end;
procedure TColorShades.SetRightRed(const Value: Byte);
begin
FRightRed := Value;
Update;
end;
procedure TColorShades.Update;
begin
FDeltaBlue := (FRightBlue - FLeftBlue ) div (FNrOfLevels - 1);
FDeltaGreen := (FRightGreen - FLeftGreen) div (FNrOfLevels - 1);
FDeltaRed := (FRightRed - FLeftRed ) div (FNrOfLevels - 1);
end;
procedure TColorShades.SetProperties(
ALeftBlue , ARightBlue ,
ALeftGreen, ARightGreen,
ALeftRed , ARightRed: Byte;
ANrOfLevels: TNrOfLevels);
begin
FLeftBlue := ALeftBlue;
FRightBlue := ARightBlue;
FLeftGreen := ALeftGreen;
FRightGreen := ARightGreen;
FLeftRed := ALeftRed;
FRightRed := ARightRed;
FNrOfLevels := ANrOfLevels;
Update;
end;
function TColorShades.Level(I: TLevelIndex): TColor;
begin
Result :=
(FLeftBlue + (I-1) * FDeltaBlue) * clBlueUnit +
(FLeftGreen + (I-1) * FDeltaGreen) * clGreenUnit +
(FLeftRed + (I-1) * FDeltaRed) * clRedUnit;
end;
initialization
StandardShadesList := TStringList.Create;
with StandardShadesList do
begin
Add('sh4LightGray ');
Add('sh4LightBlue ');
Add('sh4LightGreen ');
Add('sh4LightRed ');
Add('sh4LightYellow');
Add('sh4LightViolet');
Add('sh4LightOrange');
end;
end.
|
// **************************************************************************************************
//
// Unit Vcl.Styles.Utils.SystemMenu
// unit for the VCL Styles Utils
// https://github.com/RRUZ/vcl-styles-utils/
//
// The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the
// License at http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either express or implied. See the License for the specific language governing rights
// and limitations under the License.
//
// The Initial Developer of the Original Code is Rodrigo Ruz V.
// Portions created by Rodrigo Ruz V. are Copyright (C) 2014-2016 Rodrigo Ruz V.
// All Rights Reserved.
//
// **************************************************************************************************
unit Vcl.Styles.Utils.SystemMenu;
interface
uses
System.Rtti, System.Classes, System.Generics.Collections, WinApi.Windows,
WinApi.Messages, Vcl.Themes, Vcl.Forms;
type
TMethodInfo = class;
TProcCallback = reference to procedure(Info: TMethodInfo);
TMethodInfo = class
Value1: TValue;
Value2: TValue;
Method: TProcCallback;
end;
TVclStylesSystemMenu = class(TComponent)
strict private
FVCLStylesMenu: HMenu;
FOrgWndProc: TWndMethod;
FForm: TForm;
FMethodsDict: TObjectDictionary<NativeUInt, TMethodInfo>;
procedure CreateMenus;
procedure DeleteMenus;
procedure CreateMenuStyles;
procedure WndProc(var Message: TMessage);
private
FMenuCaption: string;
FShowNativeStyle: Boolean;
procedure SetMenuCaption(const Value: string);
procedure SetShowNativeStyle(const Value: Boolean);
public
property ShowNativeStyle: Boolean read FShowNativeStyle write SetShowNativeStyle;
property MenuCaption: string read FMenuCaption write SetMenuCaption;
constructor Create(AOwner: TForm); reintroduce;
destructor Destroy; override;
end;
implementation
uses
Vcl.Controls, System.SysUtils;
const
VCLStylesMenu = WM_USER + 666;
function InsertMenuHelper(hMenu: hMenu; uPosition: UINT; uIDNewItem: UINT_PTR; lpNewItem, IconName: LPCWSTR): BOOL;
var
LMenuItem: TMenuItemInfo;
begin
ZeroMemory(@LMenuItem, SizeOf(TMenuItemInfo));
LMenuItem.cbSize := SizeOf(TMenuItemInfo);
LMenuItem.fMask := MIIM_FTYPE or MIIM_ID or MIIM_BITMAP or MIIM_STRING;
LMenuItem.fType := MFT_STRING;
LMenuItem.wID := uIDNewItem;
LMenuItem.dwTypeData := lpNewItem;
Result := InsertMenuItem(hMenu, uPosition, True, LMenuItem);
end;
procedure AddMenuSeparatorHelper(hMenu: hMenu; var MenuIndex: Integer);
var
LMenuInfo: TMenuItemInfo;
Buffer: array[0..79] of char;
begin
ZeroMemory(@LMenuInfo, SizeOf(TMenuItemInfo));
LMenuInfo.cbSize := sizeof(LMenuInfo);
LMenuInfo.fMask := MIIM_TYPE;
LMenuInfo.dwTypeData := Buffer;
LMenuInfo.cch := SizeOf(Buffer);
if GetMenuItemInfo(hMenu, MenuIndex - 1, True, LMenuInfo) then
begin
if (LMenuInfo.fType and MFT_SEPARATOR) = MFT_SEPARATOR then
else
begin
InsertMenu(hMenu, MenuIndex, MF_BYPOSITION or MF_SEPARATOR, 0, nil);
inc(MenuIndex);
end;
end;
end;
{ TVclStylesSystemMenu }
constructor TVclStylesSystemMenu.Create(AOwner: TForm);
begin
inherited Create(AOwner);
FShowNativeStyle := True;
FMenuCaption := 'VCL Styles';
FForm := AOwner;
FMethodsDict := TObjectDictionary<NativeUInt, TMethodInfo>.Create([doOwnsValues]);
FOrgWndProc := FForm.WindowProc;
FForm.WindowProc := WndProc;
CreateMenus;
end;
destructor TVclStylesSystemMenu.Destroy;
begin
DeleteMenus;
FForm.WindowProc := FOrgWndProc;
FMethodsDict.Free;
inherited;
end;
procedure TVclStylesSystemMenu.SetMenuCaption(const Value: string);
begin
DeleteMenus;
FMenuCaption := Value;
CreateMenus;
end;
procedure TVclStylesSystemMenu.SetShowNativeStyle(const Value: Boolean);
begin
DeleteMenus;
FShowNativeStyle := Value;
CreateMenus;
end;
procedure TVclStylesSystemMenu.CreateMenus;
begin
CreateMenuStyles;
end;
procedure TVclStylesSystemMenu.DeleteMenus;
var
LSysMenu: hMenu;
begin
if IsMenu(FVCLStylesMenu) then
while GetMenuItemCount(FVCLStylesMenu) > 0 do
DeleteMenu(FVCLStylesMenu, 0, MF_BYPOSITION);
if FForm.HandleAllocated then
begin
LSysMenu := GetSystemMenu(FForm.Handle, False);
if IsMenu(LSysMenu) then
DeleteMenu(LSysMenu, VCLStylesMenu, MF_BYCOMMAND);
end;
FMethodsDict.Clear;
end;
procedure TVclStylesSystemMenu.CreateMenuStyles;
var
LSysMenu: hMenu;
LMenuItem: TMenuItemInfo;
uIDNewItem, LSubMenuIndex: Integer;
LMethodInfo: TMethodInfo;
s: string;
LStyleNames: TArray<string>;
begin
LSysMenu := GetSystemMenu(FForm.Handle, False);
LSubMenuIndex := GetMenuItemCount(LSysMenu);
AddMenuSeparatorHelper(LSysMenu, LSubMenuIndex);
FVCLStylesMenu := CreatePopupMenu();
uIDNewItem := VCLStylesMenu;
ZeroMemory(@LMenuItem, SizeOf(TMenuItemInfo));
LMenuItem.cbSize := SizeOf(TMenuItemInfo);
LMenuItem.fMask := MIIM_SUBMENU or MIIM_FTYPE or MIIM_ID or MIIM_BITMAP or MIIM_STRING;
LMenuItem.fType := MFT_STRING;
LMenuItem.wID := VCLStylesMenu;
LMenuItem.hSubMenu := FVCLStylesMenu;
LMenuItem.dwTypeData := PWideChar(FMenuCaption);
LMenuItem.cch := Length(FMenuCaption);
InsertMenuItem(LSysMenu, GetMenuItemCount(LSysMenu), True, LMenuItem);
inc(uIDNewItem);
LSubMenuIndex := 0;
LStyleNames := TStyleManager.StyleNames;
TArray.Sort<string>(LStyleNames);
for s in LStyleNames do
begin
if not FShowNativeStyle and SameText('Windows', s) then
Continue;
InsertMenuHelper(FVCLStylesMenu, LSubMenuIndex, uIDNewItem, PChar(s), nil);
if SameText(TStyleManager.ActiveStyle.Name, s) then
CheckMenuItem(FVCLStylesMenu, LSubMenuIndex, MF_BYPOSITION or MF_CHECKED);
if SameText('Windows', s) then
AddMenuSeparatorHelper(FVCLStylesMenu, LSubMenuIndex);
inc(LSubMenuIndex);
inc(uIDNewItem);
LMethodInfo := TMethodInfo.Create;
LMethodInfo.Value1 := s;
LMethodInfo.Method :=
procedure(Info: TMethodInfo)
begin
TStyleManager.SetStyle(Info.Value1.AsString);
end;
FMethodsDict.Add(uIDNewItem - 1, LMethodInfo);
end;
end;
procedure TVclStylesSystemMenu.WndProc(var Message: TMessage);
var
LVerb: NativeUInt;
begin
case Message.Msg of
CM_RECREATEWND:
begin
DeleteMenus;
FOrgWndProc(Message);
CreateMenus;
end;
WM_SYSCOMMAND:
begin
if FMethodsDict.ContainsKey(TWMSysCommand(Message).CmdType) then
begin
LVerb := TWMSysCommand(Message).CmdType;
FMethodsDict.Items[LVerb].Method(FMethodsDict.Items[LVerb]);
end
else
FOrgWndProc(Message);
end
else
FOrgWndProc(Message);
end;
end;
end.
|
unit uObjectComboList;
interface
uses SysUtils, Types, Contnrs, uObjectCombo;
type
TComboList = class(TObjectList)
protected
function GetItem(Index: Integer): TComboObject;
procedure SetItem(Index: Integer; FeaObj: TComboObject);
public
property Objects[Index: Integer]: TComboObject read GetItem write SetItem; default;
end;
implementation
{ TFeaList }
function TComboList.GetItem(Index: Integer): TComboObject;
begin
result := (Items[Index] as TComboObject);
end;
procedure TComboList.SetItem(Index: Integer; FeaObj: TComboObject);
begin
Items[Index] := FeaObj;
end;
end.
|
unit class_5;
interface
uses System;
implementation
type
TC1 = class
a, b, c: int32;
end;
TC2 = class
XX: Int32;
C1: TC1;
end;
TC3 = class
XX: Int32;
C2: TC2;
procedure Run;
end;
var c1: TC1;
c2: TC2;
c3: TC3;
G1, G2, G3: Int32;
procedure TC3.Run;
begin
if Assigned(C2) then
begin
if Assigned(C2.C1) then
begin
if C2.C1.a = 12 then
begin
C2.C1.c := 14;
C2.C1.b := 13;
end;
end;
end;
end;
procedure Test;
begin
c1 := TC1.Create();
c1.a := 12;
c2 := TC2.Create();
c2.c1 := c1;
c3 := TC3.Create();
c3.c2 := c2;
c3.run();
G1 := c1.a;
G2 := c1.b;
G3 := c1.c;
end;
initialization
Test();
finalization
Assert(G1 = 12);
Assert(G2 = 13);
Assert(G3 = 14);
end. |
unit CwAs.Xml.XmlSerializer.Attributes;
interface
type
TCustomXmlAttribute = class(TCustomAttribute)
end;
XmlIgnoreAttribute = class(TCustomXmlAttribute)
end;
XmlElementAttribute = class(TCustomXmlAttribute)
private
FElementName: string;
public
constructor create(const name: string);
property ElementName: string read FElementName write FElementName;
end;
XmlAttributeAttribute = class(TCustomXmlAttribute)
private
FAttributeName: string;
public
constructor create(const name: string);
property AttributeName: string read FAttributeName write FAttributeName;
end;
XmlRootAttribute = class(TCustomXmlAttribute)
private
FElementName: string;
public
constructor create(const name: string);
property ElementName: string read FElementName write FElementName;
end;
// For å eksluderer spesfikke properties på en klasse
XmlExcludeMemberNamesAttribute = class(TCustomXmlAttribute)
private
FNames: string;
public
constructor create(const aNames: string);
property Names: string read FNames write FNames;
end;
implementation
{ XmlElementAttribute }
constructor XmlElementAttribute.create(const name: string);
begin
FElementName := name;
end;
{ XmlAttributeAttribute }
constructor XmlAttributeAttribute.create(const name: string);
begin
FAttributeName := name;
end;
{ XmlRootAttribute }
constructor XmlRootAttribute.create(const name: string);
begin
FElementName := name;
end;
{ XmlExcludeMemberNamesAttribute }
constructor XmlExcludeMemberNamesAttribute.create(const aNames: string);
begin
FNames := aNames;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ Web server application components }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
// TUTF8ContentParser is a WebRequest content parser that parses UTF-8 requests.
// TUTF8ContentParser class automatically replace the default content parser when this unit (UTF8ContentParser)
// is used in a web application. You should only use UTF8ContentParser in web applications that generate UTF-8
// responses.
//
// To generated UTF-8 encoded responses, set Response.ContentType as follows before setting Response.Content.
// Response.ContentType := 'text/html; charset=UTF-8';
//
// Note that, if your application uses the ReqMulti unit to parse multipart content, ReqMulti must appear in the application
// uses list after UTF8ContentParser.
{$HPPEMIT LINKUNIT}
unit Web.UTF8ContentParser;
interface
uses Web.HTTPApp;
type
{ TUTF8ContentParser }
TUTF8ContentParser = class(TContentParser) // deprecated
end;
implementation
end.
|
unit EditImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB;
type
TEditX = class(TActiveXControl, IEditX)
private
{ Private declarations }
FDelphiControl: TEdit;
FEvents: IEditXEvents;
procedure ChangeEvent(Sender: TObject);
procedure ClickEvent(Sender: TObject);
procedure DblClickEvent(Sender: TObject);
procedure KeyPressEvent(Sender: TObject; var Key: Char);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_AutoSelect: WordBool; safecall;
function Get_AutoSize: WordBool; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_BorderStyle: TxBorderStyle; safecall;
function Get_CanUndo: WordBool; safecall;
function Get_CharCase: TxEditCharCase; safecall;
function Get_Color: OLE_COLOR; safecall;
function Get_Ctl3D: WordBool; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Font: IFontDisp; safecall;
function Get_HideSelection: WordBool; safecall;
function Get_ImeMode: TxImeMode; safecall;
function Get_ImeName: WideString; safecall;
function Get_MaxLength: Integer; safecall;
function Get_Modified: WordBool; safecall;
function Get_OEMConvert: WordBool; safecall;
function Get_ParentColor: WordBool; safecall;
function Get_ParentCtl3D: WordBool; safecall;
function Get_ParentFont: WordBool; safecall;
function Get_PasswordChar: Smallint; safecall;
function Get_ReadOnly: WordBool; safecall;
function Get_SelLength: Integer; safecall;
function Get_SelStart: Integer; safecall;
function Get_SelText: WideString; safecall;
function Get_Text: WideString; safecall;
function Get_Visible: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure _Set_Font(const Value: IFontDisp); safecall;
procedure AboutBox; safecall;
procedure Clear; safecall;
procedure ClearSelection; safecall;
procedure ClearUndo; safecall;
procedure CopyToClipboard; safecall;
procedure CutToClipboard; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure PasteFromClipboard; safecall;
procedure SelectAll; safecall;
procedure Set_AutoSelect(Value: WordBool); safecall;
procedure Set_AutoSize(Value: WordBool); safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_BorderStyle(Value: TxBorderStyle); safecall;
procedure Set_CharCase(Value: TxEditCharCase); safecall;
procedure Set_Color(Value: OLE_COLOR); safecall;
procedure Set_Ctl3D(Value: WordBool); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Font(const Value: IFontDisp); safecall;
procedure Set_HideSelection(Value: WordBool); safecall;
procedure Set_ImeMode(Value: TxImeMode); safecall;
procedure Set_ImeName(const Value: WideString); safecall;
procedure Set_MaxLength(Value: Integer); safecall;
procedure Set_Modified(Value: WordBool); safecall;
procedure Set_OEMConvert(Value: WordBool); safecall;
procedure Set_ParentColor(Value: WordBool); safecall;
procedure Set_ParentCtl3D(Value: WordBool); safecall;
procedure Set_ParentFont(Value: WordBool); safecall;
procedure Set_PasswordChar(Value: Smallint); safecall;
procedure Set_ReadOnly(Value: WordBool); safecall;
procedure Set_SelLength(Value: Integer); safecall;
procedure Set_SelStart(Value: Integer); safecall;
procedure Set_SelText(const Value: WideString); safecall;
procedure Set_Text(const Value: WideString); safecall;
procedure Set_Visible(Value: WordBool); safecall;
procedure Undo; safecall;
end;
implementation
uses ComObj, About11;
{ TEditX }
procedure TEditX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_EditXPage); }
end;
procedure TEditX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IEditXEvents;
end;
procedure TEditX.InitializeControl;
begin
FDelphiControl := Control as TEdit;
FDelphiControl.OnChange := ChangeEvent;
FDelphiControl.OnClick := ClickEvent;
FDelphiControl.OnDblClick := DblClickEvent;
FDelphiControl.OnKeyPress := KeyPressEvent;
end;
function TEditX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TEditX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TEditX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TEditX.Get_AutoSelect: WordBool;
begin
Result := FDelphiControl.AutoSelect;
end;
function TEditX.Get_AutoSize: WordBool;
begin
Result := FDelphiControl.AutoSize;
end;
function TEditX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TEditX.Get_BorderStyle: TxBorderStyle;
begin
Result := Ord(FDelphiControl.BorderStyle);
end;
function TEditX.Get_CanUndo: WordBool;
begin
Result := FDelphiControl.CanUndo;
end;
function TEditX.Get_CharCase: TxEditCharCase;
begin
Result := Ord(FDelphiControl.CharCase);
end;
function TEditX.Get_Color: OLE_COLOR;
begin
Result := OLE_COLOR(FDelphiControl.Color);
end;
function TEditX.Get_Ctl3D: WordBool;
begin
Result := FDelphiControl.Ctl3D;
end;
function TEditX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TEditX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TEditX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TEditX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TEditX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TEditX.Get_Font: IFontDisp;
begin
GetOleFont(FDelphiControl.Font, Result);
end;
function TEditX.Get_HideSelection: WordBool;
begin
Result := FDelphiControl.HideSelection;
end;
function TEditX.Get_ImeMode: TxImeMode;
begin
Result := Ord(FDelphiControl.ImeMode);
end;
function TEditX.Get_ImeName: WideString;
begin
Result := WideString(FDelphiControl.ImeName);
end;
function TEditX.Get_MaxLength: Integer;
begin
Result := FDelphiControl.MaxLength;
end;
function TEditX.Get_Modified: WordBool;
begin
Result := FDelphiControl.Modified;
end;
function TEditX.Get_OEMConvert: WordBool;
begin
Result := FDelphiControl.OEMConvert;
end;
function TEditX.Get_ParentColor: WordBool;
begin
Result := FDelphiControl.ParentColor;
end;
function TEditX.Get_ParentCtl3D: WordBool;
begin
Result := FDelphiControl.ParentCtl3D;
end;
function TEditX.Get_ParentFont: WordBool;
begin
Result := FDelphiControl.ParentFont;
end;
function TEditX.Get_PasswordChar: Smallint;
begin
Result := Smallint(FDelphiControl.PasswordChar);
end;
function TEditX.Get_ReadOnly: WordBool;
begin
Result := FDelphiControl.ReadOnly;
end;
function TEditX.Get_SelLength: Integer;
begin
Result := FDelphiControl.SelLength;
end;
function TEditX.Get_SelStart: Integer;
begin
Result := FDelphiControl.SelStart;
end;
function TEditX.Get_SelText: WideString;
begin
Result := WideString(FDelphiControl.SelText);
end;
function TEditX.Get_Text: WideString;
begin
Result := WideString(FDelphiControl.Text);
end;
function TEditX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TEditX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TEditX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TEditX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TEditX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TEditX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TEditX._Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TEditX.AboutBox;
begin
ShowEditXAbout;
end;
procedure TEditX.Clear;
begin
FDelphiControl.Clear;
end;
procedure TEditX.ClearSelection;
begin
FDelphiControl.ClearSelection;
end;
procedure TEditX.ClearUndo;
begin
FDelphiControl.ClearUndo;
end;
procedure TEditX.CopyToClipboard;
begin
FDelphiControl.CopyToClipboard;
end;
procedure TEditX.CutToClipboard;
begin
FDelphiControl.CutToClipboard;
end;
procedure TEditX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TEditX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TEditX.PasteFromClipboard;
begin
FDelphiControl.PasteFromClipboard;
end;
procedure TEditX.SelectAll;
begin
FDelphiControl.SelectAll;
end;
procedure TEditX.Set_AutoSelect(Value: WordBool);
begin
FDelphiControl.AutoSelect := Value;
end;
procedure TEditX.Set_AutoSize(Value: WordBool);
begin
FDelphiControl.AutoSize := Value;
end;
procedure TEditX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TEditX.Set_BorderStyle(Value: TxBorderStyle);
begin
FDelphiControl.BorderStyle := TBorderStyle(Value);
end;
procedure TEditX.Set_CharCase(Value: TxEditCharCase);
begin
FDelphiControl.CharCase := TEditCharCase(Value);
end;
procedure TEditX.Set_Color(Value: OLE_COLOR);
begin
FDelphiControl.Color := TColor(Value);
end;
procedure TEditX.Set_Ctl3D(Value: WordBool);
begin
FDelphiControl.Ctl3D := Value;
end;
procedure TEditX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TEditX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TEditX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TEditX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TEditX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TEditX.Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TEditX.Set_HideSelection(Value: WordBool);
begin
FDelphiControl.HideSelection := Value;
end;
procedure TEditX.Set_ImeMode(Value: TxImeMode);
begin
FDelphiControl.ImeMode := TImeMode(Value);
end;
procedure TEditX.Set_ImeName(const Value: WideString);
begin
FDelphiControl.ImeName := TImeName(Value);
end;
procedure TEditX.Set_MaxLength(Value: Integer);
begin
FDelphiControl.MaxLength := Value;
end;
procedure TEditX.Set_Modified(Value: WordBool);
begin
FDelphiControl.Modified := Value;
end;
procedure TEditX.Set_OEMConvert(Value: WordBool);
begin
FDelphiControl.OEMConvert := Value;
end;
procedure TEditX.Set_ParentColor(Value: WordBool);
begin
FDelphiControl.ParentColor := Value;
end;
procedure TEditX.Set_ParentCtl3D(Value: WordBool);
begin
FDelphiControl.ParentCtl3D := Value;
end;
procedure TEditX.Set_ParentFont(Value: WordBool);
begin
FDelphiControl.ParentFont := Value;
end;
procedure TEditX.Set_PasswordChar(Value: Smallint);
begin
FDelphiControl.PasswordChar := Char(Value);
end;
procedure TEditX.Set_ReadOnly(Value: WordBool);
begin
FDelphiControl.ReadOnly := Value;
end;
procedure TEditX.Set_SelLength(Value: Integer);
begin
FDelphiControl.SelLength := Value;
end;
procedure TEditX.Set_SelStart(Value: Integer);
begin
FDelphiControl.SelStart := Value;
end;
procedure TEditX.Set_SelText(const Value: WideString);
begin
FDelphiControl.SelText := String(Value);
end;
procedure TEditX.Set_Text(const Value: WideString);
begin
FDelphiControl.Text := TCaption(Value);
end;
procedure TEditX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TEditX.Undo;
begin
FDelphiControl.Undo;
end;
procedure TEditX.ChangeEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnChange;
end;
procedure TEditX.ClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnClick;
end;
procedure TEditX.DblClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnDblClick;
end;
procedure TEditX.KeyPressEvent(Sender: TObject; var Key: Char);
var
TempKey: Smallint;
begin
TempKey := Smallint(Key);
if FEvents <> nil then FEvents.OnKeyPress(TempKey);
Key := Char(TempKey);
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TEditX,
TEdit,
Class_EditX,
11,
'{695CDB2A-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
unit UnitExcel;
interface
Uses
Windows;
Type
TExcel = Class
Const
Medium = -4138;
Left = -4131;
Portrait = 1;
Solid = 1;
General = 1;
LandScape = 2;
End;
Const
gHorizontal = True;
gVertical = False;
msoTrue = -1;
msoFalse = 0;
msoScaleFromTopLeft = 0;
msoLineSolid = 1;
msoLineSingle = 1;
msoScaleFromBottomRight = 2;
msoShapeRoundedRectangle = 5;
msoShapeFlowchartProcess = 61;
xlTop = -4160;
xlToLeft = -4159;
xlRight = -4152;
xlNormal = -4143;
xlUnderlineStyleNone = -4142;
xlMedium = -4138;
xlLeft = -4131;
xlJustify = -4130;
xlDown = -4121;
xlDouble = -4119;
xlCenter = -4108;
xlAutomatic = -4105;
xlContinuous = 1;
xlGeneral = 1;
xlSolid = 1;
xlCellValue = 1;
xlHairline = 1;
xlPaperLetter = 1;
xlUnderlineStyleSingle = 2;
xlThin = 2;
xlLandscape = 2;
xlThick = 4;
xlEdgeLeft = 7;
xlEdgeTop = 8;
xlEdgeBottom = 9;
xlEdgeRight = 10;
xlInsideVertical = 11;
xlInsideHorizontal = 12;
xlValidateList = 3;
xlValidAlertStop = 1;
xlBetween = 1;
xlDash = -4115;
xlNone = -4142;
Function ColumnaNombre(Numero: Integer): String;
Function NombreArchivoTemporal: String;
implementation
Function ColumnaNombre(Numero: Integer): String;
Var
Valor, NumLetras: Integer;
Cad: String;
Begin
NumLetras := 26; // O1
Cad := '';
Valor := Numero Mod NumLetras;
if Valor = 0 then Valor := 26;
if Numero - Valor > 0 then Cad := Char(64 + Trunc((Numero - Valor) / NumLetras));
Cad := Cad + Char(64 + Valor);
Result := Cad;
End;
function NombreArchivoTemporal: string;
var
Buffer: array[0..MAX_PATH] of Char;
aFile: string;
begin
GetTempPath(SizeOf(Buffer) - 1, Buffer);
GetTempFileName(Buffer, '~', 0, Buffer);
Result := Buffer;
end;
end.
|
unit ItensDoMenu;
interface
uses
System.SysUtils, System.Contnrs;
type
TItensMenu = class
private
Nome: string;
Descricao: string;
Preco: currency;
Vegano: boolean;
public
constructor Create(Nome: string; Descricao: string; Preco: currency; Vegano: boolean);
function GetNome: string;
function GetDescricao: string;
function GetPreco: currency;
function IsVegan: boolean;
end;
implementation
{ TItensMenu }
constructor TItensMenu.Create(Nome, Descricao: string; Preco: currency;
Vegano: boolean);
begin
Self.Nome := Nome;
Self.Descricao := Descricao;
Self.Preco := Preco;
Self.Vegano := Vegano;
end;
function TItensMenu.GetDescricao: string;
begin
Result := Descricao;
end;
function TItensMenu.GetNome: string;
begin
Result := Nome;
end;
function TItensMenu.GetPreco: currency;
begin
Result := Preco;
end;
function TItensMenu.IsVegan: boolean;
begin
Result := Vegano;;
end;
end.
|
{$mode objfpc}{$H+}{$J-}
uses SysUtils, Generics.Collections;
type
TApple = class
Name: string;
end;
TAppleDictionary = specialize TDictionary<string, TApple>;
var
Apples: TAppleDictionary;
A, FoundA: TApple;
ApplePair: TAppleDictionary.TDictionaryPair;
AppleKey: string;
begin
Apples := TAppleDictionary.Create;
try
A := TApple.Create;
A.Name := 'моята ябълка';
Apples.AddOrSetValue('ключ за ябълка 1', A);
if Apples.TryGetValue('ключ за ябълка 1', FoundA) then
Writeln('Намерена ябълка с ключ "ключ за ябълка 1" с име: ' +
FoundA.Name);
for AppleKey in Apples.Keys do
Writeln('Намерен ключ за ябълка: ' + AppleKey);
for A in Apples.Values do
Writeln('Намерена ябълка с име: ' + A.Name);
for ApplePair in Apples do
Writeln('Намерен ключ за ябълка->име на ябълка: ' +
ApplePair.Key + '->' + ApplePair.Value.Name);
{ Долният ред също работи, но може да се използва само да
зададе стойност на *съществуващ* ключ в речника.
Вместо това обикновено се използва AddOrSetValue
за да се зададе или добави нов ключ ако е необходимо. }
// Apples['ключ за ябълка 1'] := ... ;
Apples.Remove('ключ за ябълка 1');
{ Забележете, че TDictionary не притежава елементите си
и трябва да ги освобожавате ръчно.
Може да използвате TObjectDictionary за да имате автоматичен
режим за притежание. }
A.Free;
finally FreeAndNil(Apples) end;
end.
|
unit xConfig;
interface
uses System.SysUtils, IniFiles, xConsts;
var
/// <summary>
/// 数据库服务器IP地址
/// </summary>
sPubDBServerIP : string;
/// <summary>
/// 数据库服务器端口
/// </summary>
sPubDBServerPort : Integer;
implementation
initialization
if sPubIniFileName <> '' then
begin
with TIniFile.Create(sPubIniFileName) do
begin
sPubDBServerIP := ReadString('Option', 'DBServerIP', '');
sPubDBServerPort := ReadInteger('Option', 'DBServerPort', 15000);
free;
end;
end;
finalization
if sPubSysIniFileName <> '' then
begin
with TIniFile.Create(sPubSysIniFileName) do
begin
WriteString('Option', 'DBServerIP', sPubDBServerIP);
WriteInteger('Option', 'DBServerPort', sPubDBServerPort);
free;
end;
end;
end.
|
unit sNIF.worker.explorador;
{ *******************************************************
sNIF
Utilidad para buscar ficheros ofimáticos con
cadenas de caracteres coincidentes con NIF/NIE.
*******************************************************
2012-2018 Ángel Fernández Pineda. Madrid. Spain.
This work is licensed under the Creative Commons
Attribution-ShareAlike 3.0 Unported License. To
view a copy of this license,
visit http://creativecommons.org/licenses/by-sa/3.0/
or send a letter to Creative Commons,
444 Castro Street, Suite 900,
Mountain View, California, 94041, USA.
******************************************************* }
interface
uses
Classes,
CSVUtils,
sNIF.data,
sNIF.params,
sNIF.worker,
sNIF.control;
type
TWorkerExplorador = class(TsNIFWorker)
{
PROPOSITO:
Toma un fichero de la cola de trabajo y busca cadenas coincidentes de
NIF/NIE. Luego escribe el resultado de la exploración.
NOTA:
No se procesan los últimos 17 bytes de un fichero porque no cabe un
NIF en formato UTF-16, aunque podrían contener un NIF en formato
UTF-8.
}
private
Buffer: PByte;
csvFields: TCSVFields;
protected
procedure Execute; override;
procedure procesarCandidato(const candidato: TsNIFdata);
public
constructor Create(const AControl: TsNIFControl;
const Parametros: TsNIFParametros);
destructor Destroy; override;
end;
implementation
uses
IOUtils,
IOUtilsFix,
System.StrUtils,
System.SysUtils,
System.DateUtils,
windows,
NIFUtils,
SyncObjs,
ThreadUtils.SafeDataTypes;
const
BUFFER_SIZE = 64 * 1024; // tamaño testado para mejor rendimiento
BYTES_PER_NIF_UTF16 = 18;
BYTES_PER_NIF_UTF8 = 9;
// --------------------------------------------------------------------------
// Hilo de trabajo
// --------------------------------------------------------------------------
procedure TWorkerExplorador.Execute;
var
candidato: TsNIFdata;
handle: THANDLE;
accessAttr: FILETIME;
preservarAttr: boolean;
fichero: string;
begin
while (not Terminated) do
try
// Sacar un fichero de la cola de trabajo
candidato := FControl.ColaCandidatos.Dequeue;
fichero := TPath.Combine(candidato.Ruta, candidato.fichero);
fichero := TPath.SetExtendedPrefix(fichero);
// Leer tiempo de ultimo acceso para intentar preservarlo
handle := CreateFile(PWideChar(fichero), GENERIC_READ,
(FILE_SHARE_READ or FILE_SHARE_WRITE), nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
if (handle <> INVALID_HANDLE_VALUE) then
preservarAttr := GetFileTime(handle, nil, @accessAttr, nil)
else
preservarAttr := false;
CloseHandle(handle);
// procesar fichero
// (altera el atributo de fecha de ultimo acceso)
procesarCandidato(candidato);
// Restaurar el atributo de fecha de ultimo acceso, si se puede
if (preservarAttr) then
begin
handle := CreateFile(PWideChar(fichero), FILE_WRITE_ATTRIBUTES,
(FILE_SHARE_READ or FILE_SHARE_WRITE), nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
if (handle <> INVALID_HANDLE_VALUE) then
SetFileTime(handle, nil, @accessAttr, nil);
CloseHandle(handle);
end;
// Escribir resultados
csvFields.Field[0] := candidato.Ruta;
csvFields.Field[1] := candidato.fichero;
if (candidato.error) and (FParametros.IncluirErrores) then
begin
csvFields.Field[2] := 'error';
csvFields.Field[3] := candidato.mensajeError;
end
else
begin
csvFields.Field[2] := candidato.CuentaNIF;
csvFields.Field[3] := candidato.FechaUltimoAcceso;
end;
if (not candidato.error) or (FParametros.IncluirErrores) then
FControl.CSVWriter.WriteLine(csvFields);
candidato.Free;
except
// cola cancelada
on E: ESyncObjectException do
Terminate;
end;
end;
procedure TWorkerExplorador.procesarCandidato(const candidato: TsNIFdata);
var
// Posicion actual en el buffer donde se están buscando cadenas NIF/NIE
pbuffer: PByte;
// Ultima posicion del buffer donde es posible buscar sin causar
// desbordamiento
maxbuffer: PByte;
// Stream asociado al fichero de entrada
input: TFileStream;
// Total de bytes leidos desde el fichero y explorados
bytesLeidos: int64;
// Número de bytes que se han cargado en el buffer a partir del fichero.
// Siempre igual o inferior a BUFFER_SIZE.
bytesEnBuffer: integer;
// Máximo de bytes donde debe aparecer alguna cadena NIF/NIE antes de
// abandonar la exploración. Depende de "FParametros".
maxBytesSinNIF: int64;
// Nombre completo del fichero a explorar
fichero: string;
begin
try
// Inicializar
bytesLeidos := 0;
ZeroMemory(Buffer + BUFFER_SIZE - BYTES_PER_NIF_UTF16, BYTES_PER_NIF_UTF16);
fichero := TPath.Combine(candidato.Ruta, candidato.fichero);
// Abrir fichero con permisos de lectura
input := TFileStream.Create(TPath.SetExtendedPrefix(fichero), fmOpenRead,
fmShareDenyWrite);
if (FParametros.MaxSinNIF < 100) and (FParametros.MaxSinNIF > 0) then
maxBytesSinNIF := Trunc(input.Size * (FParametros.MaxSinNIF / 100))
else
maxBytesSinNIF := input.Size;
try
repeat
// Los ultimos bytes de la anterior iteración son los primeros bytes
// ahora. No se vuelven a leer.
CopyMemory(Buffer, Buffer + BUFFER_SIZE - BYTES_PER_NIF_UTF16,
BYTES_PER_NIF_UTF16);
// Cargar el resto del buffer desde el fichero
bytesEnBuffer := input.Read((Buffer + BYTES_PER_NIF_UTF16)^,
BUFFER_SIZE - BYTES_PER_NIF_UTF16) + BYTES_PER_NIF_UTF16;
// Buscar cadenas coincidentes con NIF/NIE
pbuffer := Buffer;
maxbuffer := Buffer + bytesEnBuffer - BYTES_PER_NIF_UTF16;
while (not Terminated) and (candidato.CuentaNIF < FParametros.MaxNIF)
and (pbuffer < maxbuffer) do
begin
if (isNIF_UTF16(pbuffer)) then
begin
inc(candidato.CuentaNIF);
inc(pbuffer, BYTES_PER_NIF_UTF16);
end
else if (isNIF_UTF8(pbuffer)) then
begin
inc(candidato.CuentaNIF);
inc(pbuffer, BYTES_PER_NIF_UTF8);
end
else
inc(pbuffer);
end;
bytesLeidos := bytesLeidos + bytesEnBuffer - BYTES_PER_NIF_UTF16;
until
// test: exploracion cancelada o terminada
(Terminated) or
// test: fin de fichero
(bytesEnBuffer < BUFFER_SIZE) or
// test: se alcanzó el limite de búsqueda
(candidato.CuentaNIF >= FParametros.MaxNIF) or
// test: no se han encontrado cadenas NIF/NIE en
// la primera parte del fichero
((candidato.CuentaNIF = 0) and (bytesLeidos >= maxBytesSinNIF));
finally
input.Free;
end;
except
// Error al intentar abrir o leer el fichero
on E: Exception do
begin
FControl.incCuentaErroresFichero;
candidato.error := true;
candidato.mensajeError := E.Message;
end;
end;
FControl.incCuentaFicherosExplorados;
end;
// --------------------------------------------------------------------------
// Otros
// --------------------------------------------------------------------------
constructor TWorkerExplorador.Create(const AControl: TsNIFControl;
const Parametros: TsNIFParametros);
begin
inherited Create(AControl, Parametros);
GetMem(Buffer, BUFFER_SIZE);
csvFields := TCSVFields.Create;
csvFields.FieldCount := 4;
end;
destructor TWorkerExplorador.Destroy;
begin
FreeMem(Buffer);
csvFields.Free;
inherited;
end;
end.
|
Unit ListModel;
Interface
Uses
Menus, ComCtrls, Generics.Collections;
Type
TListModelColumn = Class
Private
FCaption : WideString;
FWidth : Cardinal;
FAUtoSize : Boolean;
FTag : NativeUInt;
FColumn : TListColumn;
FVisible : Boolean;
Public
Constructor Create(ACaption:WideString; ATag:NativeUInt; AAutoSize:Boolean = False; AWidth:Cardinal = 50); Reintroduce;
Property Caption : WideString Read FCaption;
Property Width : Cardinal Read FWidth;
Property AutoSize : Boolean Read FAutoSize;
Property Tag : NativeUInt Read FTag;
Property Visible : Boolean Read FVisible;
end;
TListModel<T> = Class
Private
FDisplayer : TListView;
FColumns : TList<TListModelColumn>;
Protected
Procedure OnDataCallback(Sender:TObject; Item:TListItem);
Function GetColumn(AItem:T; ATag:NativeUInt):WideString; Virtual; Abstract;
Function GetImageIndex(AItem:T):Integer; Virtual;
Procedure RefreshColumns;
Procedure FreeItem(AItem:T); Virtual; Abstract;
Function _Item(AIndex:Integer):T; Virtual; Abstract;
Function _Column(AIndex:Integer):TListModelColumn;
Procedure OnColumnNemuItemClick(Sender:TObject);
Function GetSelected:T;
Public
Constructor Create(ADisplayer:TListView); Reintroduce;
Destructor Destroy; Override;
Function RowCount : Cardinal; Virtual; Abstract;
Function ColumnCount : Cardinal;
Function Item(ARow:Cardinal; AColumn:cardinal):WideString;
Function Update:Cardinal; Virtual; Abstract;
Procedure SetDisplayer(AObject:TListView);
Procedure ColumnUpdateBegin;
Procedure ColumnClear;
Function ColumnAdd(AColumn:TListModelColumn):TListModel<T>; Overload;
Function ColumnAdd(ACaption:WideString; ATag:NativeUInt; AAutoSize:Boolean = False; AWidth:Cardinal = 50):TListModel<T>; Overload;
Procedure ColumnSetVisible(AIndex:Integer; AVisible:Boolean);
Procedure ColumnUpdateEnd;
Procedure CreateColumnsMenu(AParent:TMenuItem);
Property Displayer : TListView Read FDisplayer;
Property Items [Index:Integer] : T Read _Item;
Property Columns [Index:Integer] : TListModelColumn Read _Column;
Property Selected:T Read GetSelected;
end;
Implementation
Uses
SysUtils;
Constructor TListModel<T>.Create(ADisplayer:TListView);
begin
Inherited Create;
FColumns := TList<TListModelColumn>.Create;
If Assigned(ADisplayer) Then
SetDisplayer(ADisplayer)
Else Update;
end;
Destructor TListModel<T>.Destroy;
begin
If Assigned(FDisplayer) Then
begin
FDisplayer.OnData := Nil;
FDisplayer := Nil;
end;
FColumns.Free;
Inherited Destroy;
end;
Function TListModel<T>.GetImageIndex(AItem:T):Integer;
begin
Result := -1;
end;
Function TListModel<T>._Column(AIndex:Integer):TListModelColumn;
begin
Result := FColumns[AIndex];
end;
Procedure TListModel<T>.OnDataCallback(Sender:TObject; Item:TListItem);
Var
c : TListModelColumn;
begin
With Item Do
begin
ImageIndex := GetImageIndex(_Item(Index));
For c In FColumns Do
begin
If FColumns[0] = c Then
Caption := Self.Item(Index, c.Tag)
Else If c.Visible Then
SubItems.Add(Self.Item(Index, c.Tag));
end;
end;
end;
Procedure TListModel<T>.SetDisplayer(AObject:TListView);
begin
FDisplayer := AObject;
FDisplayer.OwnerData := True;
FDisplayer.OnData := OnDataCallback;
RefreshColumns;
Update;
end;
Function TListModel<T>.ColumnCount:Cardinal;
begin
Result := FColumns.Count;
end;
Function TListModel<T>.Item(ARow:Cardinal; AColumn:cardinal):WideString;
Var
rd : T;
begin
Result := '';
rd := _Item(ARow);
Result := GetColumn(rd, FColumns[AColumn].Tag);
end;
Procedure TListModel<T>.ColumnUpdateBegin;
begin
If Assigned(FDisplayer) Then
FDisplayer.Columns.BeginUpdate;
end;
Procedure TListModel<T>.ColumnClear;
Var
c : TListModelColumn;
begin
For c In FColumns Do
c.Free;
FColumns.Clear;
end;
Function TListModel<T>.ColumnAdd(AColumn:TListModelColumn):TListModel<T>;
begin
FColumns.Add(AColumn);
Result := Self;
end;
Function TListModel<T>.ColumnAdd(ACaption:WideString; ATag:NativeUInt; AAutoSize:Boolean = False; AWidth:Cardinal = 50):TListModel<T>;
begin
FColumns.Add(TListModelColumn.Create(ACaption, ATag, AAutoSize,AWidth));
Result := Self;
end;
Procedure TListModel<T>.ColumnUpdateEnd;
begin
If Assigned(FDisplayer) Then
begin
RefreshColumns;
FDisplayer.Columns.EndUpdate;
end;
end;
Procedure TListModel<T>.ColumnSetVisible(AIndex:Integer; AVisible:Boolean);
begin
FColumns[AIndex].FVisible := AVisible;
end;
Procedure TListModel<T>.RefreshColumns;
Var
c : TListColumn;
I : Integer;
m : TListModelColumn;
begin
FDisplayer.Columns.Clear;
For I := 0 To FColumns.Count - 1 Do
begin
m := FColumns[I];
If m.Visible Then
begin
With FDisplayer.Columns.Add Do
begin
Caption := m.Caption;
AutoSize := m.AutoSize;
Tag := m.Tag;
Width := m.Width;
end;
end;
end;
end;
Procedure TListModel<T>.OnColumnNemuItemClick(Sender:TObject);
Var
M : TMenuItem;
begin
M := (Sender As TMenuItem);
M.Checked := Not M.Checked;
ColumnUpdateBegin;
ColumnSetVisible(M.MenuIndex, M.Checked);
ColumnUpdateEnd;
end;
Procedure TListModel<T>.CreateColumnsMenu(AParent:TMenuItem);
Var
I : Integer;
M : TMenuItem;
c : TListModelColumn;
begin
For c In FColumns Do
begin
M := TMenuItem.Create(AParent);
M.Caption := c.Caption;
M.Checked := c.Visible;
M.OnClick := OnColumnNemuItemClick;
AParent.Add(M);
end;
end;
Function TListModel<T>.GetSelected:T;
Var
L : TListItem;
begin
Result := T(Nil);
If Assigned(Displayer) Then
begin
L := Displayer.Selected;
If Assigned(L) Then
Result := _Item(L.Index);
end;
end;
(*** TListModelColumn ***)
Constructor TListModelColumn.Create(ACaption:WideString; ATag:NativeUInt; AAutoSize:Boolean = False; AWidth:Cardinal = 50);
begin
Inherited Create;
FCaption := ACaption;
FWidth := AWidth;
FTag := ATag;
FAutoSize := AAutoSize;
FColumn := Nil;
FVisible := True;
end;
End.
|
unit fROR_PCall;
{
================================================================================
*
* Package: ROR - Clinical Case Registries
* Date Created: $Revision: 1 $ $Modtime: 8/05/08 5:15p $
* Site: Hines OIFO
* Developers: dddddomain.user@domain.ext
*
* Description: RPC call and RPC Error Window
*
* Notes:
*
================================================================================
* $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/ROR/fROR_PCall.pas $
*
* $History: fROR_PCall.pas $
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 8/12/09 Time: 8:29a
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/ROR
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 3/09/09 Time: 3:38p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/ROR
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/13/09 Time: 1:26p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/ROR
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/14/07 Time: 10:29a
* Created in $/Vitals GUI 2007/Vitals-5-0-18/ROR
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:43p
* Created in $/Vitals/VITALS-5-0-18/ROR
* GUI v. 5.0.18 updates the default vital type IENs with the local
* values.
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:32p
* Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/ROR
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/24/05 Time: 3:32p
* Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, No CCOW) - Delphi 6/ROR
*
* ***************** Version 3 *****************
* User: Zzzzzzandria Date: 11/12/04 Time: 5:41p
* Updated in $/CP Modernization/ROR
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 10/19/04 Time: 5:48p
* Updated in $/CP Modernization/ROR
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 9/02/04 Time: 1:17p
* Created in $/CP Modernization/ROR
*
* ***************** Version 7 *****************
* User: Zzzzzzgavris Date: 8/06/04 Time: 4:09p
* Updated in $/CCR v1.0/Current
*
* ***************** Version 6 *****************
* User: Zzzzzzgavris Date: 8/02/04 Time: 12:59p
* Updated in $/CCR v1.0/Current
*
* ***************** Version 5 *****************
* User: Zzzzzzgavris Date: 3/26/04 Time: 3:48p
* Updated in $/ICR v3.0/Current
*
================================================================================
}
interface
uses
Windows, Messages, SysUtils, Classes
, Graphics
, Controls
, Forms
, Dialogs
, StdCtrls
// , uROR_Utilities - replaced by u_Common
, TRPCB
, CCOWRPCBroker
, VERGENCECONTEXTORLib_TLB // not sure we need it here...
;
type
TRPCMode = set of (
rpcSilent, // Do not show any error messages
// (only return the error codes)
rpcNoResChk // Do not check the Results array for the errors
// returned by the remote procedure. This flag must be
// used for the remote procedures that do not conform
// to the error reporting format supported by the
// CheckRPCError function.
);
TRPCErrorForm = class(TForm)
Msg: TMemo;
btnOk: TButton;
procedure btnOkClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function CallRemoteProc( Broker: TRPCBroker; RemoteProcedure: String;
Parameters: array of String; MultList: TStringList = nil;
RPCMode: TRPCMode = []; RetList: TStrings = nil ): Boolean;
function CallRemoteProcLog( Broker: TRPCBroker; RemoteProcedure: String;
Parameters: array of String; MultList: TStringList = nil;
RPCMode: TRPCMode = []; RetList: TStrings = nil ): Boolean;
function CheckRPCError( RPCName: String; Results: TStrings;
RPCMode: TRPCMode = [] ): Integer;
procedure LogString( ll: String );
procedure LogTimeString( ll: String );
//function RPCErrorCode(Results: TStrings = nil): Integer;
var
Log: TStrings;
RPCBroker: TRPCBroker = nil;
prevRPC: String;
implementation
uses
uGMV_Common
, uGMV_Engine
;
{$R *.DFM}
function CallRemoteProc(Broker: TRPCBroker; RemoteProcedure: String;
Parameters: array of String; MultList: TStringList = nil;
RPCMode: TRPCMode = []; RetList: TStrings = nil): Boolean;
var
s,ss: String;
i, j: Integer;
procedure CheckBroker(aFlag:Boolean;aString:String='');
begin
if not aFlag then Exit;
if not (Broker.ClearParameters and Broker.ClearResults) then
begin
if Broker.ClearParameters then s := ''
else s := 'Clear Parameters = False'+ #13;
if Broker.ClearResults then ss := ''
else ss := 'Clear Results = False';
ShowMessage('Vitals: Broker settings Error'+#13+
aString+#13+
s+ss+#13+
'RPC: "'+Broker.RemoteProcedure+'"'+#13+
'Prev RPC: "'+prevRPC+'"');
Broker.ClearParameters := True;
Broker.ClearResults := True;
end;
end;
begin
Broker.RemoteProcedure := RemoteProcedure;
CheckBroker(CheckBrokerFlag,'CallRemoteProc - In');
PrevRPC := RemoteProcedure;
Broker.Param.Clear;
Broker.Results.Clear;
i := 0;
while i <= High(Parameters) do
begin
if (Copy(Parameters[i], 1, 1) = '@') and (Parameters[i] <> '@') then
begin
Broker.Param[i].Value := Copy(Parameters[i], 2, Length(Parameters[i]));
Broker.Param[i].PType := Reference;
end
else
begin
Broker.Param[i].Value := Parameters[i];
Broker.Param[i].PType := Literal;
end;
Inc(i);
end;
if MultList <> nil then
if MultList.Count > 0 then
begin
for j := 1 to MultList.Count do
Broker.Param[i].Mult[IntToStr(j)] := MultList[j-1];
Broker.Param[i].PType := List;
end;
try
Result := True;
if RetList <> nil then
begin
RetList.Clear;
Broker.lstCall(RetList);
end
else
begin
Broker.Call;
RetList := Broker.Results;
end;
CheckBroker(CheckBrokerFlag,'CallRemoteProc - Out');
if Not (rpcNoResChk in RPCMode) then
if CheckRPCError(RemoteProcedure, RetList, RPCMode) <> 0 then
Result := False;
except
on e: EBrokerError do
begin
if Not (rpcSilent in RPCMode) then
MessageDialog('RPC Error',
'Error encountered retrieving VistA data.' + #13 +
'Server: ' + Broker.Server + #13 +
'Listener port: ' + IntToStr(Broker.ListenerPort) + #13 +
'Remote procedure: ' + Broker.RemoteProcedure + #13 +
'Error is: ' + #13 +
e.Message, mtError, [mbOK], mrOK, e.HelpContext);
with Broker do
begin
Results.Clear;
Results.Add('-1000^1');
Results.Add('-1000^' + e.Message);
end;
Result := False;
end;
else
raise;
end;
end;
procedure LogString(ll: String);
begin
try
Log.Text := Log.Text + ll;
except
end;
end;
procedure LogTimeString(ll: String);
begin
LogString(#13 +
Format('%s : %s',[FormatDateTime('dd/mm/yyyy hh:nn:ss.zzz',Now),ll]));
end;
function CallRemoteProcLog(Broker: TRPCBroker; RemoteProcedure: String;
Parameters: array of String; MultList: TStringList = nil;
RPCMode: TRPCMode = []; RetList: TStrings = nil): Boolean;
var
i: integer;
begin
LogTimeString('Start -- ' +RemoteProcedure);
for i := 0 to High(Parameters) do
LogString(#13+ ' ['+IntTosTr(i)+'] ' +Parameters[i]);
if MultList <> nil then
for I := 0 to MultList.Count - 1 do
LogString(#13+ ' ['+IntTosTr(i)+'] ' +MultList[i]);
if CallRemoteProc(Broker, RemoteProcedure, Parameters, MultList, RPCMode, RetList) then
begin
if RetList <> nil then
for I := 0 to RetList.Count - 1 do
LogString(#13+ ' ['+IntTosTr(i)+'] ' +RetList[i]);
LogTimeString('Stop -- 1 ' +RemoteProcedure);
Result := True;
end
else
begin
LogTimeString('Stop -- 0 ' +RemoteProcedure);
Result := False;
end;
end;
function CheckRPCError(RPCName: String; Results: TStrings;
RPCMode: TRPCMode = [] ): Integer;
var
i, n: Integer;
buf, rc: String;
form: TRPCErrorForm;
begin
if Results.Count = 0 then
begin
Result := mrOK;
buf := 'The ''' + RPCName + ''' remote procedure returned nothing!';
if Not (rpcSilent in RPCMode) then
MessageDialog('RPC Error', buf, mtError, [mbOK], mrOK, 0);
Results.Add('-1001^1');
Results.Add('-1001^' + buf);
Exit;
end;
Result := 0;
rc := Piece(Results[0], '^');
if StrToIntDef(rc, 0) < 0 then
begin
Result := mrOK;
if Not (rpcSilent in RPCMode) then
begin
form := TRPCErrorForm.Create(Application);
n := StrToIntDef(Piece(Results[0], '^', 2), 0);
with form.Msg.Lines do
begin
buf := 'The error code ''' + rc + ''' was returned by the '''
+ RPCName + ''' remote procedure!';
if n > 0 then
begin
buf := buf + ' The problem had been caused by the following ';
if n > 1 then
buf := buf + 'errors (in reverse chronological order):'
else
buf := buf + 'error: ';
Add(buf);
for i := 1 to n do
begin
if i >= Results.Count then
break;
buf := Results[i];
Add(''); Add(' ' + Piece(buf,'^',2));
Add(' Error Code: ' + Piece(buf,'^',1) + ';' + #9 +
'Place: ' + StringReplace(Piece(buf,'^',3),'~','^',[]));
end;
end
else
Add(buf);
end;
Result := form.ShowModal;
form.Free;
end;
end;
end;
{
function RPCErrorCode(Results: TStrings): Integer;
var
res: TStrings;
begin
if Assigned(Results) then
res := Results
else
res := RPCBroker.Results;
if res.Count > 0 then
Result := StrToIntDef(Piece(Piece(res[0], '^'), '.'), -999)
else
Result := -999;
end;
}
////////////////////////////////////////////////////////////////////////////////
procedure TRPCErrorForm.btnOkClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
begin
PrevRPC := '';
end.
|
unit AverageLogger;
interface
uses
Classes, Sysutils, Dialogs, Windows, Math,
AsciiCheck;
type
TAveragePeriod = (Days30, Days90, Days180);
TPeriodAverage = record
Period: TAveragePeriod;
FormattedAverageValue: String;
end;
TAverageLogger = class abstract
private
LastDateInLog: String;
LastValueInLog: UInt64;
MaxPeriodAverage: TPeriodAverage;
PassedDaysFromFirst: Integer;
TodayDelta: Double;
UserDefaultFormat: TFormatSettings;
TimestampedValueList: TStringList;
FileName: String;
procedure ChangeLastRecordedPeriodToNow;
procedure AddNewRecordWithTimestamp(const NewValue: String);
procedure ReadFileOrCreateNew(const FileName: String);
function IsNewValueInvalid(const NewValue: String): Boolean;
procedure InitializeAverageTodayDelta;
procedure ReadAndSetAverageTodayDelta(const NewValue: String);
procedure SetAverage(const NewValue: String);
procedure RefreshFile(const NewValue: String);
procedure DisposeExpiredRecords;
procedure SaveToFile;
function IsNewRecordNeeded: Boolean;
function IsLastRecordExpired: Boolean;
protected
function GetUnit: Double; virtual; abstract;
public
constructor Create(const FileName: String); overload;
constructor Create(FileContents: TStringList); overload;
procedure ReadAndRefresh(const NewValue: String);
function GetFormattedTodayDelta: String;
function GetMaxPeriodFormattedAverage: TPeriodAverage;
class function BuildFileName(const Folder, Serial: String): String;
destructor Destroy; override;
end;
implementation
procedure TAverageLogger.ReadFileOrCreateNew(const FileName: String);
begin
self.FileName := FileName;
if not FileExists(FileName) then
TimestampedValueList.SaveToFile(FileName)
else
TimestampedValueList.LoadFromFile(FileName);
end;
constructor TAverageLogger.Create(const FileName: String);
begin
TimestampedValueList := TStringList.Create;
Create(TimestampedValueList);
ReadFileOrCreateNew(FileName);
end;
destructor TAverageLogger.Destroy;
begin
FreeAndNil(TimestampedValueList);
inherited;
end;
function TAverageLogger.IsNewValueInvalid(const NewValue: String): Boolean;
var
NewValueInUInt64: UInt64;
begin
result :=
(not (TryStrToUInt64(NewValue, NewValueInUInt64))) or
(NewValueInUInt64 = 0);
end;
procedure TAverageLogger.InitializeAverageTodayDelta;
begin
LastDateInLog := '';
LastValueInLog := 0;
PassedDaysFromFirst := 0;
MaxPeriodAverage.Period := TAveragePeriod.Days30;
MaxPeriodAverage.FormattedAverageValue := '0.0';
TodayDelta := 0;
end;
procedure TAverageLogger.SetAverage(const NewValue: String);
const
AvgMax = 2;
AveragePeriodInSet: Array[0..AvgMax] of Set of Byte =
([0..29], [30..89], [90..180]);
IntegerToAveragePeriod: Array[0..AvgMax] of TAveragePeriod =
(Days30, Days90, Days180);
var
FirstValueInLog: Integer;
CurrentAveragePeriod: Integer;
AverageValue: Double;
begin
FirstValueInLog :=
StrToUInt64(TimestampedValueList[TimestampedValueList.Count - 1]);
if StrToUInt64(NewValue) = (FirstValueInLog) then
exit;
for CurrentAveragePeriod := AvgMax downto 0 do
if PassedDaysFromFirst in AveragePeriodInSet[CurrentAveragePeriod] then
begin
MaxPeriodAverage.Period :=
IntegerToAveragePeriod[CurrentAveragePeriod];
AverageValue :=
(StrToUInt64(NewValue) - FirstValueInLog) /
PassedDaysFromFirst *
GetUnit;
MaxPeriodAverage.FormattedAverageValue :=
Format('%.1f', [AverageValue]);
break;
end;
end;
function TAverageLogger.GetFormattedTodayDelta: String;
begin
result := Format('%.1f', [TodayDelta]);
end;
function TAverageLogger.GetMaxPeriodFormattedAverage: TPeriodAverage;
begin
result := MaxPeriodAverage;
end;
procedure TAverageLogger.ReadAndSetAverageTodayDelta(const NewValue: String);
begin
if TimestampedValueList.Count = 0 then
exit;
LastDateInLog := TimestampedValueList[0];
LastValueInLog := StrToUInt64(TimestampedValueList[1]);
PassedDaysFromFirst :=
Ceil(Now - StrToDateTime(
TimestampedValueList[
TimestampedValueList.Count - 2], UserDefaultFormat));
TodayDelta :=
(StrToUInt64(NewValue) -
StrToUInt64(TimestampedValueList[1])) * GetUnit;
SetAverage(NewValue);
end;
function TAverageLogger.IsNewRecordNeeded: Boolean;
begin
result :=
(TimestampedValueList.Count = 0) or
(TodayDelta > 0);
end;
procedure TAverageLogger.RefreshFile(const NewValue: String);
begin
if LastDateInLog = FormatDateTime('yy/mm/dd', Now) then
exit;
LastDateInLog := FormatDateTime('yy/mm/dd', Now);
LastValueInLog := StrToUInt64(NewValue);
if IsNewRecordNeeded then AddNewRecordWithTimestamp(NewValue)
else ChangeLastRecordedPeriodToNow;
end;
procedure TAverageLogger.ReadAndRefresh(const NewValue: String);
begin
InitializeAverageTodayDelta;
if IsNewValueInvalid(NewValue) then
exit;
ReadAndSetAverageTodayDelta(NewValue);
RefreshFile(NewValue);
end;
function TAverageLogger.IsLastRecordExpired: Boolean;
begin
result := TimestampedValueList.Count > 0;
result := result and
((Now - 180) >
StrToDateTime(
TimestampedValueList[TimestampedValueList.Count - 2],
UserDefaultFormat));
end;
procedure TAverageLogger.DisposeExpiredRecords;
begin
while IsLastRecordExpired do
begin
TimestampedValueList.Delete(TimestampedValueList.Count - 1);
TimestampedValueList.Delete(TimestampedValueList.Count - 1);
end;
end;
procedure TAverageLogger.ChangeLastRecordedPeriodToNow;
begin
TimestampedValueList[0] := FormatDateTime('yy/mm/dd', Now);
SaveToFile;
end;
constructor TAverageLogger.Create(FileContents: TStringList);
const
PredefinedLCID = 1042;
begin
UserDefaultFormat := TFormatSettings.Create(PredefinedLCID);
UserDefaultFormat.DateSeparator := '-';
TimestampedValueList := FileContents;
if TimestampedValueList.Count > 0 then
DisposeExpiredRecords;
end;
procedure TAverageLogger.AddNewRecordWithTimestamp(const NewValue: String);
begin
TimestampedValueList.Insert(0, NewValue);
TimestampedValueList.Insert(0, FormatDateTime('yy/mm/dd', Now));
SaveToFile;
end;
procedure TAverageLogger.SaveToFile;
begin
;{$IfNDef UNITTEST}
TimestampedValueList.SaveToFile(FileName);
{$EndIf}
end;
class function TAverageLogger.BuildFileName(const Folder, Serial: String):
String;
begin
result := Folder + 'WriteLog' + Serial + '.txt';
end;
end.
|
{**************************************************}
{ TPointFigureSeries (derived from TOHLCSeries) }
{ Copyright (c) 2002-2004 by David Berneda }
{**************************************************}
unit TeePointFigure;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
{$IFDEF CLX}
QForms, QControls, QStdCtrls, QGraphics,
{$ELSE}
Forms, Controls, StdCtrls, Graphics,
{$ENDIF}
Classes, SysUtils,
TeeProcs, OHLChart, TeEngine, Series;
type
TPointFigureSeries=class(TOHLCSeries)
private
FBoxSize : Double;
FDown : TSeriesPointer;
FReversal : Double;
FUp : TSeriesPointer;
Procedure DrawColumn( Pointer:TSeriesPointer; FromValue:Double;
const ToValue:Double; tmpX:Integer);
procedure SetBoxSize(const Value: Double);
procedure SetDown(const Value: TSeriesPointer);
procedure SetReversal(const Value: Double);
procedure SetUp(const Value: TSeriesPointer);
protected
Function CalcMaxColumns(Draw:Boolean=False):Integer;
procedure DrawAllValues; override;
class Function GetEditorClass:String; override;
procedure PrepareForGallery(IsEnabled:Boolean); override;
Procedure SetParentChart(Const Value:TCustomAxisPanel); override;
public
Constructor Create(AOwner: TComponent); override;
Destructor Destroy; override;
Function CountLegendItems:Integer; override;
Function LegendItemColor(LegendIndex:Integer):TColor; override;
Function LegendString( LegendIndex:Integer;
LegendTextStyle:TLegendTextStyle ):String; override;
Function MaxXValue:Double; override;
Function MinXValue:Double; override;
published
property BoxSize:Double read FBoxSize write SetBoxSize;
property DownSymbol:TSeriesPointer read FDown write SetDown;
property ReversalAmount:Double read FReversal write SetReversal;
property UpSymbol:TSeriesPointer read FUp write SetUp;
property Active;
property Brush;
property Cursor;
property Depth;
property HorizAxis;
property Marks;
property ParentChart;
property DataSource;
property Pen;
property PercentFormat;
property SeriesColor;
property ShowInLegend;
property Title;
property ValueFormat;
property VertAxis;
property XLabelsSource;
property XValues;
property YValues;
{ events }
property AfterDrawValues;
property BeforeDrawValues;
property OnAfterAdd;
property OnBeforeAdd;
property OnClearValues;
property OnClick;
property OnDblClick;
property OnGetMarkText;
property OnMouseEnter;
property OnMouseLeave;
end;
TPointFigureEditor = class(TForm)
Label1: TLabel;
EBoxSize: TEdit;
Label2: TLabel;
EReversal: TEdit;
procedure FormShow(Sender: TObject);
procedure EBoxSizeChange(Sender: TObject);
procedure EReversalChange(Sender: TObject);
private
{ Private declarations }
UpForm : TCustomForm;
DownForm : TCustomForm;
PointFigure : TPointFigureSeries;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
uses Chart, TeeProCo, TeePoEdi, TeCanvas;
type TValueListAccess=class(TChartValueList);
{ TPointFigureSeries }
Constructor TPointFigureSeries.Create(AOwner: TComponent);
begin
inherited;
FUp:=TSeriesPointer.Create(Self);
FUp.Style:=psDiagCross;
FUp.Brush.Color:=clGreen;
FDown:=TSeriesPointer.Create(Self);
FDown.Style:=psCircle;
FDown.Brush.Color:=clRed;
FBoxSize:=1;
FReversal:=3;
TValueListAccess(XValues).InitDateTime(False);
end;
Destructor TPointFigureSeries.Destroy;
begin
FreeAndNil(FDown);
FreeAndNil(FUp);
inherited;
end;
Procedure TPointFigureSeries.DrawColumn( Pointer:TSeriesPointer; FromValue:Double;
const ToValue:Double; tmpX:Integer);
var tmpY : Integer;
begin
repeat
tmpY:=CalcYPosValue(FromValue);
Pointer.PrepareCanvas(ParentChart.Canvas,Pointer.Color);
Pointer.Draw(tmpX,tmpY);
FromValue:=FromValue+BoxSize;
until FromValue>ToValue;
end;
Function TPointFigureSeries.CalcMaxColumns(Draw:Boolean=False):Integer;
var tmpX : Integer;
tmpLow : Double;
tmpHigh : Double;
tmp : Double;
t : Integer;
tmpCol : Integer;
tmpDistance : Double;
tmpIsDown : Boolean;
begin
if Count>0 then
begin
tmpDistance:=ReversalAmount*BoxSize;
tmpLow:=LowValues.Value[0];
tmpHigh:=HighValues.Value[0];
tmpCol:=0;
if Draw then
begin
tmpX:=CalcXPosValue(tmpCol);
DrawColumn(FDown,tmpLow,tmpHigh,tmpX);
end
else tmpX:=0;
tmpIsDown:=True;
for t:=1 to Count-1 do
begin
if tmpIsDown then
begin
tmp:=LowValues.Value[t];
if tmp<=(tmpLow-BoxSize) then
begin
if Draw then
DrawColumn(FDown,tmp,tmpLow-BoxSize,tmpX);
tmpLow:=tmp;
end
else
begin
tmp:=HighValues.Value[t];
if tmp>=(tmpLow+tmpDistance) then
begin
Inc(tmpCol);
tmpHigh:=tmp;
if Draw then
begin
tmpX:=CalcXPosValue(tmpCol);
DrawColumn(FUp,tmpLow+BoxSize,tmpHigh,tmpX);
end;
tmpIsDown:=False;
end;
end;
end
else
begin
tmp:=HighValues.Value[t];
if tmp>=(tmpHigh+BoxSize) then
begin
if Draw then
DrawColumn(FUp,tmpHigh+BoxSize,tmp,tmpX);
tmpHigh:=tmp;
end
else
begin
tmp:=LowValues.Value[t];
if tmp<=(tmpHigh-tmpDistance) then
begin
Inc(tmpCol);
tmpLow:=tmp;
if Draw then
begin
tmpX:=CalcXPosValue(tmpCol);
DrawColumn(FDown,tmpLow,tmpHigh-BoxSize,tmpX);
end;
tmpIsDown:=True;
end;
end;
end;
end;
result:=tmpCol+1;
end
else result:=0;
end;
procedure TPointFigureSeries.DrawAllValues;
begin
CalcMaxColumns(True);
end;
function TPointFigureSeries.MaxXValue: Double;
begin
result:=CalcMaxColumns-1;
end;
function TPointFigureSeries.MinXValue: Double;
begin
result:=0;
end;
procedure TPointFigureSeries.SetBoxSize(const Value: Double);
begin
SetDoubleProperty(FBoxSize,Value);
end;
procedure TPointFigureSeries.SetDown(const Value: TSeriesPointer);
begin
FDown.Assign(Value);
end;
procedure TPointFigureSeries.SetReversal(const Value: Double);
begin
SetDoubleProperty(FReversal,Value);
end;
procedure TPointFigureSeries.SetUp(const Value: TSeriesPointer);
begin
FUp.Assign(Value);
end;
class function TPointFigureSeries.GetEditorClass: String;
begin
result:='TPointFigureEditor';
end;
procedure TPointFigureEditor.FormShow(Sender: TObject);
begin
PointFigure:=TPointFigureSeries({$IFDEF CLR}TObject{$ENDIF}(Tag));
if Assigned(PointFigure) then
begin
with PointFigure do
begin
EReversal.Text:=FloatToStr(ReversalAmount);
EBoxSize.Text:=FloatToStr(BoxSize);
end;
if Assigned(Parent) then
begin
if not Assigned(UpForm) then
UpForm:=TeeInsertPointerForm(Parent,PointFigure.UpSymbol,TeeMsg_Up);
if not Assigned(DownForm) then
DownForm:=TeeInsertPointerForm(Parent,PointFigure.DownSymbol,TeeMsg_Down);
end;
end;
end;
procedure TPointFigureEditor.EBoxSizeChange(Sender: TObject);
begin
if Showing then
PointFigure.BoxSize:=StrToFloatDef(EBoxSize.Text,PointFigure.BoxSize);
end;
procedure TPointFigureEditor.EReversalChange(Sender: TObject);
begin
if Showing then
PointFigure.ReversalAmount:=StrToFloatDef(EReversal.Text,PointFigure.ReversalAmount);
end;
function TPointFigureSeries.CountLegendItems: Integer;
begin
result:=2;
end;
function TPointFigureSeries.LegendItemColor(LegendIndex: Integer): TColor;
begin
if LegendIndex=0 then result:=FUp.Brush.Color
else result:=FDown.Brush.Color
end;
function TPointFigureSeries.LegendString(LegendIndex: Integer;
LegendTextStyle: TLegendTextStyle): String;
begin
if LegendIndex=0 then result:=TeeMsg_Up
else result:=TeeMsg_Down;
end;
procedure TPointFigureSeries.SetParentChart(const Value: TCustomAxisPanel);
begin
inherited;
if not (csDestroying in ComponentState) then
begin
if Assigned(FUp) then FUp.ParentChart:=ParentChart;
if Assigned(FDown) then FDown.ParentChart:=ParentChart;
end;
end;
procedure TPointFigureSeries.PrepareForGallery(IsEnabled: Boolean);
begin
inherited;
if not IsEnabled then
begin
DownSymbol.Color:=clSilver;
DownSymbol.Pen.Color:=clGray;
UpSymbol.Color:=clSilver;
UpSymbol.Pen.Color:=clGray;
end;
end;
initialization
RegisterClass(TPointFigureEditor);
RegisterTeeSeries( TPointFigureSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryPointFigure,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryFinancial, 1);
finalization
UnRegisterTeeSeries([TPointFigureSeries]);
end.
|
unit ViewMailMod;
interface
uses
Windows, Messages, SysUtils, Classes, HTTPApp, WebModu, HTTPProd,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
IdMessageClient, IdPOP3, WebAdapt, WebComp, IdMessage;
type
TViewMailModule = class(TWebPageModule)
PageProducer: TPageProducer;
popEmail: TIdPOP3;
EmailAdapter: TAdapter;
MessageId: TAdapterField;
MessageSubject: TAdapterField;
MessageDate: TAdapterField;
msgEmail: TIdMessage;
MessageFromName: TAdapterField;
MessageFromEmail: TAdapterField;
MessageSize: TAdapterField;
MessageCount: TAdapterField;
GetEmail: TAdapterAction;
procedure EmailAdapterIterateRecords(Sender: TObject;
Action: TIteratorMethod; var EOF: Boolean);
procedure WebPageModuleDeactivate(Sender: TObject);
procedure MessageIdGetValue(Sender: TObject; var Value: Variant);
procedure MessageSubjectGetValue(Sender: TObject; var Value: Variant);
procedure MessageFromNameGetValue(Sender: TObject; var Value: Variant);
procedure MessageDateGetValue(Sender: TObject; var Value: Variant);
procedure MessageFromEmailGetValue(Sender: TObject;
var Value: Variant);
procedure MessageSizeGetValue(Sender: TObject; var Value: Variant);
procedure MessageCountGetValue(Sender: TObject; var Value: Variant);
procedure GetEmailGetParams(Sender: TObject; Params: TStrings);
procedure GetEmailExecute(Sender: TObject; Params: TStrings);
private
{ Private declarations }
FMessageId: Integer;
FMessageCount: Integer;
FMessageSubject: string;
FMessageFromName: string;
FMessageFromEmail: string;
FMessageDate: string;
FMessageSize: Integer;
public
{ Public declarations }
end;
function ViewMailModule: TViewMailModule;
const
cUserName = 'UserName';
cPassword = 'Password';
implementation
{$R *.dfm} {*.html}
uses WebReq, WebCntxt, WebFact, Variants, IdEMailAddress,
EmailMessageMod, WebDisp;
function ViewMailModule: TViewMailModule;
begin
Result := TViewMailModule(WebContext.FindModuleClass(TViewMailModule));
end;
procedure TViewMailModule.EmailAdapterIterateRecords(Sender: TObject;
Action: TIteratorMethod; var EOF: Boolean);
procedure FillInMessageInfo;
begin
msgEmail.Clear;
popEmail.RetrieveHeader(FMessageId, msgEmail);
FMessageSubject := msgEmail.Subject;
FMessageFromName := msgEmail.From.Name;
FMessageFromEmail := msgEmail.From.Address;
FMessageDate := DateTimeToStr(msgEmail.Date);
FMessageSize := popEmail.RetrieveMsgSize(FMessageId);
end;
begin
if Action = itStart then
begin
// Connect to the server, using the user name and password stored
// in the session.
if popEmail.Connected then
begin
try
popEmail.Disconnect
except
end;
end;
popEmail.UserId := WebContext.Session.Values[cUserName];
popEmail.Password := WebContext.Session.Values[cPassword];
popEmail.Connect;
// Find out the message count
FMessageCount := popEmail.CheckMessages;
FMessageId := 1;
EOF := FMessageCount = 0;
end
else if Action = itNext then
begin
Inc(FMessageId);
EOF := FMessageId > FMessageCount;
end
else
begin
EOF := True;
popEmail.Disconnect;
end;
if not EOF then
FillInMessageInfo;
end;
procedure TViewMailModule.WebPageModuleDeactivate(Sender: TObject);
begin
try
if popEmail.Connected then
popEmail.Disconnect;
except
end;
end;
procedure TViewMailModule.MessageIdGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FMessageId;
end;
procedure TViewMailModule.MessageSubjectGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FMessageSubject;
end;
procedure TViewMailModule.MessageFromNameGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FMessageFromName;
end;
procedure TViewMailModule.MessageDateGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FMessageDate;
end;
procedure TViewMailModule.MessageFromEmailGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FMessageFromEmail;
end;
procedure TViewMailModule.MessageSizeGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FMessageSize;
end;
procedure TViewMailModule.MessageCountGetValue(Sender: TObject;
var Value: Variant);
begin
Value := FMessageCount;
end;
procedure TViewMailModule.GetEmailGetParams(Sender: TObject;
Params: TStrings);
begin
Params.Values['id'] := IntToStr(FMessageId);
end;
procedure TViewMailModule.GetEmailExecute(Sender: TObject;
Params: TStrings);
begin
if (Params.Values['id'] <> '') and (WebContext.EndUser.LoggedIn) then
DispatchPageName(EmailMessageModule.Name, Response, []);
end;
initialization
if WebRequestHandler <> nil then
WebRequestHandler.AddWebModuleFactory(TWebPageModuleFactory.Create(TViewMailModule, TWebPageInfo.Create([wpPublished, wpLoginRequired], '.html'), crOnDemand, caCache));
end.
|
(* Chapter 16 - Program 4 *)
program AmortizationTable;
var Month : 1..12;
StartingMonth : 1..12;
Balance : real;
Payment : real;
InterestRate : real;
AnnualAccumInterest : real;
Year : integer;
NumberOfYears : integer;
OriginalLoan : real;
procedure CalculatePayment; (* **************** calculate payment *)
var Temp : real;
Index : integer;
begin
Temp := 1.0;
for Index := 1 TO 12*NumberOfYears do
Temp := Temp * (1.0 + InterestRate);
Payment := OriginalLoan*InterestRate/(1.0 - 1.0/Temp);
end;
procedure InitializeData; (* ******************** initialize data *)
begin
Writeln(' Pascal amortization program');
Writeln;
Write('Enter amount borrowed ');
Readln(OriginalLoan);
Balance := OriginalLoan;
Write('Enter interest rate as percentage (i.e. 13.5) ');
Readln(InterestRate);
InterestRate := InterestRate/1200.0;
Write('Enter number of years of payoff ');
Readln(NumberOfYears);
Write('Enter month of first payment (i.e. 5 for May) ');
Readln(StartingMonth);
Write('Enter year of first payment (i.e. 1991) ');
Readln(Year);
CalculatePayment;
AnnualAccumInterest := 0.0; (* This is to accumulate Interest *)
end;
procedure PrintAnnualHeader; (* ************ print annual header *)
begin
Writeln;
Writeln;
Writeln('Original loan amount = ',OriginalLoan:10:2,
' Interest rate = ',1200.0*InterestRate:6:2,'%');
Writeln;
Writeln('Month payment interest princ balance');
Writeln;
end;
procedure CalculateAndPrint; (* ************ calculate and print *)
var InterestPayment : real;
PrincipalPayment : real;
begin
if Balance > 0.0 then begin
InterestPayment := InterestRate * Balance;
PrincipalPayment := Payment - InterestPayment;
if PrincipalPayment > Balance then begin (* loan payed off *)
PrincipalPayment := Balance; (* this month *)
Payment := PrincipalPayment + InterestPayment;
Balance := 0.0;
end
else begin (* regular monthly payment *)
Balance := Balance - PrincipalPayment;
end;
AnnualAccumInterest := AnnualAccumInterest
+ InterestPayment;
Writeln(Month:5,Payment:10:2,InterestPayment:10:2,
PrincipalPayment:10:2,Balance:10:2);
end; (* of if Balance > 0.0 then *)
end;
procedure PrintAnnualSummary; (* ********** print annual summary *)
begin
Writeln;
Writeln('Total interest for ',Year:5,' = ',
AnnualAccumInterest:10:2);
AnnualAccumInterest := 0.0;
Year := Year + 1;
Writeln;
end;
begin (* ******************************************* main program *)
InitializeData;
repeat
PrintAnnualHeader;
for Month := StartingMonth to 12 do begin
CalculateAndPrint;
end;
PrintAnnualSummary;
StartingMonth := 1;
until Balance <= 0.0;
end. (* of main program *)
|
{A simple benchmark with lots of reallocmem calls}
unit ReallocMemBenchmark;
interface
uses
BenchmarkClassUnit, Math;
const
{The number of pointers}
NumPointers = 10000;
{The maximum change in a block size per iteration}
BlockSizeDelta = 2048;
type
TReallocBench = class(TFastcodeMMBenchmark)
protected
FPointers: array[0..NumPointers - 1] of PChar;
FBlockSizes: array[0..NumPointers - 1] of integer;
public
constructor CreateBenchmark; override;
destructor Destroy; override;
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
{ TReallocBench }
constructor TReallocBench.CreateBenchmark;
begin
inherited;
{Clear all the pointers}
FillChar(FPointers, SizeOf(FPointers), 0);
{Clear all the block sizes}
FillChar(FBlockSizes, SizeOf(FBlockSizes), 0);
end;
destructor TReallocBench.Destroy;
var
i: integer;
begin
{Free all residual pointers}
for i := 0 to NumPointers - 1 do
ReallocMem(FPointers[i], 0);
inherited;
end;
class function TReallocBench.GetBenchmarkDescription: string;
begin
Result := 'Allocates lots of pointers of random sizes and continues to '
+ 'grow/shrink them randomly in a loop. '
+ 'Benchmark submitted by Pierre le Riche.';
end;
class function TReallocBench.GetBenchmarkName: string;
begin
Result := 'ReallocMem benchmark';
end;
class function TReallocBench.GetCategory: TBenchmarkCategory;
begin
Result := bmSingleThreadRealloc;
end;
procedure TReallocBench.RunBenchmark;
var
i, LPointerNumber: integer;
begin
{Call the inherited handler}
inherited;
{Do the benchmark}
for i := 1 to 1000000 do
begin
{Get a random pointer number}
LPointerNumber := Random(NumPointers);
{Adjust the current block size up or down by up to BlockSizeDelta}
FBlockSizes[LPointerNumber] := abs(FBlockSizes[LPointerNumber]
+ Random(BlockSizeDelta) - BlockSizeDelta shr 1);
{Reallocate the pointer}
ReallocMem(FPointers[LPointerNumber], FBlockSizes[LPointerNumber]);
{Touch the memory}
if FBlockSizes[LPointerNumber] > 0 then
begin
FPointers[LPointerNumber]^ := #1;
PChar(Integer(FPointers[LPointerNumber]) + FBlockSizes[LPointerNumber] - 1)^ := #2;
end;
end;
{What we end with should be close to the peak usage}
UpdateUsageStatistics;
end;
end.
|
unit SEA_INTV;
{$ifdef VirtualPascal}
{$stdcall+}
{$else}
Error('Interface unit for VirtualPascal');
{$endif}
(*************************************************************************
DESCRIPTION : Interface unit for SEA_DLL
REQUIREMENTS : VirtualPascal
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 16.06.07 W.Ehrhardt Initial version analog TF_INTV
0.11 15.07.09 we SEA_DLL_Version returns PAnsiChar
0.12 26.07.10 we Longint ILen, SEA_Err_Invalid_16Bit_Length
0.13 27.07.10 we Removed OMAC XL version
0.14 28.07.10 we SEA_CTR_Seek
0.15 31.07.10 we SEA_CTR_Seek via sea_seek.inc
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2007-2010 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
interface
const
SEA_Err_Invalid_Key_Size = -1; {Key size in bits not 128, 192, or 256}
SEA_Err_Invalid_Length = -3; {No full block for cipher stealing}
SEA_Err_Data_After_Short_Block = -4; {Short block must be last}
SEA_Err_MultipleIncProcs = -5; {More than one IncProc Setting}
SEA_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length}
SEA_Err_CTR_SeekOffset = -15; {Negative offset in SEA_CTR_Seek}
SEA_Err_Invalid_16Bit_Length = -20; {Pointer + Offset > $FFFF for 16 bit code}
type
TSEARndKey = packed array[0..31] of longint; {Round key schedule}
TSEABlock = packed array[0..15] of byte; {128 bit block}
PSEABlock = ^TSEABlock;
type
TSEAIncProc = procedure(var CTR: TSEABlock); {user supplied IncCTR proc}
type
TSEAContext = packed record
IV : TSEABlock; {IV or CTR }
buf : TSEABlock; {Work buffer }
bLen : word; {Bytes used in buf }
Flag : word; {Bit 1: Short block }
IncProc : TSEAIncProc; {Increment proc CTR-Mode}
RK : TSEARndKey; {Round keys }
end;
const
SEABLKSIZE = sizeof(TSEABlock); {SEED block size in bytes}
type
TSEA_EAXContext = packed record
HdrOMAC : TSEAContext; {Hdr OMAC1 context}
MsgOMAC : TSEAContext; {Msg OMAC1 context}
ctr_ctx : TSEAContext; {Msg SEACTR context}
NonceTag: TSEABlock; {nonce tag }
tagsize : word; {tag size (unused) }
flags : word; {ctx flags (unused)}
end;
function SEA_DLL_Version: PAnsiChar;
{-Return DLL version as PAnsiChar}
function SEA_Init(const Key; KeyBits: word; var ctx: TSEAContext): integer;
{-SEED context/round key initialization}
procedure SEA_Encrypt(var ctx: TSEAContext; const BI: TSEABlock; var BO: TSEABlock);
{-encrypt one block (in ECB mode)}
procedure SEA_Decrypt(var ctx: TSEAContext; const BI: TSEABlock; var BO: TSEABlock);
{-decrypt one block (in ECB mode)}
procedure SEA_XorBlock(const B1, B2: TSEABlock; var B3: TSEABlock);
{-xor two blocks, result in third}
procedure SEA_Reset(var ctx: TSEAContext);
{-Clears ctx fields bLen and Flag}
procedure SEA_SetFastInit(value: boolean);
{-set FastInit variable}
function SEA_GetFastInit: boolean;
{-Returns FastInit variable}
function SEA_CBC_Init(const Key; KeyBits: word; const IV: TSEABlock; var ctx: TSEAContext): integer;
{-SEA key expansion, error if invalid key size, save IV}
procedure SEA_CBC_Reset(const IV: TSEABlock; var ctx: TSEAContext);
{-Clears ctx fields bLen and Flag, save IV}
function SEA_CBC_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSEAContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CBC mode}
function SEA_CBC_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSEAContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CBC mode}
function SEA_CFB_Init(const Key; KeyBits: word; const IV: TSEABlock; var ctx: TSEAContext): integer;
{-SEA key expansion, error if invalid key size, encrypt IV}
procedure SEA_CFB_Reset(const IV: TSEABlock; var ctx: TSEAContext);
{-Clears ctx fields bLen and Flag, encrypt IV}
function SEA_CFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSEAContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CFB128 mode}
function SEA_CFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSEAContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CFB128 mode}
function SEA_CTR_Init(const Key; KeyBits: word; const CTR: TSEABlock; var ctx: TSEAContext): integer;
{-SEA key expansion, error if inv. key size, encrypt CTR}
procedure SEA_CTR_Reset(const CTR: TSEABlock; var ctx: TSEAContext);
{-Clears ctx fields bLen and Flag, encrypt CTR}
function SEA_CTR_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSEAContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode}
function SEA_CTR_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSEAContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode}
function SEA_CTR_Seek(const iCTR: TSEABlock; SOL, SOH: longint; var ctx: TSEAContext): integer;
{-Setup ctx for random access crypto stream starting at 64 bit offset SOH*2^32+SOL,}
{ SOH >= 0. iCTR is the initial CTR for offset 0, i.e. the same as in SEA_CTR_Init.}
function SEA_SetIncProc(IncP: TSEAIncProc; var ctx: TSEAContext): integer;
{-Set user supplied IncCTR proc}
procedure SEA_IncMSBFull(var CTR: TSEABlock);
{-Increment CTR[15]..CTR[0]}
procedure SEA_IncLSBFull(var CTR: TSEABlock);
{-Increment CTR[0]..CTR[15]}
procedure SEA_IncMSBPart(var CTR: TSEABlock);
{-Increment CTR[15]..CTR[8]}
procedure SEA_IncLSBPart(var CTR: TSEABlock);
{-Increment CTR[0]..CTR[7]}
function SEA_ECB_Init(const Key; KeyBits: word; var ctx: TSEAContext): integer;
{-SEA key expansion, error if invalid key size}
procedure SEA_ECB_Reset(var ctx: TSEAContext);
{-Clears ctx fields bLen and Flag}
function SEA_ECB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSEAContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in ECB mode}
function SEA_ECB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSEAContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in ECB mode}
function SEA_OFB_Init(const Key; KeyBits: word; const IV: TSEABlock; var ctx: TSEAContext): integer;
{-SEA key expansion, error if invalid key size, encrypt IV}
procedure SEA_OFB_Reset(const IV: TSEABlock; var ctx: TSEAContext);
{-Clears ctx fields bLen and Flag, encrypt IV}
function SEA_OFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSEAContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in OFB mode}
function SEA_OFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSEAContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in OFB mode}
function SEA_OMAC_Init(const Key; KeyBits: word; var ctx: TSEAContext): integer;
{-OMAC init: SEA key expansion, error if inv. key size}
function SEA_OMAC_Update(data: pointer; ILen: longint; var ctx: TSEAContext): integer;
{-OMAC data input, may be called more than once}
procedure SEA_OMAC_Final(var tag: TSEABlock; var ctx: TSEAContext);
{-end data input, calculate OMAC=OMAC1 tag}
procedure SEA_OMAC1_Final(var tag: TSEABlock; var ctx: TSEAContext);
{-end data input, calculate OMAC1 tag}
procedure SEA_OMAC2_Final(var tag: TSEABlock; var ctx: TSEAContext);
{-end data input, calculate OMAC2 tag}
function SEA_EAX_Init(const Key; KBits: word; const nonce; nLen: word; var ctx: TSEA_EAXContext): integer;
{-Init hdr and msg OMACs, setup SEACTR with nonce tag}
function SEA_EAX_Provide_Header(Hdr: pointer; hLen: word; var ctx: TSEA_EAXContext): integer;
{-Supply a message header. The header "grows" with each call}
function SEA_EAX_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSEA_EAXContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update OMACs}
function SEA_EAX_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSEA_EAXContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update OMACs}
procedure SEA_EAX_Final(var tag: TSEABlock; var ctx: TSEA_EAXContext);
{-Compute EAX tag from context}
implementation
function SEA_DLL_Version; external 'SEA_DLL' name 'SEA_DLL_Version';
function SEA_Init; external 'SEA_DLL' name 'SEA_Init';
procedure SEA_Encrypt; external 'SEA_DLL' name 'SEA_Encrypt';
procedure SEA_Decrypt; external 'SEA_DLL' name 'SEA_Decrypt';
procedure SEA_XorBlock; external 'SEA_DLL' name 'SEA_XorBlock';
procedure SEA_Reset; external 'SEA_DLL' name 'SEA_Reset';
procedure SEA_SetFastInit; external 'SEA_DLL' name 'SEA_SetFastInit';
function SEA_GetFastInit; external 'SEA_DLL' name 'SEA_GetFastInit';
function SEA_CBC_Init; external 'SEA_DLL' name 'SEA_CBC_Init';
procedure SEA_CBC_Reset; external 'SEA_DLL' name 'SEA_CBC_Reset';
function SEA_CBC_Encrypt; external 'SEA_DLL' name 'SEA_CBC_Encrypt';
function SEA_CBC_Decrypt; external 'SEA_DLL' name 'SEA_CBC_Decrypt';
function SEA_CFB_Init; external 'SEA_DLL' name 'SEA_CFB_Init';
procedure SEA_CFB_Reset; external 'SEA_DLL' name 'SEA_CFB_Reset';
function SEA_CFB_Encrypt; external 'SEA_DLL' name 'SEA_CFB_Encrypt';
function SEA_CFB_Decrypt; external 'SEA_DLL' name 'SEA_CFB_Decrypt';
function SEA_CTR_Init; external 'SEA_DLL' name 'SEA_CTR_Init';
procedure SEA_CTR_Reset; external 'SEA_DLL' name 'SEA_CTR_Reset';
function SEA_CTR_Encrypt; external 'SEA_DLL' name 'SEA_CTR_Encrypt';
function SEA_CTR_Decrypt; external 'SEA_DLL' name 'SEA_CTR_Decrypt';
function SEA_SetIncProc; external 'SEA_DLL' name 'SEA_SetIncProc';
procedure SEA_IncMSBFull; external 'SEA_DLL' name 'SEA_IncMSBFull';
procedure SEA_IncLSBFull; external 'SEA_DLL' name 'SEA_IncLSBFull';
procedure SEA_IncMSBPart; external 'SEA_DLL' name 'SEA_IncMSBPart';
procedure SEA_IncLSBPart; external 'SEA_DLL' name 'SEA_IncLSBPart';
function SEA_ECB_Init; external 'SEA_DLL' name 'SEA_ECB_Init';
procedure SEA_ECB_Reset; external 'SEA_DLL' name 'SEA_ECB_Reset';
function SEA_ECB_Encrypt; external 'SEA_DLL' name 'SEA_ECB_Encrypt';
function SEA_ECB_Decrypt; external 'SEA_DLL' name 'SEA_ECB_Decrypt';
function SEA_OFB_Init; external 'SEA_DLL' name 'SEA_OFB_Init';
procedure SEA_OFB_Reset; external 'SEA_DLL' name 'SEA_OFB_Reset';
function SEA_OFB_Encrypt; external 'SEA_DLL' name 'SEA_OFB_Encrypt';
function SEA_OFB_Decrypt; external 'SEA_DLL' name 'SEA_OFB_Decrypt';
function SEA_OMAC_Init; external 'SEA_DLL' name 'SEA_OMAC_Init';
function SEA_OMAC_Update; external 'SEA_DLL' name 'SEA_OMAC_Update';
procedure SEA_OMAC_Final; external 'SEA_DLL' name 'SEA_OMAC_Final';
procedure SEA_OMAC1_Final; external 'SEA_DLL' name 'SEA_OMAC1_Final';
procedure SEA_OMAC2_Final; external 'SEA_DLL' name 'SEA_OMAC2_Final';
function SEA_EAX_Init; external 'SEA_DLL' name 'SEA_EAX_Init';
function SEA_EAX_Encrypt; external 'SEA_DLL' name 'SEA_EAX_Encrypt';
function SEA_EAX_Decrypt; external 'SEA_DLL' name 'SEA_EAX_Decrypt';
procedure SEA_EAX_Final; external 'SEA_DLL' name 'SEA_EAX_Final';
function SEA_EAX_Provide_Header; external 'SEA_DLL' name 'SEA_EAX_Provide_Header';
{$define CONST}
{$i sea_seek.inc}
end.
|
unit PRFWK_Atributo;
interface
uses PRFWK_Classe, DB;
type
TTipoAtributo = (tpString, tpInteiro, tpReal, tpDataHora) ;
type
TPRFWK_Atributo = class(TPRFWK_Classe)
private
aNome : String;
aRequerido : Boolean;
aTipo : TTipoAtributo;
aTipoCampo : TFieldKind;
aTamanho : Integer;
aPrecisao : Integer;
aSqlIndice : Boolean;
aSqlUpdate : Boolean;
aSqlWhere : Boolean;
public
property nome:String read aNome write aNome;
property requerido:Boolean read aRequerido write aRequerido;
property tipo:TTipoAtributo read aTipo write aTipo;
property tipoCampo:TFieldKind read aTipoCampo write aTipoCampo;
property tamanho:Integer read aTamanho write aTamanho;
property precisao:Integer read aPrecisao write aPrecisao;
property sqlIndice:Boolean read aSqlIndice write aSqlIndice;
property sqlUpdate:Boolean read aSqlUpdate write aSqlUpdate;
property sqlWhere:Boolean read aSqlWhere write aSqlWhere;
constructor Create; override;
destructor Destroy; override;
published
end;
implementation
{**
* Construtor
*}
constructor TPRFWK_Atributo.Create;
begin
inherited;
end;
{**
* Destrutor
*}
destructor TPRFWK_Atributo.Destroy;
begin
inherited;
end;
end.
|
{
Maximum Network Flow
LiftToFront Alg. O(N3)
Input:
N: Number of vertices
C: Capacities (No restrictions)
S, T: Source, Target(Sink)
Output:
F: Flow (SkewSymmetric: F[i, j] = - F[j, i])
Flow: Maximum Flow
Reference:
CLR
By Behdad
}
program
MaximumFlow;
const
MaxN = 100 + 2;
var
N, S, T : Integer;
C, F : array [1 .. MaxN, 1 .. MaxN] of Integer;
Flow : Longint;
H : array [1 .. MaxN] of Integer;
E : array [1 .. MaxN] of Longint;
LNext, LLast : array [0 .. MaxN] of Integer;
function Min (A, B : Longint) : Longint;
begin
if A <= B then Min := A else Min := B;
end;
function CanPush (A, B : Integer) : Boolean;
begin
CanPush := (C[A, B] > F[A, B]) and (H[A] > H[B]);
end;
procedure Push (A, B : Integer);
var
Eps : Integer;
begin
Eps := Min(E[A], C[A, B] - F[A, B]);
Dec(E[A], Eps);
Inc(F[A, B], Eps);
F[B, A] := - F[A, B];
Inc(E[B], Eps);
end;
procedure Lift(A : Integer);
var
I : Integer;
begin
if A in [S, T] then Exit;
H[A] := 2 * N;
for I := 1 to N do
if (C[A, I] > F[A, I]) and (H[A] > H[I] + 1) then
H[A] := H[I] + 1;
end;
procedure DisCharge (A : Integer);
var
I : Integer;
begin
while E[A] > 0 do
begin
Lift(A);
for I := 1 to N do
if CanPush(A, I) then
Push(A, I);
end;
end;
procedure InitializePreFlow;
var
I, L : Integer;
begin
H[S] := N;
E[S] := MaxLongInt;
L := 0;
for I := 1 to N do
begin
if I <> S then
Push(S, I);
if not (I in [S, T]) then
begin
LLast[I] := L;
LNext[L] := I;
L := I;
end;
end;
end;
procedure MoveToFront (V : Integer);
begin
LNext[LLast[V]] := LNext[V];
LLast[LNext[LLast[V]]] := LLast[V];
LNext[V] := LNext[0];
LLast[LNext[V]] := V;
LNext[0] := V;
LLast[V] := 0;
end;
procedure LiftToFront;
var
V, BH, I : Integer;
begin
InitializePreFlow;
V := LNext[0];
while V <> 0 do
begin
BH := H[V];
DisCharge(V);
if BH <> H[V] then
MoveToFront(V);
V := LNext[V];
end;
Flow := 0;
for I := 1 to N do
Inc(Flow, F[S, I]);
end;
begin
LiftToFront;
end.
|
unit mml_token2;
{-------------------------------------------------------------------------------
ソフト:テキスト音楽「サクラ」
作 者:クジラ飛行机 https://sakuramml.com
説 明:
TMmlBase の下請けで、文字列処理を行うクラス
履 歴:
2002/06/03 15:13 雛型作成
2002/06/16 11:03 ほぼ完成
-------------------------------------------------------------------------------}
interface
uses
Classes, SysUtils, mml_variable, mml_var;
type
TMmlTokenBase = class
private
FMmlBase: TObject;
public
constructor Create(MmlBase: TObject); //変数参照用に、TMmlBaseを得る
destructor Destroy; override;
function GetArg (var sp: TSrcPos; CalcMode: Boolean): TMVarCustom; // 計算なしで、1つだけ得る
function GetArgCalc(var sp: TSrcPos): TMVarCustom; // 引数の後ろに計算式があれば計算する
function GetArgs (var sp: TSrcPos; varType: string): TMArray;
function GetInt(var sp: TSrcPos): TMInt;
function GetNoteLength(var sp: TSrcPos; stepmode: Boolean; def: Integer): Integer;
end;
implementation
uses
StrUnit, mml_token, mml_system, mml_error, mml_const, mml_calc;
{ TMmlTokenBase }
constructor TMmlTokenBase.Create(MmlBase: TObject);
begin
FMmlBase := MmlBase;
end;
destructor TMmlTokenBase.Destroy;
begin
inherited;
end;
function TMmlTokenBase.GetArg(var sp: TSrcPos; CalcMode: Boolean): TMVarCustom;
procedure subKakko; //( ... )
var s: string; ssp: TSrcPos;
begin
//丸括弧を展開し、その中を計算し、値を戻す
s := GetMaruKakko(sp.Ptr, sp.lineNo);
ssp := TSrcPos.Create ;
try
ssp.Assign(sp);
ssp.SetTempSource(s);
Result := GetArgCalc(ssp);
finally
ssp.Free ;
end;
end;
procedure subString;
var
sp2: TSrcPos; //文字列の取得開始位置を覚えておく
begin
sp2 := TSrcPos.Create ;
try
sp2.Assign(sp); //文字列の取得開始位置をコピー
Result := TMStr.Create ;
try
//文字列を取得
TMStr(Result).value := getString(sp.ptr, sp.lineNo);
//_debug(TMStr(Result).value);
except
//取得に失敗したらエラー
raise;// EMml.Create(ErrMsg(MML_ERR_GET_STRING,sp2));
end;
finally
sp2.Free ;
end;
end;
//文字列の取得
procedure subString2;
var
sp2: TSrcPos; //文字列の取得開始位置を覚えておく
begin
sp2 := TSrcPos.Create ;
try
sp2.Assign(sp); //文字列の取得開始位置をコピー
Result := TMStr.Create ;
try
//文字列を取得
if sp.ptr^ = '"' then Inc(sp.ptr);
TMStr(Result).value := GetTokenChars(['"'],sp.ptr);
//_debug(TMStr(Result).value);
except
//取得に失敗したらエラー
raise;
end;
finally
sp2.Free ;
end;
end;
begin
Result := nil;
skipSpace(sp.ptr);//
case sp.ptr^ of
//マイナスの後は、数値か変数である
'-':
begin
Inc(sp.ptr);
Result := GetArg(sp, True);
if Result = nil then Exit;
if Result.ClassType = TMInt then
begin
TMInt(Result).value := -1 * TMInt(Result).value ;
end else
if Result.ClassType = TMStr then
begin
TMStr(Result).value := '-' + TMStr(Result).value ;
end;
end;
//Int の時
'$','0'..'9','=','%','+'{明示的な+}:
begin
if sp.ptr^ = '=' then Inc(sp.ptr);
Result := Self.getInt(sp) ;
end;
//l のとき
'!':
begin
Inc(sp.ptr); // skip !
Result := TMInt.Create ;
TMInt(Result).value := GetNoteLength(sp, False,
(FMmlBase as TMmlSystem).CurTrack.Length.GetValue);
end;
//計算式&配列のとき
'(': subKakko;
//文字列
'{': subString;
'"': subString2;
//アルファベットのとき
'A'..'Z','a'..'z','#','_':
begin
if CalcMode = False then begin Exit; end;
Result := (FMmlBase as TMmlSystem).GetVariable(sp);
end;
else
begin
//Result := nil;
Exit;
end;
end;
end;
function TMmlTokenBase.GetNoteLength(var sp: TSrcPos;
stepmode: Boolean; def: Integer): Integer;
var
vi: Integer;
function getOne: Integer;
var
mv: TMVarCustom;
v: Extended;
stepm: Boolean;
procedure huten;
var el,divLen:Extended ;
begin
//付点の処理
el := 1;
divLen := 0.5;
while sp.ptr^ = '.' do
begin
Inc(sp.ptr);
el := el + divLen;
divLen := divLen / 2;
end;
v := v*el;
end;
begin
//値の取得
skipSpace(sp.ptr);
if not (sp.ptr^ in ['!','$','%','0'..'9','(']) then //省略されたときは、デフォルトを返す
begin
v := def; huten; Result := Trunc(v);
Exit;
end;
v := 0;
try
mv := getArg(sp, False);
except
raise EMml.Create(TMmlSystem(FMmlBase).ErrMsg(MML_ERR_SYNTAX+'音長の指定。',sp));
end;
try
if mv = nil then raise EMml.CreateFmt(TMmlSystem(FMmlBase).ErrMsg(MML_ERR_CANT_READ_INT_VALUE,sp),[sp.cmd]);
if mv.ClassType = TMInt then
begin
//StepModeの判別
if TMInt(mv).Flag = '%' then stepm := not stepmode else stepm := stepmode;
if stepm then
begin
v := TMInt(mv).value
end else begin
v := TMInt(mv).value ;
v := TMmlSystem(FMmlBase).NtoStep(Trunc(v));
end;
end else
begin
//
if stepmode then
v := mv.IntValue
else
v := TMmlSystem(FMmlBase).NtoStep(mv.IntValue);
end;
finally
mv.Free ;
end;
huten;
Result := Trunc(v);
end;
begin
vi := getOne;
//タイの処理・・・
while True do
begin
//タイがあるか?
skipSpaceReturn(sp.ptr, sp.lineNo);
//skipSpace(sp.ptr);
if sp.ptr^ in ['^','+'] then
begin
Inc(sp.ptr);
vi := vi + getOne;
end else
if sp.ptr^ = '-' then
begin
Inc(sp.ptr);
vi := vi - getOne;
end else
Break;
end;
Result := vi;
end;
function TMmlTokenBase.GetArgCalc(var sp: TSrcPos): TMVarCustom;
var
temp: TSrcPos;
procedure CalcArg;
var
stack: TMStack;
enzansi: string;
ppp: PChar;
begin
stack := TMStack.Create ;
try
try
//初めに取得した値を加える
stack.Add(Result);
while sp.ptr^ in ENZANSI_CHAR do
begin
//演算子を取得
ppp := sp.ptr;
enzansi := sp.ptr^;
if (sp.ptr^ in ENZANSI_NEXT_CHAR)and((sp.ptr+1)^ in ENZANSI_NEXT_CHAR) then
begin
enzansi := enzansi + (sp.ptr+1)^;
Inc(sp.ptr);
end;
stack.Add( CreateEnzansi(enzansi) );
Inc(sp.ptr);//inc enzansi
//項を取得
Result := GetArg(sp, True);
if Result = nil then
begin
//後ろが計算式だと思ったけど、違ったようなので、
//ポインタを元に戻す
sp.ptr := ppp;
stack.Delete(stack.Count -1);
(FMmlBase as TMmlSystem).ShowHint(Format('式の直後に演算子`%s`があったので、誤動作を起こす恐れがあります。',[enzansi]),sp);
Break;
end else begin
stack.Add(Result);
end;
skipSpaceCalc(sp.ptr);
end;
//スタックに得た計算式を計算する
Result := CalcTMStack( stack );
except
on e: Exception do
raise EParserError.Create(e.Message);
end;
finally
stack.Free ;
end;
end;
begin
//1つめの値を得る
Result := GetArg(sp, True);
if Result = nil then Exit;
//skipSpace(sp.ptr); // <- '|'がスキップされてしまう場合がある
while sp.ptr^ in [#9, ' '] do Inc(sp.ptr);
//値の後ろに計算式があれば計算する
if Result.ClassType = TMStr then //文字列で計算できるのは、+ = ! だけ
begin
if not (sp.ptr^ in ['+','=','!']) then Exit;
end else
if not(sp.ptr^ in ENZANSI_CHAR) then Exit;//演算子がないから、抜ける
//実際に計算
temp := TSrcPos.Create ;
try
try
temp.Assign(sp);
CalcArg;
except
on e: Exception do
begin
raise EMml.Create((FMmlBase as TMmlSystem).ErrMsg(MML_ERR_SYSTEM+e.Message, temp));
end;
end;
finally
temp.Free ;
end;
end;
function TMmlTokenBase.GetInt(var sp: TSrcPos): TMInt;
var
s: string;
// n: Integer;
sign: Integer;
v: TMVarCustom;
begin
skipSpace(sp.ptr);
//--------------------------------------------------
//前置記号 ('-','+')
sign := 1;
if sp.ptr^ ='-' then
begin
Inc(sp.ptr); sign := -1;
end else
if sp.ptr^ = '+' then
begin
Inc(sp.ptr);
end;
Result := TMInt.Create;
if sp.ptr^ = '%' then //フラグセット
begin
Result.Flag := '%'; Inc(sp.ptr);
v := GetArg(sp, False);
if v<>nil then Result.value := v.IntValue ;
Exit;
end;
//--------------------------------------------------
//変数なのか?
if sp.ptr^ in ['A'..'Z','a'..'z','_'] then
begin
v := (FMmlBase as TMmlSystem).GetVariable(sp);
try
Result.value := v.IntValue ;
finally
v.Free ;
end;
Exit;
end;
if sp.ptr^ = '(' then
begin
v := GetArg(sp, False);
if v<>nil then Result.value := v.IntValue ;
Exit;
end;
if sp.ptr^ = '!' then //(n)分音符指定
begin
Inc(sp.ptr);
{s := mml_token.GetNumber( sp.ptr );
n := StrToInt( s );
//全音符のタイムベースを得て、n分音符で割る
Result.value := (FMmlBase as TMmlSystem).NtoStep(n);}
Result.value := GetNoteLength(sp, (not(FMmlBase as TMmlSystem).CurTrack.Stepmode),0);
end else
begin
s := GetNumber( sp.ptr );
Result.value := StrToIntDef( s, 0 ) * sign;
end;
end;
function TMmlTokenBase.GetArgs(var sp: TSrcPos; varType: string): TMArray;
procedure getKakko;
var s: string; sp2: TSrcPos;
begin
s := GetMaruKakko(sp.ptr, sp.lineNo);
if (varType='s')and(Copy(s,1,1)<>'{') then
begin
if Pos(',',s)=0 then
begin
s := '{' + s + '}';
end;
end;
sp2 := TSrcPos.Create ;
try
sp2.Assign(sp);
sp2.SetTempSource('='+s);
Result := GetArgs(sp2, varType);
finally
sp2.Free ;
end;
end;
function skipCommaOrBreak: Boolean;
begin
skipSpace(sp.ptr);
if (sp.ptr^ in (FMmlBase as TMmlSystem).ValueSplitChar)and(sp.ptr^ <> #0) then //続きがあるか判別
begin
Inc(sp.ptr);
while sp.ptr^ in [#13,#10] do Inc(sp.ptr);
Result := False;
end else begin
Result := True;
end;
end;
procedure getArray;
var v: TMVarCustom;
begin
skipSpace(sp.ptr);
if sp.ptr^ = #0 then Exit;
repeat // カンマがなくなるまで繰り返す
if sp.ptr^ = '(' then
begin
v := GetArgs(sp, 'a');
Result.AddArray(v as TMArray);
end else
begin
v := GetArgCalc(sp);
if (v<>nil)and(v.ClassType = TMArray) then
begin // 値を展開する
Result.AddArray(v as TMArray);
end else
begin
Result.Add(v) ;
end;
end;
skipSpace(sp.ptr);
until skipCommaOrBreak;
end;
var
i: Integer;
v: TMVarCustom;
begin
//読み取りが出来るかどうか判断
skipSpace(sp.ptr);
case sp.ptr^ of
'(': begin getKakko; Exit; end;
'=':
begin
Inc(sp.ptr);
end;
'%','!','$','0'..'9','{','-':;//数値,文字列ならOK
else
begin
Result := nil; Exit;
end;
end;
Result := TMArray.Create ;
//自由形か?
if varType='' then begin
getArray; Exit;
end;
//引数を一つずつ得る(型指定あり)
for i:=1 to Length(varType) do
begin
case varType[i] of
'i':
begin
v := GetArgCalc(sp);
if v=nil then
begin
v := TMInt.Create ;
Result.Add(v);
end else begin
Result.Add( v );
end;
end;
's':
begin
v := GetArgCalc(sp);
if v=nil then
begin
v := TMStr.Create ;
Result.Add(v);
end else begin
Result.Add( v );
end;
end;
'a':
begin
getArray;
Break;
end;
end;
if skipCommaOrBreak then Break; //カンマがなければループを終了する
end;
end;
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program PBCPOINT;
Const
maxXY =1000;
Type
PNode =^TNode;
TNode =Record
u,v :SmallInt;
Link :PNode;
end;
Var
Front,Rear :PNode;
FreeR,FreeC :Array[-maxXY..maxXY] of Boolean;
MinR,MaxR,MinC,MaxC :Array[-maxXY..maxXY] of SmallInt;
InQueue :Array[-maxXY..maxXY,-maxXY..maxXY] of Boolean;
res :LongInt;
procedure Push(u,v :SmallInt);
var
P :PNode;
begin
New(P); P^.u:=u; P^.v:=v; P^.Link:=nil;
if (Front=nil) then Front:=P else Rear^.Link:=P;
Rear:=P;
end;
function Pop :PNode;
begin
Pop:=Front; Front:=Front^.Link;
end;
procedure Enter;
var
n,i :LongInt;
u,v :SmallInt;
begin
FillChar(InQueue,SizeOf(InQueue),true);
Read(n);
Front:=nil;
for i:=1 to n do
begin
Read(u,v);
if (InQueue[u,v]) then
begin
InQueue[u,v]:=false; Push(u,v);
end;
end;
FillChar(FreeR,SizeOf(FreeR),true); FreeC:=FreeR;
end;
procedure Solve;
var
P :PNode;
u,v,x :SmallInt;
begin
res:=0;
repeat
Inc(res); P:=Pop; u:=P^.u; v:=P^.v; Dispose(P);
if (FreeR[u]) then
begin
FreeR[u]:=false; MinR[u]:=v; MaxR[u]:=v;
end
else
begin
if (v<MinR[u]) then
begin
for x:=v+1 to MinR[u]-1 do
if (InQueue[u,x]) then
begin
InQueue[u,x]:=false; Push(u,x);
end;
MinR[u]:=v;
end;
if (v>MaxR[u]) then
begin
for x:=MaxR[u]+1 to v-1 do
if (InQueue[u,x]) then
begin
InQueue[u,x]:=false; Push(u,x);
end;
MaxR[u]:=v;
end;
end;
if (FreeC[v]) then
begin
FreeC[v]:=false; MinC[v]:=u; MaxC[v]:=u;
end
else
begin
if (u<MinC[v]) then
begin
for x:=u+1 to MinC[v]-1 do
if (InQueue[x,v]) then
begin
InQueue[x,v]:=false; Push(x,v);
end;
MinC[v]:=u;
end;
if (u>MaxC[v]) then
begin
for x:=MaxC[v]+1 to u-1 do
if (InQueue[x,v]) then
begin
InQueue[x,v]:=false; Push(x,v);
end;
MaxC[v]:=u;
end;
end;
until (Front=nil);
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Enter;
Solve;
Write(res);
Close(Input); Close(Output);
End. |
unit jakozememo;
//(c) Martin Tichacek mti@mrp.cz
// verze
// 1 ... zacalo cislovani ...
// 2 ... zjistovani vysky pisma , hledani
// 3 ... pridan "jazyk" :-P
// 4 ... moznost zvolit jiny jazyk za behu....
// moznost vlastnich polozek v popupu a reakce na ne.
// 5 ... mazani vety a celeho seznamu...
// 6 ... pokus o opravu refreshe (scrollbar-scroll - prekresloval pozde) pod GTK2
// setrnejsi clipboard...
// 7 ... hm... oznacovani bloku bylo taky spetne - chybel refresh..
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls,menus,Clipbrd;
const jazyk=1; // 0 cz , 1 en (nic vic zatim..., netreba menit tu, objekt "umi" zmenu za provozu)
const mpv=100000; // max pocet polozek... je to malo?
Type Tveta=record
te:string; // kus textu
bpi:TColor; // barva pisma
bpo:Tcolor; // barva podkladu
pom:longint;
end;
Pveta=^Tveta;
Tvety=array[0..mpv] of Pveta;
type
Tjakomemo = class(TPanel)
public
// vlastnosti "bezneho" panelu sem neprepsal... co s tim udedelate je vas risk :-)
oncclick:procedure(kam:longint;mb:TmouseButton;ms:TShiftState) of object;
oncdblclick:procedure(kam:longint;mb:TmouseButton;ms:TShiftState) of object;
on_vlastni_popup:procedure(kam:longint;bs:boolean;b1,b2:longint;c_tag:longint) of object;
{obsluha vlastnich radku v popup menu}
barva_bloku_pod:Tcolor; // default clHighlight
barva_bloku_pis:Tcolor; // default clHighlightText
autoscroll:boolean; // default false
{pokud true, bude se automaticky scrollovat na pozici , kam bylo vlozeno}
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
function pridej_vetu(te:string;bpi,bpo:Tcolor;pom:longint):boolean;
{ vrazi text na konec seznamu , v pripade neuspechu vraci false
bpi - barva pisma , bpo - barva podkladu ; pom - pomocne cifro - na libovolne pouziti }
function vloz_vetu(te:string;bpi,bpo:Tcolor;pom:longint;kam:longint):boolean;
{ kam - pozice kam vlozit radek textu; zacatek je 0,
jinak totez co pridej_vetu
... pridat na konec je posledniveta+1
}
function prepis_vetu(te:string;bpi,bpo:Tcolor;pom:longint;kam:longint;msk:longint):boolean;
{zmeni (prepise) EXISTUJICI vetu
bity v msk: 0 - te , 1 bpi , 2 bpo ....
kde je 0, tak zustane nezmeneno
}
function smaz_vetu(kam:longint):boolean;
{ ... ehm ... smaze vetu. He? (kam - kterou) , vraci false, pokud selze }
procedure smaz_vse;
{ ... vsechny vety ... }
function cti_vetu(var te:string;var bpi,bpo:Tcolor;var pom:longint;kam:longint):boolean;
{protikus k prepis_vetu}
function posledniveta:longint;
{cislo posledni PLATNE vety. prvni je na pozici 0, pocet vet je (posledniveta+1) }
procedure zakaz_kresleni(st:boolean);
{st=true - zakaze kresleni, false povoli. Pouzivat pri velkych zmenach v seznamech
mohlo (bud tam mam nekde chybu nebo to nema vliv.(!)) by urychlit pridavani velkeho
mnozstvi polozek najednou tim, ze si zakazete prekreslovani polozek a povolite
ho az na konci.
uvnitr zakazu je integer, takze pokud neco 2x zakazete, musite to zase 2x povolit.
po povoleni kresleni je prekresleno zrovna.
}
function jevbloku(num:longint):boolean;
{ vraci true, pokud je polozka cislo "num" ve vybranem bloku }
procedure nastav_font(f:TFont);
{ pokusi se nastavit font... hm}
function hledej(co:string;odkud:longint;smer_dolu:boolean;cely_radek:boolean):longint;
{ vrati -1, pokud nenajde, he? :-) }
procedure poskroluj(kam:longint);
{ naskroluje na radek... priblizne }
procedure nastav_jazyk(j:longint);
{ pouzitelne i jako "reset" popupu - promaze obsah menu a pak teprve nahraje nove polozky
mel-li tam nekdo vlastni, musi si je nasledne zase pridat
}
procedure prikrm_popup(c_text:string;c_tag:longint);
{ prida polozku na KONEC popup menu (za standardni veci),
v pripade, ze je uzivatel zvoli, dostanete vedet pomoci "on_vlastni_popup"
tag pod 10 budu mazat, aby se nekdo necpal do standardnich...
separator je '-' (jeden znak minus) v c_text, ale kto to dnes potrebuje vedet?
}
private
sbs,sbv:Tscrollbar; {scrollbar svisly/vodorovny}
pab:Tpaintbox;
pop:TPopupMenu;
uzmam_pop:boolean;
jazy_int:longint;
bl1,bl2:longint; {zacatek,konec bloku}
bls:boolean; {je neco vybrane...?}
refr_en:longint; {pokud 0, tak je kresleni povoleno, je li vetsi, tak se neprekresluje paintbox}
mx,my:longint; {posledni znama pozice mysi}
mx1,my1:longint; { zalozni pozce mysi - pri mouse down }
mb:TMouseButton;
ms:TShiftState;
vety:Tvety;
vetp:longint; {posledni pouzita veta}
vyska_radku:longint;
procedure jmonpaint(sender:Tobject);
procedure aktualizujpozici(sender:Tobject);
property OnResize;
procedure sbscrll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer); // scrollbarsvislyscroll....
procedure mys_pohyb(Sender: TObject;Shift: TShiftState; X,Y: Integer);
procedure mys_zmack(Sender: TObject;Button: TMouseButton;Shift: TShiftState; X,Y: Integer);
procedure mys_zmack1(Sender: TObject;Button: TMouseButton;Shift: TShiftState; X,Y: Integer);
procedure mys_WheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
procedure mys_WheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
function my_2_index(z:longint):longint;
procedure generuj_klik(Sender: TObject; X,Y: Integer;Button: TMouseButton;Shift: TShiftState);
procedure priselpopup(sender:Tobject);
procedure nactiblok(var b1,b2:longint);
// procedure mys_click(sender:Tobject);
procedure mys_dclick_in(sender:Tobject);
procedure postav_obsah_popupa(p:Tpopupmenu);
{ [je-li co, tak prvni vse smaze a znovu] nakrmi popup menu polozkama dle akt. jazyka. }
function dt(celytext:string):string;
end;
{
const text_Vybrat_vse:string='Vybrat vse';
const text_Zrusit_vyber:string='Zrusit vyber';
const text_Zacatek_bloku:string='Zacatek bloku';
const text_Konec_bloku:string='Konec bloku';
const text_Kopirovat:string='Kopirovat';
}
const text_Vybrat_vse:string='Vybrat vse|Select all';
const text_Zrusit_vyber:string='Zrusit vyber|Select none';
const text_Zacatek_bloku:string='Zacatek bloku|Start of selection';
const text_Konec_bloku:string='Konec bloku|End of selection';
const text_Kopirovat:string='Kopirovat|Copy';
implementation
constructor Tjakomemo.Create(TheOwner: TComponent);
begin
inherited create(theowner);
oncclick:=nil;
oncdblclick:=nil;
on_vlastni_popup:=nil;
uzmam_pop:=false;
jazy_int:=jazyk;
autoscroll:=false;
refr_en:=0;
DoubleBuffered:=true;
caption:='';
pab:=Tpaintbox.Create(self);
pab.parent:=self;
barva_bloku_pod:=clHighlight;
barva_bloku_pis:=clHighlightText;
sbs:=Tscrollbar.create(self);
sbs.parent:=self;
sbs.name:='sbs';
sbs.Kind:=sbVertical;
sbs.pagesize:=1;
sbv:=Tscrollbar.create(self);
sbv.parent:=self;
sbv.name:='sbv';
sbv.Kind:=sbHorizontal;
sbv.pagesize:=1;
pab.onpaint:=@jmonpaint;
onresize:=@aktualizujpozici;
mx:=0;
my:=0;
mb:=mbLeft;
ms:=[];
pab.OnMouseDown:=@mys_zmack1;
pab.OnMouseUp:=@mys_zmack;
pab.OnMouseMove:=@mys_pohyb;
pab.OnDblClick:=@mys_dclick_in;
pab.OnMouseWheelUp:= @mys_Wheelup;
pab.OnMouseWheelDown:= @mys_WheelDown;
// pab.Font.Pitch:=fpfixed;
// pab.Canvas.Font.pitch:=fpFixed;
sbs.OnScroll:=@sbscrll;
sbv.OnScroll:=@sbscrll;
vyska_radku:=20;
fillchar(vety,sizeof(vety),0);
vetp:=-1;
pop:=Tpopupmenu.Create(self);
pop.parent:=self;
postav_obsah_popupa(pop);
pab.PopupMenu:=pop;
bls:=false;
bl1:=4;
bl2:=10;
aktualizujpozici(nil);
end;
destructor Tjakomemo.Destroy;
var z:longint;
begin
for z:=0 to vetp do
if vety[z]<>nil then
begin
dispose(vety[z]);
vety[z]:=nil;
end;
sbv.destroy;
sbs.destroy;
pab.PopupMenu:=nil;
pop.destroy;
pab.destroy;
inherited destroy;
end;
function Tjakomemo.dt(celytext:string):string;
var aaa:string;
ja:longint;
begin
ja:=jazy_int;
if ja<0 then ja:=0;
aaa:=celytext;
while ja>0 do
begin aaa:=copy(aaa,pos('|',aaa)+1,length(aaa));ja:=ja-1;end;
if length(aaa)=0 then aaa:=celytext; { pokud by byl zvoleny jazyk ZA poctem prelozenych..., vratim prvni mozny}
if pos('|',aaa)<>0 then aaa:=copy(aaa,1,pos('|',aaa)-1);
dt:=aaa;
end;
procedure Tjakomemo.prikrm_popup(c_text:string;c_tag:longint);
var mi:Tmenuitem;
begin
if c_tag<10 then c_tag:=0;
mi:=Tmenuitem.create(pop);
mi.Caption:=c_text;
mi.OnClick:=@priselpopup;
mi.tag:=c_tag;
pop.Items.Add(mi);
end;
procedure Tjakomemo.postav_obsah_popupa(p:Tpopupmenu);
var mi:Tmenuitem;
begin
if uzmam_pop then
while pop.Items.Count>0 do pop.Items.Delete(0);
uzmam_pop:=true;
mi:=Tmenuitem.create(pop);
mi.Caption:=dt(text_Vybrat_vse);
mi.OnClick:=@priselpopup;
mi.tag:=1;
pop.Items.Add(mi);
mi:=Tmenuitem.create(pop);
mi.Caption:=dt(text_Zrusit_vyber);
mi.OnClick:=@priselpopup;
mi.tag:=2;
pop.Items.Add(mi);
mi:=Tmenuitem.create(pop);
mi.Caption:=dt(text_Zacatek_bloku);
mi.OnClick:=@priselpopup;
mi.tag:=3;
pop.Items.Add(mi);
mi:=Tmenuitem.create(pop);
mi.Caption:=dt(text_Konec_bloku);
mi.OnClick:=@priselpopup;
mi.tag:=4;
pop.Items.Add(mi);
mi:=Tmenuitem.create(pop);
mi.Caption:='-';
mi.OnClick:=nil;
mi.tag:=0;
pop.Items.Add(mi);
mi:=Tmenuitem.create(pop);
mi.Caption:=dt(text_Kopirovat);
mi.OnClick:=@priselpopup;
mi.tag:=5;
pop.Items.Add(mi);
end;
procedure Tjakomemo.nastav_jazyk(j:longint);
begin
jazy_int:=j;
postav_obsah_popupa(pop);
end;
procedure Tjakomemo.priselpopup(sender:Tobject);
var z,x,c,v:longint;
ua:string;
begin
z:=Tmenuitem(sender).tag;
case z of
1: begin bls:=true;bl1:=0;bl2:=vetp;if refr_en=0 then pab.Refresh;end;
2: begin bls:=false;if refr_en=0 then pab.Refresh;end;
3: begin bls:=true;x:=my_2_index(my);bl1:=x;bl2:=x;if refr_en=0 then pab.Refresh; end;
4: begin
if bls then
begin x:=my_2_index(my);bl2:=x; end
else
begin bls:=true;x:=my_2_index(my);bl1:=x;bl2:=x; end;
if refr_en=0 then pab.Refresh;
end;
5: begin
Clipboard.Clear;
if bls then
begin
nactiblok(x,c);
ua:='';
for v:=x to c do ua:=ua+vety[v]^.te+#13#10;
Clipboard.astext:=ua;
end;
end
else
if (z>=10) and (on_vlastni_popup<>nil) then
on_vlastni_popup(my_2_index(my),bls,bl1,bl2,z);
end;
end;
procedure Tjakomemo.nactiblok(var b1,b2:longint);
begin
if bl1>bl2 then begin b1:=bl2;b2:=bl1 end
else begin b1:=bl1;b2:=bl2 end;
end;
function Tjakomemo.pridej_vetu(te:string;bpi,bpo:Tcolor;pom:longint):boolean;
var z:longint;
begin
result:=true;
if vetp>=mpv then begin Result:=false; exit end; {!!!}
inc(vetp);
new(vety[vetp]);
vety[vetp]^.te:=te;
vety[vetp]^.bpi:=bpi;
vety[vetp]^.bpo:=bpo;
vety[vetp]^.pom:=pom;
aktualizujpozici(self);
if autoscroll then
begin
z:=sbs.Max;
sbs.Position:=z;
end;
if refr_en=0 then pab.Refresh;
end;
function Tjakomemo.smaz_vetu(kam:longint):boolean;
var z:longint;
begin
result:=true;
if (kam<0) or (kam>vetp) or (vety[kam]=nil) then begin Result:=false; exit end; {!!!}
dispose(vety[kam]);
for z:=kam to vetp-1 do vety[z]:=vety[z+1];
vety[vetp]:=nil;
dec(vetp);
if bl1>=kam then dec(bl1);if bl1<0 then bl1:=0;
if bl2>=kam then dec(bl2);if bl2<0 then bl2:=0;
aktualizujpozici(self);
if refr_en=0 then pab.Refresh;
end;
procedure Tjakomemo.smaz_vse;
var z:longint;
begin
bls:=false;bl1:=0;bl2:=0;
for z:=0 to vetp do begin dispose(vety[z]);vety[z]:=nil; end;
vetp:=-1;
aktualizujpozici(self);
if refr_en=0 then pab.Refresh;
end;
function Tjakomemo.vloz_vetu(te:string;bpi,bpo:Tcolor;pom:longint;kam:longint):boolean;
var z:longint;
begin
result:=true;
if kam<0 then begin result:=false;exit;end;
if kam>vetp+1 then begin result:=false;exit;end;
if vetp>=mpv then begin Result:=false;exit end; {!!!}
inc(vetp);
for z:=vetp downto kam+1 do vety[z]:=vety[z-1];
new(vety[kam]);
vety[kam]^.te:=te;
vety[kam]^.bpi:=bpi;
vety[kam]^.bpo:=bpo;
vety[kam]^.pom:=pom;
aktualizujpozici(self);
if autoscroll then
begin
poskroluj(kam);
end;
if refr_en=0 then pab.Refresh;
end;
function Tjakomemo.prepis_vetu(te:string;bpi,bpo:Tcolor;pom:longint;kam:longint;msk:longint):boolean;
var z:longint;
begin
result:=true;
if kam<0 then begin result:=false;exit;end;
if kam>vetp then begin result:=false;exit;end;
if msk and 1=1 then vety[kam]^.te:=te;
if msk and 2=2 then vety[kam]^.bpi:=bpi;
if msk and 4=4 then vety[kam]^.bpo:=bpo;
if msk and 8=8 then vety[kam]^.pom:=pom;
// aktualizujpozici(self);
if autoscroll then
begin
z:=kam;
if z>sbs.Max then z:=sbs.Max else z:=kam;
sbs.Position:=z;
end;
if refr_en=0 then pab.Refresh;
end;
function Tjakomemo.cti_vetu(var te:string;var bpi,bpo:Tcolor;var pom:longint;kam:longint):boolean;
begin
result:=true;
if kam<0 then begin result:=false;exit;end;
if kam>vetp then begin result:=false;exit;end;
te:=vety[kam]^.te;
bpi:=vety[kam]^.bpi;
bpo:=vety[kam]^.bpo;
pom:=vety[kam]^.pom;
end;
function Tjakomemo.posledniveta:longint;
begin
posledniveta:=vetp;
end;
procedure Tjakomemo.aktualizujpozici(sender:Tobject);
var z:longint;
begin
sbs.left:=width-sbs.width-2;
sbs.top:=2;
sbs.height:=height-sbs.width-4;
sbv.Top:=height-sbv.height-2;
sbv.Left:=2;
sbv.Width:=width-sbv.height-4;
pab.left:=2;
pab.top:=2;
pab.Width:=sbs.left-4;
pab.height:=sbs.height-4;
sbs.Min:=0;
z:=(vetp-(pab.height div vyska_radku)+1);
if z<0 then z:=0;
sbs.Max:=z;
sbs.LargeChange:=pab.height div vyska_radku;
end;
procedure Tjakomemo.jmonpaint(sender:Tobject);
var z,x:longint;
b1,b2:TColor;
begin
if refr_en<>0 then exit;
x:=sbs.Position;
for z:=0 to pab.height div vyska_radku do
begin
if x+z<=vetp then
begin
if jevbloku(z+x) then
begin b1:=barva_bloku_pis;b2:=barva_bloku_pod;end
else
begin b2:=vety[z+x]^.bpo;b1:=vety[z+x]^.bpi;end;
pab.Canvas.Brush.Color:=b2;
pab.Canvas.FillRect(0,1+z*vyska_radku,width-1,1+(z+1)*vyska_radku-1);
pab.Canvas.font.Color:=b1;
// pab.Canvas.font.style:=[fsBold,fsItalic];
// pab.font.style:=[fsBold,fsItalic];
pab.Canvas.TextOut(5-sbv.Position*8,5+(z)*vyska_radku,vety[x+z]^.te);
end;
end;
end;
procedure Tjakomemo.sbscrll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
begin
// jmonpaint(sender);
if refr_en=0 then pab.Invalidate;
end;
procedure Tjakomemo.zakaz_kresleni(st:boolean);
begin
if st then
inc(refr_en)
else
if refr_en>0 then
dec(refr_en)
else
refr_en:=0;
if refr_en=0 then pab.Refresh;
end;
procedure Tjakomemo.mys_pohyb(Sender: TObject; Shift: TShiftState; X,Y: Integer);
var z:longint;
begin
mx:=x;
my:=y;
// mb:=button;
ms:=shift;
if (ssleft in shift) and (abs(my-my1)>5) then
begin
if not bls then
begin
bls:=true;
bl1:=my_2_index(my1);
bl2:=my_2_index(my);
if refr_en=0 then pab.Refresh;
end
else
begin
//bl1:=my_2_index(my1);
z:=bl2;
bl2:=my_2_index(my);
if z<>bl2 then
if refr_en=0 then pab.Refresh;
end;
end;
end;
procedure Tjakomemo.mys_zmack(Sender: TObject;Button: TMouseButton;Shift: TShiftState; X,Y: Integer);
begin
mx:=x;
my:=y;
mb:=button;
ms:=shift;
if (abs(mx-mx1)<2) and (abs(my-my1)<2) then
begin
generuj_klik(sender,mx,my,mb,ms);
end;
end;
procedure Tjakomemo.mys_zmack1(Sender: TObject;Button: TMouseButton;Shift: TShiftState;X,Y: Integer );
begin
mx:=x;
my:=y;
mx1:=x;
my1:=y;
mb:=button;
ms:=shift;
if bls and (ssleft in shift) then
begin
bls:=false;
if refr_en=0 then pab.Refresh;
end
else
end;
procedure Tjakomemo.generuj_klik(Sender: TObject; X,Y: Integer;Button: TMouseButton;Shift: TShiftState);
var z:longint;
begin
z:=my_2_index(my);
if oncclick<>nil then oncclick(z,mb,ms);
end;
function Tjakomemo.my_2_index(z:longint):longint;
begin
z:=(z-2) div vyska_radku+sbs.position;
if z>vetp then z:=vetp;
if z<0 then z:=0;
result:=z;
end;
function Tjakomemo.jevbloku(num:longint):boolean;
var z,x,c:longint;
begin
z:=bl1;
x:=bl2;
if z>x then begin c:=z;z:=x;x:=c end;
result:=bls and (num>=0) and (num<=vetp) and (num>=z) and (num<=x);
end;
procedure Tjakomemo.mys_dclick_in(sender:Tobject);
var z:longint;
begin
z:=my_2_index(my);
if oncdblclick<>nil then oncdblclick(z,mb,ms);
end;
procedure Tjakomemo.nastav_font(f:Tfont);
begin
pab.font:=f;
pab.canvas.Font:=f;
vyska_radku:=pab.canvas.TextHeight('WTIjpyg')+4;
// nebo si tu pridejte dalsi pismenka, ktere jsou nejak moc nad/pod prumer normalni vysky
aktualizujpozici(nil);
if refr_en=0 then pab.Refresh;
end;
procedure Tjakomemo.poskroluj(kam:longint);
var z:longint;
begin
if kam<0 then kam:=0;
if kam>vetp then kam:=vetp;
z:=kam;
if z>sbs.Max then z:=sbs.Max else z:=kam;
sbs.Position:=z;
if refr_en=0 then pab.Refresh;
end;
procedure Tjakomemo.mys_WheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
sbs.position:=sbs.position+1;
pab.refresh;
end;
procedure Tjakomemo.mys_Wheelup(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
sbs.position:=sbs.position-1;
pab.refresh;
end;
function Tjakomemo.hledej(co:string;odkud:longint;smer_dolu:boolean;cely_radek:boolean):longint;
var z,v:longint;
function je_to_tento(kery:longint):boolean;
begin
if (kery>=0) and (kery<=vetp) then
begin
if cely_radek then
je_to_tento:=co=vety[kery]^.te
else
je_to_tento:=pos(co,vety[kery]^.te)<>0;
end
else je_to_tento:=false;
end;
begin
z:=odkud;
if smer_dolu then v:=1 else v:=-1;
while (z>=0) and (z<=vetp) and (not je_to_tento(z)) do z:=z+v;
if je_to_tento(z) then hledej:=z else hledej:=-1;
end;
end.
|
unit TestPhisicsControllerUnit;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, PhisicsControllerUnit, ControllersUnit,
System.Generics.Collections, MenuUnit, MainUnit, Test1Unit, TestsUnit;
type
// Test methods for class PhisicsController
TestPhisicsController = class(TTestCase)
strict private
FPhisicsController: PhisicsController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestgetListAnswer;
procedure TestgetQuestCaption;
procedure TestsetTest;
procedure TestgetMenu;
procedure TestgetQuest;
procedure TestgetAnswer;
procedure TestgetCorrect;
end;
implementation
procedure TestPhisicsController.SetUp;
begin
FPhisicsController := PhisicsController.Create;
end;
procedure TestPhisicsController.TearDown;
begin
FPhisicsController.Free;
FPhisicsController := nil;
end;
procedure TestPhisicsController.TestsetTest;
var
caption: string;
ReturnValue1: TList<string>;
ReturnValue2: TList<string>;
begin
FPhisicsController.setTest('Test2');
caption := 'Test2';
FPhisicsController.setTest(caption);
CheckEquals(caption, 'Test2');
ReturnValue1 := FPhisicsController.getQuest;
CheckEquals(ReturnValue1.Items[0], 'Дайте определение материальной точки.');
CheckNotEquals(ReturnValue1.Items[0],
'Как определяется положение материальной точки?');
ReturnValue2 := FPhisicsController.getQuest;
CheckEquals(ReturnValue2.Items[1],
'Как определяется положение материальной точки?');
CheckNotEquals(ReturnValue2.Items[1],
'Дайте определение материальной точки.');
CheckNotEquals(ReturnValue1.Items[0], ReturnValue2.Items[1]);
end;
procedure TestPhisicsController.TestgetMenu;
var
ReturnValue: TList<string>;
begin
ReturnValue := FPhisicsController.getMenu;
// TODO: Validate method results
CheckEquals(ReturnValue.Items[0], 'Test2');
CheckEquals(ReturnValue.Items[1], 'Движение с постоянным ускорением');
CheckEquals(ReturnValue.Count, 2);
end;
procedure TestPhisicsController.TestgetQuest;
var
ReturnValue: TList<string>;
begin
ReturnValue := FPhisicsController.getQuest;
// TODO: Validate method results
end;
procedure TestPhisicsController.TestgetQuestCaption;
var
ReturnValue: TList<string>;
begin
FPhisicsController.setTest('Test2');
ReturnValue := FPhisicsController.getQuest;
CheckEquals(ReturnValue.Items[0], 'Дайте определение материальной точки.');
CheckNotEquals(ReturnValue.Items[0], '');
end;
procedure TestPhisicsController.TestgetAnswer;
var
ReturnValue: TList<string>;
begin
ReturnValue := FPhisicsController.getAnswer;
// TODO: Validate method results
end;
procedure TestPhisicsController.TestgetCorrect;
var
ReturnValue: TDictionary<integer, integer>;
begin
ReturnValue := FPhisicsController.getCorrect;
// TODO: Validate method results
end;
procedure TestPhisicsController.TestgetListAnswer;
var
ReturnValue: TList<string>;
// ReturnValue2: string;
begin
FPhisicsController.setTest('Test2');
// ReturnValue2 := FPhisicsController.getQuestCaption;
ReturnValue := FPhisicsController.getAnswer;
CheckEquals(ReturnValue.Items[0],
'абстрактный объект (модель), не имеющий размаер, но обладающий другими характеристиками ');
CheckNotEquals(ReturnValue.Items[0], 'yyyyyyyyyyyyyyy');
CheckEquals(ReturnValue.Items[1], '1');
CheckNotEquals(ReturnValue.Items[1], 'nnnnnnnnnnnn');
CheckEquals(ReturnValue.Count, 2);
CheckNotEquals(ReturnValue.Count, 3);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestPhisicsController.Suite);
end.
|
unit StopWatch;
interface
uses Windows, SysUtils, DateUtils;
Const MSecsPerSec = 1000;
type TStopWatch = class
private
fFrequency : TLargeInteger;
fIsRunning: boolean;
fIsHighResolution: boolean;
fStartCount, fStopCount : TLargeInteger;
procedure SetTickStamp(var lInt : TLargeInteger) ;
function GetElapsedTicks: TLargeInteger;
function GetElapsedMiliseconds: TLargeInteger;
public
function GetElapsedMicroSeconds: TLargeInteger;
constructor Create(const startOnCreate : boolean = false) ;
procedure Start;
procedure Stop;
property IsHighResolution : boolean read fIsHighResolution;
property ElapsedTicks : TLargeInteger read GetElapsedTicks;
property ElapsedMiliseconds : TLargeInteger read GetElapsedMiliseconds;
property ElapsedMicroseconds : TLargeInteger read GetElapsedMicroSeconds;
property IsRunning : boolean read fIsRunning;
end;
implementation
constructor TStopWatch.Create(const startOnCreate : boolean = false) ;
begin
inherited Create;
fIsRunning := false;
fIsHighResolution := QueryPerformanceFrequency(fFrequency) ;
if NOT fIsHighResolution then fFrequency := MSecsPerSec;
if startOnCreate then Start;
end;
function TStopWatch.GetElapsedTicks: TLargeInteger;
begin
result := fStopCount - fStartCount;
end;
procedure TStopWatch.SetTickStamp(var lInt : TLargeInteger) ;
begin
if fIsHighResolution then
QueryPerformanceCounter(lInt)
else
lInt := MilliSecondOf(Now) ;
end;
function TStopWatch.GetElapsedMicroSeconds: TLargeInteger;
begin
result := (MSecsPerSec * 1000 * (fStopCount - fStartCount)) div fFrequency;
end;
function TStopWatch.GetElapsedMiliseconds: TLargeInteger;
begin
result := (MSecsPerSec * (fStopCount - fStartCount)) div fFrequency;
end;
procedure TStopWatch.Start;
begin
SetTickStamp(fStartCount) ;
fIsRunning := true;
end;
procedure TStopWatch.Stop;
begin
SetTickStamp(fStopCount) ;
fIsRunning := false;
end;
end.
|
unit fPtSelDemog;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ORCtrls, fBase508Form, VA508AccessibilityManager;
type
TfrmPtSelDemog = class(TfrmBase508Form)
orapnlMain: TORAutoPanel;
lblSSN: TStaticText;
lblPtSSN: TStaticText;
lblDOB: TStaticText;
lblPtDOB: TStaticText;
lblPtSex: TStaticText;
lblPtVet: TStaticText;
lblPtSC: TStaticText;
lblLocation: TStaticText;
lblPtRoomBed: TStaticText;
lblPtLocation: TStaticText;
lblRoomBed: TStaticText;
lblPtName: TStaticText;
Memo: TCaptionMemo;
lblCombatVet: TStaticText;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure MemoEnter(Sender: TObject);
procedure MemoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
FLastDFN: string;
FOldWinProc :TWndMethod;
procedure NewWinProc(var Message: TMessage);
public
procedure ClearIDInfo;
procedure ShowDemog(ItemID: string);
procedure ToggleMemo;
end;
var
frmPtSelDemog: TfrmPtSelDemog;
implementation
uses rCore, VA508AccessibilityRouter, uCombatVet;
{$R *.DFM}
const
{ constants referencing the value of the tag property in components }
TAG_HIDE = 1; // labels to be hidden
TAG_CLEAR = 2; // labels to be cleared
procedure TfrmPtSelDemog.ClearIDInfo;
{ clears controls with patient ID info (controls have '2' in their Tag property }
var
i: Integer;
begin
FLastDFN := '';
with orapnlMain do
for i := 0 to ControlCount - 1 do
begin
if Controls[i].Tag = TAG_HIDE then Controls[i].Visible := False;
if Controls[i].Tag = TAG_CLEAR then with Controls[i] as TStaticText do Caption := '';
end;
Memo.Clear;
end;
procedure TfrmPtSelDemog.ShowDemog(ItemID: string);
{ gets a record of patient indentifying information from the server and displays it }
var
PtRec: TPtIDInfo;
i: Integer;
CV : TCombatVet;
begin
if ItemID = FLastDFN then Exit;
Memo.Clear;
FLastDFN := ItemID;
PtRec := GetPtIDInfo(ItemID);
with PtRec do
begin
Memo.Lines.Add(Name);
Memo.Lines.Add(lblSSN.Caption + ' ' + SSN + '.');
Memo.Lines.Add(lblDOB.Caption + ' ' + DOB + '.');
if Sex <> '' then
Memo.Lines.Add(Sex + '.');
if Vet <> '' then
Memo.Lines.Add(Vet + '.');
if SCsts <> '' then
Memo.Lines.Add(SCsts + '.');
if Location <> '' then
Memo.Lines.Add(lblLocation.Caption + ' ' + Location + '.');
if RoomBed <> '' then
Memo.Lines.Add(lblRoomBed.Caption + ' ' + RoomBed + '.');
lblPtName.Caption := Name;
lblPtSSN.Caption := SSN;
lblPtDOB.Caption := DOB;
lblPtSex.Caption := Sex {+ ', age ' + Age};
lblPtSC.Caption := SCSts;
lblPtVet.Caption := Vet;
lblPtLocation.Caption := Location;
lblPtRoomBed.Caption := RoomBed;
end;
with orapnlMain do for i := 0 to ControlCount - 1 do
if Controls[i].Tag = TAG_HIDE then Controls[i].Visible := True;
if lblPtLocation.Caption = '' then
lblLocation.Hide
else
lblLocation.Show;
if lblPtRoomBed.Caption = '' then
lblRoomBed.Hide
else
lblRoomBed.Show;
CV := TCombatVet.Create(ItemID);
if CV.IsEligible then begin
lblCombatVet.Caption := 'CV ' + CV.ExpirationDate + ' ' + CV.OEF_OIF;
Memo.Lines.Add(lblCombatVet.Caption);
end else
lblCombatVet.Caption := '';
CV.Free;
// Memo.SelectAll;
if ScreenReaderSystemActive then
begin
Memo.SelStart := 0;
GetScreenReader.Speak('Selected Patient Demographics');
GetScreenReader.Speak(Memo.Text);
end;
end;
procedure TfrmPtSelDemog.ToggleMemo;
begin
if Memo.Visible then
begin
Memo.Hide;
end
else
begin
Memo.Show;
Memo.BringToFront;
end;
end;
procedure TfrmPtSelDemog.FormCreate(Sender: TObject);
begin
FOldWinProc := orapnlMain.WindowProc;
orapnlMain.WindowProc := NewWinProc;
end;
procedure TfrmPtSelDemog.NewWinProc(var Message: TMessage);
const
Gap = 4;
MaxFont = 10;
var uHeight:integer;
begin
if(assigned(FOldWinProc)) then FOldWinProc(Message);
if(Message.Msg = WM_Size) then
begin
if(lblPtSSN.Left < (lblSSN.Left+lblSSN.Width+Gap)) then
lblPtSSN.Left := (lblSSN.Left+lblSSN.Width+Gap);
if(lblPtDOB.Left < (lblDOB.Left+lblDOB.Width+Gap)) then
lblPtDOB.Left := (lblDOB.Left+lblDOB.Width+Gap);
if(lblPtSSN.Left < lblPtDOB.Left) then
lblPtSSN.Left := lblPtDOB.Left
else
lblPtDOB.Left := lblPtSSN.Left;
if(lblPtLocation.Left < (lblLocation.Left+lblLocation.Width+Gap)) then
lblPtLocation.Left := (lblLocation.Left+lblLocation.Width+Gap);
if(lblPtRoomBed.Left < (lblRoomBed.Left+lblRoomBed.Width+Gap)) then
lblPtRoomBed.Left := (lblRoomBed.Left+lblRoomBed.Width+Gap);
if(lblPtLocation.Left < lblPtRoomBed.Left) then
lblPtLocation.Left := lblPtRoomBed.Left
else
lblPtRoomBed.Left := lblPtLocation.Left;
end;
if frmPtSelDemog.Canvas.Font.Size > MaxFont then
begin
uHeight := frmPtSelDemog.Canvas.TextHeight(lblPtSSN.Caption)-2;
lblPtSSN.Top := (lblPtName.Top + uHeight);
lblSSN.Top := lblPtSSN.Top;
lblPtDOB.Height := uHeight;
lblPtDOB.Top := (lblPtSSn.Top + uHeight);
lblDOB.Top := lblPtDOB.Top;
lblPtSex.Height := uHeight;
lblPtSex.Top := (lblPtDOB.Top + uHeight);
lblPtVet.Height := uHeight;
lblPtVet.Top := (lblPtSex.Top + uHeight);
lblPtSC.Height := uHeight;
lblPtSC.Top := lblPtVet.Top;
lblLocation.Height := uHeight;
lblLocation.Top := ( lblPtVet.Top + uHeight);
lblPtLocation.Top := lblLocation.Top;
lblRoomBed.Height := uHeight;
lblRoomBed.Top :=(lblLocation.Top + uHeight)+ 2;
lblPtRoomBed.Height := uHeight;
lblPtRoomBed.Top := lblRoomBed.Top ;
lblCombatVet.Top := (lblRoomBed.Top + uHeight) + 2;
end;
end;
procedure TfrmPtSelDemog.FormDestroy(Sender: TObject);
begin
orapnlMain.WindowProc := FOldWinProc;
end;
procedure TfrmPtSelDemog.FormShow(Sender: TObject);
begin
inherited;
lblCombatVet.Caption := '';
end;
procedure TfrmPtSelDemog.MemoEnter(Sender: TObject);
begin
inherited;
if ScreenReaderSystemActive then
begin
Memo.SelStart := 0;
GetScreenReader.Speak('Selected Patient Demographics');
GetScreenReader.Speak(Memo.Text);
end;
end;
procedure TfrmPtSelDemog.MemoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if ScreenReaderSystemActive then
begin
if Memo.SelStart = Memo.GetTextLen then
if ((Key = VK_DOWN) or (Key = VK_RIGHT)) then GetScreenReader.Speak('End of Data');
if Memo.SelStart = 0 then
if ((Key = VK_UP) or (Key = VK_LEFT)) then GetScreenReader.Speak('Start of Data')
end;
end;
initialization
SpecifyFormIsNotADialog(TfrmPtSelDemog);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ IndexFileName Property Editor Dialog }
{ }
{ Copyright (c) 1997-2001 Borland Software Corp. }
{ }
{*******************************************************}
unit Ixedit;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, DBTables, LibHelp;
type
TIndexFiles = class(TForm)
GroupBox1: TGroupBox;
ListBox1: TListBox;
Add: TButton;
Delete: TButton;
Ok: TButton;
Cancel: TButton;
Help: TButton;
Clear: TButton;
OpenDialog: TOpenDialog;
procedure ListBox1Click(Sender: TObject);
procedure AddClick(Sender: TObject);
procedure DeleteClick(Sender: TObject);
procedure ClearClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure HelpClick(Sender: TObject);
private
FTable: TTable;
FNoItems: Boolean;
FEmpty: string;
procedure AddEmpty;
function IsDBaseTable: Boolean;
procedure RemoveEmpty;
procedure SetButtons;
public
property Table: TTable read FTable;
property NoItems: Boolean read FNoItems;
end;
function EditIndexFiles(ATable: TTable; List: TStrings): Boolean;
implementation
{$R *.dfm}
uses BDE, bdeconst, TypInfo, DBConsts;
function GetPath(const Path: string): string;
var
Desc: DBDesc;
SAliasName: array [0..DBIMAXNAMELEN - 1] of char;
begin
if ExtractFileDir(Path) = '' then
begin
StrPLCopy(SAliasName, Path, SizeOf(SAliasName) - 1);
AnsiToOem(SAliasName, SAliasName);
if DbiGetDatabaseDesc(SAliasName, @Desc) = 0 then
if StrPas(Desc.szDbType) = 'STANDARD' then
Result := StrPas(Desc.szPhyName);
end
else Result := Path;
end;
function TIndexFiles.IsDBaseTable: Boolean;
begin
Result := (Table.TableType = ttDBase) or
(CompareText(ExtractFileExt(Table.TableName), '.DBF') = 0);
end;
function EditIndexFiles(ATable: TTable; List: TStrings): Boolean;
begin
Session.Open;
with TIndexFiles.Create(Application) do
try
FTable := ATable;
Caption := Format(SIndexFilesEditor,
[Table.Owner.Name, DotSep, Table.Name]);
if IsDBaseTable then ListBox1.Items.Assign(List)
else Add.Enabled := False;
OpenDialog.InitialDir := GetPath(Table.DatabaseName);
if ListBox1.Items.Count = 0 then AddEmpty;
SetButtons;
Result := ShowModal = mrOk;
if Result then
begin
RemoveEmpty;
List.Assign(ListBox1.Items);
end;
finally
Free;
end;
end;
procedure TIndexFiles.SetButtons;
var
I: Integer;
begin
if not IsDBaseTable then Exit;
Clear.Enabled := not NoItems;
if NoItems then Delete.Enabled := False
else with ListBox1 do
begin
for I := Items.Count - 1 downto 0 do
if Selected[I] then Break;
Delete.Enabled := I <> -1;
end;
end;
procedure TIndexFiles.ListBox1Click(Sender: TObject);
begin
SetButtons;
end;
procedure TIndexFiles.AddClick(Sender: TObject);
begin
with OpenDialog, ListBox1.Items do
if Execute then
begin
if IndexOf(FileName) = -1 then
begin
RemoveEmpty;
Add(ExtractFileName(FileName));
end;
SetButtons;
end;
end;
procedure TIndexFiles.AddEmpty;
begin
if not FNoItems then
begin
ListBox1.Items.Add(FEmpty);
FNoItems := True;
end;
end;
procedure TIndexFiles.RemoveEmpty;
begin
if FNoItems then
begin
ListBox1.Items.Delete(0);
FNoItems := False;
end;
end;
procedure TIndexFiles.DeleteClick(Sender: TObject);
var
I: Integer;
begin
with ListBox1 do
begin
for I := Items.Count - 1 downto 0 do
if Selected[I] then Items.Delete(I);
if Items.Count = 0 then AddEmpty;
end;
SetButtons;
end;
procedure TIndexFiles.ClearClick(Sender: TObject);
begin
with ListBox1 do
begin
Clear;
AddEmpty;
end;
SetButtons;
end;
procedure TIndexFiles.FormCreate(Sender: TObject);
begin
FEmpty := SNoIndexFiles;
HelpContext := hcDTableIndexEditor;
end;
procedure TIndexFiles.HelpClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
end.
|
unit Window;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, SDL2, Utility, gl, GLext, glu;
type
{ tGameWindow }
tGameWindow = class
{property} WindowHandle: pSDL_Window;
Surface: pSDL_Surface;
GLContext: tSDL_GLContext;
XRes: integer;
YRes: integer;
FOV: integer;
VisibleRange: longword;
constructor Create;
function Open(Title: ansistring; FullScreen: boolean = true;
x: integer = 0; y: integer = 0; width: integer = 0; height: integer = 0): integer;
function InitGL: integer;
procedure Update; inline;
destructor Destroy; override;
end;
implementation
{ tGameWindow }
constructor tGameWindow.Create;
begin
end;
function tGameWindow.Open(Title: ansistring; FullScreen: boolean = true; x: integer = 0;
y: integer = 0; width: integer = 0; height: integer = 0): integer;
var
flags: longword;
pc: pchar;
begin
XRes:= width;
YRes:= height;
FOV:= 100;
pc:= pchar(Title);
flags:= SDL_WINDOW_OPENGL or SDL_WINDOW_SHOWN;
if Fullscreen then flags:= flags or SDL_WINDOW_FULLSCREEN;
WindowHandle:= SDL_CreateWindow(pc, x, y, XRes, YRes, flags);
if WindowHandle = nil then
begin
Result:= -1; //error mngmnt to property?
WriteLog(emWnd);
WriteLog(SDL_GetError);
end
else
begin
Result:= 0;
Surface:= SDL_GetWindowSurface(WindowHandle);
if Surface = nil then
begin
WriteLog(emSrf);
WriteLog(SDL_GetError);
SDL_DestroyWindow(WindowHandle);
exit(-1);
end
else
GLContext:= SDL_GL_CreateContext(WindowHandle);
if GLContext = nil then
begin
WriteLog(emCtx);
WriteLog(SDL_GetError);
SDL_DestroyWindow(WindowHandle);
exit(-1);
end;
if InitGl <> 0 then
begin
WriteLog(emIgl);
SDL_DestroyWindow(WindowHandle);
exit(-1);
end;
SDL_UpdateWindowSurface(WindowHandle);
end;
//sdl_setwindowtitle
end;
function tGameWindow.InitGL: integer;
begin
VisibleRange:= 1000;
Load_gl_version_3_1;
glClearColor(0.0, 0.0, 0.0, 1);
glViewport(0, 0, XRes, YRes);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(FOV, XRes/YRes, 0.01, VisibleRange);
//glFrustum(left, right, -1, 1, 0.1, VisibleRange: GLdouble);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
{glTranslatef(0,0,0);
glRotatef(0,1,0,0);
glRotatef(0,0,1,0);
glRotatef(0,0,0,1); }
glPolygonMode(GL_FRONT, GL_LINE);
glClearDepth(VisibleRange);
//glEnable(GL_BLEND);
//glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
{ if Culling then glFrontFace(GL_CCW/cw) перед по/против час. стрелки
begin}
glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
{end;}
Result:= glGetError();
end;
procedure tGameWindow.Update;
begin
//SDL_UpdateWindowSurface(WindowHandle); //this causes flicker
SDL_GL_SwapWindow(WindowHandle);
end;
destructor tGameWindow.Destroy;
begin
SDL_DestroyWindow(WindowHandle);
end;
end.
|
unit Location;
interface
type
TLocation = class(TObject)
private
FLocationCode: string;
FLocationName: string;
FLocationType: string;
function GetIsServer: boolean;
public
property LocationCode: string read FLocationCode write FLocationCode;
property LocationName: string read FLocationName write FLocationName;
property LocationType: string read FLocationType write FLocationType;
property IsServer: boolean read GetIsServer;
end;
implementation
function TLocation.GetIsServer: boolean;
begin
Result := FLocationType = 'SVR';
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, ExtCtrls, XPMan, Menus;
type
TfrmMain = class(TForm)
lblPeriod: TLabel;
edtPeriod: TMaskEdit;
btnGo: TButton;
lblTimer: TLabel;
tmrMain: TTimer;
XPManifest: TXPManifest;
TrayIcon: TTrayIcon;
mmoText: TMemo;
mnuTray: TPopupMenu;
mniExit: TMenuItem;
procedure btnGoClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure tmrMainTimer(Sender: TObject);
procedure TrayIconClick(Sender: TObject);
procedure mniExitClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
FPeriod: Integer;
FCounter: Integer;
FCanClose: Boolean;
procedure ShowTime;
procedure Start;
procedure Signal;
procedure ReadList;
function GetIniPath: String;
function ReadIni: Boolean;
procedure WriteIni;
procedure OnMinimize(Sender: TObject);
procedure OnRestore(Sender: TObject);
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses IniFiles, Event, Database;
resourcestring
IniFileName = 'Timer.ini';
{$R *.dfm}
procedure TfrmMain.btnGoClick(Sender: TObject);
begin
if TryStrToInt(Trim(edtPeriod.Text), FPeriod) then begin
WriteIni;
Start;
end;
end;
procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := FCanClose;
if not FCanClose then
Application.Minimize;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
Application.OnMinimize := OnMinimize;
Application.OnRestore := OnRestore;
tmrMain.Enabled := False;
FCounter := 0;
ShowTime;
if ReadIni then begin
FCanClose := False;
Start;
end;
CreateTables;
ReadList;
Signal;
end;
function TfrmMain.GetIniPath: String;
begin
Result := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) + IniFileName;
end;
procedure TfrmMain.mniExitClick(Sender: TObject);
begin
FCanClose := True;
Close;
end;
procedure TfrmMain.OnMinimize(Sender: TObject);
begin
ShowWindow(Application.Handle, SW_HIDE);
end;
procedure TfrmMain.OnRestore(Sender: TObject);
begin
ShowWindow(Application.Handle, SW_SHOW);
Application.BringToFront;
end;
function TfrmMain.ReadIni: Boolean;
var
ini: TIniFile;
begin
Result := False;
try
try
ini := TIniFile.Create(GetIniPath);
FPeriod := ini.ReadInteger('Settings', 'Period', 15);
finally
FreeAndNil(ini);
end;
Result := FPeriod > 0;
except
end;
end;
procedure TfrmMain.ReadList;
begin
mmoText.Lines.Clear;
FetchList(mmoText.Lines, Now);
end;
procedure TfrmMain.ShowTime;
var
m, s: Integer;
begin
m := FCounter div 60;
s := FCounter mod 60;
if s < 10 then
lblTimer.Caption := Format('%u:0%u', [m, s])
else
lblTimer.Caption := Format('%u:%u', [m, s]);
end;
procedure TfrmMain.Signal;
var
th, act: String;
iil: Boolean;
begin
Application.Restore;
Activate;
if ShowEvent(th, act, iil) then begin
AddEvent(Now, th, act, iil);
ReadList;
end;
end;
procedure TfrmMain.Start;
begin
FCounter := 60 * FPeriod;
tmrMain.Enabled := True;
ShowTime;
end;
procedure TfrmMain.tmrMainTimer(Sender: TObject);
begin
Dec(FCounter);
ShowTime;
if FCounter = 0 then begin
tmrMain.Enabled := False;
Signal;
Start;
end;
end;
procedure TfrmMain.TrayIconClick(Sender: TObject);
begin
Application.Restore;
end;
procedure TfrmMain.WriteIni;
var
ini: TIniFile;
begin
try
try
ini := TIniFile.Create(GetIniPath);
ini.WriteInteger('Settings', 'Period', FPeriod);
ini.UpdateFile;
finally
FreeAndNil(ini);
end;
except
end;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
{/*
* (c) Copyright 1993, Silicon Graphics, Inc.
* 1993-1995 Microsoft Corporation
*
* ALL RIGHTS RESERVED
*/}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus,
Controls, Dialogs, SysUtils,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC : HDC;
hrc : HGLRC;
procedure SetDCPixelFormat;
end;
var
frmGL: TfrmGL;
rasters : Array [0..23] of GLUByte = (
$c0, $00, $c0, $00, $c0, $00, $c0, $00, $c0, $00,
$ff, $00, $ff, $00, $c0, $00, $c0, $00, $c0, $00,
$ff, $c0, $ff, $c0);
implementation
{$R *.DFM}
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
glClear(GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 0.0);
glRasterPos2f (20.5, 20.5);
glBitmap (10, 12, 0.0, 0.0, 12.0, 0.0, @rasters);
glBitmap (10, 12, 0.0, 0.0, 12.0, 0.0, @rasters);
glBitmap (10, 12, 0.0, 0.0, 12.0, 0.0, @rasters);
SwapBuffers(DC);
end;
{=======================================================================
Установка формата пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or
PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
glClearColor (0.3, 0.4, 0.6, 1.0);
glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
glOrtho (0.0, ClientWidth, 0.0, ClientHeight, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
end;
end.
|
{ Menu pour Mister Patate }
unit MrpMenu;
interface
uses MrpVga, MrpLoad, MrpPal, MrpKey, MrpStr, MrpCode, MrpTps, MrpSon;
const
Principal = 1;
PendantJeu = 2;
Option = 3;
ClavierOpt = 4;
EcranOpt = 5;
SonOpt = 6;
SonMove: array[0..4] of Byte = (130,0,3,1,0);
SonOk : array[0..4] of Byte = (100,0,3,1,0);
var
ResultMenu: Word;
{ ‚tat des couleurs du choix actif }
StatutColor: Byte;
{ Lance un menu }
procedure Menu (What: Word);
{ Initialise les menus }
procedure InitMenu;
implementation
var
{ Nombre de choix possible du menu }
NbrChoix: Byte;
{ Pour les couleurs }
SaveCounter: Word;
{ ‚tat du programme }
avancement: Byte;
procedure CaptureEcran;
var
F: file;
x, y: Word;
p: array[0..319] of Byte;
begin
Assign(F, 'Capture');
ReWrite(F, 1);
for y := 0 to HautScr-1 do begin
for x := 0 to 319 do
p[x] := GetPixel(2, x, y);
BlockWrite(F, p, 320);
end;
BlockWrite(F, Palette, sizeof(Palette));
Close(F);
end;
procedure PutMenu (Txt: String; PosCurseur: Word);
var
PosTxt: Byte;
Ligne: Byte;
TxtTmp: String;
Plus: Word;
begin
{ D‚termine le nombre de choix de 'Txt' }
NbrChoix := 0;
for PosTxt := 1 to Length (Txt) do if Txt[PosTxt] = '/' then inc (NbrChoix);
{ Affiche le fond }
PCopy (2, Page_not_display);
{ Affiche les menus }
for Ligne := 1 to NbrChoix do begin
PosTxt := Pos ('/', Txt);
TxtTmp := Copy (Txt, 1, PosTxt-1);
if Ligne = PosCurseur then begin
Plus := Counter shr 1;
if Plus and 8 <> 0 then Plus := Length(TxtTmp)*7 + 7 + (Plus and 7)
else Plus := Length(TxtTmp)*7 + 7 + (not Plus and 7);
OutText (Page_not_display, Centre - Plus, HautScr shr 1 - 14 -NbrChoix shl 3+Ligne shl 4, '', 244, 245, True);
OutText (Page_not_display, Centre + Plus, HautScr shr 1 - 14-NbrChoix shl 3+Ligne shl 4, '', 244, 245, True);
OutText (Page_not_display, Centre, HautScr shr 1 - 14 - NbrChoix shl 3 + Ligne shl 4, TxtTmp, 244, 245, True);
end else
OutText (Page_not_display, Centre, HautScr shr 1 - 14 - NbrChoix shl 3 + Ligne shl 4, TxtTmp, 242, 243, True);
Delete (Txt, 1, PosTxt);
end;
{ Affiche … l'‚cran }
ShowPage;
end;
procedure InitMenu;
var x, y: word;
begin
Music.EnAble := FALSE;
LoadMusic(2);
Music.OfsSound := Ofs(MusicNote);
Music.EnAble := TRUE;
if avancement = 0 then FillPalette (0,0,0)
else with Palette[7] do FillPalette (r,v,b);
LoadFont;
PCopy (2, Page_not_display);
ShowPage;
ConvertPalette;
StatutColor := 2;
avancement := 1;
end;
{ Active les couleur du choix s‚lectionn‚ }
procedure LoopColorMenu;
begin
if Counter = SaveCounter then exit;
SaveCounter := Counter;
with Palette[244] do case StatutColor of
0: begin inc (V,4); if V = 63 then StatutColor := 1; end;
1: begin dec (R,4); if R = 7 then StatutColor := 2; end;
2: begin inc (B,4); if B = 63 then StatutColor := 3; end;
3: begin dec (V,4); if V = 7 then StatutColor := 4; end;
4: begin inc (R,4); if R = 63 then StatutColor := 5; end;
5: begin dec (B,4); if B = 7 then StatutColor := 0; end;
end;
Palette[245].R := Palette[244].R - 5;
Palette[245].V := Palette[244].V - 5;
Palette[245].B := Palette[244].B - 5;
OutPalette (244, 245);
end;
procedure GetCode;
var
PosCode : Byte;
Plus : Byte;
CodeRead: array[0..3] of Byte;
i : Word;
Key : Char;
CodeTmp : Word;
begin
PosCode := 0;
FillChar (CodeRead, 4, 0);
repeat
{ Prend le charactŠre frapp‚s }
Key := InKey;
LoopColorMenu;
{ Affiche le fond }
PCopy (2, Page_not_display);
{ Affiche le code entr‚ }
for i := 0 to 3 do begin
if PosCode = i then begin
Plus := Counter shr 1;
if Plus and 8 <> 0 then Plus := Plus and 7
else Plus := not Plus and 7;
OutText (Page_not_display, 105 + i * 34, HautScr shr 1 -30 - Plus, '*', 244, 245, true);
OutText (Page_not_display, 105 + i * 34, HautScr shr 1 +20 + Plus, '*', 244, 245, true);
end;
BigPut (Page_not_display, 93 + i * 34, HautScr shr 1 -14, SpriteCode[CodeRead[i]]);
end;
{ D‚place le curseur ou le personnage }
case Key of
CharDroite: begin
PosCode := (PosCode + 1) and 3;
NewSound (5, 0, 0);
end;
CharGauche: begin
PosCode := (PosCode - 1) and 3;
NewSound (5, 0, 0);
end;
CharHaut : begin
CodeRead[PosCode] := (CodeRead[PosCode] - 1) and 7;
NewSound (7, 0, 3);
end;
CharBas : begin
CodeRead[PosCode] := (CodeRead[PosCode] + 1) and 7;
NewSound (7, 0, 3);
end;
CharEchap : exit;
end;
ShowPage;
until Key = CharEntree;
CodeTmp := 0;
asm
PUSH DS
LEA SI,[CodeRead]
MOV AX,SS
MOV DS,AX
MOV CL,9
XOR BX,BX
@LoopCode:
LODSB
CBW
SHL AX,CL
OR BX,AX
SUB CL,3
JNC @LoopCode
POP DS
MOV AX,BX
MOV [i],AX
MUL AX
MOV AL,AH
MOV AH,DL
MOV [CodeTmp],AX
end;
if i <> 0 then
begin
i := StageCode(CodeTmp);
if i = 0 then i := 16;
end
else i := StageCode(CodeTmp);
PCopy (2, Page_not_display);
if i = 16 then OutText (Page_not_display, Centre, Centre, '!FAUX CODE!', 242, 243, true)
else begin
OutText (Page_not_display, Centre, Centre-20, 'NIVEAU ' + Str (i+1,2), 242, 243, true);
if Length (Nom[i]) > 20 then begin
OutText (Page_not_display, Centre, Centre+8, StrPart1 (Nom[i]), 242, 243, true);
OutText (Page_not_display, Centre, Centre+27, StrPart2 (Nom[i]), 242, 243, true);
end else OutText (Page_not_display, Centre, Centre+20, Nom[i], 242, 243, true);
Niveau := i;
end;
ShowPage;
repeat until inkey = CharEntree;
end;
procedure Menu;
var
Curseur: Word;
Key: Char;
TxtMenu: String;
ConfigSave: array[0..8] of Word;
TmpModif: Boolean;
i: Byte;
begin
{ Positionne le curseur au d‚but }
Curseur := 1;
{ S‚lectionne le menu }
case What of
Principal : TxtMenu := 'JOUER/CODE/OPTION/CREDIT/QUITTER/';
PendantJeu: TxtMenu := 'REPRENDRE/OPTION/CAPTURE/RETOUR MENU/';
Option : TxtMenu := 'CLAVIER/SON/ECRAN/RETOUR/';
ClavierOpt: move (KeyMrp, ConfigSave, 18);
end;
{ Modification des configurations }
TmpModif := false;
repeat
case What of
ClavierOpt: TxtMenu := 'DROITE:' + NomTouche (ConfigSave[0]) + '/' +
'GAUCHE:' + NomTouche (ConfigSave[1]) + '/' +
'HAUT :' + NomTouche (ConfigSave[2]) + '/' +
'BAS :' + NomTouche (ConfigSave[3]) + '/' +
'SAUTE :' + NomTouche (ConfigSave[4]) + '/' +
'ACTION:' + NomTouche (ConfigSave[5]) + '/' +
'LANCE :' + NomTouche (ConfigSave[6]) + '/' +
'STATUT:' + NomTouche (ConfigSave[7]) + '/' +
'MENU :' + NomTouche (ConfigSave[8]) + '/' +
'PAR DEFAUT/RESTORE/RETOUR/';
EcranOpt:
begin
TxtMenu := 'STATUT PERMANENT ' + StrOk (StatutPerm) + '/' +
'ECRAN CENTRE ' + StrOk (Center) + '/' +
'LARGEUR ZONE MRP=' + StrE(Screen.Zone[1].H shl 1,3) + '/' +
'HAUTEUR ZONE MRP=' + StrE(Screen.Zone[1].V shl 1,3) + '/';
if Center then TxtMenu := TxtMenu +
'LARGEUR MINIZONE=' + StrE(Screen.Zone[2].H shl 1,3) + '/' +
'HAUTEUR MINIZONE=' + StrE(Screen.Zone[2].V shl 1,3) + '/'
else TxtMenu := TxtMenu +
'VITESSE X =' + StrE(Screen.SpeedH shl 1,3) + '/' +
'VITESSE Y =' + StrE(Screen.SpeedV shl 1,3) + '/';
TxtMenu := TxtMenu + 'RETOUR/';
end;
SonOpt: TxtMenu := 'EFFET SONORE ' + StrOk (SonOn) + '/' +
'VOLUME =' + StrE(VolumeSon,3) + '/' +
'MUSIQUE ' + StrOk (MusicOn) + '/' +
'VOLUME =' + StrE(VolumeMusic,3) + '/RETOUR/';
end;
{ Affiche le menu }
PutMenu (TxtMenu, Curseur);
{ Vide le buffer du clavier }
ClearKey;
{ Attend l'appuie d'une touche }
repeat
Key := InKey;
LoopColorMenu;
PutMenu (TxtMenu, Curseur);
until Key <> #0;
{ Traite la touche }
case Key of
CharHaut: begin
if Curseur > 1 then dec (Curseur) else Curseur := NbrChoix;
NewSound (7, 0, 3);
end;
CharBas : begin
if Curseur < NbrChoix then inc (Curseur) else Curseur := 1;
NewSound (7, 0, 3);
end;
CharPlus: begin
TmpModif := True;
if What = EcranOpt then with Screen do
begin
case Curseur of
3: if Zone[1].H < 160 then Inc(Zone[1].H);
4: if Zone[1].V < 100 then Inc(Zone[1].V);
5: if Center then
begin
if Zone[2].H < 160 then Inc(Zone[2].H);
if Zone[2].H > Zone[1].H then Zone[1].H := Zone[2].H;
end
else if SpeedH < 32 then Inc(SpeedH);
6: if Center then
begin
if Zone[2].V < 100 then Inc(Zone[2].V);
if Zone[2].V > Zone[1].V then Zone[1].V := Zone[2].V;
end
else if SpeedV < 32 then Inc(SpeedV);
end;
CalculScroll;
end else if What = SonOpt then case Curseur of
2: if VolumeSon < 63 then begin Inc(VolumeSon); SetVolumeSon; end;
4: if VolumeMusic < 63 then begin Inc(VolumeMusic); SetVolumeMusique; end;
end;
end;
CharMoins:begin
TmpModif := True;
if What = EcranOpt then with Screen do
begin
case Curseur of
3: begin
if Zone[1].H > 0 then Dec(Zone[1].H);
if Zone[2].H > Zone[1].H then Zone[2].H := Zone[1].H;
end;
4: begin
if Zone[1].V > 0 then Dec(Zone[1].V);
if Zone[2].V > Zone[1].V then Zone[2].V := Zone[1].V;
end;
5: if Center then
begin
if Zone[2].H > 0 then Dec(Zone[2].H);
end
else if SpeedH > 4 then Dec(SpeedH);
6: if Center then
begin
if Zone[2].V > 0 then Dec(Zone[2].V);
end
else if SpeedV > 4 then Dec(SpeedV);
end;
CalculScroll;
end else if What = SonOpt then case Curseur of
2: if VolumeSon > 0 then begin Dec(VolumeSon); SetVolumeSon; end;
4: if VolumeMusic > 0 then begin Dec(VolumeMusic); SetVolumeMusique; end;
end;
end;
CharEntree: begin
NewSound (5, 0, 0);
case What of
Principal: case Curseur of
1: exit;
2: GetCode;
3: Menu (Option);
5: begin if ModifConfig then SaveConfig; Halt; end;
end;
Option: case Curseur of
1: Menu (ClavierOpt);
2: Menu (SonOpt);
3: Menu (EcranOpt);
4: exit;
end;
PendantJeu: case Curseur of
1: begin ResultMenu := 0; exit; end;
2: Menu (Option);
3: CaptureEcran;
4: begin ResultMenu := 1; exit; end;
end;
ClavierOpt: case Curseur of
1..9: begin
PCopy (2, Page_not_display);
OutText (Page_not_display, Centre, Centre, 'APPUYEZ SUR UNE TOUCHE', 244, 245, true);
ShowPage;
while KeyPress do LoopColorMenu;
while not KeyPress do LoopColorMenu;
i := 0;
while not GetKey[i] do inc (i);
ConfigSave[Curseur-1] := i;
TmpModif := true;
ClearKey;
end;
10: begin
ConfigSave[0] := 205;
ConfigSave[1] := 203;
ConfigSave[2] := 200;
ConfigSave[3] := 208;
ConfigSave[4] := 56;
ConfigSave[5] := 57;
ConfigSave[6] := 29;
ConfigSave[7] := 28;
ConfigSave[8] := 1;
TmpModif := true;
end;
11: begin
move (KeyMrp, ConfigSave, 18);
TmpModif := false;
end;
12: begin
move (ConfigSave, KeyMrp, 18);
ModifConfig := ModifConfig or TmpModif;
exit;
end;
end;
SonOpt: case Curseur of
1: begin SonOn := not SonOn; TmpModif := true; end;
3: begin MusicOn := not MusicOn; TmpModif := true; end;
5: begin ModifConfig := ModifConfig or TmpModif; exit; end;
end;
EcranOpt: case Curseur of
1: begin StatutPerm := not StatutPerm; TmpModif := true; end;
2: begin Center := not Center; TmpModif := true; end;
7: begin ModifConfig := ModifConfig or TmpModif; exit; CalculScroll; end;
end;
end;
end;
end;
until false;
end;
end.
|
unit Dates;
interface
type
TDate = class
private
FDate: TDateTime;
public
constructor Create; overload;
constructor Create (Month, Day, Year: Integer); overload;
procedure SetValue (Month, Day, Year: Integer); overload;
procedure SetValue (NewDate: TDateTime); overload;
function LeapYear: Boolean;
procedure Increase (NumberOfDays: Integer = 1);
procedure Decrease (NumberOfDays: Integer = 1);
function GetText: string;
end;
implementation
uses
SysUtils, DateUtils;
constructor TDate.Create;
begin
FDate := Today;
end;
constructor TDate.Create (Month, Day, Year: Integer);
begin
FDate := EncodeDate (Year, Month, Day);
end;
procedure TDate.Decrease(NumberOfDays: Integer);
begin
FDate := FDate - NumberOfDays;
end;
procedure TDate.SetValue (Month, Day, Year: Integer);
begin
FDate := EncodeDate (Year, Month, Day);
end;
function TDate.GetText: string;
begin
Result := DateToStr (FDate);
end;
procedure TDate.Increase (NumberOfDays: Integer);
begin
FDate := FDate + NumberOfDays;
end;
function TDate.LeapYear: Boolean;
begin
// call IsLeapYear in SysUtils and YearOf in DateUtils
Result := IsLeapYear (YearOf (FDate));
end;
procedure TDate.SetValue(NewDate: TDateTime);
begin
FDate := NewDate;
end;
end.
|
unit U_WE_DiagramElement;
interface
uses
Classes, Windows, Graphics, SysUtils;
type
TDgMeterPhaseType = (dmptThree, dmptFour);
TDgMeterEnergyType = (dmetActive, dmetReactive);
TDgMeterPlugSign = (dmpsIa_in, dmpsUa, dmpsIa_out, dmpsIb_in, dmpsUb, dmpsIb_out,
dmpsIc_in, dmpsUc, dmpsIc_out, dmpsUn1, dmpsUn2);
type
TDgMeter = class
private
FCanvas: TCanvas;
FPos: TPoint;
FPhaseType: TDgMeterPhaseType;
FEnergyType: TdgMeterEnergyType;
FVisible: Boolean;
procedure DrawOutline;
procedure DrawPlugs;
procedure DrawDetail;
function GetHeight: Integer;
function GetWidth: Integer;
function GetPlugCount: Integer;
public
constructor Create(ACanvas: TCanvas);
procedure Draw;
function GetPlugPos(Index: Integer): TPoint; overload;
function GetPlugPos(APlugSign: TDgMeterPlugSign): TPoint; overload;
public
property Canvas: TCanvas read FCanvas write FCanvas;
property Pos: TPoint read FPos write FPos;
property Width: Integer read GetWidth;
property Height: Integer read GetHeight;
property PhaseType: TDgMeterPhaseType read FPhaseType write FPhaseType;
property EnergyType: TdgMeterEnergyType read FEnergyType write FEnergyType;
property PlugCount: Integer read GetPlugCount;
property Visible: Boolean read FVisible write FVisible default True;
end;
TDgCT = class
private
FCanvas: TCanvas;
FWindingPos: TPoint;
FWindingWidth: Integer;
FLeadLength: Integer;
FVisible: Boolean;
function GetLeftPlugPos: TPoint;
function GetRightPlugPos: TPoint;
public
constructor Create(ACanvas: TCanvas);
procedure Draw;
public
property Canvas: TCanvas read FCanvas write FCanvas;
property WindingPos: TPoint read FWindingPos write FWindingPos;
property WindingWidth: Integer read FWindingWidth write FWindingWidth;
property LeadLength: Integer read FLeadLength write FLeadLength;
property LeftPlugPos: TPoint read GetLeftPlugPos;
property RightPlugPos: TPoint read GetRightPlugPos;
property Visible: Boolean read FVisible write FVisible default True;
end;
TDgPT = class
private
FCanvas: TCanvas;
FClientRect: TRect;
FLeadLength: Integer;
FVisible: Boolean;
function GetLeftTPlugPos: TPoint;
function GetLeftBPlugPos: TPoint;
function GetRightTPlugPos: TPoint;
function GetRightBPlugPos: TPoint;
public
constructor Create(ACanvas: TCanvas);
procedure Draw;
public
property Canvas: TCanvas read FCanvas write FCanvas;
property ClientRect: TRect read FClientRect write FClientRect;
property LeadLength: Integer read FLeadLength write FLeadLength;
property LeftTPlugPos: TPoint read GetLeftTPlugPos;
property LeftBPlugPos: TPoint read GetLeftBPlugPos;
property RightTPlugPos: TPoint read GetRightTPlugPos;
property RightBPlugPos: TPoint read GetRightBPlugPos;
property Visible: Boolean read FVisible write FVisible default True;
end;
TDgGround = class
private
FCanvas: TCanvas;
FPos: TPoint;
FLeadLength: Integer;
FVisible: Boolean;
public
constructor Create(ACanvas: TCanvas);
procedure Draw;
public
property Canvas: TCanvas read FCanvas write FCanvas;
property Pos: TPoint read FPos write FPos;
property LeadLength: Integer read FLeadLength;
property Visible: Boolean read FVisible write FVisible default True;
end;
TDgPTGroup = class
private
FCanvas: TCanvas;
FPos: TPoint;
FPT1, FPT2, FPT3: TDgPT;
FHasThreePT: Boolean;
FVisible: Boolean;
procedure SetPos(const Value: TPoint);
procedure SetHasThreePT(const Value: Boolean);
public
constructor Create(ACanvas: TCanvas);
destructor Destroy; override;
procedure Draw;
public
property Canvas: TCanvas read FCanvas write FCanvas;
property Pos: TPoint read FPos write SetPos;
property PT1: TDgPT read FPT1;
property PT2: TDgPT read FPT2;
property PT3: TDgPT read FPT3;
property HasThreePT: Boolean read FHasThreePT write SetHasThreePT default False;
property Visible: Boolean read FVisible write FVisible default True;
end;
TDgWire = class
private
FCanvas: TCanvas;
FLength: Integer;
FStartPos: TPoint;
FBreakXPos2: Integer;
FBreakXPos1: Integer;
FText: string;
FVisible: Boolean;
public
constructor Create(ACanvas: TCanvas);
procedure Draw;
public
property Canvas: TCanvas read FCanvas write FCanvas;
property StartPos: TPoint read FStartPos write FStartPos;
property Length: Integer read FLength write FLength;
property BreakXPos1: Integer read FBreakXPos1 write FBreakXPos1;
property BreakXPos2: Integer read FBreakXPos2 write FBreakXPos2;
property Text: string read FText write FText;
property Visible: Boolean read FVisible write FVisible default True;
end;
TPointArray = array of TPoint;
TDgLink = record
InPortNo: Integer;
OutPortNo: Integer;
end;
TDgLinkArray = array of TDgLink;
TDgJunctionBox = class
private
FCanvas: TCanvas;
FInPorts: TPointArray;
FOutPorts: TPointArray;
FLinks: TDgLinkArray;
FVisible: Boolean;
procedure SetLinkCount(const Value: Integer);
function GetLinkCount: Integer;
function GetPortCount: Integer;
procedure SetPortCount(const Value: Integer);
public
constructor Create(ACanvas: TCanvas; APortCount: Integer);
procedure SetOutPortOrder(AOrderArray: array of Integer);
procedure Draw;
public
property Canvas: TCanvas read FCanvas write FCanvas;
property InPorts: TPointArray read FInPorts;
property OutPorts: TPointArray read FOutPorts;
property PortCount: Integer read GetPortCount write SetPortCount;
property Links: TDgLinkArray read FLinks;
property LinkCount: Integer read GetLinkCount write SetLinkCount;
property Visible: Boolean read FVisible write FVisible default True;
end;
procedure DgDrawCircle(ACanvas: TCanvas; ACenter: TPoint; ADiameter: Integer;
AFillColor: TColor = clDefault);
procedure DgDrawArc(ACanvas: TCanvas; ACenter, AStart, AEnd: TPoint; ARadius: Integer);
procedure DgDrawJunction(ACanvas: TCanvas; ACenter: TPoint; ASolid: Boolean; ADiameter: Integer = 3);
function DgOffsetPoint(APoint: TPoint; AX, AY: Integer): TPoint;
function DgOffsetRectDef0(ARect: TRect; AX, AY: Integer): TRect;
procedure DgSwapPoints(var APoint1, APoint2: TPoint);
procedure DgDrawWinding(ACanvas: TCanvas; ARect: TRect; AIsDown: Boolean);
procedure DgDrawConnection(ACanvas: TCanvas; APosStart, APosEnd: TPoint;
AStraightLine : Boolean = False; AColor : TColor = clBlack);
procedure DgDrawConnection3X(ACanvas: TCanvas; APosStart, APosEnd: TPoint;
AXPos: Integer; AColor: TColor = clBlack);
procedure DgDrawConnection3Y(ACanvas: TCanvas; APosStart, APosEnd: TPoint;
AYPos: Integer; AColor: TColor = clBlack);
implementation
uses
Math;
const
C_PLUG_DISTANCE = 20; //电表插孔间距
procedure DgDrawCircle(ACanvas: TCanvas; ACenter: TPoint; ADiameter: Integer;
AFillColor: TColor);
var
OldColor: TColor;
begin
OldColor := ACanvas.Brush.Color;
if AFillColor <> clDefault then
ACanvas.Brush.Color := AFillColor;
ACanvas.Ellipse(ACenter.X - ADiameter div 2, ACenter.Y - ADiameter div 2,
ACenter.X + (ADiameter + 1) div 2, ACenter.Y + (ADiameter + 1) div 2);
if AFillColor <> clDefault then
ACanvas.Brush.Color := OldColor;
end;
procedure DgDrawArc(ACanvas: TCanvas; ACenter, AStart, AEnd: TPoint; ARadius: Integer);
begin
ACanvas.Arc(ACenter.X - ARadius, ACenter.Y - ARadius, ACenter.X + ARadius, ACenter.Y + ARadius,
AStart.X, AStart.Y, AEnd.X, AEnd.Y);
end;
function DgOffsetPoint(APoint: TPoint; AX, AY: Integer): TPoint;
begin
Result.X := APoint.X + AX;
Result.Y := APoint.Y + AY;
end;
function DgOffsetRectDef0(ARect: TRect; AX, AY: Integer): TRect;
begin
Result := ARect;
if not OffsetRect(Result, AX, AY) then
Result := Rect(0, 0, 0, 0);
end;
procedure DgSwapPoints(var APoint1, APoint2: TPoint);
var
ptTemp: TPoint;
begin
ptTemp := APoint1;
APoint1 := APoint2;
APoint2 := ptTemp;
end;
procedure DgDrawJunction(ACanvas: TCanvas; ACenter: TPoint; ASolid: Boolean; ADiameter: Integer);
var
OldColor: TColor;
OldStyle: TBrushstyle;
begin
with ACanvas do
begin
OldColor := Brush.Color;
OldStyle := Brush.Style;
Brush.Style := bsSolid;
if ASolid then
Brush.Color := clBlack
else
Brush.Color := clWhite;
if ADiameter >= 4 then
DgDrawCircle(ACanvas, ACenter, ADiameter)
else
Rectangle(ACenter.X - ADiameter div 2, ACenter.Y - ADiameter div 2,
ACenter.X + ADiameter div 2 + ADiameter mod 2,
ACenter.Y + ADiameter div 2 + ADiameter mod 2);
Brush.Style := OldStyle;
Brush.Color := OldColor;
end;
end;
procedure DgDrawConnection(ACanvas: TCanvas; APosStart, APosEnd: TPoint;
AStraightLine: Boolean; AColor: TColor);
var
OldColor: TColor;
begin
with ACanvas do
begin
OldColor := Pen.Color;
Pen.Color := AColor;
if ( APosStart.X = APosEnd.X ) or ( APosStart.Y = APosEnd.Y ) or
AStraightLine then
Polyline( [ APosStart, APosEnd ] )
else
begin
Polyline( [ APosStart, Point( APosEnd.X, APosStart.Y ) ] );
Polyline( [ Point( APosEnd.X, APosStart.Y ), APosEnd ] );
end;
Pen.Color := OldColor;
end;
end;
procedure DgDrawConnection3X(ACanvas: TCanvas; APosStart, APosEnd: TPoint;
AXPos: Integer; AColor: TColor);
var
OldColor: TColor;
begin
with ACanvas do
begin
OldColor := Pen.Color;
Pen.Color := AColor;
Polyline([APosStart, Point(AXPos, APosStart.Y)]);
DgDrawConnection(ACanvas, APosEnd, Point(AXPos, APosStart.Y));
Pen.Color := OldColor;
end;
end;
procedure DgDrawConnection3Y(ACanvas: TCanvas; APosStart, APosEnd: TPoint;
AYPos: Integer; AColor: TColor);
var
OldColor: TColor;
begin
with ACanvas do
begin
OldColor := Pen.Color;
Pen.Color := AColor;
Polyline([APosStart, Point(APosStart.X, AYPos)]);
DgDrawConnection(ACanvas, Point(APosStart.X, AYPos), APosEnd);
Pen.Color := OldColor;
end;
end;
procedure DgDrawWinding(ACanvas: TCanvas; ARect: TRect; AIsDown: Boolean);
var
nY, nX: Integer;
begin
nX := (ARect.Left + ARect.Right) div 2;
if AIsDown then
begin
nY := ARect.Top + 1;
Dec(ARect.Top, ARect.Bottom - ARect.Top);
ACanvas.Arc(ARect.Left, ARect.Top, nX + 1, ARect.Bottom,
ARect.Left, nY, ARect.Right, nY);
ACanvas.Arc(nX, ARect.Top, ARect.Right + 1, ARect.Bottom,
ARect.Left, nY, ARect.Right, nY);
end
else
begin
nY := ARect.Bottom;
Inc(ARect.Bottom, ARect.Bottom - ARect.Top);
ACanvas.Arc(ARect.Left, ARect.Top, nX + 1, ARect.Bottom,
ARect.Right, nY, ARect.Left, nY);
ACanvas.Arc(nX, ARect.Top, ARect.Right + 1, ARect.Bottom,
ARect.Right, nY, ARect.Left, nY);
end;
end;
{ TWdMeter }
constructor TDgMeter.Create(ACanvas: TCanvas);
begin
FCanvas := ACanvas;
FPos := Point(0, 0);
FVisible := True;
end;
procedure TDgMeter.Draw;
begin
if not FVisible then
Exit;
DrawOutline;
DrawPlugs;
DrawDetail;
end;
procedure TDgMeter.DrawDetail;
var
ptCircle1, ptCircle2, ptCircle3: TPoint;
procedure DrawCircleAndPoint(ACenter: TPoint);
var
OldColor: TColor;
begin
with FCanvas do
begin
OldColor := Brush.Color;
DgDrawCircle(FCanvas, ACenter, 25);
Brush.Color := clBlack;
Rectangle(Rect(ACenter.X - 5, ACenter.Y + 14, ACenter.X - 2, ACenter.Y + 17));
Rectangle(Rect(ACenter.X - 16, ACenter.Y - 5, ACenter.X - 13, ACenter.Y - 2));
Brush.Color := OldColor;
end;
end;
procedure DrawThreeActive;
begin
with FCanvas do
begin
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(0), 0, -14), DgOffsetPoint(GetPlugPos(2), 0, -14), ptCircle1.Y);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(4), 0, -14), DgOffsetPoint(GetPlugPos(6), 0, -14), ptCircle2.Y);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(1), 0, -14), DgOffsetPoint(GetPlugPos(5), 0, -14), ptCircle1.Y - 40);
Polyline([DgOffsetPoint(GetPlugPos(3), 0, -14), Point(GetPlugPos(3).X, ptCircle1.Y - 40)]);
DgDrawJunction(FCanvas, Point(GetPlugPos(3).X, ptCircle1.Y - 40), True);
end;
end;
procedure DrawThreeReactive;
var
rRect1, rRect2: TRect;
ptRightBottom: TPoint;
begin
rRect1.TopLeft := DgOffsetPoint(ptCircle1, -3, -30);
rRect2.TopLeft := DgOffsetPoint(ptCircle2, -3, -30);
rRect1.BottomRight := DgOffsetPoint(rRect1.TopLeft, 6, 10);
rRect2.BottomRight := DgOffsetPoint(rRect2.TopLeft, 6, 10);
ptRightBottom := DgOffsetPoint(GetPlugPos(6), 8, -26);
with FCanvas do
begin
Rectangle(rRect1);
Rectangle(rRect2);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(0), 0, -14), DgOffsetPoint(GetPlugPos(2), 0, -14), ptCircle1.Y);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(4), 0, -14), DgOffsetPoint(GetPlugPos(6), 0, -14), ptCircle2.Y);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(1), 0, -14), Point(ptCircle2.X, rRect2.Bottom - 1), GetPlugPos(0).Y - 36);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(3), 0, -14), Point(ptCircle1.X, rRect1.Bottom - 1), GetPlugPos(0).Y - 46);
DgDrawConnection(FCanvas, ptRightBottom, DgOffsetPoint(GetPlugPos(5), 0, -14));
DgDrawConnection3Y(FCanvas, ptRightBottom, Point(ptCircle1.X, rRect1.Top), ptCircle1.Y - 40);
Polyline([Point(ptCircle2.X, rRect2.Top), Point(ptCircle2.X, ptCircle2.Y - 40)]);
end;
end;
procedure DrawFourActive;
begin
with FCanvas do
begin
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(0), 0, -14), DgOffsetPoint(GetPlugPos(2), 0, -14), ptCircle1.Y);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(3), 0, -14), DgOffsetPoint(GetPlugPos(5), 0, -14), ptCircle2.Y);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(6), 0, -14), DgOffsetPoint(GetPlugPos(8), 0, -14), ptCircle3.Y);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(9), 0, -14), DgOffsetPoint(GetPlugPos(10), 0, -14), GetPlugPos(10).Y - 50);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(1), 0, -14), DgOffsetPoint(GetPlugPos(10), -10, -50), ptCircle1.Y - 40);
Polyline([DgOffsetPoint(GetPlugPos(4), 0, -14), Point(GetPlugPos(4).X, ptCircle1.Y - 40)]);
Polyline([DgOffsetPoint(GetPlugPos(7), 0, -14), Point(GetPlugPos(7).X, ptCircle1.Y - 40)]);
end;
end;
procedure DrawFourReactive;
var
ptLeftBottom, ptRightBottom, ptRightBottom2: TPoint;
begin
ptLeftBottom := DgOffsetPoint(GetPlugPos(0), -8, -26);
ptRightBottom := DgOffsetPoint(GetPlugPos(8), 8, -26);
ptRightBottom2 := DgOffsetPoint(ptRightBottom, -4, -10);
with FCanvas do
begin
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(0), 0, -14), DgOffsetPoint(GetPlugPos(2), 0, -14), ptCircle1.Y);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(3), 0, -14), DgOffsetPoint(GetPlugPos(5), 0, -14), ptCircle2.Y);
DgDrawConnection3Y(FCanvas, DgOffsetPoint(GetPlugPos(6), 0, -14), DgOffsetPoint(GetPlugPos(8), 0, -14), ptCircle3.Y);
DgDrawConnection(FCanvas, ptLeftBottom, DgOffsetPoint(GetPlugPos(1), 0, -14));
DgDrawConnection3Y(FCanvas, ptLeftBottom, ptCircle2, ptCircle2.Y - 40);
DgDrawConnection3Y(FCanvas, ptCircle2, DgOffsetPoint(ptCircle2, 30, -30), ptCircle2.Y + 20);
Polyline([DgOffsetPoint(GetPlugPos(4), 0, -14), Point(GetPlugPos(4).X, ptRightBottom2.Y)]);
DgDrawConnection(FCanvas, ptRightBottom, DgOffsetPoint(GetPlugPos(7), 0, -14));
DgDrawConnection3Y(FCanvas, ptCircle1, ptRightBottom, ptCircle1.Y - 30);
DgDrawConnection(FCanvas, ptRightBottom2, ptCircle1);
DgDrawConnection3Y(FCanvas, ptCircle3, ptRightBottom2, ptCircle3.Y - 20);
DgDrawConnection(FCanvas, DgOffsetPoint(ptLeftBottom, 0, -20), ptCircle3);
end;
end;
begin
ptCircle1 := DgOffsetPoint(GetPlugPos(1), 0, -90);
if FPhaseType = dmptFour then
begin
ptCircle2 := DgOffsetPoint(GetPlugPos(4), 0, -90);
ptCircle3 := DgOffsetPoint(GetPlugPos(7), 0, -90);
end
else if FPhaseType = dmptThree then
ptCircle2 := DgOffsetPoint(GetPlugPos(5), 0, -90);
DrawCircleAndPoint(ptCircle1);
if FPhaseType = dmptFour then
begin
DrawCircleAndPoint(ptCircle2);
DrawCircleAndPoint(ptCircle3);
if FEnergyType = dmetActive then
DrawFourActive
else
DrawFourReactive;
end
else if FPhaseType = dmptThree then
begin
DrawCircleAndPoint(ptCircle2);
if FEnergyType = dmetActive then
DrawThreeActive
else
DrawThreeReactive;
end;
end;
procedure TDgMeter.DrawOutline;
const
C_R = 10; //电表外框倒角半径
C_H = 20; //电表外框下端高度
var
ptLeftTop, ptRightTop, ptLeftMiddle, ptRightMiddle, ptLeftBottom, ptRightBottom: TPoint;
begin
ptLeftTop := FPos;
ptLeftMiddle := Point(FPos.X, FPos.Y + Height - C_H);
ptLeftBottom := Point(FPos.X + C_R, FPos.Y + Height);
ptRightTop := Point(FPos.X + Width, FPos.Y);
ptRightMiddle := Point(FPos.X + Width, FPos.Y + Height - C_H);
ptRightBottom := Point(FPos.X + Width - C_R, FPos.Y + Height);
DgDrawArc(FCanvas, DgOffsetPoint(ptLeftTop, C_R + 1, C_R + 1),
DgOffsetPoint(ptLeftTop, C_R, 0), DgOffsetPoint(ptLeftTop, 0, C_R), C_R);
FCanvas.Polyline([DgOffsetPoint(ptLeftTop, C_R, 0), Point(ptRightTop.X - C_R + 1, ptRightTop.Y )]);
DgDrawArc(FCanvas, DgOffsetPoint(ptRightTop, -C_R + 1, C_R + 1),
DgOffsetPoint(ptRightTop, 0, C_R), DgOffsetPoint(ptRightTop, -C_R, 0), C_R);
FCanvas.Polyline([DgOffsetPoint(ptRightTop, 0, C_R), Point(ptRightMiddle.X, ptRightMiddle.Y - C_R)]);
DgDrawArc(FCanvas, DgOffsetPoint(ptRightMiddle, -C_R + 1, -C_R + 1),
DgOffsetPoint(ptRightMiddle, -C_R, 0), DgOffsetPoint(ptRightMiddle, 0, -C_R), C_R);
FCanvas.Polyline([DgOffsetPoint(ptRightMiddle, -C_R, 0), ptRightBottom]);
FCanvas.Polyline([ptRightBottom, ptLeftBottom]);
FCanvas.Polyline([ptLeftBottom, DgOffsetPoint(ptLeftMiddle, C_R, 0)]);
DgDrawArc(FCanvas, DgOffsetPoint(ptLeftMiddle, C_R + 1, -C_R + 1),
DgOffsetPoint(ptLeftMiddle, 0, -C_R), DgOffsetPoint(ptLeftMiddle, C_R, 0), C_R);
FCanvas.Polyline([DgOffsetPoint(ptLeftMiddle, 0, -C_R), DgOffsetPoint(ptLeftTop, 0, C_R - 1)]);
end;
procedure TDgMeter.DrawPlugs;
var
I: Integer;
begin
for I := 0 to PlugCount - 1 do
FCanvas.Rectangle(Rect(DgOffsetPoint(GetPlugPos(I), -3, -14), DgOffsetPoint(GetPlugPos(I), 3, 1)));
end;
function TDgMeter.GetHeight: Integer;
begin
Result := 150;
end;
function TDgMeter.GetPlugCount: Integer;
begin
if FPhaseType = dmptFour then
begin
if FEnergyType = dmetActive then
Result := 11
else
Result := 9
end
else if FPhaseType = dmptThree then
Result := 7
else
Result := 0;
end;
function TDgMeter.GetPlugPos(APlugSign: TDgMeterPlugSign): TPoint;
begin
if FPhaseType = dmptFour then
begin
Result := GetPlugPos(Ord(APlugSign));
end
else
begin
case APlugSign of
dmpsIa_in, dmpsUa, dmpsIa_out: Result := GetPlugPos(Ord(APlugSign));
dmpsUb: Result := GetPlugPos(3);
dmpsIc_in, dmpsUc, dmpsIc_out: Result := GetPlugPos(Ord(APlugSign) - 2);
else
raise Exception.Create('No Plug');
end;
end;
end;
function TDgMeter.GetPlugPos(Index: Integer): TPoint;
begin
if (Index >= 0) and (Index < PlugCount) then
begin
Result.X := FPos.X + 20 + Index * C_PLUG_DISTANCE;
Result.Y := FPos.Y + Height - 6;
end
else
raise Exception.Create('Error');
end;
function TDgMeter.GetWidth: Integer;
begin
if PlugCount <= 0 then
raise Exception.Create('Error');
Result := (PlugCount - 1) * C_PLUG_DISTANCE + 40 - 1;
end;
{ TDgTransformer }
constructor TDgCT.Create(ACanvas: TCanvas);
begin
FVisible := True;
FCanvas := ACanvas;
FWindingPos := Point(0, 0);
FWindingWidth := 40;
FLeadLength := 8;
end;
procedure TDgCT.Draw;
begin
if not FVisible then
Exit;
DgDrawJunction(FCanvas, DgOffsetPoint(LeftPlugPos, 0, 2), False, 4);
DgDrawJunction(FCanvas, DgOffsetPoint(RightPlugPos, 0, 2), False, 4);
DgDrawJunction(FCanvas, DgOffsetPoint(FWindingPos, -5, 4), True);
DgDrawJunction(FCanvas, DgOffsetPoint(FWindingPos, -5, -4), True);
DgDrawConnection(FCanvas, DgOffsetPoint(LeftPlugPos, 0, 4), FWindingPos, True);
DgDrawConnection(FCanvas, DgOffsetPoint(RightPlugPos, 0, 4),
DgOffsetPoint(FWindingPos, FwindingWidth, 0), True);
DgDrawWinding(FCanvas, Rect(FWindingPos, DgOffsetPoint(FWindingPos, FWindingWidth, FWindingWidth div 4)), True);
end;
function TDgCT.GetLeftPlugPos: TPoint;
begin
Result := DgOffsetPoint(FWindingPos, 0, -FLeadLength - 2);
end;
function TDgCT.GetRightPlugPos: TPoint;
begin
Result := DgOffsetPoint(LeftPlugPos, FWindingWidth, 0);
end;
{ TDgPT }
constructor TDgPT.Create(ACanvas: TCanvas);
begin
FVisible := True;
FCanvas := ACanvas;
FClientRect := Rect(0, 0, 20, 20);
FLeadLength := 4;
end;
procedure TDgPT.Draw;
var
nRadius: Integer;
begin
if not FVisible then
Exit;
with FClientRect do
begin
nRadius := (Right - Left) div 2;
DgDrawJunction(FCanvas, TopLeft, False, 4);
DgDrawJunction(FCanvas, Point(Left, Bottom), False, 4);
DgDrawJunction(FCanvas, Point(Right, Top), False, 4);
DgDrawJunction(FCanvas, BottomRight, False, 4);
DgDrawJunction(FCanvas, Point(Left + 4, Top + FLeadLength), True, 2);
DgDrawJunction(FCanvas, Point(Left + 4, Bottom - FLeadLength), True, 2);
DgDrawConnection(FCanvas, Point(Left, Top + 2), Point(Left, Top + FLeadLength + 2), True);
DgDrawConnection(FCanvas, Point(Left, Bottom - 2), Point(Left, Bottom - FLeadLength - 2), True);
DgDrawConnection(FCanvas, Point(Right, Top + 2), Point(Right, Top + FLeadLength + 2), True);
DgDrawConnection(FCanvas, Point(Right, Bottom - 2), Point(Right, Bottom - FLeadLength - 2), True);
FCanvas.Polyline([Point(Left + 1, (Top + Bottom) div 2), Point(Right - 1, (Top + Bottom) div 2)]);
DgDrawWinding(FCanvas, Rect(Left, Top + FLeadLength, Right, Top + FLeadLength + nRadius), True);
DgDrawWinding(FCanvas, Rect(Left, Bottom - FLeadLength - nRadius, Right, Bottom - FLeadLength), False);
end;
end;
function TDgPT.GetLeftBPlugPos: TPoint;
begin
Result := Point(FClientRect.Left, FClientRect.Bottom + 1);
end;
function TDgPT.GetLeftTPlugPos: TPoint;
begin
Result := Point(FClientRect.Left, FClientRect.Top - 2);
end;
function TDgPT.GetRightBPlugPos: TPoint;
begin
Result := Point(FClientRect.Right, FClientRect.Bottom + 1);
end;
function TDgPT.GetRightTPlugPos: TPoint;
begin
Result := Point(FClientRect.Right, FClientRect.Top - 2);
end;
{ TDgPTGroup }
constructor TDgPTGroup.Create(ACanvas: TCanvas);
begin
FCanvas := ACanvas;
FVisible := True;
FPT1 := TDgPT.Create(FCanvas);
FPT2 := TDgPT.Create(FCanvas);
FPT3 := TDgPT.Create(FCanvas);
SetPos(Point(0, 0));
SetHasThreePT(False);
end;
destructor TDgPTGroup.Destroy;
begin
FPT1.Free;
FPT2.Free;
FPT3.Free;
inherited;
end;
procedure TDgPTGroup.Draw;
begin
if not FVisible then
Exit;
FPT1.Draw;
FPT2.Draw;
FPT3.Draw;
end;
procedure TDgPTGroup.SetHasThreePT(const Value: Boolean);
begin
FHasThreePT := Value;
FPT1.Visible := True;
FPT2.Visible := True;
FPT3.Visible := FHasThreePT;
SetPos(FPos);
end;
procedure TDgPTGroup.SetPos(const Value: TPoint);
begin
FPos := Value;
FPT1.ClientRect := Rect(FPos.X, FPos.Y, FPos.X + 13, FPos.Y + 25);
FPT2.ClientRect := DgOffsetRectDef0(FPT1.ClientRect, 18, 0);
FPT3.ClientRect := DgOffsetRectDef0(FPT2.ClientRect, 18, 0);
end;
{ TDgGroud }
constructor TDgGround.Create(ACanvas: TCanvas);
begin
FCanvas := ACanvas;
FPos := Point(0, 0);
FVisible := True;
FLeadLength := 5;
end;
procedure TDgGround.Draw;
begin
if Not FVisible then
Exit;
FCanvas.Polyline([FPos, DgOffsetPoint(FPos, 0, FLeadLength)]);
FCanvas.Polyline([DgOffsetPoint(FPos, -8, FLeadLength), DgOffsetPoint(FPos, 8, FLeadLength)]);
FCanvas.Polyline([DgOffsetPoint(FPos, -6, FLeadLength + 3), DgOffsetPoint(FPos, 6, FLeadLength + 3)]);
FCanvas.Polyline([DgOffsetPoint(FPos, -4, FLeadLength + 6), DgOffsetPoint(FPos, 4, FLeadLength + 6)]);
end;
{ TDgWire }
constructor TDgWire.Create(ACanvas: TCanvas);
begin
FVisible := True;
FCanvas := ACanvas;
FStartPos := Point(0, 0);
FLength := 20;
FText := '';
FBreakXPos1 := -1;
FBreakXPos2 := -1;
end;
procedure TDgWire.Draw;
var
OldColor: TColor;
ptEnd: TPoint;
begin
if not FVisible then
Exit;
OldColor := FCanvas.Brush.Color;
ptEnd := Point(FStartPos.X + FLength, FStartPos.Y);
FCanvas.Brush.Color := clWhite;
DgDrawCircle(FCanvas, FStartPos, 6);
if (FBreakXPos1 > FStartPos.X) and (FBreakXPos2 < ptEnd.X) and (FBreakXPos2 >= FBreakXPos1) then
begin
FCanvas.Polyline([DgOffsetPoint(FStartPos, 3, 0), Point(FBreakXPos1, FStartPos.Y)]);
FCanvas.Polyline([Point(FBreakXPos2, FStartPos.Y), ptEnd]);
end
else
begin
FCanvas.Polyline([DgOffsetPoint(FStartPos, 3, 0), ptEnd]);
end;
FCanvas.TextOut(FStartPos.X - 15, FStartPos.Y - 6, FText);
FCanvas.Brush.Color := clBlack;
FCanvas.Polygon([ptEnd, DgOffsetPoint(ptEnd, -8, -3), DgOffsetPoint(ptEnd, -8, 3)]);
FCanvas.Brush.Color := OldColor;
end;
{ TDgJunctionBox }
constructor TDgJunctionBox.Create(ACanvas: TCanvas; APortCount: Integer);
begin
FCanvas := ACanvas;
SetPortCount(APortCount);
SetLinkCount(APortCount);
FVisible := True;
end;
procedure TDgJunctionBox.Draw;
var
I: Integer;
begin
if not FVisible then
Exit;
for I := 0 to High(FLinks) do
FCanvas.Polyline([FInPorts[FLinks[I].InPortNo], FOutPorts[FLinks[I].OutPortNo]]);
end;
function TDgJunctionBox.GetPortCount: Integer;
begin
Result := Length(FInPorts);
end;
procedure TDgJunctionBox.SetPortCount(const Value: Integer);
begin
SetLength(FInPorts, Value);
SetLength(FOutPorts, Value);
end;
function TDgJunctionBox.GetLinkCount: Integer;
begin
Result := Length(FLinks);
end;
procedure TDgJunctionBox.SetLinkCount(const Value: Integer);
var
I: Integer;
begin
SetLength(FLinks, Value);
for I := 0 to High(FLinks) do
begin
FLinks[I].InPortNo := I;
FLinks[I].OutPortNo := I;
end;
end;
procedure TDgJunctionBox.SetOutPortOrder(AOrderArray: array of Integer);
var
I: Integer;
begin
if Length(AOrderArray) <> LinkCount then
raise Exception.Create('Error');
for I := 0 to LinkCount - 1 do
FLinks[I].OutPortNo := AOrderArray[I];
end;
end.
|
UNIT DT_TipoElemental;
INTERFACE
TYPE
TipoElemental= RECORD
id: INTEGER;
nombre: STRING;
end;
PROCEDURE CrearTipoElemental(id: INTEGER; nombre: STRING; VAR t: TipoElemental); //Inicializa un tipo elemental.
FUNCTION NombreTipoElemental(t: TipoElemental): STRING; //Retorna el nombre del tipo.
FUNCTION IdTipoElemental(t: TipoElemental): INTEGER; //Retorna el Id del tipo.
IMPLEMENTATION
PROCEDURE CrearTipoElemental(id: INTEGER; nombre: STRING; VAR t: TipoElemental);
Begin
t.id:= id;
t.nombre:= nombre;
End;//CrearTipoElemental
//--------------------------------------------------------------------------
FUNCTION NombreTipoElemental(t: TipoElemental): STRING; //Retorna el nombre del tipo.
Begin
NombreTipoElemental:= t.nombre;
end;//NombreTipoElemental
//--------------------------------------------------------------------------
FUNCTION IdTipoElemental(t: TipoElemental): INTEGER; //Retorna el Id del tipo.
Begin
IdTipoElemental:= t.id;
end;
//--------------------------------------------------------------------------
END.
|
unit MediaStream.FramePool;
interface
uses
Windows,SysUtils, Classes, SyncObjs, Generics.Collections, Collections.Lists,
MediaProcessing.Definitions,MediaStream.Frame;
type
TMediaStreamFramePool = class
private
FFreeItemsLists: array [TMediaType] of TLinkedList<TMediaStreamFrame>;
FItems: TList<TMediaStreamFrame>;
FLock : TCriticalSection;
FMaxCount: integer;
procedure SetMaxCount(const Value: integer);
function GetItems(index: integer): TMediaStreamFrame;
function FindAppropriateFreeItemToUse(aMT: TMediaType; aDataSize:cardinal; aInfoSize: cardinal): TMediaStreamFrame;
public
constructor Create;
destructor Destroy; override;
procedure Lock;
procedure Unlock;
function Add(aData: pointer; aDataSize:cardinal; const aFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal):boolean;
procedure AddAsQueue(aData: pointer; aDataSize:cardinal; const aFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal);
function ExtractFirstOrDefault: TMediaStreamFrame;
//Удаляет с начала очереди фреймы, пока не доберется до I-фрейма
function DeleteUpToIFrame: integer;
//Ищет I-frame с конца
function FindIFrameBackward: integer;
procedure Delete(index: integer);
procedure DeleteRange(aStartIndex,aCount: integer);
procedure Clear;
procedure FreeItem(aItem: TMediaStreamFrame);
function Count: integer;
function Length: cardinal; //длительность в мс
property Items[index: integer]: TMediaStreamFrame read GetItems;
property MaxCount: integer read FMaxCount write SetMaxCount;
end;
implementation
uses Math;
{ TMediaStreamFramePool }
{
procedure TMediaStreamFramePool.CheckTimeStampOrder;
var
aTs: int64;
i: Integer;
begin
FLock.Enter;
try
if FItems.Count=0 then
exit;
aTs:=FItems[0].Format.TimeStamp;
for i := 1 to FItems.Count-1 do
begin
if aTs>FItems[i].Format.TimeStamp then
raise Exception.Create('Timestamp sequence order error');
aTs:=FItems[i].Format.TimeStamp;
end;
finally
FLock.Leave;
end;
end;
}
procedure TMediaStreamFramePool.AddAsQueue(aData: pointer; aDataSize: cardinal;
const aFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal);
begin
self.Lock;
try
while Count>=MaxCount do
Delete(0);
Add(aData,aDataSize,aFormat,aInfo,aInfoSize)
finally
self.Unlock;
end;
end;
procedure TMediaStreamFramePool.Clear;
var
i: Integer;
begin
FLock.Enter;
try
for i := 0 to FItems.Count-1 do
begin
FreeItem(FItems[i]);
FItems[i]:=nil;
end;
FItems.Clear;
finally
FLock.Leave;
end;
end;
function TMediaStreamFramePool.Count: integer;
begin
Lock;
try
result:=FItems.Count;
finally
Unlock;
end;
end;
constructor TMediaStreamFramePool.Create;
var
aMT: TMediaType;
begin
FLock:=TCriticalSection.Create;
FItems:=TList<TMediaStreamFrame>.Create;
for aMT := Low(TMediaType) to High(TMediaType) do
FFreeItemsLists[aMT]:=TLinkedList<TMediaStreamFrame>.Create;
end;
procedure TMediaStreamFramePool.Delete(index: integer);
var
aItem: TMediaStreamFrame;
begin
self.Lock;
try
aItem:=FItems[index];
FItems.Delete(index);
FreeItem(aItem);
finally
self.Unlock;
end;
end;
procedure TMediaStreamFramePool.DeleteRange(aStartIndex,aCount: integer);
var
i: Integer;
begin
self.Lock;
try
for I := Min(aStartIndex+aCount-1,Count-1) downto aStartIndex do
Delete(i);
finally
self.Unlock;
end;
end;
function TMediaStreamFramePool.DeleteUpToIFrame: integer;
begin
result:=0;
Lock;
try
//Удаляем все не опорные кадры, потому что они больше не имеют смысла - будут кубики
while Count>0 do
begin
if not (ffKeyFrame in Items[0].Format.biFrameFlags) then
begin
Delete(0);
inc(result);
end
else
break;
end;
finally
Unlock;
end;
end;
destructor TMediaStreamFramePool.Destroy;
var
aMT: TMediaType;
aItem: TLinkedListItem<TMediaStreamFrame>;
begin
Clear;
//Очищаем кэш
for aMT := Low(TMediaType) to High(TMediaType) do
begin
aItem:=FFreeItemsLists[aMT].First;
while aItem<>nil do
begin
FreeAndNil(aItem.Value);
aItem:=FFreeItemsLists[aMT].Next(aItem);
end;
FreeAndNil(FFreeItemsLists[aMT]);
end;
FreeAndNil(FItems);
FreeAndNil(FLock);
inherited;
end;
function TMediaStreamFramePool.ExtractFirstOrDefault: TMediaStreamFrame;
begin
self.Lock;
try
result:=nil;
if Count>0 then
begin
result:=FItems[0];
FItems.Delete(0);
end;
finally
self.Unlock;
end;
end;
function TMediaStreamFramePool.FindAppropriateFreeItemToUse(aMT: TMediaType; aDataSize, aInfoSize: cardinal): TMediaStreamFrame;
var
aItem: TLinkedListItem<TMediaStreamFrame>;
begin
result:=nil;
aItem:=FFreeItemsLists[aMT].First;
while aItem<>nil do
begin
if (aItem.Value.DataAllocatedBlockSize>=aDataSize) and (aItem.Value.InfoAllocatedBlockSize>=aInfoSize) then
begin
result:=aItem.Value;
FFreeItemsLists[aMT].Delete(aItem);
exit;
end;
aItem:=FFreeItemsLists[aMT].Next(aItem);
end;
//Если ничего не нашли, то применим первую попавшуюся
if FFreeItemsLists[aMT].First<>nil then
begin
result:=FFreeItemsLists[aMT].First.Value;
FFreeItemsLists[aMT].Delete(FFreeItemsLists[aMT].First);
end;
end;
function TMediaStreamFramePool.FindIFrameBackward: integer;
var
i: Integer;
begin
result:=-1;
Lock;
try
for i := Count-1 downto 0 do
begin
if (ffKeyFrame in Items[i].Format.biFrameFlags) then
begin
result:=i;
break;
end;
end;
finally
Unlock;
end;
end;
procedure TMediaStreamFramePool.FreeItem(aItem: TMediaStreamFrame);
begin
self.Lock;
try
if FFreeItemsLists[aItem.Format.biMediaType].Size<FMaxCount div 10 then //10%
begin
FFreeItemsLists[aItem.Format.biMediaType].Add(aItem);
end
else begin
FreeAndNil(aItem);
end;
finally
self.Unlock;
end;
end;
function TMediaStreamFramePool.GetItems(index: integer): TMediaStreamFrame;
begin
result:=FItems[index];
end;
function TMediaStreamFramePool.Length: cardinal;
var
aStart,aStop: cardinal;
begin
result:=0;
Lock;
try
if Count>1 then
begin
aStart:=Items[0].Format.TimeStampMs;
aStop:=Items[Count-1].Format.TimeStampMs;
if aStart<aStop then
result:=aStop-aStart;
end;
finally
Unlock;
end;
end;
procedure TMediaStreamFramePool.Lock;
begin
FLock.Enter;
end;
function TMediaStreamFramePool.Add(aData: pointer; aDataSize:cardinal; const aFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal):boolean;
var
aFrame: TMediaStreamFrame;
begin
FLock.Enter;
try
result:=false;
if FItems.Count<FMaxCount then
begin
aFrame:=FindAppropriateFreeItemToUse(aFormat.biMediaType, aDataSize,aInfoSize);
if aFrame=nil then
aFrame:=TMediaStreamFrame.Create(aFormat, aData,aDataSize,aInfo,aInfoSize)
else
aFrame.Assign(aFormat,aData,aDataSize,aInfo,aInfoSize);
FItems.Add(aFrame);
result:=true;
end;
finally
FLock.Leave;
end;
end;
procedure TMediaStreamFramePool.SetMaxCount(const Value: integer);
begin
FLock.Enter;
try
FMaxCount := Value;
FItems.Capacity:=FMaxCount;
finally
FLock.Leave;
end;
end;
procedure TMediaStreamFramePool.Unlock;
begin
FLock.Leave;
end;
end.
|
unit AMostraDuplicata;
{ Autor: Douglas Thomas Jacobsen
Data Criação: 28/02/2000;
Função: TELA BÁSICA
Data Alteração:
Alterado por:
Motivo alteração:
}
interface
uses
Windows, SysUtils, Classes,Controls, Forms, Componentes1, ExtCtrls,
PainelGradiente, Formularios, StdCtrls, Buttons, Tabela, Grids, DBCtrls,
Localizacao, Mask, DBGrids, LabelCorMove, numericos, UnImpressao, Db,
DBTables, ComCtrls, UnClassesImprimir, DBClient, UnDados,
UnDadosLocaliza, UnClientes;
type
TFMostraDuplicata = class(TFormularioPermissao)
PanelFechar: TPanelColor;
BFechar: TBitBtn;
BImprimir: TBitBtn;
PainelTitulo: TPainelGradiente;
PanelModelo: TPanelColor;
Label1: TLabel;
CModelo: TDBLookupComboBoxColor;
CAD_DOC: TSQL;
CAD_DOCI_NRO_DOC: TFMTBCDField;
CAD_DOCI_SEQ_IMP: TFMTBCDField;
CAD_DOCC_NOM_DOC: TWideStringField;
CAD_DOCC_TIP_DOC: TWideStringField;
DATACAD_DOC: TDataSource;
PanelPai: TPanelColor;
Shape2: TShape;
Shape8: TShape;
Label13: TLabel;
Shape17: TShape;
Shape1: TShape;
Shape3: TShape;
Shape4: TShape;
Shape5: TShape;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label9: TLabel;
Label17: TLabel;
Label18: TLabel;
Label10: TLabel;
Label11: TLabel;
Shape6: TShape;
Label12: TLabel;
Label14: TLabel;
Label15: TLabel;
Label19: TLabel;
Label21: TLabel;
Shape9: TShape;
Shape10: TShape;
Label20: TLabel;
Label22: TLabel;
Label23: TLabel;
Shape11: TShape;
Shape12: TShape;
Label24: TLabel;
Label25: TLabel;
Label26: TLabel;
Label27: TLabel;
Label28: TLabel;
Label29: TLabel;
Label30: TLabel;
Label31: TLabel;
ENroOrdem: TEditColor;
ENomeSacado: TEditColor;
EEnderecoSacado: TEditColor;
EPracaPagto: TEditColor;
ECidadeSacado: TEditColor;
EEstadoSacado: TEditColor;
EInscricaoCGC: TEditColor;
EInscricaoEstadual: TEditColor;
EDescValor1: TEditColor;
EDescValor2: TEditColor;
ECondEspeciais: TEditColor;
EValor: Tnumerico;
Label3: TLabel;
DBText2: TDBText;
CAD_DOCC_NOM_IMP: TWideStringField;
EDescontoDe: Tnumerico;
EDataEmissao: TMaskEditColor;
EDataVencimento: TMaskEditColor;
EDataPagtoAte: TMaskEditColor;
BOK: TBitBtn;
Shape13: TShape;
Label2: TLabel;
Label16: TLabel;
ERepresentante: TEditColor;
Label32: TLabel;
ECodRepresentante: TEditColor;
ECodSacado: TRBEditLocaliza;
Label33: TLabel;
ECep: TEditColor;
EValorTotal: Tnumerico;
ENumero: TEditColor;
BLocalizaSacado: TSpeedButton;
ConsultaPadrao: TConsultaPadrao;
Label34: TLabel;
EBairroSacado: TEditColor;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure BImprimirClick(Sender: TObject);
procedure CModeloCloseUp(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure EValorChange(Sender: TObject);
procedure ECodSacadoRetorno(VpaColunas: TRBColunasLocaliza);
private
IMP : TFuncoesImpressao;
VprDCliente : TRBDCliente;
procedure DesativaEdits;
public
{ Public declarations }
procedure ImprimeDocumento;
procedure MostraDocumento(Dados: TDadosDuplicata);
procedure CarregaDados(Dados: TDadosDuplicata);
procedure CarregaEdits(Dados: TDadosDuplicata);
end;
var
FMostraDuplicata: TFMostraDuplicata;
implementation
uses APrincipal, FunSql, FunString, ConstMsg, Constantes,
FunNumeros, FunObjeto, dmRave;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFMostraDuplicata.FormCreate(Sender: TObject);
begin
VprDCliente := TRBDCliente.cria;
EDataEmissao.Text := DateToStr(Date);
EDataVencimento.Text := DateToStr(Date);
EDataPagtoAte.Text := DateToStr(Date);
IMP := TFuncoesImpressao.Criar(self, FPrincipal.BaseDados);
AbreTabela(CAD_DOC);
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFMostraDuplicata.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FechaTabela(CAD_DOC);
IMP.Destroy;
VprDCliente.Free;
Action := CaFree;
end;
procedure TFMostraDuplicata.BFecharClick(Sender: TObject);
begin
Close;
end;
procedure TFMostraDuplicata.BImprimirClick(Sender: TObject);
begin
ImprimeDocumento;
end;
procedure TFMostraDuplicata.ImprimeDocumento;
var
Dados: TDadosDuplicata;
begin
if varia.CNPJFilial = CNPJ_PAROS then
begin
Dados := TDadosDuplicata.Create;
CarregaDados(Dados);
dtRave := TdtRave.Create(self);
dtRave.ImprimeDuplicataManual(Varia.CodigoEmpFil, Dados);
dtRave.free;
Dados.free;
end
else
begin
if ((not CAD_DOC.EOF) and (CModelo.Text <> '')) then
begin
Dados := TDadosDuplicata.Create;
IMP.InicializaImpressao(CAD_DOCI_NRO_DOC.AsInteger, CAD_DOCI_SEQ_IMP.AsInteger);
CarregaDados(Dados);
IMP.ImprimeDuplicata(Dados); // Imprime 1 documento.
IMP.FechaImpressao(Config.ImpPorta, 'C:\IMP.TXT');
end
else
Aviso('Não existe modelo de documento para imprimir.')
end;
end;
procedure TFMostraDuplicata.MostraDocumento(Dados: TDadosDuplicata);
begin
BOK.Visible := True;
ActiveControl := BOK;
CarregaEdits(Dados);
DesativaEdits;
if BImprimir.Visible then
Height := Height - PanelModelo.Height - PanelFechar.Height - PainelTitulo.Height;
BImprimir.Visible := False;
PanelModelo.Visible := False;
PanelFechar.Visible := False;
PainelTitulo.Visible := False;
if BImprimir.Visible then
Height := Height - PanelModelo.Height - PanelFechar.Height - PainelTitulo.Height; DesativaEdits;
FormStyle := fsStayOnTop;
BorderStyle := bsDialog;
Show;
end;
procedure TFMostraDuplicata.DesativaEdits;
var
I: Integer;
begin
for I := 0 to (ComponentCount -1) do
begin
if (Components[I] is TEditColor) then
(Components[I] as TEditColor).ReadOnly := True;
if (Components[I] is TNumerico) then
(Components[I] as TNumerico).ReadOnly := True;
end;
end;
procedure TFMostraDuplicata.CarregaEdits(Dados: TDadosDuplicata);
begin
EDataEmissao.Text := DateToStr(Dados.DataEmissao);
ENumero.Text := Dados.Numero;
EValor.AValor := Dados.Valor;
ENroOrdem.Text := Dados.NroOrdem;
EDataVencimento.Text := DateToStr(Dados.DataVencimento);
EDescontoDe.AValor := Dados.DescontoDe;
EDataPagtoAte.Text := DateToStr(Dados.DataPagtoAte);
ECondEspeciais.Text := Dados.CondEspeciais;
ENomeSacado.Text := Dados.NomeSacado;
EEnderecoSacado.Text := Dados.EnderecoSacado;
ECidadeSacado.Text := Dados.CidadeSacado;
EEstadoSacado.Text := Dados.EstadoSacado;
EBairroSacado.Text := Dados.Bairro;
EInscricaoCGC.Text := Dados.InscricaoCGC;
EInscricaoEstadual.Text := Dados.InscricaoEstadual;
EPracaPagto.Text := Dados.PracaPagto;
EDescValor1.Text := Dados.DescValor1;
EDescValor2.Text := Dados.DescValor2;
EValorTotal.AValor := Dados.ValorTotal;
ERepresentante.Text := Dados.Representante;
ECodRepresentante.Text := Dados.Cod_Representante;
ECodSacado.Text := Dados.Cod_Sacado;
ECep.Text := Dados.CEP;
end;
procedure TFMostraDuplicata.CarregaDados(Dados: TDadosDuplicata);
begin
Dados.DataEmissao := StrToDate(EDataEmissao.Text);
Dados.Numero := ENumero.Text;
Dados.Valor := EValor.AValor;
Dados.NroOrdem := ENroOrdem.Text;
Dados.DataVencimento := StrToDate(EDataVencimento.Text);
Dados.DescontoDe := EDescontoDe.AValor;
Dados.DataPagtoAte := StrToDate(EDataPagtoAte.Text);
Dados.CondEspeciais := ECondEspeciais.Text;
Dados.NomeSacado := ENomeSacado.Text;
Dados.EnderecoSacado := EEnderecoSacado.Text;
Dados.CidadeSacado := ECidadeSacado.Text;
Dados.EstadoSacado := EEstadoSacado.Text;
Dados.Bairro := EBairroSacado.Text;
Dados.InscricaoCGC := EInscricaoCGC.Text;
Dados.InscricaoEstadual := EInscricaoEstadual.Text;
Dados.PracaPagto := EPracaPagto.Text;
Dados.DescValor1 := EDescValor1.Text;
Dados.DescValor2 := EDescValor2.Text;
Dados.ValorTotal := EValorTotal.AValor;
Dados.Representante := ERepresentante.Text;
Dados.Cod_Representante := ECodRepresentante.Text;
Dados.Cod_Sacado := ECodSacado.Text;
Dados.CEP := ECep.Text;
end;
procedure TFMostraDuplicata.CModeloCloseUp(Sender: TObject);
begin
// Limpa os Edits.
LimpaEdits(FMostraDuplicata);
LimpaEditsNumericos(FMostraDuplicata);
// Configura e limita os edits.
if (not CAD_DOC.EOF) then
IMP.LimitaTamanhoCampos(FMostraDuplicata, CAD_DOCI_NRO_DOC.AsInteger);
end;
procedure TFMostraDuplicata.FormShow(Sender: TObject);
begin
CModelo.KeyValue:=CAD_DOCI_NRO_DOC.AsInteger; // Posiciona no Primeiro;
// Configura e limita os edits.
if (not CAD_DOC.EOF) then
IMP.LimitaTamanhoCampos(FMostraDuplicata, CAD_DOCI_NRO_DOC.AsInteger);
end;
procedure TFMostraDuplicata.ECodSacadoRetorno(VpaColunas: TRBColunasLocaliza);
begin
if ECodSacado.AInteiro <> 0 then
begin
VprDCliente.CodCliente := ECodSacado.AInteiro;
FunClientes.CarDCliente(VprDCliente);
ENomeSacado.Text := VprDCliente.NomCliente;
if (VprDCliente.DesEnderecoCobranca <> '')
and (VprDCliente.CepClienteCobranca <> '')
and (VprDCliente.NumEnderecoCobranca <> '') then
begin
EEnderecoSacado.Text := VprDCliente.DesEnderecoCobranca + ', ' + VprDCliente.NumEnderecoCobranca;
ECidadeSacado.Text := VprDCliente.DesCidadeCobranca;
EEstadoSacado.Text := VprDCliente.DesUfCobranca;
EBairroSacado.Text := VprDCliente.DesBairroCobranca;
ECep.Text := VprDCliente.CepClienteCobranca;
end else
begin
EEnderecoSacado.Text := VprDCliente.DesEndereco + ', ' + VprDCliente.NumEndereco;
ECidadeSacado.Text := VprDCliente.DesCidade;
EEstadoSacado.Text := VprDCliente.DesUF;
EBairroSacado.Text := VprDCliente.DesBairro;
ECep.Text := VprDCliente.CepCliente;
end;
EInscricaoCGC.Text := VprDCliente.CGC_CPF;
EInscricaoEstadual.Text := VprDCliente.InscricaoEstadual;
EPracaPagto.Text := VprDCliente.DesPracaPagto;
end;
end;
procedure TFMostraDuplicata.EValorChange(Sender: TObject);
var
AUX: string;
begin
if (EValor.AValor > 0) then
begin
AUX := Maiusculas(RetiraAcentuacao(Extenso(EValor.AValor, 'reais', 'real')));
DivideTextoDoisComponentes(EDescValor1, EDescValor2, AUX);
end
else
begin
// Limpa descrição de valores.
EDescValor1.Clear;
EDescValor2.Clear;
end;
end;
Initialization
RegisterClasses([TFMostraDuplicata]);
end.
|
unit Quorum;
interface
uses
Classes, Btrieve, SysUtils, Windows, Forms, Dialogs, Utilits;
const
qtByte = 3;
qtWord = 4;
qtLongint = 6;
qtDate = 7;
qtTime = 8;
qtDouble = 11;
qtString = 12;
const
DeleteText: string = #$93+#$84+#$80+#$8B; {'УДАЛ' в дос-кодировке}
//Добавлено Меркуловым
BankNameText: string = 'Џ…ђЊ‘Љ€‰ ”€‹€Ђ‹ "’ЉЃ" (‡ЂЋ) ѓ Џ…ђЊњ';
type
TDicName = string[20];
TDicTitle = string[40];
TFileDicRec = packed record
frCode: Word; {Код таблицы} {k0}
frName: TDicName; {Имя таблицы} {k1}
frOwnerName: string[8]; {Имя владельца}
frTitle: TDicTitle; {Заголовок таблицы} {k2}
frLoc: string[65]; {Имя файла} {k3}
frCheckSum: Longint; {Контрольная сумма}
frLoc2: string[61]; {Не применяется}
frFlags: Word; {Флаги}
frFormat: Byte; {Формат файла}
frAttr: Word; {Атрибуты файла}
frPageSize: Word; {Размер страницы}
frRecordFixed: Word; {Размер фиксированной части записи}
frRecordSize: Word; {Размер записи}
end;
PFieldDicRec = ^TFieldDicRec;
TFieldDicRec = packed record
fiCode: Word; {Код поля 0,2} {k0.2}
fiFileCode: Word; {Код файла 2,2} {k0.1} {k1.1} {k2.1}
fiName: TDicName; {Имя поля 4,21} {k1.2} {k3}
fiTitle: TDicTitle; {Заголовок поля 25,41} {k2.2} {k4}
fiDataType: Byte; {Тип поля 66,1}
fiOffset: Word; {Смещение 67,2}
fiSize: Word; {Размер 69,2}
fiTypeCode: Word; {Код типа данных 71,2}
end; {73}
TAccCurrKey = packed record
ackOpen_Close: Word;
ackCurrCode: string[3];
ackAccNum: string[10];
end;
TAccSortCurrKey = packed record
ascAccSort: string[12];
ascCurrCode: string[3];
end;
TProKey = packed record
pkProDate: Integer;
pkProCode: Longint;
end;
//Добавлено Меркуловым
TCashKey = packed record
pcNumOp: LongInt;
pcStat: Word;
end;
//Добавлено Меркуловым
TKbkKey = packed record
dsCode: Word;
dsShifrV: string[80]; //Изменено
end;
TKvitKey = packed record
kkDoneFlag: Word;
kkOperation: Word;
kkOperNum: Longint;
kkStatus: word;
end;
TQuorumBase = class(TComponent)
private
FBuffer: PChar;
FFieldDef: TStringList;
FFileRec: TFileDicRec;
FBtrBase: TBtrBase;
FFileName: string;
FOpenMode: Word;
protected
function GetActive: Boolean;
function GetFieldDef(Index: Integer): TFieldDicRec;
function GetFieldDefCount: Integer;
function GetAsInteger(Index: Integer): Integer;
function GetAsFloat(Index: Integer): Double;
function GetAsString(Index: Integer): string;
procedure SetAsInteger(Index: Integer; Value: Integer);
procedure SetAsFloat(Index: Integer; Value: Double);
procedure SetAsString(Index: Integer; Value: string);
function GetFieldPtr(Index: Integer): PFieldDicRec;
function FieldInfo(Index: Integer): string;
public
property Buffer: PChar read FBuffer;
property Active: Boolean read GetActive;
property FileRec: TFileDicRec read FFileRec;
property FieldDefs[Index: Integer]: TFieldDicRec read GetFieldDef;
property FieldDefCount: Integer read GetFieldDefCount;
property AsInteger[Index: Integer]: Integer read GetAsInteger
write SetAsInteger;
property AsFloat[Index: Integer]: Double read GetAsFloat write SetAsFloat;
property AsString[Index: Integer]: string read GetAsString write SetAsString;
property BtrBase: TBtrBase read FBtrBase;
property OpenMode: Word read FOpenMode write FOpenMode;
property FileName: string read FFileName;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Init(BaseName: string): Boolean;
procedure Done;
function GetFieldIndexByName(S: string): Integer;
procedure GetIndexes(S: TStrings);
end;
const
coPayOrderOperation = 1102;
coMemOrderOperation = 1103;
coCashOrderOperation = 1116;
coRecognizeSumOperation = 1101;
coVypOperation = 1106;
coVbKartotOperation = 1113;
var
poPreStatus, poCurrCodeCorr, poCurrCodePay, poDocNum, poDocDate,
poInDate, poPayAcc, poBenefAcc, poDocType, poPaySum, poKAY, poStatus,
poStatusHlp, poBatchNum, poUserCode, poOperCode, poCorrAcc, poSenderBankNum,
poSenderMFO, poSenderUchCode, poSenderCorrAcc, poReceiverMFO, poReceiverCorrAcc,
poReceiverUchCode, poSenderCorrCode, poReceiverBankNum, poReceiverCorrCode,
poBranch, poSendType, poBatchType, poOrderType, poPriority, poRaceNum,
poZaklObor, poPosDate, poProcDate, poValueDate, poPayTelegSum, poOperNum,
poBenefTaxNum, poBenefName, poINNOur, poClientNameOur, poClientAcc,
poKppOur, poBenefKpp: Integer; //Добавлено Меркуловым
acAccNum, acAccPlch, acAccName, acClientCode, acAccStatus, acOpen_Close,
acCurrCode, acOpenDate, acCloseDate, acOperNum, acContNum, acRightBuffer,
acChSum, acClientMessage, acValueCode, acAccEndDate, acDayCount,
acAccNewPlch, acNewAccNum, acShifrMask, acUserGroupCode, acPriority,
acDivCode, acOwerContNum, acReAccPr, acReAccount, acRedCheck, acAccSort,
acAccCourse, acKindCont, acKindAcc, acKindSaldo, acOraF_ID_Filial,
acWayOfExt, acPerAmount, acPerType: Integer;
bnBankNum, bnRkcNum, bnMfo, bnUchCode, bnCorrAcc, bnBankCorrAcc, bnTypeAbbrev,
bnBankName, bnAdress: Integer;
crnAccTheir: Integer;
pcOperNum, pcStatus, pcComment, pcComOwner: Integer;
moDbAcc, moDbCurrCode, moKrAcc, moKrCurrCode, moDocNum, moDocDate, moBranch,
moUserCode, moBatchType, moBatchNum, moOperNum, moStatus, moPreStatus,
moBreak, moMassDocNum, moOrderType, moPro_Col, moDoc_Col, moInOperation,
moInOperNum, moPaySum, moVpCode, moPrNum, moPosDate, moProcDate,
moUserControl, moControlLink, moStatusHlp, moOperCode, moKay, moPayKrSum,
moPayNatSum, moZaklObor, moWhatConv, moAddInfo, moTypeKvit, moRaceNum,
moRaceDate, moKvitPossMask, moSumValue, moStorno, moRef, moReserv: Integer;
coDocDate, coDocCode, coOperCode, coUserCode, coDocNum, coStatus, coOperation,
coOperNum, coAccount, coCurrCode, coCourse, coCommission, coCommissionPerc,
coCashAcc, coCashCurrCode, coSumma_rec, coSumma_exp, coPrintFlag, coBatNum,
coKay, coContNum, coPreStatus, coStatusHlp, coFastChrg, coRemSum, coDocType,
coControlLink, coFIO, coNumCheck, coSerCheck, coPasp, coOldSerPasp,
coNumPasp, coResident, coNumSpraw, coNotPay, coMultiPay, coConvFlag,
coAccSumma, coEqvSumma, coSerPasp, coNewUserCode, coOldNomination,
coKvitPossMask, coRef, coCommissionCurr, coDocNumAdd, coWorkStr: Integer;
osdDocCode, osdSymbol, osdSumma, osdOldNom, osdSymbolCorr, osdSummaCorr,
osdWorkStr: Integer;
csSymbol, csFlag: Integer;
prProDate, prProCode, prDocDate, prDocCode, prDocNum, prContNum, prOperCode,
prUserCode, prDbCurrCode, prDbAcc, prKrCurrCode, prKrAcc, prExtAcc,
prBatNum, prKay, prZaklObor, prWorkStr, prDocKind, prOperation,
prOperation1, prOperNum, prOperNum1, prCash, prSumPro, prSumValPro,
prStorno, prBankCode, prSumKrValPro: Integer;
clClientCode, clClientName, clByte255a, clShortName, clAdress, clTelephone,
clHasModem, clPrizJur, clPropertyCode, clCodeOKPO, clRegisSer, clRegisNum,
clRegisDate, clRegisLocation, clTaxNum, clTaxDate, clTaxNumGNI,
clTaxLocation, clPasport, clBankNum, clPayAccOld, clClType, clRezident,
clCoClientClass, clCoClientType, clCuratorCode, clF775, clShifrMask,
clHasVoice, clCOPF, clCOATO, clCountryCode, clPayAcc, clClFromOffice,
clDocType, clSerPasp, clNumPasp, clDatePasp, clReasCode, clTaxDocType,
clUserCode, clWorkStr: Integer;
kvInOperation, kvInOperNum, kvInStatus, kvOutOperation, kvOutOperNum,
kvOutStatus, kvProcessDate, kvProcessSysDate, kvProcessTime, kvDoneFlag,
kvKvitType, kvUserCode, kvArcMask, kvOutStatusNew, kvOraF_ID_Kvitan,
kvPrimaryDoc, kvWorkStr: Integer;
ccComment: Integer;
cdProDate, cdProCode, cdSymbol, cdSumma: Integer;
caComment: Integer;
dpProDate, dpProCode, dpDocDate, dpDocCode, dpDocNum, dpContNum, dpOperCode,
dpUserCode, dpDbCurrCode, dpDbAcc, dpKrCurrCode, dpKrAcc, dpCorrAcc,
dpExtAcc, dpBatNum, dpKay, dpZaklObor, dpWorkStr, dpDocKind, dpOperation,
dpOperation1, dpOperNum, dpOperNum1, dpCash, dpSumPro, dpSumValPro,
dpStorno, dpBankCode, dpSumKrValPro, dpCurrentDate, dpCurrentTime,
dpDelUser, dpUnloadSeq: Integer;
{vkOldKartNum, vkAccNum, vkCurrCode, vkCorrAcc, vkCurrCodeCorr, vkDocNum,
vkDocDate, vkBranch, vkSenderCorrCode, vkSenderBankNum, vkSenderMfo,
vkSenderUchCode, vkOldSenderCorrAcc, vkReceiverCorrCode, vkReceiverBankNum,
vkReceiverMfo, vkReceiverUchCode, vkOldReceiverCorrAcc, vkOldBenefAcc,
vkDocType, vkUserCode,} vkOperNum, {vkStatus, vkPreStatus, vkBreak, vkPro_Col,
vkDoc_Col,} vkInOperation, vkInOperNum{, vkPaySum, vkVpCode, vkPrNum,
vkRospDate, vkAllSum, vkBankNumInUse, vkOperCode, vkStatusHlp, vkPosDate,
vkProcDate, vkUserControl, vkControlLink, vkValueDate, vkPriority,
vkOldBenefTaxNum, vkRaceNum, vkOrderNumber, vkLinkStatus, vkRaceDate,
vkMassDocNum, vkOrderType, vkBatchType, vkBatchNum, vkPayTelegSum,
vkBenefName, vkSendType, vkAcceptDate, vkKay, vkZaklObor, vkBenefTaxNum},
vkKartNum{, vkSenderCorrAcc, vkReceiverCorrAcc, vkBenefAcc, vkClVbAcc,
vkClKartAcc, vkNoVbUch, vkNoPartAccept, vkAkcept, vkClKartCurrCode,
vkPayNatSum, vkindate, vkInsKrtDate, vkReserv}: Integer;
dsOperation, dsOperNum, dsTypeCode, dsShifrValue: Integer;
lmProDate, lmAcc, lmCurrCode, lmLim, lmLimVal, lmDbTurn, lmDbTurnVal,
lmKrTurn, lmKrTurnVal, lmLastDate, lmRevCount, lmOperCount: Integer;
vkmOperNum, vkmAccNum, vkmCurrCode, vkmUserCode, vkmPaySum, vkmDateMove,
vkmStatus, vkmPreStatus, vkmCode, vkmPayNatSum: Integer;
//Добавлено Меркуловым
dsvTypeCode, dsvShifrValue, dsvShifrName: Integer;
ckClientCode, ckKPP, ckDefault_: Integer;
const
NumOfQrmBases = 22; //Добавлено Меркуловым
qbPayOrder = 1;
qbAccounts = 2;
qbBanks = 3;
qbCorRespNew = 4;
qbPayOrCom = 5;
qbMemOrder = 6;
qbCashOrder = 7;
qbCashOSD = 8;
qbCashSym = 9;
qbPro = 10;
qbClients = 11;
qbKvitan = 12;
qbCashComA = 13;
qbCashsDA = 14;
qbCommentADoc = 15;
qbDelPro = 16;
qbVbKartOt = 17;
qbDocsBySh = 18;
qbLim = 19;
qbVKrtMove = 20;
qbDocShfrV = 21; //Добавлено Меркуловым
qbCliKpp = 22; //Добавлено Меркуловым
QrmBaseNames: array[1..NumOfQrmBases] of PChar = (
'PayOrder', 'Accounts', 'Banks', 'CorRespNew', 'PayOrCom', 'MemOrder',
'CashOrder', 'CashOSD', 'CashSym', 'Pro', 'Clients', 'Kvitan', 'CashComA',
'CashsDA', 'CommentADoc', 'DelPro', 'VbKartOt', 'DocsByShifr', 'Lim',
'VKrtMove',
'DocShfrValues', 'CliKpp'); //Добавлено Меркуловым
var
QrmBases: array[1..NumOfQrmBases] of TQuorumBase;
const
KvitStatus = 50;
procedure SetDictDir(Value: string);
function DictDir: string;
procedure SetDataDir(Value: string);
function DataDir: string;
procedure SetQuorumDir(Value: string);
function QuorumDir: string;
function QuorumDictDir: string;
function QuorumDataDir: string;
function DecodeQuorumPath(S: string): string;
procedure CloseDictionary;
function OpenDictionary: Boolean;
function QrmBasesIsOpen: Boolean;
procedure GetQrmOpenedBases(var Opened, All: Integer);
function InitQuorumBase(QuorumDir, DictDir, DataDir: string): Boolean;
procedure DoneQuorumBase;
function DocumentIsExistInQuorum(Operation: Word; OperNum: Integer;
var Status: Word): Integer;
function KbkNotExistInQBase(ClientKBK: ShortString): Boolean; //Добавлено Меркуловым
function CompareKpp(ClntRS, ClntKpp: string): Boolean;//Добавлено Меркуловым
function SeeNationalCurr: string;
function GetAccAndCurrByNewAcc(Acc: ShortString;
var AccNum, CurrCode: ShortString; var UserCode: Integer): Boolean;
function GetNewAccByAccAndCurr(AccNum, CurrCode: ShortString;
var Acc: ShortString): Boolean;
function GetClientByAcc(ClientAcc, ClientCurrCode: ShortString;
var ClientInn, ClientName, ClientNewAcc: ShortString): Boolean;
function GetLimByAccAndDate(AccNum, CurrCode: ShortString;
ProDate: Integer; var Sum: Double): Boolean;
function GetBankByRekvisit(BankNum: ShortString; Info: Boolean; var CorrCode,
UchCode, MFO, CorrAcc: ShortString): Boolean;
function GetSenderCorrAcc(CurrCode, CorrAcc: ShortString): ShortString;
function GetChildOperNumByKvitan(InOperation: Word; InOperNum: Longint;
NeedOutOperation: Word): Integer;
function GetParentOperNumByKvitan(OutOperation: Word; OutOperNum: Longint;
NeedInOperation: Word): Integer;
function GetCashNazn(S: string): string;
function SortAcc(AccNum: ShortString): ShortString;
implementation
var
FDictDir: string = 'TESTDICT\';
FDataDir: string = 'TESTDATA\';
FQuorumDir: string = 'F:\QUORUM.703\';
function SlashDir(S: string): string;
var
L: Integer;
begin
Result := S;
L := Length(Result);
if (L>0) and (Result[L]<>'\') then
Result := Result + '\';
end;
procedure SetDictDir(Value: string);
begin
FDictDir := SlashDir(Value);
end;
function DictDir: string;
begin
Result := FDictDir;
end;
procedure SetDataDir(Value: string);
begin
FDataDir := SlashDir(Value);
end;
function DataDir: string;
begin
Result := FDataDir;
end;
procedure SetQuorumDir(Value: string);
begin
FQuorumDir := SlashDir(Value);
end;
function QuorumDir: string;
begin
Result := FQuorumDir;
end;
function QuorumDictDir: string;
begin
Result := FQuorumDir + FDictDir;
end;
function QuorumDataDir: string;
begin
Result := FQuorumDir + FDataDir;
end;
function DecodeQuorumPath(S: string): string;
const
Key1: string = '%DATA_PATH%DATA\';
var
I: Integer;
begin
S := Trim(UpperCase(S));
I := Pos(Key1, S);
if I>0 then
begin
I := I+Length(Key1);
S := QuorumDataDir+Copy(S, I, Length(S)-I+1);
end;
I := Pos('%', S);
while I>0 do
begin
Delete(S, I, 1);
I := Pos('%', S);
end;
Result := S;
end;
var
FileBase: TBtrBase = nil;
FieldBase: TBtrBase = nil;
procedure CloseDictionary;
begin
if FileBase<>nil then
begin
FileBase.Close;
FileBase.Free;
FileBase := nil;
end;
if FieldBase<>nil then
begin
FieldBase.Close;
FieldBase.Free;
FieldBase := nil;
end;
end;
function OpenDictionary: Boolean;
const
MesTitle: PChar = 'Открытие словаря';
var
Res: Integer;
Buf: array[0..511] of Char;
begin
Result := FileBase<>nil;
if not Result then
begin
FileBase := TBtrBase.Create;
FieldBase := TBtrBase.Create;
StrPLCopy(Buf, QuorumDictDir+'file.adf', SizeOf(Buf)-1);
Res := FileBase.Open(Buf, baReadOnly);
Result := Res=0;
if Result then
begin
StrPLCopy(Buf, QuorumDictDir+'field.adf', SizeOf(Buf)-1);
Res := FieldBase.Open(Buf, baReadOnly);
Result := Res=0;
if not Result then
ProtoMes(plError, MesTitle, 'Не удалось открыть ['+Buf+'] BtrErr='+IntToStr(Res));
end
else
ProtoMes(plError, MesTitle, 'Не удалось открыть ['+Buf+']');
if not Result then
CloseDictionary;
end;
end;
function QrmTypeToStr(AType: Word): string;
begin
case AType of
qtByte:
Result := 'Byte';
qtWord:
Result := 'Word';
qtLongint:
Result := 'Longint';
qtDate:
Result := 'Date';
qtTime:
Result := 'Time';
qtDouble:
Result := 'Double';
qtString:
Result := 'String';
else
Result := 'unknown';
end;
end;
constructor TQuorumBase.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFieldDef := TStringList.Create;
FBuffer := nil;
FBtrBase := nil;
FFileName := '';
FOpenMode := baNormal;
Done;
end;
destructor TQuorumBase.Destroy;
begin
Done;
FFieldDef.Free;
inherited Destroy;
end;
function TQuorumBase.GetActive: Boolean;
begin
Result := FBuffer<>nil;
end;
function TQuorumBase.GetFieldDef(Index: Integer): TFieldDicRec;
var
P: Pointer;
begin
with FFieldDef do
if Index<Count then
P := Objects[Index]
else
P := nil;
if P=nil then
FillChar(Result, SizeOf(Result), #0)
else
Move(P^, Result, SizeOf(Result));
end;
function TQuorumBase.GetFieldDefCount: Integer;
begin
Result := FFieldDef.Count;
end;
function TQuorumBase.GetFieldIndexByName(S: string): Integer;
begin
Result := FFieldDef.IndexOf(S);
end;
procedure TQuorumBase.GetIndexes(S: TStrings);
var
I: Integer;
begin
for I := 0 to S.Count do
S.Objects[I] := TObject(GetFieldIndexByName(S.Strings[I]));
end;
procedure TQuorumBase.Done;
var
P: Pointer;
begin
if FBtrBase<>nil then
begin
if Length(FFileName)>0 then
FBtrBase.Close;
FBtrBase.Free;
FBtrBase := nil;
end;
if FBuffer<>nil then
begin
FreeMem(FBuffer);
FBuffer := nil;
end;
with FFieldDef do
while Count>0 do
begin
P := Objects[Count-1];
if P<>nil then
FreeMem(P);
Delete(Count-1);
end;
FillChar(FFileRec, SizeOf(FFileRec), #0);
end;
function TQuorumBase.Init(BaseName: string): Boolean;
const
MesTitle: PChar = 'Инициализация q-записи';
var
Res, Len: Integer;
N: TDicName;
FieldKey:
packed record
fiFileCode: Word;
fiName: TDicName;
end;
FieldRec: TFieldDicRec;
P: Pointer;
begin
Result := FileBase<>nil;
if Result then
begin
Result := False;
Done;
N := BaseName;
Len := SizeOf(FFileRec);
Res := FileBase.GetEqual(FFileRec, Len, N, 1);
if Res=0 then
begin
GetMem(FBuffer, FFileRec.frRecordFixed);
FillChar(FBuffer^, FFileRec.frRecordFixed, #0);
FieldKey.fiFileCode := FileRec.frCode;
FillChar(FieldKey.fiName, SizeOf(FieldKey.fiName), #0);
Len := SizeOf(FieldRec);
Res := FieldBase.GetGE(FieldRec, Len, FieldKey, 1);
while (Res=0) and (FieldRec.fiFileCode = FileRec.frCode) do
begin
GetMem(P, SizeOf(FieldRec));
Move(FieldRec, P^, SizeOf(FieldRec));
FFieldDef.AddObject(FieldRec.fiName, P);
Len := SizeOf(FieldRec);
Res := FieldBase.GetNext(FieldRec, Len, FieldKey, 1);
end;
FBtrBase := TBtrBase.Create;
FFileName := DecodeQuorumPath(FileRec.frLoc);
Res := FBtrBase.Open(FFileName, FOpenMode);
Result := Res=0;
if not Result then
begin
ProtoMes({plError}plWarning, MesTitle, 'Не удалось открыть таблицу ['+FFileName
+']. BtrErr='+IntToStr(Res)+' база ['+BaseName+']');
FFileName := '';
end;
end
else begin
FillChar(FFileRec, SizeOf(FFileRec), #0);
ProtoMes(plError, MesTitle, 'Таблица ['+BaseName
+'] не найдена в словаре. BtrErr='+IntToStr(Res)+' база ['+BaseName+']');
end;
end
else
ProtoMes(plWarning, MesTitle, 'Словарь закрыт');
end;
function TQuorumBase.GetFieldPtr(Index: Integer): PFieldDicRec;
const
MesTitle: PChar = 'GetFieldPtr';
begin
if (Index>=0) and (Index<FFieldDef.Count) then
Result := Pointer(FFieldDef.Objects[Index])
else begin
Result := nil;
ProtoMes(plWarning, MesTitle, 'Запрос поля недопустимого индекса '+IntToStr(Index));
end;
end;
function TQuorumBase.FieldInfo(Index: Integer): string;
var
P: PFieldDicRec;
begin
P := GetFieldPtr(Index);
Result := P^.fiName+':'+QrmTypeToStr(P^.fiTypeCode);
end;
function TQuorumBase.GetAsInteger(Index: Integer): Integer;
const
MesTitle: PChar = 'GetAsInteger';
var
P: PFieldDicRec;
begin
P := GetFieldPtr(Index);
{showmessage(MesTitle+' : '+P^.fiName+' - '+ IntToStr(P^.fiOffset));}
case P^.fiDataType of
qtByte:
Result := PByte(@FBuffer[P^.fiOffset])^;
qtWord:
Result := PWord(@FBuffer[P^.fiOffset])^;
qtLongint, qtDate, qtTime:
Result := PLongInt(@FBuffer[P^.fiOffset])^;
qtDouble:
Result := Round(PDouble(@FBuffer[P^.fiOffset])^);
qtString:
try
Result := StrToInt(PShortString(@FBuffer[P^.fiOffset])^);
except
Result := 0;
end;
else begin
Result := 0;
ProtoMes(plError, MesTitle, 'Недопустимое чтение по индексу поля '
+IntToStr(Index));
end;
end;
end;
function TQuorumBase.GetAsFloat(Index: Integer): Double;
const
MesTitle: PChar = 'GetAsFloat';
var
P: PFieldDicRec;
begin
P := GetFieldPtr(Index);
{showmessage(MesTitle+' : '+P^.fiName+' - '+ IntToStr(P^.fiOffset));}
case P^.fiDataType of
qtByte:
Result := PByte(@FBuffer[P^.fiOffset])^;
qtWord:
Result := PWord(@FBuffer[P^.fiOffset])^;
qtLongint, qtDate, qtTime:
Result := PLongInt(@FBuffer[P^.fiOffset])^;
qtDouble:
Result := PDouble(@FBuffer[P^.fiOffset])^;
qtString:
try
Result := StrToFloat(PShortString(@FBuffer[P^.fiOffset])^);
except
Result := 0.0;
end;
else begin
Result := 0;
ProtoMes(plError, MesTitle, 'Недопустимое чтение по индексу поля '
+IntToStr(Index));
end;
end;
end;
function TQuorumBase.GetAsString(Index: Integer): string;
const
MesTitle: PChar = 'GetAsString';
var
P: PFieldDicRec;
begin
P := GetFieldPtr(Index);
{showmessage(MesTitle+' : '+P^.fiName+' - '+ IntToStr(P^.fiOffset));}
case P^.fiDataType of
qtString:
Result := PShortString(@FBuffer[P^.fiOffset])^;
qtByte:
Result := IntToStr(PByte(@FBuffer[P^.fiOffset])^);
qtWord:
Result := IntToStr(PWord(@FBuffer[P^.fiOffset])^);
qtLongint, qtDate, qtTime:
Result := IntToStr(PLongInt(@FBuffer[P^.fiOffset])^);
qtDouble:
Result := FloatToStr(PDouble(@FBuffer[P^.fiOffset])^);
else begin
Result := '';
ProtoMes(plError, MesTitle, 'Недопустимое чтение по индексу поля '
+IntToStr(Index));
end;
end;
end;
procedure FieldErrorMes(Index, Code: Integer; MesTitle: PChar);
begin
ProtoMes(plError, MesTitle, 'Недопустимое присвоение '+IntToStr(Code)
+' по индексу поля ' +IntToStr(Index));
end;
procedure TQuorumBase.SetAsInteger(Index: Integer; Value: Integer);
const
MesTitle: PChar = 'SetAsInteger';
var
P: PFieldDicRec;
begin
P := GetFieldPtr(Index);
{showmessage(MesTitle+' : '+P^.fiName+' - '+ IntToStr(P^.fiOffset));}
case P^.fiDataType of
qtString:
PShortString(@FBuffer[P^.fiOffset])^ := Copy(IntToStr(Value), 1, P^.fiSize-1);
qtByte:
PByte(@FBuffer[P^.fiOffset])^ := Value;
qtWord:
PWord(@FBuffer[P^.fiOffset])^ := Value;
qtLongint, qtDate, qtTime:
PLongInt(@FBuffer[P^.fiOffset])^ := Value;
qtDouble:
PDouble(@FBuffer[P^.fiOffset])^ := Value;
else
FieldErrorMes(Index, P^.fiDataType, MesTitle);
end;
end;
procedure TQuorumBase.SetAsFloat(Index: Integer; Value: Double);
const
MesTitle: PChar = 'SetAsFloat';
var
P: PFieldDicRec;
begin
P := GetFieldPtr(Index);
{showmessage(MesTitle+' : '+P^.fiName+' - '+ IntToStr(P^.fiOffset));}
case P^.fiDataType of
qtByte:
PByte(@FBuffer[P^.fiOffset])^ := Round(Value);
qtWord:
PWord(@FBuffer[P^.fiOffset])^ := Round(Value);
qtLongint, qtDate, qtTime:
PLongInt(@FBuffer[P^.fiOffset])^ := Round(Value);
qtDouble:
PDouble(@FBuffer[P^.fiOffset])^ := Value;
qtString:
PShortString(@FBuffer[P^.fiOffset])^ := Copy(FloatToStr(Value), 1, P^.fiSize-1);
else
FieldErrorMes(Index, P^.fiDataType, MesTitle);
end;
end;
procedure TQuorumBase.SetAsString(Index: Integer; Value: string);
const
MesTitle: PChar = 'SetAsString';
var
P: PFieldDicRec;
begin
P := GetFieldPtr(Index);
{showmessage(MesTitle+' : '+P^.fiName+' - '+ IntToStr(P^.fiOffset));}
case P^.fiDataType of
qtString:
PShortString(@FBuffer[P^.fiOffset])^ := Copy(Value, 1, P^.fiSize-1);
qtByte:
try
PByte(@FBuffer[P^.fiOffset])^ := StrToInt(Value);
except
PByte(@FBuffer[P^.fiOffset])^ := 0;
end;
qtWord:
try
PWord(@FBuffer[P^.fiOffset])^ := StrToInt(Value);
except
PWord(@FBuffer[P^.fiOffset])^ := 0;
end;
qtLongint, qtDate, qtTime:
try
PLongInt(@FBuffer[P^.fiOffset])^ := StrToInt(Value);
except
PLongInt(@FBuffer[P^.fiOffset])^ := 0;
end;
qtDouble:
try
PDouble(@FBuffer[P^.fiOffset])^ := StrToFloat(Value);
except
PDouble(@FBuffer[P^.fiOffset])^ := 0.0;
end;
else
FieldErrorMes(Index, P^.fiDataType, MesTitle);
end;
end;
procedure ProGetNeedIndexes;
begin
with QrmBases[qbPro] do //Проводки
begin
prProDate := GetFieldIndexByName('ProDate'); //"Дата проводки"
prProCode := GetFieldIndexByName('ProCode'); //
prDocDate := GetFieldIndexByName('DocDate'); //
prDocCode := GetFieldIndexByName('DocCode'); //
prDocNum := GetFieldIndexByName('DocNum'); //
prContNum := GetFieldIndexByName('ContNum'); //
prOperCode := GetFieldIndexByName('OperCode'); //
prUserCode := GetFieldIndexByName('UserCode'); //
prDbCurrCode := GetFieldIndexByName('DbCurrCode'); //
prDbAcc := GetFieldIndexByName('DbAcc'); //
prKrCurrCode := GetFieldIndexByName('KrCurrCode'); //
prKrAcc := GetFieldIndexByName('KrAcc'); //
prExtAcc := GetFieldIndexByName('ExtAcc'); //
prBatNum := GetFieldIndexByName('BatNum'); //
prKay := GetFieldIndexByName('Kay'); //
prZaklObor := GetFieldIndexByName('ZaklObor'); //
prWorkStr := GetFieldIndexByName('WorkStr'); //
prDocKind := GetFieldIndexByName('DocKind'); //
prOperation := GetFieldIndexByName('Operation'); //
prOperation1 := GetFieldIndexByName('Operation1'); //
prOperNum := GetFieldIndexByName('OperNum'); //
prOperNum1 := GetFieldIndexByName('OperNum1'); //
prCash := GetFieldIndexByName('Cash'); //
prSumPro := GetFieldIndexByName('SumPro'); //
prSumValPro := GetFieldIndexByName('SumValPro'); //
prStorno := GetFieldIndexByName('Storno'); //
prBankCode := GetFieldIndexByName('BankCode'); //
prSumKrValPro := GetFieldIndexByName('SumKrValPro'); //
end;
end;
procedure DelProGetNeedIndexes;
begin
with QrmBases[qbDelPro] do
begin
dpProDate := GetFieldIndexByName('ProDate'); //
dpProCode := GetFieldIndexByName('ProCode'); //
dpDocDate := GetFieldIndexByName('DocDate'); //
dpDocCode := GetFieldIndexByName('DocCode'); //
dpDocNum := GetFieldIndexByName('DocNum'); //
dpContNum := GetFieldIndexByName('ContNum'); //
dpOperCode := GetFieldIndexByName('OperCode'); //
dpUserCode := GetFieldIndexByName('UserCode'); //
dpDbCurrCode := GetFieldIndexByName('DbCurrCode'); //
dpDbAcc := GetFieldIndexByName('DbAcc'); //
dpKrCurrCode := GetFieldIndexByName('KrCurrCode'); //
dpKrAcc := GetFieldIndexByName('KrAcc'); //
dpCorrAcc := GetFieldIndexByName('CorrAcc'); //
dpExtAcc := GetFieldIndexByName('ExtAcc'); //
dpBatNum := GetFieldIndexByName('BatNum'); //
dpKay := GetFieldIndexByName('Kay'); //
dpZaklObor := GetFieldIndexByName('ZaklObor'); //
dpWorkStr := GetFieldIndexByName('WorkStr'); //
dpDocKind := GetFieldIndexByName('DocKind'); //
dpOperation := GetFieldIndexByName('Operation'); //
dpOperation1 := GetFieldIndexByName('Operation1'); //
dpOperNum := GetFieldIndexByName('OperNum'); //
dpOperNum1 := GetFieldIndexByName('OperNum1'); //
dpCash := GetFieldIndexByName('Cash'); //
dpSumPro := GetFieldIndexByName('SumPro'); //
dpSumValPro := GetFieldIndexByName('SumValPro'); //
dpStorno := GetFieldIndexByName('Storno'); //
dpBankCode := GetFieldIndexByName('BankCode'); //
dpSumKrValPro := GetFieldIndexByName('SumKrValPro');//
dpCurrentDate := GetFieldIndexByName('CurrentDate');//
dpCurrentTime := GetFieldIndexByName('CurrentTime');//
dpDelUser := GetFieldIndexByName('DelUser'); //
dpUnloadSeq := GetFieldIndexByName('UnloadSeq'); //
end;
end;
procedure VbKartOtGetNeedIndexes;
begin
with QrmBases[qbVbKartOt] do
begin
{vkOldKartNum := GetFieldIndexByName('OldKartNum'); //
vkAccNum := GetFieldIndexByName('AccNum'); //
vkCurrCode := GetFieldIndexByName('CurrCode'); //
vkCorrAcc := GetFieldIndexByName('CorrAcc'); //
vkCurrCodeCorr := GetFieldIndexByName('CurrCodeCorr'); //
vkDocNum := GetFieldIndexByName('DocNum'); //
vkDocDate := GetFieldIndexByName('DocDate'); //
vkBranch := GetFieldIndexByName('Branch'); //
vkSenderCorrCode := GetFieldIndexByName('SenderCorrCode'); //
vkSenderBankNum := GetFieldIndexByName('SenderBankNum'); //
vkSenderMfo := GetFieldIndexByName('SenderMfo'); //
vkSenderUchCode := GetFieldIndexByName('SenderUchCode'); //
vkOldSenderCorrAcc := GetFieldIndexByName('OldSenderCorrAcc'); //
vkReceiverCorrCode := GetFieldIndexByName('ReceiverCorrCode'); //
vkReceiverBankNum := GetFieldIndexByName('ReceiverBankNum'); //
vkReceiverMfo := GetFieldIndexByName('ReceiverMfo'); //
vkReceiverUchCode := GetFieldIndexByName('ReceiverUchCode'); //
vkOldReceiverCorrAcc := GetFieldIndexByName('OldReceiverCorrAcc'); //
vkOldBenefAcc := GetFieldIndexByName('OldBenefAcc'); //
vkDocType := GetFieldIndexByName('DocType'); //
vkUserCode := GetFieldIndexByName('UserCode');} //
vkOperNum := GetFieldIndexByName('OperNum'); //
{vkStatus := GetFieldIndexByName('Status'); //
vkPreStatus := GetFieldIndexByName('PreStatus'); //
vkBreak := GetFieldIndexByName('Break'); //
vkPro_Col := GetFieldIndexByName('Pro_Col'); //
vkDoc_Col := GetFieldIndexByName('Doc_Col');} //
vkInOperation := GetFieldIndexByName('InOperation'); //
vkInOperNum := GetFieldIndexByName('InOperNum'); //
{vkPaySum := GetFieldIndexByName('PaySum'); //
vkVpCode := GetFieldIndexByName('VpCode'); //
vkPrNum := GetFieldIndexByName('PrNum'); //
vkRospDate := GetFieldIndexByName('RospDate'); //
vkAllSum := GetFieldIndexByName('AllSum'); //
vkBankNumInUse := GetFieldIndexByName('BankNumInUse'); //
vkOperCode := GetFieldIndexByName('OperCode'); //
vkStatusHlp := GetFieldIndexByName('StatusHlp'); //
vkPosDate := GetFieldIndexByName('PosDate'); //
vkProcDate := GetFieldIndexByName('ProcDate'); //
vkUserControl := GetFieldIndexByName('UserControl'); //
vkControlLink := GetFieldIndexByName('ControlLink'); //
vkValueDate := GetFieldIndexByName('ValueDate'); //
vkPriority := GetFieldIndexByName('Priority'); //
vkOldBenefTaxNum := GetFieldIndexByName('OldBenefTaxNum'); //
vkRaceNum := GetFieldIndexByName('RaceNum'); //
vkOrderNumber := GetFieldIndexByName('OrderNumber'); //
vkLinkStatus := GetFieldIndexByName('LinkStatus'); //
vkRaceDate := GetFieldIndexByName('RaceDate'); //
vkMassDocNum := GetFieldIndexByName('MassDocNum'); //
vkOrderType := GetFieldIndexByName('OrderType'); //
vkBatchType := GetFieldIndexByName('BatchType'); //
vkBatchNum := GetFieldIndexByName('BatchNum'); //
vkPayTelegSum := GetFieldIndexByName('PayTelegSum'); //
vkBenefName := GetFieldIndexByName('BenefName'); //
vkSendType := GetFieldIndexByName('SendType'); //
vkAcceptDate := GetFieldIndexByName('AcceptDate'); //
vkKay := GetFieldIndexByName('Kay'); //
vkZaklObor := GetFieldIndexByName('ZaklObor'); //
vkBenefTaxNum := GetFieldIndexByName('BenefTaxNum');} //
vkKartNum := GetFieldIndexByName('KartNum'); //
{vkSenderCorrAcc := GetFieldIndexByName('SenderCorrAcc'); //
vkReceiverCorrAcc := GetFieldIndexByName('ReceiverCorrAcc'); //
vkBenefAcc := GetFieldIndexByName('BenefAcc'); //
vkClVbAcc := GetFieldIndexByName('ClVbAcc'); //
vkClKartAcc := GetFieldIndexByName('ClKartAcc'); //
vkNoVbUch := GetFieldIndexByName('NoVbUch'); //
vkNoPartAccept := GetFieldIndexByName('NoPartAccept'); //
vkAkcept := GetFieldIndexByName('Akcept'); //
vkClKartCurrCode := GetFieldIndexByName('ClKartCurrCode'); //
vkPayNatSum := GetFieldIndexByName('PayNatSum'); //
vkindate := GetFieldIndexByName('indate'); //
vkInsKrtDate := GetFieldIndexByName('InsKrtDate'); //
vkReserv := GetFieldIndexByName('Reserv');} //
end;
end;
procedure DocsByShGetNeedIndexes;
begin
with QrmBases[qbDocsBySh] do
begin
dsOperation := GetFieldIndexByName('Operation'); //
dsOperNum := GetFieldIndexByName('OperNum'); //
dsTypeCode := GetFieldIndexByName('TypeCode'); //
dsShifrValue := GetFieldIndexByName('ShifrValue');
end;
end;
procedure LimGetNeedIndexes;
begin
with QrmBases[qbLim] do
begin
lmProDate := GetFieldIndexByName('ProDate'); //
lmAcc := GetFieldIndexByName('Acc'); //
lmCurrCode := GetFieldIndexByName('CurrCode'); //
lmLim := GetFieldIndexByName('Lim'); //
lmLimVal := GetFieldIndexByName('LimVal'); //
lmDbTurn := GetFieldIndexByName('DbTurn'); //
lmDbTurnVal := GetFieldIndexByName('DbTurnVal'); //
lmKrTurn := GetFieldIndexByName('KrTurn'); //
lmKrTurnVal := GetFieldIndexByName('KrTurnVal'); //
lmLastDate := GetFieldIndexByName('LastDate'); //
lmRevCount := GetFieldIndexByName('RevCount'); //
lmOperCount := GetFieldIndexByName('OperCount'); //
end;
end;
procedure CashComAGetNeedIndexes;
begin
with QrmBases[qbCashComA] do
begin
ccComment := GetFieldIndexByName('Comment'); //
end;
end;
procedure CashsDAGetNeedIndexes;
begin
with QrmBases[qbCashsDA] do
begin
cdProDate := GetFieldIndexByName('ProDate'); //
cdProCode := GetFieldIndexByName('ProCode'); //
// cdSymbol := GetFieldIndexByName('Symbol'); //
cdSymbol := GetFieldIndexByName('Symbol'); //
cdSumma := GetFieldIndexByName('Summa'); //
end;
end;
procedure CommentADocGetNeedIndexes;
begin
with QrmBases[qbCommentADoc] do //
begin
{ProDate : Date "Дата проводки", //
ProCode : longint "Код проводки",} //
caComment := GetFieldIndexByName('Comment'); //
{TypeOper : str3 "Вид операции", //
UserAbbr : str3 "Код операциониста", //
Ref : Str16 "Референс", //
WorkStr : Str20 "Резерв"} //
end;
end;
procedure KvitanGetNeedIndexes;
begin
with QrmBases[qbKvitan] do
begin
kvInOperation := GetFieldIndexByName('InOperation'); //
kvInOperNum := GetFieldIndexByName('InOperNum'); //
kvInStatus := GetFieldIndexByName('InStatus'); //
kvOutOperation := GetFieldIndexByName('OutOperation'); //
kvOutOperNum := GetFieldIndexByName('OutOperNum'); //
kvOutStatus := GetFieldIndexByName('OutStatus'); //
kvProcessDate := GetFieldIndexByName('ProcessDate'); //
kvProcessSysDate := GetFieldIndexByName('ProcessSysDate');//
kvProcessTime := GetFieldIndexByName('ProcessTime'); //
kvDoneFlag := GetFieldIndexByName('DoneFlag'); //
kvKvitType := GetFieldIndexByName('KvitType'); //
kvUserCode := GetFieldIndexByName('UserCode'); //
kvArcMask := GetFieldIndexByName('ArcMask'); //
kvOutStatusNew := GetFieldIndexByName('OutStatusNew'); //
kvOraF_ID_Kvitan := GetFieldIndexByName('OraF_ID_Kvitan');//
kvPrimaryDoc := GetFieldIndexByName('PrimaryDoc'); //
kvWorkStr := GetFieldIndexByName('WorkStr'); //
end;
end;
procedure ClientsGetNeedIndexes;
begin
with QrmBases[qbClients] do
begin
clClientCode := GetFieldIndexByName('ClientCode'); //
clClientName := GetFieldIndexByName('ClientName'); //
clByte255a := GetFieldIndexByName('Byte255a'); //
clShortName := GetFieldIndexByName('ShortName'); //
clAdress := GetFieldIndexByName('Adress'); //
clTelephone := GetFieldIndexByName('Telephone'); //
clHasModem := GetFieldIndexByName('HasModem'); //
clPrizJur := GetFieldIndexByName('PrizJur'); //
clPropertyCode := GetFieldIndexByName('PropertyCode'); //
clCodeOKPO := GetFieldIndexByName('CodeOKPO'); //
clRegisSer := GetFieldIndexByName('RegisSer'); //
clRegisNum := GetFieldIndexByName('RegisNum'); //
clRegisDate := GetFieldIndexByName('RegisDate'); //
clRegisLocation := GetFieldIndexByName('RegisLocation'); //
clTaxNum := GetFieldIndexByName('TaxNum'); //
clTaxDate := GetFieldIndexByName('TaxDate'); //
clTaxNumGNI := GetFieldIndexByName('TaxNumGNI'); //
clTaxLocation := GetFieldIndexByName('TaxLocation'); //
clPasport := GetFieldIndexByName('Pasport'); //
clBankNum := GetFieldIndexByName('BankNum'); //
clPayAccOld := GetFieldIndexByName('PayAccOld'); //
clClType := GetFieldIndexByName('ClType'); //
clRezident := GetFieldIndexByName('Rezident'); //
clCoClientClass := GetFieldIndexByName('CoClientClass'); //
clCoClientType := GetFieldIndexByName('CoClientType'); //
clCuratorCode := GetFieldIndexByName('CuratorCode'); //
clF775 := GetFieldIndexByName('F775'); //
clShifrMask := GetFieldIndexByName('ShifrMask'); //
clHasVoice := GetFieldIndexByName('HasVoice'); //
clCOPF := GetFieldIndexByName('COPF'); //
clCOATO := GetFieldIndexByName('COATO'); //
clCountryCode := GetFieldIndexByName('CountryCode'); //
clPayAcc := GetFieldIndexByName('PayAcc'); //
clClFromOffice := GetFieldIndexByName('ClFromOffice'); //
clDocType := GetFieldIndexByName('DocType'); //
clSerPasp := GetFieldIndexByName('SerPasp'); //
clNumPasp := GetFieldIndexByName('NumPasp'); //
clDatePasp := GetFieldIndexByName('DatePasp'); //
clReasCode := GetFieldIndexByName('ReasCode'); //КПП
clTaxDocType := GetFieldIndexByName('TaxDocType'); //
clUserCode := GetFieldIndexByName('UserCode'); //
clWorkStr := GetFieldIndexByName('WorkStr'); //
end; //
end; //
//
procedure CorRespNewGetNeedIndexes;
begin
with QrmBases[qbCorRespNew] do
begin
{crnAccNum := GetFieldIndexByName(''); //
CurrCode : String[3] "Код валюты", //
BankNum : String[9] "Код банка корреспондента", //
Mfo : String[9] "Код МФО", //
UchCode : String[3] "Код участника прямых расчетов", //
BankCorrAccOld : String[10]"Коррсчет банка корреспондента Old", //
TypeCorr : word "Тип коррсчета", //
AccTheirOld : String[15]"Номер счета в банке корреспонденте Old", //
OpenDate : Date "Дата открытия", //
CloseDate : Date "Дата закрытия", //
CutOfTime : Time "Время приема платежа", //
RCutOff : Byte "Поправка на дату для Cutoff", //
CorrespName : string[100]"Наименование банка-корреспондента", //
CorrTelegPay : double "Сумма телеграфных расходов РКЦ", //
CorrStatus : word "Признак блокировки", //
ShifrCorr : string[6] "Шифр", //
CorrElectronPay: double "Сумма электронных расходов", //
BankCorrAcc : TExtAcc "Коррсчет банка корреспондента",} //
crnAccTheir := GetFieldIndexByName('AccTheir'); //
{CutOffIn : Word "Поправка на дату для Cutoff входящих", //
RCutOffTel : Word "Поправка на дату для Cutoff (тел.)", //
CutOffInTel : Word "Поправка на дату для Cutoff вх.(тел.)", //
RCutOffEl : Word "Поправка на дату для Cutoff (эл.)", //
CutOffInEl : Word "Поправка на дату для Cutoff вх.(эл.)", //
WorkStr : String[10]"Резерв"} //
end;
end;
procedure PayOrComGetNeedIndexes;
begin
with QrmBases[qbPayOrCom] do
begin
pcOperNum := GetFieldIndexByName('OperNum'); //
pcStatus := GetFieldIndexByName('Status'); //
pcComment := GetFieldIndexByName('Comment'); //
pcComOwner := GetFieldIndexByName('ComOwner'); //
{pcComment1 := GetFieldIndexByName('Comment1');} //
end;
end;
procedure CashSymGetNeedIndexes;
begin
with QrmBases[qbCashSym] do
begin
csSymbol := GetFieldIndexByName('Symbol'); //
{csName := GetFieldIndexByName('Name');} //
csFlag := GetFieldIndexByName('Flag'); //
{csCloseDate := GetFieldIndexByName('CloseDate'); //
csWorkStr := GetFieldIndexByName('WorkStr');} //
end;
end;
procedure AccountsGetNeedIndexes;
begin
with QrmBases[qbAccounts] do //
begin
acAccNum := GetFieldIndexByName('AccNum'); //
acAccPlch := GetFieldIndexByName('AccPlch'); //
acAccName := GetFieldIndexByName('AccName'); //
acClientCode := GetFieldIndexByName('ClientCode'); //
acAccStatus := GetFieldIndexByName('AccStatus'); //
acOpen_Close := GetFieldIndexByName('Open_Close'); //
acCurrCode := GetFieldIndexByName('CurrCode'); //
acOpenDate := GetFieldIndexByName('OpenDate'); //
acCloseDate := GetFieldIndexByName('CloseDate'); //
acOperNum := GetFieldIndexByName('OperNum'); //
acContNum := GetFieldIndexByName('ContNum'); //
acRightBuffer := GetFieldIndexByName('RightBuffer'); //
acChSum := GetFieldIndexByName('ChSum'); //
acClientMessage := GetFieldIndexByName('ClientMessage'); //
acValueCode := GetFieldIndexByName('ValueCode'); //
acAccEndDate := GetFieldIndexByName('AccEndDate'); //
acDayCount := GetFieldIndexByName('DayCount'); //
acAccNewPlch := GetFieldIndexByName('AccNewPlch'); //
acNewAccNum := GetFieldIndexByName('NewAccNum'); //
acShifrMask := GetFieldIndexByName('ShifrMask'); //
acUserGroupCode := GetFieldIndexByName('UserGroupCode'); //
acPriority := GetFieldIndexByName('Priority'); //
acDivCode := GetFieldIndexByName('DivCode'); //
acOwerContNum := GetFieldIndexByName('OwerContNum'); //
acReAccPr := GetFieldIndexByName('ReAccPr'); //
acReAccount := GetFieldIndexByName('ReAccount'); //
acRedCheck := GetFieldIndexByName('RedCheck'); //
acAccSort := GetFieldIndexByName('AccSort'); //
acAccCourse := GetFieldIndexByName('AccCourse'); //
acKindCont := GetFieldIndexByName('KindCont'); //
acKindAcc := GetFieldIndexByName('KindAcc'); //
acKindSaldo := GetFieldIndexByName('KindSaldo'); //
acOraF_ID_Filial := GetFieldIndexByName('OraF_ID_Filial'); //
acWayOfExt := GetFieldIndexByName('WayOfExt'); //
acPerAmount := GetFieldIndexByName('PerAmount'); //
acPerType := GetFieldIndexByName('PerType'); //
end;
end;
procedure PayOrderGetNeedIndexes;
begin
with QrmBases[qbPayOrder] do
begin
poPayAcc := GetFieldIndexByName('PayAcc'); //
poCurrCodePay := GetFieldIndexByName('CurrCodePay'); //
poCorrAcc := GetFieldIndexByName('CorrAcc'); //
poCurrCodeCorr := GetFieldIndexByName('CurrCodeCorr'); //
poDocNum := GetFieldIndexByName('DocNum'); //
poDocDate := GetFieldIndexByName('DocDate'); //
poBranch := GetFieldIndexByName('Branch'); //
poSenderCorrCode := GetFieldIndexByName('SenderCorrCode'); //
poSenderBankNum := GetFieldIndexByName('SenderBankNum'); //
poSenderMfo := GetFieldIndexByName('SenderMfo'); //
poSenderUchCode := GetFieldIndexByName('SenderUchCode'); //
{poOldSenderCorrAcc := GetFieldIndexByName('OldSenderCorrAcc');} //
poReceiverCorrCode := GetFieldIndexByName('ReceiverCorrCode'); //
poReceiverBankNum := GetFieldIndexByName('ReceiverBankNum'); //
poReceiverMfo := GetFieldIndexByName('ReceiverMfo'); //
poReceiverUchCode := GetFieldIndexByName('ReceiverUchCode'); //
{poCorrSum := GetFieldIndexByName('CorrSum'); //
poEqualSum := GetFieldIndexByName('EqualSum'); //
poOldBenefName := GetFieldIndexByName('OldBenefName');} //
poDocType := GetFieldIndexByName('DocType'); //
poSendType := GetFieldIndexByName('SendType'); //
poUserCode := GetFieldIndexByName('UserCode'); //
poBatchType := GetFieldIndexByName('BatchType'); //
poBatchNum := GetFieldIndexByName('BatchNum'); //
poOperNum := GetFieldIndexByName('OperNum'); //
poStatus := GetFieldIndexByName('Status'); //
poPreStatus := GetFieldIndexByName('PreStatus'); //
{poBreak := GetFieldIndexByName('Break');} //
{poCommPay := GetFieldIndexByName('CommPay');} //
poOrderType := GetFieldIndexByName('OrderType'); //
{poPro_Col := GetFieldIndexByName('Pro_Col');} //
{poDoc_Col := GetFieldIndexByName('Doc_Col');} //
{poInOperation := GetFieldIndexByName('InOperation');} //
{poInOperNum := GetFieldIndexByName('InOperNum');} //
poPaySum := GetFieldIndexByName('PaySum'); //
poPayTelegSum := GetFieldIndexByName('PayTelegSum'); //
{poVpCode := GetFieldIndexByName('VpCode');} //
{poPrNum := GetFieldIndexByName('PrNum');} //
poPosDate := GetFieldIndexByName('PosDate'); //
poProcDate := GetFieldIndexByName('ProcDate'); //
{poUserControl := GetFieldIndexByName('UserControl');} //
{poControlLink := GetFieldIndexByName('ControlLink');} //
poValueDate := GetFieldIndexByName('ValueDate'); //
poPriority := GetFieldIndexByName('Priority'); //
{poOldBenefTaxNum := GetFieldIndexByName('OldBenefTaxNum');} //
poRaceNum := GetFieldIndexByName('RaceNum'); //
{poOrderNumber := GetFieldIndexByName('OrderNumber');} //
{poLinkStatus := GetFieldIndexByName('LinkStatus');} //
{poRaceDate := GetFieldIndexByName('RaceDate');} //
poStatusHlp := GetFieldIndexByName('StatusHlp'); //
poOperCode := GetFieldIndexByName('OperCode'); //
poKay := GetFieldIndexByName('Kay'); //
poZaklObor := GetFieldIndexByName('ZaklObor'); //
{poAddInfo := GetFieldIndexByName('AddInfo');} //
poBenefTaxNum := GetFieldIndexByName('BenefTaxNum'); //
{poTypeKvit := GetFieldIndexByName('TypeKvit');} //
poBenefAcc := GetFieldIndexByName('BenefAcc'); //
{poKanvaNum := GetFieldIndexByName('KanvaNum');} //
poSenderCorrAcc := GetFieldIndexByName('SenderCorrAcc'); //
poReceiverCorrAcc := GetFieldIndexByName('ReceiverCorrAcc'); //
poBenefName := GetFieldIndexByName('BenefName'); //
poINNOur := GetFieldIndexByName('INNOur'); //
poClientNameOur := GetFieldIndexByName('ClientNameOur'); //
poClientAcc := GetFieldIndexByName('ClientAcc'); //
{poIsAviso := GetFieldIndexByName('IsAviso');} //
{poBitMask := GetFieldIndexByName('BitMask');} //
{poPaymentAlg := GetFieldIndexByName('PaymentAlg');} //
{poKvitPossMask := GetFieldIndexByName('KvitPossMask');} //
{poDppDate := GetFieldIndexByName('DppDate');} //
{poRef := GetFieldIndexByName('Ref');} //
{poVisUserCode := GetFieldIndexByName('VisUserCode');} //
{poMarshrut := GetFieldIndexByName('Marshrut');} //
{poMarshrutDate := GetFieldIndexByName('MarshrutDate');} //
{poReservPay := GetFieldIndexByName('ReservPay');} //
{poAkcept := GetFieldIndexByName('Akcept');} //
{poMenuItem := GetFieldIndexByName('MenuItem');} //
poindate := GetFieldIndexByName('indate'); //
poKppOur := GetFieldIndexByName('KppOur'); //Наш КПП
poBenefKpp := GetFieldIndexByName('BenefKpp'); //КПП бенефециара
{poWorkStr := GetFieldIndexByName('WorkStr');} //
end;
end;
procedure CashOrderGetNeedIndexes;
begin
with QrmBases[qbCashOrder] do
begin
coDocDate := GetFieldIndexByName('DocDate'); //
coDocCode := GetFieldIndexByName('DocCode'); //
coOperCode := GetFieldIndexByName('OperCode'); //
coUserCode := GetFieldIndexByName('UserCode'); //
coDocNum := GetFieldIndexByName('DocNum'); //
coStatus := GetFieldIndexByName('Status'); //
coOperation := GetFieldIndexByName('Operation'); //
coOperNum := GetFieldIndexByName('OperNum'); //
coAccount := GetFieldIndexByName('Account'); //
coCurrCode := GetFieldIndexByName('CurrCode'); //
coCourse := GetFieldIndexByName('Course'); //
coCommission := GetFieldIndexByName('Commission'); //
coCommissionPerc := GetFieldIndexByName('CommissionPerc'); //
coCashAcc := GetFieldIndexByName('CashAcc'); //
coCashCurrCode := GetFieldIndexByName('CashCurrCode'); //
coSumma_rec := GetFieldIndexByName('Summa_rec'); //
coSumma_exp := GetFieldIndexByName('Summa_exp'); //
coPrintFlag := GetFieldIndexByName('PrintFlag'); //
coBatNum := GetFieldIndexByName('BatNum'); //
coKay := GetFieldIndexByName('Kay'); //
coContNum := GetFieldIndexByName('ContNum'); //
coPreStatus := GetFieldIndexByName('PreStatus'); //
coStatusHlp := GetFieldIndexByName('StatusHlp'); //
coFastChrg := GetFieldIndexByName('FastChrg'); //
coRemSum := GetFieldIndexByName('RemSum'); //
coDocType := GetFieldIndexByName('DocType'); //
coControlLink := GetFieldIndexByName('ControlLink'); //
coFIO := GetFieldIndexByName('FIO'); //
coNumCheck := GetFieldIndexByName('NumCheck'); //
coSerCheck := GetFieldIndexByName('SerCheck'); //
coPasp := GetFieldIndexByName('Pasp'); //
coOldSerPasp := GetFieldIndexByName('OldSerPasp'); //
coNumPasp := GetFieldIndexByName('NumPasp'); //
coResident := GetFieldIndexByName('Resident'); //
coNumSpraw := GetFieldIndexByName('NumSpraw'); //
coNotPay := GetFieldIndexByName('NotPay'); //
coMultiPay := GetFieldIndexByName('MultiPay'); //
coConvFlag := GetFieldIndexByName('ConvFlag'); //
coAccSumma := GetFieldIndexByName('AccSumma'); //
coEqvSumma := GetFieldIndexByName('EqvSumma'); //
coSerPasp := GetFieldIndexByName('SerPasp'); //
coNewUserCode := GetFieldIndexByName('NewUserCode'); //
coOldNomination := GetFieldIndexByName('OldNomination'); //
coKvitPossMask := GetFieldIndexByName('KvitPossMask'); //
coRef := GetFieldIndexByName('Ref'); //
coCommissionCurr := GetFieldIndexByName('CommissionCurr'); //
coDocNumAdd := GetFieldIndexByName('DocNumAdd'); //
coWorkStr := GetFieldIndexByName('WorkStr'); //
end;
end;
procedure CashOSDGetNeedIndexes;
begin
with QrmBases[qbCashOSD] do
begin
osdDocCode := GetFieldIndexByName('DocCode'); //
osdSymbol := GetFieldIndexByName('Symbol'); //
osdSumma := GetFieldIndexByName('Summa'); //
osdOldNom := GetFieldIndexByName('OldNom'); //
osdSymbolCorr := GetFieldIndexByName('SymbolCorr'); //
osdSummaCorr := GetFieldIndexByName('SummaCorr'); //
osdWorkStr := GetFieldIndexByName('WorkStr'); //
end;
end;
procedure MemOrderGetNeedIndexes;
begin
with QrmBases[qbMemOrder] do
begin
moDbAcc := GetFieldIndexByName('DbAcc'); //
moDbCurrCode := GetFieldIndexByName('DbCurrCode'); //
moKrAcc := GetFieldIndexByName('KrAcc'); //
moKrCurrCode := GetFieldIndexByName('KrCurrCode'); //
moDocNum := GetFieldIndexByName('DocNum'); //
moDocDate := GetFieldIndexByName('DocDate'); //
moBranch := GetFieldIndexByName('Branch'); //
moUserCode := GetFieldIndexByName('UserCode'); //
moBatchType := GetFieldIndexByName('BatchType'); //
moBatchNum := GetFieldIndexByName('BatchNum'); //
moOperNum := GetFieldIndexByName('OperNum'); //
moStatus := GetFieldIndexByName('Status'); //
moPreStatus := GetFieldIndexByName('PreStatus'); //
moBreak := GetFieldIndexByName('Break'); //
moMassDocNum := GetFieldIndexByName('MassDocNum'); //
moOrderType := GetFieldIndexByName('OrderType'); //
moPro_Col := GetFieldIndexByName('Pro_Col'); //
moDoc_Col := GetFieldIndexByName('Doc_Col'); //
moInOperation := GetFieldIndexByName('InOperation'); //
moInOperNum := GetFieldIndexByName('InOperNum'); //
moPaySum := GetFieldIndexByName('PaySum'); //
moVpCode := GetFieldIndexByName('VpCode'); //
moPrNum := GetFieldIndexByName('PrNum'); //
moPosDate := GetFieldIndexByName('PosDate'); //
moProcDate := GetFieldIndexByName('ProcDate'); //
moUserControl := GetFieldIndexByName('UserControl'); //
moControlLink := GetFieldIndexByName('ControlLink'); //
moStatusHlp := GetFieldIndexByName('StatusHlp'); //
moOperCode := GetFieldIndexByName('OperCode'); //
moKay := GetFieldIndexByName('Kay'); //
moPayKrSum := GetFieldIndexByName('PayKrSum'); //
moPayNatSum := GetFieldIndexByName('PayNatSum'); //
moZaklObor := GetFieldIndexByName('ZaklObor'); //
moWhatConv := GetFieldIndexByName('WhatConv'); //
moAddInfo := GetFieldIndexByName('AddInfo'); //
moTypeKvit := GetFieldIndexByName('TypeKvit'); //
moRaceNum := GetFieldIndexByName('RaceNum'); //
moRaceDate := GetFieldIndexByName('RaceDate'); //
moKvitPossMask := GetFieldIndexByName('KvitPossMask'); //
moSumValue := GetFieldIndexByName('SumValue'); //
moStorno := GetFieldIndexByName('Storno'); //
moRef := GetFieldIndexByName('Ref'); //
moReserv := GetFieldIndexByName('Reserv'); //
moDbAcc := GetFieldIndexByName('DbAcc'); //
moDbCurrCode := GetFieldIndexByName('DbCurrCode'); //
moKrAcc := GetFieldIndexByName('KrAcc'); //
moKrCurrCode := GetFieldIndexByName('KrCurrCode'); //
moDocNum := GetFieldIndexByName('DocNum'); //
moDocDate := GetFieldIndexByName('DocDate'); //
moBranch := GetFieldIndexByName('Branch'); //
moUserCode := GetFieldIndexByName('UserCode'); //
moBatchType := GetFieldIndexByName('BatchType'); //
moBatchNum := GetFieldIndexByName('BatchNum'); //
moOperNum := GetFieldIndexByName('OperNum'); //
moStatus := GetFieldIndexByName('Status'); //
moPreStatus := GetFieldIndexByName('PreStatus'); //
moBreak := GetFieldIndexByName('Break'); //
moMassDocNum := GetFieldIndexByName('MassDocNum'); //
moOrderType := GetFieldIndexByName('OrderType'); //
moPro_Col := GetFieldIndexByName('Pro_Col'); //
moDoc_Col := GetFieldIndexByName('Doc_Col'); //
moInOperation := GetFieldIndexByName('InOperation'); //
moInOperNum := GetFieldIndexByName('InOperNum'); //
moPaySum := GetFieldIndexByName('PaySum'); //
moVpCode := GetFieldIndexByName('VpCode'); //
moPrNum := GetFieldIndexByName('PrNum'); //
moPosDate := GetFieldIndexByName('PosDate'); //
moProcDate := GetFieldIndexByName('ProcDate'); //
moUserControl := GetFieldIndexByName('UserControl'); //
moControlLink := GetFieldIndexByName('ControlLink'); //
moStatusHlp := GetFieldIndexByName('StatusHlp'); //
moOperCode := GetFieldIndexByName('OperCode'); //
moKay := GetFieldIndexByName('Kay'); //
moPayKrSum := GetFieldIndexByName('PayKrSum'); //
moPayNatSum := GetFieldIndexByName('PayNatSum'); //
moZaklObor := GetFieldIndexByName('ZaklObor'); //
moWhatConv := GetFieldIndexByName('WhatConv'); //
moAddInfo := GetFieldIndexByName('AddInfo'); //
moTypeKvit := GetFieldIndexByName('TypeKvit'); //
moRaceNum := GetFieldIndexByName('RaceNum'); //
moRaceDate := GetFieldIndexByName('RaceDate'); //
moKvitPossMask := GetFieldIndexByName('KvitPossMask'); //
moSumValue := GetFieldIndexByName('SumValue'); //
moStorno := GetFieldIndexByName('Storno'); //
moRef := GetFieldIndexByName('Ref'); //
moReserv := GetFieldIndexByName('Reserv'); //
end;
end;
procedure BanksGetNeedIndexes;
begin
with QrmBases[qbBanks] do
begin //
bnBankNum := GetFieldIndexByName('BankNum'); //
bnRkcNum := GetFieldIndexByName('RkcNum'); //
bnMfo := GetFieldIndexByName('Mfo'); //
bnUchCode := GetFieldIndexByName('UchCode'); //
bnCorrAcc := GetFieldIndexByName('CorrAcc'); //
bnBankCorrAcc := GetFieldIndexByName('BankCorrAcc'); //
{bnBankTaxNum : str10 "Инн банка",
bnCorrAccOld : str10 "Коррсчет банковского учр в РКЦ Old",
bnBankType : word "Код типа банковского учреждения (table)",}
bnTypeAbbrev := GetFieldIndexByName('TypeAbbrev');
bnBankName := GetFieldIndexByName('BankName');
{bnPostInd
bnRegionNum}
bnAdress := GetFieldIndexByName('Adress');
{bnStreet : str64 "Улица+дом",
bnTelephone : string[25]"Телефон(ы)",
bnTelegraph : str14 "Абонентский телеграф(ы)",
bnSrok : byte "Срок прохождения документов (дней)",
bnElUch : byte "Участие в электронных расчетах", // 0 - нет, 1 - да
bnOkpo : str8 "Код ОКПО",
bnRegistrNum : str9 "Регистрационный номер",
bnLicence : word "Лицензия",
bnMfoCont : string[20]"Мфо+конт",
bnNumInUse : string[20]"Используемый код банка",
bnWhichBankNum : word "Используемый номер банка",
bn //0-Мфо 1-Участник 2-Номер
bn //3-Мфо + конт.
bnUchFlag : word "0-не участник, 1-участник прямых расч",
bnVkey : Str8 "Служебная",
bnBankCorrAcc : TExtAcc "Корреспондентский сч.банка",
bnSks : string[6] ""}
end;
end;
procedure VKrtMoveGetNeedIndexes;
begin
with QrmBases[qbVKrtMove] do
begin
vkmOperNum := GetFieldIndexByName('OperNum'); //Код операции" ,
vkmAccNum := GetFieldIndexByName('AccNum'); // Номер счета",
vkmCurrCode := GetFieldIndexByName('CurrCode'); // Код валюты",
vkmUserCode := GetFieldIndexByName('UserCode'); // Код исполнителя",
vkmPaySum := GetFieldIndexByName('PaySum'); // Сумма",
vkmDateMove := GetFieldIndexByName('DateMove'); // Дата",
vkmStatus := GetFieldIndexByName('Status'); // Статус",
vkmPreStatus := GetFieldIndexByName('PreStatus'); // Статусы: 1) Новый 2) Документы отосланы 3) Документы обработаны
vkmCode := GetFieldIndexByName('Code'); // Уникальный код операции",
vkmPayNatSum := GetFieldIndexByName('PayNatSum'); // Сумма в нац. эквиваленте",
//vkmReserv := GetFieldIndexByName('Reserv');
end;
end;
//Добавлено Меркуловым
//База кодов КБК
procedure DocShfrValuesGetNeedIndexes;
begin
with QrmBases [qbDocShfrV] do
begin
dsvTypeCode := GetFieldIndexByName('TypeCode'); //Код типа шифра
dsvShifrValue := GetFieldIndexByName('ShifrValue'); //Значение шифра
dsvShifrName := GetFieldIndexByName('ShifrName'); //Комментарий
end;
end;
procedure CliKppGetNeedIndexes;
begin
with QrmBases [qbCliKpp] do
begin
ckClientCode := GetFieldIndexByName('ClientCode');
ckKPP := GetFieldIndexByName('KPP');
ckDefault_ := GetFieldIndexByName('Default_');
end;
end;
var
FOpenedBases: Integer = 0;
function QrmBasesIsOpen: Boolean;
begin
Result := FOpenedBases>=NumOfQrmBases;
end;
procedure GetQrmOpenedBases(var Opened, All: Integer);
begin
Opened := FOpenedBases;
All := NumOfQrmBases;
end;
function InitQuorumBase(QuorumDir, DictDir, DataDir: string): Boolean; { Инициализация основных баз Кворум}
const
MesTitle: PChar = 'InitQuorumBase';
var
I: Integer;
S: string;
begin
Result := False;
FOpenedBases := 0;
SetQuorumDir(QuorumDir);
SetDictDir(DictDir);
SetDataDir(DataDir);
if OpenDictionary then
begin
Result := True;
{ShowProtoMes('Открытие таблиц Кворума...');}
for I := 1 to NumOfQrmBases do
begin
QrmBases[I] := TQuorumBase.Create(Application);
S := StrPas(QrmBaseNames[I]);
if QrmBases[I].Init(S) then
begin
Inc(FOpenedBases);
case I of
qbPayOrder:
PayOrderGetNeedIndexes;
qbAccounts:
AccountsGetNeedIndexes;
qbBanks:
BanksGetNeedIndexes;
qbCorRespNew:
CorRespNewGetNeedIndexes;
qbPayOrCom:
PayOrComGetNeedIndexes;
qbMemOrder:
MemOrderGetNeedIndexes;
qbCashOrder:
CashOrderGetNeedIndexes;
qbCashOSD:
CashOSDGetNeedIndexes;
qbCashSym:
CashSymGetNeedIndexes;
qbPro:
ProGetNeedIndexes;
qbClients:
ClientsGetNeedIndexes;
qbKvitan:
KvitanGetNeedIndexes;
qbCashComA:
CashComAGetNeedIndexes;
qbCashsDA:
CashsDAGetNeedIndexes;
qbCommentADoc:
CommentADocGetNeedIndexes;
qbDelPro:
DelProGetNeedIndexes;
qbVbKartOt:
VbKartOtGetNeedIndexes;
qbDocsBySh:
DocsByShGetNeedIndexes;
qbLim:
LimGetNeedIndexes;
qbVKrtMove:
VKrtMoveGetNeedIndexes;
qbDocShfrV: //Добавлено Меркуловым
DocShfrValuesGetNeedIndexes; //Добавлено Меркуловым
qbCliKpp: //Добавлено Меркуловым
CliKppGetNeedIndexes; //Добавлено Меркуловым
end;
end
else begin
{ProtoMes(plError, MesTitle, 'Таблица ['+S+'] не открылась');}
QrmBases[I].Free;
QrmBases[I] := nil;
end;
end;
end;
end;
procedure DoneQuorumBase;
var
I: Integer;
begin
for I := 1 to NumOfQrmBases do
if QrmBases[I]<>nil then
begin
QrmBases[I].Free;
QrmBases[I] := nil;
end;
FOpenedBases := 0;
CloseDictionary;
end;
//Добавлено Меркуловым
function KbkNotExistInQBase(ClientKBK: ShortString): Boolean;
var
Len, Res: Integer;
KbkKey: TKbkKey;
begin
Res := 0;
Result := False;
with KbkKey do
begin
dsCode := 4;
dsShifrV := ClientKBK;
end;
if QrmBases[qbDocShfrV]<>nil then
with QrmBases[qbDocShfrV] do
begin
Len := FileRec.frRecordFixed;
FillChar(Buffer^, Len, #0);
Res := BtrBase.GetEqual(Buffer^, Len, KbkKey, 0);
end;
if Res<>0 then
Result := True;
end;
//Добавлено Меркуловым
function CompareKpp (ClntRS, ClntKpp: string): Boolean;
var
Res, Len: Integer;
AccSortCurrKey: TAccSortCurrKey;
AccNum: string[10];
CurrCode: string[3];
UserCodeLocal, ClCode: Integer;
CurKpp: string;
CliKppKey:
packed record
ClientCodeKey: Integer;
KPPKey: string[12];
end;
begin
Result := False;
GetAccAndCurrByNewAcc(ClntRS, AccNum, CurrCode, UserCodeLocal);
if QrmBases[qbAccounts]<>nil then
with QrmBases[qbAccounts] do
begin
Len := FileRec.frRecordFixed;
FillChar(AccSortCurrKey, SizeOf(AccSortCurrKey), ' ');
with AccSortCurrKey do
begin
ascAccSort := SortAcc(AccNum);
ascCurrCode := CurrCode;
end;
Res := BtrBase.GetEqual(Buffer^, Len, AccSortCurrKey, 10);
if Res=0 then
begin
ClCode := AsInteger[acClientCode];
if QrmBases[qbClients]<>nil then
with QrmBases[qbClients] do
begin
Len := FileRec.frRecordFixed;
FillChar(Buffer^, Len, #0);
Res := BtrBase.GetEqual(Buffer^, Len, ClCode, 1);
if Res=0 then
begin
CurKpp := AsString[clReasCode];
if (CurKpp<>ClntKpp) and (ClntKpp<>'0') then
if QrmBases[qbCliKpp]<> nil then
with QrmBases[qbCliKpp] do
begin
with CliKppKey do
begin
ClientCodeKey := ClCode;
KPPKey := ClntKpp;
end;
Res := BtrBase.GetEqualKey(CliKppKey, 1);
if Res<>0 then
Result := True;
end;
end
else
Result := True;
end;
end;
end;
end;
function DocumentIsExistInQuorum(Operation: Word; OperNum: Integer;
var Status: Word): Integer;
var
Len1, Res: Integer;
begin
Status := 0;
Res := -1;
case Operation of
coPayOrderOperation:
if QrmBases[qbPayOrder]<>nil then
with QrmBases[qbPayOrder] do
begin
Len1 := FileRec.frRecordFixed;
Res := BtrBase.GetEqual(Buffer^, Len1, OperNum, 0);
if Res=0 then
begin
Status := AsInteger[poStatus];
if AsString[poDocNum]=DeleteText then
Res := -4;
end;
end;
coMemOrderOperation:
if QrmBases[qbMemOrder]<>nil then
with QrmBases[qbMemOrder] do
begin
Len1 := FileRec.frRecordFixed;
Res := BtrBase.GetEqual(Buffer^, Len1, OperNum, 0);
if (Res=0) and (AsString[moDocNum]=DeleteText) then
Res := -4;
end;
coCashOrderOperation:
if QrmBases[qbCashOrder]<>nil then
with QrmBases[qbCashOrder] do
begin
Len1 := FileRec.frRecordFixed;
Res := BtrBase.GetEqual(Buffer^, Len1, OperNum, 0);
if (Res=0) and (AsString[coDocNum]=DeleteText) then
Res := -4;
end;
else
Res := -2;
end;
Result := Res;
end;
function SeeNationalCurr: string;
begin
Result := '000';
end;
function GetAccAndCurrByNewAcc(Acc: ShortString;
var AccNum, CurrCode: ShortString; var UserCode: Integer): Boolean;
var
Len, Res: Integer;
NewAcc: string[22];
begin
Result := False;
UserCode := -1;
AccNum := '';
CurrCode := '';
if (Length(Acc)=20) and (QrmBases[qbAccounts]<>nil) then
begin
with QrmBases[qbAccounts] do
begin
FillChar(NewAcc, SizeOf(NewAcc), #0);
NewAcc := Acc;
Len := FileRec.frRecordFixed;
FillChar(Buffer^, Len, #0);
Res := BtrBase.GetEqual(Buffer^, Len, NewAcc, 11);
Result := Res=0;
while Res=0 do
begin
AccNum := AsString[acAccNum];
CurrCode := AsString[acCurrCode];
UserCode := AsInteger[acOperNum];
if AsInteger[acOpen_Close]=0 then
Res := -1
else begin
Len := FileRec.frRecordFixed;
FillChar(Buffer^, Len, #0);
Res := BtrBase.GetNext(Buffer^, Len, NewAcc, 11);
if (Res=0) and (NewAcc<>Acc) then
Res := -1;
end;
end;
end;
end;
end;
function SortAcc(AccNum: ShortString): ShortString;
begin
Result := Copy(AccNum,4,3) + Copy(AccNum,1,3) + Copy(AccNum,7,4);
end;
function GetNewAccByAccAndCurr(AccNum, CurrCode: ShortString;
var Acc: ShortString): Boolean;
var
Len, Res: Integer;
AccSortCurrKey: TAccSortCurrKey;
begin
Result := False;
if QrmBases[qbAccounts]<>nil then
with QrmBases[qbAccounts] do
begin
Len := FileRec.frRecordFixed;
FillChar(AccSortCurrKey, SizeOf(AccSortCurrKey), ' ');
AccNum := SortAcc(AccNum);
with AccSortCurrKey do
begin
ascAccSort := AccNum;
ascCurrCode := CurrCode;
end;
Res := BtrBase.GetEqual(Buffer^, Len, AccSortCurrKey, 10);
Result := Res=0;
if Result then
begin
Acc := AsString[acNewAccNum];
while (Res=0) and (AccSortCurrKey.ascAccSort=AccNum)
and (AccSortCurrKey.ascCurrCode=CurrCode)
and (AsInteger[acOpen_Close]<>0) do
begin
Acc := AsString[acNewAccNum];
Len := FileRec.frRecordFixed;
Res := BtrBase.GetNext(Buffer^, Len, AccSortCurrKey, 10);
end;
end;
end;
end;
function GetClientByAcc(ClientAcc, ClientCurrCode: ShortString;
var ClientInn, ClientName, ClientNewAcc: ShortString): Boolean;
var
Len, Res, ClCode: Integer;
AccSortCurrKey: TAccSortCurrKey;
Buf: string;
begin
Result := False;
if QrmBases[qbAccounts]<>nil then
with QrmBases[qbAccounts] do
begin
Len := FileRec.frRecordFixed;
FillChar(AccSortCurrKey, SizeOf(AccSortCurrKey), ' ');
with AccSortCurrKey do
begin
ascAccSort := SortAcc(ClientAcc);
ascCurrCode := ClientCurrCode;
end;
Res := BtrBase.GetEqual(Buffer^, Len, AccSortCurrKey, 10);
Result := Res=0;
if Result then
begin
ClCode := AsInteger[acClientCode];
ClientName := AsString[acAccName];
ClientNewAcc := AsString[acNewAccNum];
//Добавлено Меркуловым
Buf := ClientName;
DosToWin(PChar(Buf));
if (ClientInn = 'incoming') and (ClCode = 1) then
if MessageBox(ParentWnd, PChar('Заменить '+ Buf + #10#13 + ClientNewAcc + ' на'+
#10#13 + 'типа наш банк ?'), 'Внимание!!', mb_yesno)=IDYES then
ClientName := BankNameText;
ClientInn := '';
//Конец
if QrmBases[qbClients]<>nil then
with QrmBases[qbClients] do
begin
Len := FileRec.frRecordFixed;
Res := BtrBase.GetEqual(Buffer^, Len, ClCode, 1);
if Res=0 then
ClientInn := Copy(AsString[clTaxNum], 1, 12)
else
ClientInn := '';
end;
end;
end;
end;
function GetLimByAccAndDate(AccNum, CurrCode: ShortString;
ProDate: Integer; var Sum: Double): Boolean;
var
LimKey:
packed record
lkAcc: string[10];
lkCurrCode: string[3];
lkProDate: Integer;
end;
Len, Res: Integer;
begin
Result := False;
if QrmBases[qbLim]<>nil then
with QrmBases[qbLim] do
begin
FillChar(LimKey, SizeOf(LimKey), #0);
with LimKey do
begin
lkAcc := AccNum;
lkCurrCode := CurrCode;
lkProDate := ProDate;
end;
Len := FileRec.frRecordFixed;
FillChar(Buffer^, Len, #0);
Res := BtrBase.GetLE(Buffer^, Len, LimKey, 0);
if (Res=0) and (AsString[lmAcc]=AccNum)
and (AsString[lmCurrCode]=CurrCode) then
begin
Sum := AsFloat[lmLim];
Result := True;
end;
end;
end;
function GetBankByRekvisit(BankNum: ShortString; Info: Boolean; var CorrCode,
UchCode, MFO, CorrAcc: ShortString): Boolean;
var
Len, Res: Integer;
begin
Result := False;
if QrmBases[qbBanks]<>nil then
with QrmBases[qbBanks] do
begin
Len := FileRec.frRecordFixed;
LPad(BankNum, 9, '0');
Res := BtrBase.GetEqual(Buffer^, Len, BankNum, 0);
Result := Res=0;
if Result then
begin
if Info then
begin
CorrCode := AsString[bnCorrAcc];
//Добавлено/изменено Меркуловым
UchCode := Trim(AsString[bnTypeAbbrev]);
if (UchCode = 'ђЉ–') then //Если РКЦ то подставляем в название
UchCode := UchCode+' '+Trim(AsString[bnBankName])+
' '+Trim(AsString[bnAdress])
else
UchCode := Trim(AsString[bnBankName])+' '+Trim(AsString[bnAdress]);
//Конец
end
else begin
CorrCode := AsString[bnRkcNum];
UchCode := AsString[bnUchCode];
MFO := AsString[bnMFO];
CorrAcc := AsString[bnCorrAcc];
end;
end
else begin
CorrCode := '';
UchCode := '';
MFO := '';
CorrAcc := '';
end;
end;
end;
function GetSenderCorrAcc(CurrCode, CorrAcc: ShortString): ShortString;
type
TCorRespNewKey = packed record
ckAccNum: string[10];
ckCurrCode: string[3];
end;
var
Len, Res: Integer;
CorRespNewKey: TCorRespNewKey;
begin
if QrmBases[qbCorRespNew]=nil then
Result := ''
else
with QrmBases[qbCorRespNew] do
begin
Len := FileRec.frRecordFixed;
FillChar(Buffer^, Len, #0);
RPad(CorrAcc, 10, ' ');
with CorRespNewKey do
begin
ckAccNum := CorrAcc;
ckCurrCode := CurrCode;
end;
Res := BtrBase.GetEqual(Buffer^, Len, CorRespNewKey, 0);
if Res=0 then
Result := AsString[crnAccTheir]
else
Result := '';
end;
end;
function GetChildOperNumByKvitan(InOperation: Word; InOperNum: Longint;
NeedOutOperation: Word): Integer;
var
KvitKey: TKvitKey;
Len, Res: Integer;
begin
Result := 0;
if QrmBases[qbKvitan]<>nil then
begin
with KvitKey do
begin
kkDoneFlag := 0;
kkOperation := InOperation;
kkOperNum := InOperNum;
kkStatus := 0;
end;
with QrmBases[qbKvitan] do
begin
Len := FileRec.frRecordFixed;
Res := BtrBase.GetGE(Buffer^, Len, KvitKey, 0);
while (Result=0)
and (Res=0)
and (AsInteger[kvDoneFlag]=0) {+}
and (AsInteger[kvInOperNum]=InOperNum)
and (AsInteger[kvInOperation]=InOperation) do
begin
if {(AsInteger[kvDoneFlag]=0) and ((NeedOutOperation=0)
or} (AsInteger[kvOutOperation]=NeedOutOperation) {)}
then
Result := AsInteger[kvOutOperNum];
if Result=0 then
begin
Len := FileRec.frRecordFixed;
Res := BtrBase.GetNext(Buffer^, Len, KvitKey, 0);
end;
end;
end;
end;
end;
function GetParentOperNumByKvitan(OutOperation: Word; OutOperNum: Longint;
NeedInOperation: Word): Integer;
var
KvitKey: TKvitKey;
Len, Res: Integer;
begin
Result := 0;
if QrmBases[qbKvitan]<>nil then
begin
with KvitKey do
begin
kkDoneFlag := 0;
kkOperation := OutOperation;
kkOperNum := OutOperNum;
kkStatus := 0;
end;
with QrmBases[qbKvitan] do
begin
Len := FileRec.frRecordFixed;
Res := BtrBase.GetGE(Buffer^, Len, KvitKey, 1);
while (Result=0)
and (Res=0)
and (AsInteger[kvOutOperNum]=OutOperNum)
and (AsInteger[kvOutOperation]=OutOperation) do
begin
if (AsInteger[kvDoneFlag]=0) and ((NeedInOperation=0)
or (AsInteger[kvInOperation]=NeedInOperation))
then
Result := AsInteger[kvInOperNum];
if Result=0 then
begin
Len := FileRec.frRecordFixed;
Res := BtrBase.GetNext(Buffer^, Len, KvitKey, 1);
end;
end;
end;
end;
end;
function GetCashNazn(S: string): string;
var
I: Integer;
begin
I := Pos('+', S);
if I>0 then
Result := Copy(S, 1, I-1)
else
Result := S;
end;
end.
|
unit uViewPrincipal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type //Meu Record.
TPessoa = record
Nome : string;
end;
var
Form1: TForm1;
ListaPessoa: array[0..2] of TPessoa; //Minha Lista tipo RECORD.
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
i:integer;
procedure mostrarDadosRecord(const campos: array of string);
var
texto: string;
i: integer;
begin
//mostra os campos
for i:=0 to length(campos) -1 do
begin
texto:= texto + campos[i] + #10#13;
memo1.Lines.Add(texto);
end;
end;
begin
//Preencho meu record da posicao 1 da lista.
with ListaPessoa[0] do
begin
Nome := 'Volnei'
end;
ListaPessoa[1] := ListaPessoa[0]; //Se quiser posso copiar um record e jogar em outro.
ListaPessoa[1].Nome := 'Mario'; // substituo o nome se quiser..
ListaPessoa[2].Nome := 'julio';
//varrer minha lista de record
for i:=0 to 2 do
begin
with ListaPessoa[i] do
begin
mostrarDadosRecord([nome]); //mostrarDadosRecord([nome, endereco, idade, etc]);
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{$HPPEMIT '#pragma link "Vcl.Bind.Editors"'} {Do not Localize}
unit Vcl.Bind.Editors;
interface
uses
System.Classes, System.Bindings.EvalProtocol, Data.Bind.Components, Data.Bind.Editors, Vcl.StdCtrls, System.Bindings.ObjEval, Vcl.ComCtrls, Vcl.Grids,
Vcl.Controls;
type
TBindStateCheckBoxEditor = class(TBindCheckBoxEditor)
private
FCheckBox: TCheckBox;
public
constructor Create(ACheckBox: TCheckBox);
function GetState: TBindCheckBoxState; override;
procedure SetState(Value: TBindCheckBoxState); override;
function GetAllowGrayed: Boolean; override;
procedure SetAllowGrayed(Value: Boolean); override;
end;
TBaseListBoxItemEditorObject = class
protected
FIndex: Integer;
function GetControlItems: TStrings; virtual; abstract;
function GetControlItemIndex: Integer; virtual; abstract;
procedure SetControlItemIndex(AIndex: Integer); virtual; abstract;
procedure ControlClear; virtual; abstract;
public
property ControlItems: TStrings read GetControlItems;
property ControlItemIndex: Integer read GetControlItemIndex write SetControlItemIndex;
end;
TListBoxItemEditorObject = class(TBaseListBoxItemEditorObject)
private
FListBox: TCustomListBox;
function GetOwner: TCustomListBox;
procedure SetText(const Value: string);
function GetText: string;
protected
function GetControlItems: TStrings; override;
function GetControlItemIndex: Integer; override;
procedure SetControlItemIndex(AIndex: Integer); override;
procedure ControlClear; override;
public
constructor Create(AListBox: TCustomListBox);
property Text: string read GetText write SetText;
property Owner: TCustomListBox read GetOwner;
end;
TComboBoxItemEditorObject = class(TBaseListBoxItemEditorObject)
private
FComboBox: TCustomComboBox;
function GetOwner: TCustomComboBox;
procedure SetText(const Value: string);
function GetText: string;
protected
function GetControlItems: TStrings; override;
function GetControlItemIndex: Integer; override;
procedure SetControlItemIndex(AIndex: Integer); override;
procedure ControlClear; override;
public
constructor Create(AComboBox: TCustomComboBox);
property Text: string read GetText write SetText;
property Owner: TCustomComboBox read GetOwner;
end;
TBaseBindListListBoxEditor = class(TBindListEditor)
private
FEditorObject: TBaseListBoxItemEditorObject;
protected
function CreateItemsEditor(AControl: TControl): TBaseListBoxItemEditorObject; virtual; abstract;
public
constructor Create(AControl: TControl);
destructor Destroy; override;
procedure BeginUpdate; override;
procedure EndUpdate; override;
function AddItem(Select: Boolean = False): IScope; override;
function InsertItem(Select: Boolean = False): IScope; override;
function CanInsertItem: Boolean; override;
function CurrentItem: IScope; override;
function GetRowCount: Integer; override;
function MoveNext: Boolean; override;
procedure DeleteToEnd; override;
procedure ClearList; override;
function GetSelectedText: string; override;
procedure SetSelectedText(const AValue: string); override;
end;
TBindListListBoxEditor = class(TBaseBindListListBoxEditor)
protected
function CreateItemsEditor(AControl: TControl): TBaseListBoxItemEditorObject; override;
public
constructor Create(AListBox: TCustomListBox);
end;
TBindListComboBoxEditor = class(TBaseBindListListBoxEditor)
protected
function CreateItemsEditor(AControl: TControl): TBaseListBoxItemEditorObject; override;
public
constructor Create(ACombobox: TCustomComboBox);
end;
TListViewItemEditorObject = class
private
FListView: TCustomListView;
FItemIndex: Integer;
function GetOwner: TCustomListView;
procedure SetText(const Value: string);
function GetText: string;
public
property Text: string read GetText write SetText;
property Owner: TCustomListView read GetOwner;
end;
TBindListListViewEditor = class(TBindListEditor)
private
FEditorObject: TListViewItemEditorObject;
public
constructor Create(AListView: TCustomListView);
destructor Destroy; override;
procedure BeginUpdate; override;
procedure EndUpdate; override;
function AddItem(Select: Boolean): IScope; override;
function InsertItem(Select: Boolean): IScope; override;
function CanInsertItem: Boolean; override;
function CurrentItem: IScope; override;
function GetRowCount: Integer; override;
function MoveNext: Boolean; override;
procedure DeleteToEnd; override;
procedure ClearList; override;
function GetSelectedText: string; override;
procedure SetSelectedText(const AValue: string); override;
end;
TStringGridItemEditorObject = class
private
FStringGrid: TStringGrid;
FIndex: Integer;
function GetOwner: TStringGrid;
function GetCells(ACol: Integer): string;
procedure SetCells(ACol: Integer; const Value: string);
public
property Owner: TStringGrid read GetOwner;
property Cells[ACol: Integer]: string read GetCells write SetCells;
end;
TBindListStringGridEditor = class(TBindGridEditor)
private
FEditorObject: TStringGridItemEditorObject;
function IsEmpty: Boolean;
protected
procedure BeginUpdate; override;
procedure EndUpdate; override;
function AddItem(Select: Boolean): IScope; override;
function CanInsertItem: Boolean; override;
function InsertItem(Select: Boolean): IScope; override;
function CurrentItem: IScope; override;
function GetRowCount: Integer; override;
function MoveNext: Boolean; override;
procedure DeleteToEnd; override;
procedure ClearList; override;
function GetSelectedText: string; override;
procedure SetSelectedText(const AValue: string); override;
procedure GetColumnIndices(ANames: TStrings); override;
procedure GetColumnNames(ANames: TStrings); override;
public
constructor Create(AGrid: TStringGrid);
destructor Destroy; override;
end;
implementation
uses System.SysUtils, System.Math;
type
TBindCheckBoxEditorFactory = class(TBindEditorFactory)
public
constructor Create; override;
function Supports(AIntf: TGuid; AObject: TObject): Boolean; override;
function CreateEditor(AIntf: TGuid;
AObject: TObject): IInterface; override;
end;
TBindListBoxEditorFactory = class(TBindEditorFactory)
public
constructor Create; override;
function Supports(AIntf: TGuid; AObject: TObject): Boolean; override;
function CreateEditor(AIntf: TGuid;
AObject: TObject): IInterface; override;
end;
TBindComboBoxEditorFactory = class(TBindEditorFactory)
public
constructor Create; override;
function Supports(AIntf: TGuid; AObject: TObject): Boolean; override;
function CreateEditor(AIntf: TGuid;
AObject: TObject): IInterface; override;
end;
TBindListViewEditorFactory = class(TBindEditorFactory)
public
constructor Create; override;
function Supports(AIntf: TGuid; AObject: TObject): Boolean; override;
function CreateEditor(AIntf: TGuid;
AObject: TObject): IInterface; override;
end;
TBindStringGridEditorFactory = class(TBindEditorFactory)
public
constructor Create; override;
function Supports(AIntf: TGuid; AObject: TObject): Boolean; override;
function CreateEditor(AIntf: TGuid;
AObject: TObject): IInterface; override;
end;
{ TListBoxItemEditorObject }
procedure TListBoxItemEditorObject.ControlClear;
begin
FListBox.Items.Clear;
end;
constructor TListBoxItemEditorObject.Create(AListBox: TCustomListBox);
begin
FListBox := AListBox;
end;
function TListBoxItemEditorObject.GetControlItemIndex: Integer;
begin
Result := FListBox.ItemIndex;
end;
function TListBoxItemEditorObject.GetControlItems: TStrings;
begin
Result := FListBox.Items;
end;
function TListBoxItemEditorObject.GetOwner: TCustomListBox;
begin
Result := FListBox;
end;
function TListBoxItemEditorObject.GetText: string;
begin
Result := FListBox.Items[FIndex];
end;
procedure TListBoxItemEditorObject.SetControlItemIndex(AIndex: Integer);
begin
FListBox.ItemIndex := AIndex;
end;
procedure TListBoxItemEditorObject.SetText(const Value: string);
begin
FListBox.Items[FIndex] := Value;
end;
{ TComboBoxItemEditorObject }
procedure TComboBoxItemEditorObject.ControlClear;
begin
FComboBox.Items.Clear;
end;
constructor TComboBoxItemEditorObject.Create(AComboBox: TCustomComboBox);
begin
FComboBox := AComboBox;
end;
function TComboBoxItemEditorObject.GetControlItemIndex: Integer;
begin
Result := FComboBox.ItemIndex;
end;
function TComboBoxItemEditorObject.GetControlItems: TStrings;
begin
Result := FComboBox.Items;
end;
function TComboBoxItemEditorObject.GetOwner: TCustomComboBox;
begin
Result := FComboBox;
end;
function TComboBoxItemEditorObject.GetText: string;
begin
Result := FComboBox.Items[FIndex];
end;
procedure TComboBoxItemEditorObject.SetControlItemIndex(AIndex: Integer);
begin
FComboBox.ItemIndex := AIndex;
end;
procedure TComboBoxItemEditorObject.SetText(const Value: string);
begin
FComboBox.Items[FIndex] := Value;
end;
{ TBindListBoxItemsBoxEditor }
function TBaseBindListListBoxEditor.AddItem(Select: Boolean): IScope;
begin
FEditorObject.FIndex := FEditorObject.ControlItems.Add('');
if Select then
FEditorObject.ControlItemIndex := FEditorObject.FIndex;
Result := WrapObject(FEditorObject);
end;
function TBaseBindListListBoxEditor.InsertItem(Select: Boolean): IScope;
begin
if not CanInsertItem then
Result := nil
else
begin
FEditorObject.FIndex := FEditorObject.ControlItemIndex;
FEditorObject.ControlItems.Insert(FEditorObject.FIndex, '');
if Select then
FEditorObject.ControlItemIndex := FEditorObject.FIndex;
Result := WrapObject(FEditorObject);
end;
end;
function TBaseBindListListBoxEditor.CanInsertItem: Boolean;
begin
Result := FEditorObject.ControlItemIndex <> -1;
end;
function TBaseBindListListBoxEditor.CurrentItem: IScope;
begin
if FEditorObject.FIndex = -1 then
FEditorObject.FIndex := FEditorObject.ControlItemIndex;
if FEditorObject.FIndex <> -1 then
Result := WrapObject(FEditorObject);
end;
procedure TBaseBindListListBoxEditor.BeginUpdate;
begin
FEditorObject.ControlItems.BeginUpdate;
end;
procedure TBaseBindListListBoxEditor.ClearList;
begin
FEditorObject.ControlClear;
FEditorObject.FIndex := -1;
end;
constructor TBaseBindListListBoxEditor.Create(AControl: TControl);
begin
FEditorObject := CreateItemsEditor(AControl);
FEditorObject.FIndex := -1;
end;
procedure TBaseBindListListBoxEditor.DeleteToEnd;
begin
if FEditorObject.FIndex = -1 then
FEditorObject.FIndex := FEditorObject.ControlItemIndex;
while FEditorObject.ControlItems.Count > Max(0, FEditorObject.FIndex) do
FEditorObject.ControlItems.Delete(FEditorObject.ControlItems.Count-1);
FEditorObject.FIndex := FEditorObject.ControlItems.Count - 1;
end;
destructor TBaseBindListListBoxEditor.Destroy;
begin
FEditorObject.Free;
inherited;
end;
procedure TBaseBindListListBoxEditor.EndUpdate;
begin
FEditorObject.ControlItems.EndUpdate;
end;
function TBaseBindListListBoxEditor.GetRowCount: Integer;
begin
Result := FEditorObject.ControlItems.Count;
end;
function TBaseBindListListBoxEditor.GetSelectedText: string;
begin
Result := '';
if FEditorObject.ControlItemIndex <> -1 then
with FEditorObject do
Result := ControlItems[ControlItemIndex];
end;
function TBaseBindListListBoxEditor.MoveNext: Boolean;
begin
if FEditorObject.FIndex = -1 then
begin
FEditorObject.FIndex := FEditorObject.ControlItemIndex;
if FEditorObject.FIndex < 0 then
FEditorObject.FIndex := 0;
end
else
FEditorObject.FIndex := FEditorObject.FIndex + 1;
Result := (FEditorObject.FIndex >= 0) and (FEditorObject.FIndex < FEditorObject.ControlItems.Count);
end;
procedure TBaseBindListListBoxEditor.SetSelectedText(const AValue: string);
var
I: Integer;
begin
I := FEditorObject.ControlItems.IndexOf(AValue);
FEditorObject.ControlItemIndex := I;
end;
{ TBindListListBoxEditor }
constructor TBindListListBoxEditor.Create(AListBox: TCustomListBox);
begin
inherited Create(AListBox);
end;
{ TListViewItemEditorObject }
function TListViewItemEditorObject.GetOwner: TCustomListView;
begin
Result := FListView;
end;
procedure TListViewItemEditorObject.SetText(const Value: string);
begin
FListView.Items[FItemIndex].Caption := Value;
end;
function TListViewItemEditorObject.GetText: string;
begin
Result := FListView.Items[FItemIndex].Caption;
end;
{ TBindListStringGridEditor }
function TBindListStringGridEditor.AddItem(Select: Boolean): IScope;
begin
if IsEmpty then
begin
// Assume first row is empty and use it
end
else
FEditorObject.FStringGrid.RowCount := FEditorObject.FStringGrid.RowCount + 1;
FEditorObject.FIndex := FEditorObject.FStringGrid.RowCount - 1;
if Select then
FEditorObject.FStringGrid.Row := FEditorObject.FIndex;
Result := WrapObject(FEditorObject);
end;
function TBindListStringGridEditor.InsertItem(Select: Boolean): IScope;
begin
// Not supported
Exit(nil);
end;
function TBindListStringGridEditor.CanInsertItem: Boolean;
begin
// Not supported
Result := False;
end;
function TBindListStringGridEditor.CurrentItem: IScope;
begin
//FEditorObject.FIndex := FEditorObject.FStringGrid.Row;
if FEditorObject.FIndex = -1 then
FEditorObject.FIndex := FEditorObject.FStringGrid.Row;
Result := WrapObject(FEditorObject);
end;
procedure TBindListStringGridEditor.BeginUpdate;
begin
//FEditorObject.FStringGrid
end;
procedure TBindListStringGridEditor.ClearList;
begin
FEditorObject.FIndex := -1;
if FEditorObject.FStringGrid.FixedRows > 0 then
begin
FEditorObject.FStringGrid.RowCount := FEditorObject.FStringGrid.FixedRows + 1;
FEditorObject.FStringGrid.Rows[FEditorObject.FStringGrid.FixedRows].Clear;
end
else
FEditorObject.FStringGrid.RowCount := 0;
end;
constructor TBindListStringGridEditor.Create(AGrid: TStringGrid);
begin
FEditorObject := TStringGridItemEditorObject.Create;
FEditorObject.FStringGrid := AGrid;
FEditorObject.FIndex := -1;
end;
procedure TBindListStringGridEditor.DeleteToEnd;
begin
if FEditorObject.FIndex = -1 then
FEditorObject.FIndex := FEditorObject.FStringGrid.Row;
if FEditorObject.FIndex = FEditorObject.FStringGrid.FixedRows then
ClearList
else
FEditorObject.FStringGrid.RowCount := FEditorObject.FIndex;
end;
destructor TBindListStringGridEditor.Destroy;
begin
FEditorObject.Free;
inherited;
end;
procedure TBindListStringGridEditor.EndUpdate;
begin
//FEditorObject.FListBox.Items.EndUpdate;
end;
function TBindListStringGridEditor.IsEmpty: Boolean;
begin
Result := (FEditorObject.FStringGrid.RowCount = FEditorObject.FStringGrid.FixedRows + 1)
and (Trim(FEditorObject.FStringGrid.Rows[FEditorObject.FStringGrid.FixedRows].Text) = '');
end;
function TBindListStringGridEditor.GetRowCount: Integer;
begin
if IsEmpty then
Result := 0
else
Result := FEditorObject.FStringGrid.RowCount - FEditorObject.FStringGrid.FixedRows;
end;
function TBindListStringGridEditor.GetSelectedText: string;
begin
Result := '';
with FEditorObject do
begin
if FStringGrid.Row >= FStringGrid.FixedRows then
if FStringGrid.Col >= FStringGrid.FixedCols then
Result := FStringGrid.Cells[FStringGrid.Col, FStringGrid.Row];
end;
end;
function TBindListStringGridEditor.MoveNext: Boolean;
begin
if FEditorObject.FIndex = -1 then
FEditorObject.FIndex := FEditorObject.FStringGrid.Row
else
FEditorObject.FIndex := FEditorObject.FIndex + 1;
Result := FEditorObject.FIndex < FEditorObject.FStringGrid.RowCount;
end;
procedure TBindListStringGridEditor.SetSelectedText(const AValue: string);
begin
with FEditorObject.FStringGrid do
begin
if Row >= FixedRows then
if Col >= FixedCols then
Cells[Col, Row] := AValue;
end;
end;
procedure TBindListStringGridEditor.GetColumnIndices(ANames: TStrings);
var
I: Integer;
begin
for I := 0 to FEditorObject.FStringGrid.ColCount - 1 do
ANames.Add(IntToStr(I));
end;
procedure TBindListStringGridEditor.GetColumnNames(ANames: TStrings);
begin
// no Names
end;
{ TStringGridItemEditorObject }
function TStringGridItemEditorObject.GetOwner: TStringGrid;
begin
Result := FStringGrid;
end;
function TStringGridItemEditorObject.GetCells(ACol: Integer): string;
begin
Result := Self.FStringGrid.Cells[ACol, FIndex];
end;
procedure TStringGridItemEditorObject.SetCells(ACol: Integer;
const Value: string);
begin
Self.FStringGrid.Cells[ACol, FIndex] := Value;
end;
{ TBindListBoxEditorFactory }
constructor TBindListBoxEditorFactory.Create;
begin
inherited;
end;
function TBindListBoxEditorFactory.CreateEditor(AIntf: TGuid;
AObject: TObject): IInterface;
begin
Result := TBindListListBoxEditor.Create(TCustomListBox(AObject));
end;
function TBindListBoxEditorFactory.Supports(AIntf: TGuid; AObject:
TObject): Boolean;
begin
Result := False;
if AIntf = IBindListEditor then
if (AObject <> nil) and (AObject.InheritsFrom(TCustomListBox)) then
Result := True;
end;
{ TBindComboBoxEditorFactory }
constructor TBindComboBoxEditorFactory.Create;
begin
inherited;
end;
function TBindComboBoxEditorFactory.CreateEditor(AIntf: TGuid;
AObject: TObject): IInterface;
begin
Result := TBindListComboBoxEditor.Create(TCustomComboBox(AObject));
end;
function TBindComboBoxEditorFactory.Supports(AIntf: TGuid; AObject:
TObject): Boolean;
begin
Result := False;
if AIntf = IBindListEditor then
if (AObject <> nil) and (AObject.InheritsFrom(TCustomComboBox)) then
Result := True;
end;
{ TBindListListViewEditor }
type
TCustomListViewHack = class(TCustomListView);
function TBindListListViewEditor.AddItem(Select: Boolean): IScope;
var
I: Integer;
AListItem: TListItem;
begin
AListItem := FEditorObject.FListView.Items.Add;
for I := 0 to TCustomListViewHack(FEditorObject.FListView).Columns.Count do
AListItem.SubItems.Add('');
//Result := WrapObject(FEditorObject);
FEditorObject.FItemIndex := AListItem.Index;
if Select then
FEditorObject.FListView.ItemIndex := FEditorObject.FItemIndex;
Result := WrapObject(FEditorObject.FListView.Items[FEditorObject.FItemIndex]);
end;
function TBindListListViewEditor.CanInsertItem: Boolean;
begin
Result := FEditorObject.FListView.ItemIndex <> -1;
end;
function TBindListListViewEditor.InsertItem(Select: Boolean): IScope;
var
I: Integer;
AListItem: TListItem;
begin
if FEditorObject.FListView.ItemIndex = -1 then
Exit(nil);
AListItem := FEditorObject.FListView.Items.Insert(FEditorObject.FListView.ItemIndex);
for I := 0 to TCustomListViewHack(FEditorObject.FListView).Columns.Count do
AListItem.SubItems.Add('');
//Result := WrapObject(FEditorObject);
FEditorObject.FItemIndex := AListItem.Index;
if Select then
FEditorObject.FListView.ItemIndex := FEditorObject.FItemIndex;
Result := WrapObject(FEditorObject.FListView.Items[FEditorObject.FItemIndex]);
end;
function TBindListListViewEditor.CurrentItem: IScope;
//var
// I: Integer;
begin
if FEditorObject.FItemIndex = -1 then
FEditorObject.FItemIndex := FEditorObject.FListView.ItemIndex;
//Result := WrapObject(FEditorObject);
if FEditorObject.FItemIndex <> -1 then
Result := WrapObject(FEditorObject.FListView.Items[FEditorObject.FItemIndex])
else
Result := nil;
end;
procedure TBindListListViewEditor.BeginUpdate;
begin
FEditorObject.FListView.Items.BeginUpdate;
end;
procedure TBindListListViewEditor.ClearList;
begin
FEditorObject.FListView.Clear;
FEditorObject.FItemIndex := -1;
end;
constructor TBindListListViewEditor.Create(AListView: TCustomListView);
begin
FEditorObject := TListViewItemEditorObject.Create;
FEditorObject.FListView := AListView;
FEditorObject.FItemIndex := -1;
end;
procedure TBindListListViewEditor.DeleteToEnd;
begin
if FEditorObject.FItemIndex = -1 then
FEditorObject.FItemIndex := FEditorObject.FListView.ItemIndex;
while FEditorObject.FListView.Items.Count > Max(0, FEditorObject.FItemIndex) do
FEditorObject.FListView.Items.Delete(FEditorObject.FListView.Items.Count-1);
FEditorObject.FItemIndex := FEditorObject.FListView.Items.Count - 1;
end;
destructor TBindListListViewEditor.Destroy;
begin
FEditorObject.Free;
inherited;
end;
procedure TBindListListViewEditor.EndUpdate;
begin
FEditorObject.FListView.Items.EndUpdate;
end;
function TBindListListViewEditor.GetRowCount: Integer;
begin
Result := FEditorObject.FListView.Items.Count;
end;
function TBindListListViewEditor.GetSelectedText: string;
begin
if FEditorObject.FListView.ItemIndex <> -1 then
with FEditorObject.FListView do
Result := Items[ItemIndex].Caption;
end;
function TBindListListViewEditor.MoveNext: Boolean;
begin
if FEditorObject.FItemIndex = -1 then
begin
FEditorObject.FItemIndex := FEditorObject.FListView.ItemIndex;
if FEditorObject.FItemIndex < 0 then
FEditorObject.FItemIndex := 0;
end
else
FEditorObject.FItemIndex := FEditorObject.FItemIndex + 1;
Result := (FEditorObject.FItemIndex >= 0) and (FEditorObject.FItemIndex < FEditorObject.FListView.Items.Count);
end;
procedure TBindListListViewEditor.SetSelectedText(const AValue: string);
var
LItem: TListItem;
begin
LItem := FEditorObject.FListView.FindCaption(0, AValue, False, True, False);
if LItem <> nil then
FEditorObject.FListView.ItemIndex := LItem.Index
else
FEditorObject.FListView.ItemIndex := -1;
end;
{ TBindListViewEditorFactory }
constructor TBindListViewEditorFactory.Create;
begin
inherited;
end;
function TBindListViewEditorFactory.CreateEditor(AIntf: TGuid;
AObject: TObject): IInterface;
begin
Result := TBindListListViewEditor.Create(TCustomListView(AObject));
end;
function TBindListViewEditorFactory.Supports(AIntf: TGuid; AObject:
TObject): Boolean;
begin
Result := False;
if AIntf = IBindListEditor then
if (AObject <> nil) and AObject.InheritsFrom(TCustomListView) then
Result := True;
end;
{ TBindStringGridEditorFactory }
constructor TBindStringGridEditorFactory.Create;
begin
inherited;
end;
function TBindStringGridEditorFactory.CreateEditor(AIntf: TGuid;
AObject: TObject): IInterface;
begin
Result := TBindListStringGridEditor.Create(TStringGrid(AObject));
end;
function TBindStringGridEditorFactory.Supports(AIntf: TGuid; AObject:
TObject): Boolean;
begin
Result := False;
if AIntf = IBindListEditor then
if (AObject <> nil) and AObject.InheritsFrom(TStringGrid) then
Result := True;
end;
//{ TBindListEditor }
//
//procedure TBindListEditor.FillList(ARecordEnumerator: IScopeRecordEnumerator;
// AFormatProc: TFormatCallback);
//var
// LEditor: IBindListEditor;
// LEnumerator: IScopeRecordEnumerator;
// LEditorScope: IScope;
//begin
// LEditor := Self;
// LEditor.BeginUpdate;
// try
// LEnumerator := ARecordEnumerator;
// LEnumerator.First;
// LEditor.ClearList;
// if LEnumerator <> nil then
// begin
// while LEnumerator.MoveNext do
// begin
// LEditorScope := LEditor.AddItem;
// Assert(LEditorScope <> nil);
// if LEditorScope <> nil then
// begin
// AFormatProc(LEnumerator.Current, LEditorScope);
// end;
// end;
// end
// else
// Assert(False);
// finally
// LEditor.EndUpdate;
// end;
//
//end;
//
//procedure TBindListEditor.UpdateList(ARecordEnumerator: IScopeRecordEnumerator;
// AFormatProc: TFormatCallback);
//var
// LEditor: IBindListEditor;
// LEditorScope: IScope;
//begin
// LEditor := Self;
//
// LEditor.BeginUpdate;
// try
// if ARecordEnumerator <> nil then
// begin
// // Update existing items
// while LEditor.MoveNext do
// begin
// if ARecordEnumerator.MoveNext then
// begin
// LEditorScope := LEditor.CurrentItem;
// Assert(LEditorScope <> nil);
// if LEditorScope <> nil then
// begin
// AFormatProc(ARecordEnumerator.Current, LEditorScope);
// end;
// end
// else
// begin
// Assert(True); //Debugging
// break;
// end;
// end;
// // Delete remaining items, if any
// LEditor.DeleteToEnd;
// // Add new items
// while ARecordEnumerator.MoveNext do
// begin
// LEditorScope := LEditor.AddItem;
// Assert(LEditorScope <> nil);
// if LEditorScope <> nil then
// begin
// AFormatProc(ARecordEnumerator.Current, LEditorScope);
// end;
// end;
// end
// else
// Assert(False);
// finally
// LEditor.EndUpdate;
// end;
//end;
//
//function TBindListEditor.UpdateNeeded(
// ARecordEnumerator: IScopeRecordEnumerator): Boolean;
//var
// LEditor: IBindListEditor;
// LEnumerator: IScopeRecordEnumerator;
//begin
// LEditor := Self;
// if ARecordEnumerator <> nil then
// if LEditor.RowCount = ARecordEnumerator.RecordCount then
// // Only need to do something if records added or deleted
// Exit(False);
// Result := True;
//end;
{ TBindCheckBoxEditorFactory }
constructor TBindCheckBoxEditorFactory.Create;
begin
inherited;
end;
function TBindCheckBoxEditorFactory.CreateEditor(AIntf: TGuid;
AObject: TObject): IInterface;
begin
Result := TBindStateCheckBoxEditor.Create(TCheckBox(AObject));
end;
function TBindCheckBoxEditorFactory.Supports(AIntf: TGuid;
AObject: TObject): Boolean;
begin
Result := False;
if AIntf = IBindCheckBoxEditor then
if AObject.InheritsFrom(TCheckBox) then
Result := True;
end;
{ TBindStateCheckBoxEditor }
constructor TBindStateCheckBoxEditor.Create(ACheckBox: TCheckBox);
begin
FCheckBox := ACheckBox;
end;
function TBindStateCheckBoxEditor.GetAllowGrayed: Boolean;
begin
Result := FCheckBox.AllowGrayed;
end;
function TBindStateCheckBoxEditor.GetState: TBindCheckBoxState;
begin
if GetAllowGrayed and (FCheckBox.State = TCheckBoxState.cbGrayed) then
Result := TBindCheckBoxState.cbGrayed
else
begin
if FCheckBox.Checked then
Result := TBindCheckBoxState.cbChecked
else
Result := TBindCheckBoxState.cbUnchecked;
end;
end;
procedure TBindStateCheckBoxEditor.SetAllowGrayed(Value: Boolean);
begin
FCheckBox.AllowGrayed := Value;
end;
procedure TBindStateCheckBoxEditor.SetState(Value: TBindCheckBoxState);
begin
if (Value = TBindCheckBoxState.cbGrayed) and GetAllowGrayed then
FCheckBox.State := TCheckBoxState.cbGrayed
else
FCheckBox.Checked := Value = TBindCheckBoxState.cbChecked;
end;
function TBindListListBoxEditor.CreateItemsEditor(
AControl: TControl): TBaseListBoxItemEditorObject;
begin
Result := TListBoxItemEditorObject.Create(AControl as TCustomListBox);
end;
{ TBindListComboBoxEditor }
constructor TBindListComboBoxEditor.Create(ACombobox: TCustomComboBox);
begin
inherited Create(ACombobox);
end;
function TBindListComboBoxEditor.CreateItemsEditor(
AControl: TControl): TBaseListBoxItemEditorObject;
begin
Result := TComboBoxItemEditorObject.Create(AControl as TCustomComboBox);
end;
initialization
RegisterBindEditorFactory([TBindCheckBoxEditorFactory, TBindListBoxEditorFactory,
TBindComboBoxEditorFactory, TBindListViewEditorFactory, TBindStringGridEditorFactory]);
finalization
UnregisterBindEditorFactory([TBindCheckBoxEditorFactory, TBindListBoxEditorFactory,
TBindComboBoxEditorFactory, TBindListViewEditorFactory, TBindStringGridEditorFactory]);
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls,
ATSynEdit,
ATSynEdit_Carets,
ATSynEdit_Commands,
ATSynEdit_Cmp_Form;
type
{ TForm1 }
TForm1 = class(TForm)
Ed: TATSynEdit;
Panel1: TPanel;
procedure EdCommand(Sender: TObject; ACommand: integer;
AInvoke: TATEditorCommandInvoke; const AText: string;
var AHandled: boolean);
procedure EdKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
private
procedure DoCompletionProp(Sender: TObject;
AContent: TStringList; out ACharsLeft, ACharsRight: integer);
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
const
cmd_AutoComplete = 3000;
{ TForm1 }
procedure TForm1.FormShow(Sender: TObject);
begin
Ed.Strings.LineAdd('Some text here, press Ctrl+Space');
Ed.DoCaretSingle(14, 0);
Ed.Update(true);
end;
procedure TForm1.DoCompletionProp(Sender: TObject; AContent: TStringList; out
ACharsLeft, ACharsRight: integer);
const
cNonWordChars = '-+*=/\()[]{}<>"''.,:;~?!@#$%^&|`…';
var
Caret: TATCaretItem;
SWord: UnicodeString;
begin
if Ed.Carets.Count<>1 then
begin
ShowMessage('Completion cannot handle multi-carets');
exit;
end;
Caret:= Ed.Carets[0];
EditorGetCurrentWord(Ed,
Caret.PosX, Caret.PosY,
cNonWordChars,
SWord,
ACharsLeft,
ACharsRight);
AContent.Clear;
AContent.Add('func|SomeFunc|(param1, param2)'#9'Function description');
AContent.Add('var|SomeId1|'#9'Description one');
AContent.Add('var|AnotherId2|'#9'Description two');
end;
procedure TForm1.EdCommand(Sender: TObject; ACommand: integer;
AInvoke: TATEditorCommandInvoke; const AText: string; var AHandled: boolean);
begin
if ACommand=cmd_AutoComplete then
begin
AHandled:= true;
EditorShowCompletionListbox(Ed, @DoCompletionProp);
end;
end;
procedure TForm1.EdKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key=Ord(' ')) and (Shift=[ssCtrl]) then
Ed.DoCommand(cmd_AutoComplete, cInvokeAppInternal);
end;
end.
|
unit sort_quick_1;
interface
implementation
type TIntArray = array of int32;
var A: TIntArray;
function Compare(L, R: Int32): Int32;
begin
if L < R then
Result := -1
else if L > R then
Result := 1
else
Result := 0;
end;
procedure QuickSort(Values: TIntArray; L, R: Int32);
var
I, J: Int32;
pivot, temp: Int32;
begin
if (Length(Values) = 0) or ((R - L) <= 0) then
Exit;
repeat
I := L;
J := R;
pivot := Values[L + (R - L) shr 1];
repeat
while Compare(Values[I], pivot) < 0 do
Inc(I);
while Compare(Values[J], pivot) > 0 do
Dec(J);
if I <= J then
begin
if I <> J then
begin
temp := Values[I];
Values[I] := Values[J];
Values[J] := temp;
end;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then
QuickSort(Values, L, J);
L := I;
until I >= R;
end;
procedure Test;
begin
A := [4, 7, 1, 6, 2, 0, 3, 5, 9, 8];
QuickSort(A, Low(A), High(A));
end;
initialization
Test();
finalization
Assert(A[0] = 0);
Assert(A[9] = 9);
end. |
{
@abstract(Constants for GMLib.)
@author(Xavier Martinez (cadetill) <cadetill@gmail.com>)
@created(January 20, 2016)
@lastmod(January 20, 2016)
The GMMapVCL contains the implementation of TGMMap class that encapsulate the @code(google.maps.Map) class from Google Maps API and other related classes.
}
unit GMConstants;
{$I ..\gmlib.inc}
interface
const
ct_RES_MAPA_CODE = 'RES_MAPCODE';
ct_API_KEY = 'API_KEY';
ct_API_VER = 'API_VER';
ct_API_SIGNED = 'API_SIGNED';
ct_API_LAN = 'API_LAN';
ct_FILE_NAME = 'mapa.html';
implementation
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ SOAP Support }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Soap.SOAPHTTPPasInv;
interface
uses
System.Classes, Soap.SOAPPasInv, Soap.SOAPHTTPDisp, Soap.WSDLIntf;
type
THTTPSoapPascalInvoker = class(TSoapPascalInvoker, IHTTPSoapDispatch)
public
procedure DispatchSOAP(const Path, SoapAction: string; const Request: TStream;
Response: TStream; var BindingType: TWebServiceBindingType); virtual;
end;
{ A new typename to be more C++ friendly }
THTTPSoapCppInvoker = class(THTTPSoapPascalInvoker)
end;
implementation
uses
System.SysUtils, System.TypInfo, Soap.HTTPSOAPToPasBind, Soap.IntfInfo, Soap.SOAPConst;
procedure THTTPSoapPascalInvoker.DispatchSOAP(const Path, SoapAction: string; const Request: TStream;
Response: TStream; var BindingType: TWebServiceBindingType);
var
IntfInfo: PTypeInfo;
PascalBind: IHTTPSOAPToPasBind;
InvClassType: TClass;
ActionMeth: String;
MD: TIntfMetaData;
procedure RaiseNoIntfException(const str: string);
var
IntfName: string;
begin
IntfName := SUnknownInterface;
try
GetIntfMetaData(IntfInfo, MD);
IntfName := MD.UnitName + '.' + MD.Name;
except
{ Ignore }
end;
raise Exception.CreateFmt(SInvClassNotRegistered, [IntfName, str]);
end;
begin
PascalBind := THTTPSOAPToPasBind.Create as IHTTPSOAPToPasBind;
if (SoapAction <> '') and (SoapAction <> '""') then
begin
if not PascalBind.BindToPascalByAction(SoapAction, InvClassType, IntfInfo, ActionMeth) or (InvClassType = nil) then
begin
if IntfInfo = nil then
raise Exception.CreateFmt(SInvInterfaceNotReg, [SoapAction])
else if InvClassType = nil then
RaiseNoIntfException(SoapAction)
else
raise Exception.CreateFmt(SUnknownSoapAction, [SoapAction]);
end;
end else
begin
if not PascalBind.BindToPascalByPath(Path, InvClassType, IntfInfo, ActionMeth) or (InvClassType = nil) then
begin
if IntfInfo = nil then
raise Exception.CreateFmt(SInvInterfaceNotRegURL, [Path])
else if InvClassType = nil then
RaiseNoIntfException(Path)
else
raise Exception.CreateFmt(SNoServiceForURL, [Path]);
end;
end;
{ Here we've found the interface/method to invoke }
Invoke(InvClassType, IntfInfo, ActionMeth, Request, Response, BindingType);
end;
end.
|
unit ncaFrmJust;
{
ResourceString: Dario 11/03/13
Nada pra fazer
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, cxControls,
cxContainer, cxEdit, cxTextEdit, cxMemo, cxGraphics, cxLookAndFeels,
LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
LMDSimplePanel, cxLabel;
type
TFrmJust = class(TForm)
LMDSimplePanel2: TLMDSimplePanel;
btnSalvar: TcxButton;
btnCancelar: TcxButton;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
edObs: TcxTextEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnSalvarClick(Sender: TObject);
private
{ Private declarations }
public
function Editar(var Obs: String; aSalvar: Boolean): Boolean;
{ Public declarations }
end;
var
FrmJust: TFrmJust;
implementation
{$R *.dfm}
uses ncaFrmPri;
procedure TFrmJust.btnSalvarClick(Sender: TObject);
begin
if Trim(edObs.Text)='' then begin
edObs.SetFocus;
raise Exception.Create('É obrigatório informar o motivo do cancelado');
end;
if Length(Trim(edObs.Text))<15 then begin
edObs.SetFocus;
raise Exception.Create('A justificativa deve ter no mínimo 15 caracteres');
end;
ModalResult := mrOk;
end;
function TFrmJust.Editar(var Obs: String; aSalvar: Boolean): Boolean;
begin
btnSalvar.Enabled := aSalvar;
edObs.Text := Obs;
ShowModal;
edObs.PostEditValue;
if ModalResult=mrOk then begin
Obs := Trim(edObs.Text);
Result := True;
end else
Result := False;
end;
procedure TFrmJust.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmJust.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
Key_F2 : if btnSalvar.Enabled then btnSalvar.Click;
Key_Esc : Close;
end;
end;
procedure TFrmJust.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key in [#27, #13] then Key := #0;
end;
end.
|
unit uNexTransResourceStrings_PT;
interface
resourcestring
rsCodigoExtra = 'Código Extra';
rsTaxaEntregaFrete = 'Taxa de Entrega / Frete';
rsTaxaEntFrete = 'Taxa Entr./Frete';
rsImagemMuitoGrande = 'O tamanho do arquivo de imagem não pode ser maior que 250KB';
rsRecalcComissao = 'Recalculando comissões ...';
rsCorrigeLucro =
'Corrigindo informação de lucro nas vendas ...';
rsGrava_Vendedor =
'Gravando informação do vendedor';
rsTotalizaComissao_venda_dev =
'Totalizando comissão de vendas e devoluções';
rsImportNewDoc =
'Atualizando dados de modelos de documentos';
rsCorrigindoComissaoDev =
'Corrigindo comissão de devoluções';
rsAjusta_ids_pagto =
'Corrigindo descrição de meios de pagamento usado nas vendas ...';
rsAjusta_pagesp_caixa_entrada_saida =
'Corrigindo dados de entrada e saída de dinheiro do caixa ...';
rsCorrigeDescrItensVenda =
'Corrigindo descrição de itens vendidos ...';
rsCorrigeDescrVenda =
'Corrigindo descrição das vendas ...';
rsAddCred = 'Correção Crédito +';
rsRemoverCred = 'Correção Crédito -';
rsVenda = 'Venda';
rsCompra = 'Compra';
rsEntradaEst = 'Correção de Estoque +';
rsEntradaEstTela = 'Correção de Estoque (Entrada)';
rsSaidaEst = 'Correção de Estoque -';
rsSaidaEstTela = 'Correção de Estoque (Saída)';
rsPagDebito = 'Pagamento Débito';
rsSuprCaixa = 'Suprimento Caixa';
rsSangriaCaixa = 'Sangria Caixa';
rsCorrecaoCaixa = 'Correção Data Caixa';
rsCorrecaoFid = 'Correção Fidelidade';
rsAjustaCusto = 'Ajuste de Custo';
rsZerarEstoque = 'Zerar Estoque';
rsDevolucao = 'Devolução';
rsDevFor = 'Devolução ao Fornecedor';
rsTransf = 'Transfenrência de Mercadoria (Saída)';
rsTasnsfEnt = 'Transfenrência de Mercadoria (Entrada)';
rsOutEntr = 'Ountras Entradas';
rsCaixa = 'Caixa';
rsValorCreditado = 'Valor Creditado';
rsValorRemovido = 'Valor Removido';
rsNao = 'Não';
rsSim = 'Sim';
rsPremioFidelidade = 'Prêmio Fidelidade';
SLingua = 'pt';
SncaFrmPopupUnidade_Unidade = 'unidade';
SncaFrmPopupUnidade_NãoéPossívelA = 'Não é possível apagar esta unidade pois existem outos produtos que a utilizam.';
SncaFrmPopupUnidade_EstaUnidadeJá = 'Esta unidade já existe.';
SncaFrmPopupCategoria_Categoria = 'categoria';
SncaFrmPopupCategoria_NãoéPossíve = 'Não é possível apagar esta categoria pois existem outos produtos que a utilizam.';
SncaFrmPopupCategoria_EstaCategor = 'Esta categoria já existe.';
SncaFrmPopUpEdit_ProdutoSem = 'Produto sem ';
SncaFrmPri_VocêDeveSerUmAssinanteDoNexParaU = 'Você deve ser um assinante do Nex para utilizar essa função';
SncaFrmPri_Atenção = 'Atenção';
SncaFrmPri_NexNexAdmin = 'Nex | NexAdmin';
SncaFrmPri_NexNexAdminUsuário = 'Nex | NexAdmin | Usuário: ';
SncaFrmPri_Pasta = ' | Pasta: ';
SncaFrmPri_TrocarDeUsuário = 'Trocar de Usuário';
SncaFrmPri_SuaAssinaturaPremiumVenceu = 'Sua assinatura Premium venceu.';
SncaFrmPri_SuaAssinaturaPremiumVenceHOJE = 'Sua assinatura Premium vence HOJE.';
SncaFrmPri_SuaAssinaturaPremiumVenceAMANHÃ = 'Sua assinatura Premium vence AMANHÃ.';
SncaFrmPri_SuaAssinaturaPremiumVenceEm2Dias = 'Sua assinatura Premium vence em 2 dias.';
SncaFrmPri_SuaAssinaturaPremiumVenceEm3Dias = 'Sua assinatura Premium vence em 3 dias.';
SncaFrmPri_SuaAssinaturaPremiumVenceEm4Dias = 'Sua assinatura Premium vence em 4 dias.';
SncaFrmPri_SuaAssinaturaPremiumVenceEm5Dias = 'Sua assinatura Premium vence em 5 dias.';
SncaFrmPri_SuaAssinaturaPremiumPremiumVence = 'Sua assinatura Premium Premium vence em ';
SncaFrmPri_Dias = ' dias.';
SncaFrmPri_SuaAssinaturaPremiumVenceEm = 'Sua assinatura Premium vence em ';
SncaFrmPri_Versão = 'Versão ';
SncaFrmPri_CriarSenha = 'Criar Senha';
SncaFrmPri_AlterarSenha = 'Alterar Senha';
SncaFrmPri_AConexãoComOServidorNexFoiPerdid = 'A conexão com o servidor Nex foi perdida. O NexAdmin será fechado.';
SncaFrmPri_ClienteNãoEncontrado = 'Cliente não encontrado!';
SncaFrmPri_MostrarTextoDosBotões = 'Mostrar Texto dos Botões';
SncaFrmPri_OcultarTextoDosBotões = 'Ocultar Texto dos Botões';
SncaFrmPri_Login = 'Login';
SncaFrmPri_Versão_1 = ' Versão: ';
SncaFrmPri_Ok = 'Ok';
SncaFrmPri_Versão_2 = '| Versão: ';
SncaFrmPri_Conta = ' | Conta: ';
SncaFrmPri_OcultarTextosDosBotões = 'Ocultar Textos dos Botões';
SncaFrmPri_MostrarTextosDosBotões = 'Mostrar Textos dos Botões';
SncaFrmPri_Recortar = 'Recortar';
SncaFrmPri_Copiar = '&Copiar';
SncaFrmPri_Colar = 'Colar';
SncaFrmPri_EXcluir = 'E&xcluir';
SncaFrmPri_SelecionarUmArquivo = '&Selecionar um arquivo...';
SncaFrmPri_SalvarCOmo = 'Salvar C&omo...';
SncaFrmPri_Nenhum = 'Nenhum';
SncaFrmPri_EmptyString = '';
SncaFrmPri_OrdenarCrescente = 'Ordenar Crescente';
SncaFrmPri_OrdenarDecrescente = 'Ordenar Decrescente';
SncaFrmPri_NãoOrdenar = 'Não Ordenar';
SncaFrmPri_AgruparPorEstaColuna = 'Agrupar por esta coluna';
SncaFrmPri_RemoverDoAgrupamento = 'Remover do agrupamento';
SncaFrmPri_Agrupamento = 'Agrupamento';
SncaFrmPri_Alinhamento = 'Alinhamento';
SncaFrmPri_àEsquerda = 'à Esquerda';
SncaFrmPri_àDireita = 'à Direita';
SncaFrmPri_AoCentro = 'ao Centro';
SncaFrmPri_RemoverEstaColuna = 'Remover esta coluna';
SncaFrmPri_SelecionarColunas = 'Selecionar Colunas';
SncaFrmPri_TamanhoIdeal = 'Tamanho ideal';
SncaFrmPri_TamanhoIdealTodasColunas = 'Tamanho ideal (Todas colunas)';
SncaFrmPri_Rodapé = 'Rodapé';
SncaFrmPri_RodapéEmAgrupamento = 'Rodapé em agrupamento';
SncaFrmPri_Somar = 'Somar';
SncaFrmPri_Min = 'Min';
SncaFrmPri_Max = 'Max';
SncaFrmPri_Contar = 'Contar';
SncaFrmPri_Média = 'Média';
SncaFrmPri_VocêNãoPodeCriarNiveisRecursivos = 'Você não pode criar niveis recursivos';
SncaFrmPri_ApagarRegistro = 'Apagar registro?';
SncaFrmPri_ApagarTodosRegistrosSelecionados = 'Apagar todos registros selecionados?';
SncaFrmPri_CliqueAquiParaAdicionarUmNovoReg = 'Clique aqui para adicionar um novo registro';
SncaFrmPri_FiltroEstáVazio = '<Filtro está vazio>';
SncaFrmPri_Customização = 'Customização';
SncaFrmPri_Colunas = 'Colunas';
SncaFrmPri_ArrasteAquiOCabeçalhoDeUmaColuna = 'Arraste aqui o cabeçalho de uma coluna para agrupar por esta coluna';
SncaFrmPri_Customizar = 'Customizar...';
SncaFrmPri_Bandas = 'Bandas';
SncaFrmPri_CxGridNãoExistet = 'cxGrid não existet';
SncaFrmPri_ComponenteNãoExiste = 'Componente não existe';
SncaFrmPri_ErroDeImportação = 'Erro de importação';
SncaFrmPri_GridViewNãoExiste = 'Grid view não existe';
SncaFrmPri_GridLevelAtivoNãoExiste = 'Grid level ativo não existe';
SncaFrmPri_FalhaNaCriaçãoDoArquivoDeExporta = 'Falha na criação do arquivo de exportação';
SncaFrmPri_Filtro = 'Filtro';
SncaFrmPri_NovaCondição = 'Nova &Condição';
SncaFrmPri_NovoGrupo = 'Novo &Grupo';
SncaFrmPri_RemoverLinha = '&Remover Linha';
SncaFrmPri_LimparTudo = 'Limpar &Tudo';
SncaFrmPri_PressioneOBotãoParaAdicionarUmaN = 'pressione o botão para adicionar uma nova condição';
SncaFrmPri_SeAplicaAsSeguintesCondições = 'se aplica as seguintes condições';
SncaFrmPri_Raiz = '<raiz>';
SncaFrmPri_Vazio = '<vazio>';
SncaFrmPri_NãoéPossívelMontarOFiltroNessaOr = 'Não é possível montar o filtro nessa origem';
SncaFrmPri_FiltroCustomizado = 'Filtro Customizado';
SncaFrmPri_ValorInválido = 'Valor inválido';
SncaFrmPri_Usar = 'Usar';
SncaFrmPri_ParaRepresentarQualquerCaracter = 'para representar qualquer caracter';
SncaFrmPri_ParaRepresentarQualquerSérieDeCa = 'para representar qualquer série de caracteres';
SncaFrmPri_OU = 'OU';
SncaFrmPri_MostrarRegistrosOnde = 'Mostrar registros onde:';
SncaFrmPri_CriadorDeFiltro = 'Criador de Filtro';
SncaFrmPri_SemtituloFlt = 'semtitulo.flt';
SncaFrmPri_AbrirUmFiltroExistente = 'Abrir um filtro existente';
SncaFrmPri_SalvarOFiltroAtivoParaUmArquivo = 'Salvar o filtro ativo para um arquivo';
SncaFrmPri_SalvarComo_1 = '&Salvar como...';
SncaFrmPri_Abrir = '&Abrir...';
SncaFrmPri_APlicar = 'A&plicar';
SncaFrmPri_OK_1 = 'OK';
SncaFrmPri_Cancelar_1 = 'Cancelar';
SncaFrmPri_Flt = 'flt';
SncaFrmPri_FilttrosFltFlt = 'Filttros (*.flt)|*.flt';
SncaFrmPri_SejaIgualA = 'seja igual a';
SncaFrmPri_SejaDiferenteDe = 'seja diferente de';
SncaFrmPri_SejaMenorQue = 'seja menor que';
SncaFrmPri_SejaMenorQueOuIgualA = 'seja menor que ou igual a';
SncaFrmPri_SejaMaiorQue = 'seja maior que';
SncaFrmPri_SejaMaiorQueOuIgualA = 'seja maior que ou igual a';
SncaFrmPri_Contenha = 'contenha';
SncaFrmPri_NãoContenha = 'não contenha';
SncaFrmPri_TenhaValorEntre = 'tenha valor entre';
SncaFrmPri_NãoTenhaValorEntre = 'não tenha valor entre';
SncaFrmPri_DentroDe = 'dentro de';
SncaFrmPri_ForaDe = 'fora de';
SncaFrmPri_SejaOntem = 'seja ontem';
SncaFrmPri_SejaHoje = 'seja hoje';
SncaFrmPri_SejaAmanhã = 'seja amanhã';
SncaFrmPri_SejaSemanaPassada = 'seja semana passada';
SncaFrmPri_SejaMêsPassado = 'seja mês passado';
SncaFrmPri_SejaAnoPassado = 'seja ano passado';
SncaFrmPri_SejaEstaSemana = 'seja esta semana';
SncaFrmPri_SejaEsteMês = 'seja este mês';
SncaFrmPri_SejaEsteAno = 'seja este ano';
SncaFrmPri_SejaAPróximaSemana = 'seja a próxima semana';
SncaFrmPri_SejaOPróximoMês = 'seja o próximo mês';
SncaFrmPri_SejaOPróximoAno = 'seja o próximo ano';
SncaFrmPri_AndLowerCase = 'e';
SncaFrmPri_AndUpperCase = 'E';
SncaFrmPri_Ou_1 = 'ou';
SncaFrmPri_Não = 'não';
SncaFrmPri_Branco = 'branco';
SncaFrmPri_EstejaEmBranco = 'esteja em branco';
SncaFrmPri_NaoEstejaEmBranco = 'nao esteja em branco';
SncaFrmPri_ComeceCom = 'comece com';
SncaFrmPri_NãoComeceCom = 'não comece com';
SncaFrmPri_TermineCom = 'termine com';
SncaFrmPri_NãoTermineCom = 'não termine com';
SncaFrmPri_NaoContenha = 'nao contenha';
SncaFrmPri_Todos_1 = '(Todos)';
SncaFrmPri_Customizado = '(Customizado...)';
SncaFrmPri_Brancos = '(Brancos)';
SncaFrmPri_NãoBrancos = '(não Brancos)';
SncaDM_SuaContaNexCaféNãoEstáAtivadaEmS = 'É necessário ativar sua conta';
SncaDM_OCaixaEstáFechadoÉNecessárioAbri = 'O caixa está fechado. É necessário abrir o caixa para executar essa operação.';
SncaDM_Horas = 'Horas';
SncaDM_Minutos = 'Minutos';
SncaDM_Segundos = 'Segundos';
SncaDM_Ajuda = 'Ajuda';
SncaDM_AConexãoComOServidorNexCaféFoiPe = 'A conexão com o servidor Nex foi perdida. Clique em OK e inicie novamente o NexAdmin.';
SncaDM_ErroCriandoJanelaDeAcessoRemoto = 'Erro criando janela de acesso remoto';
SncaDM_SemPrevisão = 'Sem previsão';
SncaDM_JáExisteUmCMAdminSendoExecutado = 'Já existe um CM-Admin sendo executado!';
SncaDM_AConexãoComOServidorNexCaféFoiPe_1 = 'A conexão com o servidor Nex foi perdida. O NexAdmin será fechado.';
SncaDM_ChatNexCaféMáq = 'Chat NexCafé - Máq.';
SncaDM_AtendenteDiz = 'Atendente diz';
SncaDM_MáquinaDiz = 'Máquina diz';
SncaDM_PósPago = 'Pós-Pago';
SncaDM_PósPagoTempoLivre = 'Pós-pago: Tempo Livre';
SncaDM_TempoLivre = 'Tempo Livre';
SncaDM_PósPagoLimiteDeTempo = 'Pós-pago: Limite de Tempo';
SncaDM_LimiteDeTempo = 'Limite de Tempo';
SncaDM_PréPago = 'Pré-Pago';
SncaDM_DigitarTempoOuValor = 'Digitar Tempo ou Valor';
SncaDM_CartãoDeTempo = 'Cartão de Tempo';
SncaDM_RegistroNãoEncontrado = 'Registro não encontrado';
SncaDM_EmManutenção = 'Em manutenção';
SncaDM_Livre = 'Livre';
SufmFormBase_Classe = 'Classe ';
SufmFormBase_NãoRegistrada = ' não registrada';
SufmFormBase_Mostrar = 'Mostrar';
SufmFormBase_PeríodoHoje = 'Período: Hoje';
SufmFormBase_PeríodoEstaSemana = 'Período: Esta Semana';
SufmFormBase_PeríodoEsteMês = 'Período: Este Mês';
SufmFormBase_PeríodoEsteAno = 'Período: Este Ano';
SufmFormBase_PeríodoTudo = 'Período: Tudo';
SufmFormBase_Período = 'Período: ';
SufmFormBase_DdMmYyyyHhMm = 'dd/mm/yyyy hh:mm';
SncafbMaquinas_Máquinas = 'Máquinas';
SncafbMaquinas_NãoExisteAcessoEmAndamentoNaMáqu = 'Não existe acesso em andamento na máquina ';
SncafbMaquinas_DesejaRealmenteFinalizarOAcessoN = 'Deseja realmente finalizar o acesso na máquina ';
SncafbMaquinas_ParaIniciarUmNovoAcessoNessaMáqu = 'Para iniciar um novo acesso nessa máquina é necessário registrar o pagamento. ';
SncafbMaquinas_VocêPoderáRegistrarOPagamentoAtr = 'Você poderá registrar o pagamento através do duplo-clique ou do botão "Editar"';
SncafbMaquinas_JáExisteUmAcessoEmAndamentoNaMáq = 'Já existe um acesso em andamento na máquina ';
SncafbMaquinas_AcessoGratuitoSóPodeSerAbertoDir = 'Acesso gratuito só pode ser aberto diretamente na máquina cliente.';
SncafbMaquinas_EDespausar = '&E. Despausar';
SncafbMaquinas_EPausar = '&E. Pausar';
SncafbMaquinas_ConfirmaTransferênciaDoAcessoDaM = 'Confirma transferência do acesso da máquina ';
SncafbMaquinas_ParaAMáquina = ' para a máquina ';
SncafbMaquinas_AguardaPagto = 'Aguarda Pagto.';
SncafbMaquinas_Funcionário = 'Funcionário';
SncafbMaquinas_FimDeTempo = 'Fim de Tempo';
SncafbMaquinas_Pausado = 'Pausado';
SncafbMaquinas_HoraNãoPerm = 'Hora Não Perm.';
SncafbMaquinas_EmUso = 'Em Uso';
SncafbMaquinas_Livre = 'Livre';
SncafbMaquinas_ProdutosVendidos = 'Produtos Vendidos';
SncafbMaquinas_CliqueParaEditarCorrigirAVendaMa = 'Clique para editar/corrigir a venda mais recente para essa máquina';
SncafbMaquinas_Impressões = 'Impressões';
SncafbMaquinas_CliqueParaEditarCorrigirAImpress = 'Clique para editar/corrigir a impressão mais recente dessa máquina';
SncafbMaquinas_Chat = 'Chat';
SncafbMaquinas_CliqueParaEnviarUmaMensagemDeCha = 'Clique para enviar uma mensagem de chat para essa máquina';
SncafbMaquinas_SemConexão = 'Sem conexão';
SncafbMaquinas_EssaMáquinaNãoEstáConectadaNoSer = 'Essa máquina não está conectada no servidor NexCafé. Clique para saber mais.';
SncafbMaquinas_EditarCliente = 'Editar Cliente';
SncafbMaquinas_MantenhaATeclaCTRLApertadaECliqu = 'Mantenha a tecla CTRL apertada e clique no nome do cliente para editar.';
SncafbMaquinas_CadastrarMáquina = 'Cadastrar Máquina';
SncafbMaquinas_Indisponível = '-- Indisponível --';
SncafbMaquinas_DuploCliqueAqui = '(duplo clique aqui)';
SncafbMaquinas_Página = ' página';
SncafbMaquinas_Páginas = ' páginas';
SncafbMaquinas_Pg = 'pg';
SncafbMaquinas_DespausarMáq = 'Despausar máq. ';
SncafbMaquinas_PausarMáq = 'Pausar máq. ';
SncafbMaquinas_PBloquearSite = '&P. Bloquear site: ';
SncafbMaquinas_PBloquearSite_1 = '&P. Bloquear site';
SncafbMaquinas_5LigarMáq = '&5. Ligar máq.';
SncafbMaquinas_EmManutenção = 'Em Manutenção';
SncafbMaquinas_Reservado_1 = 'Reservado: ';
SncafbMaquinas_CaixaEstáFechado = 'Caixa está fechado!';
SncaFrmLogin_DetectarAutomaticamente = 'Detectar Automaticamente';
SncaFrmLogin_Versão = 'Versão ';
SncafbTran_Transações = 'Transações';
SncafbTran_DesejaRealmenteFecharOCaixaAtual = 'Deseja realmente fechar o caixa atual?';
SncafbTran_NãoExistemTransaçõesParaEsseClie = 'Não existem transações para esse cliente';
SncafbTran_NãoFoiRealizadaNenhumaOperaçãoNe = 'Não foi realizada nenhuma operação nesse caixa';
SncafbTran_AindaNãoFoiRealizadaNenhumaTrans = 'Ainda não foi realizada nenhuma transação nesse caixa';
SncafbTran_OCaixaEstáFechado = 'O caixa está fechado';
SncafbTran_1Centavo = '1 centavo';
SncafbTran_5Centavos = '5 centavos';
SncafbTran_10Centavos = '10 centavos';
SncafbTran_25Centavos = '25 centavos';
SncafbTran_50Centavos = '50 centavos';
SncafbTran_1Moeda = '1 (moeda)';
SncafbTran_1Cédula = '1 (cédula)';
SncafbTran_10 = '10';
SncafbTran_20 = '20';
SncafbTran_50 = '50';
SncafbTran_100 = '100';
SncafbTran_R0 = 'R$ 0';
SncafbTran_R000 = 'R$ 0,00';
SncafbTran_NãoéPermitidoCancelarUmaVendaPlu = 'Não é permitido cancelar uma Venda Plus';
SncafbTran_DesejaRealmenteCancelarATransaçã = 'Deseja realmente cancelar a transação selecionada?';
SncafbTran_OpçõesDeCaixa = 'Opções de Caixa';
SncafbTran_CaixaAtualNãoEncontrado = 'Caixa atual não encontrado';
SncaFrmTipos_InicioDeSessão = 'Inicio de Sessão';
SncaFrmTipos_FimDeSessão = 'Fim de Sessão';
SncaFrmTipos_CréditoDeTempo = 'Crédito';
SncaFrmTipos_DébitoDeTempo = 'Débito de Tempo';
SncaFrmTipos_Venda = 'Venda';
SncaFrmTipos_Compra = 'Compra';
SncaFrmTipos_EntradaEstoque = 'Entrada Estoque';
SncaFrmTipos_SaídaEstoque = 'Saída Estoque';
SncaFrmTipos_PagamentoDeDébito = 'Pagamento de Débito';
SncaFrmTipos_SuprimentoCaixa = 'Suprimento Caixa';
SncaFrmTipos_SangriaCaixa = 'Sangria Caixa';
SncaFrmTipos_Impressão = 'Impressão';
SncaFrmTipos_TransferênciaDeMáquina = 'Transferência de Máquina';
SncaFrmTipos_CorreçãoDeCaixa = 'Correção de Caixa';
SncaFrmTipos_CorreçãoDePontosFidelidade = 'Correção de Pontos Fidelidade';
SncafbCartoes_MostrarNãoExpirados = 'Mostrar: Não Expirados';
SncafbCartoes_MostrarExpirados = 'Mostrar: Expirados';
SncafbCartoes_MostrarTodos = 'Mostrar: Todos';
SncafbCartoes_NãoFoiUtilizado = 'Não foi utilizado';
SncafbCartoes_Utilizados = ' utilizados';
SncafbCartoes_NãoéPossívelCancelarUmCartãoExpi = 'Não é possível cancelar um cartão expirado';
SncafbCartoes_DesejaRealmenteCancelarEsseCartã = 'Deseja realmente cancelar esse cartão de tempo?';
SncafbCartoes_CartõesDeTempo = 'Cartões de Tempo';
SncaFrmCadCli_Hora = 'hora';
SncaFrmCadCli_DataDeNascimentoNãoéVálida = 'Data de nascimento não é válida';
SncaFrmCadCli_NomeNãoPodeSerDeixadoEmBranco = 'Nome não pode ser deixado em branco !';
SncaFrmCadCli_JáExisteUmClienteCadastradoComEs = 'Já existe um cliente cadastrado com esse RG';
SncaFrmCadCli_JáExisteOutroClienteCadastradoCo = 'Já existe outro cliente cadastrado com esse mesmo Username!';
SncaFrmCadCli_ÉNecessárioEscolherUmaFaixaDeHor = 'É necessário escolher uma faixa de horário para a censura de horário';
SncaFrmCadCli_UsernameIndisponível = 'Username indisponível.';
SncaFrmCadCli_UsernameDisponível = 'Username disponível!';
SncaFrmCadCli_SeguirLimitePadrão = 'Seguir limite padrão (';
SncaFrmCadCli_SeguirOpçãoPadrão = 'Seguir opção padrão ';
SncaFrmCadCli_Livre = 'Livre';
SncaFrmCadCli_1Ano = '1 ano';
SncaFrmCadCli_Anos = ' anos';
SncafbProdutos_Produtos = 'Produtos';
SncafbProdutos_Sim = 'Sim';
SncafbProdutos_SM = 's/m';
SncafbProdutos_SemMínimo = 'Sem mínimo';
SncafbProdutos_EssaOperaçãoAlteraOEstoqueAtualD = 'Essa operação altera o estoque atual dos produtos para o mesmo ';
SncafbProdutos_ValorContidoNoHistóricoDeTransaç = 'valor contido no histórico de transações de cada produto. Deseja realmente reprocessar o estoque?';
SncafbProdutos_EstoqueReprocessadoComSucesso = 'Estoque reprocessado com sucesso!';
SncafbProdutos_DesejaRealmenteApagarOProduto = 'Deseja realmente apagar o produto ';
SncafbProdutos_OpçõesParaProdutos = 'Opções para Produtos';
SncaFrmProduto_OpçõesParaProdutos = 'Opções para Produtos';
SncaFrmProduto_CampoCódigoNãoPodeSerDeixadoEmBr = 'Campo código não pode ser deixado em branco!';
SncaFrmProduto_JáExisteUmProdutoCadastradoComEs = 'Já existe um produto cadastrado com esse código';
SncaFrmProduto_CampoDescriçãoNãoPodeSerDeixadoE = 'Campo descrição não pode ser deixado em branco!';
SncafgExtratoFid_ExtratoDeMovimentaçaoDePontos = 'Extrato de movimentaçao de pontos';
SncaFrmUsuario_ÉNecessárioInformarUmUsername = 'É necessário informar um username';
SncaFrmUsuario_ÉNecessárioInformarUmNome = 'É necessário informar um nome';
SncaFrmUsuario_MarqueOsItensQueEsseUsuárioTemDi = 'Marque os itens que esse usuário tem direito de acessar:';
SncaFrmUsuario_UsuárioAdministradorNãoéNecessár = 'Usuário Administrador. Não é necessário marcar os direitos abaixo';
SncaFrmSenhaWiz_AsSenhasNãoEstãoIguais = 'As senhas não estão iguais.';
SncafbCaixa_Caixa = 'Caixa';
SncafbCaixa_CaixaAtual = 'Caixa Atual';
SncafbCaixasA_CaixasAnteriores = 'Caixas Anteriores';
SncafbCaixasA_OEMailSeráEnviadoEmAté5Minutos = 'O e-mail será enviado em até 5 minutos';
SncafbCaixasA_PeríodoTudo = 'Período: Tudo';
SncafbCaixasA_DesejaRealmenteReprocessarOCaixa = 'Deseja realmente reprocessar o caixa n.';
SncafbCaixasA_De = ' de ';
SncaFrmCaixa_CaixaDe = 'Caixa de ';
SncaFrmCaixa_DdMmYyyy = 'dd/mm/yyyy';
SncaFrmCaixa_DdMmYyyyHhMm = 'dd/mm/yyyy hh:mm';
SncaFrmCaixa_TotalFinanceiro = 'Total Financeiro';
SncaFrmCaixa_Caixa = 'Caixa ';
SncaFrmCaixa_Abertura_1 = 'Abertura : ';
SncaFrmCaixa_Fechamento = 'Fechamento : ';
SncaFrmCaixa_Funcionário = 'Funcionário: ';
SncafbOpcoes_NomeDeUsuário = 'Nome de Usuário';
SncafbOpcoes_Opções = 'Opções';
SncafbUsuarios_Usuários = 'Usuários';
SncafbUsuarios_NãoéPossívelApagarOúnicoUsuárioA = 'Não é possível apagar o único usuário administrador do sistema';
SncafbUsuarios_ConfirmaAExclusãoDe = 'Confirma a exclusão de ';
SncaFrmAjustaFid_ÉNecessárioInformarAQuantidadeDe = 'É necessário informar a quantidade de pontos';
SncaFrmAjustaFid_ZerarPontos = 'Zerar Pontos (';
SncaFrmContato_DisponívelEmNossoSite = 'Disponível em nosso site: ';
SncClassesBase_ErroNexCafé = 'Erro Nex (';
SncClassesBase_NOMEDALOJA = 'NOME DA LOJA';
SncaFrmFundo_ArquivosJPEGJpg = 'Arquivos JPEG|*.jpg';
SncaFrmFundo_ArquivosJPEGJpgArquivosGIFGif = 'Arquivos JPEG|*.jpg|Arquivos GIF|*.gif';
SncafbClientes_TodosClientes = 'Todos Clientes';
SncafbClientes_ClientesComDébito = 'Clientes com Débito';
SncafbClientes_ClientesComCrédito = 'Clientes com Crédito';
SncafbClientes_ClientesAtivos = 'Clientes Ativos';
SncafbClientes_ClientesInativos = 'Clientes Inativos';
SncafbClientes_Aniversariantes = 'Aniversariantes';
SncafbClientes_BuscaPorNome = 'Busca por Nome';
SncafbClientes_BuscaPorUsername = 'Busca por Username';
SncafbClientes_BuscaPorCódigo = 'Busca por Código';
SncafbClientes_EXibir = 'E&xibir: ';
SncafbClientes_1Cliente = '1 Cliente';
SncafbClientes_Clientes = ' Clientes';
SncafbClientes_DesejaZerarOsPontosFidelidadeDeT = 'Deseja zerar os pontos fidelidade de TODOS os clientes?';
SncafbClientes_EssaOperaçãoVaiZerarOsPontosFide = 'Essa operação vai zerar os pontos fidelidade de TODOS os clientes da loja. Deseja continuar ?';
SncafbClientes_ZerouPontosDeTodosClientes = 'Zerou pontos de todos clientes';
SncafbClientes_Clientes_1 = 'Clientes';
SncafbClientes_DébitosReprocessados = 'Débitos Reprocessados!';
SncafbClientes_BarMgrBar1 = 'BarMgrBar1';
SncafbClientes_ClientesINATIVOS_1 = 'Clientes INATIVOS';
SncafbClientes_QueNãoVieramNaLojaNosUltimos = 'Que não vieram na loja nos ultimos:';
SncafbClientes_DesejaGerarUmaListaDeEMailsDosCl = 'Deseja gerar uma lista de e-mails dos clientes? Você poderá copiar e colar os endereços para enviar e-mail para todos seus clientes usando sua conta de e-mail.';
SncafbClientes_NãoéPossívelApagarUmClienteQueEs = 'Não é possível apagar um cliente que está com acesso em andamento!';
SncafbClientes_EsseClientePossuiItensEmDébitoÉN = 'Esse cliente possui itens em débito. É necessário fazer o pagamento primeiramente, para depois excluir';
SncafbClientes_ConfirmaAExclusãoDe = 'Confirma a exclusão de ';
SncafbClientes_VocêNãoTemPermissãoParaApagarASe = 'Você não tem permissão para apagar a senha de clientes que tem acesso gratuito';
SncafbClientes_EssaOpçãoDeveSerUtilizadaQuandoO = 'Essa opção deve ser utilizada quando o cliente esquece a senha. ';
SncafbClientes_DessaFormaElePoderáCriarUmaNovaS = 'Dessa forma ele poderá criar uma nova senha. Deseja realmente apagar a senha atual?';
SncafbClientes_ClientesATIVOS_1 = 'Clientes ATIVOS';
SncafbClientes_QueVieramNaLojaNosUltimos = 'Que vieram na loja nos ultimos:';
SncafbClientes_Fidelidade = 'Fidelidade';
SncafbClientes_ÉNecessárioAtivarOSistemaDeFidel = 'É necessário ativar o sistema de fidelização de clientes em "Opções"';
SncaFrmOpcaoRelCaixa_ResumoFinanceiro = 'Resumo Financeiro';
SncaFrmOpcaoRelCaixa_VendasMovimentaçãoDeProdutos = 'Vendas/Movimentação de Produtos';
SncaFrmOpcaoRelCaixa_VendasPorCategoria = 'Vendas por Categoria';
SncaFrmOpcaoRelCaixa_Transações = 'Transações';
SncaFrmOpcaoRelCaixa_Sessões = 'Sessões';
SncaFrmOpcaoRelCaixa_PréPagoPósPago = 'Pré-pago/Pós-Pago';
SncaFrmOpcaoRelCaixa_Impressões = 'Impressões';
SncCompCliente_JáExisteUmaTransfênciaDeArquivoE = 'Já existe uma transfência de arquivo em andamento';
SncCompCliente_TClienteNexCafeÉPrecisoInformarO = 'TClienteNexCafe: É preciso informar o servidor do NexCafé';
SncaFrmVendaProd_ValorPagoNãoPodeSerMaiorQueOTota = 'Valor pago não pode ser maior que o total final';
SncaFrmVendaProd_OProdutoLançadoAnteriormenteNãoE = 'O produto lançado anteriormente não existe mais! Selecione um novo produto';
SncaFrmVendaProd_AjustaDeEstoqueENTRADA = 'Ajusta de Estoque - ENTRADA';
SncaFrmVendaProd_AjusteDeEstoqueSAIDA = 'Ajuste de Estoque - SAIDA';
SncaFrmVendaProd_Compra = 'Compra';
SncaFrmVendaProd_CustoUnitário = 'Custo Unitário';
SncaFrmME_OpçõesParaVendas = 'Opções para Vendas';
SncaFrmME_ÉNecessárioHaverItensParaSalvar = 'É necessário haver itens para salvar';
SncaFrmME_DescontoNãoPodeSerMaiorQueOValor = 'Desconto não pode ser maior que o valor total';
SncaFrmME_ValorPagoNãoPodeSerMaiorQueOTota = 'Valor pago não pode ser maior que o total final';
SncaFrmME_ÉNecessárioInformarOCliente = 'É necessário informar o cliente';
SncaFrmME_ClienteNãoPossuiQuantidadeDePont = 'Cliente não possui quantidade de pontos suficiente';
SncaFrmME_ParaFicarEmDébitoéNecessárioSele = 'Para ficar em débito é necessário selecionar um cliente';
SncaFrmME_OLimiteMáximoDeDébitoPermitidoPa = 'O limite máximo de débito permitido para esse cliente foi ultrapassado';
SncaFrmME_EsteProdutoNãoPermiteASuaVendaFr = 'Este produto não permite a sua venda fracionada!';
SncaFrmME_Venda = 'Venda';
SncaFrmME_ResgateDeProdutoDoProgramaDePont = 'Resgate de produto do programa de pontos/fidelidade';
SncaFrmME_Compra = 'Compra';
SncaFrmME_AjusteDeEstoqueSAÍDA = 'Ajuste de Estoque - SAÍDA';
SncaFrmME_AjusteDeEstoqueENTRADA = 'Ajuste de Estoque - ENTRADA';
SncaFrmDebito_ValorPagoNãoPodeSerMaiorQueTotal = 'Valor pago não pode ser maior que total final';
SncaFrmDebito_ValorDoDescontoNãoPodeSerMaiorQu = 'Valor do desconto não pode ser maior que o valor a pagar';
SncaFrmDebito_DébitoPago = 'Débito Pago';
SncaFrmDebito_AcessoMáq = 'Acesso Máq: ';
SncaFrmDebito_Acesso = 'Acesso';
SncaFrmDebito_Venda = 'Venda';
SncaFrmDebito_Venda_1 = 'Venda: ';
SncaFrmDebito_Impressão = 'Impressão';
SncaFrmDebito_Tempo = 'Tempo';
SncaFrmDebito_Tempo_1 = 'Tempo: ';
SncaFrmImp_ParaFicarEmDébitoéNecessárioSele = 'Para ficar em débito é necessário selecionar um cliente';
SncaFrmImp_OLimiteMáximoDeDébitoPermitidoPa = 'O limite máximo de débito permitido para esse cliente foi ultrapassado';
SncaFrmImp_Maq = 'Maq.';
SncaFrmImp_R0 = 'R$ 0';
SncaFrmImp_R000 = 'R$ 0,00';
SncDMCaixa_OReprocessamentoDeCaixaSóPodeSer = 'O reprocessamento de caixa só pode ser realizado em caixas que já foram fechados';
SncDMCaixa_TOTAL = 'TOTAL';
SncDMCaixa_PÁGINASDETECTADASAUTOMATICAMENTE = 'PÁGINAS DETECTADAS AUTOMATICAMENTE';
SncDMCaixa_Acessos = 'Acessos';
SncDMCaixa_Vendas = 'Vendas';
SncDMCaixa_VendasRecPend = 'Vendas de outros caixas';
SncDMCaixa_Impressões = 'Impressões';
SncDMCaixa_TotalDoCaixa = 'Total do Caixa';
SncDMCaixa_PósPago = 'Pós-pago';
SncDMCaixa_CréditoDeTempoAvulso = 'Crédito de Tempo Avulso';
SncDMCaixa_PacoteNãoExisteMais = 'Pacote: Não existe mais';
SncDMCaixa_CartãoDeTempo = 'Cartão de Tempo: ';
SncDMCaixa_CartãoDeTempoNãoExisteMais = 'Cartão de Tempo: Não existe mais';
SncDMCaixa_PassaporteNãoExisteMais = 'Passaporte: Não existe mais';
SncDMCaixa_SaldoInicial = 'Saldo Inicial';
SncDMCaixa_DinheiroAdicionado = 'Dinheiro Adicionado';
SncDMCaixa_DinheiroRetirado = 'Dinheiro Retirado';
SncDMCaixa_SaldoFinal = 'Saldo Final';
SncDMCaixa_SaldoInformado = 'Saldo Informado';
SncDMCaixa_QuebraDeCaixa = 'Quebra de Caixa';
SncDMCaixa_DescontoS = 'Descontos concedidos';
SncDMCaixa_CancelamentoS = 'Cancelamentos';
SncDMCaixa_DevolucaoCred = 'Devoluções Creditadas';
SncDMCaixa_DevolucaoDin = 'Devoluções';
SncDMCaixa_Faturamento = 'Vendas realizadas';
SncDMCaixa_Debitado = 'Vendas debitadas';
SncDMCaixa_CredUsado = 'Créditos utilizados';
SncDMCaixa_ValoresRecebidos = 'Valores recebidos';
SncDMCaixa_ValoresDevolvidos = 'Valores devolvidos';
SncDMCaixa_DebPagos = 'Débitos pagos';
SncDMCaixa_TrocoCreditado = 'Troco creditado em conta';
SncDMCaixa_TotalRec = 'Total recebido';
SncDMCaixa_SaldoCaixa = 'Saldo do Caixa';
SncaDMComp_FIMDESESSÃO = 'FIM DE SESSÃO';
SncaDMComp_PgDescAnt = ' Pg/Desc Ant';
SncaDMComp_TempoDeUso = ': Tempo de uso';
SncaDMComp_CredTempo_1 = 'Cred.Tempo: ';
SncaDMComp_CredTempo_2 = 'Cred.Tempo';
SncaDMComp_Impressão_2 = 'Impressão: ';
SncafbFiltroWeb_Ativo = 'Ativo.';
SncafbFiltroWeb_CliqueAquiParaDesativar = 'Clique aqui para Desativar';
SncafbFiltroWeb_Inativo = 'Inativo.';
SncafbFiltroWeb_CliqueAquiParaAtivar = 'Clique aqui para Ativar';
SncafbFiltroWeb_DesejaRealmenteDesbloquearOSite = 'Deseja realmente desbloquear o site ';
SncafbFiltroWeb_FimDeImportação = 'Fim de importação. ';
SncafbFiltroWeb_SitesImportados = ' sites importados';
SncafbFiltroWeb_BloqueioDeSites = 'Bloqueio de Sites';
SncafbListaEspera_DesejaRealmenteEliminarAReservaD = 'Deseja realmente eliminar a reserva de ';
SncafbListaEspera_ListaDeEspera = 'Lista de Espera';
SncaFrmEspera_ERROClienteNãoEncontrado = '** ERRO: Cliente não encontrado';
SncaFrmProcessos_Maq = 'Maq: ';
SuDMEmail_CorpoDaMensagemNãoEncontrado = 'Corpo da mensagem não encontrado';
SncafbTiposAcesso_GruposDeTarifa = 'Grupos de Tarifa';
SncafbTiposAcesso_NãoéPossívelApagarTodosGruposDeT = 'Não é possível apagar todos grupos de tarifas';
SncafbTiposAcesso_DesejaRealmenteApagarOGrupo = 'Deseja realmente apagar o grupo ';
SncaFrmCHorario_Hora = 'hora';
SncaFrmCHorario_ÉNecessárioInformarONomeDoFornec = 'É necessário informar o nome do fornecedor';
SncaFrmLancExtra_ÉNecessárioInformarOValor = 'É necessário informar o valor';
SncaFrmLancExtra_AdicionarDinheiroAoCaixaSuprimen = 'Adicionar dinheiro ao caixa (Suprimento)';
SncaFrmLancExtra_RetirarDinheiroDoCaixaSangria = 'Retirar dinheiro do caixa (Sangria)'
;
SncaFrmMaq_Máquina = 'Máquina ';
SncafbAvisos_AvisosDeTérminoDeTempo = 'Avisos de Término de Tempo';
SncafbAvisos_DesejaRealmenteApagarOAvisoDe = 'Deseja realmente apagar o aviso de ';
SncafbAvisos_Minutos = ' minutos?';
SncaFrmAviso_ÉNecessárioDigitarOTextoQueSeráE = 'É necessário digitar o texto que será exibido ao cliente';
SncaFrmAviso_ÉNecessárioSelecionarUmArquivoDe = 'É necessário selecionar um arquivo de som a ser tocado no momento do aviso';
SncaFrmAviso_ÉNecessárioInformarAQuantidadeDe = 'É necessário informar a quantidade de minutos';
SncaFrmAviso_AlterarArquivoDeSom = 'Alterar arquivo de som';
SncaFrmAviso_SelecionarUmArquivoDeSom = 'Selecionar um arquivo de som';
SncaFrmAviso_OArquivoDeSomAindaNãoFoiSelecion = 'O arquivo de som ainda não foi selecionado';
Sumsg_Mensagem = 'Mensagem';
Sumsg_Erro = 'Erro!';
Sumsg_Atenção = 'Atenção';
Sumsg_ConfirmaExclusãoDe = 'Confirma exclusão de "';
SncFrmCreditos_CréditoDeTempo = 'Crédito de Tempo';
SncFrmCreditos_Nenhuma = 'Nenhuma';
SncFrmCreditos_Passaporte = 'Passaporte';
SncFrmCreditos_TempoVálidoParaUsoNessaSessão = ' Tempo válido para uso nessa sessão';
SncFrmCreditos_TempoComRestriçõesQueImpedemUsoN = ' Tempo com restrições que impedem uso nessa sessão';
SncafbMovEst_HistóricoDeTransações = 'Histórico de transações';
SncafbMovEst_TransaçãoNãoEncontrada = 'Transação não encontrada!';
SncNXServRemoto_ÉNecessárioInformarOEndereçoDoSe = 'É necessário informar o endereço do servidor Nex';
SncErros_TipoDeClasseInválido = 'Tipo de classe inválido';
SncErros_ItemInexistente = 'Item inexistente';
SncErros_ItemSemAlterações = 'Item sem alterações';
SncErros_UsernameOuSenhaInválida = 'Username ou Senha inválida';
SncErros_ErroAcessandoBancoDeDadosDoServi = 'Erro acessando banco de dados do servidor';
SncErros_HandleDeClienteInválido = 'Handle de Cliente Inválido!';
SncErros_ItemRepetido = 'Item Repetido!';
SncErros_OAcessoAnteriorDessaMáquinaAinda = 'O acesso anterior dessa máquina ainda não foi finalizado por completo pelo atendente';
SncErros_JáExisteMáquinaSendoUsadaPorEsse = 'Já existe máquina sendo usada por esse usuário!';
SncErros_NãoHáCréditoDisponível = 'Não há crédito disponível!';
SncErros_NúmeroDeMáquinaInexistente = 'Número de máquina inexistente!';
SncErros_EstaMáquinaJáEstáConectada = 'Esta máquina já está conectada!';
SncErros_TelaNãoDisponível = 'Tela não disponível';
SncErros_NãoExisteAcessoEmAndamentoNessaM = 'Não existe acesso em andamento nessa máquina!';
SncErros_ONexCaféEstáSendoExecutadoEmModo = 'O Nex está sendo executado em modo demonstração';
SncErros_LimiteDeMáquinasLicenciadasFoiAt = 'Limite de máquinas licenciadas foi atingido';
SncErros_NãoHáNovaVersãoDisponívelNoServi = 'Não há nova versão disponível no servidor';
SncErros_ErroDeComunicaçãoTCPIP = 'Erro de comunicação TCP/IP';
SncErros_MáquinaEstáEmManutenção = 'Máquina está em manutenção';
SncErros_MáquinaNãoEstáEmModoManutenção = 'Máquina não está em modo manutenção';
SncErros_VocêNãoPossuiDireitoDeExecutarEs = 'Você não possui direito de executar essa operação';
SncErros_EsseCartãoDeTempoOuPassaporteJáE = 'Esse cartão de tempo ou passaporte já está em uso';
SncErros_ONúmeroDeRGInformadoEstáDiferent = 'O número de RG informado está diferente do cadastrado';
SncErros_ParaUsarSuaContaéNecessárioCadas = 'Para usar sua conta é necessário cadastrar seu RG com o atendente da loja';
SncErros_ÉNecessárioAbrirUmCaixaParaReali = 'É necessário abrir um caixa para realizar essa operação';
SncErros_EssaContaDeClienteEstáInativada = 'Essa conta de cliente está inativada';
SncErros_NãoéPossívelTransferirUmAcessoQu = 'Não é possível transferir um acesso que está aguardando pagamento';
SncErros_LimiteMáximoDeMáquinasEmManutenç = 'Limite máximo de máquinas em manutenção para esse usuário já foi atigindo';
SncErros_ArquivoNãoEncontrado = 'Arquivo não encontrado';
SncErros_OArquivoDeFundoParaáreaDeTrabalh = 'O arquivo de fundo para área de trabalho tem que ser do tipo JPG';
SncErros_OArquivoDeFundoParaATelaDeLoginT = 'O arquivo de fundo para a tela de login tem que ser do tipo JPG ou GIF';
SncErros_ClienteNãoEncontrado = 'Cliente não encontrado';
SncErros_SuaContaNexCaféNãoPermiteOUsoDes = 'Sua conta Nex não permite o uso dessa máquina. Verifique sua conta no servidor NexCafé (NexServ)';
SncErros_NãoéPossívelAlterarUmaTransaçãoQ = 'Não é possível alterar uma transação que ocorreu em outro caixa';
SncErros_NãoéPermitidoCancelarUmFimDeAces = 'Não é permitido cancelar um Fim de Acesso';
SncErros_NãoéPermitidoCancelarAVendaDeUmP = 'Não é permitido cancelar a venda de um passaporte que já foi usado';
SncErros_SemCréditoDisponívelParaCancelar = 'Sem crédito disponível para cancelar a transação';
SncErros_ExisteTransaçãoPosteriorAEssaQue = 'Existe transação posterior a essa que envolve item(s) dessa transação.';
SncErros_NomeDeUsuárioInexistente = 'Nome de Usuário Inexistente';
SncErros_JáExisteUmCaixaAberto = 'Já existe um caixa aberto.';
SncErros_EsteCaixaJáEstáFechado = 'Este caixa já está fechado';
SncErros_ExistemItensAguardandoConfirmaçã = 'Existem itens aguardando confirmação de pagamento';
SncErros_EstaMáquinaEstáReservadaParaOutr = 'Esta máquina está reservada para outro cliente';
SncErros_CréditoDeTempoAtualDoClienteNãoé = 'Crédito de tempo atual do cliente não é suficiente para executar essa operação';
SncErros_OClienteNãoPossuiSaldoSuficiente = 'O cliente não possui saldo suficiente para executar essa operação';
SncErros_SenhaInválida = 'Senha Inválida';
SncErros_OLimiteMáximoDeDébitoPermitidoPa = 'O limite máximo de débito permitido para esse cliente foi ultrapassado.';
SncErros_ClienteNãoAutorizadoAUsarComputa = 'Cliente não autorizado a usar computadores nesse horário';
SncErros_EssaMáquinaEstáEmManutençãoForaD = 'Essa máquina está em manutenção / fora do ar. Não é possível usar';
SncErros_EssaTransaçãoNãoPodeSerAlteradaD = 'Essa transação não pode ser alterada diretamente. ';
SncErros_FaçaAAlteraçãoAtravésDaTelaDeFim = 'Faça a alteração através da tela de Fim de Sessão da qual ela faz parte';
SncErros_LoginNãoPermitidoValorLimiteDeDé = 'Login não permitido: Valor limite de débitos foi atingido';
SncErros_SaldoDeProdutoInsuficiente = 'Saldo de produto insuficiente';
SncErros_OAcessoFoiAlteradoAntesDeVocêSal = 'O acesso foi alterado antes de você salvar essa operação. Realize novamente essa operação';
SncErros_NãoéPossívelRealizarEssaOperação = 'Não é possível realizar essa operação em um acesso que já encerrou';
SncErros_SaldoDePontosDoFidelidadeDoClien = 'Saldo de pontos do fidelidade do cliente é insuficiente para realizar essa operação';
SncErros_FalhaNaTransferênciaDeArquivo = 'Falha na transferência de arquivo';
SncErros_AConexãoDeRedeComOServidorFoiPer = 'A conexão de rede com o servidor foi perdida';
SncErros_FalhaDeConexãoComOServidorNexCaf = 'Falha de conexão com o servidor Nex. Verifique os parâmetros de conexão e se sua rede está funcionando corretamente.';
SncErros_NãoéPossívelLiberarAcessoParaCli = 'Não é possível liberar acesso para cliente avulso. É necessário realizar um cadastro do cliente';
SncErros_OClienteNãoPossuiOsDadosCadastra = 'O cliente não possui os dados cadastrais mínimos para permitir seu acesso';
SncErros_ÉNecessárioSelecionarUmTipoDeImp = 'É necessário selecionar um tipo de impressão ou o tipo informado foi apagado';
SncErros_NãoéPermitidoOAcessoDeClienteSem = 'Não é permitido o acesso de cliente sem cadastro';
SncErros_NãoéPossívelEncerrarOAcessoPoisH = 'Não é possível encerrar o acesso pois há uma impressão aguardando liberação';
SncErros_FalhaDownloadInt = 'Falha no download de arquivo do servidor';
SncErros_TranAlteradaOutroUsuario = 'A transação foi alterada por outro usuário antes de você salvar. Realize novamente a operação';
SncErros_ExceçãoNãoTratadaNoServidor_TdmCaixa_AbreCaixa = 'Exceção não tratada no servidor (TdmCaixa.AbreCaixa)';
SncErros_ExceçãoNãoTratadaNoServidor_TdmCaixa_FechaCaixa = 'Exceção não tratada no servidor (TdmCaixa.FechaCaixa)';
SncErros_ExceçãoNãoTratadaNoServidor_TDM_ExcluiIME = 'Exceção não tratada no servidor (TDM.ExcluiIME)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ObtemStreamListaObj = 'Exceção não tratada no servidor (TncServidor.ObtemStreamListaObj)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_EnviarMsg = 'Exceção não tratada no servidor (TncServidor.EnviarMsg)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_FechaCaixa = 'Exceção não tratada no servidor (TncServidor.FechaCaixa)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_DisableAD = 'Exceção não tratada no servidor (TncServidor.DisableAD)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AlteraSessao = 'Exceção não tratada no servidor (TncServidor.AlteraSessao)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_DesativarFWSessao = 'Exceção não tratada no servidor (TncServidor.DesativarFWSessao)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_DesktopSincronizado = 'Exceção não tratada no servidor (TncServidor.DesktopSincronizado)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaUsuarioBD = 'Exceção não tratada no servidor (TncServidor.AtualizaUsuarioBD)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaConfigBD = 'Exceção não tratada no servidor (TncServidor.AtualizaConfigBD)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaTarifaBD = 'Exceção não tratada no servidor (TncServidor.AtualizaTarifaBD)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaTipoAcessoBD = 'Exceção não tratada no servidor (TncServidor.AtualizaTipoAcessoBD)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaTipoImpBD = 'Exceção não tratada no servidor (TncServidor.AtualizaTipoImpBD)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaCredTempo = 'Exceção não tratada no servidor (TncServidor.SalvaCredTempo)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaDebito = 'Exceção não tratada no servidor (TncServidor.SalvaDebito)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaDebTempo = 'Exceção não tratada no servidor (TncServidor.SalvaDebTempo)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaImpressao = 'Exceção não tratada no servidor (TncServidor.SalvaImpressao)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaClientPages = 'Exceção não tratada no servidor (TncServidor.SalvaClientPages)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaLancExtra = 'Exceção não tratada no servidor (TncServidor.SalvaLancExtra)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaLogAppUrl = 'Exceção não tratada no servidor (TncServidor.SalvaLogAppUrl)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaMovEst = 'Exceção não tratada no servidor (TncServidor.SalvaMovEst)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaProcessos = 'Exceção não tratada no servidor (TncServidor.SalvaProcessos)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaSenhaCli = 'Exceção não tratada no servidor (TncServidor.SalvaSenhaCli)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaSessaoBD = 'Exceção não tratada no servidor (TncServidor.AtualizaSessaoBD)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtualizaMaquinaBD = 'Exceção não tratada no servidor (TncServidor.AtualizaMaquinaBD)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ApagaMsgCli = 'Exceção não tratada no servidor (TncServidor.ApagaMsgCli)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ApagaObj = 'Exceção não tratada no servidor (TncServidor.ApagaObj)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_LimpaFundo = 'Exceção não tratada no servidor (TncServidor.LimpaFundo)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ArqFundoEnviado = 'Exceção não tratada no servidor (TncServidor.ArqFundoEnviado)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ObtemSitesBloqueados = 'Exceção não tratada no servidor (TncServidor.ObtemSitesBloqueados)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ObtemStreamAvisos = 'Exceção não tratada no servidor (TncServidor.ObtemStreamAvisos)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ObtemStreamConfig = 'Exceção não tratada no servidor (TncServidor.ObtemStreamConfig)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SalvaStreamObj = 'Exceção não tratada no servidor (TncServidor.SalvaStreamObj)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ShutdownMaq = 'Exceção não tratada no servidor (TncServidor.ShutdownMaq)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_SuporteRem = 'Exceção não tratada no servidor (TncServidor.SuporteRem)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_RefreshEspera = 'Exceção não tratada no servidor (TncServidor.RefreshEspera)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_RefreshPrecos = 'Exceção não tratada no servidor (TncServidor.RefreshPrecos)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ModoManutencao = 'Exceção não tratada no servidor (TncServidor.ModoManutencao)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_PermitirDownload = 'Exceção não tratada no servidor (TncServidor.PermitirDownload)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_CorrigeDataCaixa = 'Exceção não tratada no servidor (TncServidor.CorrigeDataCaixa)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_Login = 'Exceção não tratada no servidor (TncServidor.Login)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_TransferirMaq = 'Exceção não tratada no servidor (TncServidor.TransferirMaq)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_PararTempoMaq = 'Exceção não tratada no servidor (TncServidor.PararTempoMaq)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AbreCaixa = 'Exceção não tratada no servidor (TncServidor.AbreCaixa)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AdicionaPassaporte = 'Exceção não tratada no servidor (TncServidor.AdicionaPassaporte)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AjustaPontosFid = 'Exceção não tratada no servidor (TncServidor.AjustaPontosFid)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_LoginMaq = 'Exceção não tratada no servidor (TncServidor.LoginMaq)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_PreLogoutMaq = 'Exceção não tratada no servidor (TncServidor.PreLogoutMaq)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_CancelaTran = 'Exceção não tratada no servidor (TncServidor.CancelaTran)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_CancLogoutMaq = 'Exceção não tratada no servidor (TncServidor.CancLogoutMaq)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_LogoutMaq = 'Exceção não tratada no servidor (TncServidor.LogoutMaq)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_AtuaizaEspecieBD = 'Exceção não tratada no servidor (TncServidor.AtualizaEspecieBD)';
SncErros_ExceçãoNãoTratadaNoServidor_TncServidor_ZerarEstoque = 'Exceção não tratada no servidor (TncServidor.ZerarEstoque)';
SncErros_ExcecaoNaoTratada_GetCertificados = 'Exceção não tratada on servidor ao obter lista de certificados';
SncErros_ExcecaoNaoTratada_ReemitirNFCe = 'Exceção nao tratada no servidor ao reemitir NFC-e';
SncErros_ExcecaoNaoTratada_GeraXMLProt = 'Exceção não tratada no servidor ao gerar novamente XML da NFC-e de envio ao destinatário';
SncErros_ExcecaoNaoTratada_ConsultarSAT = 'Exceção não tratada no servidor ao ConsultarSAT';
SncErros_ExcecaoNaoTratada_InutilizarNFCE = 'Exceção não tratada no servidor ao InutilizarNFCE';
SrdDesktopView_Desktop = ' - Desktop ';
SrdDesktopView_LendoTelaInicialAguarde = 'Lendo tela inicial. Aguarde ...';
SrdDesktopView_SessãoFinalizadaPelaMáquinaClien = ' - Sessão finalizada pela máquina cliente';
SrdDesktopView_SessãoFinalizadaPelaMáquinaClien_1 = 'Sessão finalizada pela máquina cliente.';
SrdDesktopView_Desconectado = ' - Desconectado';
SrdDesktopView_FimDeSessão = 'Fim de sessão.';
SrdDesktopView_Máquina = 'Máquina ';
SrdDesktopView_SairDaTelaCheia = 'Sair da tela cheia';
SrdDesktopView_IrParaTelaCheia = 'Ir para Tela Cheia';
SrdDesktopView_ExibirFundoDeTela = 'Exibir fundo de tela';
SrdDesktopView_RemoverFundoDeTela = 'Remover fundo de tela';
SncafbImp_Impressões = 'Impressões';
SncafbMaq_Tarifas = 'Tarifas';
SncaFrmLiga_Máquina = 'Máquina ';
SncaFrmOperMaq_Máquina = 'Máquina ';
SncaFrmMsgChat_ChatComMáquina = 'Chat com máquina ';
SncafbMaqConfig_Opções = 'Opções';
SncafbMaqConfig_Remover = '&Remover';
SncafbMaqConfig_RecursoDesativadoÉNecessárioComp = '* Recurso desativado. É necessário comprar uma atualização do NexCafé para ativar esse recurso';
SncafbMaqConfig_AsInformaçõesDeConfiguraçãoDosCo = 'As informações de configuração dos computadores da loja são coletadas automaticamente pelo NexCafé. ';
SncafbMaqConfig_AsMáquinasClientesEnviamOsDadosD = 'As máquinas clientes enviam os dados de sua configuração no momento em que se conectam ao servidor ';
SncafbMaqConfig_NexCaféAtravésDoNexGuard = 'NexCafé através do NexGuard.';
SncafbMaqConfig_NãoéPossívelApagarUmaMáquinaComA = 'Não é possível apagar uma máquina com acesso em andamento';
SncafbMaqConfig_ConfirmaAExclusãoDaMáquina = 'Confirma a exclusão da Máquina ';
SncafbMaqConfig_InfoMáquinas = 'Info.Máquinas';
SncafbTarifas_Tarifas = 'Tarifas';
SncafbEst_VerDados = 'Ver Dados';
SncafbEst_VerGráfico = 'Ver Gráfico';
SncafbEst_EstatísticasERelatórios = 'Estatísticas e Relatórios';
SncafbEst_1PorMáquina = '1 - por Máquina';
SncafbEst_SaibaQuaisSãoAsMáquinasMaisEMeno = 'Saiba quais são as máquinas mais e menos utilizadas';
SncafbEst_2PorHorário = '2 - por Horário';
SncafbEst_SaibaQuaisSãoOsHoráriosDePicoEOs = 'Saiba quais são os horários de pico e os momentos que a loja fica mais vazia';
SncafbEst_3PorFuncionário = '3 - por Funcionário';
SncafbEst_SaibaAQuantidadeDeVezesEOTempoTo = 'Saiba a quantidade de vezes e o tempo total que os funcionários utilizaram as máquinas clientes';
SncafbEst_4PorCliente = '4 - por Cliente';
SncafbEst_RankingDeClientesPorValorGastoNa = 'Ranking de clientes por valor gasto na loja';
SncafbEst_5PorClienteGrátis = '5 - por Cliente Grátis';
SncafbEst_SaibaAQuantidadeDeVezesEOTempoTo_1 = 'Saiba a quantidade de vezes e o tempo total de uso por clientes gratuítos';
SncafbEst_6PorDuraçãoDoAcesso = '6 - por Duração do Acesso';
SncafbEst_FaçaUmaAnáliseDoTempoMédioDasSes = 'Faça uma análise do tempo médio das sessões';
SncafbEst_7PorCategoriaProdutoFuncionário = '7 - por Categoria/Produto/Funcionário';
SncafbEst_SaibaComoForamAsVendas = 'Saiba como foram as vendas';
SncafbEst_1Clientes = '1 - Clientes';
SncafbEst_2ProdutosVendas = '2 - Produtos / Vendas';
SncafbEst_TotalDeVendasPorCategoriaProduto = 'Total de vendas por Categoria/Produto/Funcionário';
SncafbEst_Outros = 'Outros';
SncafbEst_CLIENTESSEMCADASTROAVULSO = '* CLIENTES SEM CADASTRO (AVULSO)';
SncafbTotCaixa_TotalDeCaixa = 'Total de Caixa';
SncafbTotCaixa_1Centavo = '1 centavo';
SncafbTotCaixa_5Centavos = '5 centavos';
SncafbTotCaixa_10Centavos = '10 centavos';
SncafbTotCaixa_25Centavos = '25 centavos';
SncafbTotCaixa_50Centavos = '50 centavos';
SncafbTotCaixa_1Moeda = '1 (moeda)';
SncafbTotCaixa_1Cédula = '1 (cédula)';
SncafbTotCaixa_10 = '10';
SncafbTotCaixa_20 = '20';
SncafbTotCaixa_50 = '50';
SncafbTotCaixa_100 = '100';
SncafbTotCaixa_SaldoInicial = 'Saldo inicial';
SncafbTotCaixa_ValoresRecebidos = 'Valores Recebidos';
SncafbTotCaixa_Acessos = ' Acessos';
SncafbTotCaixa_Impressões = ' Impressões';
SncafbTotCaixa_Vendas = ' Vendas';
SncafbTotCaixa_DébitosPagos = ' Débitos Pagos';
SncafbTotCaixa_Suprimentos = 'Suprimentos';
SncafbTotCaixa_Sangrias = 'Sangrias';
SncafbTotCaixa_Total = 'Total';
SncafbTotCaixa_Debitado = 'Debitado';
SncafbTotCaixa_Descontos = 'Descontos';
SncafbTotCaixa_Cancelamentos = 'Cancelamentos';
SncaFrmTarifa_AplicarATarifaDa = 'Aplicar a tarifa da ';
SncaFrmTarifa_AHoraNasDemaisHoras = 'a. hora nas demais horas';
SncaFrmTarifa_RepetirTarifasAPartirDa = 'Repetir tarifas a partir da ';
SncaFrmTarifa_AHora = 'a. hora';
SncaFrmTarifa_ÉNecessárioInformarAQuantidadeDe = 'É necessário informar a quantidade de minutos que o cliente pode utilizar pagando o valor inicial';
SncaFrmTarifa_OValorInicialNãoPodeSerMaiorQueO = 'O valor inicial não pode ser maior que o valor cobrado por 1 hora de uso';
SncaFrmTarifa_AtençãoOValorASerCobradoPor = 'Atenção: o valor a ser cobrado por ';
SncaFrmTarifa_NãoPodeSerMenorQueOValorPara = ' não pode ser menor que o valor para ';
SncaFrmTarifa_AtençãoAQuantidadeDeMinutosDeveS = 'Atenção: a quantidade de minutos deve ser sempre crescente';
SncaFrmTarifa_ÉNecessárioInformarUmNomeParaIde = 'É necessário informar um nome para identificar essa tarifa';
SncaFrmTarifa_ÉNecessárioSelecionarUmaCorParaI = 'É necessário selecionar uma cor para identificar essa tarifa';
SncaFrmTarifa_JáFoiCadastradoUmaTarifaComEssaC = 'Já foi cadastrado uma tarifa com essa cor';
SncaFrmTarifa_Centavos = ' centavos';
SncaFrmTarifa_MinutoS = ' minuto(s)';
SncaFrmTarifa_Horas = 'horas';
SncaFrmTarifa_Hora = 'hora';
SncaFrmTarifa_Minuto = ' minuto';
SncaFrmTarifa_R001 = 'R$ 0,01';
SncaFrmTarifa_AQuantidadeDeMinutosTemQueEstarE = 'A quantidade de minutos tem que estar entre 1 e 59m';
SncaFrmTarifa_RemoverTarifa = 'Remover Tarifa';
SncaFrmTarifa_CliqueNaLixeiraParaRemoverEssaTa = 'Clique na lixeira para remover essa tarifa/tempo';
SncaFrmTarifa_OTempoInicialTemQueSerInformado = 'O tempo inicial tem que ser informado';
SncafbTarifas2_ConfirmaADesativaçãoDoGrupoDeTar = 'Confirma a Desativação do Grupo de Tarifas ?';
SncafbTarifas2_ConfirmaADesativaçãoDeTarifasPor = 'Confirma a Desativação de Tarifas por Dia e Horário?';
SncafbTarifas2_Tarifas = 'Tarifas';
SncafbPass_SemUso = 'Sem Uso';
SncafbPass_DesejaRealmenteCancelarEsseCrédi = 'Deseja realmente cancelar esse crédito ?';
SncafbPass_CréditosPromocionais = 'Créditos Promocionais';
SncafbDiaHora_TarifaPorDiaEHorário = 'Tarifa por Dia e Horário';
SncaFrmHorario_ÉNecessárioSelecionarUmaTarifa = 'É necessário selecionar uma tarifa';
SncaFrmTempoIniciar_EsseCartãoJáFoiVendidoParaOutroC = 'Esse cartão já foi vendido para outro cliente';
SncaFrmTempoIniciar_NãoExisteCartãoComASenhaInformad = 'Não existe cartão com a senha informada';
SncaFrmTempoIniciar_InformaASenhaDoCartãoASerVendido = 'Informa a senha do cartão a ser vendido';
SncaFrmTempoIniciar_Maq = 'Maq: ';
SncaFrmIniciarSessao_IniciarAcesso = 'Iniciar Acesso';
SncaFrmIniciarSessao_Máq = 'Máq.';
SncaFrmIniciarSessao_IniciarSessão = 'Iniciar Sessão';
SncaFrmIniciarSessao_Iniciar = '&Iniciar';
SncaFrmIniciarSessao_ÉNecessárioSelecionarUmClienteCa = 'É necessário selecionar um cliente cadastrado ou optar por cliente avulso';
SncaFrmSessao_Impressão = 'Impressão ';
SncaFrmSessao_PáginaS = ' Página(s)';
SncaFrmSessao_DesejaRealmenteCancelarATransaçã = 'Deseja realmente cancelar a transação selecionada?';
SncaFrmSessao_DescontoNãoPodeSerMaiorQueOTotal = 'Desconto não pode ser maior que o total';
SncaFrmSessao_ÉNecessárioQueTenhaUmCadastroPar = 'É necessário que tenha um cadastro para poder deixar débito';
SncaFrmSessao_OLimiteMáximoDeDébitoPermitidoPa = 'O limite máximo de débito permitido para esse cliente foi ultrapassado';
SncaFrmSessao_EditarSessão = 'Editar Sessão';
SncaFrmSessao_Máq = 'Máq. ';
SncaFrmSessao_Maq = 'Maq. ';
SncaFrmSessao_Duração = 'Duração: ';
SncaFrmSessao_TempoPrevisto = 'Tempo previsto = ';
SncaFrmSessao_Tempo = 'Tempo = ';
SncaFrmSessao_ÉNecessárioSelecionarUmClienteCa = 'É necessário selecionar um cliente cadastrado ou optar por cliente avulso';
SncaFrmTempo_EsseCartãoJáFoiVendidoParaOutroC = 'Esse cartão já foi vendido para outro cliente';
SncaFrmTempo_NãoExisteCartãoComASenhaInformad = 'Não existe cartão com a senha informada';
SncaFrmTempo_InformaASenhaDoCartãoASerVendido = 'Informa a senha do cartão a ser vendido';
SncaFrmTempo_ÉNecessárioSelecionarUmCliente = 'É necessário selecionar um cliente';
SncaFrmTempo_NenhumPrêmioFoiSelecionadoParaRe = 'Nenhum prêmio foi selecionado para resgate';
SncaFrmTempo_ClienteNãoTemPontosSuficientes = 'Cliente não tem pontos suficientes';
SncaFrmTempo_ParaFicarEmDébitoéNecessárioSele = 'Para ficar em débito é necessário selecionar um cliente';
SncaFrmTempo_OLimiteMáximoDeDébitoPermitidoPa = 'O limite máximo de débito permitido para esse cliente foi ultrapassado';
SncaFrmTempo_ResgateDePrêmioFidelidade = 'Resgate de prêmio fidelidade';
SncaFrmTempo_Maq = 'Maq: ';
SncaFrmAbrirCx_DesejaRealmenteAbrirOCaixa = 'Deseja realmente abrir o caixa?';
SncaFrmFechar_SeuCaixaNãoEstáBatendoEstáSobran = 'Seu caixa não está batendo. Está sobrando ';
SncaFrmFechar_DesejaRealmenteFecharComEssaDife = '. Deseja realmente fechar com essa diferença?';
SncaFrmFechar_SeuCaixaNãoEstáBatendoEstáFaltan = 'Seu caixa não está batendo. Está faltando ';
SncaFrmFechar_DesejaRealmenteFecharOCaixa = 'Deseja realmente fechar o caixa?';
SncaFrmFechar_QuebraDeCaixaEstáSobrando = 'Quebra de caixa. Está sobrando:';
SncaFrmFechar_QuebraDeCaixaEstáFaltando = 'Quebra de caixa. Está faltando:';
SncaFrmCliPesq_CaixaEstáFechado = 'Caixa está fechado';
SncaFrmCliPesq_ConfirmaAExclusãoDe = 'Confirma a exclusão de ';
SncaFrmCliPesq_Clientes = 'Clientes';
SncaFrmProdPesq_Produtos = 'Produtos';
SncaFrmTipoAcesso_ÉNecessárioInformarONomeDoGrupo = 'É necessário informar o nome do grupo';
SncaFrmTipoAcesso_ÉNecessárioSelecionarUmaTarifa = 'É necessário selecionar uma tarifa';
SncaFrmAss_SuaAssinaturaNexCaféPremiumVence = 'Sua assinatura NexCafé Premium venceu.';
SncaFrmAss_ComprarAssinaturaPremium = 'Comprar Assinatura Premium';
SncafbPrevSessao_PrevisãoDeTérmino = 'Previsão de Término';
SncafbPrevSessao_FimDeTempo = 'Fim de Tempo';
SncafbPrevSessao_Terminou = 'Terminou';
SncaPlusAPI_ErroCriandoIDSessao = 'Erro criando IDSessao';
SncaPlusAPI_SCRIPTERROR = 'SCRIPT ERROR: ';
SncaPlusAPI_JáFoiCriadoUmaTransação = 'Já foi criado uma transação';
SncaPlusAPI_ÉNecessárioAbrirOCaixaParaRealiz = 'É necessário abrir o caixa para realizar essa operação';
SncaPlusAPI_ASessãoAindaNãoFoiValidada = 'A sessão ainda não foi validada';
SncaPlusAPI_CancelarAdesão = 'Cancelar Adesão';
SncaPlusAPI_Exp = 'Exp: ';
SncaPlusAPI_ValorInválido = 'Valor inválido ';
SncaPlusAPI_FalhaNaValidaçãoDeSessãoParceiro = 'Falha na validação de sessão parceiro ';
SncaPlusAPI_AChaveDeValidação = '. A chave de validação ';
SncaPlusAPI_NãoéVálidaParaASessao = ' não é válida para a sessao ';
SncafbCXLetra_DesejaRealmenteContinuarSeHouver = 'Deseja realmente continuar? Se houver campos que deixaram de ter a ';
SncafbCXLetra_OpçãoLivreDeDigitaçãoNãoHaveráCo = 'opção livre de digitação, não haverá como recuperar o formato';
SncafbCXLetra_OriginalDosDadosNoFuturo = ' original dos dados no futuro.';
SncafbCXLetra_UpdateClienteSet = 'Update Cliente set ';
SncafbCXLetra_DadosPadronizadosComSucesso = 'Dados padronizados com sucesso!';
SncafbCXLetra_ConfiguraçãoMaiúsculaMinúscula = 'Configuração Maiúscula / Minúscula';
SncafbPesqFor_Fornecedores = 'Fornecedores';
SncaFrmSenha_CriarUmaSenhaPara = 'Criar uma senha para ';
SncaFrmSenha_CriarSenha = 'Criar Senha';
SncaFrmSenha_DigiteSuaSenhaAtual = 'Digite sua senha atual';
SncaFrmSenha_DigiteUmaSenha = 'Digite uma senha';
SncaFrmSenha_DigiteASenhaNovamenteParaConfirm = 'Digite a senha novamente para confirmá-la';
SncaFrmSenha_AlterarASenhaDe = 'Alterar a senha de ';
SncaFrmSenha_VocêDigitouSuaSenhaATUALIncorret = 'Você digitou sua senha ATUAL incorretamente. Certifique-se que está digitando 100% igual a senha original, ';
SncaFrmSenha_RespeitandoLetrasMaiúsculasEMinú = 'respeitando letras maiúsculas e minúsculas e também espaços.';
SncaFrmSenha_ANOVASenhaDoCampo2E3TemQueSerExa = 'A NOVA senha do campo 2 e 3 tem que ser exatamente iguais. Favor re-digitar corretamente';
SncaFrmQtdMaq_VocêNãoInformouAQuantidadeDeMáqu = 'Você não informou a quantidade de máquinas.';
SncaPlusParceiro_OCódigoDeParceiro = 'O código de parceiro ';
SncaPlusParceiro_NãoéVálido = 'não é válido';
SncaDMPlus_Transação = 'Transação ';
SncaDMPlus_NãoEncontradaNoBancoDeDados = ' não encontrada no banco de dados.';
SncaFrmVendaPlus_Maq = 'Maq.';
SncaFrmVendaPlus_DdMmYyyyHhMmSs = 'dd/mm/yyyy hh:mm:ss';
SncaFrmVendaPlus_ParaFicarEmDébitoéNecessárioSele = 'Para ficar em débito é necessário selecionar um cliente';
SncaFrmVendaPlus_OLimiteMáximoDeDébitoPermitidoPa = 'O limite máximo de débito permitido para esse cliente foi ultrapassado';
SncaFrmVendaPlus_ÉNecessárioSelecionarUmCliente = 'É necessário selecionar um cliente';
SncaFrmVendaPlus_VendaWeb = 'Venda Web ';
SncaFrmVendaPlus_NãoEncontrada = 'não encontrada.';
SncaFrmFornecedor_ÉNecessárioInformarONomeDoFornec = 'É necessário informar o nome do fornecedor';
SncaFrmCli_HhMmSs = 'hh:mm:ss';
SncaFrmCli_Cliente = 'Cliente ';
SncaFrmCli_NãoEncontradoNoBancoDeDados = ' não encontrado no banco de dados!';
SncaFrmCli_Fornecedor = 'Fornecedor:';
SncaFrmCli_Fornecedor_1 = 'Fornecedor';
SncaFrmCli_Nome = 'Nome:';
SncaFrmCli_ClienteCOMCadastro = 'Cliente COM cadastro';
SncaFrmCli_ClienteSEMCadastro = 'Cliente SEM cadastro';
SncaFrmCli_Débito = 'Débito ';
SncaFrmCli_Username = 'Username:';
SncaFrmCli_Código = 'Código:';
SncafbPesqCli_CaixaEstáFechado = 'Caixa está fechado';
SncafbPesqCli_Clientes = 'Clientes';
SncaFrmTotal_Debitar = 'Debitar';
SncaFrmTotal_DescontoNãoPodeSerMaiorQueSubTot = 'Desconto não pode ser maior que sub-total';
SncaFrmTotal_PagarNoFinalDoAcesso = 'Pagar no final do acesso';
SncaFrmTotal_Troco = ' Troco ';
SncFrmCriarConta_Avançar = '&Avançar >>';
SncFrmCriarConta_RegistrarMinhaLoja = 'Registrar Minha Loja!';
SncFrmCriarConta_TransferirRegistro = 'Transferir Registro!';
SncFrmCriarConta_FalhaDeConexãoComOServidorDeRegi = 'Falha de conexão com o servidor de registros Nextar';
SncFrmCriarConta_JáFoiRealizadoUmRegistroNexCaféC = 'Já foi realizado um registro NexCafé com e-mail informado.';
SncFrmCriarConta_ErroNoProcessamentoDoSeuRegistro = 'Erro no processamento do seu registro (';
SncFrmCriarConta_PorFavorFaçoContatoComAEquipeDeA = '). Por favor faço contato com a equipe de atendimento Nextar.';
SncFrmCriarConta_ParaUsarONEXéNecessárioRegistrar = 'Para usar o NEX é necessário registrar sua loja.';
SncFrmCriarConta_SeuNEXEstáRegistradoParaUsoEmOut = 'Seu NEX está registrado para uso em outro computador';
SncFrmCriarConta_EnviamosSuaSenhaPara = 'Enviamos sua senha para ';
SncFrmCriarConta_ConfirmarRegistro = 'Confirmar registro';
SncFrmCriarConta_RegistroNexCafé = 'Registro NexCafé';
SncFrmCriarConta_TransferirRegistro_1 = 'Transferir registro';
SncFrmCriarConta_SeuRegistroFoiRecuperadoComSuces = 'Seu registro foi recuperado com sucesso!';
SncFrmCriarConta_RegistroTransferidoComSucesso = 'Registro transferido com sucesso!';
SncFrmCriarConta_PorFavorInformeCorretamenteSeuEM = 'Por favor, informe corretamente seu e-mail';
SncFrmCriarConta_PorFavorInformeUmaSenha = 'Por favor, informe uma senha';
SncFrmCriarConta_VocêInformouSenhasDiferentesPorF = 'Você informou senhas diferentes. Por favor informe novamente sua senha';
SncFrmCriarConta_PorFavorInformeONomeDaLoja = 'Por favor informe o nome da loja';
SncFrmCriarConta_PorFavorInformeONomeDoProprietár = 'Por favor informe o nome do proprietário da loja';
SncaFrmPanTopo_SeuNEXEstáRegistradoParaOutroCom = 'Seu NEX! está registrado para outro computador';
SncaFrmPanTopo_SeuRegistroDoNEXFoiBloqueadoFaça = 'Seu registro do NEX! foi bloqueado. Faça contato com a Nextar.';
SncaFrmPanTopo_SuaContaNexCaféEstáBloqueadoFaça = 'Sua conta NexCafé está bloqueado. Faça contato com a Nextar';
SuLicEXECryptor_ArquivoDeLicenças = 'Arquivo de licenças "';
SuLicEXECryptor_NãoExiste = '" não existe';
SncaFrmObrigado_SeuRegistroFoiConfirmadoComSuces = 'Seu registro foi confirmado com sucesso!';
SncaFrmCorrigeEmail_PorFavorInformeCorretamenteSeuEM = 'Por favor, informe corretamente seu e-mail';
SncaFrmCorrigeEmail_SeuEMailFoiCorrigidoComSucesso = 'Seu e-mail foi corrigido com sucesso!';
SncFrmPrintReview_ConfirmaImpressão = 'Confirma Impressão';
SncFrmPrintReview_LiberarImpressão = 'Liberar Impressão';
SncFrmPrintReview_ReviseSuaImpressão = 'Revise sua impressão';
SncFrmPrintReview_Folhas = ' folhas';
SncFrmPrintReview_Folha = ' folha';
SncFrmPrintReview_TipoDeImpressão = 'Tipo de Impressão';
SncFrmPrintReview_Folha_1 = 'Folha ';
SncFrmPrintReview_De = ' de ';
SncFrmPrintReview_NãoImprimirAFolha = 'Não imprimir a folha ';
SncFrmPrintReview_ZerandoTrabalho = 'zerando trabalho';
SncaFrmPTProgress_Baixando = 'Baixando ';
SncPRBaseClasses_Carregando = ' - Carregando';
SncPRFrmPrintTipo_PorPágina = ' por página';
SncPRFrmPrintTipo_Selecionar = 'Selecionar';
SncPRFrmPrintTipo_Sair = 'Sair';
SncPRFrmPrintTipo_PáginaS = ' página(s) = ';
SncPRFrmEtapas_DesejaRealmenteCANCELAREssaImpre = 'Deseja realmente CANCELAR essa impressão?';
SncPRFrmEtapas_Atenção = 'Atenção';
SncPRFrmEtapas_PorPágina = ' por página';
SncPRFrmEtapas_PáginaS = ' página(s) = ';
SncPRFrmEtapas_ImprimirDiretoSemRevisar = 'Imprimir direto sem revisar.';
SncPRFrmEtapas_Imprimir = 'Imprimir - ';
SncPRFrmEtapas_Custo = ' Custo = ';
SncPRFrmEtapas_Folhas = ' Folhas';
SncPRFrmEtapas_Folha = ' Folha';
SncVersoes_ListaDeEspera = 'Lista de Espera';
SncVersoes_BloqueioDeSites = 'Bloqueio de Sites';
SncVersoes_EnvioAutomáticoDeRelatórioDeCaix = 'Envio automático de relatório de caixa por E-mail';
SncVersoes_ChatEntreAtendentesEClientes = 'Chat entre atendentes e clientes';
SncVersoes_ListaDeProcessosVerFecharProgram = 'Lista de processos: Ver / Fechar programas das máquinas clientes, através do servidor';
SncVersoes_TarifasEspecíficasPorMáquina = 'Tarifas específicas por máquina';
SncVersoes_LigarMáquinasClientes = 'Ligar máquinas clientes';
SncVersoes_Fidelidade = 'Fidelidade';
SncVersoes_ControleRemoto = 'Controle Remoto';
SncVersoes_PausaImpressão = 'Pausa Impressão';
SncVersoes_ConfiguraçãoDasMáquinasClientes = 'Configuração das máquinas clientes';
SncVersoes_RevisãoDeImpressão = 'Revisão de Impressão';
SncafbCHATHist_HistóricoDeChat = 'Histórico de Chat';
SncafbCHATHist_Atendente = 'Atendente';
SncafbCHATHist_Todos = 'Todos';
SncafbPrintMon_Impressões = 'Impressões';
SncaFrmCadFornecedor_NomeNãoPodeSerDeixadoEmBranco = 'Nome não pode ser deixado em branco !';
SncaFrmCadFornecedor_Hora = 'hora';
SncaFrmConfigEmailCaixa_VocêEsqueceuDeInformarUmEMailPar = 'Você esqueceu de informar um e-mail para onde deve ser enviado o relatório de caixa :-)';
SncaFrmConfigRec_OutraSerial = 'OUTRA (não listada)';
implementation
end.
|
const
MaxFila = 5; { cantidad de filasdel cuadro }
MaxColumna = 20; { cantidad de columnas del cuadro }
MaxPalabra = 21; { largo maximo de palabra }
MaxConjuntoPalabras = 6; { cantidad de palabras }
type
{Cuadro}
TLetra = 'a'..'z';
RangoFila = 1 .. MaxFila;
RangoColumna = 1 .. MaxColumna;
TCuadro = array [RangoFila , RangoColumna] of TLetra;
{Posicion}
TPosicion = record
fila : RangoFila;
columna : RangoColumna;
end;
{Palabra}
RangoPalabra = 1 .. MaxPalabra;
RangoTopePalabra = 0 .. MaxPalabra;
TPalabra = record
letras : array [RangoPalabra] of TLetra;
largo : RangoTopePalabra;
end;
{Conjunto de palabras}
RangoPalabras = 1 .. MaxConjuntoPalabras;
ConjuntoPalabras = array [RangoPalabras] of TPalabra;
{Lista de posiciones}
ListaPosiciones = ^ celda;
celda = record
posicion : TPosicion;
siguiente : ListaPosiciones
end;
{Ocurrencia de palabras}
OcurrenciasPalabras = array [RangoPalabras] of ListaPosiciones;
{Datos de sopa}
DatosSopa = record
comun : boolean;
case HayPalabras : boolean of
true : (
MasLarga : TPalabra;
MasVeces : TPalabra;
Ultima : TPalabra;
);
false : ();
end;
|
{
GMCircle unit
ES: contiene las clases bases necesarias para mostrar círculos en un mapa de
Google Maps mediante el componente TGMMap
EN: includes the base classes needed to show circles on Google Map map using
the component TGMMap
=========================================================================
MODO DE USO/HOW TO USE
ES: poner el componente en el formulario, linkarlo a un TGMMap y poner los
círculos a mostrar
EN: put the component into a form, link to a TGMMap and put the circled to
show
=========================================================================
History:
ver 1.5.1
ES:
error: TCustomCircle -> error corregido en el método SetRadius (thanks Thierry)
EN:
bug: TCustomCircle -> bug fixed at SetRadius method (thanks Thierry)
ver 1.4.1
ES:
error: TCustomCircle -> corregido error en método SetRadius (gracias Fred).
error: TCustomSizeable -> corregido error en método OnTimer (gracias Fred).
EN:
bug: TCustomCircle -> bug fixed on method SetRadius (thanks Fred).
bug: TCustomSizeable -> bug fixed on method OnTimer (thanks Fred).
ver 1.2.0
ES:
cambio: TCustomCircle -> la propiedad Radius pasa a ser un Real.
error: TCustomCircle -> el radio del círculo se hacía enorme con el cambio
de alguna propiedad (issue GC19).
EN:
change: TCustomCircle -> Radius property becomes a Real.
bug fixed: TCustomCircle -> the radius of the circle become very large with
changing some property (issue GC19).
ver 1.0.0
ES:
cambio: TCustomCircle -> el método GetBounds pasa ha ser un procedure.
EN:
change: TCustomCircle -> GetBounds method becomes a procedure.
ver 0.1.9
ES:
nuevo: documentación
nuevo: se hace compatible con FireMonkey
EN:
new: documentation
new: now compatible with FireMonkey
ver 0.1.7
ES:
cambio: modificados métodos Set y ShowElement para que usen el nuevo método
ChangeProperties heredado de TLinkedComponent
EN:
change: modified all Set and ShowElements methods to use the new method
ChangeProperties inherited from TLinkedComponent
ver 0.1.6
ES:
nuevo: TCustomSizeable -> añadido método Assign
error: TCustomSizeable -> cuando no era circular, el radio crecía más que el máximo
EN:
new: TCustomSizeable -> added Assign method
bug: TCustomSizeable -> when no circular, radius was growing more than the maximum
ver 0.1.5
ES:
cambio: la propiedad Radius pasa a ser un entero
nuevo: añadida propiedad AutoResize
EN:
change: Radius property becomes an integer
new: added AutoResize property
ver 0.1.4
ES: primera versión
EN: first version
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2012, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
The GMCircle unit includes the base classes needed to show circles on Google Map map using the component TGMMap.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La unit GMCircle contiene las clases bases necesarias para mostrar círculos en un mapa de Google Maps mediante el componente TGMMap.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
unit GMCircle;
{$I ..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
GMLinkedComponents, GMClasses, GMConstants;
type
TCustomCircle = class;
{*------------------------------------------------------------------------------
Base class for automatic enlarged circle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para el agrandado automático del círculo.
-------------------------------------------------------------------------------}
TCustomSizeable = class(TPersistent)
private
{*------------------------------------------------------------------------------
Maximum radius to which will enlarge.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Radio máximo hasta el que se agrandará.
-------------------------------------------------------------------------------}
FMax: Integer;
{*------------------------------------------------------------------------------
Radius increment for every interval of time.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Incremento del radio por cada intervalo de tiempo.
-------------------------------------------------------------------------------}
FIncrement: Integer;
{*------------------------------------------------------------------------------
Circle's initial radius.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Radio inicial del círculo.
-------------------------------------------------------------------------------}
FMin: Integer;
{*------------------------------------------------------------------------------
If true, when reach the maximum it returns minimum to increase again.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece a true, al llegar al máximo volverá mínimo nuevamente para volver a incrementarse.
-------------------------------------------------------------------------------}
FCircular: Boolean;
{*------------------------------------------------------------------------------
Activate or deactivate the autoenlargement.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Activa o desactiva el autoincremento.
-------------------------------------------------------------------------------}
FActive: Boolean;
{*------------------------------------------------------------------------------
Radius increment speed in milliseconds.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Velocidad de incremento del radio en milisegundos.
-------------------------------------------------------------------------------}
FSpeed: Integer;
FOwner: TCustomCircle;
protected
{*------------------------------------------------------------------------------
Set Active property
@param Value New value
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Establece la propiedad Active
@param Value Nuevo valor
-------------------------------------------------------------------------------}
procedure SetActive(const Value: Boolean); virtual;
{*------------------------------------------------------------------------------
Set Speed property
@param Value New value
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Establece la propiedad Speed
@param Value Nuevo valor
-------------------------------------------------------------------------------}
procedure SetSpeed(const Value: Integer); virtual;
{*------------------------------------------------------------------------------
Radius increment speed in miliseconds.
@return Owner
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Devuelve el propietario del objeto.
@return Propietario
-------------------------------------------------------------------------------}
function GetOwner: TCustomCircle; reintroduce; virtual;
{*------------------------------------------------------------------------------
Response to TTimer event (defined in their descendants).
@param Sender Object that fire event
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Respuesta al evento del TTimer (definido en sus descendientes).
@param Sender Objecto que dispara el evento
-------------------------------------------------------------------------------}
procedure OnTimer(Sender: TObject);
public
{*------------------------------------------------------------------------------
Constructor class
@param aOwner Owner.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
@param aOwner Propietario.
-------------------------------------------------------------------------------}
constructor Create(aOwner: TCustomCircle); virtual;
{*------------------------------------------------------------------------------
Assign method copies the contents of another similar object.
@param Source object to copy content
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método Assign copia el contenido de un objeto similar.
@param Source objeto a copiar el contenido
-------------------------------------------------------------------------------}
procedure Assign(Source: TPersistent); override;
published
property Active: Boolean read FActive write SetActive default False;
property Min: Integer read FMin write FMin default 0;
property Max: Integer read FMax write FMax default 0;
property Increment: Integer read FIncrement write FIncrement default 100;
property Circular: Boolean read FCircular write FCircular default True;
property Speed: Integer read FSpeed write SetSpeed default 0;
end;
{*------------------------------------------------------------------------------
Base class for circles.
More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#Circle
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para los círculos.
Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#Circle
-------------------------------------------------------------------------------}
TCustomCircle = class(TLinkedComponent)
private
{*------------------------------------------------------------------------------
The radius in meters on the Earth's surface.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Radio en metros en la superficie de la Tierra.
-------------------------------------------------------------------------------}
FRadius: Real;
{*------------------------------------------------------------------------------
Whether this circle is visible on the map.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si el círculo es visible en el mapa.
-------------------------------------------------------------------------------}
FVisible: Boolean;
{*------------------------------------------------------------------------------
The stroke width in pixels.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Anchura del trazo en píxeles.
-------------------------------------------------------------------------------}
FStrokeWeight: Integer;
{*------------------------------------------------------------------------------
The fill opacity between 0.0 and 1.0.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Opacidad del relleno entre 0.0 y 1.0.
-------------------------------------------------------------------------------}
FFillOpacity: Real;
{*------------------------------------------------------------------------------
Indicates whether this Circle handles mouse events.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Indica si el círculo recibe eventos del ratón.
-------------------------------------------------------------------------------}
FClickable: Boolean;
{*------------------------------------------------------------------------------
The center of the circle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Centro del círculo.
-------------------------------------------------------------------------------}
FCenter: TLatLng;
{*------------------------------------------------------------------------------
The stroke opacity between 0.0 and 1.0.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Opacidad del trazo entre 0.0 y 1.0.
-------------------------------------------------------------------------------}
FStrokeOpacity: Real;
{*------------------------------------------------------------------------------
If set to true, the user can edit this circle by dragging the control points shown at the center and around the circumference of the circle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece a treu, el usuario puede editar el círculo arrastrando los puntos de control mostrados en el centro y alrededor de la circunferencia del círculo.
-------------------------------------------------------------------------------}
FEditable: Boolean;
{*------------------------------------------------------------------------------
Features to the autoenlargement of the circle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Características para el autoagrandado del círculo.
-------------------------------------------------------------------------------}
FAutoResize: TCustomSizeable;
FIsUpdating: Boolean;
procedure SetClickable(const Value: Boolean);
procedure SetEditable(const Value: Boolean);
procedure SetFillOpacity(const Value: Real);
procedure SetRadius(const Value: Real);
procedure SetStrokeOpacity(const Value: Real);
procedure SetStrokeWeight(const Value: Integer);
procedure SetVisible(const Value: Boolean);
procedure OnChangeLatLng(Sender: TObject);
protected
function ChangeProperties: Boolean; override;
{*------------------------------------------------------------------------------
This method returns the assigned color to the FillColor property defined into its descendents.
@return String with the color in RGB format
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Método que devuelve el color asignado a la propiedad FillColor definida en los descendientes.
@return Cadena con el color en formato RGB
-------------------------------------------------------------------------------}
function GetFillColor: string; virtual; abstract;
{*------------------------------------------------------------------------------
This method returns the assigned color to the StrokeColor property defined into its descendents.
@return String with the color in RGB format
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Método que devuelve el color asignado a la propiedad StrokeColor definida en los descendientes.
@return Cadena con el color en formato RGB
-------------------------------------------------------------------------------}
function GetStrokeColor: string; virtual; abstract;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure CenterMapTo; override;
{*------------------------------------------------------------------------------
Gets the LatLngBounds of this circle.
@param LLB The LatLngBounds.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Devuelve el LatLngBounds del círculo.
@param LLB La LatLngBounds.
-------------------------------------------------------------------------------}
procedure GetBounds(LLB: TLatLngBounds);
published
property Center: TLatLng read FCenter write FCenter;
property Clickable: Boolean read FClickable write SetClickable default True;
property Editable: Boolean read FEditable write SetEditable default False;
property FillOpacity: Real read FFillOpacity write SetFillOpacity; // 0 to 1
property Radius: Real read FRadius write SetRadius;
property StrokeOpacity: Real read FStrokeOpacity write SetStrokeOpacity; // 0 to 1
property StrokeWeight: Integer read FStrokeWeight write SetStrokeWeight default 2; // 1 to 10
property Visible: Boolean read FVisible write SetVisible default True;
property AutoResize: TCustomSizeable read FAutoResize write FAutoResize;
{*------------------------------------------------------------------------------
InfoWindows associated object.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
InfoWindows asociado al objeto.
-------------------------------------------------------------------------------}
property InfoWindow;
{*------------------------------------------------------------------------------
This property is used, if applicable, to establish the name that appears in the collection editor.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Esta propiedad se usa, si procede, para establecer el nombre que aparece en el editor de la colección.
-------------------------------------------------------------------------------}
property Text;
end;
{*------------------------------------------------------------------------------
Base class for circles collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para la colección de círculos.
-------------------------------------------------------------------------------}
TCustomCircles = class(TLinkedComponents)
private
procedure SetItems(I: Integer; const Value: TCustomCircle);
function GetItems(I: Integer): TCustomCircle;
protected
function GetOwner: TPersistent; override;
public
function Add: TCustomCircle;
function Insert(Index: Integer): TCustomCircle;
{*------------------------------------------------------------------------------
Lists the circles in the collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de círculos en la colección.
-------------------------------------------------------------------------------}
property Items[I: Integer]: TCustomCircle read GetItems write SetItems; default;
end;
{*------------------------------------------------------------------------------
Class management of circles.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase para la gestión de círculos.
-------------------------------------------------------------------------------}
TCustomGMCircle = class(TGMLinkedComponent)
private
{*------------------------------------------------------------------------------
This event is fired when the circle's StrokeColor property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad StrokeColor de un círculo.
-------------------------------------------------------------------------------}
FOnStrokeColorChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when a circle is right-clicked on.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando en un círculo se pulsa el botón derecho del ratón.
-------------------------------------------------------------------------------}
FOnRightClick: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired for a mousedown on the circle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara al pulsar en el círculo.
-------------------------------------------------------------------------------}
FOnMouseDown: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the circle's Visible property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad Visible de un círculo.
-------------------------------------------------------------------------------}
FOnVisibleChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when mousemove on the circle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando el ratón se mueve por encima del círculo.
-------------------------------------------------------------------------------}
FOnMouseMove: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the circle's StrokeWeight property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad StrokeWeight de un círculo.
-------------------------------------------------------------------------------}
FOnStrokeWeightChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired for a mouseup on the circle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara al soltar el círculo.
-------------------------------------------------------------------------------}
FOnMouseUp: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the circle's FillOpacity property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad FillOpacity de un círculo.
-------------------------------------------------------------------------------}
FOnFillOpacityChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the circle's Clickable property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad Clickable de un círculo.
-------------------------------------------------------------------------------}
FOnClickableChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the circle's Center property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad Center de un círculo.
-------------------------------------------------------------------------------}
FOnCenterChange: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired on circle mouseout.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando el ratón sale del círculo.
-------------------------------------------------------------------------------}
FOnMouseOut: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the circle's StrokeOpacity property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad StrokeOpacity de un círculo.
-------------------------------------------------------------------------------}
FOnStrokeOpacityChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the circle's Editable property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad Editable de un círculo.
-------------------------------------------------------------------------------}
FOnEditableChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event occurs when the user double-clicks a circle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando el usuario hace doble click un círculo.
-------------------------------------------------------------------------------}
FOnDblClick: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the mouse enters the area of the circle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando el ratón entra en el área del círculo.
-------------------------------------------------------------------------------}
FOnMouseOver: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the circle's FillColor property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad FillColor de un círculo.
-------------------------------------------------------------------------------}
FOnFillColorChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the circle's Radius property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad Radius de un círculo.
-------------------------------------------------------------------------------}
FOnRadiusChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event occurs when the user click a circle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando el usuario pulsa un círculo.
-------------------------------------------------------------------------------}
FOnClick: TLatLngIdxEvent;
protected
function GetAPIUrl: string; override;
function GetItems(I: Integer): TCustomCircle;
procedure EventFired(EventType: TEventType; Params: array of const); override;
function GetCollectionItemClass: TLinkedComponentClass; override;
function GetCollectionClass: TLinkedComponentsClass; override;
public
{*------------------------------------------------------------------------------
Creates a new TCustomCircle instance and adds it to the Items array.
@param Lat The circle's latitude.
@param Lng The circle's longitude.
@param Radius The circle's radius.
@return A new instance of TCustomCircle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Crea una nueva instancia de TCustomCircle y la añade en el array de Items.
@param Lat Latitud del círculo.
@param Lng Longitud del círculo.
@param Radius Radio del círculo.
@return Una nueva instancia de TCustomCircle.
-------------------------------------------------------------------------------}
function Add(Lat: Real = 0; Lng: Real = 0; Radius: Integer = 0): TCustomCircle;
{*------------------------------------------------------------------------------
Array with the collection items.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con la colección de elementos.
-------------------------------------------------------------------------------}
property Items[I: Integer]: TCustomCircle read GetItems; default;
published
{*------------------------------------------------------------------------------
Collection items.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Colección de elementos.
-------------------------------------------------------------------------------}
property VisualObjects;
// eventos
// events
// both (map and properties)
property OnCenterChange: TLatLngIdxEvent read FOnCenterChange write FOnCenterChange;
property OnRadiusChange: TLinkedComponentChange read FOnRadiusChange write FOnRadiusChange;
// from map
property OnClick: TLatLngIdxEvent read FOnClick write FOnClick;
property OnDblClick: TLatLngIdxEvent read FOnDblClick write FOnDblClick;
property OnMouseDown: TLatLngIdxEvent read FOnMouseDown write FOnMouseDown;
property OnMouseMove: TLatLngIdxEvent read FOnMouseMove write FOnMouseMove;
property OnMouseOut: TLatLngIdxEvent read FOnMouseOut write FOnMouseOut;
property OnMouseOver: TLatLngIdxEvent read FOnMouseOver write FOnMouseOver;
property OnMouseUp: TLatLngIdxEvent read FOnMouseUp write FOnMouseUp;
property OnRightClick: TLatLngIdxEvent read FOnRightClick write FOnRightClick;
// from properties
property OnClickableChange: TLinkedComponentChange read FOnClickableChange write FOnClickableChange;
property OnEditableChange: TLinkedComponentChange read FOnEditableChange write FOnEditableChange;
property OnFillColorChange: TLinkedComponentChange read FOnFillColorChange write FOnFillColorChange;
property OnFillOpacityChange: TLinkedComponentChange read FOnFillOpacityChange write FOnFillOpacityChange;
property OnStrokeColorChange: TLinkedComponentChange read FOnStrokeColorChange write FOnStrokeColorChange;
property OnStrokeOpacityChange: TLinkedComponentChange read FOnStrokeOpacityChange write FOnStrokeOpacityChange;
property OnStrokeWeightChange: TLinkedComponentChange read FOnStrokeWeightChange write FOnStrokeWeightChange;
property OnVisibleChange: TLinkedComponentChange read FOnVisibleChange write FOnVisibleChange;
end;
implementation
uses
{$IFDEF DELPHIXE2}
System.SysUtils,
{$ELSE}
SysUtils,
{$ENDIF}
Lang, GMFunctions;
{ TCustomGMCircle }
function TCustomGMCircle.Add(Lat, Lng: Real; Radius: Integer): TCustomCircle;
begin
Result := TCustomCircle(inherited Add);
Result.Center.Lat := Lat;
Result.Center.Lng := Lng;
Result.Radius := Radius;
end;
procedure TCustomGMCircle.EventFired(EventType: TEventType; Params: array of const);
var
LL: TLatLng;
OldEvent: TNotifyEvent;
begin
inherited;
if EventType = etInfoWinCloseClick then Exit;
if EventType = etCircleRadiusChange then
begin
if High(Params) <> 2 then
raise Exception.Create(GetTranslateText('Número de parámetros incorrecto', Map.Language));
if Params[0].VType <> vtExtended then
raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language));
if Params[1].VType <> vtInteger then
raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language));
if Params[1].VInteger > VisualObjects.Count - 1 then
raise Exception.Create(GetTranslateText('Valor de parámetro incorrecto', Map.Language));
if Params[2].VType <> vtBoolean then
raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language));
if Items[Params[1].VInteger].FIsUpdating then
begin
if not Params[0].VBoolean then
Items[Params[1].VInteger].FIsUpdating := False;
Exit;
end;
Items[Params[1].VInteger].FIsUpdating := True;
Items[Params[1].VInteger].Radius := Params[0].VExtended^;
if Assigned(FOnRadiusChange) then FOnRadiusChange(Self, Params[1].VInteger, Items[Params[1].VInteger]);
Items[Params[1].VInteger].FIsUpdating := False;
Exit;
end;
if High(Params) <> 2 then
raise Exception.Create(GetTranslateText('Número de parámetros incorrecto', Map.Language));
if (Params[0].VType <> vtExtended) or (Params[1].VType <> vtExtended) then
raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language));
if Params[2].VType <> vtInteger then
raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language));
if Params[2].VInteger > VisualObjects.Count - 1 then
raise Exception.Create(GetTranslateText('Valor de parámetro incorrecto', Map.Language));
LL := TLatLng.Create(ControlPrecision(Params[0].VExtended^, GetMapPrecision),
ControlPrecision(Params[1].VExtended^, GetMapPrecision));
try
case EventType of
etCircleClick: if Assigned(FOnClick) then FOnClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etCircleDblClick: if Assigned(FOnDblClick) then FOnDblClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etCircleMouseDown: if Assigned(FOnMouseDown) then FOnMouseDown(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etCircleMouseMove: if Assigned(FOnMouseMove) then FOnMouseMove(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etCircleMouseOut: if Assigned(FOnMouseOut) then FOnMouseOut(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etCircleMouseOver: if Assigned(FOnMouseOver) then FOnMouseOver(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etCircleMouseUp: if Assigned(FOnMouseUp) then FOnMouseUp(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etCircleRightClick: if Assigned(FOnRightClick) then FOnRightClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etCircleCenterChange:
begin
if Items[Params[2].VInteger].FIsUpdating then
begin
Items[Params[2].VInteger].FIsUpdating := False;
Exit;
end;
OldEvent := Items[Params[2].VInteger].Center.OnChange;
Items[Params[2].VInteger].Center.OnChange := nil;
Items[Params[2].VInteger].Center.Assign(LL);
if Assigned(FOnCenterChange) then FOnCenterChange(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
Items[Params[2].VInteger].Center.OnChange := OldEvent;
end;
end;
finally
FreeAndNil(LL);
end;
end;
function TCustomGMCircle.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference?hl=en#Circle';
end;
function TCustomGMCircle.GetCollectionClass: TLinkedComponentsClass;
begin
Result := TCustomCircles;
end;
function TCustomGMCircle.GetCollectionItemClass: TLinkedComponentClass;
begin
Result := TCustomCircle;
end;
function TCustomGMCircle.GetItems(I: Integer): TCustomCircle;
begin
Result := TCustomCircle(inherited Items[i]);
end;
{ TCustomCircles }
function TCustomCircles.Add: TCustomCircle;
begin
Result := TCustomCircle(inherited Add);
end;
function TCustomCircles.GetItems(I: Integer): TCustomCircle;
begin
Result := TCustomCircle(inherited Items[I]);
end;
function TCustomCircles.GetOwner: TPersistent;
begin
Result := TCustomGMCircle(inherited GetOwner);
end;
function TCustomCircles.Insert(Index: Integer): TCustomCircle;
begin
Result := TCustomCircle(inherited Insert(Index));
end;
procedure TCustomCircles.SetItems(I: Integer; const Value: TCustomCircle);
begin
inherited SetItem(I, Value);
end;
{ TCustomCircle }
procedure TCustomCircle.Assign(Source: TPersistent);
begin
inherited;
if Source is TCustomCircle then
begin
Center.Assign(TCustomCircle(Source).Center);
Clickable := TCustomCircle(Source).Clickable;
Editable := TCustomCircle(Source).Editable;
FillOpacity := TCustomCircle(Source).FillOpacity;
Radius := TCustomCircle(Source).Radius;
StrokeOpacity := TCustomCircle(Source).StrokeOpacity;
StrokeWeight := TCustomCircle(Source).StrokeWeight;
Visible := TCustomCircle(Source).Visible;
end;
end;
procedure TCustomCircle.CenterMapTo;
begin
inherited;
if Assigned(Collection) and (Collection is TCustomCircles) and
Assigned(TCustomCircles(Collection).FGMLinkedComponent) and
Assigned(TCustomCircles(Collection).FGMLinkedComponent.Map) then
TCustomCircles(Collection).FGMLinkedComponent.Map.SetCenter(FCenter.Lat, FCenter.Lng);
end;
function TCustomCircle.ChangeProperties: Boolean;
const
StrParams = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s';
var
Params: string;
begin
inherited;
Result := False;
if not Assigned(Collection) or not(Collection is TCustomCircles) or
not Assigned(TCustomCircles(Collection).FGMLinkedComponent) or
//not TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).AutoUpdate or
not Assigned(TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).Map) or
(csDesigning in TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).ComponentState) then
Exit;
Params := Format(StrParams, [
IntToStr(IdxList),
LowerCase(TCustomTransform.GMBoolToStr(Clickable, True)),
LowerCase(TCustomTransform.GMBoolToStr(Editable, True)),
QuotedStr(GetFillColor),
StringReplace(FloatToStr(FillOpacity), ',', '.', [rfReplaceAll]),
QuotedStr(GetStrokeColor),
StringReplace(FloatToStr(StrokeOpacity), ',', '.', [rfReplaceAll]),
IntToStr(StrokeWeight),
LowerCase(TCustomTransform.GMBoolToStr(Visible, True)),
Center.LatToStr(TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).GetMapPrecision),
Center.LngToStr(TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).GetMapPrecision),
StringReplace(FloatToStr(Radius), ',', '.', [rfReplaceAll]),
IntToStr(Index),
QuotedStr(InfoWindow.GetConvertedString),
LowerCase(TCustomTransform.GMBoolToStr(InfoWindow.DisableAutoPan, True)),
IntToStr(InfoWindow.MaxWidth),
IntToStr(InfoWindow.PixelOffset.Height),
IntToStr(InfoWindow.PixelOffset.Width),
LowerCase(TCustomTransform.GMBoolToStr(InfoWindow.CloseOtherBeforeOpen, True))
]);
Result := TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).ExecuteScript('MakeCircle', Params);
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).ErrorControl;
end;
constructor TCustomCircle.Create(Collection: TCollection);
begin
inherited;
FCenter := TLatLng.Create;
FCenter.OnChange := OnChangeLatLng;
FClickable := True;
FEditable := False;
FFillOpacity := 0.5;
FRadius := 0;
FStrokeOpacity := 1;
FStrokeWeight := 2;
FVisible := True;
FIsUpdating := False;
end;
destructor TCustomCircle.Destroy;
begin
if Assigned(FCenter) then FreeAndNil(FCenter);
if Assigned(FAutoResize) then FreeAndNil(FAutoResize);
inherited;
end;
procedure TCustomCircle.GetBounds(LLB: TLatLngBounds);
const
StrParams = '%s,%s';
var
Params: string;
begin
if not Assigned(LLB) then Exit;
if not Assigned(Collection) or not (Collection is TCustomCircles) or
not Assigned(TCustomCircles(Collection).FGMLinkedComponent) or
not Assigned(TCustomCircles(Collection).FGMLinkedComponent.Map) then
Exit;
Params := Format(StrParams, [IntToStr(IdxList), IntToStr(Index)]);
if not TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).ExecuteScript('CircleGetBounds', Params) then
Exit;
LLB.NE.Lat := TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).GetFloatField(CircleForm, CircleFormNELat);
LLB.NE.Lng := TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).GetFloatField(CircleForm, CircleFormNELng);
LLB.SW.Lat := TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).GetFloatField(CircleForm, CircleFormSWLat);
LLB.SW.Lng := TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).GetFloatField(CircleForm, CircleFormSWLng);
end;
procedure TCustomCircle.OnChangeLatLng(Sender: TObject);
begin
FIsUpdating := True;
ChangeProperties;
if Assigned(TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnCenterChange) then
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnCenterChange(
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent),
Center,
Index,
Self);
end;
procedure TCustomCircle.SetClickable(const Value: Boolean);
begin
if FClickable = Value then Exit;
FClickable := Value;
FIsUpdating := True;
ChangeProperties;
if Assigned(TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnClickableChange) then
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnClickableChange(
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomCircle.SetEditable(const Value: Boolean);
begin
if FEditable = Value then Exit;
FEditable := Value;
FIsUpdating := True;
ChangeProperties;
if Assigned(TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnEditableChange) then
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnEditableChange(
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomCircle.SetFillOpacity(const Value: Real);
begin
if FFillOpacity = Value then Exit;
FFillOpacity := Value;
FIsUpdating := True;
ChangeProperties;
if Assigned(TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnFillOpacityChange) then
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnFillOpacityChange(
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomCircle.SetRadius(const Value: Real);
begin
if FRadius = Value then Exit;
FRadius := Value;
if FRadius < 0 then FRadius := 0;
if not TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).IsMapActive then
Exit;
if Assigned(Collection) and (Collection is TCustomCircles) and
Assigned(TCustomCircles(Collection).FGMLinkedComponent) and
Assigned(TCustomCircles(Collection).FGMLinkedComponent.Map) then
begin
FIsUpdating := True;
if FAutoResize.Active then
begin
if not TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).ExecuteScript('CircleSetRadius', Format('%s,%s,%s', [
IntToStr(IdxList),
StringReplace(FloatToStr(Radius), ',', '.', [rfReplaceAll]),
IntToStr(Index)
])) then
FIsUpdating := False;
end
else
if not ChangeProperties then
FIsUpdating := False;
if Assigned(TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnRadiusChange) then
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnRadiusChange(
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent),
Index,
Self);
end;
end;
procedure TCustomCircle.SetStrokeOpacity(const Value: Real);
begin
if FStrokeOpacity = Value then Exit;
FStrokeOpacity := Value;
FIsUpdating := True;
ChangeProperties;
if Assigned(TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnStrokeOpacityChange) then
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnStrokeOpacityChange(
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomCircle.SetStrokeWeight(const Value: Integer);
begin
if FStrokeWeight = Value then Exit;
FStrokeWeight := Value;
FIsUpdating := True;
ChangeProperties;
if Assigned(TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnStrokeWeightChange) then
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnStrokeWeightChange(
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomCircle.SetVisible(const Value: Boolean);
begin
if FVisible = Value then Exit;
FVisible := Value;
FIsUpdating := True;
ChangeProperties;
if Assigned(TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnVisibleChange) then
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent).FOnVisibleChange(
TCustomGMCircle(TCustomCircles(Collection).FGMLinkedComponent),
Index,
Self);
end;
{ TCustomSizeable }
procedure TCustomSizeable.Assign(Source: TPersistent);
begin
if Source is TCustomSizeable then
begin
Active := TCustomSizeable(Source).Active;
Min := TCustomSizeable(Source).Min;
Max := TCustomSizeable(Source).Max;
Increment := TCustomSizeable(Source).Increment;
Circular := TCustomSizeable(Source).Circular;
Speed := TCustomSizeable(Source).Speed;
end
else
inherited Assign(Source);
end;
constructor TCustomSizeable.Create(aOwner: TCustomCircle);
begin
FOwner := aOwner;
FActive := False;
FCircular := True;
FMin := 0;
FMax := 0;
FIncrement := 100;
end;
function TCustomSizeable.GetOwner: TCustomCircle;
begin
Result := FOwner;
end;
procedure TCustomSizeable.OnTimer(Sender: TObject);
begin
if not TCustomGMCircle(TCustomCircles(FOwner.Collection).FGMLinkedComponent).IsMapActive then
Exit;
if (FOwner.Radius > FMax) then
if FCircular then FOwner.Radius := FMin
else Active := False
else FOwner.Radius := FOwner.Radius + FIncrement;
end;
procedure TCustomSizeable.SetActive(const Value: Boolean);
begin
if FActive = Value then Exit;
FActive := Value;
end;
procedure TCustomSizeable.SetSpeed(const Value: Integer);
begin
if FSpeed = Value then Exit;
FSpeed := Value;
end;
end.
|
unit Connection.UDP;
interface
uses Windows, SysUtils, StrUtils, GMConst, GMGlobals, Connection.Base, IdUDPBase, IdUDPClient, IdGlobal, IdSocketHandle;
type
TConnectionObjectUDP = class(TConnectionObjectBase)
private
udp: TIdUDPClient;
protected
function LogSignature: string; override;
function MakeExchange(etAction: TExchangeType): TCheckCOMResult; override;
function ConnectionEquipmentInitialized(): bool; override;
public
constructor Create(); override;
destructor Destroy(); override;
procedure FreePort; override;
property UDPObject: TIdUDPClient read udp;
end;
TConnectionObjectIncomingUDP = class(TConnectionObjectBase)
private
FSocket: TIdSocketHandle;
protected
function MakeExchange(etAction: TExchangeType): TCheckCOMResult; override;
function LogSignature: string; override;
property Socket: TIdSocketHandle read FSocket write FSocket;
end;
implementation
{ TConnectionObjectUDP }
uses ProgramLogFile;
function TConnectionObjectUDP.ConnectionEquipmentInitialized: bool;
begin
Result := udp.Active;
end;
constructor TConnectionObjectUDP.Create;
begin
inherited;
udp := TIdUDPClient.Create(nil);
end;
destructor TConnectionObjectUDP.Destroy;
begin
udp.Free();
inherited;
end;
procedure TConnectionObjectUDP.FreePort;
begin
if udp <> nil then
udp.Active := false;
end;
function TConnectionObjectUDP.LogSignature: string;
begin
Result := IfThen(LogPrefix <> '', LogPrefix, 'UDP') + ' ' + udp.Host + ':' + IntToStr(udp.Port);
end;
function TConnectionObjectUDP.MakeExchange(etAction: TExchangeType): TCheckCOMResult;
var bytes: TIdBytes;
action: string;
begin
Result := ccrEmpty;
buffers.NumberOfBytesRead := 0;
action := '';
try
if etAction in [etSend, etSenRec] then
begin
action := 'udp.SendBuffer';
SetLength(bytes, buffers.LengthSend);
WriteBuf(bytes, 0, buffers.bufSend, buffers.LengthSend);
udp.SendBuffer(bytes);
end;
if etAction in [etRec, etSenRec] then
begin
action := 'udp.ReceiveBuffer';
SetLength(bytes, 1000);
buffers.NumberOfBytesRead := udp.ReceiveBuffer(bytes);
WriteBuf(buffers.bufRec, 0, bytes, buffers.NumberOfBytesRead);
end;
if buffers.NumberOfBytesRead > 0 then
Result := ccrBytes;
except
on e: Exception do
begin
ProgramLog.AddException(ClassName() + '.MakeExchange.' + action + ': ' + e.Message);
Result := ccrError;
end;
end;
end;
{ TConnectionObjectIncomingUDP }
function TConnectionObjectIncomingUDP.LogSignature: string;
begin
Result := IfThen(LogPrefix <> '', LogPrefix, 'Inc. UDP');
end;
function TConnectionObjectIncomingUDP.MakeExchange(etAction: TExchangeType): TCheckCOMResult;
begin
Socket.SendTo(Socket.PeerIP, Socket.PeerPort, IdBytesFromBuf(buffers.BufSend, buffers.LengthSend));
Result := ccrEmpty;
end;
end.
|
unit uA;
interface
procedure Register;
implementation
uses
// dbg,
Winapi.Windows,
Winapi.Messages,
Winapi.CommCtrl,
Vcl.Forms,
ToolsAPI;
type
TRADAntiFlick = class(TNotifierObject, IOTAWizard)
const
SAppBuilder = 'AppBuilder';
SIDString = 'DelphiNotes.RAD.AntiFlick';
SName = 'RAD AntiFlick';
private
FMainWndHwnd: HWND;
procedure HookMainWindow;
procedure UnhookMainWindow;
public
constructor Create;
destructor Destroy; override;
{$region 'IOTAWizard'}
function GetIDString: string;
function GetName: string;
function GetState: TWizardState;
procedure Execute;
{$endregion}
end;
procedure Register;
begin
RegisterPackageWizard(TRADAntiFlick.Create);
end;
function SubClassProc(AHandle: HWND; AMessage: UINT; AWParam: WPARAM; ALParam: LPARAM; AIdSubclass: UINT_PTR; ARefData: DWORD_PTR): LRESULT; stdcall;
begin
case AMessage of
WM_WINDOWPOSCHANGED:
if IsIconic(AHandle) then
begin
// dbgStr('Catched!');
Result := 1;
Exit;
end;
WM_DESTROY:
TRADAntiFlick(ARefData).UnhookMainWindow;
end;
Result := DefSubclassProc(AHandle, AMessage, AWParam, ALParam);
end;
{ TRADAntiFlick }
constructor TRADAntiFlick.Create;
var
i: Integer;
ICC: TInitCommonControlsEx;
begin
inherited;
i := SizeOf(TInitCommonControlsEx);
ZeroMemory(@ICC, i);
ICC.dwSize := i;
ICC.dwICC := 0;
InitCommonControlsEx(ICC);
HookMainWindow;
end;
destructor TRADAntiFlick.Destroy;
begin
UnhookMainWindow;
inherited;
end;
procedure TRADAntiFlick.HookMainWindow;
var
i: Integer;
begin
FMainWndHwnd := 0;
for i := 0 to Screen.FormCount - 1 do
if Screen.Forms[i].Name = SAppBuilder then
begin
FMainWndHwnd := Screen.Forms[i].Handle;
Break;
end;
if FMainWndHwnd > 0 then
SetWindowSubclass(FMainWndHwnd, SubClassProc, 1, NativeUInt(Self));
end;
procedure TRADAntiFlick.UnhookMainWindow;
begin
if FMainWndHwnd > 0 then
RemoveWindowSubclass(FMainWndHwnd, SubClassProc, 1);
FMainWndHwnd := 0;
end;
{$region 'IOTAWizard'}
function TRADAntiFlick.GetIDString: string;
begin
Result := SIDString;
end;
function TRADAntiFlick.GetName: string;
begin
Result := SName;
end;
function TRADAntiFlick.GetState: TWizardState;
begin
Result := [wsEnabled];
end;
procedure TRADAntiFlick.Execute;
begin
end;
{$endregion}
end.
|
unit UClient_Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base,
FMX.ListBox, FMX.Layouts, FMX.Objects, FMX.Effects, FMX.StdCtrls,
FMX.ListView, FMX.Controls.Presentation, FMX.TabControl, FMX.ScrollBox,
FMX.Memo, FMX.Edit, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors,
Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope,
System.Actions, FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions;
type
TForm2 = class(TForm)
TabControl1: TTabControl;
TabItem1: TTabItem;
TabItem2: TTabItem;
TabItem3: TTabItem;
TabItem4: TTabItem;
ToolBar1: TToolBar;
Label1: TLabel;
btnNewItem: TButton;
ListView1: TListView;
ToolBar2: TToolBar;
Label2: TLabel;
btnBackList: TButton;
btnDetail: TButton;
Layout1: TLayout;
Panel1: TPanel;
ShadowEffect1: TShadowEffect;
Image1: TImage;
Layout2: TLayout;
lblTitle: TLabel;
lblAuthor: TLabel;
ListBox1: TListBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
lblPublisher: TLabel;
lblPhone: TLabel;
lblWebSite: TLabel;
lblComment: TLabel;
OverFlowMenu: TListBox;
lstItemModify: TListBoxItem;
lstItemDelete: TListBoxItem;
ShadowEffect2: TShadowEffect;
ToolBar3: TToolBar;
Label3: TLabel;
btnCancel: TButton;
btnSaveItem: TButton;
vsbEditFocus: TVertScrollBox;
lytContentsNew: TLayout;
Layout3: TLayout;
Rectangle1: TRectangle;
imgNewItem: TImage;
ListBox2: TListBox;
ListBoxItem7: TListBoxItem;
ListBoxItem8: TListBoxItem;
ListBoxItem9: TListBoxItem;
ListBoxItem10: TListBoxItem;
ListBoxItem11: TListBoxItem;
ListBoxItem12: TListBoxItem;
edtTitle: TEdit;
edtAuthor: TEdit;
edtPublisher: TEdit;
edtPhone: TEdit;
edtWebsite: TEdit;
mmoComment: TMemo;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
LinkListControlToField1: TLinkListControlToField;
LinkPropertyToFieldText: TLinkPropertyToField;
LinkPropertyToFieldText2: TLinkPropertyToField;
LinkPropertyToFieldText3: TLinkPropertyToField;
LinkPropertyToFieldText4: TLinkPropertyToField;
LinkPropertyToFieldText5: TLinkPropertyToField;
LinkPropertyToFieldText6: TLinkPropertyToField;
LinkPropertyToFieldText7: TLinkPropertyToField;
LinkPropertyToFieldBitmap: TLinkPropertyToField;
LinkControlToField1: TLinkControlToField;
LinkControlToField2: TLinkControlToField;
LinkControlToField3: TLinkControlToField;
LinkControlToField4: TLinkControlToField;
LinkControlToField5: TLinkControlToField;
LinkControlToField6: TLinkControlToField;
LinkPropertyToFieldBitmap2: TLinkPropertyToField;
Button1: TButton;
ActionList1: TActionList;
ChangeTabAction1: TChangeTabAction;
TakePhotoFromCameraAction1: TTakePhotoFromCameraAction;
Button2: TButton;
Layout4: TLayout;
Panel2: TPanel;
Label4: TLabel;
GroupBox1: TGroupBox;
Label5: TLabel;
Label6: TLabel;
edtDSHost: TEdit;
edtDSPort: TEdit;
Button3: TButton;
StyleBook1: TStyleBook;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure btnNewItemClick(Sender: TObject);
procedure btnBackListClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnSaveItemClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lstItemModifyClick(Sender: TObject);
procedure lstItemDeleteClick(Sender: TObject);
procedure btnDetailClick(Sender: TObject);
procedure FormFocusChanged(Sender: TObject);
procedure FormVirtualKeyboardHidden(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
procedure FormVirtualKeyboardShown(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
procedure lblPhoneClick(Sender: TObject);
procedure TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap);
procedure ListView1DeleteItem(Sender: TObject; AIndex: Integer);
procedure ListView1ItemClick(const Sender: TObject;
const AItem: TListViewItem);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
FKBBounds : TRectF;
FNeedOffset: Boolean;
procedure CalcContentBoundsPro(Sender: TObject; var ContentBounds: TRectF);
procedure RestorePosition;
procedure UpdateKBBounds;
procedure GotoList;
procedure GotoDetail;
procedure GotoNew;
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.fmx}
uses UClient_DM, system.Math, FMX.Platform, FMX.PhoneDialer;
procedure TForm2.btnBackListClick(Sender: TObject);
begin
GotoList;
end;
procedure TForm2.btnCancelClick(Sender: TObject);
begin
DataModule1.CancelItem;//취소
GotoList;
end;
procedure TForm2.btnDetailClick(Sender: TObject);
begin
OverflowMenu.Visible := not OverflowMenu.Visible;
if OverflowMenu.Visible then
begin
OverflowMenu.ItemIndex := -1;
OverflowMenu.BringToFront;
OverflowMenu.ApplyStyleLookup;
OverflowMenu.RealignContent;
OverflowMenu.Position.X := Width - OverflowMenu.Width - 5;
OverflowMenu.Position.Y := Toolbar2.Height;
end;
end;
procedure TForm2.btnNewItemClick(Sender: TObject);
begin
ListView1.ItemIndex := -1;
DataModule1.AppendMode;
GotoNew
end;
procedure TForm2.btnSaveItemClick(Sender: TObject);
begin
DataModule1.SaveItem;//저장
GotoList;
end;
procedure TForm2.Button1Click(Sender: TObject);
begin
DataModule1.Refresh;
end;
procedure TForm2.Button3Click(Sender: TObject);
begin
if DataModule1.Connect(edtDSHost.Text, edtDSPort.Text) then
GotoList
else
ShowMessage('서버에 접속할 수 없습니다.');
end;
procedure TForm2.Button4Click(Sender: TObject);
begin
GotoList;
end;
procedure TForm2.CalcContentBoundsPro(Sender: TObject;
var ContentBounds: TRectF);
begin
if FNeedOffset and (FKBBounds.Top >0) then
begin
ContentBounds.Bottom := Max(ContentBounds.Bottom,2* ClientHeight - FKBBounds.Top)
end;
end;
procedure TForm2.RestorePosition;
begin
vsbEditFocus.ViewportPosition := PointF(vsbEditFocus.ViewportPosition.X, 0);
lytContentsNew.Align := TAlignLayout.Client;
vsbEditFocus.RealignContent;
end;
procedure TForm2.TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap);
begin
imgNewItem.Bitmap.Assign(Image);
DataModule1.SetImage(Image);
end;
procedure TForm2.UpdateKBBounds;
var
LFocused : TControl;
LFocusRect: TRectF;
begin
FNeedOffset := False;
if Assigned(Focused) then
begin
LFocused := TControl(Focused.GetObject);
LFocusRect := LFocused.AbsoluteRect;
LFocusRect.Offset(vsbEditFocus.ViewportPosition);
if (LFocusRect.IntersectsWith(TRectF.Create(FKBBounds))) and
(LFocusRect.Bottom > FKBBounds.Top) then
begin
FNeedOffset := True;
lytContentsNew.Align := TAlignLayout.Horizontal;
vsbEditFocus.RealignContent;
Application.ProcessMessages;
vsbEditFocus.ViewportPosition := PointF(vsbEditFocus.ViewportPosition.X,
LFocusRect.Bottom - FKBBounds.Top);
end;
end;
if not FNeedOffset then
RestorePosition;
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
TabControl1.TabPosition := TTabPosition.None;
TabControl1.TabIndex:=0;
OverFlowMenu.Visible := False;
vsbEditFocus.OnCalcContentBounds := CalcContentBoundsPro;
end;
procedure TForm2.FormFocusChanged(Sender: TObject);
begin
UpdateKBBounds;
end;
procedure TForm2.FormVirtualKeyboardHidden(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
begin
FKBBounds.Create(0, 0, 0, 0);
FNeedOffset := False;
RestorePosition;
end;
procedure TForm2.FormVirtualKeyboardShown(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
begin
FKBBounds := TRectF.Create(Bounds);
FKBBounds.TopLeft := ScreenToClient(FKBBounds.TopLeft);
FKBBounds.BottomRight := ScreenToClient(FKBBounds.BottomRight);
UpdateKBBounds;
end;
procedure TForm2.GotoDetail;
begin
ChangeTabAction1.Tab := TabItem3;
ChangeTabAction1.ExecuteTarget(nil);
end;
procedure TForm2.GotoList;
begin
ChangeTabAction1.Tab := TabItem2;
ChangeTabAction1.ExecuteTarget(nil);
end;
procedure TForm2.GotoNew;
begin
ChangeTabAction1.Tab := TabItem4;
ChangeTabAction1.ExecuteTarget(nil);
end;
procedure TForm2.lblPhoneClick(Sender: TObject);
var
PhoneDlrSvc: IFMXPhoneDialerService;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXPhoneDialerService, IInterface(PhoneDlrSvc)) then
PhoneDlrSvc.Call(lblPhone.Text);
end;
procedure TForm2.ListView1DeleteItem(Sender: TObject; AIndex: Integer);
begin
DataModule1.DeleteItem;
end;
procedure TForm2.ListView1ItemClick(const Sender: TObject;
const AItem: TListViewItem);
begin
GotoDetail;
end;
procedure TForm2.lstItemDeleteClick(Sender: TObject);
begin
OverflowMenu.Visible := False;
MessageDlg('해당 정보를 삭제하시겠습니까?', TMsgDlgType.mtWarning,
[TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0,
procedure(const AResult: TModalResult)
begin
if AResult = mrYes then
begin
DataModule1.DeleteItem; // 선택항목 삭제
GotoList;
end;
end);
end;
procedure TForm2.lstItemModifyClick(Sender: TObject); //수벙 버튼
begin
OverFlowMenu.Visible := False;
DataModule1.EditMode;
GotoNew;
end;
end.
|
unit Collisions;
interface
uses
Points, EngineTypes;
function Trace (var P : SPoint; Delta : Point) : boolean;
function TraceWithItems (var P : SPoint; Delta : Point; var CIS : integer; IP : PAPItem; NoCCheck : boolean) : boolean;
function Visible (const P1,P2: SPoint): boolean;
procedure PushConvex (var C: Convex);
procedure GetSectors (var P : SPoint; R: float; Push : boolean; var CPS : integer; PP: PAPSector);
procedure Unprocess (CPS : integer; PP : PAPSector);
implementation
uses
Memory, Level, Geometry, Items, Sounds;
type
ABool = array [0..MaxInt div sizeof(boolean)-1] of boolean;
PABool = ^ABool;
AFloat = array [0..MaxInt div sizeof(float)-1] of float;
PAFloat = ^AFloat;
function DistancePS (const P: Point; const S: Sector) : float;
var
i : integer;
ad : float;
begin
result := 0;
for i := 0 to S.CFaces-1 do begin
ad := Dot(P, S.Faces[i].INorm) - S.Faces[i].INormC;
if result<ad then result := ad;
end;
end;
function SPointCorrect (const P: SPoint) : boolean;
begin
Result := DistancePS(P.P, P.S^)<=0;
end;
procedure DoCorrect (var P: SPoint);
var
i,j : integer;
ad : float;
NP : Point;
correct : boolean;
begin
// это такой мега-костыль, потому что плавучка может такое выкинуть
repeat
correct := true;
for i := 0 to P.S.CFaces-1 do begin
j := 1;
NP := P.P;
repeat
ad := Dot(NP, P.S.Faces[i].INorm) - P.S.Faces[i].INormC;
if ad<=0 then
break;
correct := false;
NP := Add(P.P, Scale(P.S.Faces[i].INorm,-ad*j));
inc(j);
until false;
P.P := NP;
end;
until correct;
end;
function TraceWithItems (var P : SPoint; Delta : Point; var CIS : integer; IP : PAPItem; NoCCheck : boolean) : boolean;
// ну чё, смертнички, попиздовали!
var
NewF : PFace;
NewP : SPoint;
OldP,InitP : Point;
t1,t2 : float;
function GetIntersectionFace (const S: Sector; const P,Delta: Point) : PFace;
var
i : integer;
MS : MemoryState;
gf : PAFloat;
d : float;
md : float;
procedure Enlarge (var f : float; newf : float);
begin
if f<newf then f := newf;
end;
begin
SaveState(MS);
gf := Alloc(S.CFaces*sizeof(boolean));
for i := 0 to S.CFaces-1 do gf[i] := 0;
for i := 0 to S.CLines-1 do begin
d := Volume(Sub(S.Lines[i].P1^, P), Sub(S.Lines[i].P2^, P), Delta);
if d>0 then Enlarge(gf[S.Lines[i].f1.Id], d)
else if d<0 then Enlarge(gf[S.Lines[i].f2.Id],-d);
end;
Result := nil;
md := -1;
for i := 0 to S.CFaces-1 do begin
if ((md<0) or (gf[i]<md)) and (Dot(Delta, S.Faces[i].INorm)>0) then begin
Result := @S.Faces[i];
md := gf[i];
end;
end;
// по идее, md для нужной грани должно быть ваще строго ноль, но так как у нас тут блядская плавучка, то всякое бывает
Assert(Result <> nil);
RestoreState(MS);
end;
procedure AddItemsFromSector (const S : Sector);
var
PCS : PConvexInSector;
Dst,Cr : Point;
ok : boolean;
begin
if IP=nil then Exit;
PCS := S.FConvex;
while PCS<>nil do begin
if PCS.Convex.CanCollide then begin
if NoCCheck then
ok := True
else begin
Dst := Sub(PCS.Convex.Center.P, NewP.P);
if Dot(Delta, Dst)>0 then begin
ok := Dot(Dst,Dst) < sqr(PCS.Convex.R);
end else begin
Dst := Sub(PCS.Convex.Center.P, InitP);
if Dot(Delta,Dst)<0 then begin
ok := Dot(Dst,Dst) < sqr(PCS.Convex.R);
end else begin
Cr := Cross(Delta,Dst);
ok := Dot(Cr,Cr) <= sqr(PCS.Convex.R)*Dot(Delta,Delta);
end;
end;
end;
if ok and not PCS.Convex.Item.inProcess then begin
Inc(CIS);
IP[CIS-1] := PCS.Convex.Item;
PCS.Convex.Item.inProcess := True;
end;
end;
PCS := PCS.NC;
end;
end;
begin
CIS := 0;
Assert(SPointCorrect(P));
NewP.P := Add(P.P, Delta);
NewP.S := P.S;
InitP := P.P;
AddItemsFromSector(P.S^);
while not SPointCorrect(NewP) do begin
NewF := GetIntersectionFace(NewP.S^, P.P, Delta);
if (not NewF.Penetrable) or (NewF.NextSector=nil) then begin
Result := False;
OldP := P.P;
t1 := -(Dot(OldP , newF.INorm)-newF.INormC);
t2 := +(Dot(NewP.P, newF.INorm)-newF.INormC);
if (t1>=0) and (t2>0) then begin
P.P := Mid(OldP, t1, NewP.P, t2);
Delta := Sub(P.P, InitP);
end;
P.S := NewP.S;
DoCorrect(P);
Assert(SPointCorrect(P));
Exit;
end;
NewP.S := NewF.NextSector;
AddItemsFromSector(NewP.S^);
end;
P := NewP;
Assert(SPointCorrect(P));
Result := True;
end;
function Trace (var P : SPoint; Delta : Point) : boolean;
var
CI : integer;
begin
Result := TraceWithItems(P, Delta, CI, nil, True);
end;
function Visible (const P1,P2: SPoint): boolean;
var
P : SPoint;
begin
Result := False;
P := P1;
if not Trace(P, Sub(P2.P, P1.P)) then Exit;
if P.S<>P2.S then Exit;
Result := True;
end;
procedure GetSectors (var P : SPoint; R: float; Push : boolean; var CPS : integer; PP: PAPSector);
// это всего лишь коллизии, всего-то навсего, спокойствие, только спокойствие
// людей буем делать из трёх сфер
procedure TestAllFaces (var P: SPoint; S : PSector; R: float);
var
i,j : integer;
dr : float;
b : boolean;
P1, P2 : Point;
crs : PAPoint;
d1, d2 : float;
function SoftNorm (const P: Point; const N: Point): Point;
var l : float;
begin
l := LengthP(P);
if l=0 then result := N else result := Scale(P,1/l);
end;
begin
// контроль, что мы тут были уже, парадигма в выставлении флагов и их возврате обратно
if S.inProcess>0 then exit;
Inc(CPS);
PP[CPS-1] := S;
S.inProcess := 1;
// перебираем поверхности, если расстояние до неё меньше R,
// то рекурсивно перебираем и для поверхностей того сектора, на которые она выходит
for i := 0 to S.CFaces-1 do with S.Faces[i] do begin
dr := R-(INormC-Dot(P.P, INorm));
if dr>0 then begin
// кажется, мы близки к этой грани. ну по крайней мере, мы точно близки к плоскости, что её содержит
b := true;
crs := Alloc(CPoints*sizeof(Point));
for j := 0 to CPoints-1 do begin
P1 := Sub(Points[j]^, P.P);
P2 := Sub(Points[(j+1) mod CPoints]^, P.P);
crs[j] := Cross(P1,P2);
end;
for j := 0 to CPoints-1 do begin
if Dot(crs[j], INorm)>0 then begin // Volume (P1-P,P2-P,INorm)
b := false; // мы находимся не напротив этой грани(
break;
end;
end;
if b then begin
if Penetrable then TestAllFaces(P, NextSector, R)
else if Push then Trace(P, Scale(INorm, -dr));
end else begin
// может, есть близость с какой-то линией?
for j := 0 to CPoints-1 do begin
// оценить площадь треугольника, но это после обеда
P1 := Sub(Points[j]^, P.P);
P2 := Sub(Points[(j+1) mod CPoints]^, P.P);
dr := R-(LengthP(crs[j])/LengthP(Sub(P1,P2)));
if dr>0 then begin
// мы близки к линии, но не факт, что близки к отрезку
d1 := Dot (P1, Sub(P1,P2));
d2 := Dot (P2, Sub(P2,P1));
if (d1>=0) and (d2>=0) then begin
// близки к отрезку!
if Penetrable then TestAllFaces(P, NextSector, R)
else if Push then Trace(P, Scale(SoftNorm(Mid(P1,d1,P2,d2), INorm), -dr));
end else begin
// близки к одной из точек?
if d1<0 then begin
dr := R-LengthP(P1);
if dr>0 then begin
if Penetrable then TestAllFaces(P, NextSector, R)
else if Push then Trace(P, Scale(SoftNorm(P1, INorm), -dr));
end;
end else if d2<0 then begin
dr := R-LengthP(P2);
if dr>0 then begin
if Penetrable then TestAllFaces(P, NextSector, R)
else if Push then Trace(P, Scale(SoftNorm(P2, INorm), -dr));
end;
end;
end;
end;
end;
end;
end;
end;
end;
// 9 ендов, идём на рекорд!
begin
CPS := 0;
TestAllFaces(P, P.S, R);
end;
procedure Unprocess (CPS : integer; PP : PAPSector);
var i: integer;
begin
for i := 0 to CPS-1 do PP[i].inProcess := 0;
end;
procedure PushTwoConvexes (var S1,S2 : Convex);
var
DP : Point;
dr,l,mr1,mr2 : float;
procedure Get(var S1,S2 : Convex);
begin
if (S2.Item.Model.Kind=mkMonster) and (S2.Item.Model.Player) then begin
if S1.Item.Model.ApplyItemProc(S2.Item.Monster, S1.Item) then begin
S1.Item.Center.S := @Level.L.EmptyS;
S1.Item.Center.P := CenterSector(S1.Item.Center.S^);
UpdateItem(S1.Item^);
SetChanel(2);
SetStyle(120);
SetVolume(127);
Sound(60);
end;
end;
end;
begin
DP := Sub(S1.Center.P, S2.Center.P);
mr1 := S1.Mass/(S1.Mass+S2.Mass);
mr2 := 1-mr1;
l := Dot(DP,DP);
if l<sqr(s1.R+s2.R) then begin
if S1.Item.Model.Kind=mkBox then begin
Get(S1,S2);
end else if S2.Item.Model.Kind=mkBox then begin
Get(S2,S1);
end else begin
DR := s1.R+s2.R-sqrt(l);
// просто рсталкиваем
// todo : для игрока и аптечки надо другое
if l=0 then begin
DP := ToPoint(1,0,0);
l := 1;
end else
l := 1/l;
Trace(S1.Center, Scale(DP, +DR*mr2*l));
Trace(S2.Center, Scale(DP, -DR*mr1*l));
end;
end;
end;
procedure PushConvex (var C: Convex);
var
CPS : integer;
PP : PAPSector;
CPC : integer;
PC : PAPConvex;
CIS : PConvexInSector;
i : integer;
MS : MemoryState;
procedure AddC(C : PConvex);
begin
Inc(CPC);
PC[CPC-1] := C;
PC[CPC-1].inProcess := True;
end;
begin
SaveState(MS);
PP := Alloc(CSectors*sizeof(PSector));
GetSectors (C.Center, C.R, True, CPS, PP);
if C.CanCollide then begin
CPC := 0;
PC := Alloc(CConvexes*sizeof(PConvex));
for i := 0 to CPS-1 do begin
CIS := PP[i].FConvex;
while CIS<>nil do begin
if (not CIS.Convex.inProcess) and (CIS.Convex.Item <> C.Item) and (CIS.Convex.CanCollide) then
AddC(CIS.Convex);
CIS := CIS.NC;
end;
end;
// переебрать все итемы во всех этих комнатах и растолкать
for i := 0 to CPC-1 do begin
PushTwoConvexes(C, PC[i]^);
PC[i].inProcess := False;
end;
end;
Unprocess(CPS, PP);
RestoreState(MS);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC ODBC Call Interface }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.ODBCCli;
interface
uses
FireDAC.Stan.Consts;
{$HPPEMIT '#if defined(_Windows)'}
{$HPPEMIT '#include <sqltypes.h>'}
{$HPPEMIT '#endif'}
const
{$IFDEF MSWINDOWS}
C_ODBC: String = 'odbc32' + C_FD_DLLExt;
C_ODBCCP: String = 'odbccp32' + C_FD_DLLExt;
{$ENDIF}
{$IFDEF POSIX}
C_ODBC: String = 'libodbc' + C_FD_DLLExt;
C_ODBCCP: String = 'libodbcinst' + C_FD_DLLExt;
{$ENDIF}
ODBCVER = $0380;
{$EXTERNALSYM ODBCVER}
{----------------------------------------------------------------------------}
{ SQLTYPES.H }
{----------------------------------------------------------------------------}
type
// API declaration data types
SQLChar = Char;
SQLSChar = Shortint;
SQLDate = Byte;
SQLDecimal = Byte;
SQLDouble = Double;
SQLFloat = Double;
SQLInteger = Integer;
SQLUInteger = Integer;
SQLUSmallint = Word;
SQLByte = Byte;
{$IFDEF FireDAC_64}
SQLLen = Int64;
SQLULen = UInt64;
SQLSetPosiRow = UInt64;
{$ENDIF}
{$IFDEF FireDAC_32}
SQLLen = SQLInteger;
SQLULen = SQLUInteger;
SQLSetPosiRow = SQLUSmallint;
{$ENDIF}
// For Backward compatibility
{$IFDEF FireDAC_32}
SQLRowCount = SQLULen;
SQLRowsetSize = SQLULen;
SQLTransID = SQLULen;
SQLRowOffset = SQLLen;
{$ENDIF}
SQLNumeric = Byte;
SQLPointer = Pointer;
SQLReal = Single;
SQLSmallint = Smallint;
SQLTime = Byte;
SQLTimeStamp = Byte;
SQLVarchar = Byte;
// function return type
SQLReturn = SQLSmallint;
// generic data structures
SQLHandle = Pointer;
SQLHEnv = SQLHandle;
SQLHDbc = SQLHandle;
SQLHStmt = SQLHandle;
SQLHDesc = SQLHandle;
// SQL portable types for C
UChar = Byte;
SChar = Shortint;
SDword = Integer;
Dword = Cardinal;
SWord = Smallint;
UDword = Cardinal;
UWord = Word;
SLong = LongInt;
SShort = Smallint;
ULong = LongInt;
UShort = Word;
SDouble = Double;
LDouble = Double;
SFloat = Single;
Ptr = Pointer;
HEnv = Pointer;
HDbc = Pointer;
HStmt = Pointer;
Retcode = Smallint;
SQLHWnd = NativeUInt;
TSQLDateStruct = packed record
Year: SQLSmallint;
Month: SQLUSmallint;
Day: SQLUSmallint;
end;
DATE_STRUCT = TSQLDateStruct;
SQL_DATE_STRUCT = TSQLDateStruct;
TSQLTimeStruct = packed record
Hour: SQLUSmallint;
Minute: SQLUSmallint;
Second: SQLUSmallint;
end;
TIME_STRUCT = TSQLTimeStruct;
SQL_TIME_STRUCT = TSQLTimeStruct;
TODBCTimeStamp = packed record
Year: SQLSmallint;
Month: SQLUSmallint;
Day: SQLUSmallint;
Hour: SQLUSmallint;
Minute: SQLUSmallint;
Second: SQLUSmallint;
Fraction: SQLUInteger;
end;
TIMESTAMP_STRUCT = TODBCTimeStamp;
SQL_TIMESTAMP_STRUCT = TODBCTimeStamp;
// enumerations for DATETIME_INTERVAL_SUBCODE values for interval data types
// these values are from SQL-92
const
SQL_IS_UNKNOWN = 0;
SQL_IS_YEAR = 1;
SQL_IS_MONTH = 2;
SQL_IS_DAY = 3;
SQL_IS_HOUR = 4;
SQL_IS_MINUTE = 5;
SQL_IS_SECOND = 6;
SQL_IS_YEAR_TO_MONTH = 7;
SQL_IS_DAY_TO_HOUR = 8;
SQL_IS_DAY_TO_MINUTE = 9;
SQL_IS_DAY_TO_SECOND = 10;
SQL_IS_HOUR_TO_MINUTE = 11;
SQL_IS_HOUR_TO_SECOND = 12;
SQL_IS_MINUTE_TO_SECOND = 13;
type
SQLINTERVAL = Integer;
TSQLYearMonth = packed record
Year: SQLUInteger;
Month: SQLUInteger;
end;
SQL_YEAR_MONTH_STRUCT = TSQLYearMonth;
{$EXTERNALSYM SQL_YEAR_MONTH_STRUCT}
TSQLDaySecond = packed record
Day: SQLUInteger;
Hour: SQLUInteger;
Minute: SQLUInteger;
Second: SQLUInteger;
Fraction: SQLUInteger;
end;
SQL_DAY_SECOND_STRUCT = TSQLDaySecond;
{$EXTERNALSYM SQL_DAY_SECOND_STRUCT}
TSQLInterval = packed record
Interval_type: SQLInteger;
Interval_sign: SQLInteger;
case SQLInteger of
SQL_IS_YEAR_TO_MONTH: (YearMonth: TSQLYearMonth);
SQL_IS_DAY_TO_SECOND: (DaySecond: TSQLDaySecond);
end;
SQL_INTERVAL_STRUCT = TSQLInterval;
// the ODBC C types for SQL_C_SBIGINT and SQL_C_UBIGINT
ODBCInt64 = Int64;
ODBCUInt64 = UInt64;
SQLBigInt = ODBCInt64;
SQLUBigInt = ODBCUInt64;
// internal representation of numeric data type
const
SQL_MAX_NUMERIC_LEN = 16;
{$EXTERNALSYM SQL_MAX_NUMERIC_LEN}
type
PSQLNumericRec = ^TSQLNumericRec;
TSQLNumericRec = packed record
precision: SQLSChar;
scale: SQLSChar;
sign: SQLSChar; // 1 if positive, 0 if negative
val: array [0 .. SQL_MAX_NUMERIC_LEN - 1] of SQLByte;
end;
SQL_NUMERIC_STRUCT = TSQLNumericRec;
// size is 16
TSQLGuid = TGUID;
Bookmark = SQLULen;
SQLWChar = WideChar;
SQLTChar = SQLWChar;
SQLBOOL = WordBool;
{----------------------------------------------------------------------------}
{ Additional pointer types }
{----------------------------------------------------------------------------}
PUWord = ^UWord;
PSQLUInteger = ^SQLUInteger;
PSQLPointer = ^SQLPointer;
PSQLByte = ^SQLByte;
PSQLChar = ^SQLChar;
PSQLVarchar = ^SQLVarchar;
PSQLWChar = ^SQLWChar;
PSQLDate = ^SQLDate;
PSQLTime = ^SQLTime;
PSQLTimeStamp = ^SQLTimeStamp;
PSQLDouble = ^SQLDouble;
PSQLFloat = ^SQLFloat;
PSQLReal = ^SQLReal;
PSQLNumeric = ^SQLNumeric;
PSQLDecimal = ^SQLDecimal;
PSQLSmallint = ^SQLSmallint;
PSQLUSmallint = ^SQLUSmallint;
PSQLInteger = ^SQLInteger;
PSQLBigInt = ^SQLBigInt;
PSQLUBigInt = ^SQLUBigInt;
PSQLLen = ^SQLLen;
PSQLULen = ^SQLULen;
PSQLSetPosiRow = ^SQLSetPosiRow;
{$IFDEF FireDAC_32}
PSQLRowCount = ^SQLRowCount;
PSQLRowsetSize = ^SQLRowsetSize;
PSQLTransID = ^SQLTransID;
PSQLRowOffset = ^SQLRowOffset;
{$ENDIF}
PSQLDateStruct = ^TSQLDateStruct;
PSQLTimeStruct = ^TSQLTimeStruct;
PODBCTimeStamp = ^TODBCTimeStamp;
PSQLYearMonth = ^TSQLYearMonth;
PSQLDaySecond = ^TSQLDaySecond;
PSQLInterval = ^TSQLInterval;
PSQLGUID = ^TSQLGUID;
{----------------------------------------------------------------------------}
{ SQL.H }
{----------------------------------------------------------------------------}
const
// special length/indicator values
SQL_NULL_DATA = SQLLen(-1);
SQL_DATA_AT_EXEC = SQLLen(-2);
// return values from functions
SQL_SUCCESS = 0;
SQL_SUCCESS_WITH_INFO = 1;
SQL_NO_DATA = 100;
SQL_PARAM_DATA_AVAILABLE = 101;
SQL_ERROR = -1;
SQL_INVALID_HANDLE = -2;
SQL_STILL_EXECUTING = 2;
SQL_NEED_DATA = 99;
function SQL_SUCCEEDED(rc: SQLReturn): Boolean; inline;
const
// flags for null-terminated string
SQL_NTS = -3;
SQL_NTSL = -3;
// maximum message Length
SQL_MAX_MESSAGE_LENGTH = 4096;
// date/time Length constants
SQL_DATE_LEN = 10;
SQL_TIME_LEN = 8; // Add P+1 if precision is nonzero
SQL_TIMESTAMP_LEN = 19; // Add P+1 if precision is nonzero
// handle type identifiers
SQL_HANDLE_ENV = 1;
SQL_HANDLE_DBC = 2;
SQL_HANDLE_STMT = 3;
SQL_HANDLE_DESC = 4;
// environment attribute
SQL_ATTR_OUTPUT_NTS = 10001;
// connection attributes
SQL_ATTR_AUTO_IPD = 10001;
SQL_ATTR_METADATA_ID = 10014;
// statement attributes
SQL_ATTR_APP_ROW_DESC = 10010;
SQL_ATTR_APP_PARAM_DESC = 10011;
SQL_ATTR_IMP_ROW_DESC = 10012;
SQL_ATTR_IMP_PARAM_DESC = 10013;
SQL_ATTR_CURSOR_SCROLLABLE = -1;
SQL_ATTR_CURSOR_SENSITIVITY = -2;
// SQL_ATTR_CURSOR_SCROLLABLE values
SQL_NONSCROLLABLE = 0;
SQL_SCROLLABLE = 1;
// Identifiers of fields in the SQL descriptor
SQL_DESC_COUNT = 1001;
SQL_DESC_TYPE = 1002;
SQL_DESC_LENGTH = 1003;
SQL_DESC_OCTET_LENGTH_PTR = 1004;
SQL_DESC_PRECISION = 1005;
SQL_DESC_SCALE = 1006;
SQL_DESC_DATETIME_INTERVAL_CODE = 1007;
SQL_DESC_NULLABLE = 1008;
SQL_DESC_INDICATOR_PTR = 1009;
SQL_DESC_DATA_PTR = 1010;
SQL_DESC_NAME = 1011;
SQL_DESC_UNNAMED = 1012;
SQL_DESC_OCTET_LENGTH = 1013;
SQL_DESC_ALLOC_TYPE = 1099;
// Identifiers of fields in the diagnostics area
SQL_DIAG_RETURNCODE = 1;
SQL_DIAG_NUMBER = 2;
SQL_DIAG_ROW_COUNT = 3;
SQL_DIAG_SQLSTATE = 4;
SQL_DIAG_NATIVE = 5;
SQL_DIAG_MESSAGE_TEXT = 6;
SQL_DIAG_DYNAMIC_FUNCTION = 7;
SQL_DIAG_CLASS_ORIGIN = 8;
SQL_DIAG_SUBCLASS_ORIGIN = 9;
SQL_DIAG_CONNECTION_NAME = 10;
SQL_DIAG_SERVER_NAME = 11;
SQL_DIAG_DYNAMIC_FUNCTION_CODE = 12;
// dynamic function codes
SQL_DIAG_ALTER_DOMAIN = 3;
SQL_DIAG_ALTER_TABLE = 4;
SQL_DIAG_CALL = 7;
SQL_DIAG_CREATE_ASSERTION = 6;
SQL_DIAG_CREATE_CHARACTER_SET = 8;
SQL_DIAG_CREATE_COLLATION = 10;
SQL_DIAG_CREATE_DOMAIN = 23;
SQL_DIAG_CREATE_INDEX = -1;
SQL_DIAG_CREATE_SCHEMA = 64;
SQL_DIAG_CREATE_TABLE = 77;
SQL_DIAG_CREATE_TRANSLATION = 79;
SQL_DIAG_CREATE_VIEW = 84;
SQL_DIAG_DELETE_WHERE = 19;
SQL_DIAG_DROP_ASSERTION = 24;
SQL_DIAG_DROP_CHARACTER_SET = 25;
SQL_DIAG_DROP_COLLATION = 26;
SQL_DIAG_DROP_DOMAIN = 27;
SQL_DIAG_DROP_INDEX = -2;
SQL_DIAG_DROP_SCHEMA = 31;
SQL_DIAG_DROP_TABLE = 32;
SQL_DIAG_DROP_TRANSLATION = 33;
SQL_DIAG_DROP_VIEW = 36;
SQL_DIAG_DYNAMIC_DELETE_CURSOR = 38;
SQL_DIAG_DYNAMIC_UPDATE_CURSOR = 81;
SQL_DIAG_GRANT = 48;
SQL_DIAG_INSERT = 50;
SQL_DIAG_REVOKE = 59;
SQL_DIAG_SELECT_CURSOR = 85;
SQL_DIAG_UNKNOWN_STATEMENT = 0;
SQL_DIAG_UPDATE_WHERE = 82;
// SQL data type codes
SQL_UNKNOWN_TYPE = 0;
SQL_CHAR = 1;
SQL_NUMERIC = 2;
SQL_DECIMAL = 3;
SQL_INTEGER = 4;
SQL_SMALLINT = 5;
SQL_FLOAT = 6;
SQL_REAL = 7;
SQL_DOUBLE = 8;
SQL_DATETIME = 9;
SQL_VARCHAR = 12;
// One-parameter shortcuts for date/time data types
SQL_TYPE_DATE = 91;
SQL_TYPE_TIME = 92;
SQL_TYPE_TIMESTAMP = 93;
// Statement attribute values for cursor sensitivity
SQL_UNSPECIFIED = 0;
SQL_INSENSITIVE = 1;
SQL_SENSITIVE = 2;
// GetTypeInfo() request for all data types
SQL_ALL_TYPES = 0;
// Default conversion code for SQLBindCol(), SQLBindParam() and SQLGetData()
SQL_DEFAULT = 99;
// SQLGetData() code indicating that the application row / param descriptor
// specifies the data type
SQL_ARD_TYPE = -99;
SQL_APD_TYPE = -100;
// SQL date/time type subcodes
SQL_CODE_DATE = 1;
SQL_CODE_TIME = 2;
SQL_CODE_TIMESTAMP = 3;
// CLI option values
SQL_FALSE = 0;
SQL_TRUE = 1;
// Values of NULLABLE field in descriptor
SQL_NO_NULLS = 0;
SQL_NULLABLE = 1;
// Value returned by SQLGetTypeInfo() to denote that it is
// not known whether or not a data type supports null values.
SQL_NULLABLE_UNKNOWN = 2;
// Values returned by SQLGetTypeInfo() to show WHERE clause supported
SQL_PRED_NONE = 0;
SQL_PRED_CHAR = 1;
SQL_PRED_BASIC = 2;
// values of UNNAMED field in descriptor
SQL_NAMED = 0;
SQL_UNNAMED = 1;
// values of ALLOC_TYPE field in descriptor
SQL_DESC_ALLOC_AUTO = 1;
SQL_DESC_ALLOC_USER = 2;
// FreeStmt() options
SQL_CLOSE = 0;
SQL_DROP = 1;
SQL_UNBIND = 2;
SQL_RESET_PARAMS = 3;
// Codes used for FetchOrientation in SQLFetchScroll(), and in SQLDataSources()
SQL_FETCH_NEXT = 1;
SQL_FETCH_FIRST = 2;
// Other codes used for FetchOrientation in SQLFetchScroll()
SQL_FETCH_LAST = 3;
SQL_FETCH_PRIOR = 4;
SQL_FETCH_ABSOLUTE = 5;
SQL_FETCH_RELATIVE = 6;
// SQLEndTran() options
SQL_COMMIT = 0;
SQL_ROLLBACK = 1;
// Null handles returned by SQLAllocHandle()
SQL_NULL_HENV = SQLHandle(0);
SQL_NULL_HDBC = SQLHandle(0);
SQL_NULL_HSTMT = SQLHandle(0);
SQL_NULL_HDESC = SQLHandle(0);
// Null handle used in place of parent handle when allocating HENV
SQL_NULL_HANDLE = SQLHandle(0);
// Values that may appear in the Result set of SQLSpecialColumns()
SQL_SCOPE_CURROW = 0;
SQL_SCOPE_TRANSACTION = 1;
SQL_SCOPE_SESSION = 2;
SQL_PC_UNKNOWN = 0;
SQL_PC_NON_PSEUDO = 1;
SQL_PC_PSEUDO = 2;
// Reserved value for the IdentifierType argument of SQLSpecialColumns()
SQL_ROW_IDENTIFIER = 1;
// Reserved values for UNIQUE argument of SQLStatistics()
SQL_INDEX_UNIQUE = 0;
SQL_INDEX_ALL = 1;
// Values that may appear in the Result set of SQLStatistics()
SQL_INDEX_CLUSTERED = 1;
SQL_INDEX_HASHED = 2;
SQL_INDEX_OTHER = 3;
// SQLGetFunctions() values to identify ODBC APIs
SQL_API_SQLALLOCCONNECT = 1;
SQL_API_SQLALLOCENV = 2;
SQL_API_SQLALLOCHANDLE = 1001;
SQL_API_SQLALLOCSTMT = 3;
SQL_API_SQLBINDCOL = 4;
SQL_API_SQLBINDPARAM = 1002;
SQL_API_SQLCANCEL = 5;
SQL_API_SQLCLOSECURSOR = 1003;
SQL_API_SQLCOLATTRIBUTE = 6;
SQL_API_SQLCOLUMNS = 40;
SQL_API_SQLCONNECT = 7;
SQL_API_SQLCOPYDESC = 1004;
SQL_API_SQLDATASOURCES = 57;
SQL_API_SQLDESCRIBECOL = 8;
SQL_API_SQLDISCONNECT = 9;
SQL_API_SQLENDTRAN = 1005;
SQL_API_SQLERROR = 10;
SQL_API_SQLEXECDIRECT = 11;
SQL_API_SQLEXECUTE = 12;
SQL_API_SQLFETCH = 13;
SQL_API_SQLFETCHSCROLL = 1021;
SQL_API_SQLFREECONNECT = 14;
SQL_API_SQLFREEENV = 15;
SQL_API_SQLFREEHANDLE = 1006;
SQL_API_SQLFREESTMT = 16;
SQL_API_SQLGETCONNECTATTR = 1007;
SQL_API_SQLGETCONNECTOPTION = 42;
SQL_API_SQLGETCURSORNAME = 17;
SQL_API_SQLGETDATA = 43;
SQL_API_SQLGETADSCFIELD = 1008;
SQL_API_SQLGETADSCREC = 1009;
SQL_API_SQLGETDIAGFIELD = 1010;
SQL_API_SQLGETDIAGREC = 1011;
SQL_API_SQLGETENVATTR = 1012;
SQL_API_SQLGETFUNCTIONS = 44;
SQL_API_SQLGETINFO = 45;
SQL_API_SQLGETSTMTATTR = 1014;
SQL_API_SQLGETSTMTOPTION = 46;
SQL_API_SQLGETTYPEINFO = 47;
SQL_API_SQLNUMRESULTCOLS = 18;
SQL_API_SQLPARAMDATA = 48;
SQL_API_SQLPREPARE = 19;
SQL_API_SQLPUTDATA = 49;
SQL_API_SQLROWCOUNT = 20;
SQL_API_SQLSETCONNECTATTR = 1016;
SQL_API_SQLSETCONNECTOPTION = 50;
SQL_API_SQLSETCURSORNAME = 21;
SQL_API_SQLSETADSCFIELD = 1017;
SQL_API_SQLSETADSCREC = 1018;
SQL_API_SQLSETENVATTR = 1019;
SQL_API_SQLSETPARAM = 22;
SQL_API_SQLSETSTMTATTR = 1020;
SQL_API_SQLSETSTMTOPTION = 51;
SQL_API_SQLSPECIALCOLUMNS = 52;
SQL_API_SQLSTATISTICS = 53;
SQL_API_SQLTABLES = 54;
SQL_API_SQLTRANSACT = 23;
SQL_API_SQLCANCELHANDLE = 1022;
// Information requested by SQLGetInfo()
SQL_MAX_DRIVER_CONNECTIONS = 0;
SQL_MAXIMUM_DRIVER_CONNECTIONS = SQL_MAX_DRIVER_CONNECTIONS;
SQL_MAX_CONCURRENT_ACTIVITIES = 1;
SQL_MAXIMUM_CONCURRENT_ACTIVITIES = SQL_MAX_CONCURRENT_ACTIVITIES;
SQL_DATA_SOURCE_NAME = 2;
SQL_FETCH_DIRECTION = 8;
SQL_SERVER_NAME = 13;
SQL_SEARCH_PATTERN_ESCAPE = 14;
SQL_DBMS_NAME = 17;
SQL_DBMS_VER = 18;
SQL_ACCESSIBLE_TABLES = 19;
SQL_ACCESSIBLE_PROCEDURES = 20;
SQL_CURSOR_COMMIT_BEHAVIOR = 23;
SQL_DATA_SOURCE_READ_ONLY = 25;
SQL_DEFAULT_TXN_ISOLATION = 26;
SQL_IDENTIFIER_CASE = 28;
SQL_IDENTIFIER_QUOTE_CHAR = 29;
SQL_MAX_COLUMN_NAME_LEN = 30;
SQL_MAXIMUM_COLUMN_NAME_LENGTH = SQL_MAX_COLUMN_NAME_LEN;
SQL_MAX_CURSOR_NAME_LEN = 31;
SQL_MAXIMUM_CURSOR_NAME_LENGTH = SQL_MAX_CURSOR_NAME_LEN;
SQL_MAX_SCHEMA_NAME_LEN = 32;
SQL_MAXIMUM_SCHEMA_NAME_LENGTH = SQL_MAX_SCHEMA_NAME_LEN;
SQL_MAX_CATALOG_NAME_LEN = 34;
SQL_MAXIMUM_CATALOG_NAME_LENGTH = SQL_MAX_CATALOG_NAME_LEN;
SQL_MAX_TABLE_NAME_LEN = 35;
SQL_SCROLL_CONCURRENCY = 43;
SQL_TXN_CAPABLE = 46;
SQL_TRANSACTION_CAPABLE = SQL_TXN_CAPABLE;
SQL_USER_NAME = 47;
SQL_TXN_ISOLATION_OPTION = 72;
SQL_TRANSACTION_ISOLATION_OPTION = SQL_TXN_ISOLATION_OPTION;
SQL_INTEGRITY = 73;
SQL_GETDATA_EXTENSIONS = 81;
SQL_NULL_COLLATION = 85;
SQL_ALTER_TABLE = 86;
SQL_ORDER_BY_COLUMNS_IN_SELECT = 90;
SQL_SPECIAL_CHARACTERS = 94;
SQL_MAX_COLUMNS_IN_GROUP_BY = 97;
SQL_MAXIMUM_COLUMNS_IN_GROUP_BY = SQL_MAX_COLUMNS_IN_GROUP_BY;
SQL_MAX_COLUMNS_IN_INDEX = 98;
SQL_MAXIMUM_COLUMNS_IN_INDEX = SQL_MAX_COLUMNS_IN_INDEX;
SQL_MAX_COLUMNS_IN_ORDER_BY = 99;
SQL_MAXIMUM_COLUMNS_IN_ORDER_BY = SQL_MAX_COLUMNS_IN_ORDER_BY;
SQL_MAX_COLUMNS_IN_SELECT = 100;
SQL_MAXIMUM_COLUMNS_IN_SELECT = SQL_MAX_COLUMNS_IN_SELECT;
SQL_MAX_COLUMNS_IN_TABLE = 101;
SQL_MAX_INDEX_SIZE = 102;
SQL_MAXIMUM_INDEX_SIZE = SQL_MAX_INDEX_SIZE;
SQL_MAX_ROW_SIZE = 104;
SQL_MAXIMUM_ROW_SIZE = SQL_MAX_ROW_SIZE;
SQL_MAX_STATEMENT_LEN = 105;
SQL_MAXIMUM_STATEMENT_LENGTH = SQL_MAX_STATEMENT_LEN;
SQL_MAX_TABLES_IN_SELECT = 106;
SQL_MAXIMUM_TABLES_IN_SELECT = SQL_MAX_TABLES_IN_SELECT;
SQL_MAX_USER_NAME_LEN = 107;
SQL_MAXIMUM_USER_NAME_LENGTH = SQL_MAX_USER_NAME_LEN;
SQL_OJ_CAPABILITIES = 115;
SQL_OUTER_JOIN_CAPABILITIES = SQL_OJ_CAPABILITIES;
SQL_XOPEN_CLI_YEAR = 10000;
SQL_CURSOR_SENSITIVITY = 10001;
SQL_DESCRIBE_PARAMETER = 10002;
SQL_CATALOG_NAME = 10003;
SQL_COLLATION_SEQ = 10004;
SQL_MAX_IDENTIFIER_LEN = 10005;
SQL_MAXIMUM_IDENTIFIER_LENGTH = SQL_MAX_IDENTIFIER_LEN;
// SQL_ALTER_TABLE bitmasks
SQL_AT_ADD_COLUMN = $00000001;
SQL_AT_DROP_COLUMN = $00000002;
SQL_AT_ADD_CONSTRAINT = $00000008;
// The following bitmasks are ODBC extensions
SQL_AT_COLUMN_SINGLE = $00000020;
SQL_AT_ADD_COLUMN_DEFAULT = $00000040;
SQL_AT_ADD_COLUMN_COLLATION = $00000080;
SQL_AT_SET_COLUMN_DEFAULT = $00000100;
SQL_AT_DROP_COLUMN_DEFAULT = $00000200;
SQL_AT_DROP_COLUMN_CASCADE = $00000400;
SQL_AT_DROP_COLUMN_RESTRICT = $00000800;
SQL_AT_ADD_TABLE_CONSTRAINT = $00001000;
SQL_AT_DROP_TABLE_CONSTRAINT_CASCADE = $00002000;
SQL_AT_DROP_TABLE_CONSTRAINT_RESTRICT = $00004000;
SQL_AT_CONSTRAINT_NAME_DEFINITION = $00008000;
SQL_AT_CONSTRAINT_INITIALLY_DEFERRED = $00010000;
SQL_AT_CONSTRAINT_INITIALLY_IMMEDIATE = $00020000;
SQL_AT_CONSTRAINT_DEFERRABLE = $00040000;
SQL_AT_CONSTRAINT_NON_DEFERRABLE = $00080000;
// SQL_ASYNC_MODE values
SQL_AM_NONE = 0;
SQL_AM_CONNECTION = 1;
SQL_AM_STATEMENT = 2;
// SQL_CURSOR_COMMIT_BEHAVIOR values
SQL_CB_DELETE = 0;
SQL_CB_CLOSE = 1;
SQL_CB_PRESERVE = 2;
// SQL_FETCH_DIRECTION bitmasks
SQL_FD_FETCH_NEXT = $00000001;
SQL_FD_FETCH_FIRST = $00000002;
SQL_FD_FETCH_LAST = $00000004;
SQL_FD_FETCH_PRIOR = $00000008;
SQL_FD_FETCH_ABSOLUTE = $00000010;
SQL_FD_FETCH_RELATIVE = $00000020;
// SQL_GETDATA_EXTENSIONS bitmasks
SQL_GD_ANY_COLUMN = $00000001;
SQL_GD_ANY_ORDER = $00000002;
// SQL_IDENTIFIER_CASE values
SQL_IC_UPPER = 1;
SQL_IC_LOWER = 2;
SQL_IC_SENSITIVE = 3;
SQL_IC_MIXED = 4;
// SQL_OJ_CAPABILITIES bitmasks
// NB: this means 'outer join', not what you may be thinking
SQL_OJ_LEFT = $00000001;
SQL_OJ_RIGHT = $00000002;
SQL_OJ_FULL = $00000004;
SQL_OJ_NESTED = $00000008;
SQL_OJ_NOT_ORDERED = $00000010;
SQL_OJ_INNER = $00000020;
SQL_OJ_ALL_COMPARISON_OPS = $00000040;
// SQL_SCROLL_CONCURRENCY bitmasks
SQL_SCCO_READ_ONLY = $00000001;
SQL_SCCO_LOCK = $00000002;
SQL_SCCO_OPT_ROWVER = $00000004;
SQL_SCCO_OPT_VALUES = $00000008;
// SQL_TXN_CAPABLE values
SQL_TC_NONE = 0;
SQL_TC_DML = 1;
SQL_TC_ALL = 2;
SQL_TC_DDL_COMMIT = 3;
SQL_TC_DDL_IGNORE = 4;
// SQL_TXN_ISOLATION_OPTION bitmasks
SQL_TXN_READ_UNCOMMITTED = $00000001;
SQL_TRANSACTION_READ_UNCOMMITTED = SQL_TXN_READ_UNCOMMITTED;
SQL_TXN_READ_COMMITTED = $00000002;
SQL_TRANSACTION_READ_COMMITTED = SQL_TXN_READ_COMMITTED;
SQL_TXN_REPEATABLE_READ = $00000004;
SQL_TRANSACTION_REPEATABLE_READ = SQL_TXN_REPEATABLE_READ;
SQL_TXN_SERIALIZABLE = $00000008;
SQL_TRANSACTION_SERIALIZABLE = SQL_TXN_SERIALIZABLE;
// SQL_NULL_COLLATION values
SQL_NC_HIGH = 0;
SQL_NC_LOW = 1;
const
SQL_INTERVAL_COLSIZE = 28;
type
// Deprecated
TSQLAllocConnect = function(
EnvironmentHandle: SQLHEnv;
var ConnectionHandle: SQLHDbc
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// Deprecated
TSQLAllocEnv = function(
var EnvironmentHandle: SQLHEnv
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLAllocHandle = function(
HandleType: SQLSmallint;
InputHandle: SQLHandle;
var OutputHandle: SQLHandle
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// Deprecated
TSQLAllocStmt = function(
ConnectionHandle: SQLHDbc;
var StatementHandle: SQLHStmt
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLBindCol = function(
StatementHandle: SQLHStmt;
ColumnNumber: SQLUSmallint;
TargetType: SQLSmallint;
TargetValue: SQLPointer;
BufferLength: SQLLen;
StrLen_or_Ind: PSQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLBindParam = function(
StatementHandle: SQLHStmt;
ParameterNumber: SQLUSmallint;
ValueType: SQLSmallint;
ParameterType: SQLSmallint;
LengthPrecision: SQLULen;
ParameterScale: SQLSmallint;
ParameterValue: SQLPointer;
var StrLen_or_Ind: SQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLCancel = function(
StatementHandle: SQLHStmt
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLCancelHandle = function(
HandleType: SQLSmallint;
InputHandle: SQLHandle
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLCloseCursor = function(
StatementHandle: SQLHStmt
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// SQLColAttribute is overloaded
TSQLColAttribute = function(
StatementHandle: SQLHStmt;
ColumnNumber: SQLUSmallint;
FieldIdentifier: SQLUSmallint;
CharacterAttribute: SQLPointer;
BufferLength: SQLSmallint;
StringLength: PSQLSmallint;
NumericAttributePtr: PSQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// Overloaded version for String attributes
TSQLColAttributeString = function(
StatementHandle: SQLHStmt;
ColumnNumber: SQLUSmallint;
FieldIdentifier: SQLUSmallint;
CharacterAttribute: SQLPointer;
BufferLength: SQLSmallint;
var StringLength: SQLSmallint;
NumericAttribute: PSQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// Overloaded version for Integer attributes
TSQLColAttributeInt = function(
StatementHandle: SQLHStmt;
ColumnNumber: SQLUSmallint;
FieldIdentifier: SQLUSmallint;
CharacterAttribute: SQLPointer;
BufferLength: SQLSmallint;
StringLength: PSQLSmallint;
var NumericAttribute: SQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLColumns = function(
StatementHandle: SQLHStmt;
CatalogName: PSQLChar;
NameLength1: SQLSmallint;
SchemaName: PSQLChar;
NameLength2: SQLSmallint;
TableName: PSQLChar;
NameLength3: SQLSmallint;
ColumnName: PSQLChar;
NameLength4: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLConnect = function(
ConnectionHandle: SQLHDbc;
ServerName: PSQLChar;
NameLength1: SQLSmallint;
UserName: PSQLChar;
NameLength2: SQLSmallint;
Authentication: PSQLChar;
NameLength3: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLCopyDesc = function(
SourceDescHandle: SQLHDesc;
TargetDescHandle: SQLHDesc
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLDataSources = function(
EnvironmentHandle: SQLHEnv;
Direction: SQLUSmallint;
ServerName: PSQLChar;
BufferLength1: SQLSmallint;
var NameLength1: SQLSmallint;
Description: PSQLChar;
BufferLength2: SQLSmallint;
var NameLength2: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLDescribeCol = function(
StatementHandle: SQLHStmt;
ColumnNumber: SQLUSmallint;
ColumnName: PSQLChar;
BufferLength: SQLSmallint;
var NameLength: SQLSmallint;
var DataType: SQLSmallint;
var ColumnSize: SQLULen;
var DecimalDigits: SQLSmallint;
var Nullable: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLDisconnect = function(
ConnectionHandle: SQLHDbc
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLEndTran = function(
HandleType: SQLSmallint;
Handle: SQLHandle;
CompletionType: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// Deprecated
TSQLError = function(
EnvironmentHandle: SQLHEnv;
ConnectionHandle: SQLHDbc;
StatementHandle: SQLHStmt;
var SQLstate: SQLChar;
var NativeError: SQLInteger;
var MessageText: SQLChar;
BufferLength: SQLSmallint;
var TextLength: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLExecDirect = function(
StatementHandle: SQLHStmt;
StatementText: PSQLChar;
TextLength: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLExecute = function(
StatementHandle: SQLHStmt
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLFetch = function(
StatementHandle: SQLHStmt
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLFetchScroll = function(
StatementHandle: SQLHStmt;
FetchOrientation: SQLSmallint;
FetchOffset: SQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// Deprecated
TSQLFreeConnect = function(
ConnectionHandle: SQLHDbc
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// Deprecated
TSQLFreeEnv = function(
EnvironmentHandle: SQLHEnv
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLFreeHandle = function(
HandleType: SQLSmallint;
Handle: SQLHandle
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// Deprecated
TSQLFreeStmt = function(
StatementHandle: SQLHStmt;
Option: SQLUSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// SQLGetConnectAttr is overloaded. See OBDC API doc:
// "Depending on the value of Attribute,
// ValuePtr will be a 32-bit unsigned integer value
// or will point to a null-terminated character string."
TSQLGetConnectAttr = function(
ConnectionHandle: SQLHDbc;
Attribute: SQLInteger;
ValuePtr: SQLPointer;
BufferLength: SQLInteger;
var StringLength: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetConnectOption = function(
ConnectionHandle: SQLHDbc;
Option: SQLUSmallint;
Value: SQLPointer
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetCursorName = function(
StatementHandle: SQLHStmt;
CursorName: PSQLChar;
BufferLength: SQLSmallint;
var NameLength: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetData = function(
StatementHandle: SQLHStmt;
ColumnNumber: SQLUSmallint;
TargetType: SQLSmallint;
TargetValue: SQLPointer;
BufferLength: SQLLen;
StrLen_or_Ind: PSQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetDescField = function(
DescriptorHandle: SQLHDesc;
RecNumber: SQLSmallint;
FieldIdentifier: SQLSmallint;
Value: SQLPointer;
BufferLength: SQLInteger;
var StringLength: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetDescRec = function(
DescriptorHandle: SQLHDesc;
RecNumber: SQLSmallint;
var Name: SQLChar;
BufferLength: SQLSmallint;
var StringLength: SQLSmallint;
var _Type: SQLSmallint;
var SubType: SQLSmallint;
var Length: SQLLen;
var Precision: SQLSmallint;
var Scale: SQLSmallint;
var Nullable: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetDiagField = function(
HandleType: SQLSmallint;
Handle: SQLHandle;
RecNumber: SQLSmallint;
DiagIdentifier: SQLSmallint;
DiagInfo: SQLPointer;
BufferLength: SQLSmallint;
var StringLength: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetDiagRec = function(
HandleType: SQLSmallint;
Handle: SQLHandle;
RecNumber: SQLSmallint;
SQLstate: PSQLChar; // pointer to 5 character buffer
var NativeError: SQLInteger;
MessageText: PSQLChar;
BufferLength: SQLSmallint;
var TextLength: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetEnvAttr = function(
EnvironmentHandle: SQLHEnv;
Attribute: SQLInteger;
Value: SQLPointer;
BufferLength: SQLInteger;
var StringLength: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetFunctions = function(
ConnectionHandle: SQLHDbc;
FunctionId: SQLUSmallint;
var Supported: SQLUSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// SQLGetInfo is overloaded. See OBDC API doc:
// "Depending on the InfoType requested,
// the information returned will be one of the following:
// a null-terminated character string,
// an SQLUSMALLINT value,
// an SQLUINTEGER bitmask,
// an SQLUINTEGER flag,
// or a SQLUINTEGER binary value."
TSQLGetInfo = function(
ConnectionHandle: SQLHDbc;
InfoType: SQLUSmallint;
InfoValuePtr: SQLPointer;
BufferLength: SQLSmallint;
StringLengthPtr: SQLPointer
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetInfoString = function(
ConnectionHandle: SQLHDbc;
InfoType: SQLUSmallint;
InfoValueString: PSQLChar; // PSQLWChar when calling SQLGetInfoW
BufferLength: SQLSmallint;
var StringLength: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetInfoSmallint = function(
ConnectionHandle: SQLHDbc;
InfoType: SQLUSmallint;
var InfoValue: SQLUSmallint;
Ignored1: SQLSmallint; // It seems to be a SizeOf(SQLSmallint)
Ignored2: SQLPointer
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetInfoInt = function(
ConnectionHandle: SQLHDbc;
InfoType: SQLUSmallint;
var InfoValue: SQLUInteger;
Ignored1: SQLSmallint; // It seems to be a SizeOf(SQLInteger)
Ignored2: SQLPointer
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetInfoSQLLen = function(
ConnectionHandle: SQLHDbc;
InfoType: SQLUSmallint;
var InfoValue: SQLULen;
Ignored1: SQLSmallint; // It seems to be a SizeOf(SQLLen)
Ignored2: SQLPointer
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetStmtAttr = function(
StatementHandle: SQLHStmt;
Attribute: SQLInteger;
Value: SQLPointer;
BufferLength: SQLInteger;
var StringLength: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetStmtOption = function(
StatementHandle: SQLHStmt;
Option: SQLUSmallint;
Value: SQLPointer
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLGetTypeInfo = function(
StatementHandle: SQLHStmt;
DataType: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLNumResultCols = function(
StatementHandle: SQLHStmt;
var ColumnCount: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLParamData = function(
StatementHandle: SQLHStmt;
var Value: SQLPointer
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLPrepare = function(
StatementHandle: SQLHStmt;
StatementText: PSQLChar;
TextLength: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLPutData = function(
StatementHandle: SQLHStmt;
Data: SQLPointer;
StrLen_or_Ind: SQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLRowCount = function(
StatementHandle: SQLHStmt;
var RowCount: SQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLSetConnectAttr = function(
ConnectionHandle: SQLHDbc;
Attribute: SQLInteger;
ValuePtr: SQLPointer;
StringLength: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLSetConnectOption = function(
ConnectionHandle: SQLHDbc;
Option: SQLUSmallint;
Value: SQLULen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLSetCursorName = function(
StatementHandle: SQLHStmt;
CursorName: PSQLChar;
NameLength: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLSetDescField = function(
DescriptorHandle: SQLHDesc;
RecNumber: SQLSmallint;
FieldIdentifier: SQLSmallint;
Value: SQLPointer;
BufferLength: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLSetDescRec = function(
DescriptorHandle: SQLHDesc;
RecNumber: SQLSmallint;
_Type: SQLSmallint;
SubType: SQLSmallint;
Length: SQLLen;
Precision: SQLSmallint;
Scale: SQLSmallint;
Data: SQLPointer;
var StringLength: SQLLen;
var Indicator: SQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// SQLSetEnvAttr is overloaded. See OBDC API doc:
// "Depending on the value of Attribute,
// value will be a 32-bit integer value
// or point to a null-terminated character string."
TSQLSetEnvAttr = function(
EnvironmentHandle: SQLHEnv;
Attribute: SQLInteger;
ValuePtr: SQLPointer;
StringLength: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLSetParam = function(
StatementHandle: SQLHStmt;
ParameterNumber: SQLUSmallint;
ValueType: SQLSmallint;
ParameterType: SQLSmallint;
LengthPrecision: SQLULen;
ParameterScale: SQLSmallint;
ParameterValue: SQLPointer;
var StrLen_or_Ind: SQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLSetStmtAttr = function(
StatementHandle: SQLHStmt;
Attribute: SQLInteger;
Value: SQLPointer;
StringLength: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLSetStmtOption = function(
StatementHandle: SQLHStmt;
Option: SQLUSmallint;
Value: SQLULen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLSpecialColumns = function(
StatementHandle: SQLHStmt;
IdentifierType: SQLUSmallint;
CatalogName: PSQLChar;
NameLength1: SQLSmallint;
SchemaName: PSQLChar;
NameLength2: SQLSmallint;
TableName: PSQLChar;
NameLength3: SQLSmallint;
Scope: SQLUSmallint;
Nullable: SQLUSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLStatistics = function(
StatementHandle: SQLHStmt;
CatalogName: PSQLChar;
NameLength1: SQLSmallint;
SchemaName: PSQLChar;
NameLength2: SQLSmallint;
TableName: PSQLChar;
NameLength3: SQLSmallint;
Unique: SQLUSmallint;
Reserved: SQLUSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLTables = function(
StatementHandle: SQLHStmt;
CatalogName: PSQLChar;
NameLength1: SQLSmallint;
SchemaName: PSQLChar;
NameLength2: SQLSmallint;
TableName: PSQLChar;
NameLength3: SQLSmallint;
TableType: PSQLChar;
NameLength4: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLTransact = function(
EnvironmentHandle: SQLHEnv;
ConnectionHandle: SQLHDbc;
CompletionType: SQLUSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
{----------------------------------------------------------------------------}
{ SQLEXT.H }
{----------------------------------------------------------------------------}
const
// Generally useful constants
SQL_SPEC_MAJOR = 3; // Major version of specification
SQL_SPEC_MINOR = 51; // Minor version of specification
SQL_SPEC_STRING = '03.51'; // String constant for version
SQL_SQLSTATE_SIZE = 5;
type
TSQLState = array[0 .. SQL_SQLSTATE_SIZE + 1] of SQLTChar;
PSQLState = PSQLChar;
const
SQL_MAX_DSN_LENGTH = 32; // Maximum data source name size
SQL_MAX_OPTION_STRING_LENGTH = 256;
// Return code SQL_NO_DATA_FOUND is the same as SQL_NO_DATA
SQL_NO_DATA_FOUND = SQL_NO_DATA;
// An env handle type
SQL_HANDLE_SENV = 5;
// Environment attributes
SQL_ATTR_ODBC_VERSION = 200;
SQL_ATTR_CONNECTION_POOLING = 201;
SQL_ATTR_CP_MATCH = 202;
// Values for SQL_ATTR_CONNECTION_POOLING
SQL_CP_OFF = ULong(0);
SQL_CP_ONE_PER_DRIVER = ULong(1);
SQL_CP_ONE_PER_HENV = ULong(2);
SQL_CP_DEFAULT = SQL_CP_OFF;
// Values for SQL_ATTR_CP_MATCH
SQL_CP_STRICT_MATCH = ULong(0);
SQL_CP_RELAXED_MATCH = ULong(1);
SQL_CP_MATCH_DEFAULT = SQL_CP_STRICT_MATCH;
// Values for SQL_ATTR_ODBC_VERSION
SQL_OV_ODBC2 = ULong(2);
SQL_OV_ODBC3 = ULong(3);
SQL_OV_ODBC3_80 = ULong(380);
// Connection attributes
SQL_ACCESS_MODE = 101;
SQL_AUTOCOMMIT = 102;
SQL_LOGIN_TIMEOUT = 103;
SQL_OPT_TRACE = 104;
SQL_OPT_TRACEFILE = 105;
SQL_TRANSLATE_DLL = 106;
SQL_TRANSLATE_OPTION = 107;
SQL_TXN_ISOLATION = 108;
SQL_CURRENT_QUALIFIER = 109;
SQL_ODBC_CURSORS = 110;
SQL_QUIET_MODE = 111;
SQL_PACKET_SIZE = 112;
// Connection attributes with new names
SQL_ATTR_ACCESS_MODE = SQL_ACCESS_MODE;
SQL_ATTR_AUTOCOMMIT = SQL_AUTOCOMMIT;
SQL_ATTR_CONNECTION_TIMEOUT = 113;
SQL_ATTR_CURRENT_CATALOG = SQL_CURRENT_QUALIFIER;
SQL_ATTR_DISCONNECT_BEHAVIOR = 114;
SQL_ATTR_ENLIST_IN_DTC = 1207;
SQL_ATTR_ENLIST_IN_XA = 1208;
SQL_ATTR_LOGIN_TIMEOUT = SQL_LOGIN_TIMEOUT;
SQL_ATTR_ODBC_CURSORS = SQL_ODBC_CURSORS;
SQL_ATTR_PACKET_SIZE = SQL_PACKET_SIZE;
SQL_ATTR_QUIET_MODE = SQL_QUIET_MODE;
SQL_ATTR_TRACE = SQL_OPT_TRACE;
SQL_ATTR_TRACEFILE = SQL_OPT_TRACEFILE;
SQL_ATTR_TRANSLATE_LIB = SQL_TRANSLATE_DLL;
SQL_ATTR_TRANSLATE_OPTION = SQL_TRANSLATE_OPTION;
SQL_ATTR_TXN_ISOLATION = SQL_TXN_ISOLATION;
SQL_ATTR_CONNECTION_DEAD = 1209; // GetConnectAttr only
{ ODBC Driver Manager sets this connection attribute to an unicode driver
(which supports SQLConnectW) when the application is an ANSI application
(which calls SQLConnect, SQLDriverConnect, or SQLBrowseConnect).
This is SetConnectAttr only and application does not set this attribute
This attribute was introduced because some unicode driver's some APIs may
need to behave differently on ANSI or Unicode applications. A unicode
driver, which has same behavior for both ANSI or Unicode applications,
should return SQL_ERROR when the driver manager sets this connection
attribute. When a unicode driver returns SQL_SUCCESS on this attribute,
the driver manager treates ANSI and Unicode connections differently in
connection pooling. }
SQL_ATTR_ANSI_APP = 115;
SQL_ATTR_RESET_CONNECTION = 116;
SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE = 117;
// SQL_CONNECT_OPT_DRVR_START is not meaningful for 3.0 driver
SQL_CONNECT_OPT_DRVR_START = 1000;
SQL_CONN_OPT_MAX = SQL_PACKET_SIZE;
SQL_CONN_OPT_MIN = SQL_ACCESS_MODE;
// SQL_ACCESS_MODE options
SQL_MODE_READ_WRITE = ULong(0);
SQL_MODE_READ_ONLY = ULong(1);
SQL_MODE_DEFAULT = SQL_MODE_READ_WRITE;
// SQL_AUTOCOMMIT options
SQL_AUTOCOMMIT_OFF = ULong(0);
SQL_AUTOCOMMIT_ON = ULong(1);
SQL_AUTOCOMMIT_DEFAULT = SQL_AUTOCOMMIT_ON;
// SQL_LOGIN_TIMEOUT options
SQL_LOGIN_TIMEOUT_DEFAULT = ULong(15);
// SQL_OPT_TRACE options
SQL_OPT_TRACE_OFF = ULong(0);
SQL_OPT_TRACE_ON = ULong(1);
SQL_OPT_TRACE_DEFAULT = SQL_OPT_TRACE_OFF;
SQL_OPT_TRACE_FILE_DEFAULT = '\SQL.LOG';
// SQL_ODBC_CURSORS options
SQL_CUR_USE_IF_NEEDED = ULong(0);
SQL_CUR_USE_ODBC = ULong(1);
SQL_CUR_USE_DRIVER = ULong(2);
SQL_CUR_DEFAULT = SQL_CUR_USE_DRIVER;
// Values for SQL_ATTR_DISCONNECT_BEHAVIOR
SQL_DB_RETURN_TO_POOL = ULong(0);
SQL_DB_DISCONNECT = ULong(1);
SQL_DB_DEFAULT = SQL_DB_RETURN_TO_POOL;
// Values for SQL_ATTR_ENLIST_IN_DTC
SQL_DTC_DONE = 0;
// Values for SQL_ATTR_CONNECTION_DEAD
SQL_CD_TRUE = 1; // Connection is closed/dead
SQL_CD_FALSE = 0; // Connection is open/available
// Values for SQL_ATTR_ANSI_APP
SQL_AA_TRUE = 1; // the application is an ANSI app
SQL_AA_FALSE = 0; // the application is a Unicode app
// values for SQL_ATTR_RESET_CONNECTION
SQL_RESET_CONNECTION_YES = ULong(1);
// values for SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE
SQL_ASYNC_DBC_ENABLE_ON = ULong(1);
SQL_ASYNC_DBC_ENABLE_OFF = ULong(0);
SQL_ASYNC_DBC_ENABLE_DEFAULT = SQL_ASYNC_DBC_ENABLE_OFF;
// statement attributes
SQL_QUERY_TIMEOUT = 0;
SQL_MAX_ROWS = 1;
SQL_NOSCAN = 2;
SQL_MAX_LENGTH = 3;
SQL_ASYNC_ENABLE = 4; // Same as SQL_ATTR_ASYNC_ENABLE
SQL_BIND_TYPE = 5;
SQL_CURSOR_TYPE = 6;
SQL_CONCURRENCY = 7;
SQL_KEYSET_SIZE = 8;
SQL_ROWSET_SIZE = 9;
SQL_SIMULATE_CURSOR = 10;
SQL_RETRIEVE_DATA = 11;
SQL_USE_BOOKMARKS = 12;
SQL_GET_BOOKMARK = 13; // GetStmtOption Only
SQL_ROW_NUMBER = 14; // GetStmtOption Only
// statement attributes for ODBC 3.0
SQL_ATTR_ASYNC_ENABLE = 4;
SQL_ATTR_CONCURRENCY = SQL_CONCURRENCY;
SQL_ATTR_CURSOR_TYPE = SQL_CURSOR_TYPE;
SQL_ATTR_ENABLE_AUTO_IPD = 15;
SQL_ATTR_FETCH_BOOKMARK_PTR = 16;
SQL_ATTR_KEYSET_SIZE = SQL_KEYSET_SIZE;
SQL_ATTR_MAX_LENGTH = SQL_MAX_LENGTH;
SQL_ATTR_MAX_ROWS = SQL_MAX_ROWS;
SQL_ATTR_NOSCAN = SQL_NOSCAN;
SQL_ATTR_PARAM_BIND_OFFSET_PTR = 17;
SQL_ATTR_PARAM_BIND_TYPE = 18;
SQL_ATTR_PARAM_OPERATION_PTR = 19;
SQL_ATTR_PARAM_STATUS_PTR = 20;
SQL_ATTR_PARAMS_PROCESSED_PTR = 21;
SQL_ATTR_PARAMSET_SIZE = 22;
SQL_ATTR_QUERY_TIMEOUT = SQL_QUERY_TIMEOUT;
SQL_ATTR_RETRIEVE_DATA = SQL_RETRIEVE_DATA;
SQL_ATTR_ROW_BIND_OFFSET_PTR = 23;
SQL_ATTR_ROW_BIND_TYPE = SQL_BIND_TYPE;
SQL_ATTR_ROW_NUMBER = SQL_ROW_NUMBER; // GetStmtAttr
SQL_ATTR_ROW_OPERATION_PTR = 24;
SQL_ATTR_ROW_STATUS_PTR = 25;
SQL_ATTR_ROWS_FETCHED_PTR = 26;
SQL_ATTR_ROW_ARRAY_SIZE = 27;
SQL_ATTR_SIMULATE_CURSOR = SQL_SIMULATE_CURSOR;
SQL_ATTR_USE_BOOKMARKS = SQL_USE_BOOKMARKS;
// Whether an attribute is a pointer or not
SQL_IS_POINTER = -4;
SQL_IS_UINTEGER = -5;
SQL_IS_INTEGER = -6;
SQL_IS_USMALLINT = -7;
SQL_IS_SMALLINT = -8;
// The value of SQL_ATTR_PARAM_BIND_TYPE
SQL_PARAM_BIND_BY_COLUMN = ULong(0);
SQL_PARAM_BIND_TYPE_DEFAULT = SQL_PARAM_BIND_BY_COLUMN;
// SQL_QUERY_TIMEOUT options
SQL_QUERY_TIMEOUT_DEFAULT = ULong(0);
// SQL_MAX_ROWS options
SQL_MAX_ROWS_DEFAULT = ULong(0);
// SQL_NOSCAN options
SQL_NOSCAN_OFF = ULong(0); // 1.0 FALSE
SQL_NOSCAN_ON = ULong(1); // 1.0 TRUE
SQL_NOSCAN_DEFAULT = SQL_NOSCAN_OFF;
// SQL_MAX_LENGTH options
SQL_MAX_LENGTH_DEFAULT = ULong(0);
// Values for SQL_ATTR_ASYNC_ENABLE
SQL_ASYNC_ENABLE_OFF = ULong(0);
SQL_ASYNC_ENABLE_ON = ULong(1);
SQL_ASYNC_ENABLE_DEFAULT = SQL_ASYNC_ENABLE_OFF;
// SQL_BIND_TYPE options
SQL_BIND_BY_COLUMN = ULong(0);
SQL_BIND_TYPE_DEFAULT = SQL_BIND_BY_COLUMN; // Default value
// SQL_CONCURRENCY options
SQL_CONCUR_READ_ONLY = 1;
SQL_CONCUR_LOCK = 2;
SQL_CONCUR_ROWVER = 3;
SQL_CONCUR_VALUES = 4;
SQL_CONCUR_DEFAULT = SQL_CONCUR_READ_ONLY; // Default value
// SQL_CURSOR_TYPE options
SQL_CURSOR_FORWARD_ONLY = ULong(0);
SQL_CURSOR_KEYSET_DRIVEN = ULong(1);
SQL_CURSOR_DYNAMIC = ULong(2);
SQL_CURSOR_STATIC = ULong(3);
SQL_CURSOR_TYPE_DEFAULT = SQL_CURSOR_FORWARD_ONLY; // Default value
// SQL_ROWSET_SIZE options
SQL_ROWSET_SIZE_DEFAULT = ULong(1);
// SQL_KEYSET_SIZE options
SQL_KEYSET_SIZE_DEFAULT = ULong(0);
// SQL_SIMULATE_CURSOR options
SQL_SC_NON_UNIQUE = ULong(0);
SQL_SC_TRY_UNIQUE = ULong(1);
SQL_SC_UNIQUE = ULong(2);
// SQL_RETRIEVE_DATA options
SQL_RD_OFF = ULong(0);
SQL_RD_ON = ULong(1);
SQL_RD_DEFAULT = SQL_RD_ON;
// SQL_USE_BOOKMARKS options
SQL_UB_OFF = ULong(0);
SQL_UB_ON = ULong(1);
SQL_UB_DEFAULT = SQL_UB_OFF;
// New values for SQL_USE_BOOKMARKS attribute
SQL_UB_FIXED = SQL_UB_ON;
SQL_UB_VARIABLE = ULong(2);
// SQLColAttributes defines
SQL_COLUMN_COUNT = 0;
SQL_COLUMN_NAME = 1;
SQL_COLUMN_TYPE = 2;
SQL_COLUMN_LENGTH = 3;
SQL_COLUMN_PRECISION = 4;
SQL_COLUMN_SCALE = 5;
SQL_COLUMN_DISPLAY_SIZE = 6;
SQL_COLUMN_NULLABLE = 7;
SQL_COLUMN_UNSIGNED = 8;
SQL_COLUMN_MONEY = 9;
SQL_COLUMN_UPDATABLE = 10;
SQL_COLUMN_AUTO_INCREMENT = 11;
SQL_COLUMN_CASE_SENSITIVE = 12;
SQL_COLUMN_SEARCHABLE = 13;
SQL_COLUMN_TYPE_NAME = 14;
SQL_COLUMN_TABLE_NAME = 15;
SQL_COLUMN_OWNER_NAME = 16;
SQL_COLUMN_QUALIFIER_NAME = 17;
SQL_COLUMN_LABEL = 18;
// Extended descriptor field
SQL_DESC_ARRAY_SIZE = 20;
SQL_DESC_ARRAY_STATUS_PTR = 21;
SQL_DESC_AUTO_UNIQUE_VALUE = SQL_COLUMN_AUTO_INCREMENT;
SQL_DESC_BASE_COLUMN_NAME = 22;
SQL_DESC_BASE_TABLE_NAME = 23;
SQL_DESC_BIND_OFFSET_PTR = 24;
SQL_DESC_BIND_TYPE = 25;
SQL_DESC_CASE_SENSITIVE = SQL_COLUMN_CASE_SENSITIVE;
SQL_DESC_CATALOG_NAME = SQL_COLUMN_QUALIFIER_NAME;
SQL_DESC_CONCISE_TYPE = SQL_COLUMN_TYPE;
SQL_DESC_DATETIME_INTERVAL_PRECISION = 26;
SQL_DESC_DISPLAY_SIZE = SQL_COLUMN_DISPLAY_SIZE;
SQL_DESC_FIXED_PREC_SCALE = SQL_COLUMN_MONEY;
SQL_DESC_LABEL = SQL_COLUMN_LABEL;
SQL_DESC_LITERAL_PREFIX = 27;
SQL_DESC_LITERAL_SUFFIX = 28;
SQL_DESC_LOCAL_TYPE_NAME = 29;
SQL_DESC_MAXIMUM_SCALE = 30;
SQL_DESC_MINIMUM_SCALE = 31;
SQL_DESC_NUM_PREC_RADIX = 32;
SQL_DESC_PARAMETER_TYPE = 33;
SQL_DESC_ROWS_PROCESSED_PTR = 34;
SQL_DESC_ROWVER = 35;
SQL_DESC_SCHEMA_NAME = SQL_COLUMN_OWNER_NAME;
SQL_DESC_SEARCHABLE = SQL_COLUMN_SEARCHABLE;
SQL_DESC_TYPE_NAME = SQL_COLUMN_TYPE_NAME;
SQL_DESC_TABLE_NAME = SQL_COLUMN_TABLE_NAME;
SQL_DESC_UNSIGNED = SQL_COLUMN_UNSIGNED;
SQL_DESC_UPDATABLE = SQL_COLUMN_UPDATABLE;
// Defines for diagnostics fields
SQL_DIAG_CURSOR_ROW_COUNT = -1249;
SQL_DIAG_ROW_NUMBER = -1248;
SQL_DIAG_COLUMN_NUMBER = -1247;
// SQL extended datatypes
SQL_DATE = 9;
SQL_INTERVAL = 10;
SQL_TIME = 10;
SQL_TIMESTAMP = 11;
SQL_LONGVARCHAR = -1;
SQL_BINARY = -2;
SQL_VARBINARY = -3;
SQL_LONGVARBINARY = -4;
SQL_BIGINT = -5;
SQL_TINYINT = -6;
SQL_BIT = -7;
SQL_GUID = -11;
SQL_WCHAR = -8;
SQL_WVARCHAR = -9;
SQL_WLONGVARCHAR = -10;
// Interval code
SQL_CODE_YEAR = 1;
SQL_CODE_MONTH = 2;
SQL_CODE_DAY = 3;
SQL_CODE_HOUR = 4;
SQL_CODE_MINUTE = 5;
SQL_CODE_SECOND = 6;
SQL_CODE_YEAR_TO_MONTH = 7;
SQL_CODE_DAY_TO_HOUR = 8;
SQL_CODE_DAY_TO_MINUTE = 9;
SQL_CODE_DAY_TO_SECOND = 10;
SQL_CODE_HOUR_TO_MINUTE = 11;
SQL_CODE_HOUR_TO_SECOND = 12;
SQL_CODE_MINUTE_TO_SECOND = 13;
SQL_INTERVAL_YEAR = (100 + SQL_CODE_YEAR);
SQL_INTERVAL_MONTH = (100 + SQL_CODE_MONTH);
SQL_INTERVAL_DAY = (100 + SQL_CODE_DAY);
SQL_INTERVAL_HOUR = (100 + SQL_CODE_HOUR);
SQL_INTERVAL_MINUTE = (100 + SQL_CODE_MINUTE);
SQL_INTERVAL_SECOND = (100 + SQL_CODE_SECOND);
SQL_INTERVAL_YEAR_TO_MONTH = (100 + SQL_CODE_YEAR_TO_MONTH);
SQL_INTERVAL_DAY_TO_HOUR = (100 + SQL_CODE_DAY_TO_HOUR);
SQL_INTERVAL_DAY_TO_MINUTE = (100 + SQL_CODE_DAY_TO_MINUTE);
SQL_INTERVAL_DAY_TO_SECOND = (100 + SQL_CODE_DAY_TO_SECOND);
SQL_INTERVAL_HOUR_TO_MINUTE = (100 + SQL_CODE_HOUR_TO_MINUTE);
SQL_INTERVAL_HOUR_TO_SECOND = (100 + SQL_CODE_HOUR_TO_SECOND);
SQL_INTERVAL_MINUTE_TO_SECOND = (100 + SQL_CODE_MINUTE_TO_SECOND);
// The previous definitions for SQL_UNICODE_ are historical and obsolete
SQL_UNICODE = SQL_WCHAR;
SQL_UNICODE_VARCHAR = SQL_WVARCHAR;
SQL_UNICODE_LONGVARCHAR = SQL_WLONGVARCHAR;
SQL_UNICODE_CHAR = SQL_WCHAR;
// C datatype to SQL datatype mapping SQL types
SQL_C_CHAR = SQL_CHAR; // CHAR, VARCHAR, DECIMAL, NUMERIC
SQL_C_WCHAR = SQL_WCHAR;
SQL_C_LONG = SQL_INTEGER; // INTEGER
SQL_C_SHORT = SQL_SMALLINT; // SMALLINT
SQL_C_FLOAT = SQL_REAL; // REAL
SQL_C_DOUBLE = SQL_DOUBLE; // FLOAT, DOUBLE
SQL_C_NUMERIC = SQL_NUMERIC;
SQL_C_DEFAULT = 99;
SQL_SIGNED_OFFSET = -20;
SQL_UNSIGNED_OFFSET = -22;
// C datatype to SQL datatype mapping
SQL_C_DATE = SQL_DATE;
SQL_C_TIME = SQL_TIME;
SQL_C_TIMESTAMP = SQL_TIMESTAMP;
SQL_C_TYPE_DATE = SQL_TYPE_DATE;
SQL_C_TYPE_TIME = SQL_TYPE_TIME;
SQL_C_TYPE_TIMESTAMP = SQL_TYPE_TIMESTAMP;
SQL_C_INTERVAL_YEAR = SQL_INTERVAL_YEAR;
SQL_C_INTERVAL_MONTH = SQL_INTERVAL_MONTH;
SQL_C_INTERVAL_DAY = SQL_INTERVAL_DAY;
SQL_C_INTERVAL_HOUR = SQL_INTERVAL_HOUR;
SQL_C_INTERVAL_MINUTE = SQL_INTERVAL_MINUTE;
SQL_C_INTERVAL_SECOND = SQL_INTERVAL_SECOND;
SQL_C_INTERVAL_YEAR_TO_MONTH = SQL_INTERVAL_YEAR_TO_MONTH;
SQL_C_INTERVAL_DAY_TO_HOUR = SQL_INTERVAL_DAY_TO_HOUR;
SQL_C_INTERVAL_DAY_TO_MINUTE = SQL_INTERVAL_DAY_TO_MINUTE;
SQL_C_INTERVAL_DAY_TO_SECOND = SQL_INTERVAL_DAY_TO_SECOND;
SQL_C_INTERVAL_HOUR_TO_MINUTE = SQL_INTERVAL_HOUR_TO_MINUTE;
SQL_C_INTERVAL_HOUR_TO_SECOND = SQL_INTERVAL_HOUR_TO_SECOND;
SQL_C_INTERVAL_MINUTE_TO_SECOND = SQL_INTERVAL_MINUTE_TO_SECOND;
SQL_C_BINARY = SQL_BINARY;
SQL_C_BIT = SQL_BIT;
SQL_C_SBIGINT = (SQL_BIGINT + SQL_SIGNED_OFFSET); // SIGNED BIGINT
SQL_C_UBIGINT = (SQL_BIGINT + SQL_UNSIGNED_OFFSET); // UNSIGNED BIGINT
SQL_C_TINYINT = SQL_TINYINT;
SQL_C_SLONG = (SQL_C_LONG + SQL_SIGNED_OFFSET); // SIGNED INTEGER
SQL_C_SSHORT = (SQL_C_SHORT + SQL_SIGNED_OFFSET); // SIGNED SMALLINT
SQL_C_STINYINT = (SQL_TINYINT + SQL_SIGNED_OFFSET); // SIGNED TINYINT
SQL_C_ULONG = (SQL_C_LONG + SQL_UNSIGNED_OFFSET); // UNSIGNED INTEGER
SQL_C_USHORT = (SQL_C_SHORT + SQL_UNSIGNED_OFFSET); // UNSIGNED SMALLINT
SQL_C_UTINYINT = (SQL_TINYINT + SQL_UNSIGNED_OFFSET); // UNSIGNED TINYINT
SQL_C_BOOKMARK = {$IFDEF FireDAC_64} SQL_C_UBIGINT {$ELSE} // BOOKMARK
SQL_C_ULONG {$ENDIF};
SQL_C_GUID = SQL_GUID;
SQL_TYPE_NULL = 0;
// base value of driver-specific C-Type (max is 0x7fff)
// define driver-specific C-Type, named as SQL_DRIVER_C_TYPE_BASE,
// SQL_DRIVER_C_TYPE_BASE+1, SQL_DRIVER_C_TYPE_BASE+2, etc.
SQL_DRIVER_C_TYPE_BASE = $4000;
// base value of driver-specific fields/attributes (max are 0x7fff [16-bit] or 0x00007fff [32-bit])
// define driver-specific SQL-Type, named as SQL_DRIVER_SQL_TYPE_BASE,
// SQL_DRIVER_SQL_TYPE_BASE+1, SQL_DRIVER_SQL_TYPE_BASE+2, etc.
//
// Please note that there is no runtime change in this version of DM.
// However, we suggest that driver manufacturers adhere to this range
// as future versions of the DM may enforce these constraints
SQL_DRIVER_SQL_TYPE_BASE = $4000;
SQL_DRIVER_DESC_FIELD_BASE = $4000;
SQL_DRIVER_DIAG_FIELD_BASE = $4000;
SQL_DRIVER_INFO_TYPE_BASE = $4000;
SQL_DRIVER_CONN_ATTR_BASE = $00004000; // 32-bit
SQL_DRIVER_STMT_ATTR_BASE = $00004000; // 32-bit
SQL_C_VARBOOKMARK = SQL_C_BINARY;
// Define for SQL_DIAG_ROW_NUMBER and SQL_DIAG_COLUMN_NUMBER
SQL_NO_ROW_NUMBER = -1;
SQL_NO_COLUMN_NUMBER = -1;
SQL_ROW_NUMBER_UNKNOWN = -2;
SQL_COLUMN_NUMBER_UNKNOWN = -2;
// SQLBindParameter extensions
SQL_DEFAULT_PARAM = -5;
SQL_IGNORE = -6;
SQL_COLUMN_IGNORE = SQL_IGNORE;
SQL_LEN_DATA_AT_EXEC_OFFSET = -100;
function SQL_LEN_DATA_AT_EXEC(Length: SQLInteger): SQLInteger; inline;
const
// Binary Length for driver specific attributes
SQL_LEN_BINARY_ATTR_OFFSET = -100;
function SQL_LEN_BINARY_ATTR(Length: SQLInteger): SQLInteger; inline;
const
// Defines for SQLBindParameter and
// SQLProcedureColumns (returned in the Result set)
SQL_PARAM_TYPE_UNKNOWN = 0;
SQL_PARAM_INPUT = 1;
SQL_PARAM_INPUT_OUTPUT = 2;
SQL_RESULT_COL = 3;
SQL_PARAM_OUTPUT = 4;
SQL_RETURN_VALUE = 5;
SQL_PARAM_INPUT_OUTPUT_STREAM = 8;
SQL_PARAM_OUTPUT_STREAM = 16;
// Defines used by Driver Manager when mapping SQLSetParam to SQLBindParameter
SQL_PARAM_TYPE_DEFAULT = SQL_PARAM_INPUT_OUTPUT;
SQL_SETPARAM_VALUE_MAX = -1;
SQL_COLATT_OPT_MAX = SQL_COLUMN_LABEL;
SQL_COLATT_OPT_MIN = SQL_COLUMN_COUNT;
// SQLColAttributes subdefines for SQL_COLUMN_UPDATABLE
SQL_ATTR_READONLY = 0;
SQL_ATTR_WRITE = 1;
SQL_ATTR_READWRITE_UNKNOWN = 2;
// SQLColAttributes subdefines for SQL_COLUMN_SEARCHABLE
// These are also used by SQLGetInfo
SQL_UNSEARCHABLE = 0;
SQL_LIKE_ONLY = 1;
SQL_ALL_EXCEPT_LIKE = 2;
SQL_SEARCHABLE = 3;
SQL_PRED_SEARCHABLE = SQL_SEARCHABLE;
// New defines for SEARCHABLE column in SQLGetTypeInfo
SQL_COL_PRED_CHAR = SQL_LIKE_ONLY;
SQL_COL_PRED_BASIC = SQL_ALL_EXCEPT_LIKE;
// Special return values for SQLGetData
SQL_NO_TOTAL = -4;
// SQLGetFunctions: additional values for
// fFunction to represent functions that
// are not in the X/Open spec.
SQL_API_SQLALLOCHANDLESTD = 73;
SQL_API_SQLBULKOPERATIONS = 24;
SQL_API_SQLBINDPARAMETER = 72;
SQL_API_SQLBROWSECONNECT = 55;
SQL_API_SQLCOLATTRIBUTES = 6;
SQL_API_SQLCOLUMNPRIVILEGES = 56;
SQL_API_SQLDESCRIBEPARAM = 58;
SQL_API_SQLDRIVERCONNECT = 41;
SQL_API_SQLDRIVERS = 71;
SQL_API_SQLEXTENDEDFETCH = 59;
SQL_API_SQLFOREIGNKEYS = 60;
SQL_API_SQLMORERESULTS = 61;
SQL_API_SQLNATIVESQL = 62;
SQL_API_SQLNUMPARAMS = 63;
SQL_API_SQLPARAMOPTIONS = 64;
SQL_API_SQLPRIMARYKEYS = 65;
SQL_API_SQLPROCEDURECOLUMNS = 66;
SQL_API_SQLPROCEDURES = 67;
SQL_API_SQLSETPOS = 68;
SQL_API_SQLSETSCROLLOPTIONS = 69;
SQL_API_SQLTABLEPRIVILEGES = 70;
// SQL_API_ALL_FUNCTIONS returns an array
// of 'booleans' representing whether a
// function is implemented by the driver.
//
// CAUTION: Only functions defined in ODBC
// version 2.0 and earlier are returned, the
// new high-range function numbers defined by
// X/Open break this scheme. See the new
// method -- SQL_API_ODBC3_ALL_FUNCTIONS
SQL_API_ALL_FUNCTIONS = 0; // See CAUTION above
// 2.X drivers export a dummy function with
// ordinal number SQL_API_LOADBYORDINAL to speed
// loading under the windows operating system.
//
// CAUTION: Loading by ordinal is not supported
// for 3.0 and above drivers.
SQL_API_LOADBYORDINAL = 199; // See CAUTION above
// SQL_API_ODBC3_ALL_FUNCTIONS
// This returns a bitmap, which allows us to*
// handle the higher-valued function numbers.
// Use SQL_FUNC_EXISTS(bitmap,function_number)
// to determine if the function exists.
SQL_API_ODBC3_ALL_FUNCTIONS = 999;
SQL_API_ODBC3_ALL_FUNCTIONS_SIZE = 250; // Array of 250 words
function SQL_FUNC_EXISTS(pfExists: Pointer; uwAPI: Integer): Boolean;
const
// Extended definitions for SQLGetInfo
// Values in ODBC 2.0 that are not
// in the X/Open spec
SQL_INFO_FIRST = 0;
SQL_ACTIVE_CONNECTIONS = 0; // MAX_DRIVER_CONNECTIONS
SQL_ACTIVE_STATEMENTS = 1; // MAX_CONCURRENT_ACTIVITIES
SQL_DRIVER_HDBC = 3;
SQL_DRIVER_HENV = 4;
SQL_DRIVER_HSTMT = 5;
SQL_DRIVER_NAME = 6;
SQL_DRIVER_VER = 7;
SQL_ODBC_API_CONFORMANCE = 9;
SQL_ODBC_VER = 10;
SQL_ROW_UPDATES = 11;
SQL_ODBC_SAG_CLI_CONFORMANCE = 12;
SQL_ODBC_SQL_CONFORMANCE = 15;
SQL_PROCEDURES = 21;
SQL_CONCAT_NULL_BEHAVIOR = 22;
SQL_CURSOR_ROLLBACK_BEHAVIOR = 24;
SQL_EXPRESSIONS_IN_ORDERBY = 27;
SQL_MAX_OWNER_NAME_LEN = 32; // MAX_SCHEMA_NAME_LEN
SQL_MAX_PROCEDURE_NAME_LEN = 33;
SQL_MAX_QUALIFIER_NAME_LEN = 34; // MAX_CATALOG_NAME_LEN
SQL_MULT_RESULT_SETS = 36;
SQL_MULTIPLE_ACTIVE_TXN = 37;
SQL_OUTER_JOINS = 38;
SQL_OWNER_TERM = 39;
SQL_PROCEDURE_TERM = 40;
SQL_QUALIFIER_NAME_SEPARATOR = 41;
SQL_QUALIFIER_TERM = 42;
SQL_SCROLL_OPTIONS = 44;
SQL_TABLE_TERM = 45;
SQL_CONVERT_FUNCTIONS = 48;
SQL_NUMERIC_FUNCTIONS = 49;
SQL_STRING_FUNCTIONS = 50;
SQL_SYSTEM_FUNCTIONS = 51;
SQL_TIMEDATE_FUNCTIONS = 52;
SQL_CONVERT_BIGINT = 53;
SQL_CONVERT_BINARY = 54;
SQL_CONVERT_BIT = 55;
SQL_CONVERT_CHAR = 56;
SQL_CONVERT_DATE = 57;
SQL_CONVERT_DECIMAL = 58;
SQL_CONVERT_DOUBLE = 59;
SQL_CONVERT_FLOAT = 60;
SQL_CONVERT_INTEGER = 61;
SQL_CONVERT_LONGVARCHAR = 62;
SQL_CONVERT_NUMERIC = 63;
SQL_CONVERT_REAL = 64;
SQL_CONVERT_SMALLINT = 65;
SQL_CONVERT_TIME = 66;
SQL_CONVERT_TIMESTAMP = 67;
SQL_CONVERT_TINYINT = 68;
SQL_CONVERT_VARBINARY = 69;
SQL_CONVERT_VARCHAR = 70;
SQL_CONVERT_LONGVARBINARY = 71;
SQL_ODBC_SQL_OPT_IEF = 73; // SQL_INTEGRITY
SQL_CORRELATION_NAME = 74;
SQL_NON_NULLABLE_COLUMNS = 75;
SQL_DRIVER_HLIB = 76;
SQL_DRIVER_ODBC_VER = 77;
SQL_LOCK_TYPES = 78;
SQL_POS_OPERATIONS = 79;
SQL_POSITIONED_STATEMENTS = 80;
SQL_BOOKMARK_PERSISTENCE = 82;
SQL_STATIC_SENSITIVITY = 83;
SQL_FILE_USAGE = 84;
SQL_COLUMN_ALIAS = 87;
SQL_GROUP_BY = 88;
SQL_KEYWORDS = 89;
SQL_OWNER_USAGE = 91;
SQL_QUALIFIER_USAGE = 92;
SQL_QUOTED_IDENTIFIER_CASE = 93;
SQL_SUBQUERIES = 95;
SQL_UNION = 96;
SQL_MAX_ROW_SIZE_INCLUDES_LONG = 103;
SQL_MAX_CHAR_LITERAL_LEN = 108;
SQL_TIMEDATE_ADD_INTERVALS = 109;
SQL_TIMEDATE_DIFF_INTERVALS = 110;
SQL_NEED_LONG_DATA_LEN = 111;
SQL_MAX_BINARY_LITERAL_LEN = 112;
SQL_LIKE_ESCAPE_CLAUSE = 113;
SQL_QUALIFIER_LOCATION = 114;
// ODBC 3.0 SQLGetInfo values that are not part
// of the X/Open standard at this time. X/Open
// standard values are in SQL.h.
SQL_ACTIVE_ENVIRONMENTS = 116;
SQL_ALTER_DOMAIN = 117;
SQL_SQL_CONFORMANCE = 118;
SQL_DATETIME_LITERALS = 119;
SQL_ASYNC_MODE = 10021; // new X/Open spec
SQL_BATCH_ROW_COUNT = 120;
SQL_BATCH_SUPPORT = 121;
SQL_CATALOG_LOCATION = SQL_QUALIFIER_LOCATION;
SQL_CATALOG_NAME_SEPARATOR = SQL_QUALIFIER_NAME_SEPARATOR;
SQL_CATALOG_TERM = SQL_QUALIFIER_TERM;
SQL_CATALOG_USAGE = SQL_QUALIFIER_USAGE;
SQL_CONVERT_WCHAR = 122;
SQL_CONVERT_INTERVAL_DAY_TIME = 123;
SQL_CONVERT_INTERVAL_YEAR_MONTH = 124;
SQL_CONVERT_WLONGVARCHAR = 125;
SQL_CONVERT_WVARCHAR = 126;
SQL_CREATE_ASSERTION = 127;
SQL_CREATE_CHARACTER_SET = 128;
SQL_CREATE_COLLATION = 129;
SQL_CREATE_DOMAIN = 130;
SQL_CREATE_SCHEMA = 131;
SQL_CREATE_TABLE = 132;
SQL_CREATE_TRANSLATION = 133;
SQL_CREATE_VIEW = 134;
SQL_DRIVER_HDESC = 135;
SQL_DROP_ASSERTION = 136;
SQL_DROP_CHARACTER_SET = 137;
SQL_DROP_COLLATION = 138;
SQL_DROP_DOMAIN = 139;
SQL_DROP_SCHEMA = 140;
SQL_DROP_TABLE = 141;
SQL_DROP_TRANSLATION = 142;
SQL_DROP_VIEW = 143;
SQL_DYNAMIC_CURSOR_ATTRIBUTES1 = 144;
SQL_DYNAMIC_CURSOR_ATTRIBUTES2 = 145;
SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1 = 146;
SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2 = 147;
SQL_INDEX_KEYWORDS = 148;
SQL_INFO_SCHEMA_VIEWS = 149;
SQL_KEYSET_CURSOR_ATTRIBUTES1 = 150;
SQL_KEYSET_CURSOR_ATTRIBUTES2 = 151;
SQL_MAX_ASYNC_CONCURRENT_STATEMENTS = 10022; // new X/Open spec
SQL_ODBC_INTERFACE_CONFORMANCE = 152;
SQL_PARAM_ARRAY_ROW_COUNTS = 153;
SQL_PARAM_ARRAY_SELECTS = 154;
SQL_SCHEMA_TERM = SQL_OWNER_TERM;
SQL_SCHEMA_USAGE = SQL_OWNER_USAGE;
SQL_SQL92_DATETIME_FUNCTIONS = 155;
SQL_SQL92_FOREIGN_KEY_DELETE_RULE = 156;
SQL_SQL92_FOREIGN_KEY_UPDATE_RULE = 157;
SQL_SQL92_GRANT = 158;
SQL_SQL92_NUMERIC_VALUE_FUNCTIONS = 159;
SQL_SQL92_PREDICATES = 160;
SQL_SQL92_RELATIONAL_JOIN_OPERATORS = 161;
SQL_SQL92_REVOKE = 162;
SQL_SQL92_ROW_VALUE_CONSTRUCTOR = 163;
SQL_SQL92_STRING_FUNCTIONS = 164;
SQL_SQL92_VALUE_EXPRESSIONS = 165;
SQL_STANDARD_CLI_CONFORMANCE = 166;
SQL_STATIC_CURSOR_ATTRIBUTES1 = 167;
SQL_STATIC_CURSOR_ATTRIBUTES2 = 168;
SQL_AGGREGATE_FUNCTIONS = 169;
SQL_DDL_INDEX = 170;
SQL_DM_VER = 171;
SQL_INSERT_STATEMENT = 172;
SQL_CONVERT_GUID = 173;
SQL_UNION_STATEMENT = SQL_UNION;
SQL_ASYNC_DBC_FUNCTIONS = 10023;
SQL_DTC_TRANSITION_COST = 1750;
// SQL_CONVERT_* return value bitmasks
SQL_CVT_CHAR = $00000001;
SQL_CVT_NUMERIC = $00000002;
SQL_CVT_DECIMAL = $00000004;
SQL_CVT_INTEGER = $00000008;
SQL_CVT_SMALLINT = $00000010;
SQL_CVT_FLOAT = $00000020;
SQL_CVT_REAL = $00000040;
SQL_CVT_DOUBLE = $00000080;
SQL_CVT_VARCHAR = $00000100;
SQL_CVT_LONGVARCHAR = $00000200;
SQL_CVT_BINARY = $00000400;
SQL_CVT_VARBINARY = $00000800;
SQL_CVT_BIT = $00001000;
SQL_CVT_TINYINT = $00002000;
SQL_CVT_BIGINT = $00004000;
SQL_CVT_DATE = $00008000;
SQL_CVT_TIME = $00010000;
SQL_CVT_TIMESTAMP = $00020000;
SQL_CVT_LONGVARBINARY = $00040000;
SQL_CVT_INTERVAL_YEAR_MONTH = $00080000;
SQL_CVT_INTERVAL_DAY_TIME = $00100000;
SQL_CVT_WCHAR = $00200000;
SQL_CVT_WLONGVARCHAR = $00400000;
SQL_CVT_WVARCHAR = $00800000;
SQL_CVT_GUID = $01000000;
// SQL_CONVERT_FUNCTIONS functions
SQL_FN_CVT_CONVERT = $00000001;
SQL_FN_CVT_CAST = $00000002;
// SQL_STRING_FUNCTIONS functions
SQL_FN_STR_CONCAT = $00000001;
SQL_FN_STR_INSERT = $00000002;
SQL_FN_STR_LEFT = $00000004;
SQL_FN_STR_LTRIM = $00000008;
SQL_FN_STR_LENGTH = $00000010;
SQL_FN_STR_LOCATE = $00000020;
SQL_FN_STR_LCASE = $00000040;
SQL_FN_STR_REPEAT = $00000080;
SQL_FN_STR_REPLACE = $00000100;
SQL_FN_STR_RIGHT = $00000200;
SQL_FN_STR_RTRIM = $00000400;
SQL_FN_STR_SUBSTRING = $00000800;
SQL_FN_STR_UCASE = $00001000;
SQL_FN_STR_ASCII = $00002000;
SQL_FN_STR_CHAR = $00004000;
SQL_FN_STR_DIFFERENCE = $00008000;
SQL_FN_STR_LOCATE_2 = $00010000;
SQL_FN_STR_SOUNDEX = $00020000;
SQL_FN_STR_SPACE = $00040000;
SQL_FN_STR_BIT_LENGTH = $00080000;
SQL_FN_STR_CHAR_LENGTH = $00100000;
SQL_FN_STR_CHARACTER_LENGTH = $00200000;
SQL_FN_STR_OCTET_LENGTH = $00400000;
SQL_FN_STR_POSITION = $00800000;
// SQL_SQL92_STRING_FUNCTIONS
SQL_SSF_CONVERT = $00000001;
SQL_SSF_LOWER = $00000002;
SQL_SSF_UPPER = $00000004;
SQL_SSF_SUBSTRING = $00000008;
SQL_SSF_TRANSLATE = $00000010;
SQL_SSF_TRIM_BOTH = $00000020;
SQL_SSF_TRIM_LEADING = $00000040;
SQL_SSF_TRIM_TRAILING = $00000080;
// SQL_NUMERIC_FUNCTIONS functions
SQL_FN_NUM_ABS = $00000001;
SQL_FN_NUM_ACOS = $00000002;
SQL_FN_NUM_ASIN = $00000004;
SQL_FN_NUM_ATAN = $00000008;
SQL_FN_NUM_ATAN2 = $00000010;
SQL_FN_NUM_CEILING = $00000020;
SQL_FN_NUM_COS = $00000040;
SQL_FN_NUM_COT = $00000080;
SQL_FN_NUM_EXP = $00000100;
SQL_FN_NUM_FLOOR = $00000200;
SQL_FN_NUM_LOG = $00000400;
SQL_FN_NUM_MOD = $00000800;
SQL_FN_NUM_SIGN = $00001000;
SQL_FN_NUM_SIN = $00002000;
SQL_FN_NUM_SQRT = $00004000;
SQL_FN_NUM_TAN = $00008000;
SQL_FN_NUM_PI = $00010000;
SQL_FN_NUM_RAND = $00020000;
SQL_FN_NUM_DEGREES = $00040000;
SQL_FN_NUM_LOG10 = $00080000;
SQL_FN_NUM_POWER = $00100000;
SQL_FN_NUM_RADIANS = $00200000;
SQL_FN_NUM_ROUND = $00400000;
SQL_FN_NUM_TRUNCATE = $00800000;
// SQL_SQL92_NUMERIC_VALUE_FUNCTIONS
SQL_SNVF_BIT_LENGTH = $00000001;
SQL_SNVF_CHAR_LENGTH = $00000002;
SQL_SNVF_CHARACTER_LENGTH = $00000004;
SQL_SNVF_EXTRACT = $00000008;
SQL_SNVF_OCTET_LENGTH = $00000010;
SQL_SNVF_POSITION = $00000020;
// SQL_TIMEDATE_FUNCTIONS functions
SQL_FN_TD_NOW = $00000001;
SQL_FN_TD_CURDATE = $00000002;
SQL_FN_TD_DAYOFMONTH = $00000004;
SQL_FN_TD_DAYOFWEEK = $00000008;
SQL_FN_TD_DAYOFYEAR = $00000010;
SQL_FN_TD_MONTH = $00000020;
SQL_FN_TD_QUARTER = $00000040;
SQL_FN_TD_WEEK = $00000080;
SQL_FN_TD_YEAR = $00000100;
SQL_FN_TD_CURTIME = $00000200;
SQL_FN_TD_HOUR = $00000400;
SQL_FN_TD_MINUTE = $00000800;
SQL_FN_TD_SECOND = $00001000;
SQL_FN_TD_TIMESTAMPADD = $00002000;
SQL_FN_TD_TIMESTAMPDIFF = $00004000;
SQL_FN_TD_DAYNAME = $00008000;
SQL_FN_TD_MONTHNAME = $00010000;
SQL_FN_TD_CURRENT_DATE = $00020000;
SQL_FN_TD_CURRENT_TIME = $00040000;
SQL_FN_TD_CURRENT_TIMESTAMP = $00080000;
SQL_FN_TD_EXTRACT = $00100000;
// SQL_SQL92_DATETIME_FUNCTIONS
SQL_SDF_CURRENT_DATE = $00000001;
SQL_SDF_CURRENT_TIME = $00000002;
SQL_SDF_CURRENT_TIMESTAMP = $00000004;
// SQL_SYSTEM_FUNCTIONS functions
SQL_FN_SYS_USERNAME = $00000001;
SQL_FN_SYS_DBNAME = $00000002;
SQL_FN_SYS_IFNULL = $00000004;
// SQL_TIMEDATE_ADD_INTERVALS and SQL_TIMEDATE_DIFF_INTERVALS functions
SQL_FN_TSI_FRAC_SECOND = $00000001;
SQL_FN_TSI_SECOND = $00000002;
SQL_FN_TSI_MINUTE = $00000004;
SQL_FN_TSI_HOUR = $00000008;
SQL_FN_TSI_DAY = $00000010;
SQL_FN_TSI_WEEK = $00000020;
SQL_FN_TSI_MONTH = $00000040;
SQL_FN_TSI_QUARTER = $00000080;
SQL_FN_TSI_YEAR = $00000100;
// Supported SQLFetchScroll FetchOrientation's
SQL_CA1_NEXT = $00000001;
SQL_CA1_ABSOLUTE = $00000002;
SQL_CA1_RELATIVE = $00000004;
SQL_CA1_BOOKMARK = $00000008;
// Supported SQLSetPos LockType's
SQL_CA1_LOCK_NO_CHANGE = $00000040;
SQL_CA1_LOCK_EXCLUSIVE = $00000080;
SQL_CA1_LOCK_UNLOCK = $00000100;
// Supported SQLSetPos Operations
SQL_CA1_POS_POSITION = $00000200;
SQL_CA1_POS_UPDATE = $00000400;
SQL_CA1_POS_DELETE = $00000800;
SQL_CA1_POS_REFRESH = $00001000;
// Positioned updates and deletes
SQL_CA1_POSITIONED_UPDATE = $00002000;
SQL_CA1_POSITIONED_DELETE = $00004000;
SQL_CA1_SELECT_FOR_UPDATE = $00008000;
// Supported SQLBulkOperations operations
SQL_CA1_BULK_ADD = $00010000;
SQL_CA1_BULK_UPDATE_BY_BOOKMARK = $00020000;
SQL_CA1_BULK_DELETE_BY_BOOKMARK = $00040000;
SQL_CA1_BULK_FETCH_BY_BOOKMARK = $00080000;
// Supported values for SQL_ATTR_SCROLL_CONCURRENCY
SQL_CA2_READ_ONLY_CONCURRENCY = $00000001;
SQL_CA2_LOCK_CONCURRENCY = $00000002;
SQL_CA2_OPT_ROWVER_CONCURRENCY = $00000004;
SQL_CA2_OPT_VALUES_CONCURRENCY = $00000008;
// Sensitivity of the cursor to its own inserts, deletes, and updates
SQL_CA2_SENSITIVITY_ADDITIONS = $00000010;
SQL_CA2_SENSITIVITY_DELETIONS = $00000020;
SQL_CA2_SENSITIVITY_UPDATES = $00000040;
// Semantics of SQL_ATTR_MAX_ROWS
SQL_CA2_MAX_ROWS_SELECT = $00000080;
SQL_CA2_MAX_ROWS_INSERT = $00000100;
SQL_CA2_MAX_ROWS_DELETE = $00000200;
SQL_CA2_MAX_ROWS_UPDATE = $00000400;
SQL_CA2_MAX_ROWS_CATALOG = $00000800;
SQL_CA2_MAX_ROWS_AFFECTS_ALL = (SQL_CA2_MAX_ROWS_SELECT or
SQL_CA2_MAX_ROWS_INSERT or
SQL_CA2_MAX_ROWS_DELETE or
SQL_CA2_MAX_ROWS_UPDATE or
SQL_CA2_MAX_ROWS_CATALOG);
// Semantics of SQL_DIAG_CURSOR_ROW_COUNT
SQL_CA2_CRC_EXACT = $00001000;
SQL_CA2_CRC_APPROXIMATE = $00002000;
// The kinds of positioned statements that can be simulated
SQL_CA2_SIMULATE_NON_UNIQUE = $00004000;
SQL_CA2_SIMULATE_TRY_UNIQUE = $00008000;
SQL_CA2_SIMULATE_UNIQUE = $00010000;
// SQL_ODBC_API_CONFORMANCE values
SQL_OAC_NONE = $0000;
SQL_OAC_LEVEL1 = $0001;
SQL_OAC_LEVEL2 = $0002;
// SQL_ODBC_SAG_CLI_CONFORMANCE values
SQL_OSCC_NOT_COMPLIANT = $0000;
SQL_OSCC_COMPLIANT = $0001;
// SQL_ODBC_SQL_CONFORMANCE values
SQL_OSC_MINIMUM = $0000;
SQL_OSC_CORE = $0001;
SQL_OSC_EXTENDED = $0002;
// SQL_CONCAT_NULL_BEHAVIOR values
SQL_CB_NULL = $0000;
SQL_CB_NON_NULL = $0001;
// SQL_SCROLL_OPTIONS masks
SQL_SO_FORWARD_ONLY = $00000001;
SQL_SO_KEYSET_DRIVEN = $00000002;
SQL_SO_DYNAMIC = $00000004;
SQL_SO_MIXED = $00000008;
SQL_SO_STATIC = $00000010;
// SQL_FETCH_DIRECTION masks
// SQL_FD_FETCH_RESUME = $00000040; // SQL_FETCH_RESUME is no longer supported
SQL_FD_FETCH_BOOKMARK = $00000080;
// SQL_TXN_ISOLATION_OPTION masks
// SQL_TXN_VERSIONING = $00000010; // SQL_TXN_VERSIONING is no longer supported
// SQL_CORRELATION_NAME values
SQL_CN_NONE = $0000;
SQL_CN_DIFFERENT = $0001;
SQL_CN_ANY = $0002;
// SQL_NON_NULLABLE_COLUMNS values
SQL_NNC_NULL = $0000;
SQL_NNC_NON_NULL = $0001;
// SQL_NULL_COLLATION values
SQL_NC_START = $0002;
SQL_NC_END = $0004;
// SQL_FILE_USAGE values
SQL_FILE_NOT_SUPPORTED = $0000;
SQL_FILE_TABLE = $0001;
SQL_FILE_QUALIFIER = $0002;
SQL_FILE_CATALOG = SQL_FILE_QUALIFIER; // ODBC 3.0
// SQL_GETDATA_EXTENSIONS values
SQL_GD_BLOCK = $00000004;
SQL_GD_BOUND = $00000008;
SQL_GD_OUTPUT_PARAMS = $00000010;
// SQL_POSITIONED_STATEMENTS masks
SQL_PS_POSITIONED_DELETE = $00000001;
SQL_PS_POSITIONED_UPDATE = $00000002;
SQL_PS_SELECT_FOR_UPDATE = $00000004;
// SQL_GROUP_BY values
SQL_GB_NOT_SUPPORTED = $0000;
SQL_GB_GROUP_BY_EQUALS_SELECT = $0001;
SQL_GB_GROUP_BY_CONTAINS_SELECT = $0002;
SQL_GB_NO_RELATION = $0003;
SQL_GB_COLLATE = $0004;
// SQL_OWNER_USAGE masks
SQL_OU_DML_STATEMENTS = $00000001;
SQL_OU_PROCEDURE_INVOCATION = $00000002;
SQL_OU_TABLE_DEFINITION = $00000004;
SQL_OU_INDEX_DEFINITION = $00000008;
SQL_OU_PRIVILEGE_DEFINITION = $00000010;
// SQL_SCHEMA_USAGE masks
SQL_SU_DML_STATEMENTS = SQL_OU_DML_STATEMENTS;
SQL_SU_PROCEDURE_INVOCATION = SQL_OU_PROCEDURE_INVOCATION;
SQL_SU_TABLE_DEFINITION = SQL_OU_TABLE_DEFINITION;
SQL_SU_INDEX_DEFINITION = SQL_OU_INDEX_DEFINITION;
SQL_SU_PRIVILEGE_DEFINITION = SQL_OU_PRIVILEGE_DEFINITION;
// SQL_QUALIFIER_USAGE masks
SQL_QU_DML_STATEMENTS = $00000001;
SQL_QU_PROCEDURE_INVOCATION = $00000002;
SQL_QU_TABLE_DEFINITION = $00000004;
SQL_QU_INDEX_DEFINITION = $00000008;
SQL_QU_PRIVILEGE_DEFINITION = $00000010;
// SQL_CATALOG_USAGE masks
SQL_CU_DML_STATEMENTS = SQL_QU_DML_STATEMENTS;
SQL_CU_PROCEDURE_INVOCATION = SQL_QU_PROCEDURE_INVOCATION;
SQL_CU_TABLE_DEFINITION = SQL_QU_TABLE_DEFINITION;
SQL_CU_INDEX_DEFINITION = SQL_QU_INDEX_DEFINITION;
SQL_CU_PRIVILEGE_DEFINITION = SQL_QU_PRIVILEGE_DEFINITION;
// SQL_SUBQUERIES masks
SQL_SQ_COMPARISON = $00000001;
SQL_SQ_EXISTS = $00000002;
SQL_SQ_IN = $00000004;
SQL_SQ_QUANTIFIED = $00000008;
SQL_SQ_CORRELATED_SUBQUERIES = $00000010;
// SQL_UNION masks
SQL_U_UNION = $00000001;
SQL_U_UNION_ALL = $00000002;
// SQL_BOOKMARK_PERSISTENCE values
SQL_BP_CLOSE = $00000001;
SQL_BP_DELETE = $00000002;
SQL_BP_DROP = $00000004;
SQL_BP_TRANSACTION = $00000008;
SQL_BP_UPDATE = $00000010;
SQL_BP_OTHER_HSTMT = $00000020;
SQL_BP_SCROLL = $00000040;
// SQL_STATIC_SENSITIVITY values
SQL_SS_ADDITIONS = $00000001;
SQL_SS_DELETIONS = $00000002;
SQL_SS_UPDATES = $00000004;
// SQL_VIEW values
SQL_CV_CREATE_VIEW = $00000001;
SQL_CV_CHECK_OPTION = $00000002;
SQL_CV_CASCADED = $00000004;
SQL_CV_LOCAL = $00000008;
// SQL_LOCK_TYPES masks
SQL_LCK_NO_CHANGE = $00000001;
SQL_LCK_EXCLUSIVE = $00000002;
SQL_LCK_UNLOCK = $00000004;
// SQL_POS_OPERATIONS masks
SQL_POS_POSITION = $00000001;
SQL_POS_REFRESH = $00000002;
SQL_POS_UPDATE = $00000004;
SQL_POS_DELETE = $00000008;
SQL_POS_ADD = $00000010;
// SQL_QUALIFIER_LOCATION values
SQL_QL_START = $0001;
SQL_QL_END = $0002;
// Here start return values for ODBC 3.0 SQLGetInfo
// SQL_AGGREGATE_FUNCTIONS bitmasks
SQL_AF_AVG = $00000001;
SQL_AF_COUNT = $00000002;
SQL_AF_MAX = $00000004;
SQL_AF_MIN = $00000008;
SQL_AF_SUM = $00000010;
SQL_AF_DISTINCT = $00000020;
SQL_AF_ALL = $00000040;
// SQL_SQL_CONFORMANCE bit masks
SQL_SC_SQL92_ENTRY = $00000001;
SQL_SC_FIPS127_2_TRANSITIONAL = $00000002;
SQL_SC_SQL92_INTERMEDIATE = $00000004;
SQL_SC_SQL92_FULL = $00000008;
// SQL_DATETIME_LITERALS masks
SQL_DL_SQL92_DATE = $00000001;
SQL_DL_SQL92_TIME = $00000002;
SQL_DL_SQL92_TIMESTAMP = $00000004;
SQL_DL_SQL92_INTERVAL_YEAR = $00000008;
SQL_DL_SQL92_INTERVAL_MONTH = $00000010;
SQL_DL_SQL92_INTERVAL_DAY = $00000020;
SQL_DL_SQL92_INTERVAL_HOUR = $00000040;
SQL_DL_SQL92_INTERVAL_MINUTE = $00000080;
SQL_DL_SQL92_INTERVAL_SECOND = $00000100;
SQL_DL_SQL92_INTERVAL_YEAR_TO_MONTH = $00000200;
SQL_DL_SQL92_INTERVAL_DAY_TO_HOUR = $00000400;
SQL_DL_SQL92_INTERVAL_DAY_TO_MINUTE = $00000800;
SQL_DL_SQL92_INTERVAL_DAY_TO_SECOND = $00001000;
SQL_DL_SQL92_INTERVAL_HOUR_TO_MINUTE = $00002000;
SQL_DL_SQL92_INTERVAL_HOUR_TO_SECOND = $00004000;
SQL_DL_SQL92_INTERVAL_MINUTE_TO_SECOND = $00008000;
// SQL_CATALOG_LOCATION values
SQL_CL_START = SQL_QL_START;
SQL_CL_END = SQL_QL_END;
// Values for SQL_BATCH_ROW_COUNT
SQL_BRC_PROCEDURES = $0000001;
SQL_BRC_EXPLICIT = $0000002;
SQL_BRC_ROLLED_UP = $0000004;
// Bitmasks for SQL_BATCH_SUPPORT
SQL_BS_SELECT_EXPLICIT = $00000001;
SQL_BS_ROW_COUNT_EXPLICIT = $00000002;
SQL_BS_SELECT_PROC = $00000004;
SQL_BS_ROW_COUNT_PROC = $00000008;
// Values for SQL_PARAM_ARRAY_ROW_COUNTS getinfo
SQL_PARC_BATCH = 1;
SQL_PARC_NO_BATCH = 2;
// Values for SQL_PARAM_ARRAY_SELECTS
SQL_PAS_BATCH = 1;
SQL_PAS_NO_BATCH = 2;
SQL_PAS_NO_SELECT = 3;
// Bitmasks for SQL_INDEX_KEYWORDS
SQL_IK_NONE = $00000000;
SQL_IK_ASC = $00000001;
SQL_IK_DESC = $00000002;
SQL_IK_ALL = (SQL_IK_ASC or SQL_IK_DESC);
// Bitmasks for SQL_INFO_SCHEMA_VIEWS
SQL_ISV_ASSERTIONS = $00000001;
SQL_ISV_CHARACTER_SETS = $00000002;
SQL_ISV_CHECK_CONSTRAINTS = $00000004;
SQL_ISV_COLLATIONS = $00000008;
SQL_ISV_COLUMN_DOMAIN_USAGE = $00000010;
SQL_ISV_COLUMN_PRIVILEGES = $00000020;
SQL_ISV_COLUMNS = $00000040;
SQL_ISV_CONSTRAINT_COLUMN_USAGE = $00000080;
SQL_ISV_CONSTRAINT_TABLE_USAGE = $00000100;
SQL_ISV_DOMAIN_CONSTRAINTS = $00000200;
SQL_ISV_DOMAINS = $00000400;
SQL_ISV_KEY_COLUMN_USAGE = $00000800;
SQL_ISV_REFERENTIAL_CONSTRAINTS = $00001000;
SQL_ISV_SCHEMATA = $00002000;
SQL_ISV_SQL_LANGUAGES = $00004000;
SQL_ISV_TABLE_CONSTRAINTS = $00008000;
SQL_ISV_TABLE_PRIVILEGES = $00010000;
SQL_ISV_TABLES = $00020000;
SQL_ISV_TRANSLATIONS = $00040000;
SQL_ISV_USAGE_PRIVILEGES = $00080000;
SQL_ISV_VIEW_COLUMN_USAGE = $00100000;
SQL_ISV_VIEW_TABLE_USAGE = $00200000;
SQL_ISV_VIEWS = $00400000;
// Bitmasks for SQL_ALTER_DOMAIN
SQL_AD_CONSTRAINT_NAME_DEFINITION = $00000001;
SQL_AD_ADD_DOMAIN_CONSTRAINT = $00000002;
SQL_AD_DROP_DOMAIN_CONSTRAINT = $00000004;
SQL_AD_ADD_DOMAIN_DEFAULT = $00000008;
SQL_AD_DROP_DOMAIN_DEFAULT = $00000010;
SQL_AD_ADD_CONSTRAINT_INITIALLY_DEFERRED = $00000020;
SQL_AD_ADD_CONSTRAINT_INITIALLY_IMMEDIATE = $00000040;
SQL_AD_ADD_CONSTRAINT_DEFERRABLE = $00000080;
SQL_AD_ADD_CONSTRAINT_NON_DEFERRABLE = $00000100;
// SQL_CREATE_SCHEMA bitmasks
SQL_CS_CREATE_SCHEMA = $00000001;
SQL_CS_AUTHORIZATION = $00000002;
SQL_CS_DEFAULT_CHARACTER_SET = $00000004;
// SQL_CREATE_TRANSLATION bitmasks
SQL_CTR_CREATE_TRANSLATION = $00000001;
// SQL_CREATE_ASSERTION bitmasks
SQL_CA_CREATE_ASSERTION = $00000001;
SQL_CA_CONSTRAINT_INITIALLY_DEFERRED = $00000010;
SQL_CA_CONSTRAINT_INITIALLY_IMMEDIATE = $00000020;
SQL_CA_CONSTRAINT_DEFERRABLE = $00000040;
SQL_CA_CONSTRAINT_NON_DEFERRABLE = $00000080;
// SQL_CREATE_CHARACTER_SET bitmasks
SQL_CCS_CREATE_CHARACTER_SET = $00000001;
SQL_CCS_COLLATE_CLAUSE = $00000002;
SQL_CCS_LIMITED_COLLATION = $00000004;
// SQL_CREATE_COLLATION bitmasks
SQL_CCOL_CREATE_COLLATION = $00000001;
// SQL_CREATE_DOMAIN bitmasks
SQL_CDO_CREATE_DOMAIN = $00000001;
SQL_CDO_DEFAULT = $00000002;
SQL_CDO_CONSTRAINT = $00000004;
SQL_CDO_COLLATION = $00000008;
SQL_CDO_CONSTRAINT_NAME_DEFINITION = $00000010;
SQL_CDO_CONSTRAINT_INITIALLY_DEFERRED = $00000020;
SQL_CDO_CONSTRAINT_INITIALLY_IMMEDIATE = $00000040;
SQL_CDO_CONSTRAINT_DEFERRABLE = $00000080;
SQL_CDO_CONSTRAINT_NON_DEFERRABLE = $00000100;
// SQL_CREATE_TABLE bitmasks
SQL_CT_CREATE_TABLE = $00000001;
SQL_CT_COMMIT_PRESERVE = $00000002;
SQL_CT_COMMIT_DELETE = $00000004;
SQL_CT_GLOBAL_TEMPORARY = $00000008;
SQL_CT_LOCAL_TEMPORARY = $00000010;
SQL_CT_CONSTRAINT_INITIALLY_DEFERRED = $00000020;
SQL_CT_CONSTRAINT_INITIALLY_IMMEDIATE = $00000040;
SQL_CT_CONSTRAINT_DEFERRABLE = $00000080;
SQL_CT_CONSTRAINT_NON_DEFERRABLE = $00000100;
SQL_CT_COLUMN_CONSTRAINT = $00000200;
SQL_CT_COLUMN_DEFAULT = $00000400;
SQL_CT_COLUMN_COLLATION = $00000800;
SQL_CT_TABLE_CONSTRAINT = $00001000;
SQL_CT_CONSTRAINT_NAME_DEFINITION = $00002000;
// SQL_DDL_INDEX bitmasks
SQL_DI_CREATE_INDEX = $00000001;
SQL_DI_DROP_INDEX = $00000002;
// SQL_DROP_COLLATION bitmasks
SQL_DC_DROP_COLLATION = $00000001;
// SQL_DROP_DOMAIN bitmasks
SQL_DD_DROP_DOMAIN = $00000001;
SQL_DD_RESTRICT = $00000002;
SQL_DD_CASCADE = $00000004;
// SQL_DROP_SCHEMA bitmasks
SQL_DS_DROP_SCHEMA = $00000001;
SQL_DS_RESTRICT = $00000002;
SQL_DS_CASCADE = $00000004;
// SQL_DROP_CHARACTER_SET bitmasks
SQL_DCS_DROP_CHARACTER_SET = $00000001;
// SQL_DROP_ASSERTION bitmasks
SQL_DA_DROP_ASSERTION = $00000001;
// SQL_DROP_TABLE bitmasks
SQL_DT_DROP_TABLE = $00000001;
SQL_DT_RESTRICT = $00000002;
SQL_DT_CASCADE = $00000004;
// SQL_DROP_TRANSLATION bitmasks
SQL_DTR_DROP_TRANSLATION = $00000001;
// SQL_DROP_VIEW bitmasks
SQL_DV_DROP_VIEW = $00000001;
SQL_DV_RESTRICT = $00000002;
SQL_DV_CASCADE = $00000004;
// SQL_INSERT_STATEMENT bitmasks
SQL_IS_INSERT_LITERALS = $00000001;
SQL_IS_INSERT_SEARCHED = $00000002;
SQL_IS_SELECT_INTO = $00000004;
// SQL_ODBC_INTERFACE_CONFORMANCE values
SQL_OIC_CORE = ULong(1);
SQL_OIC_LEVEL1 = ULong(2);
SQL_OIC_LEVEL2 = ULong(3);
// SQL_SQL92_FOREIGN_KEY_DELETE_RULE bitmasks
SQL_SFKD_CASCADE = $00000001;
SQL_SFKD_NO_ACTION = $00000002;
SQL_SFKD_SET_DEFAULT = $00000004;
SQL_SFKD_SET_NULL = $00000008;
// SQL_SQL92_FOREIGN_KEY_UPDATE_RULE bitmasks
SQL_SFKU_CASCADE = $00000001;
SQL_SFKU_NO_ACTION = $00000002;
SQL_SFKU_SET_DEFAULT = $00000004;
SQL_SFKU_SET_NULL = $00000008;
// SQL_SQL92_GRANT bitmasks
SQL_SG_USAGE_ON_DOMAIN = $00000001;
SQL_SG_USAGE_ON_CHARACTER_SET = $00000002;
SQL_SG_USAGE_ON_COLLATION = $00000004;
SQL_SG_USAGE_ON_TRANSLATION = $00000008;
SQL_SG_WITH_GRANT_OPTION = $00000010;
SQL_SG_DELETE_TABLE = $00000020;
SQL_SG_INSERT_TABLE = $00000040;
SQL_SG_INSERT_COLUMN = $00000080;
SQL_SG_REFERENCES_TABLE = $00000100;
SQL_SG_REFERENCES_COLUMN = $00000200;
SQL_SG_SELECT_TABLE = $00000400;
SQL_SG_UPDATE_TABLE = $00000800;
SQL_SG_UPDATE_COLUMN = $00001000;
// SQL_SQL92_PREDICATES bitmasks
SQL_SP_EXISTS = $00000001;
SQL_SP_ISNOTNULL = $00000002;
SQL_SP_ISNULL = $00000004;
SQL_SP_MATCH_FULL = $00000008;
SQL_SP_MATCH_PARTIAL = $00000010;
SQL_SP_MATCH_UNIQUE_FULL = $00000020;
SQL_SP_MATCH_UNIQUE_PARTIAL = $00000040;
SQL_SP_OVERLAPS = $00000080;
SQL_SP_UNIQUE = $00000100;
SQL_SP_LIKE = $00000200;
SQL_SP_IN = $00000400;
SQL_SP_BETWEEN = $00000800;
SQL_SP_COMPARISON = $00001000;
SQL_SP_QUANTIFIED_COMPARISON = $00002000;
// SQL_SQL92_RELATIONAL_JOIN_OPERATORS bitmasks
SQL_SRJO_CORRESPONDING_CLAUSE = $00000001;
SQL_SRJO_CROSS_JOIN = $00000002;
SQL_SRJO_EXCEPT_JOIN = $00000004;
SQL_SRJO_FULL_OUTER_JOIN = $00000008;
SQL_SRJO_INNER_JOIN = $00000010;
SQL_SRJO_INTERSECT_JOIN = $00000020;
SQL_SRJO_LEFT_OUTER_JOIN = $00000040;
SQL_SRJO_NATURAL_JOIN = $00000080;
SQL_SRJO_RIGHT_OUTER_JOIN = $00000100;
SQL_SRJO_UNION_JOIN = $00000200;
// SQL_SQL92_REVOKE bitmasks
SQL_SR_USAGE_ON_DOMAIN = $00000001;
SQL_SR_USAGE_ON_CHARACTER_SET = $00000002;
SQL_SR_USAGE_ON_COLLATION = $00000004;
SQL_SR_USAGE_ON_TRANSLATION = $00000008;
SQL_SR_GRANT_OPTION_FOR = $00000010;
SQL_SR_CASCADE = $00000020;
SQL_SR_RESTRICT = $00000040;
SQL_SR_DELETE_TABLE = $00000080;
SQL_SR_INSERT_TABLE = $00000100;
SQL_SR_INSERT_COLUMN = $00000200;
SQL_SR_REFERENCES_TABLE = $00000400;
SQL_SR_REFERENCES_COLUMN = $00000800;
SQL_SR_SELECT_TABLE = $00001000;
SQL_SR_UPDATE_TABLE = $00002000;
SQL_SR_UPDATE_COLUMN = $00004000;
// SQL_SQL92_ROW_VALUE_CONSTRUCTOR bitmasks
SQL_SRVC_VALUE_EXPRESSION = $00000001;
SQL_SRVC_NULL = $00000002;
SQL_SRVC_DEFAULT = $00000004;
SQL_SRVC_ROW_SUBQUERY = $00000008;
// SQL_SQL92_VALUE_EXPRESSIONS bitmasks
SQL_SVE_CASE = $00000001;
SQL_SVE_CAST = $00000002;
SQL_SVE_COALESCE = $00000004;
SQL_SVE_NULLIF = $00000008;
// SQL_STANDARD_CLI_CONFORMANCE bitmasks
SQL_SCC_XOPEN_CLI_VERSION1 = $00000001;
SQL_SCC_ISO92_CLI = $00000002;
// SQL_UNION_STATEMENT bitmasks
SQL_US_UNION = SQL_U_UNION;
SQL_US_UNION_ALL = SQL_U_UNION_ALL;
// SQL_DTC_TRANSITION_COST bitmasks
SQL_DTC_ENLIST_EXPENSIVE = $00000001;
SQL_DTC_UNENLIST_EXPENSIVE = $00000002;
// possible values for SQL_ASYNC_DBC_FUNCTIONS
SQL_ASYNC_DBC_NOT_CAPABLE = $00000000;
SQL_ASYNC_DBC_CAPABLE = $00000001;
// additional SQLDataSources fetch directions
SQL_FETCH_FIRST_USER = 31;
SQL_FETCH_FIRST_SYSTEM = 32;
// Defines for SQLSetPos
SQL_ENTIRE_ROWSET = 0;
// Operations in SQLSetPos
SQL_POSITION = 0; // 1.0 FALSE
SQL_REFRESH = 1; // 1.0 TRUE
SQL_UPDATE = 2;
SQL_DELETE = 3;
// Operations in SQLBulkOperations
SQL_ADD = 4;
SQL_SETPOS_MAX_OPTION_VALUE = SQL_ADD;
SQL_UPDATE_BY_BOOKMARK = 5;
SQL_DELETE_BY_BOOKMARK = 6;
SQL_FETCH_BY_BOOKMARK = 7;
// Lock options in SQLSetPos
SQL_LOCK_NO_CHANGE = 0; // 1.0 FALSE
SQL_LOCK_EXCLUSIVE = 1; // 1.0 TRUE
SQL_LOCK_UNLOCK = 2;
SQL_SETPOS_MAX_LOCK_VALUE = SQL_LOCK_UNLOCK;
const
// Column types and scopes in SQLSpecialColumns.
SQL_BEST_ROWID = 1;
SQL_ROWVER = 2;
// Defines for SQLSpecialColumns (returned in the Result set
SQL_PC_NOT_PSEUDO = 1;
// Defines for SQLStatistics
SQL_QUICK = 0;
SQL_ENSURE = 1;
// Defines for SQLStatistics (returned in the Result set)
SQL_TABLE_STAT = 0;
// Defines for SQLTables
SQL_ALL_CATALOGS = '%';
SQL_ALL_SCHEMAS = '%';
SQL_ALL_TABLE_TYPES = '%';
// Options for SQLDriverConnect
SQL_DRIVER_NOPROMPT = 0;
SQL_DRIVER_COMPLETE = 1;
SQL_DRIVER_PROMPT = 2;
SQL_DRIVER_COMPLETE_REQUIRED = 3;
type
TSQLDriverConnect = function(
HDbc: SQLHDbc;
hwnd: SQLHWnd;
szConnStrIn: PSQLChar;
cbConnStrIn: SQLSmallint;
szConnStrOut: PSQLChar;
cbConnStrOutMax: SQLSmallint;
var pcbConnStrOut: SQLSmallint;
fDriverCompletion: SQLUSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
const
// SQLExtendedFetch
SQL_FETCH_BOOKMARK = 8;
// SQLExtendedFetch row status element values
SQL_ROW_SUCCESS = 0;
SQL_ROW_DELETED = 1;
SQL_ROW_UPDATED = 2;
SQL_ROW_NOROW = 3;
SQL_ROW_ADDED = 4;
SQL_ROW_ERROR = 5;
SQL_ROW_SUCCESS_WITH_INFO = 6;
SQL_ROW_PROCEED = 0;
SQL_ROW_IGNORE = 1;
// Value for SQL_DESC_ARRAY_STATUS_PTR
SQL_PARAM_SUCCESS = 0;
SQL_PARAM_SUCCESS_WITH_INFO = 6;
SQL_PARAM_ERROR = 5;
SQL_PARAM_UNUSED = 7;
SQL_PARAM_DIAG_UNAVAILABLE = 1;
SQL_PARAM_PROCEED = 0;
SQL_PARAM_IGNORE = 1;
// Defines for SQLForeignKeys (UPDATE_RULE and DELETE_RULE)
SQL_CASCADE = 0;
SQL_RESTRICT = 1;
SQL_SET_NULL = 2;
SQL_NO_ACTION = 3;
SQL_SET_DEFAULT = 4;
// Note that the following are in a different column of SQLForeignKeys than
// the previous #defines. These are for DEFERRABILITY.
SQL_INITIALLY_DEFERRED = 5;
SQL_INITIALLY_IMMEDIATE = 6;
SQL_NOT_DEFERRABLE = 7;
// Defines for SQLProcedures (returned in the Result set)
SQL_PT_UNKNOWN = 0;
SQL_PT_PROCEDURE = 1;
SQL_PT_FUNCTION = 2;
type
TSQLBrowseConnect = function(
HDbc: SQLHDbc;
szConnStrIn: PSQLChar;
cbConnStrIn: SQLSmallint;
szConnStrOut: PSQLChar;
cbConnStrOutMax: SQLSmallint;
var pcbConnStrOut: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLBulkOperations = function(
StatementHandle: SQLHStmt;
Operation: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLColAttributes = function(
HStmt: SQLHStmt;
icol: SQLUSmallint;
fDescType: SQLUSmallint;
rgbDesc: SQLPointer;
cbDescMax: SQLSmallint;
var pcbDesc: SQLSmallint;
var pfDesc: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLColumnPrivileges = function(
HStmt: SQLHStmt;
var szCatalogName: SQLChar;
cbCatalogName: SQLSmallint;
var szSchemaName: SQLChar;
cbSchemaName: SQLSmallint;
var szTableName: SQLChar;
cbTableName: SQLSmallint;
var szColumnName: SQLChar;
cbColumnName: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLDescribeParam = function(
HStmt: SQLHStmt;
ipar: SQLUSmallint;
var pfSQLType: SQLSmallint;
var pcbParamDef: SQLULen;
var pibScale: SQLSmallint;
var pfNullable: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLExtendedFetch = function(
HStmt: SQLHStmt;
fFetchType: SQLUSmallint;
irow: SQLLen;
var pcrow: SQLULen;
var rgfRowStatus: SQLUSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLForeignKeys = function(
HStmt: SQLHStmt;
szPkCatalogName: PSQLChar;
cbPkCatalogName: SQLSmallint;
szPkSchemaName: PSQLChar;
cbPkSchemaName: SQLSmallint;
szPkTableName: PSQLChar;
cbPkTableName: SQLSmallint;
szFkCatalogName: PSQLChar;
cbFkCatalogName: SQLSmallint;
szFkSchemaName: PSQLChar;
cbFkSchemaName: SQLSmallint;
szFkTableName: PSQLChar;
cbFkTableName: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLMoreResults = function(
HStmt: SQLHStmt
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLNativeSQL = function(
HDbc: SQLHDbc;
var szSQLStrIn: SQLChar;
cbSQLStrIn: SQLInteger;
var szSQLStr: SQLChar;
cbSQLStrMax: SQLInteger;
var pcbSQLStr: SQLInteger
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLNumParams = function(
HStmt: SQLHStmt;
var pcpar: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLParamOptions = function(
HStmt: SQLHStmt;
crow: SQLULen;
var pirow: SQLULen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLPrimaryKeys = function(
HStmt: SQLHStmt;
szCatalogName: PSQLChar;
cbCatalogName: SQLSmallint;
szSchemaName: PSQLChar;
cbSchemaName: SQLSmallint;
szTableName: PSQLChar;
cbTableName: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLProcedureColumns = function(
HStmt: SQLHStmt;
szCatalogName: PSQLChar;
cbCatalogName: SQLSmallint;
szSchemaName: PSQLChar;
cbSchemaName: SQLSmallint;
szProcName: PSQLChar;
cbProcName: SQLSmallint;
szColumnName: PSQLChar;
cbColumnName: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLProcedures = function(
HStmt: SQLHStmt;
szCatalogName: PSQLChar;
cbCatalogName: SQLSmallint;
szSchemaName: PSQLChar;
cbSchemaName: SQLSmallint;
szProcName: PSQLChar;
cbProcName: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLSetPos = function(
HStmt: SQLHStmt;
irow: SQLSetPosiRow;
fOption: SQLUSmallint;
fLock: SQLUSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLTablePrivileges = function(
HStmt: SQLHStmt;
var szCatalogName: SQLChar;
cbCatalogName: SQLSmallint;
var szSchemaName: SQLChar;
cbSchemaName: SQLSmallint;
var szTableName: SQLChar;
cbTableName: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLDrivers = function(
HEnv: SQLHEnv;
fDirection: SQLUSmallint;
szDriverDesc: PSQLChar;
cbDriverDescMax: SQLSmallint;
var pcbDriverDesc: SQLSmallint;
szDriverAttributes: PSQLChar;
cbDrvrAttrMax: SQLSmallint;
var pcbDrvrAttr: SQLSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLBindParameter = function(
HStmt: SQLHStmt;
ipar: SQLUSmallint;
fParamType: SQLSmallint;
fCType: SQLSmallint;
fSQLType: SQLSmallint;
cbColDef: SQLULen;
ibScale: SQLSmallint;
rgbValue: SQLPointer;
cbValueMax: SQLLen;
pcbValue: PSQLLen
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
const
// SQLAllocHandleStd is implemented to make SQLAllocHandle
// compatible with X/Open standard. an application should
// not call SQLAllocHandleStd directly
// Internal type subcodes (ODBC_STD, ie X/OPEN)
SQL_YEAR = SQL_CODE_YEAR;
SQL_MONTH = SQL_CODE_MONTH;
SQL_DAY = SQL_CODE_DAY;
SQL_HOUR = SQL_CODE_HOUR;
SQL_MINUTE = SQL_CODE_MINUTE;
SQL_SECOND = SQL_CODE_SECOND;
SQL_YEAR_TO_MONTH = SQL_CODE_YEAR_TO_MONTH;
SQL_DAY_TO_HOUR = SQL_CODE_DAY_TO_HOUR;
SQL_DAY_TO_MINUTE = SQL_CODE_DAY_TO_MINUTE;
SQL_DAY_TO_SECOND = SQL_CODE_DAY_TO_SECOND;
SQL_HOUR_TO_MINUTE = SQL_CODE_HOUR_TO_MINUTE;
SQL_HOUR_TO_SECOND = SQL_CODE_HOUR_TO_SECOND;
SQL_MINUTE_TO_SECOND = SQL_CODE_MINUTE_TO_SECOND;
type
TSQLAllocHandleStd = function(
fHandleType: SQLSmallint;
hInput: SQLHandle;
var phOutput: SQLHandle
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
const
// Deprecated defines from prior versions of ODBC
SQL_DATABASE_NAME = 16; // Use SQLGetConnectOption/SQL_CURRENT_QUALIFIER
SQL_FD_FETCH_PREV = SQL_FD_FETCH_PRIOR;
SQL_FETCH_PREV = SQL_FETCH_PRIOR;
SQL_CONCUR_TIMESTAMP = SQL_CONCUR_ROWVER;
SQL_SCCO_OPT_TIMESTAMP = SQL_SCCO_OPT_ROWVER;
SQL_CC_DELETE = SQL_CB_DELETE;
SQL_CR_DELETE = SQL_CB_DELETE;
SQL_CC_CLOSE = SQL_CB_CLOSE;
SQL_CR_CLOSE = SQL_CB_CLOSE;
SQL_CC_PRESERVE = SQL_CB_PRESERVE;
SQL_CR_PRESERVE = SQL_CB_PRESERVE;
// SQL_FETCH_RESUME is not supported by 2.0+ drivers
SQL_FETCH_RESUME = 7;
SQL_SCROLL_FORWARD_ONLY = 0; //-SQL_CURSOR_FORWARD_ONLY
SQL_SCROLL_KEYSET_DRIVEN = -1; //-SQL_CURSOR_KEYSET_DRIVEN
SQL_SCROLL_DYNAMIC = -2; //-SQL_CURSOR_DYNAMIC
SQL_SCROLL_STATIC = -3; //-SQL_CURSOR_STATIC
type
// Deprecated functions from prior versions of ODBC
// Use SQLSetStmtOptions
TSQLSetScrollOptions = function(
HStmt: SQLHStmt;
fConcurrency: SQLUSmallint;
crowKeyset: SQLLen;
crowRowset: SQLUSmallint
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
{----------------------------------------------------------------------------}
{ ODBCINST.H }
{----------------------------------------------------------------------------}
const
// SQLConfigDataSource request flags
ODBC_ADD_DSN = 1; // Add data source
ODBC_CONFIG_DSN = 2; // Configure (edit) data source
ODBC_REMOVE_DSN = 3; // Remove data source
ODBC_ADD_SYS_DSN = 4; // add a system DSN
ODBC_CONFIG_SYS_DSN = 5; // Configure a system DSN
ODBC_REMOVE_SYS_DSN = 6; // remove a system DSN
ODBC_REMOVE_DEFAULT_DSN = 7; // remove the default DSN
// install request flags
ODBC_INSTALL_INQUIRY = 1;
ODBC_INSTALL_COMPLETE = 2;
// config driver flags
ODBC_INSTALL_DRIVER = 1;
ODBC_REMOVE_DRIVER = 2;
ODBC_CONFIG_DRIVER = 3;
ODBC_CONFIG_DRIVER_MAX = 100;
// SQLGetConfigMode and SQLSetConfigMode flags
ODBC_BOTH_DSN = 0;
ODBC_USER_DSN = 1;
ODBC_SYSTEM_DSN = 2;
// SQLInstallerError code
ODBC_ERROR_GENERAL_ERR = 1;
ODBC_ERROR_INVALID_BUFF_LEN = 2;
ODBC_ERROR_INVALID_HWND = 3;
ODBC_ERROR_INVALID_STR = 4;
ODBC_ERROR_INVALID_REQUEST_TYPE = 5;
ODBC_ERROR_COMPONENT_NOT_FOUND = 6;
ODBC_ERROR_INVALID_NAME = 7;
ODBC_ERROR_INVALID_KEYWORD_VALUE = 8;
ODBC_ERROR_INVALID_DSN = 9;
ODBC_ERROR_INVALID_INF = 10;
ODBC_ERROR_REQUEST_FAILED = 11;
ODBC_ERROR_INVALID_PATH = 12;
ODBC_ERROR_LOAD_LIB_FAILED = 13;
ODBC_ERROR_INVALID_PARAM_SEQUENCE = 14;
ODBC_ERROR_INVALID_LOG_FILE = 15;
ODBC_ERROR_USER_CANCELED = 16;
ODBC_ERROR_USAGE_UPDATE_FAILED = 17;
ODBC_ERROR_CREATE_DSN_FAILED = 18;
ODBC_ERROR_WRITING_SYSINFO_FAILED = 19;
ODBC_ERROR_REMOVE_DSN_FAILED = 20;
ODBC_ERROR_OUT_OF_MEM = 21;
ODBC_ERROR_OUTPUT_STRING_TRUNCATED = 22;
ODBC_ERROR_NOTRANINFO = 23;
ODBC_ERROR_MAX = ODBC_ERROR_NOTRANINFO; // update this when we add new error message
type
TSQLConfigDataSource = function (
hwndParent: SQLHWnd;
fRequest: WORD;
lpszDriver: PSQLChar;
lpszAttributes: PSQLChar
): SQLBOOL; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TSQLInstallerError = function (
iError: WORD;
var pfErrorCode: UDword;
lpszErrorMsg: PSQLChar;
cbErrorMsgMax: WORD;
var pcbErrorMsg: WORD
): SQLReturn; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
{----------------------------------------------------------------------------}
{ MSSQL specific }
{----------------------------------------------------------------------------}
const
// MSSQL 2005 Server data types
SQL_SS_VARIANT = -150;
SQL_SS_UDT = -151;
SQL_SS_XML = -152;
// MSSQL 2008 Server data types
SQL_SS_TABLE = -153;
SQL_SS_TIME2 = -154;
SQL_SS_TIMESTAMPOFFSET = -155;
type
PSQLSSTime2Struct = ^TSQLSSTime2Struct;
TSQLSSTime2Struct = record
Hour: SQLUSmallint;
Minute: SQLUSmallint;
Second: SQLUSmallint;
Fraction: SQLUInteger;
end;
SQL_SS_TIME2_STRUCT = TSQLSSTime2Struct;
PSQLSSTimeStampOffset = ^TSQLSSTimeStampOffset;
TSQLSSTimeStampOffset = record
Year: SQLSmallint;
Month: SQLUSmallint;
Day: SQLUSmallint;
Hour: SQLUSmallint;
Minute: SQLUSmallint;
Second: SQLUSmallint;
Fraction: SQLUInteger;
Timezone_Hour: SQLSmallint;
Timezone_Minute: SQLSmallint;
end;
SQL_SS_TIMESTAMPOFFSET_STRUCT = TSQLSSTimeStampOffset;
const
// SQLSetConnectAttr driver specific defines.
// Microsoft has 1200 thru 1249 reserved for Microsoft SQL Native Client driver usage.
// Connection attributes
SQL_COPT_SS_BASE = 1200;
SQL_COPT_SS_REMOTE_PWD = (SQL_COPT_SS_BASE+1); // dbrpwset SQLSetConnectOption only
SQL_COPT_SS_USE_PROC_FOR_PREP = (SQL_COPT_SS_BASE+2); // Use create proc for SQLPrepare
SQL_COPT_SS_INTEGRATED_SECURITY = (SQL_COPT_SS_BASE+3); // Force integrated security on login
SQL_COPT_SS_PRESERVE_CURSORS = (SQL_COPT_SS_BASE+4); // Preserve server cursors after SQLTransact
SQL_COPT_SS_USER_DATA = (SQL_COPT_SS_BASE+5); // dbgetuserdata/dbsetuserdata
SQL_COPT_SS_ENLIST_IN_DTC = SQL_ATTR_ENLIST_IN_DTC; // Enlist in a DTC transaction
SQL_COPT_SS_ENLIST_IN_XA = SQL_ATTR_ENLIST_IN_XA; // Enlist in a XA transaction
SQL_COPT_SS_FALLBACK_CONNECT = (SQL_COPT_SS_BASE+10); // Enables FallBack connections
SQL_COPT_SS_PERF_DATA = (SQL_COPT_SS_BASE+11); // Used to access SQL Server ODBC driver performance data
SQL_COPT_SS_PERF_DATA_LOG = (SQL_COPT_SS_BASE+12); // Used to set the logfile name for the Performance data
SQL_COPT_SS_PERF_QUERY_INTERVAL = (SQL_COPT_SS_BASE+13); // Used to set the query logging threshold in milliseconds.
SQL_COPT_SS_PERF_QUERY_LOG = (SQL_COPT_SS_BASE+14); // Used to set the logfile name for saving queryies.
SQL_COPT_SS_PERF_QUERY = (SQL_COPT_SS_BASE+15); // Used to start and stop query logging.
SQL_COPT_SS_PERF_DATA_LOG_NOW = (SQL_COPT_SS_BASE+16); // Used to make a statistics log entry to disk.
SQL_COPT_SS_QUOTED_IDENT = (SQL_COPT_SS_BASE+17); // Enable/Disable Quoted Identifiers
SQL_COPT_SS_ANSI_NPW = (SQL_COPT_SS_BASE+18); // Enable/Disable ANSI NULL, Padding and Warnings
SQL_COPT_SS_BCP = (SQL_COPT_SS_BASE+19); // Allow BCP usage on connection
SQL_COPT_SS_TRANSLATE = (SQL_COPT_SS_BASE+20); // Perform code page translation
SQL_COPT_SS_ATTACHDBFILENAME = (SQL_COPT_SS_BASE+21); // File name to be attached as a database
SQL_COPT_SS_CONCAT_NULL = (SQL_COPT_SS_BASE+22); // Enable/Disable CONCAT_NULL_YIELDS_NULL
SQL_COPT_SS_ENCRYPT = (SQL_COPT_SS_BASE+23); // Allow strong encryption for data
SQL_COPT_SS_MARS_ENABLED = (SQL_COPT_SS_BASE+24); // Multiple active result set per connection
SQL_COPT_SS_FAILOVER_PARTNER = (SQL_COPT_SS_BASE+25); // Failover partner server
SQL_COPT_SS_OLDPWD = (SQL_COPT_SS_BASE+26); // Old Password, used when changing password during login
SQL_COPT_SS_TXN_ISOLATION = (SQL_COPT_SS_BASE+27); // Used to set/get any driver-specific or ODBC-defined TXN iso level
SQL_COPT_SS_TRUST_SERVER_CERTIFICATE = (SQL_COPT_SS_BASE+28); // Trust server certificate
SQL_COPT_SS_SERVER_SPN = (SQL_COPT_SS_BASE+29); // Server SPN
SQL_COPT_SS_FAILOVER_PARTNER_SPN = (SQL_COPT_SS_BASE+30); // Failover partner server SPN
SQL_COPT_SS_INTEGRATED_AUTHENTICATION_METHOD = (SQL_COPT_SS_BASE+31); // The integrated authentication method used for the connection
SQL_COPT_SS_MUTUALLY_AUTHENTICATED = (SQL_COPT_SS_BASE+32); // Used to decide if the connection is mutually authenticated
SQL_COPT_SS_MAX_USED = SQL_COPT_SS_MUTUALLY_AUTHENTICATED;
// SQLSetStmtAttr SQL Native Client driver specific defines.
// Statement attributes
SQL_SOPT_SS_BASE = 1225;
SQL_SOPT_SS_TEXTPTR_LOGGING = (SQL_SOPT_SS_BASE+0); // Text pointer logging
SQL_SOPT_SS_CURRENT_COMMAND = (SQL_SOPT_SS_BASE+1); // dbcurcmd SQLGetStmtOption only
SQL_SOPT_SS_HIDDEN_COLUMNS = (SQL_SOPT_SS_BASE+2); // Expose FOR BROWSE hidden columns
SQL_SOPT_SS_NOBROWSETABLE = (SQL_SOPT_SS_BASE+3); // Set NOBROWSETABLE option
SQL_SOPT_SS_REGIONALIZE = (SQL_SOPT_SS_BASE+4); // Regionalize output character conversions
SQL_SOPT_SS_CURSOR_OPTIONS = (SQL_SOPT_SS_BASE+5); // Server cursor options
SQL_SOPT_SS_NOCOUNT_STATUS = (SQL_SOPT_SS_BASE+6); // Real vs. Not Real row count indicator
SQL_SOPT_SS_DEFER_PREPARE = (SQL_SOPT_SS_BASE+7); // Defer prepare until necessary
SQL_SOPT_SS_QUERYNOTIFICATION_TIMEOUT = (SQL_SOPT_SS_BASE+8); // Notification timeout
SQL_SOPT_SS_QUERYNOTIFICATION_MSGTEXT = (SQL_SOPT_SS_BASE+9); // Notification message text
SQL_SOPT_SS_QUERYNOTIFICATION_OPTIONS = (SQL_SOPT_SS_BASE+10); // SQL service broker name
SQL_SOPT_SS_PARAM_FOCUS = (SQL_SOPT_SS_BASE+11); // Direct subsequent calls to parameter related methods to set properties on constituent columns/parameters of container types
SQL_SOPT_SS_NAME_SCOPE = (SQL_SOPT_SS_BASE+12); // Sets name scope for subsequent catalog function calls
SQL_SOPT_SS_MAX_USED = SQL_SOPT_SS_NAME_SCOPE;
SQL_COPT_SS_BASE_EX = 1240;
SQL_COPT_SS_BROWSE_CONNECT = (SQL_COPT_SS_BASE_EX+1); // Browse connect mode of operation
SQL_COPT_SS_BROWSE_SERVER = (SQL_COPT_SS_BASE_EX+2); // Single Server browse request.
SQL_COPT_SS_WARN_ON_CP_ERROR = (SQL_COPT_SS_BASE_EX+3); // Issues warning when data from the server
// had a loss during code page conversion.
SQL_COPT_SS_CONNECTION_DEAD = (SQL_COPT_SS_BASE_EX+4); // dbdead SQLGetConnectOption only
// It will try to ping the server.
// Expensive connection check
SQL_COPT_SS_BROWSE_CACHE_DATA = (SQL_COPT_SS_BASE_EX+5); // Determines if we should cache browse info
// Used when returned buffer is greater then ODBC limit (32K)
SQL_COPT_SS_RESET_CONNECTION = (SQL_COPT_SS_BASE_EX+6); // When this option is set, we will perform connection reset
// on next packet
SQL_COPT_SS_EX_MAX_USED = SQL_COPT_SS_RESET_CONNECTION;
// SQLColAttributes driver specific defines.
// SQLSetDescField/SQLGetDescField driver specific defines.
// Microsoft has 1200 thru 1249 reserved for Microsoft SQL Native Client driver usage.
SQL_CA_SS_BASE = 1200;
SQL_CA_SS_COLUMN_SSTYPE = (SQL_CA_SS_BASE+0); // dbcoltype/dbalttype
SQL_CA_SS_COLUMN_UTYPE = (SQL_CA_SS_BASE+1); // dbcolutype/dbaltutype
SQL_CA_SS_NUM_ORDERS = (SQL_CA_SS_BASE+2); // dbnumorders
SQL_CA_SS_COLUMN_ORDER = (SQL_CA_SS_BASE+3); // dbordercol
SQL_CA_SS_COLUMN_VARYLEN = (SQL_CA_SS_BASE+4); // dbvarylen
SQL_CA_SS_NUM_COMPUTES = (SQL_CA_SS_BASE+5); // dbnumcompute
SQL_CA_SS_COMPUTE_ID = (SQL_CA_SS_BASE+6); // dbnextrow status return
SQL_CA_SS_COMPUTE_BYLIST = (SQL_CA_SS_BASE+7); // dbbylist
SQL_CA_SS_COLUMN_ID = (SQL_CA_SS_BASE+8); // dbaltcolid
SQL_CA_SS_COLUMN_OP = (SQL_CA_SS_BASE+9); // dbaltop
SQL_CA_SS_COLUMN_SIZE = (SQL_CA_SS_BASE+10); // dbcollen
SQL_CA_SS_COLUMN_HIDDEN = (SQL_CA_SS_BASE+11); // Column is hidden (FOR BROWSE)
SQL_CA_SS_COLUMN_KEY = (SQL_CA_SS_BASE+12); // Column is key column (FOR BROWSE)
// SQL_DESC_BASE_COLUMN_NAME_OLD = (SQL_CA_SS_BASE+13); // This is defined at another location.
SQL_CA_SS_COLUMN_COLLATION = (SQL_CA_SS_BASE+14); // Column collation (only for chars)
// VARIANT type related metadata
SQL_CA_SS_VARIANT_TYPE = (SQL_CA_SS_BASE+15);
SQL_CA_SS_VARIANT_SQL_TYPE = (SQL_CA_SS_BASE+16);
SQL_CA_SS_VARIANT_SERVER_TYPE = (SQL_CA_SS_BASE+17);
// XML and CLR UDT type related metadata
SQL_CA_SS_UDT_CATALOG_NAME = (SQL_CA_SS_BASE+18); // UDT catalog name
SQL_CA_SS_UDT_SCHEMA_NAME = (SQL_CA_SS_BASE+19); // UDT schema name
SQL_CA_SS_UDT_TYPE_NAME = (SQL_CA_SS_BASE+20); // UDT type name
SQL_CA_SS_UDT_ASSEMBLY_TYPE_NAME = (SQL_CA_SS_BASE+21); // Qualified name of the assembly containing the UDT class
SQL_CA_SS_XML_SCHEMACOLLECTION_CATALOG_NAME=(SQL_CA_SS_BASE+22); // Name of the catalog that contains XML Schema collection
SQL_CA_SS_XML_SCHEMACOLLECTION_SCHEMA_NAME= (SQL_CA_SS_BASE+23); // Name of the schema that contains XML Schema collection
SQL_CA_SS_XML_SCHEMACOLLECTION_NAME = (SQL_CA_SS_BASE+24); // Name of the XML Schema collection
SQL_CA_SS_CATALOG_NAME = (SQL_CA_SS_BASE+25); // Catalog name
SQL_CA_SS_SCHEMA_NAME = (SQL_CA_SS_BASE+26); // Schema name
SQL_CA_SS_TYPE_NAME = (SQL_CA_SS_BASE+27); // Type name
// table valued parameter related metadata
SQL_CA_SS_COLUMN_COMPUTED = (SQL_CA_SS_BASE+29); // column is computed
SQL_CA_SS_COLUMN_IN_UNIQUE_KEY = (SQL_CA_SS_BASE+30); // column is part of a unique key
SQL_CA_SS_COLUMN_SORT_ORDER = (SQL_CA_SS_BASE+31); // column sort order
SQL_CA_SS_COLUMN_SORT_ORDINAL = (SQL_CA_SS_BASE+32); // column sort ordinal
SQL_CA_SS_COLUMN_HAS_DEFAULT_VALUE = (SQL_CA_SS_BASE+33); // column has default value for all rows of the table valued parameter
// sparse column related metadata
SQL_CA_SS_IS_COLUMN_SET = (SQL_CA_SS_BASE+34); // column is a column-set column for sparse columns
// Legacy datetime related metadata
SQL_CA_SS_SERVER_TYPE = (SQL_CA_SS_BASE+35); // column type to send on the wire for datetime types
SQL_CA_SS_MAX_USED = (SQL_CA_SS_BASE+36);
// Defines returned by SQL_ATTR_CURSOR_TYPE/SQL_CURSOR_TYPE
SQL_CURSOR_FAST_FORWARD_ONLY = 8; // Only returned by SQLGetStmtAttr/Option
// Defines for use with SQL_COPT_SS_USE_PROC_FOR_PREP
SQL_UP_OFF = 0; // Procedures won't be used for prepare
SQL_UP_ON = 1; // Procedures will be used for prepare
SQL_UP_ON_DROP = 2; // Temp procedures will be explicitly dropped
SQL_UP_DEFAULT = SQL_UP_ON;
// Defines for use with SQL_COPT_SS_INTEGRATED_SECURITY - Pre-Connect Option only
SQL_IS_OFF = 0; // Integrated security isn't used
SQL_IS_ON = 1; // Integrated security is used
SQL_IS_DEFAULT = SQL_IS_OFF;
// Defines for use with SQL_COPT_SS_PRESERVE_CURSORS
SQL_PC_OFF = 0; // Cursors are closed on SQLTransact
SQL_PC_ON = 1; // Cursors remain open on SQLTransact
SQL_PC_DEFAULT = SQL_PC_OFF;
// Defines for use with SQL_COPT_SS_USER_DATA
SQL_UD_NOTSET = nil; // No user data pointer set
// Defines for use with SQL_COPT_SS_TRANSLATE
SQL_XL_OFF = 0; // Code page translation is not performed
SQL_XL_ON = 1; // Code page translation is performed
SQL_XL_DEFAULT = SQL_XL_ON;
// Defines for use with SQL_COPT_SS_FALLBACK_CONNECT - Pre-Connect Option only
SQL_FB_OFF = 0; // FallBack connections are disabled
SQL_FB_ON = 1; // FallBack connections are enabled
SQL_FB_DEFAULT = SQL_FB_OFF;
// Defines for use with SQL_COPT_SS_BCP - Pre-Connect Option only
SQL_BCP_OFF = 0; // BCP is not allowed on connection
SQL_BCP_ON = 1; // BCP is allowed on connection
SQL_BCP_DEFAULT = SQL_BCP_OFF;
// Defines for use with SQL_COPT_SS_QUOTED_IDENT
SQL_QI_OFF = 0; // Quoted identifiers are enable
SQL_QI_ON = 1; // Quoted identifiers are disabled
SQL_QI_DEFAULT = SQL_QI_ON;
// Defines for use with SQL_COPT_SS_ANSI_NPW - Pre-Connect Option only
SQL_AD_OFF = 0; // ANSI NULLs, Padding and Warnings are enabled
SQL_AD_ON = 1; // ANSI NULLs, Padding and Warnings are disabled
SQL_AD_DEFAULT = SQL_AD_ON;
// Defines for use with SQL_COPT_SS_CONCAT_NULL - Pre-Connect Option only
SQL_CN_OFF = 0; // CONCAT_NULL_YIELDS_NULL is off
SQL_CN_ON = 1; // CONCAT_NULL_YIELDS_NULL is on
SQL_CN_DEFAULT = SQL_CN_ON;
// Defines for use with SQL_SOPT_SS_TEXTPTR_LOGGING
SQL_TL_OFF = 0; // No logging on text pointer ops
SQL_TL_ON = 1; // Logging occurs on text pointer ops
SQL_TL_DEFAULT = SQL_TL_ON;
// Defines for use with SQL_SOPT_SS_HIDDEN_COLUMNS
SQL_HC_OFF = 0; // FOR BROWSE columns are hidden
SQL_HC_ON = 1; // FOR BROWSE columns are exposed
SQL_HC_DEFAULT = SQL_HC_OFF;
// Defines for use with SQL_SOPT_SS_NOBROWSETABLE
SQL_NB_OFF = 0; // NO_BROWSETABLE is off
SQL_NB_ON = 1; // NO_BROWSETABLE is on
SQL_NB_DEFAULT = SQL_NB_OFF;
// Defines for use with SQL_SOPT_SS_REGIONALIZE
SQL_RE_OFF = 0; // No regionalization occurs on output character conversions
SQL_RE_ON = 1; // Regionalization occurs on output character conversions
SQL_RE_DEFAULT = SQL_RE_OFF;
// Defines for use with SQL_SOPT_SS_CURSOR_OPTIONS
SQL_CO_OFF = 0; // Clear all cursor options
SQL_CO_FFO = 1; // Fast-forward cursor will be used
SQL_CO_AF = 2; // Autofetch on cursor open
SQL_CO_FFO_AF = (SQL_CO_FFO or SQL_CO_AF); // Fast-forward cursor with autofetch
SQL_CO_FIREHOSE_AF = 4; // Auto fetch on fire-hose cursors
SQL_CO_DEFAULT = SQL_CO_OFF;
//SQL_SOPT_SS_NOCOUNT_STATUS
SQL_NC_OFF = 0;
SQL_NC_ON = 1;
//SQL_SOPT_SS_DEFER_PREPARE
SQL_DP_OFF = 0;
SQL_DP_ON = 1;
//SQL_SOPT_SS_NAME_SCOPE
SQL_SS_NAME_SCOPE_TABLE = 0;
SQL_SS_NAME_SCOPE_TABLE_TYPE = 1;
SQL_SS_NAME_SCOPE_EXTENDED = 2;
SQL_SS_NAME_SCOPE_SPARSE_COLUMN_SET=3;
SQL_SS_NAME_SCOPE_DEFAULT = SQL_SS_NAME_SCOPE_TABLE;
//SQL_COPT_SS_ENCRYPT
SQL_EN_OFF = 0;
SQL_EN_ON = 1;
//SQL_COPT_SS_TRUST_SERVER_CERTIFICATE
SQL_TRUST_SERVER_CERTIFICATE_NO = 0;
SQL_TRUST_SERVER_CERTIFICATE_YES = 1;
//SQL_COPT_SS_BROWSE_CONNECT
SQL_MORE_INFO_NO = 0;
SQL_MORE_INFO_YES = 1;
//SQL_COPT_SS_BROWSE_CACHE_DATA
SQL_CACHE_DATA_NO = 0;
SQL_CACHE_DATA_YES = 1;
//SQL_COPT_SS_RESET_CONNECTION
SQL_RESET_YES = 1;
//SQL_COPT_SS_WARN_ON_CP_ERROR
SQL_WARN_NO = 0;
SQL_WARN_YES = 1;
//SQL_COPT_SS_MARS_ENABLED
SQL_MARS_ENABLED_NO = 0;
SQL_MARS_ENABLED_YES = 1;
// SQL_TXN_ISOLATION_OPTION bitmasks
SQL_TXN_SS_SNAPSHOT = $20;
// The following are defines for SQL_CA_SS_COLUMN_SORT_ORDER
SQL_SS_ORDER_UNSPECIFIED = 0;
SQL_SS_DESCENDING_ORDER = 1;
SQL_SS_ASCENDING_ORDER = 2;
SQL_SS_ORDER_DEFAULT = SQL_SS_ORDER_UNSPECIFIED;
// SQL_SS_LENGTH_UNLIMITED is used to describe the max length of
// VARCHAR(max), VARBINARY(max), NVARCHAR(max), and XML columns
SQL_SS_LENGTH_UNLIMITED = 0;
// User Data Type definitions.
// Returned by SQLColAttributes/SQL_CA_SS_COLUMN_UTYPE.
SQLudtBINARY = 3;
SQLudtBIT = 16;
SQLudtBITN = 0;
SQLudtCHAR = 1;
SQLudtDATETIM4 = 22;
SQLudtDATETIME = 12;
SQLudtDATETIMN = 15;
SQLudtDECML = 24;
SQLudtDECMLN = 26;
SQLudtFLT4 = 23;
SQLudtFLT8 = 8;
SQLudtFLTN = 14;
SQLudtIMAGE = 20;
SQLudtINT1 = 5;
SQLudtINT2 = 6;
SQLudtINT4 = 7;
SQLudtINTN = 13;
SQLudtMONEY = 11;
SQLudtMONEY4 = 21;
SQLudtMONEYN = 17;
SQLudtNUM = 10;
SQLudtNUMN = 25;
SQLudtSYSNAME = 18;
SQLudtTEXT = 19;
SQLudtTIMESTAMP = 80;
SQLudtUNIQUEIDENTIFIER = 0;
SQLudtVARBINARY = 4;
SQLudtVARCHAR = 2;
MIN_USER_DATATYPE = 256;
// Aggregate operator types.
// Returned by SQLColAttributes/SQL_CA_SS_COLUMN_OP.
SQLAOPSTDEV = $30; // Standard deviation
SQLAOPSTDEVP = $31; // Standard deviation population
SQLAOPVAR = $32; // Variance
SQLAOPVARP = $33; // Variance population
SQLAOPCNT = $4b; // Count
SQLAOPSUM = $4d; // Sum
SQLAOPAVG = $4f; // Average
SQLAOPMIN = $51; // Min
SQLAOPMAX = $52; // Max
SQLAOPANY = $53; // Any
SQLAOPNOOP = $56; // None
// SQLGetDiagField driver specific defines.
// Microsoft has -1150 thru -1199 reserved for Microsoft SQL Server driver usage.
SQL_DIAG_SS_BASE = -1150;
SQL_DIAG_SS_MSGSTATE = SQL_DIAG_SS_BASE;
SQL_DIAG_SS_SEVERITY = SQL_DIAG_SS_BASE - 1;
SQL_DIAG_SS_SRVNAME = SQL_DIAG_SS_BASE - 2;
SQL_DIAG_SS_PROCNAME = SQL_DIAG_SS_BASE - 3;
SQL_DIAG_SS_LINE = SQL_DIAG_SS_BASE - 4;
{----------------------------------------------------------------------------}
{ DB2 specific }
{----------------------------------------------------------------------------}
const
SQL_ATTR_LONGDATA_COMPAT = 1253;
SQL_LD_COMPAT_NO = 0;
SQL_LD_COMPAT_YES = 1;
SQL_ATTR_MAPCHAR = 2546;
SQL_MAPCHAR_DEFAULT = 0;
SQL_MAPCHAR_WCHAR = 1;
SQL_ATTR_DESCRIBE_OUTPUT_LEVEL = 2506;
SQL_ATTR_USE_TRUSTED_CONTEXT = 2561;
SQL_GRAPHIC = -95;
SQL_VARGRAPHIC = -96;
SQL_LONGVARGRAPHIC = -97;
// These types are used if LONGDATA_COMPAT don't set to SQL_LD_COMPAT_YES
SQL_BLOB = -98;
SQL_CLOB = -99;
SQL_DBCLOB = -350;
SQL_XML = -370;
SQL_DECFLOAT = -360;
SQL_DATALINK = -400;
SQL_USER_DEFINED_TYPE = -450;
SQL_PARAMOPT_ATOMIC = 1260;
SQL_ATTR_PARAMOPT_ATOMIC = SQL_PARAMOPT_ATOMIC;
// Options for SQL_PARAMOPT_ATOMIC
SQL_ATOMIC_YES = 1;
SQL_ATOMIC_NO = 0;
SQL_ATOMIC_DEFAULT = SQL_ATOMIC_YES;
{----------------------------------------------------------------------------}
{ Oracle specific }
{----------------------------------------------------------------------------}
const
SQL_REFCURSOR = -403;
{----------------------------------------------------------------------------}
{ Sybase SQL Anywhere specific }
{----------------------------------------------------------------------------}
const
SA_UNUSED_OPTION = 1900;
SA_GET_SQLCA = 1901; // historical
SA_GET_STATEMENT_HANDLE = 1902;
SA_SQL_COLUMN_ISKEY = 1903;
SA_REGISTER_MESSAGE_CALLBACK = 1904;
SA_CONVERT_TO_UNICODE = 1905;
SA_GET_MESSAGE_CALLBACK_PARM = 1906;
SA_USE_ISOLATION_ON_OPEN = 1907;
SA_SQL_DESC_ISKEY = SA_SQL_COLUMN_ISKEY;
SA_SQL_ATTR_TXN_ISOLATION = 1908;
SA_CLIENT_API_NAME = 1909;
// Extended SQL_TXN_ISOLATION_OPTION bitmasks
SA_SQL_TXN_SNAPSHOT = $00000020;
SA_SQL_TXN_STATEMENT_SNAPSHOT = $00000040;
SA_SQL_TXN_READONLY_STATEMENT_SNAPSHOT = $00000080;
// Extra Information requested by OLEDB of SQLGetInfo()
SQL_OLEDB_GET_CHARSET_ID = 10101;
SQL_OLEDB_GET_CHARSET_WIDTH = 10102;
// Message types from the message callback
MESSAGE_TYPE_INFO = 0;
MESSAGE_TYPE_WARNING = 1;
MESSAGE_TYPE_ACTION = 2;
MESSAGE_TYPE_STATUS = 3;
type
TASA_SQL_CALLBACK = procedure (SQLCA: Pointer; msg_type: byte; code: LongWord;
len: Word; msg: PChar); stdcall;
{----------------------------------------------------------------------------}
{ Informix specific }
{----------------------------------------------------------------------------}
// http://publib.boulder.ibm.com/infocenter/idshelp/v10/topic/com.ibm.odbc.doc/odbc.htm
// http://publib.boulder.ibm.com/infocenter/idshelp/v10/topic/com.ibm.odbc.doc/odbc76.htm#sii-04-31114
const
SQL_TXN_LAST_COMMITTED = $00000010;
SQL_TRANSACTION_LAST_COMMITTED = SQL_TXN_LAST_COMMITTED;
SQL_TXN_TRANSACTION = $00000020;
SQL_TRANSACTION_TRANSACTION = SQL_TXN_TRANSACTION;
// For extended errors
SQL_DIAG_ISAM_ERROR = 13;
SQL_DIAG_XA_ERROR = 14;
// Value for SQL_DESC_ARRAY_STATUS_PTR
// Informix returns 4 instead of SQL_PARAM_SUCCESS
SQL_INFX_PARAM_SUCCESS = 4;
// START -- Q+E Software's SQLSetStmtOption extensions (1040 to 1139)
// defines here for backwards compatibility
SQL_STMTOPT_START = 1040;
// Get the rowid for the last row inserted
SQL_GET_ROWID = (SQL_STMTOPT_START + 8);
// Get the value for the serial column in the last row inserted
SQL_GET_SERIAL_VALUE = (SQL_STMTOPT_START + 9);
// END -- Q+E Software's SQLSetStmtOption extensions (1040 to 1139)
// ------------------------------------
// Informix extensions
// ------------------------------------
// Informix Column Attributes Flags Definitions
FDNULLABLE = $0001; // null allowed in field
FDDISTINCT = $0002; // distinct of all
FDDISTLVARCHAR = $0004; // distinct of SQLLVARCHAR
FDDISTBOOLEAN = $0008; // distinct of SQLBOOL
FDDISTSIMP = $0010; // distinct of simple type
FDCSTTYPE = $0020; // constructor type
FDNAMED = $0040; // named row type
// Informix Type Extensions
SQL_INFX_UDT_FIXED = -100;
SQL_INFX_UDT_VARYING = -101;
SQL_INFX_UDT_BLOB = -102;
SQL_INFX_UDT_CLOB = -103;
SQL_INFX_UDT_LVARCHAR = -104;
SQL_INFX_RC_ROW = -105;
SQL_INFX_RC_COLLECTION = -106;
SQL_INFX_RC_LIST = -107;
SQL_INFX_RC_SET = -108;
SQL_INFX_RC_MULTISET = -109;
SQL_INFX_UNSUPPORTED = -110;
SQL_INFX_C_SMARTLOB_LOCATOR = -111;
SQL_INFX_UDT_BIGINT = -114;
type
HINFX_RC = Pointer; // row & collection handle
const
// Informix Connect Attributes Extensions
SQL_OPT_LONGID = 2251;
SQL_INFX_ATTR_LONGID = SQL_OPT_LONGID;
SQL_INFX_ATTR_LEAVE_TRAILING_SPACES = 2252;
SQL_INFX_ATTR_DEFAULT_UDT_FETCH_TYPE = 2253;
SQL_INFX_ATTR_ENABLE_SCROLL_CURSORS = 2254;
SQL_ENABLE_INSERT_CURSOR = 2255;
SQL_INFX_ATTR_ENABLE_INSERT_CURSORS = SQL_ENABLE_INSERT_CURSOR;
SQL_INFX_ATTR_OPTIMIZE_AUTOCOMMIT = 2256;
SQL_INFX_ATTR_ODBC_TYPES_ONLY = 2257;
SQL_INFX_ATTR_FETCH_BUFFER_SIZE = 2258;
SQL_INFX_ATTR_OPTOFC = 2259;
SQL_INFX_ATTR_OPTMSG = 2260;
SQL_INFX_ATTR_REPORT_KEYSET_CURSORS = 2261;
SQL_INFX_ATTR_LO_AUTOMATIC = 2262;
SQL_INFX_ATTR_AUTO_FREE = 2263;
SQL_INFX_ATTR_DEFERRED_PREPARE = 2265;
SQL_INFX_ATTR_PAM_FUNCTION = 2266;
// void pamCallback (int msgStyle, void *responseBuf, int responseBufLen,
// int *responseLenPtr, void *challengeBuf, int challengeBufLen,
// int *challengeLenPtr)
SQL_INFX_ATTR_PAM_RESPONSE_BUF = 2267; // SQLPOINTER
SQL_INFX_ATTR_PAM_RESPONSE_BUF_LEN = 2268; // SQLINTEGER
SQL_INFX_ATTR_PAM_RESPONSE_LEN_PTR = 2269; // SQLPOINTER
SQL_INFX_ATTR_PAM_CHALLENGE_BUF = 2270; // SQLPOINTER
SQL_INFX_ATTR_PAM_CHALLENGE_BUF_LEN = 2271; // SQLINTEGER
SQL_INFX_ATTR_PAM_CHALLENGE_LEN_PTR = 2272; // SQLINTEGER * - number of bytes in challenge
SQL_INFX_ATTR_DELIMIDENT = 2273; // As of now this attribute is only being used
// in .NET Provider since it is sitting on top
// of ODBC.
SQL_INFX_ATTR_DBLOCALE = 2275;
SQL_INFX_ATTR_LOCALIZE_DECIMALS = 2276;
SQL_INFX_ATTR_DEFAULT_DECIMAL = 2277;
SQL_INFX_ATTR_SKIP_PARSING = 2278;
SQL_INFX_ATTR_CALL_FROM_DOTNET = 2279;
SQL_INFX_ATTR_LENGTHINCHARFORDIAGRECW = 2280;
SQL_INFX_ATTR_SENDTIMEOUT = 2281;
SQL_INFX_ATTR_RECVTIMEOUT = 2282;
// Does not work really - returns SQL_ERROR
SQL_INFX_ATTR_IDSISAMERRMSG = 2283;
// Attributes same as cli - already defined in DB2 section
// SQL_ATTR_USE_TRUSTED_CONTEXT = 2561;
// Informix Descriptor Extensions
SQL_INFX_ATTR_FLAGS = 1900; // UDWORD
SQL_INFX_ATTR_EXTENDED_TYPE_CODE = 1901; // UDWORD
SQL_INFX_ATTR_EXTENDED_TYPE_NAME = 1902; // UCHAR ptr
SQL_INFX_ATTR_EXTENDED_TYPE_OWNER = 1903; // UCHAR ptr
SQL_INFX_ATTR_EXTENDED_TYPE_ALIGNMENT = 1904; // UDWORD
SQL_INFX_ATTR_SOURCE_TYPE_CODE = 1905; // UDWORD
// Informix Statement Attributes Extensions
SQL_VMB_CHAR_LEN = 2325;
SQL_INFX_ATTR_VMB_CHAR_LEN = SQL_VMB_CHAR_LEN;
SQL_INFX_ATTR_MAX_FET_ARR_SIZE = 2326;
// Informix fOption, SQL_VMB_CHAR_LEN vParam
SQL_VMB_CHAR_EXACT = 0;
SQL_VMB_CHAR_ESTIMATE = 1;
// Informix row/collection traversal constants
SQL_INFX_RC_NEXT = 1;
SQL_INFX_RC_PRIOR = 2;
SQL_INFX_RC_FIRST = 3;
SQL_INFX_RC_LAST = 4;
SQL_INFX_RC_ABSOLUTE = 5;
SQL_INFX_RC_RELATIVE = 6;
SQL_INFX_RC_CURRENT = 7;
// ******************************************************************************
// Large Object (LO) related structures
//
// LO_SPEC: Large object spec structure
// It is used for creating smartblobs. The user may examin and/or set certain
// fields of LO_SPEC by using ifx_lo_spec[set|get]_* accessor functions.
//
// LO_PTR: Large object pointer structure
// Identifies the LO and provides ancillary, security-related information.
//
// LO_STAT: Large object stat structure
// It is used in querying attribtes of smartblobs. The user may examin fields
// herein by using ifx_lo_stat[set|get]_* accessor functions.
//
// These structures are opaque to the user. Accessor functions are provided
// for these structures.
// ******************************************************************************
// Informix GetInfo Extensions to obtain length of LO related structures
SQL_INFX_LO_SPEC_LENGTH = 2250; // UWORD
SQL_INFX_LO_PTR_LENGTH = 2251; // UWORD
SQL_INFX_LO_STAT_LENGTH = 2252; // UWORD
// *****************************************************************************
// LO Open flags: (see documentation for further explanation)
//
// LO_APPEND - Positions the seek position to end-of-file + 1. By itself,
// it is equivalent to write only mode followed by a seek to the
// end of large object. Read opeartions will fail.
// You can OR the LO_APPEND flag with another access mode.
// LO_WRONLY - Only write operations are valid on the data.
// LO_RDONLY - Only read operations are valid on the data.
// LO_RDWR - Both read and write operations are valid on the data.
//
// LO_RANDOM - If set overrides optimizer decision. Indicates that I/O is
// random and that the system should not read-ahead.
// LO_SEQUENTIAL - If set overrides optimizer decision. Indicates that
// reads are sequential in either forward or reverse direction.
//
// LO_FORWARD - Only used for sequential access. Indicates that the sequential
// access will be in a forward direction, i.e. from low offset
// to higher offset.
// LO_REVERSE - Only used for sequential access. Indicates that the sequential
// access will be in a reverse direction.
//
// LO_BUFFER - If set overrides optimizer decision. I/O goes through the
// buffer pool.
// LO_NOBUFFER - If set then I/O does not use the buffer pool.
// ******************************************************************************
LO_APPEND = $1;
LO_WRONLY = $2;
LO_RDONLY = $4; // default
LO_RDWR = $8;
LO_RANDOM = $20; // default is determined by optimizer
LO_SEQUENTIAL = $40; // default is determined by optimizer
LO_FORWARD = $80; // default
LO_REVERSE = $100;
LO_BUFFER = $200; // default is determined by optimizer
LO_NOBUFFER = $400; // default is determined by optimizer
LO_DIRTY_READ = $10;
LO_NODIRTY_READ = $800;
LO_LOCKALL = $1000; // default
LO_LOCKRANGE = $2000;
// ******************************************************************************
// LO create-time flags:
//
// Bitmask - Set/Get via ifx_lo_specset_flags() on LO_SPEC.
// ******************************************************************************
LO_ATTR_LOG = $0001;
LO_ATTR_NOLOG = $0002;
LO_ATTR_DELAY_LOG = $0004;
LO_ATTR_KEEP_LASTACCESS_TIME = $0008;
LO_ATTR_NOKEEP_LASTACCESS_TIME = $0010;
LO_ATTR_HIGH_INTEG = $0020;
LO_ATTR_MODERATE_INTEG = $0040;
// ******************************************************************************
// Symbolic constants for the "lseek" routine
// ******************************************************************************
LO_SEEK_SET = 0; // Set curr. pos. to "offset"
LO_SEEK_CUR = 1; // Set curr. pos. to current + "offset"
LO_SEEK_END = 2; // Set curr. pos. to EOF + "offset"
// ******************************************************************************
// Symbolic constants for lo_lock and lo_unlock routines.
// ******************************************************************************
LO_SHARED_MODE = 1;
LO_EXCLUSIVE_MODE = 2;
{----------------------------------------------------------------------------}
{ Teradata specific }
{----------------------------------------------------------------------------}
const
// ******************************************************************************
// Teradata Driver Defined Statement attributes
// ******************************************************************************
SQL_ATTR_TDATA_HOST_ID = 13001;
SQL_ATTR_TDATA_SESSION_NUMBER = 13002;
SQL_ATTR_TDATA_SESSION_CHARSET = 13003;
// Auto-generated key retrieval (DR 98321)
SQL_ATTR_AGKR = 13004;
// Attribute to enable/disable data encryption (DR69335-Vittal)
SQL_ATTR_DATA_ENCRYPTION = 13008;
// Attribute to get the activity row count (ODBC-4604, unsigned 64-bit value)
SQL_ATTR_TDATA_ROWCOUNT = 13009;
// ******************************************************************************
// Values for SQL_ATTR_DATA_ENCRYPTION statement attribute
// ******************************************************************************
SQL_DATA_ENCRYPTION_ON = 1;
SQL_DATA_ENCRYPTION_OFF = 0;
// ******************************************************************************
// Values for SQL_ATTR_AGKR statement attribute
// ******************************************************************************
SQL_AGKR_NO = 0;
SQL_AGKR_IDENTITY_COLUMN = 1;
SQL_AGKR_WHOLE_ROW = 2;
// ******************************************************************************
// Teradata Driver Defined Column/Descriptor attributes
// ******************************************************************************
// ODBC 3.8 defines SQL_DRIVER_DESCRIPTOR_BASE
SQL_DRIVER_DESCRIPTOR_BASE = $4000;
SQL_COLUMN_TD_DRIVER_START = 1300;
SQL_COLUMN_ACTIVITY_TYPE = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START);
SQL_COLUMN_COST_ESTIMATE = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 1);
SQL_COLUMN_FORMAT = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 2);
SQL_COLUMN_TITLE = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 3);
SQL_COLUMN_ACTUAL_NAME = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 4);
SQL_COLUMN_CHARACTER_SET = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 5);
SQL_COLUMN_EXPORT_WIDTH = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 6);
SQL_COLUMN_EXPORT_WIDTH_ADJ = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 7);
SQL_COLUMN_EXPORT_BYTES = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 8);
SQL_COLUMN_TDODBC_TYPE = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 9);
SQL_COLUMN_TD_UDT_NAME = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 10);
SQL_COLUMN_TD_UDT_INDICATOR = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 11);
SQL_COLUMN_TD_DRIVER_END = (SQL_DRIVER_DESCRIPTOR_BASE + SQL_COLUMN_TD_DRIVER_START + 11);
SQL_COLUMN_TD_DRIVER_MAX = 1349; // End of old Teradata reserved range. Replaced by 3.8 spec.
// ******************************************************************************
// The following are the corresponding Teradata specific descriptors
// ******************************************************************************
SQL_DESC_TD_ACTIVITY_TYPE = SQL_COLUMN_ACTIVITY_TYPE;
SQL_DESC_TD_COST_ESTIMATE = SQL_COLUMN_COST_ESTIMATE;
SQL_DESC_TD_FORMAT = SQL_COLUMN_FORMAT;
SQL_DESC_TD_TITLE = SQL_COLUMN_TITLE;
SQL_DESC_TD_ACTUAL_NAME = SQL_COLUMN_ACTUAL_NAME;
SQL_DESC_TD_CHARACTER_SET = SQL_COLUMN_CHARACTER_SET;
SQL_DESC_TD_EXPORT_WIDTH = SQL_COLUMN_EXPORT_WIDTH;
SQL_DESC_TD_EXPORT_WIDTH_ADJ = SQL_COLUMN_EXPORT_WIDTH_ADJ;
SQL_DESC_TD_EXPORT_BYTES = SQL_COLUMN_EXPORT_BYTES;
SQL_DESC_TD_ODBC_TYPE = SQL_COLUMN_TDODBC_TYPE;
SQL_DESC_TD_UDT_NAME = SQL_COLUMN_TD_UDT_NAME;
SQL_DESC_TD_UDT_INDICATOR = SQL_COLUMN_TD_UDT_INDICATOR;
SQL_DRIVER_DESCRIPTOR_END = SQL_COLUMN_TD_DRIVER_END;
// ******************************************************************************
// Teradata column character set codes
// ******************************************************************************
SQL_TD_CS_UNDEFINED = 0;
SQL_TD_CS_LATIN = 1;
SQL_TD_CS_UNICODE = 2;
SQL_TD_CS_KANJISJIS = 3;
SQL_TD_CS_GRAPHIC = 4;
SQL_TD_CS_KANJI1 = 5;
// ******************************************************************************
// DR 115298
//
// Teradata Driver Defined Data Types
//
// DR 141363: The ODBC 3.8 defined range for driver specific SQL types is from 0x4000 - 0x7FFF.
// To maintain compatability the existing published PERIOD types are retained but will be depricated.
// ******************************************************************************
// Internal type codes for NUMBER data types
SQL_TD_FIXED_NUMBER = 18001;
SQL_TD_FLOATING_NUMBER = 18002;
// XML data type
SQL_TD_XML = 18003;
// JSON data type
SQL_TD_JSON = 18004;
SQL_TD_WJSON = 18005;
// UDT indicator
SQL_TD_UDT = 21000;
// ******************************************************************************
// UDT Types
// Value - Type
// 1 – Structured UDT.
// 2 – Distinct UDT.
// 3 – Internal UDT.
// 0 - For all other data types.
// ******************************************************************************
SQL_TD_UDT_BASE = 0;
SQL_TD_UDT_STRUCTURED = 1;
SQL_TD_UDT_DISTINCT = 2;
SQL_TD_UDT_INTERNAL = 3;
SQL_TD_TYPE_MIN = -1049;
SQL_TD_TYPE_MAX = -1045;
// Period data types
SQL_PERIOD_DATE = -1049;
SQL_PERIOD_TIME = -1048;
SQL_PERIOD_TIME_WITH_TIME_ZONE = -1047;
SQL_PERIOD_TIMESTAMP = -1046;
SQL_PERIOD_TIMESTAMP_WITH_TIME_ZONE = -1045;
// Maximum precision for Period time and timestamp types
SQL_PERIOD_TIME_MAX_PRECISION = 6;
SQL_PERIOD_TIMESTAMP_MAX_PRECISION = 6;
// Lengths in characters of Period data type character representations
SQL_PERIOD_DATE_LEN = 28;
SQL_PERIOD_TIME_LEN = 24; // Add 2*(p+1), if p>0
SQL_PERIOD_TIME_WITH_TIME_ZONE_LEN = 36; // Add 2*(p+1), if p>0
SQL_PERIOD_TIMESTAMP_LEN = 46; // Add 2*(p+1), if p>0
SQL_PERIOD_TIMESTAMP_WITH_TIME_ZONE_LEN = 58; // Add 2*(p+1), if p>0
/// Lengths in bytes of Period data type binary representations
SQL_PERIOD_DATE_OCTET_LEN = 8;
SQL_PERIOD_TIME_OCTET_LEN = 12;
SQL_PERIOD_TIME_WITH_TIME_ZONE_OCTET_LEN = 16;
SQL_PERIOD_TIMESTAMP_OCTET_LEN = 20;
SQL_PERIOD_TIMESTAMP_WITH_TIME_ZONE_OCTET_LEN = 24;
// The scale factor for seconds fields in Period time and timestamp types. The
// seconds fields are scaled integers. The seconds with fractional part are:
// Seconds = SecondsField / SQL_PERIOD_SECONDS_SCALE
SQL_PERIOD_SECONDS_SCALE = 1000000;
// The zero base for time zone fields in Period time and timestamp types with time zone:
// TimeZoneField < SQL_PERIOD_TZ_BASE: TimeZone = - TimeZoneField.
// TimeZoneField >= SQL_PERIOD_TZ_BASE: TimeZone = TimeZoneField - SQL_PERIOD_TZ_BASE.
SQL_PERIOD_TZ_BASE = 16;
{----------------------------------------------------------------------------}
{ Data Direct specific }
{----------------------------------------------------------------------------}
const
SQL_CONOPT_START = 1040;
SQL_ATTR_APP_WCHAR_TYPE = (SQL_CONOPT_START + 21);
SQL_ATTR_APP_UNICODE_TYPE = (SQL_CONOPT_START + 24);
SQL_ATTR_DRIVER_UNICODE_TYPE = (SQL_CONOPT_START + 25);
SQL_DD_CP_ANSI = 0;
SQL_DD_CP_UCS2 = 1;
SQL_DD_CP_UTF8 = 2;
SQL_DD_CP_UTF16 = SQL_DD_CP_UCS2;
implementation
{-------------------------------------------------------------------------------}
function SQL_SUCCEEDED(rc: SQLReturn): Boolean;
begin
Result := (rc and not 1) = 0;
end;
{-------------------------------------------------------------------------------}
function SQL_LEN_BINARY_ATTR(Length: SQLInteger): SQLInteger;
begin
Result := -(Length) + SQL_LEN_BINARY_ATTR_OFFSET;
end;
{-------------------------------------------------------------------------------}
function SQL_LEN_DATA_AT_EXEC(Length: SQLInteger): SQLInteger;
begin
Result := -(Length) + SQL_LEN_DATA_AT_EXEC_OFFSET;
end;
{-------------------------------------------------------------------------------}
function SQL_FUNC_EXISTS(pfExists: Pointer; uwAPI: Integer): Boolean;
begin
Result := (PUWord(PByte(pfExists) + SizeOf(UWord) * (uwAPI shr 4))^ and
(1 shl (uwAPI and $F))) <> 0;
end;
end.
|
{******************************************}
{ TSeriesAnimationTool Editor Dialog }
{ Copyright (c) 2002-2004 by David Berneda }
{******************************************}
unit TeeSeriesAnimEdit;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls,
{$ENDIF}
TeeToolSeriesEdit, TeCanvas, TeeProcs, TeeTools;
type
TSeriesAnimToolEditor = class(TSeriesToolEditor)
Label2: TLabel;
SBSteps: TScrollBar;
Label3: TLabel;
CBStartMin: TCheckBox;
Label4: TLabel;
EStart: TEdit;
Button1: TButton;
Label5: TLabel;
Edit1: TEdit;
UpDown1: TUpDown;
Label6: TLabel;
ComboFlat1: TComboFlat;
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure CBStartMinClick(Sender: TObject);
procedure EStartChange(Sender: TObject);
procedure SBStepsChange(Sender: TObject);
procedure CBSeriesChange(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure ComboFlat1Change(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
AnimTool : TSeriesAnimationTool;
procedure StopAnimation;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
uses {$IFDEF CLR}
Variants,
{$ENDIF}
TeeProCo;
procedure TSeriesAnimToolEditor.FormShow(Sender: TObject);
begin
inherited;
AnimTool:=TSeriesAnimationTool(Tag);
if Assigned(AnimTool) then
With AnimTool do
begin
SBSteps.Position:=Steps;
Label3.Caption:=IntToStr(Steps);
CBStartMin.Checked:=StartAtMin;
EStart.Text:=FloatToStr(StartValue);
EStart.Enabled:=not CBStartMin.Checked;
UpDown1.Position:=DrawEvery;
Button1.Enabled:=Assigned(Series);
if Loop=salNo then ComboFlat1.ItemIndex:=0
else
if Loop=salOneWay then ComboFlat1.ItemIndex:=1
else
ComboFlat1.ItemIndex:=2;
if AnimTool.Running then
begin
Button1.Tag:=1;
Button1.Caption:=TeeMsg_Stop;
end;
end;
end;
procedure TSeriesAnimToolEditor.StopAnimation;
begin
AnimTool.Stop;
Button1.Tag:=0;
Button1.Caption:=TeeMsg_Execute;
end;
procedure TSeriesAnimToolEditor.Button1Click(Sender: TObject);
begin
if Button1.Tag=1 then StopAnimation
else
begin
Button1.Tag:=1;
Button1.Caption:=TeeMsg_Stop;
AnimTool.Execute;
StopAnimation;
end;
end;
procedure TSeriesAnimToolEditor.CBStartMinClick(Sender: TObject);
begin
AnimTool.StartAtMin:=CBStartMin.Checked;
EStart.Enabled:=not CBStartMin.Checked;
end;
procedure TSeriesAnimToolEditor.EStartChange(Sender: TObject);
begin
AnimTool.StartValue:=StrToFloatDef(EStart.Text,AnimTool.StartValue);
end;
procedure TSeriesAnimToolEditor.SBStepsChange(Sender: TObject);
begin
AnimTool.Steps:=SBSteps.Position;
Label3.Caption:=IntToStr(AnimTool.Steps);
end;
procedure TSeriesAnimToolEditor.CBSeriesChange(Sender: TObject);
begin
inherited;
Button1.Enabled:=Assigned(AnimTool.Series);
end;
procedure TSeriesAnimToolEditor.Edit1Change(Sender: TObject);
begin
if Showing then
AnimTool.DrawEvery:=UpDown1.Position;
end;
procedure TSeriesAnimToolEditor.ComboFlat1Change(Sender: TObject);
begin
case ComboFlat1.ItemIndex of
0: AnimTool.Loop:=salNo;
1: AnimTool.Loop:=salOneWay;
else
AnimTool.Loop:=salCircular;
end;
end;
procedure TSeriesAnimToolEditor.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
inherited;
CanClose:=(not Assigned(AnimTool)) or (not AnimTool.Running);
end;
initialization
RegisterClass(TSeriesAnimToolEditor);
end.
|
unit CharTestForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.ScrollBox;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
procedure Show (const msg: string);
procedure ShowBool (value: Boolean);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
{$HIGHCHARUNICODE ON}
uses
Character;
procedure TForm1.Button1Click(Sender: TObject);
var
ch1: Char;
begin
ch1 := 'ù';
Show ('UpCase ù: ' + UpCase(ch1));
Show ('ToUpper ù: ' + ch1.ToUpper);
end;
procedure TForm1.Button2Click(Sender: TObject);
var
str1: string;
begin
str1 := '1.' + #9 + Char.ConvertFromUtf32 (128) +
Char.ConvertFromUtf32($1D11E);
ShowBool (str1.Chars[0].IsNumber);
ShowBool (str1.Chars[1].IsPunctuation);
ShowBool (str1.Chars[2].IsWhiteSpace);
ShowBool (str1.Chars[3].IsControl);
ShowBool (str1.Chars[4].IsSurrogate);
end;
procedure TForm1.Button3Click(Sender: TObject);
var
str1: string;
begin
str1 := #$80;
Show (str1 + ' - ' + IntToStr (Ord (str1.Chars[0])));
end;
procedure TForm1.Button4Click(Sender: TObject);
var
str1: string;
begin
str1 := #$3042#$3044;
Show (str1 + ' - ' + IntToStr (Ord (str1.Chars[0])) +
' - ' + IntToStr (Ord (str1.Chars[1])));
end;
procedure TForm1.Show(const Msg: string);
begin
Memo1.Lines.Add(Msg);
end;
procedure TForm1.ShowBool(value: Boolean);
begin
Show(BoolToStr (Value, True));
end;
end.
|
unit ImportIVPStatusFromDTF;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids,
Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, Types, Zipcopy,
RPCanvas, RPrinter, RPDefine, RPBase, RPFiler, PASTypes;
type
NotFound_InvalidParcelRecord = record
Status : String;
ParcelID : String;
sOwner : String;
sLegalAddress : String;
ErrorMessage : String;
end;
NotFound_InvalidParcelPointer = ^NotFound_InvalidParcelRecord;
TImportIVPStatusFileForm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
ScrollBox1: TScrollBox;
CloseButton: TBitBtn;
TitleLabel: TLabel;
StartButton: TBitBtn;
ParcelTable: TTable;
ExemptionTable: TTable;
MiscellaneousGroupBox: TGroupBox;
PrintLabelsForUnknownStatusCheckBox: TCheckBox;
Label1: TLabel;
AssessmentYearRadioGroup: TRadioGroup;
Label2: TLabel;
PrintLabelsForDeniedStatusCheckBox: TCheckBox;
Label3: TLabel;
ReportFiler: TReportFiler;
ReportPrinter: TReportPrinter;
PrintDialog: TPrintDialog;
OpenDialog: TOpenDialog;
TrialRunCheckBox: TCheckBox;
Label4: TLabel;
ReportLabelPrinter: TReportPrinter;
ReportLabelFiler: TReportFiler;
SwisCodeTable: TwwTable;
AssessmentYearControlTable: TTable;
Label5: TLabel;
PrintLabelsForApprovedStatusCheckBox: TCheckBox;
Label6: TLabel;
PrintLabelsForApproved_NotEnrolledStatusCheckBox: TCheckBox;
Label7: TLabel;
UpdateStatusIfNotEnrolledCheckBox: TCheckBox;
Label8: TLabel;
MarkApprovedHomeownersEnfrolledCheckBox: TCheckBox;
tbParcels2: TTable;
cbxExtractToExcel: TCheckBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure StartButtonClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure ReportPrintHeader(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure ReportLabelPrintHeader(Sender: TObject);
procedure ReportLabelPrint(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
UnitName : String;
ProcessingType : Integer;
AssessmentYear : String;
TrialRun,
PrintLabelsForApprovedStatus,
PrintLabelsForApproved_NotEnrolled,
PrintLabelsForUnknownStatus, PrintLabelsForDeniedStatus : Boolean;
ImportFile : TextFile;
ApprovedStatusList, ApprovedStatusNotEnrolledList,
UnknownStatusList, DeniedStatusList, lstApprovedNoEnhancedSTAR : TStringList;
CurrentReportSection : String;
{Label variables}
LabelOptions : TLabelOptions;
ParcelListForLabels : TStringList;
NotFound_InvalidParcelList : TList;
MarkApprovedHomeownersEnrolled,
UpdateStatusEvenIfNotMarkedEnrolled,
bExtractToExcel : Boolean;
sSpreadsheetFileName : String;
flExtract : TextFile;
Procedure InitializeForm; {Open the tables and setup.}
Procedure MarkSeniorExemptionsApproved( Sender : TObject;
SwisSBLKey : String;
Status : String;
FieldList : TStringList;
var SeniorExemptionApprovedCount : LongInt;
var EnhancedSTARExemptionApprovedCount : Integer;
var NotEnrolledCount : Integer);
Procedure PrintLabelsForStatusList(StatusList : TStringList;
StatusText : String);
Procedure PrintUnknownOrDeniedStatusList(Sender : TObject;
StatusList : TStringList;
Status : String;
ReportSection : String);
Procedure PrintNotFound_OrInvalidList(Sender : TObject;
NotFound_InvalidParcelList : TList);
end;
implementation
uses GlblVars, WinUtils, Utilitys, GlblCnst, PASUtils,
UtilExsd, Prog, Preview, DataAccessUnit;
{$R *.DFM}
{========================================================}
Procedure TImportIVPStatusFileForm.FormActivate(Sender: TObject);
begin
SetFormStateMaximized(Self);
end;
{========================================================}
Procedure TImportIVPStatusFileForm.InitializeForm;
begin
UnitName := 'ImportIVPStatusFromDTF'; {mmm}
end; {InitializeForm}
{========================================================}
Procedure TImportIVPStatusFileForm.PrintLabelsForStatusList(StatusList : TStringList;
StatusText : String);
var
TempFile : TextFile;
NewLabelFileName : String;
begin
If ((MessageDlg('Please insert label paper to print out labels for the ' + StatusText,
mtConfirmation, [mbOK, mbCancel], 0) = idOK) and
ExecuteLabelOptionsDialog(LabelOptions) and
PrintDialog.Execute)
then
begin
{FXX10102003-1(2.07j1): Make sure to reset to letter paper after printing the
search report.}
ReportLabelFiler.SetPaperSize(dmPaper_Letter, 0, 0);
ReportLabelPrinter.SetPaperSize(dmPaper_Letter, 0, 0);
ParcelListForLabels := StatusList;
If PrintDialog.PrintToFile
then
begin
NewLabelFileName := GetPrintFileName(Self.Caption, True);
GlblPreviewPrint := True;
GlblDefaultPreviewZoomPercent := 70;
ReportLabelFiler.FileName := NewLabelFileName;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewLabelFileName;
PreviewForm.FilePreview.FileName := NewLabelFileName;
ReportLabelFiler.Execute;
PreviewForm.ShowModal;
finally
PreviewForm.Free;
{Now delete the file.}
try
AssignFile(TempFile, NewLabelFileName);
OldDeleteFile(NewLabelFileName);
finally
{We don't care if it does not get deleted, so we won't put up an
error message.}
ChDir(GlblProgramDir);
end;
end; {If PrintRangeDlg.PreviewPrint}
end {They did not select preview, so we will go
right to the printer.}
else ReportLabelPrinter.Execute;
end; {If ((MessageDlg('Please insert label ...}
end; {PrintLabelsForStatusList}
{===================================================================}
Procedure TImportIVPStatusFileForm.StartButtonClick(Sender: TObject);
var
Quit : Boolean;
NewFileName, IVPImportFileName : String;
ImportRecordCount : Integer;
begin
Quit := False;
CurrentReportSection := 'Approved Status';
ImportRecordCount := 0;
If OpenDialog.Execute
then
begin
IVPImportFileName := OpenDialog.FileName;
try
AssignFile(ImportFile, IVPImportFileName);
Reset(ImportFile);
except
Quit := True;
SystemSupport(001, ParcelTable, 'Error opening DTF status file.',
UnitName, GlblErrorDlgBox);
end;
If not Quit
then
begin
case AssessmentYearRadioGroup.ItemIndex of
0 : begin
AssessmentYear := GlblThisYear;
ProcessingType := ThisYear;
end;
1 : begin
AssessmentYear := GlblNextYear;
ProcessingType := NextYear;
end;
end; {case AssessmentYearRadioGroup.ItemIndex of}
OpenTablesForForm(Self, ProcessingType);
PrintLabelsForApprovedStatus := PrintLabelsForApprovedStatusCheckBox.Checked;
PrintLabelsForApproved_NotEnrolled := PrintLabelsForApproved_NotEnrolledStatusCheckBox.Checked;
PrintLabelsForUnknownStatus := PrintLabelsForUnknownStatusCheckBox.Checked;
PrintLabelsForDeniedStatus := PrintLabelsForDeniedStatusCheckBox.Checked;
TrialRun := TrialRunCheckBox.Checked;
{CHG02102004-1(2.07l): Allow for options to mark all homeonwers as enrolled or
to mark approved even if not enrolled.}
MarkApprovedHomeownersEnrolled := MarkApprovedHomeownersEnfrolledCheckBox.Checked;
UpdateStatusEvenIfNotMarkedEnrolled := UpdateStatusIfNotEnrolledCheckBox.Checked;
UnknownStatusList := TStringList.Create;
DeniedStatusList := TStringList.Create;
ApprovedStatusList := TStringList.Create;
ApprovedStatusNotEnrolledList := TStringList.Create;
lstApprovedNoEnhancedSTAR := TStringList.Create;
bExtractToExcel := cbxExtractToExcel.Checked;
If bExtractToExcel
then
begin
sSpreadsheetFileName := GetPrintFileName(Self.Caption, True);
AssignFile(flExtract, sSpreadsheetFileName);
Rewrite(flExtract);
WritelnCommaDelimitedLine(flExtract,
['Parcel ID', 'Status', 'Prior Status', 'Owner',
'Legal Address #', 'Legal Address', 'Notes']);
end; {If bExtractToExcel}
If PrintDialog.Execute
then
begin
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptLaser],
False, Quit);
If not Quit
then
begin
ProgressDialog.UserLabelCaption := '';
ProgressDialog.Start(ImportRecordCount, True, True);
{Now print the report.}
If not Quit
then
begin
GlblPreviewPrint := False;
{If they want to preview the print (i.e. have it
go to the screen), then we need to come up with
a unique file name to tell the ReportFiler
component where to put the output.
Once we have done that, we will execute the
report filer which will print the report to
that file. Then we will create and show the
preview print form and give it the name of the
file. When we are done, we will delete the file
and make sure that we go back to the original
directory.}
{FXX07221998-1: So that more than one person can run the report
at once, use a time based name first and then
rename.}
{If they want to see it on the screen, start the preview.}
If PrintDialog.PrintToFile
then
begin
GlblPreviewPrint := True;
NewFileName := GetPrintFileName(Self.Caption, True);
ReportFiler.FileName := NewFileName;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewFileName;
PreviewForm.FilePreview.FileName := NewFileName;
PreviewForm.FilePreview.ZoomFactor := 130;
ReportFiler.Execute;
{FXX09071999-6: Tell people that printing is starting and
done.}
ProgressDialog.StartPrinting(PrintDialog.PrintToFile);
PreviewForm.ShowModal;
finally
PreviewForm.Free;
end;
ShowReportDialog('ImportIVPStatus.RPT', NewFileName, True);
end
else ReportPrinter.Execute;
end; {If not Quit}
{Clear the selections.}
ProgressDialog.Finish;
{FXX09071999-6: Tell people that printing is starting and
done.}
DisplayPrintingFinishedMessage(PrintDialog.PrintToFile);
end; {If not Quit}
ResetPrinter(ReportPrinter);
If PrintLabelsForApprovedStatus
then
begin
PrintLabelsForStatusList(ApprovedStatusList, 'approved status enrollees.');
If _Compare(lstApprovedNoEnhancedSTAR.Count, 0, coGreaterThan)
then PrintLabelsForStatusList(lstApprovedNoEnhancedSTAR, 'approved status, no Enhanced STAR.');
end; {If PrintLabelsForApprovedStatus}
If PrintLabelsForApproved_NotEnrolled
then PrintLabelsForStatusList(ApprovedStatusNotEnrolledList, 'approved status, not enrolled homeowners.');
If PrintLabelsForUnknownStatus
then PrintLabelsForStatusList(UnknownStatusList, 'unknown status enrollees.');
If PrintLabelsForDeniedStatus
then PrintLabelsForStatusList(DeniedStatusList, 'denied status enrollees.');
end; {If PrintDialog.Execute}
UnknownStatusList.Free;
DeniedStatusList.Free;
ApprovedStatusList.Free;
ApprovedStatusNotEnrolledList.Free;
lstApprovedNoEnhancedSTAR.Free;
If bExtractToExcel
then
begin
CloseFile(flExtract);
SendTextFileToExcelSpreadsheet(sSpreadsheetFileName, True,
False, '');
end; {If bExtractToExcel}
end; {If not Quit}
CloseFile(ImportFile);
end; {If OpenDialog.Execute}
end; {StartButtonClick}
{===================================================================}
Procedure AddOneNotFound_InvalidParcelPointer(NotFound_InvalidParcelList : TList;
_Status : String;
_ParcelID : String;
_sOwner : String;
_sLegalAddress : String;
_ErrorMessage : String);
var
NotFound_InvalidParcelPtr : NotFound_InvalidParcelPointer;
begin
New(NotFound_InvalidParcelPtr);
with NotFound_InvalidParcelPtr^ do
begin
Status := _Status;
ParcelID := _ParcelID;
sOwner := _sOwner;
sLegalAddress := _sLegalAddress;
ErrorMessage := _ErrorMessage;
end; {with NotFound_InvalidParcelPtr^ do}
NotFound_InvalidParcelList.Add(NotFound_InvalidParcelPtr);
end; {AddOneNotFound_InvalidParcelPointer}
{===================================================================}
Procedure TImportIVPStatusFileForm.MarkSeniorExemptionsApproved( Sender : TObject;
SwisSBLKey : String;
Status : String;
FieldList : TStringList;
var SeniorExemptionApprovedCount : LongInt;
var EnhancedSTARExemptionApprovedCount : Integer;
var NotEnrolledCount : Integer);
var
Done, FirstTimeThrough, bExemptionFound : Boolean;
sParcelID, sOwner, sLegalAddressNumber,
sStatus, sLegalAddressName, ExemptionCode : String;
begin
Done := False;
FirstTimeThrough := True;
bExemptionFound := False;
{FXX04112012(2.28.4.18)[PAS-261]: Make sure to trim the fields since the fields now have leading blanks.}
sStatus := Trim(FieldList[0]);
sParcelID := Trim(FieldList[2]);
sOwner := Trim(FieldList[4]);
sLegalAddressNumber := Trim(FieldList[8]);
sLegalAddressName := Trim(FieldList[9]);
SetRangeOld(ExemptionTable, ['TaxRollYr', 'SwisSBLKey', 'ExemptionCode'],
[AssessmentYear, SwisSBLKey, '00000'],
[AssessmentYear, SwisSBLKey, '99999']);
ExemptionTable.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else ExemptionTable.Next;
If ExemptionTable.EOF
then Done := True;
ExemptionCode := ExemptionTable.FieldByName('ExemptionCode').Text;
{Only enhanced STAR.}
If ((not Done) and
(* (ExemptionIsSenior(ExemptionCode) or*)
ExemptionIsEnhancedSTAR(ExemptionCode))
then
with ExemptionTable, Sender as TBaseReport do
begin
bExemptionFound := True;
If (LinesLeft < 6)
then NewPage;
{CHG02102004-1(2.07l): Allow for options to mark all homeonwers as enrolled or
to mark approved even if not enrolled.}
If (UpdateStatusEvenIfNotMarkedEnrolled or
FieldByName('AutoRenew').AsBoolean)
then
begin
Println(#9 + ConvertSBLOnlyToDashDot(Copy(SwisSBLKey, 7, 20)) +
#9 + Status +
#9 + ExemptionCode +
#9 + 'Exemption approved.');
If not TrialRun
then
try
Edit;
FieldByName('ExemptionApproved').AsBoolean := True;
{CHG02102004-1(2.07l): Allow for options to mark all homeonwers as enrolled or
to mark approved even if not enrolled.}
If MarkApprovedHomeownersEnrolled
then FieldByName('AutoRenew').AsBoolean := True;
Post;
except
SystemSupport(002, ExemptionTable,
'Error updating exemption approved flag for ' +
ConvertSwisSBLToDashDot(SwisSBLKey) + '.',
UnitName, GlblErrorDlgBox);
end;
(*
If ExemptionIsSenior(ExemptionCode)
then SeniorExemptionApprovedCount := SeniorExemptionApprovedCount + 1; *)
If ExemptionIsEnhancedSTAR(ExemptionCode)
then EnhancedSTARExemptionApprovedCount := EnhancedSTARExemptionApprovedCount + 1;
ApprovedStatusList.Add(SwisSBLKey);
end
else
begin
ApprovedStatusNotEnrolledList.Add(SwisSBLKey);
Println(#9 + ConvertSBLOnlyToDashDot(Copy(SwisSBLKey, 7, 20)) +
#9 + Status +
#9 + ExemptionCode +
#9 + 'Owner not enrolled in IVP - not marked approved.');
NotEnrolledCount := NotEnrolledCount + 1;
end; {else of If FieldByName('AutoRenew').AsBoolean}
end; {with ExemptionTable, Sender as TBaseReport do}
until Done;
If not bExemptionFound
then
begin
lstApprovedNoEnhancedSTAR.Add(SwisSBLKey);
AddOneNotFound_InvalidParcelPointer(NotFound_InvalidParcelList, sStatus,
sParcelID, sOwner,
MakeLegalAddress(sLegalAddressNumber, sLegalAddressName),
'Approved, no Enhanced STAR.');
If bExtractToExcel
then WriteCommaDelimitedLine(flExtract,
['Approved, no Enhanced STAR.']);
end; {If not bExemptionFound}
end; {MarkSeniorExemptionsApproved}
{===================================================================}
Procedure TImportIVPStatusFileForm.PrintUnknownOrDeniedStatusList(Sender : TObject;
StatusList : TStringList;
Status : String;
ReportSection : String);
var
I : Integer;
begin
CurrentReportSection := ReportSection;
with Sender as TBaseReport do
begin
Underline := True;
Println(#9 + CurrentReportSection + ':');
Underline := False;
For I := 0 to (StatusList.Count - 1) do
begin
If (LinesLeft < 5)
then NewPage;
Println(#9 + ConvertSBLOnlyToDashDot(Copy(StatusList[I], 7, 20)) +
#9 + Status +
#9 + #9 + ReportSection);
end; {For I := 0 (StatusList.Count - 1) do}
Println('');
Println(#9 + ReportSection + ': ' + IntToStr(StatusList.Count));
Println('');
end; {with Sender as TBaseReport do}
end; {PrintUnknownOrDeniedStatusList}
{===================================================================}
Procedure TImportIVPStatusFileForm.PrintNotFound_OrInvalidList(Sender : TObject;
NotFound_InvalidParcelList : TList);
var
I : Integer;
begin
CurrentReportSection := 'Invalid or Not Found Parcels';
with Sender as TBaseReport do
begin
Underline := True;
Println(#9 + CurrentReportSection + ':');
Underline := False;
{Print the bad parcels.}
For I := 0 to (NotFound_InvalidParcelList.Count - 1) do
with NotFound_InvalidParcelPointer(NotFound_InvalidParcelList[I])^ do
begin
If (LinesLeft < 5)
then NewPage;
Println(#9 + ParcelID +
#9 + Status +
#9 +
#9 + ErrorMessage + '(' +
sOwner + ' - ' + sLegalAddress + ')');
end; {with NotFound_InvalidParcelPointer(NotFound_InvalidParcelList[I]), Sender as TBaseReport do}
Println('');
Bold := True;
Println(#9 + 'Total Errors = ' + IntToStr(NotFound_InvalidParcelList.Count));
end; {with Sender as TBaseReport do}
end; {PrintNotFound_OrInvalidList}
{===================================================================}
Procedure TImportIVPStatusFileForm.ReportPrintHeader(Sender: TObject);
begin
with Sender as TBaseReport do
begin
{Print the date and page number.}
SectionTop := 0.25;
SectionLeft := 0.5;
SectionRight := PageWidth - 0.5;
SetFont('Times New Roman',8);
PrintHeader('Page: ' + IntToStr(CurrentPage), pjRight);
PrintHeader('Date: ' + DateToStr(Date) + ' Time: ' + TimeToStr(Now), pjLeft);
SectionTop := 0.5;
SetFont('Arial',12);
Bold := True;
Home;
PrintCenter('Import IVP Status File', (PageWidth / 2));
SetFont('Times New Roman', 9);
CRLF;
Println('');
Bold := True;
If TrialRun
then
begin
Println(' Trial Run (no update)');
Println('');
end;
ClearTabs;
SetTab(0.3, pjLeft, 1.3, 0, BOXLINENone, 0); {Parcel ID}
Underline := True;
Println(#9 + CurrentReportSection + ':');
Underline := False;
Println('');
ClearTabs;
SetTab(0.3, pjCenter, 1.3, 0, BOXLINEBottom, 0); {Parcel ID}
SetTab(1.7, pjCenter, 0.6, 0, BOXLINEBottom, 0); {Status}
SetTab(2.4, pjCenter, 0.6, 0, BOXLINEBottom, 0); {Exemption Code}
SetTab(3.2, pjCenter, 2.5, 0, BOXLINEBottom, 0); {Message}
Println(#9 + 'Parcel ID' +
#9 + 'Status' +
#9 + 'EX Code' +
#9 + 'Message');
ClearTabs;
SetTab(0.3, pjLeft, 1.3, 0, BOXLINENone, 0); {Parcel ID}
SetTab(1.7, pjLeft, 0.6, 0, BOXLINENone, 0); {Status}
SetTab(2.4, pjLeft, 0.6, 0, BOXLINENone, 0); {Exemption Code}
SetTab(3.2, pjLeft, 2.5, 0, BOXLINENone, 0); {Message}
Bold := False;
end; {with Sender as TBaseReport do}
end; {ReportPrintHeader}
{===================================================================}
Procedure TImportIVPStatusFileForm.ReportPrint(Sender: TObject);
var
Done, ValidEntry, _Found, LineFeedOnly : Boolean;
SBLRec : SBLRecord;
{$H+}
TempStr, ImportLine : String;
{$H-}
ParcelID, Status, SwisSBLKey, LastParcelID,
sLegalAddressNumber, sLegalAddressName,
sOwner, sPriorStatus : String;
sTempGlblSublotSeparator : Char;
SeniorExemptionApprovedCount,
EnhancedSTARExemptionApprovedCount,
NotEnrolledCount, TotalRecords, LineFeedPos : LongInt;
FieldList : TStringList;
begin
LastParcelID := '';
Done := False;
UnknownStatusList.Clear;
DeniedStatusList.Clear;
ApprovedStatusList.Clear;
ApprovedStatusNotEnrolledList.Clear;
SeniorExemptionApprovedCount := 0;
EnhancedSTARExemptionApprovedCount := 0;
NotEnrolledCount := 0;
{First determine the number of records.}
TotalRecords := 0;
repeat
{H+}
Readln(ImportFile, TempStr);
TotalRecords := TotalRecords + 1;
{H-}
until EOF(ImportFile);
{CHG12022005-1(2.9.4.2): If there are no carriage returns, count the number of line feeds.}
LineFeedOnly := _Compare(TotalRecords, 1, coEqual);
If LineFeedOnly
then TotalRecords := CountOfCharacter(TempStr, #10);
Reset(ImportFile);
ProgressDialog.Start(TotalRecords, True, True);
NotFound_InvalidParcelList := TList.Create;
FieldList := TStringList.Create;
{Only 1 string if this is a line feed only file.}
{$H+}
If LineFeedOnly
then Readln(ImportFile, ImportLine);
{$H-}
repeat
{H+}
If not LineFeedOnly
then Readln(ImportFile, ImportLine);
If LineFeedOnly
then
begin
LineFeedPos := Pos(#10, ImportLine);
If _Compare(LineFeedPos, 0, coGreaterThan)
then
begin
TempStr := Copy(ImportLine, 1, (LineFeedPos - 1));
Delete(ImportLine, 1, LineFeedPos);
end
else Done := True;
end
else
begin
TempStr := ImportLine;
If EOF(ImportFile)
then Done := True;
end; {else of If LineFeedOnly}
ParseTabDelimitedStringIntoFields(TempStr, FieldList, True);
{$H-}
Status := Trim(FieldList[0]);
ProgressDialog.Update(Self, LastParcelID);
If (_Compare(Length(Status), 1, coEqual) and
(Status[1] in ['U', 'N', 'Y'])) {Valid status line}
then
begin
sPriorStatus := Take(1, FieldList[1]);
ParcelID := FieldList[2];
sOwner := FieldList[4];
sLegalAddressNumber := FieldList[8];
sLegalAddressName := FieldList[9];
If (ParcelID <> LastParcelID)
then
begin
SBLRec := ConvertDashDotSBLToSegmentSBL(ParcelID, ValidEntry);
If bExtractToExcel
then WriteCommaDelimitedLine(flExtract,
[ParcelID, Status, sPriorStatus, sOwner,
sLegalAddressNumber, sLegalAddressName]);
If ValidEntry
then
begin
with SBLRec do
_Found := FindKeyOld(ParcelTable,
['TaxRollYr', 'Section', 'Subsection', 'Block',
'Lot', 'Sublot', 'Suffix'],
[AssessmentYear, Section, Subsection, Block,
Lot, Sublot, Suffix]);
SwisSBLKey := ExtractSSKey(ParcelTable);
{FXX12042009-1(2.20.2.1): IVP parcel ID lookup issue.}
{If it was not found and the SWIS is on the front, try
again without it.}
If ((not _Found) and
_Compare(Pos('/', ParcelID), 3, coEqual))
then
begin
ParcelID := Copy(ParcelID, 4, 20);
SBLRec := ConvertDashDotSBLToSegmentSBL(ParcelID, ValidEntry);
with SBLRec do
_Found := FindKeyOld(ParcelTable,
['TaxRollYr', 'Section', 'Subsection', 'Block',
'Lot', 'Sublot', 'Suffix'],
[AssessmentYear, Section, Subsection, Block,
Lot, Sublot, Suffix]);
If not _Found
then
begin
SBLRec := ConvertDashDotSBLToSegmentSBL(ParcelID, ValidEntry);
sTempGlblSublotSeparator := GlblSublotSeparator;
GlblSublotSeparator := '.';
with SBLRec do
_Found := FindKeyOld(ParcelTable,
['TaxRollYr', 'Section', 'Subsection', 'Block',
'Lot', 'Sublot', 'Suffix'],
[AssessmentYear, Section, Subsection, Block,
Lot, Sublot, Suffix]);
GlblSublotSeparator := sTempGlblSublotSeparator;
end; {If not _Found}
end; {If ((not _Found) and...}
{Try to find it by legal address.}
(* If not _Found
then
begin
If _Locate(tbParcels2, [AssessmentYear, sLegalAddressNumber, sLegalAddressName], '', [])
then
begin
ValidEntry := True;
SwisSBLKey := ExtractSSKey(tbParcels2);
_Found := True;
_Locate(ParcelTable, [AssessmentYear, Copy(SwisSBLKey, 7, 20)], '', [loParseSBLOnly]);
end; {If _Locate(tbParcels2 ...}
end; {If not _Found}
{Try by the IVPKeyField, i.e. the legal address in the IVP file.}
If not _Found
then
try
tbParcels2.IndexName := 'ByIVPKeyField';
If _Locate(tbParcels2, [Trim(sLegalAddressNumber + ' ' + sLegalAddressName)], '', [])
then
begin
ValidEntry := True;
SwisSBLKey := ExtractSSKey(tbParcels2);
_Found := True;
_Locate(ParcelTable, [AssessmentYear, Copy(SwisSBLKey, 7, 20)], '', [loParseSBLOnly]);
end; {If _Locate(tbParcels2...}
finally
tbParcels2.IndexName := 'BYYEAR_LEGALADDRNO_LEGALADDR';
end; {If not _Found} *)
If _Found
then
begin
case Status[1] of
'U' : UnknownStatusList.Add(SwisSBLKey);
'N' : DeniedStatusList.Add(SwisSBLKey);
'Y' : MarkSeniorExemptionsApproved(Sender, SwisSBLKey, Status,
FieldList,
SeniorExemptionApprovedCount,
EnhancedSTARExemptionApprovedCount,
NotEnrolledCount);
end; {case Status[1] of}
If bExtractToExcel
then WritelnCommaDelimitedLine(flExtract, ['']);
with ParcelTable do
try
Edit;
FieldByName('IVPStatus').AsString := Status[1];
Post;
except
Cancel;
end;
end
else
begin
AddOneNotFound_InvalidParcelPointer(NotFound_InvalidParcelList, FieldList[0],
ParcelID, sOwner,
MakeLegalAddress(sLegalAddressNumber, sLegalAddressName),
'Parcel not found.');
If bExtractToExcel
then WritelnCommaDelimitedLine(flExtract, ['Parcel not found.']);
end
end
else
begin
AddOneNotFound_InvalidParcelPointer(NotFound_InvalidParcelList, FieldList[0],
ParcelID, sOwner,
MakeLegalAddress(sLegalAddressNumber, sLegalAddressName),
'Invalid parcel ID.');
If bExtractToExcel
then WritelnCommaDelimitedLine(flExtract, ['Invalid parcel ID.']);
end; {else of If ValidEntry}
end; {If (ParcelID <> LastParcelID)}
end; {If (Take(1, FieldList[0])[1] in ['U', 'N', 'Y'])}
LastParcelID := ParcelID;
until Done;
{Print the totals.}
with Sender as TBaseReport do
begin
Println('');
Bold := True;
(* Println(#9 + 'Senior Exemptions Approved: ' + IntToStr(SeniorExemptionApprovedCount)); *)
Println(#9 + 'Enhanced STAR Exemptions Approved: ' + IntToStr(EnhancedSTARExemptionApprovedCount));
Println(#9 + 'Not Enrolled in IVP - Exemption not Approved: ' + IntToStr(NotEnrolledCount));
Println('');
end; {with Sender as TBaseReport do}
PrintUnknownOrDeniedStatusList(Sender, UnknownStatusList, 'U', 'Unknown Status');
PrintUnknownOrDeniedStatusList(Sender, DeniedStatusList, 'N', 'Denied Status');
PrintNotFound_OrInvalidList(Sender, NotFound_InvalidParcelList);
FieldList.Free;
FreeTList(NotFound_InvalidParcelList, SizeOf(NotFound_InvalidParcelRecord));
ProgressDialog.Finish;
end; {ReportPrint}
{===================================================================}
Procedure TImportIVPStatusFileForm.ReportLabelPrintHeader(Sender: TObject);
begin
PrintLabelHeader(Sender, LabelOptions);
end; {ReportLabelPrintHeader}
{===================================================================}
Procedure TImportIVPStatusFileForm.ReportLabelPrint(Sender: TObject);
begin
PrintLabels(Sender, ParcelListForLabels, ParcelTable,
SwisCodeTable, AssessmentYearControlTable,
AssessmentYear, LabelOptions);
end; {ReportLabelPrint}
{===================================================================}
Procedure TImportIVPStatusFileForm.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
CloseTablesForForm(Self);
{Free up the child window and set the ClosingAForm Boolean to
true so that we know to delete the tab.}
Action := caFree;
GlblClosingAForm := True;
GlblClosingFormCaption := Caption;
end; {FormClose}
end. |
unit UFrmPrincipal;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Effects, FMX.TabControl, FMX.Layouts,
System.Actions, FMX.ActnList, FMX.ListView.Types, FMX.ListView.Appearances, StrUtils,
FMX.ListView.Adapters.Base, FMX.ListView, FMX.ListBox, FMX.Objects, FMX.Edit, FMX.EditBox, FMX.SpinBox, Math;
type
THabilidade = (hAlarme,hAuraDeProtecao,hAuraDeCombate,hAuraDeVelocidade,hExplodir,hFurtividade,hImortal,hIniciatia,hLadino,hParalisar,
hProtecao,hPossessao,hRecompensa,hRegenerar,hToqueDeMedo,hTravessia,hTrespassar,hVeneno,hVoar);
type
TFrmPrincipal = class(TForm)
ToolBar1: TToolBar;
Label1: TLabel;
btnMenu: TSpeedButton;
ShadowEffect1: TShadowEffect;
btnVoltar: TSpeedButton;
ActionList1: TActionList;
actHabilidades: TAction;
actVoltar: TAction;
tbcHabilidades: TTabControl;
tabListaHabilidades: TTabItem;
tabDescricaoHabilidade: TTabItem;
lsbHabilidades: TListBox;
lbiAlarme: TListBoxItem;
lbiAuraDeProtecao: TListBoxItem;
lbiAuraDeCombate: TListBoxItem;
lbiAuraDeVelocidade: TListBoxItem;
lbiExplodir: TListBoxItem;
lbiFurtividade: TListBoxItem;
lbiImortal: TListBoxItem;
lbiIniciativa: TListBoxItem;
lbiLadino: TListBoxItem;
lbiParalisar: TListBoxItem;
lbiProtecao: TListBoxItem;
lbiPossessao: TListBoxItem;
lbiRecompensa: TListBoxItem;
lbiRegenerar: TListBoxItem;
lbiToqueDeMedo: TListBoxItem;
lbiTravessia: TListBoxItem;
lbiTrespassar: TListBoxItem;
lbiVeneno: TListBoxItem;
lbiVoar: TListBoxItem;
lblNomeHabilidade: TLabel;
lblDescricaoHabilidade: TLabel;
tbcPrincipal: TTabControl;
tabInicial: TTabItem;
tabHabilidades: TTabItem;
GridPanelLayout1: TGridPanelLayout;
imgHabilidades: TImage;
Label2: TLabel;
ShadowEffect_Habilidades: TShadowEffect;
VertScrollBoxHabilidades: TVertScrollBox;
imgFortaleza: TImage;
Label3: TLabel;
ShadowEffect_Fortaleza: TShadowEffect;
tabFortaleza: TTabItem;
actFortaleza: TAction;
lytGerarDanoEDefesa: TLayout;
lytDanoGerado: TLayout;
lytFortaleza4: TLayout;
rec25: TRectangle;
Image3: TImage;
rec26: TRectangle;
Image4: TImage;
rec27: TRectangle;
Image5: TImage;
rec29: TRectangle;
Image6: TImage;
rec30: TRectangle;
Image7: TImage;
spbGerarDano: TSpinBox;
Button1: TButton;
recGerarDano: TRectangle;
lblDanoGerado: TLabel;
rec28: TRectangle;
Image29: TImage;
lytFortaleza3: TLayout;
rec19: TRectangle;
Image10: TImage;
rec20: TRectangle;
Image11: TImage;
rec21: TRectangle;
Image12: TImage;
rec23: TRectangle;
Image13: TImage;
rec24: TRectangle;
Image14: TImage;
rec22: TRectangle;
Image15: TImage;
rec17: TRectangle;
Image8: TImage;
rec18: TRectangle;
Image9: TImage;
lytFortaleza2: TLayout;
rec11: TRectangle;
Image1: TImage;
rec12: TRectangle;
Image2: TImage;
rec13: TRectangle;
Image16: TImage;
rec15: TRectangle;
Image17: TImage;
rec16: TRectangle;
Image18: TImage;
rec14: TRectangle;
Image19: TImage;
rec9: TRectangle;
Image20: TImage;
rec10: TRectangle;
Image21: TImage;
lytFortaleza1: TLayout;
rec3: TRectangle;
Image22: TImage;
rec4: TRectangle;
Image23: TImage;
rec5: TRectangle;
Image24: TImage;
rec7: TRectangle;
Image25: TImage;
rec8: TRectangle;
Image26: TImage;
rec6: TRectangle;
Image27: TImage;
rec1: TRectangle;
Image28: TImage;
rec2: TRectangle;
Image30: TImage;
lytFortaleza_BordaEsquerda: TLayout;
lytFortaleza_BordaDIreita: TLayout;
ScaledLayoutFortaleza: TScaledLayout;
recFundoGerandoDano: TRectangle;
recFundoGerarDano: TRectangle;
ShadowEffect2: TShadowEffect;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
Label16: TLabel;
Label17: TLabel;
Label18: TLabel;
Label19: TLabel;
Label20: TLabel;
Label21: TLabel;
Label22: TLabel;
Label23: TLabel;
Label24: TLabel;
Label25: TLabel;
Label26: TLabel;
Label27: TLabel;
Label28: TLabel;
Label29: TLabel;
Label30: TLabel;
Label31: TLabel;
Label32: TLabel;
Label33: TLabel;
Image31: TImage;
ShadowEffect3: TShadowEffect;
lytBotaoGerarDano: TLayout;
recTituloDefesas: TRectangle;
Label34: TLabel;
lytDefesa2: TLayout;
lytDefesa1: TLayout;
btnReconstruir: TButton;
lytAdcDefesa: TLayout;
btnAdcDefesa: TButton;
spbAdcDefesa: TSpinBox;
recFundoBotaoGerarDano: TRectangle;
ShadowEffect4: TShadowEffect;
recFundoFortaleza: TRectangle;
procedure actVoltarExecute(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure lbiHabilidadeClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure actHabilidadesExecute(Sender: TObject);
procedure imgHabilidadesClick(Sender: TObject);
procedure actFortalezaExecute(Sender: TObject);
procedure imgFortalezaClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnReconstruirClick(Sender: TObject);
procedure recGerarDanoClick(Sender: TObject);
procedure btnAdcDefesaClick(Sender: TObject);
procedure ImageFortalezaClick(Sender: TObject);
private
ListaFortaleza: TListBox;
Habilidade: THabilidade;
QuantidadeDano: Integer;
procedure AtualizaAreasDestruidas;
procedure ConstruirFortaleza;
procedure GeraMaisUmDano;
public
{ Public declarations }
end;
var
FrmPrincipal: TFrmPrincipal;
implementation
{$R *.fmx}
procedure TFrmPrincipal.actFortalezaExecute(Sender: TObject);
begin
tbcPrincipal.ActiveTab := tabFortaleza;
end;
procedure TFrmPrincipal.actHabilidadesExecute(Sender: TObject);
begin
tbcPrincipal.ActiveTab := tabHabilidades;
end;
procedure TFrmPrincipal.actVoltarExecute(Sender: TObject);
begin
if (tbcPrincipal.ActiveTab = tabHabilidades) and (tbcHabilidades.ActiveTab = tabDescricaoHabilidade) then
begin
tbcHabilidades.ActiveTab := tabListaHabilidades;
Exit;
end
else if tbcPrincipal.ActiveTab <> tabInicial then
begin
tbcPrincipal.ActiveTab := tabInicial;
end
else
begin
Close;
end;
end;
procedure TFrmPrincipal.Button1Click(Sender: TObject);
begin
if ListaFortaleza.Count = 0 then
Exit;
QuantidadeDano := Trunc(spbGerarDano.Value);
spbGerarDano.Value := 0;
if QuantidadeDano <= 0 then
Exit;
lblDanoGerado.Text := '';
recFundoGerandoDano.Visible := True;
lytDanoGerado.Visible := True;
lytDanoGerado.BringToFront;
Application.ProcessMessages;
GeraMaisUmDano;
//TimerGerarDano.Enabled := True;
end;
procedure TFrmPrincipal.FormCreate(Sender: TObject);
var
i: Integer;
begin
ListaFortaleza := TListBox.Create(Self);
ConstruirFortaleza;
end;
procedure TFrmPrincipal.FormKeyDown(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
if key = vkHardwareBack then
begin
Key := 0;
actVoltar.Execute;
end;
end;
procedure TFrmPrincipal.FormShow(Sender: TObject);
begin
tbcPrincipal.ActiveTab := tabInicial;
tbcHabilidades.ActiveTab := tabListaHabilidades;
tbcPrincipal.TabPosition := TTabPosition.None;
tbcHabilidades.TabPosition := TTabPosition.None;
end;
procedure TFrmPrincipal.imgFortalezaClick(Sender: TObject);
begin
ShadowEffect_Fortaleza.Enabled := True;
Application.ProcessMessages;
Sleep(100);
actFortaleza.Execute;
ShadowEffect_Fortaleza.Enabled := False;
end;
procedure TFrmPrincipal.imgHabilidadesClick(Sender: TObject);
begin
ShadowEffect_Habilidades.Enabled := True;
Application.ProcessMessages;
Sleep(100);
actHabilidades.Execute;
ShadowEffect_Habilidades.Enabled := False;
end;
procedure TFrmPrincipal.lbiHabilidadeClick(Sender: TObject);
begin
Habilidade := THabilidade(TListBoxItem(Sender).Index);
lblNomeHabilidade.Text := '';
lblDescricaoHabilidade.Text := '';
if Habilidade = hAlarme then
begin
lblNomeHabilidade.Text := 'ALARME';
lblDescricaoHabilidade.Text := 'Quando esta unidade é atacada, unidades aliadas a até 1 quadrado de distância podem se mover 1 quadrado.' +
'Na invasão, as unidades aliadas ignoram os inimigos e avançam 1 quadrado em direção a Fortaleza.';
end;
if Habilidade = hAuraDeProtecao then
begin
lblNomeHabilidade.Text := 'AURA DE PROTEÇÃO';
lblDescricaoHabilidade.Text := 'Outras unidades aliadas, a até 1 quadrado de distância desta unidade, ganham a habilidade "Proteção".';
end;
if Habilidade = hAuraDeCombate then
begin
lblNomeHabilidade.Text := 'AURA DE COMBATE';
lblDescricaoHabilidade.Text := 'Outras unidades aliadas, a até 1 quadrado de distância desta unidade, ganham bônus de +X(Dano).';
end;
if Habilidade = hAuraDeVelocidade then
begin
lblNomeHabilidade.Text := 'AURA DE VELOCIDADE';
lblDescricaoHabilidade.Text := 'Outras unidades aliadas, que começarem o turno a até 1 quadrado de distância desta unidade, gaham bônus '+
'de +X em seu deslocamento.';
end;
if Habilidade = hExplodir then
begin
lblNomeHabilidade.Text := 'EXPLODIR';
lblDescricaoHabilidade.Text := 'Quando esta unidade é destruida, ela causa seu valor de combate contra todas as unidades inimigas que ' +
'estejam em seu quadrado (Rajada) ou em um outro quadrado que esteja até x(Rajada) de distância. Unidades ' +
'vencidas desta forma não dão recursos ao vencedor.';
end;
if Habilidade = hFurtividade then
begin
lblNomeHabilidade.Text := 'FURTIVIDADE';
lblDescricaoHabilidade.Text := 'Unidades com Furtividade só podem ser atacadas por unidades que tenham ALARME ou INICIATIVA. Porém, se ' +
'uma unidade com Furtividade atacar um inimigo, o combate é resolvido normalmente.';
end;
if Habilidade = hImortal then
begin
lblNomeHabilidade.Text := 'IMORTAL';
lblDescricaoHabilidade.Text := 'Unidades com esta habilidade quando derrotadas não dão recursos para o vencedor; estes recursos ' +
'voltam para o dono dela.';
end;
if Habilidade = hIniciatia then
begin
lblNomeHabilidade.Text := 'INICIATIVA';
lblDescricaoHabilidade.Text := 'Após o uso de cartas de Tática, Eventos de Combate e ativação de cartas de Evolução, em caso de empate ' +
'no combate, esta unidade ataca primeiro e não recebe dano. Caso as duas unidades tenham iniciativa, ' +
'elas se cancelam.';
end;
if Habilidade = hLadino then
begin
lblNomeHabilidade.Text := 'LADINO: X[Carcaça, Mana e/ou Material]';
lblDescricaoHabilidade.Text := 'Esta unidade, quando sobrevive a um combate, rouba X[Carcaça, Mana e/ou Material] retirado diretamente ' +
'do oponente. Se a unidade atacada for controlada pela tabuleiro pegue X[Carcaça, Mana e /ou Material] ' +
'diretamente da caixa.';
end;
if Habilidade = hParalisar then
begin
lblNomeHabilidade.Text := 'PARALISAR';
lblDescricaoHabilidade.Text := 'Ao término do combate, unidades que atacaram ou foram atacadas por uma unidade com esta habilidade '+
'ficam paralisadas até o fim da rodada, ou até serem ativadas.' + #13 + #13 +
'Unidades Paralisadas: Quando uma unidade é paralisada. Esta unidade perde um em ataque e não pode se mover ' +
'usar cartas de Evento de Combate, cartas de Tática ou bônus de cartas de Evolução.';
end;
if Habilidade = hProtecao then
begin
lblNomeHabilidade.Text := 'PROTEÇÃO';
lblDescricaoHabilidade.Text := 'Em caso de empate no combate, esta unidade, em vez de ser destruída, fica paralisada. Caso as duas unidades ' +
'envolvidas no combate tenham Proteção, as duas ficam paralisadas. Se uma das unidades tiver, além de proteção ' +
'iniciativa, ela não fica paralisada.';
end;
if Habilidade = hPossessao then
begin
lblNomeHabilidade.Text := 'POSSESSÃO';
lblDescricaoHabilidade.Text := 'Quando esta unidade for derrotada em combate você pode ativar imediatamente a unidade inimiga que a derrotou ' +
'como se fosse uma de suas unidades. Se a unidade com Possessão for controlada pelo tabuleiro use-a para ' +
'atacar a Fortaleza inimiga. Se não for possível use-a para atacar a unidade inimiga mais próxima. ' +
'Se não for possível atacar um inimigo ou uma fortaleza inimiga paralise esta unidade.';
end;
if Habilidade = hRecompensa then
begin
lblNomeHabilidade.Text := 'RECOMPENSA';
lblDescricaoHabilidade.Text := 'Quando esta unidade é derrotada, quem a derrotou ganha X pontos de Influência.';
end;
if Habilidade = hRegenerar then
begin
lblNomeHabilidade.Text := 'REGENERAR: X[Carcaça, Mana e /ou Material]';
lblDescricaoHabilidade.Text := 'Quando uma unidade com regenerar é destruída em combate, você pode pagar X[Carcaça, Mana e/ou Material] ' +
'para que a unidade não seja destruída e retorne para a sua reserva.';
end;
if Habilidade = hToqueDeMedo then
begin
lblNomeHabilidade.Text := 'TOQUE DE MEDO: X';
lblDescricaoHabilidade.Text := 'Unidades inimigas que entrarem em combate com esta unidade são movidas X quadrados, na direção ' +
'escolhida pelo jogador que controla a unidade com Toque de Medo, no final do combate. Unidades controladas ' +
'pelo tabuleiro se movem em direção contrária a Fortaleza, pelo caminho que vieram.';
end;
if Habilidade = hTravessia then
begin
lblNomeHabilidade.Text := 'TRAVESSIA';
lblDescricaoHabilidade.Text := 'Esta habilidade de movimento dá à unidade a capacidade de ignorar terrenos perigosos, barreiras ' +
'terrenos intransponíveis e fossos';
end;
if Habilidade = hTrespassar then
begin
lblNomeHabilidade.Text := 'TRESPASSAR';
lblDescricaoHabilidade.Text := 'Esta unidade pode atacar todos os inimigos a seu alcance enquanto percorre seu deslocamento. ' +
'Se esta unidade for vencida, paralisada ou não puder mais se deslocar, ela não continua atacando.';
end;
if Habilidade = hVeneno then
begin
lblNomeHabilidade.Text := 'VENENO: -X(Dano)';
lblDescricaoHabilidade.Text := 'Inimigos atacados por esta unidade tem -X(Dano) de combate até o final do turno';
end;
if Habilidade = hVoar then
begin
lblNomeHabilidade.Text := 'VOAR';
lblDescricaoHabilidade.Text := 'Unidades com a habilidades voar podem ocupar espaços dentro de quadrados marcados com (Voar) e não sofrem ' +
'efeitos de fossos. Unidades com a habilidade voar só recebem dano em combate de outras unidades com a ' +
'habilidade voar, unidades com ataques à distância e unidades em Torres. Porém, se esta unidade ' +
'atacar um inimigo, o combate é resolvido normalmente.';
end;
tbcHabilidades.ActiveTab := tabDescricaoHabilidade;
VertScrollBoxHabilidades.RealignContent;
end;
procedure TFrmPrincipal.recGerarDanoClick(Sender: TObject);
begin
GeraMaisUmDano;
end;
procedure TfrmPrincipal.GeraMaisUmDano;
var
IndexAreaAtingida: Integer;
AreaAtingida: String;
RecAtingido: TRectangle;
begin
if (QuantidadeDano = 0) or (ListaFortaleza.Count = 0) then
begin
recFundoGerandoDano.Visible := False;
lytDanoGerado.Visible := False;
Exit;
end;
IndexAreaAtingida := Random(ListaFortaleza.Count-1);
RecAtingido := TRectangle(ListaFortaleza.ItemByIndex(IndexAreaAtingida).Data);
if (RecAtingido.Parent = lytDefesa2) or (RecAtingido.Parent = lytDefesa1) then
AreaAtingida := '0'
else
AreaAtingida := ReplaceStr(RecAtingido.Name,'rec','');
ListaFortaleza.Items.Delete(IndexAreaAtingida);
lblDanoGerado.Text := AreaAtingida;
Application.ProcessMessages;
AtualizaAreasDestruidas;
QuantidadeDano := QuantidadeDano - 1;
end;
procedure TFrmPrincipal.ImageFortalezaClick(Sender: TObject);
begin
if ListaFortaleza.Items.IndexOfObject(Timage(Sender).Parent) = -1 then
ListaFortaleza.Items.AddObject('',Timage(Sender).Parent)
else
ListaFortaleza.Items.Delete(ListaFortaleza.Items.IndexOfObject(Timage(Sender).Parent));
AtualizaAreasDestruidas;
end;
procedure TFrmPrincipal.AtualizaAreasDestruidas;
var
I: Integer;
def1, def2: Integer;
RecAreaAtingida: TRectangle;
begin
spbGerarDano.Value := 0;
spbAdcDefesa.Value := 0;
for I := 0 to Self.ComponentCount -1 do
begin
if (Self.Components[i] is TRectangle) then
begin
RecAreaAtingida := TRectangle(Self.Components[i]);
if RecAreaAtingida.Parent.Parent = ScaledLayoutFortaleza then
begin
if ListaFortaleza.Items.IndexOfObject( RecAreaAtingida ) = -1 then
RecAreaAtingida.Fill.Color := TAlphaColors.Red
else
RecAreaAtingida.Fill.Color := TAlphaColors.Darkgray;
end;
end;
end;
for def1 := 0 to lytDefesa1.ComponentCount -1 do
begin
if (lytDefesa1.Components[def1] is TRectangle) then
begin
RecAreaAtingida := TRectangle(lytDefesa1.Components[def1]);
if RecAreaAtingida.Parent.Parent = ScaledLayoutFortaleza then
begin
if ListaFortaleza.Items.IndexOfObject( RecAreaAtingida ) = -1 then
RecAreaAtingida.Fill.Color := TAlphaColors.Red
else
RecAreaAtingida.Fill.Color := TAlphaColors.Darkgray;
end;
end;
end;
for def2 := 0 to lytDefesa2.ComponentCount -1 do
begin
if (lytDefesa2.Components[def2] is TRectangle) then
begin
RecAreaAtingida := TRectangle(lytDefesa2.Components[def2]);
if RecAreaAtingida.Parent.Parent = ScaledLayoutFortaleza then
begin
if ListaFortaleza.Items.IndexOfObject( RecAreaAtingida ) = -1 then
RecAreaAtingida.Fill.Color := TAlphaColors.Red
else
RecAreaAtingida.Fill.Color := TAlphaColors.Darkgray;
end;
end;
end;
end;
procedure TFrmPrincipal.btnAdcDefesaClick(Sender: TObject);
var
Rec: TRectangle;
Lbl: TLabel;
Image: TImage;
I: Integer;
LayoutDestino: TLayout;
begin
if spbAdcDefesa.Value > 0 then
begin
for I := 1 to Trunc(spbAdcDefesa.Value) do
begin
if lytDefesa2.ComponentCount < 8 then
LayoutDestino := lytDefesa2
else if lytDefesa1.ComponentCount < 8 then
LayoutDestino := lytDefesa1
else
Continue;
Rec := TRectangle.Create(LayoutDestino);
Rec.Parent := LayoutDestino;
rec.Align := TAlignLayout.Left;
Rec.Width := 40;
Rec.Margins.Left := 2;
rec.Margins.Right := 2;
rec.Margins.Bottom := 2;
rec.Margins.Top := 2;
Image := TImage.Create(Rec);
Image.Parent := Rec;
Image.Align := TAlignLayout.Contents;
Image.MultiResBitmap.Add.Bitmap := Image3.MultiResBitmap[0].Bitmap;
Image.Opacity := 0.4;
image.OnClick := ImageFortalezaClick;
Lbl := TLabel.Create(Rec);
Lbl.Parent := Rec;
lbl.Align := TAlignLayout.Client;
Lbl.Text := '00';
Lbl.StyledSettings := [];
lbl.TextSettings.Font.Size := 22;
Lbl.TextSettings.Font.Style := [TFontStyle.fsbold];
lbl.TextSettings.HorzAlign := TTextAlign.Center;
ListaFortaleza.Items.AddObject('',Rec);
end;
spbAdcDefesa.Value := 0;
AtualizaAreasDestruidas;
end;
end;
procedure TFrmPrincipal.btnReconstruirClick(Sender: TObject);
begin
ConstruirFortaleza;
AtualizaAreasDestruidas;
end;
procedure TFrmPrincipal.ConstruirFortaleza;
var
i,j: Integer;
begin
//destruir retangulos de defesa
for j := lytDefesa2.ComponentCount -1 downto 0 do
lytDefesa2.Components[j].DisposeOf;
for j := lytDefesa1.ComponentCount -1 downto 0 do
lytDefesa1.Components[j].DisposeOf;
ListaFortaleza.Items.Clear;
for i := 1 to 30 do
begin
ListaFortaleza.Items.AddObject('rec'+i.ToString, (TFmxObject(FindComponent('rec'+i.ToString))));
end;
end;
end.
|
unit UBarraBotoes;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,
Data.DB, Vcl.ComCtrls, Vcl.Menus;
type
TFBarraBotoes = class(TFrame)
sbBotoes: TScrollBox;
btAnterior: TBitBtn;
btProximo: TBitBtn;
btNovo: TBitBtn;
btAlterar: TBitBtn;
btSalvar: TBitBtn;
btCancelar: TBitBtn;
btExluir: TBitBtn;
btFechar: TBitBtn;
dsDados: TDataSource;
btImprimir: TBitBtn;
pmImpressao: TPopupMenu;
procedure dsDadosStateChange(Sender: TObject);
procedure btFecharClick(Sender: TObject);
procedure btAnteriorClick(Sender: TObject);
procedure btProximoClick(Sender: TObject);
procedure btNovoClick(Sender: TObject);
procedure btAlterarClick(Sender: TObject);
procedure btCancelarClick(Sender: TObject);
private
{ Private declarations }
public
procedure HabilitaDesabilitaBotoes;
end;
implementation
uses
uDmERP, UTelaInicial;
{$R *.dfm}
procedure TFBarraBotoes.HabilitaDesabilitaBotoes;
begin
btAnterior.Enabled := (dsDados.DataSet.Active) and
(not (dsDados.DataSet.IsEmpty)) and
(dsDados.DataSet.State = dsBrowse);
btProximo.Enabled := btAnterior.Enabled;
btAlterar.Enabled := btAnterior.Enabled;
btExluir.Enabled := btAnterior.Enabled;
btNovo.Enabled := (dsDados.DataSet.Active) and
(dsDados.DataSet.State = dsBrowse);
btFechar.Enabled := (dsDados.DataSet.State = dsBrowse) or (not dsDados.DataSet.Active);
btSalvar.Enabled := (dsDados.DataSet.Active) and
(dsDados.DataSet.State in dsEditModes);
btCancelar.Enabled := btSalvar.Enabled;
end;
procedure TFBarraBotoes.btAlterarClick(Sender: TObject);
begin
dsDados.DataSet.Edit;
end;
procedure TFBarraBotoes.btAnteriorClick(Sender: TObject);
begin
dsDados.DataSet.Prior;
end;
procedure TFBarraBotoes.btCancelarClick(Sender: TObject);
begin
dsDados.DataSet.Cancel;
end;
procedure TFBarraBotoes.btFecharClick(Sender: TObject);
var
Tab : TTabSheet;
begin
dsDados.DataSet.Close;
Tab := FTelaInicial.pcTelas.ActivePage;
if Assigned(Tab) then
begin
Tab.Parent := nil;
Tab.PageControl := nil;
FreeAndNil(Tab);
end;
// Self.Parent.Free;
// FTelaInicial.pcTelas.ActivePage.Free;
FTelaInicial.pcTelas.Visible := FTelaInicial.pcTelas.PageCount > 0;
FTelaInicial.imLogoERP.Visible := not FTelaInicial.pcTelas.Visible;
end;
procedure TFBarraBotoes.btNovoClick(Sender: TObject);
begin
dsDados.DataSet.Insert;
end;
procedure TFBarraBotoes.btProximoClick(Sender: TObject);
begin
dsDados.DataSet.Next;
end;
procedure TFBarraBotoes.dsDadosStateChange(Sender: TObject);
begin
HabilitaDesabilitaBotoes;
end;
end.
|
unit uFontEditor;
interface
{$I ..\FIBPlus.inc}
uses
Windows, Messages, SysUtils, Classes,
{$IFDEF D_XE2}
Vcl.Graphics, Vcl.Controls,Vcl.Forms, Vcl.Dialogs,Vcl.StdCtrls,Vcl.ComCtrls
{$ELSE}
Graphics, Controls,Forms,ComCtrls, StdCtrls, Dialogs
{$ENDIF},
pFIBSyntaxMemo,uFIBEditorForm;
type
TfrmFontEditor = class(TFIBEditorCustomForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
lstTokens: TListBox;
Label1: TLabel;
Label2: TLabel;
edColor: TEdit;
GroupBox1: TGroupBox;
chBold: TCheckBox;
chItalic: TCheckBox;
chUnderLine: TCheckBox;
edFont: TEdit;
btnChangeFont: TButton;
btnChangeColor: TButton;
FontDialog1: TFontDialog;
ColorDialog1: TColorDialog;
TabSheet2: TTabSheet;
chUseMetaInProposal: TCheckBox;
procedure lstTokensKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lstTokensMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure chBoldClick(Sender: TObject);
procedure btnChangeFontClick(Sender: TObject);
procedure btnChangeColorClick(Sender: TObject);
procedure chUseMetaInProposalClick(Sender: TObject);
private
FEditor:TMPCustomSyntaxMemo;
procedure ShowCurrents;
procedure ChangeFontStyle(Sender: TObject);
procedure ChangeColor;
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
{ Public declarations }
end;
var
frmFontEditor: TfrmFontEditor;
procedure ChangeEditorProps(Editor:TMPCustomSyntaxMemo);
implementation
uses IBSQLSyn;
{$R *.DFM}
procedure ChangeEditorProps(Editor:TMPCustomSyntaxMemo);
var
Caller:TForm;
Form: TfrmFontEditor;
begin
Form:= TfrmFontEditor.Create(Application);
frmFontEditor:=Form;
Form.FEditor:=Editor;
Caller:=Screen.ActiveForm;
if fsModal in Caller.FormState then
begin
Caller.Enabled:=False;
try
Form.lstTokens.ItemIndex:=0;
Form.ShowCurrents;
Form.Show ;
Form.FreeNotification(Editor);
Form.SetFocus;
finally
Caller.Enabled:=True
end
end;
end;
procedure TfrmFontEditor.lstTokensKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
ShowCurrents
end;
type THackWinControl=class(TCustomControl);
procedure TfrmFontEditor.ShowCurrents;
var CurToken:TToken;
begin
chUseMetaInProposal.Checked:=FEditor.Tag=0;
edFont.Text:=THackWinControl(FEditor).Font.Name+
' (Size:'+IntToStr(THackWinControl(FEditor).Font.Size)+')'
;
case lstTokens.ItemIndex of
1: CurToken:=tokKeyWord;
2: CurToken:=tokFunction;
3: CurToken:=tokParam ;
4: CurToken:=tokTypes;
5: CurToken:=tokILComment;
6: CurToken:=tokString;
7: CurToken:=tokInteger;
else
CurToken:=tokReservedSiO
end;
if CurToken<>tokReservedSiO then
begin
chBold.Enabled:=True;
chItalic.Enabled:=True;
chUnderLine.Enabled:=True;
edColor.Color:=FEditor.SyntaxAttributes.FontColor[CurToken];
chBold.Checked:=fsBold in FEditor.SyntaxAttributes.FontStyle[CurToken];
chItalic.Checked:=fsItalic in FEditor.SyntaxAttributes.FontStyle[CurToken];
chUnderLine.Checked:=fsUnderline in FEditor.SyntaxAttributes.FontStyle[CurToken];
end
else
begin
chBold.Checked:=False;
chItalic.Checked:=False;
chUnderLine.Checked:=False;
chBold.Enabled:=False;
chItalic.Enabled:=False;
chUnderLine.Enabled:=False;
case lstTokens.ItemIndex of
0:
edColor.Color:=FEditor.Color;
8:
begin
// edColor.Color:=FEditor.SelectedWordColor;
edColor.Color:=FEditor.SelColor;
end
end;
end
end;
procedure TfrmFontEditor.lstTokensMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
ShowCurrents
end;
procedure TfrmFontEditor.chBoldClick(Sender: TObject);
begin
ChangeFontStyle(Sender)
end;
procedure TfrmFontEditor.chUseMetaInProposalClick(Sender: TObject);
begin
if chUseMetaInProposal.Checked then
FEditor.Tag:=0
else
FEditor.Tag:=1
end;
procedure TfrmFontEditor.ChangeFontStyle(Sender: TObject);
var CurToken:TToken;
begin
case lstTokens.ItemIndex of
1: CurToken:=tokKeyWord;
2: CurToken:=tokFunction;
3: CurToken:=tokParam ;
4: CurToken:=tokTypes;
5: CurToken:=tokILComment;
6: CurToken:=tokString;
7: CurToken:=tokInteger;
else
CurToken:=tokReservedSiO
end;
if CurToken<>tokReservedSiO then
begin
if TCheckBox(Sender).Checked then
begin
if Sender = chBold then
FEditor.SyntaxAttributes.FontStyle[CurToken]:=FEditor.SyntaxAttributes.FontStyle[CurToken]+[fsBold]
else
if Sender = chItalic then
FEditor.SyntaxAttributes.FontStyle[CurToken]:=FEditor.SyntaxAttributes.FontStyle[CurToken]+[fsItalic]
else
if Sender = chUnderLine then
FEditor.SyntaxAttributes.FontStyle[CurToken]:=FEditor.SyntaxAttributes.FontStyle[CurToken]+[fsUnderLine] ;
end
else
begin
if Sender = chBold then
FEditor.SyntaxAttributes.FontStyle[CurToken]:=FEditor.SyntaxAttributes.FontStyle[CurToken]-[fsBold]
else
if Sender = chItalic then
FEditor.SyntaxAttributes.FontStyle[CurToken]:=FEditor.SyntaxAttributes.FontStyle[CurToken]-[fsItalic]
else
if Sender = chUnderLine then
FEditor.SyntaxAttributes.FontStyle[CurToken]:=FEditor.SyntaxAttributes.FontStyle[CurToken]-[fsUnderLine]
end;
FEditor.SyntaxAttributes.FontStyle[tokMLCommentBeg]:=FEditor.SyntaxAttributes.FontStyle[tokILComment];
FEditor.SyntaxAttributes.FontStyle[tokMLCommentEND]:=FEditor.SyntaxAttributes.FontStyle[tokILComment];
FEditor.SyntaxAttributes.FontStyle[tokELCommentBeg]:=FEditor.SyntaxAttributes.FontStyle[tokILComment];
FEditor.SyntaxAttributes.FontStyle[tokELCommentEND]:=FEditor.SyntaxAttributes.FontStyle[tokILComment];
FEditor.Invalidate
end
end;
procedure TfrmFontEditor.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent=FEDitor) then
begin
Free;
frmFontEditor:=nil
end
end;
procedure TfrmFontEditor.btnChangeFontClick(Sender: TObject);
begin
if FontDialog1.Execute then
begin
THackWinControl(FEditor).Font:=FontDialog1.Font;
ShowCurrents
end;
end;
procedure TfrmFontEditor.btnChangeColorClick(Sender: TObject);
begin
ColorDialog1.Color:=edColor.Color;
if ColorDialog1.Execute then
begin
edColor.Color:=ColorDialog1.Color;
ChangeColor
end
end;
procedure TfrmFontEditor.ChangeColor;
var CurToken:TToken;
begin
case lstTokens.ItemIndex of
1: CurToken:=tokKeyWord;
2: CurToken:=tokFunction;
3: CurToken:=tokParam ;
4: CurToken:=tokTypes;
5: CurToken:=tokILComment;
6: CurToken:=tokString;
7: CurToken:=tokInteger;
else
CurToken:=tokReservedSiO
end;
if CurToken<>tokReservedSiO then
begin
chBold.Enabled:=True;
chItalic.Enabled:=True;
chUnderLine.Enabled:=True;
FEditor.SyntaxAttributes.FontColor[CurToken]:=edColor.Color;
with FEditor.SyntaxAttributes do
begin
FontColor[tokStringEnd]:=FontColor[tokString];
FontStyle[tokStringEnd]:=FontStyle[tokString];
FontColor[tokFloat]:=FontColor[tokInteger];
FontStyle[tokFloat]:=FontStyle[tokInteger] ;
FontColor[tokMLCommentBeg]:=FontColor[tokILComment];
FontStyle[tokMLCommentBeg]:=FontStyle[tokILComment];
FontColor[tokMLCommentEnd]:=FontColor[tokILComment];
FontStyle[tokMLCommentEnd]:=FontStyle[tokILComment];
FontColor[tokELCommentBeg]:=FontColor[tokILComment];
FontStyle[tokELCommentBeg]:=FontStyle[tokILComment];
FontColor[tokELCommentEnd]:=FontColor[tokILComment];
FontStyle[tokELCommentEnd]:=FontStyle[tokILComment];
end
end
else
begin
case lstTokens.ItemIndex of
0:
FEditor.Color:=edColor.Color;
8:
FEditor.SelColor:=edColor.Color;
end;
end;
FEditor.Invalidate;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2018 Kike Pérez
Unit : Quick.ImageFX.Types
Description : Image manipulation with multiple graphic libraries
Author : Kike Pérez
Version : 3.0
Created : 10/04/2013
Modified : 26/02/2018
This file is part of QuickImageFX: https://github.com/exilon/QuickImageFX
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.ImageFX.Types;
interface
uses
Classes,
SysUtils,
Vcl.Controls,
Graphics,
Vcl.Imaging.pngimage,
Vcl.Imaging.jpeg,
Vcl.Imaging.GIFImg;
const
MinGraphicSize = 44;
DEF_USERAGENT = 'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
DEF_CONNECTION_TIMEOUT = 60000;
DEF_RESPONSE_TIMEOUT = 60000;
type
TRGB = record
R : Byte;
G : Byte;
B : Byte;
end;
TocvColorEncode = (ceNone,ceRGB,ceBGR, ceGRAY);
TPixelInfo = record
R : Byte;
G : Byte;
B : Byte;
A : Byte;
GV : Byte;
ColorEncode : TocvColorEncode;
EncodeInfo : Byte;
end;
TImageActionResult = (arNone, arAlreadyOptim, arOk, arUnknowFmtType, arUnknowError, arNoOverwrited, arResizeError, arRotateError,
arColorizeError,arConversionError, arFileNotExist, arZeroBytes, arCorruptedData);
TJPGQualityLevel = 1..100;
TPNGCompressionLevel = 0..9;
TImageFormat = (ifBMP, ifJPG, ifPNG, ifGIF);
TScanlineMode = (smHorizontal, smVertical);
TResizeFlags = set of (rfNoMagnify, //not stretch if source image is smaller than target size
rfCenter, //center image if target is bigger
rfFillBorders //if target is bigger fills borders with a color
);
TResizeMode = (rmStretch, //stretch original image to fit target size without preserving original aspect ratio
rmScale, //recalculate width or height target size to preserve original aspect ratio
rmCropToFill, //preserve target aspect ratio cropping original image to fill whole size
rmFitToBounds //resize image to fit max bounds of target size
);
TResamplerMode = (rsAuto, //uses rmArea for downsampling and rmLinear for upsampling
rsGDIStrech, //used only by GDI
rsNearest, //low quality - High performance
rsGR32Draft, //medium quality - High performance (downsampling only)
rsOCVArea, //medium quality - High performance (downsampling only)
rsLinear, // medium quality - Medium performance
rsGR32Kernel, //high quality - Low performance (depends on kernel width)
rsOCVCubic,
rsOCVLanczos4); //high quality - Low performance
TResizeOptions = class
NoMagnify : Boolean;
ResizeMode : TResizeMode;
ResamplerMode : TResamplerMode;
Center : Boolean;
FillBorders : Boolean;
BorderColor : TColor;
SkipSmaller : Boolean; //avoid resize smaller resolution images
end;
THTTPOptions = class
UserAgent : string;
HandleRedirects : Boolean;
MaxRedirects : Integer;
AllowCookies : Boolean;
ConnectionTimeout : Integer;
ResponseTimeout : Integer;
end;
TImageFX = class(TObject);
IImageFX = interface
['{58BC1417-EC58-472E-A503-92B199C21AE8}']
function LoadFromFile(fromfile : string; CheckIfFileExists : Boolean = False) : TImageFX;
function LoadFromFile2(fromfile : string; CheckIfFileExists : Boolean = False) : TImageFX;
function LoadFromStream(stream : TStream) : TImageFX;
function LoadFromString(str : string) : TImageFX;
function LoadFromImageList(imgList : TImageList; ImageIndex : Integer) : TImageFX;
function LoadFromIcon(Icon : TIcon) : TImageFX;
function LoadFromFileIcon(FileName : string; IconIndex : Word) : TImageFX;
function LoadFromFileExtension(aFilename : string; LargeIcon : Boolean) : TImageFX;
function LoadFromResource(ResourceName : string) : TImageFX;
function LoadFromHTTP(urlImage : string; out HTTPReturnCode : Integer; RaiseExceptions : Boolean = False) : TImageFX;
procedure GetResolution(var x,y : Integer); overload;
function GetResolution : string; overload;
function AspectRatio : Double;
function AspectRatioStr : string;
function Clone : TImageFX;
function IsGray : Boolean;
function Clear(pcolor : TColor = clWhite) : TImageFX;
function DrawCentered(png : TPngImage; alpha : Double = 1) : TImageFX; overload;
function DrawCentered(stream: TStream; alpha : Double = 1) : TImageFX; overload;
function Draw(png : TPngImage; x, y : Integer; alpha : Double = 1) : TImageFX; overload;
function Draw(jpg : TJPEGImage; x: Integer; y: Integer; alpha: Double = 1) : TImageFX; overload;
function Draw(stream : TStream; x, y : Integer; alpha : Double = 1) : TImageFX; overload;
procedure SaveToPNG(outfile : string);
procedure SaveToJPG(outfile : string);
procedure SaveToBMP(outfile : string);
procedure SaveToGIF(outfile : string);
end;
IImageFXTransform = interface
['{8B7B6447-8DFB-40F5-B729-0E2F34EB3F2F}']
function Resize(w, h : Integer) : TImageFX; overload;
function Resize(w, h : Integer; ResizeMode : TResizeMode; ResizeFlags : TResizeFlags = []; ResampleMode : TResamplerMode = rsLinear) : TImageFX; overload;
function Rotate90 : TImageFX;
function Rotate180 : TImageFX;
function Rotate270 : TImageFX;
function RotateBy(RoundAngle : Integer) : TImageFX;
function RotateAngle(RotAngle : Single) : TImageFX;
function FlipX : TImageFX;
function FlipY : TImageFX;
function GrayScale : TImageFX;
function ScanlineH : TImageFX;
function ScanlineV : TImageFX;
function Lighten(StrenghtPercent : Integer = 30) : TImageFX;
function Darken(StrenghtPercent : Integer = 30) : TImageFX;
function Tint(mColor : TColor) : TImageFX;
function TintAdd(R, G , B : Integer) : TImageFX;
function TintBlue : TImageFX;
function TintRed : TImageFX;
function TintGreen : TImageFX;
function Solarize : TImageFX;
function Rounded(RoundLevel : Integer = 27) : TImageFX;
end;
implementation
end.
|
unit TestCaseBlock;
{ AFS 5 Feb 2K
This code compiles, but is not semantically meaningfull.
It is test cases for the code-formating utility
this unit test the case statement indentation }
interface
implementation
uses SysUtils, Controls, Math;
procedure FromBorlandsStyleGuide;
// the defs are quite bogus, but they make the code compile
const
csStart = 1;
csBegin = 2;
csTimeOut = 3;
csFoo = 12;
csBar = 20;
UpdateValue = 200;
SB_LINEUP = 1;
SB_LINEDOWN = 2;
SB_PAGEUP = 3;
SB_PAGEDOWN = 4;
var
Control: TControl;
NewRange, Position, AlignMargin: integer;
x, y, j, ScrollCode: integer;
Incr, FIncrement, FLineDiv, FinalIncr, Count: integer;
FPageIncrement, FPageDiv: integer;
begin
NewRange := Max(NewRange, Position);
// CORRECT
case Control.Align of
alLeft, alNone: NewRange := Max(NewRange, Position);
alRight: Inc(AlignMargin, Control.Width);
end;
// CORRECT
case x of
csStart:
begin
j := UpdateValue;
end;
csBegin: x := j;
csFoo:
x := j;
csTimeOut:
begin
j := x;
x := UpdateValue;
end;
end;
// CORRECT
case ScrollCode of
SB_LINEUP, SB_LINEDOWN:
begin
Incr := FIncrement div FLineDiv;
FinalIncr := FIncrement mod FLineDiv;
Count := FLineDiv;
end;
SB_PAGEUP, SB_PAGEDOWN:
begin
Incr := FPageIncrement;
FinalIncr := Incr mod FPageDiv;
Incr := Incr div FPageDiv;
Count := FPageDiv;
end;
else
Count := 0;
Incr := 0;
FinalIncr := 0;
end;
// anthony's additions to test differing styles:
// naked cases, complex labels, no else
case x of
csStart, csBegin:
j := UpdateValue;
csFoo .. CsBar, 23:
j := x + 1;
csTimeOut:
j := x;
end;
// naked cases, complex labels, an else
case x of
csStart, csBegin:
j := UpdateValue;
csFoo .. CsBar, 23:
j := x + 1;
csTimeOut: j := x;
else
inc(j);
end;
// block cases, complex labels, no else
case x of
csStart, csBegin:
begin
j := UpdateValue;
j := x;
x := x + UpdateValue;
end;
csFoo .. CsBar, 23:
begin
j := x + 1;
j := x;
x := x + UpdateValue;
end;
csTimeOut:
begin
j := x;
j := j + 1;
end;
end;
// block cases, complex labels, an else
case x of
csStart, csBegin:
begin
j := UpdateValue;
j := x;
x := x + UpdateValue;
end;
csFoo .. CsBar, 23:
begin
j := x + 1;
j := x;
end;
csTimeOut:
begin
j := x;
j := j + 1;
x := x + UpdateValue;
end;
else
begin
inc(j);
j := UpdateValue;
x := x + UpdateValue;
end;
end;
// naked else
case x of
csStart, csBegin:
j := UpdateValue;
else
inc(j);
j := UpdateValue;
x := x + UpdateValue;
end;
// naked else with funky stuff therein
case x of
csStart, csBegin:
j := UpdateValue;
else
if j > 3 then // last remaining indent anomaly - this is not an else..if
inc(j);
if x > 4 then
j := UpdateValue;
if x = 5 then
x := x + UpdateValue;
end;
// naked else with funky stuff therein
case x of
csStart, csBegin:
j := UpdateValue;
else
x := 3;
if j > 3 then
begin
inc(j);
end;
end;
case x of
csStart, csBegin:
j := UpdateValue;
else
x := 3;
if j > 3 then
begin
inc(j);
end;
case y of
csStart, csBegin:
j := UpdateValue;
else
x := 3;
if j > 3 then
begin
inc(j);
end;
end;
end;
end;
procedure SimpleCase;
var
li: integer;
begin
li := Random(5);
case li of
0: li := 1;
1:
li := li + 1;
2:
begin
li := li + 1;
end;
else li := 0;
end;
end;
procedure CharCase;
var
ch, ch2: char;
li: integer;
begin
li := Random(5);
ch :=
'a';
ch := Char(Ord(ch) + li);
case ch of
'a': li := 1;
'b':
li := li + 1;
'c':
begin
li := li + 1;
end;
'd': ch2 :=
'e';
else li := 0;
end;
ch :=
'a';
end;
procedure ComplexCase;
var
iA, IB: integer;
bA: Boolean;
liLoop, liLoop2: integer;
begin
iA := Random (10);
iB := Random (10);
if iA > 5 then
bA :=True
else
bA := False;
{ the case for 4 is something else, huh?
unreadable as it gets wehn on one line,
but it compiles fine
note that the last 'else' in the proc is the default case,
not part of the if in case 5:
so it should be lined up with the 5:}
case Random (7) of
1: iA := 0;
2: for liLoop := 1 to 10 do iA := iA + Random (2);
3: if iA > 5 then ba := False else ba := True;
14: if iA > 5 then for liLoop := 1 to 10 do iA := iA + Random (2) else while IA < 50 do iA := iA + Random (5);
5:
if iA > 6 then for liLoop := 1 to 10 do iA := iA + Random (2);
else while IA < 50 do iA := iA + Random (5);
end;
end;
procedure LayOutMyCaseStatement;
var
iA, iB1, iCC2: integer;
begin
// empty statement
; ; ; ; ;
if Random (10) > 4 then
begin
iA := Random (20);
case iA of
1: iA := 10;
2:
iA := Random (1000);
3:
begin
iA := Random (1000);
iB1 := iA + 10;
end;
34: ; // do nothing
5:
case Random (2) of
0:
iA := 1;
1:
iA := 0;
else
iA := 4;
end;
else
begin
Raise Exception.Create ('this sucks');
end;
end; { case }
end; { if }
end;
{ test nested cases }
procedure TestNested; var
iA: integer; begin
Case Random(7) of
0: iA := 0;
1: case Random (2) of 0: iA := 1; 2:iA := 2; end;
2: case Random (2) of 0: iA := 1; 2: case Random (2) of 0: iA := 1; 2:iA := 2; end; end;
3: case Random (2) of 0: iA := 1; 2: case Random (2) of 0: iA := 1; 2: case Random (2) of 0: iA := 1; 2:iA := 2; end; end; end;
4: case Random (2) of 0: case Random (2) of 0: iA := 1; 2:iA := 2; end; 2: case Random (2) of 0: iA := 1; 2: case Random (2) of 0: iA := 1; 2:iA := 2; end; end; end;
5: case Random (2) of 0: case Random (2) of 0: iA := 1; 2:iA := 2; end; 2: case Random (2) of 0: case Random (2) of 0: iA := 1; 2:iA := 2; end; 2: case Random (2) of 0: iA := 1; 2:iA := 2; end; end; end;
6: case Random (2) of 0: case Random (2) of 0: iA := 1; 2:iA := 2; end; 2: case Random (2) of 0: case Random (2) of 0: iA := 1; 2:iA := 2; end; 2: case Random (2) of 0: iA := 1; 2: case Random (2) of 0: iA := 1; 2:iA := 2; end; end; end; end;
end;
end;
procedure TestElse;
var
li: integer;
begin
case Random(7) of
0:
li := 1;
else
li := 0;
end;
case Random(7) of
0:
li := 1;
else
begin
li := 0;
end;
end;
case Random(7) of
0:
li := 1;
else
begin
case Random(7) of
0:
li := 1;
else
li := 0;
end;
end;
end;
case Random(7) of
0:
li := 1;
else
begin
case Random(7) of
0:
li := 1;
else
begin
case Random(7) of
0:
li := 1;
else
li := 0;
end;
end;
end;
end;
end;
end;
end.
|
unit CommandSet.ATA;
interface
uses
Windows, SysUtils, Dialogs,
OSFile.IoControl, CommandSet, BufferInterpreter, Device.SMART.List,
BufferInterpreter.ATA;
type
TATACommandSet = class sealed(TCommandSet)
public
function IdentifyDevice: TIdentifyDeviceResult; override;
function SMARTReadData: TSMARTValueList; override;
function RAWIdentifyDevice: String; override;
function RAWSMARTReadData: String; override;
function DataSetManagement(StartLBA, LBACount: Int64): Cardinal; override;
function IsDataSetManagementSupported: Boolean; override;
function IsExternal: Boolean; override;
procedure Flush; override;
private
type
ATA_SINGLE_TASK_FILE = record
Features: UCHAR;
SectorCount: UCHAR;
LBALoSectorNumber: UCHAR;
LBAMidCycleLo: UCHAR;
LBAHiCycleHi: UCHAR;
DeviceHead: UCHAR;
Command: UCHAR;
Reserved: UCHAR;
end;
ATA_TASK_FILES = record
PreviousTaskFile: ATA_SINGLE_TASK_FILE;
CurrentTaskFile: ATA_SINGLE_TASK_FILE;
end;
ATA_PASS_THROUGH_DIRECT = record
Length: USHORT;
AtaFlags: USHORT;
PathId: UCHAR;
TargetId: UCHAR;
Lun: UCHAR;
ReservedAsUchar: UCHAR;
DataTransferLength: ULONG;
TimeOutValue: ULONG;
ReservedAsUlong: ULONG;
DataBuffer: PVOID;
TaskFile: ATA_TASK_FILES;
end;
ATA_WITH_BUFFER = record
Parameter: ATA_PASS_THROUGH_DIRECT;
Buffer: TSmallBuffer;
end;
const
ATA_FLAGS_DRDY_REQUIRED = 1;
ATA_FLAGS_DATA_IN = 1 shl 1;
ATA_FLAGS_DATA_OUT = 1 shl 2;
ATA_FLAGS_48BIT_COMMAND = 1 shl 3;
ATA_FLAGS_USE_DMA = 1 shl 4;
ATA_FLAGS_NO_MULTIPLE = 1 shl 5;
ATA_FLAGS_NON_DATA = 0;
private
IoInnerBuffer: ATA_WITH_BUFFER;
IoOSBuffer: TIoControlIOBuffer;
function GetCommonBuffer: ATA_WITH_BUFFER;
function GetCommonTaskFile: ATA_TASK_FILES;
procedure SetOSBufferByInnerBuffer;
procedure SetInnerBufferAsFlagsAndTaskFile(Flags: ULONG;
TaskFile: ATA_TASK_FILES);
procedure SetInnerBufferToSMARTReadData;
procedure SetInnerBufferToDataSetManagement(StartLBA, LBACount: Int64);
procedure SetInnerBufferToIdentifyDevice;
procedure SetDataSetManagementBuffer(StartLBA, LBACount: Int64);
procedure SetLBACountToDataSetManagementBuffer(LBACount: Int64);
procedure SetStartLBAToDataSetManagementBuffer(StartLBA: Int64);
function InterpretIdentifyDeviceBuffer: TIdentifyDeviceResult;
procedure SetBufferAndIdentifyDevice;
function InterpretSMARTReadDataBuffer: TSMARTValueList;
procedure SetBufferAndSMARTReadData;
procedure SetBufferAndSMARTReadThreshold;
procedure SetInnerBufferToSMARTReadThreshold;
function InterpretSMARTThresholdBuffer(
const OriginalResult: TSMARTValueList): TSMARTValueList;
procedure SetInnerBufferToFlush;
end;
implementation
{ TATACommandSet }
function TATACommandSet.GetCommonBuffer: ATA_WITH_BUFFER;
begin
FillChar(result, SizeOf(result), #0);
result.Parameter.Length := SizeOf(result.Parameter);
result.Parameter.DataTransferLength := SizeOf(result.Buffer);
result.Parameter.TimeOutValue := 30;
end;
function TATACommandSet.GetCommonTaskFile: ATA_TASK_FILES;
begin
FillChar(result, SizeOf(result), #0);
end;
procedure TATACommandSet.SetInnerBufferAsFlagsAndTaskFile
(Flags: ULONG; TaskFile: ATA_TASK_FILES);
begin
IoInnerBuffer := GetCommonBuffer;
IoInnerBuffer.Parameter.AtaFlags := Flags;
IoInnerBuffer.Parameter.TaskFile := TaskFile;
IoInnerBuffer.Parameter.DataBuffer := @IoInnerBuffer.Buffer;
end;
procedure TATACommandSet.SetInnerBufferToIdentifyDevice;
const
IdentifyDeviceCommand = $EC;
var
IoTaskFile: ATA_TASK_FILES;
begin
IoTaskFile := GetCommonTaskFile;
IoTaskFile.CurrentTaskFile.Command := IdentifyDeviceCommand;
SetInnerBufferAsFlagsAndTaskFile(ATA_FLAGS_DATA_IN, IoTaskFile);
end;
procedure TATACommandSet.SetOSBufferByInnerBuffer;
begin
IoOSBuffer.InputBuffer.Size := SizeOf(IoInnerBuffer);
IoOSBuffer.InputBuffer.Buffer := @IOInnerBuffer;
IoOSBuffer.OutputBuffer.Size := SizeOf(IoInnerBuffer);
IoOSBuffer.OutputBuffer.Buffer := @IOInnerBuffer;
end;
procedure TATACommandSet.SetBufferAndIdentifyDevice;
begin
SetInnerBufferToIdentifyDevice;
SetOSBufferByInnerBuffer;
IoControl(TIoControlCode.ATAPassThroughDirect, IoOSBuffer);
end;
function TATACommandSet.InterpretIdentifyDeviceBuffer:
TIdentifyDeviceResult;
var
ATABufferInterpreter: TATABufferInterpreter;
begin
ATABufferInterpreter := TATABufferInterpreter.Create;
result :=
ATABufferInterpreter.BufferToIdentifyDeviceResult(IoInnerBuffer.Buffer);
FreeAndNil(ATABufferInterpreter);
end;
function TATACommandSet.IdentifyDevice: TIdentifyDeviceResult;
begin
SetBufferAndIdentifyDevice;
result := InterpretIdentifyDeviceBuffer;
result.StorageInterface := TStorageInterface.ATA;
end;
procedure TATACommandSet.SetInnerBufferToSMARTReadData;
const
SMARTFeatures = $D0;
SMARTCycleLo = $4F;
SMARTCycleHi = $C2;
SMARTReadDataCommand = $B0;
var
IoTaskFile: ATA_TASK_FILES;
begin
IoTaskFile := GetCommonTaskFile;
IoTaskFile.CurrentTaskFile.Features := SMARTFeatures;
IoTaskFile.CurrentTaskFile.LBAMidCycleLo := SMARTCycleLo;
IoTaskFile.CurrentTaskFile.LBAHiCycleHi := SMARTCycleHi;
IoTaskFile.CurrentTaskFile.Command := SMARTReadDataCommand;
SetInnerBufferAsFlagsAndTaskFile(ATA_FLAGS_DATA_IN, IoTaskFile);
end;
procedure TATACommandSet.SetBufferAndSMARTReadData;
begin
SetInnerBufferToSMARTReadData;
SetOSBufferByInnerBuffer;
IoControl(TIoControlCode.ATAPassThroughDirect, IoOSBuffer);
end;
function TATACommandSet.InterpretSMARTReadDataBuffer:
TSMARTValueList;
var
ATABufferInterpreter: TATABufferInterpreter;
begin
ATABufferInterpreter := TATABufferInterpreter.Create;
result := ATABufferInterpreter.BufferToSMARTValueList(IoInnerBuffer.Buffer);
FreeAndNil(ATABufferInterpreter);
end;
procedure TATACommandSet.SetInnerBufferToSMARTReadThreshold;
const
SMARTFeatures = $D1;
SMARTCycleLo = $4F;
SMARTCycleHi = $C2;
SMARTReadDataCommand = $B0;
var
IoTaskFile: ATA_TASK_FILES;
begin
IoTaskFile := GetCommonTaskFile;
IoTaskFile.CurrentTaskFile.Features := SMARTFeatures;
IoTaskFile.CurrentTaskFile.LBAMidCycleLo := SMARTCycleLo;
IoTaskFile.CurrentTaskFile.LBAHiCycleHi := SMARTCycleHi;
IoTaskFile.CurrentTaskFile.Command := SMARTReadDataCommand;
SetInnerBufferAsFlagsAndTaskFile(ATA_FLAGS_DATA_IN, IoTaskFile);
end;
procedure TATACommandSet.SetBufferAndSMARTReadThreshold;
begin
SetInnerBufferToSMARTReadThreshold;
SetOSBufferByInnerBuffer;
IoControl(TIoControlCode.ATAPassThroughDirect, IoOSBuffer);
end;
function TATACommandSet.InterpretSMARTThresholdBuffer(
const OriginalResult: TSMARTValueList): TSMARTValueList;
var
ATABufferInterpreter: TATABufferInterpreter;
ThresholdList: TSMARTValueList;
begin
result := OriginalResult;
ATABufferInterpreter := TATABufferInterpreter.Create;
ThresholdList := ATABufferInterpreter.BufferToSMARTThresholdValueList(
IoInnerBuffer.Buffer);
try
OriginalResult.MergeThreshold(ThresholdList);
finally
FreeAndNil(ThresholdList);
end;
FreeAndNil(ATABufferInterpreter);
end;
function TATACommandSet.SMARTReadData: TSMARTValueList;
begin
SetBufferAndSMARTReadData;
result := InterpretSMARTReadDataBuffer;
SetBufferAndSMARTReadThreshold;
result := InterpretSMARTThresholdBuffer(result);
end;
function TATACommandSet.IsDataSetManagementSupported: Boolean;
begin
exit(true);
end;
function TATACommandSet.IsExternal: Boolean;
begin
result := false;
end;
function TATACommandSet.RAWIdentifyDevice: String;
begin
SetBufferAndIdentifyDevice;
result :=
IdentifyDevicePrefix +
TBufferInterpreter.BufferToString(IoInnerBuffer.Buffer) + ';';
end;
function TATACommandSet.RAWSMARTReadData: String;
begin
SetBufferAndSMARTReadData;
result :=
SMARTPrefix +
TBufferInterpreter.BufferToString(IoInnerBuffer.Buffer) + ';';
SetBufferAndSMARTReadThreshold;
result := result +
'Threshold' +
TBufferInterpreter.BufferToString(IoInnerBuffer.Buffer) + ';';
end;
procedure TATACommandSet.SetStartLBAToDataSetManagementBuffer(StartLBA: Int64);
const
StartLBALo = 0;
begin
IoInnerBuffer.Buffer[StartLBALo] := StartLBA and 255;
StartLBA := StartLBA shr 8;
IoInnerBuffer.Buffer[StartLBALo + 1] := StartLBA and 255;
StartLBA := StartLBA shr 8;
IoInnerBuffer.Buffer[StartLBALo + 2] := StartLBA and 255;
StartLBA := StartLBA shr 8;
IoInnerBuffer.Buffer[StartLBALo + 3] := StartLBA and 255;
StartLBA := StartLBA shr 8;
IoInnerBuffer.Buffer[StartLBALo + 4] := StartLBA and 255;
StartLBA := StartLBA shr 8;
IoInnerBuffer.Buffer[StartLBALo + 5] := StartLBA;
end;
procedure TATACommandSet.SetLBACountToDataSetManagementBuffer(LBACount: Int64);
const
LBACountHi = 7;
LBACountLo = 6;
begin
IoInnerBuffer.Buffer[LBACountLo] := LBACount and 255;
IoInnerBuffer.Buffer[LBACountHi] := LBACount shr 8;
end;
procedure TATACommandSet.SetDataSetManagementBuffer(
StartLBA, LBACount: Int64);
begin
SetStartLBAToDataSetManagementBuffer(StartLBA);
SetLBACountToDataSetManagementBuffer(LBACount);
end;
procedure TATACommandSet.SetInnerBufferToDataSetManagement
(StartLBA, LBACount: Int64);
const
DataSetManagementFlags =
ATA_FLAGS_48BIT_COMMAND or ATA_FLAGS_DATA_OUT or ATA_FLAGS_USE_DMA;
DataSetManagementFeatures = $1;
DataSetManagementSectorCount = $1;
DataSetManagementCommand = $6;
var
IoTaskFile: ATA_TASK_FILES;
begin
IoTaskFile := GetCommonTaskFile;
IoTaskFile.CurrentTaskFile.Features := DataSetManagementFeatures;
IoTaskFile.CurrentTaskFile.SectorCount := DataSetManagementSectorCount;
IoTaskFile.CurrentTaskFile.Command := DataSetManagementCommand;
SetInnerBufferAsFlagsAndTaskFile(DataSetManagementFlags, IoTaskFile);
SetDataSetManagementBuffer(StartLBA, LBACount);
end;
function TATACommandSet.DataSetManagement(StartLBA, LBACount: Int64): Cardinal;
begin
SetInnerBufferToDataSetManagement(StartLBA, LBACount);
SetOSBufferByInnerBuffer;
result := ExceptionFreeIoControl
(TIoControlCode.ATAPassThroughDirect, IoOSBuffer);
end;
procedure TATACommandSet.SetInnerBufferToFlush;
const
FlushCommand = $E7;
var
IoTaskFile: ATA_TASK_FILES;
begin
IoTaskFile := GetCommonTaskFile;
IoTaskFile.CurrentTaskFile.Command := FlushCommand;
SetInnerBufferAsFlagsAndTaskFile(ATA_FLAGS_NON_DATA, IoTaskFile);
end;
procedure TATACommandSet.Flush;
begin
SetInnerBufferToFlush;
IoControl(TIoControlCode.ATAPassThroughDirect,
BuildOSBufferBy<ATA_WITH_BUFFER, ATA_WITH_BUFFER>(IoInnerBuffer,
IoInnerBuffer));
end;
end.
|
unit u_frameExamineItemUIBase;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, CnEdit, Gauges, ExtCtrls, u_CommonDef, PlumUtils;
type
TPanel = Class(ExtCtrls.TPanel)
Protected
procedure Paint; override;
End;
TFrameCustomExamineItemUI = class(TFrame, IExamineItemUI)
Panel1: TPanel;
Label1: TLabel;
edInlineInsLoss: TCnEdit;
lbExamineItemCaption: TLabel;
btnToggle: TButton;
Gauge1: TGauge;
procedure btnToggleClick(Sender: TObject);
private
{ Private declarations }
FExamineItem: Integer;//IExamineItem; //weak
Protected
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
Protected //Interface
function get_ExamineItem: IExamineItem;
Procedure set_ExamineItem(const Value: IExamineItem);
Procedure set_Percent(const Value: Single);
function get_Enabled(): Boolean;
Procedure set_Enabled(const Value: Boolean);
function get_ButtonCaption: String;
Procedure set_ButtonCaption(const Value: String);
function get_ButtonEnabled: Boolean;
Procedure set_ButtonEnabled(const Value: Boolean);
Procedure SetEnableRecursion(const Value: Boolean);
Procedure SyncUI(Ptr: Pointer); Virtual;
public
{ Public declarations }
Constructor Create(AOwner: TComponent); Override;
end;
TExamineItemUIClass = Class of TFrameCustomExamineItemUI;
implementation
uses
u_ExamineGlobal;
{$R *.dfm}
{ TFrameCustomExamineItem }
procedure TFrameCustomExamineItemUI.btnToggleClick(Sender: TObject);
var
AExamineItem: IExamineItem;
begin
g_ExamineMode:= emSingle;
AExamineItem:= IExamineItem(FExamineItem);
AExamineItem.InlineInsertLost:= edInlineInsLoss.Value;
case AExamineItem.Status of
esReady:
begin
case g_ExamineMode of
emSingle:
begin
AExamineItem.SetAll_Status(esWait, AExamineItem);
end;
emBatch:
begin
end;
end;
AExamineItem.Start;
end;
esWait: ;
esExecute:
begin
case g_ExamineMode of
emSingle:
begin
AExamineItem.SetAll_Status(esWait, AExamineItem);
end;
emBatch:
begin
end;
end;
AExamineItem.Stop;
end;
esComplete:
begin
case g_ExamineMode of
emSingle:
begin
if Dialogs.MessageDlg('已经完成此项测试, 要重新开始吗?',
mtConfirmation, mbYesNo, 0) = mrYes then
begin
AExamineItem.Start;
end;
end;
emBatch:
begin
end;
end;
end;
end;
end;
procedure TFrameCustomExamineItemUI.CMEnabledChanged(var Message: TMessage);
var
i: Integer;
begin
inherited;
if HandleAllocated and not (csDesigning in ComponentState) then
begin
for i := 0 to self.ControlCount - 1 do
begin
self.Controls[i].Enabled:= self.Enabled;
end;
end;
end;
constructor TFrameCustomExamineItemUI.Create(AOwner: TComponent);
begin
inherited;
lbExamineItemCaption.Font.Size:= lbExamineItemCaption.Font.Size + 3;
lbExamineItemCaption.Font.color:= clBlue;
end;
function TFrameCustomExamineItemUI.get_Enabled: Boolean;
begin
Result:= Self.Enabled;
end;
function TFrameCustomExamineItemUI.get_ExamineItem: IExamineItem;
begin
Result:= IExamineItem(FExamineItem);
end;
procedure TFrameCustomExamineItemUI.SetEnableRecursion(const Value: Boolean);
begin
SetControlEnable(Self, Value, True);
end;
function TFrameCustomExamineItemUI.get_ButtonCaption: String;
begin
Result:= btnToggle.Caption;
end;
function TFrameCustomExamineItemUI.get_ButtonEnabled: Boolean;
begin
Result:= btnToggle.Enabled;
end;
procedure TFrameCustomExamineItemUI.set_Percent(const Value: Single);
begin
Gauge1.Progress:= Trunc(Value);
end;
procedure TFrameCustomExamineItemUI.SyncUI(Ptr: Pointer);
begin
//
end;
procedure TFrameCustomExamineItemUI.set_ButtonCaption(const Value: String);
begin
btnToggle.Caption:= Value;
end;
procedure TFrameCustomExamineItemUI.set_ButtonEnabled(const Value: Boolean);
begin
btnToggle.Enabled:= Value;
end;
procedure TFrameCustomExamineItemUI.set_Enabled(const Value: Boolean);
begin
if Self.Enabled <> Value then
begin
Self.Enabled:= Value;
end;
end;
procedure TFrameCustomExamineItemUI.set_ExamineItem(const Value: IExamineItem);
begin
FExamineItem:= Integer(Value);
self.lbExamineItemCaption.Caption:= Value.ExamineCaption;
self.edInlineInsLoss.Text:= FloatToStr(Value.InlineInsertLost);
end;
{ TPanel }
procedure TPanel.Paint;
begin
inherited;
Exit;
// Canvas.Pen.Style:= psSolid;
// Canvas.Pen.Color:= clBlack;
Canvas.Brush.Style:= bsSolid;
Canvas.Brush.Color:= clBlack;
Canvas.FrameRect(self.BoundsRect);
end;
end.
|
unit Soccer.VotingRules.Plurality;
interface
uses
System.SysUtils,
System.Generics.Collections,
Soccer.Voting.RulesDict,
Soccer.Voting.Preferences,
Soccer.Voting.AbstractRule;
type
TSoccerPluralityVotingRule = class(TInterfacedObject, ISoccerVotingRule)
private
FMoreThenTwoAlternativesAllowed: boolean;
procedure CalculateScores(LCandidates
: System.Generics.Collections.TList<string>;
LScores: System.Generics.Collections.TList<Integer>;
AProfile: TSoccerVotingVotersPreferences);
function FindMaximalScore(AScoresList: TList<Integer>): Integer;
function FindBestCandidates(ACandidatesList: TList<string>;
AScoresList: TList<Integer>; AMaxScore: Integer): TList<string>;
function IsAppliable(AProfile: TSoccerVotingVotersPreferences): boolean;
public
constructor Create(AMoreThenTwoAlternativesAllowed: boolean);
function GetName: string;
function ExecuteOn(AProfile: TSoccerVotingVotersPreferences;
out Winners: TList<string>): boolean;
end;
implementation
{ TSoccerPluralityVotingRule }
constructor TSoccerPluralityVotingRule.Create(AMoreThenTwoAlternativesAllowed
: boolean);
begin
FMoreThenTwoAlternativesAllowed := AMoreThenTwoAlternativesAllowed;
end;
function TSoccerPluralityVotingRule.ExecuteOn
(AProfile: TSoccerVotingVotersPreferences;
out Winners: TList<string>): boolean;
var
LCandidates: TList<string>;
LScores: TList<Integer>;
LMax: Integer;
begin
Result := IsAppliable(AProfile);
if not Result then
exit;
LCandidates := TList<string>.Create;
LScores := TList<Integer>.Create;
CalculateScores(LCandidates, LScores, AProfile);
LMax := FindMaximalScore(LScores);
Winners := FindBestCandidates(LCandidates, LScores, LMax);
FreeAndNil(LCandidates);
FreeAndNil(LScores);
end;
function TSoccerPluralityVotingRule.FindBestCandidates(ACandidatesList: TList<string>;
AScoresList: TList<Integer>; AMaxScore: Integer): TList<string>;
var
i: Integer;
begin
Result := TList<string>.Create;
for i := 0 to ACandidatesList.Count - 1 do
begin
if AScoresList[i] = AMaxScore then
Result.Add(ACandidatesList[i]);
end;
end;
function TSoccerPluralityVotingRule.FindMaximalScore
(AScoresList: TList<Integer>): Integer;
var
LScore: Integer;
begin
Result := 0;
for LScore in AScoresList do
begin
if LScore > Result then
Result := LScore;
end;
end;
procedure TSoccerPluralityVotingRule.CalculateScores
(LCandidates
: System.Generics.Collections.TList<string>;
LScores: System.Generics.Collections.TList<Integer>;
AProfile: TSoccerVotingVotersPreferences);
var
LVoter: TSoccerVotingIndividualPreferenceProfile;
LFirstAlternative: string;
LIndex: Integer;
begin
{ Calculate scores }
for LVoter in AProfile.Profile do
begin
LFirstAlternative := LVoter[0];
if not LCandidates.Contains(LFirstAlternative) then
begin
LCandidates.Add(LFirstAlternative);
LScores.Add(1);
end
else
begin
LIndex := LCandidates.IndexOf(LFirstAlternative);
LScores[LIndex] := LScores[LIndex] + 1;
end;
end;
end;
function TSoccerPluralityVotingRule.GetName: string;
begin
if FMoreThenTwoAlternativesAllowed then
Result := 'plurality'
else
Result := 'plurality2';
end;
function TSoccerPluralityVotingRule.IsAppliable
(AProfile: TSoccerVotingVotersPreferences): boolean;
begin
Result := FMoreThenTwoAlternativesAllowed or
(AProfile.Properties.AlternativesCount <= 2);
end;
var
LRule: ISoccerVotingRule;
initialization
LRule := TSoccerPluralityVotingRule.Create(false);
GlobalVotingRulesDict.Rules.Add(LRule.GetName, LRule);
LRule := TSoccerPluralityVotingRule.Create(true);
GlobalVotingRulesDict.Rules.Add(LRule.GetName, LRule);
end.
|
unit ncFrmWebPopup;
{
ResourceString: Dario 12/03/13
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, SHDocVw_EWB, EwbCore, EmbeddedWB, Automation, ncClassesBase,
ExtCtrls, ncBaseWebApi;
type
TFrmWebPopup = class(TForm)
WB: TEmbeddedWB;
TimerErro: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure WBDocumentComplete(ASender: TObject; const pDisp: IDispatch;
var URL: OleVariant);
procedure FormShow(Sender: TObject);
procedure WBCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure WBNavigateError(ASender: TObject; const pDisp: IDispatch; var URL,
Frame, StatusCode: OleVariant; var Cancel: WordBool);
procedure WBGetExternal(Sender: TCustomEmbeddedWB;
var ppDispatch: IDispatch);
function WBShowMessage(Sender: TObject; HWND: Cardinal; lpstrText,
lpstrCaption: PWideChar; dwType: Integer; lpstrHelpFile: PWideChar;
dwHelpContext: Integer; var plResult: Integer): HRESULT;
procedure TimerErroTimer(Sender: TObject);
private
{ Private declarations }
function NavURL: String;
protected
function CreateApi: TncBaseWebApi; virtual; abstract;
public
Fechar : Boolean;
URL : String;
{ Public declarations }
end;
TFrmWebPopupClass = class of TFrmWebPopup;
var
FrmWebPopup: TFrmWebPopup;
FrmWebPopupClass: TFrmWebPopupClass = nil;
implementation
uses uVersionInfo, nexUrls;
{$R *.dfm}
procedure TFrmWebPopup.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmWebPopup.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := Fechar;
end;
procedure TFrmWebPopup.FormCreate(Sender: TObject);
begin
Width := 1;
Height := 1;
Fechar := False;
URL := '';
end;
procedure TFrmWebPopup.FormShow(Sender: TObject);
begin
WB.navigate(navURL);
// WB.navigate('file:///C:/Users/Joao/Desktop/premium_popup.html');
end;
procedure TFrmWebPopup.TimerErroTimer(Sender: TObject);
begin
TimerErro.Enabled := False;
WB.navigate(navURL);
end;
function TFrmWebPopup.navURL: String;
begin
if Trim(URL) = '' then
Result := gUrls.Url('nexmsg', 'conta='+ // do not localize
gConfig.Conta+'&cok='+BoolStr[gConfig.FreePremium or (gConfig.QtdLic>0)]+ // do not localize
'&ver='+SelfShortVer+ // do not localize
'&sw='+prefixo_versao) // do not localize
else
Result := URL;
end;
procedure TFrmWebPopup.WBCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
Fechar := True;
CanClose := True;
Close;
end;
procedure TFrmWebPopup.WBDocumentComplete(ASender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
var
S: String;
I, P: Integer;
SL : TStrings;
Sair : Boolean;
begin
Sair := True;
try
S := WB.DocumentSource;
P := Pos('!nexinfo!="', S); // do not localize
if P=0 then Exit;
Delete(S, 1, P+10);
S := Copy(S, 1, Pos('"', S)-1);
if S='' then Exit;
SL := TStringList.Create;
try
P := Pos(';', S);
while P > 0 do begin
SL.Add(Copy(S, 1, P-1));
Delete(S, 1, P);
P := Pos(';', S);
end;
if Trim(S)>'' then SL.Add(Trim(S));
if not SameText(SL.Values['Ok'], 'Ok') then Exit; // do not localize
Width := StrToIntDef(Sl.Values['W'], 0);
Height := StrToIntDef(Sl.Values['H'], 0);
if (Width=0) or (Height=0) then Exit;
case StrToIntDef(SL.Values['BS'], 2) of // do not localize
0 : BorderStyle := bsNone;
1 : BorderStyle := bsSingle;
2 : BorderStyle := bsDialog;
3 : BorderStyle := bsToolWindow;
4 : BorderStyle := bsSizeToolWin;
else
BorderStyle := bsDialog;
end;
Caption := WB.Doc2.Title;
{ if not SameText(SL.Values['SC'], 'S') then
WB.UserInterfaceOptions := WB.UserInterfaceOptions + [DontUseScrollbars];}
WB.Repaint;
Fechar := SameText(SL.Values['CC'], 'S'); // do not localize
Top := (Screen.Height - Height) div 2;
Left := (Screen.Width - Width) div 2;
Sair := False;
finally
SL.Free;
end;
finally
if Sair then begin
Fechar := True;
Close;
end;
end;
end;
procedure TFrmWebPopup.WBGetExternal(Sender: TCustomEmbeddedWB;
var ppDispatch: IDispatch);
begin
ppDispatch := TAutoObjectDispatch.Create(CreateApi) as IDispatch;
end;
procedure TFrmWebPopup.WBNavigateError(ASender: TObject; const pDisp: IDispatch;
var URL, Frame, StatusCode: OleVariant; var Cancel: WordBool);
begin
Cancel := True;
TimerErro.Enabled := True;
{ Fechar := True;
Close;}
end;
function TFrmWebPopup.WBShowMessage(Sender: TObject; HWND: Cardinal; lpstrText,
lpstrCaption: PWideChar; dwType: Integer; lpstrHelpFile: PWideChar;
dwHelpContext: Integer; var plResult: Integer): HRESULT;
begin
ShowMessage(lpstrText);
end;
end.
|
unit UnMovimentoDeContaCorrenteListaRegistrosView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, JvExControls, JvButton, JvTransparentButton, ExtCtrls, Grids,
DBGrids, StdCtrls, Mask, JvExMask, JvToolEdit, JvMaskEdit, JvCheckedMaskEdit,
JvDatePickerEdit,
{ helsonsant }
Util, DataUtil, UnModelo, Componentes, UnAplicacao,
UnMovimentoDeContaCorrenteListaRegistrosModelo, JvExDBGrids, JvDBGrid,
JvDBUltimGrid, Data.DB;
type
TMovimentoDeContaCorrenteListaRegistrosView = class(TForm, ITela)
Panel1: TPanel;
btnIncluir: TJvTransparentButton;
pnlFiltro: TPanel;
gMovimentos: TJvDBUltimGrid;
btnImprimir: TJvTransparentButton;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
EdtFiltro: TEdit;
txtInicio: TJvDatePickerEdit;
txtFim: TJvDatePickerEdit;
Label1: TLabel;
Label2: TLabel;
procedure btnIncluirClick(Sender: TObject);
procedure gMovimentosDblClick(Sender: TObject);
procedure btnImprimirClick(Sender: TObject);
private
FControlador: IResposta;
FMovimentoDeContaCorrenteListaRegistrosModelo:
TMovimentoDeContaCorrenteListaRegistrosModelo;
public
function Descarregar: ITela;
function Controlador(const Controlador: IResposta): ITela;
function Modelo(const Modelo: TModelo): ITela;
function Preparar: ITela;
function ExibirTela: Integer;
published
procedure FiltrarLancamentos(Sender: TObject);
end;
var
MovimentoDeContaCorrenteListaRegistrosView: TMovimentoDeContaCorrenteListaRegistrosView;
implementation
{$R *.dfm}
{ TMovimentoDeContaCorrenteListaRegistrosView }
function TMovimentoDeContaCorrenteListaRegistrosView.Controlador(
const Controlador: IResposta): ITela;
begin
Self.FControlador := Controlador;
Result := Self;
end;
function TMovimentoDeContaCorrenteListaRegistrosView.Descarregar: ITela;
begin
Self.FControlador := nil;
Result := Self;
end;
function TMovimentoDeContaCorrenteListaRegistrosView.ExibirTela: Integer;
begin
Result := Self.ShowModal;
end;
function TMovimentoDeContaCorrenteListaRegistrosView.Modelo(
const Modelo: TModelo): ITela;
begin
Self.FMovimentoDeContaCorrenteListaRegistrosModelo :=
(Modelo as TMovimentoDeContaCorrenteListaRegistrosModelo);
Result := Self;
end;
function TMovimentoDeContaCorrenteListaRegistrosView.Preparar: ITela;
begin
Self.gMovimentos.DataSource :=
Self.FMovimentoDeContaCorrenteListaRegistrosModelo.DataSource;
Self.txtInicio.Date := Date - 7;
Self.txtFim.Date := Date;
Self.FMovimentoDeContaCorrenteListaRegistrosModelo
.CarregarRegistros(Self.txtInicio.Date, Self.txtFim.Date,
Self.EdtFiltro.Text);
Result := Self;
end;
procedure TMovimentoDeContaCorrenteListaRegistrosView.btnIncluirClick(
Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FMovimentoDeContaCorrenteListaRegistrosModelo.Parametros;
_parametros
.Gravar('acao', Ord(adrIncluir));
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
procedure TMovimentoDeContaCorrenteListaRegistrosView.FiltrarLancamentos(
Sender: TObject);
begin
Self.FMovimentoDeContaCorrenteListaRegistrosModelo.CarregarRegistros(
Self.txtInicio.Date, Self.txtFim.Date, Self.EdtFiltro.Text);
end;
procedure TMovimentoDeContaCorrenteListaRegistrosView.gMovimentosDblClick(
Sender: TObject);
var
_parametros: TMap;
_chamada: TChamada;
_modelo: TModelo;
begin
_modelo := Self.FMovimentoDeContaCorrenteListaRegistrosModelo;
_parametros := _modelo.Parametros;
_parametros
.Gravar('acao', Ord(adrCarregar))
.Gravar('oid', _modelo.DataSet.FieldByName('ccormv_oid').AsString);
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
procedure TMovimentoDeContaCorrenteListaRegistrosView.btnImprimirClick(
Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FMovimentoDeContaCorrenteListaRegistrosModelo.Parametros;
_parametros
.Gravar('acao', Ord(adrOutra))
.Gravar('inicio', Self.txtInicio.Text)
.Gravar('fim', Self.txtFim.Text)
.Gravar('modelo',
Self.FMovimentoDeContaCorrenteListaRegistrosModelo);
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
//
//主要实现:
//-----------------------------------------------------------------------------}
unit untGroupRightsObjects;
interface
uses
Windows, Messages, SysUtils, Variants, Classes;
type
//用户组权限--公司信息
TGroupCompany = class
private
FGUID,
FCompanyCName,
FCompanyEName,
FCompanyID,
FParentCompanyGUID: string;
function GetCompanyCName: string;
function GetCompanyEName: string;
function GetCompanyID: string;
function GetGUID: string;
procedure SetCompanyCName(const Value: string);
procedure SetCompanyEName(const Value: string);
procedure SetCompanyID(const Value: string);
procedure SetGUID(const Value: string);
function GetParentCompanyGUID: string;
procedure SetParentCompanyGUID(const Value: string);
public
property GUID: string read GetGUID write SetGUID;
property CompanyCName: string read GetCompanyCName write SetCompanyCName;
property CompanyEName: string read GetCompanyEName write SetCompanyEName;
property CompanyID: string read GetCompanyID write SetCompanyID;
property ParentCompanyGUID: string read GetParentCompanyGUID write SetParentCompanyGUID;
end;
//用户组权限--部门信息
TGroupDept = class
private
FDeptGUID,
FDeptCName,
FDeptEName,
FParentDeptGUID,
FCompanyGUID: string;
FiOrder: Integer;
function GetDeptCName: string;
function GetDeptEName: string;
function GetDeptGUID: string;
function GetiOrder: Integer;
function GetParentDeptGUID: string;
procedure SetDeptCName(const Value: string);
procedure SetDeptEName(const Value: string);
procedure SetDeptGUID(const Value: string);
procedure SetiOrder(const Value: Integer);
procedure SetParentDeptGUID(const Value: string);
function GetCompanyGUID: string;
procedure SetCompanyGUID(const Value: string);
public
property DeptGUID: string read GetDeptGUID write SetDeptGUID;
property DeptCName: string read GetDeptCName write SetDeptCName;
property DeptEName: string read GetDeptEName write SetDeptEName;
property ParentDeptGUID: string read GetParentDeptGUID write SetParentDeptGUID;
property iOrder: Integer read GetiOrder write SetiOrder;
property CompanyGUID: string read GetCompanyGUID write SetCompanyGUID;
end;
//用户组权限--角色信息
TGroupRole = class
private
FRoleGUID,
FRoleName,
FParentRoleGUID,
FDescription,
FDeptGUID : string;
FiOrder : Integer;
function GetDescription: string;
function GetiOrder: Integer;
function GetParentRoleGUID: string;
function GetRoleGUID: string;
function GetRoleName: string;
procedure SetDescription(const Value: string);
procedure SetiOrder(const Value: Integer);
procedure SetParentRoleGUID(const Value: string);
procedure SetRoleGUID(const Value: string);
procedure SetRoleName(const Value: string);
function GetDeptGUID: string;
procedure SetDeptGUID(const Value: string);
public
property RoleGUID: string read GetRoleGUID write SetRoleGUID;
property RoleName: string read GetRoleName write SetRoleName;
property ParentRoleGUID: string read GetParentRoleGUID write SetParentRoleGUID;
property Description: string read GetDescription write SetDescription;
property iOrder: Integer read GetiOrder write SetiOrder;
property DeptGUID: string read GetDeptGUID write SetDeptGUID;
end;
//用户组权限--用户帐号信息
TGroupUser = class
private
FLoginGUID,
FLoginName,
FRoleGUID,
FEmployeeGUID,
FEmployeeCName,
FEmployeeEName,
FSexGUID: string;
function GetEmployeeCName: string;
function GetEmployeeEName: string;
function GetEmployeeGUID: string;
function GetLoginGUID: string;
function GetLoginName: string;
function GetRoleGUID: string;
function GetSexGUID: string;
procedure setEmployeeCName(const Value: string);
procedure setEmployeeEName(const Value: string);
procedure setEmployeeGUID(const Value: string);
procedure setLoginGUID(const Value: string);
procedure setLoginName(const Value: string);
procedure setRoleGUID(const Value: string);
procedure setSexGUID(const Value: string);
public
property LoginGUID: string read GetLoginGUID write setLoginGUID;
property LoginName: string read GetLoginName write setLoginName;
property RoleGUID: string read GetRoleGUID write setRoleGUID;
property EmployeeGUID: string read GetEmployeeGUID write setEmployeeGUID;
property EmployeeCName: string read GetEmployeeCName write setEmployeeCName;
property EmployeeEName: string read GetEmployeeEName write setEmployeeEName;
property SexGUID: string read GetSexGUID write setSexGUID;
end;
//用户组权限--权限资源信息
TGroupRoleResource = class
private
FGUID,
FRoleGUID,
FResourceGUID,
FResourceName,
FParentResourceGUID: string;
FiOrder: Integer;
FChecked: Boolean;
function GetGUID: string;
function GetiOrder: Integer;
function GetParentResourceGUID: string;
function GetResourceGUID: string;
function GetResourceName: string;
procedure setGUID(const Value: string);
procedure setiOrder(const Value: Integer);
procedure setParentResourceGUID(const Value: string);
procedure setResourceGUID(const Value: string);
procedure setResourceName(const Value: string);
function GetChecked: Boolean;
procedure SetChecked(const Value: Boolean);
function GetRoleGUID: string;
procedure setRoleGUID(const Value: string);
public
property GUID: string read GetGUID write setGUID;
property RoleGUID: string read GetRoleGUID write setRoleGUID;
property ResourceGUID: string read GetResourceGUID write setResourceGUID;
property ResourceName: string read GetResourceName write setResourceName;
property ParentResourceGUID: string read GetParentResourceGUID write setParentResourceGUID;
property iOrder: Integer read GetiOrder write setiOrder;
property Checked: Boolean read GetChecked write SetChecked;
end;
//角色对应的资源信息
TGroupUserResource = class
private
FGUID,
FRoleGUID,
FResourceGUID: string;
function GetGUID: string;
function GetResourceGUID: string;
function GetRoleGUID: string;
procedure setGUID(const Value: string);
procedure setResourceGUID(const Value: string);
procedure setRoleGUID(const Value: string);
public
property GUID: string read GetGUID write setGUID;
property RoleGUID: string read GetRoleGUID write setRoleGUID;
property ResourceGUID: string read GetResourceGUID write setResourceGUID;
end;
implementation
{ TGroupCompany }
function TGroupCompany.GetCompanyCName: string;
begin
Result := FCompanyCName;
end;
function TGroupCompany.GetCompanyEName: string;
begin
Result := FCompanyEName;
end;
function TGroupCompany.GetCompanyID: string;
begin
Result := FCompanyID;
end;
function TGroupCompany.GetGUID: string;
begin
Result := FGUID;
end;
function TGroupCompany.GetParentCompanyGUID: string;
begin
Result := FParentCompanyGUID;
end;
procedure TGroupCompany.SetCompanyCName(const Value: string);
begin
FCompanyCName := Value;
end;
procedure TGroupCompany.SetCompanyEName(const Value: string);
begin
FCompanyEName := Value;
end;
procedure TGroupCompany.SetCompanyID(const Value: string);
begin
FCompanyID := Value;
end;
procedure TGroupCompany.SetGUID(const Value: string);
begin
FGUID := Value;
end;
procedure TGroupCompany.SetParentCompanyGUID(const Value: string);
begin
FParentCompanyGUID := Value;
end;
{ TGroupDept }
function TGroupDept.GetCompanyGUID: string;
begin
Result := FCompanyGUID;
end;
function TGroupDept.GetDeptCName: string;
begin
Result := FDeptCName;
end;
function TGroupDept.GetDeptEName: string;
begin
Result := FDeptEName;
end;
function TGroupDept.GetDeptGUID: string;
begin
Result := FDeptGUID;
end;
function TGroupDept.GetiOrder: Integer;
begin
Result := FiOrder;
end;
function TGroupDept.GetParentDeptGUID: string;
begin
Result := FDeptGUID;
end;
procedure TGroupDept.SetCompanyGUID(const Value: string);
begin
FCompanyGUID := Value;
end;
procedure TGroupDept.SetDeptCName(const Value: string);
begin
FDeptCName := Value;
end;
procedure TGroupDept.SetDeptEName(const Value: string);
begin
FDeptEName := Value;
end;
procedure TGroupDept.SetDeptGUID(const Value: string);
begin
FDeptGUID := Value;
end;
procedure TGroupDept.SetiOrder(const Value: Integer);
begin
FiOrder := Value;
end;
procedure TGroupDept.SetParentDeptGUID(const Value: string);
begin
FParentDeptGUID := Value;
end;
{ TGroupRole }
function TGroupRole.GetDeptGUID: string;
begin
Result := FDeptGUID;
end;
function TGroupRole.GetDescription: string;
begin
Result := FDescription;
end;
function TGroupRole.GetiOrder: Integer;
begin
Result := FiOrder;
end;
function TGroupRole.GetParentRoleGUID: string;
begin
Result := FParentRoleGUID;
end;
function TGroupRole.GetRoleGUID: string;
begin
Result := FRoleGUID;
end;
function TGroupRole.GetRoleName: string;
begin
Result := FRoleName;
end;
procedure TGroupRole.SetDeptGUID(const Value: string);
begin
FDeptGUID := Value;
end;
procedure TGroupRole.SetDescription(const Value: string);
begin
FDescription := Value;
end;
procedure TGroupRole.SetiOrder(const Value: Integer);
begin
FiOrder := Value;
end;
procedure TGroupRole.SetParentRoleGUID(const Value: string);
begin
FParentRoleGUID := Value;
end;
procedure TGroupRole.SetRoleGUID(const Value: string);
begin
FRoleGUID := Value;
end;
procedure TGroupRole.SetRoleName(const Value: string);
begin
FRoleName := Value;
end;
{ TGroupUser }
function TGroupUser.GetEmployeeCName: string;
begin
Result := FEmployeeCName;
end;
function TGroupUser.GetEmployeeEName: string;
begin
Result := FEmployeeEName;
end;
function TGroupUser.GetEmployeeGUID: string;
begin
Result := FEmployeeGUID;
end;
function TGroupUser.GetLoginGUID: string;
begin
Result := FLoginGUID;
end;
function TGroupUser.GetLoginName: string;
begin
Result := FLoginName;
end;
function TGroupUser.GetRoleGUID: string;
begin
Result := FRoleGUID;
end;
function TGroupUser.GetSexGUID: string;
begin
Result := FSexGUID;
end;
procedure TGroupUser.setEmployeeCName(const Value: string);
begin
FEmployeeCName := Value;
end;
procedure TGroupUser.setEmployeeEName(const Value: string);
begin
FEmployeeEName := Value;
end;
procedure TGroupUser.setEmployeeGUID(const Value: string);
begin
FEmployeeGUID := Value;
end;
procedure TGroupUser.setLoginGUID(const Value: string);
begin
FLoginGUID := Value;
end;
procedure TGroupUser.setLoginName(const Value: string);
begin
FLoginName := Value;
end;
procedure TGroupUser.setRoleGUID(const Value: string);
begin
FRoleGUID := Value;
end;
procedure TGroupUser.setSexGUID(const Value: string);
begin
FSexGUID := Value;
end;
{ TGroupRoleResource }
function TGroupRoleResource.GetChecked: Boolean;
begin
Result := FChecked;
end;
function TGroupRoleResource.GetGUID: string;
begin
Result := FGUID;
end;
function TGroupRoleResource.GetiOrder: Integer;
begin
Result := FiOrder;
end;
function TGroupRoleResource.GetParentResourceGUID: string;
begin
Result := FParentResourceGUID;
end;
function TGroupRoleResource.GetResourceGUID: string;
begin
Result := FResourceGUID;
end;
function TGroupRoleResource.GetResourceName: string;
begin
Result := FResourceName;
end;
function TGroupRoleResource.GetRoleGUID: string;
begin
Result := FRoleGUID;
end;
procedure TGroupRoleResource.SetChecked(const Value: Boolean);
begin
FChecked := Value;
end;
procedure TGroupRoleResource.setGUID(const Value: string);
begin
FGUID := Value;
end;
procedure TGroupRoleResource.setiOrder(const Value: Integer);
begin
FiOrder := Value;
end;
procedure TGroupRoleResource.setParentResourceGUID(const Value: string);
begin
FParentResourceGUID := Value;
end;
procedure TGroupRoleResource.setResourceGUID(const Value: string);
begin
FResourceGUID := Value;
end;
procedure TGroupRoleResource.setResourceName(const Value: string);
begin
FResourceName := Value;
end;
procedure TGroupRoleResource.setRoleGUID(const Value: string);
begin
FRoleGUID := Value;
end;
{ TGroupUserResource }
function TGroupUserResource.GetGUID: string;
begin
Result := FGUID;
end;
function TGroupUserResource.GetResourceGUID: string;
begin
Result := FResourceGUID;
end;
function TGroupUserResource.GetRoleGUID: string;
begin
Result := FRoleGUID;
end;
procedure TGroupUserResource.setGUID(const Value: string);
begin
FGUID := Value;
end;
procedure TGroupUserResource.setResourceGUID(const Value: string);
begin
FResourceGUID := Value;
end;
procedure TGroupUserResource.setRoleGUID(const Value: string);
begin
FRoleGUID := Value;
end;
end.
|
unit SimpleDemo.View.Page.Cadastros;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.Controls.Presentation,
FMX.StdCtrls,
FMX.Layouts,
Router4D.Interfaces,
Router4D.Props, FMX.Edit, FMX.Objects;
type
TPageCadastros = class(TForm, iRouter4DComponent)
Layout1: TLayout;
Label1: TLabel;
Button1: TButton;
Edit1: TEdit;
Layout2: TLayout;
Layout3: TLayout;
Rectangle1: TRectangle;
Layout4: TLayout;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
procedure CreateMenuSuperior;
procedure CreateRouters;
{ Private declarations }
public
{ Public declarations }
function Render : TFMXObject;
procedure UnRender;
[Subscribe]
procedure Props ( aValue : TProps);
end;
var
PageCadastros: TPageCadastros;
implementation
uses
Router4D, SimpleDemo.View.Page.Cadastros.Sub, SimpleDemo.View.Page.Principal,
SimpleDemo.View.Components.Button01;
{$R *.fmx}
{ TPageCadastros }
procedure TPageCadastros.Button1Click(Sender: TObject);
begin
TRouter4D.Link.&To('Inicio');
end;
procedure TPageCadastros.FormCreate(Sender: TObject);
begin
CreateRouters;
CreateMenuSuperior;
end;
procedure TPageCadastros.Props(aValue: TProps);
begin
if (aValue.PropString <> '') and (aValue.Key = 'TelaCadastro') then
Label1.Text := aValue.PropString;
aValue.Free;
end;
procedure TPageCadastros.CreateRouters;
begin
TRouter4D.Switch.Router('Clientes', TPagePrincipal, 'cadastros');
TRouter4D.Switch.Router('Fornecedores', TSubCadastros, 'cadastros');
TRouter4D.Switch.Router('Produtos', TSubCadastros, 'cadastros');
end;
procedure TPageCadastros.CreateMenuSuperior;
begin
Layout4.AddObject(
TComponentButton01.Create(Self)
.createButton('Clientes')
);
Layout4.AddObject(
TComponentButton01.Create(Self)
.createButton('Produtos')
);
Layout4.AddObject(
TComponentButton01.Create(Self)
.createButton('Fornecedores')
);
end;
function TPageCadastros.Render: TFMXObject;
begin
Label1.Text := 'Cadastros';
Result := Layout1;
end;
procedure TPageCadastros.UnRender;
begin
//
end;
end.
|
{
TGMMarker component
ES: componente para mostrar ventanas de información en un mapa de Google Maps
mediante el componente TGMMap
EN: component to show balloons with information on Google Map map using the
component TGMMap
=========================================================================
MODO DE USO/HOW TO USE
ES: poner el componente en el formulario, linkarlo a un TGMMap y poner el
texto a mostrar en la propiedad "HTMLContent"
EN: put the component into a form, link to a TGMMap and put the text to show
into "HTMLContent" property
=========================================================================
History:
ver 1.0.0
ES:
cambio: las propiedades se cambian mediante el método ChangeProperties.
EN:
change: properties are changed by ChangeProperties method.
ver 0.1.9
ES:
nuevo: documentación
nuevo: se hace compatible con FireMonkey
EN:
new: documentation
new: now compatible with FireMonkey
ver 0.1.1
ES:
nuevo: añadida propiedad AutoOpen en la clase TInfoWindow
nuevo: añadido evento OnPositionChange
EN:
new: added property AutoOpen in TInfoWindow class
new: added event OnPositionChange
ver 0.1
ES- primera versión
EN- first version
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2012, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
The GMInfoWindow unit includes the classes needed to show InfoWindows on Google Map map using the component TGMMap.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La unit GMMarker contiene las clases necesarias para mostrar ventanas de información en un mapa de Google Maps mediante el componente TGMMap
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
unit GMInfoWindow;
{$I ..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
GMLinkedComponents, GMClasses;
type
TGMInfoWindow = class;
TInfoWindow = class;
{*------------------------------------------------------------------------------
Class management of InfoWindows.
More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#InfoWindow
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase para la gestión de ventanas de información.
Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#InfoWindow
-------------------------------------------------------------------------------}
TInfoWindow = class(TLinkedComponent)
private
{*------------------------------------------------------------------------------
The LatLng at which to display this InfoWindow.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
TLatLng donde se mostrará la ventana de información.
-------------------------------------------------------------------------------}
FPosition: TLatLng;
{*------------------------------------------------------------------------------
If true, when it is created, will be displayed automatically.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece a true, cuando se cree, se mostrará automáticamente.
-------------------------------------------------------------------------------}
FAutoOpen: Boolean;
function GetContent: string;
function GetDisableAutoPan: Boolean;
function GetMaxWidth: Integer;
function GetPixelOffset: TGMSize;
function GetCloseOtherBeforeOpen: Boolean;
procedure SetContent(const Value: string);
procedure SetDisableAutoPan(const Value: Boolean);
procedure SetMaxWidth(const Value: Integer);
procedure SetPixelOffset(const Value: TGMSize);
procedure SetCloseOtherBeforeOpen(const Value: Boolean);
procedure OnPositionChange(Sender: TObject);
protected
function GetDisplayName: string; override;
function ChangeProperties: Boolean; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure CenterMapTo; override;
{*------------------------------------------------------------------------------
Shows or hides the InfoWindows.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Muestra o oculta la ventana de información.
-------------------------------------------------------------------------------}
procedure OpenClose;
published
{*------------------------------------------------------------------------------
Content to display in the InfoWindow. This can be an HTML element, a plain-text string, or a string containing HTML. The InfoWindow will be sized according to the content. To set an explicit size for the content, set content to be a HTML element with that size.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Contenido a mostrar en la InfoWindow. Éste puede ser un elemento HTML, texto plano, o una cadena que contenga HTML. El InfoWindow se agrandará acorde al contenido. Para especificar unas determinadas medidas para el contenido, establece el contenido como un elemento HTML con esas medidas.
-------------------------------------------------------------------------------}
property HTMLContent: string read GetContent write SetContent;
{*------------------------------------------------------------------------------
Disable auto-pan on open.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Deshabilita el auto-pan en abierto.
-------------------------------------------------------------------------------}
property DisableAutoPan: Boolean read GetDisableAutoPan write SetDisableAutoPan;
{*------------------------------------------------------------------------------
Maximum width of the infowindow, regardless of content's width. 0 no Max.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Ancho máximo del InfoWindows, independientemente de la anchura del contenido. A 0 sin máximo.
-------------------------------------------------------------------------------}
property MaxWidth: Integer read GetMaxWidth write SetMaxWidth; // 0 = no MaxWidth
{*------------------------------------------------------------------------------
The offset, in pixels, of the tip of the info window from the point on the map at whose geographical coordinates the info window is anchored.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Offset, en píxeles, del extremo de la ventana de información desde el punto en las coordenadas geográficas en las que se ancla la ventana de información.
-------------------------------------------------------------------------------}
property PixelOffset: TGMSize read GetPixelOffset write SetPixelOffset; // (0,0) = no pixelOffset
{*------------------------------------------------------------------------------
Set to true to close others info windows opened.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Poner a true para cerrar otras ventanas de información abiertas.
-------------------------------------------------------------------------------}
property CloseOtherBeforeOpen: Boolean read GetCloseOtherBeforeOpen write SetCloseOtherBeforeOpen;
property Position: TLatLng read FPosition write FPosition;
property AutoOpen: Boolean read FAutoOpen write FAutoOpen;
end;
{*------------------------------------------------------------------------------
Class for InfoWindow collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase para la colección de InfoWindow.
-------------------------------------------------------------------------------}
TInfoWindows = class(TLinkedComponents)
private
function GetItems(I: Integer): TInfoWindow;
procedure SetItems(I: Integer; const Value: TInfoWindow);
protected
function GetOwner: TPersistent; override;
public
function Add: TInfoWindow;
function Insert(Index: Integer): TInfoWindow;
{*------------------------------------------------------------------------------
Lists the infowindow in the collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de infowindow en la colección.
-------------------------------------------------------------------------------}
property Items[I: Integer]: TInfoWindow read GetItems write SetItems; default;
end;
{*------------------------------------------------------------------------------
Class management of InfoWindow.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase para la gestión de InfoWindow.
-------------------------------------------------------------------------------}
TGMInfoWindow = class(TGMLinkedComponent)
private
{*------------------------------------------------------------------------------
This event is fired when InfoWindow's position changes.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando cambia la posición del InfoWindow.
-------------------------------------------------------------------------------}
FOnPositionChange: TLatLngIdxEvent;
protected
function GetAPIUrl: string; override;
function GetItems(I: Integer): TInfoWindow;
function GetCollectionItemClass: TLinkedComponentClass; override;
function GetCollectionClass: TLinkedComponentsClass; override;
public
{*------------------------------------------------------------------------------
Creates a new TInfoWindow instance and adds it to the Items array.
@param Lat InfoWindow latitude.
@param Lng InfoWindow longitude.
@param HTMLContent InfoWindow content in HTML format.
@return New InfoWindow.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Crea una nueva instancia de TInfoWindow y la añade en el array de Items.
@param Lat Latitud del InfoWindow.
@param Lng Longitud del InfoWindow.
@param HTMLContent Contenido del InfoWindow en formato HTML.
@return Nuevo InfoWindow.
-------------------------------------------------------------------------------}
function Add(Lat: Real = 0; Lng: Real = 0; HTMLContent: string = ''): TInfoWindow;
{*------------------------------------------------------------------------------
Array with the collection items.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con la colección de elementos.
-------------------------------------------------------------------------------}
property Items[I: Integer]: TInfoWindow read GetItems; default;
published
{*------------------------------------------------------------------------------
Collection items.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Colección de elementos.
-------------------------------------------------------------------------------}
property VisualObjects;
property OnPositionChange: TLatLngIdxEvent read FOnPositionChange write FOnPositionChange;
end;
implementation
uses
SysUtils,
GMFunctions;
{ TGMInfoWindow }
function TGMInfoWindow.Add(Lat, Lng: Real; HTMLContent: string): TInfoWindow;
begin
Result := TInfoWindow(inherited Add);
Result.Position.Lat := Lat;
Result.Position.Lng := Lng;
Result.HTMLContent := HTMLContent;
end;
function TGMInfoWindow.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference?hl=en#InfoWindow';
end;
function TGMInfoWindow.GetCollectionClass: TLinkedComponentsClass;
begin
Result := TInfoWindows;
end;
function TGMInfoWindow.GetCollectionItemClass: TLinkedComponentClass;
begin
Result := TInfoWindow;
end;
function TGMInfoWindow.GetItems(I: Integer): TInfoWindow;
begin
Result := TInfoWindow(inherited Items[i]);
end;
{ TInfoWindows }
function TInfoWindows.Add: TInfoWindow;
begin
Result := TInfoWindow(inherited Add);
end;
function TInfoWindows.GetItems(I: Integer): TInfoWindow;
begin
Result := TInfoWindow(inherited Items[I]);
end;
function TInfoWindows.GetOwner: TPersistent;
begin
Result := TGMInfoWindow(inherited GetOwner);
end;
function TInfoWindows.Insert(Index: Integer): TInfoWindow;
begin
Result := TInfoWindow(inherited Insert(Index));
end;
procedure TInfoWindows.SetItems(I: Integer; const Value: TInfoWindow);
begin
inherited SetItem(I, Value);
end;
{ TInfoWindow }
procedure TInfoWindow.Assign(Source: TPersistent);
begin
if Source is TInfoWindow then
begin
Position.Assign(TInfoWindow(Source).Position);
AutoOpen := TInfoWindow(Source).AutoOpen;
end
else
inherited Assign(Source);
end;
procedure TInfoWindow.CenterMapTo;
begin
inherited;
if Assigned(Collection) and (Collection is TInfoWindows) and
Assigned(TInfoWindows(Collection).FGMLinkedComponent) and
Assigned(TInfoWindows(Collection).FGMLinkedComponent.Map) then
TInfoWindows(Collection).FGMLinkedComponent.Map.SetCenter(Position.Lat, Position.Lng);
end;
function TInfoWindow.ChangeProperties: Boolean;
const
StrParams = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s';
var
Params: string;
begin
inherited;
Result := False;
if not Assigned(Collection) or not(Collection is TInfoWindows) or
not Assigned(TInfoWindows(Collection).FGMLinkedComponent) or
//not TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).AutoUpdate or
not Assigned(TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).Map) or
(csDesigning in TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).ComponentState) then
Exit;
Params := Format(StrParams, [
IntToStr(IdxList),
IntToStr(Index),
QuotedStr(InfoWindow.GetConvertedString),
LowerCase(TCustomTransform.GMBoolToStr(DisableAutoPan, True)),
IntToStr(MaxWidth),
IntToStr(PixelOffset.Height),
IntToStr(PixelOffset.Width),
Position.LatToStr(TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).GetMapPrecision),
Position.LngToStr(TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).GetMapPrecision),
LowerCase(TCustomTransform.GMBoolToStr(CloseOtherBeforeOpen, True))
]);
TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).ExecuteScript('MakeInfoWindow', Params);
if AutoOpen then OpenClose;
end;
constructor TInfoWindow.Create(Collection: TCollection);
begin
inherited;
FPosition := TLatLng.Create;
FPosition.OnChange := OnPositionChange;
FAutoOpen := True;
end;
destructor TInfoWindow.Destroy;
begin
if Assigned(FPosition) then FreeAndNil(FPosition);
inherited;
end;
function TInfoWindow.GetCloseOtherBeforeOpen: Boolean;
begin
Result := InfoWindow.CloseOtherBeforeOpen;
end;
function TInfoWindow.GetContent: string;
begin
Result := InfoWindow.HTMLContent;
end;
function TInfoWindow.GetDisableAutoPan: Boolean;
begin
Result := InfoWindow.DisableAutoPan;
end;
function TInfoWindow.GetDisplayName: string;
begin
if Length(InfoWindow.HTMLContent) > 0 then
begin
if Length(InfoWindow.HTMLContent) > 15 then
Result := Copy(InfoWindow.HTMLContent, 0, 12) + '...'
else
Result := InfoWindow.HTMLContent;
end
else
Result := inherited GetDisplayName;
end;
function TInfoWindow.GetMaxWidth: Integer;
begin
Result := InfoWindow.MaxWidth;
end;
function TInfoWindow.GetPixelOffset: TGMSize;
begin
Result := InfoWindow.PixelOffset;
end;
procedure TInfoWindow.OnPositionChange(Sender: TObject);
{const
StrParams = '%s,%s,%s,%s';
var
Params: string;}
begin
ChangeProperties;
if Assigned(TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).OnPositionChange) then
TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).OnPositionChange(
TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent),
FPosition,
Index,
Self);
{ if Assigned(Collection) and (Collection is TInfoWindows) and
Assigned(TInfoWindows(Collection).FGMLinkedComponent) and
TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).AutoUpdate and
Assigned(TInfoWindows(Collection).FGMLinkedComponent.Map) then
begin
Params := Format(StrParams, [
IntToStr(IdxList),
Position.LatToStr(TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).GetMapPrecision),
Position.LngToStr(TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).GetMapPrecision),
IntToStr(Index)
]);
TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).ExecuteScript('InfoWindowSetPosition', Params);
// ES/EN: evento/event
if Assigned(TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).OnPositionChange) then
TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).OnPositionChange(TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent), FPosition, Index, Self);
end;}
end;
procedure TInfoWindow.OpenClose;
const
StrParams = 'null,%s,%s';
var
Params: string;
begin
if Assigned(Collection) and (Collection is TInfoWindows) and
Assigned(TInfoWindows(Collection).FGMLinkedComponent) and
TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).AutoUpdate then
begin
Params := Format(StrParams, [
IntToStr(IdxList),
IntToStr(Index)]);
TGMInfoWindow(TInfoWindows(Collection).FGMLinkedComponent).ExecuteScript('InfoWindowOpenClose', Params);
end;
end;
procedure TInfoWindow.SetCloseOtherBeforeOpen(const Value: Boolean);
begin
InfoWindow.CloseOtherBeforeOpen := Value;
end;
procedure TInfoWindow.SetContent(const Value: string);
begin
InfoWindow.HTMLContent := Value;
end;
procedure TInfoWindow.SetDisableAutoPan(const Value: Boolean);
begin
InfoWindow.DisableAutoPan := Value;
end;
procedure TInfoWindow.SetMaxWidth(const Value: Integer);
begin
InfoWindow.MaxWidth := Value;
end;
procedure TInfoWindow.SetPixelOffset(const Value: TGMSize);
begin
InfoWindow.PixelOffset.Assign(Value);
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls,
//GLS
GLScene, GLVectorFileObjects, GLWin32Viewer,
GLCadencer, GLExplosionFx, GLFile3DS, GLCrossPlatform,
GLCoordinates, GLUtils, GLBaseClasses;
type
TForm1 = class(TForm)
Viewer: TGLSceneViewer;
GLScene1: TGLScene;
Camera1: TGLCamera;
GLLightSource1: TGLLightSource;
mesh: TGLFreeForm;
GLCadencer1: TGLCadencer;
Panel1: TPanel;
CheckOn: TCheckBox;
Button1: TButton;
StepBar: TProgressBar;
Label2: TLabel;
MaxStepsBar: TTrackBar;
Label1: TLabel;
Label3: TLabel;
SpeedBar: TTrackBar;
procedure FormCreate(Sender: TObject);
procedure CheckOnClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure ViewerMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure ViewerMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure SpeedBarChange(Sender: TObject);
procedure MaxStepsBarChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
vx, vy: integer;
Cache: TMeshObjectList;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
var
expl: TGLBExplosionFx;
begin
SetGLSceneMediaDir();
//load mesh
mesh.LoadFromFile('mushroom.3ds');
//cache information
Cache:= TMeshObjectList.Create;
Cache.Assign(mesh.MeshObjects);
//default settings
expl:= TGLBExplosionFX(mesh.Effects.Items[0]);
expl.MaxSteps:= 0;
expl.Speed:= 0.1;
end;
procedure TForm1.CheckOnClick(Sender: TObject);
begin
//turn on/off
TGLBExplosionFX(mesh.Effects.items[0]).Enabled:= checkon.checked;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
//reset simulation
TGLBExplosionFX(mesh.effects.items[0]).Reset;
checkon.checked:= false;
//restore the mesh
mesh.MeshObjects.Assign(Cache);
mesh.StructureChanged;
end;
procedure TForm1.ViewerMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if Shift <> [ssLeft] then exit;
camera1.MoveAroundTarget(Y - vy, X - vx);
vx:= X; vy:= Y;
end;
procedure TForm1.ViewerMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
vx:= X; vy:= Y;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
Viewer.Invalidate;
StepBar.Position:= TGLBExplosionFX(mesh.Effects.items[0]).Step;
end;
procedure TForm1.SpeedBarChange(Sender: TObject);
begin
TGLBExplosionFX(mesh.Effects.Items[0]).Speed:= SpeedBar.Position / 10;
end;
procedure TForm1.MaxStepsBarChange(Sender: TObject);
begin
TGLBExplosionFx(mesh.Effects.items[0]).MaxSteps:= MaxStepsBar.Position;
stepBar.Max:= MaxStepsBar.Position;
end;
end.
|
unit getrectinselection;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TmyPoints=record//Точка
X,Y:integer;
end;
TmyRect=record//прямоугольник - координаты прямоугольника
xl,yl,xr,yr:integer;
end;
TmyarrayRect=array of TmyRect;
function getRectFromPoints(var massPoint:array of TmyPoints;countPoint:integer;const deltaX:integer;Ymin,Ymax:integer):TmyarrayRect;//Получаем упорядоченный массив точек и поргешность, возвращаем массив прямоугольников
implementation
uses viewfoto;
type
TcoordX=record//координата X точки и признак выколотости
X:integer;
flag:boolean;
end;
TmyarrayXs=record//массив координат X точек и признак выколотости
X:array of TcoordX;
end;
TmyXY=record//Строка координата Y и левый и правый край
Xl,Xr,Y:integer;
end;
var
FminY,FmaxY,Fdeltax:integer;
FcountStroki:integer;
FXinY: array of TmyarrayXs;//Значения Х распределенные по Y - строкам
FStroki:array of TmyXY;
procedure MoveXinY(var massPoint:array of TmyPoints;countPoint:integer);//группируем точки по координате Y
var
i,ii,coordY,lastX:integer;
begin
setlength(FXinY,FmaxY-FminY+1);
for i:=0 to countpoint do//high(massPoint) do
begin
coordY:=massPoint[i].Y-FminY;
if high(FXinY[coordY].X)=-1 then
setlength(FXinY[coordY].X,1)
else
setlength(FXinY[coordY].X,high(FXinY[coordY].X)+2);
lastX:=high(FXinY[coordY].X);
FXinY[coordY].X[lastX].X:=massPoint[i].X;
for ii:=lastX downto 1 do
begin
if massPoint[i].X<FXinY[coordY].X[ii-1].X then
begin
FXinY[coordY].X[ii].X:=FXinY[coordY].X[ii-1].X;
FXinY[coordY].X[ii-1].X:=massPoint[i].X;
end else
break;
end;
end;
end;
procedure FillSelection(leftx_l,leftx_r,y_start:integer;indexright_old:integer=-1);//Заполняем область
var
iy,ixl,indexleft,indexleftold,indexrightold,indexright,leftxold,rightxold,leftxtmp,leftxnew,rightxnew:integer;
first,firstline,endfill:boolean;
startFcountStroki:integer;
function checknewstring:byte;{проверяем надо ли искать первую точку строки или она уже найдена
}
begin
if (leftxtmp=-1) then //начало поиска новой строки - значит ищем первую точку
begin
if FXinY[iy].x[ixl].flag then
begin//если очередная точка "выколота"(уже использовалась), то переходим к следующей точке
result:=2;
exit;
end;
if ((rightxold-1)<=FXinY[iy].x[ixl].X){нет дырки - есть разрыв заполнения
т.е.если новая точка "слишком" справа}
then
begin
leftxtmp:=-1;
result:=1;//значит прекращаем заполнение - все
exit;
end;
indexleft:=ixl;//запоминаем индекс левого края левой границы
//кандидат на левый край левой границы
leftxtmp:=FXinY[iy].x[ixl].X;
indexright:=ixl;//запоминаем индекс правого края левой границы
result:=2;
end else result:=255;
end;
function checknewrightedgeleftborder:byte;
begin
if ((rightxold-1)<=FXinY[iy].x[ixl].X)//нет дырки - есть разрыв заполнения
then //если новая точка "слишком" справа
begin
leftxtmp:=-1;//поиск левой границы заново
if leftxnew=-1 then result:=0 else result:=1;//если первоначальное заполнение, то прекращаем заполнение, иначе переходим к первоначальному
exit;
end;
if FXinY[iy].x[ixl].flag then //если очередная(соседняя) точка "выколота", то переходим к следующей точке
begin
leftxtmp:=-1;//поиск левой границы заново
result:=2;//переход к следующей точке
exit;
end;
//кандидат на правый край левой границы
leftxtmp:=FXinY[iy].x[ixl].X;//Устанавливаем новую левую границу
indexright:=ixl;//запоминаем индекс правого края левой границы
result:=2;
end;
function checkrightborder:boolean;
begin
result:=true;
if firstline and FXinY[iy].x[ixl].flag then //если очередная точка "выколота", то переходим к следующей точке
begin
leftxtmp:=-1;
result:=false;
exit;
end;
if ((leftxold+1)>=FXinY[iy].x[ixl].X)//нет дырки - есть разрыв заполнения
then //если новая точка "слишком" слева
begin
leftxtmp:=-1;
dec(ixl);
result:=false;
end;
end;
procedure correctpoint;
begin
if (FXinY[iy].X[indexright].X<(FXinY[iy-1].X[indexleftold].X-1))and(indexleftold>-1) then//если левый край линии сильно левее предыдущей границы
FXinY[iy-1].X[indexleftold].flag:=false;//отменяем выкалывание, иначе будет пропуск строки
if (FXinY[iy].x[ixl].X>(FXinY[iy-1].X[indexrightold].X+1))and(indexrightold>-1) then//если правый край линии сильно правее предыдущей границы
FXinY[iy-1].X[indexrightold].flag:=false;//отменяем выкалывание, иначе будет пропуск строки
end;
function checksharppeakright:boolean;
begin
result:=//(FXinY[iy].x[ixl].X<(FXinY[iy-1].X[indexrightold].X-1))and(indexrightold>-1)//если правый край линии сильно левее предыдущей границы
(FXinY[iy].x[ixl].X<(rightxold-1))and(indexrightold>-1)//если правый край линии сильно левее предыдущей границы
and(high(FXinY[iy].x)>ixl)and//и это не последняя точка
((FXinY[iy].x[ixl+1].X-1)<>FXinY[iy].x[ixl].X)//и следующая точка не соседняя, т.е. острая вершина
end;
begin
leftxold:=leftx_l;
rightxold:=leftx_r;
leftxtmp:=-1;
leftxnew:=-1;
rightxnew:=-1;
first:=false;
endfill:=false;
firstline:=true;
indexleftold:=-1;
indexrightold:=indexright_old;
startFcountStroki:=FcountStroki;
for iy:=y_start to high(FXinY) do
begin
for ixl:=0 to high(FXinY[iy].x) do
begin
case checknewstring of //Если ищем первую точку, то
0,1:
if not first then
begin
endfill:=true;
break;
end else
break;//прекращаем заполнение - очередная левая точка не найдена
//1:break;//пробуем продолжить заполнение со следующей строки - если было вторичное заполнение ???
2:continue;//левая точка найдена или выколота переходим к следующей
end;
//если ищем вторую точку
if (FXinY[iy].x[ixl].X-1)=(FXinY[iy].x[ixl-1].X) then//если СОСЕДНЯЯ точка
begin
case checknewrightedgeleftborder of ////ищем правый край левой границы
0,1:
begin//прекращаем заполнение
if indexrightold>-1 then
begin
endfill:=true;
break;
end else
exit;
end;
//1:break;//переходим к первоначальному заполнению
2:continue;//левая точка найдена или выколота переходим к следующей
end;
end else //если НЕ соседняя точка
begin
if not checkrightborder then //ищем правый край линии
continue;
//получаем отрезок
if first then //Если в данной строке это уже не первая линия, то начинаем заполнение в новой процедуре
begin
if (leftxtmp>=(rightxold-1))then //если новая левая граница намного правее предыдущей правой, т.е. нет дырки есть разрыв заполнения
break;
FillSelection(leftxtmp,FXinY[iy].x[ixl].X,iy,indexrightold);
leftxtmp:=-1;
continue;
end;
first:=true;//признак того, что в этой строке уже нарисован отрезок
correctpoint;
FXinY[iy].X[indexright].flag:=true;//выкалываем левую границу
if checksharppeakright then //Если справа оказалась острая вершина
begin
//FillSelection(FXinY[iy].x[ixl].X,FXinY[iy].x[ixl+1].X,iy);
FillSelection(FXinY[iy].x[ixl].X,rightxold,iy,indexrightold);
end
else
FXinY[iy].x[ixl].flag:=true;//выкалываем правую границу
if FcountStroki>high(FStroki) then setlength(Fstroki,(high(Fstroki)+1)+2*(high(FXinY)+1));//Если массив не вмещает точки, то увеличиваем размер массива
FStroki[FcountStroki].Y:=iy+FminY;
FStroki[FcountStroki].Xl:=leftxtmp+1;
FStroki[FcountStroki].Xr:=FXinY[iy].x[ixl].X-1;
inc(FcountStroki);
leftxnew:=leftxtmp;
rightxnew:=FXinY[iy].x[ixl].X;
indexleftold:=indexleft;
indexrightold:=ixl;
leftxtmp:=-1;
if firstline then
firstline:=false;
end;
end;
if endfill then
begin
break;
end;
if leftxnew=-1 then break //Если отрезок не найден, то прекращаем
else
begin
leftxold:=leftxnew;
rightxold:=rightxnew;
leftxnew:=-1;
rightxnew:=-1;
first:=false;
end;
end;
if not endfill then
begin
FcountStroki:=startFcountStroki;
end;
end;
procedure SearchStartSelect;//поиск начальных позиций для закрашивания
var
ix,iy,Min,max:integer;
procedure SearchHole(min,max,y:integer);//Поиск двух не соседних точек
var
iix,leftl,leftr:integer;
begin //Проверяем наличие двух не соседних точек
leftl:=-1;
leftr:=-1;
for iix:=0 to high(FXiny[y].X) do
begin
if FXinY[y].X[iix].flag then continue;
if FXinY[y].X[iix].X>(max+1) then break;
if leftl=-1 then
begin
leftl:=FXinY[y].X[iix].X;//Кандидат на левую границу
leftr:=FXinY[y].X[iix].X;//Кандидат на правую границу
continue;
end;
if (leftr+1)=FXinY[y].X[iix].X then//сосед
begin
leftr:=FXinY[y].X[iix].X;//новая правая граница
continue;
end else
begin
if ((leftr+1)>=min)and((leftr+1)<=max)and((FXinY[y].X[iix].X-leftr)>1) then
begin
FillSelection(leftl,FXinY[y].X[iix].X,y);
leftl:=-1;
leftr:=-1;
continue;
end else
begin
leftl:=FXinY[y].X[iix].X;//Кандидат на левую границу
leftr:=FXinY[y].X[iix].X;//Кандидат на правую границу
end;
end;
end;
end;
begin //Ищем одну(одинокую) точку или последовательность точек не выколотую
min:=-1;
setlength(FStroki, (high(FXinY)+1)*2);
for iy:=0 to high(FXinY) do
begin
for ix:=0 to high(FXinY[iy].X) do
begin
if (min=-1) and (not FXinY[iy].X[ix].flag) then
begin
min:=ix;
max:=min;
continue;
end;
if ((FXinY[iy].X[ix].X-1)=FXinY[iy].X[max].X) and (not FXinY[iy].X[ix].flag) then//соседняя точка и не выколотая
begin
max:=ix;
continue;
end
else
begin
SearchHole(FXinY[iy].X[min].X,FXinY[iy].X[max].X,iy+1);
min:=ix;
max:=min;
end;
end;
if (min>-1)and(max>-1)and(iy<high(FXinY)) then
SearchHole(FXinY[iy].X[min].X,FXinY[iy].X[max].X,iy+1);
min:=-1;
max:=-1;
end;
setlength(FStroki,FcountStroki);
dec(FcountStroki);
end;
function CreateRect(var FRects:array of TmyRect):integer;
var
pxmin,pxmax,pymin,pymax:Pinteger;
procedure saveRect(xl,yl,xr,yr,numberRect:integer);
{var
tmp:integer; }
begin
FRects[numberRect].xl:=xl;
FRects[numberRect].yl:=yl;
FRects[numberRect].xr:=xr;
FRects[numberRect].yr:=yr;
//tmp:=FRects[high(FRects)].xl;
if xl<pxmin^ then
pxmin^:=xl;
//tmp:=FRects[high(FRects)].xl;
if xr>pxmax^ then
pxmax^:=xr;
if yl<pymin^ then
pymin^:=yl;
if yr>pymax^ then
pymax^:=yr;
end;
var
istr:integer;
xl,yl,xr,yr,curRect,sumxl,sumxr,countStrok:integer;
procedure InitNewRect();
begin
xl:=FStroki[istr].Xl;
sumxl:=xl;
yl:=FStroki[istr].Y;
xr:=FStroki[istr].Xr;
sumxr:=xr;
yr:=FStroki[istr].Y;
countStrok:=1;
end;
{var
tmp:integer;}
begin
curRect:=0;
xl:=-1;
yl:=-1;
xr:=-1;
yr:=-1;
sumxl:=0;
sumxr:=0;
countStrok:=0;
//Setlength(FRects,high(FStroki)+1+4);//Последние 4 числа это minX,maxX,minY,maxY
pxmin:=@FRects[high(FRects)].xl;
pxmax:=@FRects[high(FRects)].yl;
pymin:=@FRects[high(FRects)].xr;
pymax:=@FRects[high(FRects)].yr;
//tmp:=FRects[high(FRects)].xl;
pxmin^:=maxLongint;
pxmax^:=-maxLongint;
pymin^:=maxLongint;
pymax^:=-maxLongint;
//tmp:=FRects[high(FRects)].xl;
viewfoto.frmviewfoto.ShapeFoto.Canvas.Pen.Color:=clblue;
for istr:=0 to high(FStroki) do
begin
viewfoto.frmviewfoto.ShapeFoto.Canvas.Line(FStroki[istr].Xl,FStroki[istr].Y,FStroki[istr].Xr,FStroki[istr].Y);
continue;
if xl=-1 then//новый прямоугольник в самом начале
begin
InitNewRect;
continue;
end;
if (abs(FStroki[istr].Xl-xl)<=Fdeltax)and(abs(FStroki[istr].Xr-xr)<=Fdeltax)and//разница между краями не больше допустимого(Fdeltax)
(FStroki[istr].Xr>=(FStroki[istr-1].Xl+1))//не новое заполнение
then
begin
sumxl:=sumxl+FStroki[istr].Xl;
sumxr:=sumxr+FStroki[istr].Xr;
yr:=FStroki[istr].Y;
inc(countStrok);
end else
begin
//сохраним прямоугольник
saveRect(round(sumxl/countStrok),yl,round(sumxr/countStrok),yr,currect);
inc(currect);
//новый прямоугольник
InitNewRect;
end;
end;
if xl>-1 then
begin
//сохраним прямоугольник
saveRect(round(sumxl/countStrok),yl,round(sumxr/countStrok),yr,currect);
end;
//Setlength(FRects,currect+1);
result:=currect+1;//возвращаем количество прямоугольников
//SortRectInSelection(curSelection);
end;
procedure SortRectInSelection(var FRects:array of TmyRect);
var
i,ii,best_i:integer;
best_value:integer;
begin
//сортируем по Y левый верхний угол по возрастанию
for i:=0 to high(FRects)-2 do
begin
best_value:=FRects[i].yl;
best_i:=i;
for ii:=i+1 to high(FRects)-1 do
if FRects[ii].yl<best_value then
begin
best_value:=FRects[ii].yl;
best_i:=ii;
end;
FRects[best_i].yl:=FRects[i].yl;
FRects[i].yl:=best_value;
end;
end;
function getRectFromPoints(var massPoint: array of TmyPoints;
countPoint: integer; const deltaX: integer; Ymin, Ymax: integer
): TmyarrayRect;
var
countrect:integer;
x_min,x_max,y_min,y_max:integer;
begin
FminY:=Ymin;
FmaxY:=Ymax;
Fdeltax:=deltaX;
MoveXinY(massPoint,countPoint);
SearchStartSelect;
Setlength(result,high(FStroki)+1+1);//Последние 4 числа это minX,maxX,minY,maxY
countrect:=CreateRect(result);
x_min:=result[high(result)].xl;
x_max:=result[high(result)].yl;
y_min:=result[high(result)].xr;
y_max:=result[high(result)].yr;
Setlength(result,countrect+1);//Уменьшаем размер до необходимого.Последние 4 числа это minX,maxX,minY,maxY
result[high(result)].xl:=x_min;
result[high(result)].yl:=x_max;
result[high(result)].xr:=y_min;
result[high(result)].yr:=y_max;
SortRectInSelection(result);//Сортируем по координате Y ???
end;
end.
|
unit ZLibH;
{we: ZLIB (functions), ZLIBH(types/consts), GZIO(gz functions)
should be the only units USED by applications of zlib}
(************************************************************************
zlibh -- types/consts of the 'zlib' general purpose compression library
version 1.1.4, March 11th, 2002
Copyright (C) 1995-2002 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
The data format used by the zlib library is described by RFCs (Request for
Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
(zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
Parts of Pascal translation
Copyright (C) 1998 by Jacques Nomssi Nzali
------------------------------------------------------------------------
Modification/Pascal translation by W.Ehrhardt:
Aug 2000
- ZLIB 113 changes
Feb 2002
- Source code reformating/reordering
- make code work under BP7/DPMI&Win
Mar 2002
- ZLIB 114 changes
Apr 2004
- procedure z_assign(var f: file; p: PChar): workaround for Delphi6/7 bug
Mar 2005
- Code cleanup for WWW upload
May 2005
- Assert moved from zutil (ease of use if no system.assert)
Jul 2008
- update uInt/uLong for FPC2
Jul 2009
- D12 fixes
Sep 2015
- FPC 3
------------------------------------------------------------------------
*************************************************************************)
interface
{$x+}
{$i zconf.inc}
{type declarations}
type
Bytef = byte;
charf = byte;
str255 = string[255];
{$ifdef unicode}
Char8 = AnsiChar;
PChar8 = PAnsiChar;
{$else}
Char8 = Char;
PChar8 = PChar;
{$endif}
{$ifdef VER70}
int = integer;
{$else}
int = longint;
{$endif}
intf = int;
{$ifdef MSDOS}
uInt = word;
{$else}
{$ifdef FPC}
{$ifndef VER1} {Sep 2015}
uInt = cardinal;
{$else}
uInt = longint;
{$endif}
{$else}
{$ifdef VER70}
uInt = word; {*we 0202: BP7/Win}
{$else}
uInt = cardinal; {16 bits or more}
{$endif}
{$endif}
{$endif}
uIntf = uInt;
Long = longint;
{$ifdef FPC}
{$ifdef VER1} {Sep 2015}
uLong = longint;
{$else}
uLong = cardinal;
{$endif}
{$else}
{$ifdef D4Plus}
uLong = Cardinal;
{$else}
{$ifdef ver120}
uLong = Cardinal;
{$else}
uLong = longint; {32 bits or more}
{$endif}
{$endif}
{$endif}
uLongf = uLong;
voidp = pointer;
voidpf = voidp;
pBytef = ^Bytef;
puIntf = ^uIntf;
puLong = ^uLongf;
{$ifdef FPC} {Sep 2015}
{$ifdef VER1}
ptr2int = uInt;
{$else}
ptr2int = PtrUInt;
{$endif}
{$else}
ptr2int = uInt;
{$endif}
{a pointer to integer casting is used to do pointer arithmetic.
ptr2int must be an integer type and sizeof(ptr2int) must be less
than sizeof(pointer) - Nomssi}
{The memory requirements for deflate are (in bytes):
1 shl (windowBits+2) + 1 shl (memLevel+9)
that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
plus a few kilobytes for small objects. For example, if you want to reduce
the default memory requirements from 256K to 128K, compile with
DMAX_WBITS=14
DMAX_MEM_LEVEL=7
Of course this will generally degrade compression (there's no free lunch).
The memory requirements for inflate are (in bytes)
1 shl windowBits
that is, 32K for windowBits=15 (default value) plus a few kilobytes
for small objects.}
{Compile with -DMAXSEG_64K if the alloc function cannot allocate more
than 64k bytes at a time (needed on systems with 16-bit int).}
const
{$ifdef MAXSEG_64K}
MaxMemBlock = $FFFF;
{$else}
MaxMemBlock = MaxInt;
{$endif}
{Maximum value for memLevel in deflateInit2}
{$ifdef MAXSEG_64K}
{$ifdef VER70}
MAX_MEM_LEVEL = 7;
DEF_MEM_LEVEL = MAX_MEM_LEVEL; {default memLevel}
{$else}
MAX_MEM_LEVEL = 8;
DEF_MEM_LEVEL = MAX_MEM_LEVEL; {default memLevel}
{$endif}
{$else}
MAX_MEM_LEVEL = 9;
DEF_MEM_LEVEL = 8; {if MAX_MEM_LEVEL > 8}
{$endif}
{Maximum value for windowBits in deflateInit2 and inflateInit2}
{$ifdef VER70}
MAX_WBITS = 15; {32K LZ77 window} {*we W0800}
{$else}
MAX_WBITS = 15; {32K LZ77 window}
{$endif}
{default windowBits for decompression. MAX_WBITS is for compression only}
{$ifdef VER70}
DEF_WBITS = 15; {*we W0800, with MAX_BITS = 14 some files could not be}
{decompressed with VER70, cf. Memory Footprint in zlib_tech.html}
{$else}
DEF_WBITS = MAX_WBITS;
{$endif}
type
uch = byte;
uchf = uch;
ush = word;
ushf = ush;
ulg = longint;
unsigned = uInt;
pcharf = ^charf;
pushf = ^ushf;
type
zByteArray = array[0..(MaxMemBlock div sizeof(Bytef))-1] of Bytef;
pzByteArray = ^zByteArray;
type
zIntfArray = array[0..(MaxMemBlock div sizeof(Intf))-1] of Intf;
pzIntfArray = ^zIntfArray;
type
alloc_func = function(opaque: voidpf; items: uInt; size: uInt): voidpf;
free_func = procedure(opaque: voidpf; address: voidpf);
type
z_streamp= ^z_stream;
z_stream = record
next_in : pBytef; {next input byte}
avail_in : uInt; {number of bytes available at next_in}
total_in : uLong; {total nb of input bytes read so far}
next_out : pBytef; {next output byte should be put there}
avail_out: uInt; {remaining free space at next_out}
total_out: uLong; {total nb of bytes output so far}
msg : string[255]; {last error message, '' if no error}
state : pointer; {internal state: not visible by applications}
zalloc : alloc_func; {used to allocate the internal state}
zfree : free_func; {used to free the internal state}
opaque : voidpf; {private data object passed to zalloc and zfree}
data_type: int; {best guess about the data type: ascii or binary}
adler : uLong; {adler32 value of the uncompressed data}
reserved : uLong; {reserved for future use}
end;
{ The application must update next_in and avail_in when avail_in has
dropped to zero. It must update next_out and avail_out when avail_out
has dropped to zero. The application must initialize zalloc, zfree and
opaque before calling the init function. All other fields are set by the
compression library and must not be updated by the application.
The opaque value provided by the application will be passed as the first
parameter for calls of zalloc and zfree. This can be useful for custom
memory management. The compression library attaches no meaning to the
opaque value.
zalloc must return Z_NULL if there is not enough memory for the object.
On 16-bit systems, the functions zalloc and zfree must be able to allocate
exactly 65536 bytes, but will not be required to allocate more than this
if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
pointers returned by zalloc for objects of exactly 65536 bytes *must*
have their offset normalized to zero. The default allocation function
provided by this library ensures this (see zutil.c). To reduce memory
requirements and avoid any allocation of 64K objects, at the expense of
compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
The fields total_in and total_out can be used for statistics or
progress reports. After compression, total_in holds the total size of
the uncompressed data and may be saved for use in the decompressor
(particularly if the decompressor wants to decompress everything in
a single step).}
const
{Allowed flush values; see deflate() below for details}
Z_NO_FLUSH = 0;
Z_PARTIAL_FLUSH = 1;
Z_SYNC_FLUSH = 2;
Z_FULL_FLUSH = 3;
Z_FINISH = 4;
{Return codes for the compression/decompression functions. Negative
values are errors, positive values are used for special but normal events.}
Z_OK = 0;
Z_STREAM_END = 1;
Z_NEED_DICT = 2;
Z_ERRNO = (-1);
Z_STREAM_ERROR = (-2);
Z_DATA_ERROR = (-3);
Z_MEM_ERROR = (-4);
Z_BUF_ERROR = (-5);
Z_VERSION_ERROR = (-6);
{compression levels}
Z_NO_COMPRESSION = 0;
Z_BEST_SPEED = 1;
Z_BEST_COMPRESSION = 9;
Z_DEFAULT_COMPRESSION = (-1);
{compression strategy; see deflateInit2() below for details}
Z_FILTERED = 1;
Z_HUFFMAN_ONLY = 2;
Z_DEFAULT_STRATEGY = 0;
{Possible values of the data_type field}
Z_BINARY = 0;
Z_ASCII = 1;
Z_UNKNOWN = 2;
{The deflate compression method (the only one supported in this version)}
Z_DEFLATED = 8;
{for initializing zalloc, zfree, opaque}
Z_NULL = nil;
{common constants}
const
{The three kinds of block type}
STORED_BLOCK = 0;
STATIC_TREES = 1;
DYN_TREES = 2;
const
{The minimum and maximum match lengths}
MIN_MATCH = 3;
{$ifdef MAX_MATCH_IS_258}
MAX_MATCH = 258;
{$else}
MAX_MATCH = ??; {deliberate syntax error}
{$endif}
const
{preset dictionary flag in zlib header}
PRESET_DICT = $20;
const
ZLIB_VERSION: string[10] = '1.1.4';
inflate_copyright: string[60] = ' inflate 1.1.4 Copyright 1995-2002 Mark Adler';
{If you use the zlib library in a product, an acknowledgment is welcome
in the documentation of your product. If for some reason you cannot
include such an acknowledgment, I would appreciate that you keep this
copyright string in the executable of your product.}
const
z_errbase = Z_NEED_DICT;
z_errmsg : array[0..9] of string[21] = {indexed by 2-zlib_error}
('need dictionary', {Z_NEED_DICT 2 }
'stream end', {Z_STREAM_END 1 }
'', {Z_OK 0 }
'file error', {Z_ERRNO (-1)}
'stream error', {Z_STREAM_ERROR (-2)}
'data error', {Z_DATA_ERROR (-3)}
'insufficient memory', {Z_MEM_ERROR (-4)}
'buffer error', {Z_BUF_ERROR (-5)}
'incompatible version',{Z_VERSION_ERROR (-6)}
'');
const
z_verbose : int = 1;
procedure z_assign(var f: file; p: PChar8);
{-workaround for Delphi 6/7 bug}
{$ifdef debug}
{$ifndef HaveAssert}
procedure Assert(cond: boolean; const msg: string);
{-Assert for Pascal without system.assert}
{$endif}
{$endif}
implementation
{$ifdef debug}
{$ifndef HaveAssert}
{---------------------------------------------------------------------------}
procedure Assert(cond: boolean; const msg: string);
{-Assert for Pascal without system.assert}
begin
if not cond then begin
writeln('zlib assertion failed: ', msg);
halt(1);
end;
end;
{$endif}
{$endif}
{$ifdef CONDITIONALEXPRESSIONS} {D6+}
{---------------------------------------------------------------------------}
procedure z_assign(var f: file; p: PChar8);
{-workaround for Delphi 6/7/? bug}
begin
{$ifdef UNICODE} {D12+}
assignfile(f,string(p));
{$else}
assignfile(f,ansistring(p));
{$endif}
end;
{$else}
{---------------------------------------------------------------------------}
procedure z_assign(var f: file; p: PChar8);
begin
system.assign(f,p);
end;
{$endif}
begin
if length(ZLIB_VERSION)+length(inflate_copyright)=0 then ; {only for referencing}
end.
|
namespace Importer;
interface
uses
System.Collections.Generic,
System.IO,
System.Text,
System.Linq,
System.Xml.Linq;
type
OutputType = public enum (Nougat, ObjC);
ImporterSettings = public class
private
fLibraries : List<String> := new List<String>;
fTypes: List<ImportType> := new List<ImportType>;
protected
public
property Libraries: List<String> read fLibraries;
property Types: List<ImportType> read fTypes;
property &Namespace: String;
property OutputType: OutputType;
property OutputFilename: String;
property Prefix: String;
method LoadFromXml(aFN: String);
method LoadFromXml(aDoc: XDocument);
end;
ImportType = public class
private
public
property Name: String;
property TargetName: String;
end;
implementation
method ImporterSettings.LoadFromXml(aFN: String);
begin
LoadFromXml(XDocument.Load(aFN));
end;
method ImporterSettings.LoadFromXml(aDoc: XDocument);
begin
if aDoc.Root:Name <> 'import' then raise new Exception('Root node should be "import"');
&Namespace := aDoc.Root.Element('namespace'):Value;
if aDoc.Root.Element('outputtype'):Value:ToLowerInvariant = 'objc' then
OutputType := OutputType.ObjC;
OutputFilename := aDoc.Root.Element('outputfilename'):Value:Replace("\", Path.DirectorySeparatorChar);
Prefix := aDoc.Root.Element('prefix'):Value;
case OutputType of
OutputType.ObjC: if OutputFilename = nil then OutputFilename := 'default.h';
else
if OutputFilename = nil then OutputFilename := 'default.pas';
end;
var lLibs := aDoc.Root.Elements('libraries');
if lLibs = nil then raise new Exception('"Libraries" node missing');
Libraries.AddRange(lLibs.Elements('library').Select(a->a.Value.Replace("\", System.IO.Path.DirectorySeparatorChar)));
var lTypes := aDoc.Root.Elements('types');
if lTypes = nil then raise new Exception('"Types" node missing');
for each el in lTypes.Elements('type') do begin
Types.Add(new ImportType(Name := el.Element('name'):Value, TargetName := el.Element('targetname'):Value));
end;
end;
end.
|
unit FIToolkit.Logger.Intf;
interface
uses
System.SysUtils, System.Rtti, System.TypInfo,
FIToolkit.Logger.Types;
type
IAbstractLogger = interface //FI:W523
{ Property accessors }
function GetEnabled : Boolean;
{ Logging: structure }
procedure EnterSection(const Msg : String = String.Empty); overload;
procedure EnterSection(const Vals : array of const); overload;
procedure EnterSectionFmt(const Msg : String; const Args : array of const);
procedure EnterSectionVal(const Vals : array of TValue);
procedure LeaveSection(const Msg : String = String.Empty); overload;
procedure LeaveSection(const Vals : array of const); overload;
procedure LeaveSectionFmt(const Msg : String; const Args : array of const);
procedure LeaveSectionVal(const Vals : array of TValue);
procedure EnterMethod(AClass : TClass; MethodAddress : Pointer; const Params : array of TValue); overload;
procedure EnterMethod(ARecord : PTypeInfo; MethodAddress : Pointer; const Params : array of TValue); overload;
procedure LeaveMethod(AClass : TClass; MethodAddress : Pointer); overload;
procedure LeaveMethod(AClass : TClass; MethodAddress : Pointer; AResult : TValue); overload;
procedure LeaveMethod(ARecord : PTypeInfo; MethodAddress : Pointer); overload;
procedure LeaveMethod(ARecord : PTypeInfo; MethodAddress : Pointer; AResult : TValue); overload;
{ Logging: messages }
procedure Log(Severity : TLogMsgSeverity; const Msg : String); overload;
procedure Log(Severity : TLogMsgSeverity; const Vals : array of const); overload;
procedure LogFmt(Severity : TLogMsgSeverity; const Msg : String; const Args : array of const);
procedure LogVal(Severity : TLogMsgSeverity; const Vals : array of TValue);
procedure Debug(const Msg : String); overload;
procedure Debug(const Vals : array of const); overload;
procedure DebugFmt(const Msg : String; const Args : array of const);
procedure DebugVal(const Vals : array of TValue);
procedure Info(const Msg : String); overload;
procedure Info(const Vals : array of const); overload;
procedure InfoFmt(const Msg : String; const Args : array of const);
procedure InfoVal(const Vals : array of TValue);
procedure Warning(const Msg : String); overload;
procedure Warning(const Vals : array of const); overload;
procedure WarningFmt(const Msg : String; const Args : array of const);
procedure WarningVal(const Vals : array of TValue);
procedure Error(const Msg : String); overload;
procedure Error(const Vals : array of const); overload;
procedure ErrorFmt(const Msg : String; const Args : array of const);
procedure ErrorVal(const Vals : array of TValue);
procedure Fatal(const Msg : String); overload;
procedure Fatal(const Vals : array of const); overload;
procedure FatalFmt(const Msg : String; const Args : array of const);
procedure FatalVal(const Vals : array of TValue);
{ Properties }
property Enabled : Boolean read GetEnabled;
end;
ILogOutput = interface
['{D66F4536-61D8-481D-9055-3F063F23E0B5}']
{ Property accessors }
function GetSeverityThreshold : TLogMsgSeverity;
procedure SetSeverityThreshold(Value : TLogMsgSeverity);
{ Methods }
procedure BeginSection(Instant : TLogTimestamp; const Msg : String);
procedure EndSection(Instant : TLogTimestamp; const Msg : String);
procedure WriteMessage(Instant : TLogTimestamp; Severity : TLogMsgSeverity; const Msg : String);
{ Properties }
property SeverityThreshold : TLogMsgSeverity read GetSeverityThreshold write SetSeverityThreshold;
end;
ILogger = interface (IAbstractLogger)
['{0E36214F-FFD4-4715-9631-0B6D7F12006A}']
{ Property accessors }
function GetAllowedItems : TLogItems;
function GetSeverityThreshold : TLogMsgSeverity;
procedure SetAllowedItems(Value : TLogItems);
procedure SetSeverityThreshold(Value : TLogMsgSeverity);
{ Logging: output }
function AddOutput(const LogOutput : ILogOutput) : ILogOutput;
{ Properties }
property AllowedItems : TLogItems read GetAllowedItems write SetAllowedItems;
property SeverityThreshold : TLogMsgSeverity read GetSeverityThreshold write SetSeverityThreshold;
end;
IMetaLogger = interface (IAbstractLogger)
['{BF283586-7040-4468-ADB2-FD2C62EFD996}']
{ Methods }
function AddLogger(const Logger : ILogger) : ILogger;
end;
implementation
end.
|
unit EGASave;
(*
------------------------------------------------------------------
This unit provides all of the routines necessary for saving and
restoring EGA (640x350) 16 color graphics screens to and from
RAM and/or a disk files.
Author : John Sieraski (Borland technical support)
Last update: 11/17/88
Ware-ness : Released to the public domain by the author
------------------------------------------------------------------
*)
interface
const
BitMapSize = 28000; { Size in bytes of each EGA bit plane }
MaxBitMaps = 4; { Number of Bit planes in video mode $10 }
OK = 0; { Signals that everything is OK }
type
BitMapBuffer = array[1..BitMapSize] of byte; { An EGA bit plane }
EGABuffer = array[1..MaxBitMaps] of ^BitMapBuffer; { A Full EGA screen }
Str12 = string[12]; { For DOS filenames }
(*
procedure SaveEGAScreen(Buffer : EGABuffer);
{ Saves an EGA (640x350) 16 color graphics screen into Buffer }
procedure RestoreEGAScreen(Buffer : EGABuffer);
{ Restores an EGA (640x350) 16 color graphics screen image from Buffer }
function WriteEGAScreen(FileName : Str12) : integer;
{ Saves an EGA (640x350) 16 color graphics screen into a file }
function ReadEGAScreen(FileName : Str12) : integer;
{ Restores an EGA (640x350) 16 color graphics screen from a file }
function AllocateBuffer(var Buffer : EGABuffer) : boolean;
{ Allocates a "Buffer" variable on the Heap using GetMem }
procedure DisposeBuffer(var Buffer : EGABuffer);
{ Frees a "Buffer" variable from the Heap using FreeMem }
*)
implementation
const
EGABase : pointer = Ptr($A000, $0000); { Base of EGA graphics memory }
AddrReg = $3CE; { Port address of EGA graphics 1 & 2 address register }
SetResetReg = $3CF; { Port address of EGA Set/Reset register }
ReadMapReg = $04; { Index of EGA Read Map select register }
SeqAddrReg = $3C4; { Port address of EGA sequencer address register }
ResetReg = $3C5; { Port address of EGA sequencer reset register }
MapMaskReg = $02; { Index of EGA sequencer Map Mask register }
procedure EnableMapRead(Map : byte);
{ Enables reading from one of the EGA's Bit planes 1..4 }
begin
Port[AddrReg] := ReadMapReg;
Port[SetResetReg] := Pred(Map)
end;
procedure SaveEGAScreen(Buffer : EGABuffer);
var
BitMap : integer;
begin
for BitMap := 1 to MaxBitMaps do
begin
EnableMapRead(BitMap);
Move(EGABase^, Buffer[BitMap]^, BitMapSize)
end
end; { SaveEGAScreen }
function Exists(FileName : Str12) : boolean;
{ Returns true if FileName specifies a disk file that already exists }
var
F : file;
OK : boolean;
begin
if FileName = '' then { A null filename indicates standard output }
Exists := true
else
begin
Assign(F, FileName);
{$I-}
Reset(F);
{$I+}
OK := IOResult = 0;
if OK then
begin
Exists := true;
Close(F);
end
else
Exists := false;
end;
end; { Exists }
function WriteEGAScreen(FileName : Str12) : integer;
{ Saves an EGA (640x350) 16 color graphics screen into a file }
var
BitMap : integer;
ScreenFile : file;
Result : integer;
function IOError : boolean;
begin
Result := IOResult;
if Result <> 0 then
IOError := true
else
IOError := false;
end;
begin
Assign(ScreenFile, FileName);
{$I-}
Rewrite(ScreenFile, 1);
{$I+}
if IOError then
begin
WriteEGAScreen := Result; { return error code }
Exit;
end;
for BitMap := 1 to MaxBitMaps do
begin
EnableMapRead(BitMap);
{$I-}
BlockWrite(ScreenFile, EGABase^, BitMapSize);
{$I+}
if IOError then
begin
WriteEGAScreen := Result; { return error code }
Close(ScreenFile);
Exit;
end;
end;
Close(ScreenFile);
WriteEGAScreen := OK;
end; { WriteEGAScreen }
function MapsSelected : byte;
{ Returns the number of bit planes enabled for writing }
var
BitMap : integer;
MemByte : byte;
EnabledPlanes : byte;
begin
EnabledPlanes := 0;
Port[AddrReg] := ReadMapReg;
for BitMap := 0 to 3 do
begin
Port[SetResetReg] := BitMap;
MemByte := byte(EGABase^); { Read a dummy byte from bit plane }
byte(EGABase^) := not(MemByte); { Write the byte back inverted }
if byte(EGABase^) <> MemByte then { This plane is selected }
begin
EnabledPlanes := EnabledPlanes or (1 shl BitMap);
byte(EGABase^) := MemByte; { Reset original byte read }
end;
end;
MapsSelected := EnabledPlanes;
end; { MapsSelected }
procedure EnableMapWrite(Map : byte);
{ Enables writing to one of the EGA's Bit planes 1..4 }
begin
Port[SeqAddrReg] := MapMaskReg;
Port[ResetReg] := 1 shl Pred(Map);
end;
procedure RestoreEGAScreen(Buffer : EGABuffer);
var
BitMap : integer;
MapsEnabled : byte;
begin
MapsEnabled := MapsSelected; { Save originally selected write planes }
for BitMap := 1 to MaxBitMaps do
begin
EnableMapWrite(BitMap);
Move(Buffer[BitMap]^, EGABase^, BitMapSize);
end;
Port[ResetReg] := MapsEnabled; { Restore originally selected write planes }
end; { RestoreEGAScreen }
function ReadEGAScreen(FileName : Str12) : integer;
{ Restores an EGA (640x350) 16 color graphics screen from a file }
var
BitMap : integer;
MapsEnabled : byte;
ScreenFile : file;
Result : integer;
function IOError : boolean;
begin
Result := IOResult;
if Result <> 0 then
IOError := true
else
IOError := false;
end;
begin
if not Exists(FileName) then
begin
ReadEGAScreen := 2; { return "file not found" error code }
Exit;
end;
Assign(ScreenFile, FileName);
{$I-}
Reset(ScreenFile, 1);
{$I+}
if IOError then
begin
ReadEGAScreen := Result; { return error code }
Exit;
end;
MapsEnabled := MapsSelected; { Save originally selected write planes }
for BitMap := 1 to MaxBitMaps do
begin
EnableMapWrite(BitMap);
{$I-}
BlockRead(ScreenFile, EGABase^, BitMapSize);
{$I+}
if IOError then
begin
ReadEGAScreen := Result; { return error code }
Close(ScreenFile);
Exit;
end;
end;
Close(ScreenFile);
Port[ResetReg] := MapsEnabled; { Restore originally selected write planes }
ReadEGAScreen := OK;
end; { ReadEGAScreen }
function AllocateBuffer(var Buffer : EGABuffer) : boolean;
var
BitMap : integer;
begin
if MaxAvail >= longint(MaxBitMaps*BitMapSize) then
begin
for BitMap := 1 to MaxBitMaps do
GetMem(Buffer[BitMap], BitMapSize);
AllocateBuffer := true;
end
else
AllocateBuffer := false;
end; { AllocateBuffer }
procedure DisposeBuffer(var Buffer : EGABuffer);
var
BitMap : integer;
begin
for BitMap := 1 to MaxBitMaps do
if Buffer[BitMap] <> Nil then
begin
FreeMem(Buffer[BitMap], BitMapSize);
Buffer[BitMap] := Nil;
end;
end; { DisposeBuffer }
end.
|
unit IdGoogleHTTP;
{$mode objfpc}
interface
uses Classes
, SysUtils
, IdHTTP
, IdSSLOpenSSL
;
Type
{ TIdGoogleHTTP }
TIdGoogleHTTP = class(TIdHTTP)
private
IdSSLIOHandlerSocket1: TIdSSLIOHandlerSocketOpenSSL;
public
constructor Create(AOwner: TComponent); overload;
end;
implementation
{ TIdGoogleHTTP }
constructor TIdGoogleHTTP.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
IdSSLIOHandlerSocket1 := TIdSSLIOHandlerSocketOpenSSL.create(aOwner);
with IdSSLIOHandlerSocket1 do begin
SSLOptions.Method := sslvSSLv3;
SSLOptions.Mode := sslmUnassigned;
SSLOptions.VerifyMode := [];
SSLOptions.VerifyDepth := 2;
end;
IOHandler := IdSSLIOHandlerSocket1;
ReadTimeout := 0;
AllowCookies := True;
ProxyParams.BasicAuthentication := False;
ProxyParams.ProxyPort := 0;
Request.ContentLength := -1;
Request.ContentRangeEnd := 0;
Request.ContentRangeStart := 0;
Request.ContentType := 'application/x-www-form-urlencoded';
request.host := 'https://www.google.com';
Request.Accept := 'text/html, */*';
Request.CustomHeaders.Add('GData-Version: 2.0');
Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
HTTPOptions := [hoForceEncodeParams];
end;
end.
|
unit udmRelOutros;
interface
uses
Windows, Messages, SysUtils, Classes, FMTBcd, DB, frxClass, frxDBSet, SqlExpr,
Provider, DBClient, Forms, Variants, Controls, StrUtils, StdCtrls, frxRich,
frxDesgn, frxExportPDF, Graphics, Dialogs, Padrao1, Buttons, ComCtrls,
Mask, frxExportRTF, frxExportXML;
type
TdmRelOutros = class(TDataModule)
frxReport1: TfrxReport;
qryConfigOrgao: TSQLQuery;
qryConfigOrgaoRAZAO_SOCIAL: TStringField;
qryConfigOrgaoSIGLA: TStringField;
qryConfigOrgaoCNPJ: TStringField;
qryConfigOrgaoTIPO_ORGAO: TIntegerField;
qryConfigOrgaoENDER_LOGRAD: TStringField;
qryConfigOrgaoENDER_NUM: TStringField;
qryConfigOrgaoENDER_BAIRRO: TStringField;
qryConfigOrgaoENDER_CIDADE: TStringField;
qryConfigOrgaoENDER_CEP: TStringField;
qryConfigOrgaoENDER_UF: TStringField;
qryConfigOrgaoTELEFONE: TStringField;
qryConfigOrgaoNOME_DIR_DRH: TStringField;
qryConfigOrgaoCOD_CNAE: TIntegerField;
qryConfigOrgaoCOD_FPAS: TIntegerField;
qryConfigOrgaoCOD_NATUREZA_JURIDICA: TIntegerField;
qryConfigOrgaoCOD_MUNICIPIO_RAIS: TIntegerField;
qryConfigOrgaoCOD_MUNICIPIO_TCM: TIntegerField;
qryConfigOrgaoBRASAO: TBlobField;
qryConfigOrgaoDESCR_TIPO_ORGAO: TStringField;
qryConfigOrgaoLOGO_ADMIN: TBlobField;
provConfigOrgao: TDataSetProvider;
cdsConfigOrgao: TClientDataSet;
cdsConfigOrgaoRAZAO_SOCIAL: TStringField;
cdsConfigOrgaoSIGLA: TStringField;
cdsConfigOrgaoCNPJ: TStringField;
cdsConfigOrgaoTIPO_ORGAO: TIntegerField;
cdsConfigOrgaoENDER_LOGRAD: TStringField;
cdsConfigOrgaoENDER_NUM: TStringField;
cdsConfigOrgaoENDER_BAIRRO: TStringField;
cdsConfigOrgaoENDER_CIDADE: TStringField;
cdsConfigOrgaoENDER_CEP: TStringField;
cdsConfigOrgaoENDER_UF: TStringField;
cdsConfigOrgaoTELEFONE: TStringField;
cdsConfigOrgaoNOME_DIR_DRH: TStringField;
cdsConfigOrgaoCOD_CNAE: TIntegerField;
cdsConfigOrgaoCOD_FPAS: TIntegerField;
cdsConfigOrgaoCOD_NATUREZA_JURIDICA: TIntegerField;
cdsConfigOrgaoCOD_MUNICIPIO_RAIS: TIntegerField;
cdsConfigOrgaoCOD_MUNICIPIO_TCM: TIntegerField;
cdsConfigOrgaoBRASAO: TBlobField;
cdsConfigOrgaoLOGO_ADMIN: TBlobField;
cdsConfigOrgaoDESCR_TIPO_ORGAO: TStringField;
cdsConfigOrgaoNOME_SYS: TStringField;
cdsConfigOrgaoTITULO_REL1: TWideStringField;
cdsConfigOrgaoTITULO_REL2: TWideStringField;
frxConfigOrgao: TfrxDBDataset;
qryInconsistProcess: TSQLQuery;
provInconsistProcess: TDataSetProvider;
cdsInconsistProcess: TClientDataSet;
frxInconsistProcess: TfrxDBDataset;
frxRichObject1: TfrxRichObject;
cdsConfigOrgaoMEMO1: TMemoField;
cdsConfigOrgaoMEMO2: TMemoField;
cdsConfigOrgaoMSG_CONTRA_CHEQUE: TWideStringField;
cdsConfigOrgaoRAZAO_SOCIAL2: TStringField;
cdsConfigOrgaoCNPJ_FTDO: TStringField;
frxDesigner1: TfrxDesigner;
frxPDFExport1: TfrxPDFExport;
cdsInconsistProcessID: TIntegerField;
cdsInconsistProcessTIPO_PROCESS: TStringField;
cdsInconsistProcessID_SERVIDOR: TIntegerField;
cdsInconsistProcessREFERENCIA: TStringField;
cdsInconsistProcessTIPO_INCONSIST: TStringField;
cdsInconsistProcessID_SUB_UNID_ORCAM: TIntegerField;
cdsInconsistProcessDESCRICAO: TStringField;
cdsInconsistProcessDESCR_TIPO_INCONSIST: TStringField;
cdsInconsistProcessNOME_SERVIDOR: TStringField;
qryInconsistProcessID: TIntegerField;
qryInconsistProcessTIPO_PROCESS: TStringField;
qryInconsistProcessID_SERVIDOR: TIntegerField;
qryInconsistProcessREFERENCIA: TStringField;
qryInconsistProcessTIPO_INCONSIST: TStringField;
qryInconsistProcessID_SUB_UNID_ORCAM: TIntegerField;
qryInconsistProcessDESCRICAO: TStringField;
qryInconsistProcessDESCR_TIPO_INCONSIST: TStringField;
qryInconsistProcessNOME_SERVIDOR: TStringField;
qryInconsistProcessDESCR_SUB_UNID_ORCAM: TStringField;
cdsInconsistProcessDESCR_SUB_UNID_ORCAM: TStringField;
frxXMLExport1: TfrxXMLExport;
frxRTFExport1: TfrxRTFExport;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure cdsConfigOrgaoAfterOpen(DataSet: TDataSet);
private
{ Private declarations }
pv_sPathRel : String;
pv_sEventos : WideString;
pv_sAnoMes : String[6];
pv_sParcela : String[1];
public
{ Public declarations }
Procedure RelInconsistencias(sReferencia, sTipo: String; sMultiSUO: WideString;
iServidIni,iServidFim: Integer; lVisualizar: Boolean);
end;
var
dmRelOutros: TdmRelOutros;
implementation
uses VarGlobais, udmPrincipal, uTeste, gsLib, UtilsDb;
{$R *.dfm}
procedure TdmRelOutros.cdsConfigOrgaoAfterOpen(DataSet: TDataSet);
begin
cdsConfigOrgao.Edit;
cdsConfigOrgaoRAZAO_SOCIAL2.Value :=
Criptografa(cdsConfigOrgaoRAZAO_SOCIAL.Value,'2',60);
cdsConfigOrgaoCNPJ.Value :=
Criptografa(cdsConfigOrgaoCNPJ.Value,'2',14);
cdsConfigOrgaoCNPJ_FTDO.Value :=
FormatString('99.999.999/9999-99',cdsConfigOrgaoCNPJ.Value);
cdsConfigOrgaoNOME_SYS.Value:= glb_sSistema+' - Ver. '+glb_sVersao;
cdsConfigOrgao.Post;
end;
procedure TdmRelOutros.DataModuleCreate(Sender: TObject);
Var
iConta: integer;
begin
for iConta := 0 to ComponentCount - 1 do
begin
if Components[iConta] is TClientDataSet then
TClientDataSet(Components[iConta]).Close;
if (Components[iConta] is TSQLQuery) and
(TSQLQuery(Components[iConta]).Active) then
TSQLQuery(Components[iConta]).Close;
end;
cdsConfigOrgao.Close;
cdsInconsistProcess.Close;
pv_sPathRel := GetPathRel();
cdsConfigOrgao.Close;
cdsConfigOrgao.Open;
end;
procedure TdmRelOutros.DataModuleDestroy(Sender: TObject);
begin
cdsConfigOrgao.Close;
end;
Procedure TdmRelOutros.RelInconsistencias(sReferencia, sTipo: String;
sMultiSUO: WideString; iServidIni,iServidFim: Integer; lVisualizar: Boolean);
Var
sDescrTipoProcess: string;
begin
sMultiSUO := AjustaTextoParamVarios(sMultiSUO);
if sTipo = '1' then
sDescrTipoProcess := 'CÁLCULO DA FOLHA DE PAGTO';
cdsConfigOrgao.Edit;
cdsConfigOrgaoTITULO_REL1.Value:= 'RELATÓRIOS DE INCONSISTÊNCIAS DO PROCESSAMENTO';
cdsConfigOrgaoTITULO_REL2.Value:= sDescrTipoProcess+' - REF. : '+glb_sDescrMesAnoTrab;
cdsConfigOrgao.Post;
cdsInconsistProcess.Close;
qryInconsistProcess.ParamByName('pRef').Value := sReferencia;
qryInconsistProcess.ParamByName('pTipo').Value := sTipo;
qryInconsistProcess.ParamByName('pMultiSUO').Value := sMultiSUO;
qryInconsistProcess.ParamByName('pServidIni').Value:= iServidIni;
qryInconsistProcess.ParamByName('pServidFim').Value:= iServidFim;
cdsInconsistProcess.Open;
if cdsInconsistProcess.RecordCount = 0 then
begin
Mensagem('Não há Inconsistências p/ relatar ...',
'Parabéns !!!',MB_OK+MB_ICONEXCLAMATION);
exit;
end;
frxReport1.LoadFromFile(pv_sPathRel+'InconsistProcess.fr3');
Screen.Cursor := crDefault;
frxReport1.PrepareReport(True);
if lVisualizar then
frxReport1.ShowReport()
else
frxReport1.Print;
end;
end.
|
program ElectricalProbeInfo;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, uSMBIOS
{ you can add units after this };
function ByteToBinStr(AValue:Byte):string;
const
Bits: array[1..8] of byte = (128,64,32,16,8,4,2,1);
var i: integer;
begin
Result:='00000000';
if (AValue<>0) then
for i:=1 to 8 do
if (AValue and Bits[i])<>0 then Result[i]:='1';
end;
procedure GetElectricalCurrProbeInfo;
Var
SMBios: TSMBios;
LElectCurrProbeInfo: TElectricalCurrentProbeInformation;
begin
SMBios:=TSMBios.Create;
try
WriteLn('Electrical Current Probe Information');
WriteLn('-----------------------------------');
if SMBios.HasElectricalCurrentProbeInfo then
for LElectCurrProbeInfo in SMBios.ElectricalCurrentProbeInformation do
begin
WriteLn(Format('Description %s',[LElectCurrProbeInfo.GetDescriptionStr]));
WriteLn(Format('Location and Status %s',[ByteToBinStr(LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.LocationandStatus)]));
WriteLn(Format('Location %s',[LElectCurrProbeInfo.GetLocation]));
WriteLn(Format('Status %s',[LElectCurrProbeInfo.GetStatus]));
if LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.MaximumValue=$8000 then
WriteLn(Format('Maximum Value %s',['Unknown']))
else
WriteLn(Format('Maximum Value %d milliamps.°',[LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.MaximumValue]));
if LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.MinimumValue=$8000 then
WriteLn(Format('Minimum Value %s',['Unknown']))
else
WriteLn(Format('Minimum Value %d milliamps.',[LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.MinimumValue]));
if LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.Resolution=$8000 then
WriteLn(Format('Resolution %s',['Unknown']))
else
WriteLn(Format('Resolution %d milliamps.',[LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.Resolution div 10]));
if LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.Tolerance=$8000 then
WriteLn(Format('Tolerance %s',['Unknown']))
else
WriteLn(Format('Tolerance %n milliamps.',[LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.Tolerance]));
WriteLn(Format('OEM Specific %.8x',[LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.OEMdefined]));
if LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.Header.Length>$14 then
if LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.NominalValue=$8000 then
WriteLn(Format('Nominal Value %s',['Unknown']))
else
WriteLn(Format('Nominal Value %d milliamps.',[LElectCurrProbeInfo.RAWElectricalCurrentProbeInfo^.NominalValue]));
WriteLn;
end
else
Writeln('No Electrical Current Probe Info was found');
finally
SMBios.Free;
end;
end;
begin
try
GetElectricalCurrProbeInfo;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
|
{$i deltics.interfacedobjects.inc}
unit Deltics.InterfacedObjects.InterfaceReference;
interface
type
TInterfaceReference = class(TObject, IUnknown)
private
fRef: IUnknown;
public
constructor Create(const aRef: IUnknown);
function IsReferenceTo(const aOther: IUnknown): Boolean;
// IUnknown
protected
{
IUnknown is delegated to the contained reference using "implements"
ALL methods of IUnknown are delegated to the fRef, meaning that
TInterface does not need to worry about being reference counted
itself (it won't be).
}
property Ref: IUnknown read fRef implements IUnknown;
end;
implementation
{ TInterfaceRef ---------------------------------------------------------------------------------- }
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
constructor TInterfaceReference.Create(const aRef: IInterface);
begin
inherited Create;
fRef := aRef as IUnknown;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TInterfaceReference.IsReferenceTo(const aOther: IInterface): Boolean;
begin
result := (aOther as IUnknown) = fRef
end;
end.
|
{-----------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: JvTabBarXPPainter.pas, released on 2007-05-07.
The Initial Developer of the Original Code is Valdir Stiebe Junior <valdir att dype dott com dott br>
All Rights Reserved.
Contributor(s):
You may retrieve the latest version of this file at the Project JEDI's JVCL home page,
located at http://jvcl.delphi-jedi.org
Known Issues:
-----------------------------------------------------------------------------}
// $Id$
{$MODE objfpc}{$H+}
unit JvTabBarXPPainter;
interface
uses
LCLType, Types, SysUtils, Classes, Graphics, JvTabBar;
type
TJvTabBarXPPainter = class(TJvTabBarModernPainter)
private
FFixedTabSize: Integer;
procedure SetFixedTabSize(const Value: Integer);
protected
procedure DrawBackground(Canvas: TCanvas; TabBar: TJvCustomTabBar; R: TRect); override;
procedure DrawTab(Canvas: TCanvas; Tab: TJvTabBarItem; R: TRect); override;
procedure DrawDivider(Canvas: TCanvas; LeftTab: TJvTabBarItem; R: TRect); override;
procedure DrawMoveDivider(Canvas: TCanvas; Tab: TJvTabBarItem; MoveLeft: Boolean); override;
function GetDividerWidth(Canvas: TCanvas; LeftTab: TJvTabBarItem): Integer; override;
function GetTabSize(Canvas: TCanvas; Tab: TJvTabBarItem): TSize; override;
function GetCloseRect(Canvas: TCanvas; Tab: TJvTabBarItem; R: TRect): TRect; override;
published
property FixedTabSize: Integer read FFixedTabSize write SetFixedTabSize;
end;
implementation
uses
LCLVersion, Math, Themes, imgList;
{ TJvTabBarXPPainter }
procedure TJvTabBarXPPainter.DrawBackground(Canvas: TCanvas;
TabBar: TJvCustomTabBar; R: TRect);
var
Details: TThemedElementDetails;
begin
if ThemeServices.ThemesEnabled then
begin
Details := ThemeServices.GetElementDetails(ttTabRoot);
ThemeServices.DrawElement(Canvas.Handle, Details, R);
end
else
inherited DrawBackground(Canvas, TabBar, R);
end;
procedure TJvTabBarXPPainter.DrawDivider(Canvas: TCanvas; LeftTab: TJvTabBarItem; R: TRect);
begin
if not ThemeServices.ThemesEnabled then
inherited DrawDivider(Canvas, LeftTab, R);
end;
procedure TJvTabBarXPPainter.DrawMoveDivider(Canvas: TCanvas; Tab: TJvTabBarItem;
MoveLeft: Boolean);
begin
if not ThemeServices.ThemesEnabled then
inherited DrawMoveDivider(Canvas, Tab, MoveLeft);
end;
procedure TJvTabBarXPPainter.DrawTab(Canvas: TCanvas; Tab: TJvTabBarItem;
R: TRect);
var
tabBar: TJvCustomTabBar;
tabDetails, buttonDetails: TThemedElementDetails;
CloseRect, TextRect: TRect;
imgsize: TSize;
x, y: Integer;
{$IF LCL_FullVersion >= 1090000}
imageRes: TScaledImageListResolution;
f: Double;
ppi: Integer;
{$IFEND}
begin
tabBar := GetTabBar(Tab);
if ThemeServices.ThemesEnabled then
begin
if Tab.Selected then
begin
buttonDetails := ThemeServices.GetElementDetails(twSmallCloseButtonNormal);
tabDetails := ThemeServices.GetElementDetails(ttTabItemSelected);
end
else if Tab.Hot then
begin
buttonDetails := ThemeServices.GetElementDetails(twSmallCloseButtonHot);
tabDetails := ThemeServices.GetElementDetails(ttTabItemHot);
end
else
begin
buttonDetails := ThemeServices.GetElementDetails(twSmallCloseButtonNormal);
tabDetails := ThemeServices.GetElementDetails(ttTabItemNormal);
end;
if Tab.Closing then
buttonDetails := ThemeServices.GetElementDetails(twSmallCloseButtonPushed);
ThemeServices.DrawElement(Canvas.Handle, tabDetails, R);
if (Tab.ImageIndex <> -1) and (Tab.GetImages <> nil) then
begin
imgSize := GetRealImageSize(Tab);
x := R.Left + Scale(tabBar, 4);
y := (R.Top + R.Bottom - imgSize.CY) div 2;
{$IF LCL_FullVersion >= 1090000}
f := tabBar.GetCanvasScaleFactor;
ppi := GetPixelsPerInch;
imageRes := Tab.GetImages.ResolutionForPPI[tabBar.ImagesWidth, ppi, f];
imageRes.Draw(Canvas, x, y, Tab.ImageIndex, Tab.Enabled);
{$ELSE}
Tab.GetImages.Draw(Canvas, x, y, Tab.ImageIndex, Tab.Enabled);
{$IFEND}
Inc(R.Left, imgSize.CX + Scale(tabBar, 2));
end;
TextRect := R;
TextRect.Left := TextRect.Left + Tab.TabBar.Margin;
if Tab.TabBar.CloseButton then
begin
CloseRect := GetCloseRect(Canvas, Tab, R);
TextRect.Right := CloseRect.Left - Scale(tabBar, 3);
end
else
Dec(TextRect.Right, Scale(tabBar, 3));
Canvas.Brush.Style := bsClear;
ThemeServices.DrawText(Canvas.Handle, TabDetails, Tab.Caption, TextRect, DT_SINGLELINE or DT_VCENTER or DT_END_ELLIPSIS, 0);
if Tab.TabBar.CloseButton then
ThemeServices.DrawElement(Canvas.Handle, ButtonDetails, CloseRect);
end
else
inherited DrawTab(Canvas, Tab, R);
end;
function TJvTabBarXPPainter.GetCloseRect(Canvas: TCanvas; Tab: TJvTabBarItem;
R: TRect): TRect;
var
tabBar: TJvCustomTabBar;
p15: Integer;
begin
if ThemeServices.ThemesEnabled then
begin
tabBar := GetTabBar(Tab);
p15 := Scale(tabBar, 15);
// Result.Top := R.Top + R.Bottom div 2 - Scale(tabBar, 8);
Result.Top := (R.Top + R.Bottom - p15) div 2;
Result.Bottom := Result.Top + p15;
Result.Right := R.Right - Scale(tabBar, 5);
Result.Left := Result.Right - p15;
end
else
Result := inherited GetCloseRect(Canvas, Tab, R);
end;
function TJvTabBarXPPainter.GetDividerWidth(Canvas: TCanvas; LeftTab: TJvTabBarItem): Integer;
begin
if ThemeServices.ThemesEnabled then
Result := 1
else
Result := inherited GetDividerWidth(Canvas, LeftTab);
end;
function TJvTabBarXPPainter.GetTabSize(Canvas: TCanvas; Tab: TJvTabBarItem): TSize;
var
tabBar: TJvCustomTabBar;
begin
tabBar := GetTabBar(Tab);
if FixedTabSize > 0 then
begin
if ThemeServices.ThemesEnabled then
Result.cx := FixedTabSize
else
Result.cx := Min(FixedTabSize + Scale(tabBar, 40), Canvas.TextWidth(Tab.Caption) + Scale(tabBar, 26));
end
else
begin
if ThemeServices.ThemesEnabled then
begin
Result.cx := Canvas.TextWidth(Tab.Caption) + Scale(tabBar, 16);
if (Tab.ImageIndex <> -1) and (Tab.GetImages <> nil) then
Inc(Result.cx, GetRealImageSize(Tab).CX + Scale(tabBar, 2));
if Tab.TabBar.CloseButton then
Inc(Result.cx, Scale(tabBar, 18));
end
else
Result := inherited GetTabSize(Canvas, Tab);
end;
Result.cy := Tab.TabBar.Height - Scale(tabBar, 3);
end;
procedure TJvTabBarXPPainter.SetFixedTabSize(const Value: Integer);
begin
if Value <> FixedTabSize then
begin
FFixedTabSize := Value;
Changed;
end;
end;
end.
|
unit TeeChartBook;
{$I TeeDefs.inc}
interface
uses
Windows, Messages,
SysUtils, Classes,
Graphics, Controls, Forms, Dialogs, Menus, ComCtrls, ExtCtrls,
Chart, TeeComma;
type
TChartBook=class(TPageControl)
private
Toolbar,
DeleteItem : TMenuItem;
FOnNew : TNotifyEvent;
Function CreateToolBar(AChart:TCustomChart):TTeeCommander;
Procedure DeleteClick(Sender:TObject);
Procedure EditClick(Sender:TObject);
Procedure NewClick(Sender:TObject);
Procedure Popup(Sender:TObject);
Procedure RenameClick(Sender:TObject);
Procedure ToolbarClick(Sender:TObject);
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
Function ActiveChart:TCustomChart;
Function ActiveToolbar:TTeeCommander;
Procedure AddChart(Const AName:String);
published
property PopupMenu stored False;
property TabPosition default tpBottom;
property OnNewChart:TNotifyEvent read FOnNew write FOnNew;
end;
procedure Register;
implementation
uses TeeConst, TeeProcs, EditChar;
procedure Register;
begin
RegisterComponents(TeeMsg_TeeChartPalette, [TChartBook]);
end;
{ TChartBook }
constructor TChartBook.Create(AOwner: TComponent);
var P:TPopupMenu;
begin
inherited;
TabPosition:=tpBottom;
P:=TPopupMenu.Create(Self);
P.Items.Add(TMenuItem.Create(Self));
P.Items[0].Caption:='&New';
P.Items[0].OnClick:=NewClick;
DeleteItem:=TMenuItem.Create(Self);
P.Items.Add(DeleteItem);
DeleteItem.Caption:='&Delete';
DeleteItem.OnClick:=DeleteClick;
P.Items.Add(TMenuItem.Create(Self));
P.Items[2].Caption:='&Rename...';
P.Items[2].OnClick:=RenameClick;
P.Items.Add(TMenuItem.Create(Self));
P.Items[3].Caption:='&Edit...';
P.Items[3].OnClick:=EditClick;
ToolBar:=TMenuItem.Create(Self);
P.Items.Add(Toolbar);
Toolbar.Caption:='&View Toolbar';
P.Items[4].OnClick:=ToolbarClick;
PopupMenu:=P;
P.OnPopup:=Popup;
end;
Procedure TChartBook.Popup(Sender:TObject);
begin
DeleteItem.Enabled:=PageCount>1;
Toolbar.Checked:=(ActiveToolBar<>nil);
end;
Procedure TChartBook.EditClick(Sender:TObject);
begin
EditChart(nil,ActiveChart);
end;
Function TChartBook.ActiveChart:TCustomChart;
begin
result:=ActivePage.Controls[0] as TCustomChart;
end;
Procedure TChartBook.DeleteClick(Sender:TObject);
var tmp : Integer;
begin
tmp:=ActivePage.TabIndex;
ActivePage.Free;
if tmp>0 then ActivePage:=Pages[tmp-1];
end;
Procedure TChartBook.ToolbarClick(Sender:TObject);
begin
if ActiveToolbar=nil then
ActivePage.InsertControl(CreateToolBar(ActiveChart));
Toolbar.Checked:=not Toolbar.Checked;
ActiveToolbar.Visible:=Toolbar.Checked;
end;
Procedure TChartBook.NewClick(Sender:TObject);
begin
AddChart('Chart'+IntToStr(PageCount+1));
ActivePage:=Pages[PageCount-1];
if Assigned(FOnNew) then FOnNew(Self);
end;
Function TChartBook.CreateToolBar(AChart:TCustomChart):TTeeCommander;
var B:TBevel;
begin
result:=TTeeCommander.Create(Owner);
with result do
begin
Align:=alTop;
BevelOuter:=bvNone;
Panel:=AChart;
B:=TBevel.Create(Owner);
B.Height:=1;
B.Shape:=bsBottomLine;
B.Style:=bsLowered;
B.Align:=alBottom;
InsertControl(B);
end;
end;
Procedure TChartBook.AddChart(Const AName:String);
var C: TChart;
begin
With TTabSheet.Create(Self) do
begin
Caption:=AName;
C:=TChart.Create(Self);
C.Align:=alClient;
C.BevelOuter:=bvNone;
InsertControl(C);
InsertControl(CreateToolbar(C));
PageControl:=Self;
end;
end;
procedure TChartBook.RenameClick(Sender: TObject);
var tmp:String;
begin
tmp:=ActivePage.Caption;
if InputQuery('Rename Chart page','New name:',tmp) then
ActivePage.Caption:=tmp;
end;
function TChartBook.ActiveToolbar: TTeeCommander;
var t:Integer;
begin
if Assigned(ActivePage) then
With ActivePage do
for t:=0 to ControlCount-1 do
if Controls[t] is TTeeCommander then
begin
result:=Controls[t] as TTeeCommander;
exit;
end;
result:=nil;
end;
destructor TChartBook.Destroy;
begin
if PopupMenu.Owner=Self then PopupMenu.Free;
inherited;
end;
end.
|
unit ImageResizerUnit;
interface
uses
Classes, ResizerCommonTypesUnit, ImageCommonTypesUnit,
ImageProcessingMethodsUnit, FileStructureInformationUnit,
ImageResizingInformationUnit;
type
TImageResizer = class
private
FImageProcessingMethods: TImageProcessingMethods; // Image processing methods
FImageInformation: TImageResizingInformation; // Image resizing information
FFileInformation: TFileStructureInformation; // File structure information
FContinueProcess: Boolean; // if false, stop processing
FBadFiles: TStringList; // List of bad files found during resizing
FDirListCurrent: Boolean; // FFileInformation.Dirs has been compiled with current FFileInformation.Root
FFilesListCurrent: Boolean; // FFileInformation.Files has been compiled or set with recent data
/////////////////////////
// Notification events //
/////////////////////////
FScaleCalculated: TNotifyEvent;
FWidthCalculated: TNotifyEvent;
FHeightCalculated: TNotifyEvent;
FResizingStarted: TNotifyEvent;
FResizingEnded: TNotifyEvent;
FDestinationSet: TNotifyEvent;
FLoadingFile: TNotifyEvent;
FSavingFile: TNotifyEvent;
/////////////
// Getters //
/////////////
// Image Processing Methods
function GetSourceMethod: TSourceMethod;
function GetFiletypeMethod: TFiletypeMethod;
function GetScalingMethod: TScalingMethod;
function GetFiletypeConversion: TFiletypeConversion;
function GetFileHandling: TFileHandling;
// File Information
function GetRoot: String;
function GetDirs: TStringList;
function GetFiles: TStringList;
function GetOutputPath: String;
function GetPrefix: String;
function GetSuffix: String;
function GetDestination: String;
function GetImageFileType: TImageFileType;
function GetImageTypeSet: TImageTypeSet;
// Image Resizing Information
function GetFileName: String;
function GetWidth: integer;
function GetHeight: integer;
function GetCurrentWidth: integer;
function GetCurrentHeight: integer;
function GetConvertedHeight: integer;
function GetConvertedWidth: integer;
function GetScale: real;
function GetCompressMethod: Boolean;
function GetJPEGCompression: integer;
/////////////
// Setters //
/////////////
// Image Processing Methods
procedure SetSourceMethod(const Value: TSourceMethod);
procedure SetFiletypeMethod(const Value: TFiletypeMethod);
procedure SetScalingMethod(const Value: TScalingMethod);
procedure SetFiletypeConversion(const Value: TFiletypeConversion);
procedure SetFileHandling(const Value: TFileHandling);
// File Information
procedure SetRoot(const Value: String);
procedure SetDirs(const Value: TStringList);
procedure SetFiles(const Value: TStringList);
procedure SetOutputPath(const Value: String);
procedure SetPrefix(const Value: String);
procedure SetSuffix(const Value: String);
procedure SetDestination(const Value: String);
procedure SetImageFileType(const Value: TImageFileType);
procedure SetImageTypeSet(const Value: TImageTypeSet);
// Image Resizing Information
procedure SetFileName(const sFileName: String);
procedure SetWidth(const Value: integer);
procedure SetHeight(const Value: integer);
procedure SetScale(fScaleValue: real);
procedure SetCompressMethod(const Value: Boolean);
procedure SetJPEGCompression(const Value: integer);
// Calculations
function CalculateScale(const iWidth, iHeight: integer): real;
function CalculateWidth(const iWidth: integer): integer;
function CalculateHeight(const iHeight: integer): integer;
// Business logic
procedure SetCurrentWidth(const iCurrentWidth: integer);
procedure SetCurrentHeight(const iCurrentHeight: integer);
procedure SetConvertedWidth(const iConvertedWidth: integer);
procedure SetConvertedHeight(const iConvertedHeight: integer);
procedure LogBadFile(const sFileName: String);
// Main methods
procedure CalculateImageDimensions;
public
constructor Create;
destructor Destroy; reintroduce; overload;
procedure ClearFilesList;
procedure PrepareDirsList;
procedure PrepareFilesList;
// procedure ResizeSingle[index: integer];
procedure ResizeAll;
published
// Image Processing Methods
property SourceMethod: TSourceMethod read GetSourceMethod write SetSourceMethod;
property FileTypeMethod: TFiletypeMethod read GetFiletypeMethod write SetFiletypeMethod;
property ScalingMethod: TScalingMethod read GetScalingMethod write SetScalingMethod;
property FiletypeConversion: TFiletypeConversion read GetFiletypeConversion write SetFiletypeConversion;
property FileHandling: TFileHandling read GetFileHandling write SetFileHandling;
property ContinueProcess: Boolean read FContinueProcess write FContinueProcess;
// File Information
property Root: String read GetRoot write SetRoot;
property Dirs: TStringList read GetDirs write SetDirs;
property Files: TStringList read GetFiles write SetFiles;
property OutputPath: String read GetOutputPath write SetOutputPath;
property Prefix: String read GetPrefix write SetPrefix;
property Suffix: String read GetSuffix write SetSuffix;
property Destination: String read GetDestination write SetDestination;
property ImageFileType: TImageFileType read GetImageFileType write SetImageFileType;
property ImageTypeSet: TImageTypeSet read GetImageTypeSet write SetImageTypeSet;
// Image Resizing Information
property FileName: String read GetFileName;
property Width: integer read GetWidth write SetWidth;
property Height: integer read GetHeight write SetHeight;
property CurrentWidth: integer read GetCurrentWidth;
property CurrentHeight: integer read GetCurrentHeight;
property ConvertedWidth: integer read GetConvertedWidth;
property ConvertedHeight: integer read GetConvertedHeight;
property Scale: real read GetScale write SetScale;
property CompressMethod: Boolean read GetCompressMethod write SetCompressMethod;
property JPEGCompression: integer read GetJPEGCompression write SetJPEGCompression;
property BadFiles: TStringList read FBadFiles;
// Notification Messages
property OnScaleCalculated: TNotifyEvent read FScaleCalculated write FScaleCalculated;
property OnWidthCalculated: TNotifyEvent read FWidthCalculated write FWidthCalculated;
property OnHeightCalculated: TNotifyEvent read FHeightCalculated write FHeightCalculated;
property OnResizingStarted: TNotifyEvent read FResizingStarted write FResizingStarted;
property OnResizingEnded: TNotifyEvent read FResizingEnded write FResizingEnded;
property OnDestinationSet: TNotifyEvent read FDestinationSet write FDestinationSet;
property OnLoadingFile: TNotifyEvent read FLoadingFile write FLoadingFile;
property OnSavingFile: TNotifyEvent read FSavingFile write FSavingFile;
end; // TImageResizer
implementation
uses
SysUtils, Graphics, JPEG, FileCtrl, Math,
ResizerConstsUnit, ImageFilesUnit, ImageAltercationUnit;
{ TImageResizer }
//////////////////////////////
// Constructor / Destructor //
//////////////////////////////
constructor TImageResizer.Create;
begin
inherited;
///////////////////////////
// Initialize everything //
///////////////////////////
FImageProcessingMethods := TImageProcessingMethods.Create; // Image processing methods
FFileInformation := TFileStructureInformation.Create; // File information object
FImageInformation := TImageResizingInformation.Create; // Image resizing information
FContinueProcess := True;
FBadFiles := TStringList.Create;
FDirListCurrent := False;
FFilesListCurrent := False;
end;
destructor TImageResizer.Destroy;
begin
//////////////
// Clean up //
//////////////
FreeAndNil(FImageProcessingMethods);
FreeAndNil(FFileInformation);
FreeAndNil(FImageInformation);
FreeAndNil(FBadFiles);
inherited;
end;
//////////////////
// Calculations //
//////////////////
function TImageResizer.CalculateScale(const iWidth, iHeight: integer): real;
//////////////////////////////////////////////////////////////////////////////
// Preconditions : //
// iWidth, iHeight must be valid width and height, respectively //
// FImageInformation.Width, FImageInformation.Height must be set beforehand (0 represents do not constrict) //
// //
// Output : //
// Scale that can be used to calculate width and height to be less than or //
// equal to the passed in width and height //
//////////////////////////////////////////////////////////////////////////////
var
fTemp: real;
begin
if (FImageInformation.Width <> 0) and (FImageInformation.Height <> 0) then
fTemp := Max(Abs(iWidth / FImageInformation.Width), Abs(iHeight / FImageInformation.Height))
else
if (FImageInformation.Width <> 0) then
fTemp := Abs(iWidth / FImageInformation.Width)
else
if (FImageInformation.Height <> 0) then
fTemp := Abs(iHeight / FImageInformation.Height)
else
fTemp := 1.0;
Result := fTemp;
end; // CalculateScale
function TImageResizer.CalculateWidth(const iWidth: integer): integer;
///////////////////////////////////////////
// Preconditions : //
// FImageInformation.Scale must be valid //
// //
// Output : //
// Height value, calculated with FImageInformation.Scale //
///////////////////////////////////////////
begin
Result := Round(iWidth / FImageInformation.Scale);
end; // CalculateWidth
function TImageResizer.CalculateHeight(const iHeight: integer): integer;
///////////////////////////////////////////
// Preconditions : //
// FImageInformation.Scale must be valid //
// //
// Output : //
// Height value, calculated with FImageInformation.Scale //
///////////////////////////////////////////
begin
Result := Round(iHeight / FImageInformation.Scale);
end; // CalculateHeight
////////////////////
// Business logic //
////////////////////
procedure TImageResizer.SetCurrentWidth(const iCurrentWidth: integer);
////////////////////////////////////////////
// Preconditions : //
// iCurrentWidth must be a valid integer //
// Should be called when file is loaded //
// //
// Output : //
// FImageInformation.CurrentWidth is assigned //
////////////////////////////////////////////
begin
if iCurrentWidth > 0 then
FImageInformation.CurrentWidth := iCurrentWidth
else
FImageInformation.CurrentWidth := 1;
end;
procedure TImageResizer.SetCurrentHeight(const iCurrentHeight: integer);
/////////////////////////////////////////////
// Preconditions : //
// iCurrentHeight must be a valid integer //
// Should be called when file is loaded //
// //
// Output : //
// FImageInformation.CurrentHeight is assigned //
/////////////////////////////////////////////
begin
if iCurrentHeight > 0 then
FImageInformation.CurrentHeight := iCurrentHeight
else
FImageInformation.CurrentHeight := 1;
end;
procedure TImageResizer.SetConvertedWidth(const iConvertedWidth: integer);
//////////////////////////////////////////////
// Preconditions : //
// iConvertedWidth must be a valid integer //
// //
// Output : //
// FImageInformation.ConvertedWidth is assigned //
// FWidthCalculated event is called //
//////////////////////////////////////////////
begin
FImageInformation.ConvertedWidth := iConvertedWidth;
if Assigned(FWidthCalculated) then
FWidthCalculated(Self);
end;
procedure TImageResizer.SetConvertedHeight(const iConvertedHeight: integer);
///////////////////////////////////////////////
// Preconditions : //
// iConvertedHeight must be a valid integer //
// //
// Output : //
// FImageInformation.ConvertedHeight is assigned //
// FHeightCalculated event is called //
///////////////////////////////////////////////
begin
FImageInformation.ConvertedHeight := iConvertedHeight;
if Assigned(FHeightCalculated) then
FHeightCalculated(Self);
end;
procedure TImageResizer.LogBadFile(const sFileName: String);
///////////////////////////////////////////////////////////////////////////////
// Preconditions : //
// sFileName is a valid file name that represents an erroneous file //
// //
// Output : //
// sFileName is added to a list of names of bad files found during resizing //
///////////////////////////////////////////////////////////////////////////////
begin
FBadFiles.Add(sFileName);
end;
procedure TImageResizer.ClearFilesList;
////////////////////////////////////////
// Preconditions : //
// //
// Output : //
// FFileInformation.Files is cleared //
// FBadFiles is cleared //
////////////////////////////////////////
begin
FFileInformation.Files.Clear;
FBadFiles.Clear;
end;
procedure TImageResizer.PrepareDirsList;
////////////////////////////////////////////////////////////////////
// Preconditions : //
// FImageProcessingMethods.SourceMethod needs to be set //
// to the proper setting //
// //
// Output : //
// FFileInformation.Dirs is populated with a list of directories //
// to search for files in //
// FDirListCurrent is reset to True //
// //
// Note : //
// Called when FImageProcessingMethods.SourceMethod relates to //
// directory-based, not file-based //
////////////////////////////////////////////////////////////////////
begin
FFileInformation.PrepareDirsList(FImageProcessingMethods.SourceMethod);
FDirListCurrent := True;
end;
procedure TImageResizer.PrepareFilesList;
//////////////////////////////////////////////////////////////////////////
// Preconditions : //
// FFileInformation.PrepareFilesList preconditions must be met //
// //
// Output : //
// File lists are cleared //
// FFileInformation.Files is populated with a list of files to process //
// FFilesListCurrent flag is reset to True //
//////////////////////////////////////////////////////////////////////////
begin
ClearFilesList;
FFileInformation.PrepareFilesList;
FFilesListCurrent := True;
end;
/////////////
// Setters //
/////////////
procedure TImageResizer.SetFileName(const sFileName: String);
/////////////////////////////////////////////
// Preconditions : //
// sFileName is a valid file name + path //
// Should be called when file is loaded //
// //
// Output : //
// FImageInformation.FileName is assigned //
// FLoadingFile is triggered //
/////////////////////////////////////////////
begin
FImageInformation.FileName := sFileName;
if Assigned(FLoadingFile) then
FLoadingFile(Self);
end;
procedure TImageResizer.SetScale(fScaleValue: real);
////////////////////////////////////
// Preconditions : //
// FImageInformation.Scale is a valid scale value //
// //
// Output : //
// FImageInformation.Scale is assigned //
// FScaleSet is called //
////////////////////////////////////
begin
FImageInformation.Scale := fScaleValue;
if Assigned(FScaleCalculated) then
FScaleCalculated(Self);
end;
//////////////////
// Main methods //
//////////////////
procedure TImageResizer.CalculateImageDimensions;
/////////////////////////////////////////////////////
// Preconditions : //
// FScalingMethod must be properly set beforehand //
// FImageInformation.CurrentWidth and FImageInformation.CurrentHeight must be set //
// //
// Output : //
// Scale may be altered //
// FImageInformation.Width, FImageInformation.Height are both calculated //
/////////////////////////////////////////////////////
begin
if (FImageProcessingMethods.ScalingMethod = zsmCalculate) then
Scale := CalculateScale(FImageInformation.CurrentWidth, FImageInformation.CurrentHeight);
if FImageInformation.Scale <= 0 then
Scale := 1.0;
SetConvertedWidth(CalculateWidth(FImageInformation.CurrentWidth));
SetConvertedHeight(CalculateHeight(FImageInformation.CurrentHeight));
end;
procedure TImageResizer.ResizeAll;
procedure PrepareOutputDirectory(const sFileName: String);
////////////////////////////////////////////////////////////////
// Preconditions : //
// sFileName needs to be a valid file name //
// FFileInformation.OutputPath needs to be a valid directory //
// //
// Output : //
// Future file directories are created //
////////////////////////////////////////////////////////////////
begin
if not DirectoryExists(ExtractFilePath(sFileName)) then
ForceDirectories(ExtractFilePath(sFileName));
end; // procedure PrepareOutputDirectory
function EverythingIsReady: Boolean;
var
bSourcesSet,
bScaleSet,
bDestinationSet: Boolean;
begin
bSourcesSet := FFileInformation.Files.Count > 0;
case FImageProcessingMethods.ScalingMethod of
zsmFactor:
bScaleSet := FImageInformation.Scale > 0;
zsmCalculate:
bScaleSet := (FImageInformation.Width > 0) and (FImageInformation.Height > 0);
else
bScaleSet := False;
end; // case FScalingMethod
bDestinationSet := Trim(FFileInformation.OutputPath) <> '';
Result := bSourcesSet and bScaleSet and bDestinationSet;
end; // function EverythingIsReady
function DestinationIsGood(const sFileName: String): Boolean;
begin
Result := (FImageProcessingMethods.FileHandling = zfhOverwrite)
or ((FImageProcessingMethods.FileHandling = zfhSkip) and not FileExists(sFileName));
end; // function DestinationIsGood
procedure DoCompressionSettings(const imgImage: TGraphic;
var imgConverted: TGraphic; iftFileType: TImageFileType);
/////////////////////////////////////////////////////////////////////////////
// Preconditions : //
// imgImage and imgConverted are valid TGraphics //
// iftFileType is a valid TImageFileType //
// //
// Output : //
// Compression values for the image are set, based on filetype and method //
/////////////////////////////////////////////////////////////////////////////
begin
case iftFileType of
ziftJPG:
begin
if FImageInformation.CompressMethod then
/////////////////////////////////////////////
// Use the newly defined compression value //
/////////////////////////////////////////////
TJPEGImage(imgConverted).CompressionQuality := FImageInformation.JPEGCompression
else
////////////////////////////////////
// Use the original image's value //
////////////////////////////////////
TJPEGImage(imgConverted).CompressionQuality := TJPEGImage(imgImage).CompressionQuality;
end; // ziftJPG
else
// Do nothing
end; // case iftFileType
end;
var
bBadFile: Boolean;
i: integer;
imgImage,
imgConverted: TGraphic;
iftFiletype: TImageFileType;
begin
if Assigned(FResizingStarted) then
FResizingStarted(Self);
// Validate we have data we need
// Create directory tree for destination
case FImageProcessingMethods.SourceMethod of
zsmRecursiveDirectory:
begin
if not FDirListCurrent then
PrepareDirsList;
if not FFilesListCurrent then
PrepareFilesList;
end; // zsmRecursiveDirectory
zsmDirectory:
if not FFilesListCurrent then
PrepareFilesList;
// zsmFiles:
end; // case FSourceMethod
if EverythingIsReady then
begin
//////////////////
// Set filetype //
//////////////////
if FImageProcessingMethods.FiletypeMethod = zftmPreserve then
iftFiletype := FileNameToImageFileType(FImageInformation.FileName)
else
iftFiletype := FFileInformation.ImageFileType;
for i := 0 to FFileInformation.Files.Count - 1 do
begin
if FContinueProcess and
DestinationIsGood(
CreateDestinationFilename(
FFileInformation.Root,
FFileInformation.OutputPath,
FFileInformation.Files.Strings[i],
ImageFileTypeToExtension(iftFiletype),
FFileInformation.Prefix,
FFileInformation.Suffix,
FImageProcessingMethods.SourceMethod)) then
begin
///////////////
// Load file //
///////////////
bBadFile := False;
///////////////////////////
// Create as proper type //
///////////////////////////
case FileNameToImageFileType(FFileInformation.Files.Strings[i]) of
ziftJPG:
imgImage := TJPEGImage.Create;
else
imgImage := TBitmap.Create;
end; // case FileNameToImageFileType(FFileInformation.Files.Strings[i])
try
try
imgImage.LoadFromFile(FFileInformation.Files.Strings[i]);
except
on E:EInvalidGraphic do
begin
LogBadFile(E.Message + ' - ' + FFileInformation.Files.Strings[i]);
bBadFile := True;
if Assigned(FSavingFile) then
FSavingFile(Self);
end; // EInvalidGraphic
on E:Exception do
Raise Exception.Create('Could not finish processing files: ' + E.Message);
end; // try..except
if not bBadFile then
begin
SetFileName(FFileInformation.Files.Strings[i]);
SetCurrentWidth(imgImage.Width);
SetCurrentHeight(imgImage.Height);
//////////////////////////
// Perform calculations //
//////////////////////////
CalculateImageDimensions;
//////////////////
// Resize image //
//////////////////
case iftFiletype of
ziftJPG:
begin
imgConverted := ResizeImageJPEG(imgImage, FImageInformation.ConvertedHeight, FImageInformation.ConvertedWidth);
DoCompressionSettings(imgConverted, imgConverted, iftFiletype);
end; // ziftJPG
// TODO: compression!
///////////////////////////
// Not implemented yet : //
///////////////////////////
{
ziftGIF:
ziftPNG:
}
else
///////////////////////
// Bitmap by default //
///////////////////////
// ziftBMP:
imgConverted := ResizeImageBMP(imgImage, FImageInformation.ConvertedHeight, FImageInformation.ConvertedWidth);
end; // case iftFiletype
try
///////////////
// Save file //
///////////////
SetDestination(CreateDestinationFilename(FFileInformation.Root,
FFileInformation.OutputPath,
FImageInformation.FileName,
ImageFileTypeToExtension(iftFiletype),
FFileInformation.Prefix,
FFileInformation.Suffix,
FImageProcessingMethods.SourceMethod));
PrepareOutputDirectory(FFileInformation.Destination);
if Assigned(FSavingFile) then
FSavingFile(Self);
try
imgConverted.SaveToFile(FFileInformation.Destination);
except on E:EOutOfResources do
Raise Exception.Create('Error while saving file: ' + E.Message);
end;
finally
FreeAndNil(imgConverted);
end; // imgConverted try..finally
end; // if not bBadFile
finally
FreeAndNil(imgImage);
end; // imgImage try..finally
end // if FContinueProcess and DestinationIsGood
else
begin
if Assigned(FSavingFile) then
FSavingFile(Self);
end; // if not (FContinueProcess and DestinationIsGood)
end; // for i := 0 to FFileInformation.Files.Count - 1
end; // if FFileInformation.Files.Count
if Assigned(FResizingEnded) then
FResizingEnded(Self);
if FBadFiles.Count > 0 then
Raise EInvalidGraphic.Create('Errors were detected with some files.');
end;
/////////////
// Getters //
/////////////
// Image Processing Methods
function TImageResizer.GetSourceMethod: TSourceMethod;
begin
Result := FImageProcessingMethods.SourceMethod;
end;
function TImageResizer.GetFiletypeMethod: TFiletypeMethod;
begin
Result := FImageProcessingMethods.FiletypeMethod;
end;
function TImageResizer.GetScalingMethod: TScalingMethod;
begin
Result := FImageProcessingMethods.ScalingMethod;
end;
function TImageResizer.GetFiletypeConversion: TFiletypeConversion;
begin
Result := FImageProcessingMethods.FiletypeConversion;
end;
function TImageResizer.GetFileHandling: TFileHandling;
begin
Result := FImageProcessingMethods.FileHandling;
end;
// File Information
function TImageResizer.GetRoot: String;
begin
Result := FFileInformation.Root;
end;
function TImageResizer.GetDirs: TStringList;
begin
Result := FFileInformation.Dirs;
end;
function TImageResizer.GetFiles: TStringList;
begin
Result := FFileInformation.Files;
end;
function TImageResizer.GetOutputPath: String;
begin
Result := FFileInformation.OutputPath;
end;
function TImageResizer.GetPrefix: String;
begin
Result := FFileInformation.Prefix;
end;
function TImageResizer.GetSuffix: String;
begin
Result := FFileInformation.Suffix;
end;
function TImageResizer.GetDestination: String;
begin
Result := FFileInformation.Destination;
end;
function TImageResizer.GetImageFileType: TImageFileType;
begin
Result := FFileInformation.ImageFileType;
end;
function TImageResizer.GetImageTypeSet: TImageTypeSet;
begin
Result := FFileInformation.ImageTypeSet;
end;
// Image Resizing Information
function TImageResizer.GetFileName: String;
begin
Result := FImageInformation.FileName;
end;
function TImageResizer.GetWidth: integer;
begin
Result := FImageInformation.Width;
end;
function TImageResizer.GetHeight: integer;
begin
Result := FImageInformation.Height;
end;
function TImageResizer.GetCurrentWidth: integer;
begin
Result := FImageInformation.CurrentWidth;
end;
function TImageResizer.GetCurrentHeight: integer;
begin
Result := FImageInformation.CurrentHeight;
end;
function TImageResizer.GetConvertedWidth: integer;
begin
Result := FImageInformation.ConvertedWidth;
end;
function TImageResizer.GetConvertedHeight: integer;
begin
Result := FImageInformation.ConvertedHeight;
end;
function TImageResizer.GetScale: real;
begin
Result := FImageInformation.Scale;
end;
function TImageResizer.GetCompressMethod: Boolean;
begin
Result := FImageInformation.CompressMethod;
end;
function TImageResizer.GetJPEGCompression: integer;
begin
Result := FImageInformation.JPEGCompression;
end;
/////////////
// Setters //
/////////////
// Image Processing Methods
procedure TImageResizer.SetSourceMethod(const Value: TSourceMethod);
begin
FImageProcessingMethods.SourceMethod := Value;
end;
procedure TImageResizer.SetFiletypeMethod(const Value: TFiletypeMethod);
begin
FImageProcessingMethods.FiletypeMethod := Value;
end;
procedure TImageResizer.SetScalingMethod(const Value: TScalingMethod);
begin
FImageProcessingMethods.ScalingMethod := Value;
end;
procedure TImageResizer.SetFiletypeConversion(
const Value: TFiletypeConversion);
begin
FImageProcessingMethods.FiletypeConversion := Value;
end;
procedure TImageResizer.SetFileHandling(const Value: TFileHandling);
begin
FImageProcessingMethods.FileHandling := Value;
end;
// File Information
procedure TImageResizer.SetRoot(const Value: String);
/////////////////////////////////////////////////////////////
// Preconditions : //
// Value is a valid directory //
// //
// Output : //
// FFileInformation.Root is assigned //
// FDirListCurrent and FFilesListCurrent are set to False //
/////////////////////////////////////////////////////////////
begin
FFileInformation.Root := Value;
FDirListCurrent := False;
FFilesListCurrent := False;
end;
procedure TImageResizer.SetDirs(const Value: TStringList);
begin
FFileInformation.Dirs := Value;
end;
procedure TImageResizer.SetFiles(const Value: TStringList);
//////////////////////////////////////////////////
// Preconditions : //
// Value has valid files as strings //
// //
// Output : //
// File lists are cleared //
// FFileInformation.Files is assigned to Value //
//////////////////////////////////////////////////
begin
ClearFilesList;
FFileInformation.Files := Value;
end;
procedure TImageResizer.SetOutputPath(const Value: String);
begin
FFileInformation.OutputPath := Value;
end;
procedure TImageResizer.SetPrefix(const Value: String);
begin
FFileInformation.Prefix := Value;
end;
procedure TImageResizer.SetSuffix(const Value: String);
begin
FFileInformation.Suffix := Value;
end;
procedure TImageResizer.SetDestination(const Value: String);
//////////////////////////////////////////////
// Preconditions : //
// sDestination has a valid, existing path //
// //
// Output : //
// FFileInformation.Destination is assigned //
// FDestinationSet is called //
//////////////////////////////////////////////
begin
FFileInformation.Destination := Value;
if Assigned(FDestinationSet) then
FDestinationSet(Self);
end;
procedure TImageResizer.SetImageFileType(const Value: TImageFileType);
begin
FFileInformation.ImageFileType := Value;
end;
procedure TImageResizer.SetImageTypeSet(const Value: TImageTypeSet);
begin
FFileInformation.ImageTypeSet := Value;
end;
// Image Resizing Information
procedure TImageResizer.SetCompressMethod(const Value: Boolean);
begin
FImageInformation.CompressMethod := Value;
end;
procedure TImageResizer.SetHeight(const Value: integer);
begin
FImageInformation.Height := Value;
end;
procedure TImageResizer.SetJPEGCompression(const Value: integer);
begin
FImageInformation.JPEGCompression := Value;
end;
procedure TImageResizer.SetWidth(const Value: integer);
begin
FImageInformation.Width := Value;
end;
end.
|
unit UserControl;
{/*
Модуль UserControl реализует интерфейс контроля в многопользовательской среде.
*/}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Process, pop3send, smtpsend, mimepart, mimemess,
mimeinln, SynaCode, Dialogs, SQLiteWrap, md5;
type
TFriendEntry = record
ID: Integer;
UUID,
NickName,
FirstName,
LastName,
Email: String;
end;
type
{ TUserList }
TUserList = class(TComponent)
private
fAuth: Boolean;
fUserId: Integer;
fNickName, fFirstName, fLastName, fEmail, fPassword :string;
database :TSqliteDatabase;
tab :TSqliteTable;
procedure CreateUserTables;
public
constructor Create (AOwner :TComponent); override;
destructor Destroy; override;
function RegisterUser (ANickName, AFirstName, ALastName, AEMail, APassword :string)
:boolean;
function ExistUser (AEMail :string) :boolean;
function LoginUser (AEMail, APassword :string) :boolean;
function GetCountUsers () :integer;
//function GetFriend(ID: Index): TFriendEntry;
function GetUsersList(): String;
function GetFriendList(): String;
function GetFriend(Index: Integer): TFriendEntry;
function GetFriendCount: Integer;
procedure AddContact (ANickName, AFirstName, ALastName, AEMail, AImgPath:string);
procedure AddMessage;
published
property IsAuthorized: Boolean read fAuth;
property UserId: Integer read FUserId;
property NickName: String read fNickName write fNickName;
property FirstName: String read fFirstName write fFirstName;
property LastName: String read fLastName write fLastName;
property EMail: String read fEMail write fEMail;
property Password: String read fPassword write fPassword;
end;
implementation
{ TUserList }
constructor TUserList.Create (AOwner :TComponent);
var
s :string;
begin
inherited Create (AOwner);
fAuth:= false;
database := TSqliteDatabase.Create ('crypto.db3');
CreateUserTables;
end;
////////////////////////////////////////////////////////////////////////////////
// РЕГИСТРАЦИЯ НОВОГО ПОЛЬЗОВАТЕЛЯ
////////////////////////////////////////////////////////////////////////////////
function TUserList.RegisterUser (ANickName, AFirstName, ALastName, AEMail,
APassword :string) :boolean;
var
sql :string;
Count :integer;
begin
Result := True;
try
// Если основные таблицы не созданы, создаём
CreateUserTables;
// Узнаём количество пользователей
try
Count := GetCountUsers () + 1;
except
Count := 1;
end;
// Проверяем есть ли уже такой пользователь
if not ExistUser (AEMail) then
begin
// Создаём пользователя
ShowMessage ('No user exsist');
sql := 'INSERT INTO USERS(ID_USER, NICK_NAME, FIRST_NAME, LAST_NAME, EMAIL, HASH) VALUES(';
sql += IntToStr (GetCountUsers () + 1) + ', ' + IntToStr(UserId) + ', ';
sql += '"' + ANickName + '", ';
sql += '"' + AFirstName + '", ';
sql += '"' + ALastName + '", ';
sql += '"' + AEMail + '", ';
sql += '"' + MD5Print (MD5String (APassword)) + '");';
database.ExecSQL (sql);
end;
except
Result := False;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// ЕСТЬ ЛИ ПОЛЬЗОВАТЕЛЬ С ТАКИМ ЭЛЕКТРОННЫМ АДРЕССОМ???
////////////////////////////////////////////////////////////////////////////////
function TUserList.ExistUser (AEMail :string) :boolean;
begin
Result := False;
try
//database.AddParamInt (':ID_USER', 1);
tab := database.GetTable ('SELECT EMAIL FROM USERS');
try
while not tab.EOF do
begin
if AEMail = tab.FieldAsString (tab.FieldIndex['EMAIL']) then
Result := True;
tab.Next;
end;
finally
tab.Free;
end;
finally
end;
end;
////////////////////////////////////////////////////////////////////////////////
// АВТОРИЗАЦИЯ ПОЛЬЗОВАТЕЛЯ
////////////////////////////////////////////////////////////////////////////////
function TUserList.LoginUser (AEMail, APassword :string) :boolean;
begin
Result := False;
try
tab := database.GetTable ('SELECT * FROM USERS');
try
while not tab.EOF do
begin
if (AEMail = tab.FieldAsString (tab.FieldIndex['EMAIL'])) and
(MD5Print (MD5String (APassword)) = tab.FieldAsString (
tab.FieldIndex['HASH'])) then
begin
fUserID := tab.FieldAsInteger(tab.FieldIndex['ID_USER']);
NickName := tab.FieldAsString (tab.FieldIndex['NICK_NAME']);
FirstName := tab.FieldAsString (tab.FieldIndex['FIRST_NAME']);
LastName := tab.FieldAsString (tab.FieldIndex['LAST_NAME']);
Email := AEMail;
Password := APassword;
Result := True;
fAuth := True;
end;
tab.Next;
end;
finally
tab.Free;
end;
finally
end;
end;
////////////////////////////////////////////////////////////////////////////////
// КОЛИЧЕСТВО ПОЛЬЗОВАТЕЛЕЙ ПРОГРАММЫ
////////////////////////////////////////////////////////////////////////////////
function TUserList.GetCountUsers :integer;
begin
Result := 0;
try
tab := database.GetTable ('SELECT * FROM USERS');
try
while not tab.EOF do
begin
Inc (Result, 1);
tab.Next;
end;
finally
tab.Free;
end;
except
raise Exception.Create ('Не могу узнать количество пользователей программы...');
end;
end;
function TUserList.GetFriend(Index: Integer): TFriendEntry;
begin
Result.ID:= -1;
try
tab := database.GetTable ('SELECT * FROM FRIENDS WHERE ID_FRIEND = '+ IntToStr(Index+1) +
' AND ID_USER = '+IntToStr(fUserId)); // fUserId
try
while not tab.EOF do
begin
Result.ID:= tab.FieldAsInteger (tab.FieldIndex['ID_FRIEND']);
Result.Email:= tab.FieldAsString (tab.FieldIndex['EMAIL']);
Result.FirstName:= tab.FieldAsString (tab.FieldIndex['FIRST_NAME']);
Result.LastName:= tab.FieldAsString (tab.FieldIndex['LAST_NAME']);
Result.NickName:= tab.FieldAsString (tab.FieldIndex['NICK_NAME']);
Result.UUID:= tab.FieldAsString (tab.FieldIndex['UUID']);
tab.Next;
end;
finally
tab.Free;
end;
except
raise Exception.Create ('Не могу найти пользователя...');
end;
end;
function TUserList.GetFriendCount: Integer;
begin
Result := -1;
try
tab := database.GetTable ('SELECT * FROM FRIENDS WHERE ID_USER = '+IntToStr(fUserId));
try
while not tab.EOF do
begin
Result+= 1;
tab.Next;
end;
finally
tab.Free;
end;
except
raise Exception.Create ('Не могу найти пользователя...');
end;
end;
////////////////////////////////////////////////////////////////////////////////
// ПОЛУЧИТЬ СПИСОК ПОЛЬЗОВАТЕЛЕЙ ПРОГРАММЫ
////////////////////////////////////////////////////////////////////////////////
function TUserList.GetUsersList: String;
begin
Result := '';
try
tab := database.GetTable ('SELECT * FROM USERS');
try
while not tab.EOF do
begin
Result+= tab.FieldAsString (tab.FieldIndex['EMAIL']) + #13 + #10;
tab.Next;
end;
finally
tab.Free;
end;
except
raise Exception.Create ('Не могу узнать список email адресов пользователей программы...');
end;
end;
////////////////////////////////////////////////////////////////////////////////
// ПОЛУЧИТЬ СПИСОК ДРУЗЕЙ
////////////////////////////////////////////////////////////////////////////////
function TUserList.GetFriendList: String;
begin
Result := '';
try
tab := database.GetTable ('SELECT * FROM FRIENDS');
try
while not tab.EOF do
begin
Result+= tab.FieldAsString (tab.FieldIndex['NICK_NAME']) + ' < ';
Result+= tab.FieldAsString (tab.FieldIndex['EMAIL']) + ' >' + #13 + #10;
tab.Next;
end;
finally
tab.Free;
end;
except
raise Exception.Create ('Не могу узнать список email адресов пользователей программы...');
end;
end;
procedure TUserList.AddContact(ANickName, AFirstName, ALastName, AEMail, AImgPath:string);
var
i :integer;
fSQL :string;
Res :HResult;
Uid :TGuid;
begin
i := 0;
Res := CreateGUID (Uid);
if Res = S_OK then
begin
try
tab := database.GetTable ('SELECT * FROM FRIENDS');
try
while not tab.EOF do
begin
Inc (i, 1);
tab.Next;
end;
finally
tab.Free;
end;
finally
end;
fSQL := 'INSERT INTO FRIENDS VALUES (' + IntToStr (i + 1) + ', ' +IntToStr (UserId) +
', "' + GUIDToString (Uid) + '", "' + ANickName + '", "' +
AFirstName + '", "' + ALastName + '", "' + AEMail + '", "");';
//ShowMessage(fSQL);
database.ExecSQL (fSQl);
end
else
raise Exception.Create ('Не могу добавить вашего друга в контакт лист...');
end;
procedure TUserList.AddMessage;
begin
end;
////////////////////////////////////////////////////////////////////////////////
// СОЗДАНИЕ ОСНОВНЫХ ТАБЛИЦ
////////////////////////////////////////////////////////////////////////////////
procedure TUserList.CreateUserTables;
begin
// Таблица users
database.ExecSQL ('CREATE TABLE IF NOT EXISTS USERS(ID_USER INTEGER, NICK_NAME, FIRST_NAME, '
+ 'LAST_NAME, EMAIL, HASH TEXT, AVATAR BLOB, PRIMARY KEY(ID_USER));');
// Таблица friends
database.ExecSQL ('CREATE TABLE IF NOT EXISTS FRIENDS(ID_FRIEND, ID_USER INTEGER, UUID, ' +
'NICK_NAME, FIRST_NAME, LAST_NAME, EMAIL TEXT, AVATAR BLOB, PRIMARY KEY(ID_FRIEND), FOREIGN KEY (ID_USER) REFERENCES USERS(ID_USER));');
// Таблица messages
database.ExecSQL ('CREATE TABLE IF NOT EXISTS MESSAGES(ID_FRIEND INTEGER,' +
'RDATE DATE, RTIME TIME, XID INTEGER, ISMYMSG BOOLEAN, OPEN_KEY BLOB, SECRET_KEY BLOB,'+
'MESSAGE BLOB, ZIP_FILES, FOREIGN KEY (ID_FRIEND) REFERENCES FRIENDS(ID));');
end;
destructor TUserList.Destroy;
begin
database.Free;
inherited Destroy;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.