text stringlengths 14 6.51M |
|---|
unit FFindFile;
(*====================================================================
Progress window for finding a file, implements the search in the
Run procedure
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
Grids, ComCtrls, {CustomDrawnControls,} ATGauge,
UTypes, UApiTypes;
type
{ TFormSearchName }
TFormSearchName = class(TForm)
Gauge1: TGauge;
Label1: TLabel;
LabelSearched: TLabel;
Label2: TLabel;
LabelFound: TLabel;
ButtonStop: TButton;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure ButtonStopClick(Sender: TObject);
private
CanRun : boolean;
public
StopIt : boolean;
DBaseHandle: PDBaseHandle;
procedure Run(var Info); message WM_User + 101;
procedure UpdateCounters;
procedure DefaultHandler(var Message); override;
end;
var
FormSearchName: TFormSearchName;
implementation
uses FFindFileDlg, UApi, UBaseTypes, ULang, FSettings, customdrawn_common;
{$R *.dfm}
//-----------------------------------------------------------------------------
procedure CallBackWhenChange(var Stop: boolean); far;
begin
FormSearchName.UpdateCounters;
Application.ProcessMessages;
Stop := FormSearchName.StopIt;
end;
//-----------------------------------------------------------------------------
procedure TFormSearchName.FormCreate(Sender: TObject);
begin
CanRun := false;
end;
//-----------------------------------------------------------------------------
procedure TFormSearchName.FormActivate(Sender: TObject);
begin
StopIt := false;
CanRun := true;
// This executes the Run procedure after the window is shown
PostMessage(Self.Handle, WM_User + 101, 0, 0);
end;
//-----------------------------------------------------------------------------
procedure TFormSearchName.ButtonStopClick(Sender: TObject);
begin
StopIt := true;
CanRun := false;
if QI_SearchItemsAvail(DBaseHandle)
then ModalResult := mrOK
else ModalResult := mrCancel;
end;
//-----------------------------------------------------------------------------
procedure TFormSearchName.Run (var Info);
var
Success: boolean;
begin
if not CanRun then exit;
CanRun := false;
Success := false;
try
QI_ClearTreeStruct(DBaseHandle);
QI_ClearSearchCol (DBaseHandle);
QI_SetSearchCallback(DBaseHandle, CallBackWhenChange);
QI_FindFiles(DBaseHandle, FormSearchFileDlg.DlgData);
QI_DelSearchCallback(DBaseHandle);
Success := true;
if not QI_SearchItemsAvail(DBaseHandle) then
begin
Application.MessageBox(lsNoFileFound,
lsInformation, mb_OK or mb_IconInformation);
Success := false;
end;
finally
if Success
then ModalResult := mrOk
else ModalResult := mrCancel;
end;
end;
//-----------------------------------------------------------------------------
procedure TFormSearchName.UpdateCounters;
var
Percent: Integer;
DisksCount, DirsCount, FilesCount: longint;
begin
QI_GetSearchProgress (DBaseHandle, Percent, DisksCount, DirsCount, FilesCount);
LabelSearched.Caption := IntToStr(DisksCount) + '/' + IntToStr(FilesCount);
LabelFound.Caption := IntToStr(QI_GetFoundCount (DBaseHandle));
Gauge1.Progress := Percent;
//Gauge1.Position:=Percent;
end;
//-----------------------------------------------------------------------------
// Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay
// to the top window, so we must have this handler in all forms.
procedure TFormSearchName.DefaultHandler(var Message);
begin
with TMessage(Message) do
if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and
g_CommonOptions.bDisableCdAutorun
then
Result := 1
else
inherited DefaultHandler(Message)
end;
//-----------------------------------------------------------------------------
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* 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.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFCommandLine;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
uCEFBaseRefCounted, uCEFTypes, uCEFInterfaces;
type
TCefCommandLineRef = class(TCefBaseRefCountedRef, ICefCommandLine)
protected
function IsValid: Boolean;
function IsReadOnly: Boolean;
function Copy: ICefCommandLine;
procedure InitFromArgv(argc: Integer; const argv: PPAnsiChar);
procedure InitFromString(const commandLine: ustring);
procedure Reset;
function GetCommandLineString: ustring;
procedure GetArgv(args: TStrings);
function GetProgram: ustring;
procedure SetProgram(const prog: ustring);
function HasSwitches: Boolean;
function HasSwitch(const name: ustring): Boolean;
function GetSwitchValue(const name: ustring): ustring;
procedure GetSwitches(switches: TStrings);
procedure AppendSwitch(const name: ustring);
procedure AppendSwitchWithValue(const name, value: ustring);
function HasArguments: Boolean;
procedure GetArguments(arguments: TStrings);
procedure AppendArgument(const argument: ustring);
procedure PrependWrapper(const wrapper: ustring);
public
class function UnWrap(data: Pointer): ICefCommandLine;
class function New: ICefCommandLine;
class function Global: ICefCommandLine;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions;
procedure TCefCommandLineRef.AppendArgument(const argument: ustring);
var
a: TCefString;
begin
a := CefString(argument);
PCefCommandLine(FData).append_argument(PCefCommandLine(FData), @a);
end;
procedure TCefCommandLineRef.AppendSwitch(const name: ustring);
var
n: TCefString;
begin
n := CefString(name);
PCefCommandLine(FData).append_switch(PCefCommandLine(FData), @n);
end;
procedure TCefCommandLineRef.AppendSwitchWithValue(const name, value: ustring);
var
n, v: TCefString;
begin
n := CefString(name);
v := CefString(value);
PCefCommandLine(FData).append_switch_with_value(PCefCommandLine(FData), @n, @v);
end;
function TCefCommandLineRef.Copy: ICefCommandLine;
begin
Result := UnWrap(PCefCommandLine(FData).copy(PCefCommandLine(FData)));
end;
procedure TCefCommandLineRef.GetArguments(arguments: TStrings);
var
list: TCefStringList;
i: Integer;
str: TCefString;
begin
list := cef_string_list_alloc;
try
PCefCommandLine(FData).get_arguments(PCefCommandLine(FData), list);
for i := 0 to cef_string_list_size(list) - 1 do
begin
FillChar(str, SizeOf(str), 0);
cef_string_list_value(list, i, @str);
arguments.Add(CefStringClearAndGet(str));
end;
finally
cef_string_list_free(list);
end;
end;
procedure TCefCommandLineRef.GetArgv(args: TStrings);
var
list: TCefStringList;
i: Integer;
str: TCefString;
begin
list := cef_string_list_alloc;
try
PCefCommandLine(FData).get_argv(FData, list);
for i := 0 to cef_string_list_size(list) - 1 do
begin
FillChar(str, SizeOf(str), 0);
cef_string_list_value(list, i, @str);
args.Add(CefStringClearAndGet(str));
end;
finally
cef_string_list_free(list);
end;
end;
function TCefCommandLineRef.GetCommandLineString: ustring;
begin
Result := CefStringFreeAndGet(PCefCommandLine(FData).get_command_line_string(PCefCommandLine(FData)));
end;
function TCefCommandLineRef.GetProgram: ustring;
begin
Result := CefStringFreeAndGet(PCefCommandLine(FData).get_program(PCefCommandLine(FData)));
end;
procedure TCefCommandLineRef.GetSwitches(switches: TStrings);
var
list: TCefStringList;
i: Integer;
str: TCefString;
begin
list := cef_string_list_alloc;
try
PCefCommandLine(FData).get_switches(PCefCommandLine(FData), list);
for i := 0 to cef_string_list_size(list) - 1 do
begin
FillChar(str, SizeOf(str), 0);
cef_string_list_value(list, i, @str);
switches.Add(CefStringClearAndGet(str));
end;
finally
cef_string_list_free(list);
end;
end;
function TCefCommandLineRef.GetSwitchValue(const name: ustring): ustring;
var
n: TCefString;
begin
n := CefString(name);
Result := CefStringFreeAndGet(PCefCommandLine(FData).get_switch_value(PCefCommandLine(FData), @n));
end;
class function TCefCommandLineRef.Global: ICefCommandLine;
begin
Result := UnWrap(cef_command_line_get_global);
end;
function TCefCommandLineRef.HasArguments: Boolean;
begin
Result := PCefCommandLine(FData).has_arguments(PCefCommandLine(FData)) <> 0;
end;
function TCefCommandLineRef.HasSwitch(const name: ustring): Boolean;
var
n: TCefString;
begin
n := CefString(name);
Result := PCefCommandLine(FData).has_switch(PCefCommandLine(FData), @n) <> 0;
end;
function TCefCommandLineRef.HasSwitches: Boolean;
begin
Result := PCefCommandLine(FData).has_switches(PCefCommandLine(FData)) <> 0;
end;
procedure TCefCommandLineRef.InitFromArgv(argc: Integer;
const argv: PPAnsiChar);
begin
PCefCommandLine(FData).init_from_argv(PCefCommandLine(FData), argc, argv);
end;
procedure TCefCommandLineRef.InitFromString(const commandLine: ustring);
var
cl: TCefString;
begin
cl := CefString(commandLine);
PCefCommandLine(FData).init_from_string(PCefCommandLine(FData), @cl);
end;
function TCefCommandLineRef.IsReadOnly: Boolean;
begin
Result := PCefCommandLine(FData).is_read_only(PCefCommandLine(FData)) <> 0;
end;
function TCefCommandLineRef.IsValid: Boolean;
begin
Result := PCefCommandLine(FData).is_valid(PCefCommandLine(FData)) <> 0;
end;
class function TCefCommandLineRef.New: ICefCommandLine;
begin
Result := UnWrap(cef_command_line_create);
end;
procedure TCefCommandLineRef.PrependWrapper(const wrapper: ustring);
var
w: TCefString;
begin
w := CefString(wrapper);
PCefCommandLine(FData).prepend_wrapper(PCefCommandLine(FData), @w);
end;
procedure TCefCommandLineRef.Reset;
begin
PCefCommandLine(FData).reset(PCefCommandLine(FData));
end;
procedure TCefCommandLineRef.SetProgram(const prog: ustring);
var
p: TCefString;
begin
p := CefString(prog);
PCefCommandLine(FData).set_program(PCefCommandLine(FData), @p);
end;
class function TCefCommandLineRef.UnWrap(data: Pointer): ICefCommandLine;
begin
if data <> nil then
Result := Create(data) as ICefCommandLine else
Result := nil;
end;
end.
|
//
// Generated by JavaToPas v1.5 20150830 - 103229
////////////////////////////////////////////////////////////////////////////////
unit org.apache.http.message.BasicLineFormatter;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
org.apache.http.util.ByteArrayBuffer,
org.apache.http.ProtocolVersion,
org.apache.http.message.LineFormatter,
org.apache.http.RequestLine,
org.apache.http.StatusLine,
org.apache.http.Header;
type
JBasicLineFormatter = interface;
JBasicLineFormatterClass = interface(JObjectClass)
['{435D5BE5-1634-46A9-BC0F-04D68BE808DA}']
function _GetDEFAULT : JBasicLineFormatter; cdecl; // A: $19
function appendProtocolVersion(buffer : JCharArrayBuffer; version : JProtocolVersion) : JCharArrayBuffer; cdecl;// (Lorg/apache/http/util/CharArrayBuffer;Lorg/apache/http/ProtocolVersion;)Lorg/apache/http/util/CharArrayBuffer; A: $1
function formatHeader(buffer : JCharArrayBuffer; header : JHeader) : JCharArrayBuffer; cdecl; overload;// (Lorg/apache/http/util/CharArrayBuffer;Lorg/apache/http/Header;)Lorg/apache/http/util/CharArrayBuffer; A: $1
function formatHeader(header : JHeader; formatter : JLineFormatter) : JString; cdecl; overload;// (Lorg/apache/http/Header;Lorg/apache/http/message/LineFormatter;)Ljava/lang/String; A: $19
function formatProtocolVersion(version : JProtocolVersion; formatter : JLineFormatter) : JString; cdecl;// (Lorg/apache/http/ProtocolVersion;Lorg/apache/http/message/LineFormatter;)Ljava/lang/String; A: $19
function formatRequestLine(buffer : JCharArrayBuffer; reqline : JRequestLine) : JCharArrayBuffer; cdecl; overload;// (Lorg/apache/http/util/CharArrayBuffer;Lorg/apache/http/RequestLine;)Lorg/apache/http/util/CharArrayBuffer; A: $1
function formatRequestLine(reqline : JRequestLine; formatter : JLineFormatter) : JString; cdecl; overload;// (Lorg/apache/http/RequestLine;Lorg/apache/http/message/LineFormatter;)Ljava/lang/String; A: $19
function formatStatusLine(buffer : JCharArrayBuffer; statline : JStatusLine) : JCharArrayBuffer; cdecl; overload;// (Lorg/apache/http/util/CharArrayBuffer;Lorg/apache/http/StatusLine;)Lorg/apache/http/util/CharArrayBuffer; A: $1
function formatStatusLine(statline : JStatusLine; formatter : JLineFormatter) : JString; cdecl; overload;// (Lorg/apache/http/StatusLine;Lorg/apache/http/message/LineFormatter;)Ljava/lang/String; A: $19
function init : JBasicLineFormatter; cdecl; // ()V A: $1
property &DEFAULT : JBasicLineFormatter read _GetDEFAULT; // Lorg/apache/http/message/BasicLineFormatter; A: $19
end;
[JavaSignature('org/apache/http/message/BasicLineFormatter')]
JBasicLineFormatter = interface(JObject)
['{7CFC3134-F564-4044-BD57-A239E851E03A}']
function appendProtocolVersion(buffer : JCharArrayBuffer; version : JProtocolVersion) : JCharArrayBuffer; cdecl;// (Lorg/apache/http/util/CharArrayBuffer;Lorg/apache/http/ProtocolVersion;)Lorg/apache/http/util/CharArrayBuffer; A: $1
function formatHeader(buffer : JCharArrayBuffer; header : JHeader) : JCharArrayBuffer; cdecl; overload;// (Lorg/apache/http/util/CharArrayBuffer;Lorg/apache/http/Header;)Lorg/apache/http/util/CharArrayBuffer; A: $1
function formatRequestLine(buffer : JCharArrayBuffer; reqline : JRequestLine) : JCharArrayBuffer; cdecl; overload;// (Lorg/apache/http/util/CharArrayBuffer;Lorg/apache/http/RequestLine;)Lorg/apache/http/util/CharArrayBuffer; A: $1
function formatStatusLine(buffer : JCharArrayBuffer; statline : JStatusLine) : JCharArrayBuffer; cdecl; overload;// (Lorg/apache/http/util/CharArrayBuffer;Lorg/apache/http/StatusLine;)Lorg/apache/http/util/CharArrayBuffer; A: $1
end;
TJBasicLineFormatter = class(TJavaGenericImport<JBasicLineFormatterClass, JBasicLineFormatter>)
end;
implementation
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: Text3Dunit.pas,v 1.14 2007/02/05 22:21:13 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: Text3D.cpp
//
// Desc: Example code showing how to do text in a Direct3D scene.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit Text3Dunit;
interface
uses
Windows, Messages, SysUtils, StrSafe,{$IFNDEF FPC} CommDlg,{$ENDIF}
DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTSettingsDlg;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pTextSprite: ID3DXSprite = nil; // Sprite for batching draw text calls
g_Camera: CFirstPersonCamera; // A model viewing camera
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
g_pFont: ID3DXFont = nil;
g_pFont2: ID3DXFont = nil;
g_pStatsFont: ID3DXFont = nil;
g_pMesh3DText: ID3DXMesh = nil;
g_strTextBuffer: PWideChar = nil;
g_strFont: array[0..LF_FACESIZE-1] of WideChar;
g_nFontSize: Integer;
g_matObj1: TD3DXMatrixA16;
g_matObj2: TD3DXMatrixA16;
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_CHANGEFONT = 5;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
function CreateD3DXTextMesh(const pd3dDevice: IDirect3DDevice9; out ppMesh: ID3DXMesh; pstrFont: PWideChar; dwSize: DWORD; bBold, bItalic: Boolean): HRESULT;
//function CreateD3DXFont(out ppd3dxFont: ID3DXFont; pstrFont: PWideChar; dwSize: DWORD): HRESULT;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
const
IDR_TXT = 102;
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
rsrc: HRSRC;
hgData: HGLOBAL;
pvData: Pointer;
cbData: DWORD;
nSize: Integer;
iY: Integer;
begin
StringCchCopy(g_strFont, 32, 'Arial');
rsrc := FindResource(0, MAKEINTRESOURCE(IDR_TXT), 'TEXT');
if (rsrc <> 0) then
begin
cbData := SizeofResource(0, rsrc);
if (cbData > 0) then
begin
hgData := LoadResource(0, rsrc);
if (hgData <> 0) then
begin
pvData := LockResource(hgData);
if (pvData <> nil) then
begin
nSize := cbData div SizeOf(WideChar) + 1;
GetMem(g_strTextBuffer, SizeOf(WideChar)*nSize);
CopyMemory(g_strTextBuffer, pvData, cbData);
g_strTextBuffer[nSize-1] := #0;
end;
end;
end;
end;
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent);
iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2);
g_SampleUI.SetCallback(OnGUIEvent);
iY := 10; g_SampleUI.AddButton(IDC_CHANGEFONT, 'Change Font', 35, iY, 125, 22);
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result := False;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
Result := True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(1,1))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
hDC: Windows.HDC;
nLogPixelsY: Integer;
nHeight: Integer;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
hDC := GetDC(0);
nLogPixelsY := GetDeviceCaps(hDC, LOGPIXELSY);
ReleaseDC(0, hDC);
nHeight := -g_nFontSize * nLogPixelsY div 72;
Result := D3DXCreateFontW(pd3dDevice, // D3D device
nHeight, // Height
0, // Width
FW_BOLD, // Weight
1, // MipLevels, 0 = autogen mipmaps
FALSE, // Italic
DEFAULT_CHARSET, // CharSet
OUT_DEFAULT_PRECIS, // OutputPrecision
DEFAULT_QUALITY, // Quality
DEFAULT_PITCH or FF_DONTCARE, // PitchAndFamily
g_strFont, // pFaceName
g_pFont); // ppFont
if Failed(Result) then Exit;
Result := D3DXCreateFontW(pd3dDevice, -12, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'System', g_pFont2);
if Failed(Result) then Exit;
Result := D3DXCreateFontW(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pStatsFont);
if Failed(Result) then Exit;
Result := D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if Failed(Result) then Exit;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
light: TD3DLight9;
vecLightDirUnnormalized: TD3DXVector3;
matWorld: TD3DXMatrixA16;
vecEye: TD3DXVector3;
vecAt: TD3DXVector3;
fAspectRatio: Single;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation( pBackBufferSurfaceDesc.Width-170, pBackBufferSurfaceDesc.Height-350);
g_SampleUI.SetSize(170, 300);
// Restore the fonts
g_pStatsFont.OnResetDevice;
g_pFont.OnResetDevice;
g_pFont2.OnResetDevice;
g_pTextSprite.OnResetDevice;
// Restore the textures
pd3dDevice.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pd3dDevice.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
pd3dDevice.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
pd3dDevice.SetRenderState(D3DRS_ZENABLE, iTrue);
pd3dDevice.SetRenderState(D3DRS_DITHERENABLE, iTrue);
pd3dDevice.SetRenderState(D3DRS_SPECULARENABLE, iTrue);
pd3dDevice.SetRenderState(D3DRS_LIGHTING, iTrue);
pd3dDevice.SetRenderState(D3DRS_AMBIENT, $80808080);
vecLightDirUnnormalized := D3DXVector3(10.0, -10.0, 10.0);
FillChar(light, SizeOf(TD3DLight9), #0);
light._Type := D3DLIGHT_DIRECTIONAL;
light.Diffuse.r := 1.0;
light.Diffuse.g := 1.0;
light.Diffuse.b := 1.0;
D3DXVec3Normalize(light.Direction, vecLightDirUnnormalized);
light.Position.x := 10.0;
light.Position.y := -10.0;
light.Position.z := 10.0;
light.Range := 1000.0;
pd3dDevice.SetLight(0, light);
pd3dDevice.LightEnable(0, True);
// Set the transform matrices
D3DXMatrixIdentity(matWorld);
pd3dDevice.SetTransform(D3DTS_WORLD, matWorld);
// Setup the camera with view & projection matrix
vecEye := D3DXVector3(0.0,-5.0, -10.0);
vecAt := D3DXVector3(0.2, 0.0, 0.0);
g_Camera.SetViewParams(vecEye, vecAt);
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 1.0, 1000.0);
SAFE_RELEASE(g_pMesh3DText);
Result:= CreateD3DXTextMesh(pd3dDevice, g_pMesh3DText, g_strFont, g_nFontSize, False, False);
if FAILED(Result) then
begin
Result:= E_FAIL;
Exit;
end;
Result:= S_OK;
end;
const
IsBold: array[False..True] of Integer = (FW_NORMAL, FW_BOLD);
//-----------------------------------------------------------------------------
// Name: CreateD3DXTextMesh()
// Desc:
//-----------------------------------------------------------------------------
function CreateD3DXTextMesh(const pd3dDevice: IDirect3DDevice9; out ppMesh: ID3DXMesh; pstrFont: PWideChar; dwSize: DWORD; bBold, bItalic: Boolean): HRESULT;
var
pMeshNew: ID3DXMesh;
hdc: Windows.HDC;
nHeight: Integer;
hFont: Windows.HFONT;
hFontOld: Windows.HFONT;
begin
hdc := CreateCompatibleDC(0);
if (hdc = 0) then
begin
Result:= E_OUTOFMEMORY;
Exit;
end;
nHeight := -MulDiv(dwSize, GetDeviceCaps(hdc, LOGPIXELSY), 72);
hFont := CreateFontW(nHeight, 0, 0, 0, IsBold[bBold], Cardinal(bItalic), iFalse, iFalse, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE, pstrFont);
hFontOld := SelectObject(hdc, hFont);
Result := D3DXCreateText(pd3dDevice, hdc, 'This is calling D3DXCreateText',
0.001, 0.4, pMeshNew, nil, nil);
SelectObject(hdc, hFontOld);
DeleteObject(hFont);
DeleteDC(hdc);
if SUCCEEDED(Result) then ppMesh := pMeshNew;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
vAxis1: TD3DXVector3;
vAxis2: TD3DXVector3;
mScale: TD3DXMatrix;
begin
// Setup five rotation matrices (for rotating text strings)
vAxis1 := D3DXVector3(1.0, 2.0, 0.0);
vAxis2 := D3DXVector3(1.0, 0.0, 0.0);
D3DXMatrixRotationAxis(g_matObj1, vAxis1, fTime / 2.0);
D3DXMatrixRotationAxis(g_matObj2, vAxis2, fTime);
D3DXMatrixScaling(mScale, 0.5, 0.5, 0.5);
// g_matObj2 := g_matObj2 * mScale;
D3DXMatrixMultiply(g_matObj2, g_matObj2, mScale);
// Add some translational values to the matrices
g_matObj1._41 := 1.0; g_matObj1._42 := 6.0; g_matObj1._43 := 20.0;
g_matObj2._41 := -4.0; g_matObj2._42 := -1.0; g_matObj2._43 := 0.0;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
rc: TRect;
mtrl: TD3DMaterial9;
matView: TD3DXMatrixA16;
matProj: TD3DXMatrixA16;
matViewProj: TD3DXMatrixA16;
nHeight: LongWord;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Get the view & projection matrix from camera.
// User can't control camera for this simple sample
matView := g_Camera.GetViewMatrix^;
matProj := g_Camera.GetProjMatrix^;
// matViewProj := matView * matProj;
D3DXMatrixMultiply(matViewProj, matView, matProj);
pd3dDevice.SetTransform(D3DTS_VIEW, matView);
pd3dDevice.SetTransform(D3DTS_PROJECTION, matProj);
// Clear the viewport
pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, $00000000, 1.0, 0);
// Begin the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
nHeight := DXUTGetPresentParameters.BackBufferHeight;
DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Demonstration Code');
// Demonstration 1:
// Draw a simple line using ID3DXFont::DrawText
begin
// CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Demonstration Part 1");
DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Demonstration Part 1');
{$ifNdef 1}
// Pass in DT_NOCLIP so we don't have to calc the bottom/right of the rect
SetRect(rc, 150, 200, 0, 0);
g_pFont.DrawTextA(nil, 'This is a trivial call to ID3DXFont.DrawText', -1, @rc, DT_NOCLIP, D3DXColorToDWord(D3DXColor(1.0, 0.0, 0.0, 1.0)));
{$ELSE}
// If you wanted to calc the bottom/rect of the rect make these 2 calls
SetRect(rc, 150, 200, 0, 0);
g_pFont.DrawTextA(nil, 'This is a trivial call to ID3DXFont.DrawText', -1, @rc, DT_CALCRECT, D3DXColorToDWord(D3DXColor(1.0, 0.0, 0.0, 1.0)));
g_pFont.DrawTextA(nil, 'This is a trivial call to ID3DXFont.DrawText', -1, @rc, 0, D3DXColorToDWord(D3DXColor(1.0, 0.0, 0.0, 1.0)));
{$ENDIF}
DXUT_EndPerfEvent;
end;
// Demonstration 2:
// Allow multiple draw calls to sort by texture changes by ID3DXSprite
// When drawing 2D text use flags: D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_TEXTURE
// When drawing 3D text use flags: D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_BACKTOFRONT
begin
// CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Demonstration Part 2" );
DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Demonstration Part 2');
g_pTextSprite._Begin(D3DXSPRITE_ALPHABLEND or D3DXSPRITE_SORT_TEXTURE);
SetRect(rc, 10, nHeight - 15*6, 0, 0);
g_pFont2.DrawTextA(g_pTextSprite, 'These multiple calls to ID3DXFont::DrawText using the same ID3DXSprite.', -1, @rc, DT_NOCLIP, D3DXColorToDWord(D3DXColor(1.0, 1.0, 1.0, 1.0)));
SetRect(rc, 10, nHeight - 15*5, 0, 0);
g_pFont2.DrawTextA(g_pTextSprite, 'ID3DXFont now caches letters on one or more textures.', -1, @rc, DT_NOCLIP, D3DXColorToDWord(D3DXColor(1.0, 1.0, 1.0, 1.0)));
SetRect(rc, 10, nHeight - 15*4, 0, 0);
g_pFont2.DrawTextA(g_pTextSprite, 'In order to sort by texture state changes on multiple', -1, @rc, DT_NOCLIP, D3DXColorToDWord(D3DXColor(1.0, 1.0, 1.0, 1.0)));
SetRect(rc, 10, nHeight - 15*3, 0, 0);
g_pFont2.DrawTextA(g_pTextSprite, 'draw calls to DrawText pass a ID3DXSprite and use', -1, @rc, DT_NOCLIP, D3DXColorToDWord(D3DXColor(1.0, 1.0, 1.0, 1.0)));
SetRect(rc, 10, nHeight - 15*2, 0, 0);
g_pFont2.DrawTextA(g_pTextSprite, 'flags D3DXSPRITE_ALPHABLEND or D3DXSPRITE_SORT_TEXTURE', -1, @rc, DT_NOCLIP, D3DXColorToDWord(D3DXColor(1.0, 1.0, 1.0, 1.0)));
g_pTextSprite._End;
DXUT_EndPerfEvent;
end;
// Demonstration 3:
// Word wrapping and unicode text.
// Note that not all fonts support dynamic font linking.
begin
// CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Demonstration Part 3" );
DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Demonstration Part 3');
rc.left := 10;
rc.top := 60;
rc.right := DXUTGetPresentParameters.BackBufferWidth - 150;
rc.bottom := DXUTGetPresentParameters.BackBufferHeight - 10;
g_pFont2.DrawTextW(nil, g_strTextBuffer, -1, @rc, DT_LEFT or DT_WORDBREAK or DT_EXPANDTABS, D3DXColorToDWord(D3DXColor(1.0, 0.0, 1.0, 1.0)));
DXUT_EndPerfEvent;
end;
// Demonstration 4:
// Draw 3D extruded text using a mesh created with D3DXFont
if (g_pMesh3DText <> nil) then
begin
// CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Demonstration Part 4" );
DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Demonstration Part 4');
ZeroMemory( @mtrl, SizeOf(D3DMATERIAL9));
mtrl.Diffuse.r := 0.0; mtrl.Ambient.r := 0.0;
mtrl.Diffuse.g := 0.0; mtrl.Ambient.g := 0.0;
mtrl.Diffuse.b := 1.0; mtrl.Ambient.b := 1.0;
mtrl.Diffuse.a := 1.0; mtrl.Ambient.a := 1.0;
pd3dDevice.SetMaterial(mtrl);
pd3dDevice.SetTransform(D3DTS_WORLD, g_matObj2);
g_pMesh3DText.DrawSubset(0);
DXUT_EndPerfEvent;
end;
DXUT_EndPerfEvent; // end of demonstration code
begin
// CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"HUD / Stats" );
DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'HUD / Stats');
V(g_HUD.OnRender(fElapsedTime));
V(g_SampleUI.OnRender(fElapsedTime));
// Show frame rate
SetRect(rc, 2, 0, 0, 0);
g_pStatsFont.DrawTextW(nil, DXUTGetFrameStats, -1, @rc, DT_NOCLIP, D3DXColorToDWord(D3DXColor(1.0, 1.0, 0.0, 1.0)));
SetRect(rc, 2, 15, 0, 0);
g_pStatsFont.DrawTextW(nil, DXUTGetDeviceStats, -1, @rc, DT_NOCLIP, D3DXColorToDWord(D3DXColor(1.0, 1.0, 0.0, 1.0)));
end;
// End the scene
pd3dDevice.EndScene;
end;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
case uMsg of
WM_SIZE:
begin
if (SIZE_RESTORED = wParam) then
begin
// if( !g_bMaximized && !g_bMinimized )
begin
// This sample demonstrates word wrapping, so if the
// window size is changing because the user dragging the window
// edges we'll recalc the size, re-init, and repaint
// the scene as the window resizes. This would be very
// slow for complex scene but works here since this sample
// is trivial.
(* HandlePossibleSizeChange();
// Repaint the window
if( g_pd3dDevice && !g_bActive && g_bWindowed &&
g_bDeviceObjectsInited && g_bDeviceObjectsRestored )
{
HRESULT hr;
Render();
hr = g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
if( D3DERR_DEVICELOST == hr )
g_bDeviceLost = true;
}*)
end;
end;
end;
end;
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
{$IFDEF FPC}
type
//todo -cFPC: remove PLogFontW definition after stable 1.9.7 is released
PLogFontW = ^TLogFontW;
LOGFONTW = record
lfHeight: LONG;
lfWidth: LONG;
lfEscapement: LONG;
lfOrientation: LONG;
lfWeight: LONG;
lfItalic: BYTE;
lfUnderline: BYTE;
lfStrikeOut: BYTE;
lfCharSet: BYTE;
lfOutPrecision: BYTE;
lfClipPrecision: BYTE;
lfQuality: BYTE;
lfPitchAndFamily: BYTE;
lfFaceName: array [0..LF_FACESIZE - 1] of WCHAR;
end;
LPLOGFONTW = ^LOGFONTW;
NPLOGFONTW = ^LOGFONTW;
TLogFontW = LOGFONTW;
tagCHOOSEFONTW = packed record
lStructSize: DWORD;
hWndOwner: HWnd; { caller's window handle }
hDC: HDC; { printer DC/IC or nil }
lpLogFont: PLogFontW; { pointer to a LOGFONT struct }
iPointSize: Integer; { 10 * size in points of selected font }
Flags: DWORD; { dialog flags }
rgbColors: COLORREF; { returned text color }
lCustData: LPARAM; { data passed to hook function }
lpfnHook: function(Wnd: HWND; Message: UINT; wParam: WPARAM; lParam: LPARAM): UINT; stdcall;
{ pointer to hook function }
lpTemplateName: PWideChar; { custom template name }
hInstance: HINST; { instance handle of EXE that contains
custom dialog template }
lpszStyle: PWideChar; { return the style field here
must be lf_FaceSize or bigger }
nFontType: Word; { same value reported to the EnumFonts
call back with the extra fonttype_
bits added }
wReserved: Word;
nSizeMin: Integer; { minimum point size allowed and }
nSizeMax: Integer; { maximum point size allowed if
cf_LimitSize is used }
end;
TChooseFontW = tagCHOOSEFONTW;
{$ENDIF}
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
var
bWindowed: Boolean;
hdc: Windows.HDC;
lHeight: Longint;
lf: TLogFontW;
cf: TChooseFontW;
pFontNew: ID3DXFont;
pMesh3DTextNew: ID3DXMesh;
pstrFontNameNew: PWideChar;
dwFontSizeNew: Integer;
bSuccess: Boolean;
bBold, bItalic: Boolean;
nLogPixelsY: Integer;
nHeight: Integer;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_CHANGEFONT:
begin
bWindowed := DXUTIsWindowed;
if not bWindowed then DXUTToggleFullScreen;
hdc := GetDC(DXUTGetHWND);
lHeight := -MulDiv(g_nFontSize, GetDeviceCaps(hdc, LOGPIXELSY), 72);
ReleaseDC(DXUTGetHWND, hdc);
StringCchCopy(lf.lfFaceName, 32, g_strFont);
lf.lfHeight := lHeight;
FillChar(cf, SizeOf(cf), #0);
cf.lStructSize := SizeOf(cf);
cf.hwndOwner := DXUTGetHWND;
cf.lpLogFont := @lf;
cf.Flags := CF_SCREENFONTS or CF_INITTOLOGFONTSTRUCT or CF_TTONLY;
{$IFDEF FPC}
if ChooseFontW(@cf) then
{$ELSE}
if ChooseFontW(cf) then
{$ENDIF}
begin
pFontNew := nil;
pMesh3DTextNew := nil;
pstrFontNameNew := lf.lfFaceName;
dwFontSizeNew := cf.iPointSize div 10;
bSuccess := False;
bBold := ((cf.nFontType and BOLD_FONTTYPE) = BOLD_FONTTYPE);
bItalic := ((cf.nFontType and ITALIC_FONTTYPE) = ITALIC_FONTTYPE);
hDC := GetDC(0);
nLogPixelsY := GetDeviceCaps(hDC, LOGPIXELSY);
ReleaseDC(0, hDC);
nHeight := -MulDiv(dwFontSizeNew, nLogPixelsY, 72);
if SUCCEEDED(D3DXCreateFontW(DXUTGetD3DDevice, nHeight, 0, IsBold[bBold], 1, bItalic, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
pstrFontNameNew, pFontNew)) then
begin
if SUCCEEDED(CreateD3DXTextMesh(DXUTGetD3DDevice, pMesh3DTextNew,
pstrFontNameNew, dwFontSizeNew, bBold, bItalic)) then
begin
bSuccess := True;
g_pFont := nil;
g_pFont := pFontNew;
pFontNew := nil;
g_pMesh3DText := nil;
g_pMesh3DText := pMesh3DTextNew;
pMesh3DTextNew := nil;
StringCchCopy(g_strFont, 32, pstrFontNameNew);
g_nFontSize := dwFontSizeNew;
end;
end;
pMesh3DTextNew := nil;
pFontNew := nil;
if not bSuccess then
begin
MessageBox(DXUTGetHWND, 'Could not create that font.', 'Text3D', MB_OK);
end;
end;
if not bWindowed then DXUTToggleFullScreen;
end;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
CDXUTDirectionWidget.StaticOnLostDevice;
if Assigned(g_pStatsFont) then g_pStatsFont.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pFont2) then g_pFont2.OnLostDevice;
if Assigned(g_pTextSprite) then g_pTextSprite.OnLostDevice;
SAFE_RELEASE(g_pMesh3DText);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pFont);
SAFE_RELEASE(g_pFont2);
SAFE_RELEASE(g_pStatsFont);
SAFE_RELEASE(g_pTextSprite);
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CFirstPersonCamera.Create;
g_HUD:= CDXUTDialog.Create;
g_SampleUI:= CDXUTDialog.Create;
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
end;
end.
|
unit Odontologia.Modelo.Medico.Interfaces;
interface
uses
Data.DB,
SimpleInterface,
Odontologia.Modelo.Estado.Interfaces,
Odontologia.Modelo.Entidades.Medico;
type
iModelMedico = interface
['{02DBAB3A-EA52-414E-8513-5E54173BD859}']
function Entidad : TDMEDICO; overload;
function Entidad(aEntidad: TDMEDICO) : iModelMedico; overload;
function DAO : iSimpleDAO<TDMEDICO>;
function DataSource(aDataSource: TDataSource) : iModelMedico;
function Estado : iModelEstado;
end;
implementation
end.
|
unit Graphics;
interface
procedure GraphicMainMenu;
procedure GraphicSeeContact;
procedure GraphicOrderBy(d:string);
procedure GraphicAskBy(d:string);
procedure GraphicAddContact;
procedure GraphicDelContact;
procedure GraphicListDelTree(asked:string);
procedure border(x1,y1,x2,y2:byte);
procedure centerText(y: byte; str: string);
procedure FocusMenu(e:byte);
procedure unFocusMenu(e:byte);
procedure print(x,y: byte; str: string);
procedure clrTable;
procedure clrBx;
procedure clrTable2;
procedure BarTable(h:byte);
procedure BarTable2(h:byte);
procedure FocusMenu2(e:byte);
procedure unFocusMenu2(e:byte);
procedure select(i:byte);
procedure deSelect(i:byte);
implementation
uses CRT, Files, Trees, Types, Main;
procedure GraphicMainMenu;
begin
MenuSelect := 1; { Menu por Defecto: 1 }
textcolor(15); { blanco }
clrscr; { Limpiar pantalla }
border(1,1,79,24); { Bordes de la pantalla }
centerText(2,#205+Titulo+#205); { Titulo centrado }
{ Graficamos los Menues }
border(2,4,78,8);
centerText(6,'Ver contactos');
border(2,9,78,13);
centerText(11,'Agregar Contacto');
border(2,14,78,18);
centerText(16,'Modificar Contacto');
border(2,19,78,23);
centerText(21,'Salir');
FocusMenu(MenuSelect); { Selecionamos el elemento por Defecto }
repeat
Key:= Readkey; { Leemos el teclado }
case Key of
#0 :
Begin
Key:= ReadKey;
Case Key Of
#72 : { Arriba }
begin
if MenuSelect > 1 then
begin
unFocusMenu(MenuSelect); { Quitamos el foco al anterior }
MenuSelect:= MenuSelect-1;
FocusMenu(MenuSelect); { Hacemos foco en el nuevo menu }
end;
end;
#80 : { Abajo }
begin
if MenuSelect < 4 then
begin
unFocusMenu(MenuSelect); { Quitamos el foco al anterior }
MenuSelect:= MenuSelect+1;
FocusMenu(MenuSelect); { Hacemos foco en el nuevo menu }
end;
end;
// #75 : WriteLn('Left'); { Izquierda }
// #77 : WriteLn('Right'); { Derecha }
End;
End;
#13 : case MenuSelect Of { Enter }
1: GraphicSeeContact; { Graficamos el menu para ver los contactos [Listar todos o algunos] }
2: GraphicAddContact;
3: GraphicDelContact;
4: Key := #27; { Forzamos el cambio de Key a escape }
end;
end;
until Key = #27 { Escale salir }
end;
procedure GraphicSeeContact;
begin
MenuSelect := 1; { Menu por Defecto: 1 }
textcolor(15); { Blanco }
clrscr; { Limpiar pantalla }
border(1,1,79,24); { Bordes de la pantalla }
centerText(2,#205+'Ver contactos'+#205); { Titulo centrado }
{ Graficamos los Menues }
border(2,4,78,6);
centerText(5,'Ordenar por Nombre');
border(2,7,78,9);
centerText(8,'Ordenar por Telefono');
border(2,10,78,12);
centerText(11,'Ordenar por Direccion');
border(2,13,78,15);
centerText(14,'Buscar por Nombre');
border(2,16,78,18);
centerText(17,'Buscar por Telefono');
border(2,19,78,21);
centerText(20,'Buscar por Direccion');
border(2,22,78,24);
centerText(23,'Atras');
FocusMenu2(MenuSelect); { Selecionamos el elemento por Defecto }
repeat
Key:= Readkey; { Leemos el teclado }
case Key of
#0 :
Begin
Key:= ReadKey;
Case Key Of
#72 : { Arriba }
begin
if MenuSelect > 1 then
begin
unFocusMenu2(MenuSelect); { Quitamos el foco al anterior }
MenuSelect:= MenuSelect-1;
FocusMenu2(MenuSelect); { Hacemos foco en el nuevo menu }
end;
end;
#80 : { Abajo }
begin
if MenuSelect < 7 then
begin
unFocusMenu2(MenuSelect); { Quitamos el foco al anterior }
MenuSelect:= MenuSelect+1;
FocusMenu2(MenuSelect); { Hacemos foco en el nuevo menu }
end;
end;
// #75 : WriteLn('Left'); { Izquierda }
// #77 : WriteLn('Right'); { Derecha }
End;
End;
#13 : case MenuSelect Of { Enter }
{ Listar todos }
1: GraphicOrderBy('Nombre');
2: GraphicOrderBy('Telefono');
3: GraphicOrderBy('Direccion');
{ Listar algunos contactos especificos }
4: GraphicAskBy('Nombre');
5: GraphicAskBy('Telefono');
6: GraphicAskBy('Direccion');
7: Key := #27; { Forzamos el cambio de Key a escape }
end;
end;
until Key = #27; { Escale salir }
GraphicMainMenu; { Volvemos al menu inicial }
end;
procedure GraphicOrderBy(d:string);
var i: byte;
begin
textcolor(15); { Blanco }
clrscr; { Limpiar pantalla }
border(1,1,79,24); { Bordes de la pantalla }
centerText(2,#205+'Contactos por '+d+#205); { Titulo centrado }
{ Texto Siguiente }
textcolor(10);
gotoxy(56,2);
write('[Enter Para Seguir]');
{ Texto Salir }
gotoxy(7,2);
textcolor(12);
write('[Esc Para Salir]');
{ Borde superior de la tabla de los contactos }
textcolor(15);
gotoxy(4,3);
write(#218+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#194+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#194+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#191);
{ Thead }
gotoxy(56,2);
textbackground(4); { Rojo }
gotoxy(4,4);
write(#179+' Telefono '+#179+' Nombre '+#179+' Direccion '+#179);
textbackground(0); { Negro }
{ Ver de que manera se ordenaran los contactos }
if d = 'Nombre' then GraphicListTree(A_nom);
if d = 'Telefono' then GraphicListTree(A_tel);
if d = 'Direccion' then GraphicListTree(A_dom);
readkey; { #FANAES# }
GraphicSeeContact; { Volvemos al menu anterior }
end;
procedure GraphicListTree(kTree:Ttree);
var i: cardinal;
rk: char;
procedure listRegister(kTree: Ttree);
begin
if rk <> #27 then { Si se apreto escape }
begin
if i < 9 then { Nos fijamos si ya llenamos la tabla }
begin
LeeReg(Fagenda,KTree^.position,Rcontact); { Leemos el contacto }
BarTable(5+i*2);
gotoxy(4,6+i*2);
write(#179+' '+#179+' '+#179+' '+#179); { Limpiamos la fila }
{ Telefono }
gotoxy(6,6+i*2);
write(Rcontact.telefono);
{ Nombre }
gotoxy(30,6+i*2);
write(Rcontact.nombre);
{ Domicilio }
gotoxy(54,6+i*2);
write(Rcontact.domicilio);
i:= i + 1;
end
else
{ Si la tabla esta llena }
begin
rk := readkey; { Leemos para saber si quiere seguir listando o no }
if rk = #13 then
begin
i := 0;
clrTable; { Limpiamos la pantalla }
end;
end;
if i = 8 then { Graficamos el borde inferior de la tabla }
begin
gotoxy(4,23);
write(#192+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#193+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#193+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#217);
end;
end;
end;
procedure listT(kTree: Ttree);
begin
if (KTree <> nil) and (rk <> #27) then
begin
listT(KTree^.slt); { Sub-arbol Izquierdo }
listRegister(KTree); { Nodo actual }
listT(KTree^.srt); { Sub-arbol Derecho }
end;
end;
begin
i := 0; { Inicializamos la posicion a 0 }
ListT(KTree);
end;
procedure GraphicAskBy(d:string);
var asked: string;
begin
textcolor(15); { Blanco }
clrscr; { Limpiar pantalla }
border(1,1,79,24); { Bordes de la pantalla }
{ Titulo }
gotoxy(27,2);
write(d+':'); { Titulo centrado }
{ Seguir }
textcolor(10);
gotoxy(56,2);
write('[Enter Para Seguir]');
{ Salir }
gotoxy(7,2);
textcolor(12);
write('[Esc Para Salir]');
{ Leer con que va a matchear }
textcolor(15);
gotoxy(29+length(d),2);
readln(asked);
{ Borde superior de la tabla }
gotoxy(4,3);
write(#218+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#194+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#194+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#191);
gotoxy(56,2);
textbackground(4); { Rojo }
gotoxy(4,4);
write(#179+' Telefono '+#179+' Nombre '+#179+' Direccion '+#179);
textbackground(0); { Negro }
{ Ver de que manera se ordenaran los contactos }
if d = 'Nombre' then GraphicListAskTree(A_nom,upcase(asked));
if d = 'Telefono' then GraphicListAskTree(A_tel,asked);
if d = 'Direccion' then GraphicListAskTree(A_dom,upcase(asked));
readkey; { #FANAES# }
GraphicSeeContact; { Volvemos al menu anterior }
end;
procedure GraphicListAskTree(kTree:Ttree;asked:string);
var i,j: cardinal;
rk: char;
procedure listRegister(kTree: Ttree; asked:string);
begin
if rk <> #27 then { Nos fijamos si se presiono Esc. }
begin
if i < 9 then { Nos fijamos si ya llenamos la tabla de contactos }
begin { Si queda por rellenar }
LeeReg(Fagenda,KTree^.position,Rcontact); { Leemos el position-esimo contacto }
if (pos(asked, Ktree^.key) = 1) and (Rcontact.estado = True) then { Verificamos que matchea con el campo ingresado y que el contacto esta dado de alta }
begin
{ Dibujamos los bordes de la fila }
BarTable(5+i*2);
gotoxy(4,6+i*2);
write(#179+' '+#179+' '+#179+' '+#179);
{ Telefono }
gotoxy(6,6+i*2);
write(Rcontact.telefono);
{ Nombre }
gotoxy(30,6+i*2);
write(Rcontact.nombre);
{ Domicilio }
gotoxy(54,6+i*2);
write(Rcontact.domicilio);
i:= i + 1; { Aumentamos el contador de contacto }
end;
end
else { Si la tabla esta llena }
begin
rk := readkey; { Leemos el teclado }
if rk = #13 then { Nos fijamos si quiere seguir }
begin
i := 0; { movemos el indicador de filas hacia arriba }
clrTable; { Limpiamos la tabla }
end;
end;
if i = 8 then { Si ya completamos la tabla dibujamos el borde inferior de la misma }
begin
gotoxy(4,23);
write(#192+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#193+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#193+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#217);
end;
end;
end;
procedure listT(kTree: Ttree; asked:string);
begin
if (KTree <> nil) and (rk <> #27) then { Nos fijamos que el arbol no este vacio ni que se apreto Esc. }
begin
listT(KTree^.slt, asked); { Sub-arbol Izquierdo }
listRegister(KTree, asked); { Nodo actual }
listT(KTree^.srt, asked); { Sub-arbol Derecho }
end;
end;
begin
i := 0; { Inicializamos la posicion a 0 }
j := 0;
while j < 9 do
begin
BarTable(5+j*2);
gotoxy(4,6+j*2);
write(#179+' '+#179+' '+#179+' '+#179);
j:= j + 1;
end;
gotoxy(4,23);
write(#192+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#193+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#193+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#217);
listT(KTree, asked);
end;
procedure GraphicAddContact;
var nombre, domicilio, telefono: string;
rk: char;
contacto: Tcontacto;
begin
{ Inicializamos los campos con una cadena vacia }
nombre := '';
domicilio := '';
telefono := '';
textcolor(15); { Blanco }
clrscr; { Limpiamos la pantalla }
border(1,1,79,24); { Bordes de la pantalla }
centerText(2,#205+'Agregar contacto'+#205); { Titulo centrado }
{ Nombre }
border(2,4,78,8);
centerText(6,'Nombre: ');
while nombre = '' do { Corroboramos que no deje el campo vacio }
begin
gotoxy(44,6);
readln(nombre);
end;
{ Telefono }
border(2,9,78,13);
centerText(11,'Telefono: ');
while verifNum(telefono) do { Corroboramos que ingrese una cadena numerica }
begin
gotoxy(45,11);
write(' ');
gotoxy(45,11);
readln(telefono);
end;
{ Direccion }
border(2,14,78,18);
centerText(16,'Direccion: ');
while domicilio = '' do { Corroboramos que no deje el campo vacio }
begin
gotoxy(46,16);
readln(domicilio);
end;
{ Boton enviar }
focusmenu(4);
textbackground(4); { Rojo }
centerText(21,'Enviar');
textbackground(0);
rk := readkey;
if rk = #13 then { Verificamos si desea enviarlo }
begin
{ Guardamos los campos }
contacto.nombre:= upcase(nombre);
contacto.telefono:= StrToInt(telefono);
contacto.domicilio:= upcase(domicilio);
contacto.estado:= true; { Por defecto el estado es True }
GuardaReg(Fagenda, FILESIZE(Fagenda), contacto); { Guardamos el contacto en .dat }
{ Insertamos el nuevo contacto en los arboles }
insertTree(A_tel,telefono,(filesize(Fagenda))-1);
insertTree(A_nom,upcase(nombre),(filesize(Fagenda))-1);
insertTree(A_dom,upcase(domicilio),(filesize(Fagenda))-1);
end;
GraphicMainMenu; { Volvemos al menu principal }
end;
procedure GraphicDelContact;
var asked: string;
begin
textcolor(15); { Blanco }
clrscr; { Limpiamos la pantalla }
border(1,1,79,24); { Bordes de la pantalla }
gotoxy(21,2);
write('Nombre: '); { Titulo centrado }
gotoxy(49,2);
write('ID: '); { Titulo centrado }
{ Seguir }
gotoxy(58,2);
textcolor(10);
write('[Enter Para Seguir]');
{ Salir }
gotoxy(4,2);
textcolor(12);
write('[Esc Para Salir]');
{ Borde superior de la tabla }
textcolor(15);
gotoxy(4,3);
write(#218+#196+#196+#196+#196#196+#196+#196+#196+#194+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196+#194+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#194+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#191);
{ THEAD }
textbackground(4); { Rojo }
gotoxy(4,4);
write(#179+' ID '+#179+' Telefono '+#179+' Nombre '+#179+' Direccion '+#179);
textbackground(0); { Negro }
gotoxy(29,2);
readln(asked);
GraphicListDelTree(upcase(asked));
GraphicMainMenu; { Volvemos al menu principal }
end;
procedure GraphicListDelTree(asked:string);
var i,j: cardinal;
rk: string;
procedure EditContact(pos:longint);
var rk : char;
i: byte;
nombre,domicilio,telefono : string;
estado: boolean;
contacto: Tcontacto;
begin
clrBx; { Limpiamos }
centerText(2,#205+'Editar Contacto'+#205); { Titulo centrado }
{ Mover }
textcolor(10); { Verde }
gotoxy(54,2);
write('[Mover con las felchas]');
{ Salir }
gotoxy(4,2);
textcolor(12); { Rojo }
write('[Esc Para Salir]');
{ Borde superior de la tabla }
textcolor(15); { Blanco }
gotoxy(4,4);
write(#218+#196+#196+#196+#196#196+#196+#196+#196+#196+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196+#194+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#191);
{ THEAD }
textbackground(4); { Rojo }
gotoxy(4,5);
write(#179+' Nombre '+#179);
gotoxy(4,7);
write(#179+' Telefono '+#179);
gotoxy(4,9);
write(#179+' Direccion '+#179);
gotoxy(4,11);
write(#179+' Estado '+#179);
gotoxy(4,13);
write(#179+' Guardar '+#179);
{ Dibujamos la tabla }
textbackground(0); { Negro }
gotoxy(76,5);
write(#179);
gotoxy(76,7);
write(#179);
gotoxy(76,9);
write(#179);
gotoxy(76,11);
write(#179);
gotoxy(4,6);
write(#195+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#197+#196+#196+#196++#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#180);
gotoxy(4,8);
write(#195+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#197+#196+#196+#196++#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#180);
gotoxy(4,10);
write(#195+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#197+#196+#196+#196++#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#180);
gotoxy(4,12);
write(#195+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196++#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#180);
gotoxy(4,14);
write(#192+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#217);
{ Leemos el pos-esimo contacto }
LeeReg(Fagenda,pos,Rcontact);
nombre := Rcontact.nombre;
domicilio := Rcontact.domicilio;
telefono := intToStr(Rcontact.telefono);
estado := Rcontact.estado;
{ Nombre }
gotoxy(31,5);
write(Rcontact.nombre);
{ Telefono }
gotoxy(31,7);
write(Rcontact.telefono);
{ Domicilio }
gotoxy(31,9);
write(Rcontact.domicilio);
if Rcontact.estado = False then { Nos fijamos en que estadp esta }
begin { Inactivo }
textbackground(4); { Rojo }
gotoxy(31,11);
write(' Inactivo ');
textbackground(0); { Negro }
gotoxy(53,11);
write(' Activo ');
end
else
begin { Activo }
textbackground(10); { Verde }
gotoxy(53,11);
write(' Activo ');
textbackground(0);
gotoxy(31,11);
write(' Inactivo ');
end;
i := 0; { Por defecto tiene el foco el primer campo }
select(i);
repeat
rk := readkey;
case rk of
#0 :
Begin
rk:= ReadKey;
Case rk Of
#72 : {Arriba}
begin
if i > 0 then
begin
deSelect(i); { Quitamos el foco al anterior }
i:= i-1;
select(i); { Hacemos foco en el nuevo menu }
end;
end;
#80 : {Abajo}
begin
if i < 4 then
begin
deSelect(i); { Quitamos el foco al anterior }
i:= i+1;
select(i); { Hacemos foco en el nuevo menu }
end;
end;
// #75 : WriteLn('Left'); {Izquierda}
// #77 : WriteLn('Right'); {Derecha}
End;
End; { #FANAES# es el end del case of ? }
#13 : { Enter }
begin
if i = 0 then { Nombre }
begin
gotoxy(31,5);
write(' ');
gotoxy(31,5);
readln(nombre);
end;
if i = 1 then { Telefono }
begin
gotoxy(31,7);
write(' ');
gotoxy(31,7);
readln(telefono);
end;
if i = 2 then { Domicilio }
begin
gotoxy(31,9);
write(' ');
gotoxy(31,9);
readln(domicilio);
end;
if i = 3 then { Estado }
begin
while rk <> #27 do
begin
rk := readkey;
if rk <> #27 then
begin
if estado = True then
begin
textbackground(4); { Rojo }
gotoxy(31,11);
write(' Inactivo ');
textbackground(0); { Negro }
gotoxy(53,11);
write(' Activo ');
estado := False;
end
else
begin
textbackground(10); { Verde }
gotoxy(53,11);
write(' Activo ');
textbackground(0); { Negro }
gotoxy(31,11);
write(' Inactivo ');
estado := True;
end;
end;
end;
rk := #0;
end;
if i = 4 then { Enviar }
begin
{ Guardamos los nuevos campos del contacto }
contacto.nombre:= upcase(nombre);
contacto.telefono:= StrToInt(telefono);
contacto.domicilio:= upcase(domicilio);
contacto.estado:= estado; { Por defecto el estado es True }
GuardaReg(Fagenda,pos, contacto); { Guardamos el contacto en .dat }
{ Vaciamos los arboles para ingresar el nuevo contacto modificado }
A_nom := nil;
A_tel := nil;
A_dom := nil;
loadTrees(); { Cargamos de nuevo los arboles }
rk := #27; { Salir }
end;
end;
end;
until rk = #27 {Escale salir}
end;
procedure listRegister(kTree: Ttree; asked:string);
begin
textbackground(0); { Negro }
if rk = '' then
begin
if i < 9 then
begin
if pos(asked, Ktree^.key) = 1 then
begin
LeeReg(Fagenda,KTree^.position,Rcontact);
BarTable2(5+i*2);
if Rcontact.estado = False then
textbackground(4); { Rojo }
gotoxy(4,6+i*2);
write(#179+' '+#179+' '+#179+' '+#179+' '+#179);
{ ID }
gotoxy(6,6+i*2);
write(Ktree^.position);
{ Telefono }
gotoxy(15,6+i*2);
write(Rcontact.telefono);
{ Nombre }
gotoxy(31,6+i*2);
write(Rcontact.nombre);
{ Domicilio }
gotoxy(54,6+i*2);
write(Rcontact.domicilio);
i:= i + 1;
textbackground(0);
end;
end
else
begin
gotoxy(53,2);
readln(rk);
if rk = '' then
begin
i := 0;
clrTable2; { Limpiamos la tabla }
end
else
begin
if rk <> '0' then
begin
EditContact(StrToInt(rk)); { Recargamos el procedure }
{LeeReg(Fagenda,StrToInt(rk),Rcontact);
if Rcontact.estado = True then
Rcontact.estado := False
else
Rcontact.estado := True;
guardareg(Fagenda,StrToInt(rk),Rcontact);}
end;
end;
end;
if i = 8 then { Si llenamos la tabla dibujamos el bordo inferior del mismo }
begin
gotoxy(4,23);
write(#192+#196+#196+#196+#196+#196+#196+#196+#196+#193+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196+#193+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#193+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#217);
end;
end;
end;
procedure listT(kTree: Ttree; asked:string);
begin
if (KTree <> nil) and (rk = '') then
begin
listT(KTree^.slt, asked); { Sub-arbol Izquierdo }
listRegister(KTree, asked); { Nodo actual }
listT(KTree^.srt, asked); { Sub-arbol Derecho }
end;
end;
begin
i := 0;
j := 0;
while j < 9 do
begin
BarTable2(5+j*2);
gotoxy(4,6+j*2);
write(#179+' '+#179+' '+#179+' '+#179+' '+#179);
j:= j + 1;
end;
gotoxy(4,23);
write(#192+#196+#196+#196+#196+#196+#196+#196+#196+#193+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196+#193+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#193+#196+#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196#196+#196+#196+#196+#196#196+#196+#196+#196+#217);
ListT(A_nom, asked);
if (i <> 8) and (rk <> '0') then { Si la tabla no esta llena y se quiere seguir }
begin
gotoxy(53,2);
readln(rk);
if rk <> '' then
EditContact(StrToInt(rk));
{LeeReg(Fagenda,StrToInt(rk),Rcontact);
if Rcontact.estado = True then
Rcontact.estado := False
else
Rcontact.estado := True;
guardareg(Fagenda,StrToInt(rk),Rcontact);}
end;
end;
procedure border(x1,y1,x2,y2:byte); { Dibuja cuadrado con borde doble sin modificar el contenido }
var
i: byte;
begin
{ Esquinas }
print(x1,y1,#201); { ╔ }
print(x1,y2,#200); { ╚ }
print(x2,y1,#187); { ╗ }
print(x2,y2,#188); { ╝ }
{ Bordes Sup e Inf }
for i:=(x1 + 1) to (x2 - 1) do
begin
print(i,y1,#205); { ═ }
print(i,y2,#205); { ═ }
end;
{ Bordes laterales }
for i:=(y1 + 1) to (y2 - 1) do
begin
print(x1,i,#186); { ║ }
print(x2,i,#186); { ║ }
end;
end;
procedure centerText(y: byte; str: string); { Centra un texto en cierta altura }
var
i: Integer;
begin
i:= 40 - (length(str) div 2); { Posicion para que el Texto quede centrado }
gotoxy(i,y);
write(str);
end;
procedure FocusMenu(e:byte); { e: Elemento que obtendra el foco }
var
i: byte;
str : string;
begin
case e of
0: str := '';
1: str := 'Ver contactos';
2: str := 'Agregar Contacto';
3: str := 'Modificar Contacto';
4: str := 'Salir';
end;
textcolor(15); { Blanco }
textbackground(4); { Rojo }
{ Pintamos el fondo }
for i := 3 to 77 do
begin
print(i,e*5,' ');
print(i,e*5+1,' ');
print(i,e*5 +2,' ');
end;
{ Generamos los bordes }
border(2,e*5-1,78,e*5+3);
centerText(e*5+1, str);
{ Volvemos a los valores por defecto }
textcolor(15); { Blanco }
textbackground(0); { Negro }
end;
procedure unFocusMenu(e:byte); { e: Elemento que se le quitara el foco }
var
i: byte;
str : string;
begin
case e of
1: str := 'Ver contactos';
2: str := 'Agregar Contacto';
3: str := 'Eliminar Contacto';
4: str := 'Salir';
end;
textcolor(15); { Blanco }
textbackground(0); { Negro }
{ Pintamos el fondo }
for i := 3 to 77 do
begin
print(i,e*5,' ');
print(i,e*5+1,' ');
print(i,e*5 +2,' ');
end;
{ Generamos los bordes }
border(2,e*5-1,78,e*5+3);
centerText(e*5+1, str);
end;
procedure print(x,y: byte; str: string);
begin
gotoxy(x,y);
write(str);
end;
procedure clrTable;
var i: byte;
begin
i:= 0;
while i < 9 do
begin
gotoxy(6,6+i*2);
write(' ');
gotoxy(30,6+i*2);
write(' ');
gotoxy(54,6+i*2);
write(' ');
i:= i+1;
end;
end;
procedure clrBx;
var i:byte;
begin
i:= 2;
while i < 24 do
begin
gotoxy(2,i);
write(' ');
i:=i+1;
end;
gotoxy(21,2);
write(' ');
end;
procedure clrTable2;
var i: byte;
begin
i:= 0;
while i < 9 do
begin
gotoxy(6,6+i*2);
write(' ');
gotoxy(17,6+i*2);
write(' ');
gotoxy(30,6+i*2);
write(' ');
gotoxy(54,6+i*2);
write(' ');
i:= i+1;
end;
end;
procedure BarTable(h:byte);
begin
gotoxy(4,h);
write(#195+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#197+#196+#196+#196+#196++#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#197+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#180);
end;
procedure BarTable2(h:byte);
begin
gotoxy(4,h);
write(#195+#196+#196+#196+#196+#196+#196+#196+#196+#197+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#197+#196+#196+#196++#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#197+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#196+#180);
end;
procedure FocusMenu2(e:byte); { e: Elemento que obtendra el foco }
var
i: byte;
str : string;
begin
case e of
1: str := 'Ordenar por Nombre';
2: str := 'Ordenar por Telefono';
3: str := 'Ordenar por Direccion';
4: str := 'Buscar por Nombre';
5: str := 'Buscar por Telefono';
6: str := 'Buscar por Direccion';
7: str := 'Atras';
end;
textcolor(15); { Blanco }
textbackground(4); { Rojo }
{ Pintamos el fondo }
for i := 3 to 77 do
begin
print(i,e*3+2,' ');
end;
{ Generamos los bordes }
border(2,e*3+1,78,e*3+3);
centerText(e*3+2, str);
{ Volvemos a los valores por defecto }
textcolor(15); { Blanco }
textbackground(0); { Negro }
end;
procedure unFocusMenu2(e:byte); { e: Elemento que se le quitara el foco }
var
i: byte;
str : string;
begin
case e of
1: str := 'Ordenar por Nombre';
2: str := 'Ordenar por Telefono';
3: str := 'Ordenar por Direccion';
4: str := 'Buscar por Nombre';
5: str := 'Buscar por Telefono';
6: str := 'Buscar por Direccion';
7: str := 'Atras';
end;
textcolor(15); { Blanco }
textbackground(0); { Negro }
{ Pintamos el fondo }
for i := 3 to 77 do
begin
print(i,e*3+2,' ');
end;
{ Generamos los bordes }
border(2,e*3+1,78,e*3+3);
centerText(e*3+2, str);
end;
procedure select(i:byte);
begin
gotoxy(75,5+i*2);
textbackground(10);
write(' ');
gotoxy(75,5+i*2);
textbackground(0);
end;
procedure deSelect(i:byte);
begin
gotoxy(75,5+i*2);
textbackground(0);
write(' ');
end;
end.
|
unit uModReturTrader;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
uModAPP, uModPOTrader, uModBarang, uModSatuan, uModOrganization,
System.Generics.Collections, uModUnit, uModGudang, uModDOTrader, uModAR;
type
TModReturTraderItem = class;
TModReturTrader = class(TModApp)
private
FReturTraderItems: TObjectList<TModReturTraderItem>;
FRET_DATE: TDatetime;
FRET_DESCRIPTION: string;
FRET_DISC: Double;
FRET_AR: TModAR;
FRET_DISC_MEMBER: Double;
FRET_DOTrader: TModDOTrader;
FRET_GUDANG: TModGudang;
FRET_LEAD_TIME: Double;
FRET_NO: string;
FRET_Organization: TModOrganization;
FRET_PPN: Double;
FRET_PPNBM: Double;
FRET_STATUS: string;
FRET_SUBTOTAL: Double;
FRET_TOP: Integer;
FRET_TOTAL: Double;
FRET_UNIT: TModUnit;
FRET_VALID_DATE: TDatetime;
function GetReturTraderItems: TObjectList<TModReturTraderItem>;
public
property ReturTraderItems: TObjectList<TModReturTraderItem> read
GetReturTraderItems write FReturTraderItems;
published
property RET_DATE: TDatetime read FRET_DATE write FRET_DATE;
[AttributeofSize('120')]
property RET_DESCRIPTION: string read FRET_DESCRIPTION write
FRET_DESCRIPTION;
property RET_DISC: Double read FRET_DISC write FRET_DISC;
property RET_AR: TModAR read FRET_AR write FRET_AR;
property RET_DISC_MEMBER: Double read FRET_DISC_MEMBER write
FRET_DISC_MEMBER;
property RET_DOTrader: TModDOTrader read FRET_DOTrader write FRET_DOTrader;
property RET_GUDANG: TModGudang read FRET_GUDANG write FRET_GUDANG;
property RET_LEAD_TIME: Double read FRET_LEAD_TIME write FRET_LEAD_TIME;
[AttributeofCode]
property RET_NO: string read FRET_NO write FRET_NO;
property RET_Organization: TModOrganization read FRET_Organization write
FRET_Organization;
property RET_PPN: Double read FRET_PPN write FRET_PPN;
property RET_PPNBM: Double read FRET_PPNBM write FRET_PPNBM;
property RET_STATUS: string read FRET_STATUS write FRET_STATUS;
property RET_SUBTOTAL: Double read FRET_SUBTOTAL write FRET_SUBTOTAL;
property RET_TOP: Integer read FRET_TOP write FRET_TOP;
property RET_TOTAL: Double read FRET_TOTAL write FRET_TOTAL;
property RET_UNIT: TModUnit read FRET_UNIT write FRET_UNIT;
property RET_VALID_DATE: TDatetime read FRET_VALID_DATE write
FRET_VALID_DATE;
end;
TModReturTraderItem = class(TModApp)
private
FRETITEM_BARANG: TModBarang;
FRETITEM_COGS: Double;
FRETITEM_DISC: Double;
FRETITEM_DISCRP: Double;
FRETITEM_NETSALE: Double;
FRETITEM_PPN: Double;
FRETITEM_PPNRP: Double;
FRETITEM_QTY: Double;
FRETITEM_RETURTRADER: TModReturTrader;
FRETITEM_SATUAN: TModSatuan;
FRETITEM_SELLPRICE: Double;
FRETITEM_TOTAL: Double;
published
property RETITEM_BARANG: TModBarang read FRETITEM_BARANG write
FRETITEM_BARANG;
property RETITEM_COGS: Double read FRETITEM_COGS write FRETITEM_COGS;
property RETITEM_DISC: Double read FRETITEM_DISC write FRETITEM_DISC;
property RETITEM_DISCRP: Double read FRETITEM_DISCRP write FRETITEM_DISCRP;
property RETITEM_NETSALE: Double read FRETITEM_NETSALE write
FRETITEM_NETSALE;
property RETITEM_PPN: Double read FRETITEM_PPN write FRETITEM_PPN;
property RETITEM_PPNRP: Double read FRETITEM_PPNRP write FRETITEM_PPNRP;
property RETITEM_QTY: Double read FRETITEM_QTY write FRETITEM_QTY;
[AttributeOfHeader]
property RETITEM_RETURTRADER: TModReturTrader read FRETITEM_RETURTRADER
write FRETITEM_RETURTRADER;
property RETITEM_SATUAN: TModSatuan read FRETITEM_SATUAN write
FRETITEM_SATUAN;
property RETITEM_SELLPRICE: Double read FRETITEM_SELLPRICE write
FRETITEM_SELLPRICE;
property RETITEM_TOTAL: Double read FRETITEM_TOTAL write FRETITEM_TOTAL;
end;
implementation
function TModReturTrader.GetReturTraderItems: TObjectList<TModReturTraderItem>;
begin
if not Assigned(FReturTraderItems) then
FReturTraderItems := TObjectList<TModReturTraderItem>.Create;
Result := FReturTraderItems;
end;
initialization
TModReturTrader.RegisterRTTI;
TModReturTraderItem.RegisterRTTI;
end.
|
unit Chapter04._08_Solution1;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DeepStar.DSA.Tree.TreeSet,
DeepStar.Utils;
// 220. Contains Duplicate III
// https://leetcode.com/problems/contains-duplicate-iii/description/
// 时间复杂度: O(nlogk)
// 空间复杂度: O(k)
type
TSolution = class(TObject)
public
function containsNearbyAlmostDuplicate(nums: TArr_int; k, t: integer): boolean;
end;
TSet_int = specialize TTreeSet<integer>;
procedure Main;
implementation
procedure Main;
var
nums: TArr_int;
k, t: integer;
ret: boolean;
begin
nums := [1, 5, 9, 1, 5, 9];
k := 2;
t := 3;
with TSolution.Create do
begin
ret := containsNearbyAlmostDuplicate(nums, k, t);
Free;
end;
WriteLn(ret);
end;
{ TSolution }
function TSolution.containsNearbyAlmostDuplicate(nums: TArr_int; k, t: integer): boolean;
var
recordSet: TSet_int;
i: integer;
begin
recordSet := TSet_int.Create;
for i := 0 to High(nums) do
begin
if (recordSet.Ceiling(Abs(nums[i] - t)) <> nil) and
(recordSet.Ceiling(Abs(nums[i] - t)).Value <= nums[i] + t) then
begin
Exit(true);
end;
recordSet.Add(nums[i]);
if recordSet.Count = k + 1 then
recordSet.Remove(nums[i - k]);
end;
Result := false;
recordSet.Free;
end;
end.
|
unit LrDockUtils;
interface
uses
SysUtils, Types, Classes, Controls,
dxDockControl, dxDockPanel;
type
TTabState = class(TComponent)
public
ActiveChild: TdxCustomDockControl;
constructor Create(inSite: TdxTabContainerDockSite); reintroduce;
destructor Destroy; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure Restore;
end;
//
TDockTabsState = class
private
procedure FreeTabStates;
public
Tabs: TList;
Container: TWinControl;
constructor Create(inContainer: TWinControl);
destructor Destroy; override;
procedure Capture;
procedure Restore;
end;
//
TDockLayoutState = class
private
FLayout: TMemoryStream;
public
constructor Create;
destructor Destroy; override;
procedure Capture;
procedure Restore;
end;
//
TSimpleDockState = class
public
Control: TdxCustomDockControl;
Bounds: TRect;
Visible: Boolean;
public
constructor Create(inControl: TdxCustomDockControl);
procedure Restore;
end;
//
TSimpleDockLayoutState = class
private
procedure FreeStates;
public
States: TList;
Container: TWinControl;
constructor Create(inContainer: TWinControl);
destructor Destroy; override;
procedure Capture;
procedure Restore;
end;
procedure ActivateDock(inDock: TdxCustomDockControl);
implementation
procedure ActivateDock(inDock: TdxCustomDockControl);
begin
with inDock do
if (Container <> nil) then
if (Container is TdxTabContainerDockSite) then
Container.ActiveChild := inDock
else if (Container is TdxCustomDockControl) then
ActivateDock(TdxCustomDockControl(Container));
end;
{ TTabState }
constructor TTabState.Create(inSite: TdxTabContainerDockSite);
begin
inherited Create(nil);
// Site := inSite;
// ActiveIndex := Site.ActiveChildIndex;
ActiveChild := inSite.ActiveChild;
ActiveChild.FreeNotification(Self);
end;
destructor TTabState.Destroy;
begin
//ActiveChild.RemoveFreeNotification(Sefl);
inherited;
end;
procedure TTabState.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = ActiveChild) then
ActiveChild := nil;
end;
procedure TTabState.Restore;
begin
if ActiveChild <> nil then
ActivateDock(ActiveChild);
// if Site.ChildCount > ActiveIndex then
// Site.ActiveChildIndex := ActiveIndex;
end;
{ TDockTabsState }
constructor TDockTabsState.Create(inContainer: TWinControl);
begin
Container := inContainer;
Tabs := TList.Create;
end;
destructor TDockTabsState.Destroy;
begin
FreeTabStates;
Tabs.Free;
inherited;
end;
procedure TDockTabsState.FreeTabStates;
var
i: Integer;
begin
for i := 0 to Pred(Tabs.Count) do
TTabState(Tabs[i]).Free;
Tabs.Clear;
end;
procedure TDockTabsState.Capture;
var
i: Integer;
begin
FreeTabStates;
with Container do
for i := 0 to Pred(ComponentCount) do
if Components[i] is TdxTabContainerDockSite then
Tabs.Add(TTabState.Create(TdxTabContainerDockSite(Components[i])));
end;
procedure TDockTabsState.Restore;
var
i: Integer;
begin
for i := 0 to Pred(Tabs.Count) do
TTabState(Tabs[i]).Restore;
end;
{ TDockLayoutState }
constructor TDockLayoutState.Create;
begin
FLayout := TMemoryStream.Create;
end;
destructor TDockLayoutState.Destroy;
begin
FLayout.Free;
inherited;
end;
procedure TDockLayoutState.Capture;
begin
FLayout.Clear;
dxDockingController.SaveLayoutToStream(FLayout);
end;
procedure TDockLayoutState.Restore;
begin
if FLayout.Size > 0 then
begin
FLayout.Position := 0;
dxDockingController.LoadLayoutFromStream(FLayout);
end;
end;
{ TSimpleDockState }
constructor TSimpleDockState.Create(inControl: TdxCustomDockControl);
begin
Control := inControl;
Bounds := inControl.BoundsRect;
Visible := inControl.Visible;
end;
procedure TSimpleDockState.Restore;
begin
Control.BoundsRect := Bounds;
Control.Visible := Visible;
end;
{ TSimpleDockLayoutState }
constructor TSimpleDockLayoutState.Create(inContainer: TWinControl);
begin
Container := inContainer;
States := TList.Create;
end;
destructor TSimpleDockLayoutState.Destroy;
begin
FreeStates;
States.Free;
inherited;
end;
procedure TSimpleDockLayoutState.FreeStates;
var
i: Integer;
begin
for i := 0 to Pred(States.Count) do
TSimpleDockState(States[i]).Free;
States.Clear;
end;
procedure TSimpleDockLayoutState.Capture;
var
i: Integer;
begin
FreeStates;
with Container do
for i := 0 to Pred(ComponentCount) do
if Components[i] is TdxDockPanel then
States.Add(TSimpleDockState.Create(TdxDockPanel(Components[i])));
end;
procedure TSimpleDockLayoutState.Restore;
var
i: Integer;
begin
for i := 0 to Pred(States.Count) do
TSimpleDockState(States[i]).Restore;
end;
end.
|
unit AnLinkEnum;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ToolWin, ImgList, ActnList, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData,
cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
cxButtonEdit, FIBDatabase, pFIBDatabase,Ibase, FIBDataSet, pFIBDataSet,
cxTextEdit,pFibStoredProc;
type
TfrmAnMain = class(TForm)
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
columnst: TcxStyle;
ActionList1: TActionList;
Action1: TAction;
SmallImages: TImageList;
ToolBar1: TToolBar;
DeleteButton: TToolButton;
ToolButton2: TToolButton;
ToolButton1: TToolButton;
CloseButton: TToolButton;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
cxGrid1DBTableView1DBColumn1: TcxGridDBColumn;
cxGrid1DBTableView1DBColumn2: TcxGridDBColumn;
WorkDatabase: TpFIBDatabase;
WriteTransaction: TpFIBTransaction;
ReadTransaction: TpFIBTransaction;
AnDataSet: TpFIBDataSet;
AnDataSource: TDataSource;
Action2: TAction;
cxGrid1DBTableView1DBColumn3: TcxGridDBColumn;
procedure cxGrid1DBTableView1DBColumn2PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure Action2Execute(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure cxGrid1DBTableView1DBColumn3PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
ResultValue:Variant;
constructor Create(AOwner: TComponent; DB_HANDLE: TISC_DB_HANDLE; FS: TFormStyle);
{ Public declarations }
end;
function GetIniAnalitic(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE;FS:TFormStyle):Variant;stdcall;
exports GetIniAnalitic;
implementation
uses UseEnumsMain, GlobalSpr;
function GetIniAnalitic(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE;FS:TFormStyle):Variant;
var T:TfrmAnMain;
Res:Variant;
begin
if FS=fsNormal
then begin
T:=TfrmAnMain.Create(AOwner,DB_HANDLE,FS);
if T.ShowModal=mrYes
then begin
Res:=T.ResultValue;
end
else Res:=NULL;
T.Free;
end
else begin
Res:=Integer(TfrmAnMain.Create(AOwner,DB_HANDLE,FS));
end;
end;
{$R *.dfm}
{ TfrmAnMain }
constructor TfrmAnMain.Create(AOwner: TComponent;
DB_HANDLE: TISC_DB_HANDLE; FS: TFormStyle);
begin
Inherited Create(AOwner);
self.FormStyle:=FS;
WorkDatabase.Handle:=DB_HANDLE;
AnDataSet.Open;
end;
procedure TfrmAnMain.cxGrid1DBTableView1DBColumn2PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var Res:Variant;
Sp:TpFibStoredProc;
New_id:Integer;
begin
Res:=GlobalSpr.GetEnums(self,WorkDatabase.Handle,fsNormal);
if Res<>NULL
then begin
Sp:=TpFibStoredProc.Create(self);
Sp.Database:=WorkDatabase;
Sp.Transaction:=ReadTransaction;
Sp.StoredProcName:='PUB_SPR_ANALITIC_UPDATE';
Sp.Transaction.StartTransaction;
Sp.Prepare;
New_id:=AnDataSet.FieldByName('ID_ANALITIC').AsInteger;
Sp.ParamByName('ID_ANALITIC').AsInteger:=AnDataSet.FieldByName('ID_ANALITIC').AsInteger;
Sp.ParamByName('ID_TYPE_ENUM').AsString:=Res;
Sp.ExecProc;
Sp.Transaction.Commit;
Sp.Free;
AnDataSet.CloseOpen(true);
AnDataSet.Locate('ID_ANALITIC',new_id,[]);
end;
end;
procedure TfrmAnMain.Action2Execute(Sender: TObject);
begin
if self.WindowState=wsMaximized
then self.WindowState:=wsNormal
else self.WindowState:=wsMaximized;
end;
procedure TfrmAnMain.DeleteButtonClick(Sender: TObject);
var Sp:TpFibStoredProc;
New_id:Integer;
begin
if MessageBox(Handle,PChar('Вы хотите удалить привязку к перечислению?'),PChar('Внимание!'),MB_YESNO or MB_ICONERROR)=idYes
then begin
Sp:=TpFibStoredProc.Create(self);
Sp.Database:=WorkDatabase;
Sp.Transaction:=ReadTransaction;
Sp.StoredProcName:='PUB_SPR_ANALITIC_DELETE';
Sp.Transaction.StartTransaction;
Sp.Prepare;
New_id:=AnDataSet.FieldByName('ID_ANALITIC').AsInteger;
Sp.ParamByName('ID_ANALITIC').AsInteger:=AnDataSet.FieldByName('ID_ANALITIC').AsInteger;
Sp.ExecProc;
Sp.Transaction.Commit;
Sp.Free;
AnDataSet.CloseOpen(true);
AnDataSet.Locate('ID_ANALITIC',new_id,[]);
end;
end;
procedure TfrmAnMain.cxGrid1DBTableView1DBColumn3PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var Sp:TpFibStoredProc;
New_id:integer;
New_Note:String;
begin
New_Note:=inputbox('Работа с аналитикой','Введите наименование аналитики',AnDataSet.FieldByName('NOTE').AsString);
Sp:=TpFibStoredProc.Create(self);
Sp.Database:=WorkDatabase;
Sp.Transaction:=ReadTransaction;
Sp.StoredProcName:='PUB_SPR_ANALITIC_UPDATE_NOTE';
Sp.Transaction.StartTransaction;
Sp.Prepare;
New_id:=AnDataSet.FieldByName('ID_ANALITIC').AsInteger;
Sp.ParamByName('ID_ANALITIC').AsInteger:=AnDataSet.FieldByName('ID_ANALITIC').AsInteger;
Sp.ParamByName('NOTE').AsString:=New_Note;
Sp.ExecProc;
Sp.Transaction.Commit;
Sp.Free;
AnDataSet.CloseOpen(true);
AnDataSet.Locate('ID_ANALITIC',new_id,[]);
end;
procedure TfrmAnMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
end;
end.
|
unit uExplorerPastePIDLsThread;
interface
uses
Windows,
System.Classes,
uDBForm,
uConstants,
uPortableDeviceUtils,
uShellNamespaceUtils,
ActiveX,
System.Types,
uDBThread;
type
TExplorerPastePIDLsThread = class(TDBThread)
private
{ Private declarations }
FPath: string;
Handle: HWND;
protected
procedure Execute; override;
public
constructor Create(OwnerForm: TDBForm; ToDirectory: string);
end;
implementation
{ TExplorerPastePIDLsThread }
constructor TExplorerPastePIDLsThread.Create(OwnerForm: TDBForm;
ToDirectory: string);
begin
inherited Create(OwnerForm, False);
FPath := ToDirectory;
Handle := OwnerForm.Handle;
end;
procedure TExplorerPastePIDLsThread.Execute;
begin
inherited;
FreeOnTerminate := True;
CoInitialize(nil);
try
if IsDevicePath(FPath) then
begin
Delete(FPath, 1, Length(cDevicesPath) + 1);
ExecuteShellPathRelativeToMyComputerMenuAction(Handle, FPath, nil, Point(0, 0), nil, 'Paste');
end else
PastePIDListToFolder(Handle, FPath);
finally
CoUninitialize;
end;
end;
end.
|
unit uOrderReserveDlg;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, UCCenterJournalNetZkz, uActionCore, UtilsBase;
type
TfmOrderReserveDlg = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
rbAll: TRadioButton;
rbItem: TRadioButton;
rbSubItem: TRadioButton;
lbItem: TLabel;
lbSubItem: TLabel;
procedure OKBtnClick(Sender: TObject);
private
{ Private declarations }
FOrderItem: TJSO_OrderHeaderItem;
FSpecItem: TJSO_ItemOrder;
FSubItemId: Integer;
FReserveType: TReserveType;
procedure InitControls;
public
{ Public declarations }
class function Execute(OrderItem: TJSO_OrderHeaderItem;
SpecItem: TJSO_ItemOrder; SubItemId: Integer; var ReserveType: TReserveType): Boolean;
end;
var
fmOrderReserveDlg: TfmOrderReserveDlg;
implementation
{$R *.dfm}
class function TfmOrderReserveDlg.Execute(OrderItem: TJSO_OrderHeaderItem;
SpecItem: TJSO_ItemOrder; SubItemId: Integer; var ReserveType: TReserveType): Boolean;
begin
with TfmOrderReserveDlg.Create(nil) do
try
FOrderItem := OrderItem;
FSpecItem := SpecItem;
FSubItemId := SubItemId;
try
InitControls;
Result := ShowModal = mrOk;
ReserveType := FReserveType;
except
on E: Exception do
begin
ShowError(E.Message);
Result := false;
end;
end;
finally
Free;
end;
end;
procedure TfmOrderReserveDlg.InitControls;
var
vName: string;
begin
rbSubItem.Visible := FSubItemId <> 0;
lbSubItem.Visible := rbSubItem.Visible;
if length(FSpecItem.itemName) > 40 then
vName := Copy(FSpecItem.itemName, 1, 40) + '...'
else
vName := FSpecItem.itemName;
lbItem.Caption := Format('AртКод: %d, Наименование: %s', [FSpecItem.itemCode, vName]);
lbSubItem.Caption := Format('ID: %d', [FSubItemId]);
if not rbSubItem.Visible then
Self.Height := 175;
end;
procedure TfmOrderReserveDlg.OKBtnClick(Sender: TObject);
begin
if rbItem.Checked then
FReserveType := rtItem
else if rbSubItem.Checked then
FReserveType := rtSubItem
else
FReserveType := rtAll;
end;
end.
|
Unit Box;
Interface
{ Nov-Dec 1987 Turbo Technix }
Uses Crt;
Var TopLine : Char;
LeftLine : Char;
BottomLine : Char;
RightLine : Char;
TopLeftCorner : Char;
TopRightCorner : Char;
BottomLeftCorner : Char;
BottomRightCorner : Char;
Procedure DrawBox(Top,Left,Bottom,Right:Integer);
Implementation
Const
DefTop = #205;
DefLeft = #179;
DefBottom = #196;
DefRight = #179;
DefTopLeft = #213;
DefTopRight = #184;
DefBottomLeft = #192;
DefBottomRight = #217;
Procedure DrawBox(* (Top,Left,Bottom,Right:Integer)*);
Var
X,Y : Integer;
Begin
GotoXY(Left,Top);
Write(TopLeftCorner);
GotoXY(Right,Top);
Write(TopRightCorner);
GotoXY(Left,Bottom);
Write(BottomLeftCorner);
GotoXY(Right,Bottom);
Write(BottomRightCorner);
GotoXY(Left+1,Top);
For X:=(Left+1) to (Right-1) DO
Write(TopLine);
GotoXY(Left+1,Bottom);
For X:=(Left+1) To (Right-1) DO
Write(BottomLine);
For Y:=(Top+1) To (Bottom-1) DO Begin
GotoXY(Left,Y);
Write(LeftLine);
GotoXY(Right,Y);
Write(RightLine);
End; {For}
End; {DrawBox}
Begin { Unit Initialization }
TopLine := DefTop;
LeftLine := DefLeft;
BottomLine := DefBottom;
RightLine := DefRight;
TopLeftCorner := DefTopLeft;
TopRightCorner := DefTopRight;
BottomLeftCorner := DefBottomLeft;
BottomRightCorner := DefBottomRight;
End. |
unit ibSHQuery;
interface
uses
SysUtils, Classes, Controls, Contnrs, Forms,
SHDesignIntf,
ibSHDesignIntf, ibSHDBObject;
type
TibSHQuery = class(TibBTDBObject, IibSHQuery)
private
FData: IibSHData;
FFieldList: TComponentList;
{ IibSHQuery }
function GetData: IibSHData;
procedure SetData(Value: IibSHData);
function GetField(Index: Integer): IibSHField;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Refresh; override;
end;
implementation
{ TibSHQuery }
constructor TibSHQuery.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFieldList := TComponentList.Create;
State := csSource;
end;
destructor TibSHQuery.Destroy;
begin
FFieldList.Free;
inherited Destroy;
end;
function TibSHQuery.GetData: IibSHData;
begin
Result := FData;
end;
procedure TibSHQuery.SetData(Value: IibSHData);
begin
if FData <> Value then
begin
ReferenceInterface(FData, opRemove);
FData := Value;
ReferenceInterface(FData, opInsert);
end;
end;
function TibSHQuery.GetField(Index: Integer): IibSHField;
begin
Assert(Index <= Pred(Fields.Count), 'Index out of bounds');
Supports(CreateParam(FFieldList, IibSHField, Index), IibSHField, Result);
end;
procedure TibSHQuery.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) then
begin
if AComponent.IsImplementorOf(FData) then
FData := nil;
end;
inherited Notification(AComponent, Operation);
end;
procedure TibSHQuery.Refresh;
begin
FFieldList.Clear;
inherited Refresh;
end;
end.
|
namespace RemObjects.Elements.EUnit;
interface
type
AssertMessages = public static class
public
const Unknown = "Unknown failure";
const NoException = "Action does not throw an exception";
const UnexpectedException = "Unexpected exception: <{0}>";
const NotEqual = "Expected: <{1}> but was: <{0}>";
const Equal = "Actual value expected to be different from <{1}>";
const LessExpected = "Value expected to be less than <{1}>, but was: <{0}>";
const LessOrEqualExpected = "Value expected to be less than or equal to <{1}>, but was: <{0}>";
const GreaterExpected = "Value expected to be greater than <{1}>, but was: <{0}>";
const GreaterOrEqualExpected = "Value expected to be greater than or equal to <{1}>, but was: <{0}>";
const StringPrefixMissing = "String <{1}> does not starts with <{0}>";
const StringSufixMissing = "String <{1}> does not ends with <{0}>";
const UnexpectedContains = "{1} contains unexpected element: <{0}>";
const DoesNotContains = "{1} does not contains element: <{0}>";
const ObjectIsNil = "Object is nil";
const ValueIsNaN = "Value is NaN";
const ValueIsNotNaN = "NaN expected but was: <{0}>";
const ValueIsInf = "Value is infinity";
const ValueIsNotInf = "Infinity expected but was: <{0}>";
const IsNotEmpty = "{1} is not empty";
const IsEmpty = "{1} is empty";
//sequences
const SequenceExpected = "[Sequence] expected but got (nil)";
const SequenceUnexpected = "(nil) expected but got [Sequence]";
const SequenceLengthDiffers = "Element count differs. Expected: <{0}> but was: <{1}>";
const SequenceElementMissing = "Expected element <{0}> is missing from actual sequence";
const SequenceEquals = "Sequence equals but expected to be different";
end;
implementation
end. |
unit UpOrderListSettings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxCheckBox, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit,
cxDBLookupComboBox, StdCtrls, Buttons, ExtCtrls, DB, FIBDataSet,
pFIBDataSet, pFibStoredProc, cxCalendar, ComCtrls, cxCalc, cxStyles,
cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxDBData,
ToolWin, ImgList, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGridCustomView, cxGrid, cxClasses, cxColorComboBox,
cxButtonEdit, cxLookAndFeelPainters, cxButtons, cxSplitter, UpDefSignersFrame;
type
TfrmGetSettings = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
OkButton: TBitBtn;
CancelButton: TBitBtn;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
Label2: TLabel;
LevelsObject: TcxLookupComboBox;
Label1: TLabel;
TypesObject: TcxLookupComboBox;
UseAccessInfo: TcxCheckBox;
UseMaxRateCount: TcxCheckBox;
MaxRateCount: TcxCalcEdit;
TabSheet3: TTabSheet;
StyleRepository: TcxStyleRepository;
stBackground: TcxStyle;
stContent: TcxStyle;
stContentEven: TcxStyle;
stContentOdd: TcxStyle;
stFilterBox: TcxStyle;
stFooter: TcxStyle;
stGroup: TcxStyle;
stGroupByBox: TcxStyle;
stHeader: TcxStyle;
stInactive: TcxStyle;
stIncSearch: TcxStyle;
stIndicator: TcxStyle;
stPreview: TcxStyle;
stSelection: TcxStyle;
stHotTrack: TcxStyle;
qizzStyle: TcxGridTableViewStyleSheet;
ItemsGrid: TcxGrid;
LevelsView: TcxGridDBTableView;
cxGridDBColumn5: TcxGridDBColumn;
cxGridDBColumn6: TcxGridDBColumn;
cxGridDBColumn7: TcxGridDBColumn;
cxGridLevel6: TcxGridLevel;
IL_Orders: TImageList;
ToolBar1: TToolBar;
ToolButton2: TToolButton;
RefreshButton: TToolButton;
LevelsViewDBColumn1: TcxGridDBColumn;
LevelsViewDBColumn2: TcxGridDBColumn;
LevelsViewDBColumn3: TcxGridDBColumn;
RETURN_DAY_COUNT: TcxTextEdit;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
ReestrObject: TcxLookupComboBox;
USE_CHECK_MAX_POCHAS_COUNT: TcxCheckBox;
MAX_POCHAS_COUNT: TcxCalcEdit;
USE_RAISE_ABSORB: TcxCheckBox;
TabSheet4: TTabSheet;
ToolBar2: TToolBar;
ToolButton1: TToolButton;
cxGrid1: TcxGrid;
TypesView: TcxGridDBTableView;
cxGridDBColumn1: TcxGridDBColumn;
cxGridDBColumn2: TcxGridDBColumn;
cxGridDBColumn3: TcxGridDBColumn;
cxGridDBColumn4: TcxGridDBColumn;
cxGridLevel1: TcxGridLevel;
TypesViewDBColumn1: TcxGridDBColumn;
TabSheet5: TTabSheet;
Label6: TLabel;
HOLIDAY_FOR_SOVMEST_FULL_NAME: TcxButtonEdit;
USE_AUTO_HOLIDAY_FOR_SOVMEST: TcxCheckBox;
Grid: TcxGrid;
PlanBplView: TcxGridDBTableView;
cxGridDBColumn8: TcxGridDBColumn;
cxGridDBColumn9: TcxGridDBColumn;
cxGridDBColumn10: TcxGridDBColumn;
Level: TcxGridLevel;
cxButton1: TcxButton;
cxButton2: TcxButton;
Label11: TLabel;
TabSheet6: TTabSheet;
Label7: TLabel;
ACCEPT_SHADOW_ID_TYPE_TEXT: TcxButtonEdit;
Label8: TLabel;
SET_BONUS_SHADOW_ID_TYPE_TEXT: TcxButtonEdit;
Label9: TLabel;
SET_HOLIDAY_SHADOW_ID_TYPE_TEXT: TcxButtonEdit;
Label10: TLabel;
SET_COMPENSS_SHADOW_ID_TYPE_TEXT: TcxButtonEdit;
Label12: TLabel;
DEFAULT_WORK_LEVEL_TEXT: TcxButtonEdit;
Label13: TLabel;
SET_AWAY_HOLIDAY_SHADOW_TEXT: TcxButtonEdit;
TabSheet7: TTabSheet;
cxGrid2: TcxGrid;
ExtRepView: TcxGridDBTableView;
cxGridDBColumn11: TcxGridDBColumn;
cxGridDBColumn12: TcxGridDBColumn;
cxGridDBColumn13: TcxGridDBColumn;
cxGridLevel2: TcxGridLevel;
cxButton3: TcxButton;
cxButton4: TcxButton;
PERMIT_NOT_UNIQ_ORDER_NUM: TcxCheckBox;
ToolButton4: TToolButton;
Label14: TLabel;
SET_FULL_AWAY_INST_NAME: TcxButtonEdit;
ToolButton3: TToolButton;
Label15: TLabel;
CheckReestrAttr: TcxLookupComboBox;
SignTypes: TpFIBDataSet;
Label16: TLabel;
CUR_PROJECT_NUM: TcxTextEdit;
TabSheet8: TTabSheet;
Panel3: TPanel;
PageControl2: TPageControl;
ENABLE_EDIT_PROJECT_NUM: TcxCheckBox;
cxCheckBox1: TcxCheckBox;
TypesViewDBColumn2: TcxGridDBColumn;
Label17: TLabel;
MOVE_SHADOW_NAME: TcxButtonEdit;
Label18: TLabel;
REMOVE_BONUS_SHADOW_NAME: TcxButtonEdit;
cxgrdbclmnLevelsViewDBColumn4: TcxGridDBColumn;
cxchckbxMAY_WORK_WITH_DISMISS: TcxCheckBox;
ts1: TTabSheet;
cxButton5: TcxButton;
cxButton6: TcxButton;
cxButton7: TcxButton;
cxGrid3: TcxGrid;
SpecModulesView: TcxGridDBTableView;
cxGridDBColumn14: TcxGridDBColumn;
cxGridDBColumn15: TcxGridDBColumn;
cxGridDBColumn16: TcxGridDBColumn;
cxGridLevel3: TcxGridLevel;
TypesViewDBColumn3: TcxGridDBColumn;
CancelDBColumn: TcxGridDBColumn;
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ToolButton2Click(Sender: TObject);
procedure cxGridDBColumn7StylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; out AStyle: TcxStyle);
procedure LevelsViewDBColumn1StylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; out AStyle: TcxStyle);
procedure RefreshButtonClick(Sender: TObject);
procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure ACCEPT_SHADOW_ID_TYPE_TEXTPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure SET_BONUS_SHADOW_ID_TYPE_TEXTPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure SET_COMPENSS_SHADOW_ID_TYPE_TEXTPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure cxButton1Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure SET_HOLIDAY_SHADOW_ID_TYPE_TEXTPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure DEFAULT_WORK_LEVEL_TEXTPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure SET_AWAY_HOLIDAY_SHADOW_TEXTPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure cxButton3Click(Sender: TObject);
procedure cxButton4Click(Sender: TObject);
procedure ToolButton1Click(Sender: TObject);
procedure ToolButton4Click(Sender: TObject);
procedure SET_FULL_AWAY_INST_NAMEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure ToolButton3Click(Sender: TObject);
procedure PageControl2Change(Sender: TObject);
procedure MOVE_SHADOW_NAMEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure REMOVE_BONUS_SHADOW_NAMEPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure cxButton5Click(Sender: TObject);
procedure cxButton7Click(Sender: TObject);
procedure cxButton6Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
ID_TYPE_HOLIDAY: Integer;
ACCEPT_SHADOW_ID_TYPE: Integer;
SET_BONUS_SHADOW_ID_TYPE: Integer;
SET_COMPENSS_SHADOW_ID_TYPE: Integer;
SET_HOLIDAY_SHADOW_ID_TYPE: Integer;
SET_AWAY_HOLIDAY_SHADOW_ID_TYPE: Integer;
MOVE_SHADOW_ID_TYPE: Integer;
REMOVE_BONUS_SHADOW_ID_TYPE: Integer;
DEFAULT_WORK_LEVEL: Integer;
SET_FULL_AWAY_INST: Integer;
Modules: array of TUP_DefSignersFrame;
ModTypes: array of Int64;
procedure TabVisible;
end;
implementation
uses UpOrderList, ULevelsEdit, RxmemDS, uUnivSprav, UEditPlanBpl, BaseTypes,
UEditExtReport, UEditTypes, uFormControl, USpecModuleEdit;
{$R *.dfm}
procedure TfrmGetSettings.OkButtonClick(Sender: TObject);
begin
ModalResult := mrYes;
end;
procedure TfrmGetSettings.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrNo;
end;
procedure TfrmGetSettings.FormCreate(Sender: TObject);
begin
LevelsObject.Properties.ListSource := TUpOrderListForm(self.Owner).LevelsObjectPathDataSource;
TypesObject.Properties.ListSource := TUpOrderListForm(self.Owner).TypesObjectDataSource;
ReestrObject.Properties.ListSource := TUpOrderListForm(self.Owner).OrderViewObjectDataSet;
CheckReestrAttr.Properties.ListSource := TUpOrderListForm(self.Owner).CheckReestrAttrDataSource;
LevelsView.DataController.DataSource := TUpOrderListForm(self.Owner).LevelsDataSource;
TypesView.DataController.DataSource := TUpOrderListForm(self.Owner).TypesDataSource;
SpecModulesView.DataController.DataSource := TUpOrderListForm(self.Owner).dsSpecModuleDataSource;
PlanBplView.DataController.DataSource := TUpOrderListForm(self.Owner).PlanBplDataSource;
ExtRepView.DataController.DataSource := TUpOrderListForm(self.Owner).ExtRepDataSource;
SignTypes.Database := TUpOrderListForm(self.Owner).WorkDatabase;
SignTypes.Transaction := TUpOrderListForm(self.Owner).ReadTransaction;
PageControl1.ActivePageIndex := 0;
TabVisible;
PageControl2.OnChange(PageControl2);
end;
procedure TfrmGetSettings.ToolButton2Click(Sender: TObject);
var T: TfrmUpLevelsEdit;
UpdateSP: TpFibStoredProc;
id_: Integer;
begin
T := TfrmUpLevelsEdit.Create(self);
if LevelsView.DataController.DataSource.DataSet.FieldByName('FONT_COLOR').Value <> null
then T.FontColor.ColorValue := LevelsView.DataController.DataSource.DataSet.FieldByName('FONT_COLOR').Value;
if LevelsView.DataController.DataSource.DataSet.FieldByName('CONTENT_COLOR').Value <> null
then T.ContentColor.ColorValue := LevelsView.DataController.DataSource.DataSet.FieldByName('CONTENT_COLOR').Value;
T.levelName.Text := LevelsView.DataController.DataSource.DataSet.FieldByName('LEVEL_NAME').AsString;
if LevelsView.DataController.DataSource.DataSet.FieldByName('ID_LEVEL').Value = -1
then T.levelName.Enabled := false;
if LevelsView.DataController.DataSource.DataSet.FieldByName('MAY_EDIT_REG_ATTR').Value <> null
then T.cxchckbx1.Checked := Boolean(LevelsView.DataController.DataSource.DataSet.FieldByName('MAY_EDIT_REG_ATTR').AsInteger);
if T.ShowModal = mrOk
then begin
id_ := LevelsView.DataController.DataSource.DataSet.FieldByName('ID_LEVEL').Value;
UpdateSP := TpFibStoredProc.Create(self);
UpdateSP.Database := TUpOrderListForm(self.Owner).WorkDatabase;
UpdateSP.Transaction := TUpOrderListForm(self.Owner).WriteTransaction;
TUpOrderListForm(self.Owner).WriteTransaction.StartTransaction;
UpdateSP.StoredProcName := 'UP_SYS_LEVEL_UPD';
UpdateSP.Prepare;
UpdateSP.ParamByName('LEVEL_NAME').Value := T.levelName.Text;
UpdateSP.ParamByName('FONT_COLOR').Value := T.FontColor.ColorValue;
UpdateSP.ParamByName('CONTENT_COLOR').Value := T.ContentColor.ColorValue;
UpdateSP.ParamByName('MAY_EDIT_REG_ATTR').Value := Integer(T.cxchckbx1.Checked);
UpdateSP.ParamByName('ID_LEVEL').Value := LevelsView.DataController.DataSource.DataSet.FieldByName('ID_LEVEL').Value;
UpdateSP.ExecProc;
UpdateSP.Close;
UpdateSP.Free;
TUpOrderListForm(self.Owner).WriteTransaction.Commit;
TpFibDataSet(LevelsView.DataController.DataSource.DataSet).CloseOpen(true);
LevelsView.DataController.DataSource.DataSet.Locate('id_level', id_, []);
end;
T.Free;
end;
procedure TfrmGetSettings.cxGridDBColumn7StylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; out AStyle: TcxStyle);
var LocStyle: TcxStyle;
begin
if ARecord.Values[4] <> null
then begin
LocStyle := TcxStyle.Create(nil);
LocStyle.Color := ARecord.Values[4];
AStyle := LocStyle;
end;
end;
procedure TfrmGetSettings.LevelsViewDBColumn1StylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; out AStyle: TcxStyle);
var LocStyle: TcxStyle;
begin
if ARecord.Values[5] <> null
then begin
LocStyle := TcxStyle.Create(nil);
LocStyle.Color := ARecord.Values[5];
AStyle := LocStyle;
end
end;
procedure TfrmGetSettings.RefreshButtonClick(Sender: TObject);
begin
TpFibDataSet(LevelsView.DataController.DataSource.DataSet).CloseOpen(true);
end;
procedure TfrmGetSettings.cxButtonEdit1PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів відпусток';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'HL_SP_TYPE_HOLIDAY_SEL';
Params.Fields := 'FULL_NAME,ID_TYPE_HOLIDAY';
Params.FieldsName := 'Назва';
Params.KeyField := 'ID_TYPE_HOLIDAY';
Params.ReturnFields := 'FULL_NAME,ID_TYPE_HOLIDAY';
Params.DBHandle := Integer(TUpOrderListForm(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
ID_TYPE_HOLIDAY := output['ID_TYPE_HOLIDAY'];
HOLIDAY_FOR_SOVMEST_FULL_NAME.Text := VarToStr(output['FULL_NAME']);
end;
end;
procedure TfrmGetSettings.ACCEPT_SHADOW_ID_TYPE_TEXTPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів наказів';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'UP_DT_ORDER_TYPE_SEL_EX';
Params.Fields := 'TYPE_NAME,ID_TYPE';
Params.FieldsName := 'Назва';
Params.KeyField := 'ID_TYPE';
Params.ReturnFields := 'TYPE_NAME,ID_TYPE';
Params.DBHandle := Integer(TUpOrderListForm(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
ACCEPT_SHADOW_ID_TYPE := output['ID_TYPE'];
ACCEPT_SHADOW_ID_TYPE_TEXT.Text := VarToStr(output['TYPE_NAME']);
end;
end;
procedure TfrmGetSettings.SET_BONUS_SHADOW_ID_TYPE_TEXTPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів наказів';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'UP_DT_ORDER_TYPE_SEL_EX';
Params.Fields := 'TYPE_NAME,ID_TYPE';
Params.FieldsName := 'Назва';
Params.KeyField := 'ID_TYPE';
Params.ReturnFields := 'TYPE_NAME,ID_TYPE';
Params.DBHandle := Integer(TUpOrderListForm(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
SET_BONUS_SHADOW_ID_TYPE := output['ID_TYPE'];
SET_BONUS_SHADOW_ID_TYPE_TEXT.Text := VarToStr(output['TYPE_NAME']);
end;
end;
procedure TfrmGetSettings.SET_COMPENSS_SHADOW_ID_TYPE_TEXTPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів наказів';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'UP_DT_ORDER_TYPE_SEL_EX';
Params.Fields := 'TYPE_NAME,ID_TYPE';
Params.FieldsName := 'Назва';
Params.KeyField := 'ID_TYPE';
Params.ReturnFields := 'TYPE_NAME,ID_TYPE';
Params.DBHandle := Integer(TUpOrderListForm(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
SET_COMPENSS_SHADOW_ID_TYPE := output['ID_TYPE'];
SET_COMPENSS_SHADOW_ID_TYPE_TEXT.Text := VarToStr(output['TYPE_NAME']);
end;
end;
procedure TfrmGetSettings.cxButton1Click(Sender: TObject);
var T: TfrmEditPlanBpl;
InsertSP: TpFibStoredProc;
begin
T := TfrmEditPlanBpl.Create(self);
if T.ShowModal = mrYes
then begin
InsertSP := TpFibStoredProc.Create(self);
InsertSP.Database := TUpOrderListForm(self.Owner).WorkDatabase;
InsertSP.Transaction := TUpOrderListForm(self.Owner).WriteTransaction;
TUpOrderListForm(self.Owner).WriteTransaction.StartTransaction;
InsertSP.StoredProcName := 'HL_SYS_BPL_INS';
InsertSP.Prepare;
InsertSP.ParamByName('BPL_NAME').Value := T.BplName.Text;
InsertSP.ParamByName('DATE_BEG').Value := T.DateStart.Date;
InsertSP.ExecProc;
TUpOrderListForm(self.Owner).WriteTransaction.Commit;
TUpOrderListForm(self.Owner).PlanBplDataSet.CloseOpen(true);
InsertSP.Close;
InsertSP.Free;
end;
T.Free;
end;
procedure TfrmGetSettings.cxButton2Click(Sender: TObject);
var DropSP: TpFibStoredProc;
begin
if TUpOrderListForm(self.Owner).PlanBplDataSet.RecordCount > 0
then begin
if agMessageDlg('Увага!', 'Ви хочете видалити запис?', mtConfirmation, [mbYes, MbNo]) = mrYes
then begin
DropSP := TpFibStoredProc.Create(self);
DropSP.Database := TUpOrderListForm(self.Owner).WorkDatabase;
DropSP.Transaction := TUpOrderListForm(self.Owner).WriteTransaction;
TUpOrderListForm(self.Owner).WriteTransaction.StartTransaction;
DropSP.StoredProcName := 'HL_SYS_BPL_DEL';
DropSP.Prepare;
DropSP.ParamByName('ID_BPL').Value := TUpOrderListForm(self.Owner).PlanBplDataSet.FieldByName('ID_BPL').Value;
DropSP.ExecProc;
TUpOrderListForm(self.Owner).WriteTransaction.Commit;
TUpOrderListForm(self.Owner).PlanBplDataSet.CloseOpen(true);
DropSP.Close;
DropSP.Free;
end;
end;
end;
procedure TfrmGetSettings.SET_HOLIDAY_SHADOW_ID_TYPE_TEXTPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів наказів';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'UP_DT_ORDER_TYPE_SEL_EX';
Params.Fields := 'TYPE_NAME,ID_TYPE';
Params.FieldsName := 'Назва';
Params.KeyField := 'ID_TYPE';
Params.ReturnFields := 'TYPE_NAME,ID_TYPE';
Params.DBHandle := Integer(TUpOrderListForm(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
SET_HOLIDAY_SHADOW_ID_TYPE := output['ID_TYPE'];
SET_HOLIDAY_SHADOW_ID_TYPE_TEXT.Text := VarToStr(output['TYPE_NAME']);
end;
end;
procedure TfrmGetSettings.DEFAULT_WORK_LEVEL_TEXTPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник рівнів актуальності';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'UP_SYS_LEVEL';
Params.Fields := 'LEVEL_ORDER,LEVEL_NAME,ID_LEVEL';
Params.FieldsName := 'Порядок,Назва';
Params.KeyField := 'ID_LEVEL';
Params.ReturnFields := 'LEVEL_ORDER,LEVEL_NAME,ID_LEVEL';
Params.DBHandle := Integer(TUpOrderListForm(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
DEFAULT_WORK_LEVEL := output['ID_LEVEL'];
DEFAULT_WORK_LEVEL_TEXT.Text := VarToStr(output['LEVEL_NAME']);
end;
end;
procedure TfrmGetSettings.SET_AWAY_HOLIDAY_SHADOW_TEXTPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів наказів';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'UP_DT_ORDER_TYPE_SEL_EX';
Params.Fields := 'TYPE_NAME,ID_TYPE';
Params.FieldsName := 'Назва';
Params.KeyField := 'ID_TYPE';
Params.ReturnFields := 'TYPE_NAME,ID_TYPE';
Params.DBHandle := Integer(TUpOrderListForm(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
SET_AWAY_HOLIDAY_SHADOW_ID_TYPE := output['ID_TYPE'];
SET_AWAY_HOLIDAY_SHADOW_TEXT.Text := VarToStr(output['TYPE_NAME']);
end;
end;
procedure TfrmGetSettings.cxButton3Click(Sender: TObject);
var T: TfrmGetExtReport;
InsertSp: TpFibStoredProc;
begin
T := TfrmGetExtReport.Create(self);
if T.ShowModal = mrYes
then begin
InsertSp := TpFibStoredProc.Create(self);
InsertSp.Database := TUpOrderListForm(self.Owner).WorkDatabase;
InsertSp.Transaction := TUpOrderListForm(self.Owner).WriteTransaction;
TUpOrderListForm(self.Owner).WriteTransaction.StartTransaction;
InsertSp.StoredProcName := 'UP_DT_ORDER_TYPE_EXT_REPORT_INS';
InsertSp.Prepare;
InsertSp.ParamByName('REPORT_TITLE').Value := T.ReportName.EditValue;
InsertSp.ParamByName('ID_ORDER_TYPE').Value := T.id_order_type;
InsertSp.ParamByName('MODULE').Value := T.ReportModule.EditValue;
InsertSp.ExecProc;
InsertSp.Close;
InsertSp.Free;
TUpOrderListForm(self.Owner).WriteTransaction.Commit;
TUpOrderListForm(self.Owner).ExtRepDataSet.CloseOpen(true);
end;
T.Free;
end;
procedure TfrmGetSettings.cxButton4Click(Sender: TObject);
var InsertSp: TpFibStoredProc;
begin
if TUpOrderListForm(self.Owner).ExtRepDataSet.RecordCount > 0
then begin
if agMessageDlg('Увага!', 'Ви хочете видалити запис?', mtConfirmation, [mbYes, mbNo]) = mryES
then begin
InsertSp := TpFibStoredProc.Create(self);
InsertSp.Database := TUpOrderListForm(self.Owner).WorkDatabase;
InsertSp.Transaction := TUpOrderListForm(self.Owner).WriteTransaction;
TUpOrderListForm(self.Owner).WriteTransaction.StartTransaction;
InsertSp.StoredProcName := 'UP_DT_ORDER_TYPE_EXT_REPORT_DEL';
InsertSp.Prepare;
InsertSp.ParamByName('ID_REPORT').Value := TUpOrderListForm(self.Owner).ExtRepDataSet.FieldByName('ID_REPORT').Value;
InsertSp.ExecProc;
InsertSp.Close;
InsertSp.Free;
TUpOrderListForm(self.Owner).WriteTransaction.Commit;
TUpOrderListForm(self.Owner).ExtRepDataSet.CloseOpen(true);
end;
end;
end;
procedure TfrmGetSettings.ToolButton1Click(Sender: TObject);
var
T: TfrmEditTypeInfo;
InsertSp: TpFibStoredProc;
id: integer;
begin
if (TUpOrderListForm(self.Owner).TypesDataSet.RecordCount > 0)
then begin
T := TfrmEditTypeInfo.Create(self);
T.Title.EditValue := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('TYPE_NAME').Value;
T.BplName.EditValue := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('BPL_NAME').Value;
T.PrintShablon.EditValue := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('SHABLON_NAME').Value;
T.PrintProcedure.EditValue := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('PROCEDURE_NAME').Value;
if TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('IS_ACTIVE').Value <> NULL
then T.Is_Active.Checked := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('IS_ACTIVE').Value;
if TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('USE_LOGICAL_LINK').Value <> NULL
then T.use_logic_link.Checked := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('USE_LOGICAL_LINK').Value;
if TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('SHOW_IN_PCARD').Value <> NULL
then T.SHOW_IN_PCARD.Checked := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('SHOW_IN_PCARD').Value;
if TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('IS_CANCEL').Value <> NULL
then T.IS_CANCEL.Checked := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('IS_CANCEL').Value;
if T.ShowModal = mrYes
then begin
InsertSp := TpFibStoredProc.Create(self);
InsertSp.Database := TUpOrderListForm(self.Owner).WorkDatabase;
InsertSp.Transaction := TUpOrderListForm(self.Owner).WriteTransaction;
TUpOrderListForm(self.Owner).WriteTransaction.StartTransaction;
InsertSp.StoredProcName := 'UP_DT_ORDER_TYPE_UPD';
InsertSp.Prepare;
id := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('ID_TYPE').Value;
InsertSp.ParamByName('ID_TYPE').Value := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('ID_TYPE').Value;
InsertSp.ParamByName('TYPE_NAME').Value := T.Title.EditValue;
InsertSp.ParamByName('BPL_NAME').Value := T.BplName.EditValue;
InsertSp.ParamByName('SHABLON_NAME').Value := T.PrintShablon.EditValue;
InsertSp.ParamByName('PROCEDURE_NAME').Value := T.PrintProcedure.EditValue;
InsertSp.ParamByName('IS_ACTIVE').Value := Integer(T.Is_Active.Checked);
InsertSp.ParamByName('USE_LOGICAL_LINK').Value := Integer(T.use_logic_link.Checked);
InsertSp.ParamByName('SHOW_IN_PCARD').Value := Integer(T.SHOW_IN_PCARD.Checked);
InsertSp.ParamByName('IS_CANCEL').Value := Integer(T.IS_CANCEL.Checked);
InsertSp.ExecProc;
InsertSp.Close;
InsertSp.Free;
TUpOrderListForm(self.Owner).WriteTransaction.Commit;
TUpOrderListForm(self.Owner).TypesDataSet.CloseOpen(true);
TUpOrderListForm(self.Owner).TypesDataSet.Locate('ID_TYPE', id, []);
end;
T.Free;
end;
end;
procedure TfrmGetSettings.ToolButton4Click(Sender: TObject);
var
InsertSp: TpFibStoredProc;
id: integer;
begin
if (TUpOrderListForm(self.Owner).TypesDataSet.RecordCount > 0)
then begin
InsertSp := TpFibStoredProc.Create(self);
InsertSp.Database := TUpOrderListForm(self.Owner).WorkDatabase;
InsertSp.Transaction := TUpOrderListForm(self.Owner).WriteTransaction;
TUpOrderListForm(self.Owner).WriteTransaction.StartTransaction;
InsertSp.StoredProcName := 'UP_DT_ORDER_TYPE_CLONE';
InsertSp.Prepare;
InsertSp.ParamByName('ID_TYPE').Value := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('ID_TYPE').Value;
InsertSp.ExecProc;
id := InsertSp.ParamByName('NEW_ID').Value;
InsertSp.Close;
InsertSp.Free;
TUpOrderListForm(self.Owner).WriteTransaction.Commit;
TUpOrderListForm(self.Owner).TypesDataSet.CloseOpen(true);
TUpOrderListForm(self.Owner).TypesDataSet.Locate('ID_TYPE', id, []);
end;
end;
procedure TfrmGetSettings.SET_FULL_AWAY_INST_NAMEPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів наказів';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'UP_DT_ORDER_TYPE_SEL_EX';
Params.Fields := 'TYPE_NAME,ID_TYPE';
Params.FieldsName := 'Назва';
Params.KeyField := 'ID_TYPE';
Params.ReturnFields := 'TYPE_NAME,ID_TYPE';
Params.DBHandle := Integer(TUpOrderListForm(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
SET_FULL_AWAY_INST := output['ID_TYPE'];
SET_FULL_AWAY_INST_NAME.Text := VarToStr(output['TYPE_NAME']);
end;
end;
procedure TfrmGetSettings.ToolButton3Click(Sender: TObject);
var
InsertSp: TpFibStoredProc;
begin
if (TUpOrderListForm(self.Owner).TypesDataSet.RecordCount > 0)
then begin
if agMessageDlg('Увага!', 'Ви хочете видалити запис?', mtConfirmation, [mbYes, mbNo]) = mrYes
then begin
InsertSp := TpFibStoredProc.Create(self);
InsertSp.Database := TUpOrderListForm(self.Owner).WorkDatabase;
InsertSp.Transaction := TUpOrderListForm(self.Owner).WriteTransaction;
TUpOrderListForm(self.Owner).WriteTransaction.StartTransaction;
InsertSp.StoredProcName := 'UP_DT_ORDER_TYPE_DEL';
InsertSp.Prepare;
InsertSp.ParamByName('ID_TYPE').Value := TUpOrderListForm(self.Owner).TypesDataSet.FieldByName('ID_TYPE').Value;
InsertSp.ExecProc;
InsertSp.Close;
InsertSp.Free;
TUpOrderListForm(self.Owner).WriteTransaction.Commit;
TUpOrderListForm(self.Owner).TypesDataSet.CacheDelete;
end;
end;
end;
procedure TfrmGetSettings.TabVisible;
var TabSheet: TTabSheet;
begin
SignTypes.Open;
SignTypes.First;
while not SignTypes.Eof do
begin
SetLength(Modules, Length(Modules) + 1);
SetLength(ModTypes, Length(ModTypes) + 1);
ModTypes[High(ModTypes)] := SignTypes['ID_SIGN_TYPE'];
Modules[High(Modules)] := nil;
TabSheet := TTabSheet.Create(Self);
TabSheet.Caption := SignTypes['type_Name'];
TabSheet.PageControl := PageControl2;
TabSheet.Tag := High(Modules);
SignTypes.Next;
end;
SignTypes.Close;
end;
procedure TfrmGetSettings.PageControl2Change(Sender: TObject);
var
ind: Integer;
SignFrame: TUP_DefSignersFrame;
begin
if PageControl2.ActivePage = nil then Exit;
if PageControl2.ActivePage.Tag = -1 then Exit;
ind := PageControl2.ActivePage.Tag;
if Modules[ind] = nil
then begin
SignFrame := TUP_DefSignersFrame.Create(Self, ModTypes[ind], TUpOrderListForm(self.Owner).WorkDatabase.Handle);
SignFrame.Name := 'SignFrame' + IntToStr(ind);
Modules[ind] := SignFrame;
Modules[ind].Parent := PageControl2.ActivePage;
Modules[ind].Align := alClient;
end;
end;
procedure TfrmGetSettings.MOVE_SHADOW_NAMEPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів наказів';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'UP_DT_ORDER_TYPE_SEL_EX';
Params.Fields := 'TYPE_NAME,ID_TYPE';
Params.FieldsName := 'Назва';
Params.KeyField := 'ID_TYPE';
Params.ReturnFields := 'TYPE_NAME,ID_TYPE';
Params.DBHandle := Integer(TUpOrderListForm(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
self.MOVE_SHADOW_ID_TYPE := output['ID_TYPE'];
MOVE_SHADOW_NAME.Text := VarToStr(output['TYPE_NAME']);
end;
end;
procedure TfrmGetSettings.REMOVE_BONUS_SHADOW_NAMEPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів наказів';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'UP_DT_ORDER_TYPE_SEL_EX';
Params.Fields := 'TYPE_NAME,ID_TYPE';
Params.FieldsName := 'Назва';
Params.KeyField := 'ID_TYPE';
Params.ReturnFields := 'TYPE_NAME,ID_TYPE';
Params.DBHandle := Integer(TUpOrderListForm(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
REMOVE_BONUS_SHADOW_ID_TYPE := output['ID_TYPE'];
REMOVE_BONUS_SHADOW_NAME.Text := VarToStr(output['TYPE_NAME']);
end;
end;
procedure TfrmGetSettings.cxButton5Click(Sender: TObject);
var
T: TfrmSpecModuleEdit;
InsertSp: TpFibStoredProc;
begin
T := TfrmSpecModuleEdit.Create(self);
if T.ShowModal = mrYes
then begin
InsertSp := TpFibStoredProc.Create(self);
InsertSp.Database := TUpOrderListForm(self.Owner).WorkDatabase;
InsertSp.Transaction := TUpOrderListForm(self.Owner).WriteTransaction;
TUpOrderListForm(self.Owner).WriteTransaction.StartTransaction;
InsertSp.StoredProcName := 'UP_DT_SPECIAL_EDIT_MODULES_INS';
InsertSp.Prepare;
InsertSp.ParamByName('SPEC_MODULE_NAME').Value := T.BplName.EditValue;
InsertSp.ParamByName('ID_TYPE').Value := T.id_order_type;
InsertSp.ParamByName('COMMENT').Value := T.cxtxtdtComment.EditValue;
InsertSp.ExecProc;
InsertSp.Close;
InsertSp.Free;
TUpOrderListForm(self.Owner).WriteTransaction.Commit;
TUpOrderListForm(self.Owner).SpecModulesDataSet.CloseOpen(true);
end;
T.Free;
end;
procedure TfrmGetSettings.cxButton7Click(Sender: TObject);
var
T: TfrmSpecModuleEdit;
InsertSp: TpFibStoredProc;
begin
if (TUpOrderListForm(self.Owner).SpecModulesDataSet.RecordCount > 0)
then begin
T := TfrmSpecModuleEdit.Create(self);
T.BplName.EditValue := TUpOrderListForm(self.Owner).SpecModulesDataSet.FieldByName('SPEC_MODULE_NAME').Value;
T.id_order_type := TUpOrderListForm(self.Owner).SpecModulesDataSet.FieldByName('ID_TYPE').Value;
T.cxtxtdtComment.EditValue := TUpOrderListForm(self.Owner).SpecModulesDataSet.FieldByName('COMMENT').Value;
T.OrderTypeText.EditValue := TUpOrderListForm(self.Owner).SpecModulesDataSet.FieldByName('TYPE_NAME').Value;
if T.ShowModal = mrYes
then begin
InsertSp := TpFibStoredProc.Create(self);
InsertSp.Database := TUpOrderListForm(self.Owner).WorkDatabase;
InsertSp.Transaction := TUpOrderListForm(self.Owner).WriteTransaction;
TUpOrderListForm(self.Owner).WriteTransaction.StartTransaction;
InsertSp.StoredProcName := 'UP_DT_SPECIAL_EDIT_MODULES_UPD';
InsertSp.Prepare;
InsertSp.ParamByName('ID_MODULE').Value := TUpOrderListForm(self.Owner).SpecModulesDataSet.FieldByName('ID_MODULE').Value;
InsertSp.ParamByName('SPEC_MODULE_NAME').Value := T.BplName.EditValue;
InsertSp.ParamByName('ID_TYPE').Value := T.id_order_type;
InsertSp.ParamByName('COMMENT').Value := T.cxtxtdtComment.EditValue;
InsertSp.ExecProc;
InsertSp.Close;
InsertSp.Free;
TUpOrderListForm(self.Owner).WriteTransaction.Commit;
TUpOrderListForm(self.Owner).SpecModulesDataSet.CloseOpen(true);
end;
T.Free;
end;
end;
procedure TfrmGetSettings.cxButton6Click(Sender: TObject);
var
InsertSp: TpFibStoredProc;
begin
if (TUpOrderListForm(self.Owner).SpecModulesDataSet.RecordCount > 0)
then begin
if agMessageDlg('Увага!', 'Ви хочете видалити запис?', mtConfirmation, [mbYes, mbNo]) = mrYes
then begin
InsertSp := TpFibStoredProc.Create(self);
InsertSp.Database := TUpOrderListForm(self.Owner).WorkDatabase;
InsertSp.Transaction := TUpOrderListForm(self.Owner).WriteTransaction;
TUpOrderListForm(self.Owner).WriteTransaction.StartTransaction;
InsertSp.StoredProcName := 'UP_DT_SPECIAL_EDIT_MODULES_DEL';
InsertSp.Prepare;
InsertSp.ParamByName('ID_MODULE').Value := TUpOrderListForm(self.Owner).SpecModulesDataSet.FieldByName('ID_MODULE').Value;
InsertSp.ExecProc;
InsertSp.Close;
InsertSp.Free;
TUpOrderListForm(self.Owner).WriteTransaction.Commit;
TUpOrderListForm(self.Owner).SpecModulesDataSet.CacheDelete;
end;
end;
end;
end.
|
(*
Category: SWAG Title: STRING HANDLING ROUTINES
Original name: 0016.PAS
Description: WILDCRD1.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:58
*)
Program wild_card;
Var
check:Boolean;
Function Wild(flname,card:String):Boolean;
{Returns True if the wildcard description in 'card' matches 'flname'
according to Dos wildcard principles. The 'card' String MUST have a period!
Example: Wild('test.tat','t*.t?t' returns True}
Var
name,temp:String[12];
c:Char;
p,i,n,l:Byte;
period:Boolean;
begin
wild:=True;
{test For special Case first}
if flname='*.*' then Exit;
wild:=False;
p:=pos('.',card);
i:=pos('.',flname);
if p > 0 then period:=True else Exit; {not a valid wildcard if no period}
N:=1;
Repeat
if card[n]='*' then n:=p-1 else
if (upCase(flname[n]) <> upCase(card[n])) then
if card[n]<>'?' then Exit;
inc(n);
Until n>=p;
n:=p+1; {one position past the period of the wild card}
l:=length(flname);
inc(i); {one position past the period of the Filename}
Repeat
if n > length(card) then Exit;
c:=upCase(card[n]);
if c='*' then i:=l+1 {in order to end the loop}
else
if (upCase(flname[i]) = c) or (c = '?') then
begin
inc(n);
inc(i);
end
else Exit;
Until i > l;
wild:=True;
end;
begin
check:=False;
check:=wild('TEST.Tat','T*.T?T'); {True}
Writeln(check);
check:=wild('TEST.Taq','T*.T?T'); {False}
Writeln(check);
check:=wild('12345678.pkt','*.pkt'); {True}
Writeln(check);
check:=wild('test.tat','T*.t?'); {False}
Writeln(check);
check:=wild('12345678.pkt','1234?678.*'); {True}
Writeln(check);
end.
|
unit logger;
{$mode objfpc}{$H+}
interface
uses
SysUtils
{$ifdef windows}
,windows
{$endif};
{ Sadly we could not use the Crt unit under unix, even though
it showed the right colors, because it would send spurious
codes to the terminal and change the cursor position when
shadow was executed.
For now we leave it unimplemented in unix }
const
Black = 0;
Blue = 1;
Green = 2;
Cyan = 3;
Red = 4;
Magenta = 5;
Brown = 6;
LightGray = 7;
DarkGray = 8;
LightBlue = 9;
LightGreen = 10;
LightCyan = 11;
LightRed = 12;
LightMagenta = 13;
Yellow = 14;
White = 15;
var
LogVerbose: boolean;
LogDebug: integer;
procedure Show(const Msg: string; const NewLine: boolean = True);
procedure Log(const Msg: string);
procedure LogFmt(const Msg:string; Args:array of const);
procedure Dbg(const Msg: string; const Level: integer = 1);
procedure Error(const Msg: string);
procedure TextColor(const Color: byte);
procedure ResetColors();
implementation
{$ifdef windows}
var
TextAttr: Word = $07;
{$endif}
{$ifdef unix}
procedure TextColor(const Color: byte);
var
S: string;
begin
//FIXME: most colors need to be fixed for better look
S := #27 + '[';
case Color of
Black: S := S + '30';
Blue: S := S + '1;' + '34';
Green: S := S + '0;' + '32';
Cyan: S := S + '1;' + '36';
Red: S := S + '1;' + '31';
Magenta: S := S + '1;' + '35';
Brown: S := S + '33'; //Yellow
LightGray: S := S + '37'; //White
DarkGray: S := S + '1;' + '30'; //Bold black
LightBlue: S := S + '34';
LightGreen: S := S + '32';
LightCyan: S := S + '36';
LightRed: S := S + '31';
LightMagenta: S := S + '35';
Yellow: S := S + '33';
White: S := S + '1;' + '37';
end;
S := S + 'm';
Write(S);
end;
procedure TextBackground(const Color: byte);
var
S: string;
begin
//FIXME: most colors need to be fixed for better look
S := #27 + '[';
case Color of
Black: S := S + '40';
Blue: S := S + '1;' + '44';
Green: S := S + '0;' + '42';
Cyan: S := S + '1;' + '46';
Red: S := S + '1;' + '41';
Magenta: S := S + '1;' + '45';
Brown: S := S + '43'; //Yellow
LightGray: S := S + '47'; //White
DarkGray: S := S + '1;' + '40'; //Bold black
LightBlue: S := S + '44';
LightGreen: S := S + '42';
LightCyan: S := S + '46';
LightRed: S := S + '41';
LightMagenta: S := S + '45';
Yellow: S := S + '43';
White: S := S + '1;' + '47'; //Bold
end;
S := S + 'm';
Write(S);
end;
{$endif}
{$ifdef windows}
procedure WriteAttr(const TAttr:word);
begin
SetConsoleTextAttribute(GetStdhandle(STD_OUTPUT_HANDLE),TAttr);
end;
procedure TextColor(const Color: byte);
begin
TextAttr:=(Color and $8f) or (TextAttr and $70);
WriteAttr(TextAttr);
end;
procedure TextBackground(const Color: byte);
Const
Blink = 128; //Could be added to color, but we dont expose it
begin
TextAttr:=((Color shl 4) and ($f0 and not Blink))
or (TextAttr and ($0f OR Blink) );
WriteAttr(TextAttr);
end;
{$endif}
procedure ResetColors();
begin
{$ifdef windows}
TextAttr:=$07;
WriteAttr(TextAttr);
{$endif}
{$ifdef unix}
Write(#27 + '[0m');
{$endif}
end;
function Indent(const Str: string; const Nspaces: integer; Len: integer = 77): string;
var
Spcs, S: string;
Poz, Lineno, nadds: integer;
begin
Result := Str;
if Length(Str) + Nspaces < Len then
Exit;
S := Str;
Spcs := StringOfChar(#32, Nspaces);
{FIXME Result := WrapText(S, LineEnding + Spcs, [#32, '/', '\', '-', '+'] ,Len);}
Lineno := 1;
nadds := 0;
Poz := len * lineno - Nspaces;
repeat
Insert(LineEnding + spcs, S, Poz);
Inc(nadds);
Inc(Lineno);
Poz := Poz + len;
until Poz >= Length(s);
Result := S;
end;
procedure Show(const Msg: string; const NewLine: boolean = True);
var
S: string;
begin
{$ifdef windows}
TextColor(White);
{$endif}
{$ifdef unix}
ResetColors();
{$endif}
S := Indent(Msg, 1, 79);
if (NewLine) then
WriteLn(S)
else
Write(S);
ResetColors();
end;
procedure Log(const Msg: string);
var
TS: string;
S, NL: string;
Continues: boolean;
begin
if (LogVerbose) then
begin
S := Msg;
NL := '';
//If message has a line ending in the beginning
//make sure we put it before the time/date
if (Length(Msg) > 0) and (Pos(LineEnding, Msg) = 1) then
begin
NL := LineEnding;
Delete(S, 1, Length(LineEnding));
end;
TS := FormatDateTime(' [ ddd. hh:mm:ss ] - ', Now);
TextColor(green);
//Change line ending to \n and limit size to 555 bytes per log
// The +1-1 trickery is used to prevent triggering the avast antivirus
Continues:=False;
If Length(S) > 555 then //Honor Our Lord's wounds
begin
SetLength(S,555+1-1);
Continues := True;
end;
S :=StringReplace(S,LineEnding,'\n',[rfReplaceAll]);
//Format it nicely
S := Indent(S, Length(TS), 77);
Write(NL + TS + S);
If Continues then
begin
TextColor(Blue);
WriteLn('...'); //FIXME: use utf8 ellipsis
end
else
Write(LineEnding);
ResetColors();
end;
end;
procedure LogFmt(const Msg:string; Args:array of const);
begin
Log(Format(Msg,Args));
end;
procedure Dbg(const Msg: string; const Level: integer = 1);
begin
if (Level <= LogDebug) then
WriteLn(Msg);
end;
procedure Error(const Msg: string);
const
HDR = 'ERROR: ';
begin
TextBackground(Red);
TextColor(Yellow);
WriteLn(HDR + Indent(Msg, Length(HDR), 77));
ResetColors();
end;
initialization
{$IFDEF WINDOWS}
SetConsoleOutputCP(CP_UTF8);
{$ENDIF}
end.
|
unit ulngConverter;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Buttons, IniFiles, ulngTranslator;
type
{ TfrmLanguageConverter }
TfrmLanguageConverter = class(TForm)
bconvertir: TButton;
bCerrar: TButton;
eficheroAntiguo: TEdit;
eficheroNuevo: TEdit;
lblFicheroAntiguo: TLabel;
lblFicheroNuevo: TLabel;
OpenDialogFN: TOpenDialog;
OpenDialogFA: TOpenDialog;
sbFicheroAntiguo: TSpeedButton;
sbFicheroNuevo: TSpeedButton;
procedure bCerrarClick(Sender: TObject);
procedure bconvertirClick(Sender: TObject);
procedure bTraducirClick(Sender: TObject);
procedure sbFicheroAntiguoClick(Sender: TObject);
procedure sbFicheroNuevoClick(Sender: TObject);
procedure convertLanguage;
private
{ private declarations }
public
{ public declarations }
end;
var
frmLanguageConverter: TfrmLanguageConverter;
const
NUM_OF_STRINGS = 200;
resourcestring
LNG_FILE_NO_EXIST = 'No existe el fichero:';
LNG_FILE_REFERENCE_NO_EXIST = 'No existe el fichero de referencia:';
LNG_CORRECT = 'Fichero creado correctamente';
implementation
{$R *.lfm}
{ TfrmLanguageConverter }
procedure TfrmLanguageConverter.sbFicheroAntiguoClick(Sender: TObject);
begin
if OpenDialogFA.Execute then
eficheroAntiguo.Text:=OpenDialogFA.FileName;
end;
procedure TfrmLanguageConverter.bconvertirClick(Sender: TObject);
begin
convertLanguage;
end;
procedure TfrmLanguageConverter.bTraducirClick(Sender: TObject);
begin
frmLangTranslator.Show;
end;
procedure TfrmLanguageConverter.bCerrarClick(Sender: TObject);
begin
Close;
end;
procedure TfrmLanguageConverter.sbFicheroNuevoClick(Sender: TObject);
begin
if OpenDialogFN.Execute then
eficheroNuevo.Text:=OpenDialogFN.FileName;
end;
procedure TfrmLanguageConverter.convertLanguage;
var
lngfileReference : TIniFile;
lngfileOld : TIniFile;
lngfileNew : TStringList;
i,j : integer;
tmpLine : String;
tmpSentence : String;
tmpSentenceRef : String;
lineIndex: Integer;
FilenameReference : String;
begin
// Si no existe el fichero cambia al lenguaje por defecto
if not FileExistsUTF8(eficheroAntiguo.Text) { *Converted from FileExists* } then
begin
ShowMessage(LNG_FILE_NO_EXIST+' '+eficheroAntiguo.Text);
exit;
end;
if not FileExistsUTF8(eficheroNuevo.Text) { *Converted from FileExists* } then
begin
ShowMessage(LNG_FILE_NO_EXIST+' '+eficheroNuevo.Text);
exit;
end;
FilenameReference:= 'lng'+DirectorySeparator+'Spanish.ini';
if not FileExistsUTF8(FilenameReference) { *Converted from FileExists* } then
begin
ShowMessage(LNG_FILE_REFERENCE_NO_EXIST+' '+FilenameReference);
exit;
end;
lngfileReference := TIniFile.Create(FilenameReference);
lngfileOld := TIniFile.Create(eficheroAntiguo.Text);
lngfileNew := TStringList.Create;
lngfileNew.LoadFromFile(eficheroNuevo.Text);
//LNG_DESCRIPTION := lngfileOld.ReadString('LNG', 'Description', 'NULL');
//LNG_INF := lngfileOld.ReadString('LNG', 'INFO', 'NULL');
for i := 0 to NUM_OF_STRINGS - 1 do
begin
tmpSentenceRef := lngfileReference.ReadString('LNG', IntToStr(i), 'NULL');
tmpLine := 'msgid "'+tmpSentenceRef+'"';
lineIndex := -1;
for j := 0 to lngfileNew.Count-1 do
begin
if tmpline = lngfileNew.Strings[j] then
begin
lineIndex := j;
break;
end;
end;
if lineIndex > -1 then
begin
tmpSentenceRef := lngfileOld.ReadString('LNG', IntToStr(i), 'NULL');
lngfileNew.Strings[lineIndex+1] := 'msgstr "'+tmpSentenceRef+'"';
end
end;
lngfileNew.SaveToFile(eficheroNuevo.Text);
lngfileNew.Free;
lngfileReference.Free;
lngfileOld.Free;
ShowMessage(LNG_CORRECT);
end;
end.
|
unit mtxline;
{ Break input up into words, classify them. Supply words and
information about them. }
interface uses globals;
type
music_word = (other, abcdefg, zword, lyrtag,
lparen, rparen, rlparen, lbrac, rbrac,
pmxprefix, pmxl, macro, endmacro, mword, oword, rword, nextvoice,
barword, texword, atword, FirstOnly, err );
const
bind_left: array[music_word] of boolean = (
false, false, true, false,
false, true, true, false, true,
true, true, false, true, false, true, false, true,
false, false, false, false, false );
{ changed bind_left[barword] to false }
var selected: array[voice_index] of boolean;
procedure error3(voice: voice_index; message: string );
procedure warning3(voice: voice_index; message: string );
procedure getNextMusWord (var buf, note: string; var nscan: music_word);
function MusicWord(voice, n: integer): string;
function nextMusicWord(voice: voice_index): string;
function thisNote(voice: voice_index): music_word;
function nextNote(voice: voice_index): music_word;
function getMusicWord(voice: voice_index): string;
procedure gotoBar(voice: voice_index; bar_no: integer);
function endOfBar(voice: voice_index; bar_no: integer): boolean;
function getBar(voice:voice_index; bar: integer): string;
function upper(voice: voice_index): boolean;
procedure clearLabels;
function findVoice(w: string): voice_index0;
procedure selectVoices(line: string);
procedure resetInfo(voice: voice_index; var buf: string);
procedure setVocal(voice: voice_index; voc: boolean);
function isVocal(voice: voice_index): boolean;
procedure setStavePos(voice: voice_index; stave, pos: stave_index);
function voiceStave(voice: voice_index): stave_index;
function voicePos(voice: voice_index): stave_index;
function aloneOnStave(stave: stave_index): boolean;
function companion(voice: voice_index): voice_index;
procedure appendNote(voice: voice_index; nscan: music_word);
procedure appendToLine(voice: voice_index; note: string);
procedure markBar(voice: voice_index);
function numberOfBars(voice: voice_index): integer;
procedure barForward(voice: voice_index; nbars: integer);
procedure regroup(voice: voice_index);
function beatsPerLine: integer;
procedure setExtraLength(voice: voice_index; ext: integer);
function ExtraLength(voice: voice_index): integer;
function musicLineNo(voice: voice_index): paragraph_index0;
procedure setMusicLineNo(voice: voice_index; lno: paragraph_index);
function chordLineNo(voice: voice_index): paragraph_index0;
procedure setChordLineNo(voice: voice_index; lno: paragraph_index);
procedure skipChordBar(voice: voice_index);
procedure describeVoice(voice: voice_index; describe_lyr: string);
function maybeMusicLine(l: string): boolean;
function musicLine(voice: voice_index): string;
implementation uses strings, notes, control, utility;
const
name: array[music_word] of string[9] = (
'?', 'note', 'znote', 'lyricsTag',
'(', ')', ')(', '[', ']',
'_','PMX<', 'macro', 'endMacro', 'meter', 'ornament', 'rest', '//',
'BAR', 'TeX', '@', 'firstonly', 'ERROR');
type
word_scan = array[1..max_words] of music_word;
line_info = record
here, nword: word_index0;
nbar: bar_index0;
voice_pos, voice_stave, mus, chord: paragraph_index0;
extra: integer;
vocal: boolean;
bar_bound: array[bar_index0] of word_index0;
word_bound, orig_word_bound: array[word_index0] of integer;
scan: word_scan;
end;
var info: array[voice_index] of line_info;
{ ------------------------------------------------------------- }
function beatsPerLine: integer;
var voice: voice_index;
begin for voice:=1 to nvoices do with info[voice] do
if (nbar>0) or (extra>0) then
begin
if extra mod one_beat > 0
then error3(voice,'Line length not an integer number of beats');
beatsPerLine := nbar*meternum + extra div one_beat;
end;
end;
procedure skipChordBar(voice: voice_index);
begin with info[voice] do
if chord>0 then if P[chord]=barsym then predelete(P[chord],1);
end;
function getBar(voice: voice_index; bar: integer): string;
begin with info[voice] do
getBar := substr(P[mus],word_bound[bar_bound[bar-1]]+1,
word_bound[bar_bound[bar]]-word_bound[bar_bound[bar-1]]);
end;
function musicLine(voice: voice_index): string;
begin musicLine:=P[musicLineNo(voice)]; end;
function musicLineNo(voice: voice_index): paragraph_index0;
begin musicLineNo := info[voice].mus; end;
procedure setMusicLineNo(voice: voice_index; lno: paragraph_index);
begin info[voice].mus := lno; end;
function chordLineNo(voice: voice_index): paragraph_index0;
begin chordLineNo := info[voice].chord; end;
procedure setChordLineNo(voice: voice_index; lno: paragraph_index);
begin info[voice].chord := lno; end;
procedure setVocal(voice: voice_index; voc: boolean);
begin info[voice].vocal:=voc; end;
function isVocal(voice: voice_index): boolean;
begin isVocal := info[voice].vocal; end;
procedure setStavePos(voice: voice_index; stave, pos: stave_index);
begin with info[voice] do begin voice_pos:=pos; voice_stave:=stave; end;
end;
function voiceStave(voice: voice_index): stave_index;
begin voiceStave:=info[voice].voice_stave; end;
function voicePos(voice: voice_index): stave_index;
begin voicePos:=info[voice].voice_pos; end;
function companion(voice: voice_index): voice_index;
var s: integer;
begin s:=info[voice].voice_stave;
if number_on_stave[s]=1 then companion:=voice
else if info[voice].voice_pos=1 then companion:=voice+1
else companion:=voice-1;
end;
procedure regroup(voice: voice_index);
var i, j, j2: word_index0;
begin j2 := 0; with info[voice] do
begin if debugMode then write('Voice ',voice,' has ',nbar,' bars at ');
if debugMode then for i:=1 to nbar+1 do write(bar_bound[i],' ');
for i:=1 to nbar do
begin j2:=bar_bound[i]; j:=j2+1;
while (j<=here) and (bind_left[scan[j]] or (scan[j]=barword)) do
begin inc(bar_bound[i]); inc(j) end;
end;
if extra>0 then bar_bound[nbar+1]:=here;
if debugMode then
begin write(' regrouped to ');
for i:=1 to nbar+1 do write(bar_bound[i],' ')
end;
if debugMode then writeln;
nword := here
end;
end;
procedure resetInfo(voice: voice_index; var buf: string);
begin with info[voice] do
begin buf := P[mus]; P[mus]:='';
bar_bound[0]:=0; word_bound[0]:=0; orig_word_bound[0]:=0;
nbar:=0; here := 0;
end;
end;
procedure clearLabels;
var voice: voice_index;
begin for voice:=1 to nvoices do with info[voice] do
begin chord:=0; mus:=0; end;
end;
procedure appendNote(voice: voice_index; nscan: music_word);
begin with info[voice] do
begin inc(here); if here>max_words then
error3(voice,'Words per line limit exceeded');
scan[here]:=nscan; end;
end;
procedure appendToLine(voice: voice_index; note: string);
begin if note<>'' then with info[voice] do
begin P[mus]:=P[mus]+note+blank; word_bound[here]:=length(P[mus]);
orig_word_bound[here]:=nextWordBound(orig_P[mus],note[1],
orig_word_bound[here-1]);
end;
end;
procedure markBar(voice: voice_index);
begin with info[voice] do
if nbar=0 then error3(voice,'Empty bar') else bar_bound[nbar]:=here
end;
function numberOfBars(voice: voice_index): integer;
begin numberOfBars := info[voice].nbar; end;
procedure barForward(voice: voice_index; nbars: integer);
begin with info[voice] do
begin
if (nbar+nbars<0) then error3(voice, 'Next voice before bar is full');
if nbar+nbars>max_bars then error3(voice,'Bars per line limit exceeded');
inc(nbar,nbars);
if nbars>0 then bar_bound[nbar]:=here;
end;
end;
procedure setExtraLength(voice: voice_index; ext: integer);
begin with info[voice] do begin extra:=ext; scan[here+1]:=other; end;
end;
function ExtraLength(voice: voice_index): integer;
begin ExtraLength := info[voice].extra; end;
function findVoice(w: string): voice_index0;
var i: integer;
begin curtail(w,':'); findVoice:=0;
for i:=1 to nvoices do
if w=voice_label[i] then begin findVoice:=i; exit end;
getNum(w,i); if i=0 then exit;
if (i>0) and (i<=nvoices) then findVoice:=i
else error('Numeric label outside range 1..nvoices',print);
end;
procedure info3(voice: voice_index);
var p: integer;
begin with info[voice] do
begin
writeln ('In voice "', voice_label[voice], '" near word ', here, ':');
p:=orig_word_bound[here-1]-1;
if p<0 then p:=0;
writeln(' ':p,'V')
end
end;
procedure error3(voice: voice_index; message: string );
begin info3(voice); error(' '+message,print) end;
procedure warning3(voice: voice_index; message: string );
begin info3(voice); warning(' '+message,print) end;
function nextMusicWord(voice: voice_index): string;
begin nextMusicWord := MusicWord(voice,info[voice].here); end;
function MusicWord(voice, n: integer): string;
begin with info[voice] do if (n>0) and (n<=nword) then
MusicWord := substr(P[mus],word_bound[n-1]+1,
word_bound[n]-word_bound[n-1]-1)
else MusicWord := '';
end;
function thisNote(voice: voice_index): music_word;
begin with info[voice] do thisNote := scan[here-1]; end;
function nextNote(voice: voice_index): music_word;
begin with info[voice] do nextNote := scan[here]; end;
function endOfBar(voice: voice_index; bar_no: integer): boolean;
begin with info[voice] do endOfBar := here > bar_bound[bar_no]; end;
procedure gotoBar(voice: voice_index; bar_no: integer);
begin with info[voice] do here := bar_bound[bar_no-1]+1; end;
function getMusicWord(voice: voice_index): string;
begin with info[voice] do
begin line_no := orig_line_no[mus];
GetMusicWord := MusicWord(voice,here); inc(here);
end
end;
function maybeMusicLine(l: string): boolean;
var w: string;
nscan: music_word;
begin w:=GetNextWord(l,blank,dummy); maybeMusicLine := false;
if pos1(w[1],'abcdefgr()[]{}CMm')=0 then begin maybeMusicLine := false; exit end;
if pos1(':',w)=0 then begin maybeMusicLine := true; exit end;
GetNextMusWord(w,l,nscan); maybeMusicLine := nscan=abcdefg;
end;
const macro_initialized: boolean=false;
nmacros = 99;
var macro_text: array[1..nmacros] of string;
procedure macroInit;
var i: integer;
begin if macro_initialized then exit else macro_initialized:=true;
for i:=1 to nmacros do macro_text[i]:=''
end;
function identifyMacro(s: string): integer;
var k: integer;
begin predelete(s,2); getNum(s,k); identifyMacro:=k
end;
procedure GetNextMusWord (var buf, note: string; var nscan: music_word);
var maybe_error: string;
procedure expandThisMacro;
var playtag: string[10];
playID: integer;
w: string;
begin macroInit; if length(note)=1 then
error('Can''t terminate a macro that has not been started',print);
playID:=identifyMacro(note); playtag:=toString(playID);
if (playID<1) or (playID>99) then
error('Macro ID '+playtag+' is not in range 1..99',print);
if note[2]='P' then
begin if macro_text[playID]='' then
warning('Macro '+playtag+
' inserts empty text: did you define it before use?',print);
if length(macro_text[playID])+length(buf)>255
then error('Expansion of macro '+playtag+' causes buffer overflow',print)
else begin if debugMode then
begin writeln('Inserting macro '+playtag+' text "'
+macro_text[playID]+'"');
writeln('Buffer before insert: ',buf)
end;
buf:=macro_text[playID]+buf; exit
end
end;
if pos1(note[2],'SR')=0 then error('Second character '+note[2]+
' of macro word should be in "PRS"',print);
macro_text[playID]:='';
repeat w:=getNextWord(buf,blank,dummy);
if w='' then error('Macro definition '+playtag+
' should be terminated on the same input line',print);
if w='M' then begin
if debugMode then writeln('Macro '+playtag+' is: '+macro_text[playID]);
break
end;
if (w[1]='M') and (length(w)>1) then
if (w[2]<>'P') or (identifyMacro(w)=playID) then
error(w+' not allowed inside macro definition '+playtag,print);
macro_text[playID]:=macro_text[playID]+w+' '
until false;
if note[2]='R' then begin note[2]:='P'; buf:=note+' '+buf end
end;
begin note:=GetNextWord(buf,blank,dummy);
if note='' then exit;
if (note[1]='M') and expandMacro then
begin expandThisMacro; GetNextMusWord(buf,note,nscan); exit end;
if note[1]='\' then
begin maybe_error:='';
if note[length(note)]<>'\' then maybe_error:=note;
while (buf<>'') and (note[length(note)]<>'\') do
note:=note+' '+GetNextWord(buf,blank,dummy);
if note[length(note)]<>'\' then
error('Unterminated TeX literal',print);
nscan:=texword;
if maybe_error<>'' then
warning('Possible unterminated TeX literal: '+maybe_error,print);
exit;
end;
if solfaNoteNames then
begin translateSolfa(note[1]); if note[1]='"' then predelete(note,1);
end;
case note[1] of
'_': begin nscan:=pmxprefix;delete1(note,1); end;
'a'..'g': nscan:=abcdefg;
'z': nscan:=zword;
'(': nscan:=lparen;
'{': if note[length(note)]='}' then nscan:=lyrtag else nscan:=lparen;
')': if pos1('(',note)=0 then nscan:=rparen else nscan:=rlparen;
'}': if pos1('{',note)=0 then nscan:=rparen else nscan:=rlparen;
'[': nscan:=lbrac;
']': if note='][' then nscan:=other else nscan:=rbrac;
'@': nscan:=atword;
'm': nscan:=mword;
'r': nscan:=rword;
'#','-','n','x','?','s','t','D': nscan:=pmxl;
'M': if note='M' then nscan:=endMacro else nscan:=macro;
'G': if pos1('A',note)>0 then nscan:=pmxl else nscan:=other;
'1'..'9': if pos1('/',note)>0 then nscan:=mword else nscan:=pmxl;
'o': nscan:=oword;
'A', 'V': nscan:=FirstOnly;
'/': if note='//' then nscan:=nextvoice
else if note='/' then
begin note:='//'; warning('/ changed to //',print); nscan:=nextvoice;
end
else begin error('Word starts with /: do you mean \?',print);
nscan:=err;
end;
else if pos1('|',note)>0 then nscan:=barword else
nscan:=other;
end;
end;
function upper(voice: voice_index): boolean;
begin with info[voice] do
if (voice_pos=1) and (voice<nvoices) then
upper:=(voice_stave=info[voice+1].voice_stave)
else upper:=false;
end;
procedure describeVoice(voice: voice_index; describe_lyr: string);
var bar, w: integer;
begin with info[voice] do
begin write('Voice `',voice_label[voice],''' is on line ',mus);
if vocal then
begin write(', is vocal'); writeln(describe_lyr); end
else
begin if chord>0 then write(' and has chords on line ',chord);
writeln;
end;
if debugMode then with info[voice] do
begin write('Line has ', nbar, ' bars');
if extra>0 then writeln(' + ', extra, '/64 notes') else writeln;
write('Bars:');
for bar:=1 to nbar do write(' ',getBar(voice,bar),' ');
writeln; write('Word types:');
for w:=1 to nword do write(' ',name[scan[w]]); writeln;
end;
end;
end;
function aloneOnStave(stave: stave_index): boolean;
var v: voice_index;
begin
if number_on_stave[stave]<>2 then aloneOnStave:=true else
begin v:=first_on_stave[stave];
aloneOnStave:= (info[v].mus=0) or (info[v+1].mus=0)
end
end;
procedure selectVoices(line: string);
var i, k: integer;
word: string;
begin
for k:=1 to nvoices do selected[k]:=false;
write('Voice change to: ',line,' = ');
i:=0;
while i<nvoices do
begin word:=GetNextWord(line,blank,dummy);
if word='' then begin writeln; exit; end;
inc(i); write(word,' ');
k:=findVoice(word);
if k=0 then error('This voice is not in the style',print);
selected[k]:=true;
end;
writeln;
end;
end.
|
unit hxCalendar;
interface
uses Classes, Controls, Messages, Windows, Forms, Graphics, StdCtrls,
Grids, SysUtils,DateUtils;
type
TDayOfWeek = 0..6;
TDroppedCell = procedure(Sender: TObject; ACol, ARow: LongInt; var Value: string) of object;
TCellDragOver = procedure(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean) of object;
TCalendarStrings = array[0..6, 0..6] of TStringList;
THzDate = record //农历日期
Year: integer;
Month: integer;
Day: integer;
isLeap: Boolean; //闰月
end;
TGzDate = record //干支日期
Year: integer;
Month: integer;
Day: integer;
end;
ThxCalendar = class(TCustomGrid)
private
FDate: TDate;
FViewDate: TDate;
//FCalColors: TLssCalColors;
FYear: word;
FMonth: word;
FDay: word;
FCalStrings: TCalendarStrings;
FOnDroppedCell: TDroppedCell;
FOnCellDragOver: TCellDragOver;
FMonthOffset: Integer;
FOnChange: TNotifyEvent;
FReadOnly: Boolean;
FStartOfWeek: TDayOfWeek;
FUpdating: Boolean;
FUseCurrentDate: Boolean;
function GetCellText(ACol, ARow: Integer): string;
function GetDateElement(Index: Integer): Integer;
procedure SetCalendarDate(Value: TDate);
procedure SetDateElement(Index: Integer; Value: Integer);
procedure SetStartOfWeek(Value: TDayOfWeek);
procedure SetUseCurrentDate(Value: Boolean);
function StoreCalendarDate: Boolean;
procedure SetCellString(ACol, ARow, ADay: Integer; Value: string); virtual;
protected
{ Protected declarations }
procedure AcceptDropped(Sender, Source: TObject; X, Y: integer);
procedure CellDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure Change; dynamic;
procedure ChangeMonth(Delta: Integer);
procedure Click; override;
function DaysPerMonth(AYear, AMonth: Integer): Integer; virtual;
function DaysThisMonth: Integer; virtual;
procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override;
function IsLeapYear(AYear: Integer): Boolean; virtual;
function SelectCell(ACol, ARow: Longint): Boolean; override;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
public
constructor Create(AOwner: TComponent); override;
//返回农历 y年的总天数
function DaysOfLunarYear(y: integer): integer;
//返回农历 y年闰月的天数
function daysofleapMonth(y: integer): integer;
//返回农历 y年闰哪个月 1-12 , 没闰返回 0
function leapMonth(y: integer): integer;
//返回农历 y年m月的总天数
function Daysofmonth(y, m: integer): integer;
//算出农历, 传入公历日期, 返回农历日期
function ToLunar(TheDate: TDate): THzDate;
//传入 offset 返回干支, 0=甲子
function cyclical(num: integer): string;
//算出公历, 传入农历日期控件, 返回公历
function ToGreg(objDate: THzDate): TDate;
//检查农历日期是否合法
function ChkHzDate(objDate: THzDate): Boolean;
//某年的第n个节气为几日(从0小寒起算)
function sTerm(y, n: integer): TDateTime;
//求年柱,月柱,日柱(年,月为农历数字,TheDate为当天的公历日期)
function GetGZ(y, m: integer; TheDate: TDate): TGzDate;
//取汉字日期
function FormatLunarDay(day:integer): string;
//汉字月份
function FormatLunarMonth(month:integer;isLeap:boolean): string;
//汉字年份
function FormatLunarYear(year:integer): string;
// 取得指定日期的节气
function GetJQ(TheDate: TDate): string;
// 取得新历节日
function GetsFtv(TheDate: TDate): string;
// 取得农历节日
function GetlFtv(TheDate: ThzDate): string;
property CalendarDate: TDate read FDate write SetCalendarDate stored StoreCalendarDate;
procedure MouseToCell(X, Y: Integer; var ACol, ARow: Longint);
property CellText[ACol, ARow: Integer]: string read GetCellText;
procedure NextMonth;
procedure NextYear;
procedure PrevMonth;
procedure PrevYear;
procedure UpdateCalendar; virtual;
published
property Align;
property Anchors;
property BorderStyle;
property Color;
property Constraints;
property Ctl3D;
property Day: Integer index 3 read GetDateElement write SetDateElement stored False;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property GridLineWidth;
property Month: Integer index 2 read GetDateElement write SetDateElement stored False;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly: Boolean read FReadOnly write FReadOnly default False;
property ShowHint;
property StartOfWeek: TDayOfWeek read FStartOfWeek write SetStartOfWeek;
property TabOrder;
property TabStop;
property UseCurrentDate: Boolean read FUseCurrentDate write SetUseCurrentDate default True;
property Visible;
property Year: Integer index 1 read GetDateElement write SetDateElement stored False;
property OnClick;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnStartDock;
property OnStartDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
const
lunarInfo: array[0..200] of WORD =(
$4bd8,$4ae0,$a570,$54d5,$d260,$d950,$5554,$56af,$9ad0,$55d2,
$4ae0,$a5b6,$a4d0,$d250,$d295,$b54f,$d6a0,$ada2,$95b0,$4977,
$497f,$a4b0,$b4b5,$6a50,$6d40,$ab54,$2b6f,$9570,$52f2,$4970,
$6566,$d4a0,$ea50,$6a95,$5adf,$2b60,$86e3,$92ef,$c8d7,$c95f,
$d4a0,$d8a6,$b55f,$56a0,$a5b4,$25df,$92d0,$d2b2,$a950,$b557,
$6ca0,$b550,$5355,$4daf,$a5b0,$4573,$52bf,$a9a8,$e950,$6aa0,
$aea6,$ab50,$4b60,$aae4,$a570,$5260,$f263,$d950,$5b57,$56a0,
$96d0,$4dd5,$4ad0,$a4d0,$d4d4,$d250,$d558,$b540,$b6a0,$95a6,
$95bf,$49b0,$a974,$a4b0,$b27a,$6a50,$6d40,$af46,$ab60,$9570,
$4af5,$4970,$64b0,$74a3,$ea50,$6b58,$5ac0,$ab60,$96d5,$92e0, //1999
$c960,$d954,$d4a0,$da50,$7552,$56a0,$abb7,$25d0,$92d0,$cab5,
$a950,$b4a0,$baa4,$ad50,$55d9,$4ba0,$a5b0,$5176,$52bf,$a930,
$7954,$6aa0,$ad50,$5b52,$4b60,$a6e6,$a4e0,$d260,$ea65,$d530,
$5aa0,$76a3,$96d0,$4afb,$4ad0,$a4d0,$d0b6,$d25f,$d520,$dd45,
$b5a0,$56d0,$55b2,$49b0,$a577,$a4b0,$aa50,$b255,$6d2f,$ada0,
$4b63,$937f,$49f8,$4970,$64b0,$68a6,$ea5f,$6b20,$a6c4,$aaef,
$92e0,$d2e3,$c960,$d557,$d4a0,$da50,$5d55,$56a0,$a6d0,$55d4,
$52d0,$a9b8,$a950,$b4a0,$b6a6,$ad50,$55a0,$aba4,$a5b0,$52b0,
$b273,$6930,$7337,$6aa0,$ad50,$4b55,$4b6f,$a570,$54e4,$d260,
$e968,$d520,$daa0,$6aa6,$56df,$4ae0,$a9d4,$a4d0,$d150,$f252,
$d520);
Gan: array[0..9] of string[2] =
('甲','乙','丙','丁','戊','己','庚','辛','壬','癸');
Zhi: array[0..11] of string[2] =
('子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥');
Animals: Array[0..11] of string[2] =
('鼠','牛','虎','兔','龙','蛇','马','羊','猴','鸡','狗','猪');
solarTerm: Array[0..23] of string[4] =
('小寒','大寒','立春','雨水','惊蛰','春分','清明','谷雨'
,'立夏','小满','芒种','夏至','小暑','大暑','立秋','处暑'
,'白露','秋分','寒露','霜降','立冬','小雪','大雪','冬至');
sTermInfo: Array[0..23] of integer =
(0,21208,42467,63836,85337,107014,128867,150921
,173149,195551,218072,240693,263343,285989,308563,331033
,353350,375494,397447,419210,440795,462224,483532,504758);
nStr1: array[0..10] of string[2] =
('日','一','二','三','四','五','六','七','八','九','十');
nStr2: Array[0..3] of string[2] = ('初','十','廿','卅');
sFtv : Array[0..22] of string =('0101*元旦','0214 情人节','0308 妇女节'
,'0312 植树节','0315 消费者权益日','0401 愚人节','0501 劳动节','0504 青年节'
,'0512 护士节','0601 儿童节','0701 建党节 香港回归纪念'
,'0801 建军节','0808 父亲节','0909 毛泽东逝世纪念','0910 教师节'
,'0928 孔子诞辰','1001*国庆节','1006 老人节','1024 联合国日','1112 孙中山诞辰纪念'
,'1220 澳门回归纪念','1225 Christmas Day','1226 毛泽东诞辰纪念');
lFtv:Array[0..9] of string =('0101*春节','0115 元宵节','0505 端午节'
,'0707 七夕情人节','0715 中元节','0815 中秋节','0909 重阳节','1208 腊八节','1224 小年','0100*除夕');
implementation
constructor ThxCalendar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
{ defaults }
FUseCurrentDate := True;
FixedCols := 0;
FixedRows := 1;
ColCount := 7;
RowCount := 7;
ScrollBars := ssNone;
Options := Options - [goRangeSelect] + [goDrawFocusSelected];
FDate := Date;
UpdateCalendar;
end;
procedure ThxCalendar.Change;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure ThxCalendar.MouseToCell(X, Y: Integer; var ACol, ARow: Longint);
var
Coord: TGridCoord;
begin
Coord := MouseCoord(X, Y);
ACol := Coord.X;
ARow := Coord.Y;
end;
{ AcceptDropped override }
procedure ThxCalendar.AcceptDropped(Sender, Source: TObject; X, Y: integer);
var
ACol, ARow: LongInt;
Value: string;
begin
{ convert X and Y to Col and Row for convenience }
MouseToCell(X, Y, ACol, ARow);
{ let user respond to event }
if Assigned(FOnDroppedCell) then FOnDroppedCell(Source, ACol, ARow, Value);
{ if user returns a string add it to the cells list }
if Value <> '' then SetCellString(ACol, ARow, 0, Value);
{ set focus to hxCalendar }
SetFocus;
{ force redraw }
Invalidate;
end;
{ CellDragOver override }
procedure ThxCalendar.CellDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
var
ACol, ARow: LongInt;
begin
{ convert X and Y to Col and Row for convenience }
MouseToCell(X, Y, ACol, ARow);
{ allow user to set Accept the way they want }
if Assigned(FOnCellDragOver) then
FOnCellDragOver(Sender, Source, ACol, ARow, State, Accept);
{ if Accept = true then apply further logic else leave Accept = false }
if Accept = true then
if (not FUpdating) and (not FReadOnly) and (CellText[ACol, ARow] <> '') then
Accept := true
else
Accept := false;
end;
{ SetCellString - adds a string to the cells stringlist based on Col
or Row or Day of month. }
procedure ThxCalendar.SetCellString(ACol, ARow, ADay: Integer; Value: string);
var
i, j: integer;
TheCellText: string;
begin
if (not FUpdating) and (not FReadOnly) and (CellText[ACol, ARow] <> '') then
begin
{ if ADay is being used calc ACol and ARow. Doesn't matter if
ACol and ARow are <> 0 we just calc them anyway }
if ADay <> 0 then
begin
for i := 0 to 6 do
for j := 1 to 6 do
begin
TheCellText := CellText[i, j];
if (TheCellText <> '') and (ADay = StrToInt(TheCellText)) then
begin
ACol := i;
ARow := j;
end;
end;
end;
{ if no StringList assigned then create one }
if FCalStrings[ACol, ARow] = nil then
FCalStrings[ACol, ARow] := TStringList.Create;
{ add the line of text }
FCalStrings[ACol, ARow].Add(Value);
end;
end;
procedure ThxCalendar.Click;
var
TheCellText: string;
begin
inherited Click;
TheCellText := CellText[Col, Row];
if TheCellText <> '' then Day := StrToInt(TheCellText);
end;
function ThxCalendar.IsLeapYear(AYear: Integer): Boolean;
begin
Result := (AYear mod 4 = 0) and ((AYear mod 100 <> 0) or (AYear mod 400 = 0));
end;
function ThxCalendar.DaysPerMonth(AYear, AMonth: Integer): Integer;
const
DaysInMonth: array[1..12] of Integer = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
begin
Result := DaysInMonth[AMonth];
if (AMonth = 2) and IsLeapYear(AYear) then
Inc(Result); { leap-year Feb is special }
end;
function ThxCalendar.DaysThisMonth: Integer;
begin
Result := DaysPerMonth(Year, Month);
end;
{procedure ThxCalendar.DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState);
var
TheText: string;
begin
TheText := CellText[ACol, ARow];
with ARect, Canvas do
TextRect(ARect, Left + (Right - Left - TextWidth(TheText)) div 2,
Top + (Bottom - Top - TextHeight(TheText)) div 2, TheText);
end;}
procedure ThxCalendar.DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState);
var
HzDate:THzDate;
TheText,ry,dz,hzdaystr,sf: string;
MyDate:tdate;
begin
TheText := CellText[ACol, ARow];
// DecodeDate(FDate, AYear, AMonth, ADay);
if (TheText<>'') and (ARow<>0) then
begin
MyDate := EncodeDate(year, month, strtoint(TheText));
HzDate := ToLunar(MyDate);
dz:= GetJQ(MyDate);
if dz = '' Then
if HzDate.Day = 1 then
ry:=FormatLunarMonth(HzDate.Month,HzDate.isLeap)
else
ry := FormatLunarDay(Hzdate.Day);
if GetsFtv(MyDate)<>'' then sf :=GetsFtv(MyDate);
if GetlFtv(hzDate)<>'' then sf :=sf+GetlFtv(hzDate);
end
else MyDate := 0;
with ARect, Canvas do
begin
if dz<>'' then
begin
Font.Color := $000000FF ;
TextRect(ARect, Left +2,
Top +2, TheText+sf);
TextOut(ARect.Left + Font.Size + 10, ARect.Top + 25, dz);
end
else
begin
if sf<>'' then
begin
Font.Color :=$000000FF;
TextRect(ARect, Left + 2,
Top + 2, TheText + sf);
end
else
begin
Font.Color :=clBlue;
TextRect(ARect, Left + 2,
Top +2, TheText+sf);
end;
Font.Color :=clBlue;
TextOut(ARect.Left + Font.Size + 10, ARect.Top + 25, ry);
end;
end;
end;
function ThxCalendar.GetCellText(ACol, ARow: Integer): string;
var
DayNum: Integer;
begin
if ARow = 0 then { day names at tops of columns }
Result := FormatSettings.ShortDayNames[(StartOfWeek + ACol) mod 7 + 1]
else
begin
DayNum := FMonthOffset + ACol + (ARow - 1) * 7;
if (DayNum < 1) or (DayNum > DaysThisMonth) then
Result := ''
else
Result := IntToStr(DayNum);
end;
end;
function ThxCalendar.SelectCell(ACol, ARow: Longint): Boolean;
begin
if ((not FUpdating) and FReadOnly) or (CellText[ACol, ARow] = '') then
Result := False
else
Result := inherited SelectCell(ACol, ARow);
end;
procedure ThxCalendar.SetCalendarDate(Value: TDate);
begin
FDate := Value;
UpdateCalendar;
Change;
end;
function ThxCalendar.StoreCalendarDate: Boolean;
begin
Result := not FUseCurrentDate;
end;
function ThxCalendar.GetDateElement(Index: Integer): Integer;
var
AYear, AMonth, ADay: Word;
begin
DecodeDate(FDate, AYear, AMonth, ADay);
case Index of
1: Result := AYear;
2: Result := AMonth;
3: Result := ADay;
else
Result := -1;
end;
end;
procedure ThxCalendar.SetDateElement(Index: Integer; Value: Integer);
var
AYear, AMonth, ADay: Word;
begin
if Value > 0 then
begin
DecodeDate(FDate, AYear, AMonth, ADay);
case Index of
1: if AYear <> Value then AYear := Value else Exit;
2: if (Value <= 12) and (Value <> AMonth) then AMonth := Value else Exit;
3: if (Value <= DaysThisMonth) and (Value <> ADay) then ADay := Value else Exit;
else
Exit;
end;
FDate := EncodeDate(AYear, AMonth, ADay);
FUseCurrentDate := False;
UpdateCalendar;
Change;
end;
end;
procedure ThxCalendar.SetStartOfWeek(Value: TDayOfWeek);
begin
if Value <> FStartOfWeek then
begin
FStartOfWeek := Value;
UpdateCalendar;
end;
end;
procedure ThxCalendar.SetUseCurrentDate(Value: Boolean);
begin
if Value <> FUseCurrentDate then
begin
FUseCurrentDate := Value;
if Value then
begin
FDate := Date; { use the current date, then }
UpdateCalendar;
end;
end;
end;
{ Given a value of 1 or -1, moves to Next or Prev month accordingly }
procedure ThxCalendar.ChangeMonth(Delta: Integer);
var
AYear, AMonth, ADay: Word;
NewDate: TDate;
CurDay: Integer;
begin
DecodeDate(FDate, AYear, AMonth, ADay);
CurDay := ADay;
if Delta > 0 then ADay := DaysPerMonth(AYear, AMonth)
else ADay := 1;
NewDate := EncodeDate(AYear, AMonth, ADay);
NewDate := NewDate + Delta;
DecodeDate(NewDate, AYear, AMonth, ADay);
if DaysPerMonth(AYear, AMonth) > CurDay then ADay := CurDay
else ADay := DaysPerMonth(AYear, AMonth);
CalendarDate := EncodeDate(AYear, AMonth, ADay);
end;
procedure ThxCalendar.PrevMonth;
begin
ChangeMonth(-1);
end;
procedure ThxCalendar.NextMonth;
begin
ChangeMonth(1);
end;
procedure ThxCalendar.NextYear;
begin
if IsLeapYear(Year) and (Month = 2) and (Day = 29) then Day := 28;
Year := Year + 1;
end;
procedure ThxCalendar.PrevYear;
begin
if IsLeapYear(Year) and (Month = 2) and (Day = 29) then Day := 28;
Year := Year - 1;
end;
procedure ThxCalendar.UpdateCalendar;
var
AYear, AMonth, ADay: Word;
FirstDate: TDate;
begin
FUpdating := True;
try
DecodeDate(FDate, AYear, AMonth, ADay);
FirstDate := EncodeDate(AYear, AMonth, 1);
FMonthOffset := 2 - ((DayOfWeek(FirstDate) - StartOfWeek + 7) mod 7); { day of week for 1st of month }
if FMonthOffset = 2 then FMonthOffset := -5;
MoveColRow((ADay - FMonthOffset) mod 7, (ADay - FMonthOffset) div 7 + 1,
False, False);
Invalidate;
finally
FUpdating := False;
end;
end;
procedure ThxCalendar.WMSize(var Message: TWMSize);
var
GridLines: Integer;
begin
GridLines := 6 * GridLineWidth;
DefaultColWidth := (Message.Width - GridLines) div 7;
DefaultRowHeight := (Message.Height - GridLines) div 7;
end;
function ThxCalendar.DaysOfLunarYear(y: integer): integer;
var
i, sum: integer;
begin
sum:= 348; //29 * 12
i:= $8000;
while i > $8 do
begin
if (lunarInfo[y - 1900] and i) > 0 then sum := sum + 1 ;
i:= i shr 1;
end;
Result:= sum + DaysOfLeapMonth(y);
end;
// 返回农历 y年闰月的天数
function ThxCalendar.DaysOfLeapMonth(y: integer): integer;
begin
if leapMonth(y) > 0 then
if (lunarInfo[y - 1899] and $f) = $f then
Result := 30
else
Result := 29
else
Result := 0;
end;
//返回农历 y年闰哪个月 1-12 , 没闰返回 0
function ThxCalendar.leapMonth(y: integer): integer;
var
lm: Word;
begin
lm:= lunarInfo[y - 1900] and $f;
if lm = $f then Result:= 0 else Result:= lm;
end;
//返回农历 y年m月的天数
function ThxCalendar.DaysOfMonth(y, m: integer): integer;
var
temp1, temp2, temp3: Word;
begin
temp1:= lunarInfo[y - 1900];
temp2:= $8000;
if m > 1 then temp2:= $8000 shr (m - 1);
temp3:= temp1 and temp2;
if temp3 > 0 then
Result:= 30
else Result:= 29;
end;
//算出农历, 传入公历日期, 返回农历日期
function ThxCalendar.ToLunar(TheDate: TDate): THzDate;
var
TheYear, TheMonth,leap, temp, offset: integer;
begin
if (32 > TheDate) or (TheDate >= 73416) then //73415=EncodeDate(2100,12,31)
begin //32 = EncodeDate(1900,1,31) 农历1900年1月1日
Result.Year := 0;
Result.Month:= 0;
Result.Day := 0;
Result.isLeap := False;
exit;
end;
offset:= DaysBetween(32,TheDate);
TheYear:= 1900;
while offset > 0 do
begin
temp:= DaysOfLunarYear(TheYear);
TheYear := theYear + 1;
offset:= offset - temp;
end;
if offset < 0 then
begin
offset:= offset + temp;
TheYear:= TheYear - 1;
end;
leap:= leapMonth(TheYear); //闰哪个月
result.isLeap := False;
TheMonth := 0;
while offset >= 0 do
begin
TheMonth:= TheMonth + 1;
temp:= DaysOfMonth(TheYear, TheMonth);
offset:= offset - temp; //减去该月天数
if (offset >= 0) and (TheMonth = Leap) then //如果还有剩余天数且本月有闰
begin //减去闰月天数;
temp:= DaysOfLeapMonth(TheYear);
offset:= offset - temp;
if offset < 0 then
result.isLeap := True; //置闰月标志为真;
end;
end;
if offset < 0 then
begin
offset:= offset + temp;
end;
Result.Year := TheYear;
Result.Month:= TheMonth;
Result.Day:= offset + 1;
end;
// 求年柱,月柱,日柱
// 年,月为农历数字,objDate为当天的公历日期
function ThxCalendar.GetGZ(y, m: integer; TheDate: TDate): TGzDate;
var
term: TDate;
sy, sm, sd: Word;
begin
DecodeDate(TheDate, sy, sm, sd);
term:= sTerm(sy, (sm - 1) * 2); // 当月的节气日期
//年柱 1900年立春后为庚子年(60进制36)
Result.Year:= sy - 1900 + 36;
//依立春日期调整年柱.立春日固定在公历2月
if (sm = 2) and (TheDate < term) then
Result.Year:= sy - 1900 + 35;
//月柱 农历1900年1月小寒以前为 丙子月(60进制12)
Result.Month:= (sy - 1900) * 12 + sm + 11;
//依节气调整月柱
if TheDate >= DateOf(term) then Result.Month:= (sy - 1900) * 12 + sm + 12;
// 1900/1/1 日柱为甲辰日(60进制10)
Result.Day:= DaysBetween(EncodeDate(1900,1,1),TheDate) + 10;
end;
// 算出公历, 传入农历日期控件, 返回公历
function ThxCalendar.ToGreg(objDate: THzDate): TDate;
var
i, j, t, leap, temp, offset: integer;
isLeap: Boolean;
y, m: integer;
begin
Result:= EncodeDate(1,1,1);
if not ChkHzDate(objDate) then exit;
isLeap:= False;
y:= objDate.Year;
m:= objDate.Month;
leap:= leapMonth(y);
//本年内从大年初一过来的天数
offset:= 0;
i:= 1;
while i < m do
begin
if i = leap then
begin
if isLeap then
begin
temp:= DaysOfleapMonth(y);
isLeap:= False;
end
else begin
temp:= daysOfmonth(y, i);
isLeap:= True;
i:= i - 1;
end;
end else
temp:= daysofmonth(y, i);
offset:= offset + temp;
Inc(i);
end;
offset:= offset + objDate.Day - 1;
if (m = leap) and objDate.isLeap then //若为闰月,再加上前一个非闰月天数
offset:= offset + DaysOfMonth(y, m);
// 该年到 2000.1.1 这几年的天数
if y > 2000 then
begin
i:= 2000;
j:= y - 1;
end
else begin
i:= y;
j:= 1999;
end;
temp:= 0;
for t:= i to j do
begin
temp:= temp + DaysOfLunarYear(t);
end;
if y > 1999 then offset:= offset + temp
else offset:= offset - temp;
//农历二零零零年大年初一的阳历为 2000.2.5
Result:= incDay(EncodeDate(2000,2,5),offset);
end;
// 检查农历日期是否合法
function ThxCalendar.ChkHzDate(objDate: THzDate): Boolean;
begin
if (objDate.Year > 2099) or (objDate.Year < 1901)
or (objDate.Month > 12) or (objDate.Day > 30) then
begin
Result:= False;
exit;
end;
Result:= True;
if objDate.isLeap then
begin
if leapMonth(objDate.Year) = objDate.Month then
begin
if DaysOfleapMonth(objDate.Year) < objDate.Day then
Result:= False;
end else Result:= False;
end else
begin
if DaysOfMonth(objDate.Year,objDate.Month) < objDate.Day then
Result:= False;
end;
end;
// 某年的第n个节气为几日(从0小寒起算)
function ThxCalendar.sTerm(y, n: integer): TDateTime;
var
temp: TDateTime;
t: real;
i: Int64;
begin
t:= sTermInfo[n];
t:= t * 60000;
t:= t + 31556925974.7 * (y - 1900);
i:= Round(t);
Temp:= IncMilliSecond(EncodeDateTime(1900,1,6,2,5,0,0),i);
Result:= temp;
end;
// 传入 offset 返回干支, 0=甲子
function ThxCalendar.cyclical(num: integer): string;
begin
Result:= Gan[num mod 10] + Zhi[num mod 12]+'('+Animals[num mod 12]+'年)';
end;
function ThxCalendar.FormatLunarDay(day:integer): string;
begin
case day of
1..10: Result:= nStr2[0] + nStr1[day];
11..19: Result:= nStr2[1] + nStr1[day - 10];
20: Result:= nStr1[2] + nStr1[10];
21..29: Result:= nStr2[2] + nStr1[day - 20];
30: Result:= nStr1[3] + nStr1[10];
else Result :='';
end;
end;
function ThxCalendar.FormatLunarMonth(month: integer; isLeap: boolean): string;
begin
case month of
1..10: Result:= nStr1[month];
11..12: Result:= nStr1[10] + nStr1[month - 10];
else
result :='';
end;
if isLeap then
Result:= '闰' + Result;
Result:= Result + '月';
end;
function ThxCalendar.FormatLunarYear(year:integer): string;
var
temp: integer;
zero: string;
begin
zero:= '零';
temp:= year div 1000;
Result:= nStr1[temp];
year:= year - temp * 1000;
if year >= 100 then
begin
temp:= year div 100;
Result:= Result + nStr1[temp];
year:= year - temp * 100;
end
else
Result:= Result + zero;
if year >= 10 then
begin
temp:= year div 10;
Result:= Result + nStr1[temp];
year:= year - temp * 10;
end
else
Result:= Result + zero;
if year = 0 then Result:= Result + zero else
Result:= Result + nStr1[year];
Result:= Result + '年';
end;
// 取得指定日期的节气
function ThxCalendar.GetJQ(TheDate: TDate): string;
var
jq: Integer;
term: TDateTime;
begin
Result:= '';
jq:= (MonthOf(TheDate) - 1) * 2;
term:= sTerm(Yearof(TheDate), jq); //节气时间
if DateOf(term) = TheDate then
Result:= solarTerm[jq]
else
begin
term:= sTerm(Yearof(TheDate), jq + 1); //中气时间
if DateOf(term) = TheDate then
Result:= solarTerm[jq+1];
end;
end;
function ThxCalendar.GetsFtv(TheDate: TDate): string;
var
sf:string;
jlsl:integer;
begin
for jlsl :=0 to 22 do
begin
sf:=formatdatetime('mmdd',TheDate);
if sf=copy(sFtv[jlsl],1,4)then
begin
Result:=copy(sFtv[jlsl],5,length(sFtv[jlsl])-4);
end;
end;
end;
function ThxCalendar.GetlFtv(TheDate: ThzDate): string;
var
sf,m,d:string;
jlsl:integer;
begin
//HzDate := ToLunar(MyDate);
for jlsl :=0 to 9 do
begin
if TheDate.month<10 then m:='0'+inttostr(TheDate.month)else m:=inttostr(TheDate.month);
if TheDate.day=0 then d:='01';
if TheDate.day<10 then d:='0'+inttostr(TheDate.day)else d:=inttostr(TheDate.day);
sf:=m+d;
if sf=copy(lFtv[jlsl],1,4)then
begin
Result:=copy(lFtv[jlsl],5,length(lFtv[jlsl])-4);
end;
end;
end;
end.
|
unit uConsultaCNPJ;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IPPeerClient, REST.Client,
Data.Bind.Components, Data.Bind.ObjectScope, Vcl.StdCtrls,
ACBrUtil;
type
TconsultaCNPJ = class(TForm)
Button1: TButton;
RESTClient1: TRESTClient;
RESTRequest1: TRESTRequest;
RESTResponse1: TRESTResponse;
Memo1: TMemo;
edtCNPJ: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
consultaCNPJ: TconsultaCNPJ;
implementation
uses
REST.Types, uCliente, REST.Json, pcnConversao;
{$R *.dfm}
procedure TconsultaCNPJ.Button1Click(Sender: TObject);
var
Cliente: TClienteClass;
function SoNumero(fField: String): String;
var
I: Byte;
begin
Result := '';
for I := 1 To Length(fField) do
if fField[I] In ['0' .. '9'] Then
Result := Result + fField[I];
end;
begin
RESTRequest1.Method := rmGet;
RESTClient1.BaseURL := 'https://www.receitaws.com.br/v1/cnpj/';
RESTRequest1.Resource := SoNumero(edtCNPJ.Text);
RESTRequest1.Execute;
Cliente := TClienteClass.Create;
try
Cliente := TJson.JsonToObject<TClienteClass>(RESTResponse1.Content);
Memo1.Clear;
Memo1.Lines.Add('CNPJ: ' + Cliente.cnpj);
Memo1.Lines.Add('Razão Social: ' + Cliente.nome);
Memo1.Lines.Add('Telefone: ' + Cliente.telefone);
Memo1.Lines.Add('Logradouro: ' + Cliente.logradouro);
Memo1.Lines.Add('Número: ' + Cliente.numero);
Memo1.Lines.Add('Complemento: ' + Cliente.complemento);
Memo1.Lines.Add('Bairro: ' + Cliente.bairro);
Memo1.Lines.Add('Cidade: ' + Cliente.municipio);
Memo1.Lines.Add('UF: ' + Cliente.uf);
Memo1.Lines.Add('CEP: ' + Cliente.cep);
Memo1.Lines.Add('Situação: ' + Cliente.situacao);
Memo1.Lines.Add('Data da Situação: ' + Cliente.data_situacao);
finally
Cliente.Free;
end;
end;
end.
|
program Main;
uses UFile, UTipe, UTanggal, USimulasi, UInventori, UResep, UUI, sysutils;
{Kamus}
var
MasukanUser:string;
InputTerproses:UserInput;
OpsiAngka:integer;
KodeError:integer;
isInputValid, isSimulasiAktif: boolean;
i: integer;
ResepBaru: Resep;
HargaResep: longint;
StringInput: string;
Error : boolean;
DeltaUang:longint;
NamaTxt:string;
PerintahMungkin:DaftarPerintah;
const
HARGAUPGRADE = 1000;
procedure loadInventori(nomor:string);
{I.S. : Ada file inventori dan diberi nomor inventori}
{F.S. : File inventori terload}
{Kamus lokal}
var
temp:boolean; {Menyimpan kondisi loadsukes sebelum}
begin
temp:=LoadSukses;
LoadInventoriSukses:=true;
NamaTxt := 'inventori_bahan_mentah_'+nomor+'.txt';
InventoriM := getInventoriBahanMentah(parse(NamaTxt));
InventoriM.Sorted:=false;
NamaTxt := 'inventori_bahan_olahan_'+nomor+'.txt';
InventoriO := getInventoriBahanOlahan(parse(NamaTxt));
InventoriO.sorted:=false;
sortArray();
LoadSukses:=temp;
end;
procedure hentikanSimulasi();
{I.S. Simulasi berjalan}
{F.S. Simulasi berhenti}
begin
lihatStatistik();
isInputValid := true;
isSimulasiAktif := false;
tulisInventori(InventoriM,InventoriO,SimulasiAktif.Nomor);
SemuaSimulasi.Isi[SimulasiAktif.Nomor]:=SimulasiAktif;
end;
procedure loadData();
{I.S. : variabel di unit-unit kosong}
{F.S. : Variabel di unit-unit terisi}
begin
LoadSukses:=true;
DaftarBahanM := getBahanMentah(parse('bahan_mentah.txt'));
DaftarBahanO := getBahanOlahan(parse('bahan_olahan.txt'));
ResepResep := getResep(parse('resep.txt'));
ResepResep.Sorted:=false;
sortResep();
SemuaSimulasi:= getSimulasi(parse('simulasi.txt'));
end;
procedure showHelp();
{I.S. : Tampilan layar kosong}
{F.S. : Dicetak help}
begin
writelnText('Perintah tersedia');
writelnText('load Memuat data dari file');
writelnText('exit Keluar');
writelnText('start Memulai simulasi');
writelnText('stop Mengentikan simulasi');
writelnText('lihatinventori Menampilkan inventori');
writelnText('lihatresep Menampilkan daftar resep');
writelnText('cariresep Mencari resep');
writelnText('tambahresep Menambah resep ke daftar');
writelnText('');
writelnText('Perintah khusus dalam simulasi');
writelnText('belibahan Membeli bahan mentah');
writelnText('olahbahan Mengolah bahan mentah jadi olahan');
writelnText('jualolahan Menjual bahan hasil olahan');
writelnText('jualresep Membuat dan menjual makanan sesuai resep');
writelnText('tidur Memajukan hari dan mengembalikan energi serta menghapus item kadaluarsa');
writelnText('makan Menambah 3 energi');
writelnText('istirahat Menambah 1 energi');
writelnText('lihatstatistik Melihat statistik');
writelnText('upgradeinventori Menambah kapasitas inventori');
end;
{Algoritma}
begin
isSimulasiAktif:=false;
LoadSukses:=false;
while(true)do
begin
prompt(MasukanUser,isSimulasiAktif);
InputTerproses := bacaInput(MasukanUser);
if(not(isSimulasiAktif))then
begin
isInputValid := true;
case LowerCase(InputTerproses.Perintah) of
'load' : begin
loadData();
if(LoadSukses)then
begin
writelnText('Load data berhasil');
end;
end;
'exit' : begin
if(LoadSukses)then
begin
tulisBalik(DaftarBahanM,DaftarBahanO,ResepResep,SemuaSimulasi);
end;
Halt();
end;
'start' : begin
if(LoadSukses)then
begin
if (InputTerproses.Neff = 0) then
begin
tanya('Nomor simulasi',InputTerproses.Opsi[1]);
end;
Val(InputTerproses.Opsi[1],OpsiAngka,KodeError);
if(KodeError<>0)then
begin
writeError('Main','Input opsi bukan angka');
end else
begin
loadInventori(InputTerproses.Opsi[1]);
if(LoadInventoriSukses)then
begin
startSimulasi(OpsiAngka,Error);
if(not(Error)) then
begin
isSimulasiAktif:=true;
end;
end else
begin
writeError('Main','Loading inventori gagal');
end;
end;
end else
begin
writeError('Main','Loading belum sukses');
end;
end;
else
begin
isInputValid := false;
end;
end;
end else
begin
isInputValid := true;
case LowerCase(InputTerproses.Perintah) of
'stop' : begin
hentikanSimulasi();
end;
'belibahan' : begin
if (InputTerproses.Neff < 1 ) then
begin
tanya('Nama bahan',InputTerproses.Opsi[1]);
end;
formatUserInput(InputTerproses.Opsi[1]);
if (InputTerproses.Neff < 2) then
begin
tanya('Jumlah bahan',InputTerproses.Opsi[2]);
end;
Val(InputTerproses.Opsi[2],OpsiAngka,KodeError);
if(KodeError<>0)then
begin
writeError('Main','Jumlah bahan harus berupa angka');
end else
begin
pakeEnergi(Error);
if(not(Error)) then
begin
DeltaUang := beliBahan(InputTerproses.Opsi[1], OpsiAngka);
if(DeltaUang<>-1)then
begin
pakaiUang(DeltaUang, Error);
ubahStatistik(1, OpsiAngka);
writelnText('Berhasil membeli ' + InputTerproses.Opsi[1]);
end;
end;
end;
end;
'olahbahan' : begin
if (InputTerproses.Neff = 0) then
begin
tanya('Nama bahan olahan',InputTerproses.Opsi[1]);
end;
formatUserInput(InputTerproses.Opsi[1]);
if(SimulasiAktif.Energi>0)then
begin
olahBahan(InputTerproses.Opsi[1], Error);
if not(Error) then
begin
ubahStatistik(2,1);
writelnText('Berhasil membuat ' + InputTerproses.Opsi[1]);
pakeEnergi(Error);
end;
end;
end;
'jualolahan' : begin
if (InputTerproses.Neff < 1) then
begin
tanya('Nama bahan olahan',InputTerproses.Opsi[1])
end;
formatUserInput(InputTerproses.Opsi[1]);
if (InputTerproses.Neff < 2) then
begin
tanya('Jumlah bahan olahan untuk dijual',InputTerproses.Opsi[2]);
end;
Val(InputTerproses.Opsi[2],OpsiAngka,KodeError);
if(KodeError<>0)then
begin
writeError('Main','Jumlah bahan untuk dijual harus berupa angka');
end else
begin
if(SimulasiAktif.Energi>1) then
begin
DeltaUang:=jualOlahan(InputTerproses.Opsi[1], OpsiAngka);
if (DeltaUang<>-1) then
begin
tambahUang(DeltaUang);
ubahStatistik(3,OpsiAngka);
writelnText('Berhasil menjual ' + InputTerproses.Opsi[1]);
pakeEnergi(Error);
end;
end;
end;
end;
'jualresep' : begin
if (InputTerproses.Neff = 0) then
begin
tanya('Nama resep',InputTerproses.Opsi[1])
end;
formatUserInput(InputTerproses.Opsi[1]);
if(SimulasiAktif.Energi>1) then
begin
DeltaUang:=jualResep(InputTerproses.Opsi[1]);
if (DeltaUang <> -1) then
begin
tambahUang(DeltaUang);
ubahStatistik(4, 1);
writelnText('Berhasil menjual ' + InputTerproses.Opsi[1]);
pakeEnergi(Error);
end;
end;
end;
'makan' : begin
makan();
end;
'istirahat' : begin
istirahat();
end;
'tidur' : begin
tidur(Error);
if(not(Error))then
begin
writelnText('Berhasil tidur');
hapusKadaluarsa();
if(SimulasiAktif.JumlahHidup=10)then
begin
writelnText('Simulasi selesai (10 hari)');
hentikanSimulasi();
end
end;
end;
'lihatstatistik' : begin
lihatStatistik();
end;
'statistik' : begin
lihatStatistik();
end;
else
begin
isInputValid := false;
end;
end;
end;
isInputValid := not(isInputValid);
case LowerCase(InputTerproses.Perintah) of
'upgradeinventori':begin
if(isSimulasiAktif)then
begin
upgradeInventori(Error);
if (not(Error)) then
begin
pakaiUang(HARGAUPGRADE, Error);
writelnText('Berhasil menambah kapasitas inventori menjadi ' + IntToStr(SimulasiAktif.Kapasitas));
end;
end else
begin
if(LoadSukses)then
begin
if (InputTerproses.Neff = 0) then
begin
tanya('Nomor simulasi',InputTerproses.Opsi[1]);
end;
Val(InputTerproses.Opsi[1],OpsiAngka,KodeError);
if(KodeError<>0)then
begin
writeError('Main','Nomor simulasi harus berupa angka');
end else
begin
if(simulasiAda(OpsiAngka)<>-1)then
begin
SimulasiAktif := SemuaSimulasi.Isi[simulasiAda(OpsiAngka)];
upgradeInventori(Error);
if (not(Error)) then
begin
pakaiUang(HARGAUPGRADE, Error);
writelnText('Berhasil menambah kapasitas inventori menjadi ' + IntToStr(SimulasiAktif.Kapasitas));
end;
end else
begin
writeError('Main','Nomor simulasi tidak ada');
end;
end;
end else
begin
writeError('Main','Loading belum sukses');
end;
end;
end;
'lihatresep':begin
if(LoadSukses)then
begin
sortResep();
lihatresep();
end else
begin
writeError('Main','Loading belum sukses');
end;
end;
'help':begin
writelnText('Engi''s Kitchen');
showHelp();
end;
'lihatinventori' : begin
if(not(isSimulasiAktif))then
begin
if (InputTerproses.Neff = 0) then
begin
tanya('Nomor inventori',InputTerproses.Opsi[1]);
end;
Val(InputTerproses.Opsi[1],OpsiAngka,KodeError);
if(KodeError<>0)then
begin
writeError('Main','Nomor inventori harus berupa angka');
end else
begin
loadInventori(InputTerproses.Opsi[1]);
if(LoadInventoriSukses)then
begin
lihatInventori();
end else
begin
writeError('Main','Load inventori gagal');
end;
end;
end else
begin
sortArray();
lihatInventori();
end;
end;
'cariresep' : begin
if(LoadSukses)then
begin
if (InputTerproses.Neff = 0) then
begin
tanya('Nama resep',InputTerproses.Opsi[1]);
end;
formatUserInput(InputTerproses.Opsi[1]);
cariResep(InputTerproses.Opsi[1]);
end else
begin
writeError('Main','Loading belum sukses');
end;
end;
'tambahresep' : begin
if(LoadSukses)then
begin
if(InputTerproses.Neff = 0) then
begin
tanya('Nama resep',InputTerproses.Opsi[1]);
end;
formatUserInput(InputTerproses.Opsi[1]);
ResepBaru.Nama := InputTerproses.Opsi[1];
tanya('Harga',StringInput);
Val(StringInput,HargaResep,KodeError);
if(KodeError<>0) then
begin
writeError('Main','Harga harus berupa angka');
end else
begin
ResepBaru.Harga := HargaResep;
tanya('Jumlah bahan',StringInput);
Val(StringInput,OpsiAngka,KodeError);
if(KodeError<>0) then
begin
writeError('Main','Jumlah bahan harus berupa angka');
end else
begin
if((OpsiAngka>=2)and(OpsiAngka<=20))then
begin
ResepBaru.JumlahBahan := OpsiAngka;
writelnText('Daftar bahan: ');
for i := 1 to ResepBaru.JumlahBahan do
begin
tanya(' Bahan '+ IntToStr(i),ResepBaru.Bahan[i]);
formatUserInput(ResepBaru.Bahan[i]);
end;
tambahResep(ResepBaru, Error);
if (not(Error)) then
begin
writelnText('Berhasil menambahkan resep ' + ResepBaru.Nama);
end;
end else
begin
writeError('Main','Jumlah bahan harus >= 2 dan <= 20');
end;
end;
end;
end else
begin
writeError('Main','Loading belum sukses');
end;
end;
else
begin
isInputValid := not(isInputValid);
end;
end;
if(not(isInputValid))then
begin
writeError('Main', 'Perintah tidak valid');
if(isSimulasiAktif)then
begin
{Isi daftar}
PerintahMungkin.Isi[1]:='stop';
PerintahMungkin.Isi[2]:='lihatinventori';
PerintahMungkin.Isi[3]:='lihatresep';
PerintahMungkin.Isi[4]:='cariresep';
PerintahMungkin.Isi[5]:='tambahresep';
PerintahMungkin.Isi[6]:='belibahan';
PerintahMungkin.Isi[7]:='olahbahan';
PerintahMungkin.Isi[8]:='jualolahan';
PerintahMungkin.Isi[9]:='jualresep';
PerintahMungkin.Isi[10]:='tidur';
PerintahMungkin.Isi[11]:='makan';
PerintahMungkin.Isi[12]:='istirahat';
PerintahMungkin.Isi[13]:='lihatstatistik';
PerintahMungkin.Isi[14]:='upgradeinventori';
PerintahMungkin.Neff := 13;
end else
begin
{Isi daftar}
PerintahMungkin.Isi[1]:='load';
PerintahMungkin.Isi[2]:='exit';
PerintahMungkin.Isi[3]:='start';
PerintahMungkin.Isi[5]:='lihatinventori';
PerintahMungkin.Isi[6]:='lihatresep';
PerintahMungkin.Isi[7]:='cariresep';
PerintahMungkin.Isi[8]:='tambahresep';
PerintahMungkin.Neff := 8;
end;
commandPredictor(InputTerproses.Perintah,PerintahMungkin);
end;
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: HDREnumeration.pas,v 1.5 2007/02/05 22:21:08 clootie Exp $
*----------------------------------------------------------------------------*)
//======================================================================
//
// HIGH DYNAMIC RANGE RENDERING DEMONSTRATION
// Written by Jack Hoxley, November 2005
//
//======================================================================
{$I DirectX.inc}
unit HDREnumeration;
interface
uses
Windows, Direct3D9,
DXUT, DXUTenum;
// Several modules making up this sample code need to make
// decisions based on what features the underlying hardware
// supports. These queries are contained in the following
// namespace:
// namespace HDREnumeration {}
// The following function will examine the capabilities of the device
// and store the best format in 'pBestFormat'.
function FindBestHDRFormat(out BestFormat: TD3DFormat): HRESULT;
// A similar function to above, but this one examines the single-channel
// G32R32F and G16R16F support - used by the luminance measurement calculations.
function FindBestLuminanceFormat(out BestLuminanceFormat: TD3DFormat): HRESULT;
implementation
//--------------------------------------------------------------------------------------
// FindBestHDRFormat( )
//
// DESC:
// Due to High Dynamic Range rendering still being a relatively high-end
// feature in consumer hardware, several basic properties are still not
// uniformly available. Two particular examples are texture filtering and
// post pixel-shader blending.
//
// Substantially better results can be gained from this sample if texture
// filtering is available. Post pixel-shader blending is not required. The
// following function will enumerate supported formats in the following order:
//
// 1. Single Precision (128 bit) with support for linear texture filtering
// 2. Half Precision (64 bit) with support for linear texture filtering
// 3. Single Precision (128 bit) with NO texture filtering support
// 4. Half Precision (64 bit) with NO texture filtering support
//
// If none of the these can be satisfied, the device should be considered
// incompatable with this sample code.
//
// PARAMS:
// pBestFormat : A container for the detected best format. Can be NULL.
//
// NOTES:
// The pBestFormat parameter can be set to NULL if the specific format is
// not actually required. Because of this, the function can be used as a
// simple predicate to determine if the device can handle HDR rendering:
//
// if( FAILED( FindBestHDRFormat( NULL ) ) )
// {
// // This device is not compatable.
// }
//
//--------------------------------------------------------------------------------------
function FindBestHDRFormat(out BestFormat: TD3DFormat): HRESULT;
var
info: TDXUTDeviceSettings;
begin
// Retrieve important information about the current configuration
info := DXUTGetDeviceSettings;
Result := DXUTGetD3DObject.CheckDeviceFormat(info.AdapterOrdinal, info.DeviceType, info.AdapterFormat, D3DUSAGE_QUERY_FILTER or D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F);
if FAILED(Result) then
begin
// We don't support 128 bit render targets with filtering. Check the next format.
OutputDebugString('Enumeration.FindBestHDRFormat() - Current device does *not* support single-precision floating point textures with filtering.'#10);
Result := DXUTGetD3DObject.CheckDeviceFormat(info.AdapterOrdinal, info.DeviceType, info.AdapterFormat, D3DUSAGE_QUERY_FILTER or D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F);
if FAILED(Result) then
begin
// We don't support 64 bit render targets with filtering. Check the next format.
OutputDebugString('Enumeration::FindBestHDRFormat() - Current device does *not* support half-precision floating point textures with filtering.'#10);
Result := DXUTGetD3DObject.CheckDeviceFormat(info.AdapterOrdinal, info.DeviceType, info.AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F);
if FAILED(Result) then
begin
// We don't support 128 bit render targets. Check the next format.
OutputDebugString('Enumeration::FindBestHDRFormat() - Current device does *not* support single-precision floating point textures.'#10);
Result := DXUTGetD3DObject.CheckDeviceFormat(info.AdapterOrdinal, info.DeviceType, info.AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F);
if FAILED(Result) then
begin
// We don't support 64 bit render targets. This device is not compatable.
OutputDebugString('Enumeration::FindBestHDRFormat() - Current device does *not* support half-precision floating point textures.'#10);
OutputDebugString('Enumeration::FindBestHDRFormat() - THE CURRENT HARDWARE DOES NOT SUPPORT HDR RENDERING!'#10);
Result:= E_FAIL;
Exit;
end else
begin
// We have support for 64 bit render targets without filtering
OutputDebugString('Enumeration::FindBestHDRFormat() - Best available format is ''half-precision without filtering''.'#10);
BestFormat := D3DFMT_A16B16G16R16F;
end;
end
else
begin
// We have support for 128 bit render targets without filtering
OutputDebugString('Enumeration::FindBestHDRFormat() - Best available format is ''single-precision without filtering''.'#10);
BestFormat := D3DFMT_A32B32G32R32F;
end;
end
else
begin
// We have support for 64 bit render targets with filtering
OutputDebugString('Enumeration::FindBestHDRFormat - Best available format is ''half-precision with filtering''.'#10);
BestFormat := D3DFMT_A16B16G16R16F;
end;
end else
begin
// We have support for 128 bit render targets with filtering
OutputDebugString('Enumeration::FindBestHDRFormat() - Best available format is ''single-precision with filtering''.'#10);
BestFormat := D3DFMT_A32B32G32R32F;
end;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// FindBestLuminanceFormat( )
//
// DESC:
// << See notes for 'FindBestHDRFormat' >>
// The luminance calculations store a single intensity and maximum brightness, and
// as such don't need to use textures with the full 128 or 64 bit sizes. D3D
// offers two formats, G32R32F and G16R16F for this sort of purpose - and this
// function will return the best supported format. The following function will
// enumerate supported formats in the following order:
//
// 1. Single Precision (32 bit) with support for linear texture filtering
// 2. Half Precision (16 bit) with support for linear texture filtering
// 3. Single Precision (32 bit) with NO texture filtering support
// 4. Half Precision (16 bit) with NO texture filtering support
//
// If none of the these can be satisfied, the device should be considered
// incompatable with this sample code.
//
// PARAMS:
// pBestLuminanceFormat : A container for the detected best format. Can be NULL.
//
// NOTES:
// The pBestLuminanceFormatparameter can be set to NULL if the specific format is
// not actually required. Because of this, the function can be used as a
// simple predicate to determine if the device can handle HDR rendering:
//
// if( FAILED( FindBestLuminanceFormat( NULL ) ) )
// {
// // This device is not compatable.
// }
//
//--------------------------------------------------------------------------------------
function FindBestLuminanceFormat(out BestLuminanceFormat: TD3DFormat): HRESULT;
var
info: TDXUTDeviceSettings;
begin
// Retrieve important information about the current configuration
info := DXUTGetDeviceSettings;
Result := DXUTGetD3DObject.CheckDeviceFormat(info.AdapterOrdinal, info.DeviceType, info.AdapterFormat, D3DUSAGE_QUERY_FILTER or D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_G32R32F);
if FAILED(Result) then
begin
// We don't support 32 bit render targets with filtering. Check the next format.
OutputDebugString('Enumeration::FindBestLuminanceFormat() - Current device does *not* support single-precision floating point textures with filtering.'#10);
Result := DXUTGetD3DObject.CheckDeviceFormat(info.AdapterOrdinal, info.DeviceType, info.AdapterFormat, D3DUSAGE_QUERY_FILTER or D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_G16R16F);
if FAILED(Result) then
begin
// We don't support 16 bit render targets with filtering. Check the next format.
OutputDebugString('Enumeration::FindBestLuminanceFormat() - Current device does *not* support half-precision floating point textures with filtering.'#10);
Result := DXUTGetD3DObject.CheckDeviceFormat(info.AdapterOrdinal, info.DeviceType, info.AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_G32R32F);
if FAILED(Result) then
begin
// We don't support 32 bit render targets. Check the next format.
OutputDebugString('Enumeration::FindBestLuminanceFormat() - Current device does *not* support single-precision floating point textures.'#10);
Result := DXUTGetD3DObject.CheckDeviceFormat(info.AdapterOrdinal, info.DeviceType, info.AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_G16R16F);
if FAILED(Result) then
begin
// We don't support 16 bit render targets. This device is not compatable.
OutputDebugString('Enumeration::FindBestLuminanceFormat() - Current device does *not* support half-precision floating point textures.'#10);
OutputDebugString('Enumeration::FindBestLuminanceFormat() - THE CURRENT HARDWARE DOES NOT SUPPORT HDR RENDERING!'#10);
Result:= E_FAIL;
Exit;
end else
begin
// We have support for 16 bit render targets without filtering
OutputDebugString('Enumeration::FindBestLuminanceFormat() - Best available format is ''half-precision without filtering''.'#10);
BestLuminanceFormat := D3DFMT_G16R16F;
end;
end else
begin
// We have support for 32 bit render targets without filtering
OutputDebugString('Enumeration::FindBestLuminanceFormat() - Best available format is ''single-precision without filtering''.'#10);
BestLuminanceFormat := D3DFMT_G32R32F;
end;
end else
begin
// We have support for 16 bit render targets with filtering
OutputDebugString('Enumeration::FindBestLuminanceFormat() - Best available format is ''half-precision with filtering''.'#10);
BestLuminanceFormat := D3DFMT_G16R16F;
end;
end else
begin
// We have support for 32 bit render targets with filtering
OutputDebugString('Enumeration::FindBestLuminanceFormat() - Best available format is ''single-precision with filtering''.'#10);
BestLuminanceFormat := D3DFMT_G32R32F;
end;
Result:= S_OK;
end;
end.
|
(*
Category: SWAG Title: ARCHIVE HANDLING
Original name: 0003.PAS
Description: String Compression
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:33
*)
{You won't get that sort of compression from my routines, but here
they are anyway. When testing, you'll get best compression if you
use English and longish Strings.
}
Uses Crt, Dos;
(*
Unit Compress;
Interface
*)
Const
CompressedStringArraySize = 500; { err on the side of generosity }
Type
tCompressedStringArray = Array[1..CompressedStringArraySize] of Byte;
(*
Function GetCompressedString(Arr : tCompressedStringArray) : String;
Procedure CompressString(st : String; Var Arr : tCompressedStringArray;
Var len : Integer);
{ converts st into a tCompressedStringArray of length len }
Implementation
*)
Const
FreqChar : Array[4..14] of Char = 'etaonirshdl';
{ can't be in [0..3] because two empty bits signify a space }
Function GetCompressedString(Arr : tCompressedStringArray) : String;
Var
Shift : Byte;
i : Integer;
ch : Char;
st : String;
b : Byte;
Function GetHalfNibble : Byte;
begin
GetHalfNibble := (Arr[i] shr Shift) and 3;
if Shift = 0 then begin
Shift := 6;
inc(i);
end else dec(Shift,2);
end;
begin
st := '';
i := 1;
Shift := 6;
Repeat
b := GetHalfNibble;
if b = 0 then
ch := ' '
else begin
b := (b shl 2) or GetHalfNibble;
if b = $F then begin
b := GetHalfNibble shl 6;
b := b or GetHalfNibble shl 4;
b := b or GetHalfNibble shl 2;
b := b or GetHalfNibble;
ch := Char(b);
end else
ch := FreqChar[b];
end;
if ch <> #0 then st := st + ch;
Until ch = #0;
GetCompressedString := st;
end;
Procedure CompressString(st : String; Var Arr : tCompressedStringArray;
Var len : Integer);
{ converts st into a tCompressedStringArray of length len }
Var
i : Integer;
Shift : Byte;
Procedure OutHalfNibble(b : Byte);
begin
Arr[len] := Arr[len] or (b shl Shift);
if Shift = 0 then begin
Shift := 6;
inc(len);
end else dec(Shift,2);
end;
Procedure OutChar(ch : Char);
Var
i : Byte;
bych : Byte Absolute ch;
begin
if ch = ' ' then
OutHalfNibble(0)
else begin
i := 4;
While (i<15) and (FreqChar[i]<>ch) do inc(i);
OutHalfNibble(i shr 2);
OutHalfNibble(i and 3);
if i = $F then begin
OutHalfNibble(bych shr 6);
OutHalfNibble((bych shr 4) and 3);
OutHalfNibble((bych shr 2) and 3);
OutHalfNibble(bych and 3);
end;
end;
end;
begin
len := 1;
Shift := 6;
fillChar(Arr,sizeof(Arr),0);
For i := 1 to length(st) do OutChar(st[i]);
OutChar(#0); { end of compressed String signaled by #0 }
if Shift = 6
then dec(len);
end;
{------}
(*
Category: SWAG Title: ARCHIVE HANDLING
Original name: 0009.PAS
Description: Test String Compression
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:33
*)
(*
Program TestComp; { tests Compression }
{ kludgy test of Compress Unit }
Uses Crt, Dos, Compress;
*)
Const
NumofStrings = 5;
Var
ch : Char;
LongestStringLength,i,j,len : Integer;
Textfname,Compfname : String;
TextFile : Text;
ByteFile : File;
CompArr : tCompressedStringArray;
st : Array[1..NumofStrings] of String;
Rec : SearchRec;
BigArr : Array[1..5000] of Byte;
Arr : Array[1..NumofStrings] of tCompressedStringArray;
begin
Writeln('note: No I/O checking in this test.');
Write('Test <C>ompress or <U>nCompress? ');
Repeat
ch := upCase(ReadKey);
Until ch in ['C','U',#27];
if ch = #27 then halt;
Writeln(ch);
if ch = 'C' then begin
Writeln('Enter ',NumofStrings,' Strings:');
LongestStringLength := 0;
For i := 1 to NumofStrings do begin
Write(i,': ');
readln(st[i]);
if length(st[i]) > LongestStringLength then
LongestStringLength := length(st[i]);
end;
Writeln;
Writeln('Enter name of File to store unCompressed Strings in.');
Writeln('ANY EXISTinG File With THIS NAME WILL BE OVERWRITTEN.');
readln(Textfname);
assign(TextFile,Textfname);
reWrite(TextFile);
For i := 1 to NumofStrings do
Writeln(TextFile,st[i]);
close(TextFile);
Writeln;
Writeln('Enter name of File to store Compressed Strings in.');
Writeln('ANY EXISTinG File With THIS NAME WILL BE OVERWRITTEN.');
readln(Compfname);
assign(ByteFile,Compfname);
reWrite(ByteFile,1);
For i := 1 to NumofStrings do begin
CompressString(st[i],CompArr,len);
blockWrite(ByteFile,CompArr,len);
end;
close(ByteFile);
FindFirst(Textfname,AnyFile,Rec);
Writeln;
Writeln;
Writeln('Size of Text File storing Strings: ',Rec.Size);
Writeln;
Writeln('Using Typed Files, a File of Type String[',
LongestStringLength,
'] would be necessary.');
Writeln('That would be ',
(LongestStringLength+1)*NumofStrings,
' long, including length Bytes.');
Writeln;
FindFirst(Compfname,AnyFile,Rec);
Writeln('Size of the Compressed File: ',Rec.Size);
Writeln;
Writeln('Now erase the Text File, and run this Program again, choosing');
Writeln('<U>nCompress to show that the Compression retains all info.');
end else begin { ch = 'U' }
Write('Name of Compressed File: ');
readln(Compfname);
assign(ByteFile,Compfname);
reset(ByteFile,1);
blockread(ByteFile,BigArr,Filesize(ByteFile));
close(ByteFile);
For j := 1 to NumofStrings do begin
i := 1;
While BigArr[i] <> 0 do inc(i);
move(BigArr[1],Arr[j],i);
move(BigArr[i+1],BigArr[1],sizeof(BigArr));
end;
For i := 1 to NumofStrings do
st[i] := GetCompressedString(Arr[i]);
For i := 1 to NumofStrings do
Writeln(st[i]);
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit CustomLoginResourceU;
// EMS Resource Unit
interface
uses
System.SysUtils, System.Classes, System.JSON,
EMS.Services, EMS.ResourceAPI,
EMS.ResourceTypes;
type
{$METHODINFO ON}
[ResourceName('CustomLogin')]
TCustomLogonResource = class
private
procedure ValidateCredentials(const ADomainName, AUserName,
APassword: string);
public
[EndpointName('CustomSignupUser')]
// Declare endpoint that matches signature of Users.SignupUser
[ResourceSuffix('signup')]
procedure PostSignup(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
[EndpointName('CustomLoginUser')]
// Declare endpoint that matches signature of Users.LoginUser
[ResourceSuffix('login')]
procedure PostLogin(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
end;
{$METHODINFO OFF}
procedure Register;
implementation
uses Winapi.Windows;
procedure Register;
begin
RegisterResource(TypeInfo(TCustomLogonResource));
end;
{ TCustomLogonResource }
// Validate credentials using windows logon API.
procedure TCustomLogonResource.ValidateCredentials(const ADomainName, AUserName, APassword: string);
const
LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
var
LLoginType: Cardinal;
LLoginProvider: Cardinal;
LToken: THandle;
LError: Cardinal;
begin
LLoginType := LOGON32_LOGON_NETWORK_CLEARTEXT;
LLoginProvider := LOGON32_PROVIDER_DEFAULT;
if LogonUser(PChar(AUserName), PChar(ADomainName), PChar(APassword), LLoginType, LLoginProvider, LToken) then
CloseHandle(LToken)
else
begin
LError := GetLastError;
EEMSHTTPError.RaiseUnauthorized('', SysErrorMessage(LError));
end;
end;
// Custom EMS login
procedure TCustomLogonResource.PostLogin(const AContext: TEndpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
LEMSAPI: TEMSInternalAPI;
LResponse: IEMSResourceResponseContent;
LValue: TJSONValue;
LUserName: string;
LPassword: string;
begin
// Create in-process EMS API
LEMSAPI := TEMSInternalAPI.Create(AContext);
try
// Extract credentials from request
if not (ARequest.Body.TryGetValue(LValue) and
LValue.TryGetValue<string>(TEMSInternalAPI.TJSONNames.UserName, LUserName) and
LValue.TryGetValue<string>(TEMSInternalAPI.TJSONNames.Password, LPassword)) then
AResponse.RaiseBadRequest('', 'Missing credentials');
ValidateCredentials('', LUserName, LPassword);
// Uncomment to automatically create a user if the credentials are valid.
// Otherwise, EMS will raise a not-found exception if an EMS user has not already been signed up.
// if not LEMSAPI.QueryUserName(LUserName) then
// // Add user when there is no user for these credentials
// // in-process call to actual Users/Signup endpoint
// LResponse := LEMSAPI.SignupUser(LUserName, LPassword, nil)
// else
// in-process call to actual Users/Login endpoint
LResponse := LEMSAPI.LoginUser(LUserName, LPassword);
if LResponse.TryGetValue(LValue) then
AResponse.Body.SetValue(LValue, False);
finally
LEMSAPI.Free;
end;
end;
// Custom EMS signup
procedure TCustomLogonResource.PostSignup(const AContext: TEndpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
LEMSAPI: TEMSInternalAPI;
LResponse: IEMSResourceResponseContent;
LValue: TJSONObject;
LUserName: string;
LPassword: string;
LUserFields: TJSONObject;
begin
// Create in-process EMS API
LEMSAPI := TEMSInternalAPI.Create(AContext);
try
// Extract credentials from request
if not (ARequest.Body.TryGetObject(LValue) and
LValue.TryGetValue<string>(TEMSInternalAPI.TJSONNames.UserName, LUserName) and
LValue.TryGetValue<string>(TEMSInternalAPI.TJSONNames.Password, LPassword)) then
AResponse.RaiseBadRequest('', 'Missing credentials');
ValidateCredentials('', LUserName, LPassword);
LUserFields := LValue.Clone as TJSONObject;
try
// Remove meta data
LUserFields.RemovePair(TEMSInternalAPI.TJSONNames.UserName);
LUserFields.RemovePair(TEMSInternalAPI.TJSONNames.Password);
// Add another field, for example
LUserFields.AddPair('comment', 'This user added by CustomResource.CustomSignupUser');
// in-process call to actual Users/Signup endpoint
LResponse := LEMSAPI.SignupUser(LUserName, LPassword, LUserFields)
finally
LUserFields.Free;
end;
if LResponse.TryGetObject(LValue) then
AResponse.Body.SetValue(LValue, False);
finally
LEMSAPI.Free;
end;
end;
end.
|
unit MainForm;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
FileUtil,
Forms,
Controls,
Graphics,
Dialogs,
StdCtrls,
ExtCtrls, ComCtrls, Menus,
VD_FormPosSize;
type
{ TFrmMain }
TFrmMain = class(TForm)
btnSubjects: TButton;
btnItems: TButton;
btnLanguages: TButton;
Image1: TImage;
mnItmDataBasse: TMenuItem;
statbrMain: TStatusBar;
theMainMenu: TMainMenu;
mnItmSettingsFrm: TMenuItem;
mnItmLookups: TMenuItem;
mnitmSettings: TMenuItem;
tlbrMainFrm: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
VDFormPosSize1: TVDFormPosSize;
procedure btnLanguagesClick(Sender: TObject);
procedure btnSubjectsClick(Sender: TObject);
procedure btnItemsClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure mnItmDataBasseClick(Sender: TObject);
procedure mnItmLookupsClick(Sender: TObject);
procedure btnItemsClickMulti(Sender: TObject);
procedure mnItmSettingsFrmClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.lfm}
{ TFrmMain }
uses
frm_items,
frm_subjects,
//Cls_Entities,
datamodule,
//VD_Conversie,
//ps_inifile,
frm_database,
frm_lookups,
frm_languages,
frm_settings,
cls_appinit,
globals;
var
mItmsFrms: TFormArray;
procedure TFrmMain.FormCreate(Sender: TObject);
var
lIsAppDataDir: Boolean;
begin
TAppInit.InitializeMainForm(Self);
end;
procedure TFrmMain.btnSubjectsClick(Sender: TObject);
begin
if not Assigned(frmSubjects) then
frmSubjects := TfrmSubjects.Create(Application);
frmSubjects.Show;
end;
procedure TFrmMain.btnLanguagesClick(Sender: TObject);
begin
TfrmLanguages.ShowfrmLanguages;
end;
procedure TFrmMain.btnItemsClick(Sender: TObject);
begin
if not Assigned(frmItems) then
frmItems := TfrmItems.Create(Application);
frmItems.Show;
end;
procedure TFrmMain.btnItemsClickMulti(Sender: TObject);
var
lLen : integer;
lTop, lLeft: integer;
begin
lLen := Length(mItmsFrms);
SetLength(mItmsFrms, lLen + 1);
mItmsFrms[lLen] := TfrmItems.Create(Application);
mItmsFrms[lLen].Name := 'frmItems' + IntToStr(lLen);
mItmsFrms[lLen].Caption := 'Items ' + IntToStr(lLen);
(mItmsFrms[lLen] as TfrmItems).formTakePosition;
//if lLen > 1 then
// lTop := mItmsFrms[lLen]
mItmsFrms[lLen].Show;
end;
procedure TFrmMain.FormShow(Sender: TObject);
begin
end;
procedure TFrmMain.mnItmDataBasseClick(Sender: TObject);
begin
TfrmDataBase.ShowForm;
end;
procedure TFrmMain.mnItmLookupsClick(Sender: TObject);
begin
if not Assigned(frmLookUps) then
frmLookUps := TfrmLookUps.Create(Application);
frmLookUps.Show;
end;
procedure TFrmMain.mnItmSettingsFrmClick(Sender: TObject);
begin
TfrmSettings.ShowfrmSettings;
end;
procedure TFrmMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
var
lLen : integer;
i: integer;
begin
lLen := Length(mItmsFrms);
try
//if not qInd_ProblDataBase then
for i := 0 to lLen do
begin
mItmsFrms[i].Close;
mItmsFrms[i].Free;
end;
if Assigned(frmDataBase) then
begin
frmDataBase.Close;
frmDataBase.Free;
end;
if Assigned(MainDataMod) then
MainDataMod.Destroy;
except
ShowMessage(cns_Msg_ProblClosingProgram);
end;
end;
end.
|
unit DPM.IDE.InstallerContext;
interface
uses
Spring.Collections,
VSoft.CancellationToken,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Dependency.Interfaces,
DPM.Core.Package.Installer.Interfaces,
DPM.Core.Package.InstallerContext,
DPM.Core.Spec.Interfaces,
DPM.IDE.DesignManager;
type
TDPMIDEPackageInstallerContext = class(TCorePackageInstallerContext, IPackageInstallerContext)
private
FDesignManager : IDPMIDEDesignManager;
protected
procedure Clear;override;
procedure RemoveProject(const projectFile : string);override;
function InstallDesignPackages(const cancellationToken: ICancellationToken; const projectFile : string; const packageSpecs: IDictionary<string, IPackageSpec>) : boolean;override;
public
constructor Create(const logger : ILogger; const designManager : IDPMIDEDesignManager);reintroduce;
end;
implementation
{ TDPMIDEPackageInstallerContext }
constructor TDPMIDEPackageInstallerContext.Create(const logger: ILogger; const designManager : IDPMIDEDesignManager);
begin
inherited Create(logger);
FDesignManager := designManager;
end;
function TDPMIDEPackageInstallerContext.InstallDesignPackages(const cancellationToken: ICancellationToken; const projectFile : string; const packageSpecs: IDictionary<string, IPackageSpec>): boolean;
begin
result := true;
end;
procedure TDPMIDEPackageInstallerContext.RemoveProject(const projectFile: string);
begin
inherited;
//unstall any unused design time packages.
end;
procedure TDPMIDEPackageInstallerContext.Clear;
begin
inherited;
//uninstall any design time packages.
end;
end.
|
{----------------------------------------------------------------
Nome: UntwIRCCanal
Descrição: Descendente do form TwIRCSecao.
Especialização: Form para comunicação em salas(canais) na rede
IRC.
Métodos:
-procedure AdNick(Nick: string); Adicina Nick a lista
-procedure RmNick(Nick: string); Remove um nick da lista
Propriedades:
-Canal: string que designa o canal que está conectado
-Topico: string que guarda o tópico do canal
----------------------------------------------------------------}
unit UntwIRCCanal;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
UntwIRCSecao, Menus, StdCtrls, IRCUtils, FatThings;
type
TwIRCCanal = class(TwIRCSecao)
LsbNicks: TListBox;
procedure CmdTextoKeyPress(Sender: TObject; var Key: Char);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure LsbNicksDblClick(Sender: TObject);
private
{ Private declarations }
public
Canal: string;
Topico: string;
procedure AdNick(Nick: string);
procedure RmNick(Nick: string);
end;
var
wIRCCanal: TwIRCCanal;
implementation
uses UntComandos, Untprincipal;
{$R *.DFM}
procedure TwIRCCanal.AdNick(Nick: string);
var
IndiceA, IndiceB: integer;
begin
{Só adiciona o nick se ele não estiver adicionado}
IndiceA:=LsbNicks.Items.IndexOf(Nick);
IndiceB:=LsbNicks.Items.IndexOf(NickReal(Nick)); {Testa sem os atributos}
if ((IndiceA < 0) or (IndiceB < 0)) then
LsbNicks.Items.Add(Nick);
end;
procedure TwIRCCanal.RmNick(Nick: string);
var {Remove nick da lista}
Contador: integer;
begin
for Contador:=0 to LsbNicks.Items.Count - 1 do
if (NickReal(LsbNicks.Items.Strings[Contador]) = NickReal(Nick)) then
begin
LsbNicks.Items.Delete(Contador);
break;
end;
end;
procedure TwIRCCanal.CmdTextoKeyPress(Sender: TObject; var Key: Char);
var {Envia menssagem para a seção atual (PVT ou Canal)}
Texto: string;
begin
if (Key = #13) then
begin
if (FrmPrincipal.EstIRC = eiDesconectado) then
begin {Caso não esteja conectado a menssagem não pode ser enviada}
AdLinha('Não conectado!');
CmdTexto.Text:='';
end
else
if (Length(CmdTexto.Text) > 0) then
begin
Texto:=CmdTexto.Text;
AdLinha('[MeuNick] ' + Texto); {TEMP}
PvtMsg(Canal, Texto); {Envia menssagem para seu destino}
CmdTexto.Text:='';
end;
FrmPrincipal.RolarTexto(Self.MemTexto);
Abort; {Nesessário para não produzir um beep do Windows(blergh!)}
end;
end;
procedure TwIRCCanal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
PartCha(Canal);
end;
procedure TwIRCCanal.FormShow(Sender: TObject);
begin
inherited; {Redimenciona todos os componentes para posição adequada no form}
LsbNicks.Left:=ClientWidth - LsbNicks.Width;
CmdTexto.Top:=ClientHeight - 23;
CmdTexto.Width:=ClientWidth;
MemTexto.Width:=ClientWidth - LsbNicks.Width;
MemTexto.Height:=(ClientHeight - CmdTexto.Height) - 1;
LsbNicks.Height:=(ClientHeight - CmdTexto.Height) - 1;
end;
procedure TwIRCCanal.FormCreate(Sender: TObject);
begin
inherited;
FrmPrincipal.ImlIcones.GetBitmap(1, Self.Barra.Glyph);
end;
procedure TwIRCCanal.LsbNicksDblClick(Sender: TObject);
begin
FrmPrincipal.AbrirPvt(NickReal(LsbNicks.Items.Strings[LsbNicks.ItemIndex]));
end;
end.
|
unit LoginScreen.View.PDV;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
Vcl.WinXCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.Imaging.pngimage,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TPDV = class(TForm)
Panel1: TPanel;
SplitView1: TSplitView;
Panel2: TPanel;
Panel3: TPanel;
Label1: TLabel;
Image1: TImage;
Panel5: TPanel;
Panel4: TPanel;
pnBuscaProduto: TPanel;
Label2: TLabel;
Image2: TImage;
Panel7: TPanel;
Panel8: TPanel;
pnTopo: TPanel;
pnCodigo: TPanel;
Panel6: TPanel;
DBGrid1: TDBGrid;
Panel9: TPanel;
Panel10: TPanel;
Panel11: TPanel;
Panel12: TPanel;
Panel13: TPanel;
Panel14: TPanel;
Panel15: TPanel;
Panel16: TPanel;
Panel17: TPanel;
Label3: TLabel;
Image3: TImage;
Panel18: TPanel;
Panel20: TPanel;
Label4: TLabel;
Image4: TImage;
Panel21: TPanel;
Panel22: TPanel;
Panel23: TPanel;
Label5: TLabel;
Image5: TImage;
Panel24: TPanel;
Panel25: TPanel;
Image6: TImage;
Panel26: TPanel;
Edit1: TEdit;
FDConnection1: TFDConnection;
FDQuery1: TFDQuery;
DataSource1: TDataSource;
Label6: TLabel;
Label7: TLabel;
procedure Image6Click(Sender: TObject);
private
procedure OpenSplit;
{ Private declarations }
public
{ Public declarations }
end;
var
PDV: TPDV;
implementation
{$R *.dfm}
procedure TPDV.Image6Click(Sender: TObject);
begin
OpenSplit;
end;
procedure TPDV.OpenSplit;
begin
if SplitView1.Opened then
SplitView1.Close
else
SplitView1.Open;
end;
end.
|
unit uDMExportPO;
interface
uses
SysUtils, Classes, DBClient, DB, ADODB, Provider, uDMExportTextFile;
type
TDMExportPO = class(TDMExportTextFile)
quGetPOData: TADOQuery;
cdsGetPOData: TClientDataSet;
dspGetPOData: TDataSetProvider;
quGetPODataIDPO: TIntegerField;
quGetPODataPODate: TDateTimeField;
quGetPODataFreight: TBCDField;
quGetPODataCharges: TBCDField;
quGetPODataSubTotal: TBCDField;
quGetPODataEstArrival: TDateTimeField;
quGetPODataPayDays: TIntegerField;
quGetPODataOBS: TStringField;
quGetPODataCostPrice: TBCDField;
quGetPODataSalePrice: TBCDField;
quGetPODataDateEstimatedMov: TDateTimeField;
quGetPODataDateRealMov: TDateTimeField;
quGetPODataQty: TFloatField;
quGetPODataCaseQty: TFloatField;
quGetPODataCaseCost: TBCDField;
quGetPODataModel: TStringField;
quGetPODataDescription: TStringField;
quGetPODataVendorCode: TStringField;
quGetPODataBarcode: TStringField;
quGetPODataUserCode: TStringField;
quGetPODataStoreName: TStringField;
quGetPODataVendorAccount: TStringField;
quGetPODataQtyOrdered: TFloatField;
quGetPODataIDModel: TIntegerField;
ADOConnection: TADOConnection;
quGetPODataVendor: TStringField;
quGetPODataAddress: TStringField;
quGetPODataCity: TStringField;
quGetPODataZIP: TStringField;
quGetPODataIDVendor: TIntegerField;
private
FIDPO: Integer;
function SetVendorModelCode(IDModel, IDFornecedor: Integer): String;
public
property IDPO: Integer read FIDPO write FIDPO;
procedure ExportFile; override;
end;
implementation
{$R *.dfm}
{ TDMExportPO }
procedure TDMExportPO.ExportFile;
begin
inherited;
cdsGetPOData.Close;
try
try
quGetPOData.Connection := SQLConnection;
cdsGetPOData.Params.ParamByName('IDPO').Value := FIDPO;
cdsGetPOData.Open;
cdsGetPOData.First;
while not cdsGetPOData.Eof do
begin
cdsGetPOData.Edit;
cdsGetPOData.FieldByName('VendorCode').AsString := SetVendorModelCode(cdsGetPOData.FieldByName('IDModel').AsInteger ,
cdsGetPOData.FieldByName('IDVendor').AsInteger );
cdsGetPOData.Post;
cdsGetPOData.Next;
end;
TextFile.Data := cdsGetPOData.Data;
except
on E: Exception do
Log.Add(E.Message);
end;
finally
cdsGetPOData.Close;
end;
end;
function TDMExportPO.SetVendorModelCode(IDModel, IDFornecedor: Integer): String;
var
qryVendorModelCode: TADOQuery;
begin
qryVendorModelCode := TADOQuery.Create(self);
Try
qryVendorModelCode.Connection := SQLConnection;
qryVendorModelCode.SQL.Text := ' SELECT TOP 1 VendorCode ' +
' FROM VendorModelCode ' +
' WHERE IDModel = ' + InttoStr(IDModel) + ' and IDPessoa = ' + InttoStr(IDFornecedor);
qryVendorModelCode.Open;
Result := qryVendorModelCode.FieldByName('VendorCode').AsString;
finally
FreeAndNil(qryVendorModelCode);
end;
end;
end.
|
unit uActivationUtils;
interface
uses
System.SysUtils,
System.Classes,
System.SyncObjs,
System.Win.Registry,
Winapi.Windows,
Dmitry.Utils.System,
Dmitry.CRC32,
uRuntime,
uMemory,
uConstants,
uTranslate;
const
RegistrationUserName: string = 'UserName';
RegistrationCode: string = 'AcivationCode';
type
TActivationManager = class(TObject)
private
FSync: TCriticalSection;
FRegistrationLoaded: Boolean;
FIsDemoMode: Boolean;
FIsFullMode: Boolean;
constructor Create;
function GetIsDemoMode: Boolean;
function GetIsFullMode: Boolean;
function GetApplicationCode: string;
function GetActivationKey: string;
function GetActivationUserName: string;
procedure CheckActivationStatus;
function GetCanUseFreeActivation: Boolean;
public
class function Instance: TActivationManager;
destructor Destroy; override;
function SaveActivateKey(Name, Key: string; RegisterForAllUsers: Boolean): Boolean;
procedure CheckActivationCode(ApplicationCode, ActivationCode: string; out DemoMode: Boolean; out FullMode: Boolean);
function GenerateProgramCode(HardwareString: string): string;
function ReadActivationOption(OptionName: string): string;
property IsDemoMode: Boolean read GetIsDemoMode;
property IsFullMode: Boolean read GetIsFullMode;
property ApplicationCode: string read GetApplicationCode;
property ActivationKey: string read GetActivationKey;
property ActivationUserName: string read GetActivationUserName;
property CanUseFreeActivation: Boolean read GetCanUseFreeActivation;
end;
function GenerateActivationKey(ApplicationCode: string; FullVersion: Boolean): string;
implementation
var
ActivationManager : TActivationManager = nil;
function RegistrationRoot : string;
begin
Result := RegRoot + 'Activation';
end;
function FindVolumeSerial(const Drive : string) : string;
var
VolumeSerialNumber : DWORD;
MaximumComponentLength : DWORD;
FileSystemFlags : DWORD;
SerialNumber : string;
begin
Result:='';
GetVolumeInformation(
PChar(Drive),
nil,
0,
@VolumeSerialNumber,
MaximumComponentLength,
FileSystemFlags,
nil,
0);
SerialNumber :=
IntToHex(HiWord(VolumeSerialNumber), 4) +
' - ' +
IntToHex(LoWord(VolumeSerialNumber), 4) ;
Result := SerialNumber;
end; (*FindVolumeSerial*)
function GetProcStringID: string;
var
LpSystemInfo: TSystemInfo;
begin
GetSystemInfo(LpSystemInfo);
Result := IntToStr(LpSystemInfo.DwProcessorType) + IntToStr(LpSystemInfo.wProcessorLevel) + IntToStr(LpSystemInfo.wProcessorRevision);
end;
function GetSystemHardwareString: string;
begin
Result := FindVolumeSerial(Copy(ParamStr(0), 1, Length('c:\')));
Result := Result + GetProcStringID;
end;
function GenerateActivationKey(ApplicationCode: string; FullVersion: Boolean): string;
var
I: Integer;
SSS: string;
Ar: array [1 .. 16] of Integer;
begin
Result := '';
for I := 1 to 8 do
begin
SSS := IntToHex(Abs(Round(Cos(Ord(ApplicationCode[I]) + 100 * I + 0.34) * 16)), 8);
ApplicationCode[I] := SSS[8];
end;
for I := 1 to 16 do
Ar[I] := 0;
for I := 1 to 8 do
Ar[(I - 1) * 2 + 1] := HexCharToInt(ApplicationCode[I]);
if not FullVersion then
Ar[2] := 15 - Ar[1]
else
Ar[2] := (Ar[1] + Ar[3] * Ar[7] * Ar[15]) mod 15;
if not FullVersion and (Ar[2] = (Ar[1] + Ar[3] * Ar[7] * Ar[15]) mod 15) then
Ar[2] := (Ar[2] + 1) mod 15;
Ar[4] := Ar[2] * (Ar[3] + 1) * 123 mod 15;
Ar[6] := Round(Sqrt(Ar[5]) * 100) mod 15;
Ar[8] := (Ar[4] + Ar[6]) * 17 mod 15;
Randomize;
Ar[10] := Random(16);
Ar[12] := Ar[10] * Ar[10] * Ar[10] mod 15;
Ar[14] := Ar[7] * Ar[9] mod 15;
Ar[16] := 0;
for I := 1 to 15 do
Ar[16] := Ar[16] + Ar[I];
Ar[16] := Ar[16] mod 15;
for I := 1 to 16 do
Result := Result + IntToHexChar(Ar[I]);
end;
{ TActivationManager }
function TActivationManager.ReadActivationOption(OptionName: string): string;
var
Reg: TRegistry;
AppKey, ActCode: string;
IsDemo, IsFull: Boolean;
I : Integer;
const
ActivetionModes: array [0 .. 1] of NativeUInt = (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE);
begin
AppKey := ApplicationCode;
IsDemo := True;
IsFull := False;
Result := '';
for I := 0 to Length(ActivetionModes) - 1 do
begin
Reg := TRegistry.Create;
Reg.RootKey := ActivetionModes[I];
try
if Reg.OpenKey(RegistrationRoot, True) then
begin
if Reg.ValueExists(RegistrationCode) and Reg.ValueExists(OptionName) then
begin
ActCode := Reg.ReadString(RegistrationCode);
CheckActivationCode(AppKey, ActCode, IsDemo, IsFull);
if not IsDemo then
Result := Reg.ReadString(OptionName);
if (Result <> '') and IsFull then
Exit;
end;
end;
Reg.CloseKey;
finally
F(Reg);
end;
end;
end;
procedure TActivationManager.CheckActivationCode(ApplicationCode,
ActivationCode: string; out DemoMode, FullMode: Boolean);
var
I, Sum: Integer;
Str, ActCode, S: string;
begin
DemoMode := True;
FullMode := False;
if FolderView then
Exit;
S := ApplicationCode;
ActCode := ActivationCode;
if Length(ActCode) < 16 then
ActCode := '0000000000000000';
for I := 1 to 8 do
begin
Str := Inttohex(Abs(Round(Cos(Ord(S[I]) + 100 * I + 0.34) * 16)), 8);
if ActCode[(I - 1) * 2 + 1] <> Str[8] then
Exit;
end;
Sum := 0;
for I := 1 to 15 do
Sum := Sum + HexCharToInt(ActCode[I]);
if IntToHexChar(Sum mod 15) <> ActCode[16] then
Exit;
//2 checks passed, program works not in demo mode!
DemoMode := False;
//check full version
FullMode := HexCharToInt(ActCode[2]) = (HexCharToInt(ActCode[1]) + (HexCharToInt(ActCode[3]) * HexCharToInt(ActCode[7]) * HexCharToInt(ActCode[15]))) mod 15;
end;
procedure TActivationManager.CheckActivationStatus;
begin
if FRegistrationLoaded then
Exit;
CheckActivationCode(ApplicationCode, ActivationKey, FIsDemoMode, FIsFullMode);
FRegistrationLoaded := True;
end;
constructor TActivationManager.Create;
begin
FSync := TCriticalSection.Create;
FRegistrationLoaded := False;
end;
destructor TActivationManager.Destroy;
begin
F(FSync);
inherited;
end;
function TActivationManager.GenerateProgramCode(HardwareString: string): string;
var
S, Code: string;
N: Cardinal;
begin
S := HardwareString;
CalcStringCRC32(S, N);
//N := N xor $6357A303; // v2.3
N := N xor $6357A304; // v3.0,3.1
N := N xor $6357A305; // v4.0
N := N xor $ABDC412F; // v4.5
S := IntToHex(N, 8);
CalcStringCRC32(S, N);
//Check sum
//N := N xor $162C90CA; // v2.3
N := N xor $162C90CB; // v3.0,3.1
N := N xor $162C90CC; // v4.0
N := N xor $21DFAA43; // v4.5
Code := S + IntToHex(N, 8);
Result := Code;
end;
function TActivationManager.GetActivationKey: string;
begin
Result := ReadActivationOption(RegistrationCode);
end;
function TActivationManager.GetActivationUserName: string;
begin
Result := ReadActivationOption(RegistrationUserName);
end;
function TActivationManager.GetApplicationCode: string;
begin
Result := GenerateProgramCode(GetSystemHardwareString);
end;
function TActivationManager.GetCanUseFreeActivation: Boolean;
begin
Result := (TTranslateManager.Instance.Language = 'RU') or (TTranslateManager.Instance.Language = 'EN');
end;
function TActivationManager.GetIsDemoMode: Boolean;
begin
CheckActivationStatus;
Result := (FIsDemoMode and CanUseFreeActivation)
or (not IsFullMode and not CanUseFreeActivation);
Result := Result or FolderView;
end;
function TActivationManager.GetIsFullMode: Boolean;
begin
Result := FIsFullMode;
end;
class function TActivationManager.Instance: TActivationManager;
begin
if ActivationManager = nil then
ActivationManager := TActivationManager.Create;
Result := ActivationManager;
end;
function TActivationManager.SaveActivateKey(Name, Key: string;
RegisterForAllUsers: Boolean): Boolean;
var
Reg: TRegistry;
begin
Result := False;
Reg := TRegistry.Create;
if RegisterForAllUsers then
Reg.RootKey := HKEY_LOCAL_MACHINE
else
Reg.RootKey := HKEY_CURRENT_USER;
try
if Reg.OpenKey(RegistrationRoot, True) then
begin
Reg.WriteString(RegistrationCode, Key);
Reg.WriteString(RegistrationUserName, Name);
Reg.CloseKey;
FRegistrationLoaded := False;
Result := True;
end;
finally
F(Reg);
end;
end;
initialization
finalization
F(ActivationManager);
end.
|
{
@abstract Implements an API to abbreviated numbers.
If you have something like this
@code(str := Format('There are %d hits', [hitCount]);)
and you want to localize it and use abbreviated numbers convert code to
@longCode(#
resourcestring
SHits = 'There are %s hits';
...
str := Format(SHits, [TAbbreviatedNumber.FormatShort(hitCount)]);
Delphi XE or later required.
#)
}
unit NtNumber;
interface
uses
NtPattern;
const
{ @abstract Default amount of precision digits. }
DEFAULT_PRECISION = 2;
type
{ @abstract Enumeration that specifies the format of the abbreviation type. }
TAbbreviatedNumberForm =
(
anLong, //< Long string form such as "1 thousand" and "10 millions"
anShort, //< Short string form such as "1K" or "10M"
anCurrency //< Currency string form such as "$1K" and "$10M"
);
{ @abstract Record that stores one abbreviation rule.
Abbreviation rules use CLDR syntax where there is a set of rules for each language
and abbreviation type. }
TAbbreviationRule = record
{ Minimum value where this rule is used. }
Range: UInt64;
{ Plural form of the rule. }
Plural: TPlural;
{ The abbreviation rule value. }
Value: String;
end;
{ @abstract Type that stores all abbreviation rules. }
TAbbreviationRules = array of TAbbreviationRule;
{ @abstract Static class that contains abbreviated number routines. }
TAbbreviatedNumber = class
public
{ Check of the value can be abbreviated.
@param form Abbreviation type.
@param value Number value to be abbreviated.
@return True if the value can be abbreviated. }
class function CanBeAbbreviated(
form: TAbbreviatedNumberForm;
value: Double): Boolean;
{ Converts a number to its abbreviated form.
@param form Abbreviation type.
@param value Number value to be abbreviated.
@param precision Number of digits that are used to express a value.
@return The formatted string. }
class function Format(
form: TAbbreviatedNumberForm;
value: Double;
precision: Integer = DEFAULT_PRECISION): String;
{ Converts a number to its abbreviated long form.
@param value Number value to be abbreviated.
@param precision Number of digits that are used to express a value.
@return True if the value can be abbreviated. }
class function FormatLong(
value: Double;
precision: Integer = DEFAULT_PRECISION): String;
{ Converts a number to its abbreviated short form.
@param value Number value to be abbreviated.
@param precision Number of digits that are used to express a value.
@return True if the value can be abbreviated. }
class function FormatShort(
value: Double;
precision: Integer = DEFAULT_PRECISION): String;
{ Converts a number to its abbreviated currency form.
@param value Number value to be abbreviated.
@param precision Number of digits that are used to express a value.
@return True if the value can be abbreviated. }
class function FormatCurrency(
value: Double;
precision: Integer = DEFAULT_PRECISION): String;
{ Register formatting functions for a language.
@param id IETF language tag of the language/locale.
@param longRules Rules to abbreviate a number to a long form.
@param shortRules Rules to abbreviate a number to a short form.
@param currentyRules Rules to abbreviate a number to a currency form. }
class procedure Register(
const id: String;
longRules, shortRules, currencyRules: array of TAbbreviationRule);
end;
implementation
uses
SysUtils,
Math,
Generics.Collections,
Generics.Defaults,
NtBase;
type
TData = class
Long: TAbbreviationRules;
Short: TAbbreviationRules;
Currency: TAbbreviationRules;
end;
var
FDatas: TDictionary<String, TData>;
function GetData: TData;
var
id, language, script, country, variant: String;
begin
id := TNtBase.GetActiveLocale;
if not FDatas.ContainsKey(id) then
begin
TNtBase.ParseLocaleId(id, language, script, country, variant);
id := language;
if not FDatas.ContainsKey(id) then
id := '';
end;
Result := FDatas.Items[id];
end;
function DoFormat( //FI:C103
value: Double;
form: TAbbreviatedNumberForm;
precision: Integer;
rules: TAbbreviationRules): String;
function GetValuePrecision(value: Double): Integer;
var
valueRange: UInt64;
begin
Result := 0;
valueRange := 1;
while valueRange <= value do
begin
valueRange := 10*valueRange;
Inc(Result);
end;
end;
procedure DeleteTrailingZeros(var value: String);
var
i: Integer;
begin
if Pos(FormatSettings.DecimalSeparator, value) = 0 then
Exit;
i := Length(value);
while (i > 0) and not ((value[i] = FormatSettings.DecimalSeparator) or ((value[i] >= '0') and (value[i] <= '9'))) do
Dec(i);
while (i > 0) and (value[i] = '0') do
begin
Delete(value, i, 1);
Dec(i);
end;
if (i > 0) and (value[i] = FormatSettings.DecimalSeparator) then
Delete(value, i, 1);
end;
function GetStr(value: Double): String;
var
valuePrecision: Integer;
begin
valuePrecision := GetValuePrecision(value);
value := RoundTo(value, valuePrecision - precision);
Result := FloatToStrF(value, ffFixed, 10, Max(0, precision - valuePrecision));
DeleteTrailingZeros(Result);
end;
function GetNotAbbreviatedStr(value: Double): String;
var
valuePrecision: Integer;
begin
if form = anCurrency then
begin
valuePrecision := GetValuePrecision(value);
value := RoundTo(value, valuePrecision - precision);
if value = Round(value) then
Result := CurrToStrF(value, ffCurrency, 0)
else
Result := CurrToStrF(value, ffCurrency, Max(0, precision - valuePrecision));
DeleteTrailingZeros(Result);
end
else
Result := GetStr(value);
end;
function Find(range: Int64; plural: TPlural; var rule: TAbbreviationRule): Boolean;
var
thisRule: TAbbreviationRule;
begin
for thisRule in rules do
begin
Result := (thisRule.Range = range) and (thisRule.Plural = plural);
if Result then
begin
rule := thisRule;
Exit;
end;
end;
Result := False;
end;
var
p: Integer;
count, range: Int64;
displayValue: Double;
str: String;
rule, newRule: TAbbreviationRule;
proc: TPluralProc;
plural: TPlural;
begin //FI:C101
for rule in rules do
begin
if rule.Range <= value then
begin
range := rule.Range;
Result := rule.Value;
p := Pos('0', Result);
Delete(Result, p, 1);
while (Result <> '') and (Result[p] = '0') do
begin
Delete(Result, p, 1);
range := range div 10;
end;
if Result <> '' then
begin
str := GetStr(value/range);
displayValue := StrToFloat(str);
end
else
begin
str := GetNotAbbreviatedStr(value);
displayValue := value;
end;
count := Round(displayValue);
if displayValue = count then
begin
proc := TMultiPattern.GetProc();
plural := proc(count, count, 0, 0, 0, 0);
if plural <> rule.Plural then
begin
// Wrong plural form. Find the correct one and get abbreviation again
if Find(rule.Range, plural, newRule) then
begin
range := newRule.Range;
Result := newRule.Value;
p := Pos('0', Result);
Delete(Result, p, 1);
while (Result <> '') and (Result[p] = '0') do
begin
Delete(Result, p, 1);
range := range div 10;
end;
str := GetStr(value/range);
end;
end;
end;
Result := Copy(Result, 1, p - 1) + str + Copy(Result, p, Length(Result));
p := Pos('¤', Result);
if p > 0 then
Result := Copy(Result, 1, p - 1) + FormatSettings.CurrencyString + Copy(Result, p + 1, Length(Result));
Exit;
end;
end;
Result := GetNotAbbreviatedStr(value);
end;
class function TAbbreviatedNumber.CanBeAbbreviated(form: TAbbreviatedNumberForm; value: Double): Boolean;
var
rule: TAbbreviationRule;
rules: TAbbreviationRules;
begin
case form of
anLong: rules := GetData.Long;
anShort: rules := GetData.Short;
anCurrency: rules := GetData.Currency;
end;
for rule in rules do
begin
if rule.Range <= value then
begin
Result := True;
Exit;
end;
end;
Result := False;
end;
class function TAbbreviatedNumber.FormatShort(
value: Double;
precision: Integer): String;
begin
Result := DoFormat(value, anShort, precision, GetData.Short);
end;
class function TAbbreviatedNumber.FormatLong(
value: Double;
precision: Integer): String;
begin
Result := DoFormat(value, anLong, precision, GetData.Long);
end;
class function TAbbreviatedNumber.FormatCurrency(
value: Double;
precision: Integer): String;
begin
Result := DoFormat(value, anCurrency, precision, GetData.Currency);
end;
class function TAbbreviatedNumber.Format(
form: TAbbreviatedNumberForm;
value: Double;
precision: Integer): String;
begin
case form of
anLong: Result := FormatLong(value, precision);
anShort: Result := FormatShort(value, precision);
anCurrency: Result := FormatCurrency(value, precision);
end;
end;
function CompareRules(const left, right: TAbbreviationRule): Integer;
begin
if left.Range = right.Range then
Result := TComparer<TPlural>.Default.Compare(left.Plural, right.Plural)
else
Result := TComparer<Int64>.Default.Compare(left.Range, right.Range);
end;
function ReverseCompareRules(const left, right: TAbbreviationRule): Integer;
begin
Result := -CompareRules(left, right);
end;
class procedure TAbbreviatedNumber.Register(
const id: String;
longRules, shortRules, currencyRules: array of TAbbreviationRule);
function GetArray(value: array of TAbbreviationRule): TAbbreviationRules;
begin
SetLength(Result, Length(value));
Move(value[Low(value)], Result[Low(Result)], SizeOf(value));
TArray.Sort<TAbbreviationRule>(Result, TDelegatedComparer<TAbbreviationRule>.Construct(ReverseCompareRules));
end;
var
data: TData;
begin
if not FDatas.TryGetValue(id, data) then
begin
data := TData.Create;
FDatas.Add(id, data);
end;
data.Long := GetArray(longRules);
data.Short := GetArray(shortRules);
data.Currency := GetArray(currencyRules);
end;
const
EMPTY: array[0..0] of TAbbreviationRule =
(
(Range: 0; Plural: pfOther; Value: '')
);
initialization
FDatas := TDictionary<String, TData>.Create;
TAbbreviatedNumber.Register('', EMPTY, EMPTY, EMPTY);
end.
|
{ NAME: Jordan Millett
CLASS: Comp Sci 1
DATE: 10/24/2016
PURPOSE: Create a temperature conversion program.
INPUT: fahr temperature (integer)
OUTPUT: cel temperature (integer)
Note: uses procedures.
Stage 2: Display a table of temperatures
1st column - fahr temps
2nd column - cel temps
F temps - 20 to 210 by 10's
C temps - corrisponding temps
easily adjustable
Headings over the columns
done in a procedure
may call other procedures
Above & Beyond
Menu based program
Other temp scales
Convert in other directions
color coding
History of Celsius and Fahrenheit
Convert multiple temps
}
Program FtoC;
uses
crt;
Procedure getInt(ask:string; var num : integer);
var
numStr : string;
code : integer;
begin
repeat
write(ask);
readln(numstr);
val(numStr, num, code);
if code <> 0 then
begin
writeln('You can only enter numbers');
readkey;
clrscr;
end;
until (code = 0);
end;
Procedure getmenu(ask:string; var num : integer);
var
numStr : string;
code : integer;
begin
repeat
write(ask);
readln(numstr);
val(numStr, num, code);
if code <> 0 then
begin
writeln('You can only enter numbers');
end;
until (code = 0);
end;
Procedure convert(var fahr:integer; var cel:real);
begin {convert}
cel:=(fahr-32)*5/9;
end; {convert}
Procedure table;
var
fahr,count,header:integer;
cel:real;
begin {table}
header:=1;
count:=20;
for count:=20 to 210 do
begin
if (header=1) then
begin
write('Fahrenheit':19);
writeln('Celsius':17);
header:=2;
end;
fahr:=count;
convert(fahr,cel);
write(count:15);
writeln(cel:20:2);
count:=count+9;
end;
end; {table}
Procedure fahrtocel(var fahr:integer; var cel:real);
begin {fahrtocel}
getInt('Enter a fahr temperature: ',fahr);
convert(fahr,cel);
writeln(fahr,' degrees(F) = ',cel:0:2,' degrees(C)');
readkey;
clrscr;
end; {fahrtocel}
Procedure Menu();
begin
writeln(' __ __ _ __ __ ':80);
writeln(' | \/ | (_) | \/ | ':80);
writeln(' | \ / | __ _ _ _ __ | \ / | ___ _ __ _ _ ':80);
writeln(' | |\/| |/ _` | | _ \ | |\/| |/ _ \ _ \| | | |':80);
writeln(' | | | | (_| | | | | | | | | | __/ | | | |_| |':80);
writeln(' |_| |_|\__,_|_|_| |_| |_| |_|\___|_| |_|\__,_|':80);
end;
Procedure fahrinfo();
begin
Writeln('Fahrenheit was invented in');
readkey;
end;
var
fahr,count,menuchoice:integer;
cel:real;
begin {main}
writeln('Fahrenheit to Celsius':70);
writeln;
writeln;
writeln('This program will help you with converting fahrenheit to celsuise and vice versa':100);
readkey;
repeat
clrscr;
Menu();
writeln;
writeln;
Writeln('1.Temperature Table':60);
writeln;
Writeln('2.Fahr to Cel':54);
writeln;
Writeln('3.Information about Fahrenheit':71);
writeln;
Writeln('4.Exit':47);
getmenu('',menuchoice);
clrscr;
if (menuchoice = 2) then
fahrtocel(fahr,cel)
else if (menuchoice = 3) then
fahrinfo()
else if (menuchoice = 1) then
begin
table();
readkey;
end;
until(menuchoice = 4);
end. {main}
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Repository.Manager;
interface
uses
System.Generics.Defaults,
Spring.Collections,
VSoft.Awaitable,
DPM.Core.Types,
DPM.Core.Dependency.Version,
DPM.Core.Logging,
DPM.Core.Options.Search,
DPM.Core.Options.Push,
DPM.Core.Configuration.Interfaces,
DPM.Core.Package.Interfaces,
DPM.Core.Repository.Interfaces;
type
TPackageRepositoryManager = class(TInterfacedObject, IPackageRepositoryManager)
private
FLogger : ILogger;
FConfiguration : IConfiguration;
FRepositories : IList<IPackageRepository>;
FRepoFactory : IPackageRepositoryFactory;
protected
function Initialize(const configuration : IConfiguration) : boolean;
function HasSources: Boolean;
// function InternalGetLatestVersions(const cancellationToken : ICancellationToken; const installedPackages : IList<IPackageId>; const platform : TDPMPlatform; const compilerVersion : TCompilerVersion) : IDictionary<string, IPackageLatestVersionInfo>;
function GetRepositories : IList<IPackageRepository>;
function GetRepositoryByName(const value : string) : IPackageRepository;
function UpdateRepositories : boolean;
//UI specific stuff
//TODO : Implement skip/take!
function GetPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResult;
function GetInstalledPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const installedPackages : IList<IPackageId>) : IList<IPackageSearchResultItem>;
//
function GetPackageMetaData(const cancellationToken : ICancellationToken; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResultItem;
function FindLatestVersion(const cancellationToken : ICancellationToken; const id : string; const compilerVersion : TCompilerVersion; const version : TPackageVersion; const platform : TDPMPlatform; const includePrerelease : boolean; const sources : string) : IPackageIdentity;
function DownloadPackage(const cancellationToken : ICancellationToken; const packageIdentity : IPackageIdentity; const localFolder : string; var fileName : string) : boolean;
function GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo;
function GetPackageIcon(const cancelToken : ICancellationToken; const source : string; const packageId : string; const packageVersion : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon;
function GetPackageVersions(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const packageId : string; const includePrerelease : boolean) : IList<TPackageVersion>; overload;
function GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform;
const packageId : string; const versionRange : TVersionRange; const includePrerelease : boolean ) : IList<IPackageInfo>;
//commands
function Push(const cancellationToken : ICancellationToken; const pushOptions : TPushOptions) : Boolean;
function List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageListItem>;
public
constructor Create(const logger : ILogger; const repoFactory : IPackageRepositoryFactory);
end;
implementation
uses
System.Classes,
System.SysUtils,
System.StrUtils,
Spring.Collections.Extensions,
VSoft.URI,
DPM.Core.Constants,
DPM.Core.Utils.System,
DPM.Core.Package.SearchResults;
{ TRespositoryManager }
constructor TPackageRepositoryManager.Create(const logger : ILogger; const repoFactory : IPackageRepositoryFactory);
begin
inherited Create;
FLogger := logger;
FRepoFactory := repoFactory;
FRepositories := TCollections.CreateList<IPackageRepository>;
end;
function TPackageRepositoryManager.DownloadPackage(const cancellationToken : ICancellationToken; const packageIdentity : IPackageIdentity; const localFolder : string; var fileName : string) : boolean;
var
repo : IPackageRepository;
begin
FLogger.Debug('TPackageRepositoryManager.DownloadPackage');
result := false;
if not UpdateRepositories then
begin
FLogger.Error('Unabled to get package versions, error loading repositories');
exit;
end;
if packageIdentity.SourceName <> '' then
begin
repo := GetRepositoryByName(packageIdentity.SourceName);
if repo = nil then
begin
FLogger.Error('Unabled to find repository for source [' + packageIdentity.SourceName + ']');
exit;
end;
//FLogger.Information('Downloading package [' + packageIdentity.ToString + '] from [' + repo.Name + ']');
result := repo.DownloadPackage(cancellationToken, packageIdentity, localFolder, fileName);
end
else
begin
for repo in FRepositories do
begin
if not repo.Enabled then
continue;
if cancellationToken.IsCancelled then
exit;
result := repo.DownloadPackage(cancellationToken, packageIdentity, localFolder, fileName) or result;
if result then
exit;
end;
end;
end;
function TPackageRepositoryManager.FindLatestVersion(const cancellationToken: ICancellationToken; const id: string; const compilerVersion: TCompilerVersion; const version: TPackageVersion; const platform: TDPMPlatform; const includePrerelease : boolean; const sources : string): IPackageIdentity;
var
repo : IPackageRepository;
sourcesList : TStringList;
// i : integer;
packages : IList<IPackageIdentity>;
package : IPackageIdentity;
currentPackage : IPackageIdentity;
begin
Assert(FConfiguration <> nil);
if not UpdateRepositories then
begin
FLogger.Error('Unabled to search, error loading repositories');
exit;
end;
if sources <> '' then
begin
sourcesList := TStringList.Create;
sourcesList.Delimiter := ',';
sourcesList.DelimitedText := sources;
end
else
sourcesList := nil;
packages := TCollections.CreateList<IPackageIdentity>;
try
for repo in FRepositories do
begin
if cancellationToken.IsCancelled then
exit;
if not repo.Enabled then
continue;
if sourcesList <> nil then
begin
if sourcesList.IndexOf(repo.Name) = -1 then
continue;
end;
package := repo.FindLatestVersion(cancellationToken, id, compilerVersion, version, platform, includePrerelease);
if cancellationToken.IsCancelled then
exit;
if package <> nil then
begin
//if version is empty then we want the latest version - so that's what we have, we're done.
if version.IsEmpty then
exit(package);
if currentPackage <> nil then
begin
if package.Version > currentPackage.Version then
currentPackage := package;
end
else
currentPackage := package;
end;
result := currentPackage;
end;
finally
if sourcesList <> nil then
sourcesList.Free;
end;
end;
function TPackageRepositoryManager.GetInstalledPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const installedPackages : IList<IPackageId>) : IList<IPackageSearchResultItem>;
var
packageResults : IPackageSearchResult;
packages : IDictionary<string, IPackageSearchResultItem>;
package : IPackageSearchResultItem;
platform : TDPMPlatform;
repo : IPackageRepository;
i : integer;
id : string;
begin
Assert(FConfiguration <> nil);
Assert(installedPackages <> nil);
result := TCollections.CreateList<IPackageSearchResultItem>;
//nothing to do so justr return empty list.
if not installedPackages.Any then
exit;
if not UpdateRepositories then
begin
FLogger.Error('Unabled to search, error loading repositories');
exit;
end;
if installedPackages.Count = 0 then
exit;
packages := TCollections.CreateDictionary<string, IPackageSearchResultItem>;
//always going to be all the same platform
platform := installedPackages[0].Platform;
//loop through enabled repo and get the feed.. then combine to get latest versions
for repo in FRepositories do
begin
if not repo.Enabled then
continue;
if cancelToken.IsCancelled then
exit;
packageResults := repo.GetPackageFeedByIds(cancelToken, installedPackages, options.CompilerVersion, platform );
for i := 0 to packageResults.Results.Count -1 do
begin
if cancelToken.IsCancelled then
exit;
id := LowerCase(packageResults.Results[i].Id);
if packages.ContainsKey(id) then
begin
package := packages[id]; //don't use extract!
//if we already have this package from another repo then compare versions
if packageResults.Results[i].LatestVersion > package.LatestVersion then
package.LatestVersion := packageResults.Results[i].LatestVersion;
if packageResults.Results[i].LatestStableVersion > package.LatestStableVersion then
package.LatestStableVersion := packageResults.Results[i].LatestStableVersion;
end
else
packages[id] := packageResults.Results[i];
end;
end;
result := TCollections.CreateList<IPackageSearchResultItem>;
result.AddRange(packages.Values);
result.Sort(
function(const left, right : IPackageSearchResultItem) : integer
begin
result := CompareText(left.Id, right.id);
end);
end;
function TPackageRepositoryManager.GetPackageFeed(const cancelToken : ICancellationToken; const options : TSearchOptions; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageSearchResult;
var
repo : IPackageRepository;
sources : TStringList;
searchResult : IPackageSearchResult;
allResults : IList<IPackageSearchResultItem>;
distinctResults : IEnumerable<IPackageSearchResultItem>;
comparer : IEqualityComparer<IPackageSearchResultItem>;
begin
FLogger.Debug('TPackageRepositoryManager.GetPackageFeed');
Assert(FConfiguration <> nil);
result := TDPMPackageSearchResult.Create(options.Skip, 0);
if not UpdateRepositories then
begin
FLogger.Error('Unabled to search, error loading repositories');
exit;
end;
if options.Sources <> '' then
begin
sources := TStringList.Create;
sources.Delimiter := ',';
sources.DelimitedText := options.Sources;
end
else
sources := nil;
allResults := TCollections.CreateList<IPackageSearchResultItem>;
try
for repo in FRepositories do
begin
if cancelToken.IsCancelled then
exit;
if not repo.Enabled then
continue;
if sources <> nil then
begin
if sources.IndexOf(repo.Name) = -1 then
continue;
end;
searchResult := repo.GetPackageFeed(cancelToken, options, compilerVersion, platform);
allResults.AddRange(searchResult.Results);
end;
finally
if sources <> nil then
sources.Free;
end;
comparer := TPackageSearchResultItemComparer.Create;
distinctResults := TDistinctIterator<IPackageSearchResultItem>.Create(allResults, comparer);
if options.Take > 0 then
distinctResults := distinctResults.Take(options.Take);
result.Results.AddRange(distinctResults);
result.TotalCount := result.Results.Count;
result.Results.Sort(
function(const Left, Right : IPackageSearchResultItem) : integer
begin
result := CompareText(Left.Id, Right.Id);
end);
end;
function TPackageRepositoryManager.GetPackageIcon(const cancelToken : ICancellationToken; const source, packageId, packageVersion : string;
const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : IPackageIcon;
var
repo : IPackageRepository;
begin
FLogger.Debug('TPackageRepositoryManager.GetPackageIcon');
Assert(FConfiguration <> nil);
result := nil;
if not UpdateRepositories then
begin
FLogger.Error('Unabled to search, error loading repositories');
exit;
end;
repo := GetRepositoryByName(source);
if repo = nil then
begin
FLogger.Error('Unabled to find repository for source [' + source + ']');
exit;
end;
if cancelToken.IsCancelled then
exit;
result := repo.GetPackageIcon(cancelToken, packageId, packageVersion, compilerVersion, platform);
end;
function TPackageRepositoryManager.GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo;
var
repo : IPackageRepository;
begin
FLogger.Debug('TPackageRepositoryManager.GetPackageInfo');
result := nil;
Assert(FConfiguration <> nil);
if not UpdateRepositories then
begin
FLogger.Error('Unabled to search, error loading repositories');
exit;
end;
for repo in FRepositories do
begin
if cancellationToken.IsCancelled then
exit;
if not repo.Enabled then
continue;
result := repo.GetPackageInfo(cancellationToken, packageId);
if result <> nil then
exit;
if cancellationToken.IsCancelled then
exit;
end;
end;
function TPackageRepositoryManager.GetPackageMetaData(const cancellationToken: ICancellationToken; const packageId, packageVersion: string; const compilerVersion: TCompilerVersion; const platform: TDPMPlatform): IPackageSearchResultItem;
var
repo : IPackageRepository;
begin
FLogger.Debug('TPackageRepositoryManager.GetPackageMetaData');
result := nil;
Assert(FConfiguration <> nil);
if compilerVersion = TCompilerVersion.UnknownVersion then
begin
FLogger.Error('Unabled to search, no compiler version specified');
exit;
end;
if platform = TDPMPlatform.UnknownPlatform then
begin
FLogger.Error('Unabled to search, no platform specified');
exit;
end;
if not UpdateRepositories then
begin
FLogger.Error('Unabled to search, error loading repositories');
exit;
end;
for repo in FRepositories do
begin
if cancellationToken.IsCancelled then
exit;
if not repo.Enabled then
continue;
result := repo.GetPackageMetaData(cancellationToken, packageId, packageVersion, compilerVersion, platform);
if result <> nil then
exit;
end;
end;
function TPackageRepositoryManager.GetPackageVersions(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform;
const packageId : string; const includePrerelease : boolean) : IList<TPackageVersion>;
var
repo : IPackageRepository;
searchResult : IList<TPackageVersion>;
unfilteredResults : IList<TPackageVersion>;
distinctResults : IEnumerable<TPackageVersion>;
comparer : IEqualityComparer<TPackageVersion>;
begin
FLogger.Debug('TPackageRepositoryManager.GetPackageVersions');
result := TCollections.CreateList<TPackageVersion>;
Assert(FConfiguration <> nil);
if not UpdateRepositories then
begin
FLogger.Error('Unabled to get package versions, error loading repositories');
exit;
end;
unfilteredResults := TCollections.CreateList<TPackageVersion>;
if compilerVersion = TCompilerVersion.UnknownVersion then
begin
FLogger.Error('Unabled to search, no compiler version specified');
exit;
end;
if platform = TDPMPlatform.UnknownPlatform then
begin
FLogger.Error('Unabled to search, no platform specified');
exit;
end;
for repo in FRepositories do
begin
if cancellationToken.IsCancelled then
exit;
if not repo.Enabled then
continue;
searchResult := repo.GetPackageVersions(cancellationToken, packageId, compilerVersion, platform, includePrerelease);
unfilteredResults.AddRange(searchResult);
end;
comparer := TPackageVersionComparer.Create;
//dedupe
distinctResults := TDistinctIterator<TPackageVersion>.Create(unfilteredResults, comparer);
result.AddRange(distinctResults);
//todo :// which order is this? want descending.
result.Sort(function(const Left, Right : TPackageVersion) : Integer
begin
result := right.CompareTo(left);
end);
end;
//function TPackageRepositoryManager.InternalGetLatestVersions(const cancellationToken : ICancellationToken; const installedPackages : IList<IPackageId>; const platform : TDPMPlatform; const compilerVersion : TCompilerVersion) : IDictionary<string, IPackageLatestVersionInfo>;
//var
// repo : IPackageRepository;
// repoResult : IDictionary<string, IPackageLatestVersionInfo>;
// i: Integer;
// repoVersion : IPackageLatestVersionInfo;
// resultVersion : IPackageLatestVersionInfo;
//begin
// result := TCollections.CreateDictionary<string, IPackageLatestVersionInfo>;
//
// for repo in FRepositories do
// begin
// if cancellationToken.IsCancelled then
// exit;
// if not repo.Enabled then
// continue;
//
// repoResult := repo.GetPackageLatestVersions(cancellationToken, installedPackages, platform, compilerVersion);
// if cancellationToken.IsCancelled then
// exit;
//
// if repoResult.Any then
// begin
// for i := 0 to installedPackages.Count -1 do
// begin
// if repoResult.TryGetValue(installedPackages.Items[i].Id, repoVersion) then
// begin
// if result.TryExtract(installedPackages.Items[i].Id, resultVersion) then
// begin
// if repoVersion.LatestVersion > resultVersion.LatestVersion then
// resultVersion.LatestVersion := repoVersion.LatestVersion;
// if repoVersion.LatestStableVersion > resultVersion.LatestStableVersion then
// resultVersion.LatestStableVersion := repoVersion.LatestStableVersion;
// end
// else
// result[installedPackages.Items[i].Id] := repoVersion
// end;
// end;
// end;
// end;
//
//end;
function TPackageRepositoryManager.GetPackageVersionsWithDependencies(const cancellationToken : ICancellationToken; const compilerVersion : TCompilerVersion;
const platform : TDPMPlatform; const packageId : string; const versionRange : TVersionRange;
const includePrerelease : boolean) : IList<IPackageInfo>;
var
repo : IPackageRepository;
searchResult : IList<IPackageInfo>;
unfilteredResults : IList<IPackageInfo>;
distinctResults : IEnumerable<IPackageInfo>;
comparer : IEqualityComparer<IPackageInfo>;
begin
FLogger.Debug('TPackageRepositoryManager.GetPackageVersionsWithDependencies');
result := TCollections.CreateList<IPackageInfo>;
unfilteredResults := TCollections.CreateList<IPackageInfo>;
Assert(FConfiguration <> nil);
if compilerVersion = TCompilerVersion.UnknownVersion then
begin
FLogger.Error('Unabled to search, no compiler version specified');
exit;
end;
if platform = TDPMPlatform.UnknownPlatform then
begin
FLogger.Error('Unabled to search, no platform specified');
exit;
end;
if not UpdateRepositories then
begin
FLogger.Error('Unabled to get package versions, error loading repositories');
exit;
end;
for repo in FRepositories do
begin
if cancellationToken.IsCancelled then
exit;
if not repo.Enabled then
continue;
searchResult := repo.GetPackageVersionsWithDependencies(cancellationToken, packageId, compilerVersion, platform, versionRange, includePrerelease);
unfilteredResults.AddRange(searchResult);
end;
comparer := TPackageInfoComparer.Create;
//dedupe
distinctResults := TDistinctIterator<IPackageInfo>.Create(unfilteredResults, comparer);
result.AddRange(distinctResults);
//todo :// which order is this? want descending.
result.Sort(function(const Left, Right : IPackageInfo) : Integer
begin
result := right.Version.CompareTo(left.Version); ;
end);
end;
function TPackageRepositoryManager.GetRepositories : IList<IPackageRepository>;
begin
result := FRepositories;
end;
function TPackageRepositoryManager.GetRepositoryByName(const value : string) : IPackageRepository;
begin
result := FRepositories.FirstOrDefault(function(const repo : IPackageRepository) : boolean
begin
result := SameText(value, repo.Name);
end);
end;
function TPackageRepositoryManager.HasSources: Boolean;
begin
result := FRepositories.Any;
end;
function TPackageRepositoryManager.Initialize(const configuration : IConfiguration) : boolean;
begin
FConfiguration := configuration;
result := UpdateRepositories;
end;
function TPackageRepositoryManager.List(const cancellationToken : ICancellationToken; const options : TSearchOptions) : IList<IPackageListItem>;
var
repo : IPackageRepository;
searchResult : IList<IPackageListItem>;
unfilteredResults : IList<IPackageListItem>;
sortFunc : TComparison<IPackageListItem>;
sources : TStringList;
item, currentItem : IPackageListItem;
i : integer;
begin
Assert(FConfiguration <> nil);
result := TCollections.CreateList<IPackageListItem>;
if not UpdateRepositories then
begin
FLogger.Error('Unabled to search, error loading repositories');
exit;
end;
if options.Sources <> '' then
begin
sources := TStringList.Create;
sources.Delimiter := ',';
sources.DelimitedText := options.Sources;
end
else
sources := nil;
unfilteredResults := TCollections.CreateList<IPackageListItem>;
//create the list here as if there are no repos it will be nil.
searchResult := TCollections.CreateList<IPackageListItem>;
try
for repo in FRepositories do
begin
if cancellationToken.IsCancelled then
exit;
if not repo.Enabled then
continue;
if sources <> nil then
begin
if sources.IndexOf(repo.Name) = -1 then
continue;
end;
searchResult := repo.List(cancellationToken, options);
unfilteredResults.AddRange(searchResult);
if cancellationToken.IsCancelled then
exit;
end;
finally
if sources <> nil then
sources.Free;
end;
if cancellationToken.IsCancelled then
exit;
sortFunc := function(const Left, Right : IPackageListItem) : Integer
begin
result := CompareText(left.Id, right.Id);
if result = 0 then
begin
result := Ord(left.CompilerVersion) - Ord(right.CompilerVersion);
if result = 0 then
begin
result := right.Version.CompareTo(left.Version);
if result = 0 then
result := CompareText(left.Platforms, right.Platforms);
end;
end;
end;
unfilteredResults.Sort(sortFunc);
searchResult.Clear;
//we need to dedupe here.
currentItem := nil;
for i := 0 to unfilteredResults.Count -1 do
begin
item := unfilteredResults[i];
if (currentItem <> nil) then
begin
if currentItem.IsSamePackageVersion(item) then
currentItem := currentItem.MergeWith(item)
else if currentItem.IsSamePackageId(item) then
begin
//not the same version but same compiler/packageid, so take highest version
if item.Version > currentItem.Version then
currentItem := item;
end
else
begin //different package or compiler verison.
searchResult.Add(currentItem);
currentItem := item;
end;
end
else
currentItem := item;
end;
if currentItem <> nil then
searchResult.Add(currentItem);
//Sort by id, version, platform.
searchResult.Sort(sortFunc);
result.AddRange(searchResult);
end;
function TPackageRepositoryManager.Push(const cancellationToken: ICancellationToken; const pushOptions: TPushOptions): Boolean;
var
repo : IPackageRepository;
begin
Assert(FConfiguration <> nil);
result := false;
if cancellationToken.IsCancelled then
exit;
if not UpdateRepositories then
begin
FLogger.Error('Unabled to push, error loading source repositories');
exit;
end;
repo := FRepositories.Where(
function(const repository : IPackageRepository) : Boolean
begin
result := SameText(pushOptions.Source, repository.Name);
end).FirstOrDefault;
if repo = nil then
begin
FLogger.Error('Unknown Source : ' + pushOptions.Source);
exit;
end;
if not repo.Enabled then
begin
FLogger.Error('Source not enabled : ' + pushOptions.Source);
exit;
end;
result := repo.Push(cancellationToken, pushOptions);
end;
function TPackageRepositoryManager.UpdateRepositories : boolean;
var
uri : IUri;
error : string;
source : ISourceConfig;
repo : IPackageRepository;
i : integer;
begin
//FLogger.Debug('TPackageRepositoryManager.UpdateRepositories');
result := false;
//update and remove
for i := FRepositories.Count -1 downto 0 do
begin
repo := FRepositories[i];
source := FConfiguration.GetSourceByName(repo.Name);
if source <> nil then
repo.Configure(source)
else
FRepositories.Remove(repo);
end;
//add missing repos.
for source in FConfiguration.Sources do
begin
repo := GetRepositoryByName(source.Name);
if repo = nil then
begin
if not TUriFactory.TryParseWithError(source.Source, false, uri, error) then
begin
FLogger.Error('Invalid source uri : ' + source.Source);
exit;
end;
if not MatchText(uri.Scheme, ['file', 'http', 'https']) then
begin
FLogger.Error('Invalid source uri scheme : ' + uri.Scheme);
exit;
end;
repo := FRepoFactory.CreateRepository(source.SourceType);
repo.Configure(source);
FRepositories.Add(repo);
end;
end;
result := true;
end;
end.
|
Unit Super_Bloque;
{ * Super_Bloque : *
* *
* Esta unidad se dedica al mantenimiento de los superbloques y al montado *
* de los sistema de archivo *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* 25 / 06 / 2006 : Primera Version del VFS *
* *
* 04 / 03 / 2005 : Segunda Version *
* *
* 23 - 02 - 2004 : Primera Version *
* *
***************************************************************************
}
interface
{$I ../include/toro/procesos.inc}
{$I ../include/toro/buffer.inc}
{$I ../include/toro/mount.inc}
{$I ../include/head/buffer.h}
{$I ../include/head/asm.h}
{$I ../include/head/inodes.h}
{$I ../include/head/dcache.h}
{$I ../include/head/open.h}
{$I ../include/head/procesos.h}
{$I ../include/head/scheduler.h}
{$I ../include/head/read_write.h}
{$I ../include/head/devices.h}
{$I ../include/head/printk_.h}
{$I ../include/head/malloc.h}
{Simbolos utilizados para los macros de la cola ligada de spblk}
{$DEFINE Use_Tail }
{$DEFINE nodo_struct := p_super_block_t}
{$DEFINE next_nodo := next_spblk }
{$DEFINE prev_nodo := prev_spblk }
{$DEFINE nodo_tail := Super_Tail }
{Macros creados solo para comodidad}
{$DEFINE Push_Spblk := Push_Node }
{$DEFINE Pop_Spblk := Pop_Node }
{$define Super_Lock := Lock }
{$define Super_unlock := Unlock }
const Super_Tail:p_super_block_t = nil;
Nr_Spblk : dword = 0 ;
var I_Root:p_inode_t;
implementation
{$I ../include/head/string.h}
{$I ../include/head/list.h}
{$I ../include/head/lock.h}
procedure Init_Super (Super : p_super_block_t);inline;
begin
super^.mayor := 0 ;
super^.menor := 0 ;
super^.dirty := false ;
super^.flags := 0 ;
super^.blocksize := 0 ;
super^.driver_space := nil ;
super^.wait_on_sb.lock := false ;
super^.ino_hash := nil ;
end;
procedure Remove_Spb (sp : p_super_block_t ) ;
begin
Pop_spblk (sp);
kfree_s(sp , sizeof (super_block_t));
end;
{ * Read_Super : *
* *
* Mayor , Menor : Dev *
* Flags : tipo de sb *
* fs : Puntero al driver de fs *
* *
* Funcion que lee un superbloque y lo agrega a la cola de sp montados *
* *
***********************************************************************
}
function read_super ( Mayor , Menor , flags : dword ; fs : p_file_system_type ) : p_super_block_t ;[public , alias : 'READ_SUPER'];
var tmp : p_super_block_t;
p : p_inode_t ;
begin
if Nr_Spblk = Max_Spblk then exit (nil);
tmp := kmalloc (sizeof(super_block_t));
if tmp = nil then exit (nil);
Init_Super (tmp);
tmp^.mayor := mayor ;
tmp^.menor := menor ;
tmp^.flags := flags ;
tmp^.fs_type := fs ;
if fs^.read_super (tmp) = nil then
begin
Invalid_sb (tmp);
kfree_s (tmp,sizeof(super_block_t));
exit(nil);
end;
{es metido en la cola de spb}
push_spblk (tmp);
{este debera permanecer el memoria}
p := get_inode (tmp,tmp^.ino_root);
{no se pudo traer !!!}
if (p = nil) then
begin
{todo el cache perteneciente al sp es removido!!!}
Invalid_sb (tmp);
Remove_spb (tmp);
exit(nil);
end;
{el driver nunca trabaja con el dcache , por eso el campo i_dentry debe }
{estar a nil!!!}
tmp^.pino_root := p;
{se puede crear un dentry para el cache??}
tmp^.pino_root^.i_dentry := alloc_dentry (' ');
{error al crear el la entrada}
if tmp^.pino_root^.i_dentry = nil then
begin
put_inode (tmp^.pino_root);
Invalid_sb (tmp);
remove_spb (tmp);
exit(nil);
end;
tmp^.pino_root^.i_dentry^.ino := tmp^.pino_root;
{siempre estara en memoria , prevego a que un put_dentry me saque el ino}
{root}
tmp^.pino_root^.i_dentry^.count := 1;
Nr_Spblk += 1;
exit(tmp);
end;
{ * Get_Super : *
* *
* Mayor y Menor : Idet. del dispositivo *
* Devuelve : Un puntero al superbloque *
* *
* Esta funcion devuelve el superbloque de un dispotivo dado , este *
* devera estar previamente registrado *
* *
***********************************************************************
}
function Get_Super(Mayor,Menor:dword) : p_super_block_t;[public , alias :'GET_SUPER'];
var tmp:p_super_block_t ;
begin
tmp := Super_Tail ;
repeat
If (tmp^.mayor = mayor) and (tmp^.menor = menor) then exit(tmp);
tmp := tmp^.next_spblk;
until (tmp = Super_Tail);
exit(nil);
end;
{ * Get_Fstype : *
* *
* name : Nombre del sistema de archivo *
* retorno : a la estructura del driver *
* *
* funcionque que devuelve un puntero al driver dado en name dentro de *
* los drivers instalados *
* *
***********************************************************************
}
function get_fstype ( const name : string ) : p_file_system_type ; [public , alias : 'GET_FSTYPE'];
var tmp , id : dword ;
fs : p_file_system_type ;
begin
id := 0 ;
for tmp := 1 to High (fsid) do
begin
if chararraycmp(@fsid[tmp].name[1],@name[1],dword(name[0])) then
begin
id := fsid[tmp].id ;
break;
end;
end;
if id = 0 then exit(nil);
if fs_type = nil then exit(nil);
{se buscara el id en la cola de driver instalados}
fs := fs_type ;
repeat
if fs^.fs_id = id then exit(fs) ;
fs := fs^.next_fs ;
until ( fs = fs_type) ;
exit(nil);
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clFtpFileHandler;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
{$IFDEF DELPHI7}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CAST OFF}
{$ENDIF}
uses
Classes, clFtpServer, clFtpUtils;
type
TclFtpFileHandler = class(TComponent)
private
FServer: TclFtpServer;
procedure SetServer(const Value: TclFtpServer);
function GetErrorText(AErrorCode: Integer): string;
procedure DoCreateDir(Sender: TObject; AConnection: TclFtpCommandConnection;
const AName: string; var Success: Boolean; var AErrorMessage: string);
procedure DoDelete(Sender: TObject; AConnection: TclFtpCommandConnection;
const AName: string; var Success: Boolean; var AErrorMessage: string);
procedure DoGetFile(Sender: TObject; AConnection: TclFtpCommandConnection;
const AFileName: string; var ASource: TStream; var Success: Boolean; var AErrorMessage: string);
procedure DoGetFileInfo(Sender: TObject; AConnection: TclFtpCommandConnection;
const AName: string; AInfo: TclFtpFileInfo; var Success: Boolean; var AErrorMessage: string);
procedure DoGetFileList(Sender: TObject; AConnection: TclFtpCommandConnection;
const APathName: string; AIncludeHidden: Boolean; AFileList: TclFtpFileList);
procedure DoPutFile(Sender: TObject; AConnection: TclFtpCommandConnection; const AFileName: string;
AOverwrite: Boolean; var ADestination: TStream; var Success: Boolean; var AErrorMessage: string);
procedure DoRename(Sender: TObject; AConnection: TclFtpCommandConnection;
const ACurrentName, ANewName: string; var Success: Boolean; var AErrorMessage: string);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure CleanEventHandlers; virtual;
procedure InitEventHandlers; virtual;
published
property Server: TclFtpServer read FServer write SetServer;
end;
implementation
uses
SysUtils, Windows, clUtils;
{ TclFtpFileHandler }
procedure TclFtpFileHandler.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation <> opRemove) then Exit;
if (AComponent = FServer) then
begin
CleanEventHandlers();
FServer := nil;
end;
end;
procedure TclFtpFileHandler.SetServer(const Value: TclFtpServer);
begin
if (FServer <> Value) then
begin
{$IFDEF DELPHI5}
if (FServer <> nil) then
begin
FServer.RemoveFreeNotification(Self);
CleanEventHandlers();
end;
{$ENDIF}
FServer := Value;
if (FServer <> nil) then
begin
FServer.FreeNotification(Self);
InitEventHandlers();
end;
end;
end;
procedure TclFtpFileHandler.CleanEventHandlers;
begin
Server.OnCreateDir := nil;
Server.OnDelete := nil;
Server.OnRename := nil;
Server.OnGetFileInfo := nil;
Server.OnPutFile := nil;
Server.OnGetFile := nil;
Server.OnGetFileList := nil;
end;
procedure TclFtpFileHandler.InitEventHandlers;
begin
Server.OnCreateDir := DoCreateDir;
Server.OnDelete := DoDelete;
Server.OnRename := DoRename;
Server.OnGetFileInfo := DoGetFileInfo;
Server.OnPutFile := DoPutFile;
Server.OnGetFile := DoGetFile;
Server.OnGetFileList := DoGetFileList;
end;
procedure TclFtpFileHandler.DoCreateDir(Sender: TObject; AConnection: TclFtpCommandConnection;
const AName: string; var Success: Boolean; var AErrorMessage: string);
begin
Success := CreateDir(AName);
if not Success then
begin
AErrorMessage := GetErrorText(GetLastError());
end;
end;
procedure TclFtpFileHandler.DoDelete(Sender: TObject; AConnection: TclFtpCommandConnection;
const AName: string; var Success: Boolean; var AErrorMessage: string);
var
attr: Integer;
sr: TSearchRec;
begin
attr := faDirectory;
if (FindFirst(AName, attr, sr) = 0) and ((sr.Attr and faDirectory) > 0) then
begin
Success := RemoveDir(AName);
end else
begin
Success := DeleteFile(PChar(AName));
end;
SysUtils.FindClose(sr);
if not Success then
begin
AErrorMessage := GetErrorText(GetLastError());
end;
end;
procedure TclFtpFileHandler.DoRename(Sender: TObject; AConnection: TclFtpCommandConnection;
const ACurrentName, ANewName: string; var Success: Boolean; var AErrorMessage: string);
begin
Success := RenameFile(ACurrentName, ANewName);
if not Success then
begin
AErrorMessage := GetErrorText(GetLastError());
end;
end;
procedure TclFtpFileHandler.DoGetFileInfo(Sender: TObject; AConnection: TclFtpCommandConnection;
const AName: string; AInfo: TclFtpFileInfo; var Success: Boolean; var AErrorMessage: string);
var
sr: TSearchRec;
begin
Success := (FindFirst(AName, faReadOnly or faDirectory or faArchive or faHidden, sr) = 0);
if Success then
begin
AInfo.FileName := sr.Name;
AInfo.Size := sr.Size; //TODO Int64
AInfo.IsDirectory := (sr.Attr and FILE_ATTRIBUTE_DIRECTORY) > 0;
AInfo.IsReadOnly := (sr.Attr and FILE_ATTRIBUTE_READONLY) > 0;
AInfo.ModifiedDate := ConvertFileTimeToDateTime(sr.FindData.ftLastWriteTime);
end else
begin
AErrorMessage := GetErrorText(GetLastError());
end;
SysUtils.FindClose(sr);
end;
procedure TclFtpFileHandler.DoPutFile(Sender: TObject; AConnection: TclFtpCommandConnection;
const AFileName: string; AOverwrite: Boolean; var ADestination: TStream;
var Success: Boolean; var AErrorMessage: string);
const
modes: array[Boolean] of Word = (fmOpenWrite, fmCreate);
begin
try
ADestination := TFileStream.Create(AFileName, modes[AOverwrite]);
Success := True;
except
on E: Exception do
begin
Success := False;
AErrorMessage := E.Message;
end;
end;
end;
procedure TclFtpFileHandler.DoGetFile(Sender: TObject; AConnection: TclFtpCommandConnection;
const AFileName: string; var ASource: TStream; var Success: Boolean; var AErrorMessage: string);
begin
try
ASource := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
Success := True;
except
on E: Exception do
begin
Success := False;
AErrorMessage := E.Message;
end;
end;
end;
procedure TclFtpFileHandler.DoGetFileList(Sender: TObject; AConnection: TclFtpCommandConnection;
const APathName: string; AIncludeHidden: Boolean; AFileList: TclFtpFileList);
var
searchRec: TSearchRec;
path: string;
item: TclFtpFileItem;
attr: Integer;
begin
path := APathName;
if not FileExists(path) then
begin
path := AddTrailingBackSlash(path) + '*.*';
end;
attr := faReadOnly or faDirectory or faArchive;
if AIncludeHidden then
begin
attr := attr or faHidden;
end;
if SysUtils.FindFirst(path, attr, searchRec) = 0 then
begin
repeat
if (searchRec.Name <> '.') and (searchRec.Name <> '..') then
begin
item := AFileList.Add();
item.Info.FileName := searchRec.Name;
item.Info.IsDirectory := (searchRec.Attr and FILE_ATTRIBUTE_DIRECTORY) > 0;
item.Info.IsReadOnly := (searchRec.Attr and FILE_ATTRIBUTE_READONLY) > 0;
item.Info.Size := searchRec.Size;
item.Info.ModifiedDate := ConvertFileTimeToDateTime(searchRec.FindData.ftLastWriteTime);
end;
until (SysUtils.FindNext(searchRec) <> 0);
SysUtils.FindClose(searchRec);
end;
end;
function TclFtpFileHandler.GetErrorText(AErrorCode: Integer): string;
var
Buffer: array[0..255] of Char;
begin
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, AErrorCode, 0, Buffer, SizeOf(Buffer), nil);
Result := Trim(Buffer);
end;
end.
|
unit Voxel_AutoNormals;
// Warning: The code from this file was written in Portuguese (BR) language because it is
// a feature that was published in a brazilian symposium (SIBGRAPI 2007: Simpósio
// Brasileiro de Computação Gráfica e Processamento de Imagens). The short paper
// of this feature is called "Finding Surface Normals From Voxels" and it is has
// been written in English (USA).
// Atenção: O código deste arquivo foi escrito em Português do Brasil porque esta
// funcionalidade foi publicada no SIBGRAPI 2007: Simpósio Brasileiro de Computação
// Gráfica e Processamento de Imagens. O short paper desta funcionalidade chama-se
// "Finding Surface Normals From Voxels" e foi escrito em Inglês (EUA).
interface
uses Voxel, Voxel_Tools, math, Voxel_Engine, math3d, ThreeDPointList, SysUtils,
BasicMathsTypes, BasicDataTypes, BasicVXLSETypes, Dialogs, VoxelMap,
BasicFunctions;
{$define LIMITES}
//{$define RAY_LIMIT}
//{$define DEBUG}
type
// Estruturas do Voxel_Tools and Voxel.
{
TVector3f = record
X, Y, Z : single;
end;
TApplyNormalsResult = record
applied,
confused: Integer;
end;
TDistanceArray = array of array of array of TDistanceUnit; //single;
}
// Novas estruturas.
TFiltroDistanciaUnidade = record
x,
y,
z,
Distancia : single;
end;
TFiltroDistancia = array of array of array of TFiltroDistanciaUnidade;
const
// Essas constantes mapeam o nível de influência do pixel em relação ao
// modelo. As únicas constantes que importam são as não comentadas. As
// outras só estão aí pra fins de referência
C_FORA_DO_VOLUME = 0; // não faz parte do modelo
C_INFLUENCIA_DE_UM_EIXO = 1; // não faz parte, mas está entre pixels de um eixo
C_INFLUENCIA_DE_DOIS_EIXOS = 2; // não faz parte, mas está entre pixels de dois eixos
C_INFLUENCIA_DE_TRES_EIXOS = 3; // não faz parte, mas está entre pixels de dois eixos
C_SUPERFICIE = 4; // superfície do modelo.
C_PARTE_DO_VOLUME = 5; // parte interna do modelo.
// Constante de pesos, para se usar na hora de detectar a tendência da
// massa
PESO_FORA_DO_VOLUME = 0;
PESO_INFLUENCIA_DE_UM_EIXO = 0.000001;
PESO_INFLUENCIA_DE_DOIS_EIXOS = 0.0001;
PESO_INFLUENCIA_DE_TRES_EIXOS = 0.01;
PESO_PARTE_DO_VOLUME = 0.1;
PESO_SUPERFICIE = 1;
// Função principal
function AcharNormais(var Voxel : TVoxelSection; Alcance : single; TratarDescontinuidades : boolean) : TApplyNormalsResult;
// Funções de mapeamento
procedure ConverteInfluenciasEmPesos(var Mapa : TVoxelMap);
// Funções de filtro
procedure GerarFiltro(var Filtro : TFiltroDistancia; Alcance : single);
function AplicarFiltroNoMapa(var Voxel : TVoxelSection; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; Alcance : integer; TratarDescontinuidades : boolean): integer;
procedure AplicarFiltro(var Voxel : TVoxelSection; const Mapa: TVoxelMap; const Filtro : TFiltroDistancia; var V : TVoxelUnpacked; Alcance,_x,_y,_z : integer; TratarDescontinuidades : boolean = false);
// 1.38: Funções de detecção de superfícies.
procedure DetectarSuperficieContinua(var MapaDaSuperficie: T3DBooleanMap; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; x,y,z : integer; const PontoMin,PontoMax : TVector3i; var LimiteMin,LimiteMax : TVector3i);
procedure DetectarSuperficieEsferica(var MapaDaSuperficie: T3DBooleanMap; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; const PontoMin,PontoMax: TVector3i; var LimiteMin,LimiteMax : TVector3i);
// Plano Tangente
procedure AcharPlanoTangenteEmXY(const Mapa : T3DBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio: TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i);
procedure AcharPlanoTangenteEmYZ(const Mapa : T3DBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio: TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i);
procedure AcharPlanoTangenteEmXZ(const Mapa : T3DBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio: TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i);
// Outras funções
function PontoValido (const x,y,z,maxx,maxy,maxz : integer) : boolean;
function PegarValorDoPonto(const Mapa : TVoxelMap; var Ultimo : TVector3i; const Ponto : TVector3f; var EstaNoVazio : boolean): single;
procedure AdicionaNaListaSuperficie(const Mapa: TVoxelMap; const Filtro : TFiltroDistancia; x,y,z,xdir,ydir,zdir,XFiltro,YFiltro,ZFiltro: integer; var Lista,Direcao : C3DPointList; var LimiteMin,LimiteMax : TVector3i; var MapaDeVisitas,MapaDeSuperficie : T3DBooleanMap);
implementation
// 1.37: Novo Auto-Normalizador baseado em planos tangentes
// Essa é a função principal da normalização.
function AcharNormais(var Voxel : TVoxelSection; Alcance : single; TratarDescontinuidades : boolean) : TApplyNormalsResult;
var
MapaDoVoxel : TVoxelMap;
x, y: integer;
Filtro : TFiltroDistancia;
IntAlcance : integer;
begin
// Reseta as variáveis mais básicas.
Result.applied := 0;
IntAlcance := Trunc(Alcance);
// Estratégia: Primeiro mapeamos o voxel, preparamos o filtro e depois
// aplicamos o filtro no mapa.
// ----------------------------------------------------
// Parte 1: Mapeando as superfícies, parte interna e influências do
// modelo.
// ----------------------------------------------------
MapaDoVoxel := TVoxelMap.CreateQuick(Voxel,IntAlcance);
MapaDoVoxel.GenerateFullMap;
ConverteInfluenciasEmPesos(MapaDoVoxel);
// ----------------------------------------------------
// Parte 2: Preparando o filtro.
// ----------------------------------------------------
GerarFiltro(Filtro,Alcance);
// ----------------------------------------------------
// Parte 3: Aplicando o filtro no mapa e achando as normais
// ----------------------------------------------------
Result.applied := AplicarFiltroNoMapa(Voxel,MapaDoVoxel,Filtro,IntAlcance,TratarDescontinuidades);
// ----------------------------------------------------
// Parte 4: Libera memória.
// ----------------------------------------------------
for x := Low(Filtro) to High(Filtro) do
begin
for y := Low(Filtro) to High(Filtro[x]) do
begin
SetLength(Filtro[x,y], 0);
end;
SetLength(Filtro[x], 0);
end;
SetLength(Filtro, 0);
MapaDoVoxel.Free;
end;
///////////////////////////////////////////////////////////////////////
///////////////// Funções de Mapeamento ///////////////////////////////
///////////////////////////////////////////////////////////////////////
//////////////////////////
////////////////
///////
procedure ConverteInfluenciasEmPesos(var Mapa : TVoxelMap);
var
Peso : array of single;
begin
SetLength(Peso,6);
Peso[C_FORA_DO_VOLUME] := PESO_FORA_DO_VOLUME;
Peso[C_INFLUENCIA_DE_UM_EIXO] := PESO_INFLUENCIA_DE_UM_EIXO;
Peso[C_INFLUENCIA_DE_DOIS_EIXOS] := PESO_INFLUENCIA_DE_DOIS_EIXOS;
Peso[C_INFLUENCIA_DE_TRES_EIXOS] := PESO_INFLUENCIA_DE_TRES_EIXOS;
Peso[C_PARTE_DO_VOLUME] := PESO_PARTE_DO_VOLUME;
Peso[C_SUPERFICIE] := PESO_SUPERFICIE;
Mapa.ConvertValues(Peso);
end;
///////////////////////////////////////////////////////////////////////
///////////////// Funções de Filtro ///////////////////////////////////
///////////////////////////////////////////////////////////////////////
//////////////////////////
////////////////
///////
procedure GerarFiltro(var Filtro : TFiltroDistancia; Alcance : single);
var
x,y,z : integer;
Tamanho,Meio : integer;
Distancia,DistanciaAoCubo : single;
begin
// 1.36 Setup distance array
Meio := Trunc(Alcance);
Tamanho := (2*Meio)+1;
SetLength(Filtro,Tamanho,Tamanho,Tamanho);
Filtro[Meio,Meio,Meio].X := 0;
Filtro[Meio,Meio,Meio].Y := 0;
Filtro[Meio,Meio,Meio].Z := 0;
for x := Low(Filtro) to High(Filtro) do
begin
for y := Low(Filtro[x]) to High(Filtro[x]) do
begin
for z := Low(Filtro[x,y]) to High(Filtro[x,y]) do
begin
Distancia := sqrt(((x - Meio) * (x - Meio)) + ((y - Meio) * (y - Meio)) + ((z - Meio) * (z - Meio)));
if (Distancia > 0) and (Distancia <= Alcance) then
begin
DistanciaAoCubo := Power(Distancia,3);
if Meio <> x then
Filtro[x,y,z].X := (Meio - x) / DistanciaAoCubo
else
Filtro[x,y,z].X := 0;
if Meio <> y then
Filtro[x,y,z].Y := (Meio - y) / DistanciaAoCubo
else
Filtro[x,y,z].Y := 0;
if Meio <> z then
Filtro[x,y,z].Z := (Meio - z) / DistanciaAoCubo
else
Filtro[x,y,z].Z := 0;
end
else
begin
Filtro[x,y,z].X := 0;
Filtro[x,y,z].Y := 0;
Filtro[x,y,z].Z := 0;
end;
end;
end;
end;
end;
function AplicarFiltroNoMapa(var Voxel : TVoxelSection; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; Alcance : integer; TratarDescontinuidades : boolean): integer;
var
x,y,z : integer;
v : TVoxelUnpacked;
begin
Result := 0;
for x := 0 to Voxel.Tailer.XSize-1 do
for y := 0 to Voxel.Tailer.YSize-1 do
for z := 0 to Voxel.Tailer.ZSize-1 do
begin
// Confere se o voxel é usado.
Voxel.GetVoxel(x,y,z,v);
if v.Used then
begin
// Confere se o voxel é superfície
if Mapa[x+Alcance,y+Alcance,z+Alcance] = PESO_SUPERFICIE then
begin
// Confere se ele é matematicamente viável.
AplicarFiltro(Voxel,Mapa,Filtro,v,Alcance,x,y,z,TratarDescontinuidades);
inc(Result);
end;
end;
end;
end;
procedure AplicarFiltro(var Voxel : TVoxelSection; const Mapa: TVoxelMap; const Filtro : TFiltroDistancia; var V : TVoxelUnpacked; Alcance,_x,_y,_z : integer; TratarDescontinuidades : boolean = false);
const
C_TAMANHO_RAYCASTING = 12;
var
VetorNormal : TVector3f;
x,y,z : integer;
xx,yy,zz : integer;
PontoMin,PontoMax,LimiteMin,LimiteMax,PseudoCentro: TVector3i;
PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f;
Direcao : single;
Contador : integer;
contaEixoProblematico: byte;
{$ifdef RAY_LIMIT}
ValorFrente,ValorOposto : real;
{$endif}
PararRaioDaFrente,PararRaioOposto : boolean;
Posicao,PosicaoOposta,Centro : TVector3f;
MapaDaSuperficie : T3DBooleanMap;
UltimoVisitado,UltimoOpostoVisitado : TVector3i;
begin
// Esse é o ponto do Mapa equivalente ao ponto do voxel a ser avaliado.
x := Alcance + _x;
y := Alcance + _y;
z := Alcance + _z;
// Temos os limites máximos e mínimos da vizinhança que será verificada no
// processo
PontoMin.X := _x;
PontoMax.X := x + Alcance;
PontoMin.Y := _y;
PontoMax.Y := y + Alcance;
PontoMin.Z := _z;
PontoMax.Z := z + Alcance;
// 1.38: LimiteMin e LimiteMax são a 'bounding box' do plano tangente a ser
// avaliado.
{$ifdef LIMITES}
LimiteMin := SetVectori(High(Filtro),High(Filtro[0]),High(Filtro[0,0]));
LimiteMax := SetVectori(0,0,0);
{$else}
LimiteMin := SetVectori(0,0,0);
LimiteMax := SetVectori(High(Filtro),High(Filtro[0]),High(Filtro[0,0]));
{$endif}
// 1.38: Agora vamos conferir os voxels que farão parte da superfície
// analisada.
SetLength(MapaDaSuperficie,High(Filtro)+1,High(Filtro[0])+1,High(Filtro[0,0])+1);
if TratarDescontinuidades then
begin
DetectarSuperficieContinua(MapaDaSuperficie,Mapa,Filtro,x,y,z,PontoMin,PontoMax,LimiteMin,LimiteMax);
end
else
begin
// Senão, adicionaremos os pontos que façam parte da superfície do modelo.
DetectarSuperficieEsferica(MapaDaSuperficie,Mapa,Filtro,PontoMin,PontoMax,LimiteMin,LimiteMax);
end;
// O plano tangente requer que haja pelo menos dois pontos distintos em 2 eixos
contaEixoProblematico := 0;
if ((LimiteMax.X - LimiteMin.X) < 3) then
inc(contaEixoProblematico);
if ((LimiteMax.Y - LimiteMin.Y) < 3) then
inc(contaEixoProblematico);
if ((LimiteMax.Z - LimiteMin.Z) < 3) then
inc(contaEixoProblematico);
if contaEixoProblematico = 3 then
begin
// Temos um ponto ou cubo isolado.
VetorNormal := SetVector(0,0,0);
end
else if contaEixoProblematico = 2 then
begin
VetorNormal := SetVector(0,0,0);
if ((LimiteMax.X - LimiteMin.X) < 1) then
VetorNormal.X := 1;
if ((LimiteMax.Y - LimiteMin.Y) < 1) then
VetorNormal.Y := 1;
if ((LimiteMax.Z - LimiteMin.Z) < 1) then
VetorNormal.Z := 1;
if (VetorNormal.X = 0) and (VetorNormal.Y = 0) and (VetorNormal.Z = 0) then
begin
// Temos uma emulação de um Cubed Normalizer de raio 1 que é confiável.
for xx := (Alcance-1) to (Alcance+1) do
for yy := (Alcance-1) to (Alcance+1) do
for zz := (Alcance-1) to (Alcance+1) do
begin
if MapaDaSuperficie[xx,yy,zz] then
begin
VetorNormal.X := VetorNormal.X + Filtro[xx,yy,zz].X;
VetorNormal.Y := VetorNormal.Y + Filtro[xx,yy,zz].Y;
VetorNormal.Z := VetorNormal.Z + Filtro[xx,yy,zz].Z;
end;
end;
end;
end
else if contaEixoProblematico < 2 then
begin
//{$ifdef LIMITES}
// Isso calcula o que será considerado o centro do plano tangente.
{
PseudoCentro.X := (LimiteMin.X + LimiteMax.X) div 2;
PseudoCentro.Y := (LimiteMin.Y + LimiteMax.Y) div 2;
PseudoCentro.Z := (LimiteMin.Z + LimiteMax.Z) div 2;
}
//{$else}
PseudoCentro.X := Alcance;
PseudoCentro.Y := Alcance;
PseudoCentro.Z := Alcance;
//{$endif}
// Resetamos os pontos do plano
PontoSudoeste := SetVector(0,0,0);
PontoNordeste := SetVector(0,0,0);
// Vetor Normal
VetorNormal := SetVector(0,0,0);
// Para encontrar o plano tangente, primeiro iremos ver qual é a
// provável tendência desse plano, para evitar arestas pequenas demais
// que distorceriam o resultado final.
for xx := Low(MapaDaSuperficie) to High(MapaDaSuperficie) do
for yy := Low(MapaDaSuperficie[xx]) to High(MapaDaSuperficie[xx]) do
for zz := Low(MapaDaSuperficie[xx,yy]) to High(MapaDaSuperficie[xx,yy]) do
begin
if MapaDaSuperficie[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
if (Filtro[xx,yy,zz].X >= 0) then
PontoNordeste.X := PontoNordeste.X + Filtro[xx,yy,zz].X
else
PontoSudoeste.X := PontoSudoeste.X + Filtro[xx,yy,zz].X;
if (Filtro[xx,yy,zz].Y >= 0) then
PontoNordeste.Y := PontoNordeste.Y + Filtro[xx,yy,zz].Y
else
PontoSudoeste.Y := PontoSudoeste.Y + Filtro[xx,yy,zz].Y;
if (Filtro[xx,yy,zz].Z >= 0) then
PontoNordeste.Z := PontoNordeste.Z + Filtro[xx,yy,zz].Z
else
PontoSudoeste.Z := PontoSudoeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
// Com a tendência acima, vamos escolher os dois maiores eixos
if (PontoNordeste.X - PontoSudoeste.X) > (PontoNordeste.Y - PontoSudoeste.Y) then
begin
if (PontoNordeste.Y - PontoSudoeste.Y) > (PontoNordeste.Z - PontoSudoeste.Z) then
begin
AcharPlanoTangenteEmXY(MapaDaSuperficie,Filtro,Alcance,PseudoCentro,PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste,LimiteMin,LimiteMax);
end
else
begin
AcharPlanoTangenteEmXZ(MapaDaSuperficie,Filtro,Alcance,PseudoCentro,PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste,LimiteMin,LimiteMax);
end;
end
else if (PontoNordeste.X - PontoSudoeste.X) > (PontoNordeste.Z - PontoSudoeste.Z) then
begin
AcharPlanoTangenteEmXY(MapaDaSuperficie,Filtro,Alcance,PseudoCentro,PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste,LimiteMin,LimiteMax);
end
else
begin
AcharPlanoTangenteEmYZ(MapaDaSuperficie,Filtro,Alcance,PseudoCentro,PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste,LimiteMin,LimiteMax);
end;
// Agora vamos achar uma das direções do plano. A outra vai ser o
// negativo dessa.
VetorNormal.X := ((PontoNordeste.Y - PontoSudeste.Y) * (PontoSudoeste.Z - PontoSudeste.Z)) - ((PontoSudoeste.Y - PontoSudeste.Y) * (PontoNordeste.Z - PontoSudeste.Z));
VetorNormal.Y := ((PontoNordeste.Z - PontoSudeste.Z) * (PontoSudoeste.X - PontoSudeste.X)) - ((PontoSudoeste.Z - PontoSudeste.Z) * (PontoNordeste.X - PontoSudeste.X));
VetorNormal.Z := ((PontoNordeste.X - PontoSudeste.X) * (PontoSudoeste.Y - PontoSudeste.Y)) - ((PontoSudoeste.X - PontoSudeste.X) * (PontoNordeste.Y - PontoSudeste.Y));
if (VetorNormal.X = 0) and (VetorNormal.Y = 0) and (VetorNormal.Z = 0) then
begin
VetorNormal.X := ((PontoNoroeste.Y - PontoNordeste.Y) * (PontoSudeste.Z - PontoNordeste.Z)) - ((PontoSudeste.Y - PontoNordeste.Y) * (PontoNoroeste.Z - PontoNordeste.Z));
VetorNormal.Y := ((PontoNoroeste.Z - PontoNordeste.Z) * (PontoSudeste.X - PontoNordeste.X)) - ((PontoSudeste.Z - PontoNordeste.Z) * (PontoNoroeste.X - PontoNordeste.X));
VetorNormal.Z := ((PontoNoroeste.X - PontoNordeste.X) * (PontoSudeste.Y - PontoNordeste.Y)) - ((PontoSudeste.X - PontoNordeste.X) * (PontoNoroeste.Y - PontoNordeste.Y));
end;
if (VetorNormal.X = 0) and (VetorNormal.Y = 0) and (VetorNormal.Z = 0) then
begin
VetorNormal.X := ((PontoSudoeste.Y - PontoNoroeste.Y) * (PontoNordeste.Z - PontoNoroeste.Z)) - ((PontoNordeste.Y - PontoNoroeste.Y) * (PontoSudoeste.Z - PontoNoroeste.Z));
VetorNormal.Y := ((PontoSudoeste.Z - PontoNoroeste.Z) * (PontoNordeste.X - PontoNoroeste.X)) - ((PontoNordeste.Z - PontoNoroeste.Z) * (PontoSudoeste.X - PontoNoroeste.X));
VetorNormal.Z := ((PontoSudoeste.X - PontoNoroeste.X) * (PontoNordeste.Y - PontoNoroeste.Y)) - ((PontoNordeste.X - PontoNoroeste.X) * (PontoSudoeste.Y - PontoNoroeste.Y));
end;
if (VetorNormal.X = 0) and (VetorNormal.Y = 0) and (VetorNormal.Z = 0) then
begin
VetorNormal.X := ((PontoSudeste.Y - PontoSudoeste.Y) * (PontoNoroeste.Z - PontoSudoeste.Z)) - ((PontoNoroeste.Y - PontoSudoeste.Y) * (PontoSudeste.Z - PontoSudoeste.Z));
VetorNormal.Y := ((PontoSudeste.Z - PontoSudoeste.Z) * (PontoNoroeste.X - PontoSudoeste.X)) - ((PontoNoroeste.Z - PontoSudoeste.Z) * (PontoSudeste.X - PontoSudoeste.X));
VetorNormal.Z := ((PontoSudeste.X - PontoSudoeste.X) * (PontoNoroeste.Y - PontoSudoeste.Y)) - ((PontoNoroeste.X - PontoSudoeste.X) * (PontoSudeste.Y - PontoSudoeste.Y));
{$ifdef DEBUG}
if (VetorNormal.X = 0) and (VetorNormal.Y = 0) and (VetorNormal.Z = 0) then
// ShowMessage('(' + FloatToStr(VetorNormal.X) + ',' + FloatToStr(VetorNormal.Y) + ',' + FloatToStr(VetorNormal.Z) + ')');
ShowMessage('(0,0,0) with (' + FloatToStr(PontoSudoeste.X) + ',' + FloatToStr(PontoSudoeste.Y) + ',' + FloatToStr(PontoSudoeste.Z) + ') - (' + FloatToStr(PontoSudeste.X) + ',' + FloatToStr(PontoSudeste.Y) + ',' + FloatToStr(PontoSudeste.Z) + ') - (' + FloatToStr(PontoNordeste.X) + ',' + FloatToStr(PontoNordeste.Y) + ',' + FloatToStr(PontoNordeste.Z) + ') - (' + FloatToStr(PontoNoroeste.X) + ',' + FloatToStr(PontoNoroeste.Y) + ',' + FloatToStr(PontoNoroeste.Z) + '), at (' + IntToStr(_x) + ',' + IntToStr(_y) + ',' + IntToStr(_z) + '). MinLimit: (' + IntToStr(LimiteMin.X) + ',' + IntToStr(LimiteMin.Y) + ',' + IntToStr(LimiteMin.Z) + '). MaxLimit: ' + IntToStr(LimiteMax.X) + ',' + IntToStr(LimiteMax.Y) + ',' + IntToStr(LimiteMax.Z) + '). Center at: ' + IntToStr(PseudoCentro.X) + ',' + IntToStr(PseudoCentro.Y) + ',' + IntToStr(PseudoCentro.Z) + ') with range ' + IntToStr(Alcance) + '.');
{$endif}
end;
end;
// A formula acima tá no livro da Aura:
// X = (P3.Y - P2.Y)(P1.Z - P2.Z) - (P1.Y - P2.Y)(P3.Z - P2.Z)
// Y = (P3.Z - P2.Z)(P1.X - P2.X) - (P1.Z - P2.Z)(P3.X - P2.X)
// Z = (P3.X - P2.X)(P1.Y - P2.Y) - (P1.X - P2.X)(P3.Y - P2.Y)
// Transforma o vetor normal em vetor unitário. (Normalize em math3d)
Normalize(VetorNormal);
// Pra qual lado vai a normal?
// Responderemos essa pergunta com um falso raycasting limitado.
Centro := SetVector(x + 0.5,y + 0.5,z + 0.5);
Posicao := SetVector(Centro.X,Centro.Y,Centro.Z);
PosicaoOposta := SetVector(Centro.X,Centro.Y,Centro.Z);
{$ifdef RAY_LIMIT}
PararRaioDaFrente := false;
PararRaioOposto := false;
{$endif}
Contador := 0;
Direcao := 0;
// Adicionamos aqui uma forma de prevenir que o mesmo voxel conte mais do
// que uma vez, evitando um resultado errado.
UltimoVisitado := SetVectorI(x,y,z);
UltimoOpostoVisitado := SetVectorI(x,y,z);
{$ifdef RAY_LIMIT}
while (not (PararRaioDaFrente and PararRaioOposto)) and (Contador < C_TAMANHO_RAYCASTING) do
{$else}
while Contador < C_TAMANHO_RAYCASTING do
{$endif}
begin
{$ifdef RAY_LIMIT}
if not PararRaioDaFrente then
begin
Posicao.X := Posicao.X + VetorNormal.X;
Posicao.Y := Posicao.Y + VetorNormal.Y;
Posicao.Z := Posicao.Z + VetorNormal.Z;
ValorFrente := PegarValorDoPonto(Mapa,UltimoVisitado,Posicao,PararRaioDaFrente);
end
else
begin
ValorFrente := 0;
end;
if not PararRaioOposto then
begin
PosicaoOposta.X := PosicaoOposta.X - VetorNormal.X;
PosicaoOposta.Y := PosicaoOposta.Y - VetorNormal.Y;
PosicaoOposta.Z := PosicaoOposta.Z - VetorNormal.Z;
ValorOposto := PegarValorDoPonto(Mapa,UltimoOpostoVisitado,PosicaoOposta,PararRaioOposto);
end
else
begin
ValorOposto := 0;
end;
Direcao := Direcao + ValorFrente - ValorOposto;
inc(Contador);
{$else}
Posicao.X := Posicao.X + VetorNormal.X;
Posicao.Y := Posicao.Y + VetorNormal.Y;
Posicao.Z := Posicao.Z + VetorNormal.Z;
PosicaoOposta.X := PosicaoOposta.X - VetorNormal.X;
PosicaoOposta.Y := PosicaoOposta.Y - VetorNormal.Y;
PosicaoOposta.Z := PosicaoOposta.Z - VetorNormal.Z;
inc(Contador);
Direcao := Direcao + PegarValorDoPonto(Mapa,UltimoVisitado,Posicao,PararRaioDaFrente) - PegarValorDoPonto(Mapa,UltimoOpostoVisitado,PosicaoOposta,PararRaioOposto);
{$endif}
end;
// Se a direção do vetor normal avaliado tiver mais peso do que a oposta
// é porque estamos indo para dentro do volume e não para fora.
If Direcao > 0 then
begin
VetorNormal.X := -VetorNormal.X;
VetorNormal.Y := -VetorNormal.Y;
VetorNormal.Z := -VetorNormal.Z;
end
else if Direcao = 0 then
begin
// Nesse caso temos um empate técnico. Quem tiver o maior z vence.
if VetorNormal.Z < 0 then
begin
VetorNormal.X := -VetorNormal.X;
VetorNormal.Y := -VetorNormal.Y;
VetorNormal.Z := -VetorNormal.Z;
end;
end;
// Pega a normal mais próxima da paleta de normais
V.Normal := Voxel.Normals.GetIDFromNormal(VetorNormal);
// Aplica a nova normal
Voxel.SetVoxel(_x,_y,_z,V);
// Libera memória
for x := Low(MapaDaSuperficie) to High(MapaDaSuperficie) do
begin
for y := Low(MapaDaSuperficie) to High(MapaDaSuperficie[x]) do
begin
SetLength(MapaDaSuperficie[x,y], 0);
end;
SetLength(MapaDaSuperficie[x], 0);
end;
SetLength(MapaDaSuperficie, 0);
end;
///////////////////////////////////////////////////////////////////////
///////////////// Detecção de Superficies /////////////////////////////
///////////////////////////////////////////////////////////////////////
///////////////////////////
/////////////////
///////
procedure AdicionaNaListaSuperficie(const Mapa: TVoxelMap; const Filtro : TFiltroDistancia; x,y,z,xdir,ydir,zdir,XFiltro,YFiltro,ZFiltro: integer; var Lista,Direcao : C3DPointList; var LimiteMin,LimiteMax : TVector3i; var MapaDeVisitas,MapaDeSuperficie : T3DBooleanMap);
begin
if Mapa.IsPointOK(x,y,z) then
begin
if PontoValido(xFiltro,yFiltro,zFiltro,High(Filtro),High(Filtro[0]),High(Filtro[0,0])) then
begin
if not MapaDeVisitas[XFiltro,YFiltro,ZFiltro] then
begin
MapaDeVisitas[XFiltro,YFiltro,ZFiltro] := true;
if (Mapa[x,y,z] >= PESO_SUPERFICIE) and ((Filtro[XFiltro,YFiltro,ZFiltro].X <> 0) or (Filtro[XFiltro,YFiltro,ZFiltro].Y <> 0) or (Filtro[XFiltro,YFiltro,ZFiltro].Z <> 0)) then
begin
Lista.Add(x,y,z);
Direcao.Add(xdir,ydir,zdir);
if (XFiltro > LimiteMax.X) then
begin
LimiteMax.X := XFiltro;
end
else if (XFiltro < LimiteMin.X) then
begin
LimiteMin.X := XFiltro;
end;
if (YFiltro > LimiteMax.Y) then
begin
LimiteMax.Y := YFiltro;
end
else if (YFiltro < LimiteMin.Y) then
begin
LimiteMin.Y := YFiltro;
end;
if (ZFiltro > LimiteMax.Z) then
begin
LimiteMax.Z := ZFiltro;
end
else if (ZFiltro < LimiteMin.Z) then
begin
LimiteMin.Z := ZFiltro;
end;
MapaDeSuperficie[XFiltro,YFiltro,ZFiltro] := true;
end
else
begin
MapaDeSuperficie[XFiltro,YFiltro,ZFiltro] := false;
end;
end;
end;
end;
end;
procedure DetectarSuperficieContinua(var MapaDaSuperficie: T3DBooleanMap; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; x,y,z : integer; const PontoMin,PontoMax : TVector3i; var LimiteMin,LimiteMax : TVector3i);
var
xx,yy,zz : integer;
xdir,ydir,zdir : integer;
Ponto : TVector3i;
Lista,Direcao : C3DPointList;
MapaDeVisitas : T3DBooleanMap;
Meio : integer;
begin
// Reseta elementos
Lista := C3DPointList.Create;
Lista.UseSmartMemoryManagement(true);
Direcao := C3DPointList.Create;
Direcao.UseSmartMemoryManagement(true);
SetLength(MapaDeVisitas,High(Filtro)+1,High(Filtro[0])+1,High(Filtro[0,0])+1);
for xx := Low(Filtro) to High(Filtro) do
for yy := Low(Filtro[0]) to High(Filtro[0]) do
for zz := Low(Filtro[0,0]) to High(Filtro[0,0]) do
begin
MapaDaSuperficie[xx,yy,zz] := false;
MapaDeVisitas[xx,yy,zz] := false;
end;
Meio := High(Filtro) shr 1;
MapaDaSuperficie[Meio,Meio,Meio] := true;
MapaDeVisitas[Meio,Meio,Meio] := true;
// Adiciona os elementos padrões, os vinte e poucos vizinhos cúbicos.
// Prioridade de eixos: z, y, x. Centro leva prioridade sobre as diagonais.
{
AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y,z,1,0,0,Meio+1,Meio,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y,z,-1,0,0,Meio-1,Meio,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x,y+1,z,0,1,0,Meio,Meio+1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y+1,z,1,1,0,Meio+1,Meio+1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y+1,z,-1,1,0,Meio-1,Meio+1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x,y-1,z,0,-1,0,Meio,Meio-1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y-1,z,1,-1,0,Meio+1,Meio-1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y-1,z,-1,-1,0,Meio-1,Meio-1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x,y,z+1,0,0,1,Meio,Meio,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y,z+1,1,0,1,Meio+1,Meio,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y,z+1,-1,0,1,Meio-1,Meio,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x,y+1,z+1,0,1,1,Meio,Meio+1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y+1,z+1,1,1,1,Meio+1,Meio+1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y+1,z+1,-1,1,1,Meio-1,Meio+1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x,y-1,z+1,0,-1,1,Meio,Meio-1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y-1,z+1,1,-1,1,Meio+1,Meio-1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y-1,z+1,-1,-1,1,Meio-1,Meio-1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x,y,z-1,0,0,-1,Meio,Meio,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y,z-1,1,0,-1,Meio+1,Meio,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y,z-1,-1,0,-1,Meio-1,Meio,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x,y+1,z-1,0,1,-1,Meio,Meio+1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y+1,z-1,1,1,-1,Meio+1,Meio+1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y+1,z-1,-1,1,-1,Meio-1,Meio+1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x,y-1,z-1,0,-1,-1,Meio,Meio-1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y-1,z-1,1,-1,-1,Meio+1,Meio-1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y-1,z-1,-1,-1,-1,Meio-1,Meio-1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
}
// AdicionaNaListaSuperficie(Mapa,Filtro,x,y,z,0,0,0,Meio,Meio,Meio,Lista,Direcao,MapaDeVisitas,MapaDaSuperficie);
Lista.Add(x,y,z);
Direcao.Add(0,0,0);
while Lista.GetPosition(xx,yy,zz) do
begin
Direcao.GetPosition(xdir,ydir,zdir);
// Acha o ponto atual no filtro.
Ponto.X := xx - PontoMin.X;
Ponto.Y := yy - PontoMin.Y;
Ponto.Z := zz - PontoMin.Z;
// Vamos conferir o que adicionaremos a partir da direcao que ele veio
// O eixo z leva prioridade, em seguida o eixo y e finalmente o eixo x.
// Se um determinado eixo tem valor 1 ou -1, significa que o raio parte
// na direcao daquele eixo. Enquanto, no caso de ele ser 0, ele pode ir
// pra qualquer lado.
// Primeiro os elementos centrais.
if xdir <> -1 then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy,zz,1,ydir,zdir,Ponto.X+1,Ponto.Y,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
if (xdir <> 1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy,zz,-1,ydir,zdir,Ponto.X-1,Ponto.Y,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
if ydir <> -1 then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy+1,zz,xdir,1,zdir,Ponto.X,Ponto.Y+1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
if xdir <> -1 then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy+1,zz,1,1,zdir,Ponto.X+1,Ponto.Y+1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
if (xdir <> 1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy+1,zz,-1,1,zdir,Ponto.X-1,Ponto.Y+1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
end;
if ydir <> 1 then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy-1,zz,xdir,-1,zdir,Ponto.X,Ponto.Y-1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
if xdir <> -1 then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy-1,zz,1,-1,zdir,Ponto.X+1,Ponto.Y-1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
if (xdir <> 1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy-1,zz,-1,-1,zdir,Ponto.X-1,Ponto.Y-1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
end;
// Agora adiciona z = 1
if zdir <> -1 then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy,zz+1,xdir,ydir,1,Ponto.X,Ponto.Y,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
if xdir <> -1 then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy,zz+1,1,ydir,1,Ponto.X+1,Ponto.Y,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
if (xdir <> 1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy,zz+1,1,ydir,1,Ponto.X-1,Ponto.Y,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
if ydir <> -1 then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy+1,zz+1,xdir,1,1,Ponto.X,Ponto.Y+1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
if xdir <> -1 then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy+1,zz+1,1,1,1,Ponto.X+1,Ponto.Y+1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
if (xdir <> 1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy+1,zz+1,-1,1,1,Ponto.X-1,Ponto.Y+1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
end
else if (ydir <> 1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy-1,zz+1,xdir,-1,1,Ponto.X,Ponto.Y-1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
if xdir = 1 then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy-1,zz+1,1,-1,1,Ponto.X+1,Ponto.Y-1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
if (xdir = -1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy-1,zz+1,-1,-1,1,Ponto.X-1,Ponto.Y-1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
end;
end;
// Agora adiciona z = -1
if (z <> 1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy,zz-1,xdir,ydir,-1,Ponto.X,Ponto.Y,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
if (xdir <> -1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy,zz-1,-1,ydir,-1,Ponto.X+1,Ponto.Y,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
if (xdir <> 1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy,zz-1,-1,ydir,-1,Ponto.X-1,Ponto.Y,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
if (ydir <> -1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy+1,zz-1,xdir,1,-1,Ponto.X,Ponto.Y+1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
if (xdir <> -1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy+1,zz-1,1,1,-1,Ponto.X+1,Ponto.Y+1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end
else if (xdir <> 1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy+1,zz-1,-1,1,-1,Ponto.X-1,Ponto.Y+1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
end;
if (ydir <> 1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy-1,zz-1,xdir,-1,-1,Ponto.X,Ponto.Y-1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
if (xdir <> -1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy-1,zz-1,1,-1,-1,Ponto.X+1,Ponto.Y-1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
if (xdir <> 1) then
begin
AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy-1,zz-1,-1,-1,-1,Ponto.X-1,Ponto.Y-1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie);
end;
end;
end;
Lista.GoToNextElement;
Direcao.GoToNextElement;
end;
// Libera memória
Lista.Free;
Direcao.Free;
for xx := Low(MapaDeVisitas) to High(MapaDeVisitas) do
begin
for yy := Low(MapaDeVisitas) to High(MapaDeVisitas[xx]) do
begin
SetLength(MapaDeVisitas[xx,yy], 0);
end;
SetLength(MapaDeVisitas[xx], 0);
end;
SetLength(MapaDeVisitas, 0);
end;
procedure DetectarSuperficieEsferica(var MapaDaSuperficie: T3DBooleanMap; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; const PontoMin,PontoMax: TVector3i; var LimiteMin,LimiteMax : TVector3i);
var
xx,yy,zz : integer;
Ponto : TVector3i;
begin
for xx := PontoMin.X to PontoMax.X do
for yy := PontoMin.Y to PontoMax.Y do
for zz := PontoMin.Z to PontoMax.Z do
begin
// Acha o ponto atual no filtro.
Ponto.X := xx - PontoMin.X;
Ponto.Y := yy - PontoMin.Y;
Ponto.Z := zz - PontoMin.Z;
// Confere a presença dele na superfície e no alcance do filtro
if (Mapa[xx,yy,zz] >= PESO_SUPERFICIE) and ((Filtro[Ponto.X,Ponto.Y,Ponto.Z].X <> 0) or (Filtro[Ponto.X,Ponto.Y,Ponto.Z].Y <> 0) or (Filtro[Ponto.X,Ponto.Y,Ponto.Z].Z <> 0)) then
begin
{$ifdef LIMITES}
if Ponto.X > LimiteMax.X then
begin
LimiteMax.X := Ponto.X;
end
else if Ponto.X < LimiteMin.X then
begin
LimiteMin.X := Ponto.X;
end;
if Ponto.Y > LimiteMax.Y then
begin
LimiteMax.Y := Ponto.Y;
end
else if Ponto.Y < LimiteMin.Y then
begin
LimiteMin.Y := Ponto.Y;
end;
if Ponto.Z > LimiteMax.Z then
begin
LimiteMax.Z := Ponto.Z;
end
else if Ponto.Z < LimiteMin.Z then
begin
LimiteMin.Z := Ponto.Z;
end;
{$ENDIF}
MapaDaSuperficie[Ponto.X,Ponto.Y,Ponto.Z] := true;
end
else
begin
MapaDaSuperficie[Ponto.X,Ponto.Y,Ponto.Z] := false;
end;
end;
end;
///////////////////////////////////////////////////////////////////////
///////////////// Plano Tangente /////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//////////////////////////
////////////////
///////
procedure AcharPlanoTangenteEmXY(const Mapa : T3DBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio : TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i);
var
xx,yy,zz : integer;
begin
// Resetamos os pontos do plano
PontoSudoeste := SetVector(0,0,0);
PontoNoroeste := SetVector(0,0,0);
PontoSudeste := SetVector(0,0,0);
PontoNordeste := SetVector(0,0,0);
// Vamos achar os quatro pontos da tangente.
// Ponto 1: Sudoeste. (X <= Meio e Y <= Meio)
for xx := LimiteMin.X to Meio.X do
for yy := LimiteMin.Y to Meio.Y do
for zz := LimiteMin.Z to LimiteMax.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoSudoeste.X := PontoSudoeste.X + Filtro[xx,yy,zz].X;
PontoSudoeste.Y := PontoSudoeste.Y + Filtro[xx,yy,zz].Y;
PontoSudoeste.Z := PontoSudoeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
// Ponto 2: Noroeste. (X <= Meio e Y >= Meio)
for xx := LimiteMin.X to Meio.X do
for yy := Alcance to LimiteMax.Y do
for zz := LimiteMin.Z to LimiteMax.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoNoroeste.X := PontoNoroeste.X + Filtro[xx,yy,zz].X;
PontoNoroeste.Y := PontoNoroeste.Y + Filtro[xx,yy,zz].Y;
PontoNoroeste.Z := PontoNoroeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
// Ponto 3: Sudeste. (X >= Meio e Y <= Meio)
for xx := Alcance to LimiteMax.X do
for yy := LimiteMin.Y to Meio.Y do
for zz := LimiteMin.Z to LimiteMax.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoSudeste.X := PontoSudeste.X + Filtro[xx,yy,zz].X;
PontoSudeste.Y := PontoSudeste.Y + Filtro[xx,yy,zz].Y;
PontoSudeste.Z := PontoSudeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
// Ponto 4: Nordeste. (X >= Meio e Y >= Meio)
for xx := Alcance to LimiteMax.X do
for yy := Alcance to LimiteMax.Y do
for zz := LimiteMin.Z to LimiteMax.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoNordeste.X := PontoNordeste.X + Filtro[xx,yy,zz].X;
PontoNordeste.Y := PontoNordeste.Y + Filtro[xx,yy,zz].Y;
PontoNordeste.Z := PontoNordeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
end;
procedure AcharPlanoTangenteEmYZ(const Mapa : T3DBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio : TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i);
var
xx,yy,zz : integer;
begin
// Resetamos os pontos do plano
PontoSudoeste := SetVector(0,0,0);
PontoNoroeste := SetVector(0,0,0);
PontoSudeste := SetVector(0,0,0);
PontoNordeste := SetVector(0,0,0);
// Ponto 1: Sudoeste. (Y <= Meio e Z <= Meio)
for xx := LimiteMin.X to LimiteMax.X do
for yy := LimiteMin.Y to Meio.Y do
for zz := LimiteMin.Z to Meio.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoSudoeste.X := PontoSudoeste.X + Filtro[xx,yy,zz].X;
PontoSudoeste.Y := PontoSudoeste.Y + Filtro[xx,yy,zz].Y;
PontoSudoeste.Z := PontoSudoeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
// Ponto 2: Noroeste. (Y <= Meio e Z >= Meio)
for xx := LimiteMin.X to LimiteMax.X do
for yy := LimiteMin.Y to Meio.Y do
for zz := Alcance to LimiteMax.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoNoroeste.X := PontoNoroeste.X + Filtro[xx,yy,zz].X;
PontoNoroeste.Y := PontoNoroeste.Y + Filtro[xx,yy,zz].Y;
PontoNoroeste.Z := PontoNoroeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
// Ponto 3: Sudeste. (Y >= Meio e Z <= Meio)
for xx := LimiteMin.X to LimiteMax.X do
for yy := Alcance to LimiteMax.Y do
for zz := LimiteMin.Z to Meio.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoSudeste.X := PontoSudeste.X + Filtro[xx,yy,zz].X;
PontoSudeste.Y := PontoSudeste.Y + Filtro[xx,yy,zz].Y;
PontoSudeste.Z := PontoSudeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
// Ponto 4: Nordeste. (Y >= Meio e Z >= Meio)
for xx := LimiteMin.X to LimiteMax.X do
for yy := Alcance to LimiteMax.Y do
for zz := Alcance to LimiteMax.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoNordeste.X := PontoNordeste.X + Filtro[xx,yy,zz].X;
PontoNordeste.Y := PontoNordeste.Y + Filtro[xx,yy,zz].Y;
PontoNordeste.Z := PontoNordeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
end;
procedure AcharPlanoTangenteEmXZ(const Mapa : T3DBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio : TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i);
var
xx,yy,zz : integer;
begin
// Resetamos os pontos do plano
PontoSudoeste := SetVector(0,0,0);
PontoNoroeste := SetVector(0,0,0);
PontoSudeste := SetVector(0,0,0);
PontoNordeste := SetVector(0,0,0);
// Ponto 1: Sudoeste. (X <= Meio e Z <= Meio)
for xx := LimiteMin.X to Meio.X do
for yy := LimiteMin.Y to LimiteMax.Y do
for zz := LimiteMin.Z to Meio.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoSudoeste.X := PontoSudoeste.X + Filtro[xx,yy,zz].X;
PontoSudoeste.Y := PontoSudoeste.Y + Filtro[xx,yy,zz].Y;
PontoSudoeste.Z := PontoSudoeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
// Ponto 2: Noroeste. (X <= Meio e Z >= Meio)
for xx := LimiteMin.X to Meio.X do
for yy := LimiteMin.Y to LimiteMax.Y do
for zz := Alcance to LimiteMax.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoNoroeste.X := PontoNoroeste.X + Filtro[xx,yy,zz].X;
PontoNoroeste.Y := PontoNoroeste.Y + Filtro[xx,yy,zz].Y;
PontoNoroeste.Z := PontoNoroeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
// Ponto 3: Sudeste. (X >= Meio e Z <= Meio)
for xx := Alcance to LimiteMax.X do
for yy := LimiteMin.Y to LimiteMax.Y do
for zz := LimiteMin.Z to Meio.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoSudeste.X := PontoSudeste.X + Filtro[xx,yy,zz].X;
PontoSudeste.Y := PontoSudeste.Y + Filtro[xx,yy,zz].Y;
PontoSudeste.Z := PontoSudeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
// Ponto 4: Nordeste. (X >= Meio e Z >= Meio)
for xx := Alcance to LimiteMax.X do
for yy := LimiteMin.Y to LimiteMax.Y do
for zz := Alcance to LimiteMax.Z do
begin
if Mapa[xx,yy,zz] then
begin
// Aplica o filtro no ponto (xx,yy,zz)
PontoNordeste.X := PontoNordeste.X + Filtro[xx,yy,zz].X;
PontoNordeste.Y := PontoNordeste.Y + Filtro[xx,yy,zz].Y;
PontoNordeste.Z := PontoNordeste.Z + Filtro[xx,yy,zz].Z;
end;
end;
end;
///////////////////////////////////////////////////////////////////////
///////////////// Outras Funções /////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//////////////////////////
////////////////
///////
// Verifica se o ponto é válido.
function PontoValido (const x,y,z,maxx,maxy,maxz : integer) : boolean;
begin
result := false;
if (x < 0) or (x > maxx) then exit;
if (y < 0) or (y > maxy) then exit;
if (z < 0) or (z > maxz) then exit;
result := true;
end;
// Pega o valor no ponto do mapa para o falso raytracing em AplicarFiltro.
function PegarValorDoPonto(const Mapa : TVoxelMap; var Ultimo : TVector3i; const Ponto : TVector3f; var EstaNoVazio : boolean): single;
var
PontoI : TVector3i;
begin
PontoI := SetVectorI(Trunc(Ponto.X),Trunc(Ponto.Y),Trunc(Ponto.Z));
Result := 0;
if Mapa.IsPointOK(PontoI.X,PontoI.Y,PontoI.Z) then
begin
if (Ultimo.X <> PontoI.X) or (Ultimo.Y <> PontoI.Y) or (Ultimo.Z <> PontoI.Z) then
begin
Ultimo.X := PontoI.X;
Ultimo.Y := PontoI.Y;
Ultimo.Z := PontoI.Z;
Result := Mapa[PontoI.X,PontoI.Y,PontoI.Z];
if Result >= PESO_PARTE_DO_VOLUME then
Result := PESO_SUPERFICIE;
EstaNoVazio := (Result <> PESO_SUPERFICIE);
end;
end
else
EstaNoVazio := true;
end;
end.
|
unit ufraDOKring;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, StdCtrls, ExtCtrls,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator,
Data.DB, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGridLevel, cxClasses, cxGridCustomView, cxGrid, cxContainer, cxProgressBar;
type
TfraDOKring = class(TFrame)
pnlHeader: TPanel;
Label1: TLabel;
edNama: TEdit;
rbDepan: TRadioButton;
rbSemua: TRadioButton;
pmLookup: TPopupMenu;
ExporttoCSV1: TMenuItem;
dlgSaveLookup: TSaveDialog;
cxGrid: TcxGrid;
cxGridView: TcxGridDBTableView;
cxlvMaster: TcxGridLevel;
cxcolNomorDO: TcxGridDBColumn;
cxcolNomorPO: TcxGridDBColumn;
cxcolStatus: TcxGridDBColumn;
cxcolNamaTrader: TcxGridDBColumn;
pbLookup: TcxProgressBar;
procedure cxGridViewDblClick(Sender: TObject);
procedure ExporttoCSV1Click(Sender: TObject);
procedure edNamaChange(Sender: TObject);
procedure edNamaKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure sgLookupKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FIsProcessing: Boolean;
FIsStop: Boolean;
FUnitID: Integer;
{ Private declarations }
public
procedure LoadData(ANama: String = ''; AIsDepan: Boolean = True);
property IsProcessing: Boolean read FIsProcessing write FIsProcessing;
property IsStop: Boolean read FIsStop write FIsStop;
property UnitID: Integer read FUnitID write FUnitID;
{ Public declarations }
end;
implementation
uses
Math, ufrmTransaksiKring;
const
_KolNomorDO: Integer = 0;
_KolNomorPO: Integer = 1;
_KolStatus: Integer = 2;
_KolNamaTrader: Integer = 3;
{$R *.dfm}
procedure TfraDOKring.cxGridViewDblClick(Sender: TObject);
var
lKey: Word;
begin
if cxGridView.DataController.RecNo = 0 then Exit;
if pbLookup.Position < 100 then Exit;
Self.Visible := False;
with (Self.Parent as TfrmTransaksiKring) do
begin
cxTransaksi.Visible := True;
pnlFooter.Visible := True;
edNomorDO.Text := cxGridView.DataController.Values[0,cxGridView.DataController.RecNo];
lKey := VK_RETURN;
edNomorDOKeyDown(Sender,lKey,[]);
end; // with
end;
procedure TfraDOKring.ExporttoCSV1Click(Sender: TObject);
begin
if dlgSaveLookup.Execute then
begin
// sgLookup.SaveToCSV(dlgSaveLookup.FileName);
ShowMessage('Berhasil export ke:' + dlgSaveLookup.FileName);
end;
end;
procedure TfraDOKring.LoadData(ANama: String = ''; AIsDepan: Boolean = True);
var
iRecordCOunt: Integer;
sSQL: string;
begin
IsProcessing := True;
sSQL := 'select a.doas_no, a.doas_poas_no, a.doas_status, b.trd_code, b.trd_name, b.trd_address '
+ 'from do_assgros a '
+ 'inner join trader b on a.doas_trd_id = b.trd_id and a.doas_trd_unt_id = b.trd_unt_id '
+ 'where a.doas_unt_id = ' + IntToStr(UnitID);
if Trim(ANama) <> '' then
if AIsDepan then
sSQL := sSQL + ' and upper(b.trd_name) like ''' + UpperCase(ANama) + '%'' '
else
sSQL := sSQL + ' and upper(b.trd_name) like ''%' + UpperCase(ANama) + '%'' ';
sSQL := sSQL + ' order by b.trd_name';
{
iRecordCOunt := 0;
with sgLookup do
begin
FilterActive := False;
ClearRows(1,RowCount-1);
RowCount := 2;
with cOpenQuery(sSQL) do
begin
try
if not Eof then
begin
Last;
iRecordCOunt := RecordCount;
pbLookup.Visible := True;
First;
end;
while not eof do
begin
Cells[_KolNomorDO,RowCount-1] := Fields[0].AsString;
Cells[_KolNomorPO,RowCount-1] := Fields[1].AsString;
Cells[_KolStatus,RowCount-1] := Fields[2].AsString;
Cells[_KolNamaTrader,RowCount-1] := Fields[3].AsString;
if Fields[3].AsInteger = 0 then
RowColor[RowCount-1] := clYellow;
if Fields[4].AsInteger = 0 then
RowColor[RowCount-1] := clRed;
AutoSize := True;
pbLookup.Position := Floor(((RowCount-1)/iRecordCOunt)*100);
RowCount := RowCount + 1;
Application.ProcessMessages;
if IsStop then
begin
pbLookup.Position := 100;
Break;
end;
Next;
end;
finally
Free;
pbLookup.Visible := False;
IsProcessing := False;
end;
end;
end;
}
end;
procedure TfraDOKring.edNamaChange(Sender: TObject);
begin
{
with sgLookup do
begin
Filter.Clear;
FilterActive := False;
with Filter.Add do
begin
CaseSensitive := False;
Condition := ';*' + edNama.Text + '*';
Column := 1;
end;
FilterActive := True;
end;
}
end;
procedure TfraDOKring.edNamaKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (key in [VK_ESCAPE]) then
begin
sgLookupKeyDown(Sender,Key,Shift);
end
else if (key in [VK_RETURN]) then
begin
IsStop := False;
if IsProcessing then
IsStop := True
else
LoadData(Trim(edNama.Text),rbDepan.Checked);
end
else if (key in [VK_UP,VK_DOWN,33,34]) then
begin
cxGrid.SetFocus;
if cxGridView.DataController.RowCount <= 1 then exit;
end
else if (key in [VK_F2]) then
begin
rbDepan.Checked := True;
end
else if (key in [VK_F3]) then
begin
rbSemua.Checked := True;
end;
end;
procedure TfraDOKring.sgLookupKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
IsStop := False;
if ((Key = VK_UP) or (Key = 33)) and (cxGridView.DataController.RecNo = 1) then
begin
edNama.SetFocus;
edNama.SelectAll;
Exit;
end
else
if ((Key = VK_DOWN) or (Key = 34)) and (cxGridView.DataController.RecNo = (cxGridView.DataController.RowCount-1)) then
begin
edNama.SetFocus;
edNama.SelectAll;
Exit;
end
else
if Key = VK_F5 then
begin
edNama.SetFocus;
edNama.SelectAll;
end
else if Key in [VK_ESCAPE] then
begin
Self.Visible := False;
with (Self.Parent as TfrmTransaksiKring) do
begin
cxTransaksi.Visible := True;
pnlFooter.Visible := True;
edNomorDO.SetFocus;
edNomorDO.SelectAll;
end;
end
else if Key = VK_RETURN then
begin
IsStop := True;
cxGridViewDblClick(Sender);
end
else if Key in [VK_MULTIPLY,Ord('*')] then
begin
//IsStop := True;
end;
end;
end.
|
{***************************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 2000-2001 Borland Software Corporation }
{ }
{ Русификация: 2001-02 Polaris Software }
{ http://polesoft.da.ru }
{***************************************************************}
unit SvrInfoConst;
interface
resourcestring
sFileStatus = 'Статус файл:';
sFound = 'Найден';
sNotFound = 'Не найден';
{$IFNDEF VER140}
sMissingProgID = 'Отсутствует ProgID';
{$ELSE}
sMissingClsID = 'Отсутствует ClassID';
{$ENDIF}
sGo = 'Пуск';
implementation
end.
|
(**
Предназначение : Форма для правки печати НН с определенными видом источника(OIL_NN_CAUSE).
Даеться выбор способа расчета НДС, типа товара, и схемы печати...
вызов этой формы производиться из таксбила процедурой EditCause(), собствено в тот же
момент и беруться значения для редактируемых полей.
По умолчанию форму редактировать нельзя возможность открываеться при запуска программы с
ключем @EditKey
Создана в ноябре 2005 года.
*)
unit TaxBillCause;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, DBAccess, Ora, Grids, DBGridEh, MemDS, StdCtrls, Buttons, ExtCtrls,
uCommonForm,uOilQuery,uOilStoredProc;
type
TTaxBillCauseForm = class(TCommonForm)
q: TOilQuery;
dbg: TDBGridEh;
ds: TOraDataSource;
qID: TFloatField;
qNAME_: TStringField;
qCOMMENT_: TStringField;
qHIDE: TStringField;
qSCHEME: TFloatField;
qTOVAR_TYPE: TFloatField;
qNDS_CALC_ORIENTATION: TFloatField;
pBtn: TPanel;
bbOk: TBitBtn;
bbCancel: TBitBtn;
qDECIMAL_COUNT: TFloatField;
qDECIMAL_PRICE: TFloatField;
procedure FormShow(Sender: TObject);
procedure bbOkClick(Sender: TObject);
procedure bbCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure dbgColEnter(Sender: TObject);
procedure dbgCellClick(Column: TColumnEh);
private
{ Private declarations }
public
{ Public declarations }
end;
var
TaxBillCauseForm: TTaxBillCauseForm;
implementation
uses
UDbFunc,OilStd,Main;
const
EditKey='CAUSEEDIT';
{$R *.DFM}
procedure TTaxBillCauseForm.FormShow(Sender: TObject);
var
CurField:integer;
begin
try
q.Close;
StartSQLOra;
_OpenQueryOra(q);
finally
if not(SysParamExists(EditKey)) then
begin
for CurField:=0 to q.Fields.Count-1 do
q.Fields[CurField].ReadOnly:=True;
bbOk.Visible:=False;
end;
end;
q.Edit;
end;
procedure TTaxBillCauseForm.bbOkClick(Sender: TObject);
begin
q.Post;
CommitSQLOra;
Self.ModalResult:=mrOk;
end;
procedure TTaxBillCauseForm.bbCancelClick(Sender: TObject);
begin
RollbackSQLOra;
Self.ModalResult:=mrCancel;
end;
procedure TTaxBillCauseForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
q.Close;
end;
procedure TTaxBillCauseForm.dbgColEnter(Sender: TObject);
begin
q.Edit;
end;
procedure TTaxBillCauseForm.dbgCellClick(Column: TColumnEh);
begin
q.Edit;
end;
end.
|
unit Interfaces.Goal;
interface
uses
System.Classes,
System.Types,
Vcl.ExtCtrls;
type
IGoal = Interface(IInterface)
['{D41B5854-54B2-43B5-93BA-5BE559A2FB4C}']
function Position(const Value: TPoint): IGoal; overload;
function Position: TPoint; overload;
function Owner(const Value: TGridPanel): IGoal; overload;
function Owner: TGridPanel; overload;
function CreateImages: IGoal;
End;
implementation
end.
|
unit AST.Lexer.Delphi;
interface
{$i compilers.inc}
uses AST.Lexer, SysUtils, StrUtils, Types, Classes, AST.Parser.Errors;
type
TTokenID = (
token_unknown {= -1}, // unknown token
token_eof {= 0}, // end of file
token_identifier, // some id
token_id_or_keyword, // ambiguous token: id or keyword
token_numbersign, // #
token_semicolon, // ;
token_colon, // :
token_assign, // :=
token_equal, // =
token_above, // >
token_aboveorequal, // >=
token_less, // <
token_lessorequal, // <=
token_notequal, // <>
token_period, // ..
token_exclamation, // !
token_question, // ?
token_plus, // +
token_minus, // -
token_asterisk, // *
token_slash, // /
token_caret, // ^
token_address, // @
token_ampersand, // &
token_coma, // ,
token_dot, // .
token_openround, // (
token_closeround, // )
token_openblock, // [
token_closeblock, // ]
token_openfigure, // {
token_closefigure, // }
token_quote, // '
token_openround_asteriks,
token_closeround_asteriks,
token_at, // keyword: at
token_absolute, // keyword: absolute
token_abstract, // keyword: abstract
token_aling, // keyword: align
token_asm, // keyword: asm
token_stdcall, // keyword: stdcall
token_fastcall, // keyword: fastcall
token_cdecl, // keyword: cdecl
token_unit, // keyword: unit
token_uses, // keyword: uses
token_program, // keyword: program
token_library, // keyword: library
token_export, // keyword: export
token_exports, // keyword: exports
token_external, // keyword: extern
token_name, // keyword: name
token_interface, // keyword: interface
token_implementation, // keyword: implementation
token_implement, // keyword: implementation
token_initialization, // keyword: initialization
token_finalization, // keyword: finalization
token_begin, // keyword: begin
token_end, // keyword: end
token_var, // keyword: var
token_out, // keyword: out
token_const, // keyword: const
token_procedure, // keyword: procedure
token_function, // keyword: function
token_overload, // keyword: overload
token_override, // keyword: override
token_type, // keyword: type
token_class, // keyword: class
token_record, // keyword: record
token_packed, // keyword: packed
token_package, // keyword: package
token_set, // keyword: set
token_sealed, // keyword: sealed
token_array, // keyword: array
token_if, // keyword: if
token_in, // keyword: in
//token_index, // keyword: index
token_inline, // keyword: inline
token_is, // keyword: is
token_then, // keyword: if
token_else, // keyword: else
token_forward, // keyword: forward
token_helper, // keyword: helper
// made as built-in procedures
// token_continue, // keyword: continue
// token_break, // keyword: break
token_not, // keyword: not
token_and, // keyword: and
token_or, // keyword: or
token_xor, // keyword: xor
token_div, // keyword: div
token_mod, // keyword: mod
token_shl, // keyword: shl
token_shr, // keyword: shr
token_as, // keyword: as
token_for, // keyword: for
token_to, // keyword: to
token_downto, // keyword: downto
token_do, // keyword: do
token_deprecated, // keyword: depricated
token_while, // keyword: while
token_weak, // keyword: weak
token_reference, // keyword: reference
token_repeat, // keyword: repeat
token_reintroduce, // keyword: reintroduce
token_until, // keyword: until
token_with, // keyword: until
token_case, // keyword: case
token_of, // keyword: of
token_on, // keyword: on
token_object, // keyword: object
token_operator, // keyword: operator
token_try, // keyword: try
token_final, // keyword: final
token_finally, // keyword: finally
token_except, // keyword: except
token_raise, // keyword: raise
token_strict, // keyword: strict
token_property, // keyword: property
token_private, // keyword: private
token_protected, // keyword: protected
token_public, // keyword: public
token_published, // keyword: published
token_platform, // keyword: platform
token_read, // keyword: read
token_write, // keyword: write
token_inherited, // keyword: inherited
token_virtual, // keyword: virtual
token_dynamic, // keyword: dynamic
token_delayed, // keyword: delayed
token_static, // keyword: static
token_constructor, // keyword: constructor
token_destructor, // keyword: destructor
token_default, // keyword: default
token_varargs, // keyword: varargs
token_threadvar, // keyword: threadvar
token_label, // keyword: label
token_goto, // keyword: goto
token_resourcestring, // keyword: resourcestring
token_cond_define, // {$DEFINE...
token_cond_else, // {$ELSE...
token_cond_else_if, // {$ELSEIF (condition)}
token_cond_end, // {$END... / {$IFEND... / {$ENDIF...
token_cond_include, // {$INCLUDE
token_cond_undefine, // {$UNDEFINE
token_cond_ifdef, // {$IFDEF
token_cond_ifndef, // {$IFNDEF
token_cond_if, // {$IF...
token_cond_ifopt, // {$IFOPT...
token_cond_message, // {$MESSAGE...
token_cond_any
);
TDelphiLexer = class(TGenericLexer)
private
fOriginalToken: string;
protected
procedure ParseChainedString;
procedure ParseCharCodeSymbol;
public
constructor Create(const Source: string); override;
function NextToken: TTokenID;
function TokenLexem(TokenID: TTokenID): string;
procedure RegisterToken(const Token: string; TokenID: TTokenID; const TokenCaption:
string; TokenType: TTokenType = ttToken); overload;
procedure RegisterToken(const Token: string; TokenID: TTokenID;
Priority: TTokenClass = TTokenClass.StrongKeyword); overload;
procedure ReadCurrIdentifier(var Identifier: TIdentifier); inline;
procedure ReadNextIdentifier(var Identifier: TIdentifier); inline;
procedure MatchToken(ActualToken, ExpectedToken: TTokenID); inline;
procedure MatchNextToken(ExpectedToken: TTokenID); inline;
function TokenCanBeID(TokenID: TTokenID): Boolean; inline;
property OriginalToken: string read fOriginalToken;
end;
implementation
uses AST.Delphi.Errors, AST.Parser.Utils;
{ TDelphiParser }
function TDelphiLexer.TokenCanBeID(TokenID: TTokenID): Boolean;
begin
Result := (TokenID = token_identifier) or (CurToken.TokenClass <> TTokenClass.StrongKeyword);
end;
procedure TDelphiLexer.ReadCurrIdentifier(var Identifier: TIdentifier);
begin
Identifier.Name := OriginalToken;
Identifier.TextPosition := Position;
end;
procedure TDelphiLexer.ReadNextIdentifier(var Identifier: TIdentifier);
begin
if NextToken = token_Identifier then begin
Identifier.Name := OriginalToken;
Identifier.TextPosition := Position;
end else
AbortWork(sIdExpectedButFoundFmt, [TokenLexem(TTokenID(CurrentTokenID))], PrevPosition);
end;
procedure TDelphiLexer.MatchToken(ActualToken, ExpectedToken: TTokenID);
begin
if ActualToken <> ExpectedToken then
AbortWork(sExpected, [UpperCase(TokenLexem(ExpectedToken))], PrevPosition);
end;
procedure TDelphiLexer.MatchNextToken(ExpectedToken: TTokenID);
begin
if TTokenID(GetNextTokenId()) <> ExpectedToken then
AbortWork(sExpected, [UpperCase(TokenLexem(ExpectedToken))], PrevPosition);
end;
function CharsToStr(const Str: string): string;
var
Chars: TStringDynArray;
begin
Result := '';
Chars := SplitString(Str, '#');
if Chars[0] = '' then
Delete(Chars, 0, 1);
// this is a string
if Length(Chars) > 0 then
begin
SetLength(Result, Length(Chars));
for var i := 0 to Length(Chars) - 1 do
Result[Low(string) + i] := Char(StrToInt(Chars[i]));
end;
end;
function TDelphiLexer.NextToken: TTokenID;
begin
Result := TTokenID(GetNextTokenId());
case Result of
token_identifier: fOriginalToken := CurrentToken;
token_ampersand: begin
if not GetNextCharIsSeparator then
begin
Result := TTokenID(GetNextTokenId());
fOriginalToken := TokenLexem(Result);
fCurrentTokenID := ord(token_identifier);
Result := token_identifier;
end;
end;
end;
if CurToken.TokenID = ord(token_quote) then
ParseChainedString()
else
if CurToken.TokenID = ord(token_numbersign) then
begin
ParseCharCodeSymbol();
end;
end;
procedure TDelphiLexer.ParseChainedString;
var
Token: PCharToken;
begin
while True do
begin
Token := GetNextToken();
if Token.TokenID = ord(token_numbersign) then
begin
GetNextTokenId();
fOriginalToken := fOriginalToken + CharsToStr(CurrentToken);
end else
if Token.TokenID = ord(token_quote) then
begin
GetNextTokenId();
fOriginalToken := fOriginalToken + CurrentToken;
end else
break;
end;
end;
procedure TDelphiLexer.ParseCharCodeSymbol;
var
HexStr: string;
begin
if Length(fOriginalToken) > 1 then
begin
fOriginalToken := CharsToStr(fOriginalToken);
ParseChainedString();
end else begin
if GetNextChar() = '$' then
begin
GetNextTokenId();
SetIdentifireType(TIdentifierType.itCharCodes);
HexStr := IntToStr(HexToInt32(CurrentToken));
fCurrentToken := fOriginalToken + HexStr;
end;
end;
end;
procedure TDelphiLexer.RegisterToken(const Token: string; TokenID: TTokenID; const TokenCaption: string; TokenType: TTokenType);
begin
inherited RegisterToken(Token, Integer(TokenID), TokenType, TTokenClass.StrongKeyword, TokenCaption);
end;
procedure TDelphiLexer.RegisterToken(const Token: string; TokenID: TTokenID; Priority: TTokenClass);
begin
inherited RegisterToken(Token, Integer(TokenID), ttToken, Priority, Token);
end;
function TDelphiLexer.TokenLexem(TokenID: TTokenID): string;
begin
Result := inherited TokenLexem(Integer(TokenID));
end;
constructor TDelphiLexer.Create(const Source: string);
begin
inherited Create(Source);
IdentifireID := ord(token_identifier);
EofID := ord(token_eof);
AmbiguousId := ord(token_id_or_keyword);
TokenCaptions.AddObject('end of file', TObject(token_eof));
TokenCaptions.AddObject('identifier', TObject(token_identifier));
SeparatorChars := '#$ '''#9#10#13'%^&*@()+-{}[]\/,.;:<>=~!?';
RegisterToken('#', token_NumberSign, '', ttCharCode);
RegisterToken('$', token_Unknown, '', ttHexPrefix);
RegisterToken('%', token_Unknown, '', ttBinPrefix);
RegisterToken(' ', token_Unknown, '', ttOmited);
RegisterToken(#9, token_Unknown, '', ttOmited);
RegisterToken(#10, token_Unknown, '', ttNewLine);
RegisterToken(#13#10, token_Unknown, '', ttNewLine);
RegisterToken(#13, token_Unknown, '', ttOmited);
RegisterToken('''', token_quote, 'single quote', ttSingleQuote);
RegisterToken('"', token_unknown, 'double quote', ttDoubleQuote);
RegisterToken('//', token_unknown, '', ttOneLineRem);
RegisterToken(';', token_semicolon, 'semicolon');
RegisterToken(',', token_coma, 'coma');
RegisterToken(':', token_colon, 'colon');
RegisterToken('=', token_equal, 'equal');
RegisterToken('>', token_above);
RegisterToken('>=', token_aboveorequal);
RegisterToken('<', token_less);
RegisterToken('<=', token_lessorequal);
RegisterToken('<>', token_notequal);
RegisterToken('.', token_dot, 'dot', ttToken);
RegisterToken('..', token_period, 'period');
RegisterToken('(', token_openround, 'open round');
RegisterToken(')', token_closeround, 'close round');
RegisterToken('[', token_openblock);
RegisterToken(']', token_closeblock);
RegisterToken('{', token_openfigure);
RegisterToken('}', token_closefigure);
RegisterToken('+', token_plus, 'plus');
RegisterToken('-', token_minus, 'minus');
RegisterToken('!', token_exclamation, 'exclamation');
RegisterToken('?', token_question, 'question');
RegisterToken('*', token_asterisk, 'asterisk');
RegisterToken('/', token_slash);
RegisterToken('^', token_caret);
RegisterToken('@', token_address);
RegisterToken('&', token_ampersand);
RegisterToken(':=', token_assign);
RegisterToken('at', token_at, TTokenClass.AmbiguousPriorityIdentifier);
RegisterToken('absolute', token_absolute, TTokenClass.AmbiguousPriorityKeyword);
RegisterToken('abstract', token_abstract);
RegisterToken('align', token_aling, TTokenClass.AmbiguousPriorityIdentifier);
RegisterToken('as', token_as);
RegisterToken('asm', token_asm);
RegisterToken('and', token_and);
RegisterToken('array', token_array);
RegisterToken('begin', token_begin);
//RegisterToken('break', token_break);
RegisterToken('case', token_case);
RegisterToken('cdecl', token_cdecl);
RegisterToken('const', token_const);
RegisterToken('constructor', token_constructor);
//RegisterToken('continue', token_continue);
RegisterToken('class', token_class);
RegisterToken('do', token_do);
RegisterToken('downto', token_downto);
RegisterToken('div', token_div);
RegisterToken('destructor', token_destructor);
RegisterToken('deprecated', token_deprecated);
RegisterToken('default', token_default, TTokenClass.AmbiguousPriorityIdentifier);
RegisterToken('dynamic', token_dynamic);
RegisterToken('delayed', token_delayed);
RegisterToken('end', token_end);
RegisterToken('else', token_else);
RegisterToken('except', token_except);
RegisterToken('export', token_export);
RegisterToken('exports', token_exports);
RegisterToken('external', token_external);
RegisterToken('function', token_Function);
RegisterToken('for', token_for);
RegisterToken('forward', token_forward);
RegisterToken('final', token_final);
RegisterToken('finally', token_finally);
RegisterToken('finalization', token_finalization);
RegisterToken('fastcall', token_fastcall);
RegisterToken('goto', token_goto);
RegisterToken('if', token_if);
RegisterToken('is', token_is);
RegisterToken('in', token_in);
//RegisterToken('index', token_index);
RegisterToken('interface', token_Interface);
RegisterToken('inherited', token_inherited);
RegisterToken('inline', token_inline);
RegisterToken('initialization', token_initialization);
RegisterToken('implementation', token_Implementation);
RegisterToken('implement', token_implement);
RegisterToken('library', token_library);
RegisterToken('label', token_label);
RegisterToken('mod', token_mod);
RegisterToken('not', token_not);
RegisterToken('name', token_name, TTokenClass.AmbiguousPriorityIdentifier);
RegisterToken('object', token_object);
RegisterToken('of', token_of);
RegisterToken('on', token_on);
RegisterToken('or', token_or);
RegisterToken('out', token_out, TTokenClass.AmbiguousPriorityIdentifier);
RegisterToken('override', token_override);
RegisterToken('overload', token_overload);
RegisterToken('operator', token_operator, TTokenClass.AmbiguousPriorityKeyword);
RegisterToken('package', token_package, TTokenClass.AmbiguousPriorityIdentifier);
RegisterToken('procedure', token_procedure);
RegisterToken('program', token_program);
RegisterToken('property', token_property);
RegisterToken('protected', token_protected);
RegisterToken('program', token_program);
RegisterToken('private', token_private);
RegisterToken('public', token_public);
RegisterToken('published', token_published);
RegisterToken('packed', token_packed);
RegisterToken('platform', token_platform, TTokenClass.Ambiguous);
RegisterToken('raise', token_raise);
RegisterToken('read', token_read, TTokenClass.AmbiguousPriorityKeyword);
RegisterToken('record', token_record);
RegisterToken('reference', token_reference, TTokenClass.Ambiguous);
RegisterToken('repeat', token_repeat);
RegisterToken('resourcestring', token_resourcestring);
RegisterToken('reintroduce', token_reintroduce);
RegisterToken('set', token_set);
RegisterToken('sealed', token_sealed);
RegisterToken('shl', token_shl);
RegisterToken('shr', token_shr);
RegisterToken('static', token_static);
RegisterToken('strict', token_strict);
RegisterToken('stdcall', token_stdcall);
RegisterToken('then', token_then);
RegisterToken('to', token_to);
RegisterToken('try', token_try);
RegisterToken('threadvar', token_threadvar);
RegisterToken('type', token_type);
RegisterToken('helper', token_helper);
RegisterToken('until', token_until);
RegisterToken('unit', token_unit);
RegisterToken('uses', token_uses);
RegisterToken('var', token_var);
RegisterToken('varargs', token_varargs);
RegisterToken('virtual', token_virtual);
RegisterToken('weak', token_weak);
RegisterToken('with', token_with);
RegisterToken('while', token_while);
RegisterToken('write', token_write, TTokenClass.AmbiguousPriorityKeyword);
RegisterToken('xor', token_xor);
RegisterRemToken('{', '}', ord(token_openfigure), Ord(token_closefigure));
RegisterRemToken('(*', '*)', ord(token_openround_asteriks), Ord(token_closeround_asteriks));
RegisterToken('{$DEFINE', token_cond_define);
RegisterToken('{$UNDEFINE', token_cond_undefine);
RegisterToken('{$IFDEF', token_cond_ifdef);
RegisterToken('{$IFNDEF', token_cond_ifndef);
RegisterToken('{$IF', token_cond_if);
RegisterToken('{$ELSE', token_cond_else);
RegisterToken('{$ELSEIF', token_cond_else_if);
RegisterToken('{$ENDIF', token_cond_end);
RegisterToken('{$IFEND}', token_cond_end);
RegisterToken('{$IFOPT', token_cond_ifopt);
RegisterToken('{$MESSAGE', token_cond_message);
RegisterToken('{$INCLUDE', token_cond_include);
RegisterToken('{$I', token_cond_include);
RegisterToken('{$', token_cond_any);
end;
end.
|
unit uFrmAjuste;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Mask, DXPCurrencyEdit, RxToolEdit, RxCurrEdit,
Spin;
type
TFrmAjuste = class(TForm)
Panel1: TPanel;
lblDescricaoProduto: TLabel;
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
Label3: TLabel;
Label5: TLabel;
cedPrecoUnitario: TCurrencyEdit;
cedDescValor: TCurrencyEdit;
cedDescPercentual: TCurrencyEdit;
cedPrecoTotal: TCurrencyEdit;
sedQuantidade: TSpinEdit;
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure cedDescValorExit(Sender: TObject);
procedure cedDescPercentualExit(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure sedQuantidadeChange(Sender: TObject);
private
{ Private declarations }
procedure CalcularValor;
public
{ Public declarations }
DescontoMaximoValor, DescontoMaximoPercentual: Currency;
end;
var
FrmAjuste: TFrmAjuste;
implementation
uses MensagensUtils;
{$R *.dfm}
procedure TFrmAjuste.CalcularValor;
function Total: Currency;
begin
Result := cedPrecoUnitario.Value * sedQuantidade.Value;
end;
begin
if (cedDescValor.Value = 0) then
cedPrecoTotal.Value := Total
else
cedPrecoTotal.Value := Total - cedDescValor.Value;
if (cedDescPercentual.Value <> 0) then
cedPrecoTotal.Value := cedPrecoTotal.Value - (cedPrecoTotal.Value * (cedDescPercentual.Value / 100));
end;
procedure TFrmAjuste.cedDescPercentualExit(Sender: TObject);
begin
if (DescontoMaximoPercentual > 0) and (cedDescPercentual.Value > DescontoMaximoPercentual) then
begin
Atencao('Desconto máximo permitido: '+FormatCurr(',0.00', DescontoMaximoPercentual));
cedDescPercentual.Value := DescontoMaximoPercentual;
end;
CalcularValor;
end;
procedure TFrmAjuste.cedDescValorExit(Sender: TObject);
begin
if (DescontoMaximoValor * sedQuantidade.Value > 0) and (cedDescValor.Value > DescontoMaximoValor * sedQuantidade.Value) then
begin
Atencao('Desconto máximo permitido: '+FormatCurr(',0.00', DescontoMaximoValor * sedQuantidade.Value));
cedDescValor.Value := DescontoMaximoValor;
end;
CalcularValor;
end;
procedure TFrmAjuste.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case Key of
VK_ESCAPE: Self.Close;
end;
end;
procedure TFrmAjuste.FormKeyPress(Sender: TObject; var Key: Char);
begin
if (Ord(Key) = 13) then
begin
if (Self.ActiveControl = sedQuantidade) then
cedDescValor.SetFocus
else if (Self.ActiveControl = cedDescValor) then
cedDescPercentual.SetFocus
else if (Self.ActiveControl = cedDescPercentual) then
cedPrecoTotal.SetFocus
else if (Self.ActiveControl = cedPrecoTotal) then
Self.Close;
end;
end;
procedure TFrmAjuste.sedQuantidadeChange(Sender: TObject);
begin
cedPrecoTotal.Value := sedQuantidade.Value * cedPrecoUnitario.Value;
end;
end.
|
unit Misc;
interface
uses Classes, ActiveX, SysUtils, DirectShow9;
function FindFilter(graph: IGraphBuilder; iid: TGUID): IBaseFilter;
function isRomanDigits(const s: String): Boolean;
function isLatinWord(const s: String): Boolean;
function ConvertStrTimeToMilliseconds(const s: String;
const delimiters: String): Integer;
function EscapeHtmlChars(const s: String): String;
function EscapeInvalidChars(const s: String): String;
//deprecated
type
TPinItem = class
Pin: IPin;
MediaType: _AMMediaType;
end;
TPinCollector = class
private
List: TList;
public
constructor Create;
destructor Destroy; override;
function Add(PinItem: TPinItem): Integer;
procedure Delete(Index: Integer);
function Get(Index: Integer): TPinItem;
procedure Put(Index: Integer; Item: TPinItem);
procedure Clear;
property Items[Index: Integer]: TPinItem read Get write Put; default;
function Find(Pin: IPin): Integer;
end;
procedure ExplodeToWords(s: string; ss: TStringList);
procedure ExplodeToWordsOnlyLetters(s: String; ss: TStringList);
implementation
uses Constants;
procedure ExplodeToWordsOnlyLetters(s: String; ss: TStringList);
const
SEPARATOR = ' =~!@#$%^&*()_+'#9'|\?/>.<,][{}:;"';
var i, j: Integer;
w: String;
bFound: Boolean;
begin
w := '';
for i := 1 to Length(s) do
begin
bFound := False;
for j := 1 to Length(SEPARATOR) do
begin
if s[i] = SEPARATOR[j] then
begin
bFound := True;
Break;
end;
end;
if (bFound) then
begin
if (w <> '') then
begin
ss.Add(w);
w := '';
end;
end else
w := w + s[i];
end;
end;
procedure ExplodeToWords(s: String; ss: TStringList);
const
SEPARATOR = ' =~!@#$%^&*()_+'#9'|\?/>.<,][{}:;"';
var i, j: Integer;
w: String;
bFound: Boolean;
begin
w := '';
for i := 1 to Length(s) do
begin
{bFound := False;
for j := 1 to Length(SEPARATOR) do
begin
if s[i] = SEPARATOR[j] then
begin
bFound := True;
Break;
end;
end;}
if ({bFound} s[i] = #$20) then
begin
if (w <> '') then
begin
{if (s[i] <> '"') then
ss.Add(w + s[i])
else
ss.Add(w + '\"');}
ss.Add(w);
w := '';
end;
end else
begin
if (s[i] <> '"') then
w := w + s[i]
else
w := w + '\"';
end;
end;
end;
function EscapeInvalidChars(const s: String): String;
const
VALID = '`-=~!@#$%^&*()_+'#9'|\?/>.<,][{}:;"''';
var
i, j: Integer;
begin
Result := '';
for i := 1 to Length(s) do
begin
if (s[i] in [' ', 'a'..'z']) then
Result := Result + s[i]
else if (s[i] in ['A'..'Z']) then
Result := Result + s[i]
else if (s[i] in ['0'..'9']) then
Result := Result + s[i]
else if (s[i] in ['À'..'ß']) then
Result := Result + s[i]
else if (s[i] in ['à'..'ÿ']) then
Result := Result + s[i];
for j := 1 to Length(VALID) do
begin
if s[i] = VALID[j] then
begin
Result := Result + s[i];
Break;
end;
end;
end;
end;
function findFilter(graph: IGraphBuilder; iid: TGUID): IBaseFilter;
var
vobfil: IBaseFilter;
pEnum: IEnumFilters;
hr: HRESULT;
classid: TGUID;
begin
Result := nil;
//display vobsub filter property page
try
graph.EnumFilters(pEnum);
except
Exit;
end;
vobfil := nil;
//enum all filters in the graph
if (pEnum <> nil) then
begin
while SUCCEEDED(pEnum.Next(1, vobfil, nil)) do
begin
if nil = vobfil then
Break;
if SUCCEEDED(vobfil.GetClassID(classid)) then
begin
if IsEqualGUID(classid, iid) then
begin
Result := vobfil;
Exit;
end;
end;
end;
end;
end;
function isLatinWord(const s: String): Boolean;
var
i: Integer;
begin
for i := 1 to Length(s) do
begin
if NOT (s[i] in LATIN_WORD_LETTERS) then
begin
Result := False;
Exit;
end;
end;
Result := True;
end;
function isRomanDigits(const s: String): Boolean;
var
i: Integer;
begin
for i := 1 to Length(s) do
begin
if NOT (s[i] in ROME_DIGITS) then
begin
Result := False;
Exit;
end;
end;
Result := True;
end;
function ConvertStrTimeToMilliseconds(const s: String;
const delimiters: String): Integer;
var
times: array[1..4] of Integer;
dindex, i: Integer;
t: String;
begin
times[1] := 0;
times[2] := 0;
times[3] := 0;
times[4] := 0;
Result := -1;
dindex := 1;
i := 0;
t := '';
while dindex <= Length(delimiters) do
begin
Inc(i);
if s[i] <> delimiters[dindex] then
begin
t := t + s[i];
end else
begin
times[dindex] := StrToInt(Trim(t));
Inc(dindex);
t := '';
end;
end;
t := Copy(s, i + 1, Length(s));
times[4] := StrToInt(Trim(t));
Result := times[1] * 3600 * 1000 + times[2] * 60 * 1000 + times[3] * 1000 +
times[4];
end;
function EscapeHtmlChars(const s: String): String;
var
i: Integer;
begin
Result := '';
for i := 1 to Length(s) do
begin
case s[i] of
' ': Result := Result + ' ';
'"': Result := Result + '"';
'&': Result := Result + '&';
'<': Result := Result + '<';
'>': Result := Result + '>';
else
Result := Result + s[i];
end;
end;
end;
{ TPinCollector }
function TPinCollector.Add(PinItem: TPinItem): Integer;
begin
Result := List.Add(PinItem)
end;
procedure TPinCollector.Clear;
var
i: Integer;
begin
for i := 0 to List.Count - 1 do
begin
TPinItem(List[i]).Free;
List[i] := nil;
end;
List.Clear;
end;
constructor TPinCollector.Create;
begin
List := TList.Create;
end;
procedure TPinCollector.Delete(Index: Integer);
begin
TPinItem(List[Index]).Free;
List.Delete(Index);
end;
destructor TPinCollector.Destroy;
begin
try
Clear;
finally
List.Free;
inherited;
end;
end;
function TPinCollector.Find(Pin: IPin): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to List.Count - 1 do
if Self[i].Pin = Pin then
begin
Result := i;
Break;
end;
end;
function TPinCollector.Get(Index: Integer): TPinItem;
begin
Result := List[Index];
end;
procedure TPinCollector.Put(Index: Integer; Item: TPinItem);
begin
if (List[Index] <> Item) then
begin
TPinItem(List[Index]).Free;
List[Index] := Item;
end;
end;
end.
|
unit VoxelView;
interface
uses BasicDataTypes, BasicVXLSETypes, BasicFunctions, Voxel, BasicConstants;
type
T2DVoxelView = class
private
Orient: EVoxelViewOrient;
Dir: EVoxelViewDir;
swapX, swapY, swapZ: boolean; // are these inversed for viewing?
// Constructors and Destructors
procedure CreateCanvas;
procedure Clear;
procedure CalcSwapXYZ;
public
Foreground, // the Depth in Canvas[] that is the active slice
Width, Height: Integer;
Canvas: {packed} array of {packed} array of TVoxelViewCell;
Voxel: TVoxelSection; // owner
// Constructors and Destructors
constructor Create(Owner: TVoxelSection; o: EVoxelViewOrient; d: EVoxelViewDir);
destructor Destroy; override;
procedure Reset;
// Gets
function getViewNameIdx: Integer;
function getDir: EVoxelViewDir;
function getOrient: EVoxelViewOrient;
procedure TranslateClick(i, j: Integer; var X, Y, Z: Integer);
procedure getPhysicalCursorCoords(var X, Y: integer);
// Sets
procedure setDir(newdir: EVoxelViewDir);
procedure setVoxelSection(const _Section: TVoxelSection);
// Render
procedure Refresh; // like a paint on the canvas
// Copies
procedure Assign(const _VoxelView : T2DVoxelView);
end;
implementation
// Constructors and Destructors
constructor T2DVoxelView.Create(Owner: TVoxelSection; o: EVoxelViewOrient; d: EVoxelViewDir);
begin
Voxel := Owner;
Orient := o;
Dir := d;
Reset;
end;
destructor T2DVoxelView.Destroy;
var
x : integer;
begin
for x := Low(Canvas) to high(Canvas) do
begin
SetLength(Canvas[x],0);
end;
SetLength(Canvas,0);
finalize(Canvas);
inherited Destroy;
end;
procedure T2DVoxelView.Reset;
begin
Clear;
CreateCanvas;
CalcSwapXYZ;
Refresh;
end;
procedure T2DVoxelView.CreateCanvas;
var
x: Integer;
begin
with Voxel.Tailer do
begin
case Orient of
oriX:
begin
Width := ZSize;
Height := YSize;
end;
oriY:
begin
Width := ZSize;
Height := XSize;
end;
oriZ:
begin
Width := XSize;
Height := YSize;
end;
end;
end;
SetLength(Canvas,Width);
for x := 0 to (Width - 1) do
SetLength(Canvas[x],Height);
//CalcIncs;
end;
procedure T2DVoxelView.Clear;
var
x, y: Integer;
begin
for x := Low(Canvas) to High(Canvas) do
for y := Low(Canvas[x]) to High(Canvas[x]) do
with Canvas[x,y] do
begin
Colour := VTRANSPARENT;
Depth := 0; // far away
end;
end;
procedure T2DVoxelView.CalcSwapXYZ;
var idx: integer;
begin
idx := getViewNameIdx;
case idx of
0:
begin // Right to Left
SwapX := False;
SwapY := True;
SwapZ := False;
end;
1:
begin // Left to Right
SwapX := False;
SwapY := True;
SwapZ := True;
end;
2:
begin // Top to Bottom
SwapX := True;
SwapY := True;
SwapZ := False;
end;
3:
begin // Bottom to Top
SwapX := True;
SwapY := True;
SwapZ := True;
end;
4:
begin // Back to Front
SwapX := True;
SwapY := True;
SwapZ := False;
end;
5:
begin // Front to Back
SwapX := False;
SwapY := True;
SwapZ := False;
end;
end;
end;
// Gets
function T2DVoxelView.getViewNameIdx: Integer;
begin
Result := 0;
case Orient of
oriX: Result := 0;
oriY: Result := 2;
oriZ: Result := 4;
end;
if Dir = dirAway then
Inc(Result);
end;
procedure T2DVoxelView.TranslateClick(i, j: Integer; var X, Y, Z: Integer);
procedure TranslateX;
begin
X := Foreground;
if SwapZ then
Z := Width - 1 - i
else
Z := i;
if SwapY then
Y := Height - 1 - j
else
Y := j;
end;
procedure TranslateY;
begin
if SwapZ then
Z := Width - 1 - i
else
Z := i;
Y := Foreground;
if SwapX then
X := Height - 1 - j
else
X := j;
end;
procedure TranslateZ;
begin
if SwapX then
X := Width - 1 - i
else
X := i;
if SwapY then
Y := Height - 1 - j
else
Y := j;
Z := Foreground;
end;
begin
case Orient of
oriX: TranslateX;
oriY: TranslateY;
oriZ: TranslateZ;
end;
end;
procedure T2DVoxelView.getPhysicalCursorCoords(var X, Y: integer);
procedure TranslateX;
begin
if SwapZ then
X := Width - 1 - Voxel.Z
else
X := Voxel.Z;
if SwapY then
Y := Height - 1 - Voxel.Y
else
Y := Voxel.Y;
end;
procedure TranslateY;
begin
if SwapZ then
X := Width - 1 - Voxel.Z
else
X := Voxel.Z;
if SwapX then
Y := Height - 1 - Voxel.X
else
Y := Voxel.X;
end;
procedure TranslateZ;
begin
if SwapX then
X := Width - 1 - Voxel.X
else
X := Voxel.X;
if SwapY then
Y := Height - 1 - Voxel.Y
else
Y := Voxel.Y;
end;
begin
case Orient of
oriX: TranslateX;
oriY: TranslateY;
oriZ: TranslateZ;
end;
end;
function T2DVoxelView.getDir: EVoxelViewDir;
begin
Result := Dir;
end;
function T2DVoxelView.getOrient: EVoxelViewOrient;
begin
Result := Orient;
end;
// Sets
procedure T2DVoxelView.setDir(newdir: EVoxelViewDir);
begin
Dir := newdir;
CalcSwapXYZ;
Refresh;
end;
procedure T2DVoxelView.setVoxelSection(const _Section: TVoxelSection);
begin
Voxel := _Section;
Reset;
end;
// Render
procedure T2DVoxelView.Refresh;
procedure DrawX;
var
x, y, z, // coords in model
i, j: Integer; // screen coords
v: TVoxelUnpacked;
iFactor, iOp, jFactor, jOp: integer;
begin
Foreground := Voxel.X;
if SwapZ then
begin
iFactor := Width - 1;
iOp := -1;
end
else
begin
iFactor := 0;
iOp := 1;
end;
if SwapY then
begin
jFactor := Height - 1;
jOp := -1;
end
else
begin
jFactor := 0;
jOp := 1;
end;
// increment on the x axis
if Dir = dirTowards then
begin
for z := 0 to (Width - 1) do
for y := 0 to (Height - 1) do
begin
x := Foreground;
Voxel.GetVoxel(x,y,z,v);
// find voxel on the x axis
while not v.Used do
begin
Inc(x);
if x >= Voxel.Tailer.XSize then // range check
Break; // Ok, no voxels ever to show
// get next
Voxel.GetVoxel(x,y,z,v);
end;
// and set the voxel appropriately
i := iFactor + (iOp * z);
j := jFactor + (jOp * y);
with Canvas[i,j] do
begin
Depth := x;
if v.Used then
begin
if voxel.spectrum = ModeNormals then
Colour := v.Normal
else
Colour := v.Colour;
end
else
Colour := VTRANSPARENT; // 256
end;
end;
end
else
begin // Dir = dirAway
for z := 0 to (Width - 1) do
for y := 0 to (Height - 1) do
begin
x := Foreground;
Voxel.GetVoxel(x,y,z,v);
// find voxel on the x axis
while not v.Used do
begin
Dec(x);
if x < 0 then // range check
Break; // Ok, no voxels ever to show
// get next
Voxel.GetVoxel(x,y,z,v);
end;
// and set the voxel appropriately
i := iFactor + (iOp * z);
j := jFactor + (jOp * y);
with Canvas[i,j] do
begin
Depth := x;
if v.Used then
begin
if voxel.spectrum = ModeNormals then
Colour := v.Normal
else
Colour := v.Colour;
end
else
Colour := VTRANSPARENT; // 256
end;
end;
end;
end;
procedure DrawY;
var
x, y, z, // coords in model
i, j: Integer; // screen coords
v: TVoxelUnpacked;
iFactor, iOp, jFactor, jOp: integer;
begin
Foreground := Voxel.Y;
if SwapZ then
begin
iFactor := Width - 1;
iOp := -1;
end
else
begin
iFactor := 0;
iOp := 1;
end;
if SwapX then
begin
jFactor := Height - 1;
jOp := -1;
end
else
begin
jFactor := 0;
jOp := 1;
end;
if Dir = dirTowards then
begin
for z := 0 to (Width - 1) do
for x := 0 to (Height - 1) do
begin
y := Foreground;
Voxel.GetVoxel(x,y,z,v);
// find voxel on the x axis
while not v.Used do
begin
Inc(y);
if y >= Voxel.Tailer.YSize then // range check
Break; // Ok, no voxels ever to show
// get next
Voxel.GetVoxel(x,y,z,v);
end;
// and set the voxel appropriately
i := iFactor + (iOp * z);
j := jFactor + (jOp * x);
with Canvas[i,j] do
begin
Depth := y;
if v.Used then
begin
if voxel.spectrum = ModeNormals then
Colour := v.Normal
else
Colour := v.Colour;
end
else
Colour := VTRANSPARENT; // 256
end;
end;
end
else
begin // Dir = dirAway
for z := 0 to (Width - 1) do
for x := 0 to (Height - 1) do
begin
y := Foreground;
Voxel.GetVoxel(x,y,z,v);
// find voxel on the x axis
while not v.Used do
begin
Dec(y);
if y < 0 then // range check
Break; // Ok, no voxels ever to show
// get next
Voxel.GetVoxel(x,y,z,v);
end;
// and set the voxel appropriately
i := iFactor + (iOp * z);
j := jFactor + (jOp * x);
with Canvas[i,j] do
begin
Depth := y;
if v.Used then
begin
if voxel.spectrum = ModeNormals then
Colour := v.Normal
else
Colour := v.Colour;
end
else
Colour := VTRANSPARENT; // 256
end;
end;
end;
end;
procedure DrawZ;
var
x, y, z, // coords in model
i, j: Integer; // screen coords
v: TVoxelUnpacked;
iFactor, iOp, jFactor, jOp: integer;
begin
Foreground := Voxel.Z;
if SwapX then
begin
iFactor := Width -1;
iOp := -1;
end
else
begin
iFactor := 0;
iOp := 1;
end;
if SwapY then
begin
jFactor := Height - 1;
jOp := -1;
end
else
begin
jFactor := 0;
jOp := 1;
end;
if Dir = dirTowards then
begin
for x := 0 to (Width - 1) do
for y := 0 to (Height - 1) do
begin
z := Foreground;
Voxel.GetVoxel(x,y,z,v);
// find voxel on the x axis
while not v.Used do
begin
Inc(z);
if z >= Voxel.Tailer.ZSize then // range check
Break; // Ok, no voxels ever to show
// get next
Voxel.GetVoxel(x,y,z,v);
end;
// and set the voxel appropriately
i := iFactor + (iOp * x);
j := jFactor + (jOp * y);
with Canvas[i,j] do
begin
Depth := z;
if v.Used then
begin
if voxel.spectrum = ModeNormals then
Colour := v.Normal
else
Colour := v.Colour;
end
else
Colour := VTRANSPARENT; // 256
end;
end;
end
else
begin // Dir = dirAway
for x := 0 to (Width - 1) do
for y := 0 to (Height - 1) do
begin
z := Foreground;
Voxel.GetVoxel(x,y,z,v);
// find voxel on the x axis
while not v.Used do
begin
Dec(z);
if z < 0 then // range check
Break; // Ok, no voxels ever to show
// get next
Voxel.GetVoxel(x,y,z,v);
end;
// and set the voxel appropriately
i := iFactor + (iOp * x);
j := jFactor + (jOp * y);
with Canvas[i,j] do
begin
Depth := z;
if v.Used then
begin
if voxel.spectrum = ModeNormals then
Colour := v.Normal
else
Colour := v.Colour;
end
else
Colour := VTRANSPARENT; // 256
end;
end;
end;
end;
begin
case Orient of
oriX: DrawX;
oriY: DrawY;
oriZ: DrawZ;
end;
end;
// Copies
procedure T2DVoxelView.Assign(const _VoxelView : T2DVoxelView);
var
i,j : integer;
begin
Orient := _VoxelView.Orient;
Dir := _VoxelView.Dir;
swapX := _VoxelView.swapX;
swapY := _VoxelView.swapY;
swapZ := _VoxelView.swapZ;
Foreground := _VoxelView.Foreground;
Width := _VoxelView.Width;
Height := _VoxelView.Height;
Voxel := _VoxelView.Voxel;
SetLength(Canvas,Width);
for i := Low(Canvas) to High(Canvas) do
begin
SetLength(Canvas[i],Height);
for j := Low(Canvas[i]) to High(Canvas[i]) do
begin
Canvas[i,j].Colour := _VoxelView.Canvas[i,j].Colour;
Canvas[i,j].Depth := _VoxelView.Canvas[i,j].Depth;
end;
end;
end;
end.
|
unit CFSplitter;
interface
uses
Windows, Classes, Controls, Graphics, CFControl;
type
CFNaturalNumber = 1..High(Integer);
TCFSplitter = class(TCFCustomControl)
private
FMinSize: CFNaturalNumber;
FMaxSize, FSplit, FNewSize, FOldSize: Integer;
FDownPos: TPoint;
FControl: TControl;
function FindControl: TControl;
procedure UpdateControlSize;
procedure StopSizing;
procedure CalcSplitSize(X, Y: Integer; var NewSize, Split: Integer);
procedure UpdateSize(X, Y: Integer);
protected
procedure DrawControl(ACanvas: TCanvas); override;
function CanResize(var NewWidth, NewHeight: Integer): Boolean; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure RequestAlign; override;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
uses
Forms;
{ TCFSplitter }
procedure TCFSplitter.CalcSplitSize(X, Y: Integer; var NewSize, Split: Integer);
var
S: Integer;
begin
if Align in [alLeft, alRight] then
Split := X - FDownPos.X
else
Split := Y - FDownPos.Y;
S := 0;
case Align of
alLeft: S := FControl.Width + Split;
alRight: S := FControl.Width - Split;
alTop: S := FControl.Height + Split;
alBottom: S := FControl.Height - Split;
end;
NewSize := S;
if S < FMinSize then
NewSize := FMinSize
else
if S > FMaxSize then
NewSize := FMaxSize;
if S <> NewSize then
begin
if Align in [alRight, alBottom] then
S := S - NewSize
else
S := NewSize - S;
Inc(Split, S);
end;
end;
function TCFSplitter.CanResize(var NewWidth, NewHeight: Integer): Boolean;
begin
Result := True;
if NewWidth < 3 then
NewWidth := 3;
if NewHeight < 3 then
NewHeight := 3;
end;
constructor TCFSplitter.Create(AOwner: TComponent);
begin
inherited;
Height := 100;
Align := alLeft;
Width := 6;
end;
procedure TCFSplitter.DrawControl(ACanvas: TCanvas);
const
PointCount = 12;
PointSize = 4;
PointSplit = 8;
procedure DrawLine;
begin
case Align of
alLeft, alRight:
begin
ACanvas.Pen.Color := GLineColor;
ACanvas.MoveTo(0, 0);
ACanvas.LineTo(0, Height);
ACanvas.Pen.Color := GLineColor;
ACanvas.MoveTo(Width - 1, 0);
ACanvas.LineTo(Width - 1, Height);
end;
alTop, alBottom:
begin
ACanvas.Pen.Color := GLineColor;
ACanvas.MoveTo(0, 0);
ACanvas.LineTo(Width, 0);
ACanvas.Pen.Color := GLineColor;
ACanvas.MoveTo(0, Height - 1);
ACanvas.LineTo(Width, Height - 1);
end;
end;
end;
var
vLeft, vTop: Integer;
i: Integer;
begin
inherited DrawControl(ACanvas);
ACanvas.Brush.Color := GBackColor;
ACanvas.FillRect(ClientRect);
if BorderVisible then
DrawLine;
// ΜαΚΎ΅γ
ACanvas.Brush.Color := GBorderColor;
case Align of
alLeft, alRight:
begin
vLeft := (Width - PointSize) div 2;
vTop := PointCount * PointSize + (PointCount - 1) * PointSplit;
vTop := Round((Height - vTop) div 2);
//
for i := 0 to PointCount - 1 do
begin
ACanvas.FillRect(Bounds(vLeft, vTop, PointSize, PointSize));
{ACanvas.Brush.Color := clBtnShadow;
ACanvas.FillRect(Bounds(vLeft + 1, vTop + 1, 1, 1)); }
vTop := vTop + PointSize + PointSplit;
end;
end;
alTop, alBottom:
begin
vLeft := PointCount * PointSize + (PointCount - 1) * PointSplit;
vLeft := (Width - vLeft) div 2;
vTop := Round((Height - PointSize) / 2);
//
for i := 0 to PointCount - 1 do
begin
ACanvas.FillRect(Bounds(vLeft, vTop, PointSize, PointSize));
{ACanvas.Brush.Color := clBtnShadow;
ACanvas.FillRect(Bounds(vLeft + 1, vTop + 1, 1, 1)); }
vLeft := vLeft + PointSize + PointSplit;
end;
end;
end;
end;
function TCFSplitter.FindControl: TControl;
var
P: TPoint;
I: Integer;
R: TRect;
begin
Result := nil;
P := Point(Left, Top);
case Align of
alLeft: Dec(P.X); // if AlignWithMargins then
alRight: Inc(P.X, Width);
alTop: Dec(P.Y);
alBottom: Inc(P.Y, Height);
else
Exit;
end;
for I := 0 to Parent.ControlCount - 1 do
begin
{if Parent.Controls[i] is TCCustomControl then
begin
Result := Parent.Controls[I] as TCCustomControl;}
Result := Parent.Controls[I];
if Result.Visible and Result.Enabled then
begin
R := Result.BoundsRect;
{if Result.AlignWithMargins then
begin
Inc(R.Right, Result.Margins.Right);
Dec(R.Left, Result.Margins.Left);
Inc(R.Bottom, Result.Margins.Bottom);
Dec(R.Top, Result.Margins.Top);
end; }
if (R.Right - R.Left) = 0 then
if Align in [alTop, alLeft] then
Dec(R.Left)
else
Inc(R.Right);
if (R.Bottom - R.Top) = 0 then
if Align in [alTop, alLeft] then
Dec(R.Top)
else
Inc(R.Bottom);
if PtInRect(R, P) then Exit;
end;
//end;
end;
Result := nil;
end;
procedure TCFSplitter.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
I: Integer;
begin
inherited;
if Button = mbLeft then
begin
FControl := FindControl;
FDownPos := Point(X, Y);
if Assigned(FControl) then
begin
if Align in [alLeft, alRight] then
begin
FMaxSize := Parent.ClientWidth - FMinSize;
for I := 0 to Parent.ControlCount - 1 do
with Parent.Controls[I] do
if Visible and (Align in [alLeft, alRight]) then Dec(FMaxSize, Width);
Inc(FMaxSize, FControl.Width);
end
else
begin
FMaxSize := Parent.ClientHeight - FMinSize;
for I := 0 to Parent.ControlCount - 1 do
with Parent.Controls[I] do
if Align in [alTop, alBottom] then Dec(FMaxSize, Height);
Inc(FMaxSize, FControl.Height);
end;
UpdateSize(X, Y);
{with TCustomForm(Self.Parent) do
begin
if ActiveControl <> nil then
begin
FActiveControl := ActiveControl;
FOldKeyDown := TWinControlAccess(FActiveControl).OnKeyDown;
TWinControlAccess(FActiveControl).OnKeyDown := FocusKeyDown;
end;
end;}
end;
end;
end;
procedure TCFSplitter.MouseMove(Shift: TShiftState; X, Y: Integer);
var
vNewSize, vSplit: Integer;
begin
inherited;
if (ssLeft in Shift) and Assigned(FControl) then
begin
CalcSplitSize(X, Y, vNewSize, vSplit);
FNewSize := vNewSize;
FSplit := vSplit;
UpdateControlSize;
end;
end;
procedure TCFSplitter.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
StopSizing;
end;
procedure TCFSplitter.RequestAlign;
begin
inherited;
case Align of
alLeft, alRight: Cursor := crHSplit;
else
Cursor := crVSplit;
end;
end;
procedure TCFSplitter.StopSizing;
begin
if Assigned(FControl) then
FControl := nil;
end;
procedure TCFSplitter.UpdateControlSize;
begin
if FNewSize <> FOldSize then
begin
case Align of
alLeft: FControl.Width := FNewSize;
alTop: FControl.Height := FNewSize;
alRight:
begin
Parent.DisableAlign;
try
FControl.Left := FControl.Left + (FControl.Width - FNewSize);
FControl.Width := FNewSize;
finally
Parent.EnableAlign;
end;
end;
alBottom:
begin
Parent.DisableAlign;
try
FControl.Top := FControl.Top + (FControl.Height - FNewSize);
FControl.Height := FNewSize;
finally
Parent.EnableAlign;
end;
end;
end;
Update;
FOldSize := FNewSize;
end;
end;
procedure TCFSplitter.UpdateSize(X, Y: Integer);
begin
CalcSplitSize(X, Y, FNewSize, FSplit);
end;
end.
|
unit luaParserNode;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, pLuaObject, lua, PasTree;
procedure RegisterExistingNode(L : PLua_State; Name : AnsiString; Node : TPasElement);
procedure PushExistingNode(L : PLua_State; Node : TPasElement);
implementation
uses
pLua;
function GetFileName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
var
itm : TPasElement;
begin
itm := TPasElement(target);
plua_pushstring(l, itm.SourceFilename);
result := 1;
end;
function GetLineNumber(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
var
itm : TPasElement;
begin
itm := TPasElement(target);
lua_pushinteger(l, itm.SourceLinenumber);
result := 1;
end;
function GetFullName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
var
itm : TPasElement;
begin
itm := TPasElement(target);
plua_pushstring(l, itm.FullName);
result := 1;
end;
function GetPathName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
var
itm : TPasElement;
begin
itm := TPasElement(target);
plua_pushstring(l, itm.PathName);
result := 1;
end;
function GetElementTypeName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
var
itm : TPasElement;
begin
itm := TPasElement(target);
plua_pushstring(l, itm.ElementTypeName);
result := 1;
end;
function GetName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
var
itm : TPasElement;
begin
itm := TPasElement(target);
plua_pushstring(l, itm.Name);
result := 1;
end;
function GetClassName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
var
itm : TPasElement;
begin
itm := TPasElement(target);
plua_pushstring(l, itm.ClassName);
result := 1;
end;
function GetParent(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
var
itm : TPasElement;
nfo : PLuaInstanceInfo;
begin
itm := TPasElement(target);
if itm.Parent <> nil then
begin
nfo := plua_GetObjectInfo(l, itm.Parent);
if assigned(nfo) then
plua_PushObject(nfo)
else
lua_pushnil(l);
end
else
lua_pushnil(l);
result := 1;
end;
function GetDeclaration(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
var
itm : TPasElement;
begin
result := 0;
itm := TPasElement(target);
if lua_isboolean(L, paramidxstart) then
plua_pushstring(l, itm.GetDeclaration(lua_toboolean(l, paramidxstart)))
else
plua_pushstring(l, itm.GetDeclaration(true));
result := 1;
end;
function GetDestType(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasPointerType then
PushExistingNode(l, (target as TPasPointerType).DestType)
else if target is TPasAliasType then
PushExistingNode(l, (target as TPasAliasType).DestType)
else
result := 0;
end;
function GetPackageName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasModule then
plua_pushstring(l, (target as TPasModule).PackageName)
else
result := 0;
end;
function GetValue(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasResString then
plua_pushstring(l, (target as TPasResString).Value)
else if target is TPasEnumValue then
lua_pushinteger(l, (target as TPasEnumValue).Value)
else if target is TPasArgument then
plua_pushstring(l, (target as TPasArgument).Value)
else if target is TPasVariable then
plua_pushstring(l, (target as TPasVariable).Value)
else
result := 0;
end;
function GetRangeStart(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasRangeType then
plua_pushstring(l, (target as TPasRangeType).RangeStart)
else
result := 0;
end;
function GetRangeEnd(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasRangeType then
plua_pushstring(l, (target as TPasRangeType).RangeEnd)
else
result := 0;
end;
function GetIndexRange(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasArrayType then
plua_pushstring(l, (target as TPasArrayType).IndexRange)
else
result := 0;
end;
function GetIsPacked(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasArrayType then
lua_pushboolean(l, (target as TPasArrayType).IsPacked)
else if target is TPasRecordType then
lua_pushboolean(l, (target as TPasRecordType).IsPacked)
else if target is TPasClassType then
lua_pushboolean(l, (target as TPasClassType).IsPacked)
else
result := 0;
end;
function GetElType(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasArrayType then
PushExistingNode(l, (target as TPasArrayType).ElType)
else if target is TPasFileType then
PushExistingNode(l, (target as TPasFileType).ElType)
else
result := 0;
end;
function GetIsValueUsed(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasEnumValue then
lua_pushboolean(l, (target as TPasEnumValue).IsValueUsed)
else
result := 0;
end;
function GetAssignedValue(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasEnumValue then
plua_pushstring(l, (target as TPasEnumValue).AssignedValue)
else
result := 0;
end;
function GetGetEnumNames(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
var
idx : Integer;
nl : TStringList;
itm : TPasEnumType;
begin
result := 0;
if target is TPasEnumType then
begin
itm := TPasEnumType(target);
lua_newtable(L);
result := 1;
nl := TStringList.Create;
try
itm.GetEnumNames(nl);
for idx := 0 to nl.Count -1 do
begin
lua_pushinteger(l, idx+1);
plua_pushstring(l, nl[idx]);
lua_settable(L, -3);
end;
finally
nl.Free;
end;
end;
end;
function GetEnumType(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasSetType then
PushExistingNode(l, (target as TPasSetType).EnumType)
else
result := 0;
end;
function GetVariantName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasRecordType then
plua_pushstring(l, (target as TPasRecordType).VariantName)
else
result := 0;
end;
function GetVariantType(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasRecordType then
PushExistingNode(l, (target as TPasRecordType).VariantType)
else
result := 0;
end;
function GetMembers(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasVariant then
PushExistingNode(l, (target as TPasVariant).Members)
else
result := 0;
end;
function GetObjKind(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasClassType then
begin
case (target as TPasClassType).ObjKind of
okObject : plua_pushstring(l, 'Object');
okClass : plua_pushstring(l, 'Class');
okInterface : plua_pushstring(l, 'Interface');
else
result := 0;
end;
end
else
result := 0;
end;
function GetAncestorType(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasClassType then
PushExistingNode(l, (target as TPasClassType).AncestorType)
else
result := 0;
end;
function GetInterfaceGUID(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasClassType then
plua_pushstring(l, (target as TPasClassType).InterfaceGUID)
else
result := 0;
end;
function GetAccess(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasArgument then
begin
case (target as TPasArgument).Access of
argDefault : plua_pushstring(l, 'Default');
argConst : plua_pushstring(l, 'Const');
argVar : plua_pushstring(l, 'Var');
argOut : plua_pushstring(l, 'Out');
else
result := 0;
end;
end
else
result := 0;
end;
function GetArgType(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasArgument then
PushExistingNode(l, (target as TPasArgument).ArgType)
else
result := 0;
end;
function GetIsOfObject(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasProcedureType then
lua_pushboolean(l, (target as TPasProcedureType).IsOfObject)
else
result := 0;
end;
function GetResultType(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasResultElement then
PushExistingNode(l, (target as TPasResultElement).ResultType)
else
result := 0;
end;
function GetResultEl(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasFunctionType then
PushExistingNode(l, (target as TPasFunctionType).ResultEl)
else
result := 0;
end;
function GetRefType(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasTypeRef then
PushExistingNode(l, (target as TPasTypeRef).RefType)
else
result := 0;
end;
function GetVarType(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasVariable then
PushExistingNode(l, (target as TPasVariable).VarType)
else
result := 0;
end;
function GetModifiers(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasVariable then
plua_pushstring(l, (target as TPasVariable).Modifiers)
else
result := 0;
end;
function GetAbsoluteLocation(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
result := 1;
if target is TPasVariable then
plua_pushstring(l, (target as TPasVariable).AbsoluteLocation)
else
result := 0;
end;
function GetIndexValue(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProperty then
plua_pushstring(l, (target as TPasProperty).IndexValue)
else
result := 0;
end;
function GetReadAccessorName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProperty then
plua_pushstring(l, (target as TPasProperty).ReadAccessorName)
else
result := 0;
end;
function GetWriteAccessorName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProperty then
plua_pushstring(l, (target as TPasProperty).WriteAccessorName)
else
result := 0;
end;
function GetStoredAccessorName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProperty then
plua_pushstring(l, (target as TPasProperty).StoredAccessorName)
else
result := 0;
end;
function GetDefaultValue(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProperty then
plua_pushstring(l, (target as TPasProperty).DefaultValue)
else
result := 0;
end;
function GetIsDefault(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProperty then
lua_pushboolean(l, (target as TPasProperty).IsDefault)
else
result := 0;
end;
function GetIsNodefault(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProperty then
lua_pushboolean(l, (target as TPasProperty).IsNodefault)
else
result := 0;
end;
function GetTypeName(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProcedureBase then
plua_pushstring(l, (target as TPasProcedureBase).TypeName)
else
result := 0;
end;
function GetProcType(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProcedure then
PushExistingNode(l, (target as TPasProcedure).ProcType)
else
result := 0;
end;
function GetIsVirtual(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProcedure then
lua_pushboolean(l, (target as TPasProcedure).IsVirtual)
else
result := 0;
end;
function GetIsDynamic(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProcedure then
lua_pushboolean(l, (target as TPasProcedure).IsDynamic)
else
result := 0;
end;
function GetIsAbstract(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProcedure then
lua_pushboolean(l, (target as TPasProcedure).IsAbstract)
else
result := 0;
end;
function GetIsOverride(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProcedure then
lua_pushboolean(l, (target as TPasProcedure).IsOverride)
else
result := 0;
end;
function GetIsOverload(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProcedure then
lua_pushboolean(l, (target as TPasProcedure).IsOverload)
else
result := 0;
end;
function GetIsMessage(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProcedure then
lua_pushboolean(l, (target as TPasProcedure).IsMessage)
else
result := 0;
end;
function GetisReintroduced(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProcedure then
lua_pushboolean(l, (target as TPasProcedure).isReintroduced)
else
result := 0;
end;
function GetisStatic(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
begin
result := 1;
if target is TPasProcedure then
lua_pushboolean(l, (target as TPasProcedure).isStatic)
else
result := 0;
end;
function GetVisibility(target : TObject; l : Plua_State; paramidxstart, paramcount : integer) : integer;
var
itm : TPasElement;
begin
result := 1;
itm := TPasElement(target);
plua_pushstring(l, VisibilityNames[itm.Visibility]);
end;
procedure InitClassInfo;
var
ci : PLuaClassInfo;
begin
ci := ClassTypesList.Add('TPasElement');
plua_AddClassProperty(ci^, 'Visibility', @GetVisibility, nil);
plua_AddClassProperty(ci^, 'SourceFilename', @GetFileName, nil);
plua_AddClassProperty(ci^, 'SourceLinenumber', @GetLineNumber, nil);
plua_AddClassProperty(ci^, 'FullName', @GetFullName, nil);
plua_AddClassProperty(ci^, 'PathName', @GetPathName, nil);
plua_AddClassProperty(ci^, 'ElementTypeName', @GetElementTypeName, nil);
plua_AddClassProperty(ci^, 'Name', @GetName, nil);
plua_AddClassProperty(ci^, 'Parent', @GetParent, nil);
plua_AddClassProperty(ci^, 'ClassName', @GetClassName, nil);
plua_AddClassProperty(ci^, 'DestType', @GetDestType, nil);
plua_AddClassProperty(ci^, 'PackageName', @GetPackageName, nil);
plua_AddClassProperty(ci^, 'Value', @GetValue, nil);
plua_AddClassProperty(ci^, 'RangeStart', @GetRangeStart, nil);
plua_AddClassProperty(ci^, 'RangeEnd', @GetRangeEnd, nil);
plua_AddClassProperty(ci^, 'IndexRange', @GetIndexRange, nil);
plua_AddClassProperty(ci^, 'IsPacked', @GetIsPacked, nil);
plua_AddClassProperty(ci^, 'ElType', @GetElType, nil);
plua_AddClassProperty(ci^, 'IsValueUsed', @GetIsValueUsed, nil);
plua_AddClassProperty(ci^, 'AssignedValue', @GetAssignedValue, nil);
plua_AddClassProperty(ci^, 'EnumType', @GetEnumType, nil);
plua_AddClassProperty(ci^, 'VariantName', @GetVariantName, nil);
plua_AddClassProperty(ci^, 'VariantType', @GetVariantType, nil);
plua_AddClassProperty(ci^, 'Members', @GetMembers, nil);
plua_AddClassProperty(ci^, 'ObjKind', @GetObjKind, nil);
plua_AddClassProperty(ci^, 'AncestorType', @GetAncestorType, nil);
plua_AddClassProperty(ci^, 'InterfaceGUID', @GetInterfaceGUID, nil);
plua_AddClassProperty(ci^, 'Access', @GetAccess, nil);
plua_AddClassProperty(ci^, 'ArgType', @GetArgType, nil);
plua_AddClassProperty(ci^, 'IsOfObject', @GetIsOfObject, nil);
plua_AddClassProperty(ci^, 'ResultType', @GetResultType, nil);
plua_AddClassProperty(ci^, 'ResultEl', @GetResultEl, nil);
plua_AddClassProperty(ci^, 'RefType', @GetRefType, nil);
plua_AddClassProperty(ci^, 'VarType', @GetVarType, nil);
plua_AddClassProperty(ci^, 'Modifiers', @GetModifiers, nil);
plua_AddClassProperty(ci^, 'AbsoluteLocation', @GetAbsoluteLocation, nil);
plua_AddClassProperty(ci^, 'IndexValue', @GetIndexValue, nil);
plua_AddClassProperty(ci^, 'ReadAccessorName', @GetReadAccessorName, nil);
plua_AddClassProperty(ci^, 'WriteAccessorName', @GetWriteAccessorName, nil);
plua_AddClassProperty(ci^, 'StoredAccessorName', @GetStoredAccessorName, nil);
plua_AddClassProperty(ci^, 'DefaultValue', @GetDefaultValue, nil);
plua_AddClassProperty(ci^, 'IsDefault', @GetIsDefault, nil);
plua_AddClassProperty(ci^, 'IsNodefault', @GetIsNodefault, nil);
plua_AddClassProperty(ci^, 'TypeName', @GetTypeName, nil);
plua_AddClassProperty(ci^, 'ProcType', @GetProcType, nil);
plua_AddClassProperty(ci^, 'IsVirtual', @GetIsVirtual, nil);
plua_AddClassProperty(ci^, 'IsDynamic', @GetIsDynamic, nil);
plua_AddClassProperty(ci^, 'IsAbstract', @GetIsAbstract, nil);
plua_AddClassProperty(ci^, 'IsOverride', @GetIsOverride, nil);
plua_AddClassProperty(ci^, 'IsOverload', @GetIsOverload, nil);
plua_AddClassProperty(ci^, 'IsMessage', @GetIsMessage, nil);
plua_AddClassProperty(ci^, 'isReintroduced', @GetisReintroduced, nil);
plua_AddClassProperty(ci^, 'isStatic', @GetisStatic, nil);
plua_AddClassMethod(ci^, 'GetDeclaration', @GetDeclaration);
plua_AddClassMethod(ci^, 'GetGetEnumNames', @GetGetEnumNames);
end;
procedure RegisterExistingNode(L: PLua_State; Name: AnsiString;
Node: TPasElement);
begin
plua_registerExisting(l, Name, Node, ClassTypesList['TPasElement']);
end;
procedure PushExistingNode(L: PLua_State; Node: TPasElement);
begin
plua_pushexisting(l, Node, ClassTypesList['TPasElement']);
end;
initialization
InitClassInfo;
end.
|
unit AsupRegardsCommonReport_PrintDM;
interface
uses
SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase,
frxClass, frxDBSet, frxDesgn, IBase, Forms, Variants,
Controls, FIBQuery, pFIBQuery, pFIBStoredProc, Dialogs, Math,
Asup_LoaderPrintDocs_Types, Asup_LoaderPrintDocs_Proc,
Asup_LoaderPrintDocs_WaitForm, ASUP_LoaderPrintDocs_Consts,
ASUP_LoaderPrintDocs_Messages, qFTools, frxExportHTML, frxExportXLS,
frxExportRTF, frxExportXML;
type
TDM = class(TDataModule)
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
DSetData: TpFIBDataSet;
ReportDsetData: TfrxDBDataset;
DSourceData: TDataSource;
DSetGlobalData: TpFIBDataSet;
ReportDSetGlobalData: TfrxDBDataset;
Designer: TfrxDesigner;
RTFExport: TfrxRTFExport;
HTMLExport: TfrxHTMLExport;
XLSExport: TfrxXLSExport;
Report: TfrxReport;
private
PIdRegards:integer;
PRegardsText:string;
PID_Work_Reason:integer;
public
constructor Create(AOwner:TComponent);reintroduce;
function PrintSpr(AParameter:TSimpleParam):variant;
property IdRegards:Integer read PIdRegards write PIdRegards;
property RegardsText:string read PRegardsText write PRegardsText;
property ID_Work_Reason:integer read PID_Work_Reason write PID_Work_Reason;
end;
implementation
{$R *.dfm}
const NameReport = '\AsupCommonRegardsReport.fr3';
constructor TDM.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
PID_Work_Reason:= 0;
end;
function TDM.PrintSpr(AParameter:TSimpleParam):variant;
var wf:TForm;
begin
if AParameter.Owner is TForm then
wf:=ShowWaitForm(AParameter.Owner as TForm,wfPrepareData)
else wf:=ShowWaitForm(Application.MainForm,wfPrepareData);
try
Screen.Cursor:=crHourGlass;
if PID_Work_Reason=-1 then PID_Work_Reason:=0;
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM ASUP_REPORT_REGARDS_COMMON('+inttostr(PIdRegards)+','''+datetostr(Date)+''','+inttostr(PID_Work_Reason)+')';
DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT FIRM_NAME FROM INI_ASUP_CONSTS';
try
DB.Handle:=AParameter.DB_Handle;
DSetData.Open;
DSetGlobalData.Open;
except
on E:Exception do
begin
AsupShowMessage(Error_Caption,e.Message,mtError,[mbOK]);
Screen.Cursor:=crDefault;
Exit;
end;
end;
if DSetData.IsEmpty then
begin
qFErrorDialog('За такими даними працівників не знайдено!');
Screen.Cursor:=crDefault;
Exit;
end;
Report.Clear;
Report.LoadFromFile(ExtractFilePath(Application.ExeName)+Path_ALL_Reports+NameReport,True);
Report.Variables['CUR_DATE']:=QuotedStr(DateToStr(Date));
Report.Variables['FIRM_NAME']:=QuotedStr(DSetGlobalData['FIRM_NAME']);
Report.Variables['REGARD_NAME']:=QuotedStr(RegardsText);
Screen.Cursor:=crDefault;
finally
CloseWaitForm(wf);
end;
if not DSetData.IsEmpty then
begin
if DesignReport then Report.DesignReport
else Report.ShowReport;
Report.Free;
end;
if ReadTransaction.InTransaction then ReadTransaction.Commit;
end;
end.
|
unit uFrmDadosBase;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmBase, Buttons, ExtCtrls, StdCtrls, TypesUtils, DBXCommon, Spin,
RxCurrEdit, RxToolEdit;
type
TFrmDadosBase = class(TFrmBase)
pnlBotoes: TPanel;
sbtSalvar: TSpeedButton;
sbtCancelar: TSpeedButton;
chbContinuarIncluindo: TCheckBox;
pnlDados: TPanel;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure sbtSalvarClick(Sender: TObject);
procedure sbtCancelarClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
FecharSemPerguntar: Boolean;
procedure SetFirstEditOf(Control: TWinControl);
//function NextControl(Control: TWinControl): TWinControl;
//function GetControlOrderList(aParent: TWinControl; aList: TList): integer;
//function GetTabOrderOf(aControl: TControl): integer;
//function IsFocusable(aControl: TWinControl): boolean;
protected
DBXConnection: TDBXConnection;
CamposObrigatorios: array of TWinControl;
procedure OnCreate; virtual; abstract;
procedure OnDestroy; virtual; abstract;
procedure OnSave; virtual; abstract;
procedure OnShow; virtual; abstract;
procedure LimparControles;
function ValidaCampos: Boolean;
procedure SetCamposObrigatorios(co: array of TWinControl);
public
{ Public declarations }
Operacao: TOperacao;
end;
var
FrmDadosBase: TFrmDadosBase;
implementation
uses uFrmPrincipal, MensagensUtils;
{$R *.dfm}
procedure TFrmDadosBase.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
inherited;
if not(FecharSemPerguntar) then
begin
if (Operacao = opInsert) then
CanClose := Confirma('Deseja cancelar a inclusão do registro?')
else
CanClose := Confirma('Deseja cancelar a edição do registro?');
end
else
CanClose := True;
end;
procedure TFrmDadosBase.FormCreate(Sender: TObject);
begin
DBXConnection := FrmPrincipal.ConnServidor.DBXConnection;
OnCreate;
end;
procedure TFrmDadosBase.FormDestroy(Sender: TObject);
begin
OnDestroy;
end;
procedure TFrmDadosBase.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
inherited;
case Key of
VK_F5: sbtSalvar.Click;
VK_ESCAPE: FecharSemPerguntar := False;
end;
end;
procedure TFrmDadosBase.FormKeyPress(Sender: TObject; var Key: Char);
//var
//next: TWinControl;
begin
inherited;
{if (Ord(Key) = 13) then
begin
next := NextControl(ActiveControl);
if next <> nil then
next.SetFocus;
end;}
end;
procedure TFrmDadosBase.FormShow(Sender: TObject);
begin
if (Operacao = opInsert) then
Self.Caption := 'Adicionar Novo Registro'
else
begin
Self.Caption := 'Editar registro';
chbContinuarIncluindo.Hide;
end;
SetFirstEditOf(pnlDados);
OnShow;
end;
procedure TFrmDadosBase.SetCamposObrigatorios(co: array of TWinControl);
var
i: Integer;
begin
SetLength(CamposObrigatorios, Length(co));
for i := 0 to Length(co) - 1 do
CamposObrigatorios[i] := co[i];
end;
procedure TFrmDadosBase.SetFirstEditOf(Control: TWinControl);
var
l:TList;
i:integer;
c:TWinControl;
begin
l:=TList.Create;
try
Control.GetTabOrderList(l);
for i:=0 to l.Count-1 do
begin
c:=TWinControl(l[i]);
if c.Enabled and c.TabStop and c.CanFocus then
if (c is TCustomEdit) and TEdit(c).ReadOnly then
else
begin
c.SetFocus;
Exit;
end;
end;
finally
l.Free;
end;
end;
function TFrmDadosBase.ValidaCampos: Boolean;
var
Campo: TWinControl;
begin
Result := True;
for Campo in CamposObrigatorios do
begin
if (Campo is TEdit) and ((Campo as TEdit).Text = '') then
begin
Atencao('Campo obrigatório.');
Campo.SetFocus;
Result := False;
Break;
end;
if (Campo is TDateEdit) and ((Campo as TDateEdit).Date = 0) then
begin
Atencao('Campo obrigatório.');
Campo.SetFocus;
Result := False;
Break;
end;
if (Campo is TCurrencyEdit) and ((Campo as TCurrencyEdit).Value = 0) then
begin
Atencao('Campo obrigatório.');
Campo.SetFocus;
Result := False;
Break;
end;
end;
end;
procedure TFrmDadosBase.LimparControles;
var
i, j: Integer;
begin
for i := 0 to pnlDados.ControlCount - 1 do
begin
if (pnlDados.Controls[i] is TEdit) then
(pnlDados.Controls[i] as TEdit).Clear;
if (pnlDados.Controls[i] is TDateEdit) then
(pnlDados.Controls[i] as TDateEdit).Clear;
if (pnlDados.Controls[i] is TCurrencyEdit) then
(pnlDados.Controls[i] as TCurrencyEdit).Clear;
if (pnlDados.Controls[i] is TMemo) then
(pnlDados.Controls[i] as TMemo).Clear;
if (pnlDados.Controls[i] is TSpinEdit) then
(pnlDados.Controls[i] as TSpinEdit).Value := (pnlDados.Controls[i] as TSpinEdit).MinValue;
if (pnlDados.Controls[i] is TFrame) then
begin
for j := 0 to (pnlDados.Controls[i] as TFrame).ControlCount - 1 do
begin
if ((pnlDados.Controls[i] as TFrame).Controls[j] is TEdit) then
((pnlDados.Controls[i] as TFrame).Controls[j] as TEdit).Clear;
end;
end;
if (pnlDados.Controls[i] is TGroupBox) then
begin
for j := 0 to (pnlDados.Controls[i] as TGroupBox).ControlCount - 1 do
begin
if ((pnlDados.Controls[i] as TGroupBox).Controls[j] is TEdit) then
((pnlDados.Controls[i] as TGroupBox).Controls[j] as TEdit).Clear;
if ((pnlDados.Controls[i] as TGroupBox).Controls[j] is TCurrencyEdit) then
((pnlDados.Controls[i] as TGroupBox).Controls[j] as TCurrencyEdit).Clear;
if ((pnlDados.Controls[i] as TGroupBox).Controls[j] is TSpinEdit) then
((pnlDados.Controls[i] as TGroupBox).Controls[j] as TSpinEdit).Value := ((pnlDados.Controls[i] as TGroupBox).Controls[j] as TSpinEdit).MinValue;
end;
end;
end;
SetFirstEditOf(pnlDados);
end;
{function TFrmDadosBase.GetTabOrderOf(aControl:TControl):integer;
begin
Result:=TWinControl(aControl).TabOrder;
end;
function TFrmDadosBase.GetControlOrderList(aParent:TWinControl; aList:TList):integer;
var
i,j,o:integer;
begin
aList.Clear;
for i:=0 to aParent.ControlCount-1 do
if aParent.Controls[i] is TWinControl then
begin
o:=GetTabOrderOf(aParent.Controls[i]);
if o<>-1 then
begin
j:=0;
while (j<aList.Count) and (GetTabOrderOf(TControl(aList[j]))<=o) do
Inc(j);
if j<aList.Count then
aList.Insert(j,aParent.Controls[i])
else
aList.Add(aParent.Controls[i]);
end;
end;
Result:=aList.Count;
end;
function TFrmDadosBase.IsFocusable(aControl:TWinControl):boolean;
begin
if not aControl.Enabled then
Result:=False
else if not aControl.Visible then
Result:=False
else if aControl is TRadioButton then
Result:=TRadioButton(aControl).Checked
else if aControl is TPage then
Result:=True
else if aControl.Name='' then
Result:=False
else
Result:=True;
end;
function TFrmDadosBase.NextControl(Control: TWinControl): TWinControl;
var
p,w:TWinControl;
i:integer;
l:TList;
begin
Result:=nil;
l:=TList.Create;
try
p:=Control.Parent;
if p=nil then
Exit;
GetControlOrderList(p,l);
if l.Count=0 then
Exit;
w:=Control;
if w=nil then
i:=-1
else
i:=l.IndexOf(w);
repeat
Inc(i);
if (i<0) or (i>l.Count-1) then
begin
if (p is TFrame) then
begin
SetFirstEditOf(p);
Result := nil;
end
else
Result:=NextControl(p);
Break;
end;
w:=TWinControl(l.Items[i]);
if IsFocusable(w) then
if (w is TFrame) then
begin
SetFirstEditOf(w);
Result := nil;
Break;
end
else if w.TabStop then
begin
Result:=w;
end;
until Result<>nil;
finally
l.Free;
end;
end;}
procedure TFrmDadosBase.sbtCancelarClick(Sender: TObject);
begin
inherited;
Close;
FecharSemPerguntar := False;
end;
procedure TFrmDadosBase.sbtSalvarClick(Sender: TObject);
begin
inherited;
if ValidaCampos then
begin
OnSave;
if (chbContinuarIncluindo.Checked) then
LimparControles
else
begin
Self.Close;
FecharSemPerguntar := True;
end;
end;
end;
end.
|
unit uResponsavel;
{**********************************************************************
** unit uResponsavel **
** **
** UNIT DESTINADA A MANIPULAR AS INFORMAÇÕES NO CADASTRO DE PACIENTE **
** REFERENTE AS INFORMAÇÕES DENTRO DA ABA RESPONSÁVEL PELO PACIENTE **
** **
***********************************************************************}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uCadPacientes, uClassResponsavelPaciente, uClassControlePaciente, uFrmMensagem;
type
{ Responsavel }
Responsavel = class
public
class function CarregaObjResponsavel(objResponsavel: TResponsavelPaciente; frm: TfrmCadPaciente): TResponsavelPaciente;
class procedure InclusaoOuEdicaoResponsavel(frm: TfrmCadPaciente);
class procedure ApagarResponsavel(codigo: integer);
end;
implementation
{ Responsavel }
class function Responsavel.CarregaObjResponsavel(objResponsavel: TResponsavelPaciente; frm: TfrmCadPaciente): TResponsavelPaciente;
var
codigo : integer;
begin
codigo := StrToInt(frm.edtCodResponsavel.Text);
objResponsavel.idResponsavel := codigo;
objResponsavel.idTblPaciente := StrToInt(frm.edtCodPaciente.Text);
objResponsavel.nomeResponsavel := frm.edtNomeResp.Text;
objResponsavel.parentesco := frm.edtParentesco.Text;
objResponsavel.documento.cpf := frm.mskedtCPFResp.Text;
objResponsavel.documento.identidade := frm.edtIdentidadeResp.Text;
objResponsavel.documento.orgaoExpedidor := frm.edtOrgaoExpedResp.Text;
objResponsavel.documento.idDocumentos := StrToInt(frm.edtCodDocResp.Text);
result := objResponsavel;
end;
class procedure Responsavel.InclusaoOuEdicaoResponsavel(frm: TfrmCadPaciente);
var
objResponsavel: TResponsavelPaciente;
objControlePaciente : TControlePaciente;
codResponsavel : integer;
begin
try
objResponsavel := TResponsavelPaciente.Create;
objControlePaciente := TControlePaciente.Create;
codResponsavel := objControlePaciente.InclusaoOuEdicaoResponsavel(CarregaObjResponsavel(objResponsavel, frm));
if codResponsavel > 0 then;
begin
try
frmMensagem := TfrmMensagem.Create(nil);
frmMensagem.InfoFormMensagem('Cadastro do Responsável', tiInformacao, 'Cadastro do Responsável realizado com sucesso!');
finally
FreeAndNil(frmMensagem);
end;
frm.edtCodResponsavel.Text := IntToStr(codResponsavel);
end;
//DesabilitaControles(pcCadPaciente.ActivePage);
estado := teNavegacao;
//EstadoBotoes;
finally
FreeAndNil(objControlePaciente);
FreeAndNil(objResponsavel);
end;
end;
class procedure Responsavel.ApagarResponsavel(codigo: integer);
var
frmMensagem : TfrmMensagem;
objControlePaciente : TControlePaciente;
begin
try
objControlePaciente := TControlePaciente.Create;
if objControlePaciente.ApagarResponsavel(codigo) then
begin
try
frmMensagem := TfrmMensagem.Create(nil);
frmMensagem.InfoFormMensagem('Remoção do Responsável do paciente', tiInformacao, 'Responsável removido com sucesso!');
finally
FreeAndNil(frmMensagem);
end;
end;
finally
FreeAndNil(objControlePaciente);
end;
end;
end.
|
unit Venda.Model.Dados;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MySQL,
FireDAC.Phys.MySQLDef, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, Data.DB,
FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, FireDAC.Comp.DataSet;
type
TVendaModelDados = class(TDataModule)
QClientes: TFDQuery;
DsClientes: TDataSource;
QueryTransition: TFDQuery;
QClientesid: TFDAutoIncField;
QClientesnome_cliente: TStringField;
QClientescidade: TStringField;
QClientesuf: TStringField;
QProdutos: TFDQuery;
DsProdutos: TDataSource;
QPedidos: TFDQuery;
DsPedidos: TDataSource;
QItensPedidos: TFDQuery;
DsItensPedidos: TDataSource;
FDTransaction1: TFDTransaction;
QProdutosid: TFDAutoIncField;
QProdutosnome_produto: TStringField;
QProdutospreco_venda: TSingleField;
QPedidosNUM_PED: TFDAutoIncField;
QPedidosDATA_EMISSAO: TDateField;
QPedidosID_CLIENTE: TIntegerField;
QPedidosVALOR_TOTAL: TSingleField;
QPedidosNOME_CLIENTE: TStringField;
QPedidosCIDADE: TStringField;
QPedidosUF: TStringField;
QItensPedidosSEQ_ITEM: TFDAutoIncField;
QItensPedidosNUM_PED: TIntegerField;
QItensPedidosID_PRODUTO: TIntegerField;
QItensPedidosQTDE_ITEM: TSingleField;
QItensPedidosVALOR_UNIT: TSingleField;
QItensPedidosVALOR_TOTAL: TSingleField;
QItensPedidosNOME_PRODUTO: TStringField;
QueryConsulta: TFDQuery;
QItensPedidosTemp: TFDQuery;
FDAutoIncField1: TFDAutoIncField;
IntegerField1: TIntegerField;
IntegerField2: TIntegerField;
SingleField1: TSingleField;
SingleField2: TSingleField;
SingleField3: TSingleField;
StringField1: TStringField;
DsItensPedidosTemp: TDataSource;
QueryConsulta2: TFDQuery;
private
{ Private declarations }
public
{ Public declarations }
end;
var
VendaModelDados: TVendaModelDados;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
end.
|
unit UHeatExchanger;
interface
uses UFlow;
type
HeatExchanger = class
d_in := 0.2;
d_out := 0.5;
length := 3.0;
k := 4900;
function calculate(hot, cold: Flow; h: real := 0.01): sequence of Flow;
end;
implementation
function HeatExchanger.calculate(hot, cold: Flow; h: real): sequence of Flow;
begin
var t_hot := hot.temperature;
var t_cold := cold.temperature;
var v_cold := cold.volume_flow_rate / (3.14 * d_in ** 2 / 4 * length);
var v_hot := hot.volume_flow_rate / (3.14 * d_out ** 2 / 4 * length
- 3.14 * d_in ** 2 / 4 * length);
var len := 0.0;
while len <= length do
begin
t_hot -= k * 3.14 * d_out / (v_hot * hot.density * hot.heat_capacity)
* (t_hot - t_cold) * h;
t_cold += k * 3.14 * d_in / (v_cold * cold.density * cold.heat_capacity)
* (t_hot - t_cold) * h;
len += h
end;
var hot_ := new Flow(hot.mass_flow_rate, hot.mass_fractions, t_hot);
var cold_ := new Flow(cold.mass_flow_rate, cold.mass_fractions, t_cold);
result := seq(hot_, cold_)
end;
end. |
unit DrawMeta;
{--- make a drawable metafile ---}
{ Grahame Marsh Jan 1996 }
interface
uses Graphics, Forms, WinProcs;
type
TDrawMetaFile = class(TMetaFile)
private
FCanvas : TCanvas;
FDrawing : boolean;
procedure SetDrawing (State : boolean);
protected
property Drawing : boolean read FDrawing write SetDrawing;
public
constructor Create (aWidth, aHeight : integer);
destructor Destroy; override;
procedure Open;
procedure Close;
published
property Canvas : TCanvas read FCanvas write FCanvas;
end;
implementation
{ create our drawing metafile, take the drawing width and height to those }
{ given in the parameters, set the inch property to that found in }
{ screens.pixelsperinch and finally open for drawing }
constructor TDrawMetafile.Create (aWidth, aHeight : integer);
begin
inherited Create;
Inch := Screen.PixelsPerInch;
Width := aWidth;
Height := aHeight;
Open;
end;
{ before destroying the metafile ensure that it is closed, this means }
{ that any canvas is destroyed }
destructor TDrawMetafile.Destroy;
begin
Close;
inherited Destroy;
end;
{ The key method: puts the metafile into draw and use modes depending on }
{ the boolean parameter. When true the metafile goes into draw mode by }
{ putting a CreateMetafile device context into a Canvas handle property }
{ the canvas can now be drawn on. When false the metafile goes into use }
{ mode by putting the handle returned from the CloseMetafile call into }
{ the metafile's handle property. Note that the width, height and inch }
{ properties are preserved over this assignment. Finally the canvas is }
{ freed. }
procedure TDrawMetafile.SetDrawing (State : boolean);
var
KeepInch,
KeepWidth,
KeepHeight : integer;
begin
if State <> FDrawing then
begin
FDrawing := State;
if Drawing then
begin
FCanvas := TCanvas.Create;
FCanvas.Handle := CreateMetafile(nil);
end
else
begin
KeepWidth := Width;
KeepHeight := Height;
KeepInch := Inch;
Handle := CloseMetafile(FCanvas.Handle);
Width := KeepWidth;
Height := KeepHeight;
Inch := KeepInch;
FCanvas.Free;
end;
end;
end;
procedure TDrawMetafile.Open;
begin
Drawing := true
end;
procedure TDrawMetafile.Close;
begin
Drawing := false
end;
end.
|
// -------------------------------------------------------
//
// This file was generated using Parse::Easy v1.0 alpha.
//
// https://github.com/MahdiSafsafi/Parse-Easy
//
// DO NOT EDIT !!! ANY CHANGE MADE HERE WILL BE LOST !!!
//
// -------------------------------------------------------
unit JSONLexer;
interface
uses System.SysUtils, WinApi.Windows,
Parse.Easy.Lexer.CustomLexer;
type TJSONLexer = class(TCustomLexer)
protected
procedure UserAction(Index: Integer); override;
public
class constructor Create;
function GetTokenName(Index: Integer): string; override;
end;
const
EOF = 0000;
BACKSLASH = 0001;
LPAREN = 0002;
RPAREN = 0003;
LBRACE = 0004;
RBRACE = 0005;
LBRACK = 0006;
RBRACK = 0007;
SQUOTE = 0008;
DQUOTE = 0009;
PLUS = 0010;
MINUS = 0011;
COLON = 0012;
COMMA = 0013;
TK_FALSE = 0014;
TK_TRUE = 0015;
TK_NULL = 0016;
DQSTRING = 0017;
DIGIT = 0018;
FRAC = 0019;
EXP = 0020;
WS = 0021;
SECTION_DEFAULT = 0000;
implementation
{$R JSONLexer.RES}
{ TJSONLexer }
class constructor TJSONLexer.Create;
begin
Deserialize('JSONLEXER');
end;
procedure TJSONLexer.UserAction(Index: Integer);
begin
case Index of
0000:
begin
Skip
end;
end;
end;
function TJSONLexer.GetTokenName(Index: Integer): string;
begin
case Index of
0000 : exit('EOF' );
0001 : exit('BACKSLASH');
0002 : exit('LPAREN' );
0003 : exit('RPAREN' );
0004 : exit('LBRACE' );
0005 : exit('RBRACE' );
0006 : exit('LBRACK' );
0007 : exit('RBRACK' );
0008 : exit('SQUOTE' );
0009 : exit('DQUOTE' );
0010 : exit('PLUS' );
0011 : exit('MINUS' );
0012 : exit('COLON' );
0013 : exit('COMMA' );
0014 : exit('TK_FALSE');
0015 : exit('TK_TRUE' );
0016 : exit('TK_NULL' );
0017 : exit('DQSTRING');
0018 : exit('DIGIT' );
0019 : exit('FRAC' );
0020 : exit('EXP' );
0021 : exit('WS' );
end;
Result := 'Unkown' + IntToStr(Index);
end;
end.
|
{
Author: dark_pin_guin
Github: github.com/dark-pin-guin
}
unit geometry;
{$mode objfpc}{$M+}
interface
uses
Classes, SysUtils, ExtCtrls, math;
{ TPoint }
type
TPoint = class
private
{ private declarations }
public
{ public declarations }
Constructor Create(X,Y : Integer);
procedure drawPoint(var PaintBox : TPaintBox);
procedure drawPoint(var PaintBox : TPaintBox; W , H : Integer);
var X, Y : Integer;
end;
{ TLine }
TLine = class
private
{ private declarations }
procedure CalculateLength();
type TLineArray = array of TLine;
public
{ public declarations }
Constructor Create(X1, Y1 , X2, Y2 : Integer);
Constructor Create(PointA, PointB : TPoint);
procedure drawLine(var PaintBox : TPaintBox)overload;
class procedure darwLine(var PaintBox : TPaintBox; Line :TLine)overload;
class procedure darwLine(var PaintBox : TPaintBox; PointA, PointB :TPoint)overload;
class function max(a, b, c : TLine):TLine;
class function max(a, b : TLine):TLine;
class function min(a, b : TLine):TLine;
class function sort(a, b, c :TLine):TLineArray;
var PointA, PointB : TPoint;
var Length : real;
end;
{ TTriangle }
TTriangle = class
private
{ private declarations }
public
{ public declarations }
Constructor Create();
Constructor Create(LineA, LineB, LineC :TLine);
Constructor Create(points : array of Tpoint);
Constructor Create(LengthA, LengthB, LengthC : real; var PaintBox : TPaintBox);
procedure drawTriangle(var PaintBox : TPaintBox)overload;
published class procedure darwTriangle(var PaintBox : TPaintBox; LineA, LineB, LineC :TLine)overload;
function isIsosceles():Boolean;
function isEquilateral():Boolean;
function isRightTriangle():Boolean;
var LineA, LineB, LineC : TLine;
//var alpha, beta, gamma : real;
end;
implementation
{ TPoint }
Constructor TPoint.Create(X,Y : Integer); // Constructor
begin
self.X:= X;
self.Y:= Y;
end;
procedure TPoint.drawPoint(var PaintBox : TPaintBox); // draws a Point on a PaintBox
begin
PaintBox.Canvas.Rectangle(X+5+5,Y,X,Y-5-5);
end;
procedure TPoint.drawPoint(var PaintBox : TPaintBox; W , H : Integer);
begin
PaintBox.Canvas.Rectangle(X+W,Y+H,X-W,Y-H);
end;
{ TLine }
Constructor TLine.Create(X1, Y1 , X2, Y2 : Integer); // Creates a Line by using the given coordinates
begin
self.PointA:= TPoint.Create(X1, Y1);
self.PointB:= TPoint.Create(X2, Y2);
self.calculateLength();
end;
Constructor TLine.Create(PointA, PointB : TPoint); // Creates a Line by using TPoints
begin
self.PointA := PointA;
self.PointB := PointB;
self.calculateLength();
end;
procedure TLine.calculateLength(); // Calculates the Length of an line by using theorem of Pythagoras
begin
if (PointA.X = PointB.X) xor (PointA.Y = PointB.Y)then
begin
if (PointA.X = PointB.X)then
begin
Length:=math.Max(PointA.Y, PointB.Y) - math.Min(PointA.Y, PointB.Y);
end
else
begin
Length:=math.Max(PointA.X, PointB.X) - math.Min(PointA.X, PointB.X);
end;
end
else
begin
Length:=sqrt((math.Max(PointA.X, PointB.X) - math.Min(PointA.X, PointB.X))* (math.Max(PointA.X, PointB.X) - math.Min(PointA.X, PointB.X)) + (math.Max(PointA.Y, PointB.Y) - math.Min(PointA.Y, PointB.Y)) * (math.Max(PointA.Y, PointB.Y) - math.Min(PointA.Y, PointB.Y)));
end;
end;
class function TLine.sort(a, b, c: TLine) : TLineArray; // Sorts three Lines and returns them in an Array
begin
SetLength(Result, 2);
if a.Length < b.Length then begin
if b.Length < c.Length then begin
Result[0] := c;
Result[1] := TLine.max(a,b);
Result[2] := TLine.min(a,b);
end else begin
Result[0] := b;
Result[1] := TLine.max(a,c);
Result[2] := TLine.min(a,c);
end;
end else if b.Length < a.Length then begin
if a.Length < c.Length then begin
Result[0]:= c;
Result[1]:= TLine.max(a,b);
Result[2]:= TLine.min(a,b);
end else begin
Result[0]:= a;
Result[1]:= TLine.max(b,c);
Result[2]:= TLine.min(b,c);
end;
end else begin
Result[0]:= a;
Result[1]:= TLine.max(b,c);
Result[2]:= TLine.min(b,c);
end;
end;
class function TLine.max(a,b,c: TLine) : TLine; // returns the gretest Line
begin
if(a.Length > b.Length) then
begin
if(b.Length > c.Length) then
begin
Result := c;
end
else
begin
Result := b
end;
end
else
begin
Result := a;
end;
end;
class function TLine.max(a, b: TLine) : TLine;
begin
if(a.Length > b.Length) then
begin
Result := a
end
else
begin
Result := b;
end;
end;
class function TLine.min(a, b: TLine) : TLine;
begin
if(a.Length < b.Length) then
begin
Result := a
end
else
begin
Result := b;
end;
end;
procedure TLine.drawLine(var PaintBox : TPaintBox); // draws an Line on a PaintBox
begin
PaintBox.Canvas.MoveTo(PointA.X+5,PointA.Y-5);
PaintBox.Canvas.LineTo(PointB.X+5,PointB.Y-5);
end;
class procedure TLine.darwLine(var PaintBox : TPaintBox; Line :TLine); // draws an Line on a PaintBox
begin
PaintBox.Canvas.MoveTo(Line.PointA.X+5, Line.PointA.Y-5);
PaintBox.Canvas.LineTo(Line.PointB.X+5, Line.PointB.Y-5)
end;
class procedure TLine.darwLine(var PaintBox : TPaintBox; PointA, PointB :TPoint); // draws an Line on a PaintBox
begin
PaintBox.Canvas.MoveTo(PointA.X+5, PointA.Y-5);
PaintBox.Canvas.LineTo(PointB.X+5, PointB.Y-5);
end;
{ TTriangle }
Constructor TTriangle.Create();
begin
end;
Constructor TTriangle.Create(LengthA, LengthB, LengthC : real; var PaintBox : TPaintBox); // Creates an Triangle by using three Lines
begin
Self.LineC:= TLine.Create(0, PaintBox.Height, floor(LengthC) , PaintBox.Height);
Self.LineB:= Tline.Create(0, PaintBox.Height, floor((LengthB*LengthB+LengthC*LengthC-LengthA*LengthA)/(2*LengthC)), PaintBox.Height - floor(sqrt(LengthA*LengthA-((LengthC/2-(LengthB*LengthB-LengthA*LengthA)/(2*LengthC))*(LengthC/2-(LengthB*LengthB-LengthA*LengthA)/(2*LengthC))))));
Self.LineA:= Tline.Create(floor(LengthC),PaintBox.Height,floor((LengthB*LengthB+LengthC*LengthC-LengthA*LengthA)/(2*LengthC)), PaintBox.Height - floor(sqrt(LengthA*LengthA-((LengthC/2-(LengthB*LengthB-LengthA*LengthA)/(2*LengthC))*(LengthC/2-(LengthB*LengthB-LengthA*LengthA)/(2*LengthC))))));
end;
Constructor TTriangle.Create(LineA, LineB, LineC :TLine); // Creates an Triangle by using three given Lines
begin
Self.LineA:= TLine.Sort(LineA, LineB, LineC)[2];
Self.LineC:= TLine.Sort(LineA, LineB, LineC)[1];
Self.LineB:= TLine.Sort(LineA, LineB, LineC)[0];
end;
Constructor TTriangle.Create(points : array of TPoint); // Creates an Triangle out of an Array of TPoints
begin
self.LineA:= TLine.Sort(TLine.Create(points[0], points[1]),TLine.Create(points[1], points[2]),TLine.Create(points[2], points[0]))[2];
self.LineB:= TLine.Sort(TLine.Create(points[0], points[1]),TLine.Create(points[1], points[2]),TLine.Create(points[2], points[0]))[1];
self.LineC:= TLine.Sort(TLine.Create(points[0], points[1]),TLine.Create(points[1], points[2]),TLine.Create(points[2], points[0]))[0];
end;
procedure TTriangle.drawTriangle(var PaintBox : TPaintBox); // Draws an Triangle on a PaintBox
begin
TTriangle.darwTriangle(PaintBox,LineA,LineB,LineC);
end;
class procedure TTriangle.darwTriangle(var PaintBox : TPaintBox; LineA, LineB, LineC :TLine); // Draws an Triangle on a PaintBox
begin
LineA.drawLine(PaintBox);
LineB.drawLine(PaintBox);
LineC.drawLine(PaintBox);
end;
function TTriangle.isIsosceles():Boolean; // Checks if the Triangle is an Isosceles
begin
if ((LineA.Length = LineB.Length) xor (LineA.Length = LineC.Length)) xor (LineC.Length = LineB.Length) then begin
Result:= True;
end
else
begin
Result:= False;
end;
end;
function TTriangle.isEquilateral():Boolean; // Checks if the Triangle is an Equilateral
begin
if ((LineA.Length = LineB.Length) and (LineA.Length = LineC.Length) and (LineB.Length=LineC.Length)) then
begin
Result:= True;
end
else
begin
Result:= False;
end;
end;
function TTriangle.isRightTriangle():Boolean; // Checks if the Triangle is an Right Triangle
begin
if(sqrt(LineA.Length * LineA.Length + LineB.Length * LineB.Length) = LineC.Length)then
begin
Result:= True;
end
else
begin
Result:= False;
end;
end;
end.
|
unit VMoveOldFileParamsForms;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, ToolEdit;
type
TMoveOldFilesParamsForm = class(TForm)
borrarOLDCheckBox: TCheckBox;
borrarDELCheckBox: TCheckBox;
Label1: TLabel;
fechaCorteEdit: TDateEdit;
aceptarButton: TButton;
cancelarButton: TButton;
procedure fechaCorteEditChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MoveOldFilesParamsForm: TMoveOldFilesParamsForm;
implementation
{$R *.dfm}
// ^^^^^^^
// EVENTOS
// ^^^^^^^
// Sólo se admiten fechas menores al día en curso
// Dependiendo de la "distancia" entre la fecha introducida y la fecha del día de hoy
// se pondrá un color y otro.
// Negro (de un mes para atrás)
// Amarillo (menos/igual mes hasta 15 días)
// Rojo (menos/igual 15 días)
procedure TMoveOldFilesParamsForm.fechaCorteEditChange(Sender: TObject);
var
today,
fechaCorte: TDateTime;
dif: Integer;
nuevoColor: TColor;
begin
today := date();
fechaCorte := TDateEdit( Sender ).Date;
dif := Trunc( today - fechaCorte );
nuevoColor := clBlack;
if (dif <= 30) and (dif > 15) then
nuevoColor := $004080FF
else if (dif <= 15) and (dif > 0) then
nuevoColor := clRed
else if (dif <= 0) then
raise Exception.Create('La fecha de corte debe ser, como máximo, el día de ayer.');
TDateEdit(Sender).Font.Color := nuevoColor;
end;
end.
|
unit interfaces;
interface
type
CustomAttribute = CustomAttribute;
CustomAttribute2 = CustomAttribute2;
Integer = Integer;
Single = Single;
[CustomAttribute('', '', False)]
IUnknown = interface
['{00000000-0000-0000-C000-000000000046}']
function func(): [CustomAttribute('', '', False)] Single; virtual;
procedure proc; virtual;
end;
IEnum<T> = interface
[CustomAttribute('virtual T __fastcall GetCurrentT(void) = 0')]
function GetCurrent: T;
[CustomAttribute2('__property T Current = {read=GetCurrentT}')]
property Current: T read GetCurrent;
end;
[CustomAttribute, CustomAttribute2('', '', False)]
TA = class
private
[CustomAttribute('', '', False)]
procedure IntfGetComponent; virtual;
public
function IUnknown.proc = IntfGetComponent;
end;
implementation
procedure TA.IntfGetComponent;
begin
end;
end. |
unit trtm_lng;
interface
const
TABLE_DSC_NEED_TO_CHANGE = 'Что нужно изменить по условию задачи';
TABLE_DSC_GETTING_WORSE = 'Что ухудшается при изменении';
TABLE_DSC_ALL_METHODS = 'Указано в таблице';
TABLE_DSC_ALL_F_METHODS = 'Дублируются';
TABLE_DSC_ALL_S_METHODS = 'Подходящие';
TABLE_DSC_ALL_US_METHODS = 'Неподходящие';
TXT_AUTHOR = 'Автор';
TXT_TASK = 'Задача';
TXT_SOLUTION_IDEA = 'Решение задачи с помощью таблицы приёмов разрешения технических противоречий';
TXT_CONTR = 'Противоречия';
TXT_AC = 'Административное противоречие';
TXT_TC = 'Техническое противоречие';
TXT_PHC = 'Физическое противоречие';
TXT_PARAMETERS = 'Параметры:';
TXT_METH_LIST = 'Указано в таблице';
TXT_POPULAR_METH = 'Дублируются';
TXT_GOOD_METH = 'Подходящие';
TXT_NOT_GOOD_METH = 'Неподходящие';
TXT_SOLUTION = 'Решение задачи';
TXT_GRAPHICS = 'График популярности методов';
TXT_CHANGING = 'изменяемый параметр';
TXT_GETTING_WORSE = 'ухудшающийся параметр';
TXT_INPUT = 'Введите';
TXT_TABLE_NAME = 'Таблица выбора приёмов устранения технических противоречий по Альтшуллеру';
MSG_ENTER_GETTING_WORSE = TXT_INPUT + ' ' + TXT_GETTING_WORSE;
MSG_ENTER_CHANGING = TXT_INPUT + ' ' + TXT_CHANGING;
MSG_ABOUT = 'Теория: Братцева Г.Г.' +
#13#10 + 'Реализация: Соболев С.П., sobolevsp@mail.ru' +
#13#10 + ' ' + 'Филипова О.С.' +
#13#10 + 'Доработано: Григорьев В.В., armag_vvg@hotmail.ru' +
#13#10 + 'Доработано: Степулёнок Д.О., super.denis@gmail.com';
MSG_ABOUT_HTM = '<strong>ТРТМ:</strong> Теория: Братцева Г.Г.' +
'<br>' + 'Реализация: <a href="mailto:sobolevsp@mail.ru">Соболев С.П.</a>,' +
'<br>' + 'Филипова О.С.'
;
MSG_NO_HELP = 'В данной версии программы справка не доступна.';
MSG_NOTREALIZED_YET = 'Данная функция пока не реализована.';
INI_RIZ_SECTION_MAIN = 'Main section';
INI_RIZ_PAR_AUTHOR = 'Author';
INI_RIZ_PAR_PRJ_NAME = 'Project name';
INI_RIZ_SECTION_TASK = 'Task section';
INI_RIZ_PAR_TASK = 'Task';
INI_RIZ_PAR_CONTR_ADM = 'Contr adm';
INI_RIZ_PAR_CONTR_TECH = 'Contr tech';
INI_RIZ_PAR_CONTR_PHYS = 'Contr phys';
INI_RIZ_PAR_CHANGING = 'Changing';
INI_RIZ_PAR_GETTING_W = 'Getting w';
INI_RIZ_PAR_GOOD_METH = 'Good meth';
INI_RIZ_PAR_BAD_METH = 'Bad meth';
INI_RIZ_SECTION_RESULT = 'Result section';
INI_RIZ_PAR_RESULT = 'Result';
TABLE_COL_NUM = 6;
TABLE_DSC_COL_0_W = 80;
TABLE_DSC_COL_1_W = 60;
TABLE_DSC_COL_2_W = 80;
TABLE_DSC_COL_3_W = 60;
TABLE_DSC_COL_4_W = 50;
TABLE_DSC_COL_5_W = 50;
TABLE_RO_COL_2 = 2;
TABLE_RO_COL_3 = 3;
FILE_EXT_TXT = 'Текстовый файл';
FILE_EXT_HTM = 'Html-файл';
FILE_EXT_RTF = 'RTF-документ';
CHART_TITLE = 'Популярность предложенных методов';
MAIN_FORM_TITLE = 'Решение технических противоречий';
implementation
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmKeyBindingPropEdit
Purpose : Component editor for the rmKeyBinding component.
Date : 05-03-2000
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmKeyBindingPropEdit;
interface
{$I CompilerDefines.INC}
{$ifdef D6_or_higher}
uses
DesignIntf, DesignEditors, TypInfo;
{$else}
uses
DsgnIntf, TypInfo;
{$endif}
type
TrmKeyBindingEditor = class(TComponentEditor)
private
procedure SaveToFile(Binary:boolean);
procedure LoadFromFile(Binary:Boolean);
procedure ClearData;
procedure EditBindings;
public
function GetVerb(index:integer):string; override;
function GetVerbCount:integer; override;
procedure ExecuteVerb(index:integer); override;
end;
implementation
uses
rmKeyBindings, dialogs;
{ TrmKeyBindingEditor }
procedure TrmKeyBindingEditor.ClearData;
begin
if assigned(Component) then
begin
TrmKeyBindings(Component).ClearBindings;
designer.modified;
end;
end;
procedure TrmKeyBindingEditor.EditBindings;
begin
if assigned(Component) then
begin
if TrmKeyBindings(Component).EditBindings then
begin
TrmKeyBindings(Component).ApplyBindings;
designer.modified;
end;
end;
end;
procedure TrmKeyBindingEditor.ExecuteVerb(index: integer);
begin
case index of
0:EditBindings;
1:LoadFromFile(True);
2:LoadFromFile(False);
3:SaveToFile(True);
4:SaveToFile(False);
5:ClearData;
end;
end;
function TrmKeyBindingEditor.GetVerb(index: integer): string;
begin
case index of
0:result := 'Edit bindings...';
1:result := 'Load bindings from file (Binary)...';
2:result := 'Load bindings from file (Text)...';
3:result := 'Save bindings to file (Binary)...';
4:result := 'Save bindings to file (Text)...';
5:result := 'Clear bindings';
end;
end;
function TrmKeyBindingEditor.GetVerbCount: integer;
begin
result := 6;
end;
procedure TrmKeyBindingEditor.LoadFromFile(Binary:Boolean);
begin
if assigned(Component) then
begin
with TOpenDialog.create(nil) do
try
Title := 'Load file...';
Filter := 'All Files|*.*';
FilterIndex := 1;
if execute then
begin
TrmKeyBindings(Component).LoadBindingsFromFile(filename, Binary);
designer.modified;
end;
finally
free;
end
end;
end;
procedure TrmKeyBindingEditor.SaveToFile(Binary:Boolean);
begin
if assigned(Component) then
begin
if not assigned(TrmKeyBindings(Component).Actions) then
begin
ShowMessage('No actions are assigned');
exit;
end;
with TSaveDialog.create(nil) do
try
Title := 'Save to...';
Filter := 'All Files|*.*';
FilterIndex := 1;
if execute then
TrmKeyBindings(Component).SaveBindingsToFile(filename, Binary);
finally
free;
end
end;
end;
end.
|
Program FlightLIst;
uses App, Objects, Views, Drivers, Menus, Dialogs, MsgBox, TextView;
const
cmListFlights = 199;
cmAddDialog = 200;
cmSearchDialog = 201;
type
TMyAppl = object (TApplication)
FlightCollection: PCollection;
procedure InitStatusLine; virtual;
procedure InitMenuBar; virtual;
procedure ListFlights; virtual;
procedure NewFlight; virtual;
procedure FindFlight; virtual;
procedure PrintFlights; virtual;
procedure SearchFlights; virtual;
procedure HandleEvent(var Event: TEvent); virtual;
constructor Init;
destructor Done; virtual;
end;
type
PListWindow = ^TListWindow;
TListWindow = object (TWindow)
Term: PTerminal;
Buff: Text;
constructor Init(Bounds: TRect; WinTitle: String; WinNo: Integer);
end;
type
PAddDialog = ^TAddDialog;
TAddDialog = object (TDialog)
constructor Init (var Bounds: TRect; WinTitle: String);
end;
type
PFindDialog = ^TFindDialog;
TFindDialog = object (TDialog)
constructor Init (var Bounds: TRect; WinTitle: String);
end;
type
PFlight = ^TFlight;
TFlight = object(TObject)
Id, Price, FromPoint, ToPoint, Date, Time: PString;
constructor Init(i, p, fp, tp, d, t: String);
procedure Load(S: TDosStream);
procedure Store(S: TDosStream);
destructor Done; virtual;
end;
constructor TFlight.Init(i, p, fp, tp, d, t: String);
begin
Id := NewStr(i);
Price := NewStr(p);
FromPoint := NewStr(fp);
ToPoint := NewStr(tp);
Date := NewStr(d);
Time := NewStr(t);
end;
procedure TFlight.Load(S: TDosStream);
begin
Id := S.ReadStr;
Price := S.ReadStr;
FromPoint := S.ReadStr;
ToPoint := S.ReadStr;
Date := S.ReadStr;
Time := S.ReadStr;
end;
procedure TFlight.Store(S: TDosStream);
begin
S.WriteStr(Id);
S.WriteStr(Price);
S.WriteStr(FromPoint);
S.WriteStr(ToPoint);
S.WriteStr(Date);
S.WriteStr(Time);
end;
destructor TFlight.Done;
begin
dispose(Id);
dispose(Price);
dispose(FromPoint);
dispose(ToPoint);
dispose(Date);
dispose(Time);
end;
Const
RFlight: TStreamRec = (
ObjType: 2000;
VmtLink: Ofs(TypeOf(TFlight)^);
Load: @TFlight.Load;
Store: @TFlight.Store);
type
FindData = record
Field: integer;
Value: string[128];
end;
type
AddData = record
Date: string[128];
Time: string[128];
Price: string[128];
Start: string[128];
Dest: string[128];
end;
var
FlightAppl: TMyAppl;
Find: FindData;
Add: AddData;
SaveFile: TDosStream;
procedure TMyAppl.InitStatusLine;
var R: TRect;
begin
GetExtent(R);
R.A.Y := R.B.Y - 1;
StatusLine := New(PStatusLine, Init(R,
NewStatusDef(0, $FFFF,
NewStatusKey('~Alt-X~ Exit', kbAltX, cmQuit,
NewStatusKey('~Alt-F3~ Close', kbAltF3, cmClose,
nil)),
nil)
));
end;
procedure TMyAppl.InitMenuBar;
var R: TRect;
begin
GetExtent(R);
R.B.Y := R.A.Y + 1;
MenuBar := New(PMenuBar, Init(R, NewMenu(
NewSubMenu('~F~lights', hcNoContext, NewMenu(
NewItem('List(refresh) flights', 'F3', kbF3, cmListFlights, hcNoContext,
NewItem('New flight', 'F4', kbF4, cmAddDialog, hcNoContext,
NewItem('Find flight', 'F5', kbF5, cmSearchDialog, hcNoContext,
NewLine(
NewItem('E~x~it', 'Alt-X', kbAltX, cmQuit, hcNoContext,
nil)))))),
nil)
)));
end;
constructor TMyAppl.Init;
begin
inherited Init;
RegisterType(RFlight);
MessageBox ('Start', nil, mfOkButton);
SaveFile.Init('Flight.res', stOpenRead);
FlightCollection := PCollection(SaveFile.Get);
MessageBox('1', nil, mfOkButton);
if SaveFile.Status <> stOk then
begin
MessageBox('2', nil, mfOkButton);
SaveFile.Done;
SaveFile.Init('Flight.res', stCreate);
if SaveFile.Status <> stOk then MessageBox('Creation Error', nil, mfOkButton);
FlightCollection := New(PCollection, Init(10, 5));
FlightCollection^.Insert(New(PFlight, Init('1','2','3','4','5','6')));
end;
SaveFile.Done;
MessageBox ('Running', nil, mfOkButton);
with Find do
begin
Field := 0;
Value := 'Phone home';
end;
with Add do
begin
Date:= 'asd';
Time:= '11';
Price:= '22';
Start:= '33';
Dest:= '44';
end;
end;
procedure TMyAppl.PrintFlights;
var
F: text;
i: integer;
procedure PrintFlight(P: PFlight); far;
begin
Inc(i);
With P^ do
write(F, Id^+' '+Price^+' '+FromPoint^+' '+ToPoint^+' '+Date^+' '+Time^);
if FlightCollection^.Count <> i then begin
writeln(F,'');
end;
end;
begin
Assign(F, 'DATA.TXT');
Rewrite(F);
i := 0;
FlightCollection^.ForEach(@PrintFlight);
Close(F);
end;
procedure TMyAppl.SearchFlights;
var
FoundFlight: PFlight;
temp: string;
function SearchFlight(P: PFlight):Boolean; far;
begin
Case Find.Field of
0: begin
temp := P^.Id^;
end;
1: begin
temp := P^.Price^;
end;
2: begin
temp := P^.FromPoint^;
end;
3: begin
temp := P^.ToPoint^;
end;
4: begin
temp := P^.Date^;
end;
5: begin
temp := P^.Time^;
end;
end;
SearchFlight := Pos(Find.Value, Temp)<>0;
end;
begin
FoundFlight := FlightCollection^.FirstThat(@SearchFlight);
if FoundFlight = NIL then begin
MessageBox('Not fount', nil, mfOkButton);
end else begin
temp := FoundFlight^.Id^+' '+FoundFlight^.Price^+' '+FoundFlight^.FromPoint^+' ';
temp := temp + FoundFlight^.ToPoint^+' '+FoundFlight^.Date^+' '+FoundFlight^.Time^;
MessageBox(temp, nil, mfOkButton);
end;
end;
constructor TListWindow.Init (Bounds: TRect; WinTitle: String; WinNo: Integer);
var
HSB, VSB: PScrollBar;
F: text;
temp: string;
begin
TWindow.Init (Bounds,WinTitle, WinNo);
VSB := StandardScrollBar (sbVertical);
HSB := StandardScrollBar(sbHorizontal);
GetExtent(Bounds);
Bounds.Grow(-1,-1);
New(Term, Init(Bounds, HSB, VSB, 50000));
{SaveFile.Init('Data.txt', stCreate);
SaveFile.Done;}
Assign(F, 'Data.txt');
Reset(F);
AssignDevice(Buff, Term);
Rewrite(Buff);
MessageBox('cycle', nil, mfOkButton);
while not eof(F) do
begin
Read(F, temp);
if temp[0] <> '' then Writeln(Buff, temp);
end;
MessageBox('cycle done', nil, mfOkButton);
Insert(Term);
system.close(F);
end;
constructor TAddDialog.Init (var Bounds: TRect; WinTitle: String);
var
R: TRect; B: PView;
FieldWidth: integer;
begin
inherited Init (Bounds,WinTitle);
FieldWidth := (Bounds.B.X - Bounds.A.X) div 2 - 3;
R.Assign(3,2,FieldWidth,3);
B:=New(PInputLine,Init(R,128));
Insert(B);
R.Assign(3,1,FieldWidth,2);
Insert(New(PLabel,Init(R,'Date',B)));
R.Assign(3,5,FieldWidth,6);
B:=New(PInputLine,Init(R,128));
Insert(B);
R.Assign(3,4,FieldWidth,5);
Insert(New(PLabel,Init(R,'Time',B)));
R.Assign(3,8,FieldWidth,9);
B:=New(PInputLine,Init(R,128));
Insert(B);
R.Assign(3,7,FieldWidth,8);
Insert(New(PLabel,Init(R,'Price',B)));
R.Assign(FieldWidth + 5,2,FieldWidth * 2 + 2,3);
B:=New(PInputLine,Init(R,128));
Insert(B);
R.Assign(FieldWidth + 5,1,FieldWidth * 2 + 2,2);
Insert(New(PLabel,Init(R,'Start',B)));
R.Assign(FieldWidth + 5,5,FieldWidth * 2 + 2,6);
B:=New(PInputLine,Init(R,128));
Insert(B);
R.Assign(FieldWidth + 5,4,FieldWidth * 2 + 2,5);
Insert(New(PLabel,Init(R,'Destination',B)));
R.Assign(15,10,25,12);
Insert(New (PButton, Init (R, '~A~dd Flight', cmOk, bfDefault)));
end;
constructor TFindDialog.Init (var Bounds: TRect; WinTitle: String);
var R: TRect; B: PView;
begin
inherited Init (Bounds,WinTitle);
R.Assign(3,3,30,9);
B:= New (PRadioButtons, Init (R,
NewSItem ('Id',
NewSItem ('Price',
NewSItem ('Starting location',
NewSItem ('Destination',
NewSItem ('Date',
NewSItem ('Time',
Nil))))))));
Insert(B);
R.Assign(3,1,10,2);
Insert(New(PLabel,Init(R,'Field',B)));
R.Assign(3,10,30,11);
B:=New(PInputLine,Init(R,128));
Insert(B);
R.Assign(8,12,26,14);
Insert(New (PButton, Init (R, '~F~ind', cmOk, bfDefault)));
end;
procedure TMyAppl.ListFlights;
var
FlightList: PListWindow;
R:TRect;
f: text;
begin
R.Assign(1, 1, 80, 24);
TMyAppl.PrintFlights;
FlightList:=New(PListWindow, Init (R, 'Flight List', WnNoNumber));
DeskTop^.Insert(FlightList);
end;
procedure TMyAppl.NewFlight;
var
Dialog: PAddDialog;
R: TRect;
Control: Word;
begin
R.Assign(0, 0, 40, 13);
R.Move(Random(39), Random(10));
Dialog := New(PAddDialog, Init(R, 'Add Flight'));
Dialog^.SetData(Add);
Control := DeskTop^.ExecView(Dialog);
if Control = cmOk then begin
Dialog^.GetData(Add);
FlightCollection^.Insert(New(PFlight, Init(
'1', Add.Price, Add.Start, Add.Dest, Add.Date, Add.Time)));
end;
end;
procedure TMyAppl.FindFlight;
var
Dialog: PFindDialog;
R: TRect;
Control: Word;
Data : PDosStream;
begin
R.Assign(0, 0, 33, 15);
R.Move(Random(39), Random(10));
Dialog := New(PFindDialog, Init(R, 'Find Flight'));
Dialog^.SetData(Find);
Control := DeskTop^.ExecView(Dialog);
if Control <> cmCancel then begin
Dialog^.GetData(Find);
TMyAppl.SearchFlights;
end;
end;
destructor TMyAppl.Done;
var
i:integer;
procedure SaveFlight(P: PFlight); far;
begin
With P^ do
MessageBox('writing '+Id^+' '+Price^, nil, mfOkButton);
SaveFile.Put(P);
if SaveFile.Status <> stOk then MessageBox('Failed to write', nil, mfOkButton);
end;
begin
SaveFile.Init('Flight.res', stOpenWrite);
if SaveFile.Status <> stOk then MessageBox('Open Flight.res for write failed', nil, mfOkButton);
{ SaveFile.Put(FlightCollection);}
FlightCollection^.ForEach(@SaveFlight);
if SaveFile.Status = stPutError then MessageBox('Flight.res put collection failed', nil, mfOkButton);
SaveFile.Done;
end;
procedure TMyAppl.HandleEvent(var Event: TEvent);
begin
TApplication.HandleEvent(Event);
if Event.What = evCommand then
begin
case Event.Command of
cmListFlights: ListFlights;
cmAddDialog: NewFlight;
cmSearchDialog: FindFlight;
else
Exit;
end;
ClearEvent(Event);
end;
end;
begin
FlightAppl.Init;
FlightAppl.Run;
FlightAppl.Done;
end.
|
unit Sort.ListView;
interface
uses
Windows, ComCtrls;
type
PSortData = ^TSortData;
TSortData = record
Column: Integer;
CaseSensitive: Boolean;
Asc: Boolean;
end;
TListViewSort = record
private
class function ListViewCompare(lParam1, lParam2, lParamSort: LPARAM): Integer stdcall; static;
public
class procedure SortByColumn( AListView: TListView; AColumn: Integer; ACaseSensitive, AAsc: Boolean ); static;
end;
implementation
uses
Sort.StringCompare;
{ TListViewSort }
class function TListViewSort.ListViewCompare(lParam1, lParam2,
lParamSort: LPARAM): Integer;
var
ListItem1, ListItem2: TListItem;
SortData: PSortData;
begin
ListItem1 := TListItem(lParam1);
ListItem2 := TListItem(lParam2);
SortData := PSortData(lParamSort);
if SortData^.Column = 0 then
Result := NaturalOrderCompareString( ListItem1.Caption, ListItem2.Caption, SortData^.CaseSensitive )
else
Result := NaturalOrderCompareString( ListItem1.SubItems[SortData^.Column - 1], ListItem2.SubItems[SortData^.Column - 1], SortData^.CaseSensitive );
if SortData^.Asc = False then
Result := -Result;
end;
class procedure TListViewSort.SortByColumn(AListView: TListView; AColumn: Integer;
ACaseSensitive, AAsc: Boolean);
var
SortData: TSortData;
begin
SortData.Column := AColumn;
SortData.CaseSensitive := ACaseSensitive;
SortData.Asc := AAsc;
AListView.CustomSort( ListViewCompare, Integer(@SortData) );
end;
end.
|
unit x86_Inst;
interface
uses System.SysUtils, Winapi.Windows, XED,xed.RegEnum,XED.IClassEnum,xed.OperandEnum,
xed.OperandVisibilityEnum,xed.OperandTypeEnum,xed.OperandElementXtypeEnum,xed.OperandWidthEnum,
xed.NonterminalEnum,xed.OperandActionEnum,XED.CategoryEnum,XED.ExtensionEnum,XED.IsaSetEnum,xed.IFormEnum,
xed.SyntaxEnum,xed.RegClassEnum;
type
x86_register = record
private
FXED_Reg : TXED_Reg_Enum;
public
// Operator
class operator implicit(reg:TXED_Reg_Enum): x86_register;
class operator Equal(reg:x86_register; reg1:x86_register): Boolean;
class operator Equal(reg:TXED_Reg_Enum; reg1:x86_register): Boolean;
class operator NotEqual(reg:x86_register; reg1:x86_register): Boolean;
class operator NotEqual(reg:TXED_Reg_Enum; reg1:x86_register): Boolean;
class operator LessThan(reg:x86_register; reg1:x86_register): Boolean;
// wrappers
function get_name: PAnsiChar;
function get_class: TXED_Reg_Class_enum;
function get_class_name: PAnsiChar;
// Returns the specific width GPR reg class (like XED_REG_CLASS_GPR32 or XED_REG_CLASS_GPR64) for a given GPR register.
// Or XED_REG_INVALID if not a GPR.
function get_gpr_class: TXED_Reg_Class_enum;
function get_largest_enclosing_register32: x86_register;
function get_largest_enclosing_register: x86_register;
function get_width_bits :TXEDUnsignedInt32;
function get_width_bits64:TXEDUnsignedInt32;
// helpers - GPR
function is_gpr: Boolean;
function is_low_gpr: Boolean;
function is_high_gpr: Boolean;
function get_gpr8_low: x86_register; // al, cl, dl, bl
function get_gpr8_high: x86_register; // ah, ch, dh, bh
function get_gpr16: x86_register; // ax, cx, dx, bx
function get_gpr32: x86_register; // eax, ecx, edx, ebx
function get_gpr64: x86_register; // rax, rcx, rdx, rbx
// My Function
function is_valid : Boolean;
function is_pseudo: Boolean;
function is_flag: Boolean;
end;
x86_Operand = record
private
FOp : TXED_Operand ;
public
// Operands Access
function get_name: TXED_Operand_Enum;
function get_visibility: TXED_Operand_Visibility_Enum;
function get_type:TXED_Operand_Type_Enum;
function get_xtype:TXED_Operand_Element_Xtype_Enum;
function get_width:TXED_Operand_Width_Enum;
function get_width_bits(osz: TXEDUnsignedInt32):TXEDUnsignedInt32;
function get_nonterminal_name: TXED_Nonterminal_Enum;
function get_reg: TXED_Reg_Enum; // Careful with this one – use xed_decoded_inst_get_reg()! This one is probably not what you think it is.
function template_is_register: Boolean; // Careful with this one
function imm: TXEDUnsignedInt32;
procedure print(buf: PAnsiChar; buflen: Integer);
// Operand Enum Name Classification
function is_register(name: TXED_Operand_Enum): Boolean; overload;
function is_memory_addressing_register(name: TXED_Operand_Enum):Boolean;
// Operand Read/Written
function get_rw: TXED_Operand_Action_Enum;
function is_read: Boolean;
function is_read_only: Boolean;
function is_written: Boolean;
function is_written_only: Boolean;
function is_read_written: Boolean;
function is_conditional_read: Boolean;
function is_conditional_written: Boolean;
// helpers
function is_register: Boolean;overload;
function is_memory: Boolean;
function is_immediate: Boolean;
function is_branch: Boolean;
class operator Explicit(op: TXED_Operand ): x86_Operand ;
class operator implicit(i: x86_Operand ): TXED_Operand;
class operator implicit(op: TXED_Operand ):x86_Operand;
end;
Px86_instruction = ^x86_instruction;
x86_instruction = record
private
FDecInst : TXEDDecodedInstruction ;
FAddr : Uint64;
FBytes : TArray<TXEDUnsignedInt8>;
FInst : AnsiString;
public
constructor Create(addr: UInt64);
// xed functions
function get_name: PAnsiChar;
function get_category: TXED_Category_Enum;
function get_extension: TXED_Extension_Enum;
function get_isa_set: TXEDIsaSetEnum;
function get_iclass: TXED_iClass_Enum;
function get_machine_mode_bits: Cardinal;
// bytes
function get_length: xed_uint_t;
function get_byte(byte_index: xed_uint_t): xed_uint_t;
function get_operand_length_bits(operand_index: xed_uint_t): xed_uint_t;
function get_iform_enum: TXED_iform_Enum;
// operands
function operands_const: TXEDOperandValuesPtr;
// register
function get_register(name: TXED_Operand_Enum = XED_OPERAND_REG0): x86_register;
// memory
function get_number_of_memory_operands: xed_uint_t;
function is_mem_read(mem_idx: Cardinal = 0): Boolean;
function is_mem_written(mem_idx: Cardinal = 0): Boolean;
function is_mem_written_only(mem_idx: Cardinal = 0): Boolean;
function get_segment_register(mem_idx : Cardinal = 0): x86_register;
function get_base_register(mem_idx: Cardinal = 0): x86_register;
function get_index_register(mem_idx: Cardinal = 0): x86_register;
function get_scale(mem_idx: Cardinal = 0):xed_uint_t;
function has_displacement: xed_uint_t;
function get_memory_displacement(mem_idx: Cardinal = 0): TXEDUnsignedInt64;
function get_memory_displacement_width(mem_idx : Cardinal= 0): xed_uint_t;
function get_memory_displacement_width_bits(mem_idx: Cardinal = 0): xed_uint_t;
function get_memory_operand_length(mem_idx: Cardinal = 0): xed_uint_t;
// branch
function get_branch_displacement: TXEDInt32;
function get_branch_displacement_width: xed_uint_t;
function get_branch_displacement_width_bits: xed_uint_t;
// immediate
function get_immediate_width: xed_uint_t ;
function get_immediate_width_bits: xed_uint_t ;
function get_immediate_is_signed: Boolean;
function get_signed_immediate: TXEDInt32;
function get_unsigned_immediate: TXEDUnsignedInt64;
function get_second_immediate : TXEDUnsignedInt8;
// modification
procedure set_scale(scale: xed_uint_t);
procedure set_memory_displacement(disp: TXEDInt64; length_bytes: xed_uint_t );
procedure set_branch_displacement(disp: TXEDInt32; length_bytes: xed_uint_t );
procedure set_immediate_signed(x: TXEDInt32; length_bytes: xed_uint_t );
procedure set_immediate_unsigned(x: TXEDUnsignedInt64; length_bytes: xed_uint_t );
procedure set_memory_displacement_bits(disp: TXEDInt64; length_bits: xed_uint_t);
procedure set_branch_displacement_bits(disp: TXEDInt32; length_bits: xed_uint_t);
procedure set_immediate_signed_bits(x: TXEDInt32; length_bits: xed_uint_t);
procedure set_immediate_unsigned_bits(x: TXEDUnsignedInt64; length_bits: xed_uint_t);
// encoder
procedure init_from_decode;
procedure set_iclass(iclass: TXED_iClass_Enum);
procedure set_operand_order(i: xed_uint_t; name: TXED_Operand_Enum);
procedure set_uimm0(uimm: TXEDUnsignedInt64; nbytes: xed_uint_t);
procedure encode;
// flags
function uses_rflags: xed_bool_t;
function get_read_flag_set: TXED_Flag_SetPtr;
function get_written_flag_set: TXED_Flag_SetPtr;
// my Function
procedure decode(buf: pbyte; length: uint32; mmode : TXEDMachineMode; stack_addr_width: TXEDAddressWidth = XED_ADDRESS_WIDTH_32b);
function get_addr: uint64;
function get_operand(i: Cardinal): x86_operand ;
function get_operands: TArray<x86_operand>;
function get_bytes: TArray<TXEDUnsignedInt8>;
procedure get_read_written_registers(var read_registers: TArray<x86_register>; var written_registers:TArray<x86_register>);
function get_read_registers: TArray<x86_register>;
function get_written_registers: TArray<x86_register>;
// additional
function is_branch: Boolean;
// debug functions
function get_string: string;
procedure sprintf(buf: PAnsiChar; length: Integer) ;
function ToStr: string;
class operator implicit(i: x86_instruction ): TXEDDecodedInstruction;
end;
implementation
{ x86_Operand }
class operator x86_Operand.Explicit(op: TXED_Operand ): x86_Operand ;
begin
Result := default(x86_Operand) ;
Result.FOp := op ;
end;
class operator x86_Operand.implicit(i: x86_Operand): TXED_Operand;
begin
Result := i.FOp ;
end;
class operator x86_Operand.implicit(op: TXED_Operand): x86_Operand;
begin
Result := default(x86_Operand) ;
Result.FOp := op
end;
function x86_Operand.get_name: TXED_Operand_Enum;
begin
Result := xed_operand_name(@FOp);
end;
function x86_Operand.get_nonterminal_name: TXED_Nonterminal_Enum;
begin
Result := xed_operand_nonterminal_name(@FOp);
end;
function x86_Operand.get_reg: TXED_Reg_Enum;
begin
Result := xed_operand_reg(@FOp);
end;
function x86_Operand.get_rw: TXED_Operand_Action_Enum;
begin
Result := xed_operand_rw(@FOp);
end;
function x86_Operand.get_type: TXED_Operand_Type_Enum;
begin
Result := xed_operand_type(@FOp);
end;
function x86_Operand.get_visibility: TXED_Operand_Visibility_Enum;
begin
Result := xed_operand_operand_visibility(@FOp);
end;
function x86_Operand.get_width: TXED_Operand_Width_Enum;
begin
Result := xed_operand_width(@FOp);
end;
function x86_Operand.get_width_bits(osz: TXEDUnsignedInt32): TXEDUnsignedInt32;
begin
Result := xed_operand_width_bits(@FOp, osz);
end;
function x86_Operand.get_xtype: TXED_Operand_Element_Xtype_Enum;
begin
Result := xed_operand_xtype(@FOp);
end;
function x86_Operand.imm: TXEDUnsignedInt32;
begin
Result := xed_operand_imm(@FOp);
end;
function x86_Operand.is_branch: Boolean;
begin
Result := get_name = XED_OPERAND_RELBR;
end;
function x86_Operand.is_conditional_read: Boolean;
begin
Result := xed_operand_conditional_read(@FOp) <> 0;
end;
function x86_Operand.is_conditional_written: Boolean;
begin
Result := xed_operand_conditional_write(@FOp) <> 0;
end;
function x86_Operand.is_immediate: Boolean;
begin
Result := (get_name = XED_OPERAND_IMM0) or (get_name = XED_OPERAND_IMM1);
end;
function x86_Operand.is_memory: Boolean;
begin
Result := (get_name = XED_OPERAND_MEM0) or (get_name = XED_OPERAND_MEM1);
end;
function x86_Operand.is_memory_addressing_register(name: TXED_Operand_Enum): Boolean;
begin
Result := xed_operand_is_memory_addressing_register(name);
end;
function x86_Operand.is_read: Boolean;
begin
Result := xed_operand_read(@FOp) <> 0;
end;
function x86_Operand.is_read_only: Boolean;
begin
Result := xed_operand_read_only(@FOp) <> 0;
end;
function x86_Operand.is_read_written: Boolean;
begin
Result := xed_operand_read_and_written(@FOp) <> 0;
end;
function x86_Operand.is_register(name: TXED_Operand_Enum): Boolean;
begin
Result := xed_operand_is_register(name);
end;
function x86_Operand.is_register: Boolean;
begin
Result := is_register(get_name);
end;
function x86_Operand.is_written: Boolean;
begin
Result := xed_operand_written(@FOp) <> 0;
end;
function x86_Operand.is_written_only: Boolean;
begin
Result := xed_operand_written_only(@FOp) <> 0;
end;
procedure x86_Operand.print(buf: PAnsiChar; buflen: Integer);
begin
xed_operand_print(@FOp, buf, buflen);
end;
function x86_Operand.template_is_register: Boolean;
begin
Result := xed_operand_template_is_register(@FOp);
end;
{ x86_register }
class operator x86_register.Equal(reg, reg1: x86_register): Boolean;
begin
Result := reg.FXED_Reg = reg1.FXED_Reg;
end;
class operator x86_register.Equal(reg: TXED_Reg_Enum; reg1: x86_register): Boolean;
begin
Result := reg = reg1.FXED_Reg;
end;
class operator x86_register.NotEqual(reg, reg1: x86_register): Boolean;
begin
Result := reg.FXED_Reg <> reg1.FXED_Reg;
end;
class operator x86_register.NotEqual(reg: TXED_Reg_Enum; reg1: x86_register): Boolean;
begin
Result := reg <> reg1.FXED_Reg;
end;
class operator x86_register.LessThan(reg, reg1: x86_register): Boolean;
begin
Result := reg.FXED_Reg < reg1.FXED_Reg;
end;
class operator x86_register.implicit(reg: TXED_Reg_Enum): x86_register;
begin
Result := default(x86_register);
Result.FXED_Reg := reg;
end;
function x86_register.is_flag: Boolean;
begin
Result := (XED_REG_FLAGS_FIRST <= FXED_Reg) and (FXED_Reg <= XED_REG_FLAGS_LAST);
end;
function x86_register.is_pseudo: Boolean;
begin
Result := ((XED_REG_PSEUDO_FIRST <= FXED_Reg) and (FXED_Reg <= XED_REG_PSEUDO_LAST)) or (xed_reg_enum_t_last <= FXED_Reg);
end;
function x86_register.is_valid: Boolean;
begin
Result := FXED_Reg <> XED_REG_INVALID;
end;
function x86_register.get_name: PAnsiChar;
begin
Result := xed_reg_enum_t2str(FXED_Reg);
end;
function x86_register.get_class: TXED_Reg_Class_enum;
begin
Result := xed_reg_class(FXED_Reg);
end;
function x86_register.get_class_name: PAnsiChar;
begin
Result := xed_reg_class_enum_t2str(get_class);
end;
function x86_register.get_gpr_class: TXED_Reg_Class_enum;
begin
Result := xed_gpr_reg_class(FXED_Reg);
end;
function x86_register.get_largest_enclosing_register32: x86_register;
begin
Result := xed_get_largest_enclosing_register32(FXED_Reg);
end;
function x86_register.get_largest_enclosing_register: x86_register;
begin
Result := xed_get_largest_enclosing_register(FXED_Reg);
end;
function x86_register.get_width_bits :TXEDUnsignedInt32;
begin
Result := xed_get_register_width_bits(FXED_Reg);
end;
function x86_register.get_width_bits64:TXEDUnsignedInt32;
begin
Result := xed_get_register_width_bits64(FXED_Reg);
end;
function x86_register.is_gpr: Boolean;
begin
Result := get_class = XED_REG_CLASS_GPR;
end;
function x86_register.is_low_gpr: Boolean;
begin
case FXED_Reg of
XED_REG_AL,
XED_REG_CL,
XED_REG_DL,
XED_REG_BL,
XED_REG_SPL,
XED_REG_BPL,
XED_REG_SIL,
XED_REG_DIL: Result := True;
XED_REG_AH,
XED_REG_CH,
XED_REG_DH,
XED_REG_BH: Result := False;
else
raise Exception.Create('Error in is_low_gpr()');
end;
end;
function x86_register.is_high_gpr: Boolean;
begin
case FXED_Reg of
XED_REG_AL,
XED_REG_CL,
XED_REG_DL,
XED_REG_BL,
XED_REG_SPL,
XED_REG_BPL,
XED_REG_SIL,
XED_REG_DIL: Result := False;
XED_REG_AH,
XED_REG_CH,
XED_REG_DH,
XED_REG_BH: Result := True;
else
raise Exception.Create('Error in is_low_gpr()');
end;
end;
function x86_register.get_gpr8_low: x86_register;
begin
case FXED_Reg of
XED_REG_AL,
XED_REG_AH,
XED_REG_AX,
XED_REG_EAX,
XED_REG_RAX : Result := XED_REG_AL;
XED_REG_CL,
XED_REG_CH,
XED_REG_CX,
XED_REG_ECX,
XED_REG_RCX: Result := XED_REG_CL;
XED_REG_DL,
XED_REG_DH,
XED_REG_DX,
XED_REG_EDX,
XED_REG_RDX: Result := XED_REG_DL;
XED_REG_BL,
XED_REG_BH,
XED_REG_BX,
XED_REG_EBX,
XED_REG_RBX: Result := XED_REG_BL;
XED_REG_SPL,
XED_REG_SP,
XED_REG_ESP,
XED_REG_RSP: Result := XED_REG_SPL;
XED_REG_BPL,
XED_REG_BP,
XED_REG_EBP,
XED_REG_RBP: Result := XED_REG_BPL;
XED_REG_SIL,
XED_REG_SI,
XED_REG_ESI,
XED_REG_RSI: Result := XED_REG_SIL;
XED_REG_DIL,
XED_REG_DI,
XED_REG_EDI,
XED_REG_RDI: Result := XED_REG_DIL;
XED_REG_R8B,
XED_REG_R8W,
XED_REG_R8D,
XED_REG_R8: Result := XED_REG_R8B;
XED_REG_R9B,
XED_REG_R9W,
XED_REG_R9D,
XED_REG_R9: Result := XED_REG_R9B;
XED_REG_R10B,
XED_REG_R10W,
XED_REG_R10D,
XED_REG_R10: Result := XED_REG_R10B;
XED_REG_R11B,
XED_REG_R11W,
XED_REG_R11D,
XED_REG_R11: Result := XED_REG_R11B;
XED_REG_R12B,
XED_REG_R12W,
XED_REG_R12D,
XED_REG_R12: Result := XED_REG_R12B;
XED_REG_R13B,
XED_REG_R13W,
XED_REG_R13D,
XED_REG_R13: Result := XED_REG_R13B;
XED_REG_R14B,
XED_REG_R14W,
XED_REG_R14D,
XED_REG_R14: Result := XED_REG_R14B;
XED_REG_R15B,
XED_REG_R15W,
XED_REG_R15D,
XED_REG_R15: Result := XED_REG_R15B;
else
raise Exception.Create('Error in get_gpr8_low() : '+ get_name);
end;
end;
function x86_register.get_gpr8_high: x86_register;
begin
case FXED_Reg of
XED_REG_AL,
XED_REG_AH,
XED_REG_AX,
XED_REG_EAX,
XED_REG_RAX : Result := XED_REG_AH;
XED_REG_CL,
XED_REG_CH,
XED_REG_CX,
XED_REG_ECX,
XED_REG_RCX: Result := XED_REG_CH;
XED_REG_DL,
XED_REG_DH,
XED_REG_DX,
XED_REG_EDX,
XED_REG_RDX: Result := XED_REG_DH;
XED_REG_BL,
XED_REG_BH,
XED_REG_BX,
XED_REG_EBX,
XED_REG_RBX: Result := XED_REG_BH;
XED_REG_SPL,
XED_REG_SP,
XED_REG_ESP,
XED_REG_RSP: Result := XED_REG_INVALID;
XED_REG_BPL,
XED_REG_BP,
XED_REG_EBP,
XED_REG_RBP: Result := XED_REG_INVALID;
XED_REG_SIL,
XED_REG_SI,
XED_REG_ESI,
XED_REG_RSI: Result := XED_REG_INVALID;
XED_REG_DIL,
XED_REG_DI,
XED_REG_EDI,
XED_REG_RDI: Result := XED_REG_INVALID;
XED_REG_R8B,
XED_REG_R8W,
XED_REG_R8D,
XED_REG_R8: Result := XED_REG_INVALID;
XED_REG_R9B,
XED_REG_R9W,
XED_REG_R9D,
XED_REG_R9: Result := XED_REG_INVALID;
XED_REG_R10B,
XED_REG_R10W,
XED_REG_R10D,
XED_REG_R10: Result := XED_REG_INVALID;
XED_REG_R11B,
XED_REG_R11W,
XED_REG_R11D,
XED_REG_R11: Result := XED_REG_INVALID;
XED_REG_R12B,
XED_REG_R12W,
XED_REG_R12D,
XED_REG_R12: Result := XED_REG_INVALID;
XED_REG_R13B,
XED_REG_R13W,
XED_REG_R13D,
XED_REG_R13: Result := XED_REG_INVALID;
XED_REG_R14B,
XED_REG_R14W,
XED_REG_R14D,
XED_REG_R14: Result := XED_REG_INVALID;
XED_REG_R15B,
XED_REG_R15W,
XED_REG_R15D,
XED_REG_R15: Result := XED_REG_INVALID;
else
raise Exception.Create('Error in get_gpr8_high()');
end;
end;
function x86_register.get_gpr16: x86_register;
begin
case FXED_Reg of
XED_REG_AL,
XED_REG_AH,
XED_REG_AX,
XED_REG_EAX,
XED_REG_RAX : Result := XED_REG_AX;
XED_REG_CL,
XED_REG_CH,
XED_REG_CX,
XED_REG_ECX,
XED_REG_RCX: Result := XED_REG_CX;
XED_REG_DL,
XED_REG_DH,
XED_REG_DX,
XED_REG_EDX,
XED_REG_RDX: Result := XED_REG_DX;
XED_REG_BL,
XED_REG_BH,
XED_REG_BX,
XED_REG_EBX,
XED_REG_RBX: Result := XED_REG_BX;
XED_REG_SPL,
XED_REG_SP,
XED_REG_ESP,
XED_REG_RSP: Result := XED_REG_SP;
XED_REG_BPL,
XED_REG_BP,
XED_REG_EBP,
XED_REG_RBP: Result := XED_REG_BP;
XED_REG_SIL,
XED_REG_SI,
XED_REG_ESI,
XED_REG_RSI: Result := XED_REG_SI;
XED_REG_DIL,
XED_REG_DI,
XED_REG_EDI,
XED_REG_RDI: Result := XED_REG_DI;
XED_REG_R8B,
XED_REG_R8W,
XED_REG_R8D,
XED_REG_R8: Result := XED_REG_R8W;
XED_REG_R9B,
XED_REG_R9W,
XED_REG_R9D,
XED_REG_R9: Result := XED_REG_R9W;
XED_REG_R10B,
XED_REG_R10W,
XED_REG_R10D,
XED_REG_R10: Result := XED_REG_R10W;
XED_REG_R11B,
XED_REG_R11W,
XED_REG_R11D,
XED_REG_R11: Result := XED_REG_R11W;
XED_REG_R12B,
XED_REG_R12W,
XED_REG_R12D,
XED_REG_R12: Result := XED_REG_R12W;
XED_REG_R13B,
XED_REG_R13W,
XED_REG_R13D,
XED_REG_R13: Result := XED_REG_R13W;
XED_REG_R14B,
XED_REG_R14W,
XED_REG_R14D,
XED_REG_R14: Result := XED_REG_R14W;
XED_REG_R15B,
XED_REG_R15W,
XED_REG_R15D,
XED_REG_R15: Result := XED_REG_R15W;
else
raise Exception.Create('Error in get_gpr16()');
end;
end;
function x86_register.get_gpr32: x86_register;
begin
case FXED_Reg of
XED_REG_AL,
XED_REG_AH,
XED_REG_AX,
XED_REG_EAX,
XED_REG_RAX : Result := XED_REG_EAX;
XED_REG_CL,
XED_REG_CH,
XED_REG_CX,
XED_REG_ECX,
XED_REG_RCX: Result := XED_REG_ECX;
XED_REG_DL,
XED_REG_DH,
XED_REG_DX,
XED_REG_EDX,
XED_REG_RDX: Result := XED_REG_EDX;
XED_REG_BL,
XED_REG_BH,
XED_REG_BX,
XED_REG_EBX,
XED_REG_RBX: Result := XED_REG_EBX;
XED_REG_SPL,
XED_REG_SP,
XED_REG_ESP,
XED_REG_RSP: Result := XED_REG_ESP;
XED_REG_BPL,
XED_REG_BP,
XED_REG_EBP,
XED_REG_RBP: Result := XED_REG_EBP;
XED_REG_SIL,
XED_REG_SI,
XED_REG_ESI,
XED_REG_RSI: Result := XED_REG_ESI;
XED_REG_DIL,
XED_REG_DI,
XED_REG_EDI,
XED_REG_RDI: Result := XED_REG_EDI;
XED_REG_R8B,
XED_REG_R8W,
XED_REG_R8D,
XED_REG_R8: Result := XED_REG_R8D;
XED_REG_R9B,
XED_REG_R9W,
XED_REG_R9D,
XED_REG_R9: Result := XED_REG_R9D;
XED_REG_R10B,
XED_REG_R10W,
XED_REG_R10D,
XED_REG_R10: Result := XED_REG_R10D;
XED_REG_R11B,
XED_REG_R11W,
XED_REG_R11D,
XED_REG_R11: Result := XED_REG_R11D;
XED_REG_R12B,
XED_REG_R12W,
XED_REG_R12D,
XED_REG_R12: Result := XED_REG_R12D;
XED_REG_R13B,
XED_REG_R13W,
XED_REG_R13D,
XED_REG_R13: Result := XED_REG_R13D;
XED_REG_R14B,
XED_REG_R14W,
XED_REG_R14D,
XED_REG_R14: Result := XED_REG_R14D;
XED_REG_R15B,
XED_REG_R15W,
XED_REG_R15D,
XED_REG_R15: Result := XED_REG_R15D;
else
raise Exception.Create('Error in get_gpr32()');
end;
end;
function x86_register.get_gpr64: x86_register;
begin
case FXED_Reg of
XED_REG_AL,
XED_REG_AH,
XED_REG_AX,
XED_REG_EAX,
XED_REG_RAX : Result := XED_REG_RAX;
XED_REG_CL,
XED_REG_CH,
XED_REG_CX,
XED_REG_ECX,
XED_REG_RCX: Result := XED_REG_RCX;
XED_REG_DL,
XED_REG_DH,
XED_REG_DX,
XED_REG_EDX,
XED_REG_RDX: Result := XED_REG_RDX;
XED_REG_BL,
XED_REG_BH,
XED_REG_BX,
XED_REG_EBX,
XED_REG_RBX: Result := XED_REG_RBX;
XED_REG_SPL,
XED_REG_SP,
XED_REG_ESP,
XED_REG_RSP: Result := XED_REG_RSP;
XED_REG_BPL,
XED_REG_BP,
XED_REG_EBP,
XED_REG_RBP: Result := XED_REG_RBP;
XED_REG_SIL,
XED_REG_SI,
XED_REG_ESI,
XED_REG_RSI: Result := XED_REG_RSI;
XED_REG_DIL,
XED_REG_DI,
XED_REG_EDI,
XED_REG_RDI: Result := XED_REG_RDI;
XED_REG_R8B,
XED_REG_R8W,
XED_REG_R8D,
XED_REG_R8: Result := XED_REG_R8;
XED_REG_R9B,
XED_REG_R9W,
XED_REG_R9D,
XED_REG_R9: Result := XED_REG_R9;
XED_REG_R10B,
XED_REG_R10W,
XED_REG_R10D,
XED_REG_R10: Result := XED_REG_R10;
XED_REG_R11B,
XED_REG_R11W,
XED_REG_R11D,
XED_REG_R11: Result := XED_REG_R11;
XED_REG_R12B,
XED_REG_R12W,
XED_REG_R12D,
XED_REG_R12: Result := XED_REG_R12;
XED_REG_R13B,
XED_REG_R13W,
XED_REG_R13D,
XED_REG_R13: Result := XED_REG_R13;
XED_REG_R14B,
XED_REG_R14W,
XED_REG_R14D,
XED_REG_R14: Result := XED_REG_R14;
XED_REG_R15B,
XED_REG_R15W,
XED_REG_R15D,
XED_REG_R15: Result := XED_REG_R15;
else
raise Exception.Create('Error in get_gpr64()');
end;
end;
{ x86_instruction }
constructor x86_instruction.Create(addr: UInt64);
begin
FAddr := addr;
FDecInst := default(TXEDDecodedInstruction);
SetLength(FBytes,16);
end;
procedure x86_instruction.decode(buf: pbyte; length: uint32; mmode: TXEDMachineMode; stack_addr_width: TXEDAddressWidth);
var
xedd : TXEDDecodedInstructionPtr;
xed_error : TXEDErrorEnum;
begin
xedd := @FDecInst;
// initialize for xed_decode
xed_decoded_inst_zero(xedd);
xed_decoded_inst_set_mode(xedd, mmode, stack_addr_width);
// decode array of bytes to xed_decoded_inst_t
CopyMemory(@FBytes[0],buf,length) ;
xed_error := xed_decode(xedd, @FBytes[0], length);
FInst := AnsiString(get_string);
case xed_error of
XED_ERROR_NONE: Exit;
else
raise Exception.Create('xed_decode failed at Address: '+ IntToHex(FAddr));
end;
end;
function x86_instruction.get_category: TXED_Category_Enum;
begin
Result := xed_decoded_inst_get_category(@FDecInst);
end;
function x86_instruction.get_extension: TXED_Extension_Enum;
begin
Result := xed_decoded_inst_get_extension(@FDecInst);
end;
function x86_instruction.get_iclass: TXED_iClass_Enum;
begin
Result := xed_decoded_inst_get_iclass(@FDecInst);
end;
function x86_instruction.get_isa_set: TXEDIsaSetEnum;
begin
Result := xed_decoded_inst_get_isa_set(@FDecInst);
end;
function x86_instruction.get_machine_mode_bits: Cardinal;
begin
Result := xed_decoded_inst_get_machine_mode_bits(@FDecInst);
end;
function x86_instruction.get_name: PAnsiChar;
begin
Result := xed_iclass_enum_t2str(get_iclass);
end;
function x86_instruction.get_operand(i: Cardinal): x86_operand;
var
xi : TXEDInstructionPtr;
begin
xi := xed_decoded_inst_inst(@FDecInst);
var p := xed_inst_operand(xi, i);
Result := x86_operand( p^ );
end;
function x86_instruction.get_operands: TArray<x86_operand>;
var
operands : TArray<x86_operand>;
xi : TXEDInstructionPtr;
operand : x86_operand;
noperands,i: Cardinal;
begin
xi := xed_decoded_inst_inst(@FDecInst);
noperands := xed_inst_noperands(xi);
for i := 0 to noperands - 1 do
begin
if noperands = 0 then Break;
var p := xed_inst_operand(xi, i);
operand := x86_operand(p^ );
operands := operands + [ operand];
end;
Result := operands;
end;
function x86_instruction.get_length: xed_uint_t;
begin
Result := xed_decoded_inst_get_length(@FDecInst);
end;
function x86_instruction.get_addr: uint64;
begin
Result := FAddr;
end;
function x86_instruction.get_byte(byte_index: xed_uint_t): xed_uint_t;
begin
Result := xed_decoded_inst_get_byte(@FDecInst, byte_index);
end;
function x86_instruction.get_bytes: TArray<TXEDUnsignedInt8>;
var
bytes : TArray<TXEDUnsignedInt8>;
len,i : xed_uint_t;
begin
len := get_length;
for i := 0 to len - 1 do
bytes := bytes + [ get_byte(i) ];
Result := bytes;
end;
function x86_instruction.get_operand_length_bits(operand_index: xed_uint_t): xed_uint_t;
begin
Result := xed_decoded_inst_operand_length_bits(@FDecInst, operand_index);
end;
function x86_instruction.get_iform_enum: TXED_iform_Enum;
begin
Result := xed_decoded_inst_get_iform_enum(@FDecInst);
end;
function x86_instruction.operands_const: TXEDOperandValuesPtr;
begin
Result := xed_decoded_inst_operands_const(@FDecInst);
end;
procedure x86_instruction.get_read_written_registers(var read_registers, written_registers: TArray<x86_register>);
var
operands : TArray<x86_operand>;
operand : x86_operand;
begin
operands := get_operands;
for operand in operands do
begin
var targetReg : x86_register;
var hasRead : Boolean ;
var hasWritten : Boolean ;
if operand.is_register then
begin
// Operand is register
targetReg := get_register(operand.get_name);
hasRead := operand.is_read;
hasWritten := operand.is_written;
end
else if operand.is_memory then
begin
// Ignore memory
continue;
end
else if operand.is_immediate then
begin
// Ignore immediate
continue;
end
else if (operand.get_name = XED_OPERAND_BASE0) or (operand.get_name = XED_OPERAND_BASE1) then
begin
// BASE?
targetReg := get_register(operand.get_name);
hasRead := operand.is_read;
hasWritten := operand.is_written;
// printf("\t\t%p BASE0/BASE1 %s R:%d W:%d\n", addr, access_register.get_name(), read, write);
end
else if operand.is_branch then
begin
// Ignore branch
continue;
end
else if operand.get_name = XED_OPERAND_AGEN then
begin
// Ignore agen
continue;
end else
begin
raise Exception.Create('get_read_written_registers operand name: '+ xed_operand_enum_t2str(operand.get_name));
end;
if not targetReg.is_pseudo and targetReg.is_valid then
begin
if (hasRead) then
read_registers := read_registers + [ targetReg ];
if hasWritten then
written_registers := written_registers + [ targetReg ];
end
end;
end;
function x86_instruction.get_register(name: TXED_Operand_Enum = XED_OPERAND_REG0): x86_register;
begin
Result := xed_decoded_inst_get_reg(@FDecInst, name);
end;
function x86_instruction.get_read_registers: TArray<x86_register>;
var
readRegs, writtenRegs : TArray<x86_register> ;
begin
get_read_written_registers(readRegs, writtenRegs);
Result := readRegs;
end;
function x86_instruction.get_number_of_memory_operands: xed_uint_t;
begin
Result := xed_decoded_inst_number_of_memory_operands(@FDecInst);
end;
function x86_instruction.is_mem_read(mem_idx: Cardinal = 0): Boolean;
begin
Result := xed_decoded_inst_mem_read(@FDecInst, mem_idx) <> 0;
end;
function x86_instruction.is_mem_written(mem_idx: Cardinal = 0): Boolean;
begin
Result := xed_decoded_inst_mem_written(@FDecInst, mem_idx) <> 0;
end;
function x86_instruction.is_mem_written_only(mem_idx: Cardinal = 0): Boolean;
begin
Result := False;
if xed_decoded_inst_mem_written_only(@FDecInst, mem_idx) <> 0 then
Result := True;
end;
function x86_instruction.get_segment_register(mem_idx : Cardinal = 0): x86_register;
begin
Result := xed_decoded_inst_get_seg_reg(@FDecInst, mem_idx);
end;
function x86_instruction.get_base_register(mem_idx: Cardinal = 0): x86_register;
begin
Result := xed_decoded_inst_get_base_reg(@FDecInst, mem_idx);
end;
function x86_instruction.get_index_register(mem_idx: Cardinal = 0): x86_register;
begin
Result := xed_decoded_inst_get_index_reg(@FDecInst, mem_idx);
end;
function x86_instruction.get_scale(mem_idx: Cardinal = 0):xed_uint_t;
begin
Result := xed_decoded_inst_get_scale(@FDecInst, mem_idx);
end;
function x86_instruction.has_displacement: xed_uint_t;
begin
Result := xed_operand_values_has_memory_displacement(@FDecInst);
end;
function x86_instruction.get_memory_displacement(mem_idx: Cardinal = 0): TXEDUnsignedInt64;
begin
Result := xed_decoded_inst_get_memory_displacement(@FDecInst, mem_idx);
end;
function x86_instruction.get_memory_displacement_width(mem_idx : Cardinal= 0): xed_uint_t;
begin
Result := xed_decoded_inst_get_memory_displacement_width(@FDecInst, mem_idx);
end;
function x86_instruction.get_memory_displacement_width_bits(mem_idx: Cardinal = 0): xed_uint_t;
begin
Result := xed_decoded_inst_get_memory_displacement_width_bits(@FDecInst, mem_idx);
end;
function x86_instruction.get_memory_operand_length(mem_idx: Cardinal = 0): xed_uint_t;
begin
Result := xed_decoded_inst_get_memory_operand_length(@FDecInst, mem_idx);
end;
function x86_instruction.get_branch_displacement: TXEDInt32;
begin
Result := xed_decoded_inst_get_branch_displacement(@FDecInst);
end;
function x86_instruction.get_branch_displacement_width: xed_uint_t;
begin
Result := xed_decoded_inst_get_branch_displacement_width(@FDecInst);
end;
function x86_instruction.get_branch_displacement_width_bits: xed_uint_t;
begin
Result := xed_decoded_inst_get_branch_displacement_width_bits(@FDecInst);
end;
function x86_instruction.get_immediate_width: xed_uint_t ;
begin
Result := xed_decoded_inst_get_immediate_width(@FDecInst);
end;
function x86_instruction.get_immediate_width_bits: xed_uint_t ;
begin
Result := xed_decoded_inst_get_immediate_width_bits(@FDecInst);
end;
function x86_instruction.get_immediate_is_signed: Boolean;
begin
// Return true if the first immediate (IMM0) is signed.
Result := xed_decoded_inst_get_immediate_is_signed(@FDecInst) = 1;
end;
function x86_instruction.get_signed_immediate: TXEDInt32;
begin
Result := xed_decoded_inst_get_signed_immediate(@FDecInst);
end;
function x86_instruction.get_unsigned_immediate: TXEDUnsignedInt64;
begin
if get_signed_immediate = 0 then
Exit( xed_decoded_inst_get_unsigned_immediate(@FDecInst) );
Result := xed_sign_extend_arbitrary_to_64( xed_decoded_inst_get_signed_immediate(@FDecInst), get_immediate_width_bits);
end;
function x86_instruction.get_second_immediate : TXEDUnsignedInt8;
begin
Result := xed_decoded_inst_get_second_immediate(@FDecInst);
end;
procedure x86_instruction.set_scale(scale: xed_uint_t);
begin
xed_decoded_inst_set_scale(@FDecInst, scale);
end;
procedure x86_instruction.set_memory_displacement(disp: TXEDInt64; length_bytes: xed_uint_t );
begin
xed_decoded_inst_set_memory_displacement(@FDecInst, disp, length_bytes);
end;
procedure x86_instruction.set_branch_displacement(disp: TXEDInt32; length_bytes: xed_uint_t );
begin
xed_decoded_inst_set_branch_displacement(@FDecInst, disp, length_bytes);
end;
procedure x86_instruction.set_immediate_signed(x: TXEDInt32; length_bytes: xed_uint_t );
begin
xed_decoded_inst_set_immediate_signed(@FDecInst, x, length_bytes);
end;
procedure x86_instruction.set_immediate_unsigned(x: TXEDUnsignedInt64; length_bytes: xed_uint_t );
begin
xed_decoded_inst_set_immediate_unsigned(@FDecInst, x, length_bytes);
end;
procedure x86_instruction.set_memory_displacement_bits(disp: TXEDInt64; length_bits: xed_uint_t);
begin
xed_decoded_inst_set_memory_displacement_bits(@FDecInst, disp, length_bits);
end;
procedure x86_instruction.set_branch_displacement_bits(disp: TXEDInt32; length_bits: xed_uint_t);
begin
xed_decoded_inst_set_branch_displacement_bits(@FDecInst, disp, length_bits);
end;
procedure x86_instruction.set_immediate_signed_bits(x: TXEDInt32; length_bits: xed_uint_t);
begin
xed_decoded_inst_set_immediate_signed_bits(@FDecInst, x, length_bits);
end;
procedure x86_instruction.set_immediate_unsigned_bits(x: TXEDUnsignedInt64; length_bits: xed_uint_t);
begin
xed_decoded_inst_set_immediate_unsigned_bits(@FDecInst, x, length_bits);
end;
procedure x86_instruction.init_from_decode;
begin
xed_encoder_request_init_from_decode(@FDecInst);
end;
procedure x86_instruction.set_iclass(iclass: TXED_iClass_Enum);
begin
xed_encoder_request_set_iclass(@FDecInst, iclass);
end;
procedure x86_instruction.set_operand_order(i: xed_uint_t; name: TXED_Operand_Enum);
begin
xed_encoder_request_set_operand_order(@FDecInst, i, name);
end;
procedure x86_instruction.set_uimm0(uimm: TXEDUnsignedInt64; nbytes: xed_uint_t);
begin
xed_encoder_request_set_uimm0(@FDecInst, uimm, nbytes);
end;
procedure x86_instruction.encode;
var
olen : TXEDUnsignedInt32;
buf : Array[0..15] of Byte;
begin
if xed_encode(@FDecInst, @buf[0], 16, @olen) = XED_ERROR_NONE then
decode(@buf[0], olen, XED_MACHINE_MODE_LEGACY_32);
end;
function x86_instruction.uses_rflags: xed_bool_t;
begin
Result := xed_decoded_inst_uses_rflags(@FDecInst);
end;
function x86_instruction.get_read_flag_set: TXED_Flag_SetPtr;
var
rfi : TXED_Simple_FlagPtr;
begin
rfi := xed_decoded_inst_get_rflags_info(@FDecInst);
Result := xed_simple_flag_get_read_flag_set(rfi);
end;
function x86_instruction.get_written_flag_set: TXED_Flag_SetPtr;
var
rfi : TXED_Simple_FlagPtr;
begin
rfi := xed_decoded_inst_get_rflags_info(@FDecInst);
Result := xed_simple_flag_get_written_flag_set(rfi);
end;
function x86_instruction.get_written_registers: TArray<x86_register>;
var
readRegs, writtenRegs : TArray<x86_register> ;
begin
get_read_written_registers(readRegs, writtenRegs);
Result := writtenRegs;
end;
function x86_instruction.ToStr:string;
var
buf: array[0..63] of AnsiChar;
begin
sprintf(buf, 64);
Result := Format('%08x %s',[get_addr,PAnsiChar(@buf[0])]);
end;
procedure x86_instruction.sprintf(buf: PAnsiChar; length: Integer);
begin
xed_format_context(XED_SYNTAX_INTEL, @FDecInst, buf, length, FAddr, nil, nil);
end;
function x86_instruction.get_string: string;
var
buf: array[0..63] of AnsiChar;
begin
sprintf(buf, 64);
Result := string( AnsiString( PAnsiChar(@buf[0])) );
end;
class operator x86_instruction.implicit(i: x86_instruction): TXEDDecodedInstruction;
begin
Result := i.FDecInst;
end;
function x86_instruction.is_branch: Boolean;
begin
Result := False;
case get_category of
XED_CATEGORY_COND_BR,
XED_CATEGORY_UNCOND_BR: Result := true;
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, ADODB, StdCtrls;
type
TFrmModelUpd = class(TForm)
ADOConnection1: TADOConnection;
ADOQuery1: TADOQuery;
edtMod: TEdit;
Label1: TLabel;
Button1: TButton;
Edit1: TEdit;
ADOQuery2: TADOQuery;
ADOQuery2ModuleInfo: TStringField;
procedure Button1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
//Client StatUp Variables
sPW, sUser, sDBAlias, sServer, sResult : String;
function GetConnectionStr:String;
public
{ Public declarations }
end;
var
FrmModelUpd: TFrmModelUpd;
implementation
uses Registry, uParamFunctions, uEncryptFunctions, uOperationSystem;
{$R *.DFM}
function TFrmModelUpd.GetConnectionStr:String;
var
Reg : TRegistry;
buildInfo: String;
begin
try
//Pega as info local
Reg := TRegistry.Create;
if ( getOS(buildInfo) = osW7 ) then
Reg.RootKey := HKEY_CURRENT_USER
else
Reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.OpenKey('SOFTWARE\AppleNet', True);
sResult := DecodeServerInfo(Reg.ReadString('ServerInfo'), 'Server', CIPHER_TEXT_STEALING, FMT_UU);
sServer := ParseParam(sResult, '#SRV#=');
sDBAlias := ParseParam(sResult, '#DB#=');
sUser := ParseParam(sResult, '#USER#=');
sPW := ParseParam(sResult, '#PW#=');
result := SetConnectionStr(sUser, sPw, SDBAlias, sServer);
//Fechar o Registry
Reg.CloseKey;
Reg.Free;
except
ShowMessage('Connection Error !');
Abort;
end;
end;
procedure TFrmModelUpd.Button1Click(Sender: TObject);
var
sKey : String;
begin
Screen.Cursor:= crSQLWait;
ADOConnection1.Close;
ADOConnection1.ConnectionString := GetConnectionStr;
ADOConnection1.Open;
//GetKeyParam
ADOQuery2.Open;
sKey := ParseParam(DecodeServerInfo(ADOQuery2ModuleInfo.AsString,'ModInfo', CIPHER_TEXT_STEALING, FMT_UU),
'#Key#=');
ADOQuery2.Close;
if sKey <> '' then
sKey := '#Key#='+sKey+';'
else
sKey := '#Key#=N;';
with ADOQuery1 do
begin
Parameters.ParamByName('ModuleInfo').Value:=
EncodeServerInfo('#Module#='+ edtMod.Text +';#Date#='+ DateTimeToStr(now) +';'+sKey, 'ModInfo', CIPHER_TEXT_STEALING, FMT_UU);
ExecSQL;
end;
ADOConnection1.Close;
//Edit1.Text :=
//EncodeServerInfo('#Module#='+ edtMod.Text +';#Date#='+ DateTimeToStr(now) +';', 'ModInfo');
Screen.Cursor:= crDefault;
ShowMessage('Module "'+edtMod.Text+'" updated.');
//Menu Item Visible
{
with ADOQuery1 do
begin
SQL.Text := 'Update MenuItem Set Visible = 1';
ExecSQL;
end;
ADOConnection1.Close;
ShowMessage('System updated.');
}
Close;
end;
procedure TFrmModelUpd.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
end.
|
{$I-,Q-,R-,S-}
{Problema 11: Solitario Vacuno [Rob Kolstad, 2007]
El fin del verano en la granja es un tiempo lento, muy lento. Betsy tiene
poco que hacer aparte de jugar solitario. Por razones evidentes, el
solitario vacuno no es tan desafiante como un número de juegos de
solitario jugado por humanos.
El solitario vacuno es jugado usando un arreglo N x N (3 <= N <= 7) de
cartas normales con cuatro palos (Tréboles(C), Diamantes(D),
Corazones(H), y Espadas(S)) de 13 cartas (As, 2, 3, 4,..., 10(T),
Sota(J), Reina(Q), Rey(K)). Las cartas son nombradas con dos caracteres:
su valor (A, 2, 3, 4,...,9, T, J, Q, K) seguido de su palo (C, D, H, S).
Aquí hay un arreglo típico cuando N=4:
8S AD 3C AC (Ocho de Espadas, As de Diamantes, etc.)
8C 4H QD QS
5D 9H KC 7H
TC QC AS 2D
Para jugar este juego de solitario, Betsy comienza en la esquina inferior
izquierda (TC) y procede usando exactamente 2*N-2 movimientos de
'derecha' o 'arriba' para la esquina superior derecha. A través del
camino ella acumula puntos por cada carta (el As vale 1 punto, el 2 vale
2 puntos,..., el 9 vale 9 puntos, la T vale 10 puntos, J vale 11, Q vale
12, y K vale 13) conforme va haciendo el recorrido. Su propósito es
obtener el más alto puntaje.
Si el camino de Betsy hubiera sido TC-QC-AS-2C-7H-QS-AC, su puntaje
habría sido 10+12+1+2+7+12+1=45. Si ella hubiera tomado el lado izquierdo
y luego hacia arriba (TC-5D-8C-8S-AD-3C-AC), su puntaje habría sido
10+5+8+8+1+3+1=36, no tan bueno como con la otra ruta. El mejor puntaje
para este arreglo es 69 puntos TC-QC-9H-KC-QD-QS-AC =>
10+12+9+13+12+12+1).
Betsy quiere conocer el mejor puntaje que ella puede obtener. Una de las
vacas sabias una vez le dijo a ella algo acerca de “trabajar del final
hacia el comienzo”, pero ella no entendió lo que esta vaca le decía.
NOMBRE DEL PROBLEMA: solitair
FORMATO DE ENTRADA:
* Línea 1: Un solo entero N.
* Líneas 2..N+1: La línea i+1 tiene una lista de las cartas de la fila i
(la fila 1 es
la fila superior) usando N nombres de cartas separadas por
espacio organizados
en el orden obvio.
ENTRADA EJEMPLO (archivo solitair.in):
4
8S AD 3C AC
8C 4H QD QS
5D 9H KC 7H
TC QC AS 2D
FORMATO DE SALIDA:
* Línea 1: Una sola línea con un entero que es el mejor puntaje posible
que Betsy
puede obtener
SALIDA EJEMPLO (archivo solitair.out):
69
}
const
mx = 101;
mov : array[1..2,1..2] of shortint = ((-1,0),(0,1));
var
fe,fs : text;
n,sol : longint;
sav : array[boolean,1..mx*mx*mx,1..2] of longint;
best,tab : array[1..mx,1..mx] of longint;
mk : array[1..mx,1..mx] of boolean;
function cost(x : char) : longint;
begin
case x of
'2'..'9' : cost:=ord(x)-48;
'A' : cost:=1;
'T' : cost:=10;
'J' : cost:=11;
'Q' : cost:=12;
'K' : cost:=13;
end;
end;
procedure open;
var
i,j : longint;
st : char;
begin
assign(fe,'solitair.in'); reset(fe);
assign(fs,'solitair.out'); rewrite(fs);
readln(fe,n);
for i:=1 to n do
begin
for j:=1 to n do
begin
read(fe,st);
tab[i,j]:=cost(st);
read(fe,st);
read(fe,st);
end;
end;
close(fe);
end;
procedure work;
var
i,j,cp,ch,h1,h2,x,y : longint;
s : boolean;
begin
fillchar(best,sizeof(best),0);
x:=n; y:=1; best[x,y]:=tab[x,y];
s:=true; sav[s,1,1]:=x; sav[s,1,2]:=y;
cp:=1; ch:=0; sol:=best[x,y];
while cp>0 do
begin
fillchar(mk,sizeof(mk),false);
for i:=1 to cp do
begin
x:=sav[s,i,1]; y:=sav[s,i,2];
for j:=1 to 2 do
begin
h1:=x + mov[j,1]; h2:=y + mov[j,2];
if (h1 > 0) and (h1 <= n) and (h2 > 0) and (h2 <= n)
and (best[h1,h2] < best[x,y] + tab[h1,h2]) then
begin
best[h1,h2]:=best[x,y] + tab[h1,h2];
if best[h1,h2] > sol then sol:=best[h1,h2];
if not mk[h1,h2] then
begin
inc(ch);
sav[not s,ch,1]:=h1;
sav[not s,ch,2]:=h2;
mk[h1,h2]:=true;
end;
end;
end;
end;
s:=not s;
cp:=ch;
ch:=0;
end;
end;
procedure closer;
begin
writeln(fs,sol);
close(fs);
end;
begin
open;
work;
closer;
end. |
namespace GlHelper;
{$GLOBALS ON}
interface
uses
rtl,
RemObjects.Elements.RTL,
OpenGL;
const
MAX_ATTRIBUTES = 8;
type
TAttribute = public record
Location: Byte;
Size: Byte;
Normalized: Byte;
Offset: Byte;
end;
VertexLayout= public class
{$REGION 'Internal Declarations'}
private
FProgram: GLuint;
FAttributeCount: Byte;
FStride: Byte;
FAttributes: array [0 .. MAX_ATTRIBUTES - 1] of TAttribute;
method getAttribute(const index : Integer): TAttribute;
{$ENDREGION 'Internal Declarations'}
public
{ Starts the definition of the vertex layout. You need to call this method
before calling Add.
Parameters:
AProgram: the shader that uses this vertex layout. Should not be 0.}
constructor (const aProgram: GLuint);
{ Adds a vertex attribute to the layout.
Parameters:
AName: the name of the attribute as it appears in the shader.
ACount: number of floating-point values for the attribute. For example,
a 3D position contains 3 values and a 2D texture coordinate contains
2 values.
ANormalized: (optional) if set to True, values will be normalized from a
0-255 range to 0.0 - 0.1 in the shader. Defaults to False.
AOptional: (optional) if set to True, the attribute is ignored if it
doesn't exist in the shader. Otherwise, an exception is raised if the
attribute is not found.
Returns:
This instance, for use in a fluent API. }
method &Add(const AName: String; const ACount: Integer;
const ANormalized: Boolean := False; const AOptional: Boolean := False): VertexLayout;
// Properties
property AttribCount : Byte read FAttributeCount;
property Stride : Byte read FStride;
property Attributes[index : Integer] : TAttribute read getAttribute;
end;
VertexArray = public class
{$REGION 'Internal Declarations'}
private
class var
FSupportsVAO: Boolean;
class var
FInitialized: Boolean;
private
FVertexBuffer: GLuint;
FIndexBuffer: GLuint;
FVertexArray: GLuint;
FAttributes: array of TAttribute;
FStride: Integer;
FIndexCount: Integer;
FRenderStarted: Boolean;
private
method Initialize;
private
method BeginRender;
method EndRender;
public
method Render;
public
class constructor;
{$ENDREGION 'Internal Declarations'}
public
{ Creates a vertex array.
Parameters:
ALayout: the layout of the vertices in the array.
AVertices: data containing the vertices in the given layout.
ASizeOfVertices: size of the AVertices vertex data.
AIndices: array of indices to the vertices defining the triangles.
Must contain a multiple of 3 elements. }
constructor (const ALayout: VertexLayout; const AVertices : Array of Single; const AIndices : Array of UInt16);
constructor (const ALayout: VertexLayout; const Vcount, Icount : Integer; const AVertices : ^Single; const AIndices : ^UInt16);
finalizer;
end;
implementation
{$REGION 'Internal Declarations'}
method VertexLayout.getAttribute(const &index: Integer): TAttribute;
require
&index >= 0;
&index < FAttributeCount;
begin
exit FAttributes[&index];
end;
{$ENDREGION}
constructor VertexLayout(const aProgram: GLuint);
require
aProgram > 0;
begin
inherited ();
FProgram := aProgram;
end;
method VertexLayout.&Add(const AName: String; const ACount: Integer; const ANormalized: Boolean := false; const AOptional: Boolean := false): VertexLayout;
var
Location, lStride: Integer;
begin
if (FAttributeCount = MAX_ATTRIBUTES) then
raise new Exception('Too many attributes in vertex layout');
lStride := FStride + (ACount * sizeOf(Single));
if (lStride >= 256) then
raise new Exception('Vertex layout too big');
Location := glGetAttribLocation(FProgram, glStringHelper.toPansichar(AName));
if (Location < 0) and (not AOptional) then
raise new Exception(String.format('Attribute "{0}" not found in shader', [AName]));
if (Location >= 0) then
begin
// assert(Location <= 255);
FAttributes[FAttributeCount].Location := Location;
FAttributes[FAttributeCount].Size := ACount;
FAttributes[FAttributeCount].Normalized := ord(ANormalized);
FAttributes[FAttributeCount].Offset := FStride;
inc(FAttributeCount);
end;
FStride := lStride;
Result := Self;
end;
class constructor VertexArray;
begin
{$IF TOFFEE}
// FSupportsVAO := true;
FInitialized := false;
{$ENDIF}
end;
method VertexArray.Initialize;
begin
{$IF TOFFEE}
FSupportsVAO := true;
{$ELSE}
FSupportsVAO := assigned(glGenVertexArrays);
FSupportsVAO := FSupportsVAO and assigned(glBindVertexArray) and assigned(glDeleteVertexArrays);
{$ENDIF}
FInitialized := True;
// Disable for Testing......
// FSupportsVAO := false;
end;
method VertexArray.Render;
begin
if (not FRenderStarted) then
begin
BeginRender;
glDrawElements(GL_TRIANGLES, FIndexCount, GL_UNSIGNED_SHORT, nil);
glErrorCheck;
EndRender;
end
else
glDrawElements(GL_TRIANGLES, FIndexCount, GL_UNSIGNED_SHORT, nil);
end;
method VertexArray.BeginRender;
var
I: Integer;
begin
if (FRenderStarted) then
Exit;
if (FSupportsVAO) then
{ When VAO's are supported, we simple need to bind it... }
glBindVertexArray(FVertexArray)
else
begin
{ Otherwise, we need to manually bind the VBO and EBO and configure and
enable the attributes. }
glBindBuffer(GL_ARRAY_BUFFER, FVertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, FIndexBuffer);
for I := 0 to length(FAttributes) - 1 do
begin
glVertexAttribPointer(FAttributes[I].Location, FAttributes[I].Size, GL_FLOAT, GLboolean(FAttributes[I].Normalized), FStride, Pointer(FAttributes[I].Offset));
glEnableVertexAttribArray(FAttributes[I].Location);
end;
end;
FRenderStarted := True;
end;
method VertexArray.EndRender;
var
I: Integer;
begin
if (not FRenderStarted) then
Exit;
FRenderStarted := False;
if (FSupportsVAO) then
{ When VAO's are supported, we simple unbind it... }
glBindVertexArray(0)
else
begin
{ Otherwise, we need to manually unbind the VBO and EBO and disable the
attributes. }
for I := 0 to length(FAttributes) - 1 do
glDisableVertexAttribArray(FAttributes[I].Location);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
end;
glErrorCheck;
end;
finalizer VertexArray;
begin
if (FSupportsVAO) then
glDeleteVertexArrays(1, @FVertexArray);
glDeleteBuffers(1, @FIndexBuffer);
glDeleteBuffers(1, @FVertexBuffer);
end;
constructor VertexArray(const ALayout: VertexLayout; const AVertices: array of Single; const AIndices: array of UInt16 );
begin
constructor (ALayout, AVertices.length, AIndices.length, @AVertices[0], @AIndices[0]);
end;
constructor VertexArray(const ALayout: VertexLayout; const Vcount, Icount: Integer; const AVertices: ^Single; const AIndices: ^UInt16);
var i : Integer;
begin
inherited ();
if (not FInitialized) then
Initialize;
FIndexCount := Icount;
{ Create vertex buffer and index buffer. }
glGenBuffers(1, @FVertexBuffer);
glGenBuffers(1, @FIndexBuffer);
if (FSupportsVAO) then
begin
glGenVertexArrays(1, @FVertexArray);
if FVertexArray > 0 then
begin
glBindVertexArray(FVertexArray);
glErrorCheck;
end
else FSupportsVAO := false;
end;
glBindBuffer(GL_ARRAY_BUFFER, FVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, Vcount * sizeOf(Single), Pointer(AVertices), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, FIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, FIndexCount * sizeOf(UInt16), Pointer(AIndices), GL_STATIC_DRAW);
if (FSupportsVAO) then
begin
{ We can configure the attributes as part of the VAO }
for i := 0 to ALayout.AttribCount - 1 do
begin
glVertexAttribPointer(ALayout.Attributes[i].Location, ALayout.Attributes[i].Size,
GL_FLOAT, GLboolean(ALayout.Attributes[i].Normalized), ALayout.Stride,
Pointer(ALayout.Attributes[i].Offset));
glEnableVertexAttribArray(ALayout.Attributes[i].Location);
end;
glErrorCheck;
{ We can unbind the vertex buffer now since it is registered with the VAO.
We cannot unbind the index buffer though. }
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
end
else
begin
{ VAO's are not supported. We need to keep track of the attributes
manually }
FAttributes := new TAttribute[ALayout.AttribCount];
// SetLength(FAttributes, ALayout.FAttributeCount);
for i := 0 to ALayout.AttribCount-1 do
FAttributes[i] := ALayout.Attributes[i];
FStride := ALayout.Stride;
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
end;
glErrorCheck;
end;
end. |
unit UV_VedView_Filter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxCheckBox, StdCtrls, cxButtons,
cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, cxControls,
cxGroupBox, cxSpinEdit, cxDropDownEdit, Unit_VedView_Consts, GlobalSpr,
IBase, PackageLoad, ZTypes, Dates, FIBDatabase, pFIBDatabase, DB,
FIBDataSet, pFIBDataSet, ZMessages;
type UVVedFilter = record
Id_smeta:integer;
Name_Smeta:String;
Id_department:integer;
Name_Department:String;
Id_man:integer;
FIO:string;
Kod_Setup:integer;
Kod:integer;
ModalResult:TModalResult;
end;
type
TUVVedViewFilter = class(TForm)
BoxSmeta: TcxGroupBox;
EditSmeta: TcxButtonEdit;
YesBtn: TcxButton;
CancelBtn: TcxButton;
BoxKodSetup: TcxGroupBox;
MonthesList: TcxComboBox;
YearSpinEdit: TcxSpinEdit;
CheckBoxKodSetup: TcxCheckBox;
CheckBoxKod: TcxCheckBox;
BoxKod: TcxGroupBox;
CheckBoxDepartment: TcxCheckBox;
BoxDepartment: TcxGroupBox;
EditDepartment: TcxButtonEdit;
CheckBoxSmeta: TcxCheckBox;
EditKod: TcxMaskEdit;
DB: TpFIBDatabase;
DSet: TpFIBDataSet;
ReadTransaction: TpFIBTransaction;
CheckBoxIdMan: TcxCheckBox;
BoxIdMan: TcxGroupBox;
EditMan: TcxButtonEdit;
procedure CheckBoxKodSetupClick(Sender: TObject);
procedure CheckBoxKodClick(Sender: TObject);
procedure CheckBoxDepartmentClick(Sender: TObject);
procedure CheckBoxSmetaClick(Sender: TObject);
procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure CancelBtnClick(Sender: TObject);
procedure YesBtnClick(Sender: TObject);
procedure CheckBoxIdManClick(Sender: TObject);
procedure EditManPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
PParameter:UVVedFilter;
public
constructor Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:UVVedFilter);reintroduce;
property Parameter:UVVedFilter read PParameter;
end;
function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:UVVedFilter):UVVedFilter;
implementation
{$R *.dfm}
function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:UVVedFilter):UVVedFilter;
var Filter:TUVVedViewFilter;
Res:UVVedFilter;
begin
Filter := TUVVedViewFilter.Create(AOwner,ADB_Handle,AParameter);
if Filter.ShowModal=mrYes then
Res:=Filter.Parameter;
Res.ModalResult:=Filter.ModalResult;
Filter.Free;
ViewFilter:=Res;
end;
constructor TUVVedViewFilter.Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:UVVedFilter);
begin
inherited Create(AOwner);
PParameter:=AParameter;
//******************************************************************************
Caption := TUVVedViewFilter_Caption;
CheckBoxKodSetup.Properties.Caption := TUVVedViewFilter_CheckBoxKodSetup_Caption;
CheckBoxKod.Properties.Caption := TUVVedViewFilter_CheckBoxKod_Caption;
CheckBoxDepartment.Properties.Caption := TUVVedViewFilter_CheckBoxDepartment_Caption;
CheckBoxSmeta.Properties.Caption := TUVVedViewFilter_CheckBoxSmeta_Caption;
CheckBoxIdMan.Properties.Caption := TUVVedViewFilter_CheckBoxIdMan_Caption;
YesBtn.Caption := TUVVedViewFilter_YesBtn_Caption;
CancelBtn.Caption := TUVVedViewFilter_CancelBtn_Caption;
MonthesList.Properties.Items.Text := TUVVedViewFilter_MonthesList_Text;
//******************************************************************************
DB.Handle := ADB_Handle;
ReadTransaction.StartTransaction;
if PParameter.Kod_Setup=0 then
begin
DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_KOD_SETUP_RETURN';
DSet.Open;
YearSpinEdit.Value:=YearMonthFromKodSetup(DSet.FieldValues['KOD_SETUP']);
MonthesList.ItemIndex:= YearMonthFromKodSetup(DSet.FieldValues['KOD_SETUP'],false)-1;
end
else
begin
YearSpinEdit.Value:=YearMonthFromKodSetup(PParameter.Kod_Setup);
MonthesList.ItemIndex:= YearMonthFromKodSetup(PParameter.Kod_Setup,false)-1;
CheckBoxKodSetup.Checked := True;
BoxKodSetup.Enabled := True;
end;
if PParameter.Kod<>0 then
begin
CheckBoxKod.Checked := True;
BoxKod.Enabled := True;
EditKod.Text := IntToStr(PParameter.Kod);
end;
if PParameter.Id_department<>0 then
begin
CheckBoxDepartment.Checked := True;
BoxDepartment.Enabled := True;
EditDepartment.Text := PParameter.Name_Department;
end;
if PParameter.Id_smeta<>0 then
begin
CheckBoxSmeta.Checked := True;
BoxSmeta.Enabled := True;
EditSmeta.Text := PParameter.Name_Smeta;
end;
if PParameter.Id_man<>0 then
begin
CheckBoxIdMan.Checked := True;
BoxIdMan.Enabled := True;
EditMan.Text := PParameter.FIO;
end;
//******************************************************************************
end;
procedure TUVVedViewFilter.CheckBoxKodSetupClick(Sender: TObject);
begin
BoxKodSetup.Enabled := not BoxKodSetup.Enabled;
end;
procedure TUVVedViewFilter.CheckBoxKodClick(Sender: TObject);
begin
BoxKod.Enabled := not BoxKod.Enabled;
end;
procedure TUVVedViewFilter.CheckBoxDepartmentClick(Sender: TObject);
begin
BoxDepartment.Enabled := not BoxDepartment.Enabled;
end;
procedure TUVVedViewFilter.CheckBoxSmetaClick(Sender: TObject);
begin
BoxSmeta.Enabled := not BoxSmeta.Enabled;
end;
procedure TUVVedViewFilter.cxButtonEdit1PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var Department:Variant;
begin
Department:=LoadDepartment(Self,DB.Handle,zfsNormal);
if VarArrayDimCount(Department)> 0 then
if Department[0]<>NULL then
begin
EditDepartment.Text := Department[1];
PParameter.Id_department := Department[0];
PParameter.Name_Department := VarToStr(Department[1]);
end;
end;
procedure TUVVedViewFilter.EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var Smeta:Variant;
begin
Smeta:=GetSmets(self,DB.Handle,Date,psmSmet);
if VarArrayDimCount(Smeta)> 0 then
If Smeta[0]<>NULL then
begin
EditSmeta.Text := Smeta[2];
PParameter.Id_smeta := Smeta[0];
PParameter.Name_Smeta := Smeta[2];
end;
end;
procedure TUVVedViewFilter.CancelBtnClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TUVVedViewFilter.YesBtnClick(Sender: TObject);
begin
If ((PParameter.Id_smeta=0) or (not CheckBoxSmeta.Checked)) and
((PParameter.Id_department=0) or (not CheckBoxDepartment.Checked)) and
((PParameter.Id_man=0) or (not CheckBoxIdMan.Checked)) and
(not CheckBoxKodSetup.Checked) and
((EditKod.Text='') or (not CheckBoxKod.Checked)) then
ZShowMessage(TUVVedViewFilter_Caption_Error,TUVVedViewFilter_Data_Error_Text,mtWarning,[mbOK])
else
begin
if (not CheckBoxDepartment.Checked) then
PParameter.Id_department:=0;
if not CheckBoxSmeta.Checked then
PParameter.Id_smeta:=0;
if not CheckBoxIdMan.Checked then
PParameter.Id_man:=0;
if CheckBoxKodSetup.Checked then
PParameter.Kod_Setup := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1)
else
PParameter.Kod_Setup:=0;
if (CheckBoxKod.Checked) and (EditKod.Text<>'') then
PParameter.Kod := StrToInt(EditKod.Text)
else
PParameter.Kod:=0;
ModalResult:=mrYes;
end;
end;
procedure TUVVedViewFilter.CheckBoxIdManClick(Sender: TObject);
begin
BoxIdMan.Enabled := not BoxIdMan.Enabled;
end;
procedure TUVVedViewFilter.EditManPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var Man:Variant;
begin
Man:=LoadPeopleModal(Self,DB.Handle);
if VarArrayDimCount(Man)> 0 then
If Man[0]<>NULL then
begin
EditMan.Text := VarToStr(Man[4])+' - '+VarToStr(Man[1])+' '+VarToStr(Man[2])+' '+VarToStr(Man[3]);
PParameter.Id_man := Man[0];
PParameter.FIO := EditMan.Text
end;
end;
procedure TUVVedViewFilter.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ReadTransaction.InTransaction then ReadTransaction.Commit;
end;
end.
|
unit InspectorItems;
interface
uses
SysUtils, Classes, Dialogs, ExtDlgs, Forms, Graphics,
JvInspector, JvInspExtraEditors,
htPicture;
type
TInspectorPictureItem = class(TJvInspectorClassItem)
class procedure RegisterAsDefaultItem;
//class procedure UnregisterAsDefaultItem;
protected
FFilename: string;
function ExecutePictureDialog: Boolean;
procedure Edit; override;
procedure SetFlags(const Value: TInspectorItemFlags); override;
end;
//
TInspectorHtPictureItem = class(TInspectorPictureItem)
class procedure RegisterAsDefaultItem;
//class procedure UnregisterAsDefaultItem;
protected
procedure Edit; override;
end;
//
TInspectorColorItemEx = class(TJvInspectorColorItem)
class procedure RegisterAsDefaultItem;
private
function GetPropColor: TColor;
procedure SetPropColor(const Value: TColor);
//class procedure UnregisterAsDefaultItem;
protected
FDialogColor: TColor;
function ExecuteColorDialog: Boolean;
procedure Edit; override;
procedure SetFlags(const Value: TInspectorItemFlags); override;
property PropColor: TColor read GetPropColor write SetPropColor;
end;
procedure RegisterInspectorItems;
implementation
uses
JvFullColorDialogs;
procedure RegisterInspectorItems;
begin
TInspectorPictureItem.RegisterAsDefaultItem;
TInspectorHtPictureItem.RegisterAsDefaultItem;
TInspectorColorItemEx.RegisterAsDefaultItem;
end;
{ TInspectorPictureItem }
class procedure TInspectorPictureItem.RegisterAsDefaultItem;
begin
TJvCustomInspectorData.ItemRegister.Add(
TJvInspectorTypeInfoRegItem.Create(
TInspectorPictureItem, TypeInfo(TPicture)));
// TJvInspectorMultiPropData.ItemRegister.Add(
// TJvInspectorTypeInfoRegItem.Create(
// TInspectorPictureItem, TypeInfo(TPicture)));
end;
function TInspectorPictureItem.ExecutePictureDialog: Boolean;
begin
with TOpenPictureDialog.Create(GetParentForm(Inspector)) do
try
Result := Execute;
FFilename := Filename;
finally
Free;
end;
end;
procedure TInspectorPictureItem.Edit;
begin
if ExecutePictureDialog then
TPicture(Data.AsOrdinal).LoadFromFile(FFilename);
end;
procedure TInspectorPictureItem.SetFlags(const Value: TInspectorItemFlags);
var
NewValue: TInspectorItemFlags;
begin
NewValue := Value + [ iifEditButton, iifEditFixed ];
inherited SetFlags(NewValue);
end;
{ TInspectorHtPictureItem }
class procedure TInspectorHtPictureItem.RegisterAsDefaultItem;
begin
TJvCustomInspectorData.ItemRegister.Add(
TJvInspectorTypeInfoRegItem.Create(
TInspectorHtPictureItem, TypeInfo(ThtPicture)));
// TJvInspectorMultiPropData.ItemRegister.Add(
// TJvInspectorTypeInfoRegItem.Create(
// TInspectorHtPictureItem, TypeInfo(ThtPicture)));
end;
procedure TInspectorHtPictureItem.Edit;
begin
if ExecutePictureDialog then
ThtPicture(Data.AsOrdinal).Filename := FFilename;
end;
{ TInspectorColorItemEx }
var
SharedColorDialog: TColorDialog;
function ColorDialog: TColorDialog;
begin
if SharedColorDialog = nil then
begin
// TJvFullColorDialog.Create(Application)
SharedColorDialog := TColorDialog.Create(Application);
SharedColorDialog.Options := [ cdFullOpen, cdAnyColor ];
end;
Result := SharedColorDialog;
end;
class procedure TInspectorColorItemEx.RegisterAsDefaultItem;
begin
TJvCustomInspectorData.ItemRegister.Add(
TJvInspectorTypeInfoRegItem.Create(
TInspectorColorItemEx, TypeInfo(TColor)));
end;
function TInspectorColorItemEx.GetPropColor: TColor;
begin
Result := Data.AsOrdinal;
end;
procedure TInspectorColorItemEx.SetPropColor(const Value: TColor);
begin
Data.AsOrdinal := Value;
end;
function TInspectorColorItemEx.ExecuteColorDialog: Boolean;
begin
with ColorDialog do
begin
Color := PropColor;
Result := Execute;
if Result then
PropColor := Color;
end;
end;
procedure TInspectorColorItemEx.Edit;
begin
ExecuteColorDialog;
end;
procedure TInspectorColorItemEx.SetFlags(const Value: TInspectorItemFlags);
var
NewValue: TInspectorItemFlags;
begin
NewValue := Value + [ iifEditButton, iifEditFixed ];
inherited SetFlags(NewValue);
end;
end.
|
unit UProductDescription;
interface
type
TProductDescription = class
private
itemID: integer;
description: string;
price: integer;
public
function getPrice: integer;
end;
implementation
{ TProductDescription }
function TProductDescription.getPrice: integer;
begin
result := 0;
end;
end.
|
unit Lib.SSL;
interface
uses
System.SysUtils,
Winapi.Winsock2,
Lib.SSL.Api;
type
TSSL = class
protected
FErrorText: string;
FErrorCode: Integer;
FPSSL: PSSL;
FPSSL_CTX: PSSL_CTX;
FConnected: Boolean;
procedure seterror;
public
constructor create;
destructor destroy; override;
function connect(Socket: TSocket): Boolean;
procedure shutdown;
function recv(var b; w: Integer): Integer;
function send(var b; w: Integer): Integer;
function cipher: string;
function init: Boolean;
function deinit: Boolean;
function prepare: Boolean;
function accept(Socket: TSocket): Boolean;
function SetKeys: Boolean;
public
CertCAFile: string;
CertificateFile: string;
PrivateKeyFile: string;
KeyPassword: string;
Verify: Boolean;
property ErrorCode: Integer read FErrorCode;
property ErrorText: string read FErrorText;
end;
implementation
function PasswordCallback(buf:PAnsiChar; size:Integer; rwflag:Integer; userdata: Pointer):Integer; cdecl;
var
Password: AnsiString;
begin
Password := '';
if TSSL(userdata) is TSSL then
Password := TSSL(userdata).KeyPassword;
if Length(Password) > (Size - 1) then
SetLength(Password, Size - 1);
Result := Length(Password);
StrLCopy(buf, PAnsiChar(Password + #0), Result + 1);
end;
constructor TSSL.create;
begin
FErrorText:='';
FErrorCode:=0;
FPSSL:=nil;
FPSSL_CTX:=nil;
FConnected:=False;
Verify:=False;
end;
destructor TSSL.destroy;
begin
shutdown;
inherited;
end;
function TSSL.SetKeys: Boolean;
begin
Result:=True;
if CertificateFile <> '' then
Result:=SslCtxUseCertificateChainFile(FPSSL_CTX,CertificateFile)=1;
if Result then
if PrivateKeyFile <> '' then
Result:=SslCtxUsePrivateKeyFile(FPSSL_CTX, PrivateKeyFile, SSL_FILETYPE_PEM)=1;
if Result then
if CertCAFile <> '' then
Result:=SslCtxLoadVerifyLocations(FPSSL_CTX, CertCAFile, '')=1;
end;
function TSSL.init:Boolean;
var s:ansistring;
begin
result:=False;
FErrorText:='';
FErrorCode:=0;
//FPSSL_CTX:=sslctxnew(sslmethodv2);
FPSSL_CTX:=sslctxnew(sslmethodv23);
//FPSSL_CTX:=sslctxnew(sslmethodv3);
if FPSSL_CTX=nil
then seterror
else begin
s:='DEFAULT';
sslctxsetcipherlist(FPSSL_CTX,s);
if Verify then
begin
sslctxsetverify(FPSSL_CTX,SSL_VERIFY_PEER,nil);
SslCtxSetDefaultPasswdCb(FPSSL_CTX, @PasswordCallback);
SslCtxSetDefaultPasswdCbUserdata(FPSSL_CTX, self);
if not SetKeys then Exit;
end else
sslctxsetverify(FPSSL_CTX,SSL_VERIFY_NONE,nil);
FPSSL:=sslnew(FPSSL_CTX);
if FPSSL=nil
then seterror
else result:=True;
end;
end;
function TSSL.deinit:Boolean;
begin
result:=True;
if assigned(FPSSL)
then begin
sslfree(FPSSL);
FPSSL:=nil;
end;
if assigned(FPSSL_CTX)
then begin
sslctxfree(FPSSL_CTX);
FPSSL_CTX:=nil;
errremovestate(0);
end;
FConnected:=False;
end;
function TSSL.prepare:Boolean;
begin
result:=False;
deinit;
if init
then result:=True
else deinit;
end;
function TSSL.connect(Socket: TSocket):Boolean;
begin
Result:=False;
if Socket=-1 then Exit;
if prepare and (sslsetfd(FPSSL,Socket)>=1)
then for var i:=0 to 10 do
begin
case SslGetError(FPSSL,sslconnect(FPSSL)) of
SSL_ERROR_NONE:
begin
FConnected:=True;
Exit(True);
end;
SSL_ERROR_WANT_READ,SSL_ERROR_WANT_WRITE:;
SSL_ERROR_SYSCALL:
begin
FErrorCode:=SSL_ERROR_SYSCALL;
FErrorText:='SSL_connect: SSL_ERROR_SYSCALL in connection';
Exit;
end;
else Break;
end;
sleep(1+i*10);
end;
seterror;
end;
procedure TSSL.shutdown;
begin
if assigned(FPSSL)
then sslshutdown(FPSSL);
deinit;
end;
function TSSL.accept(Socket: TSocket): Boolean;
begin
Result:=False;
if prepare and (sslsetfd(FPSSL,Socket)>=1)
then for var i:=0 to 10 do
begin
case SslGetError(FPSSL,sslaccept(FPSSL)) of
SSL_ERROR_NONE: Exit(True);
SSL_ERROR_WANT_READ,SSL_ERROR_WANT_WRITE:;
else Break;
end;
sleep(1+i*10);
end;
seterror;
end;
function TSSL.cipher: string;
begin
result:=sslcipherdescription(sslgetcurrentcipher(FPSSL));
end;
procedure TSSL.seterror;
begin
FErrorCode:=errgeterror;
errclearerror;
if FErrorCode<>0
then begin
var s:ansistring:=stringofchar(#0,256);
errerrorstring(FErrorCode,s,length(s));
FErrorText:=s;
end
else begin
FErrorCode:=1;
FErrorText:='SSL error';
end;
end;
function TSSL.recv(var b;w:Integer):Integer;
begin
result:=sslread(FPSSL,pointer(b),w);
end;
function TSSL.send(var b;w:Integer):Integer;
begin
Result:=sslwrite(FPSSL,pointer(b),w);
end;
end.
|
unit form_dbtable;
interface
uses Winapi.Windows, Winapi.Messages, Classes, Controls, Forms, Vcl.Menus, Vcl.Grids, Vcl.ValEdit, Vcl.DBGrids, Vcl.DBCtrls, Data.DB,
FireDAC.Comp.Client, FireDAC.Stan.Param, SysUtils, sysmenu;
type
TDbForm = class(TForm)
protected
procedure DoCreate; override;
procedure FormClose(Sender: TObject; var Action: TCloseAction); virtual;
procedure SetDataSet(ADataSet: TFDCustomQuery); virtual;
protected
procedure WMSysCommand(var Msg: TWMSysCommand); message WM_SYSCOMMAND;
private
FSysMenu: TSystemMenu;
FImages: TImageList;
FDataSet: TFDCustomQuery;
FDataSource: TDataSource;
FGrid: TDBGrid;
FNavigator: TDBNavigator;
FAutoOpen: boolean;
function GetConnected: boolean;
function GetDataSetActive: boolean;
procedure SetAutoOpen(Value: boolean);
procedure OnClickParams(Sender: TObject);
procedure OnClickRefresh(Sender: TObject);
procedure DoGridInit;
public
constructor Create(AOwner: TComponent); override;
property Grid: TDBGrid read FGrid;
property Navigator: TDBNavigator read FNavigator;
property AutoOpen: boolean read FAutoOpen write SetAutoOpen;
property DataSet: TFDCustomQuery read FDataSet write SetDataSet;
property DataSetActive: boolean read GetDataSetActive;
property Connected: boolean read GetConnected;
procedure DataSetOpen(Sender: TObject); virtual;
procedure DataSetClose(Sender: TObject); virtual;
end;
tfrm_values = class(TForm)
private
FValueList: TValueListEditor;
function GetValue(ValueName: string): string;
procedure SetValue(ValueName: string; Source: string);
public
constructor Create(AOwner: TComponent); override;
property Values[ValueName: string]: string read GetValue write SetValue;
end;
implementation
// TDbForm
constructor TDbForm.Create(AOwner: TComponent);
begin
inherited CreateNew(AOwner);
Width := 740;
Height := 500;
Font.Size := 10;
Position := poScreenCenter;
FImages := TImageList.Create(Self);
InsertComponent(FImages);
FSysMenu := TSystemMenu.Create(Self);
FSysMenu.Images := FImages;
InsertComponent(FSysMenu);
FSysMenu.Add('Параметры', FImages.LoadFromResource(HInstance, 'dbn_APPLYUPDATES'), OnClickParams);
FSysMenu.Add('Обновить', FImages.LoadFromResource(HInstance, 'dbn_REFRESH'), OnClickRefresh);
FSysMenu.Add('Открыть', FImages.LoadFromResource(HInstance, 'dbn_POST'), DataSetOpen);
FSysMenu.Add('Закрыть', FImages.LoadFromResource(HInstance, 'dbn_CANCEL'), DataSetClose);
FDataSet := nil;
FDataSource := TDataSource.Create(Self);
FDataSource.DataSet := FDataSet;
InsertComponent(FDataSource);
FNavigator := TDBNavigator.Create(Self);
FNavigator.Align := alBottom;
FNavigator.DataSource := FDataSource;
InsertControl(FNavigator);
FGrid := TDBGrid.Create(Self);
FGrid.Align := alClient;
FGrid.DataSource := FDataSource;
InsertControl(FGrid);
OnClose := FormClose;
FAutoOpen := true;
end;
procedure TDbForm.DoCreate;
begin
inherited;
FSysMenu.Attach(GetSystemMenu(Handle, false));
end;
procedure TDbForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
if FAutoOpen then
begin
DataSetClose(Self);
end;
end;
procedure TDbForm.SetAutoOpen(Value: boolean);
begin
FAutoOpen := Value;
if FAutoOpen then
begin
DataSetOpen(Self);
end;
end;
function TDbForm.GetConnected: boolean;
begin
Result := false;
if Assigned(FDataSet) then
if Assigned(FDataSet.Connection) then
begin
Result := FDataSet.Connection.Connected;
end;
end;
function TDbForm.GetDataSetActive: boolean;
begin
Result := false;
if Assigned(FDataSet) then
begin
Result := FDataSet.Active;
end;
end;
procedure TDbForm.SetDataSet(ADataSet: TFDCustomQuery);
begin
FDataSet := ADataSet;
FDataSource.DataSet := FDataSet;
if FAutoOpen then
begin
DataSetOpen(Self);
end;
end;
procedure TDbForm.DataSetOpen;
begin
if Connected then
begin
if not FDataSet.Active then
begin
FDataSet.Open;
end;
DoGridInit;
end;
end;
procedure TDbForm.DataSetClose;
begin
if DataSetActive then
begin
FDataSet.Close;
end;
end;
procedure TDbForm.DoGridInit;
var
col: TColumn;
j, w: integer;
begin
w := (FGrid.ClientWidth - 40) div 3;
for j := 0 to FGrid.Columns.Count - 1 do
begin
col := FGrid.Columns[j];
if col.Width > w then
col.Width := w;
end;
end;
procedure TDbForm.OnClickParams(Sender: TObject);
var
dlg: tfrm_values;
lparam: TFDParam;
j: integer;
begin
if not Connected then
exit;
dlg := tfrm_values.Create(Self);
dlg.Caption := FDataSet.Name + '.Params';
for j := 0 to FDataSet.ParamCount - 1 do
begin
lparam := FDataSet.Params[j];
dlg.Values[lparam.Name] := lparam.AsString;
end;
dlg.ShowModal;
DataSetClose(Self);
for j := 0 to FDataSet.ParamCount - 1 do
begin
lparam := FDataSet.Params[j];
lparam.Value := dlg.Values[lparam.Name];
end;
DataSetOpen(Self);
dlg.Release;
end;
procedure TDbForm.OnClickRefresh(Sender: TObject);
begin
DataSetClose(Self);
DataSetOpen(Self);
end;
procedure TDbForm.WMSysCommand(var Msg: TWMSysCommand);
begin
if not FSysMenu.OnCommand(Msg) then
inherited;
end;
// tfrm_values
constructor tfrm_values.Create(AOwner: TComponent);
begin
inherited CreateNew(AOwner);
Font.Size := 10;
Position := poScreenCenter;
FValueList := TValueListEditor.Create(Self);
FValueList.Align := alClient;
InsertControl(FValueList);
end;
function tfrm_values.GetValue(ValueName: string): string;
begin
if ValueName = '' then
Result := ''
else
Result := FValueList.Values[ValueName];
end;
procedure tfrm_values.SetValue(ValueName: string; Source: string);
begin
if ValueName <> '' then
begin
FValueList.Values[ValueName] := Source;
end;
end;
end.
|
// ----------------------------------------------------------------
// Este programa informa o dia da semana que corresponde a uma
// data informada pelo usuario :~
// Autor : Luiz Reginaldo - Desenvolvedor do Pzim
// -------------------------------------------------------------
Program CalculaDiaSemana ;
var
dia, mes, ano : integer ; // dados informados pelo usuario
diaAux, mesAux, anoAux, seculo: integer; // auxiliares
diaSemana: string[15] ; // Nome do dia da Semana
Begin
// Solicita ao usuario o dia
write('Digite o dia: ');
read(dia);
while (dia < 1) or (dia > 31) do
Begin
write('diaAux invalido, informe novamente');
read(dia);
End;
// Solicita ao usuario o mes
write ('Digite o mes: ');
read (mes);
while (mes < 1) or (mes > 12) do
Begin
write('Mes Invalido, informe novamente');
read(mes);
End;
// Solicita ao usuario o ano
write ('Digite o Ano: ');
read (ano);
while (ano < 1) or (ano > 9999) do
Begin
write('Ano invalido, informe novamente ');
read(ano);
End;
// Obtem valores para calcular o dia da semana
seculo:= ano div 100;
anoAux:= ano mod 100;
If mes <= 2 then
Begin
mesAux:= mes + 10;
anoAux:= anoAux -1;
End
Else mesAux:= mes -2;
// Calcula o dia da semana
diaAux := (Trunc(2.6 * mesAux -0.1) + dia + anoAux + anoAux div 4 + seculo div 4 - 2 * seculo) mod 7;
if diaAux < 0 then diaAux:= diaAux + 7;
// Determina o dia da semana
case diaAux of
0 : diaSemana:= 'Domingo';
1 : diaSemana:= 'Segunda-Feira';
2 : diaSemana:= 'Terca-Feira';
3 : diaSemana:= 'Quarta-feira';
4 : diaSemana:= 'Quinta-Feira';
5 : diaSemana:= 'Sexta-Feira';
6 : diaSemana:= 'Sabado';
end ;
// Exibe resultados na tela
writeln ;
writeln('=> A data informada foi : ', dia, '/', mes, '/', ano);
writeln('=> Dia da semana : ', diaSemana) ;
End.
|
unit uPrinterOption;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Dialogs, Printers;
type
TPrinterOption = class(TObject)
private
GDefPrintIndex : Integer;
GPList : TStrings;
procedure GetPrinterInfo;
procedure CheckPrinter;
public
constructor Create;
destructor Destroy;
function GetPrinters : TStrings;
function GetDefaultPrinterIndex : Integer;
function GetDefaultPrinterName : String;
procedure SetDefaultPrinter(index : integer);
function GetAppointPrinterIndex(aPrinterName : String) : Integer;
function GetAppointPrinterName(index : Integer) : String;
procedure Refurbish;
end;
implementation
{ TPrinterOption }
constructor TPrinterOption.Create;
begin
GPList := TStringList.Create;
GetPrinterInfo;
end;
destructor TPrinterOption.Destroy;
begin
if Assigned(GPList) then
begin
GPList.Clear;
FreeAndNil(GPList);
end;//if
end;
procedure TPrinterOption.GetPrinterInfo;
begin
GPList.Clear;
GPList := Printer.Printers;
GDefPrintIndex := Printer.PrinterIndex;
end;
procedure TPrinterOption.CheckPrinter;
begin
if GPList.Count = 0 then
GetPrinterInfo;
end;
function TPrinterOption.GetDefaultPrinterIndex: Integer;
begin
Result := GDefPrintIndex;
end;
function TPrinterOption.GetDefaultPrinterName: String;
begin
Result := GPList.Strings[GDefPrintIndex];
end;
function TPrinterOption.GetPrinters: TStrings;
begin
Result := GPList;
end;
procedure TPrinterOption.SetDefaultPrinter(index: integer);
var
poHandle : THandle;
poDevice, poDriver, poPort: array [0..255] of Char;
begin
CheckPrinter;
if GPList.Count > 0 then
begin
if index < 0 then
index := 0;
if index >= GPList.Count then
index := GPList.Count - 1;
Printer.PrinterIndex := index;
Printer.GetPrinter(poDevice, poDriver, poPort, poHandle);//获取打印机句柄
WriteProfileString('WINDOWS', 'DEVICE', poDevice); //设置默认打印机
end else
begin
raise Exception.Create('未获得任何打印机信息,请确认已安装打印机');
end;//else
end;
function TPrinterOption.GetAppointPrinterIndex(aPrinterName: String): Integer;
var
index : Integer;
begin
Result := -1;
CheckPrinter;
if Trim(aPrinterName) = '' then
raise Exception.Create('请确认打印机名称的正确');
index := GPList.IndexOf(aPrinterName);
if index < 0 then
begin
GetPrinterInfo;
index := GPList.IndexOf(aPrinterName);
end;//if
Result := index;
end;
function TPrinterOption.GetAppointPrinterName(index: Integer): String;
var
name : String;
begin
Result := '';
CheckPrinter;
if (index < 0) or (index >= GPList.Count) then
raise Exception.Create('请确认打印机的索引值正确');
name := GPList.Strings[index];
if Trim(name) = '' then
begin
GetPrinterInfo;
name := GPList.Strings[index];
end;//if
Result := Trim(name);
end;
procedure TPrinterOption.Refurbish;
begin
GetPrinterInfo;
end;
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 181723
////////////////////////////////////////////////////////////////////////////////
unit java.util.Date;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JDate = interface;
JDateClass = interface(JObjectClass)
['{B3AD9F7A-3F1F-4618-A801-C30DC79B6A7F}']
function UTC(year : Integer; month : Integer; day : Integer; hour : Integer; minute : Integer; second : Integer) : Int64; deprecated; cdecl;// (IIIIII)J A: $9
function after(date : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $1
function before(date : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $1
function clone : JObject; cdecl; // ()Ljava/lang/Object; A: $1
function compareTo(date : JDate) : Integer; cdecl; // (Ljava/util/Date;)I A: $1
function equals(&object : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function getDate : Integer; deprecated; cdecl; // ()I A: $1
function getDay : Integer; deprecated; cdecl; // ()I A: $1
function getHours : Integer; deprecated; cdecl; // ()I A: $1
function getMinutes : Integer; deprecated; cdecl; // ()I A: $1
function getMonth : Integer; deprecated; cdecl; // ()I A: $1
function getSeconds : Integer; deprecated; cdecl; // ()I A: $1
function getTime : Int64; cdecl; // ()J A: $1
function getTimezoneOffset : Integer; deprecated; cdecl; // ()I A: $1
function getYear : Integer; deprecated; cdecl; // ()I A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function init : JDate; cdecl; overload; // ()V A: $1
function init(&string : JString) : JDate; deprecated; cdecl; overload; // (Ljava/lang/String;)V A: $1
function init(milliseconds : Int64) : JDate; cdecl; overload; // (J)V A: $1
function init(year : Integer; month : Integer; day : Integer) : JDate; deprecated; cdecl; overload;// (III)V A: $1
function init(year : Integer; month : Integer; day : Integer; hour : Integer; minute : Integer) : JDate; deprecated; cdecl; overload;// (IIIII)V A: $1
function init(year : Integer; month : Integer; day : Integer; hour : Integer; minute : Integer; second : Integer) : JDate; deprecated; cdecl; overload;// (IIIIII)V A: $1
function parse(&string : JString) : Int64; deprecated; cdecl; // (Ljava/lang/String;)J A: $9
function toGMTString : JString; deprecated; cdecl; // ()Ljava/lang/String; A: $1
function toLocaleString : JString; deprecated; cdecl; // ()Ljava/lang/String; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure setDate(day : Integer) ; deprecated; cdecl; // (I)V A: $1
procedure setHours(hour : Integer) ; deprecated; cdecl; // (I)V A: $1
procedure setMinutes(minute : Integer) ; deprecated; cdecl; // (I)V A: $1
procedure setMonth(month : Integer) ; deprecated; cdecl; // (I)V A: $1
procedure setSeconds(second : Integer) ; deprecated; cdecl; // (I)V A: $1
procedure setTime(milliseconds : Int64) ; cdecl; // (J)V A: $1
procedure setYear(year : Integer) ; deprecated; cdecl; // (I)V A: $1
end;
[JavaSignature('java/util/Date')]
JDate = interface(JObject)
['{3DD89402-28DF-41E4-8616-761DBAD5E136}']
function after(date : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $1
function before(date : JDate) : boolean; cdecl; // (Ljava/util/Date;)Z A: $1
function clone : JObject; cdecl; // ()Ljava/lang/Object; A: $1
function compareTo(date : JDate) : Integer; cdecl; // (Ljava/util/Date;)I A: $1
function equals(&object : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function getDate : Integer; deprecated; cdecl; // ()I A: $1
function getDay : Integer; deprecated; cdecl; // ()I A: $1
function getHours : Integer; deprecated; cdecl; // ()I A: $1
function getMinutes : Integer; deprecated; cdecl; // ()I A: $1
function getMonth : Integer; deprecated; cdecl; // ()I A: $1
function getSeconds : Integer; deprecated; cdecl; // ()I A: $1
function getTime : Int64; cdecl; // ()J A: $1
function getTimezoneOffset : Integer; deprecated; cdecl; // ()I A: $1
function getYear : Integer; deprecated; cdecl; // ()I A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function toGMTString : JString; deprecated; cdecl; // ()Ljava/lang/String; A: $1
function toLocaleString : JString; deprecated; cdecl; // ()Ljava/lang/String; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure setDate(day : Integer) ; deprecated; cdecl; // (I)V A: $1
procedure setHours(hour : Integer) ; deprecated; cdecl; // (I)V A: $1
procedure setMinutes(minute : Integer) ; deprecated; cdecl; // (I)V A: $1
procedure setMonth(month : Integer) ; deprecated; cdecl; // (I)V A: $1
procedure setSeconds(second : Integer) ; deprecated; cdecl; // (I)V A: $1
procedure setTime(milliseconds : Int64) ; cdecl; // (J)V A: $1
procedure setYear(year : Integer) ; deprecated; cdecl; // (I)V A: $1
end;
TJDate = class(TJavaGenericImport<JDateClass, JDate>)
end;
implementation
end.
|
unit Backend.iPool.Connector;
interface
uses
System.JSON,
System.Generics.Collections,
System.SysUtils,
Backend.iPool.DM,
Data.Articles,
Data.User.Preferences;
type
TSAIDiPoolArticle = class(TInterfacedObject, IiPoolArticle)
private
FContent: string;
FHeading: string;
FPublisher: string;
public
constructor Create(AContent: string; AHeading: string; APublisher: string);
function GetContent: string;
function GetHeading: string;
function GetPublisher: string;
property Heading: string read GetHeading;
property Content: string read GetContent;
property Publisher: string read GetPublisher;
end;
TSAIDiPoolArticles = class(TInterfacedObject, IiPoolArticles)
private
FArticles: TList<IiPoolArticle>;
public
constructor Create(AArticles: TList<IiPoolArticle>);
function GetArticles(const AIndex: Integer): IiPoolArticle;
function GetCount: Integer;
property Articles[const AIndex: Integer]: IiPoolArticle read GetArticles;
property Count: Integer read GetCount;
destructor Destroy; override;
end;
TSAIDiPoolConnector = class
function GetArticles(APreferences: IPreferences): IiPoolArticles;
end;
implementation
{ TSAIDiPoolConnector }
function TSAIDiPoolConnector.GetArticles(APreferences: IPreferences)
: IiPoolArticles;
var
LJSONResponse, LJSONDocEntry: TJSONObject;
LDocuments: TJSONArray;
LPreferences: IPreferences;
LPublisherStr, LHeadingStr, LContentStr: string;
i: Integer;
LArticles: TList<IiPoolArticle>;
begin
LJSONResponse := DoRequestiPool(APreferences);
LArticles := TList<IiPoolArticle>.Create;
LDocuments := LJSONResponse.Values['documents'] as TJSONArray;
for i := 0 to LDocuments.Count - 1 do
begin
LJSONDocEntry := LDocuments.Items[i] as TJSONObject;
LPublisherStr := (LJSONDocEntry.Values['publisher'] as TJSONString).Value;
LHeadingStr := (LJSONDocEntry.Values['title'] as TJSONString).Value;
LContentStr := (LJSONDocEntry.Values['content'] as TJSONString).Value;
LArticles.Add(TSAIDiPoolArticle.Create(LContentStr, LHeadingStr,
LPublisherStr));
end;
Result := TSAIDiPoolArticles.Create(LArticles);
end;
{ TSAIDiPoolArticle }
constructor TSAIDiPoolArticle.Create(AContent, AHeading, APublisher: string);
begin
FContent := AContent;
FHeading := AHeading;
FPublisher := APublisher;
end;
function TSAIDiPoolArticle.GetContent: string;
begin
Result := FContent;
end;
function TSAIDiPoolArticle.GetHeading: string;
begin
Result := FHeading;
end;
function TSAIDiPoolArticle.GetPublisher: string;
begin
Result := FPublisher;
end;
{ TSAIDiPoolArticles }
constructor TSAIDiPoolArticles.Create(AArticles: TList<IiPoolArticle>);
begin
FArticles := AArticles;
end;
destructor TSAIDiPoolArticles.Destroy;
begin
FreeAndNil(FArticles);
inherited;
end;
function TSAIDiPoolArticles.GetArticles(const AIndex: Integer): IiPoolArticle;
begin
Result := FArticles.Items[AIndex];
end;
function TSAIDiPoolArticles.GetCount: Integer;
begin
Result := FArticles.Count;
end;
end.
|
unit GShare;
interface
uses
Windows,Messages,Classes,SysUtils,IniFiles;
type
TProgram = record
boGetStart :Boolean;
boReStart :Boolean; //程序异常停止,是否重新启动
btStartStatus:Byte; //0,1,2,3 未启动,正在启动,已启动,正在关闭
sProgramFile :String[50];
sDirectory :String[100];
ProcessInfo :TProcessInformation;
ProcessHandle:THandle;
MainFormHandle:THandle;
nMainFormX :Integer;
nMainFormY :Integer;
end;
pTProgram = ^TProgram;
//备份功能代码
TBakInfo = record
{DataDir : string; //数据目录
BakDir : string; //备份目录 }
TimeCls : Boolean;//备份时间类型
m_dwBakTick : LongWord;
Hour : Integer;//小时
Minute : Integer;//分钟
end;
pTBakInfo = ^TBakInfo;
TCheckCode = record
dwThread0 :LongWord;
sThread0 :string;
end;
procedure LoadConfig();
function RunProgram(var ProgramInfo:TProgram;sHandle:String;dwWaitTime:LongWord):LongWord;
function StopProgram(var ProgramInfo:TProgram;dwWaitTime:LongWord):Integer;
procedure SendProgramMsg(DesForm:THandle;wIdent:Word;sSendMsg:String);
const
g_sProductName = '66047C05F62314E7B0BC5582AC4B06A2741A4C8F13E5BAA8AFC996BD42AC494B'; //IGE科技服务器端控制器
g_sVersion = 'D581F791C43033262F344FC7EADF5DF9C920FC8BB82FB12A'; //2.00 Build 20081129
g_sUpDateTime = '3DFE5A09530242216C743D0BAB4704C7'; //更新日期: 2008/11/29
g_sProgram = 'C0CB995DE0C2A55814577F81CCE3A3BD'; //IGE科技
g_sWebSite = 'E14A1EC77CDEF28A670B57F56B07D834D8758E442B312AF440574B5A981AB1752C73BF5C6670B79C'; // http://www.IGEM2.com(官网站)
g_sBbsSite = '2E5A58E761D583C119D6606E0F38D7A9D8758E442B312AF440574B5A981AB17538E97FF2F0C39555'; //http://www.IGEM2.com.cn(程序站)
//g_sProductInfo = '8DFDF45695C4099770F02197A7BCE1C5B07D1DD7CD1455D1783D523EA941CBFB'; //欢迎使用IGE网络系列软件:
//g_sSellInfo1 = '71043F0BD11D04C7BA0E09F9A2EF83B7B936E13B070575B9';//联系(QQ):228589790
var
g_IniConf :TIniFile;
g_sButtonStartGame :String = '启动游戏服务器(&S)';
g_sButtonStopGame :String = '停止游戏服务器(&T)';
g_sButtonStopStartGame :String = '中止启动游戏服务器(&T)';
g_sButtonStopStopGame :String = '中止停止游戏服务器(&T)';
g_sGameDirectory :String = 'D:\MirServer\';
g_sConfFile :String = 'Config.ini';
g_sHeroDBName :String = 'HeroDB';
g_sGameName :String = 'IGE科技';
g_sGameName1 :String = 'IGE科技一';
g_sAllIPaddr :String = '0.0.0.0';
g_sLocalIPaddr :String = '127.0.0.1';
g_sExtIPaddr :String = '192.168.0.1';
g_boDynamicIPMode :Boolean = False;
g_boTwoServer :Boolean = False; //一机双服 20080222
g_nServerNum :Byte = 0; //一机双服里的 主从服务器;
g_nLimitOnlineUser :Integer = 2000; //服务器最高上线人数
g_sDBServer_ProgramFile :String = 'DBServer.exe';
g_sDBServer_Directory :String = 'DBServer\';
g_boDBServer_GetStart :Boolean = True;
g_sDBServer_ConfigFile :String = 'dbsrc.ini';
g_sDBServer_Config_ServerAddr :String = '127.0.0.1';
g_nDBServer_Config_ServerPort :Integer = 6000;
g_sDBServer_Config_GateAddr :String = '127.0.0.1';
g_nDBServer_Config_GatePort :Integer = 5100;
g_sDBServer_Config_IDSAddr :String = '127.0.0.1';
g_nDBServer_Config_IDSPort :Integer = 5600;
g_nDBServer_Config_Interval :Integer = 1000;
g_nDBServer_Config_Level1 :Integer = 1;
g_nDBServer_Config_Level2 :Integer = 7;
g_nDBServer_Config_Level3 :Integer = 14;
g_nDBServer_Config_Day1 :Integer = 7;
g_nDBServer_Config_Day2 :Integer = 62;
g_nDBServer_Config_Day3 :Integer = 124;
g_nDBServer_Config_Month1 :Integer = 0;
g_nDBServer_Config_Month2 :Integer = 0;
g_nDBServer_Config_Month3 :Integer = 0;
g_sDBServer_Config_Dir :String = 'FDB\';
g_sDBServer_Config_IdDir :String = 'FDB\';
g_sDBServer_Config_HumDir :String = 'FDB\';
g_sDBServer_Config_FeeDir :String = 'FDB\';
g_sDBServer_Config_BackupDir :String = 'Backup\';
g_sDBServer_Config_ConnectDir :String = 'Connection\';
g_sDBServer_Config_LogDir :String = 'Log\';
g_sDBServer_Config_SortDir :String = 'Sort\';//20080617 增加
g_sDBServer_Config_MapFile :String = 'MapInfo.txt';
g_boDBServer_Config_ViewHackMsg :Boolean = False;
g_sDBServer_AddrTableFile :String = '!addrtable.txt';
g_sDBServer_ServerinfoFile :String = '!serverinfo.txt';
g_nDBServer_MainFormX :Integer = 0;
g_nDBServer_MainFormY :Integer = 326;
g_boDBServer_DisableAutoGame :Boolean = False;
g_sLoginServer_ProgramFile :String = 'LoginSrv.exe';
g_sLoginServer_Directory :String = 'LoginSrv\';
g_sLoginServer_ConfigFile :String = 'Logsrv.ini';
g_boLoginServer_GetStart :Boolean = True;
g_sLoginServer_GateAddr :String = '127.0.0.1';
g_nLoginServer_GatePort :Integer = 5500;
g_sLoginServer_MonAddr :String = '127.0.0.1';
g_nLoginServer_MonPort :Integer = 3000;
g_sLoginServer_ServerAddr :String = '127.0.0.1';
g_nLoginServer_ServerPort :Integer = 5600;
g_sLoginServer_ReadyServers :Integer = 0;
g_sLoginServer_EnableMakingID :Boolean = True;
g_sLoginServer_EnableTrial :Boolean = False;
g_sLoginServer_TestServer :Boolean = True;
g_sLoginServer_IdDir :String = 'IDDB\';
g_sLoginServer_FeedIDList :String = 'FeedIDList.txt';
g_sLoginServer_FeedIPList :String = 'FeedIPList.txt';
g_sLoginServer_CountLogDir :String = 'CountLog\';
g_sLoginServer_WebLogDir :String = 'GameWFolder\';
g_sLoginServer_AddrTableFile :String = '!addrtable.txt';
g_sLoginServer_ServeraddrFile :String = '!serveraddr.txt';
g_sLoginServerUserLimitFile :String = '!UserLimit.txt';
g_sLoginServerFeedIDListFile :String = 'FeedIDList.txt';
g_sLoginServerFeedIPListFile :String = 'FeedIPList.txt';
g_nLoginServer_MainFormX :Integer = 251;
g_nLoginServer_MainFormY :Integer = 0;
g_nLoginServer_RouteList :TList;
g_sLogServer_ProgramFile :String = 'LogDataServer.exe';
g_sLogServer_Directory :String = 'LogServer\';
g_boLogServer_GetStart :Boolean = True;
g_sLogServer_ConfigFile :String = 'LogData.ini';
g_sLogServer_BaseDir :String = 'BaseDir\';
g_sLogServer_ServerAddr :String = '127.0.0.1';
g_nLogServer_Port :Integer = 10000;
g_nLogServer_MainFormX :Integer = 251;
g_nLogServer_MainFormY :Integer = 239;
g_sM2Server_ProgramFile :String = 'M2Server.exe';
g_sM2Server_Directory :String = 'Mir200\';
g_boM2Server_GetStart :Boolean = True;
g_sM2Server_ConfigFile :String = '!setup.txt';
g_sM2Server_AbuseFile :String = '!abuse.txt';
g_sM2Server_RunAddrFile :String = '!runaddr.txt';
g_sM2Server_ServerTableFile :String = '!servertable.txt';
g_nM2Server_ServerNumber :Integer = 0;
g_nM2Server_ServerIndex :Integer = 0;
g_boM2Server_VentureServer :Boolean = False;
g_boM2Server_TestServer :Boolean = True;
g_nM2Server_TestLevel :Integer = 1;
g_nM2Server_TestGold :Integer = 0;
g_boM2Server_ServiceMode :Boolean = False;
g_boM2Server_NonPKServer :Boolean = False;
g_sM2Server_MsgSrvAddr :String = '127.0.0.1';
g_nM2Server_MsgSrvPort :Integer = 4900;
g_sM2Server_GateAddr :String = '127.0.0.1';
g_nM2Server_GatePort :Integer = 5000;
g_sM2Server_BaseDir :String = 'Share\';
g_sM2Server_GuildDir :String = 'GuildBase\Guilds\';
g_sM2Server_GuildFile :String = 'GuildBase\Guildlist.txt';
g_sM2Server_VentureDir :String = 'ShareV\';
g_sM2Server_ConLogDir :String = 'ConLog\';
g_sM2Server_LogDir :String = 'Log\';
g_sM2Server_CastleDir :String = 'Castle\';
g_sM2Server_EnvirDir :String = 'Envir\';
g_sM2Server_MapDir :String = 'Map\';
g_sM2Server_NoticeDir :String = 'Notice\';
g_sM2Server_CastleFile :String = 'Castle\List.txt';//20081214
g_sM2Server_BoxsDir :String = 'Envir\Boxs\';//20081214
g_sM2Server_BoxsFile :String = 'Envir\Boxs\BoxsList.txt';//20081214
g_nM2Server_MainFormX :Integer = 560;
g_nM2Server_MainFormY :Integer = 0;
g_sLoginGate_ProgramFile :String = 'LoginGate.exe';
g_sLoginGate_Directory :String = 'LoginGate\';
g_boLoginGate_GetStart :Boolean = True;
g_sLoginGate_ConfigFile :String = 'Config.ini';
g_sLoginGate_ServerAddr :String = '127.0.0.1';
g_nLoginGate_ServerPort :Integer = 5500;
g_sLoginGate_GateAddr :String = '0.0.0.0';
g_nLoginGate_GatePort :Integer = 7000;
g_nLoginGate_ShowLogLevel :Integer = 3;
g_nLoginGate_MaxConnOfIPaddr :Integer = 20;
g_nLoginGate_BlockMethod :Integer = 0;
g_nLoginGate_KeepConnectTimeOut :Integer = 60000;
g_nLoginGate_MainFormX :Integer = 0;
g_nLoginGate_MainFormY :Integer = 0;
g_sSelGate_ProgramFile :String = 'SelGate.exe';
g_sSelGate_Directory :String = 'SelGate\';
g_boSelGate_GetStart :Boolean = True;
g_sSelGate_ConfigFile :String = 'Config.ini';
g_sSelGate_ServerAddr :String = '127.0.0.1';
g_nSelGate_ServerPort :Integer = 5100;
g_sSelGate_GateAddr :String = '0.0.0.0';
g_nSelGate_GatePort :Integer = 7100;
g_sSelGate_GateAddr1 :String = '0.0.0.0';
g_nSelGate_GatePort1 :Integer = 7101;
g_nSelGate_ShowLogLevel :Integer = 3;
g_nSelGate_MaxConnOfIPaddr :Integer = 20;
g_nSelGate_BlockMethod :Integer = 0;
g_nSelGate_KeepConnectTimeOut :Integer = 60000;
g_nSelGate_MainFormX :Integer = 0;
g_nSelGate_MainFormY :Integer = 163;
g_sRunGate_ProgramFile :String = 'RunGate.exe';
g_sRunGate_RegKey :String = 'ABCDEFGHIJKL';
// g_sRunGate_RegKey :String = '0123456789';
g_sRunGate_Directory :String = 'RunGate\';
g_boRunGate_GetStart :Boolean = True;
g_boRunGate1_GetStart :Boolean = True;
g_boRunGate2_GetStart :Boolean = True;
g_boRunGate3_GetStart :Boolean = False;
g_boRunGate4_GetStart :Boolean = False;
g_boRunGate5_GetStart :Boolean = False;
g_boRunGate6_GetStart :Boolean = False;
g_boRunGate7_GetStart :Boolean = False;
g_sRunGate_ConfigFile :String = 'RunGate.ini';
g_nRunGate_Count :Integer = 3; //游戏网关数量
g_sRunGate_ServerAddr :String = '127.0.0.1';
g_nRunGate_ServerPort :Integer = 5000;
g_sRunGate_GateAddr :String = '0.0.0.0';
g_nRunGate_GatePort :Integer = 7200;
g_sRunGate1_GateAddr :String = '0.0.0.0';
g_nRunGate1_GatePort :Integer = 7300;
g_sRunGate2_GateAddr :String = '0.0.0.0';
g_nRunGate2_GatePort :Integer = 7400;
g_sRunGate3_GateAddr :String = '0.0.0.0';
g_nRunGate3_GatePort :Integer = 7500;
g_sRunGate4_GateAddr :String = '0.0.0.0';
g_nRunGate4_GatePort :Integer = 7600;
g_sRunGate5_GateAddr :String = '0.0.0.0';
g_nRunGate5_GatePort :Integer = 7700;
g_sRunGate6_GateAddr :String = '0.0.0.0';
g_nRunGate6_GatePort :Integer = 7800;
g_sRunGate7_GateAddr :String = '0.0.0.0';
g_nRunGate7_GatePort :Integer = 7900;
DBServer :TProgram;
LoginServer :TProgram;
LogServer :TProgram;
M2Server :TProgram;
RunGate :TProgram;
RunGate1 :TProgram;
RunGate2 :TProgram;
RunGate3 :TProgram;
RunGate4 :TProgram;
RunGate5 :TProgram;
RunGate6 :TProgram;
RunGate7 :TProgram;
SelGate :TProgram;
SelGate1 :TProgram;
LoginGate :TProgram;
LoginGate1 :TProgram;
g_dwStopTick :LongWord;
g_dwStopTimeOut :LongWord = 15000;
g_boShowDebugTab:Boolean = False; //是否打开测试页
g_dwM2CheckCodeAddr:LongWord;
g_dwDBCheckCodeAddr:LongWord;
const
tDBServer=0;
tLoginSrv=1;
tLogServer=2;
tM2Server=3;
tLoginGate=4;
tLoginGate1=5;
tSelGate=6;
tSelGate1=7;
tRunGate=8;
tRunGate1=9;
tRunGate2=10;
tRunGate3=11;
tRunGate4=12;
tRunGate5=13;
tRunGate6=14;
tRunGate7=15;
implementation
procedure LoadConfig();
begin
g_dwStopTimeOut:=g_IniConf.ReadInteger('GameConf','dwStopTimeOut',g_dwStopTimeOut);
g_boShowDebugTab:=g_Iniconf.ReadBool('GameConf','ShowDebugTab',g_boShowDebugTab);
g_sGameDirectory:=g_IniConf.ReadString('GameConf','GameDirectory',g_sGameDirectory);
g_sHeroDBName:=g_IniConf.ReadString('GameConf','HeroDBName',g_sHeroDBName);
g_sGameName:=g_IniConf.ReadString('GameConf','GameName',g_sGameName);
g_sExtIPaddr:=g_IniConf.ReadString('GameConf','ExtIPaddr',g_sExtIPaddr);
g_boTwoServer:=g_IniConf.ReadBool('GameConf','TwoServer',g_boTwoServer);
g_nServerNum:=g_IniConf.ReadInteger('GameConf','ServerNum',g_nServerNum);
g_nDBServer_MainFormX:=g_IniConf.ReadInteger('DBServer','MainFormX',g_nDBServer_MainFormX);
g_nDBServer_MainFormY:=g_IniConf.ReadInteger('DBServer','MainFormY',g_nDBServer_MainFormY);
g_nDBServer_Config_GatePort:=g_IniConf.ReadInteger('DBServer','GatePort',g_nDBServer_Config_GatePort);
g_nDBServer_Config_ServerPort:=g_IniConf.ReadInteger('DBServer','ServerPort',g_nDBServer_Config_ServerPort);
g_boDBServer_GetStart:=g_IniConf.ReadBool('DBServer','GetStart',g_boDBServer_GetStart);
g_nM2Server_MainFormX:=g_IniConf.ReadInteger('M2Server','MainFormX',g_nM2Server_MainFormX);
g_nM2Server_MainFormY:=g_IniConf.ReadInteger('M2Server','MainFormY',g_nM2Server_MainFormY);
g_nM2Server_TestLevel:=g_IniConf.ReadInteger('M2Server','TestLevel',g_nM2Server_TestLevel);
g_nM2Server_TestGold:=g_IniConf.ReadInteger('M2Server','TestGold',g_nM2Server_TestGold);
g_nM2Server_GatePort:=g_IniConf.ReadInteger('M2Server','GatePort',g_nM2Server_GatePort);
g_nM2Server_MsgSrvPort:=g_IniConf.ReadInteger('M2Server','MsgSrvPort',g_nM2Server_MsgSrvPort);
g_boM2Server_GetStart:=g_IniConf.ReadBool('M2Server','GetStart',g_boM2Server_GetStart);
g_nLoginGate_MainFormX:=g_IniConf.ReadInteger('LoginGate','MainFormX',g_nLoginGate_MainFormX);
g_nLoginGate_MainFormY:=g_IniConf.ReadInteger('LoginGate','MainFormY',g_nLoginGate_MainFormY);
g_boLoginGate_GetStart:=g_IniConf.ReadBool('LoginGate','GetStart',g_boLoginGate_GetStart);
g_nLoginGate_GatePort:=g_IniConf.ReadInteger('LoginGate','GatePort',g_nLoginGate_GatePort);
g_nSelGate_MainFormX:=g_IniConf.ReadInteger('SelGate','MainFormX',g_nSelGate_MainFormX);
g_nSelGate_MainFormY:=g_IniConf.ReadInteger('SelGate','MainFormY',g_nSelGate_MainFormY);
g_nSelGate_GatePort:=g_IniConf.ReadInteger('SelGate','GatePort',g_nSelGate_GatePort);
g_nSelGate_GatePort1:=g_IniConf.ReadInteger('SelGate','GatePort1',g_nSelGate_GatePort1);
g_boSelGate_GetStart:=g_IniConf.ReadBool('SelGate','GetStart',g_boSelGate_GetStart);
g_nRunGate_Count:=g_IniConf.ReadInteger('RunGate','Count',g_nRunGate_Count);
g_nRunGate_GatePort:=g_IniConf.ReadInteger('RunGate','GatePort1',g_nRunGate_GatePort);
g_nRunGate1_GatePort:=g_IniConf.ReadInteger('RunGate','GatePort2',g_nRunGate1_GatePort);
g_nRunGate2_GatePort:=g_IniConf.ReadInteger('RunGate','GatePort3',g_nRunGate2_GatePort);
g_nRunGate3_GatePort:=g_IniConf.ReadInteger('RunGate','GatePort4',g_nRunGate3_GatePort);
g_nRunGate4_GatePort:=g_IniConf.ReadInteger('RunGate','GatePort5',g_nRunGate4_GatePort);
g_nRunGate5_GatePort:=g_IniConf.ReadInteger('RunGate','GatePort6',g_nRunGate5_GatePort);
g_nRunGate6_GatePort:=g_IniConf.ReadInteger('RunGate','GatePort7',g_nRunGate6_GatePort);
g_nRunGate7_GatePort:=g_IniConf.ReadInteger('RunGate','GatePort8',g_nRunGate7_GatePort);
g_boRunGate1_GetStart:=g_nRunGate_Count >= 2;
g_boRunGate2_GetStart:=g_nRunGate_Count >= 3;
g_boRunGate3_GetStart:=g_nRunGate_Count >= 4;
g_boRunGate4_GetStart:=g_nRunGate_Count >= 5;
g_boRunGate5_GetStart:=g_nRunGate_Count >= 6;
g_boRunGate6_GetStart:=g_nRunGate_Count >= 7;
g_boRunGate7_GetStart:=g_nRunGate_Count >= 8;
if g_boRunGate4_GetStart then begin
g_sDBServer_Config_GateAddr:=g_sAllIPaddr;
end else begin
g_sDBServer_Config_GateAddr:=g_sLocalIPaddr;
end;
g_nLoginServer_MainFormX:=g_IniConf.ReadInteger('LoginServer','MainFormX',g_nLoginServer_MainFormX);
g_nLoginServer_MainFormY:=g_IniConf.ReadInteger('LoginServer','MainFormY',g_nLoginServer_MainFormY);
g_nLoginServer_GatePort:=g_IniConf.ReadInteger('LoginServer','GatePort',g_nLoginServer_GatePort);
g_nLoginServer_MonPort:=g_IniConf.ReadInteger('LoginServer','MonPort',g_nLoginServer_MonPort);
g_nLoginServer_ServerPort:=g_IniConf.ReadInteger('LoginServer','ServerPort',g_nLoginServer_ServerPort);
g_boLoginServer_GetStart:=g_IniConf.ReadBool('LoginServer','GetStart',g_boLoginServer_GetStart);
g_nLogServer_MainFormX:=g_IniConf.ReadInteger('LogServer','MainFormX',g_nLogServer_MainFormX);
g_nLogServer_MainFormY:=g_IniConf.ReadInteger('LogServer','MainFormY',g_nLogServer_MainFormY);
g_boLogServer_GetStart:=g_IniConf.ReadBool('LogServer','GetStart',g_boLogServer_GetStart);
g_nLogServer_Port:=g_IniConf.ReadInteger('LogServer','Port',g_nLogServer_Port);
end;
function RunProgram(var ProgramInfo:TProgram;sHandle:String;dwWaitTime:LongWord):LongWord;
var
StartupInfo:TStartupInfo;
sCommandLine:String;
sCurDirectory:String;
begin
Result:=0;
FillChar(StartupInfo,SizeOf(TStartupInfo),#0);
{
StartupInfo.cb:=SizeOf(TStartupInfo);
StartupInfo.lpReserved:=nil;
StartupInfo.lpDesktop:=nil;
StartupInfo.lpTitle:=nil;
StartupInfo.dwFillAttribute:=0;
StartupInfo.cbReserved2:=0;
StartupInfo.lpReserved2:=nil;
}
GetStartupInfo(StartupInfo);
sCommandLine:=format('%s%s %s %d %d',[ProgramInfo.sDirectory,ProgramInfo.sProgramFile,sHandle,ProgramInfo.nMainFormX,ProgramInfo.nMainFormY]);
sCurDirectory:=ProgramInfo.sDirectory;
if not CreateProcess(nil, //lpApplicationName,
PChar(sCommandLine), //lpCommandLine,
nil, //lpProcessAttributes,
nil, //lpThreadAttributes,
True, //bInheritHandles,
0, //dwCreationFlags,
nil, //lpEnvironment,
PChar(sCurDirectory), //lpCurrentDirectory,
StartupInfo, //lpStartupInfo,
ProgramInfo.ProcessInfo) then begin //lpProcessInformation
Result:=GetLastError();
end;
Sleep(dwWaitTime);
end;
function StopProgram(var ProgramInfo:TProgram;dwWaitTime:LongWord):Integer;
var
dwExitCode:LongWord;
begin
Result:=0;
if TerminateProcess(ProgramInfo.ProcessHandle,dwExitCode) then begin
Result:=GetLastError();
end;
Sleep(dwWaitTime);
end;
procedure SendProgramMsg(DesForm:THandle;wIdent:Word;sSendMsg:String);
var
SendData:TCopyDataStruct;
nParam:Integer;
begin
nParam:=MakeLong(0,wIdent);
SendData.cbData:=Length (sSendMsg) + 1;
GetMem(SendData.lpData,SendData.cbData);
StrCopy (SendData.lpData, PChar(sSendMsg));
SendMessage(DesForm,WM_COPYDATA,nParam,Cardinal(@SendData));
FreeMem(SendData.lpData);
end;
initialization
begin
g_sConfFile := ExtractFilePath(ParamStr(0))+g_sConfFile; //增加取程序目录路径 20080222
g_IniConf:=TIniFile.Create(g_sConfFile);
end;
finalization
begin
g_IniConf.Free;
end;
end.
|
unit ComPort;
interface
uses
Windows, SysUtils;
type
TComPortWriteLnEvent = procedure(const aLine: AnsiString) of object;
TComPort = class(TObject)
private
fHandle: THandle;
fIsOpen, fIsSetup: boolean;
fOnWriteLn: TComPortWriteLnEvent;
procedure DoOnWriteLn(const aLine: AnsiString);
public
constructor Create;
destructor Destroy; override;
function Open(aDeviceName: String): boolean;
function Setup(aBaudRate: Cardinal): boolean;
procedure WriteLn(aString: AnsiString);
procedure Close;
property OnWriteLn: TComPortWriteLnEvent read fOnWriteLn write fOnWriteLn;
end;
implementation
{ TComPort }
procedure TComPort.Close;
begin
fIsOpen := false;
fIsSetup := false;
CloseHandle(fHandle);
end;
constructor TComPort.Create;
begin
inherited Create;
fIsOpen := false;
fIsSetup := false;
fOnWriteLn := nil;
end;
destructor TComPort.Destroy;
begin
Close;
inherited;
end;
procedure TComPort.DoOnWriteLn(const aLine: AnsiString);
begin
if assigned(fOnWriteLn) then
fOnWriteLn(aLine);
end;
{ First step is to open the communications device for read/write.
This is achieved using the Win32 'CreateFile' function.
If it fails, the function returns false. }
function TComPort.Open(aDeviceName: String): boolean;
var
DeviceName: array[0..80] of Char;
begin
if not fIsOpen then
begin
StrPCopy(DeviceName, aDeviceName);
fHandle := CreateFile(DeviceName,
GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if fHandle = INVALID_HANDLE_VALUE then
Result := False
else
begin
Result := True;
fIsOpen := True;
end;
end
else
Result := true;
end;
procedure TComPort.WriteLn(aString: AnsiString);
var
BytesWritten: DWORD;
begin
if (fIsOpen and fIsSetup) then
begin
aString := aString + #10;
WriteFile(fHandle, aString[1], Length(aString), BytesWritten, nil);
DoOnWriteLn(aString);
end;
end;
function TComPort.Setup(aBaudRate: Cardinal): boolean;
const
RxBufferSize = 256;
TxBufferSize = 256;
var
DCB: TDCB;
Config: string;
CommTimeouts: TCommTimeouts;
begin
Result := True;
if not SetupComm(fHandle, RxBufferSize, TxBufferSize) then
Result := False;
if not GetCommState(fHandle, DCB) then
Result := False;
Config := 'baud=' + IntToStr(aBaudRate) + ' parity=n data=8 stop=1';
if not BuildCommDCB(@Config[1], DCB) then
Result := False;
if not SetCommState(fHandle, DCB) then
Result := False;
with CommTimeouts do
begin
ReadIntervalTimeout := 0;
ReadTotalTimeoutMultiplier := 0;
ReadTotalTimeoutConstant := 1000;
WriteTotalTimeoutMultiplier := 0;
WriteTotalTimeoutConstant := 1000;
end;
if not SetCommTimeouts(fHandle, CommTimeouts) then
Result := False;
fIsSetup := Result;
end;
end.
|
unit uDrpHelperClase;
{
分销系统公用类
许志祥 2013-12-15
}
interface
uses SysUtils,Windows, Classes, Controls, Graphics,Forms,FrmCliMain,DB,Pub_Fun,ADODB,StdCtrls,cxLabel,
StringUtilClass,DBClient,IdGlobal,Math,FrmCliDM,uPubThreadQuery,cxGridDBTableView, cxGrid;
//POS方法.不区分大小字
function PosEx(Src,cpStr:String):Integer;
function IsStrExists(src,strList:string;sDelimiter:Char = ','):Boolean;
//取数据集的FID值字符串
function GetSelectedFIDs(cds:TDataSet;fieldName:string):String;
//搜索窗口内lable控件标题,并且改变颜色 ,Exclude,不参加搜索的控制名,多个以逗号隔开
function Findlablecaption(Frm:TControl;title:string;Exclude:String=''):String;
//检查重复值
function chk_Repeat(sFID,sFnumber,sTableName: string): Boolean;
//上传附件
function UpLoadFile(FilePath,FBOID,FShareRange:string;var ErrMsg:string):Boolean ;
procedure Get_UserSupplier(cdsSupplier : TClientDataSet;var ErrMsg:string);
procedure InitAssInfo(var sErrMsg : String); //初始化辅助资料 ,从服务端取数据
procedure Get_OrderType(var ErrMsg : String;IsCloseConn :Boolean=True); //获取订单类型
procedure Get_PriceType(var ErrMsg : String;IsCloseConn :Boolean=True); //价格类型
procedure Get_SizeGroup(var ErrMsg : String;IsCloseConn :Boolean=True); //尺码组
procedure Get_Attribute(var ErrMsg : String;IsCloseConn :Boolean=True); //波段
procedure Get_Brand(var ErrMsg : String;IsCloseConn :Boolean=True);//品牌
procedure Get_ShipType(var ErrMsg : String;IsCloseConn :Boolean=True);//发货类型
procedure Get_UserCust(cdsCust : TClientDataSet;var ErrMsg:string); //用户所有拥有的客户
procedure Get_UserWareHouse(cdsware : TClientDataSet;var ErrMsg:string); //用户所有拥有的仓库
procedure GetAllWarehouse(cdsware : TClientDataSet;var ErrMsg:string);
procedure Get_UserBranch(var ErrMsg:string); //获取用户的机构
procedure Get_UserBizOrg(sTable :string;var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True); //获取用户的业务组织
procedure Get_OrderingDef(var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True) ;//订货会定义
procedure Get_UserWareByStorageOrg(StorageOrgID : string;cdsware : TClientDataSet;var ErrMsg:string); //按库存组织过滤用户所拥有的仓库
Function Get_UserWareByStorageOrg_Show(sStorageOrg,_Caption,_oldVal : string;_isRadioSelect :Integer=1):TClientDataSet; //按库存组织过滤用户所拥有的仓库
procedure Get_UserCustBySaleOrg(SaleOrgID : string;cdsCust : TClientDataSet;var ErrMsg:string); //按销售组织过滤用户所拥有的客户
Function Get_UserCustBySaleOrg_Show(sSaleOrg,_Caption,_oldVal : string;_isRadioSelect :Integer=1):TADODataSet; //按销售组织过滤用户所拥有的客户
//============================================================================
{
以下为组织选择公用方法,另:uMaterDataSelectHelper.Select_Branch 支持虚体组织树形显示
}
//iFrom 2 销售组织 3 采购组织 4 库存组织 ; sTable:T_ORg_sale,t_Org_Storage,t_Org_Purchase
procedure Get_BizFindFinOrg(iFrom :Integer;sBizOrg,sTable :string;var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True); //通过业务组织找财务组织
procedure Get_FromBizToFin(sFinOrg,sTable :string;var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True); //通过财务组织找业务组织 sTable:T_ORg_sale,t_Org_Storage,t_Org_Purchase
procedure Get_FromSaleToStorage(sSaleOrg : string;var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True); //销售组织找库存组织
procedure Get_FromPurToStorage(sPurOrg : string;var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True); //采购组织找库存组织
procedure Get_FromStorageToSale(sStorageOrg : string;var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True); //库存组织找 销售组织
procedure Get_FromStorageToPur(sStorageOrg : string;var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True); //销售组织找采购组织
//以下为弹框方法
function Get_FromBizToFin_Show(sFinOrg,sTable,_Caption,_oldVal :string;_isRadioSelect :Integer=1):TClientDataSet; //通过财务组织找业务组织
function Get_FromSaleToStorage_show(sSaleOrg,_Caption,_oldVal : string;_isRadioSelect :Integer=1):TClientDataSet; //销售组织找库存组织
function Get_FromPurToStorage_show(sPurOrg,_Caption,_oldVal : string;_isRadioSelect :Integer=1):TClientDataSet; //采购组织找库存组织
function Get_FromStorageToSale_Show(sStorageOrg,_Caption,_oldVal : string;_isRadioSelect :Integer=1):TClientDataSet; //库存组织找 销售组织
function Get_FromStorageToPur_Show(sStorageOrg,_Caption,_oldVal : string;_isRadioSelect :Integer=1):TClientDataSet; //销售组织找采购组织
//选实体组织方法,无树形结构
function Get_BIZSALEORG_Show(_FormTitle,_oldVal:string;isRadioSelect:Integer=1):TClientDataSet; //选择实体销售组织
function Get_BIZPURORG_Show(_FormTitle,_oldVal:string;isRadioSelect:Integer=1):TClientDataSet; //选择实体采购组织
function Get_BIZSTORAGEORG_Show(_FormTitle,_oldVal:string;isRadioSelect:Integer=1):TClientDataSet; //选择实体库存组织
function Get_BIZFINORG_Show(_FormTitle,_oldVal:string;isRadioSelect:Integer=1):TClientDataSet; //选择实体财务组织
function Get_BIZCOST_Show(_FormTitle,_oldVal:string;isRadioSelect:Integer=1):TClientDataSet; //选择实体成本组织
//============================================================================
procedure Get_BizType(sBillTypeID:string ;var ErrMsg:string;cdsBizType : TClientDataSet);///获取业务类型
procedure Get_PURTYPE(var ErrMsg:string);
procedure Get_PurRecType(var ErrMsg:string);
procedure Get_Range(var ErrMsg:string);
procedure Get_Person(var ErrMsg:string); //人员
procedure Get_Unit(var ErrMsg :string); //单位
procedure Get_AssValue(var ErrMsg : string);
procedure Get_Year(var ErrMsg : string;IsCloseConn :Boolean=True); ///年份
procedure Get_Season(var ErrMsg : string;IsCloseConn :Boolean=True);//季节
procedure Get_Sex(var ErrMsg : string;IsCloseConn :Boolean=True);///性别
procedure Get_Position(var ErrMsg : string;IsCloseConn :Boolean=True);//位置
procedure Get_CATEGORY(var ErrMsg : string;IsCloseConn :Boolean=True);//产品类型
procedure Get_Genre(var ErrMsg : string;IsCloseConn :Boolean=True);//类别
procedure Get_ClientAssInfo; //初始化辅助资料 ,从客户端取数据
procedure InitAsstAttrTables; //初始化辅助属性相关表数据
procedure Get_ClientSizeGroup;
procedure Get_ClientSize;
procedure Get_ClientColor;
procedure Get_ClientCup;
procedure Get_ClientPACK;
procedure IniBIllCONSTInfo;
procedure IniSysParamInfo(var ErrMsg :string);//初始化系统参数
procedure CopyDataset(src,dec:TClientDataSet);
procedure CopyDatasetStructure(src,dec:TClientDataSet);
procedure CopyDatasetCurRecord(src,dec:TClientDataSet);
//-----------------多线程方法-----------------------------
Procedure Thread_OpenSQL(_PHandle: LongWord;var cdsPub: TClientDataSet;SQL:String;RstNumber:integer);
Procedure Thread_ExecSQL(_PHandle: LongWord;SQL:String;RstNumber:integer);
Procedure Thread_QueryRemind(_PHandle: LongWord;var cdsPub:TClientDataSet;RstNumber:integer);
procedure SetGridClumnTitle(fMaterialID: string;cxGridTV: TcxGridDBTableView);//设置网格列头
//-----------------多线程方法-----------------------------
implementation
uses uMaterDataSelectHelper;
Procedure Thread_OpenSQL(_PHandle: LongWord;var cdsPub: TClientDataSet;SQL:String;RstNumber:integer);
var ThreadQuery : TPubQueryThread;
begin
ThreadQuery := TPubQueryThread.Create;
ThreadQuery.PHandle := _PHandle;
ThreadQuery.SckCon.Host := CliDm.SckThread.Host;
ThreadQuery.SckCon.Port := CliDm.SckThread.Port;
ThreadQuery.cdsPub := cdsPub;
ThreadQuery.SQL := SQL;
ThreadQuery.ResultMsgNumber := RstNumber;
ThreadQuery.FType := 0;
ThreadQuery.Resume;
end;
Procedure Thread_ExecSQL(_PHandle: LongWord;SQL:String;RstNumber:integer);
var ThreadQuery : TPubQueryThread;
begin
ThreadQuery.PHandle := _PHandle;
ThreadQuery := TPubQueryThread.Create;
ThreadQuery.SckCon.Host := CliDm.SckThread.Host;
ThreadQuery.SckCon.Port := CliDm.SckThread.Port;
ThreadQuery.SQL := SQL;
ThreadQuery.ResultMsgNumber := RstNumber;
ThreadQuery.FType := 1;
ThreadQuery.Resume;
end;
Procedure Thread_QueryRemind(_PHandle: LongWord;var cdsPub:TClientDataSet;RstNumber:integer);
var ThreadQuery : TPubQueryThread;
begin
ThreadQuery := TPubQueryThread.Create;
ThreadQuery.PHandle := _PHandle;
ThreadQuery.SckCon.Host := CliDm.SckThread.Host;
ThreadQuery.SckCon.Port := CliDm.SckThread.Port;
ThreadQuery.cdsPub := cdsPub;
ThreadQuery.ResultMsgNumber := RstNumber;
ThreadQuery.FType := 3;
ThreadQuery.Resume;
end;
function PosEx(Src,cpStr:String):Integer;
begin
Result := Pos(UpperCase(Trim(src)),UpperCase(Trim(cpStr)));
end;
function GetSelectedFIDs(cds:TDataSet;fieldName:string):String;
begin
Result := '';
if cds.IsEmpty then Exit;
if cds.FindField(fieldName) = nil then Exit;
try
cds.DisableControls;
cds.First;
while not cds.Eof do
begin
if Result = '' then
Result := cds.fieldbyname(fieldName).AsString
else
Result := Result+',' + cds.fieldbyname(fieldName).AsString;
cds.Next;
end;
finally
cds.EnableControls;
end;
end;
function IsStrExists(src,strList:string;sDelimiter:Char = ','):Boolean;
var sList : TStringList;
i : Integer;
begin
Result := False;
if Trim(src) = '' then Exit;
if Trim(strList) = '' then Exit;
try
sList := TStringList.Create;
sList.Delimiter := sDelimiter;
sList.DelimitedText := strList;
for i := 0 to sList.Count - 1 do
begin
if UpperCase(Trim(sList[i])) = UpperCase(Trim(src)) then
begin
Result := True;
Exit;
end;
end;
finally
sList.Free;
end;
end;
function Findlablecaption(Frm:TControl;title:string;Exclude:String=''):String;
var i:Integer;
foc : TControl;
begin
if Frm.ComponentCount > 0 then
begin
for i:=0 to Frm.ComponentCount -1 do
begin
if (Frm.Components[i] is TLabel) then
begin
if not IsStrExists(TLabel(Frm.Components[i]).Name,Exclude) then
begin
TLabel(Frm.Components[i]).Font.Color := clBlack;
if (PosEx(title,TLabel(Frm.Components[i]).Caption) > 0 ) or
(PosEx(title,ChnToPY(TLabel(Frm.Components[i]).Caption)) > 0 )
then
TLabel(Frm.Components[i]).Font.Color := clred;
end;
Continue;
end;
if (Frm.Components[i] is TcxLabel) then
begin
if not IsStrExists(TcxLabel(Frm.Components[i]).Name,Exclude) then
begin
TcxLabel(Frm.Components[i]).Style.Font.Color := clBlack;
if (PosEx(title,TcxLabel(Frm.Components[i]).Caption) > 0) or
(PosEx(title,ChnToPY(TcxLabel(Frm.Components[i]).Caption)) > 0)
then
TcxLabel(Frm.Components[i]).Style.Font.Color := clred;
end;
Continue;
end;
foc := TControl(Frm.Components[i]);
if Frm.ComponentCount > 0 then Findlablecaption(foc,title,Exclude);
end;
end;
end;
function chk_Repeat(sFID,sFnumber,sTableName: string): Boolean;
var fid,fnumber,_sql,ErrMsg:string;
begin
Result := False;
fid := sFid;
fnumber := sFnumber;
_sql := 'select fid from '+sTableName+' where fid<>'+QuotedStr(fid)+' and fnumber='+QuotedStr(fnumber);
if (string(CliDM.Get_QueryReturn(_sql,ErrMsg))<>'') then
begin
Result := True;
end;
end;
//上传附件
function UpLoadFile(FilePath,FBOID,FShareRange:string;var ErrMsg:string):Boolean ;
var cdsAttachment, //附件表
cdsBOATTCHASSO:TClientDataSet; //业务对象关联表
boSQL,AttSQL,FAttachmentID,FileName,FileType:string;
fSize : Integer;
vstream: TMemoryStream;
begin
Result := False;
if not FileExists(FilePath) then
begin
ErrMsg := '文件不存在!';
Exit;
end;
FileName := ExtractFileName(FilePath);
FileType := ExtractFileExt(FilePath);
fSize := FileSizeByName(FilePath);
try
cdsAttachment := TClientDataSet.Create(nil);
cdsBOATTCHASSO := TClientDataSet.Create(nil);
vstream := TMemoryStream.Create;
if not CliDM.ConnectSckCon(ErrMsg) then Exit;
FAttachmentID := Get_Guid;
boSQL := ' select FID,FBoID,FAttachmentID from T_BAS_BOATTCHASSO where 1<>1';
AttSQL := ' select FID,FType,FSize,FFile,FSizeInByte,FShareRange,FStorageType,'
+' FNAME_L2,FSimpleName,FCreatorID,FCreateTime,FLastUpdateUserID,FLastUpdateTime,'
+' FControlUnitID from T_BAS_ATTACHMENT a'
+' where 1<>1';
if not CliDM.Get_OpenSQL(cdsBOATTCHASSO,boSQL,ErrMsg,False) then Exit;
if not CliDM.Get_OpenSQL(cdsAttachment,AttSQL,ErrMsg,False) then Exit;
cdsBOATTCHASSO.Append;
cdsBOATTCHASSO.FieldByName('FID').AsString := Get_Guid;
cdsBOATTCHASSO.FieldByName('FBoID').AsString := FBOID;
cdsBOATTCHASSO.FieldByName('FAttachmentID').AsString := FAttachmentID;
cdsBOATTCHASSO.Post;
cdsAttachment.Append;
cdsAttachment.FieldByName('FID').AsString := FAttachmentID;
cdsAttachment.FieldByName('FType').AsString := FileType;
vstream.LoadFromFile(FilePath);
TBlobField(cdsAttachment.FieldByName('FFile')).LoadFromStream(vstream);
cdsAttachment.FieldByName('FSize').AsString := FloatToStr(SimpleRoundTo(fSize / 1024,-4));
cdsAttachment.FieldByName('FSizeInByte').AsInteger := fSize ;
cdsAttachment.FieldByName('FShareRange').AsString := FShareRange;
cdsAttachment.FieldByName('FStorageType').AsInteger := 0;
cdsAttachment.FieldByName('FNAME_L2').AsString := FileName;
cdsAttachment.FieldByName('FSimpleName').AsString := FileType;
cdsAttachment.FieldByName('FCreatorID').AsString := UserInfo.LoginUser_FID;
cdsAttachment.FieldByName('FCreateTime').AsDateTime := now;
cdsAttachment.FieldByName('FLastUpdateUserID').AsString := UserInfo.LoginUser_FID;
cdsAttachment.FieldByName('FLastUpdateTime').AsDateTime := Now;
cdsAttachment.FieldByName('FControlUnitID').AsString := UserInfo.Controlunitid;
cdsAttachment.Post;
Result := CliDM.SckCon.AppServer.E_UpLoadFile(FBOID,cdsBOATTCHASSO.Data,cdsAttachment.Data,ErrMsg)=0;
finally
vstream.Free;
cdsAttachment.Free;
cdsBOATTCHASSO.Free;
CliDM.CloseSckCon;
end;
end;
procedure Get_UserSupplier(cdsSupplier : TClientDataSet;var ErrMsg:string);
var
strsql : string;
begin
cdsSupplier.Close;
//cdsSupplier.EmptyDataSet;
cdsSupplier.CreateDataSet;
strsql := 'Select A.FID,A.fnumber,A.fname_l2,A.FinternalCompanyID,A.FtaxRate,FhelpCode '
+' From t_Bd_Supplier A left join Ct_Pm_Usersupplierentry S on A.FID=S.CFSID '
+' left join t_Pm_Userroleorg R on R.FROLEID=S.Fparentid '
+' Where (S.Fparentid='''+userinfo.LoginUser_FID+''' or R.Fuserid='''+userinfo.LoginUser_FID+''' ) and A.FUsedStatus=1 ';
Clidm.Get_OpenSQL(CliDM.cdstemp,strsql,ErrMsg);//获取供应商owen
while not CliDM.cdstemp.Eof do
begin
if not FindRecord1(cdsSupplier,'FID',CliDM.cdstemp.fieldbyname('FID').AsString,1) then
begin
cdsSupplier.Append;
cdsSupplier.FieldByName('FID').AsString := CliDM.cdstemp.fieldbyname('FID').AsString;
cdsSupplier.FieldByName('fnumber').AsString := CliDM.cdstemp.fieldbyname('fnumber').AsString;
cdsSupplier.FieldByName('fname_l2').AsString := CliDM.cdstemp.fieldbyname('fname_l2').AsString;
cdsSupplier.FieldByName('FinternalCompanyID').AsString := CliDM.cdstemp.fieldbyname('FinternalCompanyID').AsString;
cdsSupplier.FieldByName('FtaxRate').AsFloat := CliDM.cdstemp.fieldbyname('FtaxRate').AsFloat;
cdsSupplier.FieldByName('FHelpCode').AsString := CliDM.cdstemp.fieldbyname('FhelpCode').AsString;
cdsSupplier.Post;
end;
CliDM.cdstemp.Next;
end;
CliDM.cdstemp.Close;
end;
procedure InitAssInfo(var sErrMsg : String); //初始化辅助资料
begin
///最后一个方法关闭连接
Get_OrderType(sErrMsg,False); //订单类型
Get_PriceType(sErrMsg,False);//价格类型
Get_SizeGroup(sErrMsg,False);
GET_Attribute(sErrMsg,False);//波段
GET_Brand(sErrMsg,False);
Get_UserSupplier(CliDM.cdsSupplier,sErrMsg); //供应商
Get_UserCust(CliDM.cdsCust,sErrMsg); //客户
Get_UserWareHouse(CliDM.cdsWarehouse,sErrMsg);//仓库
Get_UserBranch(sErrMsg);
GET_PURTYPE(sErrMsg);
Get_PurRecType(sErrMsg);
Get_Range(sErrMsg);
GET_Person(sErrMsg);
IniBIllCONSTInfo;
IniSysParamInfo(sErrMsg);
Get_Unit(sErrMsg);
Get_AssValue(sErrMsg);
Get_ShipType(sErrMsg);
GET_Year(sErrMsg);
GET_Season(sErrMsg);
GET_Sex(sErrMsg);
GET_Position(sErrMsg);
GET_CATEGORY(sErrMsg);
GET_Genre(sErrMsg);
GetAllWarehouse(CliDM.cdsAllWarehouse,sErrMsg);
end;
procedure Get_ClientAssInfo; //初始化辅助资料 ,从客户端取数据
begin
Get_ClientSizeGroup; //查询客户端尺码组
Get_ClientColor;
Get_ClientSize;
Get_ClientCup;
Get_ClientPACK
end;
procedure Get_ClientSizeGroup;
var
strSql : string;
begin
strSql := ' select FID,fnumber,fname_l2 from Ct_Bas_Sizegroup where FGroup=0 ';
CliDM.qrySizeGroup.Close;
CliDM.qrySizeGroup.SQL.Clear;
CliDM.qrySizeGroup.SQL.Add(strSql);
CliDM.qrySizeGroup.Open;
end;
procedure Get_ClientSize;
var
strsql : string;
begin
strSql := ' select FID,fnumber,fname_l2 from T_BD_AsstAttrValue where FBasicTypeID='+QuotedStr(UserInfo.AsstAttrValue_SizeID)+' ';
CliDM.qrySize.Close;
CliDM.qrySize.SQL.Clear;
CliDM.qrySize.SQL.Add(strSql);
CliDM.qrySize.Open;
end;
procedure Get_ClientColor;
var
strsql : string;
begin
strSql := ' select FID,fnumber,fname_l2 from T_BD_AsstAttrValue where FBasicTypeID='+QuotedStr(UserInfo.AsstAttrValue_ColorID)+' ';
CliDM.qryColor.Close;
CliDM.qryColor.SQL.Clear;
CliDM.qryColor.SQL.Add(strSql);
CliDM.qryColor.Open;
end;
procedure Get_ClientCup;
var
strsql : string;
begin
strSql := ' select FID,fnumber,fname_l2 from T_BD_AsstAttrValue where FBasicTypeID='+QuotedStr(UserInfo.AsstAttrValue_BeiID)+' ';
CliDM.qryCup.Close;
CliDM.qryCup.SQL.Clear;
CliDM.qryCup.SQL.Add(strSql);
CliDM.qryCup.Open;
end;
procedure Get_ClientPACK;
var
strsql : string;
begin
strSql := ' select FID,fnumber,fname_l2 from T_BD_AsstAttrValue where FBasicTypeID='+QuotedStr(UserInfo.AsstAttrValue_PackID)+'';
CliDM.qrypack.Close;
CliDM.qrypack.SQL.Clear;
CliDM.qrypack.SQL.Add(strSql);
CliDM.qrypack.Open;
end;
procedure Get_OrderType(var ErrMsg : String;IsCloseConn :Boolean=True);
var
strSql : string;
begin
strSql := 'select FID,fnumber,fname_l2 from CT_BAS_OrderType';
Clidm.Get_OpenSQL(CliDM.cdsOrderType,strsql,ErrMsg,IsCloseConn);
end;
procedure Get_PriceType(var ErrMsg : String;IsCloseConn :Boolean=True);
var
strSql : string;
begin
strSql :='select FID,fnumber,fname_l2 from T_SCM_PriceType';
Clidm.Get_OpenSQL(CliDM.cdsPriceType,strsql,ErrMsg,IsCloseConn);
end;
procedure Get_SizeGroup(var ErrMsg : String;IsCloseConn :Boolean=True); //尺码组
var
strSql : string;
begin
strSql :='select FID,fnumber,fname_l2 from Ct_Bas_Sizegroup where FGroup=0';
Clidm.Get_OpenSQL(CliDM.cdsSizeGroup,strsql,ErrMsg,IsCloseConn);
end;
procedure GET_Attribute(var ErrMsg : String;IsCloseConn :Boolean=True);
var
strSql : string;
begin
strSql := ' select FID,fnumber,fname_l2 from Ct_Bd_Attribute ';
Clidm.Get_OpenSQL(CliDM.cdsAttribute,strsql,ErrMsg,IsCloseConn);
end;
procedure Get_Brand(var ErrMsg : String;IsCloseConn :Boolean=True);
var
strSql : string;
begin
strSql := 'select FID,fnumber,fname_l2 from Ct_Bas_Brand ';
Clidm.Get_OpenSQL(CliDM.cdsBrand,strsql,ErrMsg,IsCloseConn);
end;
procedure Get_ShipType(var ErrMsg : String;IsCloseConn :Boolean=True);
var
strSql : string;
begin
strSql := 'select FID,fnumber,fname_l2 from Ct_Bas_Shiptype ';
Clidm.Get_OpenSQL(CliDM.cdsShipType,strsql,ErrMsg,IsCloseConn);
end;
procedure GET_Year(var ErrMsg : string;IsCloseConn :Boolean=True); ///年份
var
strSql : string;
begin
strSql := 'select FID,fnumber,fname_l2 from Ct_Bas_Years ';
Clidm.Get_OpenSQL(CliDM.cdsYear,strsql,ErrMsg,IsCloseConn);
end;
procedure GET_Season(var ErrMsg : string;IsCloseConn :Boolean=True);//季节
var
strSql : string;
begin
strSql := 'select FID,fnumber,fname_l2 from Ct_Bas_Season ';
Clidm.Get_OpenSQL(CliDM.cdsSeason,strsql,ErrMsg,IsCloseConn);
end;
procedure GET_Sex(var ErrMsg : string;IsCloseConn :Boolean=True);///性别
var
strSql : string;
begin
strSql := 'select FID,fnumber,fname_l2 from Ct_Bd_Gender ';
Clidm.Get_OpenSQL(CliDM.cdsSex,strsql,ErrMsg,IsCloseConn);
end;
procedure GET_Position(var ErrMsg : string;IsCloseConn :Boolean=True);//位置
var
strSql : string;
begin
strSql := 'select FID,fnumber,fname_l2 from Ct_Bd_Position ';
Clidm.Get_OpenSQL(CliDM.cdsPosition,strsql,ErrMsg,IsCloseConn);
end;
procedure GET_CATEGORY(var ErrMsg : string;IsCloseConn :Boolean=True);//产品类型
var
strSql : string;
begin
strSql := 'select FID,fnumber,fname_l2 from Ct_Bd_Category ';
Clidm.Get_OpenSQL(CliDM.cdsCATEGORY,strsql,ErrMsg,IsCloseConn);
end;
procedure GET_Genre(var ErrMsg : string;IsCloseConn :Boolean=True);//类别
var
strSql : string;
begin
strSql := 'select FID,fnumber,fname_l2 from Ct_Bd_Genre ';
Clidm.Get_OpenSQL(CliDM.cdsGenre,strsql,ErrMsg,IsCloseConn);
end;
procedure Get_UserCust(cdsCust : TClientDataSet;var ErrMsg:string);
var
strSql : string;
begin
cdsCust.Close;
cdsCust.CreateDataSet;
strsql := 'Select A.FID,A.fnumber,A.fname_l2,A.FinternalCompanyID,A.FtaxRate,FhelpCode,FTxRegisterNo,FAddress '
+' From t_Bd_Customer A left join Ct_Pm_Usercustomerentry S on A.FID=S.CFCID '
+' left join t_Pm_Userroleorg R on R.FROLEID=S.Fparentid '
+' Where (S.Fparentid='''+userinfo.LoginUser_FID+''' or R.Fuserid='''+userinfo.LoginUser_FID+''' ) and A.FUsedStatus=1 ';
Clidm.Get_OpenSQL(CliDM.cdstemp,strsql,ErrMsg);//获取客户owen
while not CliDM.cdstemp.Eof do
begin
if not FindRecord1(cdsCust,'FID',CliDM.cdstemp.fieldbyname('FID').AsString,1) then
begin
cdsCust.Append;
cdsCust.FieldByName('FID').AsString := CliDM.cdstemp.fieldbyname('FID').AsString;
cdsCust.FieldByName('fnumber').AsString := CliDM.cdstemp.fieldbyname('fnumber').AsString;
cdsCust.FieldByName('fname_l2').AsString := CliDM.cdstemp.fieldbyname('fname_l2').AsString;
cdsCust.FieldByName('FinternalCompanyID').AsString := CliDM.cdstemp.fieldbyname('FinternalCompanyID').AsString;
cdsCust.FieldByName('FtaxRate').AsFloat := CliDM.cdstemp.fieldbyname('FtaxRate').AsFloat;
cdsCust.FieldByName('FHelpCode').AsString := CliDM.cdstemp.fieldbyname('FhelpCode').AsString;
cdsCust.FieldByName('FTxRegisterNo').AsString := CliDM.cdstemp.fieldbyname('FTxRegisterNo').AsString;
cdsCust.FieldByName('FAddress').AsString := CliDM.cdstemp.fieldbyname('FAddress').AsString;
cdsCust.Post;
end;
CliDM.cdstemp.Next;
end;
end;
procedure Get_UserWareHouse(cdsware : TClientDataSet;var ErrMsg:string);
var
strSql : string;
begin
cdsware.Close;
cdsware.CreateDataSet;
strsql := 'Select A.FID,A.fnumber,A.fname_l2,A.FhelpCode,A.fhaslocation,A.CFCustomerID,A.fstorageorgid,A.ftransstate '
+' From t_Db_Warehouse A left join T_PM_USERPERMISSIONENTRY S on A.FID=S.FWHID '
+' left join t_Pm_Userroleorg R on R.FROLEID=S.Fparentid '
+' Where (S.Fparentid='''+userinfo.LoginUser_FID+''' or R.Fuserid='''+userinfo.LoginUser_FID+''' ) and A.FWhState=1 and A.fstorageorgid='+quotedstr(UserInfo.Branch_ID);
Clidm.Get_OpenSQL(CliDM.cdstemp,strsql,ErrMsg);//获取仓库owen
while not CliDM.cdstemp.Eof do
begin
if not FindRecord1(cdsware,'FID',CliDM.cdstemp.fieldbyname('FID').AsString,1) then
begin
cdsware.Append;
cdsware.FieldByName('FID').AsString := CliDM.cdstemp.fieldbyname('FID').AsString;
cdsware.FieldByName('fnumber').AsString := CliDM.cdstemp.fieldbyname('fnumber').AsString;
cdsware.FieldByName('fname_l2').AsString := CliDM.cdstemp.fieldbyname('fname_l2').AsString;
cdsware.FieldByName('fhaslocation').AsString := CliDM.cdstemp.fieldbyname('fhaslocation').AsString;
cdsware.FieldByName('CFCustomerID').AsString := CliDM.cdstemp.fieldbyname('CFCustomerID').AsString;
cdsware.FieldByName('FHelpCode').AsString := CliDM.cdstemp.fieldbyname('FhelpCode').AsString;
cdsware.FieldByName('fstorageorgid').AsString := CliDM.cdstemp.fieldbyname('fstorageorgid').AsString;
cdsware.Post;
end;
CliDM.cdstemp.Next;
end;
end;
procedure Get_UserBranch(var ErrMsg:string);
var
strSql : string;
begin
strSql := ' select A.FID,A.Fnumber,A.Fname_L2 from t_Org_Baseunit A left join t_Pm_Orgrange B on A.FID=B.FORGID where Ftype=10 and FUserID='+quotedstr(userinfo.LoginUser_FID);
Clidm.Get_OpenSQL(Clidm.cdsUserBranch,strSql,ErrMsg);
CliDM.cdsFindOrgUnit.Data := Clidm.cdsUserBranch.Data;
end;
procedure GET_PURTYPE(var ErrMsg:string);
var
strSql : string;
begin
strSql := 'select FID,fnumber,Fname_l2 from CT_BAS_PURTYPE ';
Clidm.Get_OpenSQL(Clidm.cdspurType,strSql,ErrMsg);
end;
procedure Get_PurRecType(var ErrMsg:string);
var
strSql : string;
begin
strSql := 'select FID,fnumber,Fname_l2 from CT_BAS_PurRecType ';
Clidm.Get_OpenSQL(Clidm.cdsPurRecType,strSql,ErrMsg);
end;
procedure Get_Range(var ErrMsg:string);
var
strSql : string;
begin
strSql := 'select FID,fnumber,Fname_l2 from CT_BD_RANGE ';
Clidm.Get_OpenSQL(Clidm.cdsRange,strSql,ErrMsg);
end;
procedure Get_Unit(var ErrMsg :string);
var
strSql : string;
begin
strSql := 'select FID,fnumber,Fname_l2 from t_Bd_Measureunit ';
Clidm.Get_OpenSQL(Clidm.cdsUnit,strSql,ErrMsg);
end;
procedure IniBIllCONSTInfo;
begin
BillConst.FCurrency := 'dfd38d11-00fd-1000-e000-1ebdc0a8100dDEB58FDC'; //币别;
BillConst.FPaymentType := '2fa35444-5a23-43fb-99ee-6d4fa5f260da6BCA0AB5';//付款方式
BillConst.BILLTYPE_SM :='7xVixzltQvOrJPBa1Q90QkY+1VI=';
BillConst.BILLTYPE_SC :='cmoltILsTtOUMZlctzkZn0Y+1VI=';
BillConst.BILLTYPE_RA :='l2swMQGOR0+kyQvofgl+rEY+1VI=';
BillConst.BILLTYPE_RP :='lE4MM+xNR3S+SIq3x/Ba6kY+1VI=';
BillConst.BILLTYPE_BA :='lQWER+xNR3S+SIq3x/Ba6kY+1VI=';
BillConst.BILLTYPE_SI :='528d806a-0106-1000-e000-0194c0a812e6463ED552';
BillConst.BILLTYPE_PT :='50957179-0105-1000-e000-0157c0a812fd463ED552';
BillConst.BILLTYPE_CS :='50957179-0105-1000-e000-015bc0a812fd463ED552';
BillConst.BILLTYPE_PI :='50957179-0105-1000-e000-015fc0a812fd463ED552';
BillConst.BILLTYPE_DT :='50957179-0105-1000-e000-016ec0a812fd463ED552';
BillConst.BILLTYPE_DI :='50957179-0105-1000-e000-0172c0a812fd463ED552';
BillConst.BILLTYPE_OD :='50957179-0105-1000-e000-0177c0a812fd463ED552';
BillConst.BILLTYPE_OI :='50957179-0105-1000-e000-017bc0a812fd463ED552';
BillConst.BILLTYPE_ML :='50957179-0105-1000-e001-1152c0a812fd463ED552';
BillConst.BILLTYPE_PA :='510b6503-0105-1000-e000-0107c0a812fd463ED552';
BillConst.BILLTYPE_PO :='510b6503-0105-1000-e000-010bc0a812fd463ED552';
BillConst.BILLTYPE_PR :='50957179-0105-1000-e006-6152c0a812fd463ED552';
BillConst.BILLTYPE_SO :='510b6503-0105-1000-e000-0113c0a812fd463ED552';
BillConst.BILLTYPE_AM :='510b6503-0105-1000-e000-011bc0a812fd463ED552';
BillConst.BILLTYPE_SA :='50957179-0105-1000-e008-8152c0a812fd463ED552';
BillConst.BILLTYPE_PK :='a6qtKyiQS9OyOaqvS81FP5n0Viw=';
BillConst.BILLTYPE_PD :='sQYZr+rAR+e4La5aiO9bGZKwWaE=';
BillConst.BILLTYPE_TR :='HhscFhgBTTa7yKxbD8KEYEGkZyw=';
BillConst.BILLTYPE_MC :='Gti/eIriT8uh7oNClYJ4RpmkaCw=';
BillConst.BILLTYPE_PM :='kOXNl5T+StKgnyJrm/fcKJKwWaE=';
BillConst.BILLTYPE_RE :='4nsgTCbcTrW+nCvddkU3EkGkkiw=';
BillConst.BILLTYPE_ST := '50957179-0105-1000-e003-3152c0a812fd463ED552';
end;
procedure IniSysParamInfo;
begin
// ParamInfo.DRP001 := CliDM.GetParaVal('4P0M53TG/EOLg7OGi7i4cKiB8+c=','') ;//是否启用EAS750
///ParamInfo.DRP002 := CliDM.GetParaVal('YhGp70nIbUGX/Gxhm5+OnKiB8+c=','') ;//是否启用EAS701
ParamInfo.DRP002 := 'true';
end;
procedure GET_Person(var ErrMsg:string);
var
strsql : string;
begin
strSql := 'select FID,fnumber,Fname_l2 from t_Bd_Person ';
Clidm.Get_OpenSQL(Clidm.cdsPerson,strSql,ErrMsg);
end;
procedure Get_AssValue(var ErrMsg : string);
var
strSql : string;
begin
strSql :=' select FID,Fnumber,Fname_l2,Ftype from t_Bd_Asstattrvalue where Fbasictypeid is not null ';
Clidm.Get_OpenSQL(Clidm.cdsAssValue,strSql,ErrMsg);
end;
procedure SetGridClumnTitle(fMaterialID: string;cxGridTV: TcxGridDBTableView);
var i,SizeCount,j,gMaxSizeCount :Integer;
sqlstr,FieldName : string;
begin
try
gMaxSizeCount := CliDM.GetMaxSizeCount;
cxGridTV.BeginUpdate;
for i:= 1 to 30 do
begin
FieldName := 'fAmount_'+inttostr(I);
if cxGridTV.GetColumnByFieldName('fAmount_'+inttostr(I))<> nil then
begin
cxGridTV.GetColumnByFieldName('fAmount_'+inttostr(I)).Caption := '';
cxGridTV.GetColumnByFieldName(FieldName).Options.Editing := False;
end;
end;
sqlstr :=
' SELECT distinct B.FSEQ,C.FNAME_L2'
+' from T_BD_Material A(nolock) '
+' LEFT OUTER JOIN ct_bas_sizegroupentry B(nolock) ON A.cfSizeGroupID collate Chinese_PRC_CS_AS_WS=B.fParentID collate Chinese_PRC_CS_AS_WS'
+' LEFT OUTER JOIN T_BD_AsstAttrValue C(nolock) on b.cfSizeID collate Chinese_PRC_CS_AS_WS=C.FID collate Chinese_PRC_CS_AS_WS'
+' WHERE A.FID collate Chinese_PRC_CS_AS_WS='+QuotedStr(fMaterialID)
+' ORDER BY B.FSEQ ';
with CliDM.qryTempSize do
begin
Close;
sql.Clear;
sql.Add(sqlstr);
Open;
SizeCount := CliDM.qryTempSize.RecordCount;
First;
//循环显示款号对应的尺码
J:=0;
try
for i:= 1 to gMaxSizeCount do
begin
FieldName := 'fAmount_'+inttostr(I);
cxGridTV.GetColumnByFieldName('fAmount_'+inttostr(I)).Caption := '';
cxGridTV.GetColumnByFieldName('fAmount_'+inttostr(I)).Visible := true;
cxGridTV.GetColumnByFieldName('fAmount_'+inttostr(I)).width := 35;
cxGridTV.GetColumnByFieldName(FieldName).Options.Editing := False;
if CliDM.qryTempSize.Locate('FSEQ',I,[]) then
if cxGridTV.GetColumnByFieldName(FieldName) <> nil then
begin
CliDM.qryTempSize.Locate('FSEQ',I,[]);
cxGridTV.GetColumnByFieldName(FieldName).Width := 35;
cxGridTV.GetColumnByFieldName(FieldName).Visible := True;
cxGridTV.GetColumnByFieldName(FieldName).Caption := FieldByName('FNAME_L2').AsString;
end;
Application.ProcessMessages;
Next;
end;
except
on E:Exception do
begin
Gio.AddShow('设置尺码标题出错:'+E.Message+' '+sqlstr);
end;
end;
end;
finally
cxGridTV.EndUpdate;
end;
end;
procedure GetAllWarehouse(cdsware : TClientDataSet;var ErrMsg:string);
var
strSql : string;
begin
strsql := 'Select A.FID,A.fnumber,A.fname_l2,A.FhelpCode,A.fhaslocation,A.CFCustomerID,A.fstorageorgid,A.ftransstate '
+' From t_Db_Warehouse A where A.FWhState=1 ';
Clidm.Get_OpenSQL(cdsware,strsql,ErrMsg);//获取仓库owen
end;
procedure CopyDataset(src,dec:TClientDataSet);
var i:Integer;
field:TField;
begin
if dec.FieldCount = 0 then
begin
dec.Fields.Clear;
for i:=0 to src.FieldCount-1 do
begin
with dec.FieldDefs.AddFieldDef do
begin
DataType := src.Fields[i].DataType;
size := src.Fields[i].Size;
Name := src.Fields[i].FieldName;
end;
end;
dec.CreateDataSet;
end;
dec.EmptyDataSet;
src.First;
while not src.Eof do
begin
dec.Append;
for i := 0 to src.FieldCount -1 do
begin
dec.FieldByName(src.Fields[i].FieldName).Value := src.Fields[i].Value;
end;
dec.Post;
src.Next;
end;
end;
procedure CopyDatasetStructure(src,dec:TClientDataSet);
var i:Integer;
field:TField;
begin
if dec.FieldCount = 0 then
begin
dec.Fields.Clear;
for i:=0 to src.FieldCount-1 do
begin
with dec.FieldDefs.AddFieldDef do
begin
DataType := src.Fields[i].DataType;
size := src.Fields[i].Size;
Name := src.Fields[i].FieldName;
end;
end;
dec.CreateDataSet;
end;
dec.EmptyDataSet;
end;
procedure CopyDatasetCurRecord(src,dec:TClientDataSet);
var
i: integer;
begin
if not src.Eof then
begin
dec.Append;
for i := 0 to src.FieldCount -1 do
begin
dec.FieldByName(src.Fields[i].FieldName).Value := src.Fields[i].Value;
end;
dec.Post;
end;
end;
procedure Get_UserBizOrg(sTable : string;var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True);
var
strSql : string;
begin
strSql := 'select A.FID,A.Fnumber,A.Fname_l2 from '+sTable+' A left join t_Pm_Orgrange B on A.FID=B.ForgID where A.Fisfreeze=0 and B.Ftype=10 '+
' and A.Fisbizunit=1 and B.FuserID= '+quotedstr(UserInfo.LoginUser_FID)+' order by A.Fnumber ' ;
Clidm.Get_OpenSQL(cds,strsql,ErrMsg,IsCloseConn);
end;
procedure GET_FromBizToFin(sFinOrg,sTable :string;var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True);
var
strSql : string;
begin
if Trim(sFinOrg)='' then Exit;
if Trim(sTable)='t_Org_Purchase' then ///根据财务组织找采购组织
strSql :=' SELECT a3.FID,a3.fnumber,a3.fname_l2,a1.Fisdefault from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN t_Org_Purchase a3 on a3.fid=a1.ffromunitid left join T_ORG_COMPANY a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a3.fid '+
' WHERE a3.Fiscu=0 and a3.Fisfreeze=0 and a2.ffromtype=3 and a2.ftotype=1 AND P.FTYPE=10 AND a4.fid='+quotedstr(sFinOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID)
else if Trim(sTable)='t_Org_Sale' then //根据财务组织找销售组织
strSql :=' SELECT a3.FID,a3.fnumber,a3.fname_l2 ,a1.Fisdefault from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN t_Org_Sale a3 on a3.fid=a1.ffromunitid left join T_ORG_COMPANY a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a3.fid '+
' WHERE a3.Fiscu=0 and a3.Fisfreeze=0 and a2.ffromtype=2 and a2.ftotype=1 AND P.FTYPE=10 AND a4.fid='+quotedstr(sFinOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID)
else if Trim(sTable)='t_Org_Storage' then ///根据财务找库存组织
strSql :=' SELECT a3.FID,a3.fnumber,a3.fname_l2,a1.Fisdefault from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN t_Org_Storage a3 on a3.fid=a1.ffromunitid left join T_ORG_COMPANY a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a3.fid '+
' WHERE a3.Fiscu=0 and a3.Fisfreeze=0 and a2.ffromtype=4 and a2.ftotype=1 AND P.FTYPE=10 AND a4.fid='+quotedstr(sFinOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID) ;
Clidm.Get_OpenSQL(cds,strsql,ErrMsg,IsCloseConn);
end;
procedure Get_OrderingDef(var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True) ;
var
strSql : string;
begin
strSql :='select F.FID,F.Fnumber,F.Fname_L2,F.Fsimplename from Ct_Ord_Orderdef F ';
Clidm.Get_OpenSQL(cds,strsql,ErrMsg,IsCloseConn);
end;
procedure Get_BizFindFinOrg(iFrom :Integer;sBizOrg,sTable :string;var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True);
var
StrSql :string;
begin
if Trim(sBizOrg)='' then Exit;
strSql :=' SELECT a4.FID,a4.fnumber,a4.fname_l2,a1.Fisdefault from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN '+sTable+' a3 on a3.fid=a1.ffromunitid left join T_ORG_COMPANY a4 on a4.fid=a1.fTounitid '+
' WHERE a2.ffromtype='+inttostr(iFrom)+' and a2.ftotype=1 AND a3.fid='+quotedstr(sBizOrg)+' ';
Clidm.Get_OpenSQL(cds,strsql,ErrMsg,IsCloseConn);
end;
procedure Get_FromSaleToStorage(sSaleOrg :string;var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True); ///销售组织找库存组织
var
StrSql :string;
begin
if Trim(sSaleOrg)='' then Exit;
StrSql := ' SELECT a4.FID,a4.fnumber,a4.fname_l2,a1.Fisdefault from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN T_ORg_sale a3 on a3.fid=a1.ffromunitid left join t_Org_Storage a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a4.fid '+
' WHERE a4.Fiscu=0 and a4.Fisfreeze=0 and P.Ftype=10 and a2.ffromtype=2 and a2.ftotype=4 AND a3.fid='+quotedstr(sSaleOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID);
Clidm.Get_OpenSQL(cds,strsql,ErrMsg,IsCloseConn);
end;
procedure Get_FromPurToStorage(sPurOrg :string; var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True); ///采购组织找库存组织
var
StrSql :string;
begin
if Trim(sPurOrg)='' then Exit;
StrSql:= ' SELECT a4.FID,a4.fnumber,a4.fname_l2,a1.Fisdefault from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN t_Org_Purchase a3 on a3.fid=a1.ffromunitid left join t_Org_Storage a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a4.fid '+
' WHERE a4.Fiscu=0 and a4.Fisfreeze=0 and P.Ftype=10 and a2.ffromtype=3 and a2.ftotype=4 AND a3.fid='+quotedstr(sPurOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID);
Clidm.Get_OpenSQL(cds,strsql,ErrMsg,IsCloseConn);
end;
procedure Get_FromStorageToSale(sStorageOrg :string; var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True); ///库存组织找 销售组织
var
StrSql :string;
begin
if Trim(sStorageOrg)='' then Exit;
StrSql :=' SELECT a3.FID,a3.fnumber,a3.fname_l2,a1.Fisdefault from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN T_ORg_sale a3 on a3.fid=a1.ffromunitid left join t_Org_Storage a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a3.fid '+
' WHERE a3.Fiscu=0 and a3.Fisfreeze=0 and P.Ftype=10 and a2.ffromtype=2 and a2.ftotype=4 AND a4.fid='+quotedstr(sStorageOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID);
Clidm.Get_OpenSQL(cds,strsql,ErrMsg,IsCloseConn);
end;
procedure Get_FromStorageToPur(sStorageOrg :string; var ErrMsg:string;cds:TClientDataSet;IsCloseConn :Boolean=True); ///库存组织找采购组织
var
StrSql :string;
begin
StrSql := ' SELECT a3.FID,a3.fnumber,a3.fname_l2,a1.Fisdefault from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN t_Org_Purchase a3 on a3.fid=a1.ffromunitid left join t_Org_Storage a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =34.fid '+
' WHERE a3.Fiscu=0 and a3.Fisfreeze=0 and P.Ftype=10 and a2.ffromtype=3 and a2.ftotype=4 AND a4.fid='+quotedstr(sStorageOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID) ;
Clidm.Get_OpenSQL(cds,strsql,ErrMsg,IsCloseConn);
end;
function GET_FromBizToFin_Show(sFinOrg,sTable ,_Caption,_oldVal :string;_isRadioSelect :Integer=1):TClientDataSet; //通过财务组织找业务组织
var
strSql : string;
begin
if Trim(sFinOrg)='' then Exit;
if Trim(sTable)='t_Org_Purchase' then ///根据财务组织找采购组织
strSql :=' SELECT a3.FID,a3.fnumber,a3.fname_l2,a3.FParentID ,''X'' as cfbranchflag from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN t_Org_Purchase a3 on a3.fid=a1.ffromunitid left join T_ORG_COMPANY a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a3.fid '+
' WHERE a3.Fiscu=0 and a3.Fisfreeze=0 and a2.ffromtype=3 and a2.ftotype=1 AND P.FTYPE=10 AND a4.fid='+quotedstr(sFinOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID)
else if Trim(sTable)='t_Org_Sale' then //根据财务组织找销售组织
strSql :=' SELECT a3.FID,a3.fnumber,a3.fname_l2,a3.FParentID,''X'' as cfbranchflag from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN t_Org_Sale a3 on a3.fid=a1.ffromunitid left join T_ORG_COMPANY a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a3.fid '+
' WHERE a3.Fiscu=0 and a3.Fisfreeze=0 and a2.ffromtype=2 and a2.ftotype=1 AND P.FTYPE=10 AND a4.fid='+quotedstr(sFinOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID)
else if Trim(sTable)='t_Org_Storage' then ///根据财务找库存组织
strSql :=' SELECT a3.FID,a3.fnumber,a3.fname_l2 ,a3.FParentID ,''X'' as cfbranchflag from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN t_Org_Storage a3 on a3.fid=a1.ffromunitid left join T_ORG_COMPANY a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a3.fid '+
' WHERE a3.Fiscu=0 and a3.Fisfreeze=0 and a2.ffromtype=4 and a2.ftotype=1 AND P.FTYPE=10 AND a4.fid='+quotedstr(sFinOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID) ;
Result := Select_BaseDataEx(_Caption,_oldVal,strSql,_isRadioSelect);
end;
function Get_FromSaleToStorage_show(sSaleOrg ,_Caption,_oldVal :string;_isRadioSelect :Integer=1):TClientDataSet; ///销售组织找库存组织
var
strsql : string;
begin
if Trim(sSaleOrg)='' then Exit;
StrSql := ' SELECT a4.FID,a4.fnumber,a4.fname_l2,a4.FParentID ,''X'' as cfbranchflag from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN T_ORg_sale a3 on a3.fid=a1.ffromunitid left join t_Org_Storage a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a4.fid '+
' WHERE a4.Fiscu=0 and a4.Fisfreeze=0 and P.Ftype=10 and a2.ffromtype=2 and a2.ftotype=4 AND a3.fid='+quotedstr(sSaleOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID);
Result := Select_BaseDataEx(_Caption,_oldVal,strSql,_isRadioSelect);
end;
function Get_FromPurToStorage_show(sPurOrg ,_Caption,_oldVal :string;_isRadioSelect :Integer=1):TClientDataSet; ///采购组织找库存组织
var
strsql : string;
begin
if Trim(sPurOrg)<>'' then Exit;
StrSql:= ' SELECT a4.FID,a4.fnumber,a4.fname_l2,a4.FParentID ,''X'' as cfbranchflag from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN t_Org_Purchase a3 on a3.fid=a1.ffromunitid left join t_Org_Storage a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a4.fid '+
' WHERE a4.Fiscu=0 and a4.Fisfreeze=0 and P.Ftype=10 and a2.ffromtype=3 and a2.ftotype=4 AND a3.fid='+quotedstr(sPurOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID);
Result := Select_BaseDataEx(_Caption,_oldVal,strSql,_isRadioSelect);
end;
function Get_FromStorageToSale_Show(sStorageOrg ,_Caption,_oldVal :string;_isRadioSelect :Integer=1):TClientDataSet; ///库存组织找 销售组织
var
strsql : string;
begin
if Trim(sStorageOrg)='' then Exit;
StrSql :=' SELECT a3.FID,a3.fnumber,a3.fname_l2,a3.FParentID ,''X'' as cfbranchflag from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN T_ORg_sale a3 on a3.fid=a1.ffromunitid left join t_Org_Storage a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =a3.fid '+
' WHERE a3.Fiscu=0 and a3.Fisfreeze=0 and P.Ftype=10 and a2.ffromtype=2 and a2.ftotype=4 AND a4.fid='+quotedstr(sStorageOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID);
Result := Select_BaseDataEx(_Caption,_oldVal,strSql,_isRadioSelect);
end;
function Get_FromStorageToPur_Show(sStorageOrg ,_Caption,_oldVal :string;_isRadioSelect :Integer=1):TClientDataSet; ///库存组织找采购组织
var
strsql : string;
begin
if Trim(sStorageOrg)='' then Exit;
StrSql := ' SELECT a3.FID,a3.fnumber,a3.fname_l2,a3.FParentID ,''X'' as cfbranchflag from T_ORG_UnitRelation a1 left join T_ORG_TypeRelation a2 on a1.ftyperelationid=a2.fid '+
' LEFT JOIN t_Org_Purchase a3 on a3.fid=a1.ffromunitid left join t_Org_Storage a4 on a4.fid=a1.fTounitid '+
' left join t_Pm_Orgrange P on P.FORGID =34.fid '+
' WHERE a3.Fiscu=0 and a3.Fisfreeze=0 and P.Ftype=10 and a2.ffromtype=3 and a2.ftotype=4 AND a4.fid='+quotedstr(sStorageOrg)+' and p.FuserID= '+quotedstr(UserInfo.LoginUser_FID) ;
Result := Select_BaseDataEx(_Caption,_oldVal,strSql,_isRadioSelect);
//Result := Select_TreeDataBySQL(_Caption,strSql,_oldVal,_isRadioSelect);
end;
function Get_BIZSALEORG_Show(_FormTitle,_oldVal:string;isRadioSelect:Integer=1):TClientDataSet; ///选择实体销售组织
var
strSql : string;
begin
strSql := 'select A.FID,A.Fnumber,A.Fname_l2,A.FParentID ,''X'' as cfbranchflag from t_Org_Sale A left join t_Pm_Orgrange B on A.FID=B.ForgID '+
' where A.Fisfreeze=0 and B.Ftype=10 and A.Fisbizunit=1 and B.FuserID= '+quotedstr(UserInfo.LoginUser_FID) ;
Result := Select_BaseDataEx(_FormTitle,_oldVal,strSql,isRadioSelect);
end;
function Get_BIZPURORG_Show(_FormTitle,_oldVal:string;isRadioSelect:Integer=1):TClientDataSet; ///选择实体采购组织
var
strSql : string;
begin
strSql := 'select A.FID,A.Fnumber,A.Fname_l2,A.FParentID ,''X'' as cfbranchflag from t_Org_Purchase A left join t_Pm_Orgrange B on A.FID=B.ForgID '+
' where A.Fisfreeze=0 and B.Ftype=10 and A.Fisbizunit=1 and B.FuserID= '+quotedstr(UserInfo.LoginUser_FID) ;
Result := Select_BaseDataEx(_FormTitle,_oldVal,strSql,isRadioSelect);
end;
function Get_BIZSTORAGEORG_Show(_FormTitle,_oldVal:string;isRadioSelect:Integer=1):TClientDataSet; ///选择实体库存组织
var
strSql : string;
begin
strSql := 'select A.FID,A.Fnumber,A.Fname_l2,A.FParentID ,''X'' as cfbranchflag from t_Org_Storage A left join t_Pm_Orgrange B on A.FID=B.ForgID '+
' where A.Fisfreeze=0 and B.Ftype=10 and A.Fisbizunit=1 and B.FuserID= '+quotedstr(UserInfo.LoginUser_FID) ;
Result := Select_BaseDataEx(_FormTitle,_oldVal,strSql,isRadioSelect);
end;
function Get_BIZFINORG_Show(_FormTitle,_oldVal:string;isRadioSelect:Integer=1):TClientDataSet; ///选择实体财务组织
var
strSql : string;
begin
strSql := 'select A.FID,A.Fnumber,A.Fname_l2,A.FParentID ,''X'' as cfbranchflag from t_Org_Company A left join t_Pm_Orgrange B on A.FID=B.ForgID '+
' where A.Fisfreeze=0 and B.Ftype=10 and A.Fisbizunit=1 and B.FuserID= '+quotedstr(UserInfo.LoginUser_FID) ;
Result := Select_BaseDataEx(_FormTitle,_oldVal,strSql,isRadioSelect);
end;
function Get_BIZCOST_Show(_FormTitle,_oldVal:string;isRadioSelect:Integer=1):TClientDataSet; //选择实体成本组织
var
strSql : string;
begin
strSql := 'select A.FID,A.Fnumber,A.Fname_l2,A.FParentID ,''X'' as cfbranchflag from t_Org_Costcenter A left join t_Pm_Orgrange B on A.FID=B.ForgID '+
' where A.Fisfreeze=0 and B.Ftype=10 and A.Fisbizunit=1 and B.FuserID= '+quotedstr(UserInfo.LoginUser_FID) ;
Result := Select_BaseDataEx(_FormTitle,_oldVal,strSql,isRadioSelect);
end;
procedure Get_UserWareByStorageOrg(StorageOrgID : string;cdsware : TClientDataSet;var ErrMsg:string); //按库存组织过滤用户所拥有的仓库
var
strSql : string;
begin
strSql := ' Select A.FID,A.fnumber,A.fname_l2,A.FhelpCode,A.fhaslocation,A.CFCustomerID,A.fstorageorgid,A.ftransstate '+
' From t_Db_Warehouse A left join T_PM_USERPERMISSIONENTRY S on A.FID=S.FWHID where S.Fparentid='''+userinfo.LoginUser_FID+''' '+
' and A.FWhState=1 and A.fstorageorgid='''+StorageOrgID+''''+
' union '+
' Select A.FID,A.fnumber,A.fname_l2,A.FhelpCode,A.fhaslocation,A.CFCustomerID,A.fstorageorgid,A.ftransstate '+
' From t_Db_Warehouse A left join T_PM_USERPERMISSIONENTRY S on A.FID=S.FWHID '+
' left join t_Pm_Userroleorg R on R.FROLEID=S.Fparentid '+
' Where R.Fuserid='''+userinfo.LoginUser_FID+''' and '+
' A.FWhState=1 and A.fstorageorgid='''+StorageOrgID+''' ';
Clidm.Get_OpenSQL(cdsware,strsql,ErrMsg);
end;
Function Get_UserWareByStorageOrg_Show(sStorageOrg,_Caption,_oldVal : string;_isRadioSelect :Integer=1):TClientDataSet; //按库存组织过滤用户所拥有的仓库
var
strSql : string;
begin
strSql := ' Select A.FID,A.fnumber,A.fname_l2,A.FhelpCode,A.fhaslocation,A.CFCustomerID,A.fstorageorgid,A.ftransstate '+
' From t_Db_Warehouse A left join T_PM_USERPERMISSIONENTRY S on A.FID=S.FWHID where S.Fparentid='''+userinfo.LoginUser_FID+''' '+
' and A.FWhState=1 and A.fstorageorgid='''+sStorageOrg+''''+
' union '+
' Select A.FID,A.fnumber,A.fname_l2,A.FhelpCode,A.fhaslocation,A.CFCustomerID,A.fstorageorgid,A.ftransstate '+
' From t_Db_Warehouse A left join T_PM_USERPERMISSIONENTRY S on A.FID=S.FWHID '+
' left join t_Pm_Userroleorg R on R.FROLEID=S.Fparentid '+
' Where R.Fuserid='''+userinfo.LoginUser_FID+''' and '+
' A.FWhState=1 and A.fstorageorgid='''+sStorageOrg+''' ';
Result := Select_BaseDataEx(_Caption,_oldVal,strSql,_isRadioSelect);
end;
{
作用:初始化辅助属性相关表数据
许志祥 2014-05-02
}
procedure InitAsstAttrTables;
var SqlStr,ErrMsg:string;
cdsTmp:TClientDataSet;
cdsAsstAttrBasicType,cdsAsstAttrCompondingType:TClientDataSet;
_cds: array[0..1] of TClientDataSet;
_SQL: array[0..1] of String;
begin
SqlStr := 'select 1 from T_BD_AsstAttrBasicType where fid=''VI1Cah6RQzKQ5F+WvTxwcQvG9C4=''' ;
try
cdsTmp := TClientDataSet.Create(nil);
cdsAsstAttrBasicType := TClientDataSet.Create(nil);
cdsAsstAttrCompondingType := TClientDataSet.Create(nil);
CliDM.Get_OpenSQL(cdsTmp,SqlStr,ErrMsg);
if cdsTmp.IsEmpty then
begin
_cds[0] := cdsAsstAttrBasicType;
_cds[1] := cdsAsstAttrCompondingType;
_SQL[0] := 'select * from T_BD_AsstAttrBasicType where 1=2';
_SQL[1] := 'select * from T_BD_AsstAttrCompondingType where 1=2';
if not (CliDM.Get_OpenClients_E('',_cds,_SQL,ErrMsg)) then
begin
Abort;
end;
cdsAsstAttrBasicType.Append;
cdsAsstAttrBasicType.FieldByName('FCREATORID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrBasicType.FieldByName('FCREATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrBasicType.FieldByName('FLASTUPDATEUSERID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrBasicType.FieldByName('FLASTUPDATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrBasicType.FieldByName('FCONTROLUNITID').Value := UserInfo.FCONTROLUNITID;
cdsAsstAttrBasicType.FieldByName('FNAME_L2').Value := '颜色';
cdsAsstAttrBasicType.FieldByName('FNUMBER').Value := 'Color';
cdsAsstAttrBasicType.FieldByName('FID').Value := 'VI1Cah6RQzKQ5F+WvTxwcQvG9C4=';
cdsAsstAttrBasicType.FieldByName('FMAPPINGFIELD').Value := 'f1';
cdsAsstAttrBasicType.Post;
cdsAsstAttrBasicType.Append;
cdsAsstAttrBasicType.FieldByName('FCREATORID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrBasicType.FieldByName('FCREATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrBasicType.FieldByName('FLASTUPDATEUSERID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrBasicType.FieldByName('FLASTUPDATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrBasicType.FieldByName('FCONTROLUNITID').Value := UserInfo.FCONTROLUNITID;
cdsAsstAttrBasicType.FieldByName('FNAME_L2').Value := '内长';
cdsAsstAttrBasicType.FieldByName('FNUMBER').Value := 'Cup';
cdsAsstAttrBasicType.FieldByName('FID').Value := 'HbZnaS6iQ3GGiSETJ7wotAvG9C4=';
cdsAsstAttrBasicType.FieldByName('FMAPPINGFIELD').Value := 'f3';
cdsAsstAttrBasicType.Post;
cdsAsstAttrBasicType.Append;
cdsAsstAttrBasicType.FieldByName('FCREATORID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrBasicType.FieldByName('FCREATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrBasicType.FieldByName('FLASTUPDATEUSERID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrBasicType.FieldByName('FLASTUPDATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrBasicType.FieldByName('FCONTROLUNITID').Value := UserInfo.FCONTROLUNITID;
cdsAsstAttrBasicType.FieldByName('FNAME_L2').Value := '尺码';
cdsAsstAttrBasicType.FieldByName('FNUMBER').Value := 'Size';
cdsAsstAttrBasicType.FieldByName('FID').Value := '+CNPS5i8SkK3Z6aghvgxCQvG9C4=';
cdsAsstAttrBasicType.FieldByName('FMAPPINGFIELD').Value := 'f2';
cdsAsstAttrBasicType.Post;
cdsAsstAttrBasicType.Append;
cdsAsstAttrBasicType.FieldByName('FCREATORID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrBasicType.FieldByName('FCREATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrBasicType.FieldByName('FLASTUPDATEUSERID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrBasicType.FieldByName('FLASTUPDATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrBasicType.FieldByName('FCONTROLUNITID').Value := UserInfo.FCONTROLUNITID;
cdsAsstAttrBasicType.FieldByName('FNAME_L2').Value := '配码';
cdsAsstAttrBasicType.FieldByName('FNUMBER').Value := 'Pack';
cdsAsstAttrBasicType.FieldByName('FID').Value := '3LxhGQ37QBu8EALR95DSEQvG9C4=';
cdsAsstAttrBasicType.FieldByName('FMAPPINGFIELD').Value := 'f4';
cdsAsstAttrBasicType.Post;
cdsAsstAttrCompondingType.Append;
cdsAsstAttrCompondingType.FieldByName('FCREATORID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrCompondingType.FieldByName('FCREATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrCompondingType.FieldByName('FLASTUPDATEUSERID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrCompondingType.FieldByName('FLASTUPDATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrCompondingType.FieldByName('FCONTROLUNITID').Value := UserInfo.FCONTROLUNITID;
cdsAsstAttrCompondingType.FieldByName('FNAME_L2').Value := '颜色+尺码+内长+配码';
cdsAsstAttrCompondingType.FieldByName('FNUMBER').Value := 'COLOR_SIZES_CUP_PACK';
cdsAsstAttrCompondingType.FieldByName('FID').Value := '5nh2ZUlST6WpxhbMwhkzBVNlqOA=';
cdsAsstAttrCompondingType.Post;
cdsAsstAttrCompondingType.Append;
cdsAsstAttrCompondingType.FieldByName('FCREATORID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrCompondingType.FieldByName('FCREATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrCompondingType.FieldByName('FLASTUPDATEUSERID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrCompondingType.FieldByName('FLASTUPDATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrCompondingType.FieldByName('FCONTROLUNITID').Value := UserInfo.FCONTROLUNITID;
cdsAsstAttrCompondingType.FieldByName('FNAME_L2').Value := '颜色+尺码+配码';
cdsAsstAttrCompondingType.FieldByName('FNUMBER').Value := 'COLOR_SIZES_PACK';
cdsAsstAttrCompondingType.FieldByName('FID').Value := '7LykpTEWQh2x5mlQ7+KMvFNlqOA=';
cdsAsstAttrCompondingType.Post;
cdsAsstAttrCompondingType.Append;
cdsAsstAttrCompondingType.FieldByName('FCREATORID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrCompondingType.FieldByName('FCREATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrCompondingType.FieldByName('FLASTUPDATEUSERID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrCompondingType.FieldByName('FLASTUPDATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrCompondingType.FieldByName('FCONTROLUNITID').Value := UserInfo.FCONTROLUNITID;
cdsAsstAttrCompondingType.FieldByName('FNAME_L2').Value := '颜色+尺码';
cdsAsstAttrCompondingType.FieldByName('FNUMBER').Value := 'COLOR_SIZES';
cdsAsstAttrCompondingType.FieldByName('FID').Value := 'ZXOYDhZgTEWWI0us2JalrFNlqOA=';
cdsAsstAttrCompondingType.Post;
cdsAsstAttrCompondingType.Append;
cdsAsstAttrCompondingType.FieldByName('FCREATORID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrCompondingType.FieldByName('FCREATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrCompondingType.FieldByName('FLASTUPDATEUSERID').Value := UserInfo.LoginUser_FID;
cdsAsstAttrCompondingType.FieldByName('FLASTUPDATETIME').Value := CliDM.Get_ServerTime;
cdsAsstAttrCompondingType.FieldByName('FCONTROLUNITID').Value := UserInfo.FCONTROLUNITID;
cdsAsstAttrCompondingType.FieldByName('FNAME_L2').Value := '颜色+尺码+内长';
cdsAsstAttrCompondingType.FieldByName('FNUMBER').Value := 'COLOR_SIZES_CUP';
cdsAsstAttrCompondingType.FieldByName('FID').Value := 'Rw1CzQ34R3KXI2KBR/aNKFNlqOA=';
cdsAsstAttrCompondingType.Post;
//保存数据
try
_cds[0] := cdsAsstAttrBasicType;
_cds[1] := cdsAsstAttrCompondingType;
if CliDM.Apply_Delta_E(_cds,['T_BD_AsstAttrBasicType','T_BD_AsstAttrCompondingType'],ErrMsg) then
begin
Gio.AddShow('辅助属性表初始化表提交成功!');
end
else
begin
Gio.AddShow('辅助属性表初始化表保存失败!'+ErrMsg);
end;
except
on E: Exception do
begin
Gio.AddShow('辅助属性表初始化表表提交失败!'+e.Message);
Abort;
end;
end;
end;
finally
cdsTmp.Free;
cdsAsstAttrBasicType.Free;
cdsAsstAttrCompondingType.Free;
end;
end;
procedure Get_BizType(sBillTypeID:string ;var ErrMsg:string;cdsBizType : TClientDataSet);///获取业务类型
var
StrSql : string;
begin
StrSql:='select A.fid,A.Fnumber,A.Fname_L2 from t_Scm_Biztype A left join T_SCM_BILLBIZTYPE B on A.FID=B.FBIZTYPEID where B.Fbilltypeid='+quotedstr(sBillTypeID)+' order by A.Fnumber ';
Clidm.Get_OpenSQL(cdsBizType,strsql,ErrMsg);
end;
procedure Get_UserCustBySaleOrg(SaleOrgID : string;cdsCust : TClientDataSet;var ErrMsg:string); //按销售组织过滤用户所拥有的客户
var
StrSql : string;
begin
strSql := ' Select A.FID,A.fnumber,A.fname_l2,A.FinternalCompanyID,A.FtaxRate,FhelpCode,FTxRegisterNo,FAddress '+
' From t_Bd_Customer A left join Ct_Pm_Usercustomerentry S on A.FID=S.CFCID '+
' left join t_Bd_Customersaleinfo F on F.Fsaleorgid='''+SaleOrgID+''' and F.fcustomerid= A.FID where S.Fparentid='''+userinfo.LoginUser_FID+''' '+
' and A.fusedstatus=1 and F.Fsaleorgid='''+SaleOrgID+''''+
' union '+
' Select A.FID,A.fnumber,A.fname_l2,A.FinternalCompanyID,A.FtaxRate,FhelpCode,FTxRegisterNo,FAddress '+
' From t_Bd_Customer A left join Ct_Pm_Usercustomerentry S on A.FID=S.CFCID '+
' left join t_Bd_Customersaleinfo F on F.Fsaleorgid='''+SaleOrgID+''' and F.fcustomerid= A.FID '+
' left join t_Pm_Userroleorg R on R.FROLEID=S.Fparentid '+
' Where R.Fuserid='''+userinfo.LoginUser_FID+''' and '+
' A.fusedstatus=1 and F.Fsaleorgid='''+SaleOrgID+''' ';
Clidm.Get_OpenSQL(cdsCust,strsql,ErrMsg);//获取客户owen
end;
Function Get_UserCustBySaleOrg_Show(sSaleOrg,_Caption,_oldVal : string;_isRadioSelect :Integer=1):TADODataSet; //按销售组织过滤用户所拥有的客户
var
StrSql : string;
begin
strSql := ' Select A.FID,A.fnumber,A.fname_l2,A.FinternalCompanyID,A.FtaxRate,FhelpCode,A.FparentID,''X'' as cfbranchflag '+
' From t_Bd_Customer A left join Ct_Pm_Usercustomerentry S on A.FID=S.CFCID '+
' left join t_Bd_Customersaleinfo F on F.Fsaleorgid='''+sSaleOrg+''' and F.fcustomerid= A.FID where S.Fparentid='''+userinfo.LoginUser_FID+''' '+
' and A.fusedstatus=1 and F.Fsaleorgid='''+sSaleOrg+''''+
' union '+
' Select A.FID,A.fnumber,A.fname_l2,A.FinternalCompanyID,A.FtaxRate,FhelpCode,A.FparentID,''X'' as cfbranchflag '+
' From t_Bd_Customer A left join Ct_Pm_Usercustomerentry S on A.FID=S.CFCID '+
' left join t_Bd_Customersaleinfo F on F.Fsaleorgid='''+sSaleOrg+''' and F.fcustomerid= A.FID '+
' left join t_Pm_Userroleorg R on R.FROLEID=S.Fparentid '+
' Where R.Fuserid='''+userinfo.LoginUser_FID+''' and '+
' A.fusedstatus=1 and F.Fsaleorgid='''+sSaleOrg+''' ';
Result := Select_TreeDataBySQL(_Caption,strSql,_oldVal,_isRadioSelect);
end;
end.
|
unit uContaPagarDAOClient;
interface
uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, Generics.Collections, DBXJSONReflect, ContaPagar;
type
TContaPagarDAOClient = class(TDSAdminClient)
private
FListCommand: TDBXCommand;
FInsertCommand: TDBXCommand;
FUpdateCommand: TDBXCommand;
FDeleteCommand: TDBXCommand;
FBaixarContaCommand: TDBXCommand;
FRelatorioCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function List: TDBXReader;
function Insert(ContaPagar: TContaPagar): Boolean;
function Update(ContaPagar: TContaPagar): Boolean;
function Delete(ContaPagar: TContaPagar): Boolean;
function BaixarConta(ContaPagar: TContaPagar): Boolean;
function Relatorio(DataInicial, DataFinal: TDateTime; FornecedorCodigo: string; Situacao: Integer): TDBXReader;
end;
implementation
function TContaPagarDAOClient.List: TDBXReader;
begin
if FListCommand = nil then
begin
FListCommand := FDBXConnection.CreateCommand;
FListCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FListCommand.Text := 'TContaPagarDAO.List';
FListCommand.Prepare;
end;
FListCommand.ExecuteUpdate;
Result := FListCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner);
end;
function TContaPagarDAOClient.Relatorio(DataInicial, DataFinal: TDateTime; FornecedorCodigo: string; Situacao: Integer): TDBXReader;
begin
if FRelatorioCommand = nil then
begin
FRelatorioCommand := FDBXConnection.CreateCommand;
FRelatorioCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FRelatorioCommand.Text := 'TContaPagarDAO.Relatorio';
FRelatorioCommand.Prepare;
end;
FRelatorioCommand.Parameters[0].Value.AsDateTime := DataInicial;
FRelatorioCommand.Parameters[1].Value.AsDateTime := DataFinal;
FRelatorioCommand.Parameters[2].Value.AsString := FornecedorCodigo;
FRelatorioCommand.Parameters[3].Value.AsInt32 := Situacao;
FRelatorioCommand.ExecuteUpdate;
Result := FRelatorioCommand.Parameters[4].Value.GetDBXReader(FInstanceOwner);
end;
function TContaPagarDAOClient.Insert(ContaPagar: TContaPagar): Boolean;
begin
if FInsertCommand = nil then
begin
FInsertCommand := FDBXConnection.CreateCommand;
FInsertCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FInsertCommand.Text := 'TContaPagarDAO.Insert';
FInsertCommand.Prepare;
end;
if not Assigned(ContaPagar) then
FInsertCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FInsertCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FInsertCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ContaPagar), True);
if FInstanceOwner then
ContaPagar.Free
finally
FreeAndNil(FMarshal)
end
end;
FInsertCommand.ExecuteUpdate;
Result := FInsertCommand.Parameters[1].Value.GetBoolean;
end;
function TContaPagarDAOClient.Update(ContaPagar: TContaPagar): Boolean;
begin
if FUpdateCommand = nil then
begin
FUpdateCommand := FDBXConnection.CreateCommand;
FUpdateCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FUpdateCommand.Text := 'TContaPagarDAO.Update';
FUpdateCommand.Prepare;
end;
if not Assigned(ContaPagar) then
FUpdateCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FUpdateCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FUpdateCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ContaPagar), True);
if FInstanceOwner then
ContaPagar.Free
finally
FreeAndNil(FMarshal)
end
end;
FUpdateCommand.ExecuteUpdate;
Result := FUpdateCommand.Parameters[1].Value.GetBoolean;
end;
function TContaPagarDAOClient.Delete(ContaPagar: TContaPagar): Boolean;
begin
if FDeleteCommand = nil then
begin
FDeleteCommand := FDBXConnection.CreateCommand;
FDeleteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FDeleteCommand.Text := 'TContaPagarDAO.Delete';
FDeleteCommand.Prepare;
end;
if not Assigned(ContaPagar) then
FDeleteCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FDeleteCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FDeleteCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ContaPagar), True);
if FInstanceOwner then
ContaPagar.Free
finally
FreeAndNil(FMarshal)
end
end;
FDeleteCommand.ExecuteUpdate;
Result := FDeleteCommand.Parameters[1].Value.GetBoolean;
end;
constructor TContaPagarDAOClient.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
function TContaPagarDAOClient.BaixarConta(ContaPagar: TContaPagar): Boolean;
begin
if FBaixarContaCommand = nil then
begin
FBaixarContaCommand := FDBXConnection.CreateCommand;
FBaixarContaCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FBaixarContaCommand.Text := 'TContaPagarDAO.BaixarConta';
FBaixarContaCommand.Prepare;
end;
if not Assigned(ContaPagar) then
FBaixarContaCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FBaixarContaCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FBaixarContaCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ContaPagar), True);
if FInstanceOwner then
ContaPagar.Free
finally
FreeAndNil(FMarshal)
end
end;
FBaixarContaCommand.ExecuteUpdate;
Result := FBaixarContaCommand.Parameters[1].Value.GetBoolean;
end;
constructor TContaPagarDAOClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TContaPagarDAOClient.Destroy;
begin
FreeAndNil(FListCommand);
FreeAndNil(FInsertCommand);
FreeAndNil(FUpdateCommand);
FreeAndNil(FDeleteCommand);
FreeAndNil(FBaixarContaCommand);
FreeAndNil(FRelatorioCommand);
inherited;
end;
end.
|
// XD Pascal - a 32-bit compiler for Windows
// Copyright (c) 2009-2010, 2019-2020, Vasiliy Tereshkov
{$I-}
{$H-}
unit Parser;
interface
uses SysUtils, Common, Scanner, CodeGen, Linker;
function CompileProgramOrUnit(const Name: TString): Integer;
implementation
type
TParserState = record
IsUnit, IsInterfaceSection: Boolean;
UnitStatus: TUnitStatus;
end;
var
ParserState: TParserState;
procedure CompileConstExpression(var ConstVal: TConst; var ConstValType: Integer); forward;
function CompileDesignator(var ValType: Integer; AllowConst: Boolean = TRUE): Boolean; forward;
procedure CompileExpression(var ValType: Integer); forward;
procedure CompileStatement(LoopNesting: Integer); forward;
procedure CompileType(var DataType: Integer); forward;
procedure DeclareIdent(const IdentName: TString; IdentKind: TIdentKind; TotalParamDataSize: Integer; IdentIsInCStack: Boolean; IdentDataType: Integer; IdentPassMethod: TPassMethod;
IdentOrdConstValue: LongInt; IdentRealConstValue: Double; const IdentStrConstValue: TString; const IdentSetConstValue: TByteSet;
IdentPredefProc: TPredefProc; const IdentReceiverName: TString; IdentReceiverType: Integer);
var
i, AdditionalStackItems, IdentTypeSize: Integer;
IdentScope: TScope;
begin
if BlockStack[BlockStackTop].Index = 1 then IdentScope := GLOBAL else IdentScope := LOCAL;
i := GetIdentUnsafe(IdentName, FALSE, IdentReceiverType);
if (i > 0) and (Ident[i].UnitIndex = ParserState.UnitStatus.Index) and (Ident[i].Block = BlockStack[BlockStackTop].Index) then
Error('Duplicate identifier ' + IdentName);
Inc(NumIdent);
if NumIdent > MAXIDENTS then
Error('Maximum number of identifiers exceeded');
with Ident[NumIdent] do
begin
Kind := IdentKind;
Name := IdentName;
Address := 0;
Scope := IdentScope;
RelocType := UNINITDATARELOC;
DataType := IdentDataType;
UnitIndex := ParserState.UnitStatus.Index;
Block := BlockStack[BlockStackTop].Index;
NestingLevel := BlockStackTop;
ReceiverName := IdentReceiverName;
ReceiverType := IdentReceiverType;
Signature.NumParams := 0;
Signature.CallConv := DEFAULTCONV;
PassMethod := IdentPassMethod;
IsUsed := FALSE;
IsUnresolvedForward := FALSE;
IsExported := ParserState.IsInterfaceSection and (IdentScope = GLOBAL);
IsTypedConst := FALSE;
IsInCStack := IdentIsInCStack;
ForLoopNesting := 0;
end;
case IdentKind of
PROC, FUNC:
begin
Ident[NumIdent].Signature.ResultType := IdentDataType;
if IdentPredefProc = EMPTYPROC then
begin
Ident[NumIdent].Address := GetCodeSize; // Routine entry point address
Ident[NumIdent].PredefProc := EMPTYPROC;
end
else
begin
Ident[NumIdent].Address := 0;
Ident[NumIdent].PredefProc := IdentPredefProc; // Predefined routine index
end;
end;
VARIABLE:
case IdentScope of
GLOBAL:
begin
IdentTypeSize := TypeSize(IdentDataType);
if IdentTypeSize > MAXUNINITIALIZEDDATASIZE - UninitializedGlobalDataSize then
Error('Not enough memory for global variable');
Ident[NumIdent].Address := UninitializedGlobalDataSize; // Variable address (relocatable)
UninitializedGlobalDataSize := UninitializedGlobalDataSize + IdentTypeSize;
end;// else
LOCAL:
if TotalParamDataSize > 0 then // Declare parameter (always 4 bytes, except structures in the C stack and doubles)
begin
if Ident[NumIdent].NestingLevel = 2 then // Inside a non-nested routine
AdditionalStackItems := 1 // Return address
else // Inside a nested routine
AdditionalStackItems := 2; // Return address, static link (hidden parameter)
with BlockStack[BlockStackTop] do
begin
if (IdentIsInCStack or (Types[IdentDataType].Kind = REALTYPE)) and (IdentPassMethod = VALPASSING) then
IdentTypeSize := Align(TypeSize(IdentDataType), SizeOf(LongInt))
else
IdentTypeSize := SizeOf(LongInt);
if IdentTypeSize > MAXSTACKSIZE - ParamDataSize then
Error('Not enough memory for parameter');
Ident[NumIdent].Address := AdditionalStackItems * SizeOf(LongInt) + TotalParamDataSize - ParamDataSize - (IdentTypeSize - SizeOf(LongInt)); // Parameter offset from EBP (>0)
ParamDataSize := ParamDataSize + IdentTypeSize;
end
end
else
with BlockStack[BlockStackTop] do // Declare local variable
begin
IdentTypeSize := TypeSize(IdentDataType);
if IdentTypeSize > MAXSTACKSIZE - LocalDataSize then
Error('Not enough memory for local variable');
Ident[NumIdent].Address := -LocalDataSize - IdentTypeSize; // Local variable offset from EBP (<0)
LocalDataSize := LocalDataSize + IdentTypeSize;
end;
end; // case
CONSTANT:
if IdentPassMethod = EMPTYPASSING then // Untyped constant
case Types[IdentDataType].Kind of
SETTYPE: begin
Ident[NumIdent].ConstVal.SetValue := IdentSetConstValue;
DefineStaticSet(Ident[NumIdent].ConstVal.SetValue, Ident[NumIdent].Address);
end;
ARRAYTYPE: begin
Ident[NumIdent].ConstVal.StrValue := IdentStrConstValue;
DefineStaticString(Ident[NumIdent].ConstVal.StrValue, Ident[NumIdent].Address);
end;
REALTYPE: Ident[NumIdent].ConstVal.RealValue := IdentRealConstValue; // Real constant value
else Ident[NumIdent].ConstVal.OrdValue := IdentOrdConstValue; // Ordinal constant value
end
else // Typed constant (actually an initialized global variable)
begin
with Ident[NumIdent] do
begin
Kind := VARIABLE;
Scope := GLOBAL;
RelocType := INITDATARELOC;
PassMethod := EMPTYPASSING;
IsTypedConst := TRUE;
end;
IdentTypeSize := TypeSize(IdentDataType);
if IdentTypeSize > MAXINITIALIZEDDATASIZE - InitializedGlobalDataSize then
Error('Not enough memory for initialized global variable');
Ident[NumIdent].Address := InitializedGlobalDataSize; // Typed constant address (relocatable)
InitializedGlobalDataSize := InitializedGlobalDataSize + IdentTypeSize;
end;
GOTOLABEL:
Ident[NumIdent].IsUnresolvedForward := TRUE;
end;// case
end; // DeclareIdent
procedure DeclareType(TypeKind: TTypeKind);
begin
Inc(NumTypes);
if NumTypes > MAXTYPES then
Error('Maximum number of types exceeded');
with Types[NumTypes] do
begin
Kind := TypeKind;
Block := BlockStack[BlockStackTop].Index;
end;
end; // DeclareType
procedure DeclarePredefinedIdents;
begin
// Constants
DeclareIdent('TRUE', CONSTANT, 0, FALSE, BOOLEANTYPEINDEX, EMPTYPASSING, 1, 0.0, '', [], EMPTYPROC, '', 0);
DeclareIdent('FALSE', CONSTANT, 0, FALSE, BOOLEANTYPEINDEX, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
// Types
DeclareIdent('INTEGER', USERTYPE, 0, FALSE, INTEGERTYPEINDEX, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
DeclareIdent('SMALLINT', USERTYPE, 0, FALSE, SMALLINTTYPEINDEX, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
DeclareIdent('SHORTINT', USERTYPE, 0, FALSE, SHORTINTTYPEINDEX, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
DeclareIdent('WORD', USERTYPE, 0, FALSE, WORDTYPEINDEX, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
DeclareIdent('BYTE', USERTYPE, 0, FALSE, BYTETYPEINDEX, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
DeclareIdent('CHAR', USERTYPE, 0, FALSE, CHARTYPEINDEX, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
DeclareIdent('BOOLEAN', USERTYPE, 0, FALSE, BOOLEANTYPEINDEX, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
DeclareIdent('REAL', USERTYPE, 0, FALSE, REALTYPEINDEX, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
DeclareIdent('SINGLE', USERTYPE, 0, FALSE, SINGLETYPEINDEX, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
DeclareIdent('POINTER', USERTYPE, 0, FALSE, POINTERTYPEINDEX, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
// Procedures
DeclareIdent('INC', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], INCPROC, '', 0);
DeclareIdent('DEC', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], DECPROC, '', 0);
DeclareIdent('READ', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], READPROC, '', 0);
DeclareIdent('WRITE', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], WRITEPROC, '', 0);
DeclareIdent('READLN', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], READLNPROC, '', 0);
DeclareIdent('WRITELN', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], WRITELNPROC, '', 0);
DeclareIdent('NEW', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], NEWPROC, '', 0);
DeclareIdent('DISPOSE', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], DISPOSEPROC, '', 0);
DeclareIdent('BREAK', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], BREAKPROC, '', 0);
DeclareIdent('CONTINUE', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], CONTINUEPROC, '', 0);
DeclareIdent('EXIT', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], EXITPROC, '', 0);
DeclareIdent('HALT', PROC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], HALTPROC, '', 0);
// Functions
DeclareIdent('SIZEOF', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], SIZEOFFUNC, '', 0);
DeclareIdent('ORD', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], ORDFUNC, '', 0);
DeclareIdent('CHR', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], CHRFUNC, '', 0);
DeclareIdent('LOW', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], LOWFUNC, '', 0);
DeclareIdent('HIGH', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], HIGHFUNC, '', 0);
DeclareIdent('PRED', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], PREDFUNC, '', 0);
DeclareIdent('SUCC', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], SUCCFUNC, '', 0);
DeclareIdent('ROUND', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], ROUNDFUNC, '', 0);
DeclareIdent('TRUNC', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], TRUNCFUNC, '', 0);
DeclareIdent('ABS', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], ABSFUNC, '', 0);
DeclareIdent('SQR', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], SQRFUNC, '', 0);
DeclareIdent('SIN', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], SINFUNC, '', 0);
DeclareIdent('COS', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], COSFUNC, '', 0);
DeclareIdent('ARCTAN', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], ARCTANFUNC, '', 0);
DeclareIdent('EXP', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], EXPFUNC, '', 0);
DeclareIdent('LN', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], LNFUNC, '', 0);
DeclareIdent('SQRT', FUNC, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], SQRTFUNC, '', 0);
end;// DeclarePredefinedIdents
procedure DeclarePredefinedTypes;
begin
NumTypes := STRINGTYPEINDEX;
Types[ANYTYPEINDEX].Kind := ANYTYPE;
Types[INTEGERTYPEINDEX].Kind := INTEGERTYPE;
Types[SMALLINTTYPEINDEX].Kind := SMALLINTTYPE;
Types[SHORTINTTYPEINDEX].Kind := SHORTINTTYPE;
Types[WORDTYPEINDEX].Kind := WORDTYPE;
Types[BYTETYPEINDEX].Kind := BYTETYPE;
Types[CHARTYPEINDEX].Kind := CHARTYPE;
Types[BOOLEANTYPEINDEX].Kind := BOOLEANTYPE;
Types[REALTYPEINDEX].Kind := REALTYPE;
Types[SINGLETYPEINDEX].Kind := SINGLETYPE;
Types[POINTERTYPEINDEX].Kind := POINTERTYPE;
Types[FILETYPEINDEX].Kind := FILETYPE;
Types[STRINGTYPEINDEX].Kind := ARRAYTYPE;
Types[POINTERTYPEINDEX].BaseType := ANYTYPEINDEX;
Types[FILETYPEINDEX].BaseType := ANYTYPEINDEX;
// Add new anonymous type: 1 .. MAXSTRLENGTH + 1
DeclareType(SUBRANGETYPE);
Types[NumTypes].BaseType := INTEGERTYPEINDEX;
Types[NumTypes].Low := 1;
Types[NumTypes].High := MAXSTRLENGTH + 1;
Types[STRINGTYPEINDEX].BaseType := CHARTYPEINDEX;
Types[STRINGTYPEINDEX].IndexType := NumTypes;
Types[STRINGTYPEINDEX].IsOpenArray := FALSE;
end;// DeclarePredefinedTypes
function AllocateTempStorage(Size: Integer): Integer;
begin
with BlockStack[BlockStackTop] do
begin
TempDataSize := TempDataSize + Size;
Result := -LocalDataSize - TempDataSize;
end;
end; // AllocateTempStorage
procedure PushTempStoragePtr(Addr: Integer);
begin
PushVarPtr(Addr, LOCAL, 0, UNINITDATARELOC);
end; // PushTempStoragePtr
procedure PushVarIdentPtr(IdentIndex: Integer);
begin
PushVarPtr(Ident[IdentIndex].Address, Ident[IdentIndex].Scope, BlockStackTop - Ident[IdentIndex].NestingLevel, Ident[IdentIndex].RelocType);
Ident[IdentIndex].IsUsed := TRUE;
end; // PushVarIdentPtr
procedure ConvertConstIntegerToReal(DestType: Integer; var SrcType: Integer; var ConstVal: TConst);
begin
// Try to convert an integer (right-hand side) into a real
if (Types[DestType].Kind in [REALTYPE, SINGLETYPE]) and
((Types[SrcType].Kind in IntegerTypes) or
((Types[SrcType].Kind = SUBRANGETYPE) and (Types[Types[SrcType].BaseType].Kind in IntegerTypes)))
then
begin
ConstVal.RealValue := ConstVal.OrdValue;
SrcType := REALTYPEINDEX;
end;
end; // ConvertConstIntegerToReal
procedure ConvertIntegerToReal(DestType: Integer; var SrcType: Integer; Depth: Integer);
begin
// Try to convert an integer (right-hand side) into a real
if (Types[DestType].Kind in [REALTYPE, SINGLETYPE]) and
((Types[SrcType].Kind in IntegerTypes) or
((Types[SrcType].Kind = SUBRANGETYPE) and (Types[Types[SrcType].BaseType].Kind in IntegerTypes)))
then
begin
GenerateDoubleFromInteger(Depth);
SrcType := REALTYPEINDEX;
end;
end; // ConvertIntegerToReal
procedure ConvertConstRealToReal(DestType: Integer; var SrcType: Integer; var ConstVal: TConst);
begin
// Try to convert a single (right-hand side) into a double or vice versa
if (Types[DestType].Kind = REALTYPE) and (Types[SrcType].Kind = SINGLETYPE) then
begin
ConstVal.RealValue := ConstVal.SingleValue;
SrcType := REALTYPEINDEX;
end
else if (Types[DestType].Kind = SINGLETYPE) and (Types[SrcType].Kind = REALTYPE) then
begin
ConstVal.SingleValue := ConstVal.RealValue;
SrcType := SINGLETYPEINDEX;
end
end; // ConvertConstRealToReal
procedure ConvertRealToReal(DestType: Integer; var SrcType: Integer);
begin
// Try to convert a single (right-hand side) into a double or vice versa
if (Types[DestType].Kind = REALTYPE) and (Types[SrcType].Kind = SINGLETYPE) then
begin
GenerateDoubleFromSingle;
SrcType := REALTYPEINDEX;
end
else if (Types[DestType].Kind = SINGLETYPE) and (Types[SrcType].Kind = REALTYPE) then
begin
GenerateSingleFromDouble;
SrcType := SINGLETYPEINDEX;
end
end; // ConvertRealToReal
procedure ConvertConstCharToString(DestType: Integer; var SrcType: Integer; var ConstVal: TConst);
var
ch: TCharacter;
begin
if IsString(DestType) and
((Types[SrcType].Kind = CHARTYPE) or
((Types[SrcType].Kind = SUBRANGETYPE) and (Types[Types[SrcType].BaseType].Kind = CHARTYPE)))
then
begin
ch := Char(ConstVal.OrdValue);
ConstVal.StrValue := ch;
SrcType := STRINGTYPEINDEX;
end;
end; // ConvertConstCharToString
procedure ConvertCharToString(DestType: Integer; var SrcType: Integer; Depth: Integer);
var
TempStorageAddr: LongInt;
begin
// Try to convert a character (right-hand side) into a 2-character temporary string
if IsString(DestType) and
((Types[SrcType].Kind = CHARTYPE) or
((Types[SrcType].Kind = SUBRANGETYPE) and (Types[Types[SrcType].BaseType].Kind = CHARTYPE)))
then
begin
TempStorageAddr := AllocateTempStorage(2 * SizeOf(TCharacter));
PushTempStoragePtr(TempStorageAddr);
GetCharAsTempString(Depth);
SrcType := STRINGTYPEINDEX;
end;
end; // ConvertCharToString
procedure ConvertStringToPChar(DestType: Integer; var SrcType: Integer);
begin
// Try to convert a string (right-hand side) into a pointer to character
if (Types[DestType].Kind = POINTERTYPE) and (Types[Types[DestType].BaseType].Kind = CHARTYPE) and IsString(SrcType) then
SrcType := DestType;
end; // ConvertStringToPChar
procedure ConvertToInterface(DestType: Integer; var SrcType: Integer);
var
SrcField, DestField: PField;
TempStorageAddr: LongInt;
FieldIndex, MethodIndex: Integer;
begin
// Try to convert a concrete or interface type to an interface type
if (Types[DestType].Kind = INTERFACETYPE) and (DestType <> SrcType) then
begin
// Allocate new interface variable
TempStorageAddr := AllocateTempStorage(TypeSize(DestType));
// Set interface's Self pointer (offset 0) to the concrete/interface data
if Types[SrcType].Kind = INTERFACETYPE then
begin
DuplicateStackTop;
DerefPtr(POINTERTYPEINDEX);
GenerateInterfaceFieldAssignment(TempStorageAddr, TRUE, 0, UNINITDATARELOC);
DiscardStackTop(1);
end
else
GenerateInterfaceFieldAssignment(TempStorageAddr, TRUE, 0, UNINITDATARELOC);
// Set interface's procedure pointers to the concrete/interface methods
for FieldIndex := 2 to Types[DestType].NumFields do
begin
DestField := Types[DestType].Field[FieldIndex];
if Types[SrcType].Kind = INTERFACETYPE then // Interface to interface
begin
SrcField := Types[SrcType].Field[GetField(SrcType, DestField^.Name)];
CheckSignatures(Types[SrcField^.DataType].Signature, Types[DestField^.DataType].Signature, SrcField^.Name, FALSE);
DuplicateStackTop;
GetFieldPtr(SrcField^.Offset);
DerefPtr(POINTERTYPEINDEX);
GenerateInterfaceFieldAssignment(TempStorageAddr + (FieldIndex - 1) * SizeOf(Pointer), TRUE, 0, CODERELOC);
DiscardStackTop(1);
end
else // Concrete to interface
begin
MethodIndex := GetMethod(SrcType, DestField^.Name);
CheckSignatures(Ident[MethodIndex].Signature, Types[DestField^.DataType].Signature, Ident[MethodIndex].Name, FALSE);
GenerateInterfaceFieldAssignment(TempStorageAddr + (FieldIndex - 1) * SizeOf(Pointer), FALSE, Ident[MethodIndex].Address, CODERELOC);
end;
end; // for
DiscardStackTop(1); // Remove source pointer
PushTempStoragePtr(TempStorageAddr); // Push destination pointer
SrcType := DestType;
end;
end; // ConvertToInterface
procedure CompileConstPredefinedFunc(func: TPredefProc; var ConstVal: TConst; var ConstValType: Integer);
var
IdentIndex: Integer;
begin
NextTok;
EatTok(OPARTOK);
case func of
SIZEOFFUNC:
begin
AssertIdent;
IdentIndex := GetIdentUnsafe(Tok.Name);
if (IdentIndex <> 0) and (Ident[IdentIndex].Kind = USERTYPE) then // Type name
begin
NextTok;
ConstVal.OrdValue := TypeSize(Ident[IdentIndex].DataType);
end
else // Variable name
Error('Type name expected');
ConstValType := INTEGERTYPEINDEX;
end;
ROUNDFUNC, TRUNCFUNC:
begin
CompileConstExpression(ConstVal, ConstValType);
if not (Types[ConstValType].Kind in IntegerTypes) then
begin
GetCompatibleType(ConstValType, REALTYPEINDEX);
if func = TRUNCFUNC then
ConstVal.OrdValue := Trunc(ConstVal.RealValue)
else
ConstVal.OrdValue := Round(ConstVal.RealValue);
end;
ConstValType := INTEGERTYPEINDEX;
end;
ORDFUNC:
begin
CompileConstExpression(ConstVal, ConstValType);
if not (Types[ConstValType].Kind in OrdinalTypes) then
Error('Ordinal type expected');
ConstValType := INTEGERTYPEINDEX;
end;
CHRFUNC:
begin
CompileConstExpression(ConstVal, ConstValType);
GetCompatibleType(ConstValType, INTEGERTYPEINDEX);
ConstValType := CHARTYPEINDEX;
end;
LOWFUNC, HIGHFUNC:
begin
AssertIdent;
IdentIndex := GetIdentUnsafe(Tok.Name);
if (IdentIndex <> 0) and (Ident[IdentIndex].Kind = USERTYPE) then // Type name
begin
NextTok;
ConstValType := Ident[IdentIndex].DataType;
end
else // Variable name
Error('Type name expected');
if (Types[ConstValType].Kind = ARRAYTYPE) and not Types[ConstValType].IsOpenArray then
ConstValType := Types[ConstValType].IndexType;
if func = HIGHFUNC then
ConstVal.OrdValue := HighBound(ConstValType)
else
ConstVal.OrdValue := LowBound(ConstValType);
end;
PREDFUNC, SUCCFUNC:
begin
CompileConstExpression(ConstVal, ConstValType);
if not (Types[ConstValType].Kind in OrdinalTypes) then
Error('Ordinal type expected');
if func = SUCCFUNC then
Inc(ConstVal.OrdValue)
else
Dec(ConstVal.OrdValue);
end;
ABSFUNC, SQRFUNC, SINFUNC, COSFUNC, ARCTANFUNC, EXPFUNC, LNFUNC, SQRTFUNC:
begin
CompileConstExpression(ConstVal, ConstValType);
if (func = ABSFUNC) or (func = SQRFUNC) then // Abs and Sqr accept real or integer parameters
begin
if not ((Types[ConstValType].Kind in NumericTypes) or
((Types[ConstValType].Kind = SUBRANGETYPE) and (Types[Types[ConstValType].BaseType].Kind in NumericTypes))) then
Error('Numeric type expected');
if Types[ConstValType].Kind = REALTYPE then
if func = ABSFUNC then
ConstVal.RealValue := abs(ConstVal.RealValue)
else
ConstVal.RealValue := sqr(ConstVal.RealValue)
else
if func = ABSFUNC then
ConstVal.OrdValue := abs(ConstVal.OrdValue)
else
ConstVal.OrdValue := sqr(ConstVal.OrdValue);
end
else
Error('Function is not allowed in constant expressions');
end;
end;// case
EatTok(CPARTOK);
end;// CompileConstPredefinedFunc
procedure CompileConstSetConstructor(var ConstVal: TConst; var ConstValType: Integer);
var
ElementVal, ElementVal2: TConst;
ElementValType: Integer;
ElementIndex: Integer;
begin
ConstVal.SetValue := [];
// Add new anonymous type
DeclareType(SETTYPE);
Types[NumTypes].BaseType := ANYTYPEINDEX;
ConstValType := NumTypes;
// Compile constructor
EatTok(OBRACKETTOK);
if Tok.Kind <> CBRACKETTOK then
repeat
CompileConstExpression(ElementVal, ElementValType);
if Types[ConstValType].BaseType = ANYTYPEINDEX then
begin
if not (Types[ElementValType].Kind in OrdinalTypes) then
Error('Ordinal type expected');
Types[ConstValType].BaseType := ElementValType;
end
else
GetCompatibleType(ElementValType, Types[ConstValType].BaseType);
if Tok.Kind = RANGETOK then
begin
NextTok;
CompileConstExpression(ElementVal2, ElementValType);
GetCompatibleType(ElementValType, Types[ConstValType].BaseType);
end
else
ElementVal2 := ElementVal;
if (ElementVal.OrdValue < 0) or (ElementVal.OrdValue >= MAXSETELEMENTS) or
(ElementVal2.OrdValue < 0) or (ElementVal2.OrdValue >= MAXSETELEMENTS)
then
Error('Set elements must be between 0 and ' + IntToStr(MAXSETELEMENTS - 1));
for ElementIndex := ElementVal.OrdValue to ElementVal2.OrdValue do
ConstVal.SetValue := ConstVal.SetValue + [ElementIndex];
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(CBRACKETTOK);
end; // CompileConstSetConstructor
procedure CompileConstFactor(var ConstVal: TConst; var ConstValType: Integer);
var
NotOpTok: TToken;
IdentIndex: Integer;
begin
case Tok.Kind of
IDENTTOK:
begin
IdentIndex := GetIdent(Tok.Name);
case Ident[IdentIndex].Kind of
GOTOLABEL:
Error('Constant expression expected but label ' + Ident[IdentIndex].Name + ' found');
PROC:
Error('Constant expression expected but procedure ' + Ident[IdentIndex].Name + ' found');
FUNC:
if Ident[IdentIndex].PredefProc <> EMPTYPROC then
CompileConstPredefinedFunc(Ident[IdentIndex].PredefProc, ConstVal, ConstValType)
else
Error('Function ' + Ident[IdentIndex].Name + ' is not allowed in constant expressions');
VARIABLE:
Error('Constant expression expected but variable ' + Ident[IdentIndex].Name + ' found');
CONSTANT:
begin
ConstValType := Ident[IdentIndex].DataType;
case Types[ConstValType].Kind of
SETTYPE: ConstVal.SetValue := Ident[IdentIndex].ConstVal.SetValue;
ARRAYTYPE: ConstVal.StrValue := Ident[IdentIndex].ConstVal.StrValue;
REALTYPE: ConstVal.RealValue := Ident[IdentIndex].ConstVal.RealValue;
else ConstVal.OrdValue := Ident[IdentIndex].ConstVal.OrdValue;
end;
NextTok;
end;
USERTYPE:
Error('Constant expression expected but type ' + Ident[IdentIndex].Name + ' found');
else
Error('Internal fault: Illegal identifier');
end; // case Ident[IdentIndex].Kind
end;
INTNUMBERTOK:
begin
ConstVal.OrdValue := Tok.OrdValue;
ConstValType := INTEGERTYPEINDEX;
NextTok;
end;
REALNUMBERTOK:
begin
ConstVal.RealValue := Tok.RealValue;
ConstValType := REALTYPEINDEX;
NextTok;
end;
CHARLITERALTOK:
begin
ConstVal.OrdValue := Tok.OrdValue;
ConstValType := CHARTYPEINDEX;
NextTok;
end;
STRINGLITERALTOK:
begin
ConstVal.StrValue := Tok.Name;
ConstValType := STRINGTYPEINDEX;
NextTok;
end;
OPARTOK:
begin
NextTok;
CompileConstExpression(ConstVal, ConstValType);
EatTok(CPARTOK);
end;
NOTTOK:
begin
NotOpTok := Tok;
NextTok;
CompileConstFactor(ConstVal, ConstValType);
CheckOperator(NotOpTok, ConstValType);
ConstVal.OrdValue := not ConstVal.OrdValue;
if Types[ConstValType].Kind = BOOLEANTYPE then
ConstVal.OrdValue := ConstVal.OrdValue and 1;
end;
OBRACKETTOK:
CompileConstSetConstructor(ConstVal, ConstValType);
else
Error('Expression expected but ' + GetTokSpelling(Tok.Kind) + ' found');
end;// case
end;// CompileConstFactor
procedure CompileConstTerm(var ConstVal: TConst; var ConstValType: Integer);
var
OpTok: TToken;
RightConstVal: TConst;
RightConstValType: Integer;
begin
CompileConstFactor(ConstVal, ConstValType);
while Tok.Kind in MultiplicativeOperators do
begin
OpTok := Tok;
NextTok;
CompileConstFactor(RightConstVal, RightConstValType);
// Try to convert integer to real
ConvertConstIntegerToReal(RightConstValType, ConstValType, ConstVal);
ConvertConstIntegerToReal(ConstValType, RightConstValType, RightConstVal);
// Special case: real division of two integers
if OpTok.Kind = DIVTOK then
begin
ConvertConstIntegerToReal(REALTYPEINDEX, ConstValType, ConstVal);
ConvertConstIntegerToReal(REALTYPEINDEX, RightConstValType, RightConstVal);
end;
ConstValType := GetCompatibleType(ConstValType, RightConstValType);
// Special case: set intersection
if (OpTok.Kind = MULTOK) and (Types[ConstValType].Kind = SETTYPE) then
ConstVal.SetValue := ConstVal.SetValue * RightConstVal.SetValue
// General rule
else
begin
CheckOperator(OpTok, ConstValType);
if Types[ConstValType].Kind = REALTYPE then // Real constants
case OpTok.Kind of
MULTOK: ConstVal.RealValue := ConstVal.RealValue * RightConstVal.RealValue;
DIVTOK: if RightConstVal.RealValue <> 0 then
ConstVal.RealValue := ConstVal.RealValue / RightConstVal.RealValue
else
Error('Constant division by zero')
end
else // Integer constants
begin
case OpTok.Kind of
MULTOK: ConstVal.OrdValue := ConstVal.OrdValue * RightConstVal.OrdValue;
IDIVTOK: if RightConstVal.OrdValue <> 0 then
ConstVal.OrdValue := ConstVal.OrdValue div RightConstVal.OrdValue
else
Error('Constant division by zero');
MODTOK: if RightConstVal.OrdValue <> 0 then
ConstVal.OrdValue := ConstVal.OrdValue mod RightConstVal.OrdValue
else
Error('Constant division by zero');
SHLTOK: ConstVal.OrdValue := ConstVal.OrdValue shl RightConstVal.OrdValue;
SHRTOK: ConstVal.OrdValue := ConstVal.OrdValue shr RightConstVal.OrdValue;
ANDTOK: ConstVal.OrdValue := ConstVal.OrdValue and RightConstVal.OrdValue;
end;
if Types[ConstValType].Kind = BOOLEANTYPE then
ConstVal.OrdValue := ConstVal.OrdValue and 1;
end // else
end; // else
end;// while
end;// CompileConstTerm
procedure CompileSimpleConstExpression(var ConstVal: TConst; var ConstValType: Integer);
var
UnaryOpTok, OpTok: TToken;
RightConstVal: TConst;
RightConstValType: Integer;
begin
UnaryOpTok := Tok;
if UnaryOpTok.Kind in UnaryOperators then
NextTok;
CompileConstTerm(ConstVal, ConstValType);
if UnaryOpTok.Kind in UnaryOperators then
CheckOperator(UnaryOpTok, ConstValType);
if UnaryOpTok.Kind = MINUSTOK then // Unary minus
if Types[ConstValType].Kind = REALTYPE then
ConstVal.RealValue := -ConstVal.RealValue
else
ConstVal.OrdValue := -ConstVal.OrdValue;
while Tok.Kind in AdditiveOperators do
begin
OpTok := Tok;
NextTok;
CompileConstTerm(RightConstVal, RightConstValType);
// Try to convert integer to real
ConvertConstIntegerToReal(RightConstValType, ConstValType, ConstVal);
ConvertConstIntegerToReal(ConstValType, RightConstValType, RightConstVal);
// Try to convert character to string
ConvertConstCharToString(RightConstValType, ConstValType, ConstVal);
ConvertConstCharToString(ConstValType, RightConstValType, RightConstVal);
ConstValType := GetCompatibleType(ConstValType, RightConstValType);
// Special case: string concatenation
if (OpTok.Kind = PLUSTOK) and IsString(ConstValType) and IsString(RightConstValType) then
ConstVal.StrValue := ConstVal.StrValue + RightConstVal.StrValue
// Special case: set union or difference
else if (OpTok.Kind in [PLUSTOK, MINUSTOK]) and (Types[ConstValType].Kind = SETTYPE) then
ConstVal.SetValue := ConstVal.SetValue + RightConstVal.SetValue
// General rule
else
begin
CheckOperator(OpTok, ConstValType);
if Types[ConstValType].Kind = REALTYPE then // Real constants
case OpTok.Kind of
PLUSTOK: ConstVal.RealValue := ConstVal.RealValue + RightConstVal.RealValue;
MINUSTOK: ConstVal.RealValue := ConstVal.RealValue - RightConstVal.RealValue;
end
else // Integer constants
begin
case OpTok.Kind of
PLUSTOK: ConstVal.OrdValue := ConstVal.OrdValue + RightConstVal.OrdValue;
MINUSTOK: ConstVal.OrdValue := ConstVal.OrdValue - RightConstVal.OrdValue;
ORTOK: ConstVal.OrdValue := ConstVal.OrdValue or RightConstVal.OrdValue;
XORTOK: ConstVal.OrdValue := ConstVal.OrdValue xor RightConstVal.OrdValue;
end;
if Types[ConstValType].Kind = BOOLEANTYPE then
ConstVal.OrdValue := ConstVal.OrdValue and 1;
end;
end;
end;// while
end;// CompileSimpleConstExpression
procedure CompileConstExpression(var ConstVal: TConst; var ConstValType: Integer);
var
OpTok: TToken;
RightConstVal: TConst;
RightConstValType: Integer;
Yes: Boolean;
begin
Yes := FALSE;
CompileSimpleConstExpression(ConstVal, ConstValType);
if Tok.Kind in RelationOperators then
begin
OpTok := Tok;
NextTok;
CompileSimpleConstExpression(RightConstVal, RightConstValType);
// Try to convert integer to real
ConvertConstIntegerToReal(RightConstValType, ConstValType, ConstVal);
ConvertConstIntegerToReal(ConstValType, RightConstValType, RightConstVal);
// Try to convert character to string
ConvertConstCharToString(RightConstValType, ConstValType, ConstVal);
ConvertConstCharToString(ConstValType, RightConstValType, RightConstVal);
GetCompatibleType(ConstValType, RightConstValType);
// Special case: string comparison
if IsString(ConstValType) and IsString(RightConstValType) then
case OpTok.Kind of
EQTOK: Yes := ConstVal.StrValue = RightConstVal.StrValue;
NETOK: Yes := ConstVal.StrValue <> RightConstVal.StrValue;
LTTOK: Yes := ConstVal.StrValue < RightConstVal.StrValue;
LETOK: Yes := ConstVal.StrValue <= RightConstVal.StrValue;
GTTOK: Yes := ConstVal.StrValue > RightConstVal.StrValue;
GETOK: Yes := ConstVal.StrValue >= RightConstVal.StrValue;
end
// Special case: set comparison
else if (OpTok.Kind in [EQTOK, NETOK, GETOK, LETOK]) and (Types[ConstValType].Kind = SETTYPE) then
case OpTok.Kind of
EQTOK: Yes := ConstVal.SetValue = RightConstVal.SetValue;
NETOK: Yes := ConstVal.SetValue <> RightConstVal.SetValue;
LETOK: Yes := ConstVal.SetValue <= RightConstVal.SetValue;
GETOK: Yes := ConstVal.SetValue >= RightConstVal.SetValue;
end
// General rule
else
begin
CheckOperator(OpTok, ConstValType);
if Types[ConstValType].Kind = REALTYPE then
case OpTok.Kind of
EQTOK: Yes := ConstVal.RealValue = RightConstVal.RealValue;
NETOK: Yes := ConstVal.RealValue <> RightConstVal.RealValue;
LTTOK: Yes := ConstVal.RealValue < RightConstVal.RealValue;
LETOK: Yes := ConstVal.RealValue <= RightConstVal.RealValue;
GTTOK: Yes := ConstVal.RealValue > RightConstVal.RealValue;
GETOK: Yes := ConstVal.RealValue >= RightConstVal.RealValue;
end
else
case OpTok.Kind of
EQTOK: Yes := ConstVal.OrdValue = RightConstVal.OrdValue;
NETOK: Yes := ConstVal.OrdValue <> RightConstVal.OrdValue;
LTTOK: Yes := ConstVal.OrdValue < RightConstVal.OrdValue;
LETOK: Yes := ConstVal.OrdValue <= RightConstVal.OrdValue;
GTTOK: Yes := ConstVal.OrdValue > RightConstVal.OrdValue;
GETOK: Yes := ConstVal.OrdValue >= RightConstVal.OrdValue;
end;
end;
if Yes then ConstVal.OrdValue := 1 else ConstVal.OrdValue := 0;
ConstValType := BOOLEANTYPEINDEX;
end;
end;// CompileConstExpression
procedure CompilePredefinedProc(proc: TPredefProc; LoopNesting: Integer);
function GetReadProcIdent(DataType: Integer): Integer;
begin
Result := 0;
with Types[DataType] do
if (Kind = INTEGERTYPE) or ((Kind = SUBRANGETYPE) and (Types[BaseType].Kind = INTEGERTYPE)) then
Result := GetIdent('READINT') // Integer argument
else if (Kind = SMALLINTTYPE) or ((Kind = SUBRANGETYPE) and (Types[BaseType].Kind = SMALLINTTYPE)) then
Result := GetIdent('READSMALLINT') // Small integer argument
else if (Kind = SHORTINTTYPE) or ((Kind = SUBRANGETYPE) and (Types[BaseType].Kind = SHORTINTTYPE)) then
Result := GetIdent('READSHORTINT') // Short integer argument
else if (Kind = WORDTYPE) or ((Kind = SUBRANGETYPE) and (Types[BaseType].Kind = WORDTYPE)) then
Result := GetIdent('READWORD') // Word argument
else if (Kind = BYTETYPE) or ((Kind = SUBRANGETYPE) and (Types[BaseType].Kind = BYTETYPE)) then
Result := GetIdent('READBYTE') // Byte argument
else if (Kind = BOOLEANTYPE) or ((Kind = SUBRANGETYPE) and (Types[BaseType].Kind = BOOLEANTYPE)) then
Result := GetIdent('READBOOLEAN') // Boolean argument
else if (Kind = CHARTYPE) or ((Kind = SUBRANGETYPE) and (Types[BaseType].Kind = CHARTYPE)) then
Result := GetIdent('READCH') // Character argument
else if Kind = REALTYPE then
Result := GetIdent('READREAL') // Real argument
else if Kind = SINGLETYPE then
Result := GetIdent('READSINGLE') // Single argument
else if (Kind = ARRAYTYPE) and (BaseType = CHARTYPEINDEX) then
Result := GetIdent('READSTRING') // String argument
else
Error('Cannot read ' + GetTypeSpelling(DataType));
end; // GetReadProcIdent
function GetWriteProcIdent(DataType: Integer): Integer;
begin
Result := 0;
with Types[DataType] do
if (Kind in IntegerTypes) or ((Kind = SUBRANGETYPE) and (Types[BaseType].Kind in IntegerTypes)) then
Result := GetIdent('WRITEINTF') // Integer argument
else if (Kind = BOOLEANTYPE) or ((Kind = SUBRANGETYPE) and (Types[BaseType].Kind = BOOLEANTYPE)) then
Result := GetIdent('WRITEBOOLEANF') // Boolean argument
else if Kind = REALTYPE then
Result := GetIdent('WRITEREALF') // Real argument
else if Kind = POINTERTYPE then
Result := GetIdent('WRITEPOINTERF') // Pointer argument
else if (Kind = ARRAYTYPE) and (BaseType = CHARTYPEINDEX) then
Result := GetIdent('WRITESTRINGF') // String argument
else
Error('Cannot write ' + GetTypeSpelling(DataType));
end; // GetWriteProcIdentIndex
var
DesignatorType, FileVarType, ExpressionType, FormatterType: Integer;
LibProcIdentIndex, ConsoleIndex: Integer;
IsFirstParam: Boolean;
begin // CompilePredefinedProc
NextTok;
case proc of
INCPROC, DECPROC:
begin
EatTok(OPARTOK);
CompileDesignator(DesignatorType, FALSE);
if (Types[DesignatorType].Kind = POINTERTYPE) and (Types[DesignatorType].BaseType <> ANYTYPEINDEX) then // Special case: typed pointer
GenerateIncDec(proc, TypeSize(DesignatorType), TypeSize(Types[DesignatorType].BaseType))
else // General rule
begin
GetCompatibleType(DesignatorType, INTEGERTYPEINDEX);
GenerateIncDec(proc, TypeSize(DesignatorType));
end;
EatTok(CPARTOK);
end;
READPROC, READLNPROC:
begin
ConsoleIndex := GetIdent('STDINPUTFILE');
FileVarType := ANYTYPEINDEX;
IsFirstParam := TRUE;
if Tok.Kind = OPARTOK then
begin
NextTok;
repeat
// 1st argument - file handle
if FileVarType <> ANYTYPEINDEX then
DuplicateStackTop
else
PushVarIdentPtr(ConsoleIndex);
// 2nd argument - stream handle
PushConst(0);
// 3rd argument - designator
CompileDesignator(DesignatorType, FALSE);
if Types[DesignatorType].Kind = FILETYPE then // File handle
begin
if not IsFirstParam or ((proc = READLNPROC) and (Types[DesignatorType].BaseType <> ANYTYPEINDEX)) then
Error('Cannot read ' + GetTypeSpelling(DesignatorType));
FileVarType := DesignatorType;
end
else // Any input variable
begin
// Select input subroutine
if (Types[FileVarType].Kind = FILETYPE) and (Types[FileVarType].BaseType <> ANYTYPEINDEX) then // Read from typed file
begin
GetCompatibleRefType(Types[FileVarType].BaseType, DesignatorType);
// 4th argument - record length
PushConst(TypeSize(Types[FileVarType].BaseType));
LibProcIdentIndex := GetIdent('READREC');
end
else // Read from text file
LibProcIdentIndex := GetReadProcIdent(DesignatorType);
// Call selected input subroutine. Interface: FileHandle; StreamHandle; var Designator [; Length]
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
end; // else
IsFirstParam := FALSE;
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(CPARTOK);
end; // if OPARTOR
// Add CR+LF, if necessary
if proc = READLNPROC then
begin
// 1st argument - file handle
if FileVarType <> ANYTYPEINDEX then
DuplicateStackTop
else
PushVarIdentPtr(ConsoleIndex);
// 2nd argument - stream handle
PushConst(0);
LibProcIdentIndex := GetIdent('READNEWLINE');
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
end;
// Remove first 3 arguments if they correspond to a file variable
if FileVarType <> ANYTYPEINDEX then
DiscardStackTop(3);
end;// READPROC, READLNPROC
WRITEPROC, WRITELNPROC:
begin
ConsoleIndex := GetIdent('STDOUTPUTFILE');
FileVarType := ANYTYPEINDEX;
IsFirstParam := TRUE;
if Tok.Kind = OPARTOK then
begin
NextTok;
repeat
// 1st argument - file handle
if FileVarType <> ANYTYPEINDEX then
DuplicateStackTop
else
PushVarIdentPtr(ConsoleIndex);
// 2nd argument - stream handle
PushConst(0);
// 3rd argument - expression (for untyped/text files) or designator (for typed files)
if (Types[FileVarType].Kind = FILETYPE) and (Types[FileVarType].BaseType <> ANYTYPEINDEX) then
CompileDesignator(ExpressionType)
else
begin
CompileExpression(ExpressionType);
// Try to convert single to double
ConvertRealToReal(REALTYPEINDEX, ExpressionType);
// Try to convert character to string
ConvertCharToString(STRINGTYPEINDEX, ExpressionType, 0);
end;
if Types[ExpressionType].Kind = FILETYPE then // File handle
begin
if not IsFirstParam or ((proc = WRITELNPROC) and (Types[ExpressionType].BaseType <> ANYTYPEINDEX)) then
Error('Cannot write ' + GetTypeSpelling(ExpressionType));
FileVarType := ExpressionType;
end
else // Any output expression
begin
// 4th argument - minimum width
if Tok.Kind = COLONTOK then
begin
if (Types[FileVarType].Kind = FILETYPE) and (Types[FileVarType].BaseType <> ANYTYPEINDEX) then
Error('Format specifiers are not allowed for typed files');
NextTok;
CompileExpression(FormatterType);
GetCompatibleType(FormatterType, INTEGERTYPEINDEX);
// 5th argument - number of decimal places
if (Tok.Kind = COLONTOK) and (Types[ExpressionType].Kind = REALTYPE) then
begin
NextTok;
CompileExpression(FormatterType);
GetCompatibleType(FormatterType, INTEGERTYPEINDEX);
end
else
PushConst(0);
end
else
begin
PushConst(0);
PushConst(0);
end;
// Select output subroutine
if (Types[FileVarType].Kind = FILETYPE) and (Types[FileVarType].BaseType <> ANYTYPEINDEX) then // Write to typed file
begin
GetCompatibleRefType(Types[FileVarType].BaseType, ExpressionType);
// Discard 4th and 5th arguments - format specifiers
DiscardStackTop(2);
// 4th argument - record length
PushConst(TypeSize(Types[FileVarType].BaseType));
LibProcIdentIndex := GetIdent('WRITEREC');
end
else // Write to text file
LibProcIdentIndex := GetWriteProcIdent(ExpressionType);
// Call selected output subroutine. Interface: FileHandle; StreamHandle; (Designator | Expression); (Length; | MinWidth; DecPlaces)
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
end; // else
IsFirstParam := FALSE;
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(CPARTOK);
end; // if OPARTOR
// Add CR+LF, if necessary
if proc = WRITELNPROC then
begin
LibProcIdentIndex := GetIdent('WRITENEWLINE');
// 1st argument - file handle
if FileVarType <> ANYTYPEINDEX then
DuplicateStackTop
else
PushVarIdentPtr(ConsoleIndex);
// 2nd argument - stream handle
PushConst(0);
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
end;
// Remove first 3 arguments if they correspond to a file variable
if FileVarType <> ANYTYPEINDEX then
DiscardStackTop(3);
end;// WRITEPROC, WRITELNPROC
NEWPROC, DISPOSEPROC:
begin
EatTok(OPARTOK);
CompileDesignator(DesignatorType, FALSE);
GetCompatibleType(DesignatorType, POINTERTYPEINDEX);
if proc = NEWPROC then
begin
PushConst(TypeSize(Types[DesignatorType].BaseType));
LibProcIdentIndex := GetIdent('GETMEM');
end
else
LibProcIdentIndex := GetIdent('FREEMEM');
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
EatTok(CPARTOK);
end;
BREAKPROC:
begin
if LoopNesting < 1 then
Error('BREAK outside of loop is not allowed');
GenerateBreakCall(LoopNesting);
end;
CONTINUEPROC:
begin
if LoopNesting < 1 then
Error('CONTINUE outside of loop is not allowed');
GenerateContinueCall(LoopNesting);
end;
EXITPROC:
GenerateExitCall;
HALTPROC:
begin
if Tok.Kind = OPARTOK then
begin
NextTok;
CompileExpression(ExpressionType);
GetCompatibleType(ExpressionType, INTEGERTYPEINDEX);
EatTok(CPARTOK);
end
else
PushConst(0);
LibProcIdentIndex := GetIdent('EXITPROCESS');
GenerateCall(Ident[LibProcIdentIndex].Address, 1, 1);
end;
end;// case
end;// CompilePredefinedProc
procedure CompilePredefinedFunc(func: TPredefProc; var ValType: Integer);
var
IdentIndex: Integer;
begin
NextTok;
EatTok(OPARTOK);
case func of
SIZEOFFUNC:
begin
AssertIdent;
IdentIndex := GetIdentUnsafe(Tok.Name);
if (IdentIndex <> 0) and (Ident[IdentIndex].Kind = USERTYPE) then // Type name
begin
NextTok;
PushConst(TypeSize(Ident[IdentIndex].DataType));
end
else // Variable name
begin
CompileDesignator(ValType);
DiscardStackTop(1);
PushConst(TypeSize(ValType));
end;
ValType := INTEGERTYPEINDEX;
end;
ROUNDFUNC, TRUNCFUNC:
begin
CompileExpression(ValType);
// Try to convert integer to real
ConvertIntegerToReal(REALTYPEINDEX, ValType, 0);
GetCompatibleType(ValType, REALTYPEINDEX);
GenerateRound(func = TRUNCFUNC);
ValType := INTEGERTYPEINDEX;
end;
ORDFUNC:
begin
CompileExpression(ValType);
if not (Types[ValType].Kind in OrdinalTypes) then
Error('Ordinal type expected');
ValType := INTEGERTYPEINDEX;
end;
CHRFUNC:
begin
CompileExpression(ValType);
GetCompatibleType(ValType, INTEGERTYPEINDEX);
ValType := CHARTYPEINDEX;
end;
LOWFUNC, HIGHFUNC:
begin
AssertIdent;
IdentIndex := GetIdentUnsafe(Tok.Name);
if (IdentIndex <> 0) and (Ident[IdentIndex].Kind = USERTYPE) then // Type name
begin
NextTok;
ValType := Ident[IdentIndex].DataType;
end
else // Variable name
begin
CompileDesignator(ValType);
DiscardStackTop(1);
end;
if (Types[ValType].Kind = ARRAYTYPE) and not Types[ValType].IsOpenArray then
ValType := Types[ValType].IndexType;
if func = HIGHFUNC then
PushConst(HighBound(ValType))
else
PushConst(LowBound(ValType));
end;
PREDFUNC, SUCCFUNC:
begin
CompileExpression(ValType);
if not (Types[ValType].Kind in OrdinalTypes) then
Error('Ordinal type expected');
if func = SUCCFUNC then
PushConst(1)
else
PushConst(-1);
GenerateBinaryOperator(PLUSTOK, INTEGERTYPEINDEX);
end;
ABSFUNC, SQRFUNC, SINFUNC, COSFUNC, ARCTANFUNC, EXPFUNC, LNFUNC, SQRTFUNC:
begin
CompileExpression(ValType);
if (func = ABSFUNC) or (func = SQRFUNC) then // Abs and Sqr accept real or integer parameters
begin
if not ((Types[ValType].Kind in NumericTypes) or
((Types[ValType].Kind = SUBRANGETYPE) and (Types[Types[ValType].BaseType].Kind in NumericTypes))) then
Error('Numeric type expected')
end
else
begin
// Try to convert integer to real
ConvertIntegerToReal(REALTYPEINDEX, ValType, 0);
GetCompatibleType(ValType, REALTYPEINDEX);
end;
GenerateMathFunction(func, ValType);
end;
end;// case
EatTok(CPARTOK);
end;// CompilePredefinedFunc
procedure CompileTypeIdent(var DataType: Integer; AllowForwardReference: Boolean);
var
IdentIndex: Integer;
begin
// STRING, FILE or type name allowed
case Tok.Kind of
STRINGTOK:
DataType := STRINGTYPEINDEX;
FILETOK:
DataType := FILETYPEINDEX
else
AssertIdent;
if AllowForwardReference then
IdentIndex := GetIdentUnsafe(Tok.Name, AllowForwardReference)
else
IdentIndex := GetIdent(Tok.Name, AllowForwardReference);
if AllowForwardReference and ((IdentIndex = 0) or (Ident[IdentIndex].Block <> BlockStack[BlockStackTop].Index)) then
begin
// Add new forward-referenced type
DeclareType(FORWARDTYPE);
Types[NumTypes].TypeIdentName := Tok.Name;
DataType := NumTypes;
end
else
begin
// Use existing type
if Ident[IdentIndex].Kind <> USERTYPE then
Error('Type name expected');
DataType := Ident[IdentIndex].DataType;
end;
end; // case
NextTok;
end; // CompileTypeIdent
procedure CompileFormalParametersAndResult(IsFunction: Boolean; var Signature: TSignature);
var
IdentInListName: array [1..MAXPARAMS] of TString;
NumIdentInList, IdentInListIndex: Integer;
ParamType, DefaultValueType: Integer;
ListPassMethod: TPassMethod;
IsOpenArrayList, StringByValFound: Boolean;
Default: TConst;
begin
Signature.NumParams := 0;
Signature.NumDefaultParams := 0;
StringByValFound := FALSE;
if Tok.Kind = OPARTOK then
begin
NextTok;
repeat
NumIdentInList := 0;
ListPassMethod := VALPASSING;
if Tok.Kind = CONSTTOK then
begin
ListPassMethod := CONSTPASSING;
NextTok;
end
else if Tok.Kind = VARTOK then
begin
ListPassMethod := VARPASSING;
NextTok;
end;
repeat
AssertIdent;
Inc(NumIdentInList);
IdentInListName[NumIdentInList] := Tok.Name;
NextTok;
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
// Formal parameter list type
if Tok.Kind = COLONTOK then // Typed parameters
begin
NextTok;
// Special case: open array parameters
if Tok.Kind = ARRAYTOK then
begin
NextTok;
EatTok(OFTOK);
IsOpenArrayList := TRUE;
end
else
IsOpenArrayList := FALSE;
// Type itself
CompileTypeIdent(ParamType, FALSE);
// Special case: open array parameters
if IsOpenArrayList then
begin
// Add new anonymous type 0..0 for array index
DeclareType(SUBRANGETYPE);
Types[NumTypes].BaseType := INTEGERTYPEINDEX;
Types[NumTypes].Low := 0;
Types[NumTypes].High := 0;
// Add new anonymous type for array itself
DeclareType(ARRAYTYPE);
Types[NumTypes].BaseType := ParamType;
Types[NumTypes].IndexType := NumTypes - 1;
Types[NumTypes].IsOpenArray := TRUE;
ParamType := NumTypes;
end;
end
else // Untyped parameters (CONST or VAR only)
ParamType := ANYTYPEINDEX;
if (ListPassMethod <> VARPASSING) and (ParamType = ANYTYPEINDEX) then
Error('Untyped parameters require VAR');
if (ListPassMethod = VALPASSING) and IsString(ParamType) then
StringByValFound := TRUE;
// Default parameter value
if (Tok.Kind = EQTOK) or (Signature.NumDefaultParams > 0) then
begin
EatTok(EQTOK);
if not (Types[ParamType].Kind in OrdinalTypes + [REALTYPE]) then
Error('Ordinal or real type expected for default parameter');
if ListPassMethod <> VALPASSING then
Error('Default parameters cannot be passed by reference');
CompileConstExpression(Default, DefaultValueType);
GetCompatibleType(ParamType, DefaultValueType);
Inc(Signature.NumDefaultParams);
end;
for IdentInListIndex := 1 to NumIdentInList do
begin
Inc(Signature.NumParams);
if Signature.NumParams > MAXPARAMS then
Error('Too many formal parameters');
New(Signature.Param[Signature.NumParams]);
with Signature, Param[NumParams]^ do
begin
Name := IdentInListName[IdentInListIndex];
DataType := ParamType;
PassMethod := ListPassMethod;
Default.OrdValue := 0;
end;
// Default parameter value
if (Signature.NumDefaultParams > 0) and (IdentInListIndex = 1) then
begin
if NumIdentInList > 1 then
Error('Default parameters cannot be grouped');
Signature.Param[Signature.NumParams]^.Default := Default;
end;
end;// for
if Tok.Kind <> SEMICOLONTOK then Break;
NextTok;
until FALSE;
EatTok(CPARTOK);
end;// if Tok.Kind = OPARTOK
// Function result type
Signature.ResultType := 0;
if IsFunction then
begin
EatTok(COLONTOK);
CompileTypeIdent(Signature.ResultType, FALSE);
end;
// Call modifier
if (Tok.Kind = IDENTTOK) and (Tok.Name = 'STDCALL') then
begin
Signature.CallConv := STDCALLCONV;
NextTok;
end
else if (Tok.Kind = IDENTTOK) and (Tok.Name = 'CDECL') then
begin
Signature.CallConv := CDECLCONV;
NextTok;
end
else
Signature.CallConv := DEFAULTCONV;
if (Signature.CallConv <> DEFAULTCONV) and StringByValFound then
Error('Strings cannot be passed by value to STDCALL/CDECL procedures');
end; // CompileFormalParametersAndResult
procedure CompileActualParameters(const Signature: TSignature; var StructuredResultAddr: LongInt);
procedure CompileExpressionCopy(var ValType: Integer; CallConv: TCallConv);
var
TempStorageAddr: Integer;
LibProcIdentIndex: Integer;
begin
CompileExpression(ValType);
// Copy structured parameter passed by value (for STDCALL/CDECL functions there is no need to do it here since it will be done in MakeCStack)
if (Types[ValType].Kind in StructuredTypes) and (CallConv = DEFAULTCONV) then
begin
SaveStackTopToEAX;
TempStorageAddr := AllocateTempStorage(TypeSize(ValType));
PushTempStoragePtr(TempStorageAddr);
RestoreStackTopFromEAX;
if IsString(ValType) then
begin
LibProcIdentIndex := GetIdent('ASSIGNSTR');
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
end
else
GenerateStructuredAssignment(ValType);
PushTempStoragePtr(TempStorageAddr);
end;
end; // CompileExpressionCopy
var
NumActualParams: Integer;
ActualParamType: Integer;
DefaultParamIndex: Integer;
CurParam: PParam;
begin
// Allocate space for structured Result as a hidden VAR parameter (except STDCALL/CDECL functions returning small structures in EDX:EAX)
with Signature do
if (ResultType <> 0) and (Types[ResultType].Kind in StructuredTypes) and ((CallConv = DEFAULTCONV) or (TypeSize(ResultType) > 2 * SizeOf(LongInt))) then
begin
StructuredResultAddr := AllocateTempStorage(TypeSize(ResultType));
PushTempStoragePtr(StructuredResultAddr);
end
else
StructuredResultAddr := 0;
NumActualParams := 0;
if Tok.Kind = OPARTOK then // Actual parameter list found
begin
NextTok;
if Tok.Kind <> CPARTOK then
repeat
if NumActualParams + 1 > Signature.NumParams then
Error('Too many actual parameters');
CurParam := Signature.Param[NumActualParams + 1];
case CurParam^.PassMethod of
VALPASSING: CompileExpressionCopy(ActualParamType, Signature.CallConv);
CONSTPASSING: CompileExpression(ActualParamType);
VARPASSING: CompileDesignator(ActualParamType, CurParam^.DataType = ANYTYPEINDEX);
else
Error('Internal fault: Illegal parameter passing method');
end;
Inc(NumActualParams);
// Try to convert integer to double, single to double or double to single
if CurParam^.PassMethod <> VARPASSING then
begin
ConvertIntegerToReal(CurParam^.DataType, ActualParamType, 0);
ConvertRealToReal(CurParam^.DataType, ActualParamType);
end;
// Try to convert character to string
ConvertCharToString(CurParam^.DataType, ActualParamType, 0);
// Try to convert string to pointer to character
ConvertStringToPChar(CurParam^.DataType, ActualParamType);
// Try to convert a concrete type to an interface type
ConvertToInterface(CurParam^.DataType, ActualParamType);
if CurParam^.PassMethod = VARPASSING then
GetCompatibleRefType(CurParam^.DataType, ActualParamType) // Strict type checking for parameters passed by reference, except for open array parameters and untyped parameters
else
GetCompatibleType(CurParam^.DataType, ActualParamType); // Relaxed type checking for parameters passed by value
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(CPARTOK);
end;// if Tok.Kind = OPARTOK
if NumActualParams < Signature.NumParams - Signature.NumDefaultParams then
Error('Too few actual parameters');
// Push default parameters
for DefaultParamIndex := NumActualParams + 1 to Signature.NumParams do
begin
CurParam := Signature.Param[DefaultParamIndex];
PushConst(CurParam^.Default.OrdValue);
end; // for
end;// CompileActualParameters
procedure MakeCStack(const Signature: TSignature);
var
ParamIndex: Integer;
SourceStackDepth: Integer;
begin
InitializeCStack;
// Push explicit parameters
SourceStackDepth := 0;
for ParamIndex := Signature.NumParams downto 1 do
with Signature.Param[ParamIndex]^ do
begin
PushToCStack(SourceStackDepth, DataType, PassMethod = VALPASSING);
if (Types[DataType].Kind = REALTYPE) and (PassMethod = VALPASSING) then
SourceStackDepth := SourceStackDepth + Align(TypeSize(DataType), SizeOf(LongInt))
else
SourceStackDepth := SourceStackDepth + SizeOf(LongInt);
end;
// Push structured Result onto the C stack, except STDCALL/CDECL functions returning small structures in EDX:EAX
with Signature do
if (ResultType <> 0) and (Types[ResultType].Kind in StructuredTypes) and ((CallConv = DEFAULTCONV) or (TypeSize(ResultType) > 2 * SizeOf(LongInt))) then
PushToCStack(NumParams * SizeOf(LongInt), ResultType, FALSE);
end; // MakeCStack
procedure ConvertResultFromCToPascal(const Signature: TSignature; StructuredResultAddr: LongInt);
begin
with Signature do
if (ResultType <> 0) and (CallConv <> DEFAULTCONV) then
if Types[ResultType].Kind in StructuredTypes then
if TypeSize(ResultType) <= 2 * SizeOf(LongInt) then
begin
// For small structures returned by STDCALL/CDECL functions, allocate structured result pointer and load structure from EDX:EAX
StructuredResultAddr := AllocateTempStorage(TypeSize(ResultType));
ConvertSmallStructureToPointer(StructuredResultAddr, TypeSize(ResultType));
end
else
begin
// Save structured result pointer to EAX (not all external functions do it themselves)
PushTempStoragePtr(StructuredResultAddr);
SaveStackTopToEAX;
end
else if Types[ResultType].Kind in [REALTYPE, SINGLETYPE] then
// STDCALL/CDECL functions generally return real result in ST(0), but we do it in EAX or EDX:EAX
MoveFunctionResultFromFPUToEDXEAX(ResultType);
end; // ConvertResultFromCToPascal
procedure ConvertResultFromPascalToC(const Signature: TSignature);
begin
with Signature do
if (ResultType <> 0) and (CallConv <> DEFAULTCONV) then
if (Types[ResultType].Kind in StructuredTypes) and (TypeSize(ResultType) <= 2 * SizeOf(LongInt)) then
// In STDCALL/CDECL functions, return small structure in EDX:EAX
ConvertPointerToSmallStructure(TypeSize(ResultType))
else if Types[ResultType].Kind in [REALTYPE, SINGLETYPE] then
// STDCALL/CDECL functions generally return real result in ST(0), but we do it in EAX or EDX:EAX
MoveFunctionResultFromEDXEAXToFPU(ResultType);
end; // ConvertResultFromCPascalToC
procedure CompileCall(IdentIndex: Integer);
var
TotalPascalParamSize, TotalCParamSize: Integer;
StructuredResultAddr: LongInt;
begin
TotalPascalParamSize := GetTotalParamSize(Ident[IdentIndex].Signature, FALSE, TRUE);
TotalCParamSize := GetTotalParamSize(Ident[IdentIndex].Signature, FALSE, FALSE);
CompileActualParameters(Ident[IdentIndex].Signature, StructuredResultAddr);
// Convert stack to C format
if (Ident[IdentIndex].Signature.CallConv <> DEFAULTCONV) and (TotalPascalParamSize > 0) then
MakeCStack(Ident[IdentIndex].Signature);
GenerateCall(Ident[IdentIndex].Address, BlockStackTop - 1, Ident[IdentIndex].NestingLevel);
// Free C stack for a CDECL function
if (Ident[IdentIndex].Signature.CallConv = CDECLCONV) and (TotalPascalParamSize > 0) then
DiscardStackTop(TotalCParamSize div SizeOf(LongInt));
// Free original stack
if (Ident[IdentIndex].Signature.CallConv <> DEFAULTCONV) and (TotalPascalParamSize > 0) then
DiscardStackTop(TotalPascalParamSize div SizeOf(LongInt));
// Treat special cases in STDCALL/CDECL functions
ConvertResultFromCToPascal(Ident[IdentIndex].Signature, StructuredResultAddr);
end; // CompileCall
procedure CompileMethodCall(ProcVarType: Integer);
var
MethodIndex: Integer;
StructuredResultAddr: LongInt;
begin
MethodIndex := Types[ProcVarType].MethodIdentIndex;
// Self pointer has already been passed as the first (hidden) argument
CompileActualParameters(Ident[MethodIndex].Signature, StructuredResultAddr);
GenerateCall(Ident[MethodIndex].Address, BlockStackTop - 1, Ident[MethodIndex].NestingLevel);
end; // CompileMethodCall
procedure CompileIndirectCall(ProcVarType: Integer);
var
TotalPascalParamSize, TotalCParamSize, CallAddrDepth: Integer;
StructuredResultAddr: LongInt;
begin
TotalPascalParamSize := GetTotalParamSize(Types[ProcVarType].Signature, Types[ProcVarType].SelfPointerOffset <> 0, TRUE);
TotalCParamSize := GetTotalParamSize(Types[ProcVarType].Signature, Types[ProcVarType].SelfPointerOffset <> 0, FALSE);
if Types[ProcVarType].SelfPointerOffset <> 0 then // Interface method found
begin
if Types[ProcVarType].Signature.CallConv <> DEFAULTCONV then
Error('STDCALL/CDECL is not allowed for methods');
// Push Self pointer as a first (hidden) VAR parameter
DuplicateStackTop;
GetFieldPtr(Types[ProcVarType].SelfPointerOffset);
DerefPtr(POINTERTYPEINDEX);
end;
CompileActualParameters(Types[ProcVarType].Signature, StructuredResultAddr);
// Convert stack to C format
if (Types[ProcVarType].Signature.CallConv <> DEFAULTCONV) and (TotalPascalParamSize > 0) then
begin
MakeCStack(Types[ProcVarType].Signature);
CallAddrDepth := TotalPascalParamSize + TotalCParamSize;
end
else
CallAddrDepth := TotalPascalParamSize;
GenerateIndirectCall(CallAddrDepth);
// Free C stack for a CDECL function
if (Types[ProcVarType].Signature.CallConv = CDECLCONV) and (TotalPascalParamSize > 0) then
DiscardStackTop(TotalCParamSize div SizeOf(LongInt));
// Free original stack
if (Types[ProcVarType].Signature.CallConv <> DEFAULTCONV) and (TotalPascalParamSize > 0) then
DiscardStackTop(TotalPascalParamSize div SizeOf(LongInt));
// Remove call address
DiscardStackTop(1);
// Treat special cases in STDCALL/CDECL functions
ConvertResultFromCToPascal(Types[ProcVarType].Signature, StructuredResultAddr);
end; // CompileIndirectCall
function CompileMethodOrProceduralVariableCall(var ValType: Integer; FunctionOnly, DesignatorOnly: Boolean): Boolean;
var
ResultType: Integer;
begin
if Types[ValType].Kind = METHODTYPE then
ResultType := Ident[Types[ValType].MethodIdentIndex].Signature.ResultType
else if Types[ValType].Kind = PROCEDURALTYPE then
ResultType := Types[ValType].Signature.ResultType
else
begin
ResultType := 0;
Error('Procedure or function expected');
end;
Result := FALSE;
if not DesignatorOnly or ((ResultType <> 0) and (Types[ResultType].Kind in StructuredTypes)) then
begin
if FunctionOnly and (ResultType = 0) then
Error('Function expected');
if Types[ValType].Kind = METHODTYPE then
CompileMethodCall(ValType)
else
CompileIndirectCall(ValType);
ValType := ResultType;
Result := TRUE;
end;
end; // CompileMethodOrProceduralVariableCall
procedure CompileFieldOrMethodInsideWith(var ValType: Integer; var IsConst: Boolean);
var
FieldIndex, MethodIndex: Integer;
RecType: Integer;
TempStorageAddr: Integer;
begin
AssertIdent;
FieldIndex := GetFieldInsideWith(TempStorageAddr, RecType, IsConst, Tok.Name);
if FieldIndex <> 0 then
begin
PushTempStoragePtr(TempStorageAddr);
DerefPtr(POINTERTYPEINDEX);
GetFieldPtr(Types[RecType].Field[FieldIndex]^.Offset);
ValType := Types[RecType].Field[FieldIndex]^.DataType;
Exit;
end;
MethodIndex := GetMethodInsideWith(TempStorageAddr, RecType, IsConst, Tok.Name);
if MethodIndex <> 0 then
begin
PushTempStoragePtr(TempStorageAddr);
DerefPtr(POINTERTYPEINDEX);
// Add new anonymous 'method' type
DeclareType(METHODTYPE);
Types[NumTypes].MethodIdentIndex := MethodIndex;
ValType := NumTypes;
Exit;
end;
ValType := 0;
end; // CompileFieldOrMethodInsideWith
procedure CompileSetConstructor(var ValType: Integer);
var
ElementType: Integer;
LibProcIdentIndex: Integer;
TempStorageAddr: Integer;
begin
// Add new anonymous type
DeclareType(SETTYPE);
Types[NumTypes].BaseType := ANYTYPEINDEX;
ValType := NumTypes;
// Allocate temporary storage
TempStorageAddr := AllocateTempStorage(TypeSize(ValType));
PushTempStoragePtr(TempStorageAddr);
// Initialize set
LibProcIdentIndex := GetIdent('INITSET');
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
// Compile constructor
LibProcIdentIndex := GetIdent('ADDTOSET');
NextTok;
if Tok.Kind <> CBRACKETTOK then
repeat
PushTempStoragePtr(TempStorageAddr);
CompileExpression(ElementType);
if Types[ValType].BaseType = ANYTYPEINDEX then
begin
if not (Types[ElementType].Kind in OrdinalTypes) then
Error('Ordinal type expected');
Types[ValType].BaseType := ElementType;
end
else
GetCompatibleType(ElementType, Types[ValType].BaseType);
if Tok.Kind = RANGETOK then
begin
NextTok;
CompileExpression(ElementType);
GetCompatibleType(ElementType, Types[ValType].BaseType);
end
else
PushConst(-1);
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(CBRACKETTOK);
PushTempStoragePtr(TempStorageAddr);
end; // CompileSetConstructor
function DereferencePointerAsDesignator(var ValType: Integer; MustDereferenceAnyPointer: Boolean): Boolean;
begin
// If a pointer-type result is immediately followed by dereferencing, treat it as a designator that has the pointer's base type
Result := FALSE;
if Types[ValType].Kind = POINTERTYPE then
if Types[ValType].BaseType <> ANYTYPEINDEX then
begin
if Tok.Kind = DEREFERENCETOK then
begin
ValType := Types[ValType].BaseType;
Result := TRUE;
NextTok;
end
else if MustDereferenceAnyPointer then
CheckTok(DEREFERENCETOK)
end
else if MustDereferenceAnyPointer then
Error('Typed pointer expected');
end; // DereferencePointerAsDesignator
function CompileSelectors(var ValType: Integer; BasicDesignatorIsStatement: Boolean = FALSE): Boolean;
var
FieldIndex, MethodIndex: Integer;
ArrayIndexType: Integer;
Field: PField;
begin
// A selector is only applicable to a memory location
// A function call can be part of a selector only if it returns an address (i.e. a structured result), not an immediate value
// All other calls are part of a factor or a statement
// Returns TRUE if constitutes a statement, i.e., ends with a function call
Result := BasicDesignatorIsStatement;
while Tok.Kind in [DEREFERENCETOK, OBRACKETTOK, PERIODTOK, OPARTOK] do
begin
Result := FALSE;
case Tok.Kind of
DEREFERENCETOK: // Pointer dereferencing
begin
if (Types[ValType].Kind <> POINTERTYPE) or (Types[ValType].BaseType = ANYTYPEINDEX) then
Error('Typed pointer expected');
DerefPtr(ValType);
ValType := Types[ValType].BaseType;
NextTok;
end;
OBRACKETTOK: // Array element access
begin
repeat
// Convert a pointer to an array if needed (C style)
if (Types[ValType].Kind = POINTERTYPE) and (Types[ValType].BaseType <> ANYTYPEINDEX) then
begin
DerefPtr(ValType);
// Add new anonymous type 0..0 for array index
DeclareType(SUBRANGETYPE);
Types[NumTypes].BaseType := INTEGERTYPEINDEX;
Types[NumTypes].Low := 0;
Types[NumTypes].High := 0;
// Add new anonymous type for array itself
DeclareType(ARRAYTYPE);
Types[NumTypes].BaseType := Types[ValType].BaseType;
Types[NumTypes].IndexType := NumTypes - 1;
ValType := NumTypes;
end;
if Types[ValType].Kind <> ARRAYTYPE then
Error('Array expected');
NextTok;
CompileExpression(ArrayIndexType); // Array index
GetCompatibleType(ArrayIndexType, Types[ValType].IndexType);
GetArrayElementPtr(ValType);
ValType := Types[ValType].BaseType;
until Tok.Kind <> COMMATOK;
EatTok(CBRACKETTOK);
end;
PERIODTOK: // Method or record field access
begin
NextTok;
AssertIdent;
// First search for a method
MethodIndex := GetMethodUnsafe(ValType, Tok.Name);
if MethodIndex <> 0 then
begin
// Add new anonymous 'method' type
DeclareType(METHODTYPE);
Types[NumTypes].MethodIdentIndex := MethodIndex;
ValType := NumTypes;
end
// If unsuccessful, search for a record field
else
begin
if not (Types[ValType].Kind in [RECORDTYPE, INTERFACETYPE]) then
Error('Record or interface expected');
FieldIndex := GetField(ValType, Tok.Name);
Field := Types[ValType].Field[FieldIndex];
GetFieldPtr(Field^.Offset);
ValType := Field^.DataType;
end;
NextTok;
end;
OPARTOK:
begin
if not CompileMethodOrProceduralVariableCall(ValType, TRUE, TRUE) then Break; // Not a designator
PushFunctionResult(ValType);
Result := TRUE;
end;
end; // case
end; // while
end; // CompileSelectors
function CompileBasicDesignator(var ValType: Integer; var IsConst: Boolean): Boolean;
var
ResultType: Integer;
IdentIndex: Integer;
begin
// A designator always designates a memory location
// A function call can be part of a designator only if it returns an address (i.e. a structured result or a pointer), not an immediate value
// All other calls are part of a factor or a statement
// Returns TRUE if constitutes a statement, i.e., ends with a function call
Result := FALSE;
IsConst := FALSE;
AssertIdent;
// First search among records in WITH blocks
CompileFieldOrMethodInsideWith(ValType, IsConst);
// If unsuccessful, search among ordinary identifiers
if ValType = 0 then
begin
IdentIndex := GetIdent(Tok.Name);
case Ident[IdentIndex].Kind of
FUNC:
begin
ResultType := Ident[IdentIndex].Signature.ResultType;
if not (Types[ResultType].Kind in StructuredTypes + [POINTERTYPE]) then // Only allow a function that returns a designator
Error('Function must return pointer or structured result');
NextTok;
CompileCall(IdentIndex);
PushFunctionResult(ResultType);
Result := TRUE;
ValType := ResultType;
if DereferencePointerAsDesignator(ValType, TRUE) then
Result := FALSE;
end;
VARIABLE:
begin
PushVarIdentPtr(IdentIndex);
ValType := Ident[IdentIndex].DataType;
IsConst := Ident[IdentIndex].IsTypedConst or (Ident[IdentIndex].PassMethod = CONSTPASSING);
// Structured CONST parameters are passed by reference, scalar CONST parameters are passed by value
if (Ident[IdentIndex].PassMethod = VARPASSING) or
((Ident[IdentIndex].PassMethod <> VALPASSING) and (Types[ValType].Kind in StructuredTypes) and Ident[IdentIndex].IsInCStack) or
((Ident[IdentIndex].PassMethod <> EMPTYPASSING) and (Types[ValType].Kind in StructuredTypes) and not Ident[IdentIndex].IsInCStack)
then
DerefPtr(POINTERTYPEINDEX);
NextTok;
end;
USERTYPE: // Type cast
begin
NextTok;
EatTok(OPARTOK);
CompileExpression(ValType);
EatTok(CPARTOK);
if not (Types[Ident[IdentIndex].DataType].Kind in StructuredTypes + [POINTERTYPE]) then // Only allow a typecast that returns a designator
Error('Typecast must return pointer or structured result');
if (Ident[IdentIndex].DataType <> ValType) and
not ((Types[Ident[IdentIndex].DataType].Kind in CastableTypes) and (Types[ValType].Kind in CastableTypes))
then
Error('Invalid typecast');
ValType := Ident[IdentIndex].DataType;
DereferencePointerAsDesignator(ValType, TRUE);
end
else
Error('Variable or function expected but ' + GetTokSpelling(Tok.Kind) + ' found');
end; // case
end
else
NextTok;
end; // CompileBasicDesignator
function CompileDesignator(var ValType: Integer; AllowConst: Boolean = TRUE): Boolean;
var
IsConst: Boolean;
begin
// Returns TRUE if constitutes a statement, i.e., ends with a function call
Result := CompileBasicDesignator(ValType, IsConst);
if IsConst and not AllowConst then
Error('Constant value cannot be modified');
Result := CompileSelectors(ValType, Result);
end; // CompileDesignator
procedure CompileFactor(var ValType: Integer);
procedure CompileDereferenceOrCall(var ValType: Integer);
begin
if Tok.Kind = OPARTOK then // Method or procedural variable call (parentheses are required even for empty parameter list)
begin
CompileMethodOrProceduralVariableCall(ValType, TRUE, FALSE);
PushFunctionResult(ValType);
end
else // Usual variable
if not (Types[ValType].Kind in StructuredTypes) then // Structured expressions are stored as pointers to them
DerefPtr(ValType);
ConvertRealToReal(REALTYPEINDEX, ValType); // Real expressions must be double, not single
end; // CompileDereferenceOrCall
var
IdentIndex: Integer;
NotOpTok: TToken;
begin // CompileFactor
case Tok.Kind of
IDENTTOK:
if FieldOrMethodInsideWithFound(Tok.Name) then // Record field or method inside a WITH block
begin
CompileDesignator(ValType);
CompileDereferenceOrCall(ValType);
end
else // Ordinary identifier
begin
IdentIndex := GetIdent(Tok.Name);
case Ident[IdentIndex].Kind of
GOTOLABEL:
Error('Expression expected but label ' + Ident[IdentIndex].Name + ' found');
PROC:
Error('Expression expected but procedure ' + Ident[IdentIndex].Name + ' found');
FUNC: // Function call
if Ident[IdentIndex].PredefProc <> EMPTYPROC then // Predefined function call
CompilePredefinedFunc(Ident[IdentIndex].PredefProc, ValType)
else // User-defined function call
begin
NextTok;
ValType := Ident[IdentIndex].Signature.ResultType;
CompileCall(IdentIndex);
PushFunctionResult(ValType);
ConvertRealToReal(REALTYPEINDEX, ValType); // Real expressions must be double, not single
if (Types[ValType].Kind in StructuredTypes) or DereferencePointerAsDesignator(ValType, FALSE) then
begin
CompileSelectors(ValType);
CompileDereferenceOrCall(ValType);
end;
end;
VARIABLE: // Variable
begin
CompileDesignator(ValType);
CompileDereferenceOrCall(ValType);
end;
CONSTANT: // Constant
begin
if Types[Ident[IdentIndex].DataType].Kind in StructuredTypes then
PushVarPtr(Ident[IdentIndex].Address, GLOBAL, 0, INITDATARELOC)
else if Types[Ident[IdentIndex].DataType].Kind = REALTYPE then
PushRealConst(Ident[IdentIndex].ConstVal.RealValue)
else
PushConst(Ident[IdentIndex].ConstVal.OrdValue);
ValType := Ident[IdentIndex].DataType;
NextTok;
if Types[Ident[IdentIndex].DataType].Kind in StructuredTypes then
begin
CompileSelectors(ValType);
CompileDereferenceOrCall(ValType);
end;
end;
USERTYPE: // Type cast
begin
NextTok;
EatTok(OPARTOK);
CompileExpression(ValType);
EatTok(CPARTOK);
if (Ident[IdentIndex].DataType <> ValType) and
not ((Types[Ident[IdentIndex].DataType].Kind in CastableTypes) and (Types[ValType].Kind in CastableTypes))
then
Error('Invalid typecast');
ValType := Ident[IdentIndex].DataType;
if (Types[ValType].Kind = POINTERTYPE) and (Types[Types[ValType].BaseType].Kind in StructuredTypes) then
begin
if DereferencePointerAsDesignator(ValType, FALSE) then
begin
CompileSelectors(ValType);
CompileDereferenceOrCall(ValType);
end
end
else
CompileSelectors(ValType);
end
else
Error('Internal fault: Illegal identifier');
end; // case Ident[IdentIndex].Kind
end; // else
ADDRESSTOK:
begin
NextTok;
if FieldOrMethodInsideWithFound(Tok.Name) then // Record field inside a WITH block
begin
CompileDesignator(ValType);
DeclareType(POINTERTYPE);
Types[NumTypes].BaseType := ValType;
end
else // Ordinary identifier
begin
IdentIndex := GetIdent(Tok.Name);
if Ident[IdentIndex].Kind in [PROC, FUNC] then
begin
if (Ident[IdentIndex].PredefProc <> EMPTYPROC) or (Ident[IdentIndex].Block <> 1) then
Error('Procedure or function cannot be predefined or nested');
PushRelocConst(Ident[IdentIndex].Address, CODERELOC); // To be resolved later when the code section origin is known
NextTok;
DeclareType(PROCEDURALTYPE);
Types[NumTypes].Signature := Ident[IdentIndex].Signature;
CopyParams(Types[NumTypes].Signature, Ident[IdentIndex].Signature);
end
else
begin
CompileDesignator(ValType);
DeclareType(POINTERTYPE);
Types[NumTypes].BaseType := ValType;
end;
end;
ValType := NumTypes;
end;
INTNUMBERTOK:
begin
PushConst(Tok.OrdValue);
ValType := INTEGERTYPEINDEX;
NextTok;
end;
REALNUMBERTOK:
begin
PushRealConst(Tok.RealValue);
ValType := REALTYPEINDEX;
NextTok;
end;
CHARLITERALTOK:
begin
PushConst(Tok.OrdValue);
ValType := CHARTYPEINDEX;
NextTok;
end;
STRINGLITERALTOK:
begin
PushVarPtr(Tok.StrAddress, GLOBAL, 0, INITDATARELOC);
ValType := STRINGTYPEINDEX;
NextTok;
end;
OPARTOK:
begin
NextTok;
CompileExpression(ValType);
EatTok(CPARTOK);
end;
NOTTOK:
begin
NotOpTok := Tok;
NextTok;
CompileFactor(ValType);
CheckOperator(NotOpTok, ValType);
GenerateUnaryOperator(NOTTOK, ValType);
end;
OBRACKETTOK:
CompileSetConstructor(ValType);
NILTOK:
begin
PushConst(0);
ValType := POINTERTYPEINDEX;
NextTok;
end
else
Error('Expression expected but ' + GetTokSpelling(Tok.Kind) + ' found');
end;// case
end;// CompileFactor
procedure CompileTerm(var ValType: Integer);
var
OpTok: TToken;
RightValType: Integer;
LibProcIdentIndex: Integer;
TempStorageAddr: Integer;
UseShortCircuit: Boolean;
begin
CompileFactor(ValType);
while Tok.Kind in MultiplicativeOperators do
begin
OpTok := Tok;
NextTok;
UseShortCircuit := (OpTok.Kind = ANDTOK) and (Types[ValType].Kind = BOOLEANTYPE);
if UseShortCircuit then
GenerateShortCircuitProlog(OpTok.Kind);
CompileFactor(RightValType);
// Try to convert integer to real
ConvertIntegerToReal(ValType, RightValType, 0);
ConvertIntegerToReal(RightValType, ValType, SizeOf(Double));
// Special case: real division of two integers
if OpTok.Kind = DIVTOK then
begin
ConvertIntegerToReal(REALTYPEINDEX, RightValType, 0);
ConvertIntegerToReal(REALTYPEINDEX, ValType, SizeOf(Double));
end;
// Special case: set intersection
if (OpTok.Kind = MULTOK) and (Types[ValType].Kind = SETTYPE) then
begin
ValType := GetCompatibleType(ValType, RightValType);
LibProcIdentIndex := GetIdent('SETINTERSECTION');
TempStorageAddr := AllocateTempStorage(TypeSize(ValType));
PushTempStoragePtr(TempStorageAddr);
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
PushTempStoragePtr(TempStorageAddr);
end
// General rule
else
begin
ValType := GetCompatibleType(ValType, RightValType);
CheckOperator(OpTok, ValType);
if UseShortCircuit then
GenerateShortCircuitEpilog
else
GenerateBinaryOperator(OpTok.Kind, ValType);
end;
end;// while
end;// CompileTerm
procedure CompileSimpleExpression(var ValType: Integer);
var
UnaryOpTok, OpTok: TToken;
RightValType: Integer;
LibProcIdentIndex: Integer;
TempStorageAddr: Integer;
UseShortCircuit: Boolean;
begin
UnaryOpTok := Tok;
if UnaryOpTok.Kind in UnaryOperators then
NextTok;
CompileTerm(ValType);
if UnaryOpTok.Kind in UnaryOperators then
CheckOperator(UnaryOpTok, ValType);
if UnaryOpTok.Kind = MINUSTOK then GenerateUnaryOperator(MINUSTOK, ValType); // Unary minus
while Tok.Kind in AdditiveOperators do
begin
OpTok := Tok;
NextTok;
UseShortCircuit := (OpTok.Kind = ORTOK) and (Types[ValType].Kind = BOOLEANTYPE);
if UseShortCircuit then
GenerateShortCircuitProlog(OpTok.Kind);
CompileTerm(RightValType);
// Try to convert integer to real
ConvertIntegerToReal(ValType, RightValType, 0);
ConvertIntegerToReal(RightValType, ValType, SizeOf(Double));
// Try to convert character to string
ConvertCharToString(ValType, RightValType, 0);
ConvertCharToString(RightValType, ValType, SizeOf(LongInt));
// Special case: string concatenation
if (OpTok.Kind = PLUSTOK) and IsString(ValType) and IsString(RightValType) then
begin
LibProcIdentIndex := GetIdent('CONCATSTR');
TempStorageAddr := AllocateTempStorage(TypeSize(STRINGTYPEINDEX));
PushTempStoragePtr(TempStorageAddr);
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
PushTempStoragePtr(TempStorageAddr);
ValType := STRINGTYPEINDEX;
end
// Special case: set union or difference
else if (OpTok.Kind in [PLUSTOK, MINUSTOK]) and (Types[ValType].Kind = SETTYPE) then
begin
ValType := GetCompatibleType(ValType, RightValType);
if OpTok.Kind = PLUSTOK then
LibProcIdentIndex := GetIdent('SETUNION')
else
LibProcIdentIndex := GetIdent('SETDIFFERENCE');
TempStorageAddr := AllocateTempStorage(TypeSize(ValType));
PushTempStoragePtr(TempStorageAddr);
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
PushTempStoragePtr(TempStorageAddr);
end
// General rule
else
begin
ValType := GetCompatibleType(ValType, RightValType);
CheckOperator(OpTok, ValType);
if UseShortCircuit then
GenerateShortCircuitEpilog
else
GenerateBinaryOperator(OpTok.Kind, ValType);
end;
end;// while
end;// CompileSimpleExpression
procedure CompileExpression(var ValType: Integer);
var
OpTok: TToken;
RightValType: Integer;
LibProcIdentIndex: Integer;
begin // CompileExpression
CompileSimpleExpression(ValType);
if Tok.Kind in RelationOperators then
begin
OpTok := Tok;
NextTok;
CompileSimpleExpression(RightValType);
// Try to convert integer to real
ConvertIntegerToReal(ValType, RightValType, 0);
ConvertIntegerToReal(RightValType, ValType, SizeOf(Double));
// Try to convert character to string
ConvertCharToString(ValType, RightValType, 0);
ConvertCharToString(RightValType, ValType, SizeOf(LongInt));
// Special case: string comparison
if IsString(ValType) and IsString(RightValType) then
begin
LibProcIdentIndex := GetIdent('COMPARESTR');
ValType := Ident[LibProcIdentIndex].Signature.ResultType;
RightValType := INTEGERTYPEINDEX;
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
PushFunctionResult(ValType);
PushConst(0);
end;
// Special case: set comparison
if (OpTok.Kind in [EQTOK, NETOK, GETOK, LETOK]) and (Types[ValType].Kind = SETTYPE) then
begin
GetCompatibleType(ValType, RightValType);
case OpTok.Kind of
GETOK: LibProcIdentIndex := GetIdent('TESTSUPERSET'); // Returns 1 if Val >= RightVal, -1 otherwise
LETOK: LibProcIdentIndex := GetIdent('TESTSUBSET'); // Returns -1 if Val <= RightVal, 1 otherwise
else LibProcIdentIndex := GetIdent('COMPARESETS'); // Returns 0 if Val = RightVal, 1 otherwise
end;
ValType := Ident[LibProcIdentIndex].Signature.ResultType;
RightValType := INTEGERTYPEINDEX;
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
PushFunctionResult(ValType);
PushConst(0);
end;
GetCompatibleType(ValType, RightValType);
CheckOperator(OpTok, ValType);
ValType := BOOLEANTYPEINDEX;
GenerateRelation(OpTok.Kind, RightValType);
end
else if Tok.Kind = INTOK then
begin
NextTok;
CompileSimpleExpression(RightValType);
if Types[RightValType].Kind <> SETTYPE then
Error('Set expected');
if Types[RightValType].BaseType <> ANYTYPEINDEX then
GetCompatibleType(ValType, Types[RightValType].BaseType)
else if not (Types[ValType].Kind in OrdinalTypes) then
Error('Ordinal type expected');
LibProcIdentIndex := GetIdent('INSET');
ValType := Ident[LibProcIdentIndex].Signature.ResultType;
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
PushFunctionResult(ValType);
end;
end;// CompileExpression
procedure CompileStatementList(LoopNesting: Integer);
begin
CompileStatement(LoopNesting);
while Tok.Kind = SEMICOLONTOK do
begin
NextTok;
CompileStatement(LoopNesting);
end;
end; // CompileStatementList
procedure CompileCompoundStatement(LoopNesting: Integer);
begin
EatTok(BEGINTOK);
CompileStatementList(LoopNesting);
EatTok(ENDTOK);
end; // CompileCompoundStatement
procedure CompileStatement(LoopNesting: Integer);
procedure CompileLabel;
var
LabelIndex: Integer;
begin
if Tok.Kind = IDENTTOK then
begin
LabelIndex := GetIdentUnsafe(Tok.Name);
if LabelIndex <> 0 then
if Ident[LabelIndex].Kind = GOTOLABEL then
begin
if Ident[LabelIndex].Block <> BlockStack[BlockStackTop].Index then
Error('Label is not declared in current procedure');
Ident[LabelIndex].Address := GetCodeSize;
Ident[LabelIndex].IsUnresolvedForward := FALSE;
Ident[LabelIndex].ForLoopNesting := ForLoopNesting;
NextTok;
EatTok(COLONTOK);
end;
end;
end; // CompileLabel
procedure CompileAssignment(DesignatorType: Integer);
var
ExpressionType: Integer;
LibProcIdentIndex: Integer;
begin
NextTok;
CompileExpression(ExpressionType);
// Try to convert integer to double, single to double or double to single
ConvertIntegerToReal(DesignatorType, ExpressionType, 0);
ConvertRealToReal(DesignatorType, ExpressionType);
// Try to convert character to string
ConvertCharToString(DesignatorType, ExpressionType, 0);
// Try to convert string to pointer to character
ConvertStringToPChar(DesignatorType, ExpressionType);
// Try to convert a concrete type to an interface type
ConvertToInterface(DesignatorType, ExpressionType);
GetCompatibleType(DesignatorType, ExpressionType);
if IsString(DesignatorType) then
begin
LibProcIdentIndex := GetIdent('ASSIGNSTR');
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
end
else if Types[DesignatorType].Kind in StructuredTypes then
GenerateStructuredAssignment(DesignatorType)
else
GenerateAssignment(DesignatorType);
end; // CompileAssignment
procedure CompileAssignmentOrCall(DesignatorType: Integer; DesignatorIsStatement: Boolean);
begin
if Tok.Kind = OPARTOK then // Method or procedural variable call (parentheses are required even for empty parameter list)
CompileMethodOrProceduralVariableCall(DesignatorType, FALSE, FALSE)
else if DesignatorIsStatement then // Optional assignment if designator already ends with a function call
if Tok.Kind = ASSIGNTOK then
CompileAssignment(DesignatorType)
else
DiscardStackTop(1) // Nothing to do - remove designator
else // Mandatory assignment
begin
CheckTok(ASSIGNTOK);
CompileAssignment(DesignatorType)
end;
end; // CompileAssignmentOrCall
procedure CompileIfStatement(LoopNesting: Integer);
var
ExpressionType: Integer;
begin
NextTok;
CompileExpression(ExpressionType);
GetCompatibleType(ExpressionType, BOOLEANTYPEINDEX);
EatTok(THENTOK);
GenerateIfCondition; // Satisfied if expression is not zero
GenerateIfProlog;
CompileStatement(LoopNesting);
if Tok.Kind = ELSETOK then
begin
NextTok;
GenerateElseProlog;
CompileStatement(LoopNesting);
end;
GenerateIfElseEpilog;
end; // CompileIfStatement
procedure CompileCaseStatement(LoopNesting: Integer);
var
SelectorType, ConstValType: Integer;
NumCaseStatements: Integer;
ConstVal, ConstVal2: TConst;
begin
NextTok;
CompileExpression(SelectorType);
if not (Types[SelectorType].Kind in OrdinalTypes) then
Error('Ordinal variable expected as CASE selector');
EatTok(OFTOK);
GenerateCaseProlog;
NumCaseStatements := 0;
repeat // Loop over all cases
repeat // Loop over all constants for the current case
CompileConstExpression(ConstVal, ConstValType);
GetCompatibleType(ConstValType, SelectorType);
if Tok.Kind = RANGETOK then // Range check
begin
NextTok;
CompileConstExpression(ConstVal2, ConstValType);
GetCompatibleType(ConstValType, SelectorType);
GenerateCaseRangeCheck(ConstVal.OrdValue, ConstVal2.OrdValue);
end
else
GenerateCaseEqualityCheck(ConstVal.OrdValue); // Equality check
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(COLONTOK);
GenerateCaseStatementProlog;
CompileStatement(LoopNesting);
GenerateCaseStatementEpilog;
Inc(NumCaseStatements);
if (Tok.Kind = ELSETOK) or (Tok.Kind = ENDTOK) then Break;
EatTok(SEMICOLONTOK);
until (Tok.Kind = ELSETOK) or (Tok.Kind = ENDTOK);
// Default statements
if Tok.Kind = ELSETOK then
begin
NextTok;
CompileStatementList(LoopNesting);
end;
EatTok(ENDTOK);
GenerateCaseEpilog(NumCaseStatements);
end; // CompileCaseStatement
procedure CompileWhileStatement(LoopNesting: Integer);
var
ExpressionType: Integer;
begin
SaveCodePos; // Save return address used by GenerateWhileEpilog
NextTok;
CompileExpression(ExpressionType);
GetCompatibleType(ExpressionType, BOOLEANTYPEINDEX);
EatTok(DOTOK);
GenerateBreakProlog(LoopNesting);
GenerateContinueProlog(LoopNesting);
GenerateWhileCondition; // Satisfied if expression is not zero
GenerateWhileProlog;
CompileStatement(LoopNesting);
GenerateContinueEpilog(LoopNesting);
GenerateWhileEpilog;
GenerateBreakEpilog(LoopNesting);
end; // CompileWhileStatement
procedure CompileRepeatStatement(LoopNesting: Integer);
var
ExpressionType: Integer;
begin
GenerateBreakProlog(LoopNesting);
GenerateContinueProlog(LoopNesting);
GenerateRepeatProlog;
NextTok;
CompileStatementList(LoopNesting);
EatTok(UNTILTOK);
GenerateContinueEpilog(LoopNesting);
CompileExpression(ExpressionType);
GetCompatibleType(ExpressionType, BOOLEANTYPEINDEX);
GenerateRepeatCondition;
GenerateRepeatEpilog;
GenerateBreakEpilog(LoopNesting);
end; // CompileRepeatStatement
procedure CompileForStatement(LoopNesting: Integer);
var
CounterIndex: Integer;
ExpressionType: Integer;
Down: Boolean;
begin
NextTok;
AssertIdent;
CounterIndex := GetIdent(Tok.Name);
if (Ident[CounterIndex].Kind <> VARIABLE) or
((Ident[CounterIndex].NestingLevel <> 1) and (Ident[CounterIndex].NestingLevel <> BlockStackTop)) or
(Ident[CounterIndex].PassMethod <> EMPTYPASSING) then
Error('Simple local variable expected as FOR loop counter');
if not (Types[Ident[CounterIndex].DataType].Kind in OrdinalTypes) then
Error('Ordinal variable expected as FOR loop counter');
PushVarIdentPtr(CounterIndex);
NextTok;
EatTok(ASSIGNTOK);
// Initial counter value
CompileExpression(ExpressionType);
GetCompatibleType(ExpressionType, Ident[CounterIndex].DataType);
if not (Tok.Kind in [TOTOK, DOWNTOTOK]) then
CheckTok(TOTOK);
Down := Tok.Kind = DOWNTOTOK;
NextTok;
// Final counter value
CompileExpression(ExpressionType);
GetCompatibleType(ExpressionType, Ident[CounterIndex].DataType);
// Assign initial value to the counter, compute and save the total number of iterations
GenerateForAssignmentAndNumberOfIterations(Ident[CounterIndex].DataType, Down);
// Save return address used by GenerateForEpilog
SaveCodePos;
// Check the remaining number of iterations
GenerateForCondition;
EatTok(DOTOK);
GenerateBreakProlog(LoopNesting);
GenerateContinueProlog(LoopNesting);
GenerateForProlog;
CompileStatement(LoopNesting);
GenerateContinueEpilog(LoopNesting);
PushVarIdentPtr(CounterIndex);
GenerateForEpilog(Ident[CounterIndex].DataType, Down);
GenerateBreakEpilog(LoopNesting);
// Pop and discard the remaining number of iterations (i.e. zero)
DiscardStackTop(1);
end; // CompileForStatement
procedure CompileGotoStatement(LoopNesting: Integer);
var
LabelIndex: Integer;
begin
NextTok;
AssertIdent;
LabelIndex := GetIdent(Tok.Name);
if Ident[LabelIndex].Kind <> GOTOLABEL then
Error('Label expected');
if Ident[LabelIndex].Block <> BlockStack[BlockStackTop].Index then
Error('Label is not declared in current procedure');
GenerateGoto(LabelIndex);
NextTok;
end; // CompileGotoStatement
procedure CompileWithStatement(LoopNesting: Integer);
var
DesignatorType: Integer;
DeltaWithNesting: Integer;
TempStorageAddr: Integer;
IsConst: Boolean;
begin
NextTok;
DeltaWithNesting := 0;
repeat
// Save designator pointer to temporary storage
TempStorageAddr := AllocateTempStorage(TypeSize(POINTERTYPEINDEX));
PushTempStoragePtr(TempStorageAddr);
CompileBasicDesignator(DesignatorType, IsConst);
CompileSelectors(DesignatorType);
if not (Types[DesignatorType].Kind in [RECORDTYPE, INTERFACETYPE]) then
Error('Record or interface expected');
GenerateAssignment(POINTERTYPEINDEX);
// Save designator info
Inc(DeltaWithNesting);
Inc(WithNesting);
if WithNesting > MAXWITHNESTING then
Error('Maximum WITH block nesting exceeded');
WithStack[WithNesting].TempPointer := TempStorageAddr;
WithStack[WithNesting].DataType := DesignatorType;
WithStack[WithNesting].IsConst := IsConst;
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(DOTOK);
CompileStatement(LoopNesting);
WithNesting := WithNesting - DeltaWithNesting;
end; // CompileWithStatement
function IsCurrentOrOuterFunc(FuncIdentIndex: Integer): Boolean;
var
BlockStackIndex: Integer;
begin
if Ident[FuncIdentIndex].Kind = FUNC then
for BlockStackIndex := BlockStackTop downto 1 do
if BlockStack[BlockStackIndex].Index = Ident[FuncIdentIndex].ProcAsBlock then
begin
Result := TRUE;
Exit;
end;
Result := FALSE;
end; // IsCurrentOrOuterFunc
var
IdentIndex: Integer;
DesignatorType: Integer;
DesignatorIsStatement: Boolean;
begin // CompileStatement
CompileLabel;
case Tok.Kind of
IDENTTOK:
begin
if FieldOrMethodInsideWithFound(Tok.Name) then // Record field or method inside a WITH block
begin
DesignatorIsStatement := CompileDesignator(DesignatorType, FALSE);
CompileAssignmentOrCall(DesignatorType, DesignatorIsStatement);
end
else // Ordinary identifier
begin
IdentIndex := GetIdent(Tok.Name);
case Ident[IdentIndex].Kind of
VARIABLE, USERTYPE: // Assignment or procedural variable call
begin
DesignatorIsStatement := CompileDesignator(DesignatorType, FALSE);
CompileAssignmentOrCall(DesignatorType, DesignatorIsStatement);
end;
PROC, FUNC: // Procedure or function call (returned result discarded)
if Ident[IdentIndex].PredefProc <> EMPTYPROC then // Predefined procedure
begin
if Ident[IdentIndex].Kind <> PROC then
Error('Procedure expected but predefined function ' + Ident[IdentIndex].Name + ' found');
CompilePredefinedProc(Ident[IdentIndex].PredefProc, LoopNesting)
end
else // User-defined procedure or function
begin
NextTok;
if Tok.Kind = ASSIGNTOK then // Special case: assignment to a function name
begin
if not IsCurrentOrOuterFunc(IdentIndex) then
Error('Function name expected but ' + Ident[IdentIndex].Name + ' found');
// Push pointer to Result
PushVarIdentPtr(Ident[IdentIndex].ResultIdentIndex);
DesignatorType := Ident[Ident[IdentIndex].ResultIdentIndex].DataType;
if Ident[Ident[IdentIndex].ResultIdentIndex].PassMethod = VARPASSING then
DerefPtr(POINTERTYPEINDEX);
CompileAssignment(DesignatorType);
end
else // General rule: procedure or function call
begin
CompileCall(IdentIndex);
DesignatorType := Ident[IdentIndex].Signature.ResultType;
if (Ident[IdentIndex].Kind = FUNC) and (Tok.Kind in [DEREFERENCETOK, OBRACKETTOK, PERIODTOK, OPARTOK]) and
((Types[DesignatorType].Kind in StructuredTypes) or DereferencePointerAsDesignator(DesignatorType, FALSE))
then
begin
PushFunctionResult(DesignatorType);
DesignatorIsStatement := CompileSelectors(DesignatorType, TRUE);
CompileAssignmentOrCall(DesignatorType, DesignatorIsStatement);
end;
end;
end;
else
Error('Statement expected but ' + Ident[IdentIndex].Name + ' found');
end // case Ident[IdentIndex].Kind
end; // else
end;
BEGINTOK:
CompileCompoundStatement(LoopNesting);
IFTOK:
CompileIfStatement(LoopNesting);
CASETOK:
CompileCaseStatement(LoopNesting);
WHILETOK:
CompileWhileStatement(LoopNesting + 1);
REPEATTOK:
CompileRepeatStatement(LoopNesting + 1);
FORTOK:
CompileForStatement(LoopNesting + 1);
GOTOTOK:
CompileGotoStatement(LoopNesting);
WITHTOK:
CompileWithStatement(LoopNesting);
end;// case
end;// CompileStatement
procedure CompileType(var DataType: Integer);
procedure CompileEnumeratedType(var DataType: Integer);
var
ConstIndex: Integer;
begin
// Add new anonymous type
DeclareType(ENUMERATEDTYPE);
DataType := NumTypes;
// Compile enumeration constants
ConstIndex := 0;
NextTok;
repeat
AssertIdent;
DeclareIdent(Tok.Name, CONSTANT, 0, FALSE, DataType, EMPTYPASSING, ConstIndex, 0.0, '', [], EMPTYPROC, '', 0);
Inc(ConstIndex);
if ConstIndex > MAXENUMELEMENTS - 1 then
Error('Too many enumeration elements');
NextTok;
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(CPARTOK);
Types[DataType].Low := 0;
Types[DataType].High := ConstIndex - 1;
end; // CompileEnumeratedType
procedure CompileTypedPointerType(var DataType: Integer);
var
NestedDataType: Integer;
begin
// Add new anonymous type
DeclareType(POINTERTYPE);
DataType := NumTypes;
// Compile pointer base type
NextTok;
CompileTypeIdent(NestedDataType, TRUE);
Types[DataType].BaseType := NestedDataType;
end; // CompileTypedPointerType
procedure CompileArrayType(var DataType: Integer);
var
ArrType, IndexType, NestedDataType: Integer;
begin
NextTok;
EatTok(OBRACKETTOK);
DataType := NumTypes + 1;
repeat
// Add new anonymous type
DeclareType(ARRAYTYPE);
Types[NumTypes].IsOpenArray := FALSE;
ArrType := NumTypes;
CompileType(IndexType);
if not (Types[IndexType].Kind in OrdinalTypes) then
Error('Ordinal type expected');
Types[ArrType].IndexType := IndexType;
if Tok.Kind <> COMMATOK then Break;
Types[ArrType].BaseType := NumTypes + 1;
NextTok;
until FALSE;
EatTok(CBRACKETTOK);
EatTok(OFTOK);
CompileType(NestedDataType);
Types[ArrType].BaseType := NestedDataType;
end; // CompileArrayType
procedure CompileRecordOrInterfaceType(var DataType: Integer; IsInterfaceType: Boolean);
procedure DeclareField(const FieldName: TString; RecType, FieldType: Integer; var NextFieldOffset: Integer);
var
i, FieldTypeSize: Integer;
begin
for i := 1 to Types[RecType].NumFields do
if Types[RecType].Field[i]^.Name = FieldName then
Error('Duplicate field ' + FieldName);
// Add new field
Inc(Types[RecType].NumFields);
if Types[RecType].NumFields > MAXFIELDS then
Error('Too many fields');
New(Types[RecType].Field[Types[RecType].NumFields]);
with Types[RecType].Field[Types[RecType].NumFields]^ do
begin
Name := FieldName;
DataType := FieldType;
Offset := NextFieldOffset;
end;
// For interfaces, save Self pointer offset from the procedural field
if Types[RecType].Kind = INTERFACETYPE then
Types[FieldType].SelfPointerOffset := -NextFieldOffset;
FieldTypeSize := TypeSize(FieldType);
if FieldTypeSize > HighBound(INTEGERTYPEINDEX) - NextFieldOffset then
Error('Type size is too large');
NextFieldOffset := NextFieldOffset + FieldTypeSize;
end; // DeclareField
procedure CompileFixedFields(RecType: Integer; var NextFieldOffset: Integer);
var
FieldInListName: array [1..MAXFIELDS] of TString;
NumFieldsInList, FieldInListIndex: Integer;
FieldType: Integer;
begin
while not (Tok.Kind in [CASETOK, ENDTOK, CPARTOK]) do
begin
NumFieldsInList := 0;
repeat
AssertIdent;
Inc(NumFieldsInList);
if NumFieldsInList > MAXFIELDS then
Error('Too many fields');
FieldInListName[NumFieldsInList] := Tok.Name;
NextTok;
if (Tok.Kind <> COMMATOK) or IsInterfaceType then Break;
NextTok;
until FALSE;
EatTok(COLONTOK);
CompileType(FieldType);
if IsInterfaceType and (Types[FieldType].Kind <> PROCEDURALTYPE) then
Error('Non-procedural fields are not allowed in interfaces');
for FieldInListIndex := 1 to NumFieldsInList do
DeclareField(FieldInListName[FieldInListIndex], DataType, FieldType, NextFieldOffset);
if Tok.Kind <> SEMICOLONTOK then Break;
NextTok;
end; // while
end; // CompileFixedFields
procedure CompileFields(RecType: Integer; var NextFieldOffset: Integer);
var
TagName: TString;
TagVal: TConst;
TagType, TagValType: Integer;
TagTypeIdentIndex: Integer;
VariantStartOffset: Integer;
begin
// Fixed fields
CompileFixedFields(DataType, NextFieldOffset);
// Variant fields
if (Tok.Kind = CASETOK) and not IsInterfaceType then
begin
NextTok;
// Tag field
AssertIdent;
TagTypeIdentIndex := GetIdentUnsafe(Tok.Name);
if (TagTypeIdentIndex <> 0) and (Ident[TagTypeIdentIndex].Kind = USERTYPE) then // Type name found
begin
TagType := Ident[TagTypeIdentIndex].DataType;
NextTok;
end
else // Field name found
begin
TagName := Tok.Name;
NextTok;
EatTok(COLONTOK);
CompileType(TagType);
DeclareField(TagName, DataType, TagType, NextFieldOffset);
end;
if not (Types[TagType].Kind in OrdinalTypes) then
Error('Ordinal type expected');
VariantStartOffset := NextFieldOffset;
EatTok(OFTOK);
// Variants
repeat
repeat
CompileConstExpression(TagVal, TagValType);
GetCompatibleType(TagType, TagValType);
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(COLONTOK);
EatTok(OPARTOK);
NextFieldOffset := VariantStartOffset;
CompileFields(DataType, NextFieldOffset);
EatTok(CPARTOK);
if (Tok.Kind = CPARTOK) or (Tok.Kind = ENDTOK) then Break;
EatTok(SEMICOLONTOK);
until (Tok.Kind = CPARTOK) or (Tok.Kind = ENDTOK);
end; // if
end; // CompileFields
var
NextFieldOffset: Integer;
begin // CompileRecordOrInterfaceType
NextFieldOffset := 0;
// Add new anonymous type
if IsInterfaceType then
DeclareType(INTERFACETYPE)
else
DeclareType(RECORDTYPE);
Types[NumTypes].NumFields := 0;
DataType := NumTypes;
// Declare hidden Self pointer for interfaces
if IsInterfaceType then
DeclareField('SELF', DataType, POINTERTYPEINDEX, NextFieldOffset);
NextTok;
CompileFields(DataType, NextFieldOffset);
EatTok(ENDTOK);
end; // CompileRecordOrInterfaceType
procedure CompileSetType(var DataType: Integer);
var
NestedDataType: Integer;
begin
// Add new anonymous type
DeclareType(SETTYPE);
DataType := NumTypes;
NextTok;
EatTok(OFTOK);
CompileType(NestedDataType);
if (LowBound(NestedDataType) < 0) or (HighBound(NestedDataType) > MAXSETELEMENTS - 1) then
Error('Too many set elements');
Types[DataType].BaseType := NestedDataType;
end; // CompileSetType
procedure CompileStringType(var DataType: Integer);
var
LenConstVal: TConst;
LenType, IndexType: Integer;
begin
NextTok;
if Tok.Kind = OBRACKETTOK then
begin
NextTok;
CompileConstExpression(LenConstVal, LenType);
if not (Types[LenType].Kind in IntegerTypes) then
Error('Integer type expected');
if (LenConstVal.OrdValue <= 0) or (LenConstVal.OrdValue > MAXSTRLENGTH) then
Error('Illegal string length');
// Add new anonymous type: 1..Len + 1
DeclareType(SUBRANGETYPE);
IndexType := NumTypes;
Types[IndexType].BaseType := LenType;
Types[IndexType].Low := 1;
Types[IndexType].High := LenConstVal.OrdValue + 1;
// Add new anonymous type: array [1..Len + 1] of Char
DeclareType(ARRAYTYPE);
DataType := NumTypes;
Types[DataType].BaseType := CHARTYPEINDEX;
Types[DataType].IndexType := IndexType;
Types[DataType].IsOpenArray := FALSE;
EatTok(CBRACKETTOK);
end
else
DataType := STRINGTYPEINDEX;
end; // CompileStringType
procedure CompileFileType(var DataType: Integer);
var
NestedDataType: Integer;
begin
NextTok;
if Tok.Kind = OFTOK then // Typed file
begin
NextTok;
CompileType(NestedDataType);
if Types[NestedDataType].Kind = FILETYPE then
Error('File of files is not allowed');
// Add new anonymous type
DeclareType(FILETYPE);
Types[NumTypes].BaseType := NestedDataType;
DataType := NumTypes;
end
else // Untyped/text file
DataType := FILETYPEINDEX;
end; // CompileFileType
procedure CompileSubrangeType(var DataType: Integer);
var
ConstVal: TConst;
LowBoundType, HighBoundType: Integer;
begin
// Add new anonymous type
DeclareType(SUBRANGETYPE);
DataType := NumTypes;
CompileConstExpression(ConstVal, LowBoundType); // Subrange lower bound
if not (Types[LowBoundType].Kind in OrdinalTypes + [SUBRANGETYPE]) then
Error('Ordinal type expected');
Types[DataType].Low := ConstVal.OrdValue;
EatTok(RANGETOK);
CompileConstExpression(ConstVal, HighBoundType); // Subrange upper bound
if not (Types[HighBoundType].Kind in OrdinalTypes + [SUBRANGETYPE]) then
Error('Ordinal type expected');
Types[DataType].High := ConstVal.OrdValue;
GetCompatibleType(LowBoundType, HighBoundType);
if Types[DataType].High < Types[DataType].Low then
Error('Illegal subrange bounds');
Types[DataType].BaseType := LowBoundType;
end; // CompileSubrangeType
procedure CompileProceduralType(var DataType: Integer; IsFunction: Boolean);
begin
DeclareType(PROCEDURALTYPE);
Types[NumTypes].MethodIdentIndex := 0;
DataType := NumTypes;
NextTok;
CompileFormalParametersAndResult(IsFunction, Types[DataType].Signature);
end; // CompileProceduralType
var
IdentIndex: LongInt;
TypeNameGiven: Boolean;
begin // CompileType
if Tok.Kind = PACKEDTOK then // PACKED has no effect
begin
NextTok;
if not (Tok.Kind in [ARRAYTOK, RECORDTOK, INTERFACETOK, SETTOK, FILETOK]) then
Error('PACKED is not allowed here');
end;
case Tok.Kind of
OPARTOK:
CompileEnumeratedType(DataType);
DEREFERENCETOK:
CompileTypedPointerType(DataType);
ARRAYTOK:
CompileArrayType(DataType);
RECORDTOK, INTERFACETOK:
CompileRecordOrInterfaceType(DataType, Tok.Kind = INTERFACETOK);
SETTOK:
CompileSetType(DataType);
STRINGTOK:
CompileStringType(DataType);
FILETOK:
CompileFileType(DataType);
PROCEDURETOK, FUNCTIONTOK:
CompileProceduralType(DataType, Tok.Kind = FUNCTIONTOK)
else // Subrange or type name
TypeNameGiven := FALSE;
IdentIndex := 0;
if Tok.Kind = IDENTTOK then
begin
IdentIndex := GetIdent(Tok.Name);
if Ident[IdentIndex].Kind = USERTYPE then TypeNameGiven := TRUE;
end;
if TypeNameGiven then // Type name
begin
DataType := Ident[IdentIndex].DataType;
NextTok;
end
else // Subrange
CompileSubrangeType(DataType);
end; // case
end;// CompileType
procedure CompileBlock(BlockIdentIndex: Integer);
procedure ResolveForwardReferences;
var
TypeIndex, TypeIdentIndex, FieldIndex: Integer;
DataType: Integer;
begin
for TypeIndex := 1 to NumTypes do
if Types[TypeIndex].Kind = FORWARDTYPE then
begin
TypeIdentIndex := GetIdent(Types[TypeIndex].TypeIdentName);
if Ident[TypeIdentIndex].Kind <> USERTYPE then
Error('Type name expected');
// Forward reference resolution
DataType := Ident[TypeIdentIndex].DataType;
Types[TypeIndex] := Types[DataType];
Types[TypeIndex].AliasType := DataType;
if Types[DataType].Kind in [RECORDTYPE, INTERFACETYPE] then
for FieldIndex := 1 to Types[DataType].NumFields do
begin
New(Types[TypeIndex].Field[FieldIndex]);
Types[TypeIndex].Field[FieldIndex]^ := Types[DataType].Field[FieldIndex]^;
end;
end; // if
end; // ResolveForwardReferences
procedure CompileInitializer(InitializedDataOffset: LongInt; ConstType: Integer);
var
ConstVal: TConst;
ConstValType: Integer;
NumElements, ElementIndex, FieldIndex: Integer;
begin
// Numbers
if Types[ConstType].Kind in OrdinalTypes + [REALTYPE, SINGLETYPE] then
begin
CompileConstExpression(ConstVal, ConstValType);
// Try to convert integer to double or double to single
ConvertConstIntegerToReal(ConstType, ConstValType, ConstVal);
ConvertConstRealToReal(ConstType, ConstValType, ConstVal);
GetCompatibleType(ConstType, ConstValType);
if Types[ConstType].Kind = REALTYPE then
Move(ConstVal.RealValue, InitializedGlobalData[InitializedDataOffset], TypeSize(ConstType))
else if Types[ConstType].Kind = SINGLETYPE then
Move(ConstVal.SingleValue, InitializedGlobalData[InitializedDataOffset], TypeSize(ConstType))
else
Move(ConstVal.OrdValue, InitializedGlobalData[InitializedDataOffset], TypeSize(ConstType));
end
// Arrays
else if Types[ConstType].Kind = ARRAYTYPE then
begin
if IsString(ConstType) and (Tok.Kind <> OPARTOK) then // Special case: strings
begin
CompileConstExpression(ConstVal, ConstValType);
ConvertConstCharToString(ConstType, ConstValType, ConstVal);
GetCompatibleType(ConstType, ConstValType);
if Length(ConstVal.StrValue) > TypeSize(ConstType) - 1 then
Error('String is too long');
DefineStaticString(ConstVal.StrValue, InitializedDataOffset, InitializedDataOffset);
end
else // General rule
begin
EatTok(OPARTOK);
NumElements := HighBound(Types[ConstType].IndexType) - LowBound(Types[ConstType].IndexType) + 1;
for ElementIndex := 1 to NumElements do
begin
CompileInitializer(InitializedDataOffset, Types[ConstType].BaseType);
InitializedDataOffset := InitializedDataOffset + TypeSize(Types[ConstType].BaseType);
if ElementIndex < NumElements then
EatTok(COMMATOK)
else
EatTok(CPARTOK);
end; // for
end; // else
end
// Records
else if Types[ConstType].Kind = RECORDTYPE then
begin
EatTok(OPARTOK);
repeat
AssertIdent;
FieldIndex := GetField(ConstType, Tok.Name);
NextTok;
EatTok(COLONTOK);
CompileInitializer(InitializedDataOffset + Types[ConstType].Field[FieldIndex]^.Offset, Types[ConstType].Field[FieldIndex]^.DataType);
if Tok.Kind <> SEMICOLONTOK then Break;
NextTok;
until FALSE;
EatTok(CPARTOK);
end
// Sets
else if Types[ConstType].Kind = SETTYPE then
begin
CompileConstExpression(ConstVal, ConstValType);
GetCompatibleType(ConstType, ConstValType);
DefineStaticSet(ConstVal.SetValue, InitializedDataOffset, InitializedDataOffset);
end
else
Error('Illegal type');
end; // CompileInitializer
procedure CompileLabelDeclarations;
begin
repeat
AssertIdent;
DeclareIdent(Tok.Name, GOTOLABEL, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
NextTok;
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(SEMICOLONTOK);
end; // CompileLabelDeclarations
procedure CompileConstDeclarations;
procedure CompileUntypedConstDeclaration(var NameTok: TToken);
var
ConstVal: TConst;
ConstValType: Integer;
begin
EatTok(EQTOK);
CompileConstExpression(ConstVal, ConstValType);
DeclareIdent(NameTok.Name, CONSTANT, 0, FALSE, ConstValType, EMPTYPASSING, ConstVal.OrdValue, ConstVal.RealValue, ConstVal.StrValue, ConstVal.SetValue, EMPTYPROC, '', 0);
end; // CompileUntypedConstDeclaration;
procedure CompileTypedConstDeclaration(var NameTok: TToken);
var
ConstType: Integer;
begin
EatTok(COLONTOK);
CompileType(ConstType);
DeclareIdent(NameTok.Name, CONSTANT, 0, FALSE, ConstType, VARPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
EatTok(EQTOK);
CompileInitializer(Ident[NumIdent].Address, ConstType);
end; // CompileTypedConstDeclaration
var
NameTok: TToken;
begin // CompileConstDeclarations
repeat
AssertIdent;
NameTok := Tok;
NextTok;
if Tok.Kind = EQTOK then
CompileUntypedConstDeclaration(NameTok)
else
CompileTypedConstDeclaration(NameTok);
EatTok(SEMICOLONTOK);
until Tok.Kind <> IDENTTOK;
end; // CompileConstDeclarations
procedure CompileTypeDeclarations;
var
NameTok: TToken;
VarType: Integer;
begin
repeat
AssertIdent;
NameTok := Tok;
NextTok;
EatTok(EQTOK);
CompileType(VarType);
DeclareIdent(NameTok.Name, USERTYPE, 0, FALSE, VarType, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
EatTok(SEMICOLONTOK);
until Tok.Kind <> IDENTTOK;
ResolveForwardReferences;
end; // CompileTypeDeclarations
procedure CompileVarDeclarations;
var
IdentInListName: array [1..MAXPARAMS] of TString;
NumIdentInList, IdentInListIndex: Integer;
VarType: Integer;
begin
repeat
NumIdentInList := 0;
repeat
AssertIdent;
Inc(NumIdentInList);
if NumIdentInList > MAXPARAMS then
Error('Too many variables in one list');
IdentInListName[NumIdentInList] := Tok.Name;
NextTok;
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(COLONTOK);
CompileType(VarType);
if Tok.Kind = EQTOK then // Initialized variable (equivalent to a typed constant, but mutable)
begin
if BlockStack[BlockStackTop].Index <> 1 then
Error('Local variables cannot be initialized');
if NumIdentInList <> 1 then
Error('Multiple variables cannot be initialized');
NextTok;
DeclareIdent(IdentInListName[1], CONSTANT, 0, FALSE, VarType, VARPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
Ident[NumIdent].IsTypedConst := FALSE; // Allow mutability
CompileInitializer(Ident[NumIdent].Address, VarType);
end
else // Uninitialized variables
for IdentInListIndex := 1 to NumIdentInList do
DeclareIdent(IdentInListName[IdentInListIndex], VARIABLE, 0, FALSE, VarType, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
EatTok(SEMICOLONTOK);
until Tok.Kind <> IDENTTOK;
ResolveForwardReferences;
end; // CompileVarDeclarations
procedure CompileProcFuncDeclarations(IsFunction: Boolean);
function CompileDirective(const ImportFuncName: TString): Boolean;
var
ImportLibNameConst: TConst;
ImportLibNameConstValType: Integer;
begin
Result := FALSE;
if Tok.Kind = IDENTTOK then
if Tok.Name = 'EXTERNAL' then // External (Windows API) declaration
begin
if BlockStackTop <> 1 then
Error('External declaration must be global');
// Read import library name
NextTok;
CompileConstExpression(ImportLibNameConst, ImportLibNameConstValType);
if not IsString(ImportLibNameConstValType) then
Error('Library name expected');
// Register import function
GenerateImportFuncStub(AddImportFunc(ImportLibNameConst.StrValue, ImportFuncName));
EatTok(SEMICOLONTOK);
Result := TRUE;
end
else if Tok.Name = 'FORWARD' then // Forward declaration
begin
Inc(NumBlocks);
Ident[NumIdent].ProcAsBlock := NumBlocks;
Ident[NumIdent].IsUnresolvedForward := TRUE;
GenerateForwardReference;
NextTok;
EatTok(SEMICOLONTOK);
Result := TRUE;
end
else
Error('Unknown directive ' + Tok.Name);
end; // CompileDirective
function CompileInterface: Boolean;
begin
Result := FALSE;
// Procedure interface in the interface section of a unit is an implicit forward declaration
if ParserState.IsInterfaceSection and (BlockStack[BlockStackTop].Index = 1) then
begin
Inc(NumBlocks);
Ident[NumIdent].ProcAsBlock := NumBlocks;
Ident[NumIdent].IsUnresolvedForward := TRUE;
GenerateForwardReference;
Result := TRUE;
end;
end; // CompileInterface
var
ForwardIdentIndex, FieldIndex: Integer;
ReceiverType: Integer;
ProcOrFunc: TIdentKind;
ProcName, NonUppercaseProcName, ReceiverName: TString;
ForwardResolutionSignature: TSignature;
begin // CompileProcFuncDeclarations
AssertIdent;
ProcName := Tok.Name;
NonUppercaseProcName := Tok.NonUppercaseName;
NextTok;
// Check for method declaration
ReceiverName := '';
ReceiverType := 0;
if Tok.Kind = FORTOK then
begin
NextTok;
AssertIdent;
ReceiverName := Tok.Name;
NextTok;
EatTok(COLONTOK);
CompileTypeIdent(ReceiverType, FALSE);
if not (Types[ReceiverType].Kind in StructuredTypes) then
Error('Structured type expected');
if BlockStack[BlockStackTop].Index <> 1 then
Error('Methods cannot be nested');
if Types[ReceiverType].Kind in [RECORDTYPE, INTERFACETYPE] then
begin
FieldIndex := GetFieldUnsafe(ReceiverType, ProcName);
if FieldIndex <> 0 then
Error('Duplicate field');
end;
end;
// Check for forward declaration resolution
if ReceiverType <> 0 then
ForwardIdentIndex := GetMethodUnsafe(ReceiverType, ProcName)
else
ForwardIdentIndex := GetIdentUnsafe(ProcName);
// Possibly found an identifier of another kind or scope, or it is already resolved
if ForwardIdentIndex <> 0 then
if not Ident[ForwardIdentIndex].IsUnresolvedForward or
(Ident[ForwardIdentIndex].Block <> BlockStack[BlockStackTop].Index) or
((Ident[ForwardIdentIndex].Kind <> PROC) and not IsFunction) or
((Ident[ForwardIdentIndex].Kind <> FUNC) and IsFunction) then
ForwardIdentIndex := 0;
// Procedure/function signature
if ForwardIdentIndex <> 0 then // Forward declaration resolution
begin
CompileFormalParametersAndResult(IsFunction, ForwardResolutionSignature);
CheckSignatures(Ident[ForwardIdentIndex].Signature, ForwardResolutionSignature, ProcName);
DisposeParams(ForwardResolutionSignature);
end
else // Conventional declaration
begin
if IsFunction then ProcOrFunc := FUNC else ProcOrFunc := PROC;
DeclareIdent(ProcName, ProcOrFunc, 0, FALSE, 0, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, ReceiverName, ReceiverType);
CompileFormalParametersAndResult(IsFunction, Ident[NumIdent].Signature);
if (ReceiverType <> 0) and (Ident[NumIdent].Signature.CallConv <> DEFAULTCONV) then
Error('STDCALL/CDECL is not allowed for methods');
end;
EatTok(SEMICOLONTOK);
// Procedure/function body, if any
if ForwardIdentIndex <> 0 then // Forward declaration resolution
begin
if (ReceiverType <> 0) and (ReceiverName <> Ident[ForwardIdentIndex].ReceiverName) then
Error('Incompatible receiver name');
GenerateForwardResolution(Ident[ForwardIdentIndex].Address);
CompileBlock(ForwardIdentIndex);
EatTok(SEMICOLONTOK);
Ident[ForwardIdentIndex].IsUnresolvedForward := FALSE;
end
else if not CompileDirective(NonUppercaseProcName) and not CompileInterface then // Declaration in the interface part, external or forward declaration
begin
Inc(NumBlocks); // Conventional declaration
Ident[NumIdent].ProcAsBlock := NumBlocks;
CompileBlock(NumIdent);
EatTok(SEMICOLONTOK);
end;
end; // CompileProcFuncDeclarations
procedure CompileDeclarations;
var
DeclTok: TToken;
ParamIndex, StackParamIndex: Integer;
TotalParamSize: Integer;
NestedProcsFound: Boolean;
procedure DeclareResult;
begin
with Ident[BlockIdentIndex].Signature do
if (Types[ResultType].Kind in StructuredTypes) and ((CallConv = DEFAULTCONV) or (TypeSize(ResultType) > 2 * SizeOf(LongInt))) then // For functions returning structured variables, Result is a hidden VAR parameter
DeclareIdent('RESULT', VARIABLE, TotalParamSize, FALSE, ResultType, VARPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0)
else // Otherwise, Result is a hidden local variable
DeclareIdent('RESULT', VARIABLE, 0, FALSE, ResultType, EMPTYPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
Ident[BlockIdentIndex].ResultIdentIndex := NumIdent;
end; // DeclareResult
begin
NestedProcsFound := FALSE;
// For procedures and functions, declare parameters and the Result variable
// Default calling convention: ([var Self,] [var Result,] Parameter1, ... ParameterN [, StaticLink]), result returned in EAX
// STDCALL calling convention: (ParameterN, ... Parameter1, [, var Result]), result returned in EAX, small structures in EDX:EAX, reals in ST(0)
// CDECL calling convention: equivalent to STDCALL, except that caller clears the stack
if BlockStack[BlockStackTop].Index <> 1 then
begin
TotalParamSize := GetTotalParamSize(Ident[BlockIdentIndex].Signature, Ident[BlockIdentIndex].ReceiverType <> 0, FALSE);
// Declare Self
if Ident[BlockIdentIndex].ReceiverType <> 0 then
DeclareIdent(Ident[BlockIdentIndex].ReceiverName, VARIABLE, TotalParamSize, FALSE, Ident[BlockIdentIndex].ReceiverType, VARPASSING, 0, 0.0, '', [], EMPTYPROC, '', 0);
// Declare Result (default calling convention)
if (Ident[BlockIdentIndex].Kind = FUNC) and (Ident[BlockIdentIndex].Signature.CallConv = DEFAULTCONV) then
DeclareResult;
// Allocate and declare other parameters
for ParamIndex := 1 to Ident[BlockIdentIndex].Signature.NumParams do
begin
if Ident[BlockIdentIndex].Signature.CallConv = DEFAULTCONV then
StackParamIndex := ParamIndex
else
StackParamIndex := Ident[BlockIdentIndex].Signature.NumParams - ParamIndex + 1; // Inverse parameter stack for STDCALL/CDECL procedures
DeclareIdent(Ident[BlockIdentIndex].Signature.Param[StackParamIndex]^.Name,
VARIABLE,
TotalParamSize,
Ident[BlockIdentIndex].Signature.CallConv <> DEFAULTCONV,
Ident[BlockIdentIndex].Signature.Param[StackParamIndex]^.DataType,
Ident[BlockIdentIndex].Signature.Param[StackParamIndex]^.PassMethod,
0,
0.0,
'',
[],
EMPTYPROC,
'',
0);
end;
// Declare Result (STDCALL/CDECL calling convention)
if (Ident[BlockIdentIndex].Kind = FUNC) and (Ident[BlockIdentIndex].Signature.CallConv <> DEFAULTCONV) then
DeclareResult;
end; // if
// Loop over interface/implementation sections
repeat
// Local declarations
while Tok.Kind in [LABELTOK, CONSTTOK, TYPETOK, VARTOK, PROCEDURETOK, FUNCTIONTOK] do
begin
DeclTok := Tok;
NextTok;
case DeclTok.Kind of
LABELTOK:
CompileLabelDeclarations;
CONSTTOK:
CompileConstDeclarations;
TYPETOK:
CompileTypeDeclarations;
VARTOK:
CompileVarDeclarations;
PROCEDURETOK, FUNCTIONTOK:
begin
if (BlockStack[BlockStackTop].Index <> 1) and not NestedProcsFound then
begin
NestedProcsFound := TRUE;
GenerateNestedProcsProlog;
end;
CompileProcFuncDeclarations(DeclTok.Kind = FUNCTIONTOK);
end;
end; // case
end;// while
if ParserState.IsUnit and ParserState.IsInterfaceSection and (BlockStack[BlockStackTop].Index = 1) then
begin
EatTok(IMPLEMENTATIONTOK);
ParserState.IsInterfaceSection := FALSE;
end
else
Break;
until FALSE;
// Jump to entry point
if NestedProcsFound then
GenerateNestedProcsEpilog;
end; // CompileDeclarations
procedure CheckUnresolvedDeclarations;
var
IdentIndex: Integer;
begin
IdentIndex := NumIdent;
while (IdentIndex > 0) and (Ident[IdentIndex].Block = BlockStack[BlockStackTop].Index) do
begin
if (Ident[IdentIndex].Kind in [GOTOLABEL, PROC, FUNC]) and Ident[IdentIndex].IsUnresolvedForward then
Error('Unresolved declaration of ' + Ident[IdentIndex].Name);
Dec(IdentIndex);
end;
end; // CheckUnresolvedDeclarations
procedure DeleteDeclarations;
begin
// Delete local identifiers
while (NumIdent > 0) and (Ident[NumIdent].Block = BlockStack[BlockStackTop].Index) do
begin
// Warn if not used
if not Ident[NumIdent].IsUsed and not Ident[NumIdent].IsExported and (Ident[NumIdent].Kind = VARIABLE) and (Ident[NumIdent].PassMethod = EMPTYPASSING) then
Warning('Variable ' + Ident[NumIdent].Name + ' is not used');
// If procedure or function, delete parameters first
if Ident[NumIdent].Kind in [PROC, FUNC] then
DisposeParams(Ident[NumIdent].Signature);
// Delete identifier itself
Dec(NumIdent);
end;
// Delete local types
while (NumTypes > 0) and (Types[NumTypes].Block = BlockStack[BlockStackTop].Index) do
begin
// If procedural type, delete parameters first
if Types[NumTypes].Kind = PROCEDURALTYPE then
DisposeParams(Types[NumTypes].Signature)
// If record or interface, delete fields first
else if Types[NumTypes].Kind in [RECORDTYPE, INTERFACETYPE] then
DisposeFields(Types[NumTypes]);
// Delete type itself
Dec(NumTypes);
end;
end; // DeleteDeclarations
var
LibProcIdentIndex: Integer;
TotalParamSize: Integer;
begin // CompileBlock
Inc(BlockStackTop);
with BlockStack[BlockStackTop] do
begin
if BlockIdentIndex = 0 then Index := 1 else Index := Ident[BlockIdentIndex].ProcAsBlock;
LocalDataSize := 0;
ParamDataSize := 0;
TempDataSize := 0;
end;
if (ParserState.UnitStatus.Index = 1) and (BlockStack[BlockStackTop].Index = 1) then
begin
DeclarePredefinedTypes;
DeclarePredefinedIdents;
end;
CompileDeclarations;
if ParserState.IsUnit and (BlockStack[BlockStackTop].Index = 1) then
begin
// Main block of a unit (may contain the implementation part, but not statements)
CheckUnresolvedDeclarations;
EatTok(ENDTOK);
end
else
begin
// Main block of a program, or a procedure as part of a program/unit
if BlockStack[BlockStackTop].Index = 1 then
SetProgramEntryPoint;
GenerateStackFrameProlog(Ident[BlockIdentIndex].Signature.CallConv <> DEFAULTCONV);
if BlockStack[BlockStackTop].Index = 1 then // Main program
begin
GenerateFPUInit;
// Initialize heap and console I/O
LibProcIdentIndex := GetIdent('INITSYSTEM');
GenerateCall(Ident[LibProcIdentIndex].Address, BlockStackTop - 1, Ident[LibProcIdentIndex].NestingLevel);
end;
// Block body
GenerateGotoProlog;
GenerateExitProlog;
CompileCompoundStatement(0);
CheckUnresolvedDeclarations;
GenerateExitEpilog; // Direct all Exit procedure calls here
GenerateGotoEpilog;
if ForLoopNesting <> 0 then
Error('Internal fault: Illegal FOR loop nesting');
// If function, return Result value (via the EAX register, except some special cases in STDCALL/CDECL functions)
if (BlockStack[BlockStackTop].Index <> 1) and (Ident[BlockIdentIndex].Kind = FUNC) then
begin
PushVarIdentPtr(Ident[BlockIdentIndex].ResultIdentIndex);
if Types[Ident[BlockIdentIndex].Signature.ResultType].Kind in StructuredTypes then
begin
if Ident[Ident[BlockIdentIndex].ResultIdentIndex].PassMethod = VARPASSING then
DerefPtr(POINTERTYPEINDEX);
end
else
DerefPtr(Ident[BlockIdentIndex].Signature.ResultType);
SaveStackTopToEAX;
// Return Double in EDX:EAX
if Types[Ident[BlockIdentIndex].Signature.ResultType].Kind = REALTYPE then
SaveStackTopToEDX;
// Treat special cases in STDCALL/CDECL functions
ConvertResultFromPascalToC(Ident[BlockIdentIndex].Signature);
end;
if BlockStack[BlockStackTop].Index = 1 then // Main program
begin
LibProcIdentIndex := GetIdent('EXITPROCESS');
PushConst(0);
GenerateCall(Ident[LibProcIdentIndex].Address, 1, 1);
end;
GenerateStackFrameEpilog(Align(BlockStack[BlockStackTop].LocalDataSize + BlockStack[BlockStackTop].TempDataSize, SizeOf(LongInt)),
Ident[BlockIdentIndex].Signature.CallConv <> DEFAULTCONV);
if BlockStack[BlockStackTop].Index <> 1 then
begin
if Ident[BlockIdentIndex].Signature.CallConv = CDECLCONV then
TotalParamSize := 0 // CDECL implies that the stack is cleared by the caller - no need to do it here
else
TotalParamSize := GetTotalParamSize(Ident[BlockIdentIndex].Signature, Ident[BlockIdentIndex].ReceiverType <> 0, FALSE);
GenerateReturn(TotalParamSize, Ident[BlockIdentIndex].NestingLevel);
end;
DeleteDeclarations;
end; // else
Dec(BlockStackTop);
end;// CompileBlock
procedure CompileUsesClause;
var
SavedParserState: TParserState;
UnitIndex: Integer;
begin
NextTok;
repeat
AssertIdent;
UnitIndex := GetUnitUnsafe(Tok.Name);
// If unit is not found, compile it now
if UnitIndex = 0 then
begin
SavedParserState := ParserState;
if not SaveScanner then
Error('Unit nesting is too deep');
UnitIndex := CompileProgramOrUnit(Tok.Name + '.pas');
ParserState := SavedParserState;
if not RestoreScanner then
Error('Internal fault: Scanner state cannot be restored');
end;
ParserState.UnitStatus.UsedUnits := ParserState.UnitStatus.UsedUnits + [UnitIndex];
SetUnitStatus(ParserState.UnitStatus);
NextTok;
if Tok.Kind <> COMMATOK then Break;
NextTok;
until FALSE;
EatTok(SEMICOLONTOK);
end; // CompileUsesClause
function CompileProgramOrUnit(const Name: TString): Integer;
begin
InitializeScanner(Name);
Inc(NumUnits);
if NumUnits > MAXUNITS then
Error('Maximum number of units exceeded');
ParserState.UnitStatus.Index := NumUnits;
NextTok;
ParserState.IsUnit := FALSE;
if Tok.Kind in [PROGRAMTOK, UNITTOK] then
begin
ParserState.IsUnit := Tok.Kind = UNITTOK;
NextTok;
AssertIdent;
Units[ParserState.UnitStatus.Index].Name := Tok.Name;
NextTok;
EatTok(SEMICOLONTOK);
end
else
Units[ParserState.UnitStatus.Index].Name := 'MAIN';
ParserState.IsInterfaceSection := FALSE;
if ParserState.IsUnit then
begin
EatTok(INTERFACETOK);
ParserState.IsInterfaceSection := TRUE;
end;
// Always use System unit, except when compiling System unit itself
if NumUnits > 1 then
ParserState.UnitStatus.UsedUnits := [1]
else
ParserState.UnitStatus.UsedUnits := [];
SetUnitStatus(ParserState.UnitStatus);
if Tok.Kind = USESTOK then
CompileUsesClause;
Notice('Compiling ' + Name);
NumBlocks := 1;
CompileBlock(0);
CheckTok(PERIODTOK);
Result := ParserState.UnitStatus.Index;
FinalizeScanner;
end;// CompileProgram
end.
|
unit CryptApi;
interface
uses
windows;
type
_CREDENTIAL_ATTRIBUTEA = record
Keyword: LPSTR;
Flags: DWORD;
ValueSize: DWORD;
Value: PBYTE;
end;
PCREDENTIAL_ATTRIBUTE = ^_CREDENTIAL_ATTRIBUTEA;
_CREDENTIALA = record
Flags: DWORD;
Type_: DWORD;
TargetName: LPSTR;
Comment: LPSTR;
LastWritten: FILETIME;
CredentialBlobSize: DWORD;
CredentialBlob: PBYTE;
Persist: DWORD;
AttributeCount: DWORD;
Attributes: PCREDENTIAL_ATTRIBUTE;
TargetAlias: LPSTR;
UserName: LPSTR;
end;
PCREDENTIAL = array of ^_CREDENTIALA;
_CRYPTPROTECT_PROMPTSTRUCT = record
cbSize: DWORD;
dwPromptFlags: DWORD;
hwndApp: HWND;
szPrompt: LPCWSTR;
end;
PCRYPTPROTECT_PROMPTSTRUCT = ^_CRYPTPROTECT_PROMPTSTRUCT;
_CRYPTOAPI_BLOB = record
cbData: DWORD;
pbData: PBYTE;
end;
DATA_BLOB = _CRYPTOAPI_BLOB;
PDATA_BLOB = ^DATA_BLOB;
function CredEnumerate(Filter: LPCSTR; Flags: DWORD; var Count: DWORD; var Credential: PCREDENTIAL): BOOL; stdcall;
function CredFree(Buffer: Pointer): BOOL; stdcall;
function CryptUnprotectData(pDataIn: PDATA_BLOB; ppszDataDescr: PLPWSTR; pOptionalEntropy: PDATA_BLOB; pvReserved: Pointer; pPromptStruct: PCRYPTPROTECT_PROMPTSTRUCT; dwFlags: DWORD; pDataOut: PDATA_BLOB): BOOL; stdcall;
implementation
function CredEnumerate(Filter: LPCSTR;
Flags: DWORD;
var Count: DWORD;
var Credential: PCREDENTIAL): BOOL; stdcall; external 'advapi32.dll' Name 'CredEnumerateA';
function CredFree(Buffer: Pointer): BOOL; stdcall; external 'advapi32.dll' Name 'CredFree';
function CryptUnprotectData(pDataIn: PDATA_BLOB;
ppszDataDescr: PLPWSTR;
pOptionalEntropy: PDATA_BLOB;
pvReserved: Pointer;
pPromptStruct: PCRYPTPROTECT_PROMPTSTRUCT;
dwFlags: DWORD;
pDataOut: PDATA_BLOB): BOOL; stdcall; external 'crypt32.dll' Name 'CryptUnprotectData';
end.
|
unit AnOut;
interface
uses
Windows, Classes, SysUtils, Forms, Graphics,
DAQDefs, pwrdaq32, pdfw_def;
type
// base acquisition thread
TAnalogOutput = class(TThread)
private
hAdapter: DWORD;
dwError: DWORD;
FFrequency: DWORD;
FAdapterType: DWORD;
hNotifyEvent: THandle;
dwEventsNotify: DWORD;
ABuffer: PAnalogOutputBuffer;
FSettingsChanges: Boolean;
protected
procedure DoTerminate; override;
procedure DoPutData;
public
constructor Create(Adapter: DWORD);
procedure Execute; override;
property AdapterType: DWORD read FAdapterType write FAdapterType;
property Frequency: DWORD read FFrequency write FFrequency;
property Buffer: PAnalogOutputBuffer read ABuffer write ABuffer;
property SettingsChanges: Boolean read FSettingsChanges write FSettingsChanges;
end;
implementation
constructor TAnalogOutput.Create(Adapter: DWORD);
begin
try
// create thread suspended
inherited Create(True);
hAdapter := Adapter;
Buffer := nil;
except
Application.HandleException(Self);
end;
end;
procedure TAnalogOutput.Execute;
var
dwAnalogOutCfg: DWORD;
dwWaitTime: DWORD;
begin
try
// lock subsystem
if not PdAdapterAcquireSubsystem(hAdapter, @dwError, AnalogOut, 1)
then raise TPwrDaqException.Create('PdAdapterAcquireSubsystem', dwError);
// reset analog output
if not _PdAOutReset(hAdapter, @dwError)
then raise TPwrDaqException.Create('_PdAOutReset', dwError);
if AdapterType and atMF > 0
then dwAnalogOutCfg := AOB_CVSTART0 or AOB_REGENERATE
else dwAnalogOutCfg := AOB_CVSTART0 or AOB_AOUT32 or AOB_REGENERATE;
// set configuration
if not _PdAOutSetCfg(hAdapter, @dwError, dwAnalogOutCfg, 0)
then raise TPwrDaqException.Create('_PdAOutSetCfg', dwError);
// set DSP D/A conversion clock divider
if not _PdAOutSetCvClk(hAdapter, @dwError, Round(11000000 / Frequency) - 1)
then raise TPwrDaqException.Create('_PdAOutSetCvClk', dwError);
// create and set private event
if not _PdAOutSetPrivateEvent(hAdapter, @hNotifyEvent)
then raise TPwrDaqException.Create('_PdSetPrivateEvent', dwError);
// enable interrupts
if not _PdAdapterEnableInterrupt(hAdapter, @dwError, 1)
then raise TPwrDaqException.Create('_PdAdapterEnableInterrupt', dwError);
dwEventsNotify := eFrameDone or eBufferDone or eTimeout or eBufferError or eStopped;
if not _PdSetUserEvents(hAdapter, @dwError, AnalogOut, dwEventsNotify)
then raise TPwrDaqException.Create('_PdSetUserEvents', dwError);
// enable conversion
if not _PdAOutEnableConv(hAdapter, @dwError, 1)
then raise TPwrDaqException.Create('_PdAOutEnableConv', dwError);
// set start trigger
if not _PdAOutSwStartTrig(hAdapter, @dwError)
then raise TPwrDaqException.Create('_PdAOutSwStartTrig', dwError);
// thread loop
while not Terminated do try
if (WaitForSingleObject(hNotifyEvent, 100) = WAIT_OBJECT_0) or (SettingsChanges)
then Synchronize(DoPutData);
except
raise;
end;
except
Application.HandleException(Self);
end;
end;
procedure TAnalogOutput.DoPutData;
var
i,j: Integer;
dwScanDone : DWORD;
begin
try
// get user event
if not _PdGetUserEvents(hAdapter, @dwError, AnalogOut, @dwEventsNotify)
then raise TPwrDaqException.Create('_PdGetUserEvents', dwError);
// now analize user event
if Bool (dwEventsNotify and eTimeout)
then raise TPwrDaqException.Create('Driver detects timeout', 0);
if Bool (dwEventsNotify and eStopped)
then raise TPwrDaqException.Create('Acquisition stopped by driver', 0);
// in other cases driver need data to output
if SettingsChanges then
begin
// output block
if not _PdAOutPutBlock(hAdapter, @dwError, 2048, @Buffer[0], @dwScanDone)
then raise TPwrDaqException.Create('_PdAOutPutBlock', dwError);
SettingsChanges := False;
dwEventsNotify := eFrameDone or eBufferDone or eTimeout or eBufferError or eStopped;
if not _PdSetUserEvents(hAdapter, @dwError, AnalogOut, dwEventsNotify)
then raise TPwrDaqException.Create('_PdSetUserEvents', dwError);
if not _PdAOutEnableConv(hAdapter, @dwError, 1)
then raise TPwrDaqException.Create('_PdAOutEnableConv', dwError);
if not _PdAOutSwStartTrig(hAdapter, @dwError)
then raise TPwrDaqException.Create('_PdAOutEnableConv', dwError);
end;
except
// Handle any exception
Application.HandleException(Self);
end;
end;
procedure TAnalogOutput.DoTerminate;
begin
// stop output sequence
try
// disable A/D conversions
if not _PdAOutClearPrivateEvent(hAdapter, @hNotifyEvent)
then raise TPwrDaqException.Create('_PdAOutClearPrivateEvent', -1);
// stop output
if not _PdAOutSwStopTrig(hAdapter, @dwError)
then raise TPwrDaqException.Create('_PdAOutSwStopTrig', dwError);
// disable conversion
if not _PdAOutEnableConv(hAdapter, @dwError, DWORD(False))
then raise TPwrDaqException.Create('_PdAOutEnableConv', dwError);
// reset analog output
if not _PdAOutReset(hAdapter, @dwError)
then raise TPwrDaqException.Create('_PdAOutReset', dwError);
// release AOut subsystem and close adapter
if not PdAdapterAcquireSubsystem(hAdapter, @dwError, AnalogOut, 0)
then raise TPwrDaqException.Create('PdAdapterAcquireSubsystem', dwError);
except
// Handle any exception
Application.HandleException(Self);
end;
inherited;
end;
end. |
{/*!
Provides COM interface to TransModeler's parameter editor.
\modified 2019-07-03 10:20am
\author Wuping Xin
*/}
namespace TsmPluginFx.Core;
uses
rtl,
RemObjects.Elements.RTL;
const
ParameterEditorMajorVersion = 3;
ParameterEditorMinorVersion = 0;
const
LIBID_ParameterEditor: String = '{EB854259-C780-1130-97DF-036698AF3825}';
IID_IParametermEditor: String = '{09A6D596-97C5-1130-B40B-487B9F57A4AA}';
CLASS_ParameterEditor: String = '{B8108142-418F-1130-A558-7562FF2FD592}';
type
{/*!
TransModeler project parameters may be stored in three seperate pml files:
- Base pml file
A mandatory file that defines default values and layout of all the parameters.
- Secondary pml file
An optional file that only saves values differing from the base file. This file
can be used to save user-specific parameter values.
- Third pml file
An optional file that only saves values differing from the secondardary file.
This file can be used to save project-specific parameter values.
A filter can be applied - it uses item lables to locate items.
*/}
[COM, Guid(IID_IParametermEditor)]
IParameterEditor = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Edit(
aBase : OleString;
aSecondary : OleString := String.Empty;
aThird : OleString := String.Empty
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Show(
aBase : OleString;
aSecondary : OleString := String.Empty;
aThird : OleString := String.Empty
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method EditPage(
aBase : OleString;
aSecondary : OleString := String.Empty;
aThird : OleString := String.Empty;
aPage : OleString := String.Empty;
aRoot : OleString := String.Empty
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ShowPage(
aBase : OleString;
aSecondary : OleString := String.Empty;
aThird : OleString := String.Empty;
aPage : OleString := String.Empty;
aRoot : OleString := String.Empty
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method EditPageInGroup(
aBase : OleString;
aSecondary : OleString := String.Empty;
aThird : OleString := String.Empty;
aRoot : OleString := String.Empty;
aGroup : OleString := String.Empty;
aPage : OleString := String.Empty
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ShowPageInGroup(
aBase : OleString;
aSecondary : OleString := String.Empty;
aThird : OleString := String.Empty;
aRoot : OleString := String.Empty;
aGroup : OleString := String.Empty;
aPage : OleString := String.Empty
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method EditPages(
aBase : OleString;
aSecondary : OleString := String.Empty;
aThird : OleString := String.Empty;
aRoot : OleString := String.Empty;
aFilter : OleString := String.Empty
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Open(
aBase : OleString;
aSecondary : OleString := String.Empty;
aThird : OleString := String.Empty;
aRoot : OleString := String.Empty;
aGroup : OleString := String.Empty;
aPage : OleString := String.Empty;
aEditable : LongInt := 0;
aModaless : LongInt := 0;
aSingle : LongInt := 0
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetCurrentPageName(
out aPage: OleString): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SelectItem(
aItem: OleString): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetItemStringValue(
aItem: OleString;
aValue: OleString): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetItemAttribute(
aItem: OleString;
aColumn: Int16;
aAttribute: OleString;
aValue: OleString): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetArrayStringValue(
aItem: OleString;
aColumn: Int16;
aRow: Int16;
aValue: OleString): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetItemStringValue(
aItem: OleString;
out aValue: OleString): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetArrayStringValue(
aItem: OleString;
aColumn: Int16;
aRow: Int16;
out aValue: OleString): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method AddTableRow(
aItem: OleString;
aLabel: OleString): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method DeleteTableRow(
aItem: OleString;
aRow: Int16): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ViewFile(
aFileName: OleString;
aTitle: OleString): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ViewFileEx(
aFileName: OleString;
aTitle: OleString;
aColumns: LongInt;
aRows: LongInt;
aTimerSpeed: LongInt): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Convert(
aFileName: OleString;
aBase: OleString;
aSecondary: OleString): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Apply: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Close(
aOK: LongInt): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetExitStatus(
out aStatus: OleString): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetModified(
aModified: LongInt): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Modified(
out aValue: VARIANT_BOOL): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Modified(
aValue: VARIANT_BOOL): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ShowHidden(
aShowHidden: LongInt): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetReFormat(
aReFormat: LongInt): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetVersion(
out aVersion: Double): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method AllowDefault(
aValue: LongInt): HRESULT;
end;
CoParameterEditor = class
public
class method Create: IParameterEditor;
begin
result := CreateComObject(CLASS_ParameterEditor) as IParameterEditor;
end;
end;
end. |
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Console.Application;
interface
uses
DPM.Console.ExitCodes,
DPM.Core.Logging,
Spring.Container,
VSoft.CancellationToken;
type
TDPMConsoleApplication = class
private
class var
FContainer : TContainer;
FLogger : ILogger;
FCancellationTokenSource : ICancellationTokenSource;
protected
class function InitContainer : TExitCode;
public
class function Run : TExitCode;
class procedure CtrlCPressed;
class procedure CtrlBreakPressed;
class procedure CloseEvent;
class procedure ShutdownEvent;
end;
implementation
uses
WinApi.Windows,
System.SysUtils,
VSoft.CommandLine.Options,
DPM.Core.Options.Common,
DPM.Core.Init,
DPM.Console.Types,
DPM.Console.Options,
DPM.Console.Writer,
DPM.Console.Banner,
DPM.Console.Command,
DPM.Console.Reg;
function ConProc(CtrlType : DWord) : Bool; stdcall;
begin
Result := True;
case CtrlType of
CTRL_C_EVENT : TDPMConsoleApplication.CtrlCPressed;
CTRL_BREAK_EVENT : TDPMConsoleApplication.CtrlBreakPressed;
CTRL_CLOSE_EVENT : TDPMConsoleApplication.CloseEvent;
CTRL_SHUTDOWN_EVENT : TDPMConsoleApplication.ShutdownEvent;
end;
end;
{ T }
///
class procedure TDPMConsoleApplication.CloseEvent;
begin
FLogger.Information('Close Detected.');
end;
class procedure TDPMConsoleApplication.CtrlBreakPressed;
begin
FLogger.Information('Ctrl-Break detected.');
FCancellationTokenSource.Cancel;
end;
class procedure TDPMConsoleApplication.CtrlCPressed;
begin
FLogger.Information('Ctrl-C detected.');
FCancellationTokenSource.Cancel;
end;
class function TDPMConsoleApplication.InitContainer : TExitCode;
begin
result := TExitCode.OK;
try
FContainer := TContainer.Create;
DPM.Core.Init.InitCore(FContainer);
DPM.Console.Reg.InitConsole(FContainer);
FContainer.Build;
except
on e : Exception do
begin
//we don't jhave a logger or console here so using system.writeln is ok.
System.Writeln('Exception while initializing : ' + e.Message);
result := TExitCode.InitException;
end;
end;
end;
class function TDPMConsoleApplication.Run: TExitCode;
var
console : IConsoleWriter;
parseresult : ICommandLineParseResult;
commandHandler : ICommandHandler;
commandFactory : ICommandFactory;
bError : boolean;
command : TDPMCommand;
begin
FCancellationTokenSource := TCancellationTokenSourceFactory.Create;
SetConsoleCtrlHandler(@ConProc, True);
result := InitContainer; //Init our DI container
if result <> TExitCode.OK then
exit;
console := FContainer.Resolve<IConsoleWriter>();
Assert(console <> nil);
FLogger := FContainer.Resolve<ILogger>;
bError := false;
parseresult := TOptionsRegistry.Parse;
if parseresult.HasErrors then
begin
ShowBanner(console);
TCommonOptions.Default.NoBanner := true; //make sure it doesn't show again.
console.WriteLine(parseresult.ErrorText,ccBrightRed);
bError := true;
TCommonOptions.Default.Help := true; //if it's a valid command but invalid options this will give us command help.
end;
FLogger.Verbosity := TCommonOptions.Default.Verbosity;
command := GetCommandFromString(parseresult.Command);
if command = TDPMCommand.Invalid then
begin
ShowBanner(console);
console.WriteLine('Invalid command : [' + parseResult.Command + ']',ccBrightRed );
exit(TExitCode.InvalidCommand);
end;
if command = TDPMCommand.None then
command := TDPMCommand.Help;
if command <> TDPMCommand.Help then
begin
if TCommonOptions.Default.Help then
begin
THelpOptions.HelpCommand := command;
command := TDPMCommand.Help;
end;
end;
commandFactory := FContainer.Resolve<ICommandFactory>;
Assert(commandFactory <> nil, 'CommandFactory did not resolve!');
commandHandler := commandFactory.CreateCommand(command);
if commandHandler = nil then
begin
console.WriteLine('No command handler registered for command : [' + CommandString[command] + ']',ccBrightRed );
exit(TExitCode.NoCommandHandler);
end;
if (not TCommonOptions.Default.NoBanner) and (not commandHandler.ForceNoBanner) then
ShowBanner(console);
result := commandHandler.ExecuteCommand(FCancellationTokenSource.Token);
if bError then //an error occured earlier so ignore command result.
result := TExitCode.InvalidArguments;
FreeAndNil(FContainer);
end;
class procedure TDPMConsoleApplication.ShutdownEvent;
begin
FLogger.Information('Shutdown detected.');
FCancellationTokenSource.Cancel;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.XML.NodeBase;
//TODO : Not used since we switched to json.. remove when we're sure we don't need it
interface
uses
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.MSXML;
type
IXMLNodeBase = interface
['{3716A814-0213-4845-80D2-2BD164E139D8}']
function LoadFromXML(const xmlElement : IXMLDOMElement) : boolean;
end;
TXMLNodeBase = class;
TXMLNodeBaseClass = class of TXMLNodeBase;
TXMLNodeBase = class(TInterfacedObject, IXMLNodeBase)
private
FLogger : ILogger;
protected
property Logger : ILogger read FLogger;
function SafeGetAttribute(const xmlElement : IXMLDOMElement; const attributeName : string) : string;
function ReadStringValue(const xmlElement : IXMLDOMElement; const nodeName : string; const required : boolean; var field : string) : boolean;
function ReadBoolValue(const xmlElement : IXMLDOMElement; const nodeName : string; const required : boolean; var field : boolean) : boolean;
function ReadBoolAttribute(const xmlElement : IXMLDOMElement; const attributeName : string; const required : boolean; var field : boolean) : boolean;
function LoadFromXML(const xmlElement : IXMLDOMElement) : Boolean; virtual; abstract;
function LoadCollection(const rootElement : IXMLDOMElement; const collectionPath : string; const nodeClass : TXMLNodeBaseClass; const action : TConstProc<IInterface>) : boolean;
public
constructor Create(const logger : ILogger); virtual;
end;
implementation
uses
System.SysUtils,
System.Variants;
constructor TXMLNodeBase.Create(const logger : ILogger);
begin
FLogger := logger;
end;
function TXMLNodeBase.ReadBoolAttribute(const xmlElement : IXMLDOMElement; const attributeName : string; const required : boolean; var field : boolean) : boolean;
var
attributeValue : Variant;
sValue : string;
begin
result := false;
attributeValue := xmlElement.getAttribute(attributeName);
if VarIsNull(attributeValue) then
begin
if required then
logger.Error('Required attribute [' + attributeName + '] is empty.')
else
result := true;
exit;
end;
sValue := attributeValue;
try
field := StrToBool(sValue);
result := true;
except
logger.Error('Invalid value [' + sValue + '] for ' + attributeName);
end;
end;
function TXMLNodeBase.ReadBoolValue(const xmlElement : IXMLDOMElement; const nodeName : string; const required : boolean; var field : boolean) : boolean;
var
sValue : string;
begin
result := ReadStringValue(xmlElement, nodeName, required, sValue);
if result then
begin
if sValue = '' then
exit;
try
field := StrToBool(sValue)
except
logger.Error('Invalid value [' + sValue + '] for ' + nodeName);
result := false;
end;
end;
end;
function TXMLNodeBase.ReadStringValue(const xmlElement : IXMLDOMElement; const nodeName : string; const required : boolean; var field : string) : boolean;
var
tmpNode : IXMLDOMElement;
begin
result := false;
tmpNode := xmlElement.selectSingleNode(nodeName) as IXMLDOMElement;
if tmpNode = nil then
begin
if required then
logger.Error('Required Element [' + nodeName + '] not found.')
else
result := true;
exit;
end;
field := tmpNode.text;
if field = '' then
begin
if required then
logger.Error('Required Element [' + nodeName + '] is empty.');
exit;
end
else
result := true;
end;
function TXMLNodeBase.SafeGetAttribute(const xmlElement : IXMLDOMElement; const attributeName : string) : string;
var
attributeValue : Variant;
begin
result := '';
attributeValue := xmlElement.getAttribute(attributeName);
if not VarIsNull(attributeValue) then
result := attributeValue;
end;
function TXMLNodeBase.LoadCollection(const rootElement : IXMLDOMElement; const collectionPath : string; const nodeClass : TXMLNodeBaseClass; const action : TConstProc<IInterface>) : boolean;
var
element : IXMLDOMElement;
nodeList : IXMLDOMNodeList;
item : IXMLNodeBase;
i : Integer;
begin
result := true;
nodeList := rootElement.selectNodes(collectionPath);
if nodeList.length = 0 then
exit;
for i := 0 to nodeList.length - 1 do
begin
element := nodeList.item[i] as IXMLDOMElement;
item := nodeClass.Create(Logger) as IXMLNodeBase;
item.LoadFromXML(element);
action(item);
end;
end;
end.
|
unit OTFEStrongDisk_U;
// Description: Delphi StrongDisk Component
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
// TRUE if integer<>0
// FALSE if integer=0
interface
uses
Classes, SysUtils, Windows, forms, controls,
OTFE_U,
OTFEStrongDiskConsts_U;
type
TOTFEStrongDisk = class(TOTFE)
private
hStrongDiskSupportDLLCrypto: THandle;
hStrongDiskSupportDLLLang: THandle;
hStrongDiskDLL: THandle;
fDefaultDrive: char;
function GetNextUnusedDrvLtr(afterDrv: char): char;
function GetUnusedDriveLetters(): string;
protected
StrongDiskDriverVersion: cardinal;
function Connect(): boolean;
function Disconnect(): boolean;
procedure SetActive(AValue : Boolean); override;
function GetDisksMounted(var mountedDrives: string; volumeFilenames: TStrings): boolean;
function GetInstallDir(): string;
// DLL FUNCTIONS
// SDMount(): mount a secure drive
function CallSDMount(driveLetter: char;
filename: string;
readonly: boolean;
autolaunch: boolean;
keymode: integer;
keyFilename: string;
password: string): boolean;
// SDDismount(): unmount a secure drive
function CallSDDismount(driveLetter: char;
force: boolean): boolean;
// SDDismountAll(): unmount a secure drive
function CallSDDismountAll(force: boolean): boolean;
// SDGetDrives(): get bitmask representing the secure drives;
function CallSDGetDrives(var drives: string): boolean;
// SDGetInfo(): get information about the secure drive;
function CallSDGetInfo(driveLetter: char;
var filename: string;
var readonly: boolean): boolean;
function TranslateDLLError(DLLerror: DWORD): integer;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
// TOTFE functions...
function Title(): string; overload; override;
function Mount(volumeFilename: string; readonly: boolean = FALSE): char; override;
function Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean; override;
function MountDevices(): string; override;
function CanMountDevice(): boolean; override;
function Dismount(driveLetter: char; emergency: boolean = FALSE): boolean; overload; override;
function Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean; overload; override;
function DrivesMounted(): string; override;
function GetVolFileForDrive(driveLetter: char): string; override;
function GetDriveForVolFile(volumeFilename: string): char; override;
function Version(): cardinal; override;
function VersionStr(): string; override;
function IsEncryptedVolFile(volumeFilename: string): boolean; override;
function GetMainExe(): string; override;
published
property DefaultDrive: char read fDefaultDrive write fDefaultDrive;
end;
procedure Register;
implementation
uses ShellAPI,
dialogs,
Registry, RegStr,
INIFiles,
Math,
OTFEConsts_U,
OTFEStrongDiskPasswordEntry_U,
SDUGeneral;
type
// Function declarations for DLL functions
//STRDISKAPI unsigned SDMount(char driveLetter, const char* fileName,
// char readOnly, char autolaunch, unsigned keyMode,
// const char* keyFileName, const char* password, unsigned passwordSize);
TSDMountFunc = function(driveLetter: char;
filename: PChar;
readOnly: byte;
autolaunch: byte;
keyMode: DWORD;
keyFileName: PChar;
password: PChar;
passwordSize: DWORD): DWORD; stdcall;
//STRDISKAPI unsigned SDDismount(char driveLetter, char force);
TSDDismountFunc = function(driveLetter: char; force: byte): DWORD; stdcall;
//STRDISKAPI unsigned SDDismountAll(char force);
TSDDismountAllFunc = function(force: byte): DWORD; stdcall;
//STRDISKAPI unsigned SDGetDrives(unsigned* drives);
TSDGetDrivesFunc = function(drives: PDWORD): DWORD; stdcall;
//STRDISKAPI unsigned SDGetInfo(char driveLetter,
// char* fileName, unsigned* size, char* readOnly);
TSDGetInfoFunc = function(driveLetter: char;
fileName: PChar;
size: PDWORD;
readonly: PByte): DWORD; stdcall;
procedure Register;
begin
RegisterComponents('OTFE', [TOTFEStrongDisk]);
end;
constructor TOTFEStrongDisk.Create(AOwner : TComponent);
begin
inherited create(AOwner);
FActive := False;
hStrongDiskDLL := 0;
StrongDiskDriverVersion := $FFFFFFFF;
end;
destructor TOTFEStrongDisk.Destroy;
begin
if FActive then
begin
Active := FALSE;
end;
inherited Destroy;
end;
function TOTFEStrongDisk.Connect(): boolean;
var
loadFilename: string;
begin
Result := Active;
if not(Active) then
begin
// The STRONGDISK_MAIN_DLL requires STRONGDISK_SUPPORT_DLL_CRYPTO
// Because STRONGDISK_MAIN_DLL can't automatically load STRONGDISK_SUPPORT_DLL_CRYPTO
// by itsself, unless *this* *executable* is in the same directory, or
// STRONGDISK_SUPPORT_DLL_CRYPTO is in the system's PATH environment - we load it
// here
// Note: We try on the path first, *then* in the StrongDisk install dir
// THIS IS THE REVERSE OF THE OTHER TWO DLLS - StrongDisk doesn't
// appear to install STRONGDISK_SUPPORT_DLL_CRYPTO in it's dir
loadFilename := STRONGDISK_SUPPORT_DLL_CRYPTO;
hStrongDiskSupportDLLCrypto := LoadLibrary(PChar(loadFilename));
if hStrongDiskSupportDLLCrypto=0 then
begin
// DLL couldn't be loaded; maybe it isn't on the path? Try again, looking
// in the StrongDisk directory
loadFilename := ExtractFilePath(GetMainExe()) + STRONGDISK_SUPPORT_DLL_CRYPTO;
hStrongDiskSupportDLLCrypto := LoadLibrary(PChar(loadFilename));
if hStrongDiskSupportDLLCrypto=0 then
begin
FLastErrCode:= OTFE_ERR_DRIVER_FAILURE;
raise EStrongDiskDLLNotFound.Create(E_STRONGDISK_DLL_NOT_FOUND+
' ('+
STRONGDISK_SUPPORT_DLL_CRYPTO+
')');
end;
end;
// THIS IS NEW - SEEMS TO HAVE BEEN ADDED TO StrongDisk v3
// The STRONGDISK_MAIN_DLL requires STRONGDISK_SUPPORT_DLL_LANG
// Because STRONGDISK_MAIN_DLL can't automatically load STRONGDISK_SUPPORT_DLL_LANG
// by itsself, unless *this* *executable* is in the same directory, or
// STRONGDISK_SUPPORT_DLL_LANG is in the system's PATH environment - we load it
// here
// STRONGDISK_SUPPORT_DLL_LANG *should* be in the StrongDisk install dir;
// so we try there first
loadFilename := ExtractFilePath(GetMainExe()) + STRONGDISK_SUPPORT_DLL_LANG;
hStrongDiskSupportDLLCrypto := LoadLibrary(PChar(loadFilename));
if hStrongDiskSupportDLLCrypto=0 then
begin
// DLL couldn't be loaded; fallback to any copy which may be on the path
loadFilename := STRONGDISK_SUPPORT_DLL_LANG;
hStrongDiskSupportDLLCrypto := LoadLibrary(PChar(loadFilename));
if hStrongDiskSupportDLLCrypto=0 then
begin
FLastErrCode:= OTFE_ERR_DRIVER_FAILURE;
raise EStrongDiskDLLNotFound.Create(E_STRONGDISK_DLL_NOT_FOUND+
' ('+
STRONGDISK_SUPPORT_DLL_LANG+
')');
end;
end;
// Load the main StrongDisk DLL
// STRONGDISK_MAIN_DLL *should* be in the StrongDisk install dir;
// so we try there first
loadFilename := ExtractFilePath(GetMainExe()) + STRONGDISK_MAIN_DLL;
hStrongDiskDLL := LoadLibrary(PChar(loadFilename));
if hStrongDiskDLL=0 then
begin
// DLL couldn't be loaded; fallback to any copy which may be on the path
loadFilename := STRONGDISK_MAIN_DLL;
hStrongDiskDLL := LoadLibrary(PChar(loadFilename));
if hStrongDiskDLL=0 then
begin
FLastErrCode:= OTFE_ERR_DRIVER_FAILURE;
// Free off the no-longer needed support DLL
FreeLibrary(hStrongDiskDLL);
raise EStrongDiskDLLNotFound.Create(E_STRONGDISK_DLL_NOT_FOUND+
' ('+
STRONGDISK_MAIN_DLL+
')');
end;
end;
Result := TRUE;
end;
end;
function TOTFEStrongDisk.Disconnect(): boolean;
begin
if Active then
begin
if (hStrongDiskDLL<>0) then
begin
FreeLibrary(hStrongDiskDLL);
hStrongDiskDLL := 0;
end;
if (hStrongDiskSupportDLLCrypto<>0) then
begin
FreeLibrary(hStrongDiskSupportDLLCrypto);
hStrongDiskSupportDLLCrypto := 0;
end;
if (hStrongDiskSupportDLLLang<>0) then
begin
FreeLibrary(hStrongDiskSupportDLLLang);
hStrongDiskSupportDLLLang := 0;
end;
end;
Result := TRUE;
end;
procedure TOTFEStrongDisk.SetActive(AValue : Boolean);
var
allOK: boolean;
begin
allOK := FALSE;
if AValue <> Active then
begin
if AValue then
begin
allOK := Connect();
end
else
begin
allOK := Disconnect();
end;
end;
if allOK then
begin
inherited;
if Active then
begin
StrongDiskDriverVersion := Version();
end;
end;
end;
// Note that the emergency parameter is IGNORED
function TOTFEStrongDisk.Dismount(driveLetter: char; emergency: boolean = FALSE): boolean;
begin
CheckActive();
Result := FALSE;
if pos(driveLetter, DrivesMounted())<1 then
begin
FLastErrCode := OTFE_ERR_INVALID_DRIVE;
exit;
end;
Result := CallSDDismount(upcase(driveLetter), emergency);
end;
function TOTFEStrongDisk.Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean;
begin
// Don't need to convert volumeFilename to SFN/LFN, this is done in
// GetDriveForVolFile(...)
Result := Dismount(GetDriveForVolFile(volumeFilename), emergency);
end;
function TOTFEStrongDisk.Mount(volumeFilename: string; readonly: boolean = FALSE): char;
var
stlVolumes: TStringList;
mountedAs: string;
begin
CheckActive();
Result := #0;
stlVolumes:= TStringList.Create();
try
stlVolumes.Add(volumeFilename);
if Mount(stlVolumes, mountedAs, readonly) then
begin
Result := mountedAs[1];
end;
finally
stlVolumes.Free();
end;
end;
function TOTFEStrongDisk.Mount(volumeFilenames: TStringList; var mountedAs: AnsiString; readonly: boolean = FALSE): boolean;
var
driveLetter: char;
thePassword: string;
theKeyFilename: string;
useHardwareKey: boolean;
oneOK: boolean;
drvLtrsFree: string;
passwordDlg: TOTFEStrongDiskPasswordEntry_F;
autolaunch: boolean;
volumeLoop: integer;
currVolFilename: string;
mountedDrvLetter: char;
currAllOK: boolean;
keymode: integer;
begin
CheckActive();
Result := FALSE;
oneOK := FALSE;
mountedAs := '';
passwordDlg:= TOTFEStrongDiskPasswordEntry_F.Create(nil);
try
// The user should be prompted for the drive letter, and offered the
// default
drvLtrsFree := GetUnusedDriveLetters();
driveLetter := DefaultDrive;
if driveLetter=#0 then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
// If we're on A or B, skip this drive
if (driveLetter='A') or (driveLetter='B') then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
end;
// If we're on B, skip this drive
if (driveLetter='B') then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
end;
end
else if pos(driveLetter, drvLtrsFree)<1 then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
end;
passwordDlg.DrivesAllowed := drvLtrsFree;
passwordDlg.Drive := driveLetter;
if passwordDlg.ShowModal()=mrCancel then
begin
passwordDlg.ClearEnteredPassword();
// Result already = FALSE, so just set the error and exit
FLastErrCode := OTFE_ERR_USER_CANCEL;
exit;
end;
// Retrieve password information from password entry dialog
thePassword := passwordDlg.mePassword.text;
theKeyFilename:= passwordDlg.edKeyfile.text;
useHardwareKey:= passwordDlg.ckElectronicKey.checked;
driveLetter := passwordDlg.Drive;
autolaunch := passwordDlg.ckAutostart.checked;
passwordDlg.ClearEnteredPassword();
finally
passwordDlg.Free();
end;
if driveLetter=#0 then
begin
// Result already = FALSE, so just set the error and exit
FLastErrCode := OTFE_ERR_INVALID_DRIVE;
Result := FALSE;
exit;
end;
DefaultDrive := driveLetter;
// Work out which keys are to be used in mounting the volume
keymode := 0;
if thePassword<>'' then
begin
keymode := keymode OR SDKM_PASSWORD;
end;
if theKeyFilename<>'' then
begin
keymode := keymode OR SDKM_KEYFILE;
end;
if useHardwareKey then
begin
keymode := keymode OR SDKM_ELKEY;
end;
for volumeLoop:=0 to (volumeFilenames.count-1) do
begin
mountedDrvLetter := #0;
currVolFilename := volumeFilenames[volumeLoop];
if IsEncryptedVolFile(currVolFilename) then
begin
currAllOK := CallSDMount(driveLetter,
currVolFilename,
readonly,
autolaunch,
keymode,
theKeyFilename,
thePassword);
if not(currAllOK) then
begin
FLastErrCode:= OTFE_ERR_WRONG_PASSWORD;
end;
if currAllOK then
begin
mountedDrvLetter := driveLetter;
oneOK := TRUE;
end;
end
else
begin
FLastErrCode:= OTFE_ERR_FILE_NOT_ENCRYPTED_VOLUME;
end;
if volumeLoop<(volumeFilenames.count-1) then
begin
driveLetter := GetNextUnusedDrvLtr(driveLetter);
if driveLetter=#0 then
begin
FLastErrCode := OTFE_ERR_INVALID_DRIVE;
break;
end;
end;
mountedAs := mountedAs + mountedDrvLetter;
end;
// Pad out the string with #0, if needed
while length(mountedAs)<volumeFilenames.count do
begin
mountedAs := mountedAs + #0;
end;
Result := oneOK;
end;
function TOTFEStrongDisk.DrivesMounted(): string;
var
output: string;
begin
GetDisksMounted(output, nil);
Result := SortString(output);
end;
function TOTFEStrongDisk.GetDisksMounted(var mountedDrives: string; volumeFilenames: TStrings): boolean;
var
i: integer;
currVolFilename: string;
retVal: boolean;
begin
CheckActive();
retVal := CallSDGetDrives(mountedDrives);
if volumeFilenames<>nil then
begin
volumeFilenames.Clear;
for i:=1 to length(mountedDrives) do
begin
currVolFilename := GetVolFileForDrive(mountedDrives[i]);
retVal := retVal AND (currVolFilename<>'');
volumeFilenames.Add(currVolFilename);
end;
end;
Result := retVal;
end;
// !! WARNING !!
// Under NT, the StrongDisk driver won't tell us the full filename if it's more than
// 64 chars long, it will only return the first 60 followed by "..."
function TOTFEStrongDisk.GetVolFileForDrive(driveLetter: char): string;
var
readonly: boolean;
filename: string;
begin
Result := '';
driveLetter := upcase(driveLetter);
if CallSDGetInfo(driveLetter, filename, readonly) then
begin
Result := filename;
end;
end;
// !! WARNING !!
// If running under NT, then if the lanegth of "volumeFilename" is >64, this
// function may FAIL as the StrongDisk driver only gives us the first 60 chars
// followed by "..." to work with
function TOTFEStrongDisk.GetDriveForVolFile(volumeFilename: string): char;
var
mountedFilenames: TStringList;
mountedDrives: string;
begin
Result := #0;
mountedFilenames:= TStringList.Create();
try
GetDisksMounted(mountedDrives, mountedFilenames);
if mountedFilenames.IndexOf(volumeFilename)>-1 then
begin
Result := mountedDrives[mountedFilenames.IndexOf(volumeFilename)+1];
end;
finally
mountedFilenames.Free();
end;
end;
function TOTFEStrongDisk.IsEncryptedVolFile(volumeFilename: string): boolean;
begin
CheckActive();
Result := TRUE;
end;
function TOTFEStrongDisk.Title(): string;
begin
Result := 'StrongDisk';
end;
function TOTFEStrongDisk.Version(): cardinal;
const
VERSIONINFO_PRODUCT_VERSION = 'ProductVersion';
var
majorVersion, minorVersion, revisionVersion, buildVersion: integer;
exeFilename: string;
vsize: Integer;
dwHandle: DWORD;
pBlock: Pointer;
aLocale : array[0..3] of Byte;
versionStringName: string;
pLocale : Pointer;
iLenOfValue: DWORD;
versionInformationValue: PChar;
langCharset: string;
versionPart: string;
tmpStr: string;
tmpByte: byte;
tmpDriverVersion: cardinal;
allOK: boolean;
begin
CheckActive();
Result := $FFFFFFFF;
// OK - here's the plan! :)
// Because the StrongDisk DLL doesn't appear to have any version information
// (yuck!), we have to get it from the main StrongDisk executable
// You'd expect the get this information from the executable in a nice'n'easy
// way, just be using SDUGetVersionInfo, however for some reason PhysTechSoft
// didn't store this information in the right place (select the executable
// in Windows Explorer and press <ALT+ENTER> to get the file properties; goto
// the "Version" tab, and you don't get version information right at the top
// of the property sheet. Pity.
// Nevermind - they do store this version information (check the "Other
// version information" groupbox on this property sheet), we'll just have to
// snag that instead!
if StrongDiskDriverVersion=$FFFFFFFF then
begin
exeFilename:= GetMainExe();
// Attempt to get the executable's version information the easy way
if SDUGetVersionInfo(exeFilename, majorVersion, minorVersion, revisionVersion, buildVersion) then
begin
if (majorVersion<>0) OR
(minorVersion<>0) OR
(revisionVersion<>0) OR
(buildVersion<>0) then
begin
// We've got useful version information; use it
StrongDiskDriverVersion := (majorVersion * $01000000) +
(minorVersion * $00010000) +
(revisionVersion * $00000100) +
(buildVersion * $00000001);
end;
end;
if (StrongDiskDriverVersion=$FFFFFFFF) then
begin
// No luck? Oh well, just have to do things the hard(er) way...
vsize := GetFileVersionInfoSize(PChar(exeFilename), dwHandle);
if vsize = 0 then
begin
exit;
end;
GetMem(pBlock,vsize);
try
if GetFileVersionInfo(PChar(exeFilename), dwHandle, vsize, pBlock) then
begin
// Determine the lang-charset to use (if possible)
// For example:
// 040904E4 = US English, Windows MultiLingual characterset
// Breaking that down:
// 04...... = SUBLANG_ENGLISH_USA
// ..09.... = LANG_ENGLISH
// ....04E4 = 1252 = Codepage for Windows:Multilingual
langCharset := '';
if VerQueryValue(pBlock,
PChar('\VarFileInfo\Translation\'),
pLocale,
iLenOfValue) then
begin
if (iLenOfValue=4) then
begin
// Move locale to array
Move(pLocale^, aLocale, 4);
// Convert into a string representation
langCharset:= IntToHex(aLocale[1], 2) +
IntToHex(aLocale[0], 2) +
IntToHex(aLocale[3], 2) +
IntToHex(aLocale[2], 2);
end;
end;
// If that failed, we'll try the local system default lang
if langCharset='' then
begin
langCharset := Format('%.4x', [GetUserDefaultLangID()]) + '04E4';
end;
versionStringName:= '\StringFileInfo\' + langCharset +'\' + VERSIONINFO_PRODUCT_VERSION + #0;
if VerQueryValue(pBlock,
@versionStringName[1],
Pointer(versionInformationValue),
iLenOfValue) then
begin
tmpDriverVersion := 0;
tmpStr := versionInformationValue;
allOK := SDUSplitString(tmpStr, versionPart, tmpStr, '.');
allOK := allOK AND (versionPart<>'');
if allOK then
begin
// We transfer AND it with $FF to limit this part of the version
// number to something a single bytes; that's all we have to
// represent it in StrongDiskDriverVersion
tmpByte := (strtoint(versionPart) AND $FF);
tmpDriverVersion := tmpDriverVersion + (tmpByte * $01000000);
end;
allOK := SDUSplitString(tmpStr, versionPart, tmpStr, '.');
allOK := allOK AND (versionPart<>'');
if allOK then
begin
// We transfer AND it with $FF to limit this part of the version
// number to something a single bytes; that's all we have to
// represent it in StrongDiskDriverVersion
tmpByte := (strtoint(versionPart) AND $FF);
tmpDriverVersion := tmpDriverVersion + (tmpByte * $00010000);
end;
// We don't set allOK on the final call to SDUSplitString, as we
// won't find a final "."
// We only use the first 4 numbers from the version string, though
// we could easily extend this to grab all 4 (if possible)
// Because the version string *could*, but might *not* have a 4th
// (build) number, we still do the SDUSplitString, but we ignore it's
// result
SDUSplitString(tmpStr, versionPart, tmpStr, '.');
allOK := (versionPart<>'');
if allOK then
begin
// We transfer AND it with $FF to limit this part of the version
// number to something a single bytes; that's all we have to
// represent it in StrongDiskDriverVersion
tmpByte := (strtoint(versionPart) AND $FF);
tmpDriverVersion := tmpDriverVersion + (tmpByte * $00000100);
end;
if allOK then
begin
StrongDiskDriverVersion := tmpDriverVersion;
end;
end;
end; // GetFileVersionInfo(...) successful
finally
FreeMem(pBlock);
end;
end;
end;
Result := StrongDiskDriverVersion;
end;
function TOTFEStrongDisk.VersionStr(): string;
var
verNo: cardinal;
majorVer : integer;
minorVer1: integer;
minorVer2: integer;
begin
verNo:= Version();
majorVer := (verNo AND $FF000000) div $FF;
minorVer1 := (verNo AND $FF0000) div $FF;
minorVer2 := (verNo AND $FF00);
Result := Format('v%d.%d.%d', [majorVer, minorVer1, minorVer2]);
end;
function TOTFEStrongDisk.GetNextUnusedDrvLtr(afterDrv: char): char;
var
finished: boolean;
unusedDrvs: string;
begin
Result := #0;
finished := FALSE;
unusedDrvs := GetUnusedDriveLetters();
while not(finished) do
begin
afterDrv := chr(ord(afterDrv)+1);
if ord(afterDrv)>ord('Z') then
begin
finished := TRUE;
end
else
begin
if pos(afterDrv, unusedDrvs)>0 then
begin
Result := afterDrv;
finished := TRUE;
end;
end;
end;
end;
// Returns a string containing the drive letters of "unallocated" drives
function TOTFEStrongDisk.GetUnusedDriveLetters(): string;
var
driveLetters: string;
DriveNum: Integer;
DriveBits: set of 0..25;
begin
driveLetters := '';
Integer(DriveBits) := GetLogicalDrives;
for DriveNum := 0 to 25 do
begin
if not(DriveNum in DriveBits) then
begin
driveLetters := driveLetters + Char(DriveNum + Ord('A'));
end;
end;
Result := driveLetters;
end;
// Get the full path & filename to the executable
function TOTFEStrongDisk.GetMainExe(): string;
var
dirRead: string;
begin
Result := '';
FLastErrCode:= OTFE_ERR_UNABLE_TO_LOCATE_FILE;
dirRead := GetInstallDir();
if (dirRead<>'') then
begin
Result := dirRead + '\' + STRONGDISK_EXE;
FLastErrCode:= OTFE_ERR_SUCCESS;
end;
end;
// Get the installation dir from the registry
function TOTFEStrongDisk.GetInstallDir(): string;
var
registry: TRegistry;
keyName: string;
dirRead: string;
begin
Result := '';
FLastErrCode:= OTFE_ERR_UNABLE_TO_LOCATE_FILE;
registry := TRegistry.create();
try
registry.RootKey := HKEY_LOCAL_MACHINE;
keyName := STRONGDISK_REGISTRY_ENTRY_PATH;
if registry.OpenKeyReadOnly(keyName) then
begin
dirRead := registry.ReadString('');
if DirectoryExists(dirRead) then
begin
Result := dirRead;
end;
registry.CloseKey;
end;
finally
registry.Free();
end;
if Result<>'' then
begin
FLastErrCode:= OTFE_ERR_SUCCESS;
end;
end;
// =============================================================================
// DLL FUNCTIONS ===============================================================
// From the API details:
// SDMount(): mount a secure drive
// return value:
// an error code;
// arguments:
// driveLetter - the letter of the mounted drive ('A'-'Z','a'-'z');
// fileName - ASCIIZ file name of the image to be mounted;
// readOnly - drive acess mode (nonzero-read only, zero-read/write);
// autolaunch - run programs from 'Startup' folder after mounting
// (nonzero-run the programs, zero-don't run the programs);
// keyMode - a combination of SDKM_... constants;
// keyFileName - ASCIIZ key file name (if SDKM_KEYFILE is used);
// password - password with any characters (if SDKM_PASSWORD is used);
// passwordSize - size of data pointed to by the 'password' argument
// (if password is zero terminated passwordSize must include the
// terminating zero for compatibility with the StrongDisk interface
//STRDISKAPI unsigned SDMount(char driveLetter, const char* fileName,
// char readOnly, char autolaunch, unsigned keyMode,
// const char* keyFileName, const char* password, unsigned passwordSize);
function TOTFEStrongDisk.CallSDMount(driveLetter: char;
filename: string;
readonly: boolean;
autolaunch: boolean;
keymode: integer;
keyFilename: string;
password: string): boolean;
var
SDFunc: TSDMountFunc;
funcResult: DWORD;
readonlyByte: byte;
autolaunchByte: byte;
ptrKeyFilename: PChar;
ptrPassword: PChar;
lenPassword: DWORD;
begin
Result := FALSE;
driveLetter := upcase(driveLetter);
// Call the DLL to mount the volume
@SDFunc := GetProcAddress(hStrongDiskDLL, ''+DLL_FUNCTIONNAME_SDMOUNT+'');
if @SDFunc=nil then
begin
raise EStrongDiskBadDLL.Create(E_STRONGDISK_BAD_DLL+' ('+DLL_FUNCTIONNAME_SDMOUNT+')');
end;
readonlyByte:= 0;
if readonly then
begin
readonlyByte := 1;
end;
autolaunchByte:= 0;
if autolaunch then
begin
autolaunchByte := 1;
end;
ptrKeyFilename := nil;
if ((keymode AND SDKM_KEYFILE)>0) then
begin
ptrKeyFilename := PChar(keyFilename);
end;
ptrPassword := nil;
lenPassword := 0;
if ((keymode AND SDKM_PASSWORD)>0) then
begin
ptrPassword := PChar(password);
lenPassword := length(password);
end;
funcResult := SDFunc(driveLetter,
PChar(filename),
readonlyByte,
autolaunchByte,
keyMode,
ptrKeyFilename,
ptrPassword,
lenPassword);
if funcResult<>SDE_OK then
begin
// Set the LastErrorCode to something appropriate
LastErrorCode := TranslateDLLError(funcResult);
end
else
begin
Result := TRUE;
end;
end;
// From the API details:
// SDDismount(): unmount a secure drive
// return value : an error code;
// arguments :
// driveLetter - the letter of a secure drive to be dismounted
// ('A'-'Z','a'-'z');
// force - check for open files or not (nonzero-don't check, zero-check) */
//STRDISKAPI unsigned SDDismount(char driveLetter, char force);
function TOTFEStrongDisk.CallSDDismount(driveLetter: char;
force: boolean): boolean;
var
SDFunc: TSDDismountFunc;
funcResult: DWORD;
forceByte: byte;
begin
Result := FALSE;
driveLetter:= upcase(driveLetter);
// Call the DLL to mount the volume
@SDFunc := GetProcAddress(hStrongDiskDLL, ''+DLL_FUNCTIONNAME_SDDISMOUNT+'');
if @SDFunc=nil then
begin
raise EStrongDiskBadDLL.Create(E_STRONGDISK_BAD_DLL+' ('+DLL_FUNCTIONNAME_SDDISMOUNT+')');
end;
forceByte:= 0;
if force then
begin
forceByte := 1;
end;
funcResult := SDFunc(driveLetter,
forceByte);
if funcResult<>SDE_OK then
begin
// Set the LastErrorCode to something appropriate
LastErrorCode := TranslateDLLError(funcResult);
end
else
begin
Result := TRUE;
end;
end;
// From the API details:
// SDDismountAll(): unmount all secure drives;
// return value : an error code;
// arguments :
// force - check for open files or not (nonzero-don't check, zero-check) */
//STRDISKAPI unsigned SDDismountAll(char force);
function TOTFEStrongDisk.CallSDDismountAll(force: boolean): boolean;
var
SDFunc: TSDDismountAllFunc;
funcResult: DWORD;
forceByte: byte;
begin
Result := FALSE;
// Call the DLL to mount the volume
@SDFunc := GetProcAddress(hStrongDiskDLL, ''+DLL_FUNCTIONNAME_SDDISMOUNTALL+'');
if @SDFunc=nil then
begin
raise EStrongDiskBadDLL.Create(E_STRONGDISK_BAD_DLL+' ('+DLL_FUNCTIONNAME_SDDISMOUNTALL+')');
end;
forceByte:= 0;
if force then
begin
forceByte := 1;
end;
funcResult := SDFunc(forceByte);
if funcResult<>SDE_OK then
begin
// Set the LastErrorCode to something appropriate
LastErrorCode := TranslateDLLError(funcResult);
end
else
begin
Result := TRUE;
end;
end;
// SDGetDrives(): get bitmask representing the secure drives;
// return value : an error code;
// arguments :
// drives - pointer to variable that will receive the bitmask
// (bit 0 (the least-significant)-'A', bit 1-'B', ...) */
//STRDISKAPI unsigned SDGetDrives(unsigned* drives);
function TOTFEStrongDisk.CallSDGetDrives(var drives: string): boolean;
var
i: integer;
currBit: cardinal;
drivesBitmask: DWORD;
SDFunc: TSDGetDrivesFunc;
funcResult: DWORD;
begin
// Call the DLL to set "drivesBitmask"
@SDFunc := GetProcAddress(hStrongDiskDLL, ''+DLL_FUNCTIONNAME_SDGETDRIVES+'');
if @SDFunc=nil then
begin
raise EStrongDiskBadDLL.Create(E_STRONGDISK_BAD_DLL+' ('+DLL_FUNCTIONNAME_SDGETDRIVES+')');
end;
funcResult := SDFunc(@drivesBitmask);
if funcResult<>SDE_OK then
begin
raise EStrongDiskDLLFailure.Create(E_STRONGDISK_DLL_FAILURE+' ('+DLL_FUNCTIONNAME_SDGETDRIVES+')');
end;
drives := '';
currBit := 1;
for i:=1 to 26 do
begin
if ((drivesBitmask AND currBit)>0) then
begin
drives := drives + chr(ord('A')+i-1);
end;
currBit := currBit * 2;
end;
Result := TRUE;
end;
// From the API details:
// SDGetInfo(): get information about the secure drive;
// return value : an error code;
// arguments :
// driveLetter - the letter of a secure drive of interest ('A'-'Z','a'-'z');
// fileName - buffer that will receive the drive image file name;
// size - the size of the 'fileName' buffer; on return it will contain
// the size of the file name (including terminating '\0'); you can set
// *size to 0 to obtain the required buffer size;
// readOnly - it will receive the access mode of the drive
// (1-read only; 0-read/write) */
//STRDISKAPI unsigned SDGetInfo(char driveLetter,
// char* fileName, unsigned* size, char* readOnly);
function TOTFEStrongDisk.CallSDGetInfo(driveLetter: char;
var filename: string;
var readonly: boolean): boolean;
var
SDFunc: TSDGetInfoFunc;
funcResult: DWORD;
filenameSize: DWORD;
readonlyByte: byte;
arrFilename: array of char;
begin
Result := FALSE;
driveLetter := upcase(driveLetter);
// Call the DLL to mount the volume
@SDFunc := GetProcAddress(hStrongDiskDLL, ''+DLL_FUNCTIONNAME_SDGETINFO+'');
if @SDFunc=nil then
begin
raise EStrongDiskBadDLL.Create(E_STRONGDISK_BAD_DLL+' ('+DLL_FUNCTIONNAME_SDGETINFO+')');
end;
// Obtain length of "filename"
funcResult := SDFunc(driveLetter,
nil,
@filenameSize,
@readonlyByte);
if funcResult<>SDE_OK then
begin
// Set the LastErrorCode to something appropriate
LastErrorCode := TranslateDLLError(funcResult);
// Result already set to FALSE, so just exit
exit;
end
else
begin
Result := TRUE;
end;
SetLength(arrFilename, filenameSize+2);
funcResult := SDFunc(driveLetter,
@arrFilename[1],
@filenameSize,
@readonlyByte);
if funcResult<>SDE_OK then
begin
// Set the LastErrorCode to something appropriate
LastErrorCode := TranslateDLLError(funcResult);
// Result already set to FALSE, so just exit
exit;
end
else
begin
Result := TRUE;
end;
end;
function TOTFEStrongDisk.TranslateDLLError(DLLerror: DWORD): integer;
var
retVal: integer;
begin
retVal := OTFE_ERR_UNKNOWN_ERROR;
case DLLerror of
// ERROR CODES
// operation succeded
SDE_OK : retVal := OTFE_ERR_SUCCESS;
// operation failed; unexpected error
SDE_ERROR : retVal := OTFE_ERR_UNKNOWN_ERROR;
// unable load a driver; possible causes: not sufficient system resources; the driver is not installed
SDE_UNABLE_LOAD_DRIVER : retVal := OTFE_ERR_DRIVER_FAILURE;
// not enough memory
SDE_NOT_ENOUGH_MEMORY : retVal := OTFE_ERR_DRIVER_FAILURE;
// failed to open or to read a file
SDE_ACCESS_DENIED : retVal := OTFE_ERR_MOUNT_FAILURE;
// unable unmount a secure drive due to open file
SDE_UNMOUNT_OPEN_FILE : retVal := OTFE_ERR_FILES_OPEN;
// the drive specified is not a StrongDisk drive
SDE_NOT_SDDRIVE : retVal := OTFE_ERR_INVALID_DRIVE;
// attempting to mount a StrongDisk image from a StrongDisk drive; StrongDisk drives don't support recursion
SDE_MOUNT_ON_SDDRIVE : retVal := OTFE_ERR_MOUNT_FAILURE;
// mounting the StrongDisk drive is not allowed by the registration
SDE_NOT_REGISTERED : retVal := OTFE_ERR_DRIVER_FAILURE;
// the file specified is not a StrongDisk drive image
SDE_INVALID_IMAGE : retVal := OTFE_ERR_FILE_NOT_ENCRYPTED_VOLUME;
// the used cryptographic library does not support an algorithm that is used in the image
SDE_UNSUPPORTED_ALGORITHM : retVal := OTFE_ERR_DRIVER_FAILURE;
// the password specified is invalid
SDE_INVALID_PASSWORD : retVal := OTFE_ERR_WRONG_PASSWORD;
// device (a drive) is not ready
SDE_KEYFILE_NOT_READY : retVal := OTFE_ERR_DISMOUNT_FAILURE;
// the file specified is too short to be a key
SDE_KEYFILE_SHORT : retVal := OTFE_ERR_MOUNT_FAILURE;
// the key file is not found
SDE_KEYFILE_NOT_FOUND : retVal := OTFE_ERR_MOUNT_FAILURE;
// unable to open or to read the key file
SDE_KEYFILE_ERROR : retVal := OTFE_ERR_UNABLE_TO_LOCATE_FILE;
// unable to open an electronic key
SDE_ELKEY_UNABLE_OPEN_DEVICE : retVal := OTFE_ERR_MOUNT_FAILURE;
// unable to open key file on the electronic key
SDE_ELKEY_UNABLE_OPEN_FILE : retVal := OTFE_ERR_MOUNT_FAILURE;
// unable to read key file on the electronic key
SDE_ELKEY_UNABLE_READ_FILE : retVal := OTFE_ERR_MOUNT_FAILURE;
// access to electronic key failed
SDE_ELKEY_ERROR : retVal := OTFE_ERR_MOUNT_FAILURE;
// SDE_INVALID_PARAMETER_1: the first parameter is invalid
SDE_INVALID_PARAMETER_1 : retVal := OTFE_ERR_UNKNOWN_ERROR;
SDE_INVALID_PARAMETER_2 : retVal := OTFE_ERR_UNKNOWN_ERROR;
SDE_INVALID_PARAMETER_3 : retVal := OTFE_ERR_UNKNOWN_ERROR;
SDE_INVALID_PARAMETER_4 : retVal := OTFE_ERR_UNKNOWN_ERROR;
SDE_INVALID_PARAMETER_5 : retVal := OTFE_ERR_UNKNOWN_ERROR;
SDE_INVALID_PARAMETER_6 : retVal := OTFE_ERR_UNKNOWN_ERROR;
SDE_INVALID_PARAMETER_7 : retVal := OTFE_ERR_UNKNOWN_ERROR;
SDE_INVALID_PARAMETER_8 : retVal := OTFE_ERR_UNKNOWN_ERROR;
SDE_INVALID_PARAMETER_9 : retVal := OTFE_ERR_UNKNOWN_ERROR;
SDE_INVALID_PARAMETER_10 : retVal := OTFE_ERR_UNKNOWN_ERROR;
// ...
SDE_INVALID_PARAMETER_100 : retVal := OTFE_ERR_UNKNOWN_ERROR;
end;
Result := retVal;
end;
// -----------------------------------------------------------------------------
// Prompt the user for a device (if appropriate) and password (and drive
// letter if necessary), then mount the device selected
// Returns the drive letter of the mounted devices on success, #0 on failure
function TOTFEStrongDisk.MountDevices(): string;
begin
// Not supported...
Result := #0;
end;
// -----------------------------------------------------------------------------
// Determine if OTFE component can mount devices.
// Returns TRUE if it can, otherwise FALSE
function TOTFEStrongDisk.CanMountDevice(): boolean;
begin
// Not supported...
Result := FALSE;
end;
// -----------------------------------------------------------------------------
END.
|
unit FMAPPE;
interface
uses {Windows,} SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls,
GifDecl;
type
TAPPEDialog = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
Bevel1: TBevel;
Label1: TLabel;
AppIdentifierMemo: TMemo;
Label2: TLabel;
AppAuthenticationCodeMemo: TMemo;
AppDataMemo: TMemo;
Label3: TLabel;
private
{ Private declarations }
public
{ Public declarations }
constructor Create(APPE: TApplicationExtension);
function GetAPPE: TApplicationExtension;
end;
var
APPEDialog: TAPPEDialog;
implementation
{$R *.DFM}
constructor TAPPEDialog.Create(APPE: TApplicationExtension);
var i: Integer;
IDLine: String;
begin { TAPPEDialog.Create }
inherited Create(nil);
with APPE
do begin
for i := 1 to 8
do begin
IDLine := '$'+IntToHex(APPE.ApplicationIdentifier[i], 2) + ' ' +
Chr(APPE.ApplicationIdentifier[i]);
AppIdentifierMemo.Lines.Add(IDLine);
end;
for i := 1 to 3
do begin
IDLine := '$'+IntToHex(APPE.AppAuthenticationCode[i], 2) + ' ' +
Chr(APPE.AppAuthenticationCode[i]);
AppAuthenticationCodeMemo.Lines.Add(IDLine);
end;
AppDataMemo.Lines := APPE.AppData;
end;
end; { TAPPEDialog.Create }
function TAPPEDialog.GetAPPE: TApplicationExtension;
var i, Value: Byte;
begin { TAPPEDialog.GetAPPE }
with Result
do begin
for i := 1 to 8
do begin
Value := StrToInt(Copy(AppIdentifierMemo.Lines[i-1], 1, 3));
Result.ApplicationIdentifier[i] := Value;
end;
for i := 1 to 3
do begin
Value := StrToInt(Copy(AppAuthenticationCodeMemo.Lines[i-1], 1, 3));
Result.AppAuthenticationCode[i] := Value;
end;
Result.AppData := TStringList.Create;
Result.AppData.Assign(AppDataMemo.Lines);
end;
end; { TAPPEDialog.GetAPPE }
end.
|
unit uModReceipt;
interface
uses
uModApp, uModRekening, uModOrganization, uModBank, uModTipePembayaran,
uModAR, uModAP, uModCostCenter;
type
TModReceipt = class(TModApp)
private
FREC_NOBUKTI: string;
FREC_TGLBUKTI: TDateTime;
FREC_NOMINAL: Double;
FREC_DESCRIPTION: string;
FREC_BANK: TModBank;
FREC_NOREF: string;
FREC_ORGANIZATION: TModOrganization;
FREC_TIPEPEMBAYARAN: TModTipePembayaran;
FREKENING: TModRekening;
public
class function GetTableName: String; override;
published
[AttributeOfCode]
property REC_NOBUKTI: string read FREC_NOBUKTI write FREC_NOBUKTI;
property REC_TGLBUKTI: TDateTime read FREC_TGLBUKTI write FREC_TGLBUKTI;
property REC_NOMINAL: Double read FREC_NOMINAL write FREC_NOMINAL;
property REC_DESCRIPTION: string read FREC_DESCRIPTION write FREC_DESCRIPTION;
property REC_BANK: TModBank read FREC_BANK write FREC_BANK;
property REC_NOREF: string read FREC_NOREF write FREC_NOREF;
property REC_ORGANIZATION: TModOrganization read FREC_ORGANIZATION write
FREC_ORGANIZATION;
property REC_TIPEPEMBAYARAN: TModTipePembayaran read FREC_TIPEPEMBAYARAN write
FREC_TIPEPEMBAYARAN;
property REKENING: TModRekening read FREKENING write FREKENING;
end;
TModReceiptARItem = class(TModApp)
private
FRECARITEM_AR: TModAR;
FRECARITEM_DESCRIPTION: string;
FRECARITEM_NOMINAL: Double;
public
class function GetTableName: String; override;
published
property RECARITEM_AR: TModAR read FRECARITEM_AR write FRECARITEM_AR;
property RECARITEM_DESCRIPTION: string read FRECARITEM_DESCRIPTION write
FRECARITEM_DESCRIPTION;
property RECARITEM_NOMINAL: Double read FRECARITEM_NOMINAL write
FRECARITEM_NOMINAL;
end;
type
TModReceiptAPItem = class(TModApp)
private
FRECAPITEM_REKENING: TModRekening;
FRECAPITEM_AP: TModAP;
FRECAPITEM_DESCRIPTION: string;
FRECAPITEM_NOMINAL: Double;
FRECARITEM_DUEDATE: TDateTime;
public
class function GetTableName: String; override;
published
property RECAPITEM_REKENING: TModRekening read FRECAPITEM_REKENING write
FRECAPITEM_REKENING;
property RECAPITEM_AP: TModAP read FRECAPITEM_AP write FRECAPITEM_AP;
property RECAPITEM_DESCRIPTION: string read FRECAPITEM_DESCRIPTION write
FRECAPITEM_DESCRIPTION;
property RECAPITEM_NOMINAL: Double read FRECAPITEM_NOMINAL write
FRECAPITEM_NOMINAL;
property RECARITEM_DUEDATE: TDateTime read FRECARITEM_DUEDATE write
FRECARITEM_DUEDATE;
end;
type
TModReceiptOI = class(TModApp)
private
FRECOIITEM_ALLOCATION: TModCostCenter;
FRECOIITEM_REKENING: TModRekening;
FRECOIITEM_DESCRIPTION: string;
FRECOIITEM_NOMINAL: Double;
public
class function GetTableName: String; override;
published
property RECOIITEM_ALLOCATION: TModCostCenter read FRECOIITEM_ALLOCATION write
FRECOIITEM_ALLOCATION;
property RECOIITEM_REKENING: TModRekening read FRECOIITEM_REKENING write
FRECOIITEM_REKENING;
property RECOIITEM_DESCRIPTION: string read FRECOIITEM_DESCRIPTION write
FRECOIITEM_DESCRIPTION;
property RECOIITEM_NOMINAL: Double read FRECOIITEM_NOMINAL write
FRECOIITEM_NOMINAL;
end;
type
TModReceiptChequeItem = class(TModApp)
private
FRECCHEQUEIITEM_CHECKNUM: string;
FRECCHEQUEIITEM_BANK: string;
FRECCHEQUEIITEM_DESCRIPTION: string;
FRECCHEQUEIITEM_DUEDATE: TDateTime;
FRECCHEQUEIITEM_NOMINAL: Double;
public
class function GetTableName: String; override;
published
property RECCHEQUEIITEM_CHECKNUM: string read FRECCHEQUEIITEM_CHECKNUM write
FRECCHEQUEIITEM_CHECKNUM;
property RECCHEQUEIITEM_BANK: string read FRECCHEQUEIITEM_BANK write
FRECCHEQUEIITEM_BANK;
property RECCHEQUEIITEM_DESCRIPTION: string read FRECCHEQUEIITEM_DESCRIPTION
write FRECCHEQUEIITEM_DESCRIPTION;
property RECCHEQUEIITEM_DUEDATE: TDateTime read FRECCHEQUEIITEM_DUEDATE write
FRECCHEQUEIITEM_DUEDATE;
property RECCHEQUEIITEM_NOMINAL: Double read FRECCHEQUEIITEM_NOMINAL write
FRECCHEQUEIITEM_NOMINAL;
end;
implementation
class function TModReceipt.GetTableName: String;
begin
Result := 'RECEIPT';
end;
class function TModReceiptARItem.GetTableName: String;
begin
Result := 'RECEIPT_ARITEM';
end;
class function TModReceiptAPItem.GetTableName: String;
begin
Result := 'RECEIPT_ARITEM';
end;
class function TModReceiptOI.GetTableName: String;
begin
Result := 'RECEIPT_ARITEM';
end;
class function TModReceiptChequeItem.GetTableName: String;
begin
Result := 'RECEIPT_ARITEM';
end;
initialization
TModReceipt.RegisterRTTI;
end.
|
unit TrackBar2; { TDQTrackBar component. }
{ Created 12/23/97 3:19:26 PM }
{ Eagle Software CDK, Version 2.02 Rev. C }
{$D-}
{$L-}
interface
uses
Windows,
SysUtils,
Messages,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
Menus,
ComCtrls;
type
TDQTrackBar = class(ttrackbar)
private
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published properties and events }
{ Inherited events: }
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end; { TDQTrackBar }
procedure Register;
implementation
destructor TDQTrackBar.Destroy;
begin
{ CDK: Free allocated memory and created objects here. }
inherited Destroy;
end; { Destroy }
constructor TDQTrackBar.Create(AOwner: TComponent);
{ Creates an object of type TDQTrackBar, and initializes properties. }
begin
inherited Create(AOwner);
{ CDK: Add your initialization code here. }
end; { Create }
procedure Register;
begin
RegisterComponents('NRC', [TDQTrackBar]);
end; { Register }
end.
|
unit wmutil;
interface
uses
Windows, DXDraws;
type
TWMImageHeader = record
Title: String[40]; // 库文件标题 'WEMADE Entertainment inc.'
ImageCount: integer; // 图片数量
ColorCount: integer; // 色彩数量
PaletteSize: integer; // 调色板大小
VerFlag:integer;
end;
PTWMImageHeader = ^TWMImageHeader;
TWMImageInfo = record
nWidth :SmallInt; // 位图宽度
nHeight :SmallInt; // 位图高度
px: smallint;
py: smallint;
bits: PByte;
end;
PTWMImageInfo = ^TWMImageInfo;
TWMIndexHeader = record
Title: string[40]; //'WEMADE Entertainment inc.'
IndexCount: integer; // 索引总数
VerFlag:integer;
end;
PTWMIndexHeader = ^TWMIndexHeader;
TWMIndexInfo = record
Position: integer;
Size: integer;
end;
PTWMIndexInfo = ^TWMIndexInfo;
TDXImage = record
nPx :SmallInt;
nPy :SmallInt;
Surface :TDirectDrawSurface;
dwLatestTime :LongWord;
end;
pTDxImage = ^TDXImage;
function WidthBytes(w: Integer): Integer;
implementation
function WidthBytes(w: Integer): Integer;
begin
Result := (((w * 8) + 31) div 32) * 4;
end;
end.
|
unit uConversao;
interface
type
TConversao = class
function Converter: string; virtual; abstract;
end;
TConverteTexto = class(TConversao)
private
FTexto: string;
FQuantidadeLetras: integer;
procedure SetTexto(const Value: string);
procedure SetQuantidadeLetras(const Value: integer);
public
function Converter: string; override;
property Texto: string read FTexto write SetTexto;
property QuantidadeLetras: integer read FQuantidadeLetras write SetQuantidadeLetras;
end;
TConverteInvertido = class(TConverteTexto)
public
function Converter: string; override;
end;
TConvertePrimeiraMaiuscula = class(TConverteTexto)
public
function Converter: string; override;
end;
TConverteOrdenado = class(TConverteTexto)
public
function Converter: string; override;
end;
const
nINVERTIDO = 0;
nPRIMEIRA_MAIUSCULA = 1;
nORDEM_ALFABETICA = 2;
nNUMERO_INDEFINIDO = -999;
implementation
uses
System.SysUtils, System.StrUtils, System.Types, System.Classes;
{ TConverteTexto }
function TConverteTexto.Converter: string;
begin
// Sem codificação
end;
procedure TConverteTexto.SetQuantidadeLetras(const Value: integer);
begin
FQuantidadeLetras := Value;
end;
procedure TConverteTexto.SetTexto(const Value: string);
begin
if Value = EmptyStr then
Exit;
FTexto := Value;
end;
{ TConverteInvertido }
function TConverteInvertido.Converter: string;
var
sTexto: string;
begin
sTexto := FTexto;
if FQuantidadeLetras <> nNUMERO_INDEFINIDO then
sTexto := Copy(FTexto, 0, FQuantidadeLetras);
Result := System.StrUtils.ReverseString(sTexto);
end;
{ TConverteOrdenado }
{Todas as letras em ordem alfabética}
function TConverteOrdenado.Converter: string;
var
sTexto: string;
sTemp: string;
nContador: Integer;
lsTexto: TStringList;
begin
sTexto := FTexto;
if FQuantidadeLetras <> nNUMERO_INDEFINIDO then
sTexto := Copy(FTexto, 0, FQuantidadeLetras);
lsTexto := TStringList.Create;
try
for nContador := 1 to (Length(sTexto) + 1) do
begin
sTemp := Copy(sTexto, nContador, 1);
if Trim(sTemp) <> EmptyStr then
lsTexto.Add(sTemp);
end;
lsTexto.Sort;
for nContador := 0 to (lsTexto.Count - 1) do
begin
Result := Result + lsTexto[nContador];
end;
finally
FreeAndNil(lsTexto);
end;
end;
{ TConvertePrimeiraMaiuscula }
function TConvertePrimeiraMaiuscula.Converter: string;
var
sTexto: string;
lsTexto: TStringDynArray;
nContador: Integer;
begin
sTexto := FTexto;
if FQuantidadeLetras <> nNUMERO_INDEFINIDO then
sTexto := Copy(FTexto, 0, FQuantidadeLetras);
lsTexto := System.StrUtils.SplitString(sTexto, ' ');
for nContador := Low(lsTexto) to High(lsTexto) do
begin
lsTexto[nContador] := LowerCase(lsTexto[nContador]);
sTexto := UpperCase(Copy(lsTexto[nContador], 1, 1)) + Copy(lsTexto[nContador], 2, Length(lsTexto[nContador]));
lsTexto[nContador] := sTexto;
Result := Result + ' ' + sTexto;
end;
end;
end.
|
unit Литера8х8;
uses GraphABC;
type
тТочка = class
private
/// Скрытое свойство состояния
_сост: boolean := false;
/// Размер одной точки
_размер: integer = 10;
/// Координаты точки
_х_поз: integer = 0;
_у_поз: integer = 0;
public
property сост: boolean read _сост;
constructor Create(размер, х_поз, у_поз: integer);
begin
self._размер := размер;
self._х_поз := х_поз;
self._у_поз := у_поз;
self.Рисовать;
end;
/// Переключение состояния точки
procedure Переключить;
begin
if self._сост then
begin
self._сост := false;
self.Рисовать;
end
else
begin
self._сост := true;
self.Рисовать;
end;
end;
/// Рисует по разному (в зависимости от состояния) клетку точки
procedure Рисовать;
begin
if self._сост then
begin
Brush.Color := RGB($FF, $FF, $80);
FillRect(self._х_поз, self._у_поз, self._х_поз + self._размер, self._у_поз + self._размер);
end
else
begin
Brush.Color := RGB(0, 0, 0);
FillRect(self._х_поз, self._у_поз, self._х_поз + self._размер, self._у_поз + self._размер);
Brush.Color := RGB($70, $70, $70);
//DrawRectangle(self._х_поз, self._у_поз, self._х_поз + self._размер, self._у_поз + self._размер);
Rectangle(self._х_поз, self._у_поз, self._х_поз + self._размер, self._у_поз + self._размер);
end;
end;
end;
тСтрока8х = class
private
/// Размер одиночной клетки
_размер: integer = 10;
/// Позиция строки
_х_поз: integer = 0;
_у_поз: integer = 0;
/// Числовое представление строки битов
function _Число_Получ(): integer;
begin
var sum := 0;
for var i := 0 to 7 do
if self.тчк[7 - i].сост then
sum += (1 shl i);
result := sum;
end;
public
/// Массив точек
тчк: array [0..7] of тТочка;
property число: integer read _Число_Получ;
constructor Create(размер, х_поз, у_поз: integer);
begin
self._размер := размер;
self._х_поз := х_поз;
self._у_поз := у_поз;
for var x := 0 to 7 do
begin
self.тчк[x] := new тТочка(размер, х_поз + x * self._размер, у_поз);
end;
end;
/// Переключает одну из точек в строке
procedure Переключить(x: integer);
begin
Assert((0 <= x) and (x <= 7));
self.тчк[x].Переключить;
end;
/// Рисует строку клеток
procedure Рисовать;
begin
for var x := 0 to 7 do
self.тчк[x].Рисовать;
end;
end;
///Тип отображаемой литеры 8х8
тЛит8х8 = class
private
/// размер клетки
_размер: integer = 10;
_min: integer = 0;
_max: integer = 7;
procedure _Мини_Рисовать;
begin
var x_pos: integer = self.х_смещ + (((self._max + 1) * self._размер) shr 2 )+ 50;
var y_pos: integer = self.у_смещ + (self._max + 1) * self._размер + 50;
for var y: integer := 0 to 7 do
for var x: integer := 0 to 7 do
begin
if self.стр[y].тчк[x].сост then
SetPixel(x_pos + x, y_pos + y, clGray)
else
SetPixel(x_pos + x, y_pos + y, clBlack);
end;
end;
/// Отображение чисел после клика
procedure _Числа_Показ;
begin
var x_pos: integer = self.х_смещ + (self._max + 1) * self._размер + (self._размер shr 2);
var y_pos: integer = self.у_смещ + (self._размер shr 2);
var y: integer := self._max;
while y >= self._min do
begin
Font.Name := 'Consolas';
Font.Size := 11;
Brush.Color := clWhite;
var txt := IntToStr(self.стр[y].число);
while Length(txt) < 3 do
txt := ' ' + txt;
TextOut(x_pos, y_pos + y * self._размер, txt);
y -= 1;
end;
end;
public
/// Массив строк
стр: array [0..7] of тСтрока8х;
/// Начальное смещение по х
х_смещ: integer = 50;
/// Начальное смещение по y
у_смещ: integer = 50;
property min: integer read _min;
property max: integer read _max;
constructor Create(размер, х_смещ: integer);
begin
self._размер := размер;
self.х_смещ := х_смещ;
for var y := 0 to self._max do
begin
self.стр[y] := new тСтрока8х(размер, х_смещ, у_смещ + y * self._размер);
end;
end;
/// Проверяет находятся ли x, y в допустимом диапазоне
function Провер(var x, y: integer): boolean;
var
_res: boolean = False;
begin
if (x >= self.х_смещ) and (x <= self.х_смещ + (self._max + 1) * self._размер) and
(y >= self.у_смещ) and (y <= self.у_смещ + (self._max + 1) * self._размер) then
begin
x := (x - self.х_смещ) div self._размер;
y := (y - self.у_смещ) div self._размер;
if (x >= self._min) and (x <= self._max) and (y >= self._min) and (y <= self._max) then
_res := True;
Result := _res;
end;
end;
/// Рисует литеру целиком
procedure Рисовать;
begin
for var y := 0 to 7 do
self.стр[y].Рисовать;
self._Мини_Рисовать;
end;
/// Переключение отдельных битов
procedure Переключить(x, y: integer);
begin
self.стр[y].Переключить(x);
self._Мини_Рисовать;
self._Числа_Показ;
end;
/// Рисует отметки напротив клеток по двум осям
procedure Оси_Рис;
begin
var x_pos: integer = self.х_смещ + (self._размер shr 2) - 2;
var x1_pos: integer = x_pos - (self._размер shr 2) - 10;
var y_pos: integer = self.у_смещ - (self._размер shr 2) - 13;
var y1_pos: integer = self.у_смещ + (self._размер shr 2);
Font.Name := 'Consolas';
Font.Size := 11;
Brush.Color := clYellow;
var x: integer := self._max;
while x >= self._min do
begin
TextOut(x_pos + x * self._размер, y_pos, IntToStr(7 - x));
x -= 1;
end;
var y: integer := self._max;
while y >= self._min do
begin
TextOut(x1_pos, y1_pos + y * self._размер, IntToStr(y));
y -= 1;
end;
end;
end;
begin
end. |
unit CodeExpert;
interface
uses
Windows, Messages, SysUtils, Classes,
EasyClasses, EasyEditSource, EasyEditor, EasyParser,
PhpParser, EasyEditState;
type
TCodeExpert = class
private
{ Private declarations }
FEasyEdit: TEasyEdit;
FEasyParser: TEasyEditorParser;
FEasyEditState: TEasyEditState;
FCodeInfo: TUnitInfo;
FNames: TStringList;
protected
procedure SetEasyEdit(const Value: TEasyEdit);
protected
function GlobalsToDecl(inStrings: TStrings): string;
procedure ParseCode;
procedure ProcessFunctionGlobals(Strings: TStrings);
public
{ Public declarations }
constructor Create(inEasyEdit: TEasyEdit = nil);
destructor Destroy; override;
procedure UpdateGlobals(inNames: TStringList);
public
property EasyEdit: TEasyEdit read FEasyEdit write SetEasyEdit;
property EasyParser: TEasyEditorParser read FEasyParser
write FEasyParser;
end;
implementation
{ TCodeExpert }
constructor TCodeExpert.Create(inEasyEdit: TEasyEdit = nil);
begin
FCodeInfo := TUnitInfo.Create;
FEasyEditState := TEasyEditState.Create;
EasyEdit := inEasyEdit;
end;
destructor TCodeExpert.Destroy;
begin
FEasyEditState.Free;
FCodeInfo.Free;
inherited;
end;
procedure TCodeExpert.SetEasyEdit(const Value: TEasyEdit);
begin
FEasyEdit := Value;
if (EasyEdit <> nil) then
EasyParser := TEasyEditorParser(EasyEdit.Parser);
end;
function TCodeExpert.GlobalsToDecl(inStrings: TStrings): string;
var
i: Integer;
begin
if inStrings.Count = 0 then
Result := ''
else begin
Result := ' global ' + inStrings[0];
for i := 1 to Pred(inStrings.Count) do
Result := Result + ', ' + inStrings[i];
Result := Result + ';'
end;
end;
procedure TCodeExpert.ProcessFunctionGlobals(Strings: TStrings);
var
i, line, added: Integer;
info: TElementInfo;
procedure AddMissingNamedGlobal(const inVar: string);
begin
with TFunctionInfo(info).GlobalDecls do
if (FNames.IndexOfName(inVar) > -1) and (IndexOf(inVar) = -1) then
Add(inVar);
end;
procedure InsertLine(inStrings: TStrings; inLineNo: Integer);
var
i: Integer;
info: TElementInfo;
begin
with inStrings do
for i := 0 to Count - 1 do
begin
info := TElementInfo(Objects[i]);
if (info <> nil) and (info.LineNo >= inLineNo) then
begin
info.LineNo := info.LineNo + 1;
if (info is TFunctionInfo) then
InsertLine(TFunctionInfo(info).GlobalDecls, inLineNo);
end;
end;
end;
procedure ProcessFunction;
var
i: Integer;
begin
with TFunctionInfo(info) do
begin
if GlobalDecls.Count > 0 then
line := TElementInfo(GlobalDecls.Objects[0]).LineNo + added
else
line := -1;
//
for i := 0 to Pred(UsedVars.Count) do
AddMissingNamedGlobal(UsedVars[i]);
//
if GlobalDecls.Count > 0 then
begin
if line = -1 then
begin
line := LineNo + added + 2;
InsertLine(Strings, line);
EasyEdit.Lines.Insert(line, '');
//Inc(added);
end;
EasyEdit.Lines[line] := GlobalsToDecl(GlobalDecls);
end;
end;
end;
begin
added := 0;
with Strings do
for i := 0 to Count - 1 do
begin
info := TElementInfo(Objects[i]);
if (info <> nil) {and (Info.Scope = AScope)} then
if (info is TFunctionInfo) then
ProcessFunction;
end;
end;
procedure TCodeExpert.ParseCode;
begin
if EasyEdit <> nil then
begin
FCodeInfo.Parser := EasyParser;
FCodeInfo.ReparseStrings(EasyEdit.Lines);
end else
FCodeInfo.ReparseStrings(nil);
end;
procedure TCodeExpert.UpdateGlobals(inNames: TStringList);
begin
FEasyEditState.GetState(EasyEdit);
try
EasyEdit.Lines.BeginUpdate;
try
FNames := inNames;
ParseCode;
ProcessFunctionGlobals(FCodeInfo.Functions);
finally
EasyEdit.Lines.EndUpdate;
end;
finally
FEasyEditState.SetState(EasyEdit);
end;
end;
end.
|
unit Demo.SteppedAreaChart.Custom;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_SteppedAreaChart_Custom = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_SteppedAreaChart_Custom.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_STEPPED_AREA_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Year'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Colonial'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Victorian'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Modern'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Contemporary')
]);
Chart.Data.AddRow(['2013', 5.2, 3.6, 2.8, 2]);
Chart.Data.AddRow(['2014', 5.6, 4.0, 2.8, 3]);
Chart.Data.AddRow(['2015', 7.2, 2.2, 2.2, 6]);
Chart.Data.AddRow(['2016', 8.0, 1.7, 0.8, 4]);
// Options
Chart.Options.BackgroundColor('#ddd');
Chart.Options.Legend('position', 'bottom');
Chart.Options.Colors(['#4374E0', '#53A8FB', '#F1CA3A', '#E49307']);
Chart.Options.SetAsBoolean('connectSteps', False);
Chart.Options.IsStacked(True);
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_SteppedAreaChart_Custom);
end.
|
unit UPrecoGasVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO,UCnaeVO, UCidadeVO, UEstadoVO, UPaisVO, UPessoasVO;
type
[TEntity]
[TTable('PrecoGas')]
TPrecoGasVO = class(TGenericVO)
private
FidPrecoGas: Integer;
FdtMesAno : TdateTime;
FvlGas : currency;
FNome : String;
FidPessoa : Integer;
public
PessoaVo : TPessoasVO;
[TId('idprecogas')]
[TGeneratedValue(sAuto)]
property idPrecoGas: Integer read FidPrecoGas write FidPrecoGas;
[TColumn('dtMesAno','Data Inicio',20,[ldGrid,ldLookup,ldComboBox], False)]
property dtMesAno: TDateTime read FdtMesAno write FdtMesAno;
[TColumn('idPessoa','Pessoa',0,[ldLookup,ldComboBox], False)]
property idPessoa: integer read FidPessoa write FidPessoa;
[TColumn('nome','Fornecedor',350,[ldGrid], True, 'Pessoa', 'idPessoa', 'idPessoa')]
property Nome: string read FNome write FNome;
[TColumn('vlGas','Valor Total',50,[ldGrid,ldLookup,ldComboBox], False)]
property vlGas: currency read FvlGas write FvlGas;
Procedure ValidarCamposObrigatorios;
end;
implementation
{ TPrecoGasVO }
Procedure TPrecoGasVO.ValidarCamposObrigatorios;
begin
if (Self.FvlGas <= 0) then
raise Exception.Create('O campo Valor do Gás é obrigatório!')
else if (self.FdtMesAno = 0) then
raise Exception.Create('O campo data é obrigatório!')
else if (self.idPessoa = 0 ) then
raise Exception.Create('O campo Fornecedor é obrigatório!');
end;
end.
|
unit Synch;
interface
uses
System.SyncObjs,
System.Generics.Collections;
type
TSynch = class // based on TOmniSynchronizer<T> from OtlSync.Utils
strict private
FEvents: TObjectDictionary<string, TEvent>;
FLock : TCriticalSection;
strict protected
function Ensure(const name: string): TEvent;
public
constructor Create;
destructor Destroy; override;
procedure Signal(const name: string); inline;
function WaitFor(const name: string; timeout: cardinal = INFINITE): boolean;
function SnW(const sigName, waitName: string; timeout: cardinal = INFINITE): boolean;
end; { TSynch }
implementation
uses
System.SysUtils;
{ TSynch }
constructor TSynch.Create;
begin
inherited Create;
FLock := TCriticalSection.Create;
FEvents := TObjectDictionary<string, TEvent>.Create;
end;
destructor TSynch.Destroy;
begin
FreeAndNil(FEvents);
FreeAndNil(FLock);
inherited;
end;
function TSynch.Ensure(const name: string): TEvent;
var
event: TEvent;
begin
FLock.Acquire;
try
if FEvents.TryGetValue(name, Result) then
Exit;
event := TEvent.Create(nil, true, false, '');
Result := event;
FEvents.Add(name, Result);
finally FLock.Release; end;
end;
procedure TSynch.Signal(const name: string);
begin
Ensure(name).SetEvent;
end;
function TSynch.SnW(const sigName, waitName: string; timeout: cardinal):
boolean;
begin
Signal(sigName);
Result := WaitFor(waitName, timeout);
end;
function TSynch.WaitFor(const name: string; timeout: cardinal): boolean;
begin
Result := Ensure(name).WaitFor(timeout) = wrSignaled;
end;
end.
|
unit FormVoxelTexture;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls,voxel, ExtDlgs,math, ComCtrls, Voxel_Engine, Palette,
undo_engine;
type
TFrmVoxelTexture = class(TForm)
Panel1: TPanel;
Image1: TImage;
Button1: TButton;
Button6: TButton;
Button2: TButton;
Button3: TButton;
OpenPictureDialog1: TOpenPictureDialog;
SavePictureDialog1: TSavePictureDialog;
Button4: TButton;
Image2: TImage;
CheckBox1: TCheckBox;
Bevel2: TBevel;
Panel2: TPanel;
Image3: TImage;
Label2: TLabel;
Label3: TLabel;
Bevel3: TBevel;
Panel3: TPanel;
Button8: TButton;
Button9: TButton;
ProgressBar1: TProgressBar;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button8Click(Sender: TObject);
procedure Button9Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmVoxelTexture: TFrmVoxelTexture;
implementation
uses FormMain;
{$R *.dfm}
procedure TFrmVoxelTexture.Button1Click(Sender: TObject);
var
x,y,z,zmax,xmax,ymax,lastheight : integer;
v : tvoxelunpacked;
begin
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1);
Image1.Picture.Bitmap.Width := 0;
Image1.Picture.Bitmap.Height := 0;
Image1.Picture.Bitmap.Width := ActiveSection.Tailer.XSize;
Image1.Picture.Bitmap.Height := ActiveSection.Tailer.YSize;
zmax := ActiveSection.Tailer.ZSize-1;
for x := 0 to ActiveSection.Tailer.XSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
z := 0;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour);
Image1.Picture.Bitmap.Canvas.Pixels[x,y] := Image1.Picture.Bitmap.Canvas.Brush.Color;
end;
z := z + 1;
until (z > zmax) or (v.Used = true);
end;
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1);
lastheight := Image1.Picture.Bitmap.Height+1;
Image1.Picture.Bitmap.Height := lastheight + ActiveSection.Tailer.YSize;
zmax := ActiveSection.Tailer.ZSize-1;
for x := 0 to ActiveSection.Tailer.XSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
z := zmax;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour);
Image1.Picture.Bitmap.Canvas.Pixels[x,lastheight+y] := Image1.Picture.Bitmap.Canvas.Brush.Color;
end;
z := z - 1;
until (z < 0) or (v.Used = true);
end;
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1);
lastheight := Image1.Picture.Bitmap.Height+1;
Image1.Picture.Bitmap.Height := lastheight + ActiveSection.Tailer.ZSize;
ymax := ActiveSection.Tailer.YSize-1;
for x := 0 to ActiveSection.Tailer.XSize-1 do
for z := 0 to ActiveSection.Tailer.ZSize-1 do
begin
y := 0;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour);
Image1.Picture.Bitmap.Canvas.Pixels[x,lastheight+z] := Image1.Picture.Bitmap.Canvas.Brush.Color;
end;
y := y + 1;
until (y > ymax) or (v.Used = true);
end;
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1);
lastheight := Image1.Picture.Bitmap.Height+1;
Image1.Picture.Bitmap.Height := lastheight + ActiveSection.Tailer.ZSize;
ymax := ActiveSection.Tailer.YSize-1;
for x := 0 to ActiveSection.Tailer.XSize-1 do
for z := 0 to ActiveSection.Tailer.ZSize-1 do
begin
y := ymax;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour);
Image1.Picture.Bitmap.Canvas.Pixels[x,lastheight+z] := Image1.Picture.Bitmap.Canvas.Brush.Color;
end;
y := y - 1;
until (y < 0) or (v.Used = true);
end;
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1);
lastheight := Image1.Picture.Bitmap.Height+1;
Image1.Picture.Bitmap.Height := lastheight + ActiveSection.Tailer.YSize;
xmax := ActiveSection.Tailer.XSize-1;
for z := 0 to ActiveSection.Tailer.ZSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
x := 0;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour);
Image1.Picture.Bitmap.Canvas.Pixels[z,lastheight+y] := Image1.Picture.Bitmap.Canvas.Brush.Color;
end;
x := x + 1;
until (x > xmax) or (v.Used = true);
end;
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1);
lastheight := Image1.Picture.Bitmap.Height+1;
Image1.Picture.Bitmap.Height := lastheight + ActiveSection.Tailer.YSize;
xmax := ActiveSection.Tailer.XSize-1;
for z := 0 to ActiveSection.Tailer.ZSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
x := xmax;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
Image1.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(v.colour);
Image1.Picture.Bitmap.Canvas.Pixels[z,lastheight+y] := Image1.Picture.Bitmap.Canvas.Brush.Color;
end;
x := x - 1;
until (x < 0) or (v.Used = true);
end;
Image1.refresh;
end;
procedure TFrmVoxelTexture.FormShow(Sender: TObject);
begin
Image1.Picture.Bitmap.FreeImage;
Button1Click(sender);
end;
procedure TFrmVoxelTexture.Button2Click(Sender: TObject);
begin
if OpenPictureDialog1.Execute then
Image1.Picture.LoadFromFile(OpenPictureDialog1.filename);
end;
procedure TFrmVoxelTexture.Button3Click(Sender: TObject);
begin
if SavePictureDialog1.Execute then
image1.Picture.SaveToFile(SavePictureDialog1.FileName);
end;
procedure TFrmVoxelTexture.Button4Click(Sender: TObject);
var x,y,c,cmax,size : integer;
begin
if SavePictureDialog1.Execute then
begin
if SpectrumMode = ModeColours then
cmax := 256
else
cmax := ActiveNormalsCount;
size := 5;
Image2.Picture.Bitmap.width := 0;
Image2.Picture.Bitmap.height := 0;
Image2.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(-1);
Image2.Picture.Bitmap.width := 8*size;
Image2.Picture.Bitmap.height := 32*size;
c := 0;
for x := 0 to 7 do
for y := 0 to 31 do
begin
if c < cmax then
begin
Image2.Picture.Bitmap.Canvas.Brush.Color := GetVXLPaletteColor(c);
Image2.Picture.Bitmap.Canvas.FillRect(rect(x*size,y*size,x*size+size,y*size+size));
end;
c := c +1;
end;
Image2.Picture.SaveToFile(SavePictureDialog1.FileName);
end;
end;
procedure TFrmVoxelTexture.Button6Click(Sender: TObject);
var
x,y,z,zmax,xmax,ymax,lastheight,col,pp : integer;
v : tvoxelunpacked;
begin
//zmax := ActiveSection.Tailer.ZSize-1;
ProgressBar1.Visible := true;
if CheckBox1.Checked then
begin
Label1.Visible := true;
Label1.Caption := 'Applying Bottom View To Layers';
Label1.Refresh;
lastheight := 0;
ProgressBar1.Position := 0;
ProgressBar1.Max := ActiveSection.Tailer.XSize *2;
for x := 0 to ActiveSection.Tailer.XSize-1 do
begin
ProgressBar1.Position := x;
for y := 0 to ActiveSection.Tailer.YSize-1 do
for z := 0 to ((ActiveSection.Tailer.ZSize-1) div 2) do
begin
ActiveSection.GetVoxel(x,y,((ActiveSection.Tailer.ZSize-1) div 2)-z,v);
if v.Used then
begin
col := getsquarecolour(x,lastheight+y,Image1.Picture.Bitmap);
if col <> GetVXLPaletteColor(-1) then
if SpectrumMode = ModeColours then
v.Colour := col
else
v.Normal := col;
ActiveSection.SetVoxel(x,y,((ActiveSection.Tailer.ZSize-1) div 2)-z,v);
end;
end;
end;
Label1.Caption := 'Applying Top View To Layers';
Label1.Refresh;
lastheight := ActiveSection.Tailer.YSize+1;
for x := 0 to ActiveSection.Tailer.XSize-1 do
begin
ProgressBar1.Position := ActiveSection.Tailer.XSize+x;
for y := 0 to ActiveSection.Tailer.YSize-1 do
for z := 0 to ((ActiveSection.Tailer.ZSize-1) div 2) do
begin
ActiveSection.GetVoxel(x,y,((ActiveSection.Tailer.ZSize-1) div 2)+z,v);
if v.Used then
begin
col := getsquarecolour(x,lastheight+y,Image1.Picture.Bitmap);
if col <> GetVXLPaletteColor(-1) then
if SpectrumMode = ModeColours then
v.Colour := col
else
v.Normal := col;
ActiveSection.SetVoxel(x,y,((ActiveSection.Tailer.ZSize-1) div 2)+z,v);
end;
end;
end;
end;
Label1.Visible := true;
Label1.Caption := 'Applying Texture To Left And Right Sides';
Label1.Refresh;
ProgressBar1.Max := ((ActiveSection.Tailer.XSize-1)*4)+ ((ActiveSection.Tailer.ZSize-1)*2);
{
for x := 0 to ActiveSection.Tailer.XSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
z := 0;
ProgressBar1.Position := x;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
col := getsquarecolour(x,y);
if col <> GetVXLPaletteColor(-1) then
if SpectrumMode = ModeColours then
v.Colour := col
else
v.Normal := col;
ActiveSection.SetVoxel(x,y,z,v);
end;
z := z + 1;
until (z > zmax) or (v.Used = true);
end;
}
lastheight := ActiveSection.Tailer.YSize+1;
zmax := ActiveSection.Tailer.ZSize-1;
{
for x := 0 to ActiveSection.Tailer.XSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
z := zmax;
ProgressBar1.Position := x + (ActiveSection.Tailer.XSize-1);
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
col := getsquarecolour(x,lastheight+y);
if col <> GetVXLPaletteColor(-1) then
if SpectrumMode = ModeColours then
v.Colour := col
else
v.Normal := col;
ActiveSection.SetVoxel(x,y,z,v);
end;
z := z - 1;
until (z < 0) or (v.Used = true);
end; }
lastheight := lastheight +ActiveSection.Tailer.YSize+1;
ymax := ActiveSection.Tailer.YSize-1;
pp := 0;
for x := 0 to ActiveSection.Tailer.XSize-1 do
for z := 0 to ActiveSection.Tailer.ZSize-1 do
begin
y := 0;
ProgressBar1.Position := x +pp;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
col := getsquarecolour(x,lastheight+z,Image1.Picture.Bitmap);
if col <> GetVXLPaletteColor(-1) then
if SpectrumMode = ModeColours then
v.Colour := col
else
v.Normal := col;
ActiveSection.SetVoxel(x,y,z,v);
end;
y := y + 1;
until (y > ymax) or (v.Used = true);
end;
lastheight := lastheight +ActiveSection.Tailer.ZSize+1;
ymax := ActiveSection.Tailer.YSize-1;
pp := ProgressBar1.Position;
for x := 0 to ActiveSection.Tailer.XSize-1 do
for z := 0 to ActiveSection.Tailer.ZSize-1 do
begin
y := ymax;
ProgressBar1.Position := x + pp;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
col := getsquarecolour(x,lastheight+z,Image1.Picture.Bitmap);
if col <> GetVXLPaletteColor(-1) then
if SpectrumMode = ModeColours then
v.Colour := col
else
v.Normal := col;
ActiveSection.SetVoxel(x,y,z,v);
end;
y := y - 1;
until (y < 0) or (v.Used = true);
end;
lastheight := lastheight +ActiveSection.Tailer.ZSize+1;
xmax := ActiveSection.Tailer.XSize-1;
pp := ProgressBar1.Position;
Label1.Caption := 'Applying Texture To Front And Back Sides';
Label1.Refresh;
for z := 0 to ActiveSection.Tailer.ZSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
x := 0;
ProgressBar1.Position := z + pp;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
col := getsquarecolour(z,lastheight+y,Image1.Picture.Bitmap);
if col <> GetVXLPaletteColor(-1) then
if SpectrumMode = ModeColours then
v.Colour := col
else
v.Normal := col;
ActiveSection.SetVoxel(x,y,z,v);
end;
x := x + 1;
until (x > xmax) or (v.Used = true);
end;
lastheight := lastheight +ActiveSection.Tailer.YSize+1;
xmax := ActiveSection.Tailer.XSize-1;
pp := ProgressBar1.Position;
for z := 0 to ActiveSection.Tailer.ZSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
x := xmax;
ProgressBar1.Position := z + pp;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
col := getsquarecolour(z,lastheight+y,Image1.Picture.Bitmap);
if col <> GetVXLPaletteColor(-1) then
if SpectrumMode = ModeColours then
v.Colour := col
else
v.Normal := col;
ActiveSection.SetVoxel(x,y,z,v);
end;
x := x - 1;
until (x < 0) or (v.Used = true);
end;
// Apply top and bottom images
pp := ProgressBar1.Position;
Label1.Caption := 'Applying Texture To Top And Bottom Sides';
Label1.Refresh;
for x := 0 to ActiveSection.Tailer.XSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
z := 0;
ProgressBar1.Position := x + pp;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
col := getsquarecolour(x,y,Image1.Picture.Bitmap);
if col <> GetVXLPaletteColor(-1) then
if SpectrumMode = ModeColours then
v.Colour := col
else
v.Normal := col;
ActiveSection.SetVoxel(x,y,z,v);
end;
z := z + 1;
until (z > zmax) or (v.Used = true);
end;
lastheight := ActiveSection.Tailer.YSize+1;
zmax := ActiveSection.Tailer.ZSize-1;
pp := ProgressBar1.Position;
for x := 0 to ActiveSection.Tailer.XSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
z := zmax;
ProgressBar1.Position := x + pp;
repeat
ActiveSection.GetVoxel(x,y,z,v);
if v.Used then
begin
col := getsquarecolour(x,lastheight+y,Image1.Picture.Bitmap);
if col <> GetVXLPaletteColor(-1) then
if SpectrumMode = ModeColours then
v.Colour := col
else
v.Normal := col;
ActiveSection.SetVoxel(x,y,z,v);
end;
z := z - 1;
until (z < 0) or (v.Used = true);
end;
ProgressBar1.Visible := false;
Label1.Visible := false;
FrmMain.RefreshAll;
//showmessage('Texture Applyed to Voxel');
end;
procedure TFrmVoxelTexture.Button8Click(Sender: TObject);
begin
CreateVXLRestorePoint(ActiveSection,Undo);
Button6Click(sender);
FrmMain.UpdateUndo_RedoState;
//FrmMain.RefreshAll;
VXLChanged := true;
Close;
end;
procedure TFrmVoxelTexture.Button9Click(Sender: TObject);
begin
Close;
end;
procedure TFrmVoxelTexture.FormCreate(Sender: TObject);
begin
Panel2.DoubleBuffered := true;
end;
end.
|
unit AI.Utils;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Math,
DeepStar.Utils;
type
int = integer;
TUtils = class(TObject)
public
class function GenerateRandomArray(n, rangeL, rangeR: integer): TArr_int;
class function GenerateOrderedArray(n: integer): TArr_int;
end;
TAlgorithmTester = class(TObject)
public
// O(logn)
class function BinarySearch(arr: TArr_int; target: integer): integer;
// O(N)
class function FindMax(arr: TArr_int): integer;
// O(NlogN)
class procedure MergeSort(arr: TArr_int);
// O(N^2)
class procedure SelectionSort(arr: TArr_int);
end;
implementation
{ TAlgorithmTester }
class function TAlgorithmTester.BinarySearch(arr: TArr_int; target: integer): integer;
var
l, r, mid: integer;
begin
l := 0;
r := High(arr);
while l <= r do
begin
mid := l + (r - l) div 2;
if arr[mid] = target then
Exit(mid);
if arr[mid] > target then
r := mid - 1
else
l := mid + 1;
end;
Result := -1;
end;
class function TAlgorithmTester.FindMax(arr: TArr_int): integer;
var
res, i: integer;
begin
Assert(Length(arr) > 0);
res := arr[0];
for i := 0 to High(arr) do
if arr[i] > res then
res := arr[i];
Result := res;
end;
class procedure TAlgorithmTester.MergeSort(arr: TArr_int);
function __arrayCopyOfRange__(l, r: integer): TArr_int;
var
res: TArr_int;
i: integer;
begin
SetLength(res, r - l + 1);
for i := l to r do
res[i - l] := arr[i];
Result := res;
end;
procedure __merge__(l, mid, r: integer);
var
aux: array of integer;
i, leftIndex, rightIndex: integer;
begin
aux := __arrayCopyOfRange__(l, r);
// 初始化,leftIndex 指向左半部分的起始索引位置 l;
// rightIndex 指向右半部分起始索引位置 mid+1
leftIndex := l;
rightIndex := mid + 1;
for i := l to r do
begin
if leftIndex > mid then // 如果左半部分元素已经全部处理完毕
begin
arr[i] := aux[rightIndex - l];
rightIndex += 1;
end
else if rightIndex > r then // 如果右半部分元素已经全部处理完毕
begin
arr[i] := aux[leftIndex - l];
leftIndex += 1;
end
else if aux[leftIndex - l] < aux[rightIndex - l] then // 左半部分所指元素 < 右半部分所指元素
begin
arr[i] := aux[leftIndex - l];
leftIndex += 1;
end
else // 左半部分所指元素 >= 右半部分所指元素
begin
arr[i] := aux[rightIndex - l];
rightIndex += 1;
end;
end;
end;
var
sz, i: integer;
begin
sz := 1;
while sz < Length(arr) do
begin
i := 0;
while i < Length(arr) - sz do
begin
// 对 arr[i...i+sz-1] 和 arr[i+sz...i+2*sz-1] 进行归并
__merge__(i, i + sz - 1, Min(i + sz + sz - 1, Length(arr) - 1));
i += sz * 2;
end;
sz *= 2;
end;
end;
class procedure TAlgorithmTester.SelectionSort(arr: TArr_int);
procedure __swap__(i, j: integer);
var
temp: integer;
begin
temp := arr[i];
arr[i] := arr[j];
arr[j] := temp;
end;
var
i, minIndex, j: integer;
begin
for i := 0 to High(arr) do
begin
minIndex := i;
for j := i + 1 to High(arr) do
begin
if arr[j] < arr[minIndex] then
minIndex := j;
end;
__swap__(i, minIndex);
end;
end;
{ TUtils }
class function TUtils.GenerateOrderedArray(n: integer): TArr_int;
var
res: TArr_int;
i: integer;
begin
SetLength(res, n);
for i := 0 to n - 1 do
res[i] := i;
Result := res;
end;
class function TUtils.GenerateRandomArray(n, rangeL, rangeR: integer): TArr_int;
var
res: TArr_int;
i: integer;
begin
Assert((n > 0) and (rangeL <= rangeR));
SetLength(res, n);
Randomize;
for i := 0 to n - 1 do
res[i] := Random(rangeR - rangeL) + rangeL;
Result := res;
end;
end.
|
unit DsiEMVXIntegration;
Interface
uses ProcessorInterface, DeviceIntegrationInterface, uCreditCardFunction, DSIEMVXLib_TLB, VER1000XLib_TLB,
VER2000XLib_TLB, uXML, uMRPinPad, DeviceIntegration;
type
TDsiEMVXIntegration = class(TDeviceIntegration, IDeviceIntegration)
private
FTranMsgStatus: TCardTranMsgStatus;
Fprocessor: IProcessor;
FPinPad: TMRPinPad;
FDevice: TDsiPDCX;
FXMLResult : WideString; // XML answer from Server
FXMLServer : WideString; // XML Server
FXMLSent : WideString; // XML Sent
FXMLReceived : WideString; // XML Received Aprooved/Declined
FXMLContent : TXMLContent;
function CreatePadResetXML(): String;
function ShouldResubmit(): Boolean;
function initializeStatusXML(): String;
function CreditProcessSaleXML(): String;
function CreditResubmitProcessSaleXML(): String;
function CreditProcessReturnXML(): String;
function CreditVoidSaleXML(): String;
function CreditVoidReturnXML(): String;
function CreditResubmitReturnXML(): String;
function CreditReturnByRecordNoXML(): String;
function CreditSaleByRecordNoXML(): String;
function CreditVoiceAuthXML(): String;
function CreditVoidReturnByRecordNoXML(): String;
function DebitProcessSaleXML(): String;
function DebitProcessReturnXML(): String;
function DebitResubmitProcessSaleXML(): String;
function DebitResubmitReturnXML(): String;
{ gift is lacking }
function GiftProcessSaleXML(): String;
function GiftProcessReturnXML() :String;
function GiftVoidSaleXML(): String;
function GiftVoidReturnXML(): String;
function GiftIssueXML(): String;
function GiftVoidIssueXML(): String;
function GiftReloadXML(): String;
function GiftVoidReloadXML(): String;
function GiftBalanceXML(): String;
function GiftNoNSFSaleXML(): String;
function GiftCashOutXML(): String;
protected
procedure SetPadType(arg_name: String); override;
procedure SetIdPaymentType(arg_paymentType: Integer);
function VerifyTransaction(): Boolean; override;
public
constructor Create();
function ProcessCommand(arg_xml: WideString): Boolean;
// Credit Transactions
function CreditProcessSale(): Boolean;
function CreditProcessReturn(): Boolean;
function CreditVoidSale(): Boolean;
function CreditVoidReturn(): Boolean;
// Debit Transactions
function DebitProcessSale(): Boolean;
function DebitProcessReturn(): Boolean;
// Prepaid transactions
function GiftProcessSale(): Boolean;
function GiftProcessReturn(): Boolean;
function GiftVoidSale(): Boolean;
function GiftVoidReturn(): Boolean;
function GiftIssue: Boolean;
function GiftVoidIssue: Boolean;
function GiftReload: Boolean;
function GiftVoidReload: Boolean;
function GiftBalance: Boolean;
function GiftNoNSFSale: Boolean;
function GiftCashOut: Boolean;
// Antonio September 11, 2013
function tryIssueCard(arg_salePrice: double): TTransactionReturn;
function tryBalanceCard(arg_salePrice: double): TTransactionReturn;
procedure SetProcessor(arg_processor: IProcessor);
procedure SetPinPad(arg_pinpad: TMRPinPad);
function GetTransaction(): IProcessor;
procedure BeforeProcessCard();
procedure BeforeVoid();
end;
implementation
{ TDsiEMVXIntegration }
procedure TDsiEMVXIntegration.BeforeProcessCard;
begin
end;
procedure TDsiEMVXIntegration.BeforeVoid;
begin
end;
constructor TDsiEMVXIntegration.Create;
begin
FDevice := TDsiEMVX.Create(nil);
FTranMsgStatus : TCardTranMsgStatus.Create();
end;
function TDsiEMVXIntegration.DebitProcessSaleXML(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVSale</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + fDeviceName.Strings[2] + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinPad.FComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<SequenceNo>' + fSequenceNo + '</SequenceNo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditProcessReturn: Boolean;
var
status: String;
text: String;
begin
if ( fDeviceInitialized ) then begin
beforeTransaction();
fAcctNoSecureDevice := 'SecureDevice';
result := processCommand(CreditProcessReturnXML());
status := FXMLContent.GetAttributeString('CmdStatus');
text := FXMLContent.GetAttributeString('TextResponse');
// CmdStatus and TextResponse from Mercury
if ( (status = 'Error') and (text = 'TRANSACTION CANCELLED - Operation Cancelled 08.') ) then begin
result := processCommand(CreditResubmitReturnXML);
end;
if ( result ) then begin
FAuthorize := FAuthorize * (-1);
end;
end;
end;
function TDsiEMVXIntegration.InitializeStatusXML(): String;
begin
{}
end;
function TDsiEMVXIntegration.EMVAdjustByRecordNoXML(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVAdjustByRecordNo</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ FPinPad.ComPort + '</ComPort>' + ccrlf +
//ctab + ctab + '<Account>' + ccrlf +
//ctab + ctab + ctab + '<AccttNo>' + FAcctNo + '</AcctNo>' + ccrlf +
//ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
//ctab + ctab + ctab + '<Gratuity>' + Gratuity + '</Gratuity>' + ccrlf +
//ctab + ctab + ctab + '<CashBack>' + CashBack + '</CashBack>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
//ctab + ctab + '<LaneID>' + LaneID + '</LaneID>' + ccrlf +
//ctab + ctab + '<Duplicate>' + Duplicate + '</Duplicate>' + ccrlf +
//ctab + ctab + '<SequenceNo>' + fSequenceNo + '</SequenceNo>' + ccrlf +
//ctab + ctab + '<PartialAuth>' + fPartialAuth + '</PartialAuth>' + ccrlf +
ctab + ctab + '<RecordNo>' + FProcessor.GetRefNo() + '</RecordNo>' + ccrlf +
//ctab + ctab + '<Frequency>' + FFrequency + '</Frequency>' + ccrlf +
ctab + ctab + '<AcqRefData>' + FResultAcqRefData + '</AcqRefData>' ;
//ctab + ctab + '<ProcessData>' + FProcessData + '</ProcessData>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditEMVZeroAuthXML(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
//ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
//ctab + ctab + '<UserTrace>' + '' + '</UserTrace>' + ccrlf +
ctab + ctab + '<TranCode>EMVZeroAuth</TranCode>' + ccrlf +
//ctab + ctab + '<CollectData>' + quotedStr('CardholderName') + //'</CollectData>' + ccrlf;
// ctab + ctab + '<SecureDevice>INGENICOISC250_MERCURY_E2E</SecureDevice>' + ccrlf +
// ctab + ctab + '<SecureDevice>VX805XPI_MERCURY_E2E</SecureDevice>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ FPinPad.ComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>';// + ccrlf +
//ctab + ctab + '<SequenceNo>' + fSequenceNo + '</SequenceNo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVIntegration.CreditEMVVoiceAuthXML():String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
//ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
//ctab + ctab + '<UserTrace>' + '' + '</UserTrace>' + ccrlf +
ctab + ctab + '<TranCode>EMVVoiceAuth</TranCode>' + ccrlf +
//ctab + ctab + '<CollectData>' + quotedStr('CardholderName') + //'</CollectData>' + ccrlf;
// ctab + ctab + '<SecureDevice>INGENICOISC250_MERCURY_E2E</SecureDevice>' + ccrlf +
// ctab + ctab + '<SecureDevice>VX805XPI_MERCURY_E2E</SecureDevice>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ FPinPad.ComPort + '</ComPort>' + ccrlf +
//ctab + ctab + '<Account>' + ccrlf +
//ctab + ctab + ctab + '<AccttNo>' + FAcctNo + '</AcctNo>' + ccrlf +
//ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
//ctab + ctab + ctab + '<Gratuity>' + Gratuity + '</Gratuity>' + ccrlf +
//ctab + ctab + ctab + '<CashBack>' + CashBack + '</CashBack>' + ccrlf +
ctab + ctab + '</Amount>';
//ctab + ctab + '<Duplicate>' + Duplicate + '</Duplicate>' + ccrlf +
//ctab + ctab + '<SequenceNo>' + fSequenceNo + '</SequenceNo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditVoidReturnByRecordNoXML(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
//ctab + ctab + '<IpPort>' + FProcessor.GetIPAddress() + '</IpPort>' + ccrlf;
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
//ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
//ctab + ctab + '<UserTrace>' + '' + '</UserTrace>' + ccrlf +
ctab + ctab + '<TranCode>EMVVoidReturnByRecordNo</TranCode>' + ccrlf +
//ctab + ctab + '<CollectData>' + quotedStr('CardholderName') + //'</CollectData>' + ccrlf;
// ctab + ctab + '<SecureDevice>INGENICOISC250_MERCURY_E2E</SecureDevice>' + ccrlf +
// ctab + ctab + '<SecureDevice>VX805XPI_MERCURY_E2E</SecureDevice>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ FPinPad.ComPort + '</ComPort>' + ccrlf +
//ctab + ctab + '<Account>' + ccrlf +
//ctab + ctab + ctab + '<AccttNo>' + FAcctNo + '</AcctNo>' + ccrlf +
//ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
//ctab + ctab + ctab + '<Gratuity>' + Gratuity + '</Gratuity>' + ccrlf +
//ctab + ctab + ctab + '<CashBack>' + CashBack + '</CashBack>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
//ctab + ctab + '<LaneID>' + LaneID + '</LaneID>' + ccrlf +
//ctab + ctab + '<Duplicate>' + Duplicate + '</Duplicate>' + ccrlf +
//ctab + ctab + '<SequenceNo>' + fSequenceNo + '</SequenceNo>' + ccrlf +
//ctab + ctab + '<PartialAuth>' + fPartialAuth + '</PartialAuth>' + ccrlf +
ctab + ctab + '<AcqRefData>' + FResultAcqRefData + '</AcqRefData>'; // + ccrlf +
//ctab + ctab + '<ProcessData>' + FProcessData + '</ProcessData>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditVoiceAuthXML(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
//ctab + ctab + '<IpPort>' + FProcessor.GetIPAddress() + '</IpPort>' + ccrlf;
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
//ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
//ctab + ctab + '<UserTrace>' + '' + '</UserTrace>' + ccrlf +
ctab + ctab + '<TranCode>EMVVoiceAuth</TranCode>' + ccrlf +
//ctab + ctab + '<CollectData>' + quotedStr('CardholderName') + //'</CollectData>' + ccrlf;
// ctab + ctab + '<SecureDevice>INGENICOISC250_MERCURY_E2E</SecureDevice>' + ccrlf +
// ctab + ctab + '<SecureDevice>VX805XPI_MERCURY_E2E</SecureDevice>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ FPinPad.FComPort + '</ComPort>' + ccrlf +
//ctab + ctab + '<Account>' + ccrlf +
//ctab + ctab + ctab + '<AccttNo>' + FAcctNo + '</AcctNo>' + ccrlf +
//ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
//ctab + ctab + ctab + '<Gratuity>' + Gratuity + '</Gratuity>' + ccrlf +
//ctab + ctab + ctab + '<CashBack>' + CashBack + '</CashBack>' + ccrlf +
ctab + ctab + '</Amount>';
//ctab + ctab + '<Duplicate>' + Duplicate + '</Duplicate>' + ccrlf +
//ctab + ctab + '<SequenceNo>' + fSequenceNo + '</SequenceNo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditSaleByRecordNoXML(): String;
var
strRequest: string;
begin
FProcessor.SetAcctNo('SecureDevice');
strRequest := '';
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidSaleByRecordNo</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<RecordNo>' + FProcessor.GetRecordNo() + '</RecordNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ FPinPad.ComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditReturnByRecordNoXML(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
//ctab + ctab + '<IpPort>' + FProcessor.GetIPAddress() + '</IpPort>' + ccrlf;
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
//ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
//ctab + ctab + '<UserTrace>' + '' + '</UserTrace>' + ccrlf +
ctab + ctab + '<TranCode>EMVVoidReturnByRecordNo</TranCode>' + ccrlf +
//ctab + ctab + '<CollectData>' + quotedStr('CardholderName') + //'</CollectData>' + ccrlf;
// ctab + ctab + '<SecureDevice>INGENICOISC250_MERCURY_E2E</SecureDevice>' + ccrlf +
// ctab + ctab + '<SecureDevice>VX805XPI_MERCURY_E2E</SecureDevice>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ FPinPad.ComPort + '</ComPort>' + ccrlf +
//ctab + ctab + '<Account>' + ccrlf +
//ctab + ctab + ctab + '<AccttNo>' + FAcctNo + '</AcctNo>' + ccrlf +
//ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
//ctab + ctab + ctab + '<Gratuity>' + Gratuity + '</Gratuity>' + ccrlf +
//ctab + ctab + ctab + '<CashBack>' + CashBack + '</CashBack>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
//ctab + ctab + '<LaneID>' + LaneID + '</LaneID>' + ccrlf +
//ctab + ctab + '<Duplicate>' + Duplicate + '</Duplicate>' + ccrlf +
//ctab + ctab + '<SequenceNo>' + fSequenceNo + '</SequenceNo>' + ccrlf +
//ctab + ctab + '<PartialAuth>' + fPartialAuth + '</PartialAuth>' + ccrlf +
ctab + ctab + '<AcqRefData>' + FProcessor.GetResultAcqRefData() + '</AcqRefData>'; // + ccrlf +
//ctab + ctab + '<ProcessData>' + FProcessData + '</ProcessData>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditResubmitReturnXML(): String;
var
strRequest: string;
returnPurchase: Double;
begin
returnPurchase := FProcessor.GetPurchase() * (-1);
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVReturn</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinPad.ComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>Prompt</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr(returnPurchase) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<SequenceNo>' + FProcessor.GetSequenceNo() + '</SequenceNo>' + ccrlf+
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditVoidReturnXML(): String;
var
strRequest: string;
begin
FProcessor.SetAcctNo('SecureDevice');
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPOrt() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVVoidReturn</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinPad.ComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<AcqRefData>' + FResultAcqRefData + '</AcqRefData>' + ccrlf +
ctab + ctab + '<SequenceNo>' + SequenceNo + '</SequenceNo>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVIntegration.CreditResubmitProcessSaleXML(): String
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIpPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVSale</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinPad.ComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>Prompt</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<SequenceNo>' + FProcessor.GetSequenceNo() + '</SequenceNo>' + ccrlf+
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.ShouldResubmit(): Boolean;
begin
result := ( ( FtranMsgStatus.GetCmdStatus() = 'Error') and ( ( FTranMsgStatus.GetCmdStatus() = 'Cancelled.') or FTranMsgStatus.GetTextResponse() = 'Cancelled at POS.') ) )
end;
function TDsiEMVXIntegration.CreditProcessSaleXML(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVSale</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinPad.ComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>Prompt</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<SequenceNo>' + FProcessor.GetSequenceNo() + '</SequenceNo>' + ccrlf+
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditProcessReturnXML(): String;
var
strRequest: string;
returnPurchase: Double;
begin
strRequest := '';
returnPurchase := FProcessor.GetPurchase() * (-1);
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVReturn</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinPad.ComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr(Abs(returnPurchase)) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<SequenceNo>' + FProcessor.GetSequenceNo() + '</SequenceNo>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditVoidSaleXML(): String;
var
strRequest: string;
begin
FProcessor.SetAcctNo('SecureDevice');
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVVoidSale</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinPad.FComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + Fprocessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<AcqRefData>' + FResultAcqRefData + '</AcqRefData>' + ccrlf +
ctab + ctab + '<SequenceNo>' + FProcessor.GetSequenceNo() + '</SequenceNo>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditResubmitProcessSaleXM(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVSale</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinPad.ComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>Prompt</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<SequenceNo>' + FProcessor.GetSequenceNo() + '</SequenceNo>' + ccrlf+
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.CreditProcessSale: Boolean;
var
status: String;
text: String;
begin
if ( fDeviceInitialized ) then begin
beforeTransaction();
fAcctNoSecureDevice := 'SecureDevice';
result := processCommand(CreditProcessSaleXML());
status := FXMLContent.GetAttributeString('CmdStatus');
text := FXMLContent.GetAttributeString('TextResponse');
// CmdStatus and TextResponse from Mercury
if ( (status = 'Error') and (text = 'TRANSACTION CANCELLED - Operation Cancelled 08.') ) then begin
result := processCommand(CreditResubmitProcessSaleXML());
end;
end;
end;
function TDsiEMVXIntegration.CreditVoidReturn: Boolean;
begin
beforeTransaction();
result := processCommand(CreditVoidReturnXML());
if ( result ) then begin
FAuthorize := FAuthorize * (-1);
end;
afterTransaction();
end;
function TDsiEMVXIntegration.CreditVoidSale: Boolean;
begin
beforeTransaction();
result := processCommand(DebitVoidSaleXML());
afterTransaction();
end;
function TDsiEMVXIntegration.DebitProcessReturn: Boolean;
var
status: String;
text: String;
begin
if ( fDeviceInitialized ) then begin
beforeTransaction();
fAcctNoSecureDevice := 'SecureDevice';
result := processCommand(DebitProcessReturnXML());
status := FXMLContent.GetAttributeString('CmdStatus');
text := FXMLContent.GetAttributeString('TextResponse');
// CmdStatus and TextResponse from Mercury
if ( (status = 'Error') and (text = 'TRANSACTION CANCELLED - Operation Cancelled 08.') ) then begin
result := processCommand(DebitResubmitReturnXML());
end;
if ( result ) then begin
FAuthorize := FAuthorize * (-1);
end;
end;
end;
function TDsiEMVXIntegration.DebitResubmitReturnXML(): String;
var
strRequest: string;
returnPurchase: Double;
begin
strRequest := '';
returnPurchase := FProcessor.GetPurchase() * (-1);
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVReturn</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinPad.ComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>Prompt</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr(returnPurchase) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<SequenceNo>' + FProcessor.GetSequenceNo() + '</SequenceNo>' + ccrlf+
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.DebitResubmitProcessSaleXML(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' +FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVSale</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinPad.ComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>Prompt</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr( FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<SequenceNo>' + FProcessor.GetSequenceNo() + '</SequenceNo>' + ccrlf+
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.DebitProcessReturnXML: String;
var
strRequest: string;
returnPurchase: Double;
begin
strRequest := '';
returnPurchase := FProcessor.GetPurchase() * (-1);
strRequest := ctab + ctab + '<HostOrIP>' + FProcessor.GetIPAddress() + '</HostOrIP>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<TranCode>EMVReturn</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinPad.ComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr(Abs(returnPurchase)) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<SequenceNo>' + FProcessor.GetSequenceNo() + '</SequenceNo>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.DebitProcessSale: Boolean;
var
status: String;
text: String;
begin
if ( fDeviceInitialized ) then begin
beforeTransaction();
fAcctNoSecureDevice := 'SecureDevice';
result := processCommand(DebitProcessSaleXML());
status := FXMLContent.GetAttributeString('CmdStatus');
text := FXMLContent.GetAttributeString('TextResponse');
// CmdStatus and TextResponse from Mercury
if ( (status = 'Error') and (text = 'TRANSACTION CANCELLED - Operation Cancelled 08.') ) then begin
result := processCommand(DebitResubmitProcessSaleXML());
end;
end;
end;
function TDsiEMVXIntegration.GetIdPaymentType: Integer;
begin
end;
function TDsiEMVXIntegration.GetTransaction: IProcessor;
begin
result := FProcessor;
end;
function TDsiEMVXIntegration.GiftCashOutXML(): String;
var
strRequest: string;
begin
FProcessor.SetAcctNo('SecureDevice');
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>CashOut</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', 0) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.GiftNoNSFSaleXML(): String;
var
strRequest: string;
begin
strRequest := '';
FProcessor.SetAcctNo('SecureDevice');
strRequest := strRequest + ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' +FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>NoNSFSale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Authorize>' + formatFloat('0.00', FAuthorize) + '</Authorize>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Balance>' + formatFloat('0.00', FBalance) + '</Balance>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.GiftBalanceXML(): String;
var
strRequest: string;
begin
strRequest := '';
FProcessor.SetAcctNo('SecureDeevice');
strRequest := strRequest + ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Balance</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDSiEMVXIntegration.GiftVoidReloadXML(): String;
var
strRequest: string;
begin
strRequest := '';
FProcessor.SetAcctNo('SecureDevice');
strRequest := strRequest + ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID()+ '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidReload</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.GiftReloadXML(): String;
var
strRequest: string;
begin
strRequest := '';
FProcessor.SetAcctNo('SecureDevice');
strRequest := strRequest + ctab + ctab + '<IpPort>' + FProcessor.GetGiftIPPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidReload</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.GiftVoidIssueXML(): String;
var
strRequest: string;
begin
strRequest := '';
FProcessor.SetAcctNo('SecureDevice');
strRequest := strRequest + ctab + ctab + '<IpPort>' + FProcessor.GetGiftIPPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FFProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidIssue</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.GiftIssueXML(): String;
var
strRequest: string;
begin
// Construct XML for PrePaid
strRequest := '';
FProcessor.SetAcctNo('SecureDevice');
strRequest := strRequest + ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Issue</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Tax>' + formatfloat('0.00', FTax) + '</Tax>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
{
if FTrack2 = '' then
begin
// Manually entered so do the Address and CVV blocks
if ((FZip <> '') or (FAddress <> '')) then
begin
strRequest := strRequest + ctab + ctab + '<AVS>'+ ccrlf;
if FAddress<>'' then
strRequest := strRequest + ctab + ctab + ctab + '<Address>' + FAddress + '</Address>' + ccrlf;
if FZip <> '' then
strRequest := strRequest + ctab + ctab + ctab + '<Zip>' + FZip + '</Zip>' + ccrlf;
strRequest := strRequest + ctab + ctab + '</AVS>' + ccrlf;
end;
end;
}
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.GiftVoidReturnXML(): String
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidReturn</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.GiftVoidSaleXML(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidSale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FAcctNo + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FExpDate + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.GiftProcessReturnXML(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidReturn</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FAcctNo + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FExpDate + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.GiftProcessSaleXML(): String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest + ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() + '</IpPort>' + ccrlf;
strRequest := strRequest +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TerminalID>' + FProcessor.GetTerminalID() + '</TerminalID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidSale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<TranInfo>' + ccrlf +
ctab + ctab + ctab + '<AuthCode>' + FProcessor.GetAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '</TranInfo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiEMVXIntegration.GiftBalance: Boolean;
begin
result := ProcessCommand(GiftBalanceXML());
end;
function TDsiEMVXIntegration.GiftCashOut: Boolean;
begin
result := ProcessCommand(GiftCashOutXML());
end;
function TDsiEMVXIntegration.GiftIssue: Boolean;
begin
result := ProcessCommand(GiftIssueXML());
end;
function TDsiEMVXIntegration.GiftNoNSFSale: Boolean;
begin
result := ProcessCommand(GiftNoNSFSaleXML());
end;
function TDsiEMVXIntegration.GiftProcessReturn: Boolean;
begin
result := ProcessCommand(GiftProcessReturnXML());
end;
function TDsiEMVXIntegration.GiftProcessSale: Boolean;
begin
result := ProcessCommand(GiftProcessSaleXML());
end;
function TDsiEMVXIntegration.GiftReload: Boolean;
begin
result := ProcessCommand(GiftReloadXML());
end;
function TDsiEMVXIntegration.GiftVoidIssue: Boolean;
begin
result := ProcessCommand(GiftVoidIssueXML());
end;
function TDsiEMVXIntegration.GiftVoidReload: Boolean;
begin
result := ProcessCommand(GiftVoidReloadXML());
end;
function TDsiEMVXIntegration.GiftVoidReturn: Boolean;
begin
result := ProcessCommand(GiftVoidReturnXML());
end;
function TDsiEMVXIntegration.GiftVoidSale: Boolean;
begin
result := ProcessCommand(GiftVoidSaleXML());
end;
function TDsiEMVXIntegration.ProcessCommand(arg_xml: WideString): Boolean;
var
FUserTraceData : String;
begin
Result := False;
FXMLResult := FDevice.ProcessTransaction(arg_xml);
FXMLReceived := FXMLResult;
if VerifyTransaction then begin
Result := True;
end;
end;
procedure TDsiEMVXIntegration.SetIDPaymentType(arg_paymentType: Integer);
begin
end;
procedure TDsiEMVXIntegration.SetPadType(arg_name: String);
begin
inherited;
if ( Fprocessor.GetPadType = 'ISC250' ) then begin // Ingenico
Fprocessor.SetSecureDevice('INGENICOISC250_MERCURY_E2E');
end else if ( Fprocessor.GetPadType = 'VX805' ) then begin // Verifone
if ( Fprocessor.GetClassTypeName() = 'TMercuryProcessor' ) then begin
Fprocessor.SetSecureDevice('EMV_VX805_MERCURY');
end else if ( Fprocessor.GetClassTypeName() = 'TWorldPayProcessor' ) then begin
Fprocessor.SetSecureDevice('EMV_VX805_WORLDPAY');
end;
end;
end;
procedure TDsiEMVXIntegration.SetPinPad(arg_pinpad: TMRPinPad);
begin
fpinpad := arg_pinpad;
end;
procedure TDsiEMVXIntegration.SetProcessor(arg_processor: IProcessor);
begin
fProcessor := arg_processor;
end;
function TDsiEMVXIntegration.tryBalanceCard(
arg_salePrice: double): TTransactionReturn;
var
msg: String;
msgButtonSelected: Integer;
balanceToBeAdded: double;
begin
prePaidBalance();
result := fTransactionReturn;
// Antonio, 2013 Oct 19 - (MR-67)
if ( FXMLContent.GetAttributeString('CmdStatus') = 'Approved' ) then begin
balanceToBeAdded := Fbalance + arg_saleprice;
msg := Format('Card %s already issued.'+#13#10+' New balance will be %f', [self.getSecureSerialNumber(self.FAcctNo),balanceToBeAdded]);
messageDlg(msg, mtInformation, [mbOK], 0);
end;
end;
function TDsiEMVXIntegration.tryIssueCard(
arg_salePrice: double): TTransactionReturn;
var
msg: String;
msgButtonSelected: Integer;
begin
self.prePaidIssue;
result := fTransactionReturn;
if ( FXMLContent.GetAttributeString('CmdStatus') = 'Approved' ) then begin
result := fTransactionReturn;
end
else begin
msg := ' Card Declined. Try again.';
MessageDlg(msg, mtError, [mbOk], 0);
result := fTransactionReturn;
end;
end;
function TDsiEMVXIntegration.VerifyTransaction: Boolean;
begin
inherited;
end;
end.
|
unit glgizmoutils;
interface
uses
opengl1x, glscene, GLVectorGeometry, contnrs;
(*
// Copyright 2001, softSurfer (www.softsurfer.com)
// This code may be freely used and modified for any purpose
// providing that this copyright notice is included with it.
// SoftSurfer makes no warranty for this code, and cannot be held
// liable for any real or imagined damage resulting from its use.
// Users of this code must verify correctness for their application.
// Assume that classes are already given for the objects:
// Point and Vector with
// coordinates {float x, y;}
// operators for:
// Point = Point ± Vector
// Vector = Point - Point
// Vector = Vector ± Vector
// Vector = Scalar * Vector (scalar product)
// Vector = Vector / Scalar (scalar division)
// Ball with a center and radius {Point center; float radius;}
//===================================================================
// dot product which allows vector operations in arguments
#define dot(u,v) ((u).x * (v).x + (u).y * (v).y)
#define norm2(v) dot(v,v) // norm2 = squared length of vector
#define norm(v) sqrt(norm2(v)) // norm = length of vector
#define d(u,v) norm(u-v) // distance = norm of difference
// fastBall(): a fast approximation of the bounding ball for a point set
// based on the algorithm given by [Jack Ritter, 1990]
// Input: an array V[] of n points
// Output: a bounding ball = {Point center; float radius;}
void
fastBall( Point V[], int n, Ball* B)
{
Point C; // Center of ball
float rad, rad2; // radius and radius squared
float xmin, xmax, ymin, ymax; // bounding box extremes
int Pxmin, Pxmax, Pymin, Pymax; // index of V[] at box extreme
// find a large diameter to start with
// first get the bounding box and V[] extreme points for it
xmin = xmax = V[0].x;
ymin = ymax = V[0].y;
Pxmin = Pxmax = Pymin = Pymax = 0;
for (int i=1; i<n; i++) {
if (V[i].x < xmin) {
xmin = V[i].x;
Pxmin = i;
}
else if (V[i].x > xmax) {
xmax = V[i].x;
Pxmax = i;
}
if (V[i].y < ymin) {
ymin = V[i].y;
Pymin = i;
}
else if (V[i].y > ymax) {
ymax = V[i].y;
Pymax = i;
}
}
// select the largest extent as an initial diameter for the ball
Vector dVx = V[Pxmax] - V[Pxmin]; // diff of Vx max and min
Vector dVy = V[Pymax] - V[Pymin]; // diff of Vy max and min
float dx2 = norm2(dVx); // Vx diff squared
float dy2 = norm2(dVy); // Vy diff squared
if (dx2 >= dy2) { // x direction is largest extent
C = V[Pxmin] + (dVx / 2.0); // Center = midpoint of extremes
rad2 = norm2(V[Pxmax] - C); // radius squared
}
else { // y direction is largest extent
C = V[Pymin] + (dVy / 2.0); // Center = midpoint of extremes
rad2 = norm2(V[Pymax] - C); // radius squared
}
rad = sqrt(rad2);
// now check that all points V[i] are in the ball
// and if not, expand the ball just enough to include them
Vector dV;
float dist, dist2;
for (int i=0; i<n; i++) {
dV = V[i] - C;
dist2 = norm2(dV);
if (dist2 <= rad2) // V[i] is inside the ball already
continue;
// V[i] not in ball, so expand ball to include it
dist = sqrt(dist2);
rad = (rad + dist) / 2.0; // enlarge radius just enough
rad2 = rad * rad;
C = C + ((dist-rad)/dist) * dV; // shift Center toward V[i]
}
B->Center = C;
B->radius = rad;
return;
}
*)
procedure FastBall(AObjects: TObjectList; var APosition: TVector; var ARadius: TGlFloat);
implementation
procedure FastBall(AObjects: TObjectList; var APosition: TVector; var ARadius: TGlFloat);
var
C: TVector;
rad, rad2: TGLFloat; // radius and radius squared
min, max: TVector;
// float xmin, xmax, ymin, ymax; // bounding box extremes
Pxmin, Pxmax,
Pymin, Pymax,
Pzmin, pzmax: Integer; // index of V[] at box extreme
dx, dy, dz: TGLFloat;
i: Integer;
dV,
dVx,
dVy,
dVz: TVector;
dist, dist2: TGLFloat;
begin
if AObjects.Count = 0 then
Exit;
// first get the bounding box and V[] extreme points for it
// find a large diameter to start with
min := (AObjects[0] as TGLBaseSceneObject).AbsolutePosition;
Pxmin := 0;
Pxmax := 0;
Pymin := 0;
Pymax := 0;
Pzmin := 0;
Pzmax := 0;
for i := 1 to AObjects.Count - 1 do
begin
if ((AObjects[i] as TGLBaseSceneObject).AbsolutePosition[0] < min[0]) then
begin
min[0] := (AObjects[i] as TGLBaseSceneObject).AbsolutePosition[0];
Pxmin := i;
end
else if ((AObjects[i] as TGLBaseSceneObject).AbsolutePosition[0] > max[0]) then
begin
max[0] := (AObjects[i] as TGLBaseSceneObject).AbsolutePosition[0];
Pxmax := i;
end;
if ((AObjects[i] as TGLBaseSceneObject).AbsolutePosition[1] < min[1]) then
begin
min[1] := (AObjects[i] as TGLBaseSceneObject).AbsolutePosition[1];
Pymin := i;
end
else if ((AObjects[i] as TGLBaseSceneObject).AbsolutePosition[1] > max[1]) then
begin
max[1] := (AObjects[i] as TGLBaseSceneObject).AbsolutePosition[1];
Pymax := i;
end;
if ((AObjects[i] as TGLBaseSceneObject).AbsolutePosition[2] < min[2]) then
begin
min[2] := (AObjects[i] as TGLBaseSceneObject).AbsolutePosition[2];
Pzmin := i;
end
else if ((AObjects[i] as TGLBaseSceneObject).AbsolutePosition[2] > max[2]) then
begin
max[2] := (AObjects[i] as TGLBaseSceneObject).AbsolutePosition[2];
Pzmax := i;
end;
end;
// select the largest extent as an initial diameter for the ball
dVx := VectorSubtract((AObjects[Pxmax] as TGLBaseSceneObject).AbsolutePosition,
(AObjects[Pxmin] as TGLBaseSceneObject).AbsolutePosition);
dVy := VectorSubtract((AObjects[Pymax] as TGLBaseSceneObject).AbsolutePosition,
(AObjects[Pymin] as TGLBaseSceneObject).AbsolutePosition);
dVz := VectorSubtract((AObjects[Pzmax] as TGLBaseSceneObject).AbsolutePosition,
(AObjects[Pzmin] as TGLBaseSceneObject).AbsolutePosition);
dx := VectorLength(dVx);
dy := VectorLength(dVy);
dz := VectorLength(dVz);
if (dx >= dy) then // x direction is largest extent
begin
if (dx >= dz) then
begin
C := VectorAdd((AObjects[Pxmin] as TGLBaseSceneObject).AbsolutePosition, VectorScale(dVx, 1/2)); // Center = midpoint of extremes
rad := VectorLength(VectorSubtract((AObjects[Pxmin] as TGLBaseSceneObject).AbsolutePosition, C)); // radius squared
end
else
begin
C := VectorAdd((AObjects[Pzmin] as TGLBaseSceneObject).AbsolutePosition, VectorScale(dVz, 1/2)); // Center = midpoint of extremes
rad := VectorLength(VectorSubtract((AObjects[Pzmin] as TGLBaseSceneObject).AbsolutePosition, C)); // radius squared
end;
end
else // y direction is largest extent
begin
if (dy >= dz) then
begin
C := VectorAdd((AObjects[Pymin] as TGLBaseSceneObject).AbsolutePosition, VectorScale(dVy, 1/2)); // Center = midpoint of extremes
rad := VectorLength(VectorSubtract((AObjects[Pymin] as TGLBaseSceneObject).AbsolutePosition, C)); // radius squared
end
else
begin
C := VectorAdd((AObjects[Pzmin] as TGLBaseSceneObject).AbsolutePosition, VectorScale(dVz, 1/2)); // Center = midpoint of extremes
rad := VectorLength(VectorSubtract((AObjects[Pzmin] as TGLBaseSceneObject).AbsolutePosition, C)); // radius squared
end;
end;
rad2 := sqr(rad);
// now check that all points V[i] are in the ball
// and if not, expand the ball just enough to include them
for i := 0 to AObjects.Count - 1 do
begin
dV := VectorSubtract((AObjects[i] as TGLBaseSceneObject).AbsolutePosition, C);
dist2 := sqr(VectorLength(dV));
if (dist2 <= rad2) then // V[i] is inside the ball already
continue;
// V[i] not in ball, so expand ball to include it
dist := sqrt(dist2);
rad := (rad + dist) / 2.0; // enlarge radius just enough
rad2 := rad * rad;
C := VectorAdd(C, VectorScale(dV, ((dist-rad)/dist))); // shift Center toward V[i]
end;
APosition := C;
ARadius := rad;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.